// Today — daily task list, wired to today-tasks + complete-task
const { useState: tUseState, useEffect: tUseEffect } = React;

function Today() {
  const [tasks, setTasks] = tUseState([]);
  const [loading, setLoading] = tUseState(true);

  tUseEffect(() => {
    fnGetCached('today-tasks')
      .then(r => {
        const list = (r.tasks || []).map(transformTask);
        setTasks(list);
        window.TODAY_TASKS = list;
      })
      .catch(e => console.error('today-tasks:', e))
      .finally(() => setLoading(false));
  }, []);

  const toggle = (task) => {
    // Optimistic update
    setTasks(ts => ts.map(t => t.id === task.id ? { ...t, done: !t.done } : t));
    fnPost('complete-task', { task_id: task.id, mission_id: task.missionId, task_type: task.taskType })
      .catch(() => {
        // Revert on error
        setTasks(ts => ts.map(t => t.id === task.id ? { ...t, done: task.done } : t));
      });
  };

  const remaining = tasks.filter(t => !t.done);
  const totalMin = remaining.reduce((a, t) => a + parseInt(t.est, 10), 0);
  const hours = Math.floor(totalMin / 60);
  const mins = totalMin % 60;
  const totalLabel = hours > 0 ? `${hours}hr ${mins}min` : `${mins}min`;

  const grouped = VISIBLE_SUBJECTS
    .map(s => ({ subject: s, items: tasks.filter(t => t.subject === s.id) }))
    .filter(g => g.items.length > 0);

  const today = new Date();
  const dateLabel = today.toLocaleString('en', { weekday: 'long', month: 'long', day: 'numeric' });

  return (
    <>
      <Topbar crumbs={['Today']} actions={<span className="dim" style={{ fontSize: 12 }}>{dateLabel}</span>} />
      <div className="content">
        <div className="today-wrap">
          <div style={{ marginBottom: 28 }}>
            <div style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.018em', marginBottom: 4 }}>
              Good {greeting()}, Sahishnu.
            </div>
            <div className="muted" style={{ fontSize: 12.5 }}>
              {loading ? 'Loading…' : (
                <>
                  {remaining.length} task{remaining.length === 1 ? '' : 's'} today
                  <span className="faint"> · </span>~{totalLabel} total
                  {tasks.length - remaining.length > 0 && (
                    <><span className="faint"> · </span>{tasks.length - remaining.length} done</>
                  )}
                </>
              )}
            </div>
          </div>

          {loading && <div className="empty" style={{ padding: 48 }}><span className="spinner" /> Loading tasks…</div>}

          {!loading && grouped.map(({ subject, items }) => (
            <div key={subject.id} style={{ marginBottom: 22 }}>
              <div className="hstack" style={{ marginBottom: 6, gap: 8 }}>
                <span className="subj-dot" style={{ background: subject.hex, width: 6, height: 6 }} />
                <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--fg)' }}>{subject.short}</span>
                <span className="dim" style={{ fontSize: 11.5 }}>· {items[0]?.mission}</span>
                <span style={{ flex: 1, height: 1, background: 'var(--border)', marginLeft: 4 }} />
              </div>
              {items.map(t => (
                <div
                  key={t.id}
                  className="hstack"
                  style={{ padding: '8px 8px', borderRadius: 'var(--r-2)', cursor: 'pointer', gap: 10, transition: 'background 0.08s' }}
                  onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-1)'}
                  onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
                  onClick={() => toggle(t)}
                >
                  <Checkbox checked={t.done} onChange={() => toggle(t)} />
                  <span style={{ flex: 1, fontSize: 13, color: t.done ? 'var(--fg-3)' : 'var(--fg)', textDecoration: t.done ? 'line-through' : 'none' }}>
                    {t.label}
                  </span>
                  <span className="hstack dim" style={{ fontSize: 11.5, gap: 4 }}>
                    <I.Clock size={10} /> {t.est}
                  </span>
                </div>
              ))}
            </div>
          ))}

          {!loading && tasks.length === 0 && (
            <div className="empty" style={{ padding: '64px 24px' }}>
              <div style={{ fontSize: 13, color: 'var(--fg)', marginBottom: 4 }}>No tasks for today.</div>
              <div className="dim">Create a mission to build a study schedule.</div>
            </div>
          )}

          {!loading && remaining.length === 0 && tasks.length > 0 && (
            <div className="empty" style={{ padding: '64px 24px' }}>
              <div style={{ fontSize: 13, color: 'var(--fg)', marginBottom: 4 }}>All done for today.</div>
              <div className="dim">Take a break.</div>
            </div>
          )}
        </div>
      </div>
    </>
  );
}

function greeting() {
  const h = new Date().getHours();
  if (h < 12) return 'morning';
  if (h < 17) return 'afternoon';
  return 'evening';
}

window.Today = Today;
window.greeting = greeting;
