/* Reports — Dashboard, Workload, Time, Audit log */

function ReportsView({ which }) {
  if (which === 'dashboard') return <DashboardReport />;
  if (which === 'workload')  return <WorkloadReport />;
  if (which === 'time')      return <TimeReport />;
  if (which === 'audit')     return <AuditReport />;
  return null;
}

function DashboardReport() {
  const t = D.tasks;
  const open      = t.filter(x => x.statusId !== 6 && !x.snoozedUntil).length;
  const overdue   = t.filter(x => x.dueDate && dayDelta(x.dueDate) < 0 && x.statusId !== 6).length;
  const dueToday  = t.filter(x => x.dueDate && dayDelta(x.dueDate) === 0).length;
  const unsched   = t.filter(x => !x.dueDate && x.statusId !== 6).length;
  const snoozed   = t.filter(x => x.snoozedUntil).length;
  const archived  = t.filter(x => x.statusId === 6).length;

  const trend = Array.from({ length: 14 }, (_, i) => {
    const d = new Date(TODAY); d.setDate(d.getDate() - (13 - i));
    return {
      iso: d.toISOString().slice(0, 10),
      label: d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' }),
      created: 2 + Math.floor(Math.abs(Math.sin(i * 1.6)) * 7),
      closed:  1 + Math.floor(Math.abs(Math.cos(i * 1.1)) * 5),
    };
  });

  const bySpace = D.spaces.map(s => ({
    name: s.name, colour: s.colour,
    count: t.filter(x => x.spaceId === s.id && x.statusId !== 6).length,
  })).sort((a, b) => b.count - a.count);

  const byAssignee = D.users.map(u => ({
    name: u.name, colour: u.colour,
    count: t.filter(x => x.assignees.includes(u.id) && x.statusId !== 6).length,
  })).filter(r => r.count > 0).sort((a, b) => b.count - a.count);

  return (
    <div style={{ flex: 1, overflowY: 'auto', background: 'rgb(var(--bg))' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '32px 32px 60px' }}>

        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 8 }}>
          <div>
            <p style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', color: 'rgb(var(--accent))', marginBottom: 6, textTransform: 'uppercase' }}>Reports</p>
            <h1 style={{ margin: 0, fontSize: 32, fontWeight: 700, letterSpacing: '-0.03em' }}>Dashboard</h1>
          </div>
          <div style={{ display: 'inline-flex', gap: 2, padding: 3, background: 'rgb(var(--paper-2))', borderRadius: 10 }}>
            {['7d','30d','90d','12m'].map((r, i) => (
              <button key={r} style={{
                padding: '5px 14px', fontSize: 12.5, fontWeight: 600,
                background: i === 1 ? 'rgb(var(--surface))' : 'transparent',
                color: i === 1 ? 'rgb(var(--ink))' : 'rgb(var(--muted))',
                borderRadius: 7,
                boxShadow: i === 1 ? 'var(--sh-sm)' : 'none',
              }}>{r}</button>
            ))}
          </div>
        </div>

        <p style={{ color: 'rgb(var(--muted))', fontSize: 13.5, maxWidth: 580, marginTop: 0, marginBottom: 24 }}>
          Operational health for the clinical team. Numbers refresh every 5 minutes.
          Last updated <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 12 }}>{TODAY.toLocaleString('en-GB', { weekday: 'short', day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' })}</span>.
        </p>

        {/* KPIs as cards */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 12, marginBottom: 24 }}>
          {[
            ['Open',        open,     'rgb(var(--accent))',  'rgb(var(--accent-soft))'],
            ['Overdue',     overdue,  'rgb(var(--brick))',   'rgb(var(--brick-soft))'],
            ['Due today',   dueToday, 'rgb(var(--warm))',    'rgb(var(--warm-soft))'],
            ['Unscheduled', unsched,  'rgb(var(--muted))',   'rgb(var(--paper-2))'],
            ['Snoozed',     snoozed,  'rgb(100 116 139)',    'rgb(var(--paper-2))'],
            ['Done',        archived, 'rgb(var(--forest))',  'rgb(var(--forest-soft))'],
          ].map(([lbl, n, c, soft]) => (
            <div key={lbl} style={{
              padding: '18px 18px',
              background: 'rgb(var(--surface))',
              border: '1px solid rgb(var(--rule))',
              borderRadius: 12,
              boxShadow: 'var(--sh-sm)',
              position: 'relative',
              overflow: 'hidden',
            }}>
              <span style={{ position: 'absolute', top: 0, left: 0, width: 24, height: 3, background: c, borderRadius: '0 0 4px 0' }} />
              <p style={{ margin: 0, fontSize: 12, fontWeight: 600, color: 'rgb(var(--muted))' }}>{lbl}</p>
              <p className="num" style={{ margin: '6px 0 0', fontSize: 32, fontWeight: 700, letterSpacing: '-0.03em', color: c, lineHeight: 1 }}>{n}</p>
            </div>
          ))}
        </div>

        {/* Trend */}
        <div style={{ background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))', padding: 20, marginBottom: 24, borderRadius: 12, boxShadow: 'var(--sh-sm)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 16 }}>
            <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700, letterSpacing: '-0.01em' }}>Created vs done</h3>
            <span style={{ fontSize: 12, color: 'rgb(var(--muted))' }}>last 14 days</span>
            <span style={{ flex: 1 }} />
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'rgb(var(--muted))' }}>
              <span style={{ width: 10, height: 10, background: 'rgb(var(--accent))', borderRadius: 3 }} /> Created
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'rgb(var(--muted))' }}>
              <span style={{ width: 10, height: 10, background: 'rgb(var(--forest))', borderRadius: 3 }} /> Done
            </span>
          </div>
          <TrendChart data={trend} />
        </div>

        {/* Two columns */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 24 }}>

          <div style={{ background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))', padding: 20, borderRadius: 12, boxShadow: 'var(--sh-sm)' }}>
            <h3 style={{ margin: '0 0 16px', fontSize: 15, fontWeight: 700 }}>Active by space</h3>
            <BarRows rows={bySpace} />
          </div>

          <div style={{ background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))', padding: 20, borderRadius: 12, boxShadow: 'var(--sh-sm)' }}>
            <h3 style={{ margin: '0 0 16px', fontSize: 15, fontWeight: 700 }}>Active by assignee</h3>
            <BarRows rows={byAssignee} />
          </div>
        </div>

        {/* SLA / aging */}
        <div style={{ background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))', padding: 20, borderRadius: 12, boxShadow: 'var(--sh-sm)' }}>
          <h3 style={{ margin: '0 0 16px', fontSize: 15, fontWeight: 700 }}>SLA &amp; aging per space</h3>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
            <thead>
              <tr style={{ borderBottom: '1px solid rgb(var(--rule))' }}>
                <th style={th}>Space</th>
                <th style={th}>SLA</th>
                <th style={th}>On time</th>
                <th style={th}>In flight</th>
                <th style={th}>Overdue</th>
                <th style={th}>Avg. cycle</th>
                <th style={{ ...th, textAlign: 'right' }}>Health</th>
              </tr>
            </thead>
            <tbody>
              {D.spaces.map(s => {
                const total = D.tasks.filter(x => x.spaceId === s.id && x.statusId !== 6).length;
                const od = D.tasks.filter(x => x.spaceId === s.id && x.statusId !== 6 && x.dueDate && dayDelta(x.dueDate) < 0).length;
                const health = total ? Math.round(((total - od) / total) * 100) : 100;
                const cycle = ['1.2d','2.4d','5.6d','3.8d','1.9d','7.1d'][s.id - 1] || '—';
                return (
                  <tr key={s.id} style={{ borderBottom: '1px solid rgb(var(--rule) / 0.6)' }}>
                    <td style={td}>
                      <span style={{ display: 'inline-flex', alignItems: 'baseline', gap: 8 }}>
                        <span style={{ width: 6, height: 6, background: s.colour }} />
                        <span style={{ fontWeight: 500 }}>{s.name}</span>
                        <span className="ticket-id">{s.prefix}</span>
                      </span>
                    </td>
                    <td style={td}><span className="ticket-id">{s.sla ? `${s.sla}d` : '—'}</span></td>
                    <td style={td}><span className="num">{total - od}</span></td>
                    <td style={td}><span className="num">{total}</span></td>
                    <td style={td}><span className="num" style={{ color: od > 0 ? 'rgb(var(--brick))' : 'rgb(var(--ink))', fontWeight: od > 0 ? 600 : 400 }}>{od}</span></td>
                    <td style={td}><span className="ticket-id">{cycle}</span></td>
                    <td style={{ ...td, textAlign: 'right' }}>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, justifyContent: 'flex-end' }}>
                        <span style={{ width: 80 }}>
                          <ProgressBar value={health} height={4} colour={health >= 90 ? 'rgb(var(--forest))' : health >= 70 ? 'rgb(var(--warm))' : 'rgb(var(--brick))'} />
                        </span>
                        <span className="num ticket-id" style={{ minWidth: 32, textAlign: 'right' }}>{health}%</span>
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

      </div>
    </div>
  );
}

const th = { textAlign: 'left', padding: '10px 12px 10px 0', fontSize: 10.5, fontWeight: 600, color: 'rgb(var(--muted))', textTransform: 'uppercase', letterSpacing: '0.06em' };
const td = { padding: '12px 12px 12px 0', fontSize: 13, verticalAlign: 'middle' };

function BarRows({ rows }) {
  const max = Math.max(1, ...rows.map(r => r.count));
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {rows.map(r => (
        <div key={r.name} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <span style={{ width: 130, fontSize: 13, color: 'rgb(var(--ink-2))', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: 500 }}>{r.name}</span>
          <div style={{ flex: 1, height: 8, background: 'rgb(var(--paper-2))', position: 'relative', borderRadius: 999 }}>
            <div style={{
              position: 'absolute', left: 0, top: 0, bottom: 0,
              width: `${(r.count / max) * 100}%`,
              background: r.colour || 'rgb(var(--accent))',
              borderRadius: 999,
              transition: 'width .4s ease-out',
            }} />
          </div>
          <span className="num" style={{ width: 30, textAlign: 'right', fontSize: 12, fontWeight: 600, color: 'rgb(var(--ink))' }}>{r.count}</span>
        </div>
      ))}
    </div>
  );
}

function TrendChart({ data }) {
  const max = Math.max(1, ...data.flatMap(d => [d.created, d.closed]));
  return (
    <div>
      <svg viewBox="0 0 1000 200" preserveAspectRatio="none" style={{ width: '100%', height: 190, display: 'block', overflow: 'visible' }}>
        {/* gridlines */}
        {[0, 0.25, 0.5, 0.75, 1].map(p => (
          <line key={p} x1="0" x2="1000" y1={20 + p * 160} y2={20 + p * 160} stroke="rgb(226,232,240)" strokeWidth="1" strokeDasharray={p === 0 || p === 1 ? '0' : '2 6'} />
        ))}
        {data.map((d, i) => {
          const x = i * (1000 / data.length);
          const hC = (160 * d.created) / max;
          const hX = (160 * d.closed)  / max;
          const w = (1000 / data.length) * 0.34;
          return (
            <g key={i}>
              <rect x={x + (1000 / data.length) * 0.16} y={180 - hC} width={w} height={hC} fill="rgb(99,102,241)" rx="3" />
              <rect x={x + (1000 / data.length) * 0.52} y={180 - hX} width={w} height={hX} fill="rgb(16,185,129)" rx="3" />
            </g>
          );
        })}
      </svg>
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${data.length}, 1fr)`, fontSize: 10.5, color: 'rgb(var(--muted))', fontFamily: 'JetBrains Mono, monospace', marginTop: 4 }}>
        {data.map((d, i) => (
          <span key={d.iso} style={{ textAlign: 'center', visibility: i % 2 === 0 ? 'visible' : 'hidden' }}>{d.label}</span>
        ))}
      </div>
    </div>
  );
}

function WorkloadReport() {
  const start = new Date(TODAY); start.setDate(start.getDate() - ((start.getDay() + 6) % 7));
  const days = Array.from({ length: 7 }, (_, i) => {
    const d = new Date(start); d.setDate(start.getDate() + i);
    return d;
  });

  const rows = D.users.map(u => {
    const cells = days.map(d => {
      const iso = d.toISOString().slice(0, 10);
      return D.tasks.filter(t => t.assignees.includes(u.id) && t.dueDate === iso);
    });
    const totalMins = cells.flat().reduce((s, t) => s + (t.estimateMins || 0), 0);
    return { u, cells, totalMins };
  });

  return (
    <div style={{ flex: 1, overflowY: 'auto', background: 'rgb(var(--bg))' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '32px 32px 60px' }}>
        <p style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', color: 'rgb(var(--accent))', marginBottom: 6, textTransform: 'uppercase' }}>Reports</p>
        <h1 style={{ margin: 0, fontSize: 32, fontWeight: 700, letterSpacing: '-0.03em' }}>Workload</h1>
        <p style={{ color: 'rgb(var(--muted))', fontSize: 13.5, marginTop: 8, marginBottom: 24 }}>
          Dated tasks for w/c <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 12 }}>{start.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })}</span>, grouped by assignee. Estimates aggregated.
        </p>

        <div style={{ background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))', borderRadius: 12, overflow: 'hidden', boxShadow: 'var(--sh-sm)' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
            <thead>
              <tr style={{ borderBottom: '1px solid rgb(var(--rule))', background: 'rgb(var(--bg))' }}>
                <th style={{ ...th, padding: '12px 16px', width: 200 }}>Assignee</th>
                {days.map(d => {
                  const isToday = d.toDateString() === TODAY.toDateString();
                  return (
                    <th key={d.toISOString()} style={{
                      ...th, padding: '12px 10px',
                      background: isToday ? 'rgb(var(--accent-soft) / 0.7)' : 'transparent',
                      color: isToday ? 'rgb(var(--accent-2))' : 'rgb(var(--muted))',
                      borderLeft: '1px solid rgb(var(--rule))',
                    }}>
                      <span style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                        <span style={{ fontSize: 10 }}>{d.toLocaleDateString('en-GB', { weekday: 'short' })}</span>
                        <span style={{ fontSize: 15, fontWeight: 700, letterSpacing: '-0.01em' }}>{d.getDate()}</span>
                      </span>
                    </th>
                  );
                })}
                <th style={{ ...th, padding: '12px 16px', textAlign: 'right', borderLeft: '1px solid rgb(var(--rule))' }}>Total est</th>
              </tr>
            </thead>
            <tbody>
              {rows.map(({ u, cells, totalMins }) => (
                <tr key={u.id} style={{ borderBottom: '1px solid rgb(var(--rule) / 0.6)' }}>
                  <td style={{ padding: '14px 16px', verticalAlign: 'top' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <Avatar user={u} size={28} />
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 600 }}>{u.name}</div>
                        <div style={{ fontSize: 11, color: 'rgb(var(--muted))' }}>{u.role}</div>
                      </div>
                    </div>
                  </td>
                  {cells.map((cellTasks, i) => (
                    <td key={i} style={{ padding: '10px 8px', verticalAlign: 'top', borderLeft: '1px solid rgb(var(--rule))', minWidth: 110 }}>
                      {cellTasks.length === 0 && <span style={{ color: 'rgb(var(--rule-2))', fontSize: 11 }}>—</span>}
                      {cellTasks.map(t => {
                        const st = statusById(t.statusId);
                        return (
                          <div key={t.id} style={{
                            padding: '5px 8px', marginBottom: 5,
                            background: st.colour + '12',
                            borderRadius: 6,
                            fontSize: 11.5, lineHeight: 1.35,
                          }}>
                            <div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: 500 }}>{t.title}</div>
                            {t.estimateMins > 0 && <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'rgb(var(--muted))', marginTop: 1 }}>{fmtMins(t.estimateMins)}</div>}
                          </div>
                        );
                      })}
                    </td>
                  ))}
                  <td style={{ padding: '14px 16px', textAlign: 'right', borderLeft: '1px solid rgb(var(--rule))', verticalAlign: 'top' }}>
                    <span className="num" style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 12.5, fontWeight: 600 }}>{fmtMins(totalMins) || '—'}</span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function TimeReport() {
  const userRows = D.users.map(u => {
    const mins = D.tasks.filter(t => t.assignees.includes(u.id)).reduce((s, t) => s + (t.actualMins || 0), 0);
    const est  = D.tasks.filter(t => t.assignees.includes(u.id)).reduce((s, t) => s + (t.estimateMins || 0), 0);
    return { name: u.name, colour: u.colour, mins, est, role: u.role, user: u };
  }).filter(r => r.mins + r.est > 0).sort((a, b) => b.mins - a.mins);

  return (
    <div style={{ flex: 1, overflowY: 'auto', background: 'rgb(var(--bg))' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '32px 32px 60px' }}>
        <p style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', color: 'rgb(var(--accent))', marginBottom: 6, textTransform: 'uppercase' }}>Reports</p>
        <h1 style={{ margin: 0, fontSize: 32, fontWeight: 700, letterSpacing: '-0.03em' }}>Time report</h1>
        <p style={{ color: 'rgb(var(--muted))', fontSize: 13.5, marginTop: 8, marginBottom: 24 }}>
          Estimate vs. actual per clinician for the last 30 days.
        </p>

        <div style={{ background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))', borderRadius: 12, boxShadow: 'var(--sh-sm)', overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
            <thead>
              <tr style={{ borderBottom: '1px solid rgb(var(--rule))', background: 'rgb(var(--bg))' }}>
                <th style={{ ...th, padding: '12px 18px' }}>Clinician</th>
                <th style={{ ...th, padding: '12px 18px', textAlign: 'right' }}>Estimated</th>
                <th style={{ ...th, padding: '12px 18px', textAlign: 'right' }}>Logged</th>
                <th style={{ ...th, padding: '12px 18px', textAlign: 'right', width: 280 }}>Estimate vs actual</th>
                <th style={{ ...th, padding: '12px 18px', textAlign: 'right' }}>Δ</th>
              </tr>
            </thead>
            <tbody>
              {userRows.map(r => {
                const max = Math.max(r.mins, r.est, 1);
                const pctMins = (r.mins / max) * 100;
                const pctEst  = (r.est / max) * 100;
                const delta = r.mins - r.est;
                return (
                  <tr key={r.name} style={{ borderBottom: '1px solid rgb(var(--rule) / 0.6)' }}>
                    <td style={{ padding: '14px 18px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <Avatar user={r.user} size={26} />
                        <div>
                          <div style={{ fontSize: 13, fontWeight: 600 }}>{r.name}</div>
                          <div style={{ fontSize: 11, color: 'rgb(var(--muted))' }}>{r.role}</div>
                        </div>
                      </div>
                    </td>
                    <td style={{ padding: '14px 18px', textAlign: 'right' }}>
                      <span className="num" style={{ fontSize: 12.5, color: 'rgb(var(--muted))', fontFamily: 'JetBrains Mono, monospace' }}>{fmtMins(r.est) || '—'}</span>
                    </td>
                    <td style={{ padding: '14px 18px', textAlign: 'right' }}>
                      <span className="num" style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 13, fontWeight: 700, color: 'rgb(var(--ink))' }}>{fmtMins(r.mins) || '—'}</span>
                    </td>
                    <td style={{ padding: '14px 18px' }}>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          <span style={{ width: 30, fontSize: 10, fontWeight: 600, color: 'rgb(var(--muted))' }}>EST</span>
                          <div style={{ flex: 1, height: 6, background: 'rgb(var(--paper-2))', borderRadius: 999 }}>
                            <div style={{ width: `${pctEst}%`, height: '100%', background: 'rgb(var(--rule-2))', borderRadius: 999 }} />
                          </div>
                        </div>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          <span style={{ width: 30, fontSize: 10, fontWeight: 600, color: 'rgb(var(--muted))' }}>LOG</span>
                          <div style={{ flex: 1, height: 6, background: 'rgb(var(--paper-2))', borderRadius: 999 }}>
                            <div style={{ width: `${pctMins}%`, height: '100%', background: 'rgb(var(--accent))', borderRadius: 999 }} />
                          </div>
                        </div>
                      </div>
                    </td>
                    <td style={{ padding: '14px 18px', textAlign: 'right' }}>
                      <span style={{
                        fontSize: 11.5, fontWeight: 600, fontFamily: 'JetBrains Mono, monospace',
                        padding: '3px 9px', borderRadius: 999,
                        color: delta > 0 ? 'rgb(var(--brick))' : 'rgb(var(--forest))',
                        background: delta > 0 ? 'rgb(var(--brick-soft))' : 'rgb(var(--forest-soft))',
                      }}>
                        {delta > 0 ? '+' : '−'}{fmtMins(Math.abs(delta)) || '0m'}
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function AuditReport() {
  const rows = [];
  D.tasks.forEach(t => {
    (t.activity || []).forEach((a, i) => {
      rows.push({ ...a, task: t, key: `${t.id}-${i}` });
    });
  });

  return (
    <div style={{ flex: 1, overflowY: 'auto', background: 'rgb(var(--bg))' }}>
      <div style={{ maxWidth: 1000, margin: '0 auto', padding: '32px 32px 60px' }}>
        <p style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', color: 'rgb(var(--accent))', marginBottom: 6, textTransform: 'uppercase' }}>Reports</p>
        <h1 style={{ margin: 0, fontSize: 32, fontWeight: 700, letterSpacing: '-0.03em' }}>Audit log</h1>
        <p style={{ color: 'rgb(var(--muted))', fontSize: 13.5, marginTop: 8, marginBottom: 24 }}>
          Append-only record of every change. Filter, search, or export to CSV. Required for ICO retention proofs.
        </p>

        <div style={{ display: 'flex', gap: 8, marginBottom: 18 }}>
          <input placeholder="Search audit events…" style={{ flex: 1, padding: '8px 12px', fontSize: 13 }} />
          <select style={{ fontSize: 12 }}>
            <option>All actions</option><option>Created</option><option>Updated</option><option>Deleted</option>
          </select>
          <select style={{ fontSize: 12 }}>
            <option>All users</option>
            {D.users.map(u => <option key={u.id}>{u.name}</option>)}
          </select>
          <button className="btn btn-secondary" style={{ fontSize: 12 }}>⇩ CSV</button>
        </div>

        <div style={{ background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))', borderRadius: 12, boxShadow: 'var(--sh-sm)', overflow: 'hidden' }}>
          {rows.length === 0 && <p style={{ padding: 30, color: 'rgb(var(--muted))', textAlign: 'center' }}>No events captured.</p>}
          {rows.map((r, i) => {
            const u = userById(r.who);
            return (
              <div key={r.key} style={{
                display: 'grid',
                gridTemplateColumns: '100px 32px 1fr auto',
                gap: 14, alignItems: 'center',
                padding: '12px 18px',
                borderBottom: i === rows.length - 1 ? 'none' : '1px solid rgb(var(--rule) / 0.7)',
              }}>
                <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11.5, color: 'rgb(var(--muted))' }}>{r.at}</span>
                <Avatar user={u} size={28} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13.5 }}>
                    <span style={{ fontWeight: 600 }}>{u?.name}</span>
                    <span style={{ color: 'rgb(var(--muted))' }}> {r.what}</span>
                  </div>
                  <div style={{ marginTop: 2, fontSize: 11.5, color: 'rgb(var(--muted))' }}>
                    <span style={{ fontFamily: 'JetBrains Mono, monospace' }}>{r.task.ticket}</span>
                    {' · '}{r.task.title.slice(0, 80)}{r.task.title.length > 80 ? '…' : ''}
                  </div>
                </div>
                <button style={{ fontSize: 12, color: 'rgb(var(--accent))', fontWeight: 600 }}>Open ›</button>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.ReportsView = ReportsView;
