/* global React */
const { useState: useState_V, useMemo: useMemo_V } = React;

// ═══════════════ VOCABULARY — 翻面卡片 ═══════════════
function Vocabulary({ learned, setLearned, customWords, setCustomWords }) {
  const [query, setQuery] = useState_V('');
  const [cat, setCat] = useState_V('all');
  const [flipped, setFlipped] = useState_V({});
  const [adding, setAdding] = useState_V(false);
  const [draft, setDraft] = useState_V({ term: '', zh: '', def: '', ex: '' });

  const allWords = [...(window.NFL_VOCABULARY || []), ...customWords];

  const filtered = useMemo_V(() => {
    const q = query.trim().toLowerCase();
    return allWords.filter(w => {
      if (cat !== 'all' && w.cat !== cat) return false;
      if (!q) return true;
      return w.term.toLowerCase().includes(q) ||
             (w.zh || '').includes(q) ||
             (w.abbr || '').toLowerCase().includes(q);
    });
  }, [allWords, query, cat]);

  function flip(id) { setFlipped({ ...flipped, [id]: !flipped[id] }); }
  function toggleLearned(id, e) {
    e.stopPropagation();
    setLearned(learned.includes(id) ? learned.filter(x => x !== id) : [...learned, id]);
  }
  function saveNew() {
    if (!draft.term || !draft.zh) return;
    const newWord = { ...draft, id: 'custom_' + Date.now(), cat: 'custom', level: 2,
                       zhDef: draft.def };
    setCustomWords([...customWords, newWord]);
    setDraft({ term: '', zh: '', def: '', ex: '' });
    setAdding(false);
  }

  return (
    <section>
      <div className="section-head">
        <div className="kicker">§ 02 · Vocabulary Bank</div>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
          <h2>NFL <span className="underline-hand">常用詞彙</span></h2>
          <div className="hand" style={{ fontSize: 20, color: 'var(--ink-faint)',
                                           transform: 'rotate(-2deg)' }}>
            點卡片翻面 → 右上角勾勾表示「已經會了」
          </div>
        </div>
        <div className="zh">共 {allWords.length} 個詞 · 已會 {learned.length} 個 · 點擊翻面 / ✓ 標記熟悉</div>
      </div>

      {/* controls */}
      <div style={{ display: 'flex', gap: 20, marginBottom: 24, flexWrap: 'wrap', alignItems: 'center' }}>
        <div style={{ flex: '1 1 260px', minWidth: 220, position: 'relative' }}>
          <input type="text" value={query} onChange={e => setQuery(e.target.value)}
                 placeholder="search  ·  quarterback  ·  盯防  ·  blitz..." />
          <span className="mono" style={{ position: 'absolute', right: 4, bottom: 8,
                                           fontSize: 11, color: 'var(--ink-faint)' }}>
            {filtered.length} results
          </span>
        </div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {(window.NFL_CATEGORIES || []).map(c => (
            <div key={c.id} className={`chip ${cat === c.id ? 'active' : ''}`}
                 onClick={() => setCat(c.id)}>
              {c.label} <span style={{ opacity: 0.6, marginLeft: 4 }}>{c.zh}</span>
            </div>
          ))}
        </div>
        <button className="btn btn-sm" onClick={() => setAdding(!adding)}>
          + Add word
        </button>
      </div>

      {/* add form */}
      {adding && (
        <div className="card" style={{ padding: 20, marginBottom: 24, background: 'rgba(242,193,78,0.15)' }}>
          <div className="hand" style={{ fontSize: 22, marginBottom: 12 }}>✎ 新增一個詞</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--ink-faint)',
                                                letterSpacing: '0.1em', textTransform: 'uppercase' }}>English</div>
              <input type="text" value={draft.term}
                     onChange={e => setDraft({ ...draft, term: e.target.value })}
                     placeholder="e.g. Flag on the play" />
            </div>
            <div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--ink-faint)',
                                                letterSpacing: '0.1em', textTransform: 'uppercase' }}>中文</div>
              <input type="text" value={draft.zh}
                     onChange={e => setDraft({ ...draft, zh: e.target.value })}
                     placeholder="e.g. 犯規黃旗" />
            </div>
          </div>
          <div style={{ marginTop: 14 }}>
            <div className="mono" style={{ fontSize: 10, color: 'var(--ink-faint)',
                                              letterSpacing: '0.1em', textTransform: 'uppercase' }}>解釋</div>
            <input type="text" value={draft.def}
                   onChange={e => setDraft({ ...draft, def: e.target.value })}
                   placeholder="何時用這個詞、怎麼翻譯..." />
          </div>
          <div style={{ marginTop: 14 }}>
            <div className="mono" style={{ fontSize: 10, color: 'var(--ink-faint)',
                                              letterSpacing: '0.1em', textTransform: 'uppercase' }}>例句</div>
            <input type="text" value={draft.ex}
                   onChange={e => setDraft({ ...draft, ex: e.target.value })}
                   placeholder="聽到主播怎麼說..." />
          </div>
          <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
            <button className="btn btn-primary btn-sm" onClick={saveNew}>Save</button>
            <button className="btn btn-ghost btn-sm" onClick={() => setAdding(false)}>Cancel</button>
          </div>
        </div>
      )}

      {/* cards grid */}
      <div className="grid grid-3" style={{ gap: 18 }}>
        {filtered.map(w => (
          <FlashCard key={w.id} word={w}
                     flipped={!!flipped[w.id]}
                     learned={learned.includes(w.id)}
                     onFlip={() => flip(w.id)}
                     onToggleLearned={(e) => toggleLearned(w.id, e)} />
        ))}
      </div>

      {filtered.length === 0 && (
        <div className="hand" style={{ fontSize: 24, color: 'var(--ink-faint)',
                                          textAlign: 'center', padding: '40px 0' }}>
          ¯\_(ツ)_/¯ 沒找到 — 換個關鍵字？
        </div>
      )}
    </section>
  );
}

function FlashCard({ word, flipped, learned, onFlip, onToggleLearned }) {
  return (
    <div onClick={onFlip}
         style={{ perspective: 1200, cursor: 'pointer', height: 220 }}>
      <div style={{ position: 'relative', width: '100%', height: '100%',
                     transition: 'transform 0.5s', transformStyle: 'preserve-3d',
                     transform: flipped ? 'rotateY(180deg)' : 'rotateY(0)' }}>

        {/* FRONT */}
        <div style={{
          position: 'absolute', inset: 0, backfaceVisibility: 'hidden',
          background: 'rgba(255,251,240,0.75)',
          border: '1px solid var(--rule)',
          padding: '20px 22px',
          display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
        }}>
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em',
                                                color: 'var(--ink-faint)', textTransform: 'uppercase' }}>
                {word.cat} {word.abbr && `· ${word.abbr}`}
              </div>
              <div onClick={onToggleLearned}
                   style={{ width: 22, height: 22, border: '1.5px solid var(--ink)',
                             display: 'flex', alignItems: 'center', justifyContent: 'center',
                             background: learned ? 'var(--field-green)' : 'transparent',
                             borderColor: learned ? 'var(--field-green)' : 'var(--ink)' }}>
                {learned && (
                  <svg width="14" height="14" viewBox="0 0 20 20" fill="none">
                    <path d="M3 10 L 8 15 L 17 4" stroke="var(--paper)" strokeWidth="2.5"
                          strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                )}
              </div>
            </div>
            <div className="hand" style={{ fontSize: 44, fontWeight: 700, lineHeight: 1.05,
                                             marginTop: 16, color: 'var(--ink)' }}>
              {word.term}
            </div>
          </div>
          <div>
            <div style={{ display: 'flex', gap: 4, marginBottom: 6 }}>
              {[1,2,3].map(l => (
                <div key={l} style={{ width: 18, height: 3,
                                        background: l <= (word.level || 1) ? 'var(--ink)' : 'var(--rule)' }} />
              ))}
            </div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--ink-faint)',
                                              letterSpacing: '0.06em' }}>
              → flip for meaning
            </div>
          </div>
        </div>

        {/* BACK */}
        <div style={{
          position: 'absolute', inset: 0, backfaceVisibility: 'hidden',
          transform: 'rotateY(180deg)',
          background: 'var(--term-bg)', color: 'var(--term-fg)',
          padding: '18px 20px',
          fontFamily: 'var(--f-mono)', fontSize: 12, lineHeight: 1.55,
          overflow: 'auto'
        }}>
          <div style={{ color: '#ffde7a', fontSize: 18, marginBottom: 8, fontWeight: 500 }}>
            {word.zh}
          </div>
          <div style={{ color: 'var(--term-fg)', marginBottom: 10 }}>
            {word.def}
          </div>
          {word.zhDef && (
            <div style={{ color: 'var(--term-dim)', marginBottom: 10, fontStyle: 'italic' }}>
              // {word.zhDef}
            </div>
          )}
          {word.ex && (
            <div style={{ borderTop: '1px solid var(--term-line)', paddingTop: 8, marginTop: 8 }}>
              <span style={{ color: '#8fd4ff' }}>ex:</span> <span style={{ color: 'var(--term-fg)' }}>"{word.ex}"</span>
            </div>
          )}
        </div>

      </div>
    </div>
  );
}

window.Vocabulary = Vocabulary;
