// Komonichi — Tasks page: CRUD + soft-delete + content-hash + area filter + recreate
const { useKomonichi, actions, sel } = window.KomonichiState;

function readAreaFromHash() {
  const [, qs] = (location.hash || '').replace(/^#/, '').split('?');
  return new URLSearchParams(qs || '').get('area') || 'all';
}

function TasksPage() {
  const [state] = useKomonichi();
  const [showAdd, setShowAdd] = React.useState(false);
  const [editingId, setEditingId] = React.useState(null);
  const [filter, setFilter] = React.useState('open');       // open | done | archived | all
  const [area, setArea]     = React.useState(readAreaFromHash());

  React.useEffect(() => {
    const f = () => setArea(readAreaFromHash());
    window.addEventListener('hashchange', f);
    return () => window.removeEventListener('hashchange', f);
  }, []);

  const activeAreas = state.areas.filter(a => a.status !== 'archived');
  let tasks = state.tasks;
  if (area === 'none')        tasks = tasks.filter(t => !t.areaId);
  else if (area === 'orphan') tasks = tasks.filter(t => t.areaId && !activeAreas.some(a => a.id === t.areaId));
  else if (area !== 'all')    tasks = tasks.filter(t => t.areaId === area);
  if (filter !== 'all')       tasks = tasks.filter(t => t.status === filter);

  return (
    <div className="fade-in">
      <div className="page-head" style={{ display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'end', marginBottom: 22, gap: 18 }}>
        <div>
          <div className="label">the work itself</div>
          <h2 className="display page-title" style={{ fontSize: 48, lineHeight: 1, margin: '8px 0 0' }}>
            tasks, <span style={{ color: 'var(--persimmon)' }}>kept small</span>
          </h2>
        </div>
        <div className="task-controls" style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap', justifyContent: 'flex-end' }}>
          <div className="task-area-select" style={{ width: 180 }}>
            {React.createElement(window.ThemedSelect, {
              value: area,
              onChange: (v) => { setArea(v); location.hash = '#tasks?area=' + v; },
              options: [
                { value: 'all',    label: 'all areas' },
                { value: 'none',   label: 'no area' },
                ...activeAreas.map(a => ({ value: a.id, label: a.name })),
                { value: 'orphan', label: '— orphaned —' },
              ],
            })}
          </div>
          {['open', 'done', 'archived', 'all'].map(f => (
            <button key={f} onClick={() => setFilter(f)} className="btn tiny"
              style={{ background: filter === f ? 'var(--ink)' : 'transparent', color: filter === f ? 'var(--paper)' : 'var(--ink)' }}>
              {f}
            </button>
          ))}
          <button className="btn warm" onClick={() => { setShowAdd(true); setEditingId(null); }}>+ task</button>
        </div>
      </div>

      <div className="brush" style={{ marginBottom: 22 }}></div>

      {showAdd && (
        <TaskForm
          initialAreaId={area && !['all','none','orphan'].includes(area) ? area : null}
          onCancel={() => setShowAdd(false)}
          onSubmit={(data) => { actions.addTask(data); setShowAdd(false); }}
        />
      )}

      <div style={{ display: 'grid', gap: 0 }}>
        {tasks.length === 0 && (
          <div className="haiku" style={{ padding: '40px 0', textAlign: 'center' }}>
            <span className="line">An empty page.</span>
            <span className="line">The brush is yours to lift — or</span>
            <span className="line">to lay quietly down.</span>
          </div>
        )}
        {tasks.map(t => (
          editingId === t.id ? (
            <div key={t.id} style={{ borderBottom: '1px solid var(--paper-line)' }}>
              <TaskForm
                initial={t}
                onCancel={() => setEditingId(null)}
                onSubmit={(data) => { actions.editTask(t.id, data); setEditingId(null); }}
              />
            </div>
          ) : (
            <TaskRow key={t.id} task={t} onEdit={() => setEditingId(t.id)} />
          )
        ))}
      </div>
    </div>
  );
}

function TaskRow({ task, onEdit }) {
  const [state] = useKomonichi();
  const obj  = task.objectiveId ? state.objectives.flat?.find(o => o.id === task.objectiveId) : null;
  const area = task.areaId      ? state.areas.find(a => a.id === task.areaId) : null;
  const isDone = task.status === 'done';
  const today = window.KomonichiState.todayKey();
  const overdue = task.status === 'open' && task.dueDate && task.dueDate < today;
  const dueToday = task.dueDate === today;
  return (
    <div className="task-row" style={{
      display: 'grid', gridTemplateColumns: '22px 1fr auto auto auto auto',
      gap: 16, alignItems: 'center', padding: '16px 4px',
      borderBottom: '1px dashed var(--paper-line)',
      opacity: task.status === 'archived' ? 0.4 : (isDone ? 0.55 : 1),
    }}>
      <button onClick={() => actions.toggleTaskDone(task.id)} aria-label="toggle"
        style={{
          width: 18, height: 18, borderRadius: '50%',
          border: '1px solid var(--ink-soft)',
          background: isDone ? 'var(--ink)' : 'transparent',
          padding: 0, cursor: 'pointer',
        }} />
      <div>
        <div style={{ fontSize: 15, textDecoration: isDone ? 'line-through' : 'none', textDecorationColor: 'var(--ink-ghost)' }}>
          {task.title}
          {task.content_hash ? (
            <span className="num" style={{ marginLeft: 10, color: 'var(--ink-ghost)', fontSize: 11 }}>#{task.content_hash}</span>
          ) : null}
        </div>
        {task.notes ? <div className="display" style={{ fontSize: 14, color: 'var(--ink-soft)', marginTop: 3 }}>{task.notes}</div> : null}
        <div style={{ marginTop: 5, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          {area ? <span className="chip moss">{area.name}</span> : null}
          {obj  ? <span className="chip indigo">↳ {obj.text}</span> : null}
          {task.dueDate ? (
            <span className={`chip ${overdue ? 'warm' : dueToday ? 'gold' : ''}`}>
              {overdue ? 'overdue · ' : dueToday ? 'today · ' : 'due · '}
              {new Date(task.dueDate + 'T00:00').toLocaleString('en', { month: 'short', day: 'numeric' })}
            </span>
          ) : task.status === 'open' ? (
            <button
              className="chip chip-button gold"
              onClick={() => actions.editTask(task.id, { due_date: today })}
              title="schedule for today">
              + today
            </button>
          ) : null}
        </div>
      </div>
      <div className="task-row-actions">
        <span className="chip">{task.estimate_min || task.estimateMin || 25}m</span>
        {task.status === 'done' ? (
          <button className="btn ghost tiny" onClick={() => actions.recreateTask(task.id)} title="recreate from this">recreate</button>
        ) : null}
        <button className="btn ghost tiny" onClick={onEdit}>edit</button>
        <button className="btn ghost tiny" onClick={() => actions.archiveTask(task.id)} title="archive (soft-delete)">×</button>
      </div>
    </div>
  );
}

function TaskForm({ initial, initialAreaId, onSubmit, onCancel }) {
  const [state] = useKomonichi();
  const [title, setTitle] = React.useState(initial?.title || '');
  const [notes, setNotes] = React.useState(initial?.notes || '');
  const [estimateMin, setEstimateMin] = React.useState(initial?.estimate_min || initial?.estimateMin || 25);
  const [objectiveId, setObjectiveId] = React.useState(initial?.objectiveId || '');
  const [areaId, setAreaId]           = React.useState(initial?.areaId || initialAreaId || '');
  const [dueDate, setDueDate]         = React.useState(initial?.dueDate || initial?.due_date || '');

  const allObjs = [
    ...state.objectives.weekly.map(o => ({ ...o, scale: 'week' })),
    ...state.objectives.monthly.map(o => ({ ...o, scale: 'month' })),
    ...state.objectives.quarterly.map(o => ({ ...o, scale: 'quarter' })),
    ...state.objectives.yearly.map(o => ({ ...o, scale: 'year' })),
  ];
  const activeAreas = state.areas.filter(a => a.status !== 'archived');

  const submit = (e) => {
    e.preventDefault();
    if (!title.trim()) return;
    onSubmit({
      title, notes,
      estimate_min: Number(estimateMin),
      objective_id: objectiveId || null,
      area_id:      areaId || null,
      due_date:     dueDate || null,
    });
  };

  return (
    <form onSubmit={submit} className="card fade-in" style={{ margin: '0 0 18px', background: 'rgba(255,253,247,0.7)' }}>
      <div className="cap">
        <div>
          <div className="label">{initial ? 'tend to' : 'place a new'}</div>
          <h3 className="title">{initial ? 'edit task' : 'a small task'}</h3>
        </div>
        <button type="button" className="btn ghost tiny" onClick={onCancel}>cancel</button>
      </div>
      <div style={{ display: 'grid', gap: 14 }}>
        <input className="f" autoFocus placeholder="what is to be done…" value={title} onChange={e => setTitle(e.target.value)} />
        <textarea className="f" placeholder="a note, if one is needed" value={notes} onChange={e => setNotes(e.target.value)} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 18 }}>
          <div>
            <div className="label" style={{ marginBottom: 6 }}>linked area</div>
            {React.createElement(window.ThemedSelect, {
              value: areaId,
              onChange: setAreaId,
              placeholder: '— none —',
              options: [
                { value: '', label: '— none —' },
                ...activeAreas.map(a => ({ value: a.id, label: a.name })),
              ],
            })}
          </div>
          <div>
            <div className="label" style={{ marginBottom: 6 }}>linked objective</div>
            {React.createElement(window.ThemedSelect, {
              value: objectiveId,
              onChange: setObjectiveId,
              placeholder: '— none —',
              options: [
                { value: '', label: '— none —' },
                ...allObjs.map(o => ({ value: o.id, label: `[${o.scale}] ${o.text}` })),
              ],
            })}
          </div>
          <div>
            <div className="label" style={{ marginBottom: 6 }}>estimate (minutes)</div>
            <input className="f" type="number" min="5" max="240" step="5" value={estimateMin} onChange={e => setEstimateMin(e.target.value)} />
          </div>
        </div>
        <div>
          <div className="label" style={{ marginBottom: 6 }}>due date</div>
          <input className="f" type="date" value={dueDate} onChange={e => setDueDate(e.target.value)} style={{ maxWidth: 220 }} />
        </div>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 6 }}>
          <button type="button" className="btn ghost" onClick={onCancel}>release</button>
          <button type="submit" className="btn warm">{initial ? 'save' : 'place'}</button>
        </div>
      </div>
    </form>
  );
}

window.TasksPage = TasksPage;
