/* ============================================================
   Dictionary — look up an English word to get the Russian lemma
   (dictionary form) plus its inflections: noun cases, verb
   conjugations, or adjective agreement. Every form is tappable
   to hear it, and shown in the universal Cyrillic / phonetic style.
   ============================================================ */
(function () {
  const { useState } = React;
  const A = window.APP;
  const speak = window.speakRU;

  function Entry({ entry, open, onToggle }) {
    return (
      <div style={{ background:'var(--surface)', border:'1px solid var(--line)', borderRadius:18, overflow:'hidden' }}>
        {/* 2026-06-05 7:47PM — header is a div (role=button) so the heart/speaker
            child <button>s are valid HTML (no nested-button DOM warning). PENDING USER TESTING */}
        <div onClick={onToggle} role="button" tabIndex={0}
          onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onToggle(); } }}
          style={{ cursor:'pointer', width:'100%', textAlign:'left',
            background:'transparent', padding:'14px 16px', display:'flex', alignItems:'center', gap:12 }}>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontFamily:'"Hanken Grotesk",system-ui', fontWeight:700, fontSize:12.5, color:'var(--muted)' }}>
              {entry.en}
            </div>
            <div style={{ display:'flex', alignItems:'baseline', gap:8, marginTop:3 }}>
              <span style={{ fontFamily:'"Golos Text",system-ui', fontWeight:600, fontSize:26, color:'var(--ink)', lineHeight:1.05 }}>{entry.ru}</span>
              <span style={{ fontFamily:'"JetBrains Mono",monospace', fontSize:11.5, fontWeight:600, color:'oklch(0.55 0.1 65)' }}>{entry.phon}</span>
            </div>
            <div style={{ fontFamily:'"Hanken Grotesk",system-ui', fontWeight:600, fontSize:12.5, color:'var(--muted)', marginTop:4 }}>
              {entry.pos} · {entry.gloss}
            </div>
          </div>
          {/* 2026-06-05 7:47PM — save heart on each dictionary entry (doc 03 §B2).
              kind='lemma' when the entry maps to a seeded lemma id, else 'phrase'.
              PENDING USER TESTING */}
          {window.SaveHeart && (
            <span onClick={(e) => e.stopPropagation()} style={{ flexShrink:0 }}>
              <window.SaveHeart
                kind={entry.lemma_id != null ? 'lemma' : 'phrase'}
                lemmaId={entry.lemma_id != null ? entry.lemma_id : null}
                surface="dictionary"
                item={{ type:'word', ru:entry.ru, translation:entry.gloss, note:entry.pos,
                        direction:'ru', lemma_id: entry.lemma_id != null ? entry.lemma_id : null,
                        words:[{ ru:entry.ru, phon:entry.phon, en:entry.gloss }] }}
                size={19} />
            </span>
          )}
          <button onClick={(e) => { e.stopPropagation(); speak(entry.ru); }} aria-label="Play"
            style={{ appearance:'none', border:'none', cursor:'pointer', width:40, height:40, borderRadius:999,
              background:'var(--primary-wash)', color:'var(--primary-deep)', display:'flex', alignItems:'center',
              justifyContent:'center', flexShrink:0 }}>
            <Speaker size={19} color="var(--primary-deep)" />
          </button>
          <svg width="14" height="14" viewBox="0 0 24 24" style={{ flexShrink:0, transform: open ? 'rotate(180deg)' : 'none', transition:'transform .2s' }}>
            <path d="M5 9l7 7 7-7" stroke="var(--muted)" strokeWidth="2.4" fill="none" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </div>

        {open && (
          <div style={{ padding:'4px 16px 16px', borderTop:'1px solid var(--line)' }}>
            <div style={{ fontFamily:'"JetBrains Mono",monospace', fontSize:10.5, fontWeight:600, letterSpacing:'0.1em',
              textTransform:'uppercase', color:'var(--muted)', padding:'12px 0 10px' }}>{entry.groupLabel}</div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:9 }}>
              {entry.forms.map(f => (
                <button key={f.label} onClick={() => speak(f.ru)}
                  style={{ appearance:'none', border:'1px solid var(--line)', cursor:'pointer', textAlign:'left',
                    background:'var(--bg)', borderRadius:12, padding:'9px 11px', display:'flex', flexDirection:'column', gap:2 }}>
                  <span style={{ fontFamily:'"Hanken Grotesk",system-ui', fontWeight:700, fontSize:10.5, color:'var(--muted)' }}>{f.label}</span>
                  <span style={{ fontFamily:'"Golos Text",system-ui', fontWeight:600, fontSize:18, color:'var(--ink)', lineHeight:1.1 }}>{f.ru}</span>
                  <span style={{ fontFamily:'"JetBrains Mono",monospace', fontSize:10, fontWeight:600, color:'oklch(0.55 0.1 65)' }}>{f.phon}</span>
                </button>
              ))}
            </div>
          </div>
        )}
      </div>
    );
  }

  function Dictionary() {
    const [q, setQ] = useState('');
    const [openId, setOpenId] = useState(A.dictionary[0].en);
    const query = q.trim().toLowerCase();
    const results = query
      ? A.dictionary.filter(e => e.en.toLowerCase().includes(query) || e.ru.toLowerCase().includes(query) || e.gloss.toLowerCase().includes(query))
      : A.dictionary;

    return (
      <div style={{ minHeight:'100%', background:'var(--bg)' }}>
        <div style={{ padding:'58px 20px 0' }}>
          <div style={{ fontFamily:'"Bricolage Grotesque",system-ui', fontWeight:800, fontSize:30,
            color:'var(--ink)', letterSpacing:'-0.02em' }}>Dictionary</div>
          <div style={{ fontFamily:'"Hanken Grotesk",system-ui', fontWeight:600, fontSize:13,
            color:'var(--muted)', marginTop:2 }}>Find a word’s dictionary form and every inflection.</div>
          {/* search */}
          <div style={{ marginTop:14, display:'flex', alignItems:'center', gap:10, background:'var(--surface)',
            border:'1px solid var(--line)', borderRadius:14, padding:'12px 14px' }}>
            <svg width="18" height="18" viewBox="0 0 24 24"><circle cx="11" cy="11" r="7" stroke="var(--muted)" strokeWidth="2" fill="none" /><path d="M16 16l5 5" stroke="var(--muted)" strokeWidth="2" strokeLinecap="round" /></svg>
            <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search an English word…"
              style={{ flex:1, border:'none', outline:'none', background:'transparent',
                fontFamily:'"Hanken Grotesk",system-ui', fontSize:16, fontWeight:600, color:'var(--ink)' }} />
            {q && <button onClick={() => setQ('')} style={{ appearance:'none', border:'none', background:'transparent',
              cursor:'pointer', color:'var(--muted)', fontSize:18, lineHeight:1 }}>×</button>}
          </div>
        </div>

        <div style={{ padding:'16px 20px 100px', display:'flex', flexDirection:'column', gap:11 }}>
          {results.length ? results.map(e => (
            <Entry key={e.en} entry={e} open={openId === e.en}
              onToggle={() => setOpenId(openId === e.en ? null : e.en)} />
          )) : (
            <div style={{ textAlign:'center', fontFamily:'"Hanken Grotesk",system-ui', fontWeight:600, fontSize:14,
              color:'var(--muted)', padding:'40px 20px' }}>
              No entries for “{q}”. Try house, water, friend, good, or to speak.
            </div>
          )}
        </div>
      </div>
    );
  }

  window.Dictionary = Dictionary;
})();
