// Weak-problem queue + SRS revisit board

function RevisitView() {
  const { state, update } = useStore();
  const data = window.PLAN_DATA;
  const TODAY = useToday();
  const today = fmtDate(TODAY);

  const [draft, setDraft] = React.useState({ topic: data.dsa[0]?.topic || '', title: '' });

  const setWeak = (id, patch) => {
    update(prev => ({
      ...prev,
      weak: { ...prev.weak, [id]: patch == null ? undefined : { ...prev.weak[id], ...patch } }
    }));
  };
  const removeWeak = (id) => {
    update(prev => {
      const next = { ...prev.weak };
      delete next[id];
      return { ...prev, weak: next };
    });
  };

  function addWeak() {
    if (!draft.title.trim()) return;
    const id = `w_${Date.now()}_${Math.floor(Math.random()*1e4)}`;
    setWeak(id, {
      id, topic: draft.topic, title: draft.title.trim(),
      addedOn: today, intervalIdx: 0,
      dueDate: srsNextDue(TODAY, 0),
      history: [],
    });
    setDraft({ ...draft, title: '' });
  }

  function markReviewed(id) {
    const w = state.weak[id];
    if (!w) return;
    const nextIdx = (w.intervalIdx ?? 0) + 1;
    if (nextIdx >= SRS_INTERVALS.length) {
      // Graduated — drop from queue
      removeWeak(id);
      return;
    }
    setWeak(id, {
      intervalIdx: nextIdx,
      dueDate: srsNextDue(TODAY, nextIdx),
      history: [...(w.history || []), today],
    });
  }

  const items = Object.values(state.weak).filter(Boolean);
  const due = items.filter(w => w.dueDate <= today).sort((a,b) => a.dueDate.localeCompare(b.dueDate));
  const upcoming = items.filter(w => w.dueDate > today).sort((a,b) => a.dueDate.localeCompare(b.dueDate));

  function Row({ w, dueState }) {
    const daysLate = daysBetween(parseDate(w.dueDate), TODAY);
    return (
      <div className="card" style={{padding:'14px 18px', display:'grid', gridTemplateColumns:'1fr 140px 100px 90px 90px', gap:'12px', alignItems:'center'}}>
        <div>
          <div style={{fontSize:'13px', fontWeight:500}}>{w.title}</div>
          <div className="mono muted" style={{fontSize:'10px', marginTop:'2px', letterSpacing:'0.06em'}}>
            {w.topic} · added {w.addedOn} · {w.history?.length || 0} review{(w.history?.length||0) === 1 ? '' : 's'}
          </div>
        </div>
        <div className="mono" style={{fontSize:'11px', color: dueState === 'late' ? 'var(--rose)' : dueState === 'today' ? 'var(--accent)' : 'var(--ink-2)'}}>
          {dueState === 'late' && `due ${daysLate}d ago`}
          {dueState === 'today' && 'due today'}
          {dueState === 'upcoming' && `in ${-daysLate}d`}
        </div>
        <div className="mono muted" style={{fontSize:'11px'}}>
          step {(w.intervalIdx ?? 0) + 1}/{SRS_INTERVALS.length}
        </div>
        <button className="btn" onClick={() => markReviewed(w.id)} style={{padding:'6px 10px', fontSize:'11px'}}>Reviewed</button>
        <button className="btn ghost" onClick={() => removeWeak(w.id)} style={{padding:'6px 10px', fontSize:'11px', color:'var(--rose)'}}>Drop</button>
      </div>
    );
  }

  return (
    <div className="fade-in">
      <div className="section-h">
        <div>
          <div className="kicker">Spaced repetition · {SRS_INTERVALS.join(' / ')} day intervals</div>
          <h1 className="h-title">Weak problems, <em>hammered</em>.</h1>
        </div>
        <div style={{display:'flex',gap:'14px'}}>
          <Stat label="Due now" value={<CountUp to={due.length} />} accent sub={due.length ? 'work these today' : 'clean queue'} />
          <Stat label="In queue" value={<CountUp to={items.length} />} sub={`${upcoming.length} scheduled ahead`} />
        </div>
      </div>

      {/* Add new */}
      <div className="card" style={{marginBottom:'24px'}}>
        <div className="kicker" style={{marginBottom:'10px'}}>Log a weak problem</div>
        <div style={{display:'grid', gridTemplateColumns:'200px 1fr 110px', gap:'10px'}}>
          <select className="select" value={draft.topic} onChange={e => setDraft({...draft, topic: e.target.value})}>
            {data.dsa.map(t => <option key={t.num} value={t.topic}>{t.topic}</option>)}
            <option value="LLD">LLD</option>
            <option value="HLD">HLD</option>
            <option value="Other">Other</option>
          </select>
          <input className="input" placeholder="e.g. Koko Eating Bananas — couldn't ID search-on-answer in 5 min"
            value={draft.title}
            onChange={e => setDraft({...draft, title: e.target.value})}
            onKeyDown={e => { if (e.key === 'Enter') addWeak(); }} />
          <button className="btn primary" onClick={addWeak} style={{justifyContent:'center'}}>+ Add</button>
        </div>
      </div>

      {due.length > 0 && (
        <div style={{marginBottom:'24px'}}>
          <div className="kicker" style={{marginBottom:'10px'}}>Due / Overdue</div>
          <div className="col" style={{gap:'8px'}}>
            {due.map(w => (
              <Row key={w.id} w={w} dueState={w.dueDate < today ? 'late' : 'today'} />
            ))}
          </div>
        </div>
      )}

      {upcoming.length > 0 && (
        <div>
          <div className="kicker" style={{marginBottom:'10px'}}>Upcoming reviews</div>
          <div className="col" style={{gap:'8px'}}>
            {upcoming.map(w => <Row key={w.id} w={w} dueState="upcoming" />)}
          </div>
        </div>
      )}

      {items.length === 0 && (
        <div className="card" style={{textAlign:'center', padding:'48px'}}>
          <div className="kicker">Empty queue</div>
          <div style={{fontFamily:'var(--serif)',fontSize:'28px',marginTop:'8px'}}>Nothing to revisit.</div>
          <div className="muted" style={{fontSize:'12px',marginTop:'8px'}}>
            Log a problem when you couldn't ID its pattern in 5 minutes during Pass 2 / Pass 3.
          </div>
        </div>
      )}
    </div>
  );
}

window.RevisitView = RevisitView;
