/*
 * 공개 홍보 사이트 공통 셸 — 단일 상단 헤더(1 프레임) + 푸터. (AppShell 미사용, 비로그인 공개 영역)
 * COEX 벤치마크(docs/analysis/coex-website.md): 상단 트랙 스위처 + 유틸을 하나의 상단 바로 통합.
 * design.md §3B/§3C-0: 3-트랙 스위처(role=tablist·로빙 탭인덱스)·GNB·다국어 토글을 단일 헤더로 흡수.
 */
import {
  useRef,
  useState,
  type ComponentType,
  type KeyboardEvent,
  type ReactNode,
  type SVGProps,
} from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useNavigate } from 'react-router-dom';
import {
  IconMenu,
  IconClose,
  IconSearch,
  IconPerson,
  IconBuyer,
  IconFactory,
} from './publicIcons';
import { LanguageSwitcher } from '../../components/ui/LanguageSwitcher';
import { useAuthStore } from '../../store/authStore';
import { usePublicMotion } from './usePublicMotion';
import './public.css';

const GNB = [
  { key: 'events', i18n: 'shell.nav.events' },
  { key: 'exhibit', i18n: 'shell.nav.exhibit' },
  { key: 'visit', i18n: 'shell.nav.visit' },
  { key: 'transport', i18n: 'shell.nav.transport' },
] as const;

/** 3-트랙 진입 레이어 키 (§3C). 관문(SCR-T0)은 미선택 → undefined. */
export type PublicTrack = 'visitor' | 'business' | 'agency';

type TabIcon = ComponentType<SVGProps<SVGSVGElement>>;

/**
 * 3-트랙 진입 탭. 텍스트 대신 선 SVG 아이콘 + 툴팁(title)·aria-label로 의미 전달
 * (아이콘만으로 의미 전달 금지 원칙 → 항상 라벨 텍스트를 접근성 속성에 부여).
 * 관람=사람 · 비즈니스=바이어(브리프케이스) · 협력사=시공(공장) 계열.
 */
const TRACK_TABS: { key: PublicTrack; to: string; i18n: string; icon: TabIcon }[] = [
  { key: 'visitor', to: '/visitor', i18n: 'track.shell.tab.visitor', icon: IconPerson },
  { key: 'business', to: '/business', i18n: 'track.shell.tab.business', icon: IconBuyer },
  { key: 'agency', to: '/agency', i18n: 'track.shell.tab.agency', icon: IconFactory },
];

/**
 * 3-트랙 탭 (§3C-0) — 단일 헤더 내부에 흡수. role=tablist·로빙 탭인덱스·좌우/Home/End 키 이동.
 * 관문(SCR-T0)은 track 미지정(미선택), 서브홈(T1~T3)은 해당 탭 활성(aria-current).
 */
function TrackTabs({ track, variant }: { track?: PublicTrack; variant: 'bar' | 'menu' }) {
  const { t } = useTranslation();
  const refs = useRef<(HTMLAnchorElement | null)[]>([]);
  const activeIdx = TRACK_TABS.findIndex((it) => it.key === track);
  const baseIdx = activeIdx >= 0 ? activeIdx : 0;

  function onKeyDown(e: KeyboardEvent<HTMLAnchorElement>, i: number) {
    let next = i;
    if (e.key === 'ArrowRight' || e.key === 'ArrowDown') next = (i + 1) % TRACK_TABS.length;
    else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp')
      next = (i - 1 + TRACK_TABS.length) % TRACK_TABS.length;
    else if (e.key === 'Home') next = 0;
    else if (e.key === 'End') next = TRACK_TABS.length - 1;
    else return;
    e.preventDefault();
    refs.current[next]?.focus();
  }

  return (
    <div
      className={variant === 'bar' ? 'kxp-tracktabs' : 'kxp-tracktabs kxp-tracktabs--menu'}
      role="tablist"
      aria-label={t('track.shell.tablistAria')}
    >
      {TRACK_TABS.map((it, i) => {
        const isActive = it.key === track;
        const Icon = it.icon;
        const label = t(it.i18n);
        return (
          <Link
            key={it.key}
            ref={(el) => {
              refs.current[i] = el;
            }}
            to={it.to}
            role="tab"
            className={`kxp-tracktab${isActive ? ' is-active' : ''}`}
            aria-selected={isActive}
            aria-current={isActive ? 'page' : undefined}
            aria-label={label}
            title={label}
            tabIndex={i === baseIdx ? 0 : -1}
            onKeyDown={(e) => onKeyDown(e, i)}
          >
            <Icon className="kxp-tracktab__ic" aria-hidden />
            {variant === 'menu' && <span className="kxp-tracktab__label">{label}</span>}
          </Link>
        );
      })}
    </div>
  );
}

interface PublicShellProps {
  children: ReactNode;
  /** 현재 활성 GNB 키 (하이라이트) */
  active?: string;
  /** 현재 트랙 (§3C — 상단 스위처 활성 탭). 관문은 미지정. */
  track?: PublicTrack;
  /** 헤더 우측 주요 CTA 라벨 (없으면 사전등록 기본) */
  cta?: string;
  /** 헤더에 검색 노출 여부 */
  search?: boolean;
  /** 헤더 브랜드명 (마이크로사이트는 업체명) */
  brand?: string;
}

export function PublicShell({
  children,
  active,
  track,
  cta,
  search = true,
  brand = 'KINTEX',
}: PublicShellProps) {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
  const [menuOpen, setMenuOpen] = useState(false);
  const ctaLabel = cta ?? t('shell.cta.register');
  // §3C-V 비주얼·모션 레이어 — 공개 트랙(.kxp) 하위에만 스코프 주입.
  const rootRef = useRef<HTMLDivElement>(null);
  usePublicMotion(rootRef);

  return (
    <div className="kxp" ref={rootRef}>
      {/* ── 단일 상단 헤더 (1 프레임 · COEX 통합 top bar) ── */}
      <header className="kxp-header">
        <div className="kxp-header__inner">
          <div className="kxp-header__left">
            <Link className="kxp-brand" to="/" aria-label={t('shell.homeAria', { brand })}>
              {brand}
            </Link>
            <nav className="kxp-gnb" aria-label={t('shell.primaryMenu')}>
              {GNB.map((it) => (
                <a
                  key={it.key}
                  href="#top"
                  className={`kxp-gnb__link${active === it.key ? ' is-active' : ''}`}
                  aria-current={active === it.key ? 'page' : undefined}
                >
                  {t(it.i18n)}
                </a>
              ))}
            </nav>
          </div>

          <div className="kxp-header__right">
            <TrackTabs track={track} variant="bar" />

            {search && (
              <div className="kxp-search" role="search">
                <IconSearch className="kxp-search__icon" />
                <input
                  className="kxp-search__input"
                  type="search"
                  placeholder={t('shell.searchPlaceholder')}
                  aria-label={t('shell.searchPlaceholder')}
                />
              </div>
            )}

            <LanguageSwitcher variant="light" className="kxp-lang__btn" />

            {isAuthenticated ? (
              <button
                type="button"
                className="kxp-btn kxp-btn--outline kxp-header__login"
                onClick={() => navigate('/home')}
              >
                {t('track.shell.myHome')}
              </button>
            ) : (
              <Link className="kxp-btn kxp-btn--outline kxp-header__login" to="/login">
                {t('shell.login')}
              </Link>
            )}

            <a className="kxp-btn kxp-btn--primary kxp-header__cta" href="#top">
              {ctaLabel}
            </a>

            <button
              type="button"
              className="kxp-header__burger"
              aria-label={menuOpen ? t('shell.menuClose') : t('shell.menuOpen')}
              aria-expanded={menuOpen}
              onClick={() => setMenuOpen((v) => !v)}
            >
              {menuOpen ? <IconClose /> : <IconMenu />}
            </button>
          </div>
        </div>

        {menuOpen && (
          <nav className="kxp-mobilenav" aria-label={t('shell.mobileMenu')}>
            <TrackTabs track={track} variant="menu" />
            {GNB.map((it) => (
              <a key={it.key} href="#top" className="kxp-mobilenav__link">
                {t(it.i18n)}
              </a>
            ))}
            {isAuthenticated ? (
              <button
                type="button"
                className="kxp-btn kxp-btn--outline kxp-mobilenav__cta"
                onClick={() => navigate('/home')}
              >
                {t('track.shell.myHome')}
              </button>
            ) : (
              <Link className="kxp-btn kxp-btn--outline kxp-mobilenav__cta" to="/login">
                {t('shell.login')}
              </Link>
            )}
            <a className="kxp-btn kxp-btn--primary kxp-mobilenav__cta" href="#top">
              {ctaLabel}
            </a>
          </nav>
        )}
      </header>

      <main id="top" className="kxp-main">
        {children}
      </main>

      <footer className="kxp-footer">
        <div className="kxp-footer__inner">
          <div className="kxp-footer__brand">
            <div className="kxp-footer__logo">KINTEX</div>
            <p className="kxp-footer__desc">{t('shell.footer.brandDesc')}</p>
          </div>
          <div className="kxp-footer__cols">
            <div className="kxp-footer__col">
              <h4>{t('shell.footer.quickTitle')}</h4>
              <a href="#top">{t('shell.footer.quickSchedule')}</a>
              <a href="#top">{t('shell.footer.quickExhibit')}</a>
              <a href="#top">{t('shell.footer.quickDirections')}</a>
              <a href="#top">{t('shell.footer.quickSitemap')}</a>
            </div>
            <div className="kxp-footer__col">
              <h4>{t('shell.footer.supportTitle')}</h4>
              <a href="#top">{t('shell.footer.supportPrivacy')}</a>
              <a href="#top">{t('shell.footer.supportTerms')}</a>
              <a href="#top">{t('shell.footer.supportContact')}</a>
            </div>
            <div className="kxp-footer__col">
              <h4>{t('shell.footer.contactTitle')}</h4>
              <span>{t('shell.footer.contactAddress')}</span>
              <span>{t('shell.footer.contactTel')}</span>
              <span>{t('shell.footer.contactEmail')}</span>
            </div>
          </div>
        </div>
        <div className="kxp-footer__bottom">{t('shell.footer.bottom')}</div>
      </footer>
    </div>
  );
}
