/*
 * SCR-T1 visitor 메인 (§3C v2.3.2) — `/visitor`, 미인증 공개 · track="visitor".
 * "세련된 AI 관람 도우미 홈페이지"로 격상: 히어로 AI 도우미(중심) → AI 기능 쇼케이스 →
 * AI 연/월 기획 브리핑 → 전시 쇼케이스 → 관심사 추천 → 방문가이드 허브 → 여정 3스텝 →
 * 공지 → 전시장 소개 → 푸터(PublicShell).
 * 데이터(라이브): AI 도우미(POST /ai/visitor-assistant)·기획(calendar+monthly-summary)·
 *   방문가이드/교통(visitor-guide+transport)·쇼케이스(/events)·공지(/cms/NOTICE).
 * ※ Stitch 생성 2회 실패 → design.md 스펙+기존 컨벤션 재조합 직접 구현(신규 토큰 0).
 *   Stitch 확보 시 히어로/타일/브리핑 마크업 교체 지점 = 각 섹션 주석 "STITCH-REPLACE".
 */
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { PublicShell } from './PublicShell';
import { PublicHeroSlides } from './PublicHeroSlides';
import { usePublicEvents, EventGrid } from './trackShared';
import { AiAssistant } from './AiAssistant';
import { AiPlanningBriefing } from './AiPlanningBriefing';
import { publicApi, type PublicNotice, type VisitorGuide, type TransportInfo } from './publicApi';
import { errorMessage } from './publicFormat';
import { AiLabel } from '../../components/ui/Badge';
import {
  IconTrain,
  IconParking,
  IconMap,
  IconInfo,
  IconShield,
  IconChat,
  IconChevronRight,
  IconArrowRight,
  IconSparkles,
  IconTarget,
  IconCalendar,
  IconRobot,
  IconCloud,
  IconQr,
  IconCheckCircle,
  IconTicket,
  IconVenue,
  IconBell,
} from './publicIcons';
import type { ComponentType, SVGProps } from 'react';

type Ico = ComponentType<SVGProps<SVGSVGElement>>;

/** AI 기능 쇼케이스 타일(4~6) — 정적 능력 메타. `soon`=준비 중 배지. */
const AI_TILES: { key: string; icon: Ico; to: string; soon?: boolean }[] = [
  { key: 'assistant', icon: IconSparkles, to: '#hero' },
  { key: 'recommend', icon: IconTarget, to: '#recommend' },
  // 실내 길찾기는 로그인/앱 기능 → 공개 방문가이드 섹션으로 안내(로그인 유도 금지).
  { key: 'wayfinding', icon: IconMap, to: '#guide' },
  { key: 'schedule', icon: IconCalendar, to: '#briefing' },
  { key: 'crowd', icon: IconCloud, to: '#briefing', soon: true },
  { key: 'render', icon: IconRobot, to: '/business', soon: true },
];

/** 방문 가이드 허브(2×3) 정적 폴백 — 라이브 visitor-guide 부재 시. */
const GUIDE_CARDS: { key: string; icon: Ico; to: string }[] = [
  { key: 'transport', icon: IconTrain, to: '#transport' },
  { key: 'parking', icon: IconParking, to: '#transport' },
  // 길찾기는 공개 교통·오시는 길 안내로 대체(로그인 유도 금지).
  { key: 'wayfinding', icon: IconMap, to: '#transport' },
  { key: 'amenities', icon: IconInfo, to: '#guide' },
  { key: 'accessibility', icon: IconShield, to: '#guide' },
  { key: 'inquiry', icon: IconChat, to: '/public/exhibit-inquiry' },
];

/** 관심사 추천 칩(정적 카테고리 라벨). */
const INTEREST_KEYS = ['robot', 'smartfactory', 'healthcare', 'eco', 'mobility', 'content'] as const;

/** 관람객 여정 3-스텝. `linkKey`=기본 link 라벨 대체(로그인 유도 라벨 제거 시). */
const JOURNEY: { key: string; icon: Ico; to: string; linkKey?: string }[] = [
  { key: 'register', icon: IconTicket, to: '#showcase' },
  { key: 'badge', icon: IconQr, to: '/tickets/lookup' },
  // 현장 체크인은 로그인 대신 공개 입장권/QR 조회로 안내(로그인 유도 금지).
  { key: 'checkin', icon: IconCheckCircle, to: '/tickets/lookup', linkKey: 'track.visitor.guideMore' },
];

function LinkOrAnchor({
  to,
  className,
  children,
  style,
}: {
  to: string;
  className: string;
  children: React.ReactNode;
  style?: React.CSSProperties;
}) {
  if (to.startsWith('#')) {
    return (
      <a className={className} href={to} style={style}>
        {children}
      </a>
    );
  }
  return (
    <Link className={className} to={to} style={style}>
      {children}
    </Link>
  );
}

/** 방문가이드 카테고리 → 아이콘 휴리스틱(라이브 카테고리 텍스트 매칭). */
function guideIcon(cat: string | null, title: string | null): Ico {
  const s = `${cat ?? ''} ${title ?? ''}`.toLowerCase();
  if (/교통|transport|gtx|지하철|버스|subway|bus/.test(s)) return IconTrain;
  if (/주차|park/.test(s)) return IconParking;
  if (/길찾기|wayfind|지도|map|동선/.test(s)) return IconMap;
  if (/접근|access|휠체어|수어/.test(s)) return IconShield;
  if (/문의|faq|inquir|연락/.test(s)) return IconChat;
  return IconInfo;
}

export function VisitorTrackPage() {
  const { t } = useTranslation();
  const events = usePublicEvents(12);

  const [notices, setNotices] = useState<PublicNotice[]>([]);
  const [noticeErr, setNoticeErr] = useState('');
  const [noticeLoading, setNoticeLoading] = useState(true);

  const [guides, setGuides] = useState<VisitorGuide[]>([]);
  const [transport, setTransport] = useState<TransportInfo[]>([]);

  const [interest, setInterest] = useState<string>('');

  useEffect(() => {
    let alive = true;
    setNoticeLoading(true);
    publicApi
      .listNotices(5)
      .then((list) => alive && (setNotices(list), setNoticeErr('')))
      .catch((e) => alive && setNoticeErr(errorMessage(e)))
      .finally(() => alive && setNoticeLoading(false));

    // 방문가이드·교통(라이브) — 실패해도 정적 폴백으로 화면 유지(빈 화면 금지).
    publicApi
      .listVisitorGuide()
      .then((list) => alive && setGuides(list))
      .catch(() => alive && setGuides([]));
    publicApi
      .listTransport()
      .then((list) => alive && setTransport(list))
      .catch(() => alive && setTransport([]));

    return () => {
      alive = false;
    };
  }, []);

  const useLiveGuides = guides.length > 0;

  return (
    <PublicShell active="visit" track="visitor" cta={t('track.visitor.ctaPreReg')}>
      {/* ── 1. 풀블리드 히어로 + AI 관람 도우미(중심) ── STITCH-REPLACE:hero ── */}
      {/* 히어로 배경 실사진 5장 크로스페이드 회전(그라디언트+도트 패턴은 로드 실패 폴백). */}
      <section className="kxp-vhero pub-hero" id="hero" aria-label={t('track.visitor.heroAria')}>
        <div className="kxp-vhero__bg pub-pattern-dots" data-parallax="0.18" aria-hidden>
          <PublicHeroSlides />
        </div>
        <div className="kxp-vhero__scrim" aria-hidden />
        <span className="kxp-vhero__wm" aria-hidden>
          {t('track.visitor.aiWatermark')}
        </span>
        <div className="kxp-vhero__inner pub-hero__fg">
          <h1 className="kxp-vhero__title">{t('track.visitor.hero.title')}</h1>
          <p className="kxp-vhero__lead">{t('track.visitor.hero.subtitle')}</p>

          <AiAssistant />

          <div className="kxp-vhero__cta">
            <a className="kxp-btn kxp-btn--primary kxp-btn--lg" href="#showcase">
              {t('track.visitor.ctaPreReg')}
            </a>
            <Link className="kxp-btn kxp-btn--ghost kxp-btn--lg" to="/tickets/lookup">
              {t('track.visitor.ctaTicket')}
            </Link>
          </div>
        </div>
      </section>

      {/* ── 1b. 통계 밴드(카운트업) ── */}
      <section className="pub-statsband" aria-label={t('track.visitor.stats.aria')}>
        <div className="kxp-wrap">
          <div className="pub-statsband__grid pub-reveal pub-reveal--stagger">
            {(['exhibitions', 'exhibitors', 'visitors'] as const).map((k, i) => (
              <div key={k} className="pub-stat" style={{ '--i': i } as React.CSSProperties}>
                <span
                  className="pub-stat__num pub-countup"
                  data-count-to={t(`track.visitor.stats.${k}.countTo`)}
                  data-count-suffix={t(`track.visitor.stats.${k}.suffix`)}
                >
                  0
                </span>
                <span className="pub-stat__label">{t(`track.visitor.stats.${k}.label`)}</span>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ── 2. AI 기능 쇼케이스 타일 ── STITCH-REPLACE:tiles ── */}
      <section className="kxp-section" id="ai-tiles" aria-label={t('track.visitor.aiTiles.title')}>
        <div className="kxp-wrap">
          <div className="kxp-section__head pub-reveal">
            <div>
              <h2 className="kxp-section__title"><IconSparkles className="kx-title-ic" width={22} height={22} />{t('track.visitor.aiTiles.title')}</h2>
              <p className="kxp-section__sub">{t('track.visitor.aiTiles.sub')}</p>
            </div>
          </div>
          <div className="kxp-aitiles pub-reveal pub-reveal--stagger">
            {AI_TILES.map(({ key, icon: Icon, to, soon }, i) => (
              <LinkOrAnchor key={key} to={to} className="kxp-aitile" style={{ '--i': i } as React.CSSProperties}>
                <span className="kxp-aitile__top">
                  <AiLabel>{t('ai.assistant.label')}</AiLabel>
                  {soon && <span className="kxp-aitile__soon">{t('track.visitor.aiTiles.soon')}</span>}
                </span>
                <span className="kxp-aitile__ic" aria-hidden>
                  <Icon width={24} height={24} />
                </span>
                <span className="kxp-aitile__title">{t(`track.visitor.aiTiles.${key}.title`)}</span>
                <span className="kxp-aitile__desc">{t(`track.visitor.aiTiles.${key}.desc`)}</span>
                <span className="kxp-aitile__go" aria-hidden>
                  <IconArrowRight width={16} height={16} />
                </span>
              </LinkOrAnchor>
            ))}
          </div>
        </div>
      </section>

      {/* ── 3. AI 전시·행사 기획 브리핑(연/월) ── */}
      <AiPlanningBriefing />

      {/* ── 4. 진행 중·예정 전시 쇼케이스 ── */}
      <section className="kxp-section" id="showcase" aria-label={t('track.visitor.eventsAria')}>
        <div className="kxp-wrap">
          <div className="kxp-section__head pub-reveal">
            <div>
              <h2 className="kxp-section__title"><IconVenue className="kx-title-ic" width={22} height={22} />{t('track.visitor.showcaseTitle')}</h2>
              <p className="kxp-section__sub">{t('track.visitor.showcaseSub')}</p>
            </div>
          </div>
          <EventGrid state={events} />
        </div>
      </section>

      {/* ── 5. 관심사 맞춤 추천 레일(AI) ── */}
      <section className="kxp-section kxp-section--alt" id="recommend" aria-label={t('track.visitor.recommendTitle')}>
        <div className="kxp-wrap">
          <div className="kxp-section__head pub-reveal">
            <div>
              <h2 className="kxp-section__title">
                <IconTarget className="kx-title-ic" width={22} height={22} />
                {t('track.visitor.recommendTitle')}{' '}
                <span className="kxp-inlineai">
                  <AiLabel>{t('track.visitor.recommendTag')}</AiLabel>
                </span>
              </h2>
              <p className="kxp-section__sub">{t('track.visitor.recommendSub')}</p>
            </div>
          </div>
          <div className="kxp-vinterests" role="group" aria-label={t('track.visitor.recommendTitle')}>
            {INTEREST_KEYS.map((k) => (
              <button
                key={k}
                type="button"
                className={`kxp-ai__chip${interest === k ? ' is-active' : ''}`}
                aria-pressed={interest === k}
                onClick={() => setInterest((cur) => (cur === k ? '' : k))}
              >
                {t(`track.visitor.interests.${k}`)}
              </button>
            ))}
          </div>
          <EventGrid state={events} />
        </div>
      </section>

      {/* ── 6. 방문 가이드 허브(2×3, 라이브 우선·정적 폴백) ── */}
      <section className="kxp-section" id="guide" aria-label={t('track.visitor.guideAria')}>
        <div className="kxp-wrap">
          <div className="kxp-section__head pub-reveal">
            <div>
              <h2 className="kxp-section__title"><IconMap className="kx-title-ic" width={22} height={22} />{t('track.visitor.guideTitle')}</h2>
              <p className="kxp-section__sub">{t('track.visitor.guideSub')}</p>
            </div>
          </div>

          {/* 교통 요약 스트립(라이브 transport) — 없으면 자동 숨김 */}
          {transport.length > 0 && (
            <div className="kxp-transtrip" id="transport" aria-label={t('track.visitor.guide.transport.title')}>
              {transport.slice(0, 5).map((tr) => (
                <div key={tr.id} className="kxp-transtrip__item">
                  <span className="kxp-transtrip__ic" aria-hidden>
                    <IconTrain width={18} height={18} />
                  </span>
                  <div>
                    <div className="kxp-transtrip__name">{tr.lineName || tr.mode}</div>
                    <div className="kxp-transtrip__desc">
                      {[tr.route, tr.travelTime].filter(Boolean).join(' · ')}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}

          <div className="kxp-guidegrid pub-reveal pub-reveal--stagger">
            {useLiveGuides
              ? guides.slice(0, 6).map((g) => {
                  const Icon = guideIcon(g.category, g.title);
                  return (
                    <article key={g.id} className="kxp-guide">
                      <span className="kxp-guide__ic" aria-hidden>
                        <Icon width={22} height={22} />
                      </span>
                      <div>
                        <div className="kxp-guide__title">{g.title}</div>
                        <p className="kxp-guide__desc">{g.summary || g.body || ''}</p>
                        {g.sourceUrl && (
                          <a className="kxp-guide__link" href={g.sourceUrl} target="_blank" rel="noreferrer noopener">
                            {t('track.visitor.guideMore')} <IconChevronRight width={15} height={15} />
                          </a>
                        )}
                      </div>
                    </article>
                  );
                })
              : GUIDE_CARDS.map(({ key, icon: Icon, to }) => (
                  <article key={key} className="kxp-guide">
                    <span className="kxp-guide__ic" aria-hidden>
                      <Icon width={22} height={22} />
                    </span>
                    <div>
                      <div className="kxp-guide__title">{t(`track.visitor.guide.${key}.title`)}</div>
                      <p className="kxp-guide__desc">{t(`track.visitor.guide.${key}.desc`)}</p>
                      <LinkOrAnchor to={to} className="kxp-guide__link">
                        {t(`track.visitor.guide.${key}.link`)} <IconChevronRight width={15} height={15} />
                      </LinkOrAnchor>
                    </div>
                  </article>
                ))}
          </div>
        </div>
      </section>

      {/* ── 7. 관람객 여정 3-스텝 ── */}
      <section className="kxp-section kxp-section--alt" id="journey" aria-label={t('track.visitor.journeyTitle')}>
        <div className="kxp-wrap">
          <div className="kxp-section__head pub-reveal">
            <div>
              <h2 className="kxp-section__title"><IconArrowRight className="kx-title-ic" width={22} height={22} />{t('track.visitor.journeyTitle')}</h2>
              <p className="kxp-section__sub">{t('track.visitor.journeySub')}</p>
            </div>
          </div>
          <ol className="kxp-journey pub-reveal pub-reveal--stagger">
            {JOURNEY.map(({ key, icon: Icon, to, linkKey }, i) => (
              <li key={key} className="kxp-journey__step" style={{ '--i': i } as React.CSSProperties}>
                <span className="kxp-journey__num" aria-hidden>
                  {i + 1}
                </span>
                <span className="kxp-journey__ic" aria-hidden>
                  <Icon width={22} height={22} />
                </span>
                <div className="kxp-journey__body">
                  <div className="kxp-journey__title">{t(`track.visitor.journey.${key}.title`)}</div>
                  <p className="kxp-journey__desc">{t(`track.visitor.journey.${key}.desc`)}</p>
                  <LinkOrAnchor to={to} className="kxp-guide__link">
                    {t(linkKey ?? `track.visitor.journey.${key}.link`)}{' '}
                    <IconChevronRight width={15} height={15} />
                  </LinkOrAnchor>
                </div>
                {i < JOURNEY.length - 1 && (
                  <span className="kxp-journey__arrow" aria-hidden>
                    <IconArrowRight width={18} height={18} />
                  </span>
                )}
              </li>
            ))}
          </ol>
        </div>
      </section>

      {/* ── 8. 공지·뉴스 ── */}
      <section className="kxp-section" id="notices" aria-label={t('track.visitor.noticeAria')}>
        <div className="kxp-wrap">
          <div className="kxp-section__head pub-reveal">
            <div>
              <h2 className="kxp-section__title"><IconBell className="kx-title-ic" width={22} height={22} />{t('track.visitor.noticeTitle')}</h2>
              <p className="kxp-section__sub">{t('track.visitor.noticeSub')}</p>
            </div>
          </div>

          {noticeLoading && (
            <p className="kxp-empty" role="status">
              {t('home.loading')}
            </p>
          )}
          {!noticeLoading && (noticeErr || notices.length === 0) && (
            <p className="kxp-empty">{t('track.visitor.noticeEmpty')}</p>
          )}
          {!noticeLoading && !noticeErr && notices.length > 0 && (
            <div className="kxp-list">
              {notices.map((n) => (
                <div key={n.id} className="kxp-listrow">
                  <div className="kxp-listrow__main">
                    <div className="kxp-listrow__title">{n.title}</div>
                    <div className="kxp-listrow__meta">{n.publishedAt ?? n.createdAt ?? ''}</div>
                  </div>
                  <span className="kxp-listrow__right">
                    <IconArrowRight width={18} height={18} />
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>
      </section>

      {/* ── 9. 전시장 소개 밴드 ── */}
      <section className="kxp-section kxp-section--alt" id="venue" aria-label={t('track.visitor.venueTitle')}>
        <div className="kxp-wrap">
          <div className="kxp-venue pub-reveal">
            <div className="kxp-venue__intro">
              <span className="kxp-venue__ic" aria-hidden>
                <IconVenue width={28} height={28} />
              </span>
              <div>
                <h2 className="kxp-section__title"><IconVenue className="kx-title-ic" width={22} height={22} />{t('track.visitor.venueTitle')}</h2>
                <p className="kxp-section__sub">{t('track.visitor.venueSub')}</p>
              </div>
            </div>
            <dl className="kxp-venue__stats">
              {(['halls', 'area', 'parking', 'access'] as const).map((k) => (
                <div key={k} className="kxp-venue__stat">
                  <dt>{t(`track.visitor.venue.${k}.label`)}</dt>
                  <dd className="kxp-tabnum">{t(`track.visitor.venue.${k}.value`)}</dd>
                </div>
              ))}
            </dl>
          </div>
        </div>
      </section>
    </PublicShell>
  );
}
