/* ============================================================
   Lessons — the learner's full "Your Path": a guided journey of
   lessons across every track, in learning order.
   ============================================================ */
(function () {
  const { useState, useEffect } = React;
  const A = window.APP;

  /* 2026-06-05 7:47PM — Saved tab (doc 03 §B3). A segmented control at
     the top of Lessons toggles "Your Path | Saved". Saved view: count
     header, client-side search, most-recent-first compact StackedGloss
     rows, unsave via the same heart, empty state. Reads SavedStore
     (Supabase when signed in, localStorage when anonymous).
     Status: ⚠️ PENDING USER TESTING */

  function SavedSeg({ value, onChange }) {
    const opts = [{ id:'path', label:'Your Path' }, { id:'saved', label:'Saved' }];
    return (
      <div style={{ display:'flex', gap:4, background:'var(--chip)', borderRadius:12, padding:4, marginTop:14 }}>
        {opts.map(o => (
          <button key={o.id} onClick={() => onChange(o.id)}
            style={{ appearance:'none', border:'none', cursor:'pointer', flex:1, borderRadius:9,
              padding:'9px 8px', fontFamily:'"Hanken Grotesk",system-ui', fontWeight:800, fontSize:14,
              background: value === o.id ? 'var(--surface)' : 'transparent',
              color: value === o.id ? 'var(--ink)' : 'var(--muted)',
              boxShadow: value === o.id ? '0 1px 4px -1px rgba(0,0,0,0.15)' : 'none', transition:'all .15s' }}>
            {o.label}
          </button>
        ))}
      </div>
    );
  }

  function SavedView({ seg }) {
    const [items, setItems] = useState(null);  // null=loading, []=empty
    const [q, setQ] = useState('');
    const [err, setErr] = useState('');

    const load = () => {
      if (!window.SavedStore) { setItems([]); return; }
      window.SavedStore.list()
        .then(rows => setItems(rows || []))
        .catch(e => { setErr('Couldn’t load your saved words.'); setItems([]); });
    };
    useEffect(() => {
      load();
      if (window.SavedStore) return window.SavedStore.subscribe(load);
    }, []);

    const query = q.trim().toLowerCase();
    const filtered = (items || []).filter(r => {
      if (!query) return true;
      const p = r.payload || {};
      if ((p.ru || '').toLowerCase().includes(query)) return true;
      if ((p.translation || '').toLowerCase().includes(query)) return true;
      return Array.isArray(p.words) && p.words.some(w => (w.en || '').toLowerCase().includes(query));
    });

    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' }}>Saved</div>
          {seg}
          <div style={{ fontFamily:'"Hanken Grotesk",system-ui', fontWeight:600, fontSize:13,
            color:'var(--muted)', marginTop:12 }}>
            {items == null ? 'Loading…'
              : `${items.length} saved word${items.length === 1 ? '' : 's'} & phrase${items.length === 1 ? '' : 's'}.`}
          </div>
          {(items && items.length > 0) && (
            <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 your saved words…"
                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 104px', display:'flex', flexDirection:'column', gap:12 }}>
          {items == null ? null
            : items.length === 0 ? (
              <div style={{ textAlign:'center', padding:'56px 24px', display:'flex', flexDirection:'column',
                alignItems:'center', gap:12 }}>
                {window.SaveHeart && <Heart24 />}
                <div style={{ fontFamily:'"Hanken Grotesk",system-ui', fontWeight:700, fontSize:15, color:'var(--ink)' }}>
                  Nothing saved yet.</div>
                <div style={{ fontFamily:'"Hanken Grotesk",system-ui', fontWeight:600, fontSize:13, color:'var(--muted)',
                  maxWidth:260, lineHeight:1.4 }}>
                  Tap the heart on any word, lesson, or translation to keep it here.</div>
              </div>
            ) : filtered.length === 0 ? (
              <div style={{ textAlign:'center', fontFamily:'"Hanken Grotesk",system-ui', fontWeight:600, fontSize:14,
                color:'var(--muted)', padding:'40px 20px' }}>No saved words match “{q}”.</div>
            ) : filtered.map(r => {
              const p = r.payload || {};
              const it = { ...p, words: Array.isArray(p.words) && p.words.length ? p.words
                : [{ ru:p.ru, phon:'', en:p.translation }], lemma_id: r.lemma_id != null ? r.lemma_id : (p.lemma_id != null ? p.lemma_id : null) };
              return (
                <StackedGloss key={r.id || r.dedupe_key} item={it} compact
                  surface={r.source_surface || 'saved'} saveKind={r.kind} />
              );
            })}
          {err && <div style={{ fontFamily:'"Hanken Grotesk",system-ui', fontWeight:600, fontSize:13,
            color:'var(--muted)', textAlign:'center' }}>{err}</div>}
        </div>
      </div>
    );
  }

  function Heart24() {
    return (
      <svg width="40" height="40" viewBox="0 0 24 24" fill="none">
        <path d="M12 20.5l-1.4-1.27C5.4 14.5 2.5 11.9 2.5 8.6 2.5 6.06 4.5 4 7.05 4
                 c1.54 0 3.04.72 3.95 1.86C11.9 4.72 13.4 4 14.95 4 17.5 4 19.5 6.06 19.5 8.6
                 c0 3.3-2.9 5.9-8.1 10.63L12 20.5z"
          fill="none" stroke="var(--line)" strokeWidth="1.6" strokeLinejoin="round" />
      </svg>
    );
  }

  function Lessons({ nav }) {
    const [view, setView] = useState('path');
    const seg = <SavedSeg value={view} onChange={setView} />;
    if (view === 'saved') return <SavedView seg={seg} />;
    return <PathView nav={nav} seg={seg} />;
  }

  function PathView({ nav, seg }) {
    const T = id => A.findTrack(id);
    const open = (n) => {
      if (n.status === 'locked') return;
      if (n.id === 'alphabet') nav.go('alphabet', {});
      else nav.go('lesson', { lessonId:n.id });
    };
    const path = [
      { id:'alphabet', label:'The Alphabet', track:T('foundations'), status:'done' },
      { id:'numbers0', label:'Numbers 0–10', track:T('foundations'), status:'done' },
      { id:'greetings', label:'First Words', track:T('words'), status:'active' },
      { id:'family', label:'Family & People', track:T('words'), status:'open' },
      { id:'food', label:'Food & Drink', track:T('words'), status:'open' },
      { id:'colours', label:'Colours', track:T('words'), status:'open' },
      { id:'cafe', label:'At the Café', track:T('scenarios'), status:'open' },
      { id:'meet', label:'Meeting Someone', track:T('scenarios'), status:'open' },
      { id:'airport', label:'At the Airport', track:T('travel'), status:'open' },
      { id:'ty-vy', label:'ты or вы?', track:T('culture'), status:'locked' },
    ];
    const done = path.filter(n => n.status === 'done').length;

    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' }}>Your Path</div>
          <div style={{ fontFamily:'"Hanken Grotesk",system-ui', fontWeight:600, fontSize:13,
            color:'var(--muted)', marginTop:2 }}>Your recommended route, lesson by lesson.</div>
          {seg}
          <div style={{ display:'flex', alignItems:'center', gap:12, marginTop:14 }}>
            <div style={{ flex:1 }}><Bar value={done / path.length} color="var(--primary)" /></div>
            <span style={{ fontFamily:'"JetBrains Mono",monospace', fontWeight:700, fontSize:12.5, color:'var(--ink)', whiteSpace:'nowrap' }}>
              {done}<span style={{ color:'var(--muted)' }}>/{path.length} done</span></span>
          </div>
        </div>

        <div style={{ padding:'20px 20px 104px' }}>
          <div style={{ position:'relative' }}>
            <div style={{ position:'absolute', left:26, top:20, bottom:20, width:2, background:'var(--line)' }} />
            <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
              {path.map(n => {
                const can = n.status !== 'locked';
                const isActive = n.status === 'active';
                return (
                  <button key={n.id} disabled={!can} onClick={() => open(n)}
                    style={{ appearance:'none', border:'none', cursor:can ? 'pointer' : 'default', textAlign:'left',
                      background: isActive ? 'var(--surface)' : 'transparent', borderRadius:16,
                      padding: isActive ? '13px 14px' : '9px 14px', display:'flex', alignItems:'center', gap:14,
                      boxShadow: isActive ? '0 1px 0 var(--line), 0 8px 20px -14px rgba(0,0,0,0.3)' : 'none',
                      position:'relative', zIndex:1 }}>
                    <div style={{ position:'relative', zIndex:2, flexShrink:0 }}>
                      {n.status === 'done' ? (
                        <div style={{ width:32, height:32, borderRadius:999, background:n.track.color,
                          display:'flex', alignItems:'center', justifyContent:'center', boxShadow:'0 0 0 4px var(--bg)' }}>
                          <svg width="17" height="17" viewBox="0 0 24 24"><path d="M5 13l4 4 10-11" stroke="#fff" strokeWidth="2.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                        </div>
                      ) : isActive ? (
                        <div style={{ width:32, height:32, borderRadius:999, background:n.track.color,
                          boxShadow:`0 0 0 4px var(--bg), 0 0 0 6px ${n.track.color}`,
                          display:'flex', alignItems:'center', justifyContent:'center' }}>
                          <div style={{ width:11, height:11, borderRadius:999, background:'#fff' }} />
                        </div>
                      ) : n.status === 'open' ? (
                        <div style={{ width:32, height:32, borderRadius:999, background:'var(--surface)',
                          boxShadow:`0 0 0 4px var(--bg), inset 0 0 0 2px ${n.track.color}`,
                          display:'flex', alignItems:'center', justifyContent:'center' }}>
                          <div style={{ width:9, height:9, borderRadius:999, background:n.track.color }} />
                        </div>
                      ) : (
                        <div style={{ width:32, height:32, borderRadius:999, background:'var(--chip)',
                          boxShadow:'0 0 0 4px var(--bg)', display:'flex', alignItems:'center', justifyContent:'center' }}>
                          <svg width="14" height="14" viewBox="0 0 24 24"><path d="M6 11V8a6 6 0 0112 0v3" stroke="var(--muted)" strokeWidth="2" fill="none"/><rect x="4" y="11" width="16" height="9" rx="2.5" fill="var(--muted)"/></svg>
                        </div>
                      )}
                    </div>
                    <div style={{ flex:1, minWidth:0 }}>
                      <div style={{ fontFamily:'"Hanken Grotesk",system-ui', fontWeight:800, fontSize:15.5,
                        color: can ? 'var(--ink)' : 'var(--muted)' }}>{n.label}</div>
                      <div style={{ fontFamily:'"Hanken Grotesk",system-ui', fontWeight:600, fontSize:12, color:n.track.color, marginTop:1 }}>{n.track.name}</div>
                    </div>
                    {isActive && <span style={{ fontFamily:'"JetBrains Mono",monospace', fontSize:10, fontWeight:700,
                      color:n.track.color, letterSpacing:'0.08em', flexShrink:0 }}>NOW</span>}
                  </button>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.Lessons = Lessons;
})();
