// AUTOMATION PLATFORM — Dashboard + Tasks tabs
const { useState: useAuDashState, useMemo: useAuDashMemo } = React;
const Taud = window.ArbiterTokens;

function AutoDashboard({ data }) {
  const au = window.__au;
  const k = data.kpis;
  const daily = data.analytics.daily14;
  const maxRuns = Math.max(...daily.map(d => d.runs));
  const outcomes = data.analytics.runsByOutcome;
  const totalOutcomes = outcomes.reduce((s, o) => s + o.count, 0);

  const upcomingTasks = [...data.tasks]
    .filter(t => t.status !== 'Completed' && t.status !== 'Cancelled')
    .sort((a, b) => a.dueDate.localeCompare(b.dueDate))
    .slice(0, 6);

  return (
    <div>
      <AuHero
        accent={au.lime} bg={au.limeBg}
        title="Automation platform — control center"
        description={<>
          Cross-platform view of tasks, workflow runs, events, and triggers. <b style={{ fontFamily: Taud.font.mono }}>{k.activeRuns}</b> runs in flight · <b style={{ color: au.emerald, fontFamily: Taud.font.mono }}>{k.successRatePct}%</b> success YTD · <b style={{ fontFamily: Taud.font.mono }}>{au.num(k.eventsPerDay)}</b> events/day across <b>{k.integrationsConnected}</b> integrations.
        </>}
      />
      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={au.stat}><span style={au.statLabel}>Active tasks</span><span style={au.statValue}>{au.num(k.activeTasks)}</span><span style={{ ...au.statDelta, color: Taud.color.text.tertiary }}>{k.dueThisWeek} due this week · <span style={{ color: au.crimson, fontWeight: 700 }}>{k.overdue} overdue</span></span></div>
        <div style={au.stat}><span style={au.statLabel}>Active runs</span><span style={{ ...au.statValue, color: au.lime }}>{k.activeRuns}</span><span style={{ ...au.statDelta, color: Taud.color.text.tertiary }}>avg {k.avgRunMinutes} min / run</span></div>
        <div style={au.stat}><span style={au.statLabel}>Workflows</span><span style={au.statValue}>{k.workflowsActive}<span style={{ fontSize: '14px', color: Taud.color.text.tertiary, fontWeight: 500 }}> / {k.workflowsDefined}</span></span><span style={{ ...au.statDelta, color: Taud.color.text.tertiary }}>active / defined</span></div>
        <div style={au.stat}><span style={au.statLabel}>Success rate YTD</span><span style={{ ...au.statValue, color: au.emerald }}>{k.successRatePct}%</span><span style={{ ...au.statDelta, color: Taud.color.text.tertiary }}>{au.num(k.runsSucceededYtd)} succ · {k.runsFailedYtd} fail</span></div>
        <div style={au.stat}><span style={au.statLabel}>Events / day</span><span style={{ ...au.statValue, color: au.cobalt }}>{au.num(k.eventsPerDay)}</span><span style={{ ...au.statDelta, color: Taud.color.text.tertiary }}>{k.triggersActive} triggers · {k.integrationsConnected} integrations</span></div>
        <div style={au.stat}><span style={au.statLabel}>Audit events YTD</span><span style={au.statValue}>{au.num(k.auditEventsYtd)}</span><span style={{ ...au.statDelta, color: Taud.color.text.tertiary }}>compliance-grade log</span></div>
      </div>

      {/* 14-day trend + run outcome donut */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: '14px', marginBottom: '16px' }}>
        <div style={au.card}>
          <div style={au.cardH}>
            <span>Runs · last 14 days</span>
            <span style={{ fontSize: '10px', color: Taud.color.text.tertiary, fontWeight: 500 }}>Peak {Math.max(...daily.map(d=>d.runs))} / day</span>
          </div>
          <div style={{ padding: '18px 16px 14px', display: 'flex', gap: '6px', alignItems: 'flex-end', height: '160px' }}>
            {daily.map((d, i) => (
              <div key={d.d} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '3px' }}>
                <div style={{ width: '100%', height: '120px', display: 'flex', alignItems: 'flex-end', justifyContent: 'center' }}>
                  <div style={{ width: '70%', height: `${(d.runs / maxRuns) * 100}%`, background: `linear-gradient(180deg, ${au.limeLight} 0%, ${au.lime} 100%)`, borderRadius: '3px 3px 0 0' }} />
                </div>
                <span style={{ fontSize: '9px', color: Taud.color.text.tertiary, fontFamily: Taud.font.mono }}>{d.d}</span>
              </div>
            ))}
          </div>
        </div>

        <div style={au.card}>
          <div style={au.cardH}>Run outcomes YTD</div>
          <div style={{ padding: '18px 16px' }}>
            {outcomes.map(o => {
              const color = o.outcome === 'Succeeded' ? au.emerald : o.outcome === 'Failed' ? au.crimson : Taud.color.text.tertiary;
              return (
                <div key={o.outcome} style={{ marginBottom: '14px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
                    <span style={{ fontSize: '11px', fontWeight: 600, color: Taud.color.text.primary }}>{o.outcome}</span>
                    <span style={{ fontSize: '11px', fontFamily: Taud.font.mono, color }}>{au.num(o.count)} · {o.pct}%</span>
                  </div>
                  <div style={{ height: '8px', background: Taud.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                    <div style={{ width: `${(o.count / totalOutcomes) * 100}%`, height: '100%', background: color }} />
                  </div>
                </div>
              );
            })}
            <div style={{ marginTop: '18px', padding: '10px', background: Taud.color.bg.secondary, borderRadius: '6px', fontSize: '10px', color: Taud.color.text.tertiary, textAlign: 'center' }}>
              <span style={{ fontWeight: 700, color: au.emerald }}>{au.num(totalOutcomes)}</span> total runs · <span style={{ color: au.lime, fontWeight: 700 }}>99.2% uptime</span>
            </div>
          </div>
        </div>
      </div>

      {/* Two column: pipeline + upcoming tasks */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px', marginBottom: '16px' }}>
        <div style={au.card}>
          <div style={au.cardH}>Task pipeline — by stage</div>
          <div style={{ padding: '14px 16px', display: 'flex', gap: '8px' }}>
            {[
              { name: 'To Do',       count: data.tasks.filter(t => t.status === 'To Do').length,       color: au.slate },
              { name: 'In Progress', count: data.tasks.filter(t => t.status === 'In Progress').length, color: au.cobalt },
              { name: 'Waiting',     count: data.tasks.filter(t => t.status === 'Waiting').length,     color: au.amber },
              { name: 'Blocked',     count: data.tasks.filter(t => t.status === 'Blocked').length,     color: au.crimson },
              { name: 'Completed',   count: data.tasks.filter(t => t.status === 'Completed').length,   color: au.emerald },
            ].map((s, i, arr) => (
              <div key={s.name} style={{ flex: 1, position: 'relative' }}>
                <div style={{ padding: '10px 8px', background: `${s.color}12`, border: `1px solid ${s.color}22`, borderRadius: '6px', textAlign: 'center' }}>
                  <div style={{ fontSize: '9px', fontWeight: 700, color: s.color, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '3px' }}>{s.name}</div>
                  <div style={{ fontSize: '22px', fontWeight: 700, color: s.color, fontFamily: Taud.font.mono }}>{s.count}</div>
                </div>
                {i < arr.length - 1 && (
                  <div style={{ position: 'absolute', right: '-5px', top: '50%', transform: 'translateY(-50%)', color: Taud.color.text.tertiary, fontSize: '11px' }}>›</div>
                )}
              </div>
            ))}
          </div>
        </div>

        <div style={au.card}>
          <div style={{ ...au.cardH, color: au.amber }}>◷ Upcoming deadlines</div>
          <div>
            {upcomingTasks.map(t => {
              const pc = au.priorityColor(t.priority);
              return (
                <div key={t.id} style={{ padding: '9px 16px', borderBottom: `1px solid ${Taud.color.border.light}`, borderLeft: `3px solid ${pc.color}` }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
                    <span style={{ fontSize: '10px', fontFamily: Taud.font.mono, color: au.amber, fontWeight: 700 }}>{t.dueDate}</span>
                    <span style={{ ...au.tag, background: pc.bg, color: pc.color }}>{t.priority}</span>
                  </div>
                  <div style={{ fontSize: '11px', fontWeight: 600, color: Taud.color.text.primary, lineHeight: 1.35 }}>{t.title}</div>
                  <div style={{ fontSize: '10px', color: Taud.color.text.tertiary, marginTop: '2px' }}>{t.matter} · {t.assignee}</div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Active triggers summary */}
      <div style={au.card}>
        <div style={au.cardH}>
          <span>Most active triggers · today</span>
          <span style={{ fontSize: '10px', color: Taud.color.text.tertiary, fontWeight: 500 }}>fired count · YTD</span>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={au.th}>Trigger</th>
              <th style={au.th}>Kind</th>
              <th style={au.th}>Target</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Today</th>
              <th style={{ ...au.th, textAlign: 'right' }}>YTD</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Avg ms</th>
            </tr>
          </thead>
          <tbody>
            {[...data.triggers].sort((a, b) => b.firedToday - a.firedToday).slice(0, 6).map(t => {
              const ks = au.triggerStyle(t.kind);
              return (
                <tr key={t.id}>
                  <td style={{ ...au.td, fontWeight: 600, color: Taud.color.text.primary, maxWidth: '380px' }}>{t.name}<div style={{ fontSize: '10px', color: Taud.color.text.tertiary, marginTop: '2px', fontFamily: Taud.font.mono }}>{t.id} · on {t.on}</div></td>
                  <td style={au.td}><span style={{ ...au.tag, background: ks.bg, color: ks.color }}>{ks.icon} {t.kind}</span></td>
                  <td style={{ ...au.td, fontSize: '11px', color: Taud.color.text.secondary }}>{t.target}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Taud.font.mono, color: au.lime, fontWeight: 700 }}>{t.firedToday}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Taud.font.mono, color: Taud.color.text.primary }}>{au.num(t.firedYtd)}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Taud.font.mono, color: Taud.color.text.tertiary }}>{au.num(t.avgRunMs)}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function AutoTasks({ data }) {
  const au = window.__au;
  const [statusFilter, setStatusFilter] = useAuDashState('All');
  const [priorityFilter, setPriorityFilter] = useAuDashState('All');
  const [assigneeFilter, setAssigneeFilter] = useAuDashState('All');
  const [search, setSearch] = useAuDashState('');

  const statuses  = useAuDashMemo(() => ['All', ...new Set(data.tasks.map(t => t.status))], [data]);
  const priorities = ['All', 'P0', 'P1', 'P2', 'P3'];
  const assignees  = useAuDashMemo(() => ['All', ...new Set(data.tasks.map(t => t.assignee))], [data]);

  const filtered = data.tasks.filter(t =>
    (statusFilter === 'All'   || t.status === statusFilter) &&
    (priorityFilter === 'All' || t.priority === priorityFilter) &&
    (assigneeFilter === 'All' || t.assignee === assigneeFilter) &&
    (!search || t.title.toLowerCase().includes(search.toLowerCase()) || t.matter.toLowerCase().includes(search.toLowerCase()))
  );

  const overdueCount = data.tasks.filter(t => t.status !== 'Completed' && t.status !== 'Cancelled' && t.dueDate < '2026-04-20').length;

  // Status distribution
  const statusCounts = ['To Do', 'In Progress', 'Waiting', 'Blocked', 'Scheduled', 'Completed'].map(s => ({
    status: s, count: data.tasks.filter(t => t.status === s).length,
    color: au.statusColor(s).color, bg: au.statusColor(s).bg,
  })).filter(s => s.count > 0);
  const statusTotal = statusCounts.reduce((s, x) => s + x.count, 0);

  // Priority breakdown
  const priorityCounts = ['P0', 'P1', 'P2', 'P3'].map(p => ({
    priority: p, count: data.tasks.filter(t => t.priority === p).length,
    color: au.priorityColor(p).color, bg: au.priorityColor(p).bg,
  }));
  const maxPriority = Math.max(...priorityCounts.map(p => p.count), 1);

  // Load by assignee — from analytics (richer than 20-row sample)
  const assigneeLoad = [...data.analytics.tasksByAssignee].sort((a, b) => b.open - a.open);
  const maxLoad = Math.max(...assigneeLoad.map(a => a.open));

  // Aging buckets — days since creation for OPEN tasks
  const today = new Date('2026-04-20');
  const openTasks = data.tasks.filter(t => t.status !== 'Completed' && t.status !== 'Cancelled');
  const ageOf = (t) => Math.floor((today - new Date(t.created)) / 86400000);
  const buckets = [
    { label: '0–3 days',  min: 0,  max: 3,    color: au.emerald },
    { label: '4–7 days',  min: 4,  max: 7,    color: au.lime },
    { label: '8–14 days', min: 8,  max: 14,   color: au.amber },
    { label: '15–30 days',min: 15, max: 30,   color: au.orange },
    { label: '30+ days',  min: 31, max: 9999, color: au.crimson },
  ].map(b => ({ ...b, count: openTasks.filter(t => { const a = ageOf(t); return a >= b.min && a <= b.max; }).length }));
  const maxBucket = Math.max(...buckets.map(b => b.count), 1);

  // Hours utilization — sum of est vs spent for open tasks
  const totalEst = openTasks.reduce((s, t) => s + t.estHours, 0);
  const totalSpent = openTasks.reduce((s, t) => s + t.spentHours, 0);
  const utilPct = totalEst > 0 ? Math.round((totalSpent / totalEst) * 100) : 0;

  // Top workflows by task volume
  const wfTaskCounts = {};
  data.tasks.forEach(t => { if (t.workflow) wfTaskCounts[t.workflow] = (wfTaskCounts[t.workflow] || 0) + 1; });
  const topWorkflows = Object.entries(wfTaskCounts).sort((a, b) => b[1] - a[1]).slice(0, 6);
  const maxWfCount = Math.max(...topWorkflows.map(w => w[1]), 1);

  return (
    <div>
      <AuHero
        accent={au.cobalt} bg={au.cobaltBg}
        title={`Tasks dashboard — ${data.tasks.length} tracked`}
        description={<>
          Workflow-driven tasks across all matters. Filter by status, priority, assignee. <b style={{ color: au.crimson, fontFamily: Taud.font.mono }}>{overdueCount}</b> overdue · <b style={{ fontFamily: Taud.font.mono }}>{utilPct}%</b> of estimated hours consumed.
        </>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={au.stat}><span style={au.statLabel}>Shown</span><span style={au.statValue}>{filtered.length}</span><span style={{ ...au.statDelta, color: Taud.color.text.tertiary }}>of {data.tasks.length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>In progress</span><span style={{ ...au.statValue, color: au.cobalt }}>{data.tasks.filter(t => t.status === 'In Progress').length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Waiting</span><span style={{ ...au.statValue, color: au.amber }}>{data.tasks.filter(t => t.status === 'Waiting').length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Blocked</span><span style={{ ...au.statValue, color: au.crimson }}>{data.tasks.filter(t => t.status === 'Blocked').length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Overdue</span><span style={{ ...au.statValue, color: au.crimson }}>{overdueCount}</span><span style={{ ...au.statDelta, color: Taud.color.text.tertiary }}>past due date</span></div>
      </div>

      {/* Row 1: Status stacked bar + Priority histogram */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: '14px', marginBottom: '14px' }}>
        <div style={au.card}>
          <div style={au.cardH}>Status distribution</div>
          <div style={{ padding: '16px' }}>
            <div style={{ display: 'flex', height: '14px', borderRadius: '4px', overflow: 'hidden', marginBottom: '12px' }}>
              {statusCounts.map(s => (
                <div key={s.status} title={`${s.status}: ${s.count}`} style={{ width: `${(s.count / statusTotal) * 100}%`, background: s.color }} />
              ))}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '6px' }}>
              {statusCounts.map(s => (
                <div key={s.status} style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                  <span style={{ width: '10px', height: '10px', borderRadius: '2px', background: s.color }} />
                  <span style={{ fontSize: '11px', color: Taud.color.text.primary, fontWeight: 500 }}>{s.status}</span>
                  <span style={{ fontSize: '11px', color: Taud.color.text.tertiary, fontFamily: Taud.font.mono, marginLeft: 'auto' }}>{s.count}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div style={au.card}>
          <div style={au.cardH}>By priority</div>
          <div style={{ padding: '14px 16px', display: 'flex', gap: '10px', alignItems: 'flex-end', height: '150px' }}>
            {priorityCounts.map(p => (
              <div key={p.priority} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '6px' }}>
                <span style={{ fontSize: '13px', fontWeight: 700, color: p.color, fontFamily: Taud.font.mono }}>{p.count}</span>
                <div style={{ width: '100%', height: `${(p.count / maxPriority) * 90}px`, background: p.color, borderRadius: '4px 4px 0 0', minHeight: '4px' }} />
                <span style={{ fontSize: '10px', fontWeight: 700, color: p.color, fontFamily: Taud.font.mono, letterSpacing: '0.04em' }}>{p.priority}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Row 2: Assignee load + Aging buckets */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: '14px', marginBottom: '14px' }}>
        <div style={au.card}>
          <div style={au.cardH}>
            <span>Load by assignee — open tasks</span>
            <span style={{ fontSize: '10px', color: Taud.color.text.tertiary, fontWeight: 500 }}>overdue highlighted</span>
          </div>
          <div style={{ padding: '14px 16px' }}>
            {assigneeLoad.map(a => {
              const loadColor = a.open > 20 ? au.crimson : a.open > 14 ? au.amber : au.lime;
              return (
                <div key={a.name} style={{ marginBottom: '10px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
                    <span style={{ fontSize: '11px', fontWeight: 600, color: Taud.color.text.primary }}>{a.name}</span>
                    <span style={{ fontSize: '11px', fontFamily: Taud.font.mono, color: Taud.color.text.tertiary }}>
                      <span style={{ color: loadColor, fontWeight: 700 }}>{a.open} open</span>
                      {a.overdue > 0 && <span style={{ color: au.crimson, fontWeight: 700 }}> · {a.overdue} overdue</span>}
                      <span> · {a.avgCloseHrs}h avg close</span>
                    </span>
                  </div>
                  <div style={{ height: '6px', background: Taud.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                    <div style={{ width: `${(a.open / maxLoad) * 100}%`, height: '100%', background: loadColor }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <div style={au.card}>
          <div style={au.cardH}>Aging · open tasks</div>
          <div style={{ padding: '14px 16px' }}>
            {buckets.map(b => (
              <div key={b.label} style={{ marginBottom: '10px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
                  <span style={{ fontSize: '11px', fontWeight: 600, color: Taud.color.text.primary }}>{b.label}</span>
                  <span style={{ fontSize: '11px', fontFamily: Taud.font.mono, color: b.color, fontWeight: 700 }}>{b.count}</span>
                </div>
                <div style={{ height: '8px', background: Taud.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                  <div style={{ width: `${(b.count / maxBucket) * 100}%`, height: '100%', background: b.color }} />
                </div>
              </div>
            ))}
            <div style={{ marginTop: '14px', padding: '8px', background: Taud.color.bg.secondary, borderRadius: '5px', fontSize: '10px', color: Taud.color.text.tertiary, textAlign: 'center' }}>
              <span style={{ fontWeight: 700, color: au.cobalt }}>{openTasks.length}</span> open · avg age <span style={{ fontWeight: 700, color: Taud.color.text.primary }}>{openTasks.length > 0 ? Math.round(openTasks.reduce((s, t) => s + ageOf(t), 0) / openTasks.length) : 0}d</span>
            </div>
          </div>
        </div>
      </div>

      {/* Row 3: Top workflows + Hours utilization */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: '14px', marginBottom: '14px' }}>
        <div style={au.card}>
          <div style={au.cardH}>Task volume by workflow — top 6</div>
          <div style={{ padding: '14px 16px' }}>
            {topWorkflows.map(([wf, count]) => (
              <div key={wf} style={{ marginBottom: '9px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
                  <span style={{ fontSize: '11px', fontWeight: 600, color: Taud.color.text.primary, fontFamily: Taud.font.mono }}>{wf}</span>
                  <span style={{ fontSize: '11px', fontFamily: Taud.font.mono, color: au.lime, fontWeight: 700 }}>{count}</span>
                </div>
                <div style={{ height: '6px', background: Taud.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                  <div style={{ width: `${(count / maxWfCount) * 100}%`, height: '100%', background: `linear-gradient(90deg, ${au.limeLight} 0%, ${au.lime} 100%)` }} />
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={au.card}>
          <div style={au.cardH}>Hours utilization · open tasks</div>
          <div style={{ padding: '18px 16px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
              <div>
                <div style={{ fontSize: '10px', color: Taud.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Spent</div>
                <div style={{ fontSize: '20px', fontWeight: 700, color: au.cobalt, fontFamily: Taud.font.mono }}>{totalSpent}h</div>
              </div>
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '10px', color: Taud.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Utilization</div>
                <div style={{ fontSize: '20px', fontWeight: 700, color: utilPct >= 90 ? au.crimson : utilPct >= 70 ? au.amber : au.emerald, fontFamily: Taud.font.mono }}>{utilPct}%</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: '10px', color: Taud.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Estimated</div>
                <div style={{ fontSize: '20px', fontWeight: 700, color: Taud.color.text.primary, fontFamily: Taud.font.mono }}>{totalEst}h</div>
              </div>
            </div>
            <div style={{ height: '14px', background: Taud.color.border.light, borderRadius: '7px', overflow: 'hidden', position: 'relative' }}>
              <div style={{ width: `${Math.min(utilPct, 100)}%`, height: '100%', background: `linear-gradient(90deg, ${au.emerald} 0%, ${au.lime} 60%, ${au.amber} 90%, ${au.crimson} 100%)` }} />
            </div>
            <div style={{ marginTop: '10px', fontSize: '10px', color: Taud.color.text.tertiary, textAlign: 'center' }}>
              {totalEst - totalSpent > 0 ? `${totalEst - totalSpent}h remaining on estimate` : `${totalSpent - totalEst}h over budget`} · across {openTasks.length} open tasks
            </div>
          </div>
        </div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>Task backlog — {filtered.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search title / matter…"
              style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Taud.color.border.light}`, borderRadius: '5px', background: Taud.color.bg.card, color: Taud.color.text.primary, minWidth: '220px', fontFamily: Taud.font.family }} />
            <select value={statusFilter} onChange={e => setStatusFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Taud.color.border.light}`, borderRadius: '5px', background: Taud.color.bg.card, color: Taud.color.text.secondary }}>
              {statuses.map(s => <option key={s} value={s}>Status: {s}</option>)}
            </select>
            <select value={priorityFilter} onChange={e => setPriorityFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Taud.color.border.light}`, borderRadius: '5px', background: Taud.color.bg.card, color: Taud.color.text.secondary }}>
              {priorities.map(p => <option key={p} value={p}>Priority: {p}</option>)}
            </select>
            <select value={assigneeFilter} onChange={e => setAssigneeFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Taud.color.border.light}`, borderRadius: '5px', background: Taud.color.bg.card, color: Taud.color.text.secondary }}>
              {assignees.map(a => <option key={a} value={a}>Assignee: {a}</option>)}
            </select>
            <button style={au.btnPrimary}>+ New task</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={au.th}>ID</th>
              <th style={au.th}>Title</th>
              <th style={au.th}>Matter</th>
              <th style={au.th}>Assignee</th>
              <th style={au.th}>Priority</th>
              <th style={au.th}>Status</th>
              <th style={au.th}>Due</th>
              <th style={au.th}>Workflow</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Hrs</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(t => {
              const ss = au.statusColor(t.status);
              const pc = au.priorityColor(t.priority);
              const overdue = t.dueDate < '2026-04-20' && t.status !== 'Completed' && t.status !== 'Cancelled';
              return (
                <tr key={t.id}>
                  <td style={{ ...au.td, fontFamily: Taud.font.mono, color: au.lime, fontWeight: 700 }}>{t.id}</td>
                  <td style={{ ...au.td, fontWeight: 600, color: Taud.color.text.primary, maxWidth: '320px' }}>
                    {t.title}
                    {t.tags && t.tags.length > 0 && (
                      <div style={{ marginTop: '3px', display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
                        {t.tags.slice(0, 3).map(tag => (
                          <span key={tag} style={{ fontSize: '9px', padding: '1px 6px', borderRadius: '8px', background: Taud.color.bg.secondary, color: Taud.color.text.tertiary, fontFamily: Taud.font.mono }}>{tag}</span>
                        ))}
                      </div>
                    )}
                  </td>
                  <td style={{ ...au.td, color: Taud.color.text.secondary, fontSize: '11px', maxWidth: '160px' }}>{t.matter}</td>
                  <td style={{ ...au.td, fontSize: '11px', color: Taud.color.text.secondary }}>{t.assignee}</td>
                  <td style={au.td}><span style={{ ...au.tag, background: pc.bg, color: pc.color }}>{t.priority}</span></td>
                  <td style={au.td}><span style={{ ...au.tag, background: ss.bg, color: ss.color }}>{t.status}</span></td>
                  <td style={{ ...au.td, fontFamily: Taud.font.mono, fontSize: '11px', color: overdue ? au.crimson : Taud.color.text.primary, fontWeight: overdue ? 700 : 400 }}>{t.dueDate}</td>
                  <td style={{ ...au.td, fontSize: '10px', color: Taud.color.text.tertiary, fontFamily: Taud.font.mono, maxWidth: '160px' }}>{t.workflow || '—'}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Taud.font.mono, fontSize: '11px', color: Taud.color.text.secondary }}>{t.spentHours}/{t.estHours}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.AutoDashboard = AutoDashboard;
window.AutoTasks     = AutoTasks;
