// Pending work board - carry-forward items that did not fit into the planned day.

function PendingView() {
  const { state, update } = useStore();
  const data = window.PLAN_DATA;
  const TODAY = useToday();
  const today = fmtDate(TODAY);
  const [filter, setFilter] = React.useState('open');
  const [draft, setDraft] = React.useState({
    title: '',
    sourceDate: today,
    targetDate: '',
    type: 'DSA',
    priority: 'normal',
  });

  const items = Object.values(state.pending || {}).filter(Boolean);
  const openItems = items.filter(item => item.status !== 'done');
  const doneItems = items.filter(item => item.status === 'done');
  const dueItems = openItems.filter(item => item.targetDate && item.targetDate <= today);
  const unscheduledItems = openItems.filter(item => !item.targetDate);
  const sourceDates = Array.from(new Set(openItems.map(item => item.sourceDate).filter(Boolean))).sort();

  function dateAfter(days) {
    const d = new Date(TODAY);
    d.setDate(d.getDate() + days);
    return fmtDate(d);
  }

  function nextSunday() {
    const d = new Date(TODAY);
    const add = (7 - d.getDay()) % 7;
    d.setDate(d.getDate() + add);
    return fmtDate(d);
  }

  function addPending() {
    const title = draft.title.trim();
    if (!title) return;
    const id = `p_${Date.now()}_${Math.floor(Math.random() * 1e4)}`;
    update(prev => ({
      ...prev,
      pending: {
        ...(prev.pending || {}),
        [id]: {
          id,
          title,
          sourceDate: draft.sourceDate || today,
          targetDate: draft.targetDate || '',
          type: draft.type || 'OTHER',
          priority: draft.priority || 'normal',
          status: 'open',
          createdAt: new Date().toISOString(),
          completedAt: '',
          note: '',
        },
      },
    }));
    setDraft(prev => ({ ...prev, title: '' }));
  }

  function patchPending(id, patch) {
    update(prev => ({
      ...prev,
      pending: {
        ...(prev.pending || {}),
        [id]: { ...(prev.pending || {})[id], ...patch },
      },
    }));
  }

  function removePending(id) {
    update(prev => {
      const next = { ...(prev.pending || {}) };
      delete next[id];
      return { ...prev, pending: next };
    });
  }

  function completePending(id) {
    patchPending(id, { status: 'done', completedAt: new Date().toISOString() });
  }

  function reopenPending(id) {
    patchPending(id, { status: 'open', completedAt: '' });
  }

  function sourceEntry(item) {
    return data.calendar.find(day => day.date === item.sourceDate);
  }

  const visibleItems = (() => {
    if (filter === 'due') return dueItems;
    if (filter === 'unscheduled') return unscheduledItems;
    if (filter === 'done') return doneItems;
    return openItems;
  })().sort((a, b) => {
    const priorityRank = { high: 0, normal: 1, low: 2 };
    const aDue = a.targetDate || '9999-12-31';
    const bDue = b.targetDate || '9999-12-31';
    if (aDue !== bDue) return aDue.localeCompare(bDue);
    return (priorityRank[a.priority] ?? 1) - (priorityRank[b.priority] ?? 1);
  });

  function PendingRow({ item }) {
    const entry = sourceEntry(item);
    const isDone = item.status === 'done';
    const isDue = !isDone && item.targetDate && item.targetDate <= today;
    return (
      <div className="card" style={{padding:'16px 18px', borderColor: isDue ? 'var(--warn)' : 'var(--line)'}}>
        <div style={{display:'grid', gridTemplateColumns:'1fr auto', gap:'14px', alignItems:'start'}}>
          <div style={{minWidth:0}}>
            <div style={{display:'flex', gap:'8px', flexWrap:'wrap', alignItems:'center', marginBottom:'8px'}}>
              <TypePill type={item.type || 'OTHER'} />
              <Pill kind={item.priority === 'high' ? 'hot' : ''}>{item.priority || 'normal'}</Pill>
              {item.targetDate ? <Pill>{item.targetDate <= today && !isDone ? 'due now' : `planned ${item.targetDate}`}</Pill> : <Pill>unscheduled</Pill>}
              <span className="mono muted" style={{fontSize:'10px'}}>from {item.sourceDate || 'unknown'}</span>
            </div>
            <div style={{fontSize:'16px', fontWeight:700, lineHeight:1.35, textDecoration:isDone ? 'line-through' : 'none', opacity:isDone ? 0.55 : 1}}>
              {item.title}
            </div>
            {entry && (
              <div className="mono muted" style={{fontSize:'10px', marginTop:'8px', lineHeight:1.6}}>
                source: {entry.type} - {entry.hours}h planned - {(entry.dsa || entry.lld || '').slice(0, 110)}
              </div>
            )}
            <textarea
              className="textarea"
              placeholder="Small note, blocker, or exact remaining range..."
              value={item.note || ''}
              onChange={e => patchPending(item.id, { note: e.target.value })}
              style={{marginTop:'12px', minHeight:'74px'}}
            />
          </div>
          <div style={{display:'grid', gap:'8px', minWidth:'190px'}}>
            <input
              className="input"
              type="date"
              value={item.targetDate || ''}
              onChange={e => patchPending(item.id, { targetDate: e.target.value })}
              style={{fontFamily:'var(--mono)', padding:'8px 10px'}}
            />
            <select className="select" value={item.priority || 'normal'} onChange={e => patchPending(item.id, { priority: e.target.value })}>
              <option value="high">High priority</option>
              <option value="normal">Normal priority</option>
              <option value="low">Low priority</option>
            </select>
            <div style={{display:'flex', gap:'8px', flexWrap:'wrap'}}>
              <button className="btn" onClick={() => patchPending(item.id, { targetDate: today })} style={{padding:'7px 10px', fontSize:'11px'}}>Today</button>
              <button className="btn" onClick={() => patchPending(item.id, { targetDate: nextSunday() })} style={{padding:'7px 10px', fontSize:'11px'}}>Sunday</button>
              <button className="btn" onClick={() => patchPending(item.id, { targetDate: dateAfter(7) })} style={{padding:'7px 10px', fontSize:'11px'}}>+7d</button>
            </div>
            {isDone ? (
              <button className="btn" onClick={() => reopenPending(item.id)}>Reopen</button>
            ) : (
              <button className="btn primary" onClick={() => completePending(item.id)}>Complete</button>
            )}
            <button className="btn ghost" onClick={() => removePending(item.id)} style={{color:'var(--rose)'}}>Delete</button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="fade-in">
      <div className="section-h">
        <div>
          <div className="kicker">Carry-forward work</div>
          <h1 className="h-title">Pending list, <em>under control</em>.</h1>
        </div>
        <div style={{display:'grid', gridTemplateColumns:'repeat(3, minmax(120px, 1fr))', gap:'14px'}}>
          <Stat label="Open" value={<CountUp to={openItems.length} />} sub={`${dueItems.length} due now`} accent={openItems.length > 0} />
          <Stat label="Unscheduled" value={<CountUp to={unscheduledItems.length} />} sub="needs a date" />
          <Stat label="Done" value={<CountUp to={doneItems.length} />} sub="closed items" />
        </div>
      </div>

      <div className="card" style={{marginBottom:'22px'}}>
        <div className="kicker" style={{marginBottom:'10px'}}>Add pending item</div>
        <div style={{display:'grid', gridTemplateColumns:'1fr 150px 150px 140px 130px auto', gap:'10px', alignItems:'center'}}>
          <input
            className="input"
            value={draft.title}
            onChange={e => setDraft({ ...draft, title: e.target.value })}
            onKeyDown={e => { if (e.key === 'Enter') addPending(); }}
            placeholder="e.g. DP problems 31-52 still pending"
          />
          <input className="input" type="date" value={draft.sourceDate} onChange={e => setDraft({ ...draft, sourceDate: e.target.value })} style={{fontFamily:'var(--mono)'}} />
          <input className="input" type="date" value={draft.targetDate} onChange={e => setDraft({ ...draft, targetDate: e.target.value })} style={{fontFamily:'var(--mono)'}} />
          <select className="select" value={draft.type} onChange={e => setDraft({ ...draft, type: e.target.value })}>
            <option value="DSA">DSA</option>
            <option value="LLD">LLD</option>
            <option value="HLD">HLD</option>
            <option value="MOCK">MOCK</option>
            <option value="APPLY">APPLY</option>
            <option value="OTHER">OTHER</option>
          </select>
          <select className="select" value={draft.priority} onChange={e => setDraft({ ...draft, priority: e.target.value })}>
            <option value="high">High</option>
            <option value="normal">Normal</option>
            <option value="low">Low</option>
          </select>
          <button className="btn primary" onClick={addPending}>+ Add</button>
        </div>
      </div>

      <div className="card" style={{marginBottom:'18px'}}>
        <div style={{display:'flex', gap:'8px', flexWrap:'wrap', justifyContent:'space-between', alignItems:'center'}}>
          <div style={{display:'flex', gap:'8px', flexWrap:'wrap'}}>
            {[
              ['open', `Open (${openItems.length})`],
              ['due', `Due now (${dueItems.length})`],
              ['unscheduled', `Unscheduled (${unscheduledItems.length})`],
              ['done', `Done (${doneItems.length})`],
            ].map(([id, label]) => (
              <button key={id} className={`btn ${filter === id ? 'primary' : ''}`} onClick={() => setFilter(id)}>{label}</button>
            ))}
          </div>
          {sourceDates.length > 0 && (
            <div className="mono muted" style={{fontSize:'10px'}}>
              source days: {sourceDates.slice(0, 4).join(', ')}{sourceDates.length > 4 ? ` +${sourceDates.length - 4}` : ''}
            </div>
          )}
        </div>
      </div>

      {visibleItems.length > 0 ? (
        <div className="col" style={{gap:'12px'}}>
          {visibleItems.map(item => <PendingRow key={item.id} item={item} />)}
        </div>
      ) : (
        <div className="card" style={{textAlign:'center', padding:'48px'}}>
          <div className="kicker">No items here</div>
          <div style={{fontFamily:'var(--serif)',fontSize:'28px',marginTop:'8px'}}>
            Nothing pending in this filter.
          </div>
          <div className="muted" style={{fontSize:'12px', marginTop:'8px'}}>
            Use Today to carry forward unfinished schedule pieces, or add one manually above.
          </div>
        </div>
      )}
    </div>
  );
}

window.PendingView = PendingView;
