// ─── Wave 27-B — GaokaoQABlock ("🤖 AI 问答" chip + modal) ──────────────────
// Renders a chip that opens a modal for LLM-grounded Q&A using /api/gaokao/calculate?action=qa
// (consolidated into calculate.js per Vercel 12-function cap; Wave 30 hotfix).
// Caches last 5 questions in localStorage.
// i18n keys: gk.qa.{chip,placeholder,submit,thinking,emptyAnswer,noDataAnswer,scopeNote,citations}
//
// IIFE-wrapped so it doesn't pollute global scope with helper vars.
;(function () {

  const QA_CACHE_KEY = 'pb_gaokao_qa_history';
  const QA_CACHE_MAX = 5;

  // ── localStorage helpers ──────────────────────────────────────────────────

  function _loadHistory() {
    try {
      const raw = window.localStorage.getItem(QA_CACHE_KEY);
      return raw ? JSON.parse(raw) : [];
    } catch (_) {
      return [];
    }
  }

  function _saveHistory(history) {
    try {
      window.localStorage.setItem(QA_CACHE_KEY, JSON.stringify(history.slice(-QA_CACHE_MAX)));
    } catch (_) {}
  }

  // ── Main component ────────────────────────────────────────────────────────

  function GaokaoQABlock({ lang, province, year }) {
    const t = (window.I18N && window.I18N[lang] && window.I18N[lang].gk && window.I18N[lang].gk.qa) || {};
    const chip        = t.chip        || '🤖 AI 问答';
    const placeholder = t.placeholder || '输入你的高考问题…';
    const submitLabel = t.submit      || '提问';
    const thinkingMsg = t.thinking    || '正在思考…';
    const emptyAnswer = t.emptyAnswer || '暂无相关数据';
    const noDataAnswer = t.noDataAnswer || (lang === 'en'
      ? 'AI Q&A currently only covers ingested Hainan gaokao school, major, cutoff, and restriction data. No matching record was found for this question. Please use the free plan generator for a ranked plan, or book an advisor to verify edge cases.'
      : 'AI 问答当前仅支持已收录的海南院校、专业、投档线和章程限制数据。本题暂无匹配记录，请先使用免费志愿方案生成可参考志愿表，或预约顾问核验特殊情况。');
    const scopeNote = t.scopeNote || (lang === 'en'
      ? 'Data scope: ingested Hainan gaokao school, major, cutoff, and restriction records only. Answers are for triage and should be checked with the plan result and official admission sources.'
      : '数据范围：当前仅覆盖已收录的海南高考院校、专业、投档线和章程限制数据。回答仅作初步判断，请结合测算结果与官方招生资料核验。');
    const citationsLabel = t.citations || '参考来源';

    const [open, setOpen]       = React.useState(false);
    const [query, setQuery]     = React.useState('');
    const [loading, setLoading] = React.useState(false);
    const [answer, setAnswer]   = React.useState('');
    const [citations, setCitations] = React.useState([]);
    const [error, setError]     = React.useState('');
    const [history, setHistory] = React.useState(_loadHistory);

    function _openModal() { setOpen(true); setAnswer(''); setCitations([]); setError(''); }
    function _closeModal() { setOpen(false); }

    // ESC closes the modal — matches the FAQ / events / mock-tracker / cohort
    // convention so users don't have to hunt for the X button (#229.7).
    React.useEffect(() => {
      if (!open) return;
      function _onKey(e) { if (e.key === 'Escape') _closeModal(); }
      document.addEventListener('keydown', _onKey);
      return function _cleanup() { document.removeEventListener('keydown', _onKey); };
    }, [open]);

    function _normalizeAnswer(rawAnswer) {
      const text = (rawAnswer || '').trim();
      if (!text || text === emptyAnswer || text === '暂无相关数据' || /No relevant data found/i.test(text)) {
        return noDataAnswer;
      }
      return text;
    }

    async function _submit(e) {
      if (e && e.preventDefault) e.preventDefault();
      const q = query.trim();
      if (!q || loading) return;

      setLoading(true);
      setAnswer('');
      setCitations([]);
      setError('');

      try {
        const body = JSON.stringify({
          query: q,
          province: province || 'HI',
          year: year || 2025,
        });
        const resp = await fetch('/api/gaokao/calculate?action=qa', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body,
        });
        if (!resp.ok) throw new Error('HTTP ' + resp.status);
        const data = await resp.json();
        const normalizedAnswer = _normalizeAnswer(data.answer);
        setAnswer(normalizedAnswer);
        setCitations(Array.isArray(data.citations) ? data.citations : []);

        // Cache to history
        const newHistory = [...history, { q, a: normalizedAnswer }];
        _saveHistory(newHistory);
        setHistory(newHistory.slice(-QA_CACHE_MAX));
      } catch (err) {
        setError('请求失败，请稍后重试。' + (err && err.message ? ' (' + err.message + ')' : ''));
      } finally {
        setLoading(false);
      }
    }

    function _useHistoryItem(item) {
      setQuery(item.q);
      setAnswer(item.a);
      setCitations([]);
      setError('');
    }

    // ── Chip ────────────────────────────────────────────────────────────────
    const chipEl = React.createElement('button', {
      'data-testid': 'gaokao-qa-chip',
      onClick: _openModal,
      className: 'pb-btn pb-btn--ghost',
      style: {
        fontSize: 13,
        padding: '4px 10px',
        borderRadius: 20,
        border: '1px solid var(--pb-border)',
        cursor: 'pointer',
        background: 'var(--pb-surface)',
        color: 'var(--pb-fg)',
        whiteSpace: 'nowrap',
      },
    }, chip);

    if (!open) return chipEl;

    // ── Modal ───────────────────────────────────────────────────────────────
    const overlay = React.createElement('div', {
      'data-testid': 'gaokao-qa-modal',
      role: 'dialog',
      'aria-modal': 'true',
      'aria-label': chip,
      onClick: _closeModal,
      style: {
        position: 'fixed', inset: 0,
        background: 'rgba(0,0,0,0.45)',
        zIndex: 2147483647,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: 16,
      },
    },
      React.createElement('div', {
        onClick: (e) => e.stopPropagation(),
        style: {
          background: 'var(--pb-surface, #fff)',
          borderRadius: 12,
          padding: 24,
          width: '100%',
          maxWidth: 560,
          maxHeight: '80vh',
          overflowY: 'auto',
          boxShadow: '0 8px 32px rgba(0,0,0,0.2)',
          position: 'relative',
        },
      },
        // Close button
        React.createElement('button', {
          'aria-label': lang === 'en' ? 'Close AI Q&A' : '关闭 AI 问答',
          onClick: _closeModal,
          style: {
            position: 'absolute', top: 12, right: 14,
            background: 'none', border: 'none',
            fontSize: 20, cursor: 'pointer',
            color: 'var(--pb-fg-muted)',
            lineHeight: 1,
          },
        }, '×'),

        // Title
        React.createElement('h3', {
          style: { margin: '0 0 10px', fontSize: 16, fontWeight: 600 },
        }, chip),

        React.createElement('div', {
          'data-testid': 'gaokao-qa-scope',
          style: {
            background: 'rgba(37, 99, 235, 0.08)',
            border: '1px solid rgba(37, 99, 235, 0.18)',
            borderRadius: 8,
            color: 'var(--pb-fg)',
            fontSize: 12,
            lineHeight: 1.6,
            marginBottom: 16,
            padding: '8px 10px',
          },
        }, scopeNote),

        // Form
        React.createElement('form', { onSubmit: _submit, style: { display: 'flex', gap: 8, marginBottom: 16 } },
          React.createElement('input', {
            'data-testid': 'gaokao-qa-input',
            value: query,
            onChange: (e) => setQuery(e.target.value),
            placeholder,
            disabled: loading,
            style: {
              flex: 1,
              padding: '8px 12px',
              borderRadius: 8,
              border: '1px solid var(--pb-border)',
              fontSize: 14,
              background: 'var(--pb-surface-alt, #f8f8f8)',
              color: 'var(--pb-fg)',
              outline: 'none',
            },
          }),
          React.createElement('button', {
            type: 'submit',
            'data-testid': 'gaokao-qa-submit',
            disabled: loading || !query.trim(),
            className: 'pb-btn pb-btn--primary',
            style: { padding: '8px 16px', fontSize: 14, borderRadius: 8, flexShrink: 0 },
          }, loading ? thinkingMsg : submitLabel),
        ),

        // Error
        error && React.createElement('div', {
          style: {
            padding: '8px 12px',
            background: '#fdecea',
            color: '#9b1c1c',
            border: '1px solid #f3b5b1',
            borderRadius: 8,
            fontSize: 13,
            marginBottom: 12,
          },
        }, error),

        // Thinking indicator
        loading && React.createElement('div', {
          'data-testid': 'gaokao-qa-thinking',
          style: { color: 'var(--pb-fg-muted)', fontSize: 14, marginBottom: 12, fontStyle: 'italic' },
        }, thinkingMsg),

        // Answer
        answer && React.createElement('div', {
          'data-testid': 'gaokao-qa-answer',
          style: {
            background: 'var(--pb-surface-alt, #f8f9fa)',
            border: '1px solid var(--pb-border)',
            borderRadius: 8,
            padding: '12px 16px',
            fontSize: 14,
            lineHeight: 1.7,
            whiteSpace: 'pre-wrap',
            marginBottom: citations.length ? 8 : 0,
          },
        }, answer),

        // Citations
        citations.length > 0 && React.createElement('div', {
          'data-testid': 'gaokao-qa-citations',
          style: { marginBottom: 16 },
        },
          React.createElement('div', {
            style: { fontSize: 12, color: 'var(--pb-fg-muted)', marginBottom: 4 },
          }, citationsLabel + ':'),
          React.createElement('ul', {
            style: { margin: 0, padding: '0 0 0 18px', listStyle: 'disc' },
          },
            citations.map((c, i) =>
              React.createElement('li', {
                key: i,
                style: { fontSize: 12, color: 'var(--pb-fg-muted)', lineHeight: 1.6 },
              }, c)
            )
          )
        ),

        // Recent history
        history.length > 0 && React.createElement('div', {
          style: { marginTop: 16 },
        },
          React.createElement('div', {
            style: { fontSize: 12, color: 'var(--pb-fg-muted)', marginBottom: 6 },
          }, lang === 'zh' ? '最近提问：' : 'Recent questions:'),
          React.createElement('div', {
            style: { display: 'flex', flexDirection: 'column', gap: 4 },
          },
            [...history].reverse().map((item, i) =>
              React.createElement('button', {
                key: i,
                onClick: () => _useHistoryItem(item),
                style: {
                  textAlign: 'left',
                  background: 'none',
                  border: '1px solid var(--pb-border)',
                  borderRadius: 6,
                  padding: '4px 10px',
                  fontSize: 12,
                  cursor: 'pointer',
                  color: 'var(--pb-fg)',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                },
                title: item.q,
              }, item.q)
            )
          )
        ),
      )
    );

    // Portal overlay to body to escape sticky stacking context (#258)
    return React.createElement(React.Fragment, null, chipEl,
      ReactDOM.createPortal(overlay, document.body));
  }

  window.GaokaoQABlock = GaokaoQABlock;
})();
