/*
 * SCR-P1 공개 홍보 사이트 홈 (M12) — 비로그인 공개.
 * design.md §3B. 히어로 + 진행/예정 행사 카드 + 교통(GTX-A) 섹션.
 * 데이터: GET /api/public/events (공개 카탈로그, 비인증).
 */
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { PublicShell } from './PublicShell';
import { publicApi, type PublicEvent } from './publicApi';
import { deriveStatus, dday, formatRange, errorMessage } from './publicFormat';
import {
  IconSparkles,
  IconCalendar,
  IconPin,
  IconArrowRight,
  IconChevronRight,
  IconTrain,
  IconBus,
  IconParking,
  IconShuttle,
  IconMap,
  IconVenue,
  IconBuyer,
  IconFactory,
  IconQr,
  IconRobot,
  IconTarget,
} from './publicIcons';
import type { ComponentType, SVGProps } from 'react';

function ddayClass(d: number) {
  if (d <= 3) return 'kxp-dday kxp-dday--soon';
  if (d <= 7) return 'kxp-dday kxp-dday--warn';
  return 'kxp-dday';
}

type Ico = ComponentType<SVGProps<SVGSVGElement>>;

/** P1 제품 아이덴티티 — 역할별 가치 카드 4종(주최자·참가업체·공사업체·관람객). */
const ROLE_CARDS: {
  key: string;
  icon: Ico;
  /** 진입 CTA 목적지(로그인 또는 사전등록). */
  to: string;
}[] = [
  { key: 'organizer', icon: IconVenue, to: '/login' },
  { key: 'exhibitor', icon: IconBuyer, to: '/login' },
  { key: 'contractor', icon: IconFactory, to: '/login' },
  { key: 'visitor', icon: IconQr, to: '#events' },
];

/** P1 핵심 기능 스텝(과장 없이 실기능만): AI 배치 → 나노바나나 시안 → 역경매 옥션 → 실시간 정산. */
const FEATURE_STEPS: { key: string; icon: Ico }[] = [
  { key: 'layout', icon: IconRobot },
  { key: 'render', icon: IconSparkles },
  { key: 'auction', icon: IconFactory },
  { key: 'settle', icon: IconTarget },
];

/** 진행중·예정 우선 정렬 후 상위 N건만 홈에 노출. */
function pickFeatured(events: PublicEvent[], max = 6): PublicEvent[] {
  const rank = (e: PublicEvent) => {
    const s = deriveStatus(e.startDate, e.endDate);
    return s === 'ongoing' ? 0 : s === 'upcoming' ? 1 : 2;
  };
  return [...events].sort((a, b) => rank(a) - rank(b)).slice(0, max);
}

export function PublicHomePage() {
  const { t } = useTranslation();
  const [events, setEvents] = useState<PublicEvent[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    let alive = true;
    setLoading(true);
    publicApi
      .listEvents()
      .then((list) => {
        if (alive) {
          setEvents(pickFeatured(list));
          setError('');
        }
      })
      .catch((e) => alive && setError(errorMessage(e)))
      .finally(() => alive && setLoading(false));
    return () => {
      alive = false;
    };
  }, []);

  return (
    <PublicShell active="events">
      {/* 히어로 */}
      <section
        className="kxp-hero"
        aria-label={t('home.heroAria')}
        style={{
          backgroundColor: 'var(--color-canvas-bg)',
        }}
      >
        <div
          className="kxp-hero__bg"
          style={{
            background:
              'linear-gradient(135deg, #12233b 0%, #1f3a5f 55%, #0066b3 130%)',
          }}
          aria-hidden
        />
        <div className="kxp-hero__scrim" aria-hidden />
        <div className="kxp-hero__inner">
          <div className="kxp-hero__content">
            <span className="kxp-hero__eyebrow">
              <IconSparkles width={16} height={16} /> {t('home.prodEyebrow')}
            </span>
            <h1 className="kxp-hero__title">{t('home.prodTitle')}</h1>
            <p className="kxp-hero__lead">{t('home.prodTagline')}</p>
            <div className="kxp-hero__actions">
              <Link className="kxp-btn kxp-btn--primary kxp-btn--lg" to="/login">
                {t('home.ctaLogin')}
              </Link>
              <a className="kxp-btn kxp-btn--ghost kxp-btn--lg" href="#events">
                {t('home.ctaPreReg')}
              </a>
            </div>
          </div>
        </div>
      </section>

      {/* 제품 소개 — 역할별 가치 카드 4장 (제품 아이덴티티) */}
      <section className="kxp-section" id="product" aria-label={t('home.roleAria')}>
        <div className="kxp-wrap">
          <div className="kxp-section__head">
            <div>
              <h2 className="kxp-section__title">{t('home.roleTitle')}</h2>
              <p className="kxp-section__sub">{t('home.roleSub')}</p>
            </div>
          </div>

          <div className="kxp-roles">
            {ROLE_CARDS.map(({ key, icon: Icon, to }) => {
              const cta = (
                <span className="kxp-role__cta">
                  {t(`home.roleCard.${key}.cta`)} <IconChevronRight width={16} height={16} />
                </span>
              );
              return (
                <article key={key} className="kxp-role">
                  <span className="kxp-role__ic" aria-hidden>
                    <Icon width={26} height={26} />
                  </span>
                  <span className="kxp-role__badge">{t(`home.roleCard.${key}.badge`)}</span>
                  <h3 className="kxp-role__title">{t(`home.roleCard.${key}.title`)}</h3>
                  <p className="kxp-role__desc">{t(`home.roleCard.${key}.desc`)}</p>
                  {to.startsWith('#') ? (
                    <a className="kxp-role__link" href={to}>
                      {cta}
                    </a>
                  ) : (
                    <Link className="kxp-role__link" to={to}>
                      {cta}
                    </Link>
                  )}
                </article>
              );
            })}
          </div>
        </div>
      </section>

      {/* 핵심 기능 스트립 — AI 배치 → 시공 시안 → 역경매 옥션 → 실시간 정산 */}
      <section className="kxp-section kxp-section--alt" aria-label={t('home.stepsAria')}>
        <div className="kxp-wrap">
          <div className="kxp-section__head">
            <div>
              <h2 className="kxp-section__title">{t('home.stepsTitle')}</h2>
              <p className="kxp-section__sub">{t('home.stepsSub')}</p>
            </div>
          </div>

          <ol className="kxp-steps">
            {FEATURE_STEPS.map(({ key, icon: Icon }, i) => (
              <li key={key} className="kxp-step">
                <div className="kxp-step__card">
                  <span className="kxp-step__ic" aria-hidden>
                    <Icon width={24} height={24} />
                  </span>
                  <span className="kxp-step__no">{i + 1}</span>
                  <h4 className="kxp-step__title">{t(`home.featStep.${key}.title`)}</h4>
                  <p className="kxp-step__desc">{t(`home.featStep.${key}.desc`)}</p>
                </div>
                {i < FEATURE_STEPS.length - 1 && (
                  <span className="kxp-step__arrow" aria-hidden>
                    <IconArrowRight width={20} height={20} />
                  </span>
                )}
              </li>
            ))}
          </ol>
        </div>
      </section>

      {/* 진행/예정 행사 */}
      <section className="kxp-section" id="events" aria-label={t('home.eventsAria')}>
        <div className="kxp-wrap">
          <div className="kxp-section__head">
            <div>
              <h2 className="kxp-section__title">{t('home.eventsTitle')}</h2>
              <p className="kxp-section__sub">{t('home.eventsSub')}</p>
            </div>
            <a className="kxp-section__more" href="#events">
              {t('home.eventsMore')} <IconArrowRight width={16} height={16} />
            </a>
          </div>

          {loading && (
            <p className="kxp-empty" role="status">
              {t('home.loading')}
            </p>
          )}
          {!loading && error && (
            <p className="kxp-empty" role="alert" style={{ color: 'var(--color-error)' }}>
              {error}
            </p>
          )}
          {!loading && !error && events.length === 0 && (
            <p className="kxp-empty">{t('home.empty')}</p>
          )}

          {!loading && !error && events.length > 0 && (
            <div className="kxp-eventgrid">
              {events.map((ev, i) => {
                const status = deriveStatus(ev.startDate, ev.endDate);
                const d = dday(ev.startDate);
                const accentAi = i % 3 === 1;
                return (
                  <article
                    key={ev.id}
                    className="kxp-ecard"
                    style={accentAi ? { borderLeftColor: 'var(--color-ai-accent)' } : undefined}
                  >
                    <div className="kxp-ecard__media">
                      <div
                        style={{
                          width: '100%',
                          height: '100%',
                          background: accentAi
                            ? 'linear-gradient(135deg, #6d4aff 0%, #1f29fc 100%)'
                            : 'linear-gradient(135deg, #0066b3 0%, #004c86 100%)',
                        }}
                        aria-hidden
                      />
                      {accentAi && (
                        <span className="kxp-ecard__topright kxp-chip kxp-chip--ai">
                          <IconSparkles width={13} height={13} /> {t('home.aiOptimized')}
                        </span>
                      )}
                      {status === 'ongoing' ? (
                        <span className="kxp-ecard__botleft kxp-dday kxp-dday--soon">{t('home.ongoing')}</span>
                      ) : status === 'ended' ? (
                        <span className="kxp-ecard__botleft kxp-dday">{t('home.ended')}</span>
                      ) : (
                        <span className={`kxp-ecard__botleft ${ddayClass(d)}`}>
                          {d === 0 ? t('home.ddayZero') : t('home.dday', { n: d })}
                        </span>
                      )}
                    </div>
                    <div className="kxp-ecard__body">
                      <div className="kxp-ecard__tags">
                        <span className="kxp-tag">{t('home.tagExhibition')}</span>
                        {ev.boothCount != null && ev.boothCount > 0 && (
                          <span className="kxp-tag">{t('home.booth', { count: ev.boothCount })}</span>
                        )}
                      </div>
                      <h3 className="kxp-ecard__title">{ev.name}</h3>
                      <div className="kxp-ecard__meta">
                        <span>
                          <IconCalendar width={18} height={18} /> {formatRange(ev.startDate, ev.endDate)}
                        </span>
                        <span>
                          <IconPin width={18} height={18} /> {ev.hallLabel ?? t('home.hallTbd')}
                        </span>
                      </div>
                      <Link
                        className="kxp-btn kxp-btn--primary kxp-btn--block"
                        to={`/public/events/${encodeURIComponent(ev.id)}/register`}
                      >
                        {t('home.register')}
                      </Link>
                    </div>
                  </article>
                );
              })}
            </div>
          )}
        </div>
      </section>

      {/* 교통 */}
      <section className="kxp-section kxp-section--alt" id="transport" aria-label={t('home.transportAria')}>
        <div className="kxp-wrap">
          <div className="kxp-transport">
            <div>
              <h2 className="kxp-section__title">{t('home.transportTitle')}</h2>
              <p className="kxp-section__sub">{t('home.transportSub')}</p>

              <div className="kxp-transport__gtx">
                <span className="kxp-transport__gtx-ic">
                  <IconTrain width={30} height={30} />
                </span>
                <div>
                  <h4>{t('home.gtxTitle')}</h4>
                  <p>{t('home.gtxDesc')}</p>
                </div>
              </div>

              <div className="kxp-transport__opts">
                <div className="kxp-transport__opt">
                  <IconBus />
                  <h5>{t('home.transit')}</h5>
                  <span>{t('home.transitDesc')}</span>
                </div>
                <div className="kxp-transport__opt">
                  <IconParking />
                  <h5>{t('home.parking')}</h5>
                  <span>{t('home.parkingDesc')}</span>
                </div>
                <div className="kxp-transport__opt">
                  <IconShuttle />
                  <h5>{t('home.shuttle')}</h5>
                  <span>{t('home.shuttleDesc')}</span>
                </div>
              </div>
            </div>

            <div
              className="kxp-transport__map"
              style={{
                background:
                  'linear-gradient(135deg, #d9eaf7 0%, #eff6fc 60%, #ffffff 100%)',
              }}
              role="img"
              aria-label={t('home.mapAria')}
            >
              <div className="kxp-transport__mapcard">
                <div>
                  <small>{t('home.mapAddress')}</small>
                  <strong>{t('home.mapPlace')}</strong>
                </div>
                <a
                  className="kxp-btn kxp-btn--primary"
                  href="#transport"
                  aria-label={t('home.mapViewAria')}
                  style={{ padding: 12, borderRadius: '9999px' }}
                >
                  <IconMap />
                </a>
              </div>
            </div>
          </div>
        </div>
      </section>
    </PublicShell>
  );
}
