/*
 * AI 전시·행사 기획 브리핑 (SCR-T1 레이아웃 4) — 연/월 관점 토글.
 * 연간 = 12개월 타임라인(월별 건수 바) + "AI 요약" 헤드라인, 월간 = 선택 월 전시 리스트 + AI 월간 요약.
 * 데이터: publicApi.listMonthlySummary(연간 근거) + listCalendar(월간 근거) — 크롤 적재 DB 서빙.
 * AI 요약 문구는 assistant 미가용 시 데이터 기반 정적 폴백(degraded). 이모지 금지·선 SVG·kx 토큰.
 */
import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { AiLabel } from '../../components/ui/Badge';
import { publicApi, type MonthlySummary, type PublicCalendarEvent } from './publicApi';
import { formatRange, dday, errorMessage } from './publicFormat';
import { ddayClass } from './trackShared';
import { IconChevronRight, IconCalendar, IconPin, IconSparkles } from './publicIcons';

type View = 'year' | 'month';
const NOW = new Date();

export function AiPlanningBriefing() {
  const { t } = useTranslation();
  const [view, setView] = useState<View>('year');
  const [year] = useState(NOW.getFullYear());
  const [month, setMonth] = useState(NOW.getMonth() + 1);

  const [summary, setSummary] = useState<MonthlySummary[]>([]);
  const [sumLoading, setSumLoading] = useState(true);
  const [sumErr, setSumErr] = useState('');

  const [monthEvents, setMonthEvents] = useState<PublicCalendarEvent[]>([]);
  const [mLoading, setMLoading] = useState(false);
  const [mErr, setMErr] = useState('');

  // 연간 월별 요약 로드(1회).
  useEffect(() => {
    let alive = true;
    setSumLoading(true);
    publicApi
      .listMonthlySummary(year)
      .then((list) => alive && (setSummary(list), setSumErr('')))
      .catch((e) => alive && setSumErr(errorMessage(e)))
      .finally(() => alive && setSumLoading(false));
    return () => {
      alive = false;
    };
  }, [year]);

  // 월간 전시 로드(월 변경 시).
  useEffect(() => {
    if (view !== 'month') return;
    let alive = true;
    setMLoading(true);
    publicApi
      .listCalendar({ year, month, limit: 40 })
      .then((list) => alive && (setMonthEvents(list), setMErr('')))
      .catch((e) => alive && setMErr(errorMessage(e)))
      .finally(() => alive && setMLoading(false));
    return () => {
      alive = false;
    };
  }, [view, year, month]);

  const byMonth = useMemo(() => {
    const m = new Map<number, number>();
    summary.forEach((s) => {
      if (s.eventMonth != null) m.set(s.eventMonth, (m.get(s.eventMonth) ?? 0) + (s.eventCount ?? 0));
    });
    return m;
  }, [summary]);

  const maxCount = useMemo(() => Math.max(1, ...Array.from(byMonth.values())), [byMonth]);
  const totalCount = useMemo(
    () => Array.from(byMonth.values()).reduce((a, b) => a + b, 0),
    [byMonth],
  );
  const peakMonth = useMemo(() => {
    let best = 0;
    let bestC = -1;
    byMonth.forEach((c, mo) => {
      if (c > bestC) {
        bestC = c;
        best = mo;
      }
    });
    return best;
  }, [byMonth]);
  const monthCount = byMonth.get(month) ?? monthEvents.length;

  return (
    <section className="kxp-section kxp-section--alt" id="briefing" aria-label={t('track.visitor.briefing.title')}>
      <div className="kxp-wrap">
        <div className="kxp-section__head kxp-briefing__head">
          <div>
            <h2 className="kxp-section__title"><IconSparkles className="kx-title-ic" width={22} height={22} />{t('track.visitor.briefing.title')}</h2>
            <p className="kxp-section__sub">{t('track.visitor.briefing.sub')}</p>
          </div>
          <div className="kxp-briefing__toggle" role="tablist" aria-label={t('track.visitor.briefing.title')}>
            <button
              type="button"
              role="tab"
              aria-selected={view === 'year'}
              className={`kxp-seg${view === 'year' ? ' is-active' : ''}`}
              onClick={() => setView('year')}
            >
              {t('track.visitor.briefing.viewYear', { year })}
            </button>
            <button
              type="button"
              role="tab"
              aria-selected={view === 'month'}
              className={`kxp-seg${view === 'month' ? ' is-active' : ''}`}
              onClick={() => setView('month')}
            >
              {t('track.visitor.briefing.viewMonth')}
            </button>
          </div>
        </div>

        {view === 'year' ? (
          <div className="kxp-briefing__year">
            {/* AI 요약 헤드라인 */}
            <div className="kxp-briefing__ai">
              <AiLabel>{t('track.visitor.briefing.aiSummary')}</AiLabel>
              <p className="kxp-briefing__aitext">
                {sumLoading
                  ? t('track.visitor.briefing.loading')
                  : sumErr || totalCount === 0
                    ? t('track.visitor.briefing.empty')
                    : t('track.visitor.briefing.yearSummary', {
                        year,
                        count: totalCount,
                        peak: t('track.visitor.briefing.monthLabel', { month: peakMonth || month }),
                      })}
              </p>
            </div>

            {/* 12개월 타임라인 */}
            {sumLoading ? (
              <div className="kxp-briefing__timeline kxp-briefing__timeline--skel" aria-hidden>
                {Array.from({ length: 12 }).map((_, i) => (
                  <div key={i} className="kxp-briefing__lane">
                    <span className="kxp-briefing__bar" style={{ height: '30%' }} />
                    <span className="kxp-briefing__mo">{i + 1}</span>
                  </div>
                ))}
              </div>
            ) : (
              <div className="kxp-briefing__timeline" role="img" aria-label={t('track.visitor.briefing.title')}>
                {Array.from({ length: 12 }).map((_, i) => {
                  const mo = i + 1;
                  const c = byMonth.get(mo) ?? 0;
                  const h = Math.max(6, Math.round((c / maxCount) * 100));
                  const isPeak = c > 0 && c === maxCount;
                  return (
                    <button
                      key={mo}
                      type="button"
                      className={`kxp-briefing__lane${isPeak ? ' is-peak' : ''}`}
                      onClick={() => {
                        setMonth(mo);
                        setView('month');
                      }}
                      title={t('track.visitor.briefing.eventsCount', { count: c })}
                    >
                      <span className="kxp-briefing__count">{c}</span>
                      <span className="kxp-briefing__bar" style={{ height: `${h}%` }} />
                      <span className="kxp-briefing__mo">{mo}</span>
                    </button>
                  );
                })}
              </div>
            )}
          </div>
        ) : (
          <div className="kxp-briefing__month">
            <div className="kxp-briefing__nav">
              <button
                type="button"
                className="kxp-briefing__navbtn"
                aria-label={t('track.visitor.briefing.prevMonth')}
                onClick={() => setMonth((m) => (m <= 1 ? 12 : m - 1))}
              >
                <IconChevronRight width={18} height={18} style={{ transform: 'rotate(180deg)' }} />
              </button>
              <span className="kxp-briefing__navlabel">
                {year}. {String(month).padStart(2, '0')}
              </span>
              <button
                type="button"
                className="kxp-briefing__navbtn"
                aria-label={t('track.visitor.briefing.nextMonth')}
                onClick={() => setMonth((m) => (m >= 12 ? 1 : m + 1))}
              >
                <IconChevronRight width={18} height={18} />
              </button>
            </div>

            <div className="kxp-briefing__ai">
              <AiLabel>{t('track.visitor.briefing.aiSummary')}</AiLabel>
              <p className="kxp-briefing__aitext">
                {mLoading
                  ? t('track.visitor.briefing.loading')
                  : monthCount === 0
                    ? t('track.visitor.briefing.empty')
                    : t('track.visitor.briefing.monthSummary', { count: monthCount })}
              </p>
            </div>

            {mLoading ? (
              <p className="kxp-empty" role="status">
                {t('home.loading')}
              </p>
            ) : mErr ? (
              <p className="kxp-empty" role="alert" style={{ color: 'var(--color-error)' }}>
                {mErr}
              </p>
            ) : monthEvents.length === 0 ? (
              <p className="kxp-empty">{t('track.visitor.briefing.empty')}</p>
            ) : (
              <div className="kxp-briefing__list">
                {monthEvents.map((ev) => {
                  const d = dday(ev.startDate);
                  const ended = ev.lifecycle === 'ENDED';
                  return (
                    <article key={ev.id} className="kxp-briefing__row">
                      <div className="kxp-briefing__rowmain">
                        <div className="kxp-briefing__rowname">{ev.name}</div>
                        <div className="kxp-briefing__rowmeta">
                          <span>
                            <IconCalendar width={15} height={15} /> {formatRange(ev.startDate, ev.endDate)}
                          </span>
                          {ev.hallLabel && (
                            <span>
                              <IconPin width={15} height={15} /> {ev.hallLabel}
                            </span>
                          )}
                          {ev.category && <span className="kxp-tag">{ev.category}</span>}
                        </div>
                      </div>
                      {!ended && d >= 0 && (
                        <span className={`kxp-dday ${ddayClass(d)}`}>
                          {d === 0 ? t('home.ddayZero') : t('home.dday', { n: d })}
                        </span>
                      )}
                    </article>
                  );
                })}
              </div>
            )}
          </div>
        )}
      </div>
    </section>
  );
}
