/* Reports Hub — landing page for all analytics */

function ReportsHub({ allTasks, onView }) {
  const open      = allTasks.filter(t => t.statusId !== 6 && !t.snoozedUntil).length;
  const overdue   = allTasks.filter(t => t.dueDate && dayDelta(t.dueDate) < 0 && t.statusId !== 6).length;
  const dueToday  = allTasks.filter(t => t.dueDate && dayDelta(t.dueDate) === 0).length;
  const done      = allTasks.filter(t => t.statusId === 6).length;
  const totalEst  = allTasks.reduce((s, t) => s + (t.estimateMins || 0), 0);
  const totalLog  = allTasks.reduce((s, t) => s + (t.actualMins || 0), 0);

  // Sparkline data (last 14 days, deterministic)
  const trend = Array.from({ length: 14 }, (_, i) => ({
    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 cards = [
    {
      key: 'dashboard', title: 'KPIs & trends', glyph: '◐', tint: '#6366F1',
      desc: 'Health of the whole workspace — open, overdue, done, SLA.',
      stat: { n: open, label: 'open' },
      bullets: ['Created vs done trend', 'Active by space + assignee', 'SLA health table'],
    },
    {
      key: 'workload', title: 'Workload', glyph: '⊟', tint: '#10B981',
      desc: 'Who is over-stretched and who has slack this week.',
      stat: { n: fmtMins(totalEst) || '0m', label: 'estimated', isText: true },
      bullets: ['Per-assignee × day grid', 'Estimates aggregated', 'Today highlighted'],
    },
    {
      key: 'time', title: 'Time tracking', glyph: '⏱', tint: '#F59E0B',
      desc: 'Estimate vs actual per clinician for the last 30 days.',
      stat: { n: fmtMins(totalLog) || '0m', label: 'logged', isText: true },
      bullets: ['Variance flags', 'Logged-vs-estimated bars', 'Per-person Δ'],
    },
    {
      key: 'audit', title: 'Audit log', glyph: '⌬', tint: '#8B5CF6',
      desc: 'Append-only record of every change. Filter and export.',
      stat: { n: allTasks.reduce((s, t) => s + (t.activity?.length || 0), 0), label: 'events' },
      bullets: ['Per-user filter', 'CSV export', 'ICO retention proof'],
    },
  ];

  return (
    <div style={{ flex: 1, overflowY: 'auto', background: 'rgb(var(--bg))' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '28px 32px 60px' }}>
        <header style={{ marginBottom: 22 }}>
          <p style={{ margin: 0, fontSize: 12, fontWeight: 600, color: 'rgb(var(--accent))', letterSpacing: '0.04em', textTransform: 'uppercase' }}>Reports</p>
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginTop: 4 }}>
            <div>
              <h1 style={{ margin: 0, fontSize: 28, fontWeight: 700, letterSpacing: '-0.025em' }}>Analytics</h1>
              <p style={{ margin: '6px 0 0', fontSize: 13.5, color: 'rgb(var(--muted))', maxWidth: 600 }}>
                Health, workload, time, and audit — everything you need to run the practice. Pick a report to drill in.
              </p>
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => onView('dashboards')} className="btn btn-secondary" style={{ fontSize: 12.5 }}>◇ Custom dashboards</button>
              <button className="btn btn-accent" style={{ fontSize: 12.5 }}>⇩ Export PDF</button>
            </div>
          </div>
        </header>

        {/* Snapshot strip */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 12, marginBottom: 24 }}>
          <Kpi label="Open"      n={open}                       c="rgb(var(--accent))"  soft="rgb(var(--accent-soft))" />
          <Kpi label="Due today" n={dueToday}                   c="rgb(var(--warm))"    soft="rgb(var(--warm-soft))" />
          <Kpi label="Overdue"   n={overdue}                    c="rgb(var(--brick))"   soft="rgb(var(--brick-soft))" />
          <Kpi label="Done"      n={done}                       c="rgb(var(--forest))"  soft="rgb(var(--forest-soft))" />
          <Kpi label="Estimated" n={fmtMins(totalEst) || '0m'}  c="rgb(var(--navy))"    soft="rgb(var(--navy-soft))" isText />
          <Kpi label="Logged"    n={fmtMins(totalLog) || '0m'}  c="rgb(var(--berry))"   soft="rgb(var(--berry-soft))" isText />
        </div>

        {/* Report cards */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14, marginBottom: 28 }}>
          {cards.map(card => (
            <button key={card.key} onClick={() => onView(card.key)} style={{
              textAlign: 'left', padding: 22,
              background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))',
              borderRadius: 14, boxShadow: 'var(--sh-sm)',
              position: 'relative', overflow: 'hidden',
              transition: 'box-shadow .14s, border-color .14s, transform .06s',
            }}
              onMouseEnter={e => { e.currentTarget.style.boxShadow = 'var(--sh-md)'; e.currentTarget.style.borderColor = card.tint + '60'; }}
              onMouseLeave={e => { e.currentTarget.style.boxShadow = 'var(--sh-sm)'; e.currentTarget.style.borderColor = 'rgb(var(--rule))'; }}>
              <span style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: card.tint }} />
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, marginBottom: 14 }}>
                <div style={{
                  width: 44, height: 44, borderRadius: 12,
                  background: card.tint + '14', color: card.tint,
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 18, fontWeight: 700,
                }}>{card.glyph}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <h3 style={{ margin: 0, fontSize: 17, fontWeight: 700, letterSpacing: '-0.015em' }}>{card.title}</h3>
                  <p style={{ margin: '4px 0 0', fontSize: 12.5, color: 'rgb(var(--muted))', lineHeight: 1.5 }}>{card.desc}</p>
                </div>
                <div style={{ textAlign: 'right', flexShrink: 0 }}>
                  <div className="num" style={{ fontSize: card.stat.isText ? 18 : 26, fontWeight: 700, color: card.tint, letterSpacing: '-0.025em', lineHeight: 1 }}>{card.stat.n}</div>
                  <div style={{ fontSize: 10, fontWeight: 600, color: 'rgb(var(--muted))', marginTop: 4, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{card.stat.label}</div>
                </div>
              </div>
              <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {card.bullets.map(b => (
                  <li key={b} style={{
                    fontSize: 11, color: card.tint, fontWeight: 500,
                    padding: '3px 9px', background: card.tint + '0e', borderRadius: 999,
                  }}>{b}</li>
                ))}
              </ul>
              <div style={{ marginTop: 14, fontSize: 12, fontWeight: 600, color: card.tint, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                Open report <span>→</span>
              </div>
            </button>
          ))}
        </div>

        {/* Recent activity trend mini-chart */}
        <section style={{
          background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))',
          borderRadius: 14, padding: 20, boxShadow: 'var(--sh-sm)', marginBottom: 24,
        }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 14 }}>
            <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700 }}>Two-week trend</h3>
            <span style={{ fontSize: 12, color: 'rgb(var(--muted))' }}>Created vs done</span>
            <span style={{ flex: 1 }} />
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'rgb(var(--muted))' }}>
              <span style={{ width: 8, height: 8, background: 'rgb(var(--accent))', borderRadius: 2 }} /> Created
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'rgb(var(--muted))' }}>
              <span style={{ width: 8, height: 8, background: 'rgb(var(--forest))', borderRadius: 2 }} /> Done
            </span>
          </div>
          <svg viewBox="0 0 700 100" preserveAspectRatio="none" style={{ width: '100%', height: 90, display: 'block' }}>
            {trend.map((d, i) => {
              const x = i * 50;
              const max = 12;
              const hC = (d.created / max) * 80;
              const hX = (d.closed / max) * 80;
              return (
                <g key={i}>
                  <rect x={x + 4} y={90 - hC} width={20} height={hC} fill="rgb(99,102,241)" rx="3" />
                  <rect x={x + 26} y={90 - hX} width={20} height={hX} fill="rgb(16,185,129)" rx="3" />
                </g>
              );
            })}
          </svg>
        </section>

        {/* Per-space mini table */}
        <section style={{
          background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))',
          borderRadius: 14, padding: 20, boxShadow: 'var(--sh-sm)',
        }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 14 }}>
            <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700 }}>Per-space snapshot</h3>
            <span style={{ flex: 1 }} />
            <button onClick={() => onView('dashboard')} className="btn-ghost" style={{ fontSize: 11.5 }}>Full breakdown →</button>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ borderBottom: '1px solid rgb(var(--rule))' }}>
                <th style={th2}>Space</th>
                <th style={{ ...th2, textAlign: 'right' }}>Open</th>
                <th style={{ ...th2, textAlign: 'right' }}>Overdue</th>
                <th style={{ ...th2, textAlign: 'right' }}>Done</th>
                <th style={{ ...th2, textAlign: 'right', width: 160 }}>Health</th>
              </tr>
            </thead>
            <tbody>
              {D.spaces.map(s => {
                const tasks = allTasks.filter(t => t.spaceId === s.id);
                const op = tasks.filter(t => t.statusId !== 6).length;
                const od = tasks.filter(t => t.statusId !== 6 && t.dueDate && dayDelta(t.dueDate) < 0).length;
                const dn = tasks.filter(t => t.statusId === 6).length;
                const health = op ? Math.round(((op - od) / op) * 100) : 100;
                const healthC = health >= 90 ? 'rgb(var(--forest))' : health >= 70 ? 'rgb(var(--warm))' : 'rgb(var(--brick))';
                return (
                  <tr key={s.id} style={{ borderBottom: '1px solid rgb(var(--rule) / 0.6)' }}>
                    <td style={td2}>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                        <span style={{ width: 8, height: 8, background: s.colour, borderRadius: 2 }} />
                        <span style={{ fontWeight: 600 }}>{s.name}</span>
                        <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: 'rgb(var(--muted))' }}>{s.prefix}</span>
                      </span>
                    </td>
                    <td style={{ ...td2, textAlign: 'right' }}><span className="num" style={{ fontWeight: 600 }}>{op}</span></td>
                    <td style={{ ...td2, textAlign: 'right' }}><span className="num" style={{ color: od > 0 ? 'rgb(var(--brick))' : 'rgb(var(--muted))', fontWeight: od > 0 ? 700 : 500 }}>{od}</span></td>
                    <td style={{ ...td2, textAlign: 'right' }}><span className="num" style={{ color: 'rgb(var(--forest))', fontWeight: 600 }}>{dn}</span></td>
                    <td style={{ ...td2, textAlign: 'right' }}>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, justifyContent: 'flex-end' }}>
                        <span style={{ width: 80, height: 5, background: 'rgb(var(--paper-2))', borderRadius: 999, overflow: 'hidden' }}>
                          <span style={{ display: 'block', width: `${health}%`, height: '100%', background: healthC, borderRadius: 999 }} />
                        </span>
                        <span className="num" style={{ minWidth: 36, fontSize: 12, fontWeight: 700, color: healthC }}>{health}%</span>
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </section>
      </div>
    </div>
  );
}

function Kpi({ label, n, c, soft, isText }) {
  return (
    <div style={{
      padding: '14px 16px',
      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: 22, height: 3, background: c }} />
      <p style={{ margin: 0, fontSize: 10.5, fontWeight: 600, color: 'rgb(var(--muted))', letterSpacing: '0.04em', textTransform: 'uppercase' }}>{label}</p>
      <p className="num" style={{ margin: '4px 0 0', fontSize: isText ? 19 : 25, fontWeight: 700, color: c, letterSpacing: '-0.025em', lineHeight: 1 }}>{n}</p>
    </div>
  );
}

const th2 = { textAlign: 'left', padding: '8px 12px 8px 0', fontSize: 10.5, fontWeight: 700, color: 'rgb(var(--muted))', letterSpacing: '0.04em', textTransform: 'uppercase' };
const td2 = { padding: '12px 12px 12px 0', verticalAlign: 'middle' };

window.ReportsHub = ReportsHub;
