/*
 * §3C 3-트랙(SCR-T0~T3) 공용 헬퍼 — 행사 로드 훅 + 행사 카드 그리드.
 * 기존 SCR-P1(PublicHomePage) 컨벤션·publicApi·publicFormat·publicIcons 재사용.
 */
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { publicApi, type PublicEvent } from './publicApi';
import { deriveStatus, dday, formatRange, errorMessage } from './publicFormat';
import { IconCalendar, IconPin } from './publicIcons';

export 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';
}

/** 진행중·예정 우선 정렬 후 상위 N건. */
export function pickFeatured(events: PublicEvent[], max = 8): 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 interface EventsState {
  events: PublicEvent[];
  loading: boolean;
  error: string;
}

/** 공개 행사 카탈로그 로드(비인증). */
export function usePublicEvents(max = 8): EventsState {
  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, max));
          setError('');
        }
      })
      .catch((e) => alive && setError(errorMessage(e)))
      .finally(() => alive && setLoading(false));
    return () => {
      alive = false;
    };
  }, [max]);

  return { events, loading, error };
}

/**
 * 행사 포스터 미디어 — 실 포스터(/media/posters/*.jpg) 우선, onerror·부재 시 브랜드
 * 그라디언트+라인 패턴 폴백(§3C-V V-4, CLS 0 · aspect-ratio 예약).
 */
function EventPoster({ name, posterUrl, eager }: { name: string; posterUrl?: string | null; eager?: boolean }) {
  const [failed, setFailed] = useState(false);
  const showImg = !!posterUrl && !failed;
  return (
    <>
      {showImg ? (
        <img
          className="kxp-ecard__poster"
          src={posterUrl as string}
          alt=""
          loading={eager ? 'eager' : 'lazy'}
          decoding="async"
          onError={() => setFailed(true)}
        />
      ) : (
        <div className="kxp-ecard__poster pub-fallback-gradient pub-pattern-grid" aria-hidden>
          <span className="kxp-ecard__posterfallback">{name}</span>
        </div>
      )}
    </>
  );
}

/**
 * 행사 카드 그리드 — SCR-P1 카드 자산 재사용. 빈/로딩/에러 인라인 처리.
 * variant='rail' → 가로 오토스크롤 레일(§3C-V V-3, .pub-rail--auto). 기본 'grid'(불변).
 */
export function EventGrid({
  state,
  variant = 'grid',
}: {
  state: EventsState;
  variant?: 'grid' | 'rail';
}) {
  const { t } = useTranslation();
  const { events, loading, error } = state;

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

  const isRail = variant === 'rail';
  const gridCls = isRail ? 'kxp-eventgrid kxp-eventgrid--rail pub-rail--auto' : 'kxp-eventgrid';

  return (
    <div className={gridCls} data-interval={isRail ? '4500' : undefined}>
      {events.map((ev) => {
        const status = deriveStatus(ev.startDate, ev.endDate);
        const d = dday(ev.startDate);
        return (
          <article key={ev.id} className="kxp-ecard pub-card--lift" data-rail-item={isRail ? '' : undefined}>
            <div className="kxp-ecard__media pub-card__media">
              <EventPoster name={ev.name} posterUrl={ev.posterUrl} />
              {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>
  );
}
