/* eslint-disable */
// Dashboard panels — stats, streak, level picker, browse list, search

const Dashboard = ({ state, setState, words, onStart }) => {
  const [level, setLevel] = useState(state.settings?.level || 'A1');
  const [search, setSearch] = useState('');

  // Stats
  const today = new Date().toISOString().slice(0,10);
  const todayCount = state.stats?.byDay?.[today] || 0;
  const dailyGoal = state.settings?.dailyGoal || 20;
  const streak = state.streak?.count || 0;

  // 14-day spark
  const last14 = useMemo(() => {
    const arr = [];
    for (let i = 13; i >= 0; i--) {
      const d = new Date(Date.now() - i * 86400000).toISOString().slice(0,10);
      arr.push(state.stats?.byDay?.[d] || 0);
    }
    return arr;
  }, [state.stats]);

  // Level breakdown
  const levelStats = useMemo(() => {
    const out = { A1:{total:0,learned:0}, A2:{total:0,learned:0}, B1:{total:0,learned:0}, B2:{total:0,learned:0} };
    words.forEach(w => {
      out[w.cefr].total++;
      const card = state.cards[w.id];
      if (card && card.reps > 0) out[w.cefr].learned++;
    });
    return out;
  }, [words, state.cards]);

  // Words for selected level
  const levelWords = words.filter(w => w.cefr === level);

  // Due count for level
  const dueCount = levelWords.filter(w => {
    const c = state.cards[w.id];
    return !c || window.SM2.isDue(c);
  }).length;

  // Search results
  const searchResults = search.trim()
    ? words.filter(w =>
        w.word.toLowerCase().includes(search.toLowerCase()) ||
        w.zh.includes(search) ||
        w.en.toLowerCase().includes(search.toLowerCase())
      ).slice(0, 8)
    : [];

  const exportData = () => {
    const blob = new Blob([window.VocabStore.exportJSON(state)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `oxford3000-${today}.json`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const setSetting = (k, v) => {
    setState(s => ({ ...s, settings: { ...s.settings, [k]: v }}));
  };

  return (
    <div style={{ maxWidth: 980, margin:'0 auto', padding:'0 20px 60px' }}>
      {/* Hero header */}
      <header style={{ padding:'28px 0 18px', position:'relative' }}>
        <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', flexWrap:'wrap', gap:12 }}>
          <div>
            <div className="serif" style={{ fontSize: 44, fontWeight:500, lineHeight:1, letterSpacing:'-0.01em' }}>
              The Oxford 3000
            </div>
            <div style={{ marginTop:6, color:'var(--ink-faded)', fontSize:13, fontFamily:'var(--font-mono)', letterSpacing:'0.06em', textTransform:'uppercase' }}>
              Vocabulary · A1–B2 · {words.length} words in this set
            </div>
          </div>
          <span className="stamp" style={{ color:'var(--red-stamp)' }}>Edition · 2026</span>
        </div>
        <hr className="rule-double" style={{ margin:'18px 0 0' }}/>
      </header>

      {/* Top stats row */}
      <section style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(200px, 1fr))', gap: 14, marginTop:20 }}>
        <StatCard label="Today" value={todayCount} sub={`/ ${dailyGoal} goal`} progress={Math.min(1, todayCount/dailyGoal)}/>
        <StatCard label="Streak" value={streak} sub="days in a row" icon="🔥" hand={streak >= 3 ? 'on fire' : ''}/>
        <StatCard label="Mastered" value={Object.values(state.cards).filter(c => window.SM2.status(c)==='mature').length} sub="mature words"/>
        <StatCard label="Total reviews" value={state.stats?.totalReviews || 0} sub="all time"/>
      </section>

      {/* Activity sparkline */}
      <section style={{ marginTop:14 }}>
        <PaperCard style={{ padding:'18px 22px' }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', position:'relative', zIndex:2 }}>
            <div style={{ fontSize:12, fontFamily:'var(--font-mono)', textTransform:'uppercase', letterSpacing:'0.15em', color:'var(--ink-faded)' }}>
              Last 14 days
            </div>
            <div style={{ fontSize:12, fontFamily:'var(--font-mono)', color:'var(--ink-faded)' }}>
              {last14.reduce((a,b)=>a+b,0)} reviews
            </div>
          </div>
          <div style={{ marginTop:10, position:'relative', zIndex:2 }}>
            <SparkBar data={last14} height={48}/>
          </div>
          <div style={{ display:'flex', justifyContent:'space-between', marginTop:6, fontSize:10, fontFamily:'var(--font-mono)', color:'var(--ink-ghost)' }}>
            <span>—14d</span><span>today</span>
          </div>
        </PaperCard>
      </section>

      {/* Level picker + Start */}
      <section style={{ marginTop:24 }}>
        <h2 className="serif" style={{ fontSize:22, fontWeight:500, margin:'0 0 10px' }}>Choose a level</h2>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(200px, 1fr))', gap:12 }}>
          {['A1','A2','B1','B2'].map(L => {
            const stat = levelStats[L];
            const active = level === L;
            return (
              <button key={L} onClick={() => { setLevel(L); setSetting('level', L); }}
                style={{
                  position:'relative', overflow:'hidden',
                  textAlign:'left', cursor:'pointer',
                  background: active ? 'var(--paper-2)' : 'var(--paper-1)',
                  border:`1.5px solid ${active ? 'var(--ink)' : 'var(--rule)'}`,
                  borderRadius: 3,
                  padding:'16px 18px',
                  boxShadow: active ? '3px 3px 0 var(--ink)' : 'none',
                  transition:'transform 0.08s',
                }}>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                  <span className={cefrClass(L)} style={{ fontSize: 13, padding:'3px 10px' }}>{L}</span>
                  <span className="serif" style={{ fontSize:14, color:'var(--ink-faded)' }}>{cefrLabel(L)}</span>
                </div>
                <div style={{ marginTop:14, display:'flex', alignItems:'baseline', gap:6 }}>
                  <span className="serif" style={{ fontSize: 28, fontWeight:500 }}>{stat.learned}</span>
                  <span style={{ fontSize:14, color:'var(--ink-faded)' }}>/ {stat.total}</span>
                </div>
                <ProgressBar value={stat.total ? stat.learned/stat.total : 0}/>
              </button>
            );
          })}
        </div>
      </section>

      {/* Mode picker + start */}
      <section style={{ marginTop:24 }}>
        <PaperCard style={{ padding:'22px 24px' }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', flexWrap:'wrap', gap:12, position:'relative', zIndex:2 }}>
            <div>
              <h3 className="serif" style={{ fontSize:22, fontWeight:500, margin:0 }}>
                Today's session
              </h3>
              <div style={{ marginTop:4, color:'var(--ink-faded)', fontSize:13 }}>
                <span className="serif" style={{ fontStyle:'italic' }}>{level}</span> · {dueCount} due now · pick a mode
              </div>
            </div>
            <button className="btn primary" style={{ fontSize:15, padding:'12px 24px' }} onClick={() => onStart(level)}>
              Start session →
            </button>
          </div>
          <div style={{ marginTop:18, display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(150px,1fr))', gap:10, position:'relative', zIndex:2 }}>
            {[
              { id:'flashcard', label:'Flashcard', sub:'flip & grade', icon:'⌖' },
              { id:'choice',    label:'Multiple',  sub:'pick meaning', icon:'☰' },
              { id:'listen',    label:'Listening', sub:'audio → word', icon:'♪' },
              { id:'cloze',     label:'Cloze',     sub:'fill blank', icon:'✎' },
            ].map(m => {
              const active = state.settings?.mode === m.id;
              return (
                <button key={m.id} onClick={() => setSetting('mode', m.id)}
                  style={{
                    cursor:'pointer', textAlign:'left',
                    background: active ? 'var(--ink)' : 'var(--paper-1)',
                    color: active ? 'var(--paper-0)' : 'var(--ink)',
                    border: `1px solid ${active ? 'var(--ink)' : 'var(--rule)'}`,
                    borderRadius: 3, padding:'12px 14px',
                  }}>
                  <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                    <span style={{ fontSize:18, opacity:0.8 }}>{m.icon}</span>
                    <span style={{ fontSize:14, fontWeight:600 }}>{m.label}</span>
                  </div>
                  <div style={{ marginTop:4, fontSize:11, fontFamily:'var(--font-mono)', opacity:0.7, textTransform:'uppercase', letterSpacing:'0.08em' }}>{m.sub}</div>
                </button>
              );
            })}
          </div>
        </PaperCard>
      </section>

      {/* Search + Browse + Difficult */}
      <section style={{ marginTop:24, display:'grid', gridTemplateColumns:'1fr', gap:16 }}>
        <PaperCard style={{ padding:'18px 22px' }}>
          <div style={{ display:'flex', alignItems:'center', gap:10, position:'relative', zIndex:2 }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--ink-soft)" strokeWidth="1.6"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4-4"/></svg>
            <input
              value={search} onChange={e => setSearch(e.target.value)}
              placeholder="Search any word — English, 中文, definition..."
              style={{
                flex:1, padding:'8px 0', border:'none', outline:'none',
                background:'transparent', fontFamily:'var(--font-serif)', fontSize: 18,
              }}/>
            {search && <button className="btn ghost" style={{ padding:'4px 10px', fontSize:12 }} onClick={() => setSearch('')}>Clear</button>}
          </div>
          {searchResults.length > 0 && (
            <div style={{ marginTop:14, position:'relative', zIndex:2, display:'grid', gap:6 }}>
              {searchResults.map(w => <WordRow key={w.id} word={w} state={state} setState={setState}/>)}
            </div>
          )}
        </PaperCard>

        <PaperCard style={{ padding:'18px 22px' }}>
          <BrowseList words={levelWords} state={state} setState={setState} level={level}/>
        </PaperCard>
      </section>

      {/* Footer actions */}
      <footer style={{ marginTop:32, display:'flex', gap:12, flexWrap:'wrap', justifyContent:'space-between', alignItems:'center' }}>
        <div style={{ fontSize:12, fontFamily:'var(--font-mono)', color:'var(--ink-faded)', letterSpacing:'0.05em' }}>
          Data stored locally · No account
        </div>
        <div style={{ display:'flex', gap:10 }}>
          <button className="btn ghost" onClick={exportData}>Export JSON</button>
          <button className="btn ghost" onClick={() => {
            if (confirm('Reset all progress?')) { localStorage.removeItem(window.VocabStore.KEY); location.reload(); }
          }}>Reset progress</button>
        </div>
      </footer>
    </div>
  );
};

const cefrLabel = (l) => ({
  A1:'Beginner', A2:'Elementary', B1:'Intermediate', B2:'Upper Int.',
})[l];

const StatCard = ({ label, value, sub, progress, icon, hand }) => (
  <PaperCard style={{ padding:'16px 18px', position:'relative' }}>
    <div style={{ position:'relative', zIndex:2 }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
        <div style={{ fontSize:11, fontFamily:'var(--font-mono)', textTransform:'uppercase', letterSpacing:'0.15em', color:'var(--ink-faded)' }}>{label}</div>
        {icon && <span style={{ fontSize:16 }}>{icon}</span>}
      </div>
      <div className="serif" style={{ fontSize: 36, fontWeight:500, marginTop:4, lineHeight:1 }}>{value}</div>
      <div style={{ fontSize:12, color:'var(--ink-faded)', marginTop:4 }}>{sub}</div>
      {progress != null && <ProgressBar value={progress} top={8}/>}
      {hand && <div className="hand" style={{ position:'absolute', bottom:-2, right:0, color:'var(--red-stamp)', fontSize: 22, transform:'rotate(-6deg)' }}>{hand}</div>}
    </div>
  </PaperCard>
);

const ProgressBar = ({ value, top = 12 }) => (
  <div style={{ marginTop: top, height: 6, background:'var(--rule-soft)', borderRadius:0, overflow:'hidden', position:'relative' }}>
    <div style={{ width: `${Math.min(100, value*100)}%`, height:'100%', background:'var(--ink)', transition:'width 0.4s' }}/>
  </div>
);

const BrowseList = ({ words, state, setState, level }) => {
  const [filter, setFilter] = useState('all'); // all | new | learning | mature | starred
  const filtered = useMemo(() => {
    return words.filter(w => {
      const card = state.cards[w.id];
      const status = window.SM2.status(card);
      if (filter==='all') return true;
      if (filter==='starred') return state.starred[w.id];
      return status === filter;
    });
  }, [words, state.cards, state.starred, filter]);

  return (
    <>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', flexWrap:'wrap', gap:8, position:'relative', zIndex:2 }}>
        <h3 className="serif" style={{ fontSize:20, fontWeight:500, margin:0 }}>{level} · word list</h3>
        <Tabs
          value={filter} onChange={setFilter}
          options={[
            { value:'all',      label:'All', badge: words.length },
            { value:'new',      label:'New' },
            { value:'learning', label:'Learning' },
            { value:'mature',   label:'Mature' },
            { value:'starred',  label:'★ Difficult', badge: Object.values(state.starred).filter(Boolean).length || null },
          ]}/>
      </div>
      <div style={{ marginTop:12, display:'grid', gap:6, maxHeight: 360, overflow:'auto', position:'relative', zIndex:2 }}>
        {filtered.length === 0 && (
          <div style={{ padding:'24px 0', textAlign:'center', color:'var(--ink-faded)', fontSize:13, fontStyle:'italic' }}>No words in this filter.</div>
        )}
        {filtered.map(w => <WordRow key={w.id} word={w} state={state} setState={setState}/>)}
      </div>
    </>
  );
};

const WordRow = ({ word, state, setState }) => {
  const card = state.cards[word.id];
  const status = window.SM2.status(card);
  const starred = !!state.starred[word.id];
  const statusColor = {
    new:      'var(--ink-ghost)',
    learning: 'var(--gold)',
    young:    'var(--blue-mark)',
    mature:   'var(--green-ok)',
  }[status];
  const statusLabel = { new:'NEW', learning:'LEARN', young:'YOUNG', mature:'★ MATURE' }[status];

  const toggleStar = () => {
    setState(s => ({ ...s, starred: { ...s.starred, [word.id]: !s.starred[word.id] }}));
  };

  return (
    <div style={{
      display:'grid', gridTemplateColumns:'auto 1fr auto auto auto auto', gap:12,
      alignItems:'center', padding:'8px 10px',
      borderBottom:'1px dotted var(--rule-soft)',
    }}>
      <span className={cefrClass(word.cefr)} style={{ fontSize:9, padding:'1px 5px' }}>{word.cefr}</span>
      <div style={{ minWidth:0 }}>
        <div style={{ display:'flex', alignItems:'baseline', gap:8, flexWrap:'wrap' }}>
          <span className="serif" style={{ fontSize:17, fontWeight:500 }}>{word.word}</span>
          <span className="phon" style={{ fontSize:12 }}>{word.phonetic}</span>
          <span style={{ fontSize:11, fontFamily:'var(--font-mono)', color:'var(--ink-faded)' }}>{word.pos}</span>
        </div>
        <div style={{ fontSize:13, color:'var(--ink-soft)', marginTop:1, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{word.zh} · {word.en}</div>
      </div>
      <span style={{ fontSize:9, fontFamily:'var(--font-mono)', color: statusColor, letterSpacing:'0.1em', whiteSpace:'nowrap' }}>{statusLabel}</span>
      <SpeakerBtn text={word.word} size={16}/>
      <StarBtn active={starred} onClick={toggleStar}/>
      <span style={{ fontSize:10, fontFamily:'var(--font-mono)', color:'var(--ink-ghost)', minWidth:36, textAlign:'right' }}>
        {window.SM2.formatInterval(card?.interval)}
      </span>
    </div>
  );
};

window.Dashboard = Dashboard;
