/* ============================================================
   WordGrid — a vocabulary lesson IS its word list.
   Every card shows the universal Cyrillic / phonetic / English
   stack, a play button, and a learned check. A progress bar tracks
   mastery; once every word is checked a “Mark lesson complete”
   button rises up. Mirrors the Alphabet page. No separate exercises.
   ============================================================ */
(function () {
  const { useState, useRef, useEffect } = React;
  const A = window.APP;

  function WordGrid({ nav, lessonId }) {
    const found = A.findLesson(lessonId);
    if (!found) return null;
    const { track, lesson } = found;
    const items = lesson.teach || [];
    const KEY = 'ru_lesson_' + lessonId;

    const [learned, setLearned] = useState(() => {
      try { return JSON.parse(localStorage.getItem(KEY)) || {}; } catch (e) { return {}; }
    });
    const [active, setActive] = useState(null);
    const tRef = useRef(null);
    useEffect(() => () => clearTimeout(tRef.current), []);

    const total = items.length;
    const count = items.filter(it => learned[it.ru]).length;

    const play = (it) => {
      setActive(it.ru);
      window.speakRU(it.ru);
      clearTimeout(tRef.current);
      tRef.current = setTimeout(() => setActive(null), 1100);
    };
    const toggle = (it, e) => {
      e.stopPropagation();
      setLearned(prev => {
        const n = { ...prev };
        if (n[it.ru]) delete n[it.ru]; else n[it.ru] = 1;
        try { localStorage.setItem(KEY, JSON.stringify(n)); } catch (er) {}
        return n;
      });
    };

    return (
      <div style={{ height:'100%', display:'flex', flexDirection:'column', background:'var(--bg)', position:'relative' }}>
        {/* header — track label inline with the close button (top-right) */}
        <div style={{ padding:'50px 18px 0', display:'flex', alignItems:'center', justifyContent:'space-between', gap:12 }}>
          <div style={{ display:'flex', alignItems:'center', gap:9, minWidth:0 }}>
            <Emblem letter={track.emblem} color={track.color} size={28} radius={9} />
            <span style={{ fontFamily:'"Hanken Grotesk",system-ui', fontWeight:700, fontSize:13.5,
              color:track.color, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{track.name}</span>
          </div>
          <IconBtn kind="close" onClick={nav.back} />
        </div>
        <div style={{ padding:'10px 22px 12px' }}>
          <div style={{ fontFamily:'"Bricolage Grotesque",system-ui', fontWeight:800, fontSize:27,
            color:'var(--ink)', letterSpacing:'-0.02em' }}>{lesson.title}</div>
          <div style={{ fontFamily:'"Hanken Grotesk",system-ui', fontWeight:600, fontSize:13,
            color:'var(--muted)', marginTop:2 }}>Tap a card to hear it · check each one you’ve learned</div>
          <div style={{ display:'flex', alignItems:'center', gap:12, marginTop:12 }}>
            <div style={{ flex:1 }}><Bar value={total ? count/total : 0} color={track.color} /></div>
            <span style={{ fontFamily:'"JetBrains Mono",monospace', fontWeight:700, fontSize:12.5,
              color:'var(--ink)', whiteSpace:'nowrap' }}>{count}<span style={{ color:'var(--muted)' }}>/{total} learned</span></span>
          </div>
        </div>

        {/* cards */}
        <div style={{ flex:1, minHeight:0, overflowY:'auto', padding:`2px 18px ${count >= total && total ? 92 : 40}px`,
          display:'flex', flexDirection:'column', gap:10 }}>
          {items.map(it => {
            const isOn = !!learned[it.ru];
            const isActive = active === it.ru;
            return (
              <button key={it.ru} onClick={() => play(it)}
                style={{ appearance:'none', cursor:'pointer', textAlign:'left',
                  background:'var(--surface)', borderRadius:16, padding:'14px 15px',
                  border:`1.5px solid ${isActive ? 'var(--primary)' : (isOn ? 'oklch(0.80 0.11 150)' : 'var(--line)')}`,
                  boxShadow: isActive ? '0 8px 22px -12px var(--primary)' : '0 1px 0 var(--line)',
                  transition:'border-color .15s, box-shadow .15s, transform .1s',
                  transform: isActive ? 'translateY(-1px)' : 'none',
                  display:'flex', alignItems:'center', gap:12 }}>
                <div style={{ flex:1, minWidth:0 }}>
                  <StackRow item={it} active={isActive} />
                </div>
                <div style={{ display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'space-between',
                  alignSelf:'stretch', gap:10 }}>
                  <span onClick={(e) => toggle(it, e)} role="checkbox" aria-checked={isOn}
                    style={{ width:22, height:22, borderRadius:999, flexShrink:0,
                      display:'flex', alignItems:'center', justifyContent:'center',
                      background: isOn ? 'oklch(0.60 0.13 150)' : 'transparent',
                      border: isOn ? 'none' : '1.5px solid var(--line)', transition:'background .15s' }}>
                    {isOn && <svg width="13" height="13" viewBox="0 0 24 24"><path d="M5 13l4 4 10-11" stroke="#fff" strokeWidth="3" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>}
                  </span>
                  <Speaker size={18} color={isActive ? 'var(--primary)' : 'var(--muted)'} playing={isActive} />
                </div>
              </button>
            );
          })}
        </div>

        {/* footer — appears only once every word is learned */}
        {count >= total && total > 0 && (
          <div style={{ position:'absolute', left:0, right:0, bottom:0, zIndex:5,
            padding:'12px 20px calc(20px + env(safe-area-inset-bottom))', borderTop:'1px solid var(--line)',
            background:'var(--bg)', animation:'footerRise .3s cubic-bezier(.2,.9,.3,1)' }}>
            <Btn full onClick={() => nav.go('complete', { lessonId, accuracy:100, learned:total })}>
              Mark lesson complete
            </Btn>
          </div>
        )}
      </div>
    );
  }

  window.WordGrid = WordGrid;
})();
