PageSourceSearch

https://valuethropy.ai/assets/DataLayerPage-BO06FbKi.js

js valuethropy.ai collected 2026-10-05 15:01:56 UTC 150,990 bytes, 63 lines download raw bytes

1import{j as e,r as v,a as He,u as rt,b as kt}from"./vendor-query-CVWBAYQN.js";import{B as K,L as Ae,c as G,l as Ue,G as Dt,aJ as Jt,C as be,b as je,d as ve,e as we,f as ke,v as st,I as it,ah as hs,S as Nt,h as Ne,s as B,aw as qe,H as sn,bz as nn,a1 as fs,n as le,K as an,A as rn,P as Wt}from"./index-DJLejKcN.js";import{P as ht}from"./PageShell-DDy5DWJ7.js";import{T as on}from"./ToolLoadingState-B6nB0p0M.js";import{E as Le}from"./ErrorState-De3uL_pY.js";import{T as Gt}from"./ToolEmptyState-DVqvBD_X.js";import{o as ot,b as Je,p as xs,q as ln,r as cn,s as ft,t as dn,v as un,w as mn,x as pn,y as hn,A as lt,u as ct,z as Qt}from"./useAssertions-CSG4x_JW.js";import{u as dt}from"./useDocuments-HBO-p2kI.js";import{u as gs}from"./useOutputs-Cj92hpm8.js";import{b as Pt}from"./useKPIs-1s1-W_Ho.js";import{u as ys}from"./useInitiatives-CCXC_-mx.js";import{u as ut}from"./useRisks-nSvEWL3K.js";import{H as xt}from"./HeroToolbarButton-BuXzhSGl.js";import{B as ie}from"./badge-CtvL8b_T.js";import{T as fn,a as xn,b as gn,c as De}from"./tabs-qNXxdrrk.js";import{F as yn}from"./FeaturePreview-Cb6GecCv.js";import{ae as Be,O as Rt,f as bs,de as bn,S as Ke,c as jn,be as vn,w as wn,bN as Yt,L as pe,u as kn,df as Nn,as as _n,ak as Sn,aR as mt,U as Tt,x as Cn,dg as js,cn as Mn,b as Ot,b3 as $t,cM as En,T as An,m as Ln,ax as vs,W as Dn,aw as Pn,aj as ws,b7 as Rn,aQ as Tn,bS as On,D as ks,a_ as $n,V as Ns,aG as zn,X as In,aM as Fn,dh as _t,G as Bn,di as qn,z as Kn,bJ as Vn,k as Ve,Y as Hn,d as Un,a5 as _s,A as Jn,ad as Wn,a7 as Gn,dj as Qn,dk as Yn,af as Zn}from"./vendor-icons-BJ-Rh-HN.js";import{S as Xn}from"./SchematicFrame-CqxcW1O7.js";import{C as ea}from"./CountChip-DLuSDc1h.js";import{S as ta,a as sa}from"./SchematicMotion-DekALH8l.js";import{u as na,a as aa,E as ra}from"./useBackgroundBulkReview-Ck289whA.js";import{E as St}from"./ExportFormatButton-ClLJ1XtD.js";import{C as Ss,a as Cs,b as Ms}from"./collapsible-Cx1cM-fT.js";import{S as ia}from"./switch-DK1JlUxA.js";import{A as oa,a as la,b as ca,c as da,f as ua,d as ma,e as pa,g as ha}from"./alert-dialog-C7f-X0uR.js";import{S as Se,a as Ce,b as Me,c as Ee,d as X}from"./select-BvxMsBnz.js";import{T as zt,a as It,b as re,c as ge,d as Ft,e as ee}from"./table-Cgzn4dty.js";import{e as Es,a as fa,r as Te,d as As}from"./exportHelpers-CIU_06FO.js";import{u as xa}from"./useDecisions-DZFZ82Zp.js";import{P as Ct}from"./progress-rdO3yYS2.js";import{J as pt}from"./jszip.min-BsVKgAUs.js";import{f as Ls}from"./useFinancialAssumptions-BxnMidAF.js";import{v as ga}from"./vcpConstants-qZroZsGr.js";import{f as Ds}from"./vcpServerPack-nEuP9Hcv.js";import{v as ya}from"./vcpPackMappers-CRMJm4cv.js";import{e as Ps}from"./useActivityLog-BORE_R3Z.js";import{F as me}from"./FileTypeIcon-GYuVn306.js";import{a as Mt,f as Rs}from"./vendor-datefns-BmjLTXHn.js";import{u as ba}from"./useEvidenceHealth-BKDqDkTO.js";import{A as Ts,a as Os,b as $s}from"./alert-CvCQHsjB.js";import{g as Zt}from"./activityConstants-BjKresWa.js";import{r as ja,u as va}from"./xlsx-DLNWaC59.js";import{m as nt}from"./vendor-motion-8aOieDHp.js";import{u as wa,p as ka,S as Na}from"./useCampaignSubjects-CTq4vko9.js";import{f as Xt,n as _a}from"./ebitdaTypes-xTNTyCWL.js";import{u as Sa}from"./useMarketLayerItems-CjyxKqju.js";import"./vendor-supabase-DhFQUKws.js";import"./HeroBackdrop-CytUHOCH.js";import"./DrawerHero-CNs4a2F0.js";import"./HelpButton-C88-Kq3v.js";import"./HelpOverlayContext-vHZe9ebM.js";import"./chunkArray-DMouHHwM.js";import"./aiErrorTaxonomy-DleRkU-P.js";import"./edgeInvokeFailureBody-AV6SLBoL.js";import"./useAIInvoke-LNVUoQSQ.js";import"./useAIQuota-BYj0JUQV.js";import"./GoldButton-BIVXRXfD.js";import"./index-CYh4Bhy3.js";import"./index-DuqMQ53p.js";import"./drawerAccent-D0n61eR-.js";import"./OpenLink-BTzZeUnT.js";import"./index-CfMy7Hxv.js";import"./index-BdQq_4o_.js";import"./_commonjs-dynamic-modules-TDtrdbi3.js";import"./types--Y47UT_S.js";import"./useValueBridge-Cv6hd5yA.js";import"./leverClass-_abxq6kL.js";import"./industryBenchmarks-BmEN5e0d.js";import"./accentTone-B1MD0lV9.js";import"./currency-BxZBgS5P.js";function Ca(){return e.jsxs("svg",{viewBox:"0 0 420 180",className:"mx-auto h-auto w-full max-w-lg text-muted-foreground","aria-hidden":!0,
1children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"dl-edge",x1:"0%",y1:"0%",x2:"100%",y2:"0%",children:[e.jsx("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:"0.25"}),e.jsx("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:"0.5"})]})}),e.jsxs("g",{stroke:"url(#dl-edge)",strokeWidth:"1.5",fill:"none",children:[e.jsx("path",{d:"M 60 90 L 120 90"}),e.jsx("path",{d:"M 200 90 L 260 90"}),e.jsx("path",{d:"M 340 90 L 380 55"}),e.jsx("path",{d:"M 340 90 L 380 125"})]}),e.jsx("rect",{x:"20",y:"65",width:"80",height:"50",rx:"8",className:"fill-navy/8 stroke-navy/35 dark:fill-primary/10 dark:stroke-primary/40",strokeWidth:"1.5"}),e.jsx("text",{x:"60",y:"88",textAnchor:"middle",className:"fill-foreground text-[11px] font-semibold",children:"Sources"}),e.jsx("text",{x:"60",y:"104",textAnchor:"middle",className:"fill-muted-foreground text-[8px]",children:"docs · insights"}),e.jsx("rect",{x:"130",y:"60",width:"90",height:"60",rx:"10",className:"fill-oposgold/12 stroke-oposgold/45",strokeWidth:"1.5"}),e.jsx("text",{x:"175",y:"88",textAnchor:"middle",className:"fill-foreground text-[11px] font-semibold",children:"Truth flow"}),e.jsx("text",{x:"175",y:"104",textAnchor:"middle",className:"fill-muted-foreground text-[8px]",children:"campaign graph"}),e.jsx("rect",{x:"270",y:"65",width:"90",height:"50",rx:"8",className:"fill-navy/8 stroke-navy/40",strokeWidth:"1.5"}),e.jsx("text",{x:"315",y:"88",textAnchor:"middle",className:"fill-foreground text-[11px] font-semibold",children:"Schema"}),e.jsx("text",{x:"315",y:"104",textAnchor:"middle",className:"fill-muted-foreground text-[8px]",children:"reference"}),e.jsx("rect",{x:"350",y:"35",width:"70",height:"36",rx:"6",className:"fill-muted/40 stroke-border",strokeWidth:"1"}),e.jsx("text",{x:"385",y:"56",textAnchor:"middle",className:"fill-foreground text-[9px] font-medium",children:"Exports"}),e.jsx("rect",{x:"350",y:"109",width:"70",height:"36",rx:"6",className:"fill-muted/40 stroke-border",strokeWidth:"1"}),e.jsx("text",{x:"385",y:"130",textAnchor:"middle",className:"fill-foreground text-[9px] font-medium",children:"Governance"})]})}function Ma(){return e.jsx(yn,{icon:Be,accent:"gold",title:"Data Layer workspace",tagline:e.jsxs("span",{className:"block space-y-3",children:[e.jsx("span",{className:"block",children:"Enterprise-grade introspection into your campaign: how evidence flows into insights, initiatives, KPIs, and outputs - plus schema reference and export surfaces for governance and audit. Built for Enterprise teams who need a controlled view of truth, not a consumer dashboard."}),e.jsx("span",{className:"block text-sm font-medium text-foreground",children:"What you unlock"}),e.jsxs("ul",{className:"list-disc space-y-1 pl-4 text-sm text-muted-foreground",children:[e.jsx("li",{children:"Campaign inspector - insights, evidence links, batch review"}),e.jsx("li",{children:"Export suite - full ZIP, themed bundles, CSVs"}),e.jsx("li",{children:"Quality diagnostics - coverage, contradictions, freshness"}),e.jsx("li",{children:"Activity timeline - who changed what, exportable trail"}),e.jsx("li",{children:"Schema explorer - integration reference (documented shapes)"})]})]}),badge:e.jsx(ie,{variant:"outline",className:"border-navy bg-navy/5 font-normal text-navy dark:border-blue-200 dark:text-blue-100",children:"For enterprise customers"}),visual:e.jsx(Ca,{}),visualAriaLabel:"Abstract diagram: data sources flow through truth and schema to exports",actions:e.jsxs(e.Fragment,{children:[e.jsx(K,{asChild:!0,children:e.jsx(Ae,{to:"/settings",children:"Upgrade via settings"})}),e.jsx(K,{variant:"outline",asChild:!0,children:e.jsx("a",{href:"mailto:[email protected]?subject=Data%20Layer%20Enterprise",children:"Contact sales"})}),e.jsx(K,{variant:"ghost",asChild:!0,children:e.jsx(Ae,{to:"/home",children:"Back to home"})})]}),pillars:[{title:"Campaign inspector",description:"Review and batch-manage insights with evidence links - filter, export, and confirm in one place."},{title:"Export suite",description:"Full ZIPs, themed bundles, and CSVs for diligence, board prep, and downstream BI."},{title:"Quality, diagnostics & activity",description:"Coverage, contradictions, freshness, and a timeline of activity for audit-friendly narratives."}]})}function Ea({breakdown:t}){const[s,n]=v.useState(!1),a=(t==null?void 0:t.score)??0,c=Math.min(100,Math.max(0,a))/100*360;return e.jsxs("div",{className:"rounded-xl border bg-card p-4 shadow-sm",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-6",children:[e.jsx("div",{className:"relative mx-auto h-28 w-28 shrink-0 rounded-full p-1",style:{background:`conic-gradient(var(--gold) ${c}deg, hsl(var(--primary) / 0.15) 0deg)`}
1,children:e.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center rounded-full bg-card",children:[e.jsx("span",{className:"text-2xl font-semibold tabular-nums text-navy dark:text-foreground",children:t?a:"-"}),e.jsx("span",{className:"text-step-caption font-medium uppercase tracking-wide text-muted-foreground",children:"Health"})]})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"Campaign health score"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Composite of confirmation rate, category coverage, documents, value creation, freshness, minus contradiction penalty."}),t?e.jsxs(K,{type:"button",variant:"ghost",size:"sm",className:"mt-2 h-8 gap-1 px-2 text-xs",onClick:()=>n(!s),children:[s?e.jsx(Rt,{className:"h-3.5 w-3.5"}):e.jsx(bs,{className:"h-3.5 w-3.5"}),"Breakdown"]}):null]})]}),s&&t?e.jsxs("ul",{className:"mt-3 space-y-1 border-t pt-3 text-xs text-muted-foreground",children:[e.jsx(Ie,{label:"Confirmation",value:t.confirmPts,max:25}),e.jsx(Ie,{label:"Categories",value:t.categoryPts,max:20}),e.jsx(Ie,{label:"Documents",value:t.docPts,max:15}),e.jsx(Ie,{label:"Value creation",value:t.valuePts,max:15}),e.jsx(Ie,{label:"Freshness",value:t.freshPts,max:25}),e.jsxs("li",{className:G(t.penalty>0&&"text-amber-700 dark:text-amber-400"),children:["Contradiction penalty: −",t.penalty]})]}):null]})}function Ie({label:t,value:s,max:n}){return e.jsxs("li",{className:"flex justify-between gap-2",children:[e.jsx("span",{children:t}),e.jsxs("span",{className:"tabular-nums",children:[s,"/",n]})]})}function Aa({docCount:t,assertionCount:s,outputCount:n,assertionsPerDoc:a,citedPct:i}){const c=Math.round(i),u=[{stage:"Ingest",caption:"Sources",value:t,sub:"documents",Icon:bn},{stage:"Extract",caption:"Insight layer",value:s,sub:"insights tracked",Icon:Ke},{stage:"Confirm",caption:"Validation",value:c,sub:"cited in deliverables",Icon:jn,isPercent:!0,highlight:c>0},{stage:"Consume",caption:"Deliverables",value:n,sub:"reports and outputs",Icon:vn}];return e.jsxs(Xn,{eyebrow:"Evidence pipeline",title:"Truth flow",accent:"navy",ariaLabel:"Evidence pipeline: ingest through extract, confirm, and consume into deliverables",children:[e.jsx("p",{className:"mb-4 text-xs text-muted-foreground",children:"Ingest, extract, confirm, then consume: evidence moves from sources into deliverables."}),e.jsx(ta,{children:e.jsx(sa,{children:e.jsx("div",{className:"flex flex-col flex-wrap items-stretch justify-center gap-2 text-xs sm:flex-row sm:items-center sm:gap-1 md:gap-2",children:u.map((m,p)=>e.jsxs("div",{className:"contents",children:[e.jsx(Da,{...m}),p<u.length-1?e.jsx(La,{}):null]},m.stage))})})}),a>0?e.jsxs("p",{className:"mt-3 text-step-caption text-muted-foreground",children:[a.toFixed(1)," insights per document on average"]}):null]})}function La(){return e.jsxs("div",{className:"flex min-h-[12px] items-center justify-center self-center sm:min-h-[48px] sm:w-6","aria-hidden":!0,children:[e.jsxs("svg",{width:"24",height:"12",viewBox:"0 0 24 12",className:"text-oposgold sm:hidden",preserveAspectRatio:"none",children:[e.jsx("defs",{children:e.jsx("marker",{id:"truth-flow-arrow-v",markerWidth:"6",markerHeight:"6",refX:"3",refY:"3",orient:"auto",children:e.jsx("path",{d:"M0,0 L6,3 L0,6 Z",fill:"currentColor"})})}),e.jsx("line",{x1:"12",y1:"0",x2:"12",y2:"10",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",markerEnd:"url(#truth-flow-arrow-v)"})]}),e.jsxs("svg",{width:"40",height:"10",viewBox:"0 0 40 10",className:"hidden text-oposgold sm:block",preserveAspectRatio:"none",children:[e.jsx("defs",{children:e.jsx("marker",{id:"truth-flow-arrow-h",markerWidth:"6",markerHeight:"6",refX:"5",refY:"3",orient:"auto",children:e.jsx("path",{d:"M0,0 L6,3 L0,6 Z",fill:"currentColor"})})}),e.jsx("line",{x1:"0",y1:"5",x2:"36",y2:"5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",markerEnd:"url(#truth-flow-arrow-h)"})]})]})}function Da({stage:t,caption:s,value:n,sub:a,isPercent:i,Icon:c,highlight:u}){return e.jsxs("div",{className:"flex min-w-[96px] flex-1 flex-col rounded-lg border px-2 py-2.5 text-center shadow-sm sm:min-w-[104px]",style:{borderColor:"color-mix(in srgb, var(--chart-navy) 45%, hsl(var(--border)))",background:"color-mix(in srgb, var(--chart-navy) 12%, hsl(var(--card)))"},children:[e.jsx(c,{className:"mx-auto mb-1 size-4",style:{color:"var(--chart-navy)"},"aria-hidden":!0}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide",style:{color:"var(--chart-navy)"},children:t}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s}),e.jsx("div",{className:"mt-1 flex justify-center",children:e.jsx(ea,{value:n,suffix:i?"%":void 0,variant:u?"gold":"default"})}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:a})]})}function Et(t){if(t==null||t==="")return null;const s=new Date(t).getTime();return Number.isFinite(s)?s:null}function Pa(t){const s=t.map(c=>JSON.stringify(c.content_json??{})).join(`
2`),n=/\[A#([a-f0-9]{8})\]/gi,a=new Set;let i;for(;(i=n.exec(s))!==null;)a.add(i[1].toLowerCase());return a}function Ra(t,s){if(t.length===0)return 0;const n=Pa(s);let a=0;for(const i of t){const c=i.id.slice(0,8).toLowerCase();n.has(c)&&a++}return Math.round(a/t.length*100)}function zs(t){const{totalAssertions:s,confirmedAssertions:n,categoriesWithData:a,docsTotal:i,docsCompleted:c,kpiCount:u,initiativeCount:m,riskCount:p,lastAssertionMs:j,lastOutputMs:o,contradictionCount:g}=t,d=s===0?0:Math.round(n/s*25),r=Math.round(a/ot.length*20),h=Math.round(i===0?15*.5:c/i*15),x=Math.min(15,(u>=3?5:0)+(m>=2?5:0)+(p>=2?5:0)),N=j!=null&&o!=null?Math.max(j,o):j??o,l=Ta(N),_=Math.min(10,g*2),A=d+r+h+x+l;return{score:Math.max(0,Math.min(100,A-_)),confirmPts:d,categoryPts:r,docPts:h,valuePts:x,freshPts:l,penalty:_}}function Ta(t){if(t==null||!Number.isFinite(t))return 0;const s=(Date.now()-t)/(86400*1e3);return s<=7?25:s>=30?0:Math.round(25*(1-(s-7)/23))}function Bt(t){const s=new Set;for(const a of t){const i=(a.category??"").trim().toLowerCase();i&&s.add(i)}let n=0;for(const a of ot)s.has(a)&&n++;return n}function Is(t){let s=0;for(const n of t){const a=n.metadata;a&&typeof a=="object"&&!Array.isArray(a)&&a.has_contradiction===!0&&s++}return s}const Oa=50,Oe=50,$a=[{id:"contradictions",label:"Review contradictions"},{id:"low-confidence",label:"Review low-confidence"},{id:"all-pending",label:"All pending"}],za=[{id:"all",label:"All sources"},{id:"document",label:"Document"},{id:"external_research",label:"External research"},{id:"public_markets_data",label:"Public markets"},{id:"manual",label:"Manual"},{id:"ai_synthesis",label:"AI synthesis"},{id:"orphan",label:"Source file removed"}];function Ia({campaignId:t}){const{toast:s}=Ue(),{data:n,isLoading:a}=Dt(t),{data:i=[]}=Je(t),{runBulkReview:c,runBulkRevert:u}=na(t),m=aa(t),[p,j]=v.useState(""),[o,g]=v.useState("all"),[d,r]=v.useState("all"),[h,x]=v.useState("all"),[N,l]=v.useState("all"),[_,A]=v.useState("any"),[C,E]=v.useState(null),[R,M]=v.useState(0),[$,I]=v.useState(!1),[T,H]=v.useState(!0),[k,O]=v.useState(!1),[b,L]=v.useState(new Set),[y,D]=v.useState(null);v.useEffect(()=>{M(0),L(new Set)},[p,o,d,h,N,_,$,C]);const P=v.useMemo(()=>({statusFilter:o,source:h,category:d,search:p,confidenceTier:N,contradictionLevel:_}),[o,h,d,p,N,_]),{data:F,isLoading:f,isError:q}=xs(t,P,{limit:Oe,offset:R*Oe}),J=(F==null?void 0:F.rows)??[],W=(F==null?void 0:F.totalCount)??0,oe=v.useMemo(()=>J.map(S=>S.id),[J]),{data:se=new Set}=ln(t,oe),Q=v.useMemo(()=>({search:"",statusFilter:o,category:d,source:h,hideSkipped:$?!1:o==="pending",showSkippedOnly:!1}),[o,d,h,$]),z=v.useMemo(()=>cn(J,Q),[J,Q]),U=v.useCallback(S=>{Jt("truth.preset",{preset:S},{campaign_id:t}),E(S),g("pending"),l(S==="low-confidence"?"low":"all"),A(S==="contradictions"?"flagged":"any"),H(!1)},[t]),fe=S=>
2{L(te=>{const ne=new Set(te);return ne.has(S)?ne.delete(S):ne.add(S),ne})},ce=v.useCallback(()=>{L(new Set(z.map(S=>S.id)))},[z]),ae=v.useCallback(()=>{L(new Set)},[]);v.useEffect(()=>{const S=te=>{var ne,Vt,Ht;if((te.metaKey||te.ctrlKey)&&te.key.toLowerCase()==="a"){const Ut=(Vt=(ne=te.target)==null?void 0:ne.tagName)==null?void 0:Vt.toLowerCase();if(Ut==="input"||Ut==="textarea"||(Ht=te.target)!=null&&Ht.isContentEditable)return;te.preventDefault(),ce()}};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[ce]);const w=v.useCallback((S,te)=>{Jt("truth.bulk",{action:S,count:te,filters:{source:h,status:o,category:d,confidenceTier:N,contradictionLevel:_}},{campaign_id:t})},[t,h,o,d,N,_]),V=v.useCallback(async S=>{if(b.size===0)return;const te=Array.from(b);await c({assertionIds:te,action:S},{actionLabel:S,onUndo:ne=>void u(ne),onComplete:()=>{w(S,te.length),ae()}})},[b,c,u,w,ae]),Y=S=>{if(b.size!==0){if(b.size>Oa){D(S);return}V(S)}};async function Z(){O(!0);try{const S=await dn(t,P,1e4,{...Q,search:p});L(new Set(S)),s({title:`${S.length.toLocaleString()} insights selected`,description:"All rows matching your current filters."})}catch{s({title:"Could not select all matching insights",variant:"destructive"})}finally{O(!1)}}async function xe(){if(b.size===0)return;const S=Array.from(b);await m.mutateAsync(S),ae()}const Gs=z.map(S=>S),We=v.useMemo(()=>{let S=null;for(const te of i){const ne=Et(te.created_at);ne!=null&&(S==null||ne>S)&&(S=ne)}return S},[i]),Qs=async()=>{const S={campaign:n??null,summary:{insightsLoaded:i.length,filteredCount:z.length,lastInsightActivity:We?new Date(We).toISOString():null},exportedAt:new Date().toISOString()};try{await navigator.clipboard.writeText(JSON.stringify(S,null,2)),s({title:"Copied",description:"Campaign summary JSON copied to clipboard."})}catch{s({title:"Copy failed",variant:"destructive"})}},Kt=[o!=="all"?`status=${o}`:null,d!=="all"?`category=${d}`:null,h!=="all"?`source=${h}`:null,N!=="all"?`confidence=${N}`:null,_!=="any"?`contradiction=${_}`:null,p.trim()?`search="${p.trim()}"`:null].filter(Boolean).join(", "),Ys=W===0?0:R*Oe+1,Zs=Math.min((R+1)*Oe,W),Xs=R>0,en=(R+1)*Oe<W,tn=W>z.length||W>Oe;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{className:"border-navy/12",children:[e.jsx(je,{className:"pb-2",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(ve,{className:"text-base",children:"Campaign context"}),e.jsx(we,{children:"Selected workspace metadata. Insight list below uses the same campaign scope."})]}),e.jsxs(K,{type:"button",variant:"outline",size:"sm",className:"shrink-0 gap-1",onClick:()=>void Qs(),children:[e.jsx(wn,{className:"h-3.5 w-3.5"}),"Copy as JSON"]})]})}),e.jsx(ke,{className:"space-y-3 text-sm",children:a?e.jsx("p",{className:"text-muted-foreground",children:"Loading campaign…"}):n?e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-step-caption font-medium uppercase tracking-wide text-muted-foreground",children:"Name"}),e.jsx("p",{className:"font-medium",children:n.company_name??n.id.slice(0,8)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-step-caption font-medium uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsx("p",{children:n.status??"-"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-step-caption font-medium uppercase tracking-wide text-muted-foreground",children:"Created"}),e.jsx("p",{className:"tabular-nums text-muted-foreground",children:n.created_at?new Date(n.created_at).toLocaleString():"-"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-step-caption font-medium uppercase tracking-wide text-muted-foreground",children:"Last insight activity"}),e.jsx("p",{className:"tabular-nums text-muted-foreground",children:We?new Date(We).toLocaleString():"-"})]})]}):e.jsx("p",{className:"text-muted-foreground",children:"Campaign not found."})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-3 text-sm font-semibold text-foreground",children:"Insights"}),e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-step-caption font-semibold uppercase tracking-wide text-muted-foreground",children:"Qu
2ick start"}),$a.map(S=>e.jsx("button",{type:"button",onClick:()=>U(S.id),className:G("rounded-full border px-2.5 py-1 text-step-caption font-medium transition-colors",C===S.id?"border-chart-gold bg-accent text-chart-gold-dark dark:text-chart-gold":"border-border text-muted-foreground hover:bg-muted"),children:S.label},S.id))]}),e.jsxs(Ss,{open:T,onOpenChange:H,children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e.jsx(Cs,{asChild:!0,children:e.jsxs(K,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1 text-xs",children:[e.jsx(Yt,{className:"h-3.5 w-3.5"}),"Filters",e.jsx(Rt,{className:G("h-3.5 w-3.5 transition-transform",T&&"rotate-180")})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ia,{id:"inspector-show-skipped",checked:$,onCheckedChange:I}),e.jsx(st,{htmlFor:"inspector-show-skipped",className:"text-xs text-muted-foreground",children:"Show skipped"})]}),e.jsx(St,{format:"json",label:"JSON",variant:"outline",size:"sm",onClick:()=>Es(i,"insights.json")}),e.jsx(St,{format:"csv",label:"CSV",variant:"outline",size:"sm",onClick:()=>fa(Gs,"insights.csv")})]}),e.jsx(Ms,{children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-[160px] flex-1",children:[e.jsx(it,{placeholder:"Search content…",value:p,onChange:S=>j(S.target.value),className:"pr-8"}),e.jsx(Yt,{className:"absolute right-2.5 top-2.5 h-4 w-4 text-muted-foreground","aria-hidden":!0})]}),e.jsxs(Se,{value:o,onValueChange:S=>g(S),children:[e.jsx(Ce,{className:"w-[160px]",children:e.jsx(Me,{placeholder:"Status"})}),e.jsxs(Ee,{children:[e.jsx(X,{value:"all",children:"All statuses"}),e.jsx(X,{value:"pending",children:"Pending"}),e.jsx(X,{value:"active",children:"Active"}),e.jsx(X,{value:"archived",children:"Archived"})]})]}),e.jsxs(Se,{value:d,onValueChange:r,children:[e.jsx(Ce,{className:"w-[180px]",children:e.jsx(Me,{placeholder:"Category"})}),e.jsxs(Ee,{children:[e.jsx(X,{value:"all",children:"All categories"}),ot.map(S=>e.jsx(X,{value:S,children:S},S))]})]}),e.jsxs(Se,{value:h,onValueChange:S=>x(S),children:[e.jsx(Ce,{className:"w-[160px]",children:e.jsx(Me,{placeholder:"Source"})}),e.jsx(Ee,{children:za.map(S=>e.jsx(X,{value:S.id,children:S.label},S.id))})]}),e.jsxs(Se,{value:N,onValueChange:S=>l(S),children:[e.jsx(Ce,{className:"w-[140px]",children:e.jsx(Me,{placeholder:"Confidence"})}),e.jsxs(Ee,{children:[e.jsx(X,{value:"all",children:"All confidence"}),e.jsx(X,{value:"high",children:ft.high}),e.jsx(X,{value:"medium",children:ft.medium}),e.jsx(X,{value:"low",children:ft.low}
2)]})]}),e.jsxs(Se,{value:_,onValueChange:S=>A(S),children:[e.jsx(Ce,{className:"w-[160px]",children:e.jsx(Me,{placeholder:"Contradiction"})}),e.jsxs(Ee,{children:[e.jsx(X,{value:"any",children:"Any contradiction"}),e.jsx(X,{value:"none",children:"No contradiction"}),e.jsx(X,{value:"flagged",children:"Flagged only"}),e.jsx(X,{value:"active",children:"Active links"})]})]})]})})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-2 rounded-lg border bg-muted/30 px-3 py-2 text-sm",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"text-muted-foreground",children:[b.size," selected (of ",z.length," on this page)"]}),e.jsx(K,{type:"button",size:"sm",variant:"ghost",onClick:ce,disabled:z.length===0,children:"Select visible"}),tn?e.jsxs(K,{type:"button",size:"sm",variant:"ghost",disabled:k,onClick:()=>void Z(),children:[k?e.jsx(pe,{className:"mr-1 h-3 w-3 animate-spin"}):null,"Select all ",W.toLocaleString()," matching"]}):null,e.jsx(K,{type:"button",size:"sm",variant:"ghost",onClick:ae,disabled:b.size===0,children:"Clear"}),b.size>0?e.jsxs(e.Fragment,{children:[e.jsxs(K,{size:"sm",variant:"secondary",className:"gap-1",onClick:()=>Y("confirm"),children:[e.jsx(kn,{className:"h-3.5 w-3.5"}),"Confirm"]}),e.jsx(K,{size:"sm",variant:"outline",onClick:()=>Y("reject"),children:"Reject"}),e.jsxs(K,{size:"sm",variant:"outline",className:"gap-1",disabled:m.isPending,onClick:()=>void xe(),children:[m.isPending?e.jsx(pe,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Nn,{className:"h-3.5 w-3.5"}),"Skip"]})]}):null]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:f?"Loading…":W===0?"Showing 0 of 0":`Showing ${Ys.toLocaleString()}–${Zs.toLocaleString()} of ${W.toLocaleString()}`}),e.jsxs(K,{type:"button",size:"xs",variant:"outline",disabled:!Xs||f,onClick:()=>M(S=>Math.max(0,S-1)),children:[e.jsx(_n,{className:"h-3.5 w-3.5"}),"Prev"]}),e.jsxs(K,{type:"button",size:"xs",variant:"outline",disabled:!en||f,onClick:()=>M(S=>S+1),children:["Next",e.jsx(bs,{className:"h-3.5 w-3.5"})]})]})]}),e.jsx("div",{className:"mt-3 overflow-x-auto rounded-md border",children:e.jsxs(zt,{children:[e.jsx(It,{children:e.jsxs(re,{children:[e.jsx(ge,{className:"w-10",children:e.jsx(hs,{checked:z.length>0&&z.every(S=>b.has(S.id)),onCheckedChange:()=>{z.every(S=>b.has(S.id))?ae():ce()},"aria-label":"Select all visible"})}),e.jsx(ge,{children:"Status"}),e.jsx(ge,{children:"Category"}),e.jsx(ge,{children:"Confidence"}),e.jsx(ge,{children:"Content"}),e.jsx(ge,{children:"Source"}),e.jsx(ge,{className:"w-24",children:"Review"})]})}),e.jsx(Ft,{children:f?Array.from({length:5}).map((S,te)=>e.jsx(re,{children:e.jsx(ee,{colSpan:7,children:e.jsx(Nt,{className:"h-10 w-full"})})},te)):q?e.jsx(re,{children:e.jsx(ee,{colSpan:7,className:"text-center text-muted-foreground py-8",children:"Could not load insights  -  server under load. Please refresh and try again."})}):z.length===0?e.jsx(re,{children:e.jsx(ee,{colSpan:7,className:"text-center text-muted-foreground",children:"No insights match filters."})}):z.map(S=>e.jsx(Fa,{row:S,campaignId:t,selected:b.has(S.id),activeContradictionIds:se,onToggle:()=>fe(S.id)},S.id))})]})})]}),e.jsx(oa,{open:y!=null,onOpenChange:S=>!S&&D(null),children:e.jsxs(la,{children:[e.jsxs(ca,{children:[e.jsxs(da,{children:[y==="confirm"?"Confirm":"Reject"," ",b.size," insights?"]}),e.jsxs(ua,{children:["You are about to ",y==="confirm"?"confirm":"reject"," ",b.size," insights",Kt?` matching filters: ${Kt}`:"",". This action is logged in the review audit trail."]})]}),e.jsxs(ma,{children:[e.jsx(pa,{children:"Cancel"}),e.jsx(ha,{type:"button",onClick:()=>{const S=y;D(null),S&&V(S)},children:y==="confirm"?"Confirm all":"Reject all"})]})]})})]})}function Fa({row:t,campaignId:s,selected:n,activeContradictionIds:a,onToggle:i}){var p;const c=un(t.confidence),u=mn(t),m=a.has(t.id);return e.jsxs(re,{children:[e.jsx(ee,{children:e.jsx(hs,{checked:n,onCheckedChange:i,"aria-label":`Select ${t.id}`})}),e.jsx(ee,{children:e.jsx(ie,{variant:"outline",className:"text-step-caption",children:t.status??"-"})}),e.jsx(ee,{children:e.jsx(ie,{variant:"outline",className:G("text-step-caption",pn[t.category??""]??""),children:t.category??"-"})}),e.jsx(ee,{children:e.jsx("span",{className:G("rounded px-1.5 py-0.5 text-step-caption",hn[c]),children:c})}),e.jsxs(ee,{className:"max-w-[280px]",children:[e.jsx("p",{className:"truncate text-sm",children:t.content}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap gap-1",children:[u?e.jsxs(ie,{variant:"outline",className:"h-5 border-rose-300 px-1 py-0 text-step-caption text-rose-600 dar
2k:border-rose-700 dark:text-rose-400",children:[e.jsx(Sn,{className:"mr-0.5 h-2.5 w-2.5"}),"Flagged"]}):null,m?e.jsx(ie,{variant:"outline",className:"h-5 border-amber-300 px-1 py-0 text-step-caption text-amber-700 dark:border-amber-700 dark:text-amber-400",children:"Active"}):null]})]}),e.jsx(ee,{className:"max-w-[120px] truncate text-xs text-muted-foreground",children:((p=t.documents)==null?void 0:p.file_name)??"-"}),e.jsx(ee,{children:e.jsx(K,{variant:"ghost",size:"sm",className:"h-8 gap-1 px-2",asChild:!0,children:e.jsxs(Ae,{to:`/campaigns/${s}`,children:[e.jsx(mt,{className:"h-3.5 w-3.5"}),"Open"]})})})]})}function Ba(t){const{user:s}=Ne();return He({queryKey:["data-exports",t],queryFn:async()=>{if(!t)return[];const{data:n,error:a}=await B.from("data_exports").select("*").eq("campaign_id",t).order("created_at",{ascending:!1}).limit(80);if(a)throw a;return n??[]},enabled:!!s&&!!t})}const de=["Campaign info","Insights","Documents","Reports","Risks","Initiatives & KPIs","Decisions","Activity & local drafts","Expert engagements"];async function Fs(t){var a;const s=[];try{const i=await Ds(t),c=ya(i);if(((a=i.draft)==null?void 0:a.confirmed_payload)!=null&&s.push({path:"vcp_confirmed_snapshot.json",body:JSON.stringify(i.draft.confirmed_payload,null,2)}),c!=null)return{vcpDraft:c,extraZipEntries:s}}catch{}let n=null;if(typeof localStorage<"u")try{const i=localStorage.getItem(ga(t));n=i?JSON.parse(i):null}catch{n=null}return{vcpDraft:n,extraZipEntries:s}}function qt(t,s=72){return(t.replace(/[^\w-]+/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")||"file").slice(0,s)}function qa(t){return`${qe.productName} - campaign export
3Company: ${t}
4Generated: ${new Date().toISOString()}
5
6This ZIP contains structured JSON/CSV and text snapshots of your campaign workspace.
7
8Included:
9- campaign_info.json - full campaign row (value bridge, scenarios, etc.)
10- insights.json / insights.csv - assertions (Insight Layer)
11- documents_index.* - uploaded document metadata (file names, storage paths). Binary files are NOT included.
12- risks.*, initiatives.*, kpis.*, decisions.*
13- activity_log_sample.json - last 50 activity rows
14- expert_engagements.json - Expert Directory engagement records for this campaign
15- financial_model_assumptions.json - from this browser's localStorage (if present)
16- vcp_draft.json - VCP builder draft from Postgres when available, otherwise localStorage cache
17- reports/ - each generated output as JSON text (content_json)
18
19To recover uploaded files, use storage paths from documents_index with your Supabase project.
20`}async function Bs(t,s,n){const a=new pt,i=de.length;let c=0;const u=P=>{c+=1,n==null||n({stage:P,current:c,total:i})};u(de[0]);const{data:m,error:p}=await B.from("campaigns").select("*").eq("id",t).single();if(p)throw p;a.file("campaign_info.json",JSON.stringify(m,null,2)),u(de[1]);const{data:j,error:o}=await B.from("assertions").select(lt).eq("campaign_id",t);if(o)throw o;const g=j??[];a.file("insights.json",JSON.stringify(j??[],null,2)),a.file("insights.csv",Te(g)),u(de[2]);const{data:d,error:r}=await B.from("documents").select("id, campaign_id, file_name, file_type, file_size, storage_path, processing_status, processing_step, assertion_count, uploaded_by, created_at, updated_at").eq("campaign_id",t);if(r)throw r;const h=d??[];a.file("documents_index.json",JSON.stringify(d??[],null,2)),a.file("documents_index.csv",Te(h)),u(de[3]);const{data:x,error:N}=await B.from("outputs").select("*").eq("campaign_id",t).order("created_at",{ascending:!1});if(N)throw N;const l=a.folder("reports"),_=[];for(const P of x??[]){const f=`${qt((P.title??"output").replace(/\s+/g,"_"))}_v${P.version??1}_${P.id.slice(0,8)}.txt`,q=P.content_json!=null?JSON.stringify(P.content_json,null,2):"";l==null||l.file(f,q),_.push({id:P.id,output_type:P.output_type,title:P.title,version:P.version,file:f})}l==null||l.file("reports_index.json",JSON.stringify(_,null,2)),u(de[4]);const{data:A,error:C}=await B.from("campaign_risks").select("*").eq("campaign_id",t);if(C)throw C;const E=A??[];a.file("risks.json",JSON.stringify(A??[],null,2)),a.file("risks.csv",Te(E)),u(de[5]);const{data:R,error:M}=await B.from("initiatives").select("*").eq("campaign_id",t);if(M)throw M;const $=R??[];a.file("initiatives.json",JSON.stringify(R??[],null,2)),a.file("initiatives.csv",Te($));const{data:I,error:T}=await B.from("campaign_kpis").select("*").eq("campaign_id",t);if(T)throw T;a.file("kpis.json",JSON.stringify(I??[],null,2)),u(de[6]);const{data:H,error:k}=await B.from("campaign_decisions").select("*").eq("campaign_id",t);if(k)throw k;a.file("decisions.json",JSON.stringify(H??[],null,2)),u(de[7]);const{data:O}=await B.from("activity_log").select("*").eq("campaign_id",t).order("created_at",{ascending:!1}).limit(50);a.file("activity_log_sample.json",JSON.stringify(O??[],null,2)),u(de[8]);const{data:b}=await B.from("expert_engagements").select("*").eq("campaign_id",t);a.file("expert_engagements.json",JSON.stringify(b??[],null,2));let L=null;if(typeof localStorage<"u")try{const P=localStorage.getItem(Ls(t));L=P?JSON.parse(P):null}catch{L=null}const{vcpDraft:y,extraZipEntries:D}=await Fs(t);for(const P of D)a.file(P.path,P.body);return a.file("financial_model_assumptions.json",JSON.stringify(L??{},null,2)),a.file("vcp_draft.json",JSON.stringify(y??{},null,2)),a.file("README.txt",qa(s)),a.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{level:6}})}function Xe(t,s){As(t,s)}function qs(t){const s=qt(t||"campaign",48),n=new Date().toISOString().slice(0,10);return`${s}_OPOS_Export_${n}.zip`}async function Ka(t,s,n,a){const i=new pt,c=6;let u=0;const m=o=>{u+=1,a==null||a({stage:o,current:Math.min(u,c),total:c})};m("Campaign");const{data:p,error:j}=await B.from("campaigns").select("*").eq("id",t).single();if(j)throw j;if(n==="board_prep"){m("KPIs & risks");const[{data:o},{data:g},{data:d}]=await Promise.all([B.from("campaign_kpis").select("*").eq("campaign_id",t),B.from("campaign_risks").select("*").eq("campaign_id",t).order("impact_score",{ascending:!1}).limit(20),B.from("outputs").select("*").eq("campaign_id",t).order("created_at",{ascending:!1}).limit(12)]);i.file("board_meeting_prep.json",JSON.stringify({company:s,generated_at:new Date().toISOString(),attention_items:(p==null?void 0:p.attention_items)??null,kpis:o??[],top_risks:g??[],recent_outputs:d??[]},null,2)),i.file("README.txt",`${qe.productName} - Board Meeting Prep bundle
21Company: ${s}
22Generated: ${new Date().toISOString()}
23
24Includes KPIs, top risks, recent outputs, and attention items snapshot.
25`),m("Finalize")}else if(n==="due_diligence"){m("Insights & documents");const[{data:o,error:g},{data:d,error:r}]=await Promise.all([B.from("assertions").select(lt).eq("campaign_id",t),B.from("documents").select("*").eq("campaign_id",t)]);if(g)throw g;if(r)throw r;const h=o??[];i.file("insights.json",JSON.stringify(o??[],null,2)),i.file("insights.csv",Te(h));const x=d??[];i.file("documents_index.json",JSON.stringify(d??[],null,2)),i.file("documents_index.csv",Te(x)),m("Risks & campaign");const[{data:N,error:l}]=await Promise.all([B.from("campaign_risks").select("*").eq("campaign_id",t)]);if(l)throw l;i.file("risks.json",JSON.stringify(N??[],null,2)),i.file("campaign_info.json",JSON.stringify(p,null,2));let _=null;if(typeof localStorage<"u")try{const E=localStorage.getItem(Ls(t));_=E?JSON.parse(E):null}catch{_=null}const{vcpDraft:A,extraZipEntries:C}=await Fs(t);for(const E of C)i.file(E.path,E.body);i.file("financial_model_assumptions.json",JSON.stringify(_??{},null,2)),i.file("vcp_draft.json",JSON.stringify(A??{},null,2)),i.file("README.txt",`${qe.productName} - Due Diligence bundle
26Company: ${s}
27Generated: ${new Date().toISOString()}
28
29Assertions, document index, risks, campaign row, and local financial/VCP drafts.
30`),m("Finalize")}else{m("Quarterly data");const[{data:o},{data:g},{data:d},{data:r}]=await Promise.all([B.from("activity_log").select("*").eq("campaign_id",t).order("created_at",{ascending:!1}).limit(200),B.from("outputs").select("*").eq("campaign_id",t).order("created_at",{ascending:!1}).limit(50),B.from("campaign_kpis").select("*").eq("campaign_id",t),B.from("initiatives").select("*").eq("campaign_id",t)]);i.file("activity_log.json",JSON.stringify(o??[],null,2)),i.file("outputs.json",JSON.stringify(g??[],null,2)),i.file("kpis.json",JSON.stringify(d??[],null,2)),i.file("initiatives.json",JSON.stringify(r??[],null,2)),i.file("quarterly_review_summary.json",JSON.stringify({company:s,generated_at:new Date().toISOString(),note:"Pair with Data Layer health score in the app for full quarterly context."},null,2)),i.file("README.txt",`${qe.productName} - Quarterly Review bundle
31Company: ${s}
32Generated: ${new Date().toISOString()}
33
34Activity, outputs, KPIs, and initiatives.
35`),m("Finalize")}return i.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{level:6}})}function Va(t,s){const n=qt(t||"campaign",48),a=new Date().toISOString().slice(0,10);return`${n}_OPOS_${s==="board_prep"?"BoardPrep":s==="due_diligence"?"DueDiligence":"QuarterlyReview"}_${a}.zip`}async function Ks(t){const{error:s}=await B.from("data_exports").insert({campaign_id:t.campaignId,sponsor_id:t.sponsorId,export_kind:t.exportKind,filename:t.filename,byte_size:t.byteSize})}const es="0.1",ue=["Manifest","Assertions","Risks","KPIs","Initiatives","Decisions","Market","Outputs","Documents"];function ts(t){if(t==null)return"null";if(typeof t=="number"||typeof t=="boolean")return String(t);const s=String(t);return s===""||s.trim()!==s||/[:#?{}[\],&*!|>'"%@`\n]/.test(s)?JSON.stringify(s):s}function At(t){const s=["---"];for(const[n,a]of Object.entries(t))if(a!=null)if(Array.isArray(a)){if(a.length===0)continue;s.push(`${n}:`);for(const i of a)s.push(`  - ${ts(i)}`)}else s.push(`${n}: ${ts(a)}`);return s.push("---"),s.join(`
36`)}function $e(t,s){return`${At(t)}
37
38${(s??"").trim()}
39`}function Pe(t){return(t||"").replace(/-/g,"").slice(0,8).toUpperCase()}function gt(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function _e(t){return[...t].sort((s,n)=>{const a=String(s.created_at??""),i=String(n.created_at??"");if(a!==i)return a<i?-1:1;const c=String(s.id??""),u=String(n.id??"");return c<u?-1:c>u?1:0})}function Ha(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)&&t.quarantined===!0}async function Ua(t,s,n={}){var F;const a=n.redaction??"standard",i=new pt,c=ue.length;let u=0;const m=f=>{var q;u+=1,(q=n.onProgress)==null||q.call(n,{stage:f,current:u,total:c})},p={};m(ue[1]);const{data:j}=await B.from("assertions").select(lt).eq("campaign_id",t).in("status",["confirmed","edited"]),o=_e((j??[]).filter(f=>a==="full"||!Ha(f.metadata))),g=i.folder("assertions");for(const f of o){const q=Pe(String(f.id));g==null||g.file(`A_${q}
39.md`,$e({id:f.id,type:"assertion",status:f.status,category:f.category,epistemic_type:f.epistemic_type??"fact",confidence:f.confidence,source:f.source_type??f.source,document:f.document_id??void 0,subject:f.subject_id??void 0,decision:f.decision_id??void 0,updated_at:f.updated_at??f.created_at},String(f.content??"")))}p.assertions=o.length,m(ue[2]);const{data:d}=await B.from("campaign_risks").select("*").eq("campaign_id",t),r=_e(d??[]),h=i.folder("risks");for(const f of r){const q=[gt(f.description),gt(f.mitigation)?`
40## Mitigation
41${gt(f.mitigation)}`:""].filter(Boolean).join(`
42`);h==null||h.file(`R_${Pe(String(f.id))}.md`,$e({id:f.id,type:"risk",title:f.title,category:f.category,likelihood:f.likelihood,severity:f.severity??f.impact,status:f.status,owner:f.owner??void 0,updated_at:f.updated_at??f.created_at},q||String(f.title??"")))}p.risks=r.length,m(ue[3]);const{data:x}=await B.from("campaign_kpis").select("*").eq("campaign_id",t),N=_e(x??[]),l=i.folder("kpis");for(const f of N)l==null||l.file(`K_${Pe(String(f.id))}.md`,$e({id:f.id,type:"kpi",name:f.name??f.metric??f.label,unit:f.unit??void 0,target:f.target_value??f.target,current:f.current_value??f.value,updated_at:f.updated_at??f.created_at},String(f.notes??f.name??"")));p.kpis=N.length,m(ue[4]);const{data:_}=await B.from("initiatives").select("*").eq("campaign_id",t),A=_e(_??[]),C=i.folder("initiatives");for(const f of A)C==null||C.file(`I_${Pe(String(f.id))}.md`,$e({id:f.id,type:"initiative",title:f.title??f.name,status:f.status,owner:f.owner??void 0,strategic_priority:f.strategic_priority_id??void 0,updated_at:f.updated_at??f.created_at},String(f.description??f.title??"")));p.initiatives=A.length,m(ue[5]);const{data:E}=await B.from("campaign_decisions").select("*").eq("campaign_id",t),R=_e(E??[]),M=i.folder("decisions");for(const f of R)M==null||M.file(`D_${Pe(String(f.id))}.md`,$e({id:f.id,type:"decision",title:f.title,status:f.status,updated_at:f.updated_at??f.created_at},String(f.rationale??f.description??f.title??"")));p.decisions=R.length,m(ue[6]);const{data:$}=await B.from("market_intelligence_items").select("*").eq("campaign_id",t),I=_e($??[]),T=i.folder("market");for(const f of I)T==null||T.file(`MI_${Pe(String(f.id))}.md`,$e({id:f.id,type:"market_intelligence",kind:f.kind,title:f.title,source_url:f.source_url??void 0,refreshed_at:f.refreshed_at??f.created_at},String(f.body??f.title??"")));p.market=I.length,m(ue[7]);const{data:H}=await B.from("outputs").select("id, output_type, title, version, content_json, created_at, updated_at").eq("campaign_id",t),k=_e(H??[]),O=i.folder("outputs");for(const f of k){const q=O==null?void 0:O.folder(`O_${Pe(String(f.id))}`);q==null||q.file("index.yaml",`${At({id:f.id,type:"output",output_type:f.output_type,title:f.title,version:f.version,created_at:f.created_at})}
43`);const J=f.content_json,W=typeof J=="string"?J:J!=null?JSON.stringify(J,null,2):"";q==null||q.file("content.md",`${W}
44`)}p.outputs=k.length,m(ue[8]);const{data:b}=await B.from("documents").select("id, file_name, file_type, storage_path, processing_status, created_at").eq("campaign_id",t),L=_e(b??[]),y="id,file_name,file_type,processing_status,storage_path,created_at",D=L.map(f=>[f.id,f.file_name,f.file_type,f.processing_status,f.storage_path,f.created_at].map(q=>`"${String(q??"").replace(/"/g,'""')}"`).join(","));(F=i.folder("documents"))==null||F.file("index.csv",[y,...D].join(`
45`)+`
46`),p.documents=L.length,m(ue[0]);const P=At({format:"opos-deal-format",format_version:es,company:s,generated_at:new Date().toISOString(),redaction:a,sort:"created_at,id",excludes:["embeddings","private_notes",a==="standard"?"quarantined":""].filter(Boolean),counts_assertions:p.assertions,counts_risks:p.risks,counts_kpis:p.kpis,counts_initiatives:p.initiatives,counts_decisions:p.decisions,counts_market:p.market,counts_outputs:p.outputs,counts_documents:p.documents});return i.file("META.yaml",`${P}
47`),i.file("README.md",`# ${s} - ${qe.productName} Deal Format v${es}
48
49The deal, in plain text. One entity per file; filenames use the same 8-char short IDs as the \`[A#]\` citation chips. Read it with any editor, diff it with any git, ingest it with any AI, and (soon) re-import it into OPOs as pending for sponsor review.
50
51- \`assertions/\` - confirmed Truth-Layer facts (one per file)
52- \`risks/\` \`kpis/\` \`initiatives/\` \`decisions/\` \`market/\`
53- \`outputs/\` - each generated report (index.yaml + content.md)
54- \`documents/index.csv\` - source-document references only (no binaries)
55- \`META.yaml\` - manifest: counts, sort rule, format version, redaction
56
57Never included: embeddings, private notes.`+(a==="standard"?` Quarantined facts are excluded (redaction: standard).
58`:`
59`)),i.generateAsync({type:"blob"})}function Ja(t,s=new Date().toISOString().slice(0,10)){return`${t.replace(/[^\w-]+/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").toLowerCase().slice(0,48)||"deal"}_${s}_opos-deal-format.zip`}function ss(t){const s=t.replace(/\r\n/g,`
60`);if(!s.startsWith(`---
61`))return{data:{},body:s.trim()};const n=s.indexOf(`
62---`,4);if(n===-1)return{data:{},body:s.trim()};const a=s.slice(4,n),i=s.slice(n+4).replace(/^\n+/,""),c={};let u=null;for(const m of a.split(`
63`)){const p=m.match(/^\s+-\s(.*)$/);if(p&&u){const d=c[u],r=ns(p[1]);Array.isArray(d)?d.push(r):c[u]=[r];continue}const j=m.match(/^([\w-]+):\s?(.*)$/);if(!j)continue;const[,o,g]=j;g===""?(c[o]=[],u=o):(c[o]=ns(g),u=o)}return{data:c,body:i}}function ns(t){const s=t.trim();if(s.startsWith('"'))try{return String(JSON.parse(s))}catch{return s}return s}function Re(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function Wa(t){const s=Number(Re(t));return Number.isFinite(s)&&s>=0&&s<=1?s:null}async function Ga(t,s){const n=await pt.loadAsync(s),a=n.file("META.yaml");if(!a)throw new Error("Not a Deal Format archive (no META.yaml found).");const i=ss(await a.async("string")).data;if(Re(i.format)!=="opos-deal-format")throw new Error("This ZIP is not an OPOs Deal Format archive.");const c=Re(i.format_version)??"";if(!c.startsWith("0."))throw new Error(`Unsupported Deal Format version "${c||"unknown"}". This build imports v0.x.`);const u=Re(i.company),m=crypto.randomUUID(),p=[];n.forEach((r,h)=>{!h.dir&&/^assertions\/A_[^/]+\.md$/i.test(r)&&p.push(h)}),p.sort((r,h)=>r.name<h.name?-1:r.name>h.name?1:0);const j=[];let o=0;for(const r of p){const{data:h,body:x}=ss(await r.async("string")),N=x.trim();if(!N){o+=1;continue}j.push({campaign_id:t,content:N,category:Re(h.category)??null,source_type:"deal_format_import",actor_role:"human",status:"pending",confidence:Wa(h.confidence),metadata:{import_batch:m,source:"deal_format",format_version:c,original_id:Re(h.id),epistemic_type:Re(h.epistemic_type)}})}if(j.length===0)return{imported:0,skipped:o,batchId:m,company:u,formatVersion:c};let g=0;const d=200;for(let r=0;r<j.length;r+=d){const h=j.slice(r,r+d),{error:x}=await B.from("assertions").insert(h);if(x)throw new Error(x.message);g+=h.length}return{imported:g,skipped:o,batchId:m,company:u,formatVersion:c}}function Qa({campaignId:t,companyName:s}){const{toast:n}=Ue(),{user:a}=Ne(),i=rt(),{data:c=[]}=Je(t),{data:u=[]}=dt(t),{data:m=[]}=ut(t),{data:p=[]}=Pt(t),{data:j=[]}=xa(t),{data:o=[]}=Ba(t),[g,d]=v.useState(null),[r,h]=v.useState(null),x=a==null?void 0:a.id,N=async(k,O,b)=>{x&&(await Ks({campaignId:t,sponsorId:x,exportKind:k,filename:O,byteSize:b}),i.invalidateQueries({queryKey:["data-exports",t]}))},l=async()=>{h("full"),d(null);try{const k=await Bs(t,s,b=>d(b)),O=qs(s);Xe(k,O),await N("full_zip",O,k.size),n({title:"Export Ready",description:"Campaign ZIP downloaded."})}catch(k){n({title:"Export failed",description:k instanceof Error?k.message:"Unknown error",variant:"destructive"})}finally{h(null),d(null)}},_=async()=>{h("deal_format"),d(null);try{const k=await Ua(t,s,{onProgress:b=>d(b)}),O=Ja(s);Xe(k,O),await N("deal_format_v0",O,k.size),n({title:"Deal Format ready",description:"Plain-text deal folder downloaded."})}catch(k){n({title:"Export failed",description:k instanceof Error?k.message:"Unknown error",variant:"destructive"})}finally{h(null),d(null)}},A=v.useRef(null),C=async k=>{h("deal_format_import");try{const O=await Ga(t,k);i.invalidateQueries({queryKey:["assertions",t]}),O.imported===0?n({title:"Nothing to import",description:"No importable assertions were found in that archive."}):n({title:`Imported ${O.imported} as pending`,description:`Review them in the Truth Layer.${O.skipped?` ${O.skipped} skipped (empty).`:""}`})}catch(O){n({title:"Import failed",description:O instanceof Error?O.message:"Unknown error",variant:"destructive"})}finally{h(null),A.current&&(A.current.value="")}},E=async k=>{h(k);try{const O=await Ka(t,s,k,L=>d(L)),b=Va(s,k);Xe(O,b),await N(`smart_${k}`,b,O.size),n({title:"Bundle Ready",description:"Download started."})}catch(O){n({title:"Export failed",description:O instanceof Error?O.message:"Unknown error",variant:"destructive"})}finally{h(null),d(null)}},R=async()=>{h("activity");try{await Ps(t),n({title:"Activity log exported"})}catch(k){n({title:"Export failed",description:k instanceof Error?k.message:"Unknown error",variant:"destructive"})}finally{h(null)}},M=(k,O,b)=>{const L=Te(k),y=new Blob([L],{type:"text/csv;charset=utf-8"});
63As(y,O),N(b,O,y.size)},$=async()=>{h("json");try{const[{data:k},{data:O},{data:b},{data:L},{data:y}]=await Promise.all([B.from("campaigns").select("*").eq("id",t).single(),B.from("assertions").select(lt).eq("campaign_id",t),B.from("campaign_risks").select("*").eq("campaign_id",t),B.from("campaign_kpis").select("*").eq("campaign_id",t),B.from("campaign_decisions").select("*").eq("campaign_id",t)]),D={exported_at:new Date().toISOString(),campaign:k,assertions:O??[],risks:b??[],kpis:L??[],decisions:y??[]},F=`${s.replace(/[^\w-]+/g,"_").slice(0,48)||"campaign"}_snapshot_${Mt(new Date,"yyyy-MM-dd")}.json`;Es(D,F);const f=new Blob([JSON.stringify(D,null,2)],{type:"application/json"}).size;await N("custom_json_snapshot",F,f),n({title:"Snapshot ready",description:"JSON download started."})}catch(k){n({title:"Snapshot failed",description:k instanceof Error?k.message:"Unknown error",variant:"destructive"})}finally{h(null)}},I=u,T=`~${Math.max(120,Math.round(c.length*3+u.length*12+200))} KB est.`,H=`~${Math.max(48,Math.round(c.length*2+u.length*6))} KB est.`;return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-2",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Campaign bundle"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Single archive aligned with the header “Download full data dump” action - each download is logged for audit."}),e.jsxs(be,{className:"border-navy/12",children:[e.jsxs(je,{children:[e.jsx(ve,{className:"text-base",children:"Full ZIP"}),e.jsx(we,{children:"Everything in one ZIP: insights, documents index, reports, risks, KPIs, activity sample, and local drafts."})]}),e.jsxs(ke,{className:"space-y-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Size estimate: ",T]}),e.jsxs(K,{className:"gap-2 bg-navy text-white hover:bg-navy/90 dark:bg-primary dark:text-primary-foreground",disabled:r!==null,onClick:()=>void l(),children:[r==="full"?e.jsx(pe,{className:"h-4 w-4 animate-spin"}):e.jsx(me,{fileType:"zip",className:"h-4 w-4"}),"Download full ZIP"]}),g&&r==="full"?e.jsxs("div",{className:"space-y-1",children:[e.jsx(Ct,{value:g.current/g.total*100,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:g.stage})]}):null]})]})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"OPOs Deal Format (plain text)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The deal as a deterministic folder of markdown - one entity per file, diffable, AI-readable, and re-importable soon. Embeddings and private notes are never included."}),e.jsxs(be,{className:"border-[var(--gold-dark)]/25",children:[e.jsxs(je,{children:[e.jsx(ve,{className:"text-base",children:"Deal Format v0"}),e.jsx(we,{children:"assertions / risks / KPIs / initiatives / decisions / market / outputs, plus META.yaml. Confirmed facts only; quarantined excluded."})]}),e.jsxs(ke,{className:"space-y-3",children:[e.jsxs(K,{className:"gap-2",variant:"outline",disabled:r!==null,onClick:()=>void _(),children:[r==="deal_format"?e.jsx(pe,{className:"h-4 w-4 animate-spin"}):e.jsx(me,{fileType:"zip",className:"h-4 w-4"}),"Download Deal Format"]}),g&&r==="deal_format"?e.jsxs("div",{className:"space-y-1",children:[e.jsx(Ct,{value:g.current/g.total*100,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:g.stage})]}):null]})]}),e.jsxs(be,{className:"border-[var(--gold-dark)]/25",children:[e.jsxs(je,{children:[e.jsx(ve,{className:"text-base",children:"Import a Deal Format"}),e.jsx(we,{children:"Bring a Deal Format archive back in. Its assertions land as pending for your review in the Truth Layer - nothing is auto-confirmed. (v0 imports assertions; other entities follow.)"})]}),e.jsxs(ke,{className:"space-y-2",children:[e.jsx("input",{ref:A,type:"file",accept:".zip",className:"hidden",onChange:k=>{var b;const O=(b=k.target.files)==null?void 0:b[0];O&&C(O)}}),e.jsxs(K,{type:"button",variant:"outline",className:"gap-2",disabled:r!==null,onClick:()=>{var k;return(k=A.current)==null?void 0:k.click()},children:[r==="deal_format_import"?e.jsx(pe,{className:"h-4 w-4 animate-spin"}):e.jsx(Tt,{className:"h-4 w-4"}),"Import Deal Format"]})]})]})]}),e.jsxs("section",{className:"space-y-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Themed campaign bundles"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Curated slices for board prep, diligence, and quarterly reviews. ",H," per bundle (heur
63istic)."]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(yt,{icon:e.jsx(Cn,{className:"h-5 w-5 text-oposgold"}),title:"Board meeting prep",description:"KPIs, top risks, recent outputs, attention items.",sizeHint:H,loading:r==="board_prep",onClick:()=>void E("board_prep"),disabled:r!==null}),e.jsx(yt,{icon:e.jsx(js,{className:"h-5 w-5 text-oposgold"}),title:"Financial / diligence workbook",description:"Insights, documents index, risks, campaign row, financial/VCP drafts (due diligence bundle).",sizeHint:H,loading:r==="due_diligence",onClick:()=>void E("due_diligence"),disabled:r!==null}),e.jsx(yt,{icon:e.jsx(Mn,{className:"h-5 w-5 text-oposgold"}),title:"Quarterly review",description:"Activity, outputs, KPIs, initiatives, plus quarterly summary stub.",sizeHint:H,loading:r==="quarterly_review",onClick:()=>void E("quarterly_review"),disabled:r!==null})]}),g&&r&&r!=="full"&&r!=="activity"&&r!=="json"?e.jsx("p",{className:"text-xs text-muted-foreground",children:g.stage}):null]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Spreadsheets & logs"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Lightweight CSV exports for analysis in Excel or your data warehouse."}),e.jsxs(be,{children:[e.jsxs(je,{children:[e.jsx(ve,{className:"text-base",children:"Structured CSVs"}),e.jsx(we,{children:"Insights, documents, KPIs, risks, decisions, and activity (activity opens export dialog for row cap)."})]}),e.jsxs(ke,{className:"flex flex-wrap gap-2",children:[e.jsxs(K,{variant:"outline",size:"sm",className:"gap-1",disabled:r!==null,onClick:()=>{M(c,"insights.csv","insights_csv"),n({title:"Insights CSV"})},children:[e.jsx(me,{fileType:"csv",className:"h-4 w-4"})," Insights CSV"]}),e.jsxs(K,{variant:"outline",size:"sm",className:"gap-1",disabled:r!==null,onClick:()=>{M(I,"documents_index.csv","documents_csv"),n({title:"Documents CSV"})},children:[e.jsx(me,{fileType:"csv",className:"h-4 w-4"})," Documents CSV"]}),e.jsxs(K,{variant:"outline",size:"sm",className:"gap-1",disabled:r!==null,onClick:()=>{M(m,"risks.csv","risks_csv"),n({title:"Risks CSV"})},children:[e.jsx(me,{fileType:"csv",className:"h-4 w-4"})," Risks CSV"]}),e.jsxs(K,{variant:"outline",size:"sm",className:"gap-1",disabled:r!==null,onClick:()=>{M(p,"kpis.csv","kpis_csv"),n({title:"KPIs CSV"})},children:[e.jsx(me,{fileType:"csv",className:"h-4 w-4"})," KPIs CSV"]}),e.jsxs(K,{variant:"outline",size:"sm",className:"gap-1",disabled:r!==null,onClick:()=>{M(j,"decisions.csv","decisions_csv"),n({title:"Decisions CSV"})},children:[e.jsx(me,{fileType:"csv",className:"h-4 w-4"})," Decisions CSV"]}),e.jsxs(K,{variant:"outline",size:"sm",className:"gap-1",disabled:r!==null,onClick:()=>void R(),children:[r==="activity"?e.jsx(pe,{className:"h-4 w-4 animate-spin"}):e.jsx(me,{fileType:"csv",className:"h-4 w-4"}),"Activity log CSV"]})]})]})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Custom JSON snapshot"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Portable bundle of campaign row, assertions, risks, KPIs, and decisions."}),e.jsxs(K,{type:"button",variant:"secondary",size:"sm",className:"gap-1",disabled:r!==null,onClick:()=>void $(),children:[r==="json"?e.jsx(pe,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(me,{fileType:"json",className:"h-3.5 w-3.5"}),"Download JSON snapshot"]})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Export history"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recent downloads for this campaign (sponsor-only log)."}),o.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No exports logged yet in this session."}):e.jsx("ul",{className:"max-h-48 space-y-1 overflow-y-auto rounded-md border border-border p-2 text-xs",children:o.map(k=>e.jsxs("li",{className:"flex flex-wrap justify-between gap-2 border-b border-border/50 py-1 last:border-0",children:[e.jsx("span",{className:"font-medium",children:k.export_kind}),e.jsx("span",{className:"text-muted-foreground",children:k.filename}),e.jsxs("span",{className:"text-muted-foreground",children:[Mt(new Date(k.created_at),"MMM d HH:mm")," · ",(k.byte_size/1024).toFixed(1)," KB"]}
63)]},k.id))})]})]})}function yt({icon:t,title:s,description:n,sizeHint:a,onClick:i,loading:c,disabled:u}){return e.jsxs(be,{className:G("border-oposgold/20",c&&"ring-1 ring-oposgold/30"),children:[e.jsx(je,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"rounded-lg bg-navy/10 p-2",children:t}),e.jsxs("div",{children:[e.jsx(ve,{className:"text-sm",children:s}),e.jsx(we,{className:"text-xs",children:n}),a?e.jsxs("p",{className:"mt-1 text-step-caption text-muted-foreground",children:["Size estimate: ",a]}):null]})]})}),e.jsx(ke,{children:e.jsxs(K,{type:"button",size:"sm",variant:"secondary",className:"w-full gap-1",disabled:u,onClick:i,children:[c?e.jsx(pe,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(me,{fileType:"zip",className:"h-3.5 w-3.5"}),"Download"]})})]})}function as(t){return t.format==="percent"||t.format==="ratio",t.current>=t.target}function Ya({campaignId:t}){const{report:s,isLoading:n}=ba(t),a=Je(t),i=dt(t),c=Pt(t),u=ys(t),m=ut(t),p=gs(t),j=a.isError||i.isError||c.isError||u.isError||m.isError||p.isError,o=()=>{a.refetch(),i.refetch(),c.refetch(),u.refetch(),m.refetch(),p.refetch()},g=v.useMemo(()=>a.data??[],[a.data]),{data:d}=ct(t),r=((d==null?void 0:d.total)??g.length)>500&&g.length>=500,h=v.useMemo(()=>i.data??[],[i.data]),x=v.useMemo(()=>p.data??[],[p.data]),N=v.useMemo(()=>c.data??[],[c.data]),l=v.useMemo(()=>u.data??[],[u.data]),_=v.useMemo(()=>m.data??[],[m.data]),A=v.useMemo(()=>Xa(g,h,x,N,l,_),[g,h,x,N,l,_]),C=v.useMemo(()=>ar(g,h,x,N,l,_),[g,h,x,N,l,_]),E=g.filter(M=>{const $=M.metadata;return $&&typeof $=="object"&&!Array.isArray($)?$.has_contradiction===!0:!1}),R=v.useMemo(()=>{const M=Date.now(),$=30*86400*1e3,I=g.filter(b=>{if(b.status!=="pending")return!1;const L=new Date(b.created_at).getTime();return M-L>$}).length,T=g.filter(b=>b.confidence==null?!1:Number(b.confidence)<.5).length,H=new Set(g.map(b=>b.document_id).filter(b=>!!b)),k=h.filter(b=>!H.has(b.id)).length,O=N.length===0;return{staleInsights:I,lowConfidence:T,orphanedDocuments:k,emptyKpis:O}},[g,h,N]);return e.jsxs("div",{className:"space-y-8",children:[e.jsx(ra,{campaignId:t,report:s,isLoading:n,size:"full"}),e.jsxs("section",{children:[e.jsx("h3",{className:"mb-3 text-sm font-semibold text-foreground",children:"Governance checklist"}),j?e.jsx(Le,{noun:"the governance checklist",description:"One or more of the queries behind these counts failed, so every row would report zero - an all-clear we cannot honestly give.",onRetry:o}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"Heuristic signals from this campaign's loaded data - use as a review queue, not an audit opinion."}),e.jsxs("div",{className:"space-y-2 rounded-lg border border-navy/10 bg-muted/15 p-3 dark:bg-muted/10",children:[e.jsx(Ge,{label:"Stale pending insights",count:R.staleInsights,helper:"Pending insights older than 30 days.",campaignId:t}),e.jsx(Ge,{label:"Low-confidence insights",count:R.lowConfidence,helper:"Confidence score under 0.5.",campaignId:t}),e.jsx(Ge,{label:"Orphaned documents",count:R.orphanedDocuments,helper:"Uploaded files with no linked insight yet.",campaignId:t}),e.jsx(Ge,{label:"Empty KPI set",count:R.emptyKpis?1:0,helper:"No KPI rows for this campaign.",campaignId:t,emptyAsIssue:!0})]})]})]}),e.jsxs("section",{children:[e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Health checklist"}),r?e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"Insight-based metrics below are based on the latest 500 loaded insights, not the full campaign total."}):null,e.jsx("div",{className:"space-y-3",children:A.map(M=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{children:M.label}),e.jsxs("span",{className:"tabular-nums text-muted-foreground",children:[sr(M)," / ",nr(M),as(M)?e.jsx(ie,{variant:"outline",className:"ml-2 border-navy/35 text-navy dark:text-oposgold",children:"Pass"}):e.jsx(ie,{variant:"outline",className:"ml-2 border-oposgold/50 text-amber-900 dark:text-amber-100",children:"Gap"})]})]}),e.jsx(Ct,{value:Math.min(100,M.current/Math.max(M.target,.01)*100),className:G("h-2",as(M)?"":"opacity-90")})]},M.label))})]}),e.jsxs("section",{children:[e.jsxs("h3",{className:"mb-3 flex items-center gap-2 text-sm font-medium",children:["Contradiction flags",E.length>0?e.jsx(ie,{variant:"destructive",className:"text-step-caption",children:E.length}):null]}),E.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No unresolved contradiction flags on insights."}):e.jsx("div",{className:"space-y-3",children:E.map(M=>e.jsxs(Ts,{variant:"default",className:"border-amber-200 bg-amber-50/50 dark:border-amber-900/40 dark:bg-amber-950/20",children:[e.jsx(Ot,{className:"h-4 w-4 text-amber-600"}),e.jsx(Os,{className:"text-sm",children:"Insight needs review"}),e.jsxs($s,{className:"text-xs",children:[e.jsx("p",{className:"mb-2 line-clamp-3",children:M.content}),e.jsx(Za,{campaignId:t})]})]},M.id))})]}),e.jsxs("section",{children:[e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Data freshness"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:C.map(M=>e.jsxs("div",{className:G("rounded-lg border px-3 py-2 text-xs",M.tone==="ok"&&"border-emerald-200 bg-emerald-50/50 dark:border-emerald-900/40",M.tone==="mid"&&"border-amber-200 bg-amber-50/40 dark:border-amber-900/40",M.tone==="stale"&&"animate-pulse border-red-200 bg-red-50/40 dark:border-red-900/40"),children:[e.jsx("p",{className:"font-medium",children:M.label}),e.jsx("p",{className:"text-muted-foreground",children:M.ageLabel})]},M.label))})]})]})}function Ge({label:t,count:s,helper:n,campaignId:a,emptyAsIssue:i}){const c=s>0;return e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-border/60 py-2 last:border-0",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:t}),e.jsx("p",{className:"text-step-caption text-muted-foreground",children:n})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ie,{variant:"outline",className:"tabular-nums",children:s}),c?e.jsx(Ae,{to:`/campaigns/${a}`,className:"text-xs font-medium text-navy underline underline-offset-2 dark:text-oposgold",children:"Go fix"}):e.jsx("span",{className:"text-step-caption text-muted-foreground",children:"OK"})]})]})}function Za({campaignId:t}){return e.jsx(Ae,{to:`/campaigns/${t}`,className:"text-xs font-medium text-navy underline underline-offset-2 dark:text-oposgold",children:"Go fix - open campaign"})}function Xa(t,s,n,a,i,c){var h;const u=t.length,m=t.filter(x=>x.status==="confirmed"||x.status==="edited").length,p=u===0?0:m/u*100,j=Bt(t),o=s.length===0?100:s.filter(x=>x.processing_status==="completed").length/s.length*100,g=(h=n[0])!=null&&h.created_at?new Date(n[0].created_at).getTime():null,d=g==null?999:(Date.now()-g)/(86400*1e3),r=
63d<=14?100:Math.max(0,100-(d-14)*5);return[{label:"Confirmation rate",current:p,target:80,format:"percent"},{label:"Category coverage",current:er(j),target:75,format:"percent"},{label:"Document processing",current:o,target:90,format:"percent"},{label:"Output currency (≤14d)",current:r,target:80,format:"percent"},{label:"Value creation depth (KPI/init/risk)",current:tr(a.length,i.length,c.length),target:100,format:"percent"}]}function er(t){return t/ot.length*100}function tr(t,s,n){const a=Math.min(1,t/3)*33,i=Math.min(1,s/2)*33,c=Math.min(1,n/2)*34;return a+i+c}function sr(t){return t.format==="percent"?`${Math.round(t.current)}%`:String(Math.round(t.current))}function nr(t){return t.format==="percent"?`${Math.round(t.target)}%`:String(Math.round(t.target))}function ar(t,s,n,a,i,c){const u=(m,p)=>{const j=p.length===0?null:new Date(Math.max(...p.map(d=>d.getTime())));if(!j)return{label:m,ageLabel:"No data",tone:"mid"};const o=(Date.now()-j.getTime())/(86400*1e3),g=o<7?"ok":o<30?"mid":"stale";return{label:m,ageLabel:`${o<1?"<1":Math.floor(o)}d since last update`,tone:g}};return[u("Insights",t.map(m=>new Date(m.created_at))),u("Documents",s.map(m=>new Date(m.created_at))),u("Outputs",n.map(m=>new Date(m.created_at))),u("KPIs",a.map(m=>new Date(m.updated_at))),u("Initiatives",i.map(m=>new Date(m.updated_at))),u("Risks",c.map(m=>new Date(m.created_at)))]}function rr(t){const s=t.toLowerCase();return s.includes("copilot")||s.includes("openai")||s.includes("assistant")||s.includes("llm")||s.includes("ai_")||s.includes("_ai")?"ai":s.includes("system")||s.includes("edge")||s.includes("cron")||s.includes("sync")||s.includes("process_document")?"system":"user"}function ir({campaignId:t}){const{user:s}=Ne(),[n,a]=v.useState("all"),[i,c]=v.useState("all"),{data:u=[],error:m,isLoading:p,refetch:j}=He({queryKey:["activity-log-dl",t],queryFn:async()=>{const{data:r,error:h}=await B.from("activity_log").select("*").eq("campaign_id",t).order("created_at",{ascending:!1}).limit(500);if(h)throw h;return r??[]},enabled:!!s&&!!t}),o=v.useMemo(()=>{const r=new Set;for(const h of u)r.add(h.action_type);return Array.from(r).sort()},[u]),g=v.useMemo(()=>{let r=u;return i!=="all"&&(r=r.filter(h=>rr(h.action_type)===i)),n==="__ids_workflow__"?r.filter(h=>h.action_type.startsWith("ids_")):n==="all"?r:r.filter(h=>h.action_type===n)},[u,n,i]),d=[{id:"all",label:"All"},{id:"system",label:"System"},{id:"user",label:"User"},{id:"ai",label:"AI"}];return e.jsxs("div",{className:"space-y-4",children:[m?e.jsxs(Ts,{variant:"destructive",children:[e.jsx(Os,{children:"Could not load activity"}),e.jsx($s,{children:m instanceof Error?m.message:"Unknown error"})]}):null,e.jsx("div",{className:"flex flex-wrap gap-2",children:d.map(r=>e.jsx("button",{type:"button",onClick:()=>c(r.id),className:G("rounded-full border px-3 py-1 text-xs font-medium transition-colors",i===r.id?"border-[var(--navy-deep)] surface-navy text-[var(--gold-dark)]":"border-border bg-background text-muted-foreground hover:bg-muted/60"),children:r.label},r.id))}),e.jsxs("p",{className:"text-step-caption text-muted-foreground",children:["Timeline shows up to ",e.jsx("span",{className:"font-medium text-foreground",children:"500"})," rows. Export CSV pulls up to"," ",e.jsx("span",{className:"font-medium text-foreground",children:"5,000"})," rows for the same campaign."]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Se,{value:n,onValueChange:a,children:[e.jsx(Ce,{className:"w-[220px]",children:e.jsx(Me,{placeholder:"Filter by action"})}),e.jsxs(Ee,{children:[e.jsx(X,{value:"all",children:"All actions"}),e.jsx(X,{value:"__ids_workflow__",children:"Decision workflow actions"}),o.map(r=>e.jsx(X,{value:r,children:Zt(r,r.replace(/_/g," "))},r))]})]}),e.jsx(St,{format:"csv",label:"Export CSV (up to 5k)",variant:"outline",size:"sm",onClick:()=>void Ps(t)})]}),e.jsx("div",{className:"relative border-l-2 border-oposgold/35 pl-4",children:p?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading activity…"}):m?e.jsx(Le,{compact:!0,noun:"activity",onRetry:()=>void j()}):g.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No activity rows for this filter."}):e.jsx("ul",{className:"space-y-5",children:g.map(r=>e.jsxs("li",{className:"relative",children:[e.jsx("span",{className:G("absolute -left-[21px] top-1.5 h-2.5 w-2.5 rounded-full border-2 border-background","bg-navy ring-2 ring-oposgold/40")}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[new Date(r.created_at).toLocaleStr
63ing()," ",e.jsx("span",{className:"font-medium text-foreground",children:Zt(r.action_type,r.action_type.replace(/_/g," "))})]}),e.jsx("p",{className:"text-sm",children:r.description})]},r.id))})})]})}const rs=[{name:"campaigns",description:"Core campaign / portfolio company workspace.",documentedRlsPolicyCount:2,columns:[{name:"id",type:"uuid",nullable:!1,description:"Primary key"},{name:"company_name",type:"text",description:"Display name"},{name:"attention_items",type:"jsonb",description:"Computed attention signals"},{name:"financial_scenarios",type:"jsonb",description:"Stored scenario JSON"},{name:"value_bridge",type:"jsonb",description:"Value bridge structure"},{name:"dashboard_layout",type:"text",description:"Reports dashboard widget keys"},{name:"status",type:"text",description:"active | archived"}]},{name:"assertions",description:"Insight Layer rows (extracted or manual insights).",documentedRlsPolicyCount:3,columns:[{name:"id",type:"uuid",nullable:!1},{name:"campaign_id",type:"uuid",nullable:!1},{name:"content",type:"text"},{name:"status",type:"assertion_status"},{name:"category",type:"text"},{name:"confidence",type:"numeric"},{name:"metadata",type:"jsonb",description:"Review metadata, contradiction flags"},{name:"document_id",type:"uuid"}]},{name:"documents",description:"Uploaded files metadata (binaries in storage).",documentedRlsPolicyCount:3,columns:[{name:"id",type:"uuid",nullable:!1},{name:"campaign_id",type:"uuid",nullable:!1},{name:"file_name",type:"text"},{name:"processing_status",type:"text"},{name:"storage_path",type:"text"}]},{name:"outputs",description:"Generated reports and structured outputs.",documentedRlsPolicyCount:2,columns:[{name:"id",type:"uuid",nullable:!1},{name:"campaign_id",type:"uuid",nullable:!1},{name:"output_type",type:"output_type"},{name:"title",type:"text"},{name:"content_json",type:"jsonb"},{name:"version",type:"int"}]},{name:"activity_log",description:"Audit trail of user and system actions.",documentedRlsPolicyCount:2,columns:[{name:"id",type:"uuid",nullable:!1},{name:"campaign_id",type:"uuid",nullable:!1},{name:"action_type",type:"text"},{name:"description",type:"text"},{name:"actor_id",type:"uuid"},{name:"details",type:"jsonb"},{name:"created_at",type:"timestamptz"}]},{name:"campaign_risks",description:"Risk register entries.",documentedRlsPolicyCount:2,columns:[{name:"id",type:"uuid",nullable:!1},{name:"campaign_id",type:"uuid",nullable:!1},{name:"risk_id",type:"text"},{name:"impact_score",type:"numeric"}]},{name:"campaign_kpis",description:"KPI engine rows.",documentedRlsPolicyCount:2,columns:[{name:"id",type:"uuid",nullable:!1},{name:"campaign_id",type:"uuid",nullable:!1},{name:"name",type:"text"},{name:"current_value",type:"text"},{name:"history",type:"jsonb"}]},{name:"initiatives",description:"Value creation initiatives.",documentedRlsPolicyCount:2,columns:[{name:"id",type:"uuid",nullable:!1},{name:"campaign_id",type:"uuid",nullable:!1},{name:"title",type:"text"},{name:"status",type:"text"}]},{name:"platform_experts",description:"Admin-curated experts powering the Expert Directory.",documentedRlsPolicyCount:4,columns:[{name:"id",type:"text",nullable:!1},{name:"name",type:"text"},{name:"hourly_rate_usd",type:"numeric"},{name:"status",type:"text",description:"active | inactive"}]},{name:"expert_engagements",description:"Requested / active expert engagements per campaign.",documentedRlsPolicyCount:3,columns:[{name:"id",type:"uuid",nullable:!1},{name:"campaign_id",type:"uuid",nullable:!1},{name:"expert_id",type:"text"},{name:"status",type:"text"},{name:"fee_estimate_usd",type:"numeric"},{name:"scope_summary",type:"text"}]},{name:"data_exports",description:"Audit log of Data Layer and header ZIP exports (sponsor).",documentedRlsPolicyCount:2,columns:[{name:"id",type:"uuid",nullable:!1},{name:"campaign_id",type:"uuid",nullable:!1},{name:"export_kind",type:"text"},{name:"filename",type:"text"},{name:"byte_size",type:"bigint"}]},{name:"api_keys",description:"Developer API keys (SHA-256 hash at rest; routes TBD).",documentedRlsPolicyCount:1,columns:[{name:"id",type:"uuid",nullable:!1},{name:"prefix",type:"text"},{name:"hash",type:"text"},{name:"revoked_at",type:"timestamptz"}]}];function or(){const[t,s]=v.useState(""),n=v.useMemo(()=>{const a=t.trim().toLowerCase();return a?rs.filter(i=>{const c=i.name.toLowerCase().includes(a),u=i.description.toLowerCase().includes(a),m=i.columns.some(p=>p.name.toLowerCase().includes(a)||(p.description??"").toLowerCase().includes(a)||p.type.toLowerCase().includes(a));return c||u||m}):rs},[t]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Reference schema for integrations - not a live database console. RLS counts are documented from migrations, not queried at runtime."}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx($t,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(it,{className:"pl-9",placeholder:"Search tables, columns, descriptions…",value:t,onChange:a=>s(a.target.value)})]}),e.jsx("div",{className:"space-y-2",children:n.map(a=>e.jsxs(Ss,{defaultOpen:n.length<=4,children:[e.jsxs(Cs,{className:"flex w-full items-center justify-between rounded-lg border bg-card px-3 py-2 text-left text-sm font-medium hover:bg-muted/50",children:[e.jsxs("span",{children:[a.name,e.jsxs("span",{className:"ml-2 font-normal text-muted-foreground",children:["- ",a.description]}),a.documentedRlsPolicyCount!=null?e.jsxs("span",{className:"ml-2 roun
63ded border border-navy/20 px-1.5 py-0.5 text-step-caption font-normal text-muted-foreground",children:["RLS policies (documented): ",a.documentedRlsPolicyCount]}):null]}),e.jsx(Rt,{className:"h-4 w-4 shrink-0 transition-transform [[data-state=open]_&]:rotate-180"})]}),e.jsx(Ms,{children:e.jsx("div",{className:"overflow-x-auto border-x border-b rounded-b-lg",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/40 text-left",children:[e.jsx("th",{className:"p-2 font-medium",children:"Column"}),e.jsx("th",{className:"p-2 font-medium",children:"Type"}),e.jsx("th",{className:"p-2 font-medium",children:"Notes"})]})}),e.jsx("tbody",{children:a.columns.map(i=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"p-2 font-mono",children:i.name}),e.jsx("td",{className:"p-2 font-mono text-muted-foreground",children:i.type}),e.jsxs("td",{className:G("p-2 text-muted-foreground",i.nullable===!1&&"text-foreground"),children:[i.nullable===!1?"required · ":"",i.description??"-"]})]},i.name))})]})})})]},a.name))})]})}function lr({campaignId:t}){const{user:s}=Ne(),{toast:n}=Ue(),a=rt(),i=v.useRef(null),[c,u]=v.useState([]),[m,p]=v.useState([]),[j,o]=v.useState(""),[g,d]=v.useState("data_import"),r=kt({mutationFn:async()=>{if(!s||!j)throw new Error("Map a content column");const x=m.map(l=>{const _=l[j],A=typeof _=="string"?_.trim():String(_??"").trim();if(!A)return null;const C=l.category??l.Category??l["Insight category"],E=typeof C=="string"?C.trim():null;return{campaign_id:t,content:A,category:E||"general",source_type:g,actor_role:"human",status:"pending",confidence:null,metadata:{import_batch:"data_layer_tab"}}}).filter(Boolean);if(x.length===0)throw new Error("No rows with content");const{error:N}=await B.from("assertions").insert(x);if(N)throw N;return x.length},onSuccess:async x=>{a.invalidateQueries({queryKey:["assertions",t]}),await sn({campaignId:t,actionType:"data_import_applied",description:`Imported ${x} pending insights`,details:{source:g}}),n({title:"Import Complete",description:`${x} rows added as pending.`}),p([]),u([])},onError:x=>{n({title:"Import failed",description:x.message||"Could not import rows.",variant:"destructive"})}}),h=async x=>{try{const N=ja(await x.arrayBuffer(),{type:"array"}),l=N.Sheets[N.SheetNames[0]??""];if(!l){n({title:"Empty file",variant:"destructive"});return}const _=va.sheet_to_json(l,{defval:""});if(_.length===0){n({title:"No data rows",variant:"destructive"});return}const A=Object.keys(_[0]??{}),C=2e3;u(A),p(_.slice(0,C)),_.length>C&&n({title:"Large file",description:`Showing and importing the first ${C.toLocaleString()} of ${_.length.toLocaleString()} rows.`});const E=A.find(R=>/content|insight|text|assertion/i.test(R))??A[0]??"";o(E)}catch{n({title:"Could not parse file",variant:"destructive"})}};return e.jsx("div",{className:"space-y-4",children:e.jsxs(be,{children:[e.jsxs(je,{children:[e.jsx(ve,{className:"text-base",children:"CSV / Excel → pending insights"}),e.jsxs(we,{children:["Rows become ",e.jsx("code",{className:"text-xs",children:"assertions"})," with status ",e.jsx("code",{className:"text-xs",children:"pending"}),". Sponsor confirms in Truth Layer."]})]}),e.jsxs(ke,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(st,{children:"Source label"}),e.jsxs(Se,{value:g,onValueChange:x=>d(x),children:[e.jsx(Ce,{className:"w-[200px]",children:e.jsx(Me,{})}),e.jsxs(Ee,{children:[e.jsx(X,{value:"data_import",children:"data_import"}),e.jsx(X,{value:"manual_import",children:"manual_import"})]})]})]}),e.jsx("input",{ref:i,type:"file",accept:".csv,.xlsx,.xls",className:"hidden",onChange:x=>{var l;const N=(l=x.target.files)==null?void 0:l[0];x.target.value="",N&&h(N)}}),e.jsxs(K,{type:"button",variant:"secondary",className:"gap-1",onClick:()=>{var x;return(x=i.current)==null?void 0:x.click()},children:[e.jsx(Tt,{className:"h-3.5 w-3.5"}),"Choose file"]})]}),c.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(st,{children:"Content column"}),e.jsxs(Se,{value:j,onValueChange:o,children:[e.jsx(Ce,{className:"max-w-md",children:e.jsx(Me,{})}),e.jsx(Ee,{children:c.map(x=>e.jsx(X,{value:x,children:x},x))})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Optional: include a ",e.jsx("span",{className:"font-mono",children:"category"})," column for assertion category."]})]}),e.jsx("div",{className:"overflow-x-auto rounded-md border",children:e.jsxs(zt,{children:[e.jsx(It,{children:e.jsx(re,{children:c.slice(0,6).map(x=>e.jsx(ge,{children:x},x))})}),e.jsx(Ft,{children:m.slice(0,8).map((x,N)=>e.jsx(re,{children:c.slice(0,6).map(l=>e.jsx(ee,{className:"max-w-[180px] truncate text-xs",children:String(x[l]??"")},l))},N))})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Preview limited to 8 rows · import processes up to 200 rows."}),e.jsx(K,{type:"button",onClick:()=>r.mutate(),disabled:r.isPending||!j,children:r.isPending?"Importing…":"Import as pending insights"})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload a spreadsheet to map columns."})]})]})})}async function cr(t){const s=await crypto.subtle.digest("SHA-256",
63new TextEncoder().encode(t));return Array.from(new Uint8Array(s)).map(n=>n.toString(16).padStart(2,"0")).join("")}function dr(){return`opos_${typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID().replace(/-/g,""):String(Date.now())}`}function ur(){const{user:t}=Ne(),{toast:s}=Ue(),n=rt(),[a,i]=v.useState("Developer key"),[c,u]=v.useState(null),m=He({queryKey:["api-keys",t==null?void 0:t.id],queryFn:async()=>{const{data:o,error:g}=await B.from("api_keys").select("id, name, prefix, created_at, last_used_at, revoked_at").order("created_at",{ascending:!1});if(g)throw g;return o??[]},enabled:!!t}),p=kt({mutationFn:async()=>{if(!t)throw new Error("Sign in required");const o=a.trim()||"API key",g=dr(),d=g.slice(0,12),r=await cr(g),{error:h}=await B.from("api_keys").insert({user_id:t.id,name:o,prefix:d,hash:r});if(h)throw h;return g},onSuccess:o=>{n.invalidateQueries({queryKey:["api-keys",t==null?void 0:t.id]}),u(o),s({title:"API key created",description:"Copy it now - it won’t be shown again."})},onError:o=>{s({title:"Could not create key",description:o instanceof Error?o.message:"Try again.",variant:"destructive"})}}),j=kt({mutationFn:async o=>{const{error:g}=await B.from("api_keys").update({revoked_at:new Date().toISOString()}).eq("id",o);if(g)throw g},onSuccess:()=>{n.invalidateQueries({queryKey:["api-keys",t==null?void 0:t.id]}),s({title:"Key revoked"})}});return e.jsxs("div",{className:"space-y-4",children:[e.jsx(mr,{}),e.jsxs(be,{children:[e.jsxs(je,{children:[e.jsxs(ve,{className:"flex items-center gap-2 text-base",children:[e.jsx(En,{className:"h-4 w-4"}),"Create key"]}),e.jsx(we,{children:"Keys are stored as a hash - only a prefix is visible afterward."})]}),e.jsxs(ke,{className:"space-y-3 max-w-md",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(st,{htmlFor:"key-name",children:"Label"}),e.jsx(it,{id:"key-name",value:a,onChange:o=>i(o.target.value),placeholder:"e.g. Partner integration"})]}),e.jsxs(K,{type:"button",disabled:p.isPending,onClick:()=>p.mutate(),children:[p.isPending?e.jsx(pe,{className:"h-4 w-4 animate-spin"}):null,"Generate key"]}),c?e.jsxs("div",{className:"rounded-md border border-oposgold/40 bg-muted/30 p-3 font-mono text-xs break-all",children:[e.jsx("p",{className:"mb-1 text-step-caption font-sans text-muted-foreground",children:"Copy now (shown once):"}),c]}):null]})]}),e.jsxs(be,{children:[e.jsxs(je,{children:[e.jsx(ve,{className:"text-base",children:"Your keys"}),e.jsx(we,{children:"Developer API endpoints launch later - revocation works today."})]}),e.jsx(ke,{children:m.isError?e.jsx(Le,{compact:!0,noun:"API keys",onRetry:()=>void m.refetch()}):m.isLoading?e.jsxs("div",{className:"space-y-2","aria-busy":"true","aria-label":"Loading keys",children:[e.jsx(Nt,{className:"h-10 w-full"}),e.jsx(Nt,{className:"h-10 w-full"})]}):(m.data??[]).length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No keys yet."}):e.jsx("ul",{className:"space-y-2 text-sm",children:(m.data??[]).map(o=>e.jsxs("li",{className:"flex flex-wrap items-center justify-between gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:o.name}),e.jsxs("span",{className:"ml-2 text-muted-foreground",children:[o.prefix,"… · ",Mt(new Date(o.created_at),"MMM d yyyy")]}),o.revoked_at?e.jsx("span",{className:"ml-2 text-destructive",children:"Revoked"}):null]}),o.revoked_at?null:e.jsx(K,{type:"button",size:"icon",variant:"ghost","aria-label":"Revoke",onClick:()=>j.mutate(o.id),disabled:j.isPending,children:e.jsx(An,{className:"h-4 w-4"})})]},o.id))})})]})]})}function mr(){return e.jsxs("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-950 dark:text-amber-100",children:[e.jsx("strong",{className:"font-semibold",children:"Stub"})," - HTTP API routes are not wired yet. Keys are hashed at rest; treat them like passwords until the developer gateway ships."]})}function pr(t){const{user:s}=Ne(),n=[...t].sort().join(",");return He({queryKey:["portfolio-dl-stats",n],queryFn:async()=>
63{if(t.length===0)return[];const[{data:a,error:i},{data:c,error:u},{data:m,error:p},{data:j,error:o}]=await Promise.all([B.from("assertions").select("id, campaign_id, status, category, metadata, created_at").in("campaign_id",t),B.from("documents").select("id, campaign_id, processing_status, created_at").in("campaign_id",t),B.from("outputs").select("id, campaign_id, created_at").in("campaign_id",t),B.from("campaign_risks").select("id, campaign_id").in("campaign_id",t)]);if(i)throw i;if(u)throw u;if(p)throw p;if(o)throw o;const g=a??[],d=c??[],r=m??[],h=j??[],[{data:x},{data:N}]=await Promise.all([B.from("campaign_kpis").select("campaign_id").in("campaign_id",t),B.from("initiatives").select("campaign_id").in("campaign_id",t)]),l=new Map,_=new Map;for(const I of t)l.set(I,0),_.set(I,0);for(const I of x??[]){const T=I.campaign_id;l.set(T,(l.get(T)??0)+1)}for(const I of N??[]){const T=I.campaign_id;_.set(T,(_.get(T)??0)+1)}const A=I=>{const T=new Map;for(const H of t)T.set(H,0);for(const H of I){const k=H.campaign_id;T.set(k,(T.get(k)??0)+1)}return T},C=A(g),E=A(d),R=A(r),M=A(h),$=[];for(const I of t){const T=g.filter(f=>f.campaign_id===I),H=T.length,k=T.filter(f=>f.status==="confirmed"||f.status==="edited").length,O=H===0?0:Math.round(k/H*100);let b=0,L=0;for(const f of T){const q=new Date(f.created_at).getTime();q>b&&(b=q)}const y=r.filter(f=>f.campaign_id===I);for(const f of y){const q=new Date(f.created_at).getTime();q>L&&(L=q)}const D=d.filter(f=>f.campaign_id===I),P=D.filter(f=>f.processing_status==="completed").length,{score:F}=zs({totalAssertions:H,confirmedAssertions:k,categoriesWithData:Bt(T),docsTotal:D.length,docsCompleted:P,kpiCount:l.get(I)??0,initiativeCount:_.get(I)??0,riskCount:M.get(I)??0,lastAssertionMs:b||null,lastOutputMs:L||null,contradictionCount:Is(T)});$.push({campaignId:I,assertions:C.get(I)??0,confirmed:k,confirmPct:O,documents:E.get(I)??0,outputs:R.get(I)??0,risks:M.get(I)??0,healthScore:F})}return $},enabled:!!s&&t.length>0})}function hr(){const{user:t}=Ne(),{data:s=[]}=nn(),{setCampaignId:n}=fs(),a=v.useMemo(()=>s.filter(r=>r.status!=="archived").map(r=>r.id),[s]),{data:i=[],isLoading:c,isError:u,refetch:m}=pr(a),p=v.useMemo(()=>{const r=new Map;for(const h of s)r.set(h.id,h.company_name??h.id.slice(0,8));return r},[s]),[j,o]=v.useState({key:"healthScore",dir:"desc"}),g=v.useMemo(()=>{const r=i.map(x=>({...x,name:p.get(x.campaignId)??x.campaignId})),h=j.dir==="asc"?1:-1;return[...r].sort((x,N)=>{if(j.key==="name")return x.name.localeCompare(N.name)*h;const l=x[j.key],_=N[j.key];return typeof l=="number"&&typeof _=="number"?(l-_)*h:0})},[i,p,j]),d=(r,h)=>e.jsx(ge,{className:"font-semibold",children:e.jsxs("button",{type:"button",className:"inline-flex w-full cursor-pointer select-none items-center hover:bg-muted/50",onClick:()=>o(x=>x.key===r?{key:r,dir:x.dir==="asc"?"desc":"asc"}:{key:r,dir:"desc"}),children:[h,j.key===r?j.dir==="asc"?" ↑":" ↓":""]})});return t?e.jsx("div",{className:"overflow-x-auto rounded-md border",children:e.jsxs(zt,{children:[e.jsx(It,{children:e.jsxs(re,{children:[d("name","Campaign"),d("assertions","Insights"),d("confirmPct","Confirm %"),d("documents","Docs"),d("outputs","Outputs"),d("risks","Risks"),d("healthScore","Health")]})}),e.jsx(Ft,{children:c?e.jsx(re,{children:e.jsx(ee,{colSpan:7,className:"text-center text-muted-foreground",children:"Loading portfolio…"})}):u?e.jsx(re,{children:e.jsx(ee,{colSpan:7,className:"p-0",children:e.jsx(Le,{compact:!0,noun:"portfolio stats",onRetry:()=>void m()})})}):g.length===0?e.jsx(re,{children:e.jsx(ee,{colSpan:7,className:"text-center text-muted-foreground",children:"No campaigns to compare."})}):g.map(r=>e.jsxs(re,{className:"cursor-pointer hover:bg-muted/40",onClick:()=>n(r.campaignId),children:[e.jsx(ee,{className:"font-medium",children:r.name}),e.jsx(ee,{className:"tabular-nums",children:r.assertions}),e.jsxs(ee,{className:G("tabular-nums",fr(r.confirmPct)),children:[r.confirmPct,"%"]}),e.jsx(ee,{className:"tabular-nums",children:r.documents}),e.jsx(ee,{className:"tabular-nums",children:r.outputs}),e.jsx(ee,{className:"tabular-nums",children:r.risks}
63),e.jsx(ee,{className:G("tabular-nums font-semibold",xr(r.healthScore)),children:r.healthScore})]},r.campaignId))})]})}):null}function fr(t){return t>=70?"text-emerald-700 dark:text-emerald-400":t>=40?"text-amber-700 dark:text-amber-400":"text-red-700 dark:text-red-400"}function xr(t){return t>=70?"text-emerald-700 dark:text-emerald-400":t>=45?"text-amber-700 dark:text-amber-400":"text-red-700 dark:text-red-400"}const he={company:{label:"Company",color:"var(--gold)",icon:ws,r:34,iconColor:"var(--navy)"},subject:{label:"Subjects",color:le[0],icon:Pn,r:23,iconColor:"white"},insight:{label:"Insights",color:le[1],icon:Dn,r:18,iconColor:"white"},document:{label:"Documents",color:le[3],icon:vs,r:16,iconColor:"white"},risk:{label:"Risks",color:"hsl(var(--destructive))",icon:Ot,r:17,iconColor:"white"},value_driver:{label:"Value drivers",color:le[4],icon:Ln,r:18,iconColor:"white"}},Lt={cites:"cites",supports:"supports",mitigates:"mitigates",targets:"targets",relates:"relates to",belongs:"belongs to"};function Vs(t,s){const n=new Set,a=new Set;return s.forEach((i,c)=>{i.source===t?(n.add(i.target),a.add(c)):i.target===t&&(n.add(i.source),a.add(c))}),{nodeIds:n,edgeIdx:a}}function gr(t,s,n){const a=new Map,i=(m,p)=>{let j=a.get(m);j||(j=new Set,a.set(m,j)),j.add(p)};for(const m of n)i(m.source,m.target),i(m.target,m.source);const c=new Set([t]);let u=[t];for(let m=0;m<s;m++){const p=[];for(const j of u)for(const o of a.get(j)??[])c.has(o)||(c.add(o),p.push(o));u=p}return c}function Hs(t,s){const n=(t.x+s.x)/2,a=(t.y+s.y)/2,i=s.x-t.x,c=s.y-t.y,u=Math.hypot(i,c)||1,m=Math.min(38,u*.13),p=n-c/u*m,j=a+i/u*m;return`M ${t.x.toFixed(1)} ${t.y.toFixed(1)} Q ${p.toFixed(1)} ${j.toFixed(1)} ${s.x.toFixed(1)} ${s.y.toFixed(1)}`}function Us(t,s,n){const{nodes:a,edges:i}=t,c=s/2,u=n/2,m=new Map,p=new Set(a.filter(d=>d.type==="company").map(d=>d.id)),j=d=>{const r=Math.sin(d*127.1+311.7)*43758.5453;return r-Math.floor(r)};a.forEach((d,r)=>{if(p.has(d.id)){m.set(d.id,{x:c,y:u});return}const h=r/Math.max(1,a.length)*Math.PI*2+j(r)*.9,x=130+j(r+99)*190;m.set(d.id,{x:c+Math.cos(h)*x,y:u+Math.sin(h)*x})});const o=160;for(let d=0;d<o;d++){const r=1-d/o;for(let h=0;h<a.length;h++)for(let x=h+1;x<a.length;x++){const N=m.get(a[h].id),l=m.get(a[x].id);let _=N.x-l.x,A=N.y-l.y,C=_*_+A*A;C<.01&&(_=j(h+d)-.5,A=j(x+d)-.5,C=.01);const E=Math.sqrt(C),R=9500/C*r,M=_/E*R,$=A/E*R;p.has(a[h].id)||(N.x+=M,N.y+=$),p.has(a[x].id)||(l.x-=M,l.y-=$)}for(const h of i){const x=m.get(h.source),N=m.get(h.target);if(!x||!N)continue;const l=N.x-x.x,_=N.y-x.y,A=Math.hypot(l,_)||.01,E=(A-135)*.02*r,R=l/A*E,M=_/A*E;p.has(h.source)||(x.x+=R,x.y+=M),p.has(h.target)||(N.x-=R,N.y-=M)}for(const h of a){if(p.has(h.id))continue;const x=m.get(h.id);x.x+=(c-x.x)*.006*r,x.y+=(u-x.y)*.006*r}}const g=52;for(const d of a){const r=m.get(d.id);r.x=Math.max(g,Math.min(s-g,r.x)),r.y=Math.max(g,Math.min(n-g,r.y))}return m}const yr={nodes:[{id:"c1",type:"company",label:"NovaTech Solutions",detail:"Mid-market DevOps SaaS - the active portfolio company."},{id:"s1",type:"subject",label:"Helios Cloud",detail:"Primary competitor in the mid-market segment."},{id:"s2",type:"subject",label:"DataForge",detail:"Bolt-on acquisition target - data-pipeline tooling."},{id:"s3",type:"subject",label:"Mid-market DevOps",detail:"The market the company plays in."},{id:"i1",type:"insight",label:"NRR 112%",detail:"Net revenue retention is healthy and expanding."},{id:"i2",type:"insight",label:"SMB logo churn rising",detail:"Churn is concentrated in the SMB cohort."},{id:"i3",type:"insight",label:"Gross margin 78%",detail:"Software-grade gross margin."},{id:"i4",type:"insight",label:"No VP of Sales",detail:"Sales is still founder-led; no second-line leader."},{id:"i5",type:"insight",label:"Cloud costs +40% YoY",detail:"Infrastructure spend is outpacing revenue."},{id:"i6",type:"insight",label:"Top 10 = 48% of ARR",detail:"Revenue is concentrated in a few accounts."},{id:"i7",type:"insight",label:"DataForge fills a gap",detail:"DataForge would complete the data-pipeline story."},{id:"i8",type:"insight",label:"Pricing below market",detail:"List pricing trails the closest comparable."},{id:"d1",type:"document",label:"CIM 2024.pdf",detail:"Confidential information memorandum."}
63,{id:"d2",type:"document",label:"Q3 board pack",detail:"Latest board reporting."},{id:"d3",type:"document",label:"Cohort analysis.xlsx",detail:"Customer cohort and retention model."},{id:"d4",type:"document",label:"DataForge teaser",detail:"Target one-pager."},{id:"d5",type:"document",label:"Cloud cost audit",detail:"Infrastructure spend review."},{id:"r1",type:"risk",label:"Customer concentration",detail:"Over-reliance on the top accounts.",metric:"$4.9M",metricValue:4.9},{id:"r2",type:"risk",label:"Key-person risk",detail:"Founder-dependent sales motion.",metric:"$2.1M",metricValue:2.1},{id:"r3",type:"risk",label:"Margin compression",detail:"Rising cloud spend erodes gross margin.",metric:"$3.4M",metricValue:3.4},{id:"r4",type:"risk",label:"SMB churn",detail:"Leaky SMB cohort drags net retention.",metric:"$1.6M",metricValue:1.6},{id:"v1",type:"value_driver",label:"Hire VP of Sales",detail:"Build a repeatable, second-line sales engine.",metric:"$1.8M",metricValue:1.8},{id:"v2",type:"value_driver",label:"Bolt-on: DataForge",detail:"Acquire to complete the platform.",metric:"$3.2M",metricValue:3.2},{id:"v3",type:"value_driver",label:"Cloud cost optimization",detail:"Re-architect to protect margin.",metric:"$1.1M",metricValue:1.1},{id:"v4",type:"value_driver",label:"Land-and-expand",detail:"Re-price and widen the expansion motion.",metric:"$2.4M",metricValue:2.4}],edges:[{source:"c1",target:"s1",kind:"relates"},{source:"c1",target:"s2",kind:"targets"},{source:"c1",target:"s3",kind:"belongs"},{source:"c1",target:"i1",kind:"supports"},{source:"c1",target:"i3",kind:"supports"},{source:"c1",target:"i6",kind:"supports"},{source:"i1",target:"d3",kind:"cites"},{source:"i2",target:"d3",kind:"cites"},{source:"i2",target:"r4",kind:"supports"},{source:"i3",target:"d1",kind:"cites"},{source:"i5",target:"d5",kind:"cites"},{source:"i5",target:"r3",kind:"supports"},{source:"i6",target:"d2",kind:"cites"},{source:"i6",target:"r1",kind:"supports"},{source:"i4",target:"r2",kind:"supports"},{source:"i4",target:"v1",kind:"mitigates"},{source:"i7",target:"d4",kind:"cites"},{source:"i7",target:"s2",kind:"relates"},{source:"i7",target:"v2",kind:"supports"},{source:"i8",target:"s3",kind:"relates"},{source:"i8",target:"v4",kind:"supports"},{source:"r1",target:"v4",kind:"mitigates"},{source:"r2",target:"v1",kind:"mitigates"},{source:"r3",target:"v3",kind:"mitigates"},{source:"r4",target:"v4",kind:"mitigates"},{source:"v2",target:"s2",kind:"targets"}]},ze=900,Qe=620,br=new Set;function jr({graph:t,selectedId:s,hoveredId:n,onSelect:a,onHover:i,hiddenTypes:c=br,matchIds:u=null,focusIds:m=null}){const p=v.useMemo(()=>Us(t,ze,Qe),[t]),j=Math.min(.016,1/Math.max(1,t.nodes.length)),o=Math.min(.012,.8/Math.max(1,t.edges.length)),g=v.useMemo(()=>{const y=new Map;for(const D of t.edges)y.set(D.source,(y.get(D.source)??0)+1),y.set(D.target,(y.get(D.target)??0)+1);return y},[t.edges]),d=v.useMemo(()=>new Set(t.nodes.filter(y=>y.type==="company").map(y=>y.id)),[t.nodes]),r=(y,D)=>{const P=he[D].r,F=g.get(y)??0;return D==="company"?P+Math.min(10,F):P+Math.min(12,Math.sqrt(F)*3.2)},h=v.useMemo(()=>new Set(t.nodes.filter(y=>!c.has(y.type)).map(y=>y.id)),[t.nodes,c]),x=y=>h.has(y)&&(!m||m.has(y)),N=n??s,l=v.useMemo(()=>N?Vs(N,t.edges):null,[N,t.edges]),_=y=>!N||y===N||((l==null?void 0:l.nodeIds.has(y))??!1),[A,C]=v.useState({x:0,y:0,k:1}),[E,R]=v.useState(!1),M=v.useRef(null),$=v.useRef(null),I=v.useRef(!1),T=()=>{var y;return ze/(((y=M.current)==null?void 0:y.clientWidth)||ze)},H=y=>C(D=>{const P=Math.max(.5,Math.min(3,D.k*y)),F=ze/2,f=Qe/2;return{k:P,x:F-(F-D.x)*(P/D.k),y:f-(f-D.y)*(P/D.k)}}),k=()=>C({x:0,y:0,k:1}),O=y=>{var D;y.target.closest("[data-node]")||($.current={px:y.clientX,py:y.clientY,vx:A.x,vy:A.y},I.current=!1,R(!0),(D=M.current)==null||D.setPointerCapture(y.pointerId))},b=y=>{const D=$.current;if(!D)return;const P=T(),F=(y.clientX-D.px)*P,f=(y.clientY-D.py)*P;Math.abs(F)+Math.abs(f)>3&&(I.current=!0),C(q=>({...q,x:D.vx+F,y:D.vy+f}))},L=()=>{$.current=null,R(!1)};return e.jsxs("div",{className:"relative h-full w-full",children:[e.jsxs("svg",{ref:M,viewBox:`0 0 ${ze} ${Qe}`,className:"h-full w-full touch-none select-none",style:{cursor:E?"grabbing":"grab"},role:"img","aria-label":"Connected Mind relationship graph",onPointerDown:O,onPointerMove:b,onPointerUp:L,onPointerLeave:L,onPointerCancel:L,onClick:y=>{I.current||y.target.closest("[data-node]")||a(null)},children:[e.jsxs("defs",{children:[e.jsxs("filter",{id:"cm-glow",x:"-60%",y:"-60%",width:"220%",height:"220%",children:[e.jsx("feGaussianBlur",{stdDeviation:"7",result:"b"}),e.jsxs("feMerge",{children:[e.jsx("feMergeNode",{in:"b"}),e.jsx("feMergeNode",{in:"SourceGraphic"})]})]}),e.jsx("filter",{id:"cm-soft",x:"-40%",y:"-40%",width:"180%",height:"180%",children:e.jsx("feDropShadow",{dx:"0",dy:"2",stdDeviation:"3",floodColor:"hsl(var(--navy))",floodOpacity:"0.18"})}),e.jsxs("radialGradient",{id:"cm-bg",cx:"50%",cy:"42%",r:"70%",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--gold))",stopOpacity:"0.07"}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--gold))",stopOpacity:"0"})]})]}),e.jsx("rect",{x:-2e3,y:-2e3,width:ze+4e3,height:Qe+4e3,fill:"url(#cm-bg)"}),e.jsxs("g",{id:"cm-view",transform:`translate(${A.x} ${A.y}) scale(${A.k})`,children:[t.edges.map((y,D)=>{const P=p.get(y.source),F=p.get(y.target);if(!P||!F||!x(y.source)||!x(y.target))return null;const f=N?(l==null?void 0:l.edgeIdx.has(D))??!1:!1,q=d.has(y.source)||d.has(y.target),J=u?u.has(y.source)&&u.has(y.target):!0,W=u?J?.5:.04:N?f?.85:.05:q?.55:.16;return e.jsx(nt.path,{d:Hs(P,F),fill:"none",stroke:f||q?"hsl(var(--primary))":"hsl(var(--muted-foreground))",strokeWidth:f?2.2:q?1.8:1.1,filter:void 0,strokeLinecap:"round",initial:{pathLength:0,opacity:0}
63,animate:{pathLength:1,opacity:W},transition:{pathLength:{duration:.7,delay:.1+Math.min(D*o,.9)},opacity:{duration:.25}}},`${y.source}-${y.target}-${D}`)}),t.nodes.map((y,D)=>{if(!x(y.id))return null;const P=p.get(y.id),F=he[y.type],f=F.icon,q=r(y.id,y.type),J=y.id===N,W=y.id===s,oe=!u||u.has(y.id),Q=(u?!u.has(y.id):!1)?.07:_(y.id)?1:.14,z=Math.round(q*.8);return e.jsxs(nt.g,{"data-node":"1",role:"button",tabIndex:0,"aria-label":`${F.label}: ${y.label}`,className:"cursor-pointer focus:outline-none",style:{transformBox:"fill-box",transformOrigin:"center"},initial:{scale:0,opacity:0},animate:{scale:J?1.14:1,opacity:Q},transition:{scale:{type:"spring",stiffness:260,damping:18,delay:Math.min(D*j,1)},opacity:{duration:.3}},onPointerDown:U=>U.stopPropagation(),onClick:U=>{U.stopPropagation(),a(W?null:y.id)},onMouseEnter:()=>i(y.id),onMouseLeave:()=>i(null),onKeyDown:U=>{(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),a(W?null:y.id))},filter:J?"url(#cm-glow)":"url(#cm-soft)",children:[oe&&u?e.jsx("circle",{cx:P.x,cy:P.y,r:q+6,fill:"none",stroke:"var(--gold-dark)",strokeWidth:2,strokeOpacity:.9}):null,J?e.jsx("circle",{cx:P.x,cy:P.y,r:q+7,fill:"none",stroke:F.color,strokeOpacity:.35,strokeWidth:2}):null,e.jsx("circle",{cx:P.x,cy:P.y,r:q,fill:F.color,stroke:"white",strokeOpacity:.85,strokeWidth:1.5}),e.jsx(f,{x:P.x-z/2,y:P.y-z/2,width:z,height:z,color:F.iconColor,strokeWidth:2})]},y.id)}),t.nodes.map(y=>{if(!x(y.id))return null;const D=p.get(y.id),P=r(y.id,y.type),F=y.type==="company"||y.type==="subject";if(!(!(u?!u.has(y.id):!1)&&(F||!!N&&_(y.id)||!!u)))return null;const J=y.type==="company",W=D.y+P+(J?16:13);return e.jsxs("g",{children:[e.jsx("text",{x:D.x,y:W,textAnchor:"middle",fill:"hsl(var(--foreground))",stroke:"hsl(var(--background))",strokeWidth:3,paintOrder:"stroke",fontWeight:J?600:400,style:{fontSize:J?15:11},children:y.label}),y.metric?e.jsx("text",{x:D.x,y:W+12,textAnchor:"middle",fill:y.type==="risk"?"hsl(var(--destructive))":"var(--gold-dark)",stroke:"hsl(var(--background))",strokeWidth:3,paintOrder:"stroke",fontWeight:600,style:{fontSize:10},children:y.metric}):null]},`label-${y.id}`)}),t.edges.map((y,D)=>{const P=p.get(y.source),F=p.get(y.target);if(!P||!F||!x(y.source)||!x(y.target))return null;const f=N?(l==null?void 0:l.edgeIdx.has(D))??!1:!1;if(!(m||f))return null;const q=(P.x+F.x)/2,J=(P.y+F.y)/2,W=F.x-P.x,oe=F.y-P.y,se=Math.hypot(W,oe)||1,Q=Math.min(38,se*.13)*.55;return e.jsx("text",{x:q-oe/se*Q,y:J+W/se*Q,textAnchor:"middle",fill:"hsl(var(--muted-foreground))",stroke:"hsl(var(--background))",strokeWidth:3,paintOrder:"stroke",style:{fontSize:9},children:Lt[y.kind]},`elabel-${D}`)})]})]}),e.jsxs("div",{className:"absolute bottom-3 right-3 flex flex-col gap-1.5",children:[e.jsx(bt,{label:"Zoom in",onClick:()=>H(1.25),children:e.jsx(Rn,{className:"size-4","aria-hidden":!0})}),e.jsx(bt,{label:"Zoom out",onClick:()=>H(.8),children:e.jsx(Tn,{className:"size-4","aria-hidden":!0})}),e.jsx(bt,{label:"Reset view",onClick:k,children:e.jsx(On,{className:"size-4","aria-hidden":!0})})]})]})}function bt({label:t,onClick:s,children:n}){return e.jsx("button",{type:"button","aria-label":t,onClick:s,className:"flex size-8 items-center justify-center rounded-md border border-border bg-card/90 text-foreground shadow-sm backdrop-blur transition-colors hover:bg-muted",children:n})}const vr=120,wr=40,kr=20,Nr=20,_r={company:"belongs",ma_target:"targets",bolt_on:"targets",competitor:"relates",market:"belongs"},is={company:0,subject:0,insight:0,document:0,risk:0,value_driver:0};function Ye(t,s=54){const n=(t??"").replace(/\s+/g," ").trim();return n.length>s?`${n.slice(0,s-1).trimEnd()}…`:n}function os(t){return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}function ls(t){return t==="confirmed"||t==="edited"?0:1}function Sr(t){var C,E,R;const{user:s}=Ne(),n=!!s&&!!t,a=Dt(t||void 0),i=wa(t),c=dt(t),u=xs(t,{},{limit:300,offset:0,enabled:n}),m=ct(t),p=ut(t),j=He({queryKey:["connected-mind-vcp",t],enabled:n,staleTime:3e4,queryFn:()=>Ds(t)}),o=i.isLoading||c.isLoading||u.isLoading||p.isLoading||j.isLoading,g=a.isError||i.isError||c.isError||u.isError||m.isError||p.isError||j.isError,d=v.useCallback(()=>{a.refetch(),i.refetch(),c.refetch(),u.refetch(),m.refetch(),p.refetch(),j.refetch()},[a,i,c,u,m,p,j]),r=i.data,h=c.data,x=(C=u.data)==null?void 0:C.rows,N=p.data,l=(E=j.data)==null?void 0:E.levers,_=(R=a.data)==null?void 0:R.company_name,A=m.data;return v.useMemo(()=>{var ae;const M=r??[],$=h??[],I=x??[],T=N??[],H=l??[],k=[],O=new Set,b=w=>{O.has(w.id)||(O.add(w.id),k.push(w))},L=ka(M);let y=null;
63L?(y=L.id,b({id:L.id,type:"company",label:L.name,detail:"The portfolio company under management."})):_&&(y="company",b({id:"company",type:"company",label:_,detail:"The active portfolio company."}));for(const w of M)L&&w.id===L.id||b({id:w.id,type:"subject",label:w.name,detail:(ae=Na[w.kind])==null?void 0:ae.hint});const D=I.filter(w=>w.status!=="rejected"&&!Qt(w)).sort((w,V)=>{const Y=ls(w.status)-ls(V.status);if(Y!==0)return Y;const Z=(V.confidence??0)-(w.confidence??0);return Z!==0?Z:(V.created_at??"")<(w.created_at??"")?-1:1}).slice(0,vr);for(const w of D)b({id:w.id,type:"insight",label:Ye(w.content),detail:w.content??void 0,citation:`[A#${w.id.slice(0,8)}]`});const P=new Set(D.map(w=>w.id)),F=new Set;for(const w of D)w.document_id&&F.add(w.document_id);const f=[...$.filter(w=>F.has(w.id)),...$.filter(w=>!F.has(w.id))].slice(0,wr);for(const w of f)b({id:w.id,type:"document",label:Ye(w.file_name,38),detail:w.file_name??void 0});const q=H.filter(w=>w.status!=="rejected").slice(0,kr);for(const w of q){const V=typeof w.ebitda_impact_mid=="number"&&isFinite(w.ebitda_impact_mid)?w.ebitda_impact_mid:null;b({id:w.id,type:"value_driver",label:Ye(w.name),detail:w.description??void 0,metric:V!=null&&V!==0?Xt(V):void 0,metricValue:V??void 0})}const J=T.slice(0,Nr);for(const w of J){const V=typeof w.value_at_risk_usd=="number"&&isFinite(w.value_at_risk_usd)?w.value_at_risk_usd:null,Y=V!=null?_a(V,0):null;b({id:w.id,type:"risk",label:Ye(w.title),detail:w.description??void 0,metric:Y!=null&&Y!==0?Xt(Y):void 0,metricValue:Y??void 0})}const W=[],oe=new Set,se=new Set,Q=(w,V,Y)=>{if(w===V||!O.has(w)||!O.has(V))return!1;const Z=w<V?`${w}|${V}`:`${V}|${w}`;return oe.has(Z)?!1:(oe.add(Z),W.push({source:w,target:V,kind:Y}),se.add(w),se.add(V),!0)};if(y)for(const w of M)L&&w.id===L.id||Q(y,w.id,_r[w.kind]??"relates");const z=new Map;for(const w of M)w.ma_target_id&&z.set(w.ma_target_id,w.id);for(const w of D){let V=!1;if(w.document_id&&Q(w.id,w.document_id,"cites")&&(V=!0),w.subject_id&&Q(w.id,w.subject_id,"belongs")&&(V=!0),!V&&w.target_id){const Y=z.get(w.target_id);Y&&Q(w.id,Y,"relates")&&(V=!0)}!V&&y&&Q(y,w.id,"supports")}for(const w of f)se.has(w.id)||w.subject_id&&Q(w.id,w.subject_id,"belongs")||y&&Q(y,w.id,"relates");for(const w of q){const V=os(w.source_insight_ids).filter(Z=>
63P.has(Z));let Y=!1;for(const Z of V)Q(w.id,Z,"supports")&&(Y=!0);!Y&&y&&Q(y,w.id,"supports")}for(const w of J){const V=os(w.linked_assertion_ids).filter(Z=>P.has(Z));let Y=!1;for(const Z of V)Q(w.id,Z,"supports")&&(Y=!0);!Y&&y&&Q(y,w.id,"relates")}const U={...is};for(const w of k)U[w.type]+=1;const fe={...is,company:U.company,subject:U.subject,insight:A!=null?Math.max(0,A.total-A.rejected):I.filter(w=>w.status!=="rejected"&&!Qt(w)).length,document:$.length,value_driver:H.filter(w=>w.status!=="rejected").length,risk:T.length},ce=y===null||k.length-U.company<3;return{graph:{nodes:k,edges:W},isLoading:o,isError:g,refetch:d,isEmpty:ce,counts:U,totals:fe}},[r,h,x,N,l,_,o,g,d,A])}const Cr=["fill","stroke","stop-color","stop-opacity","fill-opacity","stroke-opacity","stroke-width"];function Js(t,s){const n=window.getComputedStyle(t);for(const c of Cr){const u=n.getPropertyValue(c);u&&u!=="none"&&s.setAttribute(c,u)}const a=t.children,i=s.children;for(let c=0;c<a.length&&c<i.length;c++)Js(a[c],i[c])}async function Mr(t,s){if(!t)return;const n=t.viewBox.baseVal,a=n&&n.width?n.width:900,i=n&&n.height?n.height:620,c=2,u=t.cloneNode(!0),m=u.querySelector("#cm-view");m&&m.setAttribute("transform","translate(0 0) scale(1)"),u.querySelectorAll("[filter]").forEach(o=>o.removeAttribute("filter")),u.querySelectorAll("[data-node]").forEach(o=>{const g=o;g.style.transform="none",g.style.opacity="1"}),Js(t,u),u.setAttribute("width",String(a*c)),u.setAttribute("height",String(i*c)),u.setAttribute("viewBox",`0 0 ${a} ${i}`);const p=new XMLSerializer().serializeToString(u),j=URL.createObjectURL(new Blob([p],{type:"image/svg+xml;charset=utf-8"}));await new Promise(o=>{const g=new Image;g.onload=()=>{const d=document.createElement("canvas");d.width=a*c,d.height=i*c;const r=d.getContext("2d");r&&(r.fillStyle="white",r.fillRect(0,0,d.width,d.height),r.drawImage(g,0,0,d.width,d.height)),URL.revokeObjectURL(j),d.toBlob(h=>{if(h){const x=URL.createObjectURL(h),N=document.createElement("a");N.href=x,N.download=s,N.click(),URL.revokeObjectURL(x)}o()},"image/png")},g.onerror=()=>{URL.revokeObjectURL(j),o()},g.src=j})}const et=["company","subject","insight","document","risk","value_driver"],cs={company:{to:"/campaign/overview",label:"Open campaign overview"},subject:{to:"/campaign/overview",label:"Open campaign overview"},insight:{to:"/campaign/truth-layer",label:"Open in Truth Layer"},document:{to:"/campaign/ingestion",label:"Open in Documents"},risk:{to:"/risk",label:"Open in Risk register"},value_driver:{to:"/value-creation",label:"Open in Value Creation"}};function Er(t,s){const n=[];for(const a of s.edges)if(a.source===t){const i=s.nodes.find(c=>c.id===a.target);i&&n.push({node:i,kind:Lt[a.kind]})}else if(a.target===t){const i=s.nodes.find(c=>c.id===a.source);i&&n.push({node:i,kind:Lt[a.kind]})}return n}const Ar={amber:"border-amber-500/40 text-amber-700 dark:text-amber-300",gold:"border-[var(--gold-dark)]/40 text-[var(--gold-dark)]",muted:"border-border text-muted-foreground",navy:"border-[var(--navy)]/30 text-foreground"};function Lr(t){var o,g;const s=new Map(t.nodes.map(d=>[d.id,d.type])),n=new Map,a=new Map;for(const d of t.nodes)n.set(d.id,new Set);for(const d of t.edges){const r=s.get(d.source),h=s.get(d.target);h&&((o=n.get(d.source))==null||o.add(h)),r&&((g=n.get(d.target))==null||g.add(r)),a.set(d.source,(a.get(d.source)??0)+1),a.set(d.target,(a.get(d.target)??0)+1)}const i=(d,r)=>{var h;return!(((h=n.get(d))==null?void 0:h.has(r))??!1)},c=[],u=t.nodes.filter(d=>d.type==="risk"&&i(d.id,"value_driver"));u.length&&c.push({key:"risk",tone:"amber",ids:u.map(d=>d.id),label:`${u.length} risk${u.length>1?"s":""} with no value driver mapped yet`});const m=t.nodes.filter(d=>d.type==="value_driver"&&i(d.id,"insight"));m.length&&c.push({key:"vd",tone:"gold",ids:m.map(d=>d.id),label:`${m.length} value driver${m.length>1?"s":""} could use a grounding insight`});const p=t.nodes.filter(d=>d.type==="insight"&&i(d.id,"document"));p.length&&c.push({key:"ins",tone:"muted",ids:p.map(d=>d.id),label:`${p.length} insight${p.length>1?"s":""} awaiting a source document`});const j=t.nodes.filter(d=>d.type!=="company").sort((d,r)=>(a.get(r.id)??0)-(a.get(d.id)??0))[0];
63return j&&c.push({key:"hub",tone:"navy",ids:[j.id],label:`Most connected: ${j.label} (${a.get(j.id)??0} links)`}),c}function Dr(t,s){var p,j;const n=new Map(t.nodes.map(o=>[o.id,o.type])),a=new Map;for(const o of t.nodes)a.set(o.id,new Set);for(const o of t.edges){const g=n.get(o.source),d=n.get(o.target);d&&((p=a.get(o.source))==null||p.add(d)),g&&((j=a.get(o.target))==null||j.add(g))}const i=(o,g)=>{var d;return((d=a.get(o))==null?void 0:d.has(g))??!1},c=t.nodes.filter(o=>o.type==="value_driver"),u=t.nodes.filter(o=>o.type==="risk"),m=t.nodes.filter(o=>o.type==="insight");return[{key:"grounded",label:"Value drivers grounded",n:c.filter(o=>i(o.id,"insight")).length,total:c.length,dealTotal:s.value_driver},{key:"addressed",label:"Risks addressed",n:u.filter(o=>i(o.id,"value_driver")).length,total:u.length,dealTotal:s.risk},{key:"sourced",label:"Insights sourced",n:m.filter(o=>i(o.id,"document")).length,total:m.length,dealTotal:s.insight}].filter(o=>o.total>0)}function Pr({metric:t}){const s=t.total?Math.round(t.n/t.total*100):0,n=t.dealTotal>t.total,a=s>=80?"bg-emerald-500":s>=50?"bg-highlight":"bg-amber-500";return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t.label}),e.jsxs("span",{className:"font-display text-sm font-semibold tabular-nums text-foreground",children:[s,"%"]})]}),e.jsx("div",{className:"mt-1.5 h-1.5 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:G("h-full rounded-full",a),style:{width:`${s}%`}})}),e.jsxs("span",{className:"mt-1 block text-step-caption text-muted-foreground",children:[t.n," of ",t.total,n?` shown (${t.dealTotal} on the deal)`:null]})]})}function Rr(t){const s=new Map;for(const n of t){const a=s.get(n.node.type);a?a.push(n.node):s.set(n.node.type,[n.node])}return et.filter(n=>s.has(n)).map(n=>[n,s.get(n)])}function Tr(t,s){for(const n of s.edges){if(n.source!==t&&n.target!==t)continue;const a=n.source===t?n.target:n.source,i=s.nodes.find(c=>c.id===a);if((i==null?void 0:i.type)==="document")return i}return null}function Or({insightId:t,graph:s,onSelect:n}){const a=Tr(t,s);return a?e.jsxs("button",{type:"button",onClick:()=>n(a.id),className:"ml-4 flex items-center gap-1.5 px-2 py-0.5 text-step-caption text-muted-foreground hover:text-foreground",children:[e.jsx("span",{className:"text-muted-foreground/60",children:"via"}),e.jsx("span",{className:"truncate",children:a.label})]}):null}function tt({type:t}){return e.jsx("span",{className:"inline-block size-2.5 shrink-0 rounded-full",style:{backgroundColor:he[t].color},"aria-hidden":!0})}function $r({campaignId:t}){const{data:s}=Dt(t||void 0),[n,a]=v.useState(null),[i,c]=v.useState(null),[u,m]=v.useState(new Set),[p,j]=v.useState(""),[o,g]=v.useState(null),[d,r]=v.useState(!1),h=v.useRef(null),x=Sr(t),N=!x.isLoading&&!x.isError&&x.isEmpty,l=x.isLoading||x.isEmpty?yr:x.graph;v.useEffect(()=>{a(null),c(null),j(""),m(new Set),g(null)},[N,x.isLoading]);const _=v.useMemo(()=>l.nodes.find(b=>b.id===n)??null,[l,n]),A=v.useMemo(()=>n?Er(n,l):[],[n,l]),C=v.useMemo(()=>{const b=Object.fromEntries(et.map(L=>[L,0]));for(const L of l.nodes)b[L.type]+=1;return b},[l]),E=v.useMemo(()=>{const b=p.trim().toLowerCase();if(!b)return null;const L=new Set;for(const y of l.nodes)(y.label.toLowerCase().includes(b)||(y.detail??"").toLowerCase().includes(b))&&L.add(y.id);return L},[p,l]),R=b=>m(L=>{const y=new Set(L);return y.has(b)?y.delete(b):y.add(b),y}),M=b=>{a(b),b||g(null)},$=v.useMemo(()=>o==null||!n||!l.nodes.some(b=>b.id===n)?null:gr(n,o,l.edges),[o,n,l]),I=v.useMemo(()=>Lr(l),[l]),T=v.useMemo(()=>N||x.isLoading?C:x.totals,[N,x.isLoading,x.totals,C]),H=v.useMemo(()=>Dr(l,T),[l,T]),k=v.useMemo(()=>{const b=et.filter(L=>T[L]>C[L]).map(L=>`${C[L]} of ${T[L]} ${he[L].label.toLowerCase()}`);return b.length?b:null},[T,C]),O=async()=>{var L;const b=((L=h.current)==null?void 0:L.querySelector("svg"))??null;if(b){r(!0);try{const y=((s==null?void 0:s.company_name)??"map").replace(/[^a-z0-9]+/gi,"-").toLowerCase();await Mr(b,`connected-mind-${y}.png`)}finally{r(!1)}}};return t?x.isError?e.jsx(Le,{noun:"the relationship map",onRetry:()=>x.refetch()}):e.jsx("div",{className:"space-y-5",children:x.isLoading?e.jsx("div",{className:"flex h-[420px] items-center justify-center rounded-2xl border border-border bg-muted/10 text-sm text-muted-foreground",children:"Mapping the campaign…"}):e.jsxs(e.Fragment,{children:[N?e.jsxs("div",{className:"flex items-start gap-3 rounded-xl border border-[var(--gold-dark)]/40 bg-accent px-4 py-3",children:[e.jsx(Ke,{className:"mt-0.5 size-4 shrink-0 text-[var(--gold-dark)]","aria-hidden":!0}),e.jsxs("p",{className:"text-sm text-foreground",children:[e.jsx("span",{className:"font-medium",children:"Sample relationship map."})," ",e.jsxs("span",{className:"text-muted-foreground",children:[(s==null?void 0:s.company_name)??"This campaign"," doesn't have enough mapped data yet - add documents and confirm insights to see it mapped live. This is a preview."]})]})]}):e.jsxs("div",{className:"flex items-start gap-3 rounded-xl border border-emerald-500/30 bg-emerald-50/50 px-4 py-3 dark:bg-emerald-950/20",children:[e.jsx(Ke,{className:"mt-0.5 size-4 shrink-0 text-emerald-600","aria-hidden":!0}),e.jsxs("p",{className:"text-sm text-foreground",children:[e.jsx("span",{className:"font-medium",children:"Live map."})," ",e.jsxs("span",{className:"text-muted-foreground",children:[(s==null?void 0:s.company_name)??"This campaign","'s web of connected items - the company, its insights, documents, risks and value drivers (the nodes), and the links between them (the threads). Hover any node to light up what it touches; click to lock focus and trace the full chain."]}),k?e.jsxs("span",{className:"mt-1.5 block text-muted-foreground",children:["Drawn for legibility: ",k.join(", "),". Insights are ranked confirmed-first, then by confidence, and documents cited by a shown insight are drawn ahead of the rest. Nothing is dropped from the deal - the Data Layer and every other surface still count them all."]}):null]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative w-full max-w-xs",children:[e.jsx($t,{className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(it,{value:p,onChange:b=>j(b.target.value),placeholder:"Search nodes…",className:"h-9 pl-8"})]}),p||u.size>0?e.jsx(K,{variant:"ghost",size:"sm",onClick:()=>{j(""),m(new Set)},children:"Reset"}):null,e.jsxs(K,{type:"button",variant:"outline",size:"sm",className:"ml-auto gap-1.5",disabled:d,onClick:()=>void O(),children:[e.jsx(ks,{className:"size-3.5","aria-hidden":!0}),d?"Exporting…":"Export PNG"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-5",children:[e.jsx(jt,{label:"Nodes drawn",value:l.nodes.length}),e.jsx(jt,{label:"Threads",value:l.edges.length}),e.jsx(jt,{label:"Insights",value:T.insight>C.insight?`${C.insight} of ${T.insight}`:C.insight})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:et.map(b=>{const L=u.has(b);return e.jsxs("button",{type:"button",onClick:()=>R(b),"aria-pressed":!L,title:T[b]>C[b]?`${C[b]} of ${T[b]} ${he[b].label.toLowerCase()} drawn on the map`:L?`Show ${he[b].label}`:`Hide ${he[b].label}`,className:G("inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs transition-colors",L?"border-border bg-transparent text-muted-foreground
63/50":"border-border bg-muted/30 text-foreground hover:border-[var(--gold-dark)]/50"),children:[e.jsx(tt,{type:b}),e.jsx("span",{className:L?"line-through":void 0,children:he[b].label}),e.jsx("span",{className:"font-mono text-step-caption text-muted-foreground",children:T[b]>C[b]?`${C[b]}/${T[b]}`:C[b]})]},b)})})]}),e.jsxs("div",{className:"flex flex-col gap-5",children:[e.jsx("div",{ref:h,className:"relative w-full overflow-hidden rounded-2xl border border-border bg-[var(--paper-cream)]/30 dark:bg-muted/10",children:e.jsx("div",{className:"h-[420px] sm:h-[520px] md:h-[580px]",children:e.jsx(jr,{graph:l,selectedId:n,hoveredId:i,onSelect:M,onHover:c,hiddenTypes:u,matchIds:E,focusIds:$})})}),e.jsx(zr,{node:_,connections:A,onSelect:M,onClear:()=>M(null),graph:l,focusDepth:o,focusCount:($==null?void 0:$.size)??0,onSetFocus:g})]}),H.length>0||I.length>0?e.jsxs("div",{className:"space-y-4 rounded-2xl border border-border bg-card p-4",children:[H.length>0?e.jsxs("div",{children:[e.jsxs("p",{className:"kicker mb-3 flex items-center gap-1.5 text-[var(--gold-dark)]",children:[e.jsx($n,{className:"size-3.5","aria-hidden":!0}),"Evidence coverage"]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-3",children:H.map(b=>e.jsx(Pr,{metric:b},b.key))})]}):null,I.length>0?e.jsxs("div",{children:[e.jsxs("p",{className:"kicker mb-2 flex items-center gap-1.5 text-[var(--gold-dark)]",children:[e.jsx(Ns,{className:"size-3.5","aria-hidden":!0}),"Signals"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:I.map(b=>e.jsx("button",{type:"button",onClick:()=>b.ids[0]&&M(b.ids[0]),className:G("inline-flex items-center rounded-lg border bg-transparent px-3 py-1.5 text-xs transition-colors hover:bg-muted/40",Ar[b.tone]),children:b.label},b.key))})]}):null]}):null]})}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a campaign to map its Connected Mind."})}function jt({label:t,value:s,tone:n}){const a=n==="gold"?"text-[var(--gold-dark)]":n==="rose"?"text-rose-600 dar
63k:text-rose-400":"text-foreground";return e.jsxs("div",{children:[e.jsx("p",{className:G("font-display text-2xl font-semibold tabular-nums",a),children:s}),e.jsx("p",{className:"kicker text-muted-foreground",children:t})]})}function zr({node:t,connections:s,onSelect:n,onClear:a,graph:i,focusDepth:c,focusCount:u,onSetFocus:m}){if(!t){const j=i.nodes.filter(o=>o.type==="company"||o.type==="subject");return e.jsxs("div",{className:"w-full rounded-2xl border border-border bg-card p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-foreground",children:[e.jsx(zn,{className:"size-4 text-[var(--gold-dark)]","aria-hidden":!0}),"Trace a thread"]}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Hover any node to light up what it touches. Click to lock focus and read the full connection list."}),e.jsx("p",{className:"kicker mt-5 mb-2 text-muted-foreground",children:"Start here"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:j.map(o=>e.jsxs("button",{type:"button",onClick:()=>n(o.id),className:"inline-flex items-center gap-1.5 rounded-full border border-border bg-muted/30 px-3 py-1.5 text-xs text-foreground transition-colors hover:border-[var(--gold-dark)]/60 hover:bg-accent",children:[e.jsx(tt,{type:o.type}),o.label]},o.id))})]})}const p=he[t.type];return e.jsxs("div",{className:"w-full rounded-2xl border border-border bg-card p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(ie,{variant:"outline",className:"kicker mb-2 gap-1.5",style:{borderColor:p.color,color:p.color},children:[e.jsx(tt,{type:t.type}),p.label]}),e.jsx("h3",{className:"font-display text-lg font-semibold leading-tight text-foreground",children:t.label})]}),e.jsx("button",{type:"button",onClick:a,"aria-label":"Clear focus",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(In,{className:"size-4"})})]}),t.detail?e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:t.detail}):null,t.citation?e.jsx("span",{className:"mt-3 inline-flex rounded border border-[var(--gold-dark)]/40 bg-accent px-1.5 py-0.5 font-mono text-step-caption text-[var(--gold-dark)]",children:t.citation}):null,t.metric?e.jsxs("div",{className:G("mt-3 flex items-center gap-2 rounded-lg border px-3 py-2",t.type==="risk"?"border-rose-500/40 bg-rose-500/10":"border-[var(--gold-dark)]/40 bg-accent"),children:[e.jsx("span",{className:G("font-display text-lg font-semibold",t.type==="risk"?"text-rose-600 dar
63k:text-rose-400":"text-[var(--gold-dark)]"),children:t.metric}),e.jsx("span",{className:"text-xs text-muted-foreground",children:t.type==="risk"?"value at risk":"EBITDA at stake"})]}):null,e.jsx("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:c==null?e.jsxs(K,{variant:"outline",size:"sm",className:"h-7 gap-1.5 text-xs",onClick:()=>m(1),children:[e.jsx(Fn,{className:"size-3.5","aria-hidden":!0}),"Focus neighbourhood"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-step-caption text-muted-foreground",children:["Focus: ",c,"-hop · ",u," nodes"]}),e.jsx(K,{variant:"outline",size:"sm",className:"h-7 px-2 text-xs",disabled:c>=3,onClick:()=>m(Math.min(3,c+1)),children:"Expand"}),e.jsx(K,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>m(null),children:"Show all"})]})}),e.jsxs("p",{className:"kicker mt-5 mb-2 text-muted-foreground",children:["Reasoning chain (",s.length,")"]}),e.jsx("div",{className:"space-y-3",children:Rr(s).map(([j,o])=>e.jsxs("div",{children:[e.jsxs("p",{className:"kicker mb-1 flex items-center gap-1.5 text-muted-foreground",children:[e.jsx(tt,{type:j}),he[j].label]}),e.jsx("ul",{className:"space-y-0.5",children:o.map(g=>e.jsxs("li",{children:[e.jsx("button",{type:"button",onClick:()=>n(g.id),className:"flex w-full items-center gap-2 rounded-md border border-transparent px-2 py-1.5 text-left text-sm transition-colors hover:border-border hover:bg-muted/40",children:e.jsx("span",{className:"min-w-0 flex-1 truncate text-foreground",children:g.label})}),(t.type==="value_driver"||t.type==="risk")&&g.type==="insight"?e.jsx(Or,{insightId:g.id,graph:i,onSelect:n}):null]},g.id))})]},j))}),e.jsxs(Ae,{to:cs[t.type].to,className:"mt-4 inline-flex items-center gap-1.5 text-xs font-medium text-[var(--gold-dark)] hover:underline",children:[e.jsx(mt,{className:"size-3.5","aria-hidden":!0}),cs[t.type].label]})]})}const ds={document:"document",external_research:"web research",public_markets_data:"market data",ai_synthesis:"AI-synthesized",manual:"manual"},Ze=t=>Math.round(t*100);function Ir(t,s){const n=t.confirmed+t.edited+t.rejected,a=n>0?(t.confirmed+t.edited)/n:0,i=n>0?t.edited/n:0,c=n>0?t.rejected/n:0,u=new Map,m=new Map;let p=0,j=0;const o=new Set,g=new Map;let d=0,r=0;for(const E of s)if(E.status==="confirmed"||E.status==="edited"){r+=1;const M=(E.category??"").trim();M&&(u.set(M,(u.get(M)??0)+1),o.add(M));const $=ds[E.source??""]??(E.source??"").trim();$&&g.set($,(g.get($)??0)+1),typeof E.confidence=="number"&&isFinite(E.confidence)&&(p+=E.confidence,j+=1,E.confidence>=.8&&(d+=1))}else if(E.status==="rejected"){const M=ds[E.source??""]??(E.source??"").trim();M&&m.set(M,(m.get(M)??0)+1)}const h=[...u.entries()].sort((E,R)=>R[1]-E[1]).slice(0,5).map(([E,R])=>({label:E,n:R})),x=[...m.entries()].sort((E,R)=>R[1]-E[1])[0],N=x?{label:x[0],n:x[1]}:null,l=j>0?p/j:null,_=r>0?d/r:null,A=[...g.entries()].sort((E,R)=>R[1]-E[1])[0]??null,C=[];return n>0&&(C.push(`You keep ${Ze(a)}% of the claims you review.`),i>=.2&&C.push(`You refine more than you discard - ${Ze(i)}% of your decisions are edits, not rejections.`),c===0&&i===0&&C.push("You have not rejected or edited a claim yet - your house standard is still forming as you review more."),o.size>0&&C.push(`Your house has ruled on evidence across ${o.size} categor${o.size===1?"y":"ies"}.`),h.length>0&&C.push(`Your house trusts ${h.slice(0,2).map(E=>E.label).join(" and ")} insights most.`),_!=null&&C.push(`${Ze(_)}% of what you keep is high-confidence (80%+).`),A&&C.push(`Most of your kept evidence comes from ${A[0]} sources.`),N&&C.push(`You are most skeptical of ${N.label} claims.`),l!=null&&C.push(`You typically keep claims around ${Ze(l)}% confidence and up.`)),t.pending>0&&C.push(`${t.pending} claim${t.pending===1?"":"s"} ${t.pending===1?"is":"are"} waiting for your review.`),{decided:n,pending:t.pending,acceptanceRate:a,editRate:i,rejectionRate:c,topTrustedCategories:h,mostSkepticalSource:N,signals:C}}function Fr({campaignId:t}){const{data:s,isLoading:n,isError:a,refetch:i}=ct(t),{data:c=[],isError:u,refetch:m}=Je(t),p=v.useMemo(()=>Ir(s??{pending:0,confirmed:0,rejected:0,edited:0},c.map(g=>({status:g.status,category:g.category,source:g.source,confidence:g.confidence}))),[s,c]);if(!t)return e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a campaign to see its House Lens."});if(a||u)return e.jsx(Le,{compact:!0,noun:"the House Lens",onRetry:()=>
63{i(),m()}});if(n&&!s)return e.jsx("div",{className:"h-64 w-full rounded-2xl border border-border bg-muted/10"});if(p.decided===0)return e.jsxs("div",{className:"rounded-2xl border border-dashed border-border bg-muted/10 p-8 text-center",children:[e.jsx(_t,{className:"mx-auto size-7 text-[var(--gold-dark)]","aria-hidden":!0}),e.jsx("p",{className:"mt-3 text-sm font-medium text-foreground",children:"Your House Lens is still forming."}),e.jsx("p",{className:"mx-auto mt-1 max-w-md text-sm text-muted-foreground",children:"Confirm, edit, or reject claims in the Truth Layer and this builds a profile of how your house judges evidence - the foundation for steering AI toward your standards."})]});const j=Math.round(p.acceptanceRate*100),o=Math.round(p.rejectionRate*100);return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-start gap-3 rounded-xl border border-[var(--gold-dark)]/40 bg-accent px-4 py-3",children:[e.jsx(_t,{className:"mt-0.5 size-4 shrink-0 text-[var(--gold-dark)]","aria-hidden":!0}),e.jsxs("p",{className:"text-sm text-foreground",children:[e.jsx("span",{className:"font-medium",children:"Your house lens."})," ",e.jsxs("span",{className:"text-muted-foreground",children:["How this house judges evidence, learned from ",p.decided," Truth Layer decisions. It sharpens as you review more."]})]})]}),e.jsxs("div",{className:"grid gap-5 lg:grid-cols-3",children:[e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5",children:[e.jsx("p",{className:"kicker text-[var(--gold-dark)]",children:"House signature"}),e.jsxs("p",{className:"mt-2 font-display text-4xl font-semibold tabular-nums text-foreground",children:[j,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"of reviewed claims are kept"}),e.jsxs("div",{className:"mt-4 flex h-2 overflow-hidden rounded-full bg-muted",children:[e.jsx("div",{className:"h-full bg-emerald-500",style:{width:`${j}%`}}),e.jsx("div",{className:"h-full bg-rose-500",style:{width:`${o}%`}})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-x-4 gap-y-1 text-step-caption text-muted-foreground",children:[e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium text-emerald-600",children:[j,"%"]})," kept"]}),e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium text-rose-600",children:[o,"%"]})," rejected"]}),e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium text-foreground",children:[Math.round(p.editRate*100),"%"]})," edited"]}),p.pending>0?e.jsxs("span",{children:[p.pending," pending"]}):null]})]}),e.jsxs("div",{className:"rounded-2xl border border-border bg-card p-5 lg:col-span-2",children:[e.jsxs("p",{className:"kicker flex items-center gap-1.5 text-[var(--gold-dark)]",children:[e.jsx(Ke,{className:"size-3.5","aria-hidden":!0}),"What your decisions reveal"]}),e.jsx("ul",{className:"mt-3 space-y-2",children:p.signals.map((g,d)=>e.jsxs("li",{className:"flex gap-2 text-sm text-foreground",children:[e.jsx("span",{className:"mt-2 size-1.5 shrink-0 rounded-full bg-primary","aria-hidden":!0}),e.jsx("span",{className:"leading-relaxed",children:g})]},d))}),p.topTrustedCategories.length>0||p.mostSkepticalSource?e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-x-6 gap-y-3 border-t border-border/60 pt-4",children:[p.topTrustedCategories.length>0?e.jsxs("div",{className:"min-w-[220px] flex-1",children:[e.jsx("p",{className:"kicker mb-2 text-muted-foreground",children:"Where your house places its trust"}),e.jsx("div",{className:"space-y-1.5",children:p.topTrustedCategories.map(g=>{var h;const d=((h=p.topTrustedCategories[0])==null?void 0:h.n)||1,r=Math.max(Math.round(g.n/d*100),6);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-24 shrink-0 truncate text-xs capitalize text-foreground",children:g.label}),e.jsx("div",{className:"h-2.5 flex-1 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-primary",style:{width:`${r}%`}})}),e.jsx("span",{className:"w-8 shrink-0 text-right font-mono text-step-caption text-muted-foreground",children:g.n})]},g.label)})})]}):null,p.mostSkepticalSource?e.jsxs("div",{children:[e.jsx("p",{className:"kicker mb-1.5 text-muted-foreground",children:"Most skeptical of"}),e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-rose-500/30 bg-rose-50/50 px-2.5 py-1 text-xs text-rose-700 dark:bg-rose-950/20 dark:text-rose-300",children:[p.mostSkepticalSource.label,e.jsx("span",{className:"font-mono text-step-caption opacity-70",children:p.mostSkepticalSource.n})]})]}):null]}):null]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-xl border border-border bg-muted/20 px-4 py-3",children:[e.jsx(Ke,{className:"mt-0.5 size-4 shrink-0 text-[var(--gold-dark)]","aria-hidden":!0}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Already in effect:"})," this lens quietly steers new AI output - your reports, the AI CFO and the operating partner AI - toward your house's judgment. The part competitors can't copy, because it's trained on your decisions."]})]})]})}const at=["sector_brief","key_player","public_peer","private_peer","comparable","target","ma_activity","macro_risk","regulatory"],ye={sector_brief:{label:"Sector brief",Icon:vs,color:le[0]},key_player:{label:"Key players",Icon:Hn,color:le[1]},public_peer:{label:"Public peers",Icon:Ve,color:le[2]},private_peer:{label:"Private peers",Icon:ws,color:le[3]},comparable:{label:"Comparables",Icon:Vn,color:le[4]},target:{label:"Bolt-on targets",Icon:Kn,color:"var(--gold-dark)"},ma_activity:{label:"M&A activity",Icon:qn,color:le[1]},macro_risk:{label:"Macro risks",Icon:Ot,color:"hsl(var(--destructive))"},regulatory:{label:"Regulatory",Icon:Bn,color:le[0]}},vt=1200,wt=820,Ws=12;function Br(t){const s=[{id:"center",kind:"center",label:"Your market"}],n=[];for(const a of at){const i=t.filter(u=>u.kind===a);if(i.length===0)continue;
63const c=`hub:${a}`;s.push({id:c,kind:"cluster",marketKind:a,label:ye[a].label,count:i.length}),n.push({source:"center",target:c}),i.slice(0,Ws).forEach(u=>{const m=`item:${u.id}`;s.push({id:m,kind:"item",marketKind:a,label:u.title,detail:u.body,confidence:u.confidence,sourceUrl:u.source_url}),n.push({source:c,target:m})})}return{nodes:s,edges:n}}function qr({items:t}){const{nodes:s,edges:n}=v.useMemo(()=>Br(t),[t]),a=v.useMemo(()=>n.map(l=>({source:l.source,target:l.target,kind:"relates"})),[n]),i=v.useMemo(()=>{const l={nodes:s.map(_=>({id:_.id,type:_.kind==="center"?"company":"subject",label:_.label})),edges:a};return Us(l,vt,wt)},[s,a]),[c,u]=v.useState(null),[m,p]=v.useState(null),j=c??m,o=v.useMemo(()=>j?Vs(j,a):null,[j,a]),g=l=>!j||l===j||((o==null?void 0:o.nodeIds.has(l))??!1),d=v.useMemo(()=>new Map(s.map(l=>[l.id,l])),[s]),r=m?d.get(m)??null:null,h=l=>l.kind==="center"?"var(--gold)":l.marketKind?ye[l.marketKind].color:"hsl(var(--muted-foreground))",x=l=>l.kind==="center"?30:l.kind==="cluster"?19:8,N=v.useMemo(()=>at.filter(l=>t.some(_=>_.kind===l)),[t]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"relative overflow-hidden rounded-2xl border border-border bg-card",children:e.jsxs("svg",{viewBox:`0 0 ${vt} ${wt}`,className:"h-[clamp(420px,52vh,580px)] w-full select-none",role:"img","aria-label":"Market Layer constellation",onClick:l=>{l.target.closest("[data-mnode]")||p(null)},children:[e.jsxs("defs",{children:[e.jsx("filter",{id:"ml-soft",x:"-40%",y:"-40%",width:"180%",height:"180%",children:e.jsx("feDropShadow",{dx:"0",dy:"2",stdDeviation:"3",floodColor:"hsl(var(--navy))",floodOpacity:"0.18"})}),e.jsxs("radialGradient",{id:"ml-bg",cx:"50%",cy:"42%",r:"70%",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--gold))",stopOpacity:"0.06"}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--gold))",stopOpacity:"0"})]})]}),e.jsx("rect",{x:0,y:0,width:vt,height:wt,fill:"url(#ml-bg)"}),n.map((l,_)=>{const A=i.get(l.source),C=i.get(l.target);if(!A||!C)return null;const E=j?(o==null?void 0:o.edgeIdx.has(_))??!1:!1,R=j?E?.8:.05:.16;return e.jsx(nt.path,{d:Hs(A,C),fill:"none",stroke:E?"var(--gold-dark)":"hsl(var(--muted-foreground))",strokeWidth:E?2:1,strokeLinecap:"round",initial:{pathLength:0,opacity:0},animate:{pathLength:1,opacity:R},transition:{pathLength:{duration:.6,delay:.08+_*.01},opacity:{duration:.25}}},`${l.source}-${l.target}`)}),s.map((l,_)=>{const A=i.get(l.id);if(!A)return null;const C=x(l),E=g(l.id),R=l.id===j,M=l.kind==="center"?Ve:l.kind==="cluster"&&l.marketKind?ye[l.marketKind].Icon:null,$=Math.round(C*.85);return e.jsxs(nt.g,{"data-mnode":"1",role:"button",tabIndex:0,"aria-label":l.label,className:"cursor-pointer focus:outline-none",style:{transformBox:"fill-box",transformOrigin:"center"},initial:{scale:0,opacity:0},animate:{scale:R?1.12:1,opacity:E?1:.18},transition:{scale:{type:"spring",stiffness:260,damping:18,delay:_*.012},opacity:{duration:.3}},onMouseEnter:()=>u(l.id),onMouseLeave:()=>u(null),onClick:I=>{I.stopPropagation(),p(T=>T===l.id?null:l.id)},onKeyDown:I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),p(T=>T===l.id?null:l.id))},filter:"url(#ml-soft)",children:[e.jsx("circle",{cx:A.x,cy:A.y,r:C,fill:h(l),stroke:"white",strokeOpacity:.85,strokeWidth:1.5}),M?e.jsx(M,{x:A.x-$/2,y:A.y-$/2,width:$,height:$,color:l.kind==="center"?"var(--navy)":"white",strokeWidth:2}):null]},l.id)}),s.map(l=>{const _=i.get(l.id);if(!_||!(l.kind==="center"||l.kind==="cluster"||!!j&&g(l.id)))return null;const E=x(l),R=l.kind==="center",M=l.kind==="item"&&l.label.length>26?`${l.label.slice(0,26)}…`:l.label;return e.jsxs("g",{children:[e.jsx("text",{x:_.x,y:_.y+E+(R?16:13),textAnchor:"middle",fill:"hsl(var(--foreground))",stroke:"hsl(var(--background))",strokeWidth:3,paintOrder:"stroke",fontWeight:R||l.kind==="cluster"?600:400,style:{fontSize:R?14:l.kind==="cluster"?12:10},children:M}),l.kind==="cluster"&&l.count?e.jsx("text",{x:_.x,y:_.y+E+28,textAnchor:"middle",fill:"var(--gold-dark)",stroke:"hsl(var(--background))",strokeWidth:3,paintOrder:"stroke",fontWeight:600,style:{fontSize:10},children:l.count}):null]},`l-${l.id}`)})]})}),r&&r.kind==="item"?e.jsxs("div",{className:"rounded-xl border border-border bg-muted/20 p-3",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:r.label}),r.detail?e.jsx("p",{className:"mt-1 line-clamp-3 text-xs text-muted-foreground",children:r.detail}):null,e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-step-caption text-muted-foreground",children:[r.marketKind?e.jsx("span",{children:ye[r.marketKind].label}):null,r.confidence?e.jsxs("span",{className:"capitalize",children:["· ",r.confidence," confidence"]}):null,r.sourceUrl?e.jsxs("a",{href:r.sourceUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-[var(--gold-dark)] hover:underline",children:["Source ",e.jsx(mt,{className:"size-3","aria-hidden":!0})]}):null]})]}):e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Hover a cluster to trace its items - click any no
63de for details. Showing up to ",Ws," items per cluster."]}),e.jsx("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1.5",children:N.map(l=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-step-caption text-muted-foreground",children:[e.jsx("span",{className:"inline-block size-2.5 rounded-full",style:{backgroundColor:ye[l].color}}),ye[l].label]},l))})]})}function Kr(t){if(!t)return"";const s=t.trim();return s.length>320?`${s.slice(0,320).trimEnd()}…`:s}function Vr({campaignId:t}){var d;const{data:s=[],isLoading:n,isError:a,refetch:i}=Sa(t),[c,u]=v.useState("all"),[m,p]=v.useState("list"),j=v.useMemo(()=>{const r=new Map;for(const h of s)r.set(h.kind,(r.get(h.kind)??0)+1);return at.filter(h=>r.has(h)).map(h=>({kind:h,count:r.get(h)??0}))},[s]),o=v.useMemo(()=>{const r=c==="all"?s:s.filter(h=>h.kind===c);return at.map(h=>[h,r.filter(x=>x.kind===h)]).filter(([,h])=>h.length>0)},[s,c]),g=((d=s[0])==null?void 0:d.refreshed_at)??null;return t?a?e.jsx(Le,{compact:!0,noun:"market intelligence",onRetry:()=>void i()}):n&&s.length===0?e.jsx("div",{className:"h-64 w-full rounded-2xl border border-border bg-muted/10"}):s.length===0?e.jsxs("div",{className:"rounded-2xl border border-dashed border-border bg-muted/10 p-8 text-center",children:[e.jsx(Ve,{className:"mx-auto size-7 text-[var(--gold-dark)]","aria-hidden":!0}),e.jsx("p",{className:"mt-3 text-sm font-medium text-foreground",children:"Your Market Layer is ready to fill."}),e.jsx("p",{className:"mx-auto mt-1 max-w-md text-sm text-muted-foreground",children:"Run sector research, public peers, comparables, or a bolt-on scan in the Market and M&A tools, and the intelligence accumulates here, deduped and always feeding your reports."})]}):e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-start gap-3 rounded-xl border border-[var(--gold-dark)]/40 bg-accent px-4 py-3",children:[e.jsx(Ve,{className:"mt-0.5 size-4 shrink-0 text-[var(--gold-dark)]","aria-hidden":!0}),e.jsxs("p",{className:"text-sm text-foreground",children:[e.jsx("span",{className:"font-medium",children:"Market Layer."})," ",e.jsxs("span",{className:"text-muted-foreground",children:["The market intelligence this campaign has accumulated, deduped and feeding your reports automatically. ",s.length," item",s.length===1?"":"s",g?`, last updated ${Rs(new Date(g),{addSuffix:!0})}`:"","."]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(us,{active:m==="list",label:"List",Icon:Un,onClick:()=>p("list")}),e.jsx(us,{active:m==="map",label:"Map",Icon:_s,onClick:()=>p("map")})]}),m==="map"?e.jsx(qr,{items:s}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(ms,{active:c==="all",label:"All",count:s.length,onClick:()=>u("all")}),j.map(({kind:r,count:h})=>e.jsx(ms,{active:c===r,label:ye[r].label,count:h,Icon:ye[r].Icon,onClick:()=>u(r)},r))]}),e.jsx("div",{className:"space-y-6",children:o.map(([r,h])=>{const{label:x,Icon:N}=ye[r];return e.jsxs("section",{children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(N,{className:"size-4 text-[var(--gold-dark)]","aria-hidden":!0}),e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:x}),e.jsx("span",{className:"font-mono text-step-caption text-muted-foreground",children:h.length})]}),e.jsx("ul",{className:"space-y-2.5",children:h.map(l=>e.jsx(Hr,{item:l},l.id))})]},r)})})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a campaign to see its Market Layer."})}function us({active:t,label:s,Icon:n,onClick:a}){return e.jsxs("button",{type:"button",onClick:a,"aria-pressed":t,className:G("inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-medium transition-colors",t?"border-[var(--gold-dark)] bg-accent text-foreground":"border-border bg-background text-muted-foreground hover:border-foreground
63/30 hover:text-foreground"),children:[e.jsx(n,{className:"size-3.5 shrink-0","aria-hidden":!0}),s]})}function ms({active:t,label:s,count:n,Icon:a,onClick:i}){return e.jsxs("button",{type:"button",onClick:i,"aria-pressed":t,className:G("inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium transition-colors",t?"border-[var(--gold-dark)] bg-accent text-foreground":"border-border bg-background text-muted-foreground hover:border-foreground/30 hover:text-foreground"),children:[a?e.jsx(a,{className:"size-3 shrink-0","aria-hidden":!0}):null,s,e.jsx("span",{className:"font-data text-foreground/70",children:n})]})}function Hr({item:t}){const s=Kr(t.body);return e.jsxs("li",{className:"rounded-xl border border-border bg-card p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("p",{className:"font-medium leading-snug text-foreground",children:t.title}),t.confidence?e.jsx(ie,{variant:"outline",className:"shrink-0 capitalize text-muted-foreground",children:t.confidence}):null]}),s?e.jsx("p",{className:"mt-1.5 whitespace-pre-wrap text-sm text-muted-foreground",children:s}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-step-caption text-muted-foreground",children:[e.jsxs("span",{children:["Updated ",Rs(new Date(t.refreshed_at),{addSuffix:!0})]}),t.source_url?e.jsxs("a",{href:t.source_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-[var(--gold-dark)] hover:underline",children:["Source ",e.jsx(mt,{className:"size-3","aria-hidden":!0})]}):null]})]})}const ps=new Set(["inspector","export","quality","activity","schema","import","api"]);function lo(){var se,Q;const t=rt(),{user:s}=Ne(),{toast:n}=Ue(),{canUseDataLayer:a,canUseApiAccess:i,isLoading:c,isProfileError:u}=an(),{campaignId:m,setCampaignId:p,campaigns:j,isLoading:o,isCampaignsError:g,refetchCampaigns:d}=fs(),[r,h]=rn(),x=r.get("tab"),N=r.get("campaign"),[l,_]=v.useState(()=>x&&ps.has(x)?x:"inspector");v.useEffect(()=>{N&&j.some(z=>z.id===N)&&p(N)},[N,j,p]),v.useEffect(()=>{x&&ps.has(x)&&_(x)},[x]);const A=z=>{_(z);const U=new URLSearchParams(r);z==="inspector"?U.delete("tab"):U.set("tab",z),h(U,{replace:!0})},[C,E]=v.useState("campaign"),[R,M]=v.useState(!1),[$,I]=v.useState(()=>{const z=r.get("view");return z==="mind"||z==="lens"||z==="market"?z:"data"}),T=r.get("view");v.useEffect(()=>{(T==="mind"||T==="data"||T==="lens"||T==="market")&&I(T)},[T]);const H=z=>{I(z);const U=new URLSearchParams(r);z==="data"?U.delete("view"):U.set("view",z),h(U,{replace:!0})},k=m||((se=j[0])==null?void 0:se.id)||"",O=((Q=j.find(z=>z.id===k))==null?void 0:Q.company_name)??"Campaign",{data:b}=ct(k||void 0),{data:L=[]}=Je(k||void 0),{data:y=[]}=dt(k||void 0),{data:D=[]}=gs(k||void 0),{data:P=[]}=Pt(k||void 0),{data:F=[]}=ys(k||void 0),{data:f=[]}=ut(k||void 0),q=v.useMemo(()=>{if(!k||!b)return null;const z=b.total,U=b.confirmed+b.edited,fe=Bt(L),ce=y.length,ae=y.filter(Z=>Z.processing_status==="completed").length;let w=null,V=null;for(const Z of L){const xe=Et(Z.created_at);xe!=null&&(w==null||xe>w)&&(w=xe)}for(const Z of D){const xe=Et(Z.created_at);xe!=null&&(V==null||xe>V)&&(V=xe)}const Y=Is(L);return zs({totalAssertions:z,confirmedAssertions:U,categoriesWithData:fe,docsTotal:ce,docsCompleted:ae,kpiCount:P.length,initiativeCount:F.length,riskCount:f.length,lastAssertionMs:w,lastOutputMs:V,contradictionCount:Y})},[k,b,L,y,D,P,F,f]),J=v.useMemo(()=>{const z=y.length,U=(b==null?void 0:b.total)??0,fe=D.length,ce=z===0?0:U/z,ae=Ra(L,D);return{docCount:z,assertionCount:U,outputCount:fe,assertionsPerDoc:ce,citedPct:ae}},[y.length,b,L,D]),W=v.useMemo(()=>!b||b.total===0?0:Math.round((b.confirmed+b.edited)/b.total*100),[b]),oe=async()=>{if(!(!k||R)){M(!0);try{const z=await Bs(k,O),U=qs(O);Xe(z,U),s!=null&&s.id&&(await Ks({campaignId:k,sponsorId:s.id,exportKind:"full_zip_header",filename:U,byteSize:z.size}),t.invalidateQueries({queryKey:["data-exports",k]})),n({title:"Export Ready",description:"Full data dump (ZIP) downloaded."})}catch(z){n({title:"Export failed",description:z instanceof Error?z.message:"Unknown error",variant:"destructive"})}finally{M(!1)}}};return c||o?e.jsx(on,{}):u?e.jsxs("div",{className:G(Wt,"max-w-3xl py-8 text-center animate-fade-in"),children:[e.jsx("p",{className:"font-medium text-destructive",children:"Could not verify subscription tier."}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Check your connection and try again, or refresh the page."}),e.jsx(K,{type:"button",variant:"outline",className:"mt-4",onClick:()=>window.location.reload(),children:"Retry"})]}):g?e.jsx(ht,{icon:Be,title:"Data Layer",subtitle:"Full introspection into your campaign's evidence graph.",children:e.jsx(Le,{noun:"campaigns",onRetry:()=>void d()})}):a?j.length===0?e.jsx(ht,{icon:Be,title:"Data Layer",subtitle:"Full introspection into your campaign's evidence graph.",children:e.jsx(Gt,{toolTitle:"Data Layer",variant:"noCampaignsExist"})}):e.jsxs(ht,{icon:Be,accent:"gold",heroGradient:!0,title:"Data Layer",subtitle:"Full introspection into your campaign's evidence graph, AI truth flow, and schema - exports and governance in one place.",badge:e.jsx(ie,{variant:"outline",className:"border-navy font-normal text-navy dark:border-blue-200 dark:text-blue-100",children:"Enterprise-grade"}),campaignName:C==="campaign"?O:void 0,actions:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(xt,{type:"button",toolbarVariant:"navy",disabled:!k||R,title:"Download full data dump",onClick:()=>void oe(),children:[R?e.jsx(pe,{className:"size-4 animate-spin","aria-hidden":!0}):e.jsx(js,{className:"size-4","aria-hidden":!0}),"Export data"]}),e.jsxs("div",{className:"flex rounded-lg border p-0.5",children:[e.jsxs(xt,{type:"button",toolbarVariant:C==="campaign"?"secondary":"ghost",className:C==="campaign"?void 0:"border-0 shadow-none",onClick:()=>E("campaign"),children:[e.jsx(Yn,{className:"size-4","aria-hidden":!0}),"Campaign"]}),e.jsxs(xt,{type:"button",toolbarVariant:C==="portfolio"?"secondary":"ghost",className:C==="portfolio"?void 0:"border-0 shadow-none",onClick:()=>E("portfolio"),children:[e.jsx(Zn,{className:"size-4","aria-hidden":!0}),"Portfolio"]})]})]}),children:[e.jsx(K,{variant:"ghost",size:"sm",className:"mb-4 gap-1 px-0",asChild:!0,children:e.jsxs(Ae,{to:"/enterprise",children:[e.jsx(Jn,{className:"h-4 w-4"})," Back to Enterprise"]})}
63),e.jsxs("div",{className:"mb-5 flex w-fit rounded-lg border p-0.5",children:[e.jsxs(K,{type:"button",size:"sm",variant:$==="data"?"secondary":"ghost",className:"gap-1.5",onClick:()=>H("data"),children:[e.jsx(Be,{className:"h-4 w-4"}),"Data Layer"]}),e.jsxs(K,{type:"button",size:"sm",variant:$==="mind"?"secondary":"ghost",className:"gap-1.5",onClick:()=>H("mind"),children:[e.jsx(_s,{className:"h-4 w-4"}),"Connected Mind"]}),e.jsxs(K,{type:"button",size:"sm",variant:$==="lens"?"secondary":"ghost",className:"gap-1.5",onClick:()=>H("lens"),children:[e.jsx(_t,{className:"h-4 w-4"}),"House Lens"]}),e.jsxs(K,{type:"button",size:"sm",variant:$==="market"?"secondary":"ghost",className:"gap-1.5",onClick:()=>H("market"),children:[e.jsx(Ve,{className:"h-4 w-4"}),"Market Layer"]})]}),$==="data"?e.jsxs(e.Fragment,{children:[C==="campaign"&&k&&b?e.jsxs("div",{className:"mb-6 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5",children:[e.jsx(Fe,{label:"Assertions",value:String(b.total)}),e.jsx(Fe,{label:"Confirmed",value:`${W}%`}),e.jsx(Fe,{label:"Documents",value:String(y.length)}),e.jsx(Fe,{label:"Outputs",value:String(D.length)}),e.jsx(Fe,{label:"Health score",value:q!=null?`${q.score}`:"-"})]}):null,C==="portfolio"?e.jsx(hr,{}):m?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-6 grid gap-4 lg:grid-cols-2",children:[e.jsx(Ea,{breakdown:q}),e.jsx(Aa,{docCount:J.docCount,assertionCount:J.assertionCount,outputCount:J.outputCount,assertionsPerDoc:J.assertionsPerDoc,citedPct:J.citedPct})]}),e.jsxs(fn,{value:l,onValueChange:A,className:"space-y-4",children:[e.jsx(xn,{className:"flex h-auto flex-wrap gap-1 rounded-lg border bg-muted/30 p-1",children:[{value:"inspector",label:"Inspector",Icon:$t},{value:"export",label:"Export",Icon:ks},{value:"import",label:"Import",Icon:Tt},{value:"api",label:"API",Icon:Wn},{value:"quality",label:"Quality",Icon:Gn},{value:"activity",label:"Activity",Icon:Ns},{value:"schema",label:"Schema",Icon:Qn}].map(({value:z,label:U,Icon:fe})=>e.jsxs(gn,{value:z,className:"inline-flex items-center gap-1.5 rounded-md px-4 py-1.5 text-sm after:hidden data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",children:[e.jsx(fe,{className:"size-3.5 shrink-0 opacity-70","aria-hidden":!0}),U]},z))}),e.jsx(De,{value:"inspector",className:G("space-y-4","outline-none"),children:k?e.jsx(Ia,{campaignId:k}):null}),e.jsx(De,{value:"export",children:k?e.jsx(Qa,{campaignId:k,companyName:O}):null}),e.jsx(De,{value:"import",children:k?e.jsx(lr,{campaignId:k}):null}),e.jsx(De,{value:"api",children:i?e.jsx(ur,{}):e.jsxs("div",{className:"rounded-lg border border-dashed bg-muted/20 p-6 text-sm",children:[e.jsx("p",{className:"font-medium text-foreground",children:"API access"}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:"Key management is available on Enterprise plans."}),e.jsx(K,{asChild:!0,className:"mt-4",size:"sm",children:e.jsx(Ae,{to:"/billing",children:"View plans"})})]})}),e.jsx(De,{value:"quality",children:k?e.jsx(Ya,{campaignId:k}):null}),e.jsx(De,{value:"activity",children:k?e.jsx(ir,{campaignId:k}):null}),e.jsx(De,{value:"schema",children:e.jsx(or,{})})]})]}):e.jsx(Gt,{toolTitle:"Data Layer",variant:"noCampaignSelected"})]}):$==="mind"?e.jsx($r,{campaignId:k||void 0}):$==="lens"?e.jsx(Fr,{campaignId:k||void 0}):e.jsx(Vr,{campaignId:k||void 0})]}):e.jsx("div",{className:G(Wt,"max-w-3xl py-8 animate-fade-in"),children:e.jsx(Ma,{})})}function Fe({label:t,value:s}){return e.jsxs("div",{className:"rounded-lg border border-navy/12 bg-muted/20 px-3 py-2 dark:bg-muted/10",children:[e.jsx("p",{className:"text-step-caption font-medium uppercase tracking-wide text-muted-foreground",children:t}),e.jsx("p",{className:"text-lg font-semibold tabular-nums text-navy dark:text-oposgold",children:s})]})}export{lo as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.