/*
 * SCR-P4 관람객 사전등록 폼 (M10) — 비로그인 공개.
 * design.md §3B. 4단계 로컬 플로우(유형→정보→관심분야→완료).
 * 제출은 POST /api/public/events/{eventId}/register (visitor 팀 계약) 실배선 — 미배포 시 에러 토스트 3상태 처리.
 * 개인정보 동의(필수) 미체크 시 진행 차단. 완료 시 모바일 배지 QR(발급 배지코드).
 */
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useParams } from 'react-router-dom';
import { PublicShell } from './PublicShell';
import { publicApi, type RegistrationReceipt } from './publicApi';
import { errorMessage } from './publicFormat';
import {
  IconPerson,
  IconBuyer,
  IconVip,
  IconCheckCircle,
  IconQr,
  IconArrowRight,
  IconChevronRight,
  IconBell,
} from './publicIcons';

const STEP_KEYS = ['register.steps.type', 'register.steps.info', 'register.steps.interest', 'register.steps.done'];

const TYPES = [
  { key: 'general', ic: <IconPerson width={26} height={26} />, titleKey: 'register.type.general', descKey: 'register.type.generalDesc' },
  { key: 'buyer', ic: <IconBuyer width={26} height={26} />, titleKey: 'register.type.buyer', descKey: 'register.type.buyerDesc' },
  { key: 'vip', ic: <IconVip width={26} height={26} />, titleKey: 'register.type.vip', descKey: 'register.type.vipDesc' },
];

const INTERESTS = [
  'register.interest.ai',
  'register.interest.factory',
  'register.interest.robotics',
  'register.interest.bigdata',
  'register.interest.cloud',
];

const TYPE_LABEL_KEY: Record<string, string> = {
  general: 'register.type.general',
  buyer: 'register.type.buyer',
  vip: 'register.type.vip',
};

export function PublicRegistrationPage() {
  const { t } = useTranslation();
  const { eventId } = useParams<{ eventId: string }>();
  const [step, setStep] = useState(0); // 0..3
  const [type, setType] = useState('general');
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [email, setEmail] = useState('');
  const [org, setOrg] = useState('');
  const [interests, setInterests] = useState<string[]>([]);
  const [agreePrivacy, setAgreePrivacy] = useState(false);
  const [agreeMkt, setAgreeMkt] = useState(false);
  const [error, setError] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [receipt, setReceipt] = useState<RegistrationReceipt | null>(null);

  const toggleInterest = (v: string) =>
    setInterests((prev) => (prev.includes(v) ? prev.filter((i) => i !== v) : [...prev, v]));

  const submit = async () => {
    setError('');
    if (!agreePrivacy) {
      setError(t('register.errPrivacy'));
      return;
    }
    if (!name.trim()) {
      setError(t('register.errName'));
      return;
    }
    if (!eventId) {
      setError(t('register.errEvent'));
      return;
    }
    setSubmitting(true);
    try {
      const r = await publicApi.register(eventId, {
        name: name.trim(),
        phone: phone.trim(),
        email: email.trim(),
        visitorType: type,
        agreePrivacy,
        agreeMarketing: agreeMkt,
      });
      setReceipt(r);
      setStep(3);
    } catch (e) {
      // 백엔드(visitor 트랙) 미배포 시에도 UX 차단하지 않음 — 오류 메시지 노출.
      setError(errorMessage(e));
    } finally {
      setSubmitting(false);
    }
  };

  const next = () => {
    setError('');
    if (step === 2) {
      void submit();
      return;
    }
    if (step === 1 && !name.trim()) {
      setError(t('register.errName'));
      return;
    }
    setStep((s) => Math.min(3, s + 1));
  };
  const prev = () => {
    setError('');
    setStep((s) => Math.max(0, s - 1));
  };

  const fillPct = (step / (STEP_KEYS.length - 1)) * 100;

  return (
    <PublicShell active="visit" cta={t('shell.cta.register')} search={false}>
      <div className="kxp-reg">
        {/* 진행 인디케이터 */}
        <div className="kxp-steps" role="list" aria-label={t('register.stepsAria')}>
          <div className="kxp-steps__track" aria-hidden />
          <div className="kxp-steps__fill" style={{ width: `calc(${fillPct}% - 48px * ${fillPct / 100})` }} aria-hidden />
          {STEP_KEYS.map((labelKey, i) => (
            <div
              key={labelKey}
              className={`kxp-step${i === step ? ' is-active' : ''}${i < step ? ' is-done' : ''}`}
              role="listitem"
              aria-current={i === step ? 'step' : undefined}
            >
              <span className="kxp-step__dot">{i < step ? <IconCheckCircle width={20} height={20} /> : i + 1}</span>
              <span className="kxp-step__label">{t(labelKey)}</span>
            </div>
          ))}
        </div>

        <div className="kxp-regcard">
          {/* Step 1: 유형 */}
          {step === 0 && (
            <div>
              <h2 className="kxp-regcard__title">{t('register.step0Title')}</h2>
              <p className="kxp-regcard__sub">{t('register.step0Sub')}</p>
              <div className="kxp-typegrid" role="radiogroup" aria-label={t('register.typeGroupAria')}>
                {TYPES.map((item) => (
                  <button
                    key={item.key}
                    type="button"
                    role="radio"
                    aria-checked={type === item.key}
                    className={`kxp-typecard${type === item.key ? ' is-active' : ''}`}
                    onClick={() => setType(item.key)}
                  >
                    <span className="kxp-typecard__ic">{item.ic}</span>
                    <h3>{t(item.titleKey)}</h3>
                    <p>{t(item.descKey)}</p>
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Step 2: 정보 */}
          {step === 1 && (
            <div>
              <h2 className="kxp-regcard__title" style={{ fontSize: 'var(--fs-h2)' }}>
                {t('register.step1Title')}
              </h2>
              <p className="kxp-regcard__sub">{t('register.step1Sub')}</p>
              <div className="kxp-formgrid kxp-formgrid--2">
                <div className="kxp-field">
                  <label htmlFor="reg-name">{t('register.name')}</label>
                  <input
                    id="reg-name"
                    className="kxp-input"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    placeholder={t('register.namePh')}
                  />
                </div>
                <div className="kxp-field">
                  <label htmlFor="reg-tel">{t('register.phone')}</label>
                  <input
                    id="reg-tel"
                    className="kxp-input"
                    type="tel"
                    placeholder="010-0000-0000"
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                  />
                </div>
                <div className="kxp-field kxp-formgrid__full">
                  <label htmlFor="reg-email">{t('register.email')}</label>
                  <input
                    id="reg-email"
                    className="kxp-input"
                    type="email"
                    placeholder={t('register.emailPh')}
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                </div>
                <div className="kxp-field kxp-formgrid__full">
                  <label htmlFor="reg-org">{t('register.org')}</label>
                  <input
                    id="reg-org"
                    className="kxp-input"
                    placeholder={t('register.orgPh')}
                    value={org}
                    onChange={(e) => setOrg(e.target.value)}
                  />
                </div>
              </div>
            </div>
          )}

          {/* Step 3: 관심분야 + 동의 */}
          {step === 2 && (
            <div>
              <h2 className="kxp-regcard__title" style={{ fontSize: 'var(--fs-h2)' }}>
                {t('register.step2Title')}
              </h2>
              <p className="kxp-regcard__sub">{t('register.step2Sub')}</p>
              <div className="kxp-interests" role="group" aria-label={t('register.interestsAria')}>
                {INTERESTS.map((vKey) => {
                  const label = t(vKey);
                  return (
                    <button
                      key={vKey}
                      type="button"
                      aria-pressed={interests.includes(label)}
                      className={`kxp-interest${interests.includes(label) ? ' is-active' : ''}`}
                      onClick={() => toggleInterest(label)}
                    >
                      {label}
                    </button>
                  );
                })}
              </div>
              <div className="kxp-consent">
                <div className="kxp-consent__row">
                  <label className="kxp-check">
                    <input
                      type="checkbox"
                      checked={agreePrivacy}
                      onChange={(e) => setAgreePrivacy(e.target.checked)}
                    />
                    <span>
                      {t('register.consentPrivacy')} <span className="kxp-check__req">{t('register.required')}</span>
                    </span>
                  </label>
                  <a className="kxp-consent__more" href="#top">
                    {t('register.consentMore')}
                  </a>
                </div>
                <div className="kxp-consent__row">
                  <label className="kxp-check">
                    <input type="checkbox" checked={agreeMkt} onChange={(e) => setAgreeMkt(e.target.checked)} />
                    <span>{t('register.consentMarketing')}</span>
                  </label>
                  <a className="kxp-consent__more" href="#top">
                    {t('register.consentMore')}
                  </a>
                </div>
              </div>
              {error && (
                <p role="alert" style={{ color: 'var(--color-error)', fontSize: 'var(--fs-body)', marginTop: 12 }}>
                  {error}
                </p>
              )}
            </div>
          )}

          {/* Step 4: 완료 */}
          {step === 3 && (
            <div className="kxp-done">
              <div className="kxp-done__ic">
                <IconCheckCircle width={40} height={40} />
              </div>
              <h2 className="kxp-regcard__title">{t('register.doneTitle')}</h2>
              <p className="kxp-regcard__sub">
                {t('register.doneSub', { name: name || t('register.visitorDefault') })}
              </p>

              <div className="kxp-badge" aria-label={t('register.badgeAria')}>
                <div className="kxp-badge__top">
                  <span className="kxp-badge__pass">PASS</span>
                  <span className="kxp-badge__role">{t(TYPE_LABEL_KEY[type])}</span>
                </div>
                <div className="kxp-badge__name">{name || t('register.badgeName')}</div>
                <div className="kxp-badge__qr">
                  <div className="kxp-badge__qrbox">
                    <IconQr />
                  </div>
                  <div className="kxp-badge__id">{t('register.badgeCodeLabel')}</div>
                  <div className="kxp-badge__idval">{receipt?.badgeCode ?? receipt?.registrationId ?? '—'}</div>
                </div>
              </div>

              <div className="kxp-donenote">
                <span style={{ display: 'inline-flex', gap: 8, alignItems: 'center' }}>
                  <IconBell width={18} height={18} /> {t('register.doneNote')}
                </span>
                {receipt?.registrationId && <span>{t('register.regNo', { id: receipt.registrationId })}</span>}
              </div>
            </div>
          )}

          {/* 내비게이션 */}
          {step < 3 ? (
            <div className="kxp-regnav">
              {step > 0 && (
                <button type="button" className="kxp-btn kxp-btn--outline" onClick={prev}>
                  {t('common.actions.prev')}
                </button>
              )}
              <button
                type="button"
                className="kxp-btn kxp-btn--primary"
                onClick={next}
                disabled={submitting}
              >
                {step === 2
                  ? submitting
                    ? t('register.submitting')
                    : t('register.submit')
                  : t('common.actions.next')}{' '}
                <IconChevronRight width={18} height={18} />
              </button>
            </div>
          ) : (
            <div className="kxp-regnav">
              <Link className="kxp-btn kxp-btn--outline" to="/public">
                {t('common.actions.home')}
              </Link>
              {eventId ? (
                <Link
                  className="kxp-btn kxp-btn--primary"
                  to={`/public/events/${encodeURIComponent(eventId)}/floorplan`}
                >
                  {t('register.floorplan')} <IconArrowRight width={18} height={18} />
                </Link>
              ) : (
                <Link className="kxp-btn kxp-btn--primary" to="/public">
                  {t('register.eventBrowse')} <IconArrowRight width={18} height={18} />
                </Link>
              )}
            </div>
          )}
        </div>
      </div>
    </PublicShell>
  );
}
