/*
 * SCR-P2 행사 상세 (소개·일정·연사·교통·FAQ) — M12, 비로그인 공개.
 * design.md §3B. 히어로 + 서브탭(앵커) + 리치 콘텐츠 + 아젠다 타임라인 + 연사 + 사전등록 고정 CTA.
 * 데이터: GET /api/public/events/{eventId} (공개 카탈로그). 아젠다·연사·FAQ는 안내용 예시(전용 API 후속).
 */
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useParams } from 'react-router-dom';
import { PublicShell } from './PublicShell';
import { publicApi, type PublicEvent } from './publicApi';
import { formatRange, errorMessage } from './publicFormat';
import {
  IconCalendar,
  IconPin,
  IconFactory,
  IconCloud,
  IconRobot,
  IconLeaf,
  IconChat,
  IconShare,
  IconLink,
  IconChevronRight,
} from './publicIcons';

const TABS = [
  { key: 'intro', i18n: 'detail.tabs.intro' },
  { key: 'program', i18n: 'detail.tabs.program' },
  { key: 'speakers', i18n: 'detail.tabs.speakers' },
  { key: 'exhibitors', i18n: 'detail.tabs.exhibitors' },
  { key: 'transport', i18n: 'detail.tabs.transport' },
  { key: 'faq', i18n: 'detail.tabs.faq' },
];

const THEMES = [
  { ic: <IconRobot width={40} height={40} />, titleKey: 'detail.theme1Title', descKey: 'detail.theme1Desc' },
  { ic: <IconCloud width={40} height={40} />, titleKey: 'detail.theme2Title', descKey: 'detail.theme2Desc' },
  { ic: <IconLeaf width={40} height={40} />, titleKey: 'detail.theme3Title', descKey: 'detail.theme3Desc' },
];

const AGENDA = [
  { time: '10:00 – 11:30', roomKey: 'detail.agenda1Room', tag: 'KEYNOTE', titleKey: 'detail.agenda1Title', descKey: 'detail.agenda1Desc' },
  { time: '13:00 – 14:30', roomKey: 'detail.agenda2Room', tag: 'TECH SESSION', titleKey: 'detail.agenda2Title', descKey: 'detail.agenda2Desc' },
  { time: '15:00 – 17:00', roomKey: 'detail.agenda3Room', tag: 'NETWORKING', titleKey: 'detail.agenda3Title', descKey: 'detail.agenda3Desc' },
];

const SPEAKERS = [
  { name: '김철수', roleKey: 'detail.speaker1Role' },
  { name: '이영희', roleKey: 'detail.speaker2Role' },
  { name: '박지성', roleKey: 'detail.speaker3Role' },
  { name: 'Sarah Jenkins', roleKey: 'detail.speaker4Role' },
];

export function PublicEventDetailPage() {
  const { t } = useTranslation();
  const { eventId } = useParams<{ eventId: string }>();
  const [activeTab, setActiveTab] = useState('intro');
  const [day, setDay] = useState(1);
  const [event, setEvent] = useState<PublicEvent | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    if (!eventId) return;
    let alive = true;
    setLoading(true);
    publicApi
      .getEvent(eventId)
      .then((e) => {
        if (alive) {
          setEvent(e);
          setError('');
        }
      })
      .catch((e) => alive && setError(errorMessage(e)))
      .finally(() => alive && setLoading(false));
    return () => {
      alive = false;
    };
  }, [eventId]);

  const title = event?.name ?? (loading ? t('detail.loadingTitle') : t('detail.fallbackTitle'));
  const dateRange = event ? formatRange(event.startDate, event.endDate) : t('detail.dateTbd');
  const place = event?.hallLabel ?? t('detail.placeTbd');
  const registerTo = eventId ? `/public/events/${encodeURIComponent(eventId)}/register` : '#program';

  return (
    <PublicShell active="events" cta={t('detail.ctaRegister')}>
      {/* 행사 히어로 */}
      <section
        className="kxp-hero"
        aria-label={title}
        style={{ backgroundColor: 'var(--color-canvas-bg)' }}
      >
        <div
          className="kxp-hero__bg"
          style={{ background: 'linear-gradient(135deg, #101828 0%, #1f3a5f 60%, #0066b3 120%)' }}
          aria-hidden
        />
        <div className="kxp-hero__scrim" aria-hidden />
        <div className="kxp-hero__inner">
          <div className="kxp-hero__content">
            <span className="kxp-hero__eyebrow">{t('detail.eyebrow')}</span>
            <h1 className="kxp-hero__title">{title}</h1>
            <p className="kxp-hero__lead">{error ? error : t('detail.lead')}</p>
            <div className="kxp-eventhero__facts kxp-hero__meta">
              <span className="kxp-hero__metacard">
                <IconCalendar width={18} height={18} />
                <span>
                  <small>{t('detail.factDate')}</small>
                  <strong>{dateRange}</strong>
                </span>
              </span>
              <span className="kxp-hero__metacard">
                <IconPin width={18} height={18} />
                <span>
                  <small>{t('detail.factPlace')}</small>
                  <strong>{place}</strong>
                </span>
              </span>
            </div>
            <div className="kxp-hero__actions">
              <Link className="kxp-btn kxp-btn--primary kxp-btn--lg" to={registerTo}>
                {t('detail.ctaRegister')}
              </Link>
              {eventId && (
                <Link
                  className="kxp-btn kxp-btn--ghost kxp-btn--lg"
                  to={`/public/events/${encodeURIComponent(eventId)}/floorplan`}
                >
                  {t('detail.ctaFloorplan')}
                </Link>
              )}
            </div>
          </div>
        </div>
      </section>

      {/* 서브탭(앵커) */}
      <nav className="kxp-subtabs" aria-label={t('detail.navAria')}>
        <div className="kxp-subtabs__inner">
          {TABS.map((tab) => (
            <a
              key={tab.key}
              href={`#${tab.key}`}
              className={`kxp-subtab${activeTab === tab.key ? ' is-active' : ''}`}
              onClick={() => setActiveTab(tab.key)}
            >
              {t(tab.i18n)}
            </a>
          ))}
        </div>
      </nav>

      {/* 공유 사이드 */}
      <div className="kxp-share" aria-label={t('detail.shareAria')}>
        <button type="button" className="kxp-share__btn" title={t('detail.share')}>
          <IconShare />
        </button>
        <button type="button" className="kxp-share__btn" title={t('detail.copyLink')}>
          <IconLink />
        </button>
      </div>

      {/* 소개 */}
      <section className="kxp-section" id="intro" aria-label={t('detail.overviewAria')}>
        <div className="kxp-wrap">
          <div className="kxp-detail">
            <div>
              <h2 className="kxp-section__title">{t('detail.overviewTitle')}</h2>
              <p className="kxp-detail__lead">{t('detail.overviewLead')}</p>
              <div className="kxp-detail__stats">
                <div className="kxp-statcard">
                  <IconFactory width={28} height={28} />
                  <strong>{event?.boothCount != null && event.boothCount > 0 ? `${event.boothCount}+` : '500+'}</strong>
                  <span>{t('detail.statBooth')}</span>
                </div>
                <div className="kxp-statcard">
                  <IconRobot width={28} height={28} />
                  <strong>{t('detail.statVisitorsValue')}</strong>
                  <span>{t('detail.statVisitors')}</span>
                </div>
              </div>
            </div>
            <div
              className="kxp-detail__img"
              style={{ background: 'linear-gradient(135deg, #0066b3 0%, #6d4aff 120%)' }}
              role="img"
              aria-label={t('detail.overviewAria')}
            />
          </div>

          <h3 className="kxp-section__title" style={{ fontSize: 22, textAlign: 'center', marginTop: 48 }}>
            {t('detail.themesTitle')}
          </h3>
          <div className="kxp-themes">
            {THEMES.map((theme) => (
              <div className="kxp-theme" key={theme.titleKey}>
                {theme.ic}
                <h4>{t(theme.titleKey)}</h4>
                <p>{t(theme.descKey)}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* 프로그램 */}
      <section className="kxp-section kxp-section--alt" id="program" aria-label={t('detail.programAria')}>
        <div className="kxp-wrap">
          <div className="kxp-section__head">
            <h2 className="kxp-section__title">{t('detail.programTitle')}</h2>
            <div className="kxp-daytabs" role="tablist" aria-label={t('detail.programAria')}>
              <button
                type="button"
                role="tab"
                aria-selected={day === 1}
                className={`kxp-daytab${day === 1 ? ' is-active' : ''}`}
                onClick={() => setDay(1)}
              >
                {t('detail.day1')}
              </button>
              <button
                type="button"
                role="tab"
                aria-selected={day === 2}
                className={`kxp-daytab${day === 2 ? ' is-active' : ''}`}
                onClick={() => setDay(2)}
              >
                {t('detail.day2')}
              </button>
            </div>
          </div>

          <div className="kxp-agenda">
            {AGENDA.map((a) => (
              <div className="kxp-agenda__item" key={a.titleKey}>
                <div className="kxp-agenda__time">
                  {a.time}
                  <small>{t(a.roomKey)}</small>
                </div>
                <div>
                  <span className="kxp-tag" style={{ marginBottom: 8, display: 'inline-block' }}>
                    {a.tag}
                  </span>
                  <h4 className="kxp-agenda__title">{t(a.titleKey)}</h4>
                  <p className="kxp-agenda__desc">{t(a.descKey)}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* 연사 */}
      <section className="kxp-section" id="speakers" aria-label={t('detail.speakersTitle')}>
        <div className="kxp-wrap">
          <div className="kxp-section__head" style={{ justifyContent: 'center' }}>
            <h2 className="kxp-section__title">{t('detail.speakersTitle')}</h2>
          </div>
          <div className="kxp-speakers">
            {SPEAKERS.map((s, i) => (
              <div className="kxp-speaker" key={s.name}>
                <div
                  className="kxp-speaker__photo"
                  style={{
                    background: `linear-gradient(135deg, ${
                      ['#0066b3', '#6d4aff', '#0e8a5f', '#004c86'][i % 4]
                    } 0%, #101828 160%)`,
                  }}
                  role="img"
                  aria-label={t('detail.profileAria', { name: s.name })}
                />
                <h5>{s.name}</h5>
                <p>{t(s.roleKey)}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* FAQ (요약) */}
      <section className="kxp-section kxp-section--tint" id="faq" aria-label={t('detail.faqAria')}>
        <div className="kxp-wrap">
          <div className="kxp-section__head">
            <h2 className="kxp-section__title">{t('detail.faqTitle')}</h2>
          </div>
          <div className="kxp-eventgrid" style={{ gridTemplateColumns: '1fr' }}>
            {[
              [t('detail.faq1Q'), t('detail.faq1A')],
              [t('detail.faq2Q'), t('detail.faq2A')],
              [t('detail.faq3Q'), t('detail.faq3A')],
            ].map(([q, a]) => (
              <div className="kxp-boothtype__body" key={q} style={{ background: 'var(--color-white)', border: 'var(--border-card)', borderRadius: 8 }}>
                <h4 style={{ display: 'flex', gap: 8, alignItems: 'center', margin: 0, color: 'var(--color-neutral-900)', fontSize: 'var(--fs-h3)' }}>
                  <IconChat width={18} height={18} /> {q}
                </h4>
                <p style={{ margin: 0, color: 'var(--color-neutral-500)', fontSize: 'var(--fs-body)' }}>{a}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* 사전등록 고정 CTA */}
      <Link className="kxp-btn kxp-btn--primary kxp-btn--lg kxp-fab" to={registerTo}>
        {t('detail.fabCta')} <IconChevronRight width={18} height={18} />
      </Link>
    </PublicShell>
  );
}
