// Today.jsx — daily home: streak, review queue, continue, recent work

function TodayScreen({ openMaterial, startSession, openTopic, go, streakOpen, dismissStreak, profile }) {
  const dueTotal = REVIEW_QUEUE.length;
  const firstName = ((profile && profile.name) || 'there').trim().split(/\s+/)[0];
  const ICONS = { sync:'refresh', gen:'sparkles', review:'check' };
  const [done, setDone] = React.useState(() => getReviewed());
  const toggleDone = (id) => { const arr = toggleReviewed(id); setDone(arr); try { window.dispatchEvent(new CustomEvent('pl-reviewed')); } catch (e) {} };
  // Stay in sync with reviews completed elsewhere (the "Mark complete" button on a
  // material, or a deck finishing) so a reviewed item shows "Completed" on return.
  React.useEffect(() => {
    const refresh = () => setDone(getReviewed());
    refresh();
    window.addEventListener('pl-reviewed', refresh);
    window.addEventListener('focus', refresh);
    document.addEventListener('visibilitychange', refresh);
    return () => { window.removeEventListener('pl-reviewed', refresh); window.removeEventListener('focus', refresh); document.removeEventListener('visibilitychange', refresh); };
  }, []);
  const doneCount = REVIEW_QUEUE.filter((q) => done.includes(q.id)).length;
  const remaining = dueTotal - doneCount;
  const ordered = [...REVIEW_QUEUE].sort((a, b) => (done.includes(a.id) ? 1 : 0) - (done.includes(b.id) ? 1 : 0));
  const firstDue = (REVIEW_QUEUE.find((q) => !done.includes(q.id)) || REVIEW_QUEUE[0]);
  // "Continue" advances to the next unfinished deck once the current one is completed.
  const CONTINUE = [
    { id:'m-nn-deck',   title:'Neural network fundamentals', topic:'Machine Learning',  left:'4 of 6 cards left',  value:60 },
    { id:'m-verb-deck', title:'Preterite vs. imperfect',     topic:'Language Learning', left:'9 of 24 cards left', value:62 },
    { id:'m-bees-deck', title:'Waggle dance — key facts',    topic:'Honeybees',         left:'2 of 6 cards left',  value:67 },
    { id:'m-cell-deck', title:'Cell Biology — core terms',   topic:'Biology',           left:'3 of 8 cards left',  value:62 },
  ];
  const cont = CONTINUE.find((c) => !done.includes(c.id)) || CONTINUE[CONTINUE.length - 1];
  const [compareOpen, setCompareOpen] = React.useState(false);
  // Cards the learner rated "Again/Hard" — surfaced so they get another pass.
  const HARD_QUESTIONS = [
    { id:'m-caf-sum',    q:'How can caffeine block adenosine if it’s a different molecule?', topic:'Caffeine',         accent:ACCENT.clay,  miss:3 },
    { id:'m-simpson-map',q:'Why can a trend reverse when groups are merged?',                topic:'Simpson’s Paradox',accent:ACCENT.lilac, miss:3 },
    { id:'m-sky-deck',   q:'Why is the sky blue but sunsets red, from the same physics?',    topic:'The Blue Sky',     accent:ACCENT.blue,  miss:2 },
    { id:'m-minor-deck', q:'What single change makes a chord sound minor?',                  topic:'Minor Chords',     accent:ACCENT.sage,  miss:2 },
  ];
  return (
    <div className="content-pad fade-up">
      <div className="page-head">
        <div>
          <p className="eyebrow">Tuesday, June 2</p>
          <h1>Good morning, {firstName}</h1>
          <p className="sub">{dueTotal} items in your review queue · 3 topics active this week</p>
        </div>
        <div style={{ display:'flex', gap:10, flexWrap:'wrap' }}>
          <button className="btn lg" onClick={()=>setCompareOpen(true)}>
            <Icon name="chart" size={17} /> Compare progress
          </button>
          <button className="btn blue lg" onClick={()=>startSession(ordered.map(q=>q.id))}>
            <Icon name="bolt" size={17} /> Start review
          </button>
        </div>
      </div>

      {streakOpen && (
        <div className="streak" style={{ marginBottom:22 }}>
          <span className="flame"><Icon name="flame" size={24} /></span>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:15, fontWeight:600 }}>7-day streak — nicely done</div>
            <div className="t-small">Review at least one deck today to keep it alive.</div>
          </div>
          <div className="seg-dots" style={{ marginRight:18 }}>
            {Array.from({length:7}).map((_,i)=><i key={i} className="done" style={{ background:'var(--positive)' }} />)}
          </div>
          <button className="x" onClick={dismissStreak} title="Dismiss"><Icon name="x" size={16} /></button>
        </div>
      )}

      <div className="col-main">
        <div style={{ display:'flex', flexDirection:'column', gap:20, minWidth:0 }}>
        {/* Review queue */}
        <div className="card pad">
          <div className="section-title">
            <h2><Icon name="clock" size={18} style={{ color:'var(--blue-ink)' }} /> Review queue
              <span className="count-pill">{remaining} due today</span>
              {doneCount>0 && <span className="count-pill" style={{ background:'color-mix(in srgb,var(--positive) 16%, var(--paper))', color:'var(--positive)' }}>{doneCount} done</span>}</h2>
            <button className="btn blue sm" onClick={()=>startSession(ordered.map(q=>q.id))}>Start <Icon name="arrow-right" size={15} /></button>
          </div>
          {ordered.map(q => { const isDone = done.includes(q.id); return (
            <div key={q.id} className="lrow" style={{ background:isDone?'color-mix(in srgb,var(--positive) 12%, var(--paper))':'color-mix(in srgb,var(--blue) 6%, var(--paper))', border:'1px solid var(--line)', borderRadius:12, padding:'10px 12px', marginBottom:8 }}>
              <button onClick={()=>toggleDone(q.id)} title={isDone?'Mark not done':'Mark done'} style={{ width:24, height:24, borderRadius:99, flex:'none', border:'2px solid '+(isDone?'var(--positive)':'var(--line-strong)'), background:isDone?'var(--positive)':'transparent', color:'#fff', display:'grid', placeItems:'center', cursor:'pointer', padding:0 }}>{isDone && <Icon name="check" size={14} />}</button>
              <span className="thumb" style={{ background:MAT_TYPE[q.type].bg, color:MAT_TYPE[q.type].tint, opacity:isDone?0.55:1 }}>
                <Icon name={MAT_TYPE[q.type].icon} size={20} /></span>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:14.5, fontWeight:600, letterSpacing:'-0.01em', textDecoration:isDone?'line-through':'none', opacity:isDone?0.6:1 }}>{q.title}</div>
                <div style={{ display:'flex', alignItems:'center', gap:7, marginTop:3 }}>
                  <span style={{ width:7, height:7, borderRadius:99, background:q.accent }} />
                  <span style={{ fontSize:12.5, color:'var(--ink-3)' }}>{q.topic}</span>
                </div>
              </div>
              <span className="mono" style={{ fontSize:11.5, color:isDone?'var(--positive)':'var(--ink-3)' }}>{isDone?'done':q.due}</span>
              {isDone
                ? <button className="btn sm" onClick={()=>openMaterial(q.id)} title="Review again" style={{ background:'color-mix(in srgb,var(--positive) 14%, var(--paper))', color:'var(--positive)', borderColor:'color-mix(in srgb,var(--positive) 32%, var(--line))', display:'inline-flex', alignItems:'center', gap:5 }}><Icon name="check" size={14} /> Completed</button>
                : <button className="btn sm" onClick={()=>openMaterial(q.id)}>Review</button>}
            </div>
          ); })}
        </div>

        {/* Hard questions — encourage another pass */}
        <div className="card pad">
          <div className="section-title">
            <h2><Icon name="flame" size={18} style={{ color:'var(--clay, #9C5B40)' }} /> Hard questions
              <span className="count-pill">{HARD_QUESTIONS.length}</span>
              {HARD_QUESTIONS.filter((h)=>done.includes(h.id)).length>0 && <span className="count-pill" style={{ background:'color-mix(in srgb,var(--positive) 16%, var(--paper))', color:'var(--positive)' }}>{HARD_QUESTIONS.filter((h)=>done.includes(h.id)).length} done</span>}</h2>
            <button className="btn blue sm" onClick={()=>startSession(HARD_QUESTIONS.map(h=>h.id))}>Review all <Icon name="arrow-right" size={15} /></button>
          </div>
          <div className="t-small" style={{ marginTop:-4, marginBottom:14 }}>These tripped you up recently — another pass will lock them in.</div>
          {HARD_QUESTIONS.map((h,i)=>{ const hd=done.includes(h.id); return (
            <button key={i} className="lrow" onClick={()=>openMaterial(h.id)}
              style={{ width:'100%', textAlign:'left', border:'1px solid var(--line)', background:hd?'color-mix(in srgb,var(--positive) 12%, var(--paper))':'transparent', cursor:'pointer', borderRadius:12, padding:'10px 12px', marginBottom:8, display:'flex', alignItems:'center', gap:11 }}>
              <span className="thumb" style={{ background:'color-mix(in srgb,'+h.accent+' 16%, var(--paper))', color:h.accent, flex:'none', opacity:hd?0.55:1 }}><Icon name="flame" size={18} /></span>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:14, fontWeight:600, letterSpacing:'-0.01em', lineHeight:1.35, textDecoration:hd?'line-through':'none', opacity:hd?0.6:1 }}>{h.q}</div>
                <div style={{ display:'flex', alignItems:'center', gap:7, marginTop:4 }}>
                  <span style={{ width:7, height:7, borderRadius:99, background:h.accent }} />
                  <span style={{ fontSize:12.5, color:'var(--ink-3)' }}>{h.topic} · missed {h.miss}×</span>
                </div>
              </div>
              {hd
                ? <span className="btn sm" style={{ pointerEvents:'none', flex:'none', background:'color-mix(in srgb,var(--positive) 14%, var(--paper))', color:'var(--positive)', borderColor:'color-mix(in srgb,var(--positive) 32%, var(--line))', display:'inline-flex', alignItems:'center', gap:5 }}><Icon name="check" size={13} /> Completed</span>
                : <span className="btn sm" style={{ pointerEvents:'none', flex:'none' }}>Review</span>}
            </button>); })}
        </div>
        </div>

        {/* right column */}
        <div style={{ display:'flex', flexDirection:'column', gap:20 }}>
          {/* Continue */}
          <div>
            <div className="section-title"><h2>Continue</h2></div>
            <div className="card hover" style={{ overflow:'hidden', cursor:'pointer' }} onClick={()=>openMaterial(cont.id)}>
              <div style={{ height:96, background:'linear-gradient(120deg, rgba(30,143,240,.16), rgba(30,143,240,.04))',
                position:'relative', display:'flex', alignItems:'center', justifyContent:'center' }}>
                <ConstellationField opacity={0.5} />
              </div>
              <div style={{ padding:16 }}>
                <TypeTag type="deck" />
                <div style={{ fontSize:15.5, fontWeight:600, margin:'9px 0 4px', letterSpacing:'-0.01em' }}>{cont.title}</div>
                <div style={{ fontSize:12.5, color:'var(--ink-3)', marginBottom:12 }}>{cont.topic} · {cont.left}</div>
                <ProgressBar value={cont.value} />
                <button className="btn primary block" style={{ marginTop:14 }} onClick={(e)=>{ e.stopPropagation(); openMaterial(cont.id); }}>Resume <Icon name="arrow-right" size={15} /></button>
              </div>
            </div>
          </div>

          {/* Recent work */}
          <div>
            <div className="section-title"><h2>Recent work</h2></div>
            <div className="card pad">
              {ACTIVITY.map((a,i)=>(
                <button key={i} className="lrow" onClick={()=>{ if(a.nav){ a.nav.type==='material' ? openMaterial(a.nav.id) : openTopic(a.nav.id); } }}
                  style={{ padding:'11px 6px', width:'100%', textAlign:'left', border:'none', background:'transparent', cursor:'pointer', borderRadius:'var(--r-sm)' }}
                  onMouseEnter={e=>e.currentTarget.style.background='var(--surface-2)'} onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                  <span className="itile" style={{ width:30, height:30, borderRadius:8,
                    background:'color-mix(in srgb,'+a.accent+' 16%, var(--paper))', color:a.accent }}>
                    <Icon name={ICONS[a.kind]} size={15} /></span>
                  <div style={{ flex:1, minWidth:0, lineHeight:1.35 }}>
                    <div style={{ fontSize:13.5, fontWeight:500 }}>{a.text}</div>
                    <div className="mono" style={{ fontSize:11, color:'var(--ink-3)', marginTop:2 }}>{a.meta}</div>
                  </div>
                  <Icon name="chevron-right" size={15} style={{ color:'var(--ink-4)' }} />
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>
      {compareOpen && <ProgressCompareModal subject={meSubject(profile)} onClose={()=>setCompareOpen(false)} />}
    </div>
  );
}
window.TodayScreen = TodayScreen;
