// ============================================
// Reliq — Public report share page
// Route: #/r/:reportId
// ============================================
//
// SECURITY RULES:
//   • reportId MUST start with rep_ or rep_preview_ — scn_ IDs are always rejected
//   • No auth required — this page is fully public/read-only
//   • Does NOT expose: API keys, workspace IDs, billing info, team members,
//     private comments, raw file paths, or any account-level data
//   • Uses LandingLayout (no sidebar, no account chrome)
//
// ID model:
//   Scan IDs:            scn_*         (never appear in share URLs)
//   Full report IDs:     rep_*
//   Preview report IDs:  rep_preview_*
//
// Share URL format: https://reliq.dev/r/{reportId}
// Hash route:       #/r/{reportId}

// ── Mock public report data ───────────────────────────────────────────────────
// Only safe, public-facing fields are included.
// No scan internals, workspace data, billing info, or API credentials.
const PUBLIC_REPORTS = {
  // Full report — Roamly 1.4.0
  "rep_2k8x": {
    id:           "rep_2k8x",
    type:         "full",
    app:          "Roamly",
    letters:      "R",
    grad:         "linear-gradient(135deg,#5B9DFF,#A78BFA)",
    bundle:       "com.roamly.app",
    version:      "1.4.0",
    stores:       ["Google Play", "App Store"],
    score:        78,
    verdict:      "needs_fixes",
    createdAt:    "2026-05-22",
    critCount:    3,
    warnCount:    8,
    infoCount:    5,
    summary:      "This app has issues that must be resolved before it can be listed on one or more of your target stores. Review the critical findings below and resubmit once addressed.",
    // Agent Readiness summary (platform expansion) — illustrative.
    agentReadiness: {
      score: 55, passed: 6, warnings: 1, missing: 5, total: 12,
      signals: [
        { id:"docs",             label:"Developer / documentation", status:"pass", recommendation:null },
        { id:"pricing",          label:"Pricing page",              status:"pass", recommendation:null },
        { id:"privacy",          label:"Privacy policy",            status:"pass", recommendation:null },
        { id:"terms",            label:"Terms of service",          status:"pass", recommendation:null },
        { id:"support",          label:"Support / contact",         status:"pass", recommendation:null },
        { id:"faq",              label:"FAQ / help",                status:"pass", recommendation:null },
        { id:"well_known_reliq", label:"/.well-known/reliq.json",   status:"warn", recommendation:"Add name plus at least 3 useful link fields (docs, api, pricing, security)." },
        { id:"llms_txt",         label:"llms.txt",                  status:"fail", recommendation:"Publish /llms.txt summarizing your product for LLM agents." },
        { id:"openapi",          label:"OpenAPI / Swagger spec",    status:"fail", recommendation:"Publish and link an OpenAPI spec." },
        { id:"security",         label:"Security page",             status:"fail", recommendation:"Publish a security page describing your posture." },
        { id:"status",           label:"Status page",               status:"fail", recommendation:"Publish a status page so agents can assess reliability." },
        { id:"api_docs",         label:"API documentation",         status:"fail", recommendation:"Expose API reference documentation." },
      ],
    },
    // API Readiness + Documentation Quality + Vendor Trust (platform expansion) — illustrative.
    apiScore: 78,
    docsScore: 82,
    vendorScore: 60,
    mcpScore: 55,
    complianceScore: 48,
    // Unified Reliq Trust Score — illustrative.
    trustScore: {
      overall: 72, grade: "Needs Work",
      pillars: [
        { key:"release",  label:"Release Readiness",     score:78, grade:"Good",       explanation:"Loads over HTTPS with valid status and metadata." },
        { key:"security", label:"Security",              score:90, grade:"Excellent",  explanation:"Strong HTTP security headers protecting users." },
        { key:"agent",    label:"Agent Readiness",       score:55, grade:"Risky",      explanation:"How easily AI agents can understand and use the product." },
        { key:"api",      label:"API Readiness",         score:78, grade:"Good",       explanation:"Developers and agents can integrate the API." },
        { key:"docs",     label:"Documentation Quality", score:82, grade:"Good",       explanation:"Docs are reasonably complete and usable." },
        { key:"vendor",   label:"Vendor Trust",          score:60, grade:"Needs Work", explanation:"Company identity, contact, pricing, support, security, legal, status, changelog, public proof, and refund clarity." },
        { key:"mcp",      label:"MCP Security",          score:55, grade:"Risky",      explanation:"How safely the product exposes MCP tools — discoverability, schemas, auth, scopes, audit, approvals, and absence of dangerous risks." },
        { key:"compliance", label:"Compliance Readiness", score:48, grade:"Risky",     explanation:"Privacy/legal readiness — policy, terms, cookies, retention, deletion, sub-processors, GDPR/CCPA/POPIA rights, AI disclosure, and a privacy contact." },
      ],
      topActions: [
        { severity:"WARNING", title:"Missing llms.txt",            recommendation:"Publish /llms.txt summarizing your product for LLM agents." },
        { severity:"WARNING", title:"Missing OpenAPI / Swagger spec", recommendation:"Publish and link an OpenAPI spec." },
        { severity:"WARNING", title:"Missing security page",       recommendation:"Publish a security page describing your posture." },
        { severity:"WARNING", title:"Missing status page",         recommendation:"Publish a status page so agents can assess reliability." },
        { severity:"INFO",    title:"Thin /.well-known/reliq.json", recommendation:"Add name plus at least 3 useful link fields." },
      ],
      badges: { agentReady:false, integrationReady:true, trustReady:false },
    },
    topCategories: [
      { name:"Privacy & Data Handling", crit:2, warn:3 },
      { name:"Permissions",             crit:1, warn:2 },
      { name:"SDK Compliance",          crit:0, warn:2 },
      { name:"Metadata Quality",        crit:0, warn:1 },
    ],
    storeReadiness: [
      { store:"Google Play", ready:false, blockers:2 },
      { store:"App Store",   ready:false, blockers:3 },
    ],
  },

  // Full report — QuickInvoice 2.1.3
  "rep_2k8w": {
    id:           "rep_2k8w",
    type:         "full",
    app:          "QuickInvoice",
    letters:      "Q",
    grad:         "linear-gradient(135deg,#F59E0B,#EF4444)",
    bundle:       "com.quickinvoice.android",
    version:      "2.1.3",
    stores:       ["Google Play"],
    score:        41,
    verdict:      "will_reject",
    createdAt:    "2026-05-22",
    critCount:    7,
    warnCount:    4,
    infoCount:    2,
    summary:      "This app is very likely to be rejected by the store review team. Multiple critical policy violations were detected. Significant remediation work is required before submission.",
    topCategories: [
      { name:"Financial Data Handling", crit:3, warn:1 },
      { name:"Privacy & Data Handling", crit:2, warn:2 },
      { name:"Permissions",             crit:1, warn:0 },
      { name:"SDK Compliance",          crit:1, warn:1 },
    ],
    storeReadiness: [
      { store:"Google Play", ready:false, blockers:7 },
    ],
  },

  // Full report — MoodBoard AI 0.9.2
  "rep_2k8v": {
    id:           "rep_2k8v",
    type:         "full",
    app:          "MoodBoard AI",
    letters:      "M",
    grad:         "linear-gradient(135deg,#A78BFA,#EF4444)",
    bundle:       "com.moodboard.ai",
    version:      "0.9.2",
    stores:       ["Google Play", "App Store"],
    score:        64,
    verdict:      "needs_fixes",
    createdAt:    "2026-05-22",
    critCount:    2,
    warnCount:    6,
    infoCount:    4,
    summary:      "This app has a number of issues that should be resolved before submission. While not all are immediate blockers, addressing them now reduces the risk of rejection and future policy strikes.",
    topCategories: [
      { name:"AI & Machine Learning",   crit:1, warn:2 },
      { name:"Privacy & Data Handling", crit:1, warn:2 },
      { name:"Content Policy",          crit:0, warn:1 },
      { name:"Metadata Quality",        crit:0, warn:1 },
    ],
    storeReadiness: [
      { store:"Google Play", ready:false, blockers:1 },
      { store:"App Store",   ready:false, blockers:2 },
    ],
  },

  // CI report — TidalFlow 3.0.1
  "rep_2k8u": {
    id:           "rep_2k8u",
    type:         "ci",
    app:          "TidalFlow",
    letters:      "T",
    grad:         "linear-gradient(135deg,#00D4AA,#5B9DFF)",
    bundle:       "com.tidalflow.app",
    version:      "3.0.1",
    stores:       ["App Store"],
    score:        88,
    verdict:      "pass",
    createdAt:    "2026-05-21",
    critCount:    0,
    warnCount:    2,
    infoCount:    3,
    summary:      "This build passed all critical policy checks and is ready for submission. Two low-priority warnings were noted; they do not block release but are worth addressing in a future update.",
    topCategories: [
      { name:"Privacy & Data Handling", crit:0, warn:1 },
      { name:"Metadata Quality",        crit:0, warn:1 },
    ],
    storeReadiness: [
      { store:"App Store", ready:true, blockers:0 },
    ],
  },
};

// ── Verdict helpers ───────────────────────────────────────────────────────────
const VERDICT_META = {
  pass:        { label:"Pass",        color:"var(--teal)",   icon:"check-circle" },
  needs_fixes: { label:"Needs fixes", color:"var(--yellow)",  icon:"alert-triangle" },
  will_reject: { label:"Will reject", color:"var(--red)",    icon:"x-circle" },
};

const STORE_ICON = {
  "Google Play": "▶",
  "App Store":   "",
};

// ── Type badge ────────────────────────────────────────────────────────────────
const TypeBadge = ({ type }) => {
  const meta = {
    full:    { label:"Full Report",    color:"var(--teal)",   bg:"var(--teal-bg)",   border:"rgba(0,212,170,0.3)" },
    preview: { label:"Preview Report", color:"var(--blue)",   bg:"var(--blue-bg)",   border:"rgba(91,157,255,0.3)" },
    ci:      { label:"CI Report",      color:"var(--violet)", bg:"var(--violet-bg)", border:"rgba(167,139,250,0.25)" },
  }[type] || { label:"Report", color:"var(--fg-2)", bg:"var(--bg-2)", border:"var(--line-2)" };

  return (
    <span style={{
      fontFamily:   "var(--font-mono)",
      fontSize:     10,
      fontWeight:   600,
      letterSpacing:"0.04em",
      textTransform:"uppercase",
      padding:      "2px 7px",
      borderRadius: 4,
      color:        meta.color,
      background:   meta.bg,
      border:       `1px solid ${meta.border}`,
      display:      "inline-block",
    }}>{meta.label}</span>
  );
};

// ── Score ring ────────────────────────────────────────────────────────────────
const ScoreRing = ({ score, verdict }) => {
  const color =
    verdict === "pass"        ? "var(--teal)"   :
    verdict === "will_reject" ? "var(--red)"    :
    "var(--yellow)";

  const r   = 38;
  const circ = 2 * Math.PI * r;
  const dash = (score / 100) * circ;

  return (
    <div style={{position:"relative", width:100, height:100, flexShrink:0}}>
      <svg width={100} height={100} style={{transform:"rotate(-90deg)"}}>
        <circle cx={50} cy={50} r={r} fill="none" stroke="var(--line-1)" strokeWidth={7} />
        <circle cx={50} cy={50} r={r} fill="none"
          stroke={color} strokeWidth={7}
          strokeDasharray={`${dash} ${circ - dash}`}
          strokeLinecap="round"
        />
      </svg>
      <div style={{
        position:"absolute", inset:0,
        display:"flex", flexDirection:"column",
        alignItems:"center", justifyContent:"center",
        lineHeight:1,
      }}>
        <div style={{fontFamily:"var(--font-display)", fontSize:26, fontWeight:700, color:"var(--fg-0)"}}>{score}</div>
        <div style={{fontSize:9, color:"var(--fg-3)", marginTop:2, fontFamily:"var(--font-mono)", textTransform:"uppercase", letterSpacing:"0.06em"}}>score</div>
      </div>
    </div>
  );
};

// ── Not found state ───────────────────────────────────────────────────────────
const ReportNotFound = ({ reportId, go, reason }) => (
  <LandingLayout go={go} pageTitle="Report not found">
    <div style={{maxWidth:560, margin:"80px auto 120px", textAlign:"center", padding:"0 24px"}}>
      <div style={{
        width:56, height:56, borderRadius:14,
        background:"var(--red-bg)", border:"1px solid rgba(239,68,68,0.25)",
        display:"flex", alignItems:"center", justifyContent:"center",
        margin:"0 auto 20px",
      }}>
        <Icon name="x-circle" size={24} style={{color:"var(--red)"}} />
      </div>
      <h1 style={{fontFamily:"var(--font-display)", fontSize:22, fontWeight:700, color:"var(--fg-0)", margin:"0 0 10px"}}>
        Report not found
      </h1>
      <p style={{fontSize:13.5, color:"var(--fg-2)", lineHeight:1.6, margin:"0 0 6px"}}>
        {reason || "The report you're looking for doesn't exist or the link may have expired."}
      </p>
      {reportId && (
        <div className="mono" style={{
          fontSize:11, color:"var(--fg-3)", margin:"12px auto 24px",
          background:"var(--bg-2)", border:"1px solid var(--line-1)",
          borderRadius:6, padding:"5px 12px", display:"inline-block",
        }}>
          {reportId}
        </div>
      )}
      <div style={{display:"flex", gap:10, justifyContent:"center", flexWrap:"wrap", marginTop:8}}>
        <button className="btn btn-primary" onClick={() => go("/")}>Go to Reliq</button>
        <button className="btn btn-secondary" onClick={() => go("/free-scan")}>Try a free scan</button>
      </div>
      <p style={{fontSize:11.5, color:"var(--fg-3)", marginTop:28, lineHeight:1.5}}>
        If you believe this is an error, ask the person who shared this link to re-share it.
      </p>
    </div>
  </LandingLayout>
);

// ── Preview report fallback ───────────────────────────────────────────────────
// Preview reports are generated from the free scan preview flow.
// Their public share pages show a limited, clearly-labelled preview.
const PreviewReportShare = ({ reportId, go }) => {
  // Demo data for the canonical preview report; generic fallback for unknown rep_preview_ IDs.
  const PREVIEW_MOCK = reportId === "rep_preview_9xk2m" ? {
    app:      "Roamly",
    letters:  "R",
    grad:     "linear-gradient(135deg,#5B9DFF,#A78BFA)",
    bundle:   "com.roamly.app",
    version:  "1.4.0",
    stores:   ["Google Play", "App Store"],
    score:    78,
    verdict:  "needs_fixes",
    createdAt:"2026-05-22",
    critCount:3,
    warnCount:8,
    infoCount:5,
    summary:  "This is a free scan preview. It shows a partial compliance summary for evaluation purposes only. A full report includes detailed per-finding analysis, fix guidance, and export options.",
  } : {
    app:      "App",
    letters:  "A",
    grad:     "linear-gradient(135deg,#5B9DFF,#A78BFA)",
    bundle:   "—",
    version:  "—",
    stores:   [],
    score:    0,
    verdict:  "needs_fixes",
    createdAt:"—",
    critCount:0,
    warnCount:0,
    infoCount:0,
    summary:  "This is a free scan preview. A full report includes detailed findings and fix guidance.",
  };

  const vm = VERDICT_META[PREVIEW_MOCK.verdict] || VERDICT_META.needs_fixes;

  return (
    <LandingLayout go={go} pageTitle={`Preview Report · ${PREVIEW_MOCK.app}`}>
      <div style={{maxWidth:700, margin:"40px auto 100px", padding:"0 20px"}}>
        {/* Preview notice banner */}
        <div style={{
          background:"var(--blue-bg)", border:"1px solid rgba(91,157,255,0.3)",
          borderRadius:10, padding:"12px 16px", marginBottom:24,
          display:"flex", alignItems:"center", gap:10,
          fontSize:12.5, color:"var(--blue)",
        }}>
          <Icon name="info" size={14} style={{flexShrink:0}} />
          <span>
            <strong>Free preview report</strong> — This is a limited summary generated without an account.{" "}
            <span style={{cursor:"pointer", textDecoration:"underline"}} onClick={() => go("/free-scan")}>
              Run a full scan
            </span>{" "}
            for detailed findings, fix guidance, and PDF export.
          </span>
        </div>

        {/* Header */}
        <div style={{display:"flex", alignItems:"flex-start", gap:16, marginBottom:28}}>
          <div style={{
            width:52, height:52, borderRadius:12, background:PREVIEW_MOCK.grad,
            display:"flex", alignItems:"center", justifyContent:"center",
            fontFamily:"var(--font-display)", fontWeight:700, fontSize:20, color:"#fff",
            flexShrink:0,
          }}>{PREVIEW_MOCK.letters}</div>

          <div style={{flex:1, minWidth:0}}>
            <div style={{display:"flex", alignItems:"center", gap:8, flexWrap:"wrap", marginBottom:6}}>
              <h1 style={{fontFamily:"var(--font-display)", fontSize:20, fontWeight:700, color:"var(--fg-0)", margin:0}}>
                {PREVIEW_MOCK.app}
              </h1>
              <TypeBadge type="preview" />
            </div>
            <div className="mono" style={{fontSize:11, color:"var(--fg-3)", marginBottom:3}}>{PREVIEW_MOCK.bundle}</div>
            {PREVIEW_MOCK.version !== "—" && (
              <div className="mono" style={{fontSize:10.5, color:"var(--fg-3)"}}>
                v{PREVIEW_MOCK.version} · {PREVIEW_MOCK.stores.join(", ")}
              </div>
            )}
          </div>

          <ScoreRing score={PREVIEW_MOCK.score} verdict={PREVIEW_MOCK.verdict} />
        </div>

        {/* Verdict */}
        <div style={{
          display:"flex", alignItems:"center", gap:10, padding:"14px 16px",
          background:"var(--bg-2)", border:"1px solid var(--line-1)", borderRadius:10, marginBottom:20,
        }}>
          <Icon name={vm.icon} size={18} style={{color:vm.color, flexShrink:0}} />
          <div>
            <div style={{fontWeight:600, fontSize:13.5, color:vm.color}}>{vm.label}</div>
            <div style={{fontSize:12, color:"var(--fg-2)", marginTop:2, lineHeight:1.5}}>{PREVIEW_MOCK.summary}</div>
          </div>
        </div>

        {/* Finding counts */}
        <div style={{display:"grid", gridTemplateColumns:"repeat(3,1fr)", gap:10, marginBottom:28}}>
          {[
            { label:"Critical", count:PREVIEW_MOCK.critCount, color:"var(--red)",    bg:"var(--red-bg)",    border:"rgba(239,68,68,0.2)" },
            { label:"Warning",  count:PREVIEW_MOCK.warnCount, color:"var(--yellow)", bg:"var(--yellow-bg)", border:"rgba(234,179,8,0.2)" },
            { label:"Info",     count:PREVIEW_MOCK.infoCount, color:"var(--blue)",   bg:"var(--blue-bg)",   border:"rgba(91,157,255,0.2)" },
          ].map(f => (
            <div key={f.label} style={{
              background:f.bg, border:`1px solid ${f.border}`, borderRadius:10,
              padding:"14px 16px", textAlign:"center",
            }}>
              <div style={{fontFamily:"var(--font-display)", fontSize:28, fontWeight:700, color:f.color}}>{f.count}</div>
              <div style={{fontSize:11, color:"var(--fg-2)", marginTop:2}}>{f.label}</div>
            </div>
          ))}
        </div>

        {/* CTA */}
        <div style={{
          background:"var(--bg-2)", border:"1px solid var(--line-1)", borderRadius:10,
          padding:"24px", textAlign:"center",
        }}>
          <div style={{fontFamily:"var(--font-display)", fontSize:15, fontWeight:600, color:"var(--fg-0)", marginBottom:8}}>
            See the full compliance report
          </div>
          <div style={{fontSize:12.5, color:"var(--fg-2)", marginBottom:16, lineHeight:1.6}}>
            Full reports include per-finding analysis, fix recommendations, store readiness breakdown, and PDF export.
          </div>
          <div style={{display:"flex", gap:10, justifyContent:"center", flexWrap:"wrap"}}>
            <button className="btn btn-primary" onClick={() => go("/free-scan")}>Run a free scan</button>
            <button className="btn btn-secondary" onClick={() => go("/signup")}>Create account</button>
          </div>
        </div>

        {/* Footer */}
        <div style={{
          marginTop:32, paddingTop:20, borderTop:"1px solid var(--line-1)",
          display:"flex", alignItems:"center", justifyContent:"space-between", flexWrap:"wrap", gap:8,
        }}>
          <div className="mono" style={{fontSize:10, color:"var(--fg-3)"}}>{reportId}</div>
          <div style={{fontSize:11, color:"var(--fg-3)"}}>Generated by <span style={{color:"var(--fg-2)", fontWeight:600}}>Reliq</span></div>
        </div>
      </div>
    </LandingLayout>
  );
};

// ── Main public report share page ─────────────────────────────────────────────
// Map the backend public-report response → the shape this view renders.
const RVERDICT = { PASS: "pass", WARNING: "needs_fixes", FAIL: "will_reject" };
function mapPublicReport(api) {
  const s = api.summary || {};
  return {
    id: api.id, type: (api.type || "full").toLowerCase(),
    app: "Trust Report", letters: "R", grad: "linear-gradient(135deg,#5B9DFF,#A78BFA)",
    bundle: api.id, version: "—", stores: [],
    score: api.score, verdict: RVERDICT[api.verdict] || "needs_fixes",
    createdAt: (api.generatedAt || "").slice(0, 10),
    critCount: s.criticalCount || 0, warnCount: s.warningCount || 0, infoCount: s.infoCount || 0,
    storeReadiness: s.storeReadiness || {}, topCategories: s.categories || [],
    agentReadiness: s.agentReadiness || null,
    trustScore: api.trustScore || null,
    agentScore: api.agentScore, apiScore: api.apiScore, docsScore: api.docsScore,
    vendorScore: api.vendorScore, mcpScore: api.mcpScore, complianceScore: api.complianceScore,
    summary: "Public Reliq Trust report — Trust Score, pillar breakdown, and findings.",
    findings: api.findings || [],
  };
}

const ReportShare = ({ go }) => {
  // Extract reportId from the current hash route: #/r/:reportId
  const routeRaw = window.location.hash.replace(/^#\/?/, "");
  const reportId = routeRaw.startsWith("r/") ? routeRaw.slice(2).split("?")[0].trim() : "";

  const isScn = window.reliqIds ? window.reliqIds.isScanId(reportId) : reportId.startsWith("scn_");
  const isRep = window.reliqIds ? window.reliqIds.isReportId(reportId) : reportId.startsWith("rep_");
  const isPreview = window.reliqIds ? window.reliqIds.isPreviewReportId(reportId) : reportId.startsWith("rep_preview_");
  const wantFetch = !!reportId && !isScn && isRep && !isPreview;

  // ── Fetch the public report from the backend (hooks first) ──────────────────
  const [r, setR] = React.useState(null);
  const [loading, setLoading] = React.useState(wantFetch);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    if (!wantFetch) { setLoading(false); return; }
    let cancelled = false;
    setLoading(true); setError(null); setR(null);
    window.reliqReportsApi.getPublicReport(reportId)
      .then((api) => { if (!cancelled) setR(mapPublicReport(api)); })
      .catch((e) => { if (!cancelled) setError(e); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [reportId]);

  // ── Validation guards ───────────────────────────────────────────────────────
  if (!reportId) return <ReportNotFound reportId={null} go={go} reason="No report ID was provided in the URL." />;
  if (isScn) return <ReportNotFound reportId={reportId} go={go} reason={`"${reportId}" is a scan ID, not a report ID. Share links must use report IDs (rep_…).`} />;
  if (!isRep) return <ReportNotFound reportId={reportId} go={go} reason="This link does not contain a valid report ID." />;
  if (isPreview) return <PreviewReportShare reportId={reportId} go={go} />;

  if (loading) {
    return (
      <LandingLayout go={go} pageTitle="Loading report…">
        <div style={{maxWidth:700, margin:"80px auto", padding:"0 20px", textAlign:"center", color:"var(--fg-3)", fontSize:13}}>Loading the public report…</div>
      </LandingLayout>
    );
  }
  if (error || !r) {
    const notShared = error && error.status === 404;
    return <ReportNotFound reportId={reportId} go={go} reason={notShared ? "This report is not publicly shared, or the share link has been disabled." : `The report API returned an error (${error?.code || "error"}).`} />;
  }

  // ── Render ─────────────────────────────────────────────────────────────────
  const vm = VERDICT_META[r.verdict] || VERDICT_META.needs_fixes;

  return (
    <LandingLayout go={go} pageTitle={`${r.app} Compliance Report`}>
      <div style={{maxWidth:700, margin:"40px auto 100px", padding:"0 20px"}}>

        {/* ── Header ── */}
        <div style={{display:"flex", alignItems:"flex-start", gap:16, marginBottom:28}}>
          <div style={{
            width:56, height:56, borderRadius:13, background:r.grad,
            display:"flex", alignItems:"center", justifyContent:"center",
            fontFamily:"var(--font-display)", fontWeight:700, fontSize:22, color:"#fff",
            flexShrink:0,
          }}>{r.letters}</div>

          <div style={{flex:1, minWidth:0}}>
            <div style={{display:"flex", alignItems:"center", gap:8, flexWrap:"wrap", marginBottom:6}}>
              <h1 style={{fontFamily:"var(--font-display)", fontSize:21, fontWeight:700, color:"var(--fg-0)", margin:0}}>
                {r.app}
              </h1>
              <TypeBadge type={r.type} />
            </div>
            <div className="mono" style={{fontSize:11, color:"var(--fg-3)", marginBottom:3}}>{r.bundle}</div>
            <div className="mono" style={{fontSize:10.5, color:"var(--fg-3)"}}>
              v{r.version} · {r.stores.join(", ")}
            </div>
            <div style={{marginTop:6, display:"flex", gap:8, flexWrap:"wrap", alignItems:"center"}}>
              <span className="mono" style={{fontSize:10, color:"var(--fg-3)"}}>{r.id}</span>
              <span style={{color:"var(--line-2)", fontSize:10}}>·</span>
              <span style={{fontSize:11, color:"var(--fg-3)"}}>{r.createdAt}</span>
            </div>
          </div>

          <ScoreRing score={r.score} verdict={r.verdict} />
        </div>

        {/* ── Verdict bar ── */}
        <div style={{
          display:"flex", alignItems:"center", gap:10, padding:"14px 18px",
          background:"var(--bg-2)", border:"1px solid var(--line-1)", borderRadius:10, marginBottom:20,
        }}>
          <Icon name={vm.icon} size={20} style={{color:vm.color, flexShrink:0}} />
          <div>
            <div style={{fontWeight:600, fontSize:14, color:vm.color}}>{vm.label}</div>
            <div style={{fontSize:12.5, color:"var(--fg-2)", marginTop:3, lineHeight:1.55}}>{r.summary}</div>
          </div>
        </div>

        {/* ── Finding counts ── */}
        <div style={{display:"grid", gridTemplateColumns:"repeat(3,1fr)", gap:10, marginBottom:24}}>
          {[
            { label:"Critical", count:r.critCount, color:"var(--red)",    bg:"var(--red-bg)",    border:"rgba(239,68,68,0.2)" },
            { label:"Warning",  count:r.warnCount, color:"var(--yellow)", bg:"var(--yellow-bg)", border:"rgba(234,179,8,0.2)" },
            { label:"Info",     count:r.infoCount, color:"var(--blue)",   bg:"var(--blue-bg)",   border:"rgba(91,157,255,0.2)" },
          ].map(f => (
            <div key={f.label} style={{
              background:f.bg, border:`1px solid ${f.border}`, borderRadius:10,
              padding:"16px", textAlign:"center",
            }}>
              <div style={{fontFamily:"var(--font-display)", fontSize:30, fontWeight:700, color:f.color, lineHeight:1}}>{f.count}</div>
              <div style={{fontSize:11.5, color:"var(--fg-2)", marginTop:4}}>{f.label}</div>
            </div>
          ))}
        </div>

        {/* ── Top finding categories ── */}
        {r.topCategories && r.topCategories.length > 0 && (
          <div style={{
            background:"var(--bg-2)", border:"1px solid var(--line-1)", borderRadius:10,
            padding:"16px 18px", marginBottom:20,
          }}>
            <div style={{fontWeight:600, fontSize:13, color:"var(--fg-0)", marginBottom:14}}>Finding categories</div>
            <div style={{display:"flex", flexDirection:"column", gap:10}}>
              {r.topCategories.map(cat => (
                <div key={cat.name} style={{display:"flex", alignItems:"center", gap:10}}>
                  <div style={{flex:1, fontSize:12.5, color:"var(--fg-1)"}}>{cat.name}</div>
                  <div style={{display:"flex", gap:6, flexShrink:0}}>
                    {cat.crit > 0 && (
                      <span style={{
                        fontFamily:"var(--font-mono)", fontSize:10, fontWeight:600,
                        padding:"2px 6px", borderRadius:4,
                        color:"var(--red)", background:"var(--red-bg)", border:"1px solid rgba(239,68,68,0.2)",
                      }}>{cat.crit} crit</span>
                    )}
                    {cat.warn > 0 && (
                      <span style={{
                        fontFamily:"var(--font-mono)", fontSize:10, fontWeight:600,
                        padding:"2px 6px", borderRadius:4,
                        color:"var(--yellow)", background:"var(--yellow-bg)", border:"1px solid rgba(234,179,8,0.2)",
                      }}>{cat.warn} warn</span>
                    )}
                    {cat.crit === 0 && cat.warn === 0 && (
                      <span style={{fontFamily:"var(--font-mono)", fontSize:10, color:"var(--fg-3)"}}>—</span>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* ── Reliq Trust Score (unified) ── */}
        {r.trustScore && (
          <div style={{
            background:"var(--bg-2)", border:"1px solid var(--line-1)", borderRadius:10,
            padding:"16px 18px", marginBottom:20,
          }}>
            <div style={{display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:10}}>
              <div style={{fontWeight:600, fontSize:13, color:"var(--fg-0)"}}>Reliq Trust Score</div>
              <div style={{fontFamily:"var(--font-mono)", fontSize:13, fontWeight:600, color:"var(--fg-0)"}}>
                {r.trustScore.overall}<span style={{color:"var(--fg-3)", fontSize:11}}>/100</span>
                <span style={{color:"var(--fg-2)", fontSize:11, marginLeft:6}}>{r.trustScore.grade}</span>
              </div>
            </div>

            {/* Badges */}
            {(() => {
              const b = r.trustScore.badges || {};
              const badges = [];
              if (b.trustReady)       badges.push("Trust-ready");
              if (b.agentReady)       badges.push("Agent-ready");
              if (b.integrationReady) badges.push("Integration-ready");
              if (badges.length === 0) return null;
              return (
                <div style={{display:"flex", gap:6, flexWrap:"wrap", marginBottom:14}}>
                  {badges.map(label => (
                    <span key={label} style={{
                      fontFamily:"var(--font-mono)", fontSize:9.5, fontWeight:600, letterSpacing:"0.04em",
                      padding:"2px 7px", borderRadius:4, color:"var(--teal)", background:"var(--teal-bg)",
                      border:"1px solid rgba(0,212,170,0.25)", textTransform:"uppercase",
                    }}>{label}</span>
                  ))}
                </div>
              );
            })()}

            {/* Five pillars */}
            <div style={{display:"flex", flexDirection:"column", gap:10}}>
              {r.trustScore.pillars.map(p => (
                <div key={p.key} style={{display:"flex", alignItems:"flex-start", gap:10}}>
                  <div style={{
                    fontFamily:"var(--font-mono)", fontSize:13, fontWeight:600, minWidth:48, textAlign:"right",
                    color:p.score>=75?"var(--teal)":p.score>=60?"var(--yellow)":"var(--red)",
                  }}>{p.score}</div>
                  <div style={{flex:1, minWidth:0}}>
                    <div style={{display:"flex", alignItems:"center", gap:8}}>
                      <span style={{fontSize:12.5, color:"var(--fg-1)", fontWeight:500}}>{p.label}</span>
                      <span className="mono" style={{fontSize:10, color:"var(--fg-3)"}}>{p.grade}</span>
                    </div>
                    <div style={{fontSize:11.5, color:"var(--fg-3)", marginTop:2, lineHeight:1.5}}>{p.explanation}</div>
                  </div>
                </div>
              ))}
            </div>

            {/* Top actions */}
            {r.trustScore.topActions && r.trustScore.topActions.length > 0 && (
              <div style={{marginTop:16, paddingTop:14, borderTop:"1px solid var(--line-1)"}}>
                <div style={{fontWeight:600, fontSize:12.5, color:"var(--fg-0)", marginBottom:10}}>
                  Top {r.trustScore.topActions.length} actions to improve your score
                </div>
                <ol style={{margin:0, paddingLeft:18, display:"flex", flexDirection:"column", gap:8}}>
                  {r.trustScore.topActions.map((a, i) => (
                    <li key={i} style={{fontSize:12, color:"var(--fg-1)", lineHeight:1.5}}>
                      <span style={{fontWeight:500}}>{a.title}</span>
                      {a.recommendation && <span style={{color:"var(--fg-3)"}}> — {a.recommendation}</span>}
                    </li>
                  ))}
                </ol>
              </div>
            )}
          </div>
        )}

        {/* ── Agent Readiness ── */}
        {r.agentReadiness && (
          <div style={{
            background:"var(--bg-2)", border:"1px solid var(--line-1)", borderRadius:10,
            padding:"16px 18px", marginBottom:20,
          }}>
            <div style={{display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:4}}>
              <div style={{display:"flex", alignItems:"center", gap:8}}>
                <span style={{fontWeight:600, fontSize:13, color:"var(--fg-0)"}}>Agent Readiness</span>
                {r.agentReadiness.score >= 75 && (
                  <span title="Agent readiness ≥ 75" style={{
                    fontFamily:"var(--font-mono)", fontSize:9.5, fontWeight:600, letterSpacing:"0.04em",
                    padding:"1px 6px", borderRadius:4, color:"var(--teal)", background:"var(--teal-bg)",
                    border:"1px solid rgba(0,212,170,0.25)", textTransform:"uppercase",
                  }}>Agent-ready</span>
                )}
              </div>
              <div style={{fontFamily:"var(--font-mono)", fontSize:13, fontWeight:600, color:"var(--fg-0)"}}>
                {r.agentReadiness.score}<span style={{color:"var(--fg-3)", fontSize:11}}>/100</span>
              </div>
            </div>
            <div style={{fontSize:11.5, color:"var(--fg-2)", marginBottom:8, lineHeight:1.5}}>
              How easily AI agents can understand, evaluate, and use this product.
            </div>
            <div className="mono" style={{fontSize:11, color:"var(--fg-3)", marginBottom:14}}>
              {r.agentReadiness.passed} passed · {r.agentReadiness.warnings} warnings · {r.agentReadiness.missing} missing
              {r.apiScore != null && <> · API {r.apiScore}/100</>}
              {r.docsScore != null && <> · Docs {r.docsScore}/100</>}
            </div>
            <div style={{display:"flex", flexDirection:"column", gap:8}}>
              {r.agentReadiness.signals.map(sig => {
                const meta = sig.status === "pass"
                  ? { color:"var(--teal)", bg:"var(--teal-bg)", label:"PASS" }
                  : sig.status === "warn"
                  ? { color:"var(--yellow)", bg:"var(--yellow-bg)", label:"WARN" }
                  : { color:"var(--red)", bg:"var(--red-bg)", label:"MISSING" };
                return (
                  <div key={sig.id} style={{display:"flex", alignItems:"flex-start", gap:10}}>
                    <span style={{
                      fontFamily:"var(--font-mono)", fontSize:9, fontWeight:600, letterSpacing:"0.04em",
                      padding:"2px 6px", borderRadius:4, flexShrink:0, minWidth:58, textAlign:"center",
                      color:meta.color, background:meta.bg, border:`1px solid ${meta.color}33`,
                    }}>{meta.label}</span>
                    <div style={{flex:1, minWidth:0}}>
                      <div style={{fontSize:12.5, color:"var(--fg-1)", fontWeight:500}}>{sig.label}</div>
                      {sig.status !== "pass" && sig.recommendation && (
                        <div style={{fontSize:11.5, color:"var(--fg-3)", marginTop:2, lineHeight:1.5}}>{sig.recommendation}</div>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* ── Store readiness ── */}
        {r.storeReadiness && r.storeReadiness.length > 0 && (
          <div style={{
            background:"var(--bg-2)", border:"1px solid var(--line-1)", borderRadius:10,
            padding:"16px 18px", marginBottom:24,
          }}>
            <div style={{fontWeight:600, fontSize:13, color:"var(--fg-0)", marginBottom:14}}>Store readiness</div>
            <div style={{display:"flex", flexDirection:"column", gap:10}}>
              {r.storeReadiness.map(s => (
                <div key={s.store} style={{
                  display:"flex", alignItems:"center", gap:12, padding:"10px 14px",
                  background:"var(--bg-1)", border:"1px solid var(--line-1)", borderRadius:8,
                }}>
                  <div style={{fontSize:11, color:"var(--fg-3)", width:12, textAlign:"center"}}>{STORE_ICON[s.store] || "◆"}</div>
                  <div style={{flex:1, fontSize:12.5, color:"var(--fg-1)", fontWeight:500}}>{s.store}</div>
                  {s.ready ? (
                    <div style={{display:"flex", alignItems:"center", gap:5, color:"var(--teal)", fontSize:12}}>
                      <Icon name="check-circle" size={13} />
                      <span style={{fontWeight:500}}>Ready</span>
                    </div>
                  ) : (
                    <div style={{display:"flex", alignItems:"center", gap:5, color:"var(--red)", fontSize:12}}>
                      <Icon name="x-circle" size={13} />
                      <span style={{fontWeight:500}}>{s.blockers} blocker{s.blockers !== 1 ? "s" : ""}</span>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        {/* ── Read-only notice ── */}
        <div style={{
          background:"var(--bg-2)", border:"1px solid var(--line-1)", borderRadius:8,
          padding:"10px 14px", marginBottom:28,
          display:"flex", alignItems:"center", gap:8,
          fontSize:11.5, color:"var(--fg-3)",
        }}>
          <Icon name="lock" size={12} style={{flexShrink:0}} />
          <span>
            This is a read-only shared report. Account details, API keys, and workspace information are never included in shared links.
          </span>
        </div>

        {/* ── CTA ── */}
        <div style={{
          background:"var(--bg-2)", border:"1px solid var(--line-1)", borderRadius:10,
          padding:"20px", textAlign:"center",
        }}>
          <div style={{fontFamily:"var(--font-display)", fontSize:14, fontWeight:600, color:"var(--fg-0)", marginBottom:6}}>
            Run your own compliance scan
          </div>
          <div style={{fontSize:12.5, color:"var(--fg-2)", marginBottom:14, lineHeight:1.5}}>
            Reliq checks your app for policy violations before you submit to the store.
          </div>
          <div style={{display:"flex", gap:10, justifyContent:"center", flexWrap:"wrap"}}>
            <button className="btn btn-primary" onClick={() => go("/free-scan")}>Try for free</button>
            <button className="btn btn-secondary" onClick={() => go("/signup")}>Create account</button>
          </div>
        </div>

        {/* ── Footer ── */}
        <div style={{
          marginTop:32, paddingTop:20, borderTop:"1px solid var(--line-1)",
          display:"flex", alignItems:"center", justifyContent:"space-between", flexWrap:"wrap", gap:8,
        }}>
          <div className="mono" style={{fontSize:10, color:"var(--fg-3)"}}>{r.id}</div>
          <div style={{fontSize:11, color:"var(--fg-3)"}}>
            Generated by{" "}
            <span
              style={{color:"var(--fg-2)", fontWeight:600, cursor:"pointer"}}
              onClick={() => go("/")}
            >Reliq</span>
          </div>
        </div>

      </div>
    </LandingLayout>
  );
};

// Export to window for use in index.html router
Object.assign(window, { ReportShare });
