// Reports page + Report detail sub-page

// ─────────────────────────────────────────────────────────────
//  Reports — main page (one-click generation UI)
// ─────────────────────────────────────────────────────────────
function Reports({ setScreen, setReport }){
  const [filter, setFilter] = useState("all");
  const [search, setSearch] = useState("");

  const recent = REPORTS_RECENT;
  const counts = {
    all:       recent.length,
    personal:  recent.filter(r => r.template === "personal").length,
    executive: recent.filter(r => r.template === "executive").length,
    csv:       recent.filter(r => r.template === "csv").length,
  };
  const filtered = recent
    .filter(r => filter === "all" || r.template === filter)
    .filter(r => !search || r.title.toLowerCase().includes(search.toLowerCase()));

  return (
    <div data-screen-label="04 Reports" style={{ padding:"24px 28px 40px", maxWidth:1380, margin:"0 auto", display:"flex", flexDirection:"column", gap:22 }}>

      {/* ── Page header ───────────────────────────────────────── */}
      <header style={{ display:"flex", alignItems:"flex-end", justifyContent:"space-between", gap:16 }}>
        <div>
          <h1 style={{ margin:0, fontSize:26, fontWeight:600, letterSpacing:-0.5, color:"var(--fg-0)" }}>Reports</h1>
          <div style={{ color:"var(--fg-2)", fontSize:13, marginTop:4 }}>Generate, schedule, and share cost reports</div>
        </div>
      </header>

      {/* ── Template cards 2×2 ────────────────────────────────── */}
      <div style={{ display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:14 }}>
        <ReportTemplateCard
          icon="receipt"
          title="Monthly summary"
          description="Your spend, models, and project mix for the period."
          stats="Used 11 times · avg 180 KB"
          badge="popular"
          cta="Generate"
        />
        <ReportTemplateCard
          icon="user"
          title="Client invoice"
          description="Per-client billable summary, GBP+USD, signed."
          stats="Used 4 times · avg 210 KB"
          cta="Generate"
        />
        <ReportTemplateCard
          icon="chart"
          title="Executive summary"
          description="Cross-workspace P&L, MoM trends, top movers."
          stats="Used 6 times · avg 250 KB"
          cta="Generate"
        />
        <ReportTemplateCard
          icon="sparkles"
          title="Custom builder"
          description="Pick rows, columns, charts, and branding."
          stats="Drag-and-drop · any period"
          cta="Open builder"
        />
      </div>

      {/* ── Two-column lower section ───────────────────────────── */}
      <div style={{ display:"grid", gridTemplateColumns:"minmax(0, 1fr) 300px", gap:18, alignItems:"start" }}>

        {/* Left: Generated reports */}
        <section className="card" style={{ padding:0, overflow:"hidden" }}>
          <div style={{ padding:"16px 20px 14px", borderBottom:"1px solid var(--line-1)", display:"flex", alignItems:"center", justifyContent:"space-between", gap:12, flexWrap:"wrap" }}>
            <h2 style={{ margin:0, fontSize:14, fontWeight:600, color:"var(--fg-0)" }}>Generated reports</h2>
            <div style={{ display:"flex", gap:10, alignItems:"center", flexWrap:"wrap" }}>
              {/* Filter tabs */}
              <div style={{ display:"flex", gap:1, background:"var(--bg-3)", borderRadius:8, padding:3, border:"1px solid var(--line-1)" }}>
                {[
                  { id:"all",       label:"All",       count: counts.all },
                  { id:"personal",  label:"Personal",  count: counts.personal },
                  { id:"executive", label:"Executive", count: counts.executive },
                  { id:"csv",       label:"CSV",       count: counts.csv },
                ].map(tab => (
                  <button
                    key={tab.id}
                    onClick={() => setFilter(tab.id)}
                    style={{
                      appearance:"none", border:"none",
                      height:26, padding:"0 10px",
                      borderRadius:6,
                      fontSize:12, fontWeight: filter === tab.id ? 500 : 400,
                      color: filter === tab.id ? "var(--fg-0)" : "var(--fg-2)",
                      background: filter === tab.id ? "#fff" : "transparent",
                      boxShadow: filter === tab.id ? "0 0 0 1px var(--line-1), var(--sh-1)" : "none",
                      cursor:"pointer",
                      display:"inline-flex", alignItems:"center", gap:5,
                      whiteSpace:"nowrap",
                    }}
                  >
                    {tab.label}
                    <span style={{ fontSize:10.5, color: filter === tab.id ? "var(--fg-3)" : "var(--fg-3)", fontWeight:400 }}>{tab.count}</span>
                  </button>
                ))}
              </div>
              {/* Search */}
              <div style={{ position:"relative" }}>
                <span style={{ position:"absolute", left:9, top:"50%", transform:"translateY(-50%)", pointerEvents:"none" }}>
                  <Icon name="search" size={13} stroke="var(--fg-3)"/>
                </span>
                <input
                  placeholder="Search reports…"
                  value={search}
                  onChange={e => setSearch(e.target.value)}
                  style={{ height:32, padding:"0 10px 0 30px", width:190, border:"1px solid var(--line-2)", borderRadius:8, background:"#fff", fontFamily:"inherit", fontSize:12.5, outline:"none", color:"var(--fg-0)" }}
                />
              </div>
            </div>
          </div>

          <table className="tbl">
            <thead>
              <tr>
                <th style={{ paddingLeft:20 }}>REPORT</th>
                <th>PERIOD</th>
                <th>FORMAT</th>
                <th className="right">SPEND</th>
                <th className="right">DOWNLOADS</th>
                <th>GENERATED</th>
                <th style={{ paddingRight:20, width:72 }}></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(r => (
                <tr key={r.id} className="clickable" onClick={() => { setReport(r.id); setScreen("report-detail"); }}>
                  <td style={{ paddingLeft:20 }}>
                    <div style={{ display:"flex", alignItems:"center", gap:12 }}>
                      <ReportThumb format={r.format}/>
                      <div style={{ display:"flex", flexDirection:"column", gap:1, minWidth:0 }}>
                        <span style={{ color:"var(--fg-0)", fontWeight:500, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{r.title}</span>
                        <span style={{ fontSize:11, color:"var(--fg-3)" }}>{TEMPLATE_LABEL[r.template]} · {r.pages} page{r.pages !== 1 ? "s" : ""}</span>
                      </div>
                    </div>
                  </td>
                  <td className="mono" style={{ fontSize:12, color:"var(--fg-1)" }}>{r.period}</td>
                  <td><ReportFormatBadge fmt={r.format}/></td>
                  <td className="right"><Money value={r.spend} size="sm"/></td>
                  <td className="right mono" style={{ color:"var(--fg-1)", fontSize:12 }}>
                    {r.downloads}
                    {r.shareUrl && <span style={{ marginLeft:6, color:"var(--accent)", fontSize:11 }}>· shared</span>}
                  </td>
                  <td>
                    <div style={{ display:"flex", flexDirection:"column" }}>
                      <span className="mono" style={{ fontSize:12, color:"var(--fg-1)" }}>{r.ago}</span>
                      <span style={{ fontSize:10.5, color:"var(--fg-3)" }}>by {r.by}</span>
                    </div>
                  </td>
                  <td style={{ paddingRight:20 }}>
                    <div style={{ display:"flex", gap:4, justifyContent:"flex-end" }}>
                      <button title="Download"   onClick={e => e.stopPropagation()} style={iconBtnStyle()}><Icon name="download" size={13}/></button>
                      <button title="Share"      onClick={e => e.stopPropagation()} style={iconBtnStyle()}><Icon name="ext" size={13}/></button>
                      <button title="Regenerate" onClick={e => e.stopPropagation()} style={iconBtnStyle()}><Icon name="refresh" size={13}/></button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          {filtered.length === 0 && (
            <div style={{ padding:"48px 24px", textAlign:"center", color:"var(--fg-2)", fontSize:13 }}>
              No reports match those filters.
            </div>
          )}
        </section>

        {/* Right: Scheduled reports */}
        <aside>
          <div className="card" style={{ padding:"16px 18px" }}>
            <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:14 }}>
              <h3 style={{ margin:0, fontSize:13, fontWeight:600, color:"var(--fg-0)" }}>Scheduled reports</h3>
              <button style={{ ...btnSubtle(), color:"var(--accent)" }}>
                <Icon name="plus" size={12} stroke="var(--accent)"/> New
              </button>
            </div>

            <div style={{ display:"flex", flexDirection:"column", gap:10 }}>
              <div style={{ padding:"11px 12px", border:"1px solid var(--line-1)", borderRadius:9, background:"#fff" }}>
                <div style={{ display:"flex", justifyContent:"space-between", alignItems:"baseline", marginBottom:4 }}>
                  <span style={{ fontSize:12.5, fontWeight:500, color:"var(--fg-0)" }}>Monthly summary</span>
                  <span className="badge badge--pos" style={{ fontSize:10 }}>active</span>
                </div>
                <div style={{ fontSize:11.5, color:"var(--fg-2)", marginBottom:6 }}>Monthly · 1st @ 09:00</div>
                <div style={{ display:"flex", justifyContent:"space-between", fontSize:11 }}>
                  <span style={{ color:"var(--fg-3)" }}>next <span className="mono" style={{ color:"var(--fg-1)" }}>1 Jun 09:00</span></span>
                  <span className="mono" style={{ color:"var(--fg-3)" }}>1 recipient</span>
                </div>
              </div>
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

// ── Template card ───────────────────────────────────────────────
function ReportTemplateCard({ icon, title, description, badge, cta, soon, disabledNote, stats }){
  return (
    <div
      className="card"
      style={{
        padding:"18px 18px 15px",
        position:"relative",
        opacity: soon ? 0.72 : 1,
        cursor: soon ? "not-allowed" : "pointer",
        transition:"transform 120ms ease, box-shadow 120ms ease",
        overflow:"hidden",
      }}
      onMouseEnter={e => { if (!soon) { e.currentTarget.style.transform = "translateY(-1px)"; e.currentTarget.style.boxShadow = "var(--sh-2)"; } }}
      onMouseLeave={e => { if (!soon) { e.currentTarget.style.transform = "translateY(0)";    e.currentTarget.style.boxShadow = "var(--sh-1)"; } }}
    >
      {soon && (
        <span style={{ position:"absolute", top:12, right:12, fontSize:9.5, color:"var(--fg-3)", letterSpacing:0.06, textTransform:"uppercase", fontWeight:600, padding:"2px 7px", border:"1px solid var(--line-2)", borderRadius:5, background:"#fff" }}>
          Coming soon
        </span>
      )}
      {badge && !soon && (
        <span className="badge badge--accent" style={{ position:"absolute", top:12, right:12, fontSize:10 }}>{badge}</span>
      )}
      <div style={{ width:32, height:32, borderRadius:8, background: soon ? "var(--bg-3)" : "var(--accent-soft)", color: soon ? "var(--fg-3)" : "var(--accent)", display:"flex", alignItems:"center", justifyContent:"center", border:"1px solid " + (soon ? "var(--line-1)" : "var(--accent-line)") }}>
        <Icon name={icon} size={15}/>
      </div>
      <h3 style={{ margin:"12px 0 4px", fontSize:14, fontWeight:600, color:"var(--fg-0)" }}>{title}</h3>
      <div style={{ fontSize:12, color:"var(--fg-2)", lineHeight:1.5, minHeight:36 }}>{description}</div>
      <div style={{ marginTop:12, paddingTop:11, borderTop:"1px solid var(--line-1)", display:"flex", alignItems:"center", justifyContent:"space-between", gap:10, minHeight:30 }}>
        <span style={{ fontSize:11, color:"var(--fg-3)" }}>{disabledNote || stats}</span>
        {!soon && (
          <button style={{ ...btnSubtle(), color:"var(--accent)", flexShrink:0 }}>
            {cta} <Icon name="arrow" size={11} stroke="var(--accent)"/>
          </button>
        )}
      </div>
    </div>
  );
}

// ── Shared helpers ──────────────────────────────────────────────
function ReportThumb({ format, title }){
  const color = format === "PDF" ? "var(--accent)" : format === "CSV" ? "var(--pos)" : "var(--fg-2)";
  return (
    <div style={{
      width:36, height:46, flexShrink:0,
      borderRadius:5,
      background:"#fff",
      border:"1px solid var(--line-2)",
      boxShadow:"0 1px 2px rgba(20,16,8,0.04)",
      position:"relative",
      overflow:"hidden",
    }}>
      <div style={{ position:"absolute", top:0, left:0, right:0, height:8, background:color, opacity:0.18 }}/>
      <div style={{ position:"absolute", left:5, right:5, top:13, height:1.5, background:"var(--line-1)" }}/>
      <div style={{ position:"absolute", left:5, right:8, top:18, height:1.5, background:"var(--line-1)" }}/>
      <div style={{ position:"absolute", left:5, right:14, top:23, height:1.5, background:"var(--line-1)" }}/>
      <div style={{ position:"absolute", left:5, right:10, top:30, height:5, background:color, opacity:0.18, borderRadius:1 }}/>
      <div style={{ position:"absolute", left:5, top:38, fontSize:6.5, fontWeight:700, color:color, letterSpacing:0.1 }}>{format}</div>
    </div>
  );
}

function ReportFormatBadge({ fmt }){
  const map = {
    PDF:  { color:"var(--accent)", bg:"var(--accent-soft)", line:"var(--accent-line)" },
    CSV:  { color:"var(--pos)",    bg:"var(--pos-soft)",    line:"rgba(15,138,79,0.28)" },
    XLSX: { color:"var(--pos)",    bg:"var(--pos-soft)",    line:"rgba(15,138,79,0.28)" },
  };
  const c = map[fmt] || map.PDF;
  return (
    <span style={{ display:"inline-flex", alignItems:"center", gap:5, padding:"2px 8px", borderRadius:99, background:c.bg, color:c.color, border:"1px solid " + c.line, fontSize:11, fontWeight:500 }} className="mono">
      <span style={{ width:5, height:5, borderRadius:"50%", background:c.color }}/>{fmt}
    </span>
  );
}

function iconBtnStyle(){
  return { width:28, height:28, borderRadius:6, border:"1px solid var(--line-1)", background:"#fff", color:"var(--fg-2)", display:"inline-flex", alignItems:"center", justifyContent:"center", cursor:"pointer" };
}

// ─────────────────────────────────────────────────────────────
//  Report detail sub-page
// ─────────────────────────────────────────────────────────────
function ReportDetail({ id, setScreen }){
  const r = REPORTS_RECENT.find(x => x.id === id) || REPORTS_RECENT[0];

  return (
    <div data-screen-label="04b Report Detail" style={{ padding:"20px 28px 40px", maxWidth:1380, margin:"0 auto", display:"flex", flexDirection:"column", gap:18 }}>
      {/* Breadcrumb */}
      <div style={{ display:"flex", alignItems:"center", gap:8, fontSize:12.5, color:"var(--fg-2)" }}>
        <button onClick={() => setScreen("reports")} style={{ background:"none", border:"none", color:"var(--fg-2)", padding:0, cursor:"pointer", fontSize:12.5, display:"inline-flex", alignItems:"center", gap:5 }}>
          <Icon name="chevLeft" size={12}/> Reports
        </button>
        <span style={{ color:"var(--fg-3)" }}>/</span>
        <span style={{ color:"var(--fg-0)", fontWeight:500 }}>{r.title}</span>
      </div>

      {/* Header */}
      <header className="card" style={{ padding:"22px 26px", display:"flex", justifyContent:"space-between", alignItems:"flex-start", gap:24 }}>
        <div style={{ display:"flex", gap:16, alignItems:"flex-start" }}>
          <ReportThumb format={r.format}/>
          <div>
            <div style={{ display:"flex", alignItems:"center", gap:10 }}>
              <h1 style={{ margin:0, fontSize:22, fontWeight:600, letterSpacing:-0.3 }}>{r.title}</h1>
              <ReportFormatBadge fmt={r.format}/>
              {r.shareUrl && <span className="badge badge--accent" style={{ fontSize:10 }}><Icon name="ext" size={10} stroke="var(--accent)"/> shared</span>}
            </div>
            <div style={{ display:"flex", gap:10, marginTop:5, fontSize:12, color:"var(--fg-2)" }}>
              <span>{TEMPLATE_LABEL[r.template]}</span>
              <span style={{ color:"var(--fg-3)" }}>·</span>
              <span><span className="mono">{r.period}</span> · {r.pages} page{r.pages !== 1 ? "s" : ""}</span>
              <span style={{ color:"var(--fg-3)" }}>·</span>
              <span>generated <span className="mono">{r.ago}</span> by <span style={{ color:"var(--fg-1)" }}>{r.by}</span></span>
            </div>
          </div>
        </div>
        <div style={{ display:"flex", gap:8 }}>
          <button style={btnSecondary()}><Icon name="ext" size={13}/> Copy link</button>
          <button style={btnSecondary()}><Icon name="refresh" size={13}/> Regenerate</button>
          <button style={btnPrimary()}><Icon name="download" size={13}/> Download {r.format}</button>
        </div>
      </header>

      {/* Main two-column */}
      <div style={{ display:"grid", gridTemplateColumns:"minmax(0, 1fr) 340px", gap:18 }}>
        {/* Preview */}
        <section className="card" style={{ padding:24, background:"var(--bg-3)" }}>
          <PDFPreview report={r}/>
        </section>

        {/* Right column */}
        <aside style={{ display:"flex", flexDirection:"column", gap:14 }}>
          <ReportMetaCard r={r}/>
          <ShareAccessCard r={r}/>
          <DownloadAuditCard r={r}/>
          <RelatedReportsCard current={r} setScreen={setScreen}/>
        </aside>
      </div>
    </div>
  );
}

// Faux PDF preview — readable summary of what's in the report
function PDFPreview({ report }){
  return (
    <div style={{
      background:"#fff",
      borderRadius:4,
      boxShadow:"0 4px 24px rgba(20,16,8,0.12)",
      padding:"48px 56px",
      minHeight:780,
      display:"flex", flexDirection:"column", gap:24,
    }}>
      {/* Letterhead */}
      <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start", paddingBottom:20, borderBottom:"2px solid var(--fg-0)" }}>
        <div>
          <div style={{ display:"flex", alignItems:"center", gap:10 }}>
            <img src="/halton-meter-mark-on-paper.svg" width="28" height="28" alt="Halton Meter" style={{ borderRadius:7, display:"block" }}/>
            <span style={{ fontSize:16, fontWeight:600 }}>Halton Labs</span>
          </div>
          <div style={{ marginTop:14, fontSize:11, color:"var(--fg-2)", lineHeight:1.6 }}>
            Halton Labs Ltd · UK · VAT GB 412 7831 09<br/>
            hello@meridianstudio.io · meridianstudio.io
          </div>
        </div>
        <div style={{ textAlign:"right" }}>
          <div style={{ fontSize:22, fontWeight:600, letterSpacing:-0.3 }}>LLM Cost Report</div>
          <div style={{ fontSize:11.5, color:"var(--fg-2)", marginTop:4 }}>
            Period: <span className="mono">{report.period}</span><br/>
            Generated: <span className="mono">15 May 2026 · 14:32 UTC</span><br/>
            Report ID: <span className="mono">{report.id}</span>
          </div>
        </div>
      </div>

      {/* Executive summary */}
      <div>
        <div style={{ fontSize:10.5, letterSpacing:0.08, textTransform:"uppercase", color:"var(--fg-3)", fontWeight:600, marginBottom:8 }}>Executive summary</div>
        <p style={{ margin:0, fontSize:13, color:"var(--fg-1)", lineHeight:1.6 }}>
          During {report.period}, Halton Labs processed <span style={{ fontWeight:600 }}>6,735 LLM requests</span> across <span style={{ fontWeight:600 }}>21 active projects</span>, incurring a total cost of <span style={{ fontWeight:600 }} className="mono">£277.88</span> (≈ $351.75). Spend was up 53.3% versus April, driven primarily by increased Opus 4.7 usage on internal product development. Anthropic accounted for 99.99% of cost, with sub-cent Gemini usage for low-stakes lookups.
        </p>
      </div>

      {/* Headline numbers */}
      <div style={{ display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:14, padding:"16px 0", borderTop:"1px solid var(--line-1)", borderBottom:"1px solid var(--line-1)" }}>
        {[
          { l:"Total cost",      v:"£277.88", s:"≈ $351.75" },
          { l:"Requests",        v:"6,735",   s:"225/day avg" },
          { l:"Active projects", v:"21",      s:"of 21 total" },
          { l:"Reconciliation",  v:"0.30%",   s:"within tolerance" },
        ].map((k, i) => (
          <div key={i}>
            <div style={{ fontSize:10, color:"var(--fg-3)", textTransform:"uppercase", letterSpacing:0.08, fontWeight:600 }}>{k.l}</div>
            <div className="mono" style={{ fontSize:18, fontWeight:600, color:"var(--fg-0)", marginTop:4 }}>{k.v}</div>
            <div style={{ fontSize:10.5, color:"var(--fg-2)", marginTop:2 }}>{k.s}</div>
          </div>
        ))}
      </div>

      {/* Cost breakdown table */}
      <div>
        <div style={{ fontSize:10.5, letterSpacing:0.08, textTransform:"uppercase", color:"var(--fg-3)", fontWeight:600, marginBottom:8 }}>Cost breakdown by model</div>
        <table style={{ width:"100%", borderCollapse:"collapse", fontSize:11.5 }}>
          <thead>
            <tr style={{ borderBottom:"1px solid var(--line-2)" }}>
              <th style={{ textAlign:"left", padding:"6px 0", fontWeight:600, color:"var(--fg-2)" }}>Provider</th>
              <th style={{ textAlign:"left", fontWeight:600, color:"var(--fg-2)" }}>Model</th>
              <th style={{ textAlign:"right", fontWeight:600, color:"var(--fg-2)" }}>Requests</th>
              <th style={{ textAlign:"right", fontWeight:600, color:"var(--fg-2)" }}>Input tok</th>
              <th style={{ textAlign:"right", fontWeight:600, color:"var(--fg-2)" }}>Output tok</th>
              <th style={{ textAlign:"right", fontWeight:600, color:"var(--fg-2)" }}>Cost (GBP)</th>
              <th style={{ textAlign:"right", fontWeight:600, color:"var(--fg-2)" }}>Cost (USD)</th>
            </tr>
          </thead>
          <tbody>
            {[
              { p:"Anthropic", m:"Opus 4.7",      r:5980, i:"25.1M", o:"5.9M",  gbp:"275.08", usd:"348.20" },
              { p:"Anthropic", m:"Sonnet 4.6",    r:32,   i:"71K",   o:"17K",   gbp:"2.01",   usd:"2.55"   },
              { p:"Anthropic", m:"Haiku 4.5",     r:710,  i:"1.2M",  o:"285K",  gbp:"0.77",   usd:"0.97"   },
              { p:"Google",    m:"Gemini 2 Flash", r:6,   i:"7.2K",  o:"2.4K",  gbp:"0.02",   usd:"0.03"   },
              { p:"—",         m:"Unknown",        r:7,   i:"—",     o:"—",     gbp:"0.00",   usd:"0.00"   },
            ].map((row, i) => (
              <tr key={i} style={{ borderBottom: i < 4 ? "1px solid var(--line-1)" : "none" }}>
                <td style={{ padding:"7px 0", color:"var(--fg-1)" }}>{row.p}</td>
                <td className="mono" style={{ color:"var(--fg-0)" }}>{row.m}</td>
                <td className="mono right" style={{ textAlign:"right", color:"var(--fg-1)" }}>{row.r.toLocaleString()}</td>
                <td className="mono" style={{ textAlign:"right", color:"var(--fg-1)" }}>{row.i}</td>
                <td className="mono" style={{ textAlign:"right", color:"var(--fg-1)" }}>{row.o}</td>
                <td className="mono" style={{ textAlign:"right", color:"var(--fg-0)", fontWeight:500 }}>£{row.gbp}</td>
                <td className="mono" style={{ textAlign:"right", color:"var(--fg-2)" }}>${row.usd}</td>
              </tr>
            ))}
            <tr style={{ borderTop:"2px solid var(--fg-0)" }}>
              <td colSpan="5" style={{ padding:"8px 0", fontWeight:600 }}>Total</td>
              <td className="mono" style={{ textAlign:"right", fontWeight:600 }}>£277.88</td>
              <td className="mono" style={{ textAlign:"right", color:"var(--fg-2)", fontWeight:600 }}>$351.75</td>
            </tr>
          </tbody>
        </table>
      </div>

      {/* Spend chart */}
      <div>
        <div style={{ fontSize:10.5, letterSpacing:0.08, textTransform:"uppercase", color:"var(--fg-3)", fontWeight:600, marginBottom:8 }}>Daily spend</div>
        <svg width="100%" height="120" viewBox="0 0 600 120" preserveAspectRatio="none">
          <line x1="0" x2="600" y1="100" y2="100" stroke="var(--line-2)"/>
          {DAILY.map((d, i) => {
            const x = (i / (DAILY.length - 1)) * 580 + 10;
            const y = 100 - (d.cost / Math.max(...DAILY.map(x => x.cost))) * 80;
            return <circle key={i} cx={x} cy={y} r="2.5" fill="var(--accent)"/>;
          })}
          <polyline points={DAILY.map((d, i) => {
            const x = (i / (DAILY.length - 1)) * 580 + 10;
            const y = 100 - (d.cost / Math.max(...DAILY.map(x => x.cost))) * 80;
            return `${x},${y}`;
          }).join(" ")} fill="none" stroke="var(--accent)" strokeWidth="1.5"/>
        </svg>
      </div>

      {/* Reconciliation */}
      <div style={{ padding:"12px 14px", border:"1px solid var(--pos)", borderRadius:6, background:"var(--pos-soft)", display:"flex", justifyContent:"space-between", alignItems:"center" }}>
        <div>
          <div style={{ display:"flex", alignItems:"center", gap:7 }}>
            <Icon name="check" size={14} stroke="var(--pos)"/>
            <span style={{ fontSize:12.5, fontWeight:600, color:"var(--pos)" }}>Reconciliation: matched</span>
          </div>
          <div style={{ fontSize:11, color:"var(--fg-2)", marginTop:3 }}>
            Logged total <span className="mono">£277.88</span> · Anthropic billed <span className="mono">£277.04</span> · Variance <span className="mono">0.30%</span> (within 1% tolerance)
          </div>
        </div>
      </div>

      {/* Footer */}
      <div style={{ marginTop:"auto", paddingTop:16, borderTop:"1px solid var(--line-1)", fontSize:10, color:"var(--fg-3)", textAlign:"center", lineHeight:1.6 }}>
        Generated by Halton Meter · meridianstudio.io · All costs computed from provider-published rates.<br/>
        Token counts captured via local proxy. Reconciled against provider billing API.
      </div>
    </div>
  );
}

function ReportMetaCard({ r }){
  return (
    <div className="card" style={{ padding:"16px 18px" }}>
      <h3 style={{ margin:"0 0 12px", fontSize:12.5, fontWeight:600 }}>Report details</h3>
      <div style={{ display:"flex", flexDirection:"column", gap:9, fontSize:12 }}>
        {[
          ["Template", TEMPLATE_LABEL[r.template]],
          ["Period",   r.period],
          ["Format",   r.format],
          ["File size", r.size],
          ["Pages",    r.pages],
          ["Generated", "15 May 2026 14:32"],
          ["By",       r.by],
          ["Report ID", r.id],
        ].map(([k, v], i) => (
          <div key={i} style={{ display:"flex", justifyContent:"space-between", alignItems:"baseline" }}>
            <span style={{ color:"var(--fg-2)" }}>{k}</span>
            <span className="mono" style={{ color:"var(--fg-0)", fontSize:11.5 }}>{v}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function ShareAccessCard({ r }){
  return (
    <div className="card" style={{ padding:"16px 18px" }}>
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:10 }}>
        <h3 style={{ margin:0, fontSize:12.5, fontWeight:600 }}>Share & access</h3>
        <span style={{ fontSize:10, color:"var(--fg-3)" }}>{r.shareUrl ? "Link active" : "Private"}</span>
      </div>
      {r.shareUrl ? (
        <>
          <div style={{ padding:"7px 9px", background:"var(--bg-3)", border:"1px solid var(--line-1)", borderRadius:6, fontSize:11, color:"var(--fg-1)", overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap", marginBottom:8 }} className="mono">
            haltonmeter.app/r/{r.id}
          </div>
          <div style={{ display:"flex", flexDirection:"column", gap:7, fontSize:11.5, color:"var(--fg-2)" }}>
            <div style={{ display:"flex", justifyContent:"space-between" }}>
              <span>Access</span>
              <span style={{ color:"var(--fg-0)" }}>Anyone with link</span>
            </div>
            <div style={{ display:"flex", justifyContent:"space-between" }}>
              <span>Expires</span>
              <span className="mono" style={{ color:"var(--fg-0)" }}>29 May 2026</span>
            </div>
            <div style={{ display:"flex", justifyContent:"space-between" }}>
              <span>Password</span>
              <span style={{ color:"var(--fg-3)" }}>—</span>
            </div>
          </div>
          <button style={{ ...btnGhost(), width:"100%", justifyContent:"center", marginTop:10 }}>Manage link</button>
        </>
      ) : (
        <>
          <div style={{ fontSize:11.5, color:"var(--fg-2)", marginBottom:8 }}>This report is private. Only workspace members can access it.</div>
          <button style={{ ...btnSecondary(), width:"100%", justifyContent:"center" }}><Icon name="ext" size={13}/> Create share link</button>
        </>
      )}
    </div>
  );
}

function DownloadAuditCard({ r }){
  const events = r.downloads > 0 ? [
    { who:"Alex Pemberton",  email:"alex@meridianstudio.io", ago:"2h ago",    from:"Web" },
    { who:"finance@foxgrove.io", email:"finance@foxgrove.io", ago:"yesterday", from:"Email link", ext:true },
  ] : [];
  return (
    <div className="card" style={{ padding:"16px 18px" }}>
      <h3 style={{ margin:"0 0 10px", fontSize:12.5, fontWeight:600 }}>Download audit</h3>
      {events.length === 0 ? (
        <div style={{ fontSize:11.5, color:"var(--fg-2)" }}>No downloads yet.</div>
      ) : (
        <div style={{ display:"flex", flexDirection:"column", gap:10 }}>
          {events.map((e, i) => (
            <div key={i} style={{ display:"flex", gap:9, alignItems:"flex-start" }}>
              <div style={{ width:6, height:6, borderRadius:"50%", background: e.ext ? "var(--warn)" : "var(--pos)", marginTop:6, flexShrink:0 }}/>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:11.5, color:"var(--fg-0)", fontWeight:500 }}>{e.who}</div>
                <div style={{ fontSize:10.5, color:"var(--fg-3)", display:"flex", justifyContent:"space-between" }}>
                  <span>{e.from}</span>
                  <span className="mono">{e.ago}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function RelatedReportsCard({ current, setScreen }){
  const related = REPORTS_RECENT.filter(r => r.id !== current.id).slice(0, 3);
  return (
    <div className="card" style={{ padding:"16px 18px" }}>
      <h3 style={{ margin:"0 0 10px", fontSize:12.5, fontWeight:600 }}>Related reports</h3>
      <div style={{ display:"flex", flexDirection:"column", gap:8 }}>
        {related.map(r => (
          <button key={r.id} onClick={() => setScreen("reports")} style={{ display:"flex", alignItems:"center", gap:10, padding:"8px 9px", border:"1px solid var(--line-1)", borderRadius:7, background:"#fff", cursor:"pointer", textAlign:"left" }}>
            <ReportThumb format={r.format}/>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ fontSize:12, fontWeight:500, color:"var(--fg-0)", overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{r.title}</div>
              <div style={{ fontSize:10.5, color:"var(--fg-3)" }} className="mono">{r.period} · {r.size}</div>
            </div>
            <Icon name="chevron" size={12} stroke="var(--fg-3)"/>
          </button>
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
//  Mock data
// ─────────────────────────────────────────────────────────────
const TEMPLATE_LABEL = {
  personal:  "Monthly summary",
  client:    "Client invoice",
  executive: "Executive summary",
  csv:       "Custom CSV",
  custom:    "Custom",
};

const REPORTS_RECENT = [
  { id:"r-2026-05-01-pers", title:"May 2026 — Monthly summary",           period:"May 2026 (partial)", template:"personal",  format:"PDF", size:"180.0 KB", pages:4, spend:277.88, downloads:1, ago:"2h ago",  by:"Alex", shareUrl:false },
  { id:"r-2026-04-01-pers", title:"April 2026 — Monthly summary",         period:"Apr 2026",           template:"personal",  format:"PDF", size:"172.4 KB", pages:4, spend:181.27, downloads:3, ago:"2d ago",  by:"Alex", shareUrl:false },
  { id:"r-2026-q1-fox",     title:"Q1 2026 — Client invoice (Foxgrove Studio)", period:"Q1 2026",      template:"client",    format:"PDF", size:"90.0 KB",  pages:2, spend:412.00, downloads:5, ago:"8d ago",  by:"Alex", shareUrl:true  },
  { id:"r-2026-03-exec",    title:"March 2026 — Executive summary",        period:"Mar 2026",           template:"executive", format:"PDF", size:"250.5 KB", pages:6, spend:153.10, downloads:2, ago:"14d ago", by:"Alex", shareUrl:false },
  { id:"r-2026-03-csv",     title:"March 2026 — Cost CSV",                 period:"Mar 2026",           template:"csv",       format:"CSV", size:"31.0 KB",  pages:1, spend:153.10, downloads:1, ago:"14d ago", by:"Alex", shareUrl:false },
  { id:"r-2026-02-exec",    title:"February 2026 — Executive summary",     period:"Feb 2026",           template:"executive", format:"PDF", size:"245.0 KB", pages:6, spend:142.80, downloads:1, ago:"42d ago", by:"Alex", shareUrl:false },
];

Object.assign(window, { Reports, ReportDetail });
