/*
 * 공용 AI 관람 도우미 (SCR-T1 히어로 중심 요소) — 재사용 컴포넌트.
 * PLANNING §8A 계약 정합: 자연어 입력(role=search) + 예시 질문칩 + 대화형 답변 패널
 * (답변·구조화 카드(전시/교통/가이드)·근거 인용·후속칩·AI 고지문·degraded 안내).
 * 데이터: publicApi.askVisitorAssistant → POST /api/public/ai/visitor-assistant(크롤 적재 DB 근거).
 * 상태: 대기(placeholder 로테이션)·생각중·성공·degraded(provider=search|none)·에러·빈결과(grounded=false).
 * 이모지 금지·선 SVG·kx 토큰만·AiLabel(보라) 구분·aria-live=polite.
 */
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { AiLabel } from '../../components/ui/Badge';
import { publicApi, type AssistantResult } from './publicApi';
import { formatRange, dday, errorMessage } from './publicFormat';
import { ddayClass } from './trackShared';
import {
  IconSend,
  IconCalendar,
  IconPin,
  IconTrain,
  IconInfo,
  IconLink,
  IconArrowRight,
} from './publicIcons';

/** 예시/후속 질문칩 i18n 키. */
const EXAMPLE_KEYS = ['chip1', 'chip2', 'chip3', 'chip4', 'chip5'] as const;
const FOLLOWUP_KEYS = ['followup1', 'followup2', 'followup3'] as const;

type Phase = 'idle' | 'thinking' | 'done' | 'error';

export function AiAssistant() {
  const { t } = useTranslation();
  const [question, setQuestion] = useState('');
  const [phase, setPhase] = useState<Phase>('idle');
  const [result, setResult] = useState<AssistantResult | null>(null);
  const [error, setError] = useState('');
  const [phIdx, setPhIdx] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);
  const reqSeq = useRef(0);

  // 대기 중 placeholder 로테이션(입력 비어 있을 때만).
  useEffect(() => {
    if (phase !== 'idle' || question) return;
    const id = window.setInterval(() => setPhIdx((i) => (i + 1) % EXAMPLE_KEYS.length), 3800);
    return () => window.clearInterval(id);
  }, [phase, question]);

  const ask = useCallback(
    (q: string) => {
      const query = q.trim();
      if (!query) return;
      const seq = ++reqSeq.current;
      setQuestion(query);
      setPhase('thinking');
      setError('');
      publicApi
        .askVisitorAssistant(query)
        .then((res) => {
          if (seq !== reqSeq.current) return;
          setResult(res);
          setPhase('done');
        })
        .catch((e) => {
          if (seq !== reqSeq.current) return;
          setError(errorMessage(e));
          setPhase('error');
        });
    },
    [],
  );

  const onSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    ask(question);
  };

  const placeholder = t(`ai.assistant.${EXAMPLE_KEYS[phIdx]}`);

  return (
    <div className="kxp-ai">
      <form className="kxp-ai__bar" role="search" onSubmit={onSubmit}>
        <span className="kxp-ai__badge" aria-hidden>
          <AiLabel>{t('ai.assistant.label')}</AiLabel>
        </span>
        <input
          ref={inputRef}
          className="kxp-ai__input"
          type="search"
          value={question}
          onChange={(e) => setQuestion(e.target.value)}
          placeholder={placeholder}
          aria-label={t('ai.assistant.inputAria')}
          enterKeyHint="search"
        />
        <button
          type="submit"
          className="kxp-ai__send"
          aria-label={t('ai.assistant.sendAria')}
          disabled={phase === 'thinking' || !question.trim()}
        >
          <IconSend width={20} height={20} />
        </button>
      </form>

      {/* 예시 질문칩 */}
      <div className="kxp-ai__chips" aria-label={t('ai.assistant.chipsLabel')}>
        {EXAMPLE_KEYS.map((k) => (
          <button
            key={k}
            type="button"
            className="kxp-ai__chip"
            onClick={() => ask(t(`ai.assistant.${k}`))}
          >
            {t(`ai.assistant.${k}`)}
          </button>
        ))}
      </div>

      {/* 대화형 답변 패널 */}
      <div className="kxp-ai__panel" aria-live="polite" aria-atomic="false">
        {phase === 'thinking' && (
          <div className="kxp-ai__thinking" role="status">
            <span className="kxp-ai__dots" aria-hidden>
              <i />
              <i />
              <i />
            </span>
            {t('ai.assistant.thinking')}
          </div>
        )}

        {phase === 'error' && (
          <div className="kxp-ai__answer kxp-ai__answer--error" role="alert">
            <p className="kxp-ai__text">{error || t('ai.assistant.error')}</p>
            <button type="button" className="kxp-btn kxp-btn--outline" onClick={() => ask(question)}>
              {t('ai.assistant.retry')}
            </button>
          </div>
        )}

        {phase === 'done' && result && <AnswerCard result={result} onFollowup={ask} />}
      </div>
    </div>
  );
}

function AnswerCard({
  result,
  onFollowup,
}: {
  result: AssistantResult;
  onFollowup: (q: string) => void;
}) {
  const { t } = useTranslation();
  const { answer, events, transport, guide, citations, grounded, degraded } = result;
  const hasCards = events.length > 0 || transport.length > 0 || guide.length > 0;

  return (
    <div className="kxp-ai__answer">
      <div className="kxp-ai__answerhead">
        <AiLabel>{t('ai.assistant.providerAi')}</AiLabel>
        {degraded && <span className="kxp-ai__degraded">{t('ai.assistant.degraded')}</span>}
      </div>

      {answer ? (
        <p className="kxp-ai__text">{answer}</p>
      ) : (
        <p className="kxp-ai__text">{t('ai.assistant.notFound')}</p>
      )}

      {!grounded && !answer && <p className="kxp-ai__text kxp-ai__muted">{t('ai.assistant.notFound')}</p>}

      {hasCards && (
        <div className="kxp-ai__cards">
          {events.length > 0 && (
            <section className="kxp-ai__group" aria-label={t('ai.assistant.cardEventsTitle')}>
              <h4 className="kxp-ai__grouptitle">{t('ai.assistant.cardEventsTitle')}</h4>
              <div className="kxp-ai__grouprows">
                {events.slice(0, 4).map((ev) => {
                  const d = dday(ev.startDate);
                  const ended = ev.lifecycle === 'ENDED';
                  return (
                    <article key={ev.id} className="kxp-ai__evcard">
                      <div className="kxp-ai__evposter" aria-hidden>
                        {ev.posterUrl ? (
                          <img src={ev.posterUrl} alt="" loading="lazy" />
                        ) : (
                          <span className="kxp-ai__evfallback">{ev.name.slice(0, 2)}</span>
                        )}
                      </div>
                      <div className="kxp-ai__evbody">
                        <div className="kxp-ai__evname">{ev.name}</div>
                        <div className="kxp-ai__evmeta">
                          <span>
                            <IconCalendar width={15} height={15} /> {formatRange(ev.startDate, ev.endDate)}
                          </span>
                          {ev.hallLabel && (
                            <span>
                              <IconPin width={15} height={15} /> {ev.hallLabel}
                            </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>
            </section>
          )}

          {transport.length > 0 && (
            <section className="kxp-ai__group" aria-label={t('ai.assistant.cardTransportTitle')}>
              <h4 className="kxp-ai__grouptitle">{t('ai.assistant.cardTransportTitle')}</h4>
              <div className="kxp-ai__grouprows">
                {transport.slice(0, 3).map((tr) => (
                  <div key={tr.id} className="kxp-ai__inforow">
                    <span className="kxp-ai__ic" aria-hidden>
                      <IconTrain width={18} height={18} />
                    </span>
                    <div>
                      <div className="kxp-ai__infotitle">{tr.lineName || tr.mode}</div>
                      <div className="kxp-ai__infodesc">
                        {[tr.route, tr.travelTime].filter(Boolean).join(' · ')}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </section>
          )}

          {guide.length > 0 && (
            <section className="kxp-ai__group" aria-label={t('ai.assistant.cardGuideTitle')}>
              <h4 className="kxp-ai__grouptitle">{t('ai.assistant.cardGuideTitle')}</h4>
              <div className="kxp-ai__grouprows">
                {guide.slice(0, 3).map((g) => (
                  <div key={g.id} className="kxp-ai__inforow">
                    <span className="kxp-ai__ic" aria-hidden>
                      <IconInfo width={18} height={18} />
                    </span>
                    <div>
                      <div className="kxp-ai__infotitle">{g.title}</div>
                      {g.summary && <div className="kxp-ai__infodesc">{g.summary}</div>}
                    </div>
                  </div>
                ))}
              </div>
            </section>
          )}
        </div>
      )}

      {/* 후속 질문칩 */}
      <div className="kxp-ai__followups" aria-label={t('ai.assistant.followupLabel')}>
        {FOLLOWUP_KEYS.map((k) => (
          <button
            key={k}
            type="button"
            className="kxp-ai__chip kxp-ai__chip--sm"
            onClick={() => onFollowup(t(`ai.assistant.${k}`))}
          >
            {t(`ai.assistant.${k}`)}
          </button>
        ))}
        <a className="kxp-ai__chip kxp-ai__chip--sm" href="#showcase">
          {t('ai.assistant.register')} <IconArrowRight width={14} height={14} />
        </a>
      </div>

      {/* 근거 출처 인용 */}
      {citations.length > 0 && (
        <div className="kxp-ai__cites">
          <span className="kxp-ai__citelabel">{t('ai.assistant.citations')}</span>
          {citations.slice(0, 6).map((c, i) =>
            c.sourceUrl ? (
              <a
                key={`${c.id}-${i}`}
                className="kxp-ai__cite"
                href={c.sourceUrl}
                target="_blank"
                rel="noreferrer noopener"
              >
                <IconLink width={13} height={13} /> {c.title}
              </a>
            ) : (
              <span key={`${c.id}-${i}`} className="kxp-ai__cite">
                <IconLink width={13} height={13} /> {c.title}
              </span>
            ),
          )}
        </div>
      )}

      {/* AI 고지문 — 제거 불가·상시 노출 */}
      <p className="kxp-ai__disclaimer">{t('ai.assistant.disclaimer')}</p>
    </div>
  );
}
