// Direction A — additional views (Calendar, Pipeline, Metrics, Digest, Table)
// and the Task Detail slide-over panel.

function ATableRow({ task: t, onOpen, onDelete }) {
  const [hovered, setHovered] = React.useState(false);
  const [confirming, setConfirming] = React.useState(false);
  React.useEffect(() => { if (!hovered) setConfirming(false); }, [hovered]);
  return (
    <tr
      onClick={onOpen}
      onMouseEnter={(e) => { setHovered(true); e.currentTarget.style.background = A_TOKENS.paperDeep; }}
      onMouseLeave={(e) => { setHovered(false); e.currentTarget.style.background = 'transparent'; }}
      style={{
        borderBottom: `1px solid ${A_TOKENS.lineSoft}`,
        cursor: 'pointer',
        background: 'transparent',
        transition: 'background .1s',
      }}
    >
      <td style={{ padding: '14px 4px 14px 0', width: 4, background: A_CAT_COLOR[t.category] }} />
      <td style={{ padding: '14px 14px', fontWeight: 500, color: A_TOKENS.ink, maxWidth: 280, letterSpacing: -0.1 }}>{t.title}</td>
      <td style={{ padding: '14px 14px', color: A_TOKENS.inkSoft, maxWidth: 280, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t.next_step || '—'}</td>
      <td style={{ padding: '14px 14px', fontFamily: 'var(--mono)', fontSize: 10.5, color: A_CAT_COLOR[t.category], textTransform: 'uppercase', letterSpacing: 0.6 }}>{t.category}</td>
      <td style={{ padding: '14px 14px' }}><AAvatar name={t.owner} size={20} /></td>
      <td style={{ padding: '14px 14px', fontSize: 12, color: t.priority === 'High' ? A_TOKENS.accent : A_TOKENS.inkSoft, fontWeight: t.priority === 'High' ? 600 : 450 }}>{t.priority}</td>
      <td style={{ padding: '14px 14px' }}>
        <span style={{ fontSize: 12, color: A_TOKENS.inkSoft, display: 'inline-flex', alignItems: 'center', gap: 5 }}>
          <span>{A_STATUS_META[t.status].glyph}</span>{t.status}
        </span>
      </td>
      <td style={{ padding: '14px 14px' }}><ADueChip due={t.due_date} /></td>
      <td style={{ padding: '14px 10px', width: 32, textAlign: 'right' }}>
        {hovered && (
          <button
            onClick={(e) => {
              e.stopPropagation();
              if (confirming) onDelete(t.id);
              else setConfirming(true);
            }}
            title={confirming ? 'Click again to confirm' : 'Delete task'}
            style={{
              border: 'none', cursor: 'pointer',
              background: confirming ? A_TOKENS.accent : 'transparent',
              color: confirming ? '#fff' : A_TOKENS.inkSoft,
              fontSize: confirming ? 10 : 14, lineHeight: 1,
              padding: confirming ? '3px 8px' : '2px 6px', borderRadius: 3,
              fontFamily: confirming ? 'var(--mono)' : 'inherit',
              letterSpacing: confirming ? 0.5 : 0, textTransform: confirming ? 'uppercase' : 'none',
              fontWeight: confirming ? 600 : 400,
            }}
          >{confirming ? 'Delete?' : '×'}</button>
        )}
      </td>
    </tr>
  );
}

function ATable({ store, filter, onOpenTask }) {
  const visible = store.tasks.filter((t) => {
    if (filter.owner && filter.owner !== 'All' && t.owner !== filter.owner && t.owner !== 'Both') return false;
    if (filter.category && t.category !== filter.category) return false;
    if (filter.q && !(`${t.title} ${t.next_step}`.toLowerCase().includes(filter.q.toLowerCase()))) return false;
    return true;
  });
  const priOrd = { High: 0, Medium: 1, Low: 2 };
  visible.sort((a, b) => (priOrd[a.priority] - priOrd[b.priority]) || ((a.due_date || '9999') < (b.due_date || '9999') ? -1 : 1));

  return (
    <div style={{ padding: '0 32px 32px' }}>
      <div style={{
        background: A_TOKENS.card, border: `1px solid ${A_TOKENS.line}`,
        borderRadius: 6, overflow: 'hidden',
      }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, fontFamily: 'var(--body)' }}>
          <thead>
            <tr style={{ background: A_TOKENS.paperDeep, borderBottom: `1px solid ${A_TOKENS.line}` }}>
              {['', 'Task', 'Next step', 'Cat.', 'Owner', 'Priority', 'Status', 'Due', ''].map((h, i) => (
                <th key={i} style={{
                  textAlign: 'left', padding: '12px 14px',
                  fontSize: 10, fontWeight: 600, letterSpacing: 0.8, textTransform: 'uppercase',
                  color: A_TOKENS.inkSoft, fontFamily: 'var(--body)',
                }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {visible.map((t, i) => (
              <ATableRow key={t.id} task={t} onOpen={() => onOpenTask(t.id)} onDelete={store.deleteTask} />
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─────── Calendar — 4-week grid of due dates ───────
function ACalendar({ store, filter, onOpenTask }) {
  const today = new Date(); today.setHours(0,0,0,0);
  const start = new Date(today);
  start.setDate(start.getDate() - start.getDay()); // Sunday of this week
  const days = Array.from({ length: 28 }, (_, i) => {
    const d = new Date(start);
    d.setDate(start.getDate() + i);
    return d;
  });

  const tasksByDay = {};
  store.tasks.forEach((t) => {
    if (!t.due_date) return;
    if (filter.owner && filter.owner !== 'All' && t.owner !== filter.owner && t.owner !== 'Both') return;
    if (filter.category && t.category !== filter.category) return;
    (tasksByDay[t.due_date] ||= []).push(t);
  });

  const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

  return (
    <div style={{ padding: '0 32px 32px' }}>
      <div style={{ background: A_TOKENS.card, border: `1px solid ${A_TOKENS.line}`, borderRadius: 6, overflow: 'hidden' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', background: A_TOKENS.paperDeep, borderBottom: `1px solid ${A_TOKENS.line}` }}>
          {dayNames.map((d) => (
            <div key={d} style={{
              padding: '10px 12px', fontSize: 10, fontWeight: 600, letterSpacing: 0.8, textTransform: 'uppercase',
              color: A_TOKENS.inkSoft, textAlign: 'center',
            }}>{d}</div>
          ))}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gridAutoRows: '128px' }}>
          {days.map((d, i) => {
            const iso = d.toISOString().slice(0, 10);
            const list = tasksByDay[iso] || [];
            const isToday = d.getTime() === today.getTime();
            const isPast = d < today;
            return (
              <div key={i} style={{
                borderRight: `1px solid ${A_TOKENS.lineSoft}`,
                borderBottom: `1px solid ${A_TOKENS.lineSoft}`,
                padding: 10,
                background: isPast ? 'rgba(0,0,0,.015)' : 'transparent',
                display: 'flex', flexDirection: 'column',
                overflow: 'hidden',
              }}>
                <div style={{
                  fontSize: 11.5, fontFamily: 'var(--mono)',
                  fontWeight: isToday ? 700 : 500,
                  color: isToday ? A_TOKENS.accent : A_TOKENS.inkSoft,
                  marginBottom: 8,
                  display: 'flex', alignItems: 'baseline', gap: 6,
                }}>
                  <span>{d.getDate()}</span>
                  {d.getDate() === 1 && <span style={{ fontWeight: 400, fontSize: 10 }}>{d.toLocaleDateString(undefined, { month: 'short' })}</span>}
                  {isToday && <span style={{ fontSize: 9, color: A_TOKENS.accent, fontWeight: 600, letterSpacing: 0.8 }}>TODAY</span>}
                </div>
                <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column', gap: 3 }}>
                  {list.slice(0, 3).map((t) => (
                    <div key={t.id} onClick={() => onOpenTask(t.id)} style={{
                      fontSize: 11, lineHeight: 1.3, padding: '3px 6px',
                      background: A_TOKENS.paperDeep,
                      borderLeft: `2px solid ${A_CAT_COLOR[t.category]}`,
                      color: A_TOKENS.ink,
                      cursor: 'pointer', borderRadius: 2,
                      whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                    }}>{t.title}</div>
                  ))}
                  {list.length > 3 && (
                    <div style={{ fontSize: 10, color: A_TOKENS.inkFaint, marginTop: 2 }}>+{list.length - 3} more</div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ─────── Pipeline — stages for Acquisition tasks ───────
function APipeline({ store, onOpenTask }) {
  const stages = ['To Do', 'In Progress', 'Waiting', 'Blocked', 'Done'];
  const stageLabels = { 'To Do': 'Identified', 'In Progress': 'Active', 'Waiting': 'Awaiting', 'Blocked': 'Stuck', 'Done': 'Closed' };
  const acq = store.tasks.filter((t) => t.category === 'Acquisition');

  const byStage = Object.fromEntries(stages.map((s) => [s, acq.filter((t) => t.status === s)]));

  return (
    <div style={{ padding: '0 32px 32px' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, marginBottom: 20 }}>
        <div style={{ fontSize: 18, fontWeight: 600, color: A_TOKENS.ink, letterSpacing: -0.3 }}>Acquisition pipeline</div>
        <div style={{ fontSize: 12, color: A_TOKENS.inkSoft }}>{acq.length} deals in motion</div>
        <div style={{ flex: 1, height: 1, background: A_TOKENS.line }} />
      </div>

      {/* funnel bar */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 28 }}>
        {stages.map((s, i) => {
          const n = byStage[s].length;
          const pct = (n / Math.max(1, acq.length)) * 100;
          return (
            <div key={s} style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 6 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                <span style={{ fontSize: 28, fontWeight: 600, color: A_TOKENS.ink, fontFamily: 'var(--mono)', letterSpacing: -1 }}>{n}</span>
                <span style={{ fontSize: 10.5, fontFamily: 'var(--mono)', color: A_TOKENS.inkFaint, letterSpacing: 0.8, textTransform: 'uppercase' }}>{stageLabels[s]}</span>
              </div>
              <div style={{ height: 4, background: A_TOKENS.paperDeep, position: 'relative', borderRadius: 2, overflow: 'hidden' }}>
                <div style={{ position: 'absolute', inset: 0, background: s === 'Done' ? A_TOKENS.good : s === 'Blocked' ? A_TOKENS.bad : A_TOKENS.accent, width: `${Math.max(8, pct)}%`, opacity: 0.85 }} />
              </div>
            </div>
          );
        })}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12 }}>
        {stages.map((s) => (
          <div key={s}>
            <div style={{ fontSize: 10.5, fontFamily: 'var(--mono)', color: A_TOKENS.inkFaint, letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 10, padding: '0 2px' }}>
              {stageLabels[s]}
            </div>
            {byStage[s].map((t) => (
              <div key={t.id} onClick={() => onOpenTask(t.id)} style={{
                background: A_TOKENS.card, border: `1px solid ${A_TOKENS.lineSoft}`,
                padding: '11px 12px', marginBottom: 8, cursor: 'pointer', borderRadius: 5,
                borderLeft: `3px solid ${A_CAT_COLOR.Acquisition}`,
                transition: 'box-shadow .1s, border-color .1s',
              }}
              onMouseEnter={(e) => { e.currentTarget.style.borderColor = A_TOKENS.line; e.currentTarget.style.boxShadow = '0 2px 6px rgba(0,0,0,.04)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.borderColor = A_TOKENS.lineSoft; e.currentTarget.style.boxShadow = 'none'; }}>
                <div style={{ fontSize: 12.5, fontWeight: 500, color: A_TOKENS.ink, lineHeight: 1.35, marginBottom: 8, letterSpacing: -0.1 }}>{t.title}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <AAvatar name={t.owner} size={16} />
                  <ADueChip due={t.due_date} />
                </div>
              </div>
            ))}
            {byStage[s].length === 0 && (
              <div style={{ fontSize: 11, color: A_TOKENS.inkFaint, padding: 8 }}>—</div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

// ─────── Metrics ───────
function AMetrics({ store }) {
  const tasks = store.tasks;
  const active = tasks.filter((t) => t.status !== 'Done');
  const overdue = active.filter((t) => t.due_date && new Date(t.due_date) < new Date(new Date().toDateString()));
  const dueWeek = active.filter((t) => {
    if (!t.due_date) return false;
    const d = new Date(t.due_date);
    const now = new Date(new Date().toDateString());
    const wk = new Date(now); wk.setDate(wk.getDate() + 7);
    return d >= now && d <= wk;
  });

  const byStatus = Object.fromEntries(window.MOCK.STATUSES.map((s) => [s, tasks.filter((t) => t.status === s).length]));
  const byCat = Object.fromEntries(window.MOCK.CATEGORIES.map((c) => [c, tasks.filter((t) => t.category === c).length]));
  const byOwner = { Phil: tasks.filter((t) => t.owner === 'Phil' || t.owner === 'Both').filter((t) => t.status !== 'Done').length,
                    Bob: tasks.filter((t) => t.owner === 'Bob' || t.owner === 'Both').filter((t) => t.status !== 'Done').length };

  const max = Math.max(1, ...Object.values(byCat));

  const Stat = ({ label, value, sub, tone }) => (
    <div style={{ background: A_TOKENS.card, border: `1px solid ${A_TOKENS.line}`, borderRadius: 6, padding: '18px 20px', flex: 1 }}>
      <div style={{ fontSize: 10, fontFamily: 'var(--mono)', color: A_TOKENS.inkFaint, letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 10 }}>{label}</div>
      <div style={{ fontSize: 36, fontWeight: 600, color: tone === 'bad' ? A_TOKENS.bad : tone === 'warn' ? A_TOKENS.accent : A_TOKENS.ink, fontFamily: 'var(--mono)', lineHeight: 1, letterSpacing: -1.2 }}>{value}</div>
      {sub && <div style={{ fontSize: 11.5, color: A_TOKENS.inkSoft, marginTop: 10 }}>{sub}</div>}
    </div>
  );

  return (
    <div style={{ padding: '0 32px 32px', display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', gap: 14 }}>
        <Stat label="Active tasks" value={active.length} sub={`${tasks.length} total · ${byStatus.Done} done`} />
        <Stat label="Overdue" value={overdue.length} tone={overdue.length ? 'bad' : null} sub={overdue.length ? 'Needs attention' : 'All caught up'} />
        <Stat label="Due this week" value={dueWeek.length} tone={dueWeek.length > 5 ? 'warn' : null} />
        <Stat label="On Phil's plate" value={byOwner.Phil} />
        <Stat label="On Bob's plate" value={byOwner.Bob} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <div style={{ background: A_TOKENS.card, border: `1px solid ${A_TOKENS.line}`, borderRadius: 6, padding: 20 }}>
          <div style={{ fontSize: 11, fontFamily: 'var(--mono)', color: A_TOKENS.inkSoft, letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 18 }}>By category</div>
          {window.MOCK.CATEGORIES.map((c) => (
            <div key={c} style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 }}>
              <div style={{ width: 96, fontSize: 12.5, color: A_TOKENS.ink, fontWeight: 500, letterSpacing: -0.1 }}>{c}</div>
              <div style={{ flex: 1, height: 10, background: A_TOKENS.paperDeep, position: 'relative', borderRadius: 2, overflow: 'hidden' }}>
                <div style={{ position: 'absolute', inset: 0, right: 'auto', width: `${(byCat[c] / max) * 100}%`, background: A_CAT_COLOR[c], opacity: 0.9 }} />
              </div>
              <div style={{ width: 24, textAlign: 'right', fontSize: 11.5, fontFamily: 'var(--mono)', color: A_TOKENS.inkSoft }}>{byCat[c]}</div>
            </div>
          ))}
        </div>

        <div style={{ background: A_TOKENS.card, border: `1px solid ${A_TOKENS.line}`, borderRadius: 6, padding: 20 }}>
          <div style={{ fontSize: 11, fontFamily: 'var(--mono)', color: A_TOKENS.inkSoft, letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 18 }}>Flow — last 30 days</div>
          <svg viewBox="0 0 400 140" style={{ width: '100%', height: 140 }}>
            {/* Mock sparkline */}
            <g fontFamily="var(--mono)" fontSize="9" fill={A_TOKENS.inkFaint}>
              <text x="0" y="10">20</text>
              <text x="0" y="75">10</text>
              <text x="0" y="138">0</text>
            </g>
            {/* grid */}
            {[0, 1, 2, 3].map((i) => (
              <line key={i} x1="20" x2="400" y1={10 + i * 42} y2={10 + i * 42} stroke={A_TOKENS.lineSoft} strokeWidth="1" />
            ))}
            {/* In Progress */}
            <polyline fill="none" stroke={A_TOKENS.accent} strokeWidth="1.8"
              points="20,90 60,85 100,70 140,65 180,55 220,60 260,45 300,50 340,42 380,38" />
            {/* Done */}
            <polyline fill="none" stroke={A_TOKENS.good} strokeWidth="1.8"
              points="20,120 60,115 100,110 140,100 180,92 220,82 260,75 300,65 340,60 380,52" />
            {/* Overdue */}
            <polyline fill="none" stroke={A_TOKENS.bad} strokeWidth="1.8" strokeDasharray="2 3"
              points="20,128 60,130 100,128 140,122 180,120 220,115 260,118 300,122 340,125 380,122" />
          </svg>
          <div style={{ display: 'flex', gap: 16, fontSize: 10.5, fontFamily: 'var(--mono)', color: A_TOKENS.inkSoft, marginTop: 8 }}>
            <span><span style={{ display: 'inline-block', width: 8, height: 8, background: A_TOKENS.accent, marginRight: 4 }} />ACTIVE</span>
            <span><span style={{ display: 'inline-block', width: 8, height: 8, background: A_TOKENS.good, marginRight: 4 }} />DONE</span>
            <span><span style={{ display: 'inline-block', width: 8, height: 8, background: A_TOKENS.bad, marginRight: 4 }} />OVERDUE</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────── Weekly Digest preview ───────
function ADigest({ store, onOpenTask }) {
  const active = store.tasks.filter((t) => t.status !== 'Done');
  const overdue = active.filter((t) => t.due_date && new Date(t.due_date) < new Date(new Date().toDateString()));
  const dueWeek = active.filter((t) => {
    if (!t.due_date) return false;
    const d = new Date(t.due_date);
    const now = new Date(new Date().toDateString());
    const wk = new Date(now); wk.setDate(wk.getDate() + 7);
    return d >= now && d <= wk;
  });
  const completed = store.tasks.filter((t) => t.status === 'Done');
  const philTasks = active.filter((t) => t.owner === 'Phil' || t.owner === 'Both');
  const bobTasks = active.filter((t) => t.owner === 'Bob' || t.owner === 'Both');

  const Sec = ({ title, children }) => (
    <div style={{ marginBottom: 28 }}>
      <div style={{ fontSize: 10, fontFamily: 'var(--mono)', color: A_TOKENS.inkFaint, letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 10, borderBottom: `1px solid ${A_TOKENS.lineSoft}`, paddingBottom: 6 }}>{title}</div>
      {children}
    </div>
  );

  const Item = ({ t }) => (
    <div onClick={() => onOpenTask(t.id)} style={{ display: 'flex', gap: 10, padding: '7px 0', cursor: 'pointer', alignItems: 'center' }}>
      <div style={{ width: 3, height: 16, background: A_CAT_COLOR[t.category], borderRadius: 1 }} />
      <div style={{ flex: 1, fontSize: 13, color: A_TOKENS.ink, lineHeight: 1.4, letterSpacing: -0.1 }}>{t.title}</div>
      <ADueChip due={t.due_date} />
      <AAvatar name={t.owner} size={18} />
    </div>
  );

  return (
    <div style={{ padding: '0 32px 32px', display: 'flex', gap: 24 }}>
      <div style={{ width: 220, flexShrink: 0 }}>
        <div style={{ fontSize: 10, fontFamily: 'var(--mono)', color: A_TOKENS.inkFaint, letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 10 }}>Preview · Monday digest</div>
        <div style={{ fontSize: 12, color: A_TOKENS.inkSoft, lineHeight: 1.6 }}>
          Auto-generated every Monday at 7am. Sent to both of you. Summarizes what's overdue, what's due this week, what shipped, and where @mentions are waiting on you.
        </div>
      </div>
      <div style={{
        flex: 1, maxWidth: 680, background: A_TOKENS.card, border: `1px solid ${A_TOKENS.line}`, borderRadius: 6,
        padding: '32px 40px',
      }}>
        <div style={{ fontSize: 10, fontFamily: 'var(--mono)', color: A_TOKENS.inkFaint, letterSpacing: 1, textTransform: 'uppercase', marginBottom: 6 }}>
          FROM: DASHBOARD · TO: PHIL, BOB · MONDAY 7:00 AM
        </div>
        <div style={{ fontSize: 26, fontWeight: 600, color: A_TOKENS.ink, letterSpacing: -0.6, marginBottom: 6 }}>Week of {new Date().toLocaleDateString(undefined, { month: 'long', day: 'numeric' })}</div>
        <div style={{ fontSize: 13.5, color: A_TOKENS.inkSoft, marginBottom: 28 }}>
          {active.length} active · {overdue.length} overdue · {completed.length} shipped all-time
        </div>

        {overdue.length > 0 && <Sec title={`Overdue (${overdue.length})`}>{overdue.map((t) => <Item key={t.id} t={t} />)}</Sec>}
        <Sec title={`Due this week (${dueWeek.length})`}>{dueWeek.map((t) => <Item key={t.id} t={t} />)}</Sec>
        <Sec title={`On Phil's plate (${philTasks.length})`}>{philTasks.slice(0, 5).map((t) => <Item key={t.id} t={t} />)}</Sec>
        <Sec title={`On Bob's plate (${bobTasks.length})`}>{bobTasks.slice(0, 5).map((t) => <Item key={t.id} t={t} />)}</Sec>
      </div>
    </div>
  );
}

Object.assign(window, { ATable, ACalendar, APipeline, AMetrics, ADigest });
