/*
 * SCR-P7 입장권 예매 (M10·M9) — 비로그인 공개.
 * design.md §3B. 예매 플로우(권종→예매자→결제→완료) + 예매 확인·취소(manage) 뷰.
 * 결제 PG 미연동 — 데모 플로우(카드 입력 UI 없음, PG 위임 고지 상시). PII 마스킹.
 * 데이터: 티켓·재고·결제 API 부재 → 샘플 데이터.
 */
import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { PublicShell } from './PublicShell';
import {
  IconTicket,
  IconCalendar,
  IconPin,
  IconPlus,
  IconMinus,
  IconShield,
  IconInfo,
  IconCheckCircle,
  IconQr,
  IconArrowRight,
  IconSparkles,
  IconPerson,
} from './publicIcons';

interface TicketType {
  key: string;
  nameKey: string;
  descKey: string;
  price: number;
  priceKey: string;
  badge?: { labelKey: string; kind: 'ai' | 'off' };
  soldout?: boolean;
  accent: string;
}

const TICKETS: TicketType[] = [
  { key: 'general', nameKey: 'ticket.type.general', descKey: 'ticket.type.generalDesc', price: 0, priceKey: 'ticket.type.generalPrice', accent: '#0066b3' },
  { key: 'buyer', nameKey: 'ticket.type.buyer', descKey: 'ticket.type.buyerDesc', price: 0, priceKey: 'ticket.type.buyerPrice', badge: { labelKey: 'ticket.aiOptimized', kind: 'ai' }, accent: '#6d4aff' },
  { key: 'group', nameKey: 'ticket.type.group', descKey: 'ticket.type.groupDesc', price: 9000, priceKey: 'ticket.type.groupPrice', badge: { labelKey: 'ticket.off10', kind: 'off' }, accent: '#0e8a5f' },
  { key: 'vip', nameKey: 'ticket.type.vip', descKey: 'ticket.type.vipDesc', price: 50000, priceKey: 'ticket.type.vipPrice', soldout: true, accent: '#101828' },
];

const STEP_KEYS = ['ticket.steps.s1', 'ticket.steps.s2', 'ticket.steps.s3', 'ticket.steps.s4'];
const won = (n: number) => `₩${n.toLocaleString('ko-KR')}`;

function EventBanner() {
  const { t } = useTranslation();
  return (
    <div className="kxp-ticket__banner">
      <div
        className="kxp-ticket__poster"
        style={{ background: 'linear-gradient(135deg, #0066b3 0%, #6d4aff 130%)' }}
        role="img"
        aria-label={t('ticket.posterAria')}
      />
      <div>
        <h1>{t('ticket.bannerTitle')}</h1>
        <div className="kxp-ticket__facts">
          <span>
            <IconCalendar width={16} height={16} /> {t('ticket.bannerDate')}
          </span>
          <span>
            <IconPin width={16} height={16} /> {t('ticket.bannerPlace')}
          </span>
        </div>
      </div>
    </div>
  );
}

function PurchaseView() {
  const { t } = useTranslation();
  const [step, setStep] = useState(0);
  const [qty, setQty] = useState<Record<string, number>>({});
  const [pay, setPay] = useState('card');

  const setCount = (key: string, delta: number) =>
    setQty((prev) => {
      const v = Math.max(0, (prev[key] ?? 0) + delta);
      return { ...prev, [key]: v };
    });

  const { subtotal, discount, total, count } = useMemo(() => {
    let sub = 0;
    let disc = 0;
    let cnt = 0;
    for (const t of TICKETS) {
      const q = qty[t.key] ?? 0;
      cnt += q;
      if (t.key === 'group') {
        const base = 10000 * q; // 정가 기준 예시
        sub += base;
        disc += base - t.price * q;
      } else {
        sub += t.price * q;
      }
    }
    return { subtotal: sub, discount: disc, total: sub - disc, count: cnt };
  }, [qty]);

  const isFree = total === 0;

  const next = () => {
    // 무료 권종만이면 결제 단계 자동 스킵
    if (step === 1 && isFree) {
      setStep(3);
      return;
    }
    setStep((s) => Math.min(3, s + 1));
  };
  const prev = () => {
    if (step === 3 && isFree) {
      setStep(1);
      return;
    }
    setStep((s) => Math.max(0, s - 1));
  };

  return (
    <>
      <EventBanner />

      {/* 스텝 인디케이터 */}
      <div className="kxp-ticket__steps" role="list" aria-label={t('ticket.stepsAria')}>
        {STEP_KEYS.map((l, i) => (
          <span
            key={l}
            className={`kxp-ticket__step${i === step ? ' is-active' : ''}`}
            role="listitem"
            aria-current={i === step ? 'step' : undefined}
          >
            {`0${i + 1} `}
            {t(l)}
          </span>
        ))}
      </div>

      {/* 로그인 배너 */}
      <div className="kxp-loginbanner">
        <IconInfo width={18} height={18} /> {t('ticket.loginBanner')}
        <a href="#top">{t('ticket.loginLink')}</a>
      </div>

      <div className="kxp-ticket__grid">
        <div className="kxp-ticket__main">
          {/* Step 1: 권종 */}
          {step === 0 && (
            <section>
              <h2 className="kxp-ticket__h2">
                <IconTicket width={20} height={20} /> {t('ticket.h2Type')}
                <span className="kxp-sample" style={{ marginLeft: 'auto' }}>
                  {t('ticket.sample')}
                </span>
              </h2>
              <div className="kxp-tickrows">
                {TICKETS.map((tk) => (
                  <div
                    key={tk.key}
                    className={`kxp-tickrow${tk.soldout ? ' kxp-tickrow--soldout' : ''}`}
                    style={{ borderLeftColor: tk.soldout ? undefined : tk.accent }}
                  >
                    <div className="kxp-tickrow__info">
                      <h3>
                        {t(tk.nameKey)}
                        {tk.badge && (
                          <span className={tk.badge.kind === 'ai' ? 'kxp-chip kxp-chip--ai' : 'kxp-chip'}>
                            {tk.badge.kind === 'ai' && <IconSparkles width={12} height={12} />}
                            {t(tk.badge.labelKey)}
                          </span>
                        )}
                        {tk.soldout && <span className="kxp-status kxp-status--soldout">{t('ticket.soldout')}</span>}
                      </h3>
                      <p>{t(tk.descKey)}</p>
                      <div className="kxp-tickrow__price">{t(tk.priceKey)}</div>
                    </div>
                    <div className="kxp-stepper" aria-label={t('ticket.qtyAria', { name: t(tk.nameKey) })}>
                      <button
                        type="button"
                        aria-label={t('ticket.decrease')}
                        disabled={tk.soldout}
                        onClick={() => setCount(tk.key, -1)}
                      >
                        <IconMinus width={16} height={16} />
                      </button>
                      <span>{qty[tk.key] ?? 0}</span>
                      <button
                        type="button"
                        aria-label={t('ticket.increase')}
                        disabled={tk.soldout}
                        onClick={() => setCount(tk.key, 1)}
                      >
                        <IconPlus width={16} height={16} />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </section>
          )}

          {/* Step 2: 예매자 */}
          {step === 1 && (
            <section>
              <h2 className="kxp-ticket__h2">
                <IconPerson width={20} height={20} /> {t('ticket.h2Booker')}
              </h2>
              <div className="kxp-formcard">
                <div className="kxp-formgrid kxp-formgrid--2">
                  <div className="kxp-field">
                    <label htmlFor="tk-name">{t('ticket.bookerName')}</label>
                    <input id="tk-name" className="kxp-input" placeholder={t('ticket.bookerNamePh')} />
                  </div>
                  <div className="kxp-field">
                    <label htmlFor="tk-tel">{t('ticket.bookerTel')}</label>
                    <input id="tk-tel" className="kxp-input" type="tel" placeholder="010-0000-0000" />
                  </div>
                  <div className="kxp-field kxp-formgrid__full">
                    <label htmlFor="tk-email">{t('ticket.bookerEmail')}</label>
                    <input id="tk-email" className="kxp-input" type="email" placeholder="example@domain.com" />
                  </div>
                </div>
                <div className="kxp-consent">
                  <label className="kxp-check">
                    <input type="checkbox" />
                    <span>
                      {t('ticket.consentPrivacy')} <span className="kxp-check__req">{t('ticket.required')}</span>
                    </span>
                  </label>
                  <label className="kxp-check">
                    <input type="checkbox" />
                    <span>{t('ticket.consentMarketing')}</span>
                  </label>
                </div>
              </div>
            </section>
          )}

          {/* Step 3: 결제 */}
          {step === 2 && (
            <section>
              <h2 className="kxp-ticket__h2">
                <IconShield width={20} height={20} /> {t('ticket.h2Pay')}
              </h2>
              <div className="kxp-paychips" role="group" aria-label={t('ticket.payGroupAria')}>
                {[
                  ['card', t('ticket.payCard')],
                  ['easy', t('ticket.payEasy')],
                  ['bank', t('ticket.payBank')],
                ].map(([k, label]) => (
                  <button
                    key={k}
                    type="button"
                    className={`kxp-paychip${pay === k ? ' is-active' : ''}`}
                    aria-pressed={pay === k}
                    onClick={() => setPay(k)}
                  >
                    {label}
                  </button>
                ))}
              </div>
              <div className="kxp-pgnote">
                <IconShield width={18} height={18} />
                <span>{t('ticket.pgNote')}</span>
              </div>
            </section>
          )}

          {/* Step 4: 완료 */}
          {step === 3 && (
            <section className="kxp-tikdone">
              <div className="kxp-done__ic" style={{ margin: '0 auto 16px' }}>
                <IconCheckCircle width={40} height={40} />
              </div>
              <h2 className="kxp-regcard__title">{t('ticket.doneTitle')}</h2>
              <div className="kxp-tikdone__no">{t('ticket.doneNo')}</div>
              <p className="kxp-regcard__sub">
                {t('ticket.doneSub', { count, total: won(total) })}
              </p>
              <div className="kxp-tikdone__qr">
                <IconQr width={110} height={110} />
              </div>
              <span className="kxp-sample">{t('ticket.sampleReady')}</span>
              <div className="kxp-tikdone__actions">
                <a className="kxp-btn kxp-btn--outline" href="#top">
                  {t('ticket.walletBtn')}
                </a>
                <a className="kxp-btn kxp-btn--primary" href="#top">
                  {t('ticket.manageBtn')} <IconArrowRight width={18} height={18} />
                </a>
              </div>
            </section>
          )}
        </div>

        {/* 우측 요약 */}
        {step < 3 && (
          <aside className="kxp-ticket__summary" aria-label={t('ticket.summaryAria')}>
            <h3>{t('ticket.summaryTitle')}</h3>
            <div className="kxp-sumrow">
              <span>{t('ticket.summaryCount')}</span>
              <span>{t('ticket.count', { n: count })}</span>
            </div>
            <div className="kxp-sumrow">
              <span>{t('ticket.subtotal')}</span>
              <span>{won(subtotal)}</span>
            </div>
            <div className="kxp-sumrow kxp-sumrow--discount">
              <span>{t('ticket.discount')}</span>
              <span>-{won(discount)}</span>
            </div>
            <div className="kxp-sumtotal">
              <small>{t('ticket.finalTotal')}</small>
              <strong>{won(total)}</strong>
            </div>
            <button
              type="button"
              className="kxp-btn kxp-btn--primary kxp-btn--block kxp-btn--lg"
              disabled={count === 0}
              onClick={next}
            >
              {step === 0
                ? t('ticket.nextStep')
                : step === 1
                  ? isFree
                    ? t('ticket.freeDone')
                    : t('ticket.pay')
                  : t('ticket.payProceed')}
            </button>
            {step > 0 && (
              <button
                type="button"
                className="kxp-btn kxp-btn--outline kxp-btn--block"
                style={{ marginTop: 10 }}
                onClick={prev}
              >
                {t('common.actions.prev')}
              </button>
            )}
            <p style={{ marginTop: 14, fontSize: 11, textAlign: 'center', color: 'var(--color-neutral-500)' }}>
              {t('ticket.customerCenter')}
            </p>
          </aside>
        )}
      </div>
    </>
  );
}

function ManageView() {
  const { t } = useTranslation();
  const [looked, setLooked] = useState(false);
  const [confirmOpen, setConfirmOpen] = useState(false);

  return (
    <>
      <header style={{ textAlign: 'center', marginBottom: 24 }}>
        <h1 className="kxp-regcard__title">{t('ticket.manageTitle')}</h1>
        <p className="kxp-regcard__sub" style={{ marginBottom: 0 }}>
          {t('ticket.manageSub')}
        </p>
      </header>

      {/* 조회 폼 */}
      <div className="kxp-manage__lookup">
        <div className="kxp-manage__lookrow">
          <div className="kxp-field">
            <label htmlFor="mg-no">{t('ticket.lookNo')}</label>
            <input id="mg-no" className="kxp-input" placeholder={t('ticket.lookNoPh')} />
          </div>
          <div className="kxp-field">
            <label htmlFor="mg-email">{t('ticket.lookEmail')}</label>
            <input id="mg-email" className="kxp-input" type="email" placeholder={t('ticket.lookEmailPh')} />
          </div>
          <button type="button" className="kxp-btn kxp-btn--primary" onClick={() => setLooked(true)}>
            {t('ticket.lookBtn')}
          </button>
        </div>
        <div style={{ textAlign: 'center', marginTop: 14 }}>
          <a href="#top" style={{ fontSize: 'var(--fs-caption)', color: 'var(--color-neutral-500)', textDecoration: 'underline' }}>
            {t('ticket.loginToView')}
          </a>
        </div>
      </div>

      {!looked ? (
        <p className="kxp-empty">{t('ticket.notLooked')}</p>
      ) : (
        <div className="kxp-manage__grid">
          {/* 예매 상세 */}
          <div>
            <article className="kxp-bookcard">
              <div className="kxp-bookcard__head">
                <div>
                  <span className="kxp-status kxp-status--done">{t('ticket.booked')}</span>
                  <h2>{t('ticket.bannerTitle')}</h2>
                  <span className="kxp-bookcard__no">
                    {t('ticket.bookNoLabel')} <b>KTX-2026-018245</b>
                  </span>
                </div>
                <div className="kxp-bookcard__paid">
                  <small>{t('ticket.paidAt')}</small>
                  <br />
                  <b>2025-10-24 14:32</b>
                </div>
              </div>

              <table className="kxp-ticktable">
                <thead>
                  <tr>
                    <th>{t('ticket.colType')}</th>
                    <th>{t('ticket.colQty')}</th>
                    <th>{t('ticket.colAmount')}</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>
                      <div className="kxp-ticktable__cell">
                        <span className="kxp-ticktable__qr">
                          <IconQr width={22} height={22} />
                        </span>
                        일반권 (Early Bird)
                      </div>
                    </td>
                    <td>2매</td>
                    <td>₩ 30,000</td>
                  </tr>
                  <tr>
                    <td>
                      <div className="kxp-ticktable__cell">
                        <span className="kxp-ticktable__qr">
                          <IconQr width={22} height={22} />
                        </span>
                        학생/군인 할인
                      </div>
                    </td>
                    <td>1매</td>
                    <td>₩ 10,000</td>
                  </tr>
                </tbody>
              </table>

              <div className="kxp-booker">
                <div className="kxp-booker__id">
                  <IconPerson width={20} height={20} />
                  <div>
                    <small>{t('ticket.bookerInfo')}</small>
                    <br />
                    <b>jo***@ex***.com · 010-****-1234</b>
                  </div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <small style={{ fontSize: 'var(--fs-caption)', color: 'var(--color-neutral-500)' }}>{t('ticket.totalPaid')}</small>
                  <div style={{ fontSize: 'var(--fs-h2)', fontWeight: 800, color: 'var(--color-primary-700)' }}>
                    ₩ 40,000
                  </div>
                </div>
              </div>
            </article>
          </div>

          {/* 환불 정책 */}
          <aside>
            <div className="kxp-refund">
              <h3>
                <IconInfo width={18} height={18} /> {t('ticket.refundTitle')}
              </h3>
              <div className="kxp-refund__table">
                <div className="kxp-refund__row kxp-refund__row--full">
                  <span>{t('ticket.refundD7')}</span>
                  <b>{t('ticket.refundD7Val')}</b>
                </div>
                <div className="kxp-refund__row kxp-refund__row--half">
                  <span>{t('ticket.refundD3')}</span>
                  <b>{t('ticket.refundD3Val')}</b>
                </div>
                <div className="kxp-refund__row kxp-refund__row--none">
                  <span>{t('ticket.refundDay')}</span>
                  <b>{t('ticket.refundDayVal')}</b>
                </div>
              </div>
              <div className="kxp-refund__est">
                <span>{t('ticket.refundEst')}</span>
                <strong>₩ 40,000</strong>
              </div>
              <button
                type="button"
                className="kxp-btn kxp-btn--danger kxp-btn--block"
                onClick={() => setConfirmOpen(true)}
              >
                {t('ticket.cancelBooking')}
              </button>
              <p className="kxp-refund__note">{t('ticket.refundNote')}</p>
            </div>

            <div className="kxp-ai-helper">
              <IconSparkles width={18} height={18} />
              <div>
                <strong>{t('ticket.aiHelper')}</strong>
                <p>{t('ticket.aiHelperDesc')}</p>
              </div>
            </div>
          </aside>
        </div>
      )}

      {confirmOpen && (
        <div className="kxp-modal" role="dialog" aria-modal="true" aria-label={t('ticket.cancelModalAria')}>
          <div className="kxp-modal__scrim" onClick={() => setConfirmOpen(false)} aria-hidden />
          <div className="kxp-modal__box">
            <h3>{t('ticket.cancelModalTitle')}</h3>
            <p>{t('ticket.cancelModalDesc')}</p>
            <div className="kxp-modal__actions">
              <button type="button" className="kxp-btn kxp-btn--outline" onClick={() => setConfirmOpen(false)}>
                {t('common.actions.close')}
              </button>
              <button type="button" className="kxp-btn kxp-btn--danger" onClick={() => setConfirmOpen(false)}>
                {t('ticket.cancelConfirm')}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

export function PublicTicketPage() {
  const { t } = useTranslation();
  const [view, setView] = useState<'purchase' | 'manage'>('purchase');

  return (
    <PublicShell active="visit" cta={t('ticket.viewPurchase')} search={false}>
      <div className={view === 'purchase' ? 'kxp-ticket' : 'kxp-manage'}>
        {/* 뷰 전환 */}
        <div className="kxp-daytabs" style={{ justifyContent: 'center', marginBottom: 24 }} role="tablist" aria-label={t('ticket.viewSwitchAria')}>
          <button
            type="button"
            role="tab"
            aria-selected={view === 'purchase'}
            className={`kxp-daytab${view === 'purchase' ? ' is-active' : ''}`}
            onClick={() => setView('purchase')}
          >
            {t('ticket.viewPurchase')}
          </button>
          <button
            type="button"
            role="tab"
            aria-selected={view === 'manage'}
            className={`kxp-daytab${view === 'manage' ? ' is-active' : ''}`}
            onClick={() => setView('manage')}
          >
            {t('ticket.viewManage')}
          </button>
        </div>

        {view === 'purchase' ? <PurchaseView /> : <ManageView />}
      </div>
    </PublicShell>
  );
}
