// ============================================
// Reliq — Reports
// ============================================

// ── Backend → row mapping (GET /v1/reports returns ReportSummaryResponse[]) ─────
// The generalized report list returns id/scanId/appId/type/score/verdict/dates/
// status. Mobile-presentation fields (app name, bundle, version, stores, pages)
// are not part of the generalized API and are derived/defaulted; visibility is
// per-action (the list does not expose share state).
const REPORTS_VERDICT_MAP = { PASS: "pass", WARNING: "needs_fixes", FAIL: "will_reject" };
function mapReportRow(api) {
  const created = (api.createdAt || "").replace("T", " ").slice(0, 16);
  return {
    id: api.id, scanId: api.scanId || null, appId: api.appId || null,
    type: (api.type || "FULL").toLowerCase(),
    app: api.appId || "Report", letters: (api.appId || "R").replace(/[^a-zA-Z0-9]/g, "").slice(0, 1).toUpperCase() || "R",
    grad: "linear-gradient(135deg,#5B9DFF,#A78BFA)",
    version: "—", build: "—", bundle: api.appId || api.id, stores: [],
    score: api.score != null ? api.score : 0,
    verdict: REPORTS_VERDICT_MAP[api.verdict] || "needs_fixes",
    createdAt: created, lastRegenAt: (api.generatedAt || "").replace("T", " ").slice(0, 16) || created,
    visibility: "private", whiteLabelEnabled: false, pages: null,
  };
}

// Reference shape (removed mock kept only as a comment for documentation):
//   { id:"rep_…", scanId:"scn_…", type:"full", app, score, verdict, createdAt, visibility }

// ── Report type display metadata ──────────────────────────────────────────────
const TYPE_META = {
  full:    { label:"Full",    color:"var(--teal)",   bg:"var(--teal-bg)",   border:"rgba(0,212,170,0.3)" },
  preview: { label:"Preview", color:"var(--blue)",   bg:"var(--blue-bg)",   border:"rgba(91,157,255,0.3)" },
  ci:      { label:"CI",      color:"var(--violet)", bg:"var(--violet-bg)", border:"rgba(167,139,250,0.25)" },
};

const VISIBILITY_META = {
  private:  { label:"Private",  color:"var(--fg-3)",   bg:"var(--bg-3)",      border:"var(--line-2)" },
  shared:   { label:"Shared",   color:"var(--teal)",   bg:"var(--teal-bg)",   border:"rgba(0,212,170,0.3)" },
  expired:  { label:"Expired",  color:"var(--amber)",  bg:"var(--amber-bg)",  border:"rgba(245,158,11,0.3)" },
};

const Reports = ({ go }) => {
  const [search, setSearch]           = React.useState("");
  const [filterVerdict, setFilterVerdict] = React.useState("all");
  const [filterVis, setFilterVis]     = React.useState("all");
  const [sortKey, setSortKey]         = React.useState("createdAt");
  const [sortDir, setSortDir]         = React.useState("desc");

  // ── Feature gate checks ─────────────────────────────────────────────────────
  const canShare  = window.reliqGates ? window.reliqGates.canShareReport()  : true;
  const canExport = window.reliqGates ? window.reliqGates.canExportReport() : true;

  const cycleSort = (key) => {
    if (sortKey === key) setSortDir(d => d === "asc" ? "desc" : "asc");
    else { setSortKey(key); setSortDir("desc"); }
  };
  const SI = ({ col }) => sortKey !== col
    ? <span style={{color:"var(--fg-3)",marginLeft:3,fontSize:10}}>↕</span>
    : <span style={{color:"var(--teal)",marginLeft:3,fontSize:10}}>{sortDir==="asc"?"↑":"↓"}</span>;
  const [visibilities, setVisibilities] = React.useState({});
  const [copiedId, setCopiedId]       = React.useState(null);
  const [sentId, setSentId]           = React.useState(null);
  const [publishTarget, setPublishTarget] = React.useState(null);

  // ── Real report list from the backend (GET /v1/reports) ─────────────────────
  const [reportsData, setReportsData] = React.useState([]);
  const [loading, setLoading]         = React.useState(true);
  const [error, setError]             = React.useState(null);
  const [reloadKey, setReloadKey]     = React.useState(0);

  React.useEffect(() => {
    let cancelled = false;
    setLoading(true); setError(null);
    window.reliqReportsApi.listReports()
      .then((res) => { if (!cancelled) setReportsData((res.reports || []).map(mapReportRow)); })
      .catch((e) => { if (!cancelled) setError(e); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [reloadKey]);

  // Deep-link: if global search navigated here for a specific report, expand it
  const _focusReportId = React.useRef(null);
  const [expandedId, setExpandedId]   = React.useState(() => {
    const t = window.__reliq_pending_focus;
    if (t && t.type === "report") {
      window.__reliq_pending_focus = null;
      _focusReportId.current = t.id;
      return t.id;
    }
    return null;
  });

  // Scroll the focused row into view after mount
  React.useEffect(() => {
    const id = _focusReportId.current;
    if (!id) return;
    setTimeout(() => {
      const el = document.getElementById("report-row-" + id);
      if (el) el.scrollIntoView({ behavior: "smooth", block: "center" });
    }, 80);
  }, []);

  // ── Copy share link ───────────────────────────────────────────────────────────
  // Gated: requires canShare. Also requires visibility to be "shared".
  // Share URL always uses the report ID (rep_*) — never the scan ID.
  const copyLink = (reportId, vis, e) => {
    e && e.stopPropagation();
    if (!canShare) {
      window.reliqGatePrompt?.show({ title:"Upgrade to share reports", description:"Share read-only report links with Starter plan or above.", planRequired:"starter", go });
      return;
    }
    if (vis !== "shared") {
      window.reliqToast?.info("Enable sharing first — set visibility to Shared.");
      return;
    }
    // Report share URLs use rep_ IDs only — verified by reliqIds if available
    const shareUrl = window.reliqIds
      ? window.reliqIds.makeShareReportUrl(reportId)
      : "https://reliq.dev/r/" + reportId;
    try { navigator.clipboard.writeText(shareUrl).catch(() => {}); } catch (_) {}
    setCopiedId(reportId);
    setTimeout(() => setCopiedId(null), 2000);
    window.reliqToast?.success("Share link copied to clipboard.");
  };

  // ── PDF download (per-report) ─────────────────────────────────────────────────
  // Gated: requires canExport. Filename uses the report ID (never scan ID).
  const downloadPdf = (r, e) => {
    e && e.stopPropagation();
    if (!canExport) {
      window.reliqGatePrompt?.show({ title:"Export requires Starter plan", description:"Upgrade to export reports as PDF.", planRequired:"starter", go });
      return;
    }
    // Mock export — in production, call the report PDF generation API
    const filename = "reliq-report-" + r.id + ".pdf";
    const content  = [
      "RELIQ COMPLIANCE REPORT",
      "Report ID: " + r.id,
      "Scan ID:   " + (r.scanId || "—"),
      "Type:      " + (r.type || "full"),
      "App:       " + r.app + " v" + r.version + " (build " + r.build + ")",
      "Bundle:    " + r.bundle,
      "Score:     " + r.score + "/100",
      "Verdict:   " + r.verdict,
      "Created:   " + r.createdAt,
      "",
      "This is a mock PDF. Wire up real PDF generation in production.",
    ].join("\n");
    const blob = new Blob([content], { type:"application/pdf" });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = filename;
    a.click();
    window.reliqToast?.success("Downloading " + filename);
  };

  const sendIntegration = (id, e) => {
    e && e.stopPropagation();
    setSentId(id);
    setTimeout(() => setSentId(null), 2000);
  };

  // Share / revoke via the real backend; optimistic local visibility update.
  const setVis = (id, val, e) => {
    e && e.stopPropagation();
    setVisibilities(s => ({ ...s, [id]: val }));
    if (val === "shared") {
      window.reliqReportsApi.shareReport(id).catch((err) => { window.reliqToast?.info?.(err.message || "Could not share report."); });
    } else if (val === "expired") {
      window.reliqReportsApi.revokeShare(id).catch((err) => { window.reliqToast?.info?.(err.message || "Could not revoke share."); });
    }
  };

  const selStyle = {
    background:"var(--bg-1)", border:"1px solid var(--line-2)",
    borderRadius:"var(--r-sm)", padding:"0 10px",
    height:34, boxSizing:"border-box",
    fontSize:13, color:"var(--fg-0)", outline:"none", cursor:"pointer", flexShrink:0
  };

  const filtered = reportsData.filter(r => {
    if (search) {
      const q = search.toLowerCase();
      const matchApp     = r.app.toLowerCase().includes(q);
      const matchBundle  = r.bundle.toLowerCase().includes(q);
      const matchId      = r.id.toLowerCase().includes(q);
      const matchScanId  = r.scanId && r.scanId.toLowerCase().includes(q);
      const matchVerdict = r.verdict.toLowerCase().includes(q);
      if (!matchApp && !matchBundle && !matchId && !matchScanId && !matchVerdict) return false;
    }
    if (filterVerdict !== "all" && r.verdict !== filterVerdict) return false;
    const vis = visibilities[r.id] ?? r.visibility;
    if (filterVis !== "all" && vis !== filterVis) return false;
    return true;
  }).sort((a, b) => {
    let av, bv;
    if (sortKey === "score")  { av = a.score; bv = b.score; }
    else if (sortKey === "app") { av = a.app.toLowerCase(); bv = b.app.toLowerCase(); }
    else if (sortKey === "pages") { av = a.pages; bv = b.pages; }
    else { av = a.createdAt; bv = b.createdAt; }
    if (av < bv) return sortDir === "asc" ? -1 : 1;
    if (av > bv) return sortDir === "asc" ? 1 : -1;
    return 0;
  });

  const sharedCount = reportsData.filter(r => (visibilities[r.id] ?? r.visibility) === "shared").length;

  return (
    <AuthLayout
      route="reports"
      go={go}
      crumbs={["Workspace", "Reports"]}
      actions={
        <button className="btn btn-sm" onClick={() => {
          if (window.reliqGates && !window.reliqGates.canExportReport()) {
            window.reliqGatePrompt?.show({ title:"Export requires Starter plan", description:"Upgrade to export reports.", planRequired:"starter", go });
            return;
          }
          const csv = [["Report ID","App","Bundle","Version","Build","Score","Verdict","Visibility","Created","Last Regen","Pages"],
            ...reportsData.map(r => [r.id, r.app, r.bundle, r.version, r.build, r.score, r.verdict, (visibilities[r.id] ?? r.visibility), r.createdAt, r.lastRegenAt, r.pages])]
            .map(row => row.map(v => `"${v}"`).join(",")).join("\n");
          const blob = new Blob([csv], {type:"text/csv"});
          const a = document.createElement("a"); a.href = URL.createObjectURL(blob);
          a.download = "reliq-reports.csv"; a.click();
        }}>
          <Icon name="download" size={13} /> Export all
        </button>
      }
    >
          <div className="page-head">
            <div>
              <h1 className="page-title">Reports</h1>
              <p className="page-sub">{reportsData.length} reports · {sharedCount} shared publicly</p>
            </div>
          </div>

          {/* Filter bar */}
          <div style={{display:"flex", gap:8, marginBottom:20, flexWrap:"nowrap", alignItems:"center", overflowX:"auto"}}>
            <div style={{position:"relative", flex:"1 1 auto", minWidth:140}}>
              <Icon name="search" size={14} style={{position:"absolute", left:10, top:"50%", transform:"translateY(-50%)", color:"var(--fg-3)", pointerEvents:"none"}} />
              <input
                value={search} onChange={e => setSearch(e.target.value)}
                placeholder="Search app, bundle, report ID…"
                style={{width:"100%", height:34, boxSizing:"border-box",
                  background:"var(--bg-1)", border:"1px solid var(--line-2)", borderRadius:"var(--r-sm)",
                  padding:"0 12px 0 34px", fontSize:13, color:"var(--fg-0)", outline:"none"}}
              />
            </div>
            <select value={filterVerdict} onChange={e => setFilterVerdict(e.target.value)} style={selStyle}>
              <option value="all">All verdicts</option>
              <option value="pass">Pass</option>
              <option value="likely_pass">Likely Pass</option>
              <option value="needs_fixes">Needs Fixes</option>
              <option value="will_reject">Will Reject</option>
            </select>
            <select value={filterVis} onChange={e => setFilterVis(e.target.value)} style={selStyle}>
              <option value="all">All visibility</option>
              <option value="private">Private</option>
              <option value="shared">Shared</option>
              <option value="expired">Expired</option>
            </select>
            {(search || filterVerdict !== "all" || filterVis !== "all") && (
              <button className="btn btn-sm btn-ghost" onClick={() => { setSearch(""); setFilterVerdict("all"); setFilterVis("all"); }}>
                <Icon name="x" size={12} /> Clear
              </button>
            )}
          </div>

          <div className="card">
            <div className="tbl-scroll">
            <table className="tbl">
              <thead>
                <tr>
                  <th style={{cursor:"pointer",userSelect:"none"}} onClick={() => cycleSort("app")}>Report <SI col="app" /></th>
                  <th>Stores</th>
                  <th style={{textAlign:"right",cursor:"pointer",userSelect:"none"}} onClick={() => cycleSort("score")}>Score <SI col="score" /></th>
                  <th>Verdict</th>
                  <th>Visibility</th>
                  <th style={{cursor:"pointer",userSelect:"none"}} onClick={() => cycleSort("createdAt")}>Created <SI col="createdAt" /></th>
                  <th>Last regen</th>
                  <th style={{textAlign:"right",cursor:"pointer",userSelect:"none"}} onClick={() => cycleSort("pages")}>Pages <SI col="pages" /></th>
                  <th style={{textAlign:"right"}}>Actions</th>
                </tr>
              </thead>
              <tbody>
                {loading && (
                  <tr><td colSpan={9} style={{textAlign:"center", padding:"48px 20px", color:"var(--fg-3)"}}>
                    <div style={{fontSize:13}}>Loading reports…</div>
                  </td></tr>
                )}
                {!loading && error && (
                  <tr><td colSpan={9} style={{textAlign:"center", padding:"48px 20px", color:"var(--fg-3)"}}>
                    <div style={{fontSize:13, fontWeight:500, marginBottom:6, color:"var(--red)"}}>Couldn’t load reports ({error.code || "error"}).</div>
                    <button className="btn btn-sm" onClick={() => setReloadKey(k => k + 1)}>Retry</button>
                  </td></tr>
                )}
                {!loading && !error && reportsData.length === 0 && (
                  <tr><td colSpan={9} style={{textAlign:"center", padding:"48px 20px", color:"var(--fg-3)"}}>
                    <div style={{fontSize:13, fontWeight:500, marginBottom:6}}>No reports yet.</div>
                    <div style={{fontSize:12}}>Run a scan to generate your first report.</div>
                  </td></tr>
                )}
                {!loading && !error && reportsData.length > 0 && filtered.length === 0 && (
                  <tr>
                    <td colSpan={9} style={{textAlign:"center", padding:"48px 20px", color:"var(--fg-3)"}}>
                      <div style={{fontSize:13, fontWeight:500, marginBottom:6}}>No reports match your filters.</div>
                      <div style={{fontSize:12}}>Try adjusting your search or filter criteria.</div>
                    </td>
                  </tr>
                )}
                {!loading && !error && filtered.map(r => {
                  const vis = visibilities[r.id] ?? r.visibility;
                  const vm = VISIBILITY_META[vis] || VISIBILITY_META.private;
                  const isExpanded = expandedId === r.id;
                  return (
                    <React.Fragment key={r.id}>
                      <tr id={"report-row-" + r.id} onClick={() => setExpandedId(isExpanded ? null : r.id)} style={{cursor:"pointer"}}>
                        <td>
                          <div style={{display:"flex", alignItems:"center", gap:12}}>
                            <AppIcon letters={r.letters} size={32} gradient={r.grad} />
                            <div>
                              <div style={{display:"flex", alignItems:"center", gap:8}}>
                                <span style={{fontWeight:500, fontSize:13.5}}>{r.app}</span>
                                {/* Report type badge — Full / Preview / CI */}
                                {(() => { const tm = TYPE_META[r.type] || TYPE_META.full; return (
                                  <span style={{fontFamily:"var(--font-mono)", fontSize:10, letterSpacing:"0.06em", textTransform:"uppercase", padding:"1px 6px", borderRadius:4, color:tm.color, background:tm.bg, border:`1px solid ${tm.border}`}}>{tm.label}</span>
                                ); })()}
                                {r.whiteLabelEnabled && (
                                  <span style={{fontFamily:"var(--font-mono)", fontSize:10, color:"var(--violet)", background:"var(--violet-bg)", border:"1px solid rgba(167,139,250,0.25)", borderRadius:4, padding:"1px 6px", letterSpacing:"0.06em", textTransform:"uppercase"}}>WL</span>
                                )}
                              </div>
                              <div className="mono" style={{fontSize:11, color:"var(--fg-3)"}}>v{r.version} · build {r.build}</div>
                              {/* Report ID and linked scan ID — displayed separately */}
                              <div className="mono" style={{fontSize:10, color:"var(--fg-3)", marginTop:2, display:"flex", gap:6, alignItems:"center"}}>
                                <span>{r.id}</span>
                                {r.scanId && <><span style={{color:"var(--line-2)"}}>·</span><span>{r.scanId}</span></>}
                              </div>
                            </div>
                          </div>
                        </td>
                        <td>
                          <div style={{display:"flex", gap:4, flexWrap:"wrap"}}>
                            {r.stores.map(st => <StoreChip key={st} store={st} iconOnly={true} />)}
                          </div>
                        </td>
                        <td style={{textAlign:"right"}}>
                          <span className="mono" style={{fontSize:15, fontWeight:600,
                            color:r.score>=85?"var(--teal)":r.score>=60?"var(--amber)":"var(--red)"}}>
                            {r.score}
                          </span>
                          <span className="mono" style={{color:"var(--fg-3)", fontSize:11}}>/100</span>
                        </td>
                        <td><VerdictPill verdict={r.verdict} /></td>
                        <td onClick={e => e.stopPropagation()}>
                          <span style={{
                            fontFamily:"var(--font-mono)", fontSize:10.5, fontWeight:600, letterSpacing:"0.06em",
                            textTransform:"uppercase", padding:"2px 8px", borderRadius:4, whiteSpace:"nowrap",
                            color:vm.color, background:vm.bg, border:`1px solid ${vm.border}`
                          }}>{vm.label}</span>
                        </td>
                        <td className="mono" style={{fontSize:12, color:"var(--fg-2)"}}>{r.createdAt}</td>
                        <td className="mono" style={{fontSize:12, color:"var(--fg-2)"}}>{r.lastRegenAt}</td>
                        <td className="mono" style={{textAlign:"right", fontSize:13, color:"var(--fg-2)"}}>{r.pages}</td>
                        <td style={{textAlign:"right"}}>
                          <div style={{display:"flex", gap:4, justifyContent:"flex-end"}} onClick={e => e.stopPropagation()}>
                            {/* PDF download — gated; filename uses report ID */}
                            <button className="btn btn-sm btn-ghost"
                              title={canExport ? "Download PDF" : "Upgrade to download PDF"}
                              onClick={e => downloadPdf(r, e)}>
                              <Icon name="download" size={13} />
                              {!canExport && <Icon name="lock" size={9} style={{marginLeft:2, opacity:.5}} />}
                            </button>
                            {/* Copy share link — gated; URL uses report ID (rep_*), never scan ID */}
                            <button className="btn btn-sm btn-ghost"
                              title={canShare ? "Copy share link" : "Upgrade to share reports"}
                              onClick={e => copyLink(r.id, vis, e)}>
                              <Icon name={copiedId === r.id ? "check" : "copy"} size={13} />
                              {!canShare && <Icon name="lock" size={9} style={{marginLeft:2, opacity:.5}} />}
                            </button>
                            <button className="btn btn-sm btn-ghost" title="Regenerate report"
                              onClick={e => e.stopPropagation()}>
                              <Icon name="refresh" size={13} />
                            </button>
                            {vis === "shared" && (
                              <button className="btn btn-sm btn-ghost" title="Revoke link"
                                onClick={e => setVis(r.id, "expired", e)}
                                style={{color:"var(--red)"}}>
                                <Icon name="x" size={13} />
                              </button>
                            )}
                            {/* View scan — only for reports with a linked scan; disabled for preview reports */}
                            {r.scanId && (
                              <button className="btn btn-sm btn-ghost" title="View scan"
                                onClick={e => { e.stopPropagation(); go("/scan/" + r.scanId); }}>
                                <Icon name="external-link" size={13} />
                              </button>
                            )}
                          </div>
                        </td>
                      </tr>

                      {/* Expanded share panel */}
                      {isExpanded && (
                        <tr>
                          <td colSpan={9} style={{padding:0}}>
                            <div style={{padding:"14px 18px", background:"var(--bg-2)", borderTop:"1px solid var(--line-1)", borderBottom:"1px solid var(--line-1)"}}>
                              <div style={{display:"flex", gap:20, flexWrap:"wrap"}}>

                                {/* Share link */}
                                <div style={{flex:"1 1 300px"}}>
                                  <div className="mono" style={{fontSize:10, letterSpacing:"0.1em", textTransform:"uppercase", color:"var(--fg-3)", marginBottom:8}}>Share link</div>
                                  {vis === "shared" ? (
                                    <div style={{display:"flex", gap:8, alignItems:"center"}}>
                                      <div style={{flex:1, display:"flex", alignItems:"center", gap:8, padding:"8px 12px", background:"var(--bg-1)", border:"1px solid var(--line-2)", borderRadius:"var(--r-sm)"}}>
                                        <Icon name="link" size={12} style={{color:"var(--fg-3)"}} />
                                        {/* Share URL uses the report ID (rep_*) — never the scan ID */}
                                        <span className="mono" style={{fontSize:12, color:"var(--fg-2)", overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>
                                          https://reliq.dev/r/{r.id}
                                        </span>
                                      </div>
                                      <button className="btn btn-sm" onClick={e => copyLink(r.id, vis, e)}>
                                        {copiedId === r.id ? <><Icon name="check" size={12}/> Copied</> : <><Icon name="copy" size={12}/> Copy</>}
                                      </button>
                                      <button className="btn btn-sm btn-ghost" style={{color:"var(--red)"}}
                                        onClick={e => setVis(r.id, "expired", e)}>
                                        <Icon name="x" size={12} /> Revoke
                                      </button>
                                    </div>
                                  ) : (
                                    <div style={{display:"flex", gap:8, alignItems:"center"}}>
                                      <span style={{fontSize:13, color:"var(--fg-3)"}}>
                                        {vis === "expired" ? "Link revoked — re-share to generate a new link." : "Set visibility to Shared to generate a public link."}
                                      </span>
                                      <button className="btn btn-sm" onClick={e => setVis(r.id, "shared", e)}>
                                        <Icon name="link" size={12} /> Share
                                      </button>
                                    </div>
                                  )}
                                </div>

                                {/* Visibility control */}
                                <div style={{flex:"0 0 auto"}}>
                                  <div className="mono" style={{fontSize:10, letterSpacing:"0.1em", textTransform:"uppercase", color:"var(--fg-3)", marginBottom:8}}>Visibility</div>
                                  <select
                                    value={vis}
                                    onChange={e => setVis(r.id, e.target.value)}
                                    style={{...selStyle, padding:"5px 10px", fontSize:12}}
                                    onClick={e => e.stopPropagation()}
                                  >
                                    <option value="private">Private</option>
                                    <option value="shared">Shared</option>
                                    <option value="expired">Expired</option>
                                  </select>
                                </div>

                                {/* Integrations */}
                                <div style={{flex:"1 1 240px"}}>
                                  <div className="mono" style={{fontSize:10, letterSpacing:"0.1em", textTransform:"uppercase", color:"var(--fg-3)", marginBottom:8}}>Send to</div>
                                  <div style={{display:"flex", gap:6}}>
                                    <button className="btn btn-sm" onClick={e => sendIntegration(r.id, e)}>
                                      <Icon name="webhook" size={12} /> Slack
                                    </button>
                                    <button className="btn btn-sm" onClick={e => sendIntegration(r.id, e)}>
                                      <Icon name="git-branch" size={12} /> Linear
                                    </button>
                                    <button className="btn btn-sm btn-ghost"
                                      onClick={() => {}}>
                                      <Icon name="refresh" size={12} /> Regenerate
                                    </button>
                                  </div>
                                </div>

                                {/* Registry — publish this report as a public Trust Profile */}
                                <div style={{flex:"1 1 220px"}}>
                                  <div className="mono" style={{fontSize:10, letterSpacing:"0.1em", textTransform:"uppercase", color:"var(--fg-3)", marginBottom:8}}>Registry</div>
                                  <button className="btn btn-sm" onClick={(e) => {
                                    e.stopPropagation();
                                    if (!canShare) { window.reliqGatePrompt?.show({ title:"Publishing requires Starter plan", description:"Upgrade to publish reports to the Reliq Registry.", planRequired:"starter", go }); return; }
                                    setPublishTarget(r);
                                  }}>
                                    <Icon name="globe" size={12} /> Publish to Registry
                                  </button>
                                </div>

                                {/* White-label note */}
                                {r.whiteLabelEnabled && (
                                  <div style={{flex:"1 1 200px"}}>
                                    <div className="mono" style={{fontSize:10, letterSpacing:"0.1em", textTransform:"uppercase", color:"var(--fg-3)", marginBottom:8}}>White-label</div>
                                    <span style={{fontSize:12, color:"var(--violet)"}}>Active — custom branding applied</span>
                                  </div>
                                )}
                              </div>
                            </div>
                          </td>
                        </tr>
                      )}
                    </React.Fragment>
                  );
                })}
              </tbody>
            </table>
            </div>
          </div>

          <div style={{display:"flex", alignItems:"center", justifyContent:"space-between", marginTop:14}}>
            <div className="mono" style={{fontSize:12, color:"var(--fg-3)"}}>
              Showing {filtered.length} of {reportsData.length} reports
            </div>
          </div>

          {publishTarget && window.RegistryPublishModal &&
            React.createElement(window.RegistryPublishModal, { report: publishTarget, go, onClose: () => setPublishTarget(null) })}
    </AuthLayout>
  );
};

Object.assign(window, { Reports });
