PageSourceSearch

https://app.ololand.ai/assets/DealSummaryView-DK2K8OtX.js

js ololand.ai collected 2026-10-05 12:21:19 UTC 140,081 bytes, 5 lines download raw bytes

1import{r as i,j as e,al as le,aR as Dt,X as ge,aE as en,d_ as Mt,fe as Es,eZ as tn,aO as sn,bq as $t,A as an,by as Fs,e5 as nn,am as rn,T as ot,ff as hs,bA as At,bp as ln,db as on,p as ct,bo as cn,bM as dn,c1 as un,dm as mn,aM as xn,d6 as hn,ar as pn,dv as Ts,aD as dt,ed as fn,bR as gn,bJ as bn,f7 as Ps,bQ as Is,bT as yn,bV as lt,bK as Et,dN as rt,aj as ut,k as mt,w as Lt,cz as qt,ao as ps,aK as fs,an as qe,ap as vn,dt as gs,aP as jn,bm as bs,bu as _n,i as Re,l as Nn,z as wn,fg as kn,fh as ys,dg as Sn,au as Cn,fi as Rn,fj as Dn,fk as An,fl as En,fm as Fn,fn as Tn,fo as Pn,fp as In,fq as Mn}from"./vendor-CJ3Pa3Ob.js";import{f5 as $n,f6 as Ms,c as K,f7 as Ln,dC as Ut,c0 as qn,s as be,au as Ot,bl as Bt,c5 as me,f8 as $s,dB as Un,f9 as On,aS as Ue,aW as zt,bi as Bn,bk as zn,dG as Hn,dZ as Gn,a4 as Vn,eA as Kn,dx as Qn,ed as Wn,N as Yn,e0 as Zn,cT as Xn,fa as Jn,bX as er,fb as Ls,fc as qs,fd as Us,bH as tr,fe as Ht,ff as sr,fg as ar,fh as nr,eD as pe,fi as Os,fj as Bs,fk as zs,fl as rr,fm as Hs,a5 as ir,a6 as lr,a8 as or,fn as cr,fo as dr,fp as ur,fq as mr,fr as xr,fs as hr,ft as Ce,dS as pr,fu as Ft,fv as fr,fw as gr}from"./index-CT7QwV5N.js";import{h as br,u as yr}from"./directUpload-CRcKFNDv.js";import{u as vr}from"./unifiedFileUploadService-CTx52RVe.js";import{p as jr,u as _r,M as Nr}from"./uploadValidation-i1vYGecM.js";import{e as wr,f as kr,g as _t,u as Sr,S as Tt,T as Cr,d as Rr}from"./TileManager-hbVI2XPd.js";import{C as Dr}from"./CompanySearchInput-09SBbQft.js";import{d as Ar}from"./events-CbQvI4Zk.js";import{e as Nt}from"./enhancedFinancial-BJPR4atB.js";import{P as Er}from"./progress-DURQ2Zcq.js";import{u as Fr}from"./useDealSummaryGenerationInputs-DyHZyQMv.js";import{u as Tr}from"./useDocumentProcessingSSE-C6TprDFv.js";import{u as Pr}from"./usePodcast-C70ywKTV.js";import{W as vs}from"./dealSummaryEvents-DdsqpeO4.js";function Ir({deal:t,onOpenAudioBrief:s,onOpenAnalysisStatus:a,onRunResearch:n,onRegenerateAll:r,isRegenerateDisabled:l=!1,onOpenTileManager:o,onShare:m,onExport:c,onRecordOutcome:f,compact:d=!1,isPlaceholderIdentity:u=!1,onSaveIdentity:x,identityEditValue:_}){const[D,w]=i.useState(!1),[p,k]=i.useState(!1),[b,v]=i.useState(""),[g,S]=i.useState(!1),[E,j]=i.useState(null),{outcome:O}=$n(t.id),F=Ms(t.deal_mode),R=(t.name?.[0]??"?").toUpperCase(),q=!!x,Q=()=>{v(u?"":_??t.name),j(null),k(!0)},C=()=>{k(!1),j(null)},H=async()=>{const A=b.trim();if(!(!A||!x||g)){S(!0),j(null);try{await x(A),k(!1)}catch{j("Couldn't save — try again.")}finally{S(!1)}}},P=[a&&{icon:e.jsx(sn,{size:14}),label:"Analysis Status",handler:a},n&&{icon:e.jsx($t,{size:14}),label:"Run Research",handler:n},r&&{icon:e.jsx(an,{size:14}),label:Ut.REGENERATE_SUMMARY,handler:r,disabled:l,title:l?"Analysis in progress":void 0},o&&{icon:e.jsx(Fs,{size:14}),label:"Tile Manager",handler:o},m&&{icon:e.jsx(nn,{size:14}),label:"Share",handler:m},c&&{icon:e.jsx(rn,{size:14}),label:"Export",handler:c}].filter(Boolean);return e.jsxs("div",{className:K("bg-theme-surface-light flex items-center justify-between border-b border-white/[0.06]",d?"h-10 px-3":"h-14 px-4"),children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[!d&&e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-indigo-500 to-purple-600 text-sm font-bold !text-white shadow-sm",children:R}),e.jsxs("div",{className:"group flex min-w-0 items-center gap-2",children:[p?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("input",{autoFocus:!0,value:b,onChange:A=>v(A.target.value),onKeyDown:A=>{A.key==="Enter"?(A.preventDefault(),H()):A.key==="Escape"&&(A.preventDefault(),g||C())},disabled:g,placeholder:"Company name","aria-label":"Company name",maxLength:200,className:K("bg-theme-surface border-theme-divider text-theme-text min-w-0 rounded-md border px-2 py-0.5 font-bold outline-none focus:border-theme-accent",d?"text-sm":"text-[17px]")}),e.jsx("button",{type:"button",onClick:()=>{H()},disabled:g||!b.trim(),title:"Save",className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-emerald-400 hover:text-emerald-300 disabled:opacity-40",children:g?e.jsx(le,{size:14,className:"animate-spin"}):e.jsx(Dt,{size:14})}),e.jsx("button",{type:"button",onClick:C,disabled:g,title:"Cancel",className:"text-theme-text-muted hover:text-theme-text-secondary flex h-7 w-7 shrink-0 items-center justify-center rounded-md disabled:opacity-40",children:e.jsx(ge,{size:14})}),E&&e.jsx("span",{className:"text-[11px] text-red-400",children:E})]}):u&&q?e.jsxs("button",{type:"button",onClick:Q,"data-testid":"deal-identity-add-name",className:"text-theme-text-muted hover:text-theme-text-secondary hover:bg-theme-hover border-theme-divider flex shrink-0 items-center gap-1 rounded-full border border-dashed px-2 py-0.5 text-[11px] font-medium transition-colors",children:[e.jsx(en,{size:11}),"Add company name"]}):e.jsxs(e.Fragment,{children:[q?e.jsx("button",{type:"button","data-testid":"deal-identity-name",onClick:Q,title:"Click to edit company name",className:K("text-theme-text hover:text-theme-text-secondary min-w-0 truncate leading-none font-bold",d?"text-sm":"text-[17px]"),children:t.name}):e.jsx("span",{"data-testid":"deal-identity-name",className:K("text-theme-text min-w-0 truncate leading-none font-bold",d?"text-sm":"text-[17px]"),children:t.name}),q&&e.jsx("button",{type:"button",onClick:Q,title:"Edit company name",className:"text-theme-text-muted hover:text-theme-text-secondary flex h-6 w-6 shrink-0 items-center justify-center rounded-md opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-[var(--app-focus-ring)] focu
1s-visible:outline-none",children:e.jsx(Mt,{size:12})})]}),t.industry&&e.jsx("span",{className:"text-theme-text-muted bg-theme-surface-light shrink-0 rounded-full px-2 py-0.5 text-[11px] font-medium",children:t.industry}),e.jsx("span",{className:"shrink-0 rounded-full bg-emerald-500/20 px-2 py-0.5 text-[11px] font-medium text-emerald-400 capitalize",children:t.status}),F&&e.jsx("span",{className:"text-theme-text-muted shrink-0 text-[11px] font-medium",children:F}),e.jsx(Ln,{outcome:O,onRecordOutcome:f})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[s&&e.jsx("button",{onClick:s,className:"text-theme-text-muted hover:text-theme-text-secondary hover:bg-theme-hover flex h-8 w-8 items-center justify-center rounded-lg transition-colors",title:"Audio Brief",children:e.jsx(Es,{size:15})}),e.jsxs("div",{className:"relative",children:[e.jsx("button",{onClick:()=>w(!D),className:"text-theme-text-muted hover:text-theme-text-secondary hover:bg-theme-hover flex h-8 w-8 items-center justify-center rounded-lg transition-colors",title:"More actions",children:e.jsx(tn,{size:15})}),D&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>w(!1)}),e.jsx("div",{className:"border-theme-divider bg-theme-surface-light absolute top-full right-0 z-50 mt-1 w-48 rounded-lg border py-1 shadow-lg",children:P.map(({icon:A,label:$,handler:G,disabled:N,title:te})=>e.jsxs("button",{onClick:()=>{N||(w(!1),G())},disabled:N,title:te,className:"text-theme-text-secondary disabled:text-theme-text-muted hover:bg-theme-hover flex w-full items-center gap-2 px-3 py-1.5 text-sm disabled:cursor-not-allowed disabled:hover:bg-transparent",children:[A,$]},$))})]})]})]})]})}const Mr=new Set(["full_pipeline","extraction"]);function $r(t){return Mr.has(t.task_type)?t.parent_task_id?t.parent_task_id===(t.task_id??t.id):!0:!1}function Lr(t,s){return!t||t.length===0?null:t.filter(n=>n.deal_id===s&&n.task_type==="full_pipeline"&&$r(n)).sort((n,r)=>{const l=n.started_at?new Date(n.started_at).getTime():0;return(r.started_at?new Date(r.started_at).getTime():0)-l})[0]??null}function qr(t,s){const[a,n]=i.useState(!1),[r,l]=i.useState(!1),{completeFirstUpload:o}=qn(),[m,c]=i.useState(null),[f,d]=i.useState(null),u=i.useCallback(()=>{n(!0),d(null)},[]),x=i.useCallback(()=>{n(!1),c(null)},[]),_=i.useCallback(async(D,w={enableAIEnrichment:!0,enrichmentFocus:"comprehensive",mergeWithExisting:!0,notifyTeam:!1})=>{if(!D.length)return;const{empty:p,oversize:k,audioOversize:b}=jr(D),v=br(),g=v?[]:k;if(p.length>0||g.length>0||b.length>0){d({success:!1,error:_r(p,g,b)});return}l(!0),c({current:0,total:D.length});try{const S=await Promise.all(D.map(async(j,O)=>{if(c({current:O+1,total:D.length,fileName:j.name}),await vr.processFile(j,{dealId:t.id,userId:t.createdBy||""}),v&&j.size>Nr){const q=await yr(t.id,j);return{success:!0,job_ids:q.job_id?[q.job_id]:[]}}const F=new FormData;return F.append("files",j),await be.postFormData(`/deals/${t.id}/documents/upload-async`,F)})),E={success:S.every(j=>j.success===!0||j.job_ids!=null&&j.job_ids.length>0),uploadResults:S,updatedDeal:t};d(E),E.success&&(s(E.updatedDeal),o())}catch(S){console.error("Document upload failed:",S),d({success:!1,error:S instanceof Error?S.message:"Upload failed"})}finally{l(!1),c(null)}},[t,s,o]);return{isUploadModalOpen:a,openUploadModal:u,closeUploadModal:x,uploadDocuments:_,isUploading:r,uploadProgress:m,lastUploadResult:f}}function Le(t,s,a,n,r){if(t)return"completed";if(s){if(a===null)return"running";if(a>=n)return a>=r?"completed":"running"}return"pending"}function js(t,s){const a=t.research_seed_metadata?.[s];if(!a||typeof a!="object"||Array.isArray(a))return;const n=a.status;return typeof n=="string"?n:void 0}function Gs(t){const s=t.research_seed_metadata?.public_ingest;if(!s||typeof s!="object"||Array.isArray(s))return!1;const a=s;return a.status==="completed"&&typeof a.phase1_task_id=="string"&&a.phase1_task_id.length>0&&a.phase1_task_id===t.data_collection_phase1_task_id}function _s(t,s){return t===s?{status:"completed"}:{status:"skipped",note:t?"No usable data":"Availability not confirmed"}}function Ur(t,s){const a=t.data_collection_status??"none",n=a==="phase2_queued"&&t.is_public===!0&&Gs(t),r=a==="phase1_running"||a==="phase2_queued"&&!n,l=n||["phase1_done","phase2_running","phase2_failed","completed"].includes(a),o=a==="phase2_running",m=a==="completed",c=a==="phase2_failed";let f="skipped";t.ticker&&(f=Le(l,r,s,70,90));let d="pending",u;m?d="completed":c?(d="failed",u="Failed · phase 1 data kept"):(o||a==="phase1_done")&&(d="running");const x={icon:ln,label:"Deep market research",status:d,note:u};if(t.is_public===!0){const _=l?_s(js(t,"edgar"),"ingested"):{status:t.ticker?Le(l,r,s,10,55
1):"skipped"},D=l?_s(js(t,"fmp"),"ingested"):{status:Le(l,r,s,55,80)};return[{icon:hs,label:t.ticker?`SEC filings (${t.ticker})`:"SEC filings check",..._},{icon:At,label:"FMP standardized financials",...D},x]}return[{icon:At,label:"Apollo company data",status:Le(l,r,s,20,40)},{icon:on,label:"Web search intelligence",status:Le(l,r,s,40,70)},{icon:hs,label:t.ticker?`SEC filings (${t.ticker})`:"SEC filings check",status:f},x]}const Or=new Set(["completed","failed","cancelled"]),Br=({deal:t,className:s,onSkipToUpload:a})=>{const n=t.data_collection_status==="failed",{tasks:r}=Ot({dealId:t.id,taskTypes:["data_collection"]}),l=i.useMemo(()=>r.find(w=>w.deal_id===t.id&&!Or.has(w.status??"")),[r,t.id]),o=t.data_collection_status??"none",m=typeof l?.progress=="number"?Math.min(100,Math.max(0,l.progress)):null,c=["phase1_running","phase1_done","phase2_queued","phase2_running"].includes(o),f=m??(o==="completed"?100:0),d=m===null&&c,u=l?.message??l?.current_step??(o==="phase1_running"?t.is_public===!0?"Collecting SEC filings and standardized financials...":"Collecting company profile, web intelligence, and SEC data...":o==="phase2_running"?"Running deep market research...":o==="phase2_queued"&&Gs(t)?"Source collection complete — waiting to start deep market research...":"Collecting intelligence..."),x=i.useMemo(()=>Ur(t,m),[t,m]),_=x.filter(w=>w.status==="completed").length,D=x.filter(w=>w.status!=="skipped").length;return n?e.jsxs("div",{className:K("space-y-4",s),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ot,{className:"h-4 w-4 text-red-500"}),e.jsx("p",{className:"text-theme-text text-sm font-semibold",children:"Auto-research failed"})]}),e.jsx("p",{className:"text-theme-text-secondary text-sm",children:"We couldn't complete the automatic data collection. You can still build your dashboard by uploading documents manually."}),a&&e.jsx("button",{onClick:a,className:"bg-theme-surface-light text-theme-text-secondary hover:bg-theme-surface-light inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium transition-colors dark:bg-white/5 dark:hover:bg-white/10",children:"Proceed to next step"})]}):e.jsxs("div",{className:K("space-y-4",s),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($t,{className:"text-theme-accent h-4 w-4"}),e.jsx("p",{className:"text-theme-text text-sm font-semibold",children:"Collecting Company Intelligence"})]}),e.jsx("p",{className:"text-theme-text-secondary text-sm",children:"Gathering data from external sources to build your deal dashboard."}),e.jsxs("div",{children:[e.jsx("div",{className:"bg-theme-surface-light h-2 w-full overflow-hidden rounded-full",role:"progressbar","aria-valuenow":d?void 0:f,"aria-valuemin":0,"aria-valuemax":100,"aria-label":d?"Collecting data (progress unknown)":void 0,children:d?e.jsx("div",{className:"bg-theme-accent progress-indeterminate h-full w-1/3 rounded-full"}):e.jsx("div",{className:"bg-theme-accent h-full rounded-full transition-all duration-500",style:{width:`${f}%`}})}),e.jsxs("div",{className:"mt-1 flex items-center justify-between",children:[e.jsx("span",{className:"text-theme-text-muted text-xs",children:u}),e.jsxs("span",{className:"text-theme-text-muted text-xs font-medium",children:[_,"/",D," sources"]})]})]}),e.jsx("div",{className:"space-y-2",children:x.map(w=>e.jsx(Gr,{source:w},w.label))})]})},zr={completed:{container:"border-[var(--status-positive-border)] bg-[var(--status-positive-bg)]",text:"text-[var(--status-positive-text)]"},running:{container:"border-[var(--theme-accent)]/30 bg-[var(--theme-accent-tint)]",text:"text-theme-accent"},failed:{container:"border-[var(--status-warning-border)] bg-[var(--status-warning-bg)]",text:"text-[var(--status-warning-text)]"},skipped:{container:"border-theme-divider bg-slate-50/30 text-theme-text-muted dark:border-white/[0.04] dark:bg-zinc-800/20",text:"text-theme-text-muted line-through"},pending:{container:"border-theme-divider bg-white/60 dark:border-white/[0.06] dark:bg-zinc-800/30",text:"text-theme-text-secondary"}};function Hr({source:t}){return t.status==="completed"?e.jsx(ct,{className:"h-4 w-4 shrink-0 text-emerald-500"}):t.status==="running"?e.jsx(le,{className:"text-theme-accent h-4 w-4 shrink-0 animate-spin"}):t.status==="failed"?e.jsx(ot,{className:"h-4 w-4 shrink-0 text-[var(--status-warning-text)]"}):e.jsx(t.icon,{className:"text-theme-text-muted h-4 w-4 shrink-0"})}function Gr({source:t}){const s=zr[t.status];return e.jsxs("div",{className:K("flex items-center gap-2.5 rounded-lg border px-3 py-2 text-sm",s.container),children:[e.jsx(Hr,{source:t}),e.jsx("span",{className:K("font-medium",s.text),children:t.label}),t.status==="skipped"&&!t.note&&e.jsx("span",{className:"text-theme-text-muted ml-auto text-xs",children:"N/A"}),t.note&&e.jsx("span",{className:"text-theme-text-muted ml-auto text-xs whitespace-nowrap",children:t.note})]})}const Vr={FileText:ut,DollarSign:rt,TrendingUp:Et,BarChart:lt,BarChart3:lt,AlertTriangle:ot,Users:yn,GitCompare:Is,ArrowLeftRight:Ps,BookOpen:bn,Calculator:gn,Landmark:fn,Sparkles:dt,Shield:Ts,ShieldAlert:pn,TrendingDown:hn,Clock:xn,ListChecks:mn,Bell:un,Brain:dn,Gauge:cn};function Kr({entry:t}){const s=Vr[t.icon]??Fs;return e.jsxs("div",{className:"flex items-center gap-2.5 rounded-xl border border-dashed border-theme-divider bg-white/30 px-4 py-3 dark:border-white/[0.08] dark:bg-zinc-800/20",children:[e.jsx(s,{className:"h-4 w-4 shrink-0 text-theme-text-secondary"}),e.jsx("span",{className:"text-slate-350 text-sm font-medium text-theme-text-muted",children:t.title})]})}const Qr=({className:t})=>{const a=wr.filter(r=>r.isDefault).reduce((r,l)=>(r[l.group]||(r[l.group]=[]),r[l.group].push(l),r),{}),n=["screening","diligence","valuation","execution","operational"];return e.jsxs("div",{className:K("space-y-4",t),children:[e.jsx("p",{className:"text-center text-xs font-medium tracking-wide text-theme-text-muted uppercase",children:"Tiles that will be generated"}),n.map(r=>{const l=a[r];return l?.length?e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-semibold text-theme-text-muted",children:kr[r]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 @5xl:grid-cols-3",children:l.map(o=>e.jsx(Kr,{entry:o},o.type))})]},r):null})]})},Wr={queued:"Queued",uploading:"Uploading",extracting:"Extracting",analyzing:"Analyzing",completed:"Ready for Search",failed:"Failed"};function wt({icon:t,label:s,count:a,available:n}){return e.jsxs("div",{className:K("flex items-center gap-2 rounded-lg border px-3 py-2 text-sm",n?"border-emerald-200/80 bg-emerald-50/60 text-emerald-700 dark:border-emerald-500/30 dark:bg-emerald-500/10 dark:text-emerald-400":"border-theme-divider text-theme-text-muted bg-slate-50/60 dark:border-white/[0.06] dark:bg-zinc-800/30"),children:[n?e.jsx(ct,{className:"h-4 w-4 shrink-0 text-emerald-500"}):e.jsx(t,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"font-medium",children:n?`${a} ${s}`:`No ${s.toLowerCase()}`})]})}
1const Yr=({deal:t,hasUploadedDocuments:s,hasExternalEvidence:a,uploadedDocumentCount:n,externalComparableCount:r,externalPrecedentCount:l,onNavigateToComparables:o,onNavigateToPrecedents:m,onGenerateSummaryOnly:c,isGenerateSummaryLoading:f,generationInputs:d,hasGenerationInputsError:u=!1,isGenerating:x,generationProgress:_,onFileUploaded:D,processingStatus:w,dataCollectionStatus:p,canRunFullAnalysis:k=!0,fullAnalysisDisabledReason:b,hasActiveFullPipelineRun:v=!1})=>{const g=mt(),S=t.name||t.target||"Deal",[E,j]=i.useState("undecided"),[O,F]=i.useState(!1),R=Bt(),q=i.useCallback(async()=>{F(!0);try{await me.startDataCollection(t.id),await g.invalidateQueries({queryKey:["deal",t.id]})}catch(L){console.error("Failed to start data collection:",L),L instanceof Error&&"status"in L&&L.status===409?(await g.invalidateQueries({queryKey:["deal",t.id]}),R.info("Data collection is already running for this deal.")):R.error("Failed to start research. Please try again.")}finally{F(!1)}},[t.id,g,R]);i.useEffect(()=>{s&&E==="undecided"&&j("upload")},[s,E]);const Q=Lt(),[C,H]=i.useState(0),P=i.useMemo(()=>Object.values(w),[w]),A=i.useMemo(()=>P.some(L=>L.status!=="completed"&&L.status!=="failed"),[P]),[$,G]=i.useState(!1);i.useEffect(()=>{P.length>0&&!$&&G(!0)},[P.length,$]),i.useEffect(()=>{C>0&&$&&(P.length===0||P.every(oe=>oe.status==="completed"||oe.status==="failed"))&&(H(0),G(!1))},[C,$,P]),i.useEffect(()=>{if(C>0&&P.length===0&&!$){const oe=setTimeout(()=>{H(0),G(!1),g.invalidateQueries({queryKey:["deal",t.id]})},15e3);return()=>clearTimeout(oe)}},[C,P.length,$,g,t.id]);const N=i.useRef(Date.now());i.useEffect(()=>{N.current=Date.now()},[P]),i.useEffect(()=>{if(C>0&&$&&P.some(L=>L.status!=="completed"&&L.status!=="failed")){const L=setInterval(()=>{Date.now()-N.current>3e4&&(H(0),G(!1),g.invalidateQueries({queryKey:["deal",t.id]}))},1e4);return()=>clearInterval(L)}},[C,$,P,g,t.id]);const te=P.length===0?C===0:P.every(L=>L.status==="completed"||L.status==="failed"),I=n+C,X=s||C>0,T=X||a,Y=T&&k,ae=d?.can_generate??!1,ne=ae?void 0:u?"Couldn't check available inputs — try again shortly":"Needs comparables, precedent transactions, or a prior analysis",{tasks:h,hasActiveTasks:V,isConnected:B}=Ot({dealId:t.id,taskTypes:["full_pipeline"]}),z=V||v,W=i.useMemo(()=>Lr(h,t.id),[h,t.id]),J=W?.progress??0,re=W?.message??W?.current_step??"",ie=W?.status==="failed",ue=p??t.data_collection_status,De=i.useMemo(()=>({...t,data_collection_status:ue}),[t,ue]),xe=ue==="phase1_running"||ue==="phase2_queued"||ue==="phase2_running",ye=ue==="failed"||ue==="phase2_failed",ee=i.useMemo(()=>x||z||ie?4:xe||ye&&E==="undecided"?0:E==="research"&&T||(T||ae)&&te?3:X&&!te?2:1,[x,z,ie,xe,ye,E,T,ae,te,X]),Ae=i.useCallback(L=>{H(oe=>oe+L.length),D?.(oe=>oe+L.length),g.invalidateQueries({queryKey:["deal",t.id]})},[g,t.id,D]),je=i.useCallback(async()=>{try{await me.updateDeal(t.id,{data_collection_status:"skipped"}),g.invalidateQueries({queryKey:["deal",t.id]})}catch{g.invalidateQueries({queryKey:["deal",t.id]})}},[t.id,g]);return e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6",children:[e.jsxs("div",{className:"border-theme-divider rounded-2xl border bg-gradient-to-br from-slate-50 via-white to-blue-50/30 p-6 dark:to-blue-950/20",children:[ee!==4&&(()=>{const L=ee===0?1:ee;return e.jsxs("div",{className:"mb-5 flex items-center gap-2",role:"navigation","aria-label":"Wizard progress",children:[E==="research"&&ee!==0&&e.jsx("span",{className:"text-theme-text-muted mr-1 shrink-0 rounded-full border border-emerald-200/80 bg-emerald-50/60 px-2 py-0.5 text-[10px] font-semibold tracking-wide uppercase dark:border-emerald-500/30 dark:bg-emerald-500/10",children:"Research track"}),e.jsx(kt,{phase:1,currentPhase:L,label:"Upload documents",completedOverride:X,optionalWhenSkipped:!0}),e.jsx(Ns,{completed:X&&L>1,active:L===1}),e.jsx(kt,{phase:2,currentPhase:L,label:"Review what was found"}),e.jsx(Ns,{completed:L>2,active:L===2}),e.jsx(kt,{phase:3,currentPhase:L,label:"Run Full Analysis"})]})})(),ee===0&&e.jsx("div",{children:ye?e.jsx(Jr,{deal:t,dataCollectionStatus:p,hasExternalEvidence:a,externalComparableCount:r,externalPrecedentCount:l,onChooseUpload:()=>{je(),j("upload")},onChooseResearch:()=>{je(),j("research")}}):e.jsxs(e.Fragment,{children:[e.jsx(Br,{deal:De,onSkipToUpload:je}),e.jsx("p",{className:"text-theme-text-muted mt-4 text-center text-xs",children:"Your dashboard will populate automatically when research completes."})]})}),ee===1&&e.jsx("div",{children:E==="undecided"?e.jsx(Xr,{dealName:S,hasExternalEvidence:a,externalComparableCount:r,externalPrecedentCount:l,dataCollectionStatus:p,onChooseUpload:()=>j("upload"),onChooseResearch:()=>j("research"),onStartResearch:q,isStartingResearch:O}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(qt,{className:"h-4 w-4 text-blue-500"}),e.jsx("p",{className:"text-theme-text text-sm font-semibold",children:"Upload Documents"})]}),e.jsxs("p",{className:"text-theme-text-secondary text-sm",children:["Add documents to the data room for"," ",e.jsx("span",{className:"text-theme-text-secondary font-medium",children:S}),". We'll extract financials, risks, and key insights to build your dashboard."]})]}),e.jsx(Zr,{deal:t,onUploadComplete:Ae}),e.jsxs("div",{className:"mt-4 flex flex-col items-center justify-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-theme-text-muted text-xs",children:"or start with"}),e.jsx("button",{onClick:o,className:"text-theme-text-muted hover:text-theme-text-secondary text-xs font-medium underline decoration-slate-300 underline-offset-2 transition-colors dark:decoration-slate-600",children:"Comparable Companies"}),e.jsx("span",{className:"text-theme-text-secondary text-xs",children:"|"}),e.jsx("button",{onClick:m,className:"text-theme-text-muted hover:text-theme-text-secondary text-xs font-medium underline decoration-slate-300 underline-offset-2 transition-colors dark:decoration-slate-600",children:"Precedent Transactions"})]}),e.jsx("button",{onClick:()=>j("undecided"),className:"text-theme-text-muted hover:text-theme-text-secondary mt-2 text-xs font-medium transition-colors",children:"Back to path selection"})]})]})}),ee===2&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(le,{className:"h-4 w-4 animate-spin text-blue-500"}),e.jsx("p",{className:"text-theme-text text-sm font-semibold",children:"Step 2: Review what was found"})]}),e.jsx("p",{className:"text-theme-text-secondary text-sm",children:"Extracting text and building search indexes for your documents."})]}),e.jsx("div",{className:"mb-4 space-y-2",children:P.map(L=>e.jsx(ei,{file:L},L.file_id))}),e.jsx("div",{className:"rounded-lg border border-theme-accent bg-blue-50/50 px-3 py-2 dark:bg-blue-500/5",children:P.length===0?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(le,{className:"h-3 w-3 animate-spin text-blue-500"}),e.jsx("span",{className:"text-xs font-medium text-theme-text dark:text-theme-accent-text",children:"Waiting for processing status..."})]}):e.jsxs("span",{className:"text-xs font-medium text-theme-text dark:text-theme-accent-text",children:[P.filter(L=>L.status==="completed").length," of"," ",P.length," files ready"]})})]}),ee===3&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(dt,{className:"h-4 w-4 text-violet-500"}),e.jsx("p",{className:"text-theme-text text-sm font-semibold",children:"Step 3: Run Full Analysis"})]}),e.jsx("p",{className:"text-theme-text-secondary text-sm",children:X?"Your documents are indexed and ready — choose an analysis path to generate your deal summary.":"Your deal data is ready — choose an analysis path to generate your deal summary."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("p",{className:"text-theme-text-secondary mb-2 text-xs font-semibold tracking-wide uppercase",children:"Data sources detected"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(wt,{icon:ut,label:I===1?"document":"documents",count:I,available:X}),e.jsx(wt,{icon:Is,label:r===1?"comparable":"comparables",count:r,available:r>0}),e.jsx(wt,{icon:Ps,label:l===1?"precedent txn":"precedent txns",count:l,available:l>0})]})]}),e.jsxs("div",{className:"border-theme-divider space-y-3 rounded-xl border bg-slate-50/70 p-4 dark:bg-black/20",children:[e.jsx("p",{className:"text-theme-text text-xs font-semibold tracking-wide uppercase",children:"Choose your analysis"}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:K("roun
1ded-xl border p-4 transition-colors",Y?"border-theme-accent bg-blue-50/50 dark:bg-blue-500/5":"border-theme-divider bg-theme-surface/60 opacity-50 dark:border-white/[0.06]"),children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(ps,{className:"h-4 w-4 text-theme-accent-text dark:text-theme-accent-text"}),e.jsx("span",{className:"text-theme-text text-sm font-semibold",children:"Run Full Analysis"})]}),e.jsx("p",{className:"text-theme-text-muted mb-3 text-xs",children:"Extracts financials, risks, opportunities, and commercial insights, then generates all dashboard tiles."}),e.jsx($s,{dealId:t.id,dealName:S,disabled:!Y,disabledReason:Y?void 0:b??"Add source documents or research before running Full Analysis",hasProcessingDocuments:A}),!Y&&b&&e.jsx("p",{className:"text-theme-text-muted mt-2 text-xs",children:b})]}),e.jsxs("div",{className:"border-theme-divider bg-theme-surface/60 rounded-xl border p-4 transition-colors dark:border-white/[0.06]",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(fs,{className:"h-4 w-4 text-violet-600 dark:text-violet-400"}),e.jsx("span",{className:"text-theme-text text-sm font-semibold",children:"Quick Summary"})]}),e.jsx("p",{className:"text-theme-text-muted mb-3 text-xs",children:"Creates tiles from data already available — comparables, precedent transactions, and any prior analysis."}),e.jsx(Un,{label:Ut.QUICK_SUMMARY,busyLabel:"Generating...",icon:e.jsx(fs,{className:"h-4 w-4"}),busy:f,disabled:!ae,disabledReason:ne,onRun:c}),!ae&&ne&&e.jsx("p",{className:"text-theme-text-muted mt-2 text-xs",children:ne})]})]})]}),e.jsx("div",{className:"mt-3 text-center",children:e.jsx("button",{onClick:()=>Q(`/deals/${t.id}/dataroom`),className:"text-theme-text-muted hover:text-theme-text-secondary text-xs font-medium transition-colors",children:"Upload more documents"})})]}),ee===4&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(ps,{className:"h-4 w-4 text-theme-accent-text dark:text-theme-accent-text"}),e.jsx("p",{className:"text-theme-text text-sm font-semibold",children:z?"Full Analysis Running":"Generating Tiles"})]}),e.jsx("p",{className:"text-theme-text-secondary text-sm",children:z?On:"Building your deal summary dashboard..."})]}),z&&e.jsxs("div",{className:"mb-4 space-y-2",children:[e.jsx("div",{className:"bg-theme-surface-light h-2 w-full overflow-hidden rounded-full",role:"progressbar","aria-valuenow":J,"aria-valuemin":0,"aria-valuemax":100,"aria-label":"Full analysis progress",children:e.jsx("div",{className:K("h-full rounded-full transition-all duration-500",ie?"bg-red-500":"bg-[var(--theme-button-primary-bg)]"),style:{width:`${J}%`}})}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-theme-text-muted min-w-0 truncate text-xs",children:re||"Running full analysis..."}),e.jsxs("span",{className:"text-theme-text-muted shrink-0 font-mono text-xs font-medium",children:[J,"%"]})]})]}),!z&&x&&e.jsxs("div",{className:"mb-4",children:[e.jsx("div",{className:"bg-theme-surface-light h-2 w-full overflow-hidden rounded-full",role:"progressbar","aria-valuenow":_,"aria-valuemin":0,"aria-valuemax":100,"aria-label":"Tile generation progress",children:e.jsx("div",{className:"h-full rounded-full bg-violet-500 transition-all duration-500",style:{width:`${_}%`}})}),e.jsxs("span",{className:"text-theme-text-muted mt-1 block text-xs font-medium",children:["Generating tiles... ",_,"%"]})]}),ie&&e.jsxs("div",{className:"mb-4 flex items-center gap-2 rounded-lg bg-red-50 p-3 text-sm text-red-800 dark:bg-red-500/10 dark:text-red-400",children:[e.jsx(qe,{className:"h-4 w-4 shrink-0"}),"Analysis encountered errors. Partial results may still be available."]}),z&&!B&&!ie&&e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-lg bg-amber-50 p-3 text-sm text-amber-800 dark:bg-amber-500/10 dark:text-amber-400",children:[e.jsx(qe,{className:"h-4 w-4 shrink-0"}),"Live updates paused — connection lost. Analysis continues on the server. Refresh to see latest status."]}),z&&!ie&&B&&e.jsx("p",{className:"text-theme-text-muted text-center text-xs",children:"You can navigate freely — analysis continues in the background."})]})]}),e.jsx(Qr,{})]})};function Zr({deal:t,onUploadComplete:s}){const[a,n]=i.useState([]),r=i.useRef(null),l=Bt(),o=i.useRef(0),m=i.useRef(null),c=i.useCallback(()=>{s(new Array(o.current).fill(null)),n([])},[s]),{uploadDocuments:f,isUploading:d,uploadProgress:u,lastUploadResult:x}=qr(t,c);i.useEffect(()=>{if(!x||x===m.current)return;m.current=x;const p=x;!p.success&&p.error&&l.error(p.error)},[x,l]);const _=i.useCallback(p=>{p.length!==0&&n(k=>[...k,...p])},[]),D=i.useCallback(p=>{n(k=>k.filter((b,v)=>v!==p))},[]),w=i.useCallback(()=>{a.length===0||d||(o.current=a.length,f(a))},[a,d,f]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx("input",{ref:r,type:"file",multiple:!0,accept:".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.csv,.htm,.html,.xhtml,.ixbrl",onChange:p=>{_(Array.from(p.target.files??[])),p.target.value=""},className:"hidden","aria-label":"Choose documents to upload"}),e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>r.current?.click(),onKeyDown:p=>{(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),r.current?.click())},onDragOver:p=>p.preventDefault(),onDrop:p=>{p.preventDefault(),_(Array.from(p.dataTransfer.files??[]))},className:"border-theme-divider bg-theme-surface-light cursor-pointer rounded-lg border-2 border-dashed p-6 text-center transition-colors hover:border-[var(--theme-accent)]",children:[e.jsx(gs,{className:"text-theme-text-muted mx-auto mb-2 h-8 w-8","aria-hidden":!0}),e.jsx("p",{className:"text-theme-text text-sm font-medium",children:"Drop files here or click to browse"}),e.jsx("p",{className:"text-theme-text-muted mt-1 text-xs",children:"PDF, Word, Excel, PowerPoint, and text files"})]}),a.length>0&&e.jsx("ul",{className:"space-y-1.5",children:a.map((p,k)=>e.jsxs("li",{className:"border-theme-divider bg-theme-surface flex items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm",children:[e.jsx("span",{className:"text-theme-text min-w-0 flex-1 truncate",children:p.name}),e.jsx("button",{type:"button",onClick:()=>D(k),disabled:d,"aria-label":`Remove ${p.name}`,className:"text-theme-text-muted hover:text-theme-text shrink-0 disabled:opacity-50",children:e.jsx(ge,{className:"h-3.5 w-3.5"})})]},`${p.name}:${p.size}:${k}`))}),a.length>0&&e.jsx("div",{className:"flex justify-end",children:e.jsx("button",{type:"button",onClick:w,disabled:d,className:"bg-theme-accent hover:bg-theme-accent-hover inline-flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-white disabled:cursor-not-allowed disabled:opacity-60",children:d?e.jsxs(e.Fragment,{children:[e.jsx(le,{className:"h-4 w-4 animate-spin"}),u?`Uploading ${u.current}/${u.total}...`:"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(gs,{className:"h-4 w-4"}),"Upload ",a.length," ",a.length===1?"File":"Files"]})})})]})}function Xr({dealName:t,hasExternalEvidence:s,externalComparableCount:a,externalPrecedentCount:n,dataCollectionStatus:r,onChooseUpload:l,onChooseResearch:o,onStartResearch:m,isStartingResearch:c}){const f=r==="phase1_done"||r==="phase2_running"||r==="phase2_failed"||r==="completed",d=!s&&(r==="none"||r==="skipped"||r==="failed"||r==="phase2_failed"||!r);return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-theme-text text-sm font-semibold",children:"How would you like to proceed?"}),e.jsxs("p",{className:"text-theme-text-secondary mt-1 text-sm",children:["Choose how to build your deal summary for"," ",e.jsx("span",{className:"text-theme-text-secondary font-medium",children:t}),"."]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("button",{onClick:l,className:"group rounded-xl border-2 border-theme-accent bg-blue-50/30 p-5 text-left transition-all hover:border-[var(--theme-accent)] hover:bg-blue-50/60 hover:shadow-md dark:bg-blue-500/5 dark:hover:bg-blue-500/10",children:[e.jsx("div",{className:"mb-3 flex h-10 w-10 items-center justify-center rounded-lg bg-blue-100 dar
1k:bg-blue-500/20",children:e.jsx(qt,{className:"h-5 w-5 text-theme-accent-text dark:text-theme-accent-text"})}),e.jsx("p",{className:"text-theme-text text-sm font-semibold",children:"Upload Documents"}),e.jsx("p",{className:"text-theme-text-muted mt-1 text-xs",children:"Upload CIMs, financials, or other deal documents for comprehensive analysis."})]}),d?e.jsxs("button",{onClick:m,disabled:c,className:"group rounded-xl border-2 border-amber-200/80 bg-amber-50/30 p-5 text-left transition-all hover:border-amber-400 hover:bg-amber-50/60 hover:shadow-md disabled:cursor-not-allowed disabled:opacity-70 dark:border-amber-500/20 dark:bg-amber-500/5 dark:hover:border-amber-500/40 dark:hover:bg-amber-500/10",children:[e.jsx("div",{className:"mb-3 flex h-10 w-10 items-center justify-center rounded-lg bg-amber-100 dark:bg-amber-500/20",children:c?e.jsx(le,{className:"h-5 w-5 animate-spin text-amber-600 dark:text-amber-400"}):e.jsx(vn,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"})}),e.jsx("p",{className:"text-theme-text text-sm font-semibold",children:"Run Research"}),e.jsx("p",{className:"text-theme-text-muted mt-1 text-xs",children:c?"Starting data collection...":"Gather company data, web intelligence, and SEC filings to build your dashboard."})]}):e.jsxs("button",{onClick:o,disabled:!s,className:K("group rounded-xl border-2 p-5 text-left transition-all",s?"border-emerald-200/80 bg-emerald-50/30 hover:border-emerald-400 hover:bg-emerald-50/60 hover:shadow-md dark:border-emerald-500/20 dark:bg-emerald-500/5 dark:hover:border-emerald-500/40 dark:hover:bg-emerald-500/10":"border-theme-divider cursor-not-allowed bg-slate-50/30 opacity-50 dark:border-white/[0.06] dark:bg-zinc-800/20"),children:[e.jsx("div",{className:K("mb-3 flex h-10 w-10 items-center justify-center rounded-lg",s?"bg-emerald-100 dark:bg-emerald-500/20":"bg-theme-surface-light dark:bg-slate-700/30"),children:e.jsx($t,{className:K("h-5 w-5",s?"text-emerald-600 dark:text-emerald-400":"text-theme-text-muted")})}),e.jsx("p",{className:"text-theme-text text-sm font-semibold",children:"Analyze with Research Data"}),e.jsx("p",{className:"text-theme-text-muted mt-1 text-xs",children:s?"Proceed directly to Full Analysis using collected research data.":"No research data available yet. Upload documents instead."}),s&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-1.5",children:[f&&e.jsx("span",{className:"rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-medium text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400",children:"Research data"}),a>0&&e.jsxs("span",{className:"rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-medium text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400",children:[a," comp",a!==1?"s":""]}),n>0&&e.jsxs("span",{className:"rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-medium text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400",children:[n," precedent",n!==1?"s":""]})]})]})]})]})}function Jr({deal:t,dataCollectionStatus:s,hasExternalEvidence:a,externalComparableCount:n,externalPrecedentCount:r,onChooseUpload:l,onChooseResearch:o}){const m=s==="phase2_failed";return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-amber-200/80 bg-amber-50/60 p-4 dark:border-amber-500/20 dark:bg-amber-500/5",children:[e.jsx(ot,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold text-amber-800 dark:text-amber-300",children:"Data collection encountered issues"}),e.jsx("p",{className:"mt-1 text-xs text-amber-700/80 dark:text-amber-400/70",children:m?"Deep research failed, but initial data (company info, web search, SEC filings) was collected successfully.":"We couldn't complete the automatic data collection. You can still proceed with available data or upload documents manually."})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("button",{onClick:l,className:"bg-theme-surface-light text-theme-text-secondary hover:bg-theme-surface-light dark:bg-theme-surface/5 dark:hover:bg-theme-surface/10 inline-flex items-center gap-1.5 rounded-lg px-4 py-2 text-sm font-medium transition-colors",children:[e.jsx(qt,{className:"h-4 w-4"}),"Upload Documents"]}),e.jsxs("button",{onClick:o,disabled:!a,className:K("inline-flex items-center gap-1.5 rounded-lg px-4 py-2 text-sm font-medium transition-colors",a?"bg-emerald-100 text-emerald-700 hover:bg-emerald-200 dark:bg-emerald-500/20 dark:text-emerald-400 dark:hover:bg-emerald-500/30":"bg-theme-surface-light text-theme-text-muted dark:bg-theme-surface/5 cursor-not-allowed opacity-50"),children:[e.jsx(dt,{className:"h-4 w-4"}),"Proceed with Available Data"]})]}),a&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[m&&e.jsx("span",{className:"rounded-full bg-emerald-100/80 px-2.5 py-0.5 text-xs font-medium text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-400",children:"Phase 1 data collected"}),n>0&&e.jsxs("span",{className:"rounded-full bg-emerald-100/80 px-2.5 py-0.5 text-xs font-medium text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-400",children:[n," comparable",n!==1?"s":""]}),r>0&&e.jsxs("span",{className:"rounded-full bg-emerald-100/80 px-2.5 py-0.5 text-xs font-medium text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-400",children:[r," precedent",r!==1?"s":""]})]})]})}function kt({phase:t,currentPhase:s,label:a,completedOverride:n,optionalWhenSkipped:r=!1}){const l=s>t,o=n??l,m=s===t,c=r&&!o&&l,f=t===0?1:t;return e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:K("flex h-7 w-7 items-center justify-center rounded-full text-xs font-bold transition-all",o?"bg-emerald-500 text-white":m?"bg-[var(--theme-button-primary-bg)] text-[var(--theme-button-primary-text)] shadow-md shadow-blue-500/30":"bg-theme-surface-light text-theme-text-muted"),children:o?e.jsx(ct,{className:"h-4 w-4"}):f}),e.jsxs("span",{className:K("hidden text-xs font-medium sm:inline",m?"text-theme-text-secondary":o?"text-emerald-600 dark:text-emerald-400":"text-theme-text-muted"),children:[a,c&&e.jsx("span",{className:"text-theme-text-muted ml-1 text-[10px] font-normal",children:"(optional)"})]})]})}function Ns({completed:t,active:s}){return e.jsxs("div",{className:"relative h-px flex-1",children:[e.jsx("div",{className:K("absolute inset-0 transition-colors",t?"bg-emerald-400 dark:bg-emerald-500":s?"bg-blue-300 dark:bg-blue-500/50":"border-theme-divider border-t border-dashed bg-transparent")}),s&&e.jsx("div",{className:"absolute inset-0 animate-pulse bg-blue-400/60 dark:bg-blue-400/40"})]})}function ei({file:t}){const s=t.status==="completed",a=t.status==="failed",n=s||a?100:t.progress??0;return e.jsxs("div",{className:"border-theme-divider bg-theme-surface/60 rounded-lg border p-3 dark:border-white/[0.06] dark:bg-zinc-800/30",children:[e.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ut,{className:"text-theme-text-muted h-3.5 w-3.5"}),e.jsx("span",{className:"text-theme-text-secondary max-w-[200px] truncate text-xs font-medium",children:t.file_name})]}),e.jsx("span",{className:K("text-xs font-medium",s?"text-emerald-600 dark:text-emerald-400":a?"text-red-600 dark:text-red-400":"text-theme-accent-text dark:text-theme-accent-text"),children:Wr[t.status]??t.status})]}),e.jsx("div",{className:"bg-theme-surface-light dark:bg-theme-surface/5 h-1.5 w-full overflow-hidden rounded-full",children:e.jsx("div",{className:K("h-full rounded-full transition-all duration-500",s?"bg-emerald-500":a?"bg-red-500":"bg-[var(--theme-button-primary-bg)]"),style:{width:`${n}%`}})}),a&&t.error&&e.jsx("p",{className:"mt-1 truncate text-xs text-red-500 dark:text-red-400",children:t.error})]})}function Pt(t){return t.filter(s=>{if(s.status!=="completed"||s.tile_type.startsWith("live_"))return!1;const a=s.content;return a?a._empty===!0||typeof a.data_completeness_pct=="number"&&a.data_completeness_pct<50:!1})}function Vs({tiles:t,ddNotStarted:s,deal:a}){return a?.data_collection_status==="phase2_queued"||a?.data_collection_status==="phase2_running"||a?.data_collection_status==="completed"||s?!1:Pt(t).length>0}const ti=({tiles:t,onNavigateToDataRoom:s,onRerunAnalysis:a,onDismiss:n,ddNotStarted:r,deal:l,isRunActive:o=!1,className:m})=>{const c=l?.data_collection_status==="phase2_queued",f=l?.data_collection_status==="phase2_running",d=c||f,u=l?.data_collection_status==="completed";if(d)return e.jsxs("div",{className:K("relative rounded-xl border border-theme-accent bg-blue-50/60 p-4 dark:bg-blue-500/5",m),children:[e.jsx("button",{onClick:n,className:"absolute top-3 right-3 rounded p-0.5 text-blue-400 transition-colors hover:text-theme-accent-text dark:text-blue-500 dark:hover:text-blue-300","aria-label":"Dismiss",children:e.jsx(ge,{size:14})}),e.jsxs("div",{className:"flex items-start gap-3",children:[c?e.jsx(jn,{size:16,className:"mt-0.5 shrink-0 text-blue-500"}):e.jsx(le,{size:16,className:"mt-0.5 shrink-0 animate-spin text-blue-500"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-theme-text dark:text-blue-300",children:c?"Deep research queued":"Deep research running"}),e.jsx("p",{className:"mt-0.5 text-xs text-blue-700/80 dark:text-blue-400/70",children:c?"Your public filings are ready. Deeper market research will start when a worker is available.":"More insights arriving soon — your dashboard will refresh automatically with enriched market intelligence."})]})]})]});if(u)return Pt(t).length===0||r?null:e.jsxs("div",{className:K("relative rounded-xl border border-emerald-200/80 bg-emerald-50/60 p-4 dark:border-emerald-500/20 dark:bg-emerald-500/5",m),children:[e.jsx("button",{onClick:n,className:"absolute top-3 right-3 rounded p-0.5 text-emerald-400 transition-colors hover:text-emerald-600 dark:text-emerald-500 dark:hover:text-emerald-300","aria-label":"Dismiss",children:e.jsx(ge,{size:14})}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(dt,{size:16,className:"mt-0.5 shrink-0 text-emerald-500"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-emerald-800 dark:text-emerald-300",children:"Dashboard enriched with deep market research"}),e.jsx("p",{className:"mt-0.5 text-xs text-emerald-700/80 dark:text-emerald-400/70",children:"Want even more detail? Upload documents for comprehensive due diligence analysis."}),e.jsx("div",{className:"mt-3",children:e.jsxs("button",{onClick:s,className:"inline-flex items-center gap-1.5 rounded-lg bg-emerald-100 px-3 py-1.5 text-xs font-medium text-emerald-800 transition-colors hover:bg-emerald-200 dark:bg-emerald-500/15 dark:text-emerald-300 dark:hover:bg-emerald-500/25",children:["Upload Documents",e.jsx(bs,{size:12})]})})]})]})]});if(!Vs({tiles:t,ddNotStarted:r,deal:l}))return null;const x=Pt(t),_=x.slice(0,3).map(w=>w.title),D=x.length-_.length;return e.jsxs("div",{className:K("relative rounded-xl border border-amber-200/80 bg-amber-50/60 p-4 dark:border-amber-500/20 dark:bg-amber-500/5",m),children:[e.jsx("button",{onClick:n,className:"absolute top-3 right-3 rounded p-0.5 text-amber-400 transition-colors hover:text-amber-600 dar
1k:text-amber-500 dark:hover:text-amber-300","aria-label":"Dismiss",children:e.jsx(ge,{size:14})}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(_n,{size:16,className:"mt-0.5 shrink-0 text-amber-500"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-semibold text-amber-800 dark:text-amber-300",children:[x.length," ",x.length===1?"tile has":"tiles have"," limited data"]}),e.jsxs("p",{className:"mt-0.5 text-xs text-amber-700/80 dark:text-amber-400/70",children:[_.join(", "),D>0&&` and ${D} more`," — upload more documents or re-run analysis to enrich."]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[e.jsxs("button",{onClick:s,className:"inline-flex items-center gap-1.5 rounded-lg bg-amber-100 px-3 py-1.5 text-xs font-medium text-amber-800 transition-colors hover:bg-amber-200 dark:bg-amber-500/15 dark:text-amber-300 dark:hover:bg-amber-500/25",children:["Upload Documents",e.jsx(bs,{size:12})]}),e.jsx("button",{onClick:a,disabled:o,title:o?"Analysis in progress":void 0,className:"inline-flex items-center gap-1.5 rounded-lg border border-amber-200 bg-white px-3 py-1.5 text-xs font-medium text-amber-700 transition-colors hover:bg-amber-50 disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent dark:border-amber-500/20 dark:bg-transparent dark:text-amber-400 dark:hover:bg-amber-500/10 dark:disabled:hover:bg-transparent",children:Ut.REGENERATE_SUMMARY})]})]})]})]})};function si({dealId:t,knownPublic:s,knownTicker:a,hasUploadedDocuments:n,canEditIdentity:r,isResearchRunning:l,perspective:o,analysisPolicy:m}){const c=mt(),[f,d]=i.useState(""),[u,x]=i.useState(null),[_,D]=i.useState(null),[w,p]=i.useState("idle"),[k,b]=i.useState(null),[v,g]=i.useState(!1),S=i.useRef(t),E=i.useRef(l),j=!n&&r&&!(s&&!a)&&o!=="third_party_merger"&&o!=="capital_raise",O=Re({queryKey:["public-identity-recovery",t],queryFn:()=>me.getPublicIdentityRecovery(t),enabled:j&&!s,retry:!1}),{refetch:F}=O,R=O.data,q=R?.mode==="research_history",Q=!O.isLoading&&(!R||O.isError||!R.eligible||R.mode==="blocked");if(i.useEffect(()=>{S.current=t,d(""),x(null),D(null),p("idle"),b(null),g(!1)},[t]),i.useEffect(()=>{g(!1)},[u?.ticker,u?.cik,R?.research_history_token]),i.useEffect(()=>{const T=E.current&&!l;E.current=l,T&&j&&!s&&F()},[l,j,s,F]),!j)return null;const C=_??u,H=!!_?.ticker,P=s?!!a:H||!!u?.ticker&&!O.isLoading&&!Q&&(!q||v&&!!R?.research_history_token),A=w==="starting"||l,$=w==="saved"?"Retry filing collection":s?"Collect public filings":"Confirm company and collect filings",G=async()=>{S.current===t&&await c.invalidateQueries({queryKey:["deal",t]})},N=(T,Y)=>T instanceof Ue?zt(T)||Y:T instanceof Error&&T.message?T.message:Y,te=T=>{d(T),x(null),(!_||T!==(_.name||_.ticker||""))&&(D(null),p("idle")),b(null),g(!1)},I=T=>{const Y=!!T.cik||T.market==="US"||T.country==="US";if(!T.is_public||!T.ticker||!Y){x(null),b("Choose a US public listing for SEC filings, or upload source documents.");return}x(T),g(!1),b(null)},X=async()=>{if(A||!P)return;p("starting"),b(null);let T=_;try{if(!s&&!_){const Y=u;if(!Y?.ticker)return;const ae={ticker:Y.ticker,cik:Y.cik??null,...q&&v&&R?.research_history_token?{confirm_research_history:!0,research_history_token:R.research_history_token}:{}},ne=await me.bindPublicIdentity(t,ae);if(T={...Y,name:ne.company_name,ticker:ne.ticker,cik:ne.cik,is_public:!0},S.current!==t||(D(T),await G(),S.current!==t))return}if(await me.startDataCollection(t),S.current!==t||(await G(),S.current!==t))return;p("started")}catch(Y){if(S.current!==t||(await G(),S.current!==t))return;if(Y instanceof Ue&&Y.status===409){if(g(!1),await c.invalidateQueries({queryKey:["public-identity-recovery",t]}),S.current!==t)return;p(T||s?"saved":"idle"),b(N(Y,"The server could not start filing collection yet."))}else T&&!s?(p("saved"),b("Company identity saved, but filing collection did not start. Try again.")):s?(p("saved"),b("Filing collection did not start. Try again.")):(p("idle"),b(N(Y,"Filing collection could not be started. Try again.")))}};return e.jsxs("section",{className:"border-theme-divider bg-theme-surface rounded-xl border p-5","aria-live":"polite",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(At,{className:"text-theme-accent mt-0.5 h-5 w-5 shrink-0","aria-hidden":!0}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-theme-text text-base font-semibold",children:s?"Collect public filings":"Identify this company for public filings"}),e.jsxs("p",{className:"text-theme-text-secondary mt-1 text-sm leading-relaxed",children:["This collects publicly available company filings and research. It does not replace uploaded diligence materials."," ",m==="full"?"Full Analysis will run automatically because it is enabled for this deal.":m==="screen"?"Automatic screening is enabled for this deal.":"It does not start Full Analysis."]})]})]}),!s&&e.jsxs("div",{className:"mt-4",children:[e.jsx(Dr,{value:f,onChange:te,onPick:I,onCreateAsTyped:()=>b("Choose a verified public company from the suggestions."),hint:"public",disabled:A,placeholder:"Search a public company by name or ticker"}),u?.ticker&&e.jsxs("p",{className:"text-theme-text mt-2 text-sm",children:["Selected: ",e.jsx("strong",{children:u.name||u.ticker})," (",u.ticker,")"]})]}),!s&&O.isLoading&&e.jsx("p",{className:"text-theme-text-secondary mt-4 text-sm",children:"Checking whether public identity recovery is available…"}),!s&&O.isError&&e.jsxs("p",{className:"text-theme-text mt-4 text-sm",children:["We could not check public identity recovery. Try again to continue.",e.jsx("button",{type:"button",className:"text-theme-accent ml-2 underline",onClick:()=>{F()},children:"Retry"})]}),!s&&Q&&!O.isError&&!O.isLoading&&e.jsx("p",{className:"text-theme-text mt-4 text-sm",children:R?.reason||"Public identity recovery is not available for this deal."}),!s&&q&&e.jsxs("label",{className:"text-theme-text mt-4 flex items-start gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:v,onChange:T=>g(T.target.checked),disabled:A||!u?.ticker||Q}),e.jsx("span",{children:"I confirm this company is the same business as the existing research. That research history remains research and is not verified filing evidence."})]}),C?.ticker&&!s&&e.jsxs("p",{className:"text-theme-text-secondary mt-3 text-sm",children:["Confirm ",e.jsx("strong",{children:C.name||C.ticker})," (",C.ticker,") to bind the filing identity to this deal."]}),e.jsxs("button",{type:"button",onClick:X,disabled:A||!P,className:"bg-theme-accent text-theme-accent-foreground hover:bg-theme-accent/90 mt-4 inline-flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium disabled:cursor-not-allowed disabled:opacity-50",children:[A&&e.jsx(le,{className:"h-4 w-4 animate-spin","aria-hidden":!0}),$]}),w==="started"&&e.jsxs("p",{className:"text-theme-text mt-3 flex items-center gap-2 text-sm",children:[e.jsx(ct,{className:"h-4 w-4 text-emerald-600","aria-hidden":!0}),"Filing collection started. Progress will appear here as the deal updates."]}),l&&e.jsx("p",{className:"text-theme-text-secondary mt-3 text-sm",children:"Filing collection is in progress."}),k&&e.jsx("p",{className:"text-theme-text mt-3 text-sm",children:k})]})}function ai(t){if(t.perspective==="sponsor_buyside")return e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-theme-divider bg-theme-surface-light px-4 py-2",children:[e.jsx("span",{className:"text-sm font-medium text-theme-text-muted",children:"Sponsor buy-side"}),e.jsxs("span",{className:"text-sm text-theme-text-secondary",children:["· ",t.firmName]})]});const{acquirerName:s,targetName:a,announcedDate:n,dealValue:r,financingType:l}=t;return e.jsxs("div",{className:"flex flex-col gap-1 rounded-lg border border-theme-divider bg-theme-surface-light px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-theme-text",children:s}),e.jsx("span",{className:"text-theme-text-muted","aria-hidden":"true",children:"▸"}),e.jsx("span",{className:"font-semibold text-theme-text",children:a}),e.jsx("span",{className:"text-sm text-theme-text-muted",children:"· Third-party merger view"})]}),(n||l||r)&&e.jsxs("div",{className:"text-xs text-theme-text-muted",children:[n&&e.jsxs("span",{children:["Announced ",n]}),l&&e.jsxs("span",{children:[" · ",l]}),r&&e.jsxs("span",{children:[" · ",r]})]})]})}async function ni(t){return be.get(`/deals/${t}/merger-readiness`)}async function ri(t){return be.get(`/deals/${t}/terms`)}async function ii(t,s,a){return be.post(`/deals/${t}/merger/run-${s}`,{overrides:a})}async function li(t,s){return be.post(`/deals/${t}/merger/scenario-inputs`,s)}const oi=300*1e3;function ci(t,s){return["merger-engine",t,s]}function fe(t,s){return Re({queryKey:ci(t,s),queryFn:()=>ii(t,s),enabled:!!t,staleTime:oi,refetchOnWindowFocus:!1})}function di(t,s){return t.invalidateQueries({predicate:a=>{const n=a.queryKey;return Array.isArray(n)&&n[0]==="merger-engine"&&n[1]===s}})}function ui(t){const s=mt();return()=>di(s,t)}function mi({dealId:t}){const{data:s,isLoading:a}=fe(t,"accretion");if(a)return e.jsxs("div",{className:"rounded-lg border border-theme-divider bg-theme-surface-light p-4",children:[e.jsx("div",{className:"mb-2 text-sm text-theme-text-muted",children:"Accretion / Dilution"}),e.jsx("div",{className:"text-sm text-theme-text-muted",children:"Computing accretion…"})]});if(s?.status==="insufficient_data")return e.jsxs("div",{className:"rounded-lg border border-yellow-700 bg-theme-surface-light p-4",children:[e.jsx("div",{className:"mb-2 text-sm text-theme-text-muted",children:"Accretion / Dilution"}),e.jsx("div",{className:"text-sm text-yellow-400",children:"Awaiting EPS + share-count inputs"})]});const n=s?.outputs??{},r=[["Year 1",n.year_1_eps_change_pct],["Year 2",n.year_2_eps_change_pct],["Year 3",n.year_3_eps_change_pct]];return e.jsxs("div",{className:"rounded-lg border border-theme-divider bg-theme-surface-light p-4",children:[e.jsx("div",{className:"mb-2 text-sm text-theme-text-muted",children:"Accretion / Dilution"}),e.jsx("div",{className:"mt-2 grid grid-cols-3 gap-3",children:r.map(([l,o])=>e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-theme-text-muted",children:l}),e.jsx("div",{className:`text-xl font-semibold ${(o??0)>=0?"text-green-400":"text-red-400"}`,children:o!=null?`${o.toFixed(1)}%`:"—"})]},l))}),e.jsxs("div",{className:"mt-3 text-xs text-theme-text-muted",children:["Breakeven synergies: $",((n.breakeven_synergies_usd??0)/1e6).toFixed(0),"M"]})]})}function xi({dealId:t}){const{data:s,isLoading:a}=fe(t,"hhi");if(a)return e.jsxs("div",{className:"rounded-lg border border-theme-divider bg-theme-surface-light p-4",children:[e.jsx("div",{className:"mb-2 text-sm text-theme-text-muted",children:"Antitrust HHI"}),e.jsx("div",{className:"text-sm text-theme-text-muted",children:"Running HHI…"})]});if(s?.status==="insufficient_data")return e.jsxs("div",{className:"rounded-lg border border-yellow-700 bg-theme-surface-light p-4",children:[e.jsx("div",{className:"mb-2 text-sm text-theme-text-muted",children:"Antitrust HHI"}),e.jsx("div",{className:"text-sm text-yellow-400",children:"Awaiting market shares for rivals"})]});const n=s?.outputs??{},r=n.presumptive_challenge,l=n.confidence??"low",o=l==="high"?"bg-green-900 text-green-300":l==="medium"?"bg-yellow-900 text-yellow-300":"bg-red-900 text-red-300";return e.jsxs("div",{className:"rounded-lg border border-theme-divider bg-theme-surface-light p-4",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between",children:[e.jsx("div",{className:"text-sm text-theme-text-muted",children:"Antitrust HHI"}),e.jsxs("span",{className:`rounded px-2 py-0.5 text-xs ${o}`,children:[l," confidence"]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-theme-text-muted",children:"Pre"}),e.jsx("div",{className:"text-xl text-theme-text",children:n.pre_hhi??"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-theme-text-muted",children:"Post"}),e.jsx("div",{className:"text-xl text-theme-text",children:n.post_hhi??"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-theme-text-muted",children:"Δ HHI"}),e.jsx("div",{className:`text-xl ${(n.hhi_delta??0)>200?"text-red-400":"text-theme-text"}`,children:n.hhi_delta??"—"})]})]}),n.market_concentration_tier&&e.jsxs("div",{className:"mt-3 text-sm text-theme-text-secondary",children:["Market: ",e.jsx("span",{className:"capitalize",children:n.market_concentration_tier})]}),r===!0&&e.jsx("div",{className:"mt-2 text-sm font-medium text-red-400",children:"⚠ Presumptive challenge per DOJ guidelines"}),r===null&&e.jsx("div",{className:"mt-2 text-xs text-yellow-400",children:"Challenge flag suppressed (low confidence)"})]})}const hi=1e3;function at(t,s){return`$${(t/hi).toFixed(s)}B`}function pi({dealId:t}){const{data:s,isLoading:a}=fe(t,"dcf");if(a)return e.jsxs("div",{className:"rounded-lg border border-theme-divider bg-theme-surface-light p-4",children:[e.jsx("div",{className:"mb-2 text-sm text-theme-text-muted",children:"Combined Valuation"}),e.jsx("div",{className:"text-sm text-theme-text-muted",children:"Computing combined DCF…"})]});if(s?.status==="insufficient_data")return e.jsxs("div",{className:"rounded-lg border border-yellow-700 bg-theme-surface-light p-4",children:[e.jsx("div",{className:"mb-2 text-sm text-theme-text-muted",children:"Combined Valuation"}),e.jsx("div",{className:"text-sm text-yellow-400",children:"Need both target + acquirer financial snapshots"})]});const n=s?.outputs??{},r=typeof n.combined_ev_usd=="number",l=typeof n.sum_of_parts_ev_usd=="number",o=typeof n.implied_synergy_value_usd=="number";if(!r&&!l&&!o)return e.jsxs("div",{className:"rounded-lg border border-theme-divider bg-theme-surface-light p-4",children:[e.jsx("div",{className:"mb-2 text-sm text-theme-text-muted",children:"Combined Valuation"}),e.jsx("div",{className:"text-sm text-theme-text-secondary",children:"Upload combined docs to compute pro-forma EV and implied synergy."})]});const m=n.implied_synergy_value_usd??0,c=Math.abs(m)<1,f=m>0&&!c,d=m<0&&!c;return e.jsxs("div",{className:"rounded-lg border border-theme-divider bg-theme-surface-light p-4",children:[e.jsx("div",{className:"mb-2 text-sm text-theme-text-muted",children:"Combined Valuation"}),e.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-theme-text-muted",children:"Combined EV"}),e.jsx("div",{className:"text-xl text-theme-text",children:r?at(n.combined_ev_usd,1):"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-theme-text-muted",children:"Sum of parts"}),e.jsx("div",{className:"text-xl text-theme-text",children:l?at(n.sum_of_parts_ev_usd,1):"—"})]})]}),e.jsxs("div",{className:"mt-3 border-t border-theme-divider pt-3",children:[e.jsx("div",{className:"text-xs text-theme-text-muted",children:"Implied synergy value"}),o?c?e.jsxs("div",{className:"text-2xl font-semibold text-theme-text-secondary",children:[at(0,2),e.jsx("span",{className:"ml-2 text-sm text-theme-text-muted",children:"no synergy modeled"})]}):e.jsxs("div",{className:`text-2xl font-semibold ${f?"text-green-400":"text-red-400"}`,children:[at(m,2),e.jsx("span",{className:"ml-2 text-sm",children:f?"value created":d?"value destroyed":""})]}):e.jsx("div",{className:"text-sm text-theme-text-muted",children:"Awaiting combined DCF"})]})]})}function fi({dealId:t}){const{data:s,isLoading:a}=Re({queryKey:["deal-terms",t],queryFn:()=>ri(t),enabled:!!t});if(a)return e.jsxs("div",{className:"rounded-lg border border-theme-divider bg-theme-surface-light p-4",children:[e.jsx("div",{className:"mb-2 text-sm text-theme-text-muted",children:"Deal Terms"}),e.jsx("div",{className:"text-sm text-theme-text-muted",children:"Loading deal terms…"})]});if(!s||s.offer_price_per_share==null)return e.jsxs("div",{className:"rounded-lg border border-theme-divider bg-theme-surface-light p-4",children:[e.jsx("div",{className:"mb-2 text-sm text-theme-text-muted",children:"Deal Terms"}),e.jsx("div",{className:"text-sm text-theme-text-muted italic",children:"Awaiting Lane C deal artifacts…"})]});const n=s.financing_mix;return e.jsxs("div",{className:"rounded-lg bord
1er border-theme-divider bg-theme-surface-light p-4",children:[e.jsx("div",{className:"mb-2 text-sm text-theme-text-muted",children:"Deal Terms"}),e.jsxs("div",{className:"text-2xl font-semibold text-theme-text",children:["$",s.offer_price_per_share.toFixed(2)," / share"]}),n&&e.jsxs("div",{className:"mt-1 text-sm text-theme-text-secondary",children:[n.cash_pct,"% cash / ",n.stock_pct,"% stock / ",n.debt_pct,"% debt"]}),s.exchange_ratio!=null&&e.jsxs("div",{className:"text-sm text-theme-text-secondary",children:["Exchange ratio: ",s.exchange_ratio]}),s.breakup_fee_usd!=null&&e.jsxs("div",{className:"mt-2 text-xs text-theme-text-muted",children:["Breakup fee: $",(s.breakup_fee_usd/1e6).toFixed(0),"M"]}),s.citation&&e.jsx("div",{className:"mt-1 text-xs text-[var(--theme-accent)]",children:s.citation})]})}function gi({dealId:t,acquirerName:s,targetName:a}){const n=fe(t,"dcf"),r=fe(t,"premium"),l=fe(t,"accretion"),o=fe(t,"hhi"),m=n.data?.outputs??{},c=l.data?.outputs??{},f=r.data?.outputs??{},d=o.data?.outputs??{},u=ws(m.combined_ev_usd),x=ws(m.implied_synergy_value_usd),_=ks(c.year_1_accretion_pct??c.y1_accretion),D=ks(f.premium_to_unaffected??f.premium_pct),w=typeof d.hhi_delta=="number"?Math.round(d.hhi_delta):void 0,p=!!d.presumptive_challenge,k=[n.data,r.data,l.data,o.data],b=k.filter(S=>S?.status==="completed").length,v=k.filter(S=>S?.status==="insufficient_data").length;let g;return b===4?g=" · every number below is replayable via its run_id":v>0&&b+v===4?g=` · ${v} awaiting input — enter scenario inputs below`:v>0?g=` · ${v} awaiting input · loading remaining engines…`:g=" · loading remaining engines…",e.jsxs("div",{className:"rounded-lg border border-theme-divider bg-theme-surface-light p-5",children:[e.jsxs("div",{className:"mb-4 flex items-center gap-3",children:[e.jsx("span",{className:"rounded bg-emerald-700/30 px-2 py-0.5 text-[10px] font-bold tracking-wider text-emerald-300 uppercase",children:"Executive summary"}),e.jsxs("span",{className:"text-[11px] text-theme-text-muted",children:[b," of 4 engines completed",g]})]}),e.jsxs("p",{className:"mb-4 text-sm leading-relaxed text-theme-text-secondary",children:[e.jsx("span",{className:"font-semibold text-theme-text",children:s}),"'s announced acquisition of ",e.jsx("span",{className:"font-semibold text-theme-text",children:a}),", analyzed end-to-end via OloLand's deterministic merger engines. Combined DCF, accretion-dilution, antitrust HHI, and premium analysis run directly against EDGAR primary filings — every output below carries a"," ",e.jsx("code",{className:"rounded bg-theme-surface px-1 py-0.5 text-[11px] text-emerald-300",children:"run_id"})," ","the IC can replay against the original inputs."]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 @3xl:grid-cols-3 @5xl:grid-cols-6",children:[e.jsx(Se,{label:"Combined EV",value:u,subtitle:St(n.data),accent:"emerald"}),e.jsx(Se,{label:"Implied synergy NPV",value:x,subtitle:"from combined DCF",accent:"emerald"}),e.jsx(Se,{label:"Premium to unaffected",value:D,subtitle:St(r.data),accent:"amber"}),e.jsx(Se,{label:"Year-1 EPS accretion",value:_,subtitle:St(l.data),accent:"emerald"}),e.jsx(Se,{label:"Antitrust Δ HHI",value:typeof w=="number"?`+${w}`:void 0,subtitle:p?"presumptive challenge":"unconcentrated · no challenge",accent:p?"red":"emerald"}),e.jsx(Se,{label:"Engine call status",value:`${b}/4`,subtitle:"dcf · premium · accretion · hhi",accent:"slate"})]}),e.jsxs("p",{className:"mt-4 border-t border-theme-divider pt-3 text-[12px] leading-relaxed text-theme-text-muted",children:[e.jsx("span",{className:"font-semibold text-theme-text-secondary",children:"How to read this cockpit:"})," the tiles below drill into each engine with the inputs visible inline, the per-side strips show target and acquirer scoped tiles, and risks extracted from ingested filings appear once document indexing completes (~5–10 min after ingestion)."]})]})}const bi=1e3;function ws(t){if(typeof t=="number")return`$${(t/bi).toFixed(1)}B`}function ks(t){if(typeof t!="number")return;const s=t*100;return`${s>=0?"+":""}${s.toFixed(1)}%`}function St(t){return t?t.status==="insufficient_data"?"needs more inputs":t.status==="failed"?"engine error":t.run_id?`run ${t.run_id.slice(0,8)}`:"engine ran":"loading…"}function Se({label:t,value:s,subtitle:a,accent:n}){const r={emerald:"border-t-emerald-500",amber:"border-t-amber-500",red:"border-t-red-500",slate:"border-t-slate-500"}[n];return e.jsxs("div",{className:`rounded-lg border border-theme-divider${r}border-t-2 bg-theme-surface p-3`,children:[e.jsx("div",{className:"text-[10px] font-semibold tracking-wider text-theme-text-muted uppercase",children:t}),e.jsx("div",{className:"mt-1 text-xl font-bold text-theme-text",children:s??e.jsx("span",{className:"text-theme-text-muted",children:"—"})}),e.jsx("div",{className:"mt-1 text-[10px] text-theme-text-muted",children:a})]})}function yi({dealId:t}){const{data:s,isLoading:a}=fe(t,"premium");
1if(a)return e.jsxs("div",{className:"rounded-lg border border-theme-divider bg-theme-surface-light p-4",children:[e.jsx("div",{className:"mb-2 text-sm text-theme-text-muted",children:"Premium Analysis"}),e.jsx("div",{className:"text-sm text-theme-text-muted",children:"Computing premium…"})]});const n=s?.outputs??{};return s?.status==="insufficient_data"?e.jsxs("div",{className:"rounded-lg border border-yellow-700 bg-theme-surface-light p-4",children:[e.jsx("div",{className:"mb-2 text-sm text-theme-text-muted",children:"Premium Analysis"}),e.jsx("div",{className:"text-sm text-yellow-400",children:"Awaiting data:"}),e.jsx("ul",{className:"mt-1 list-inside list-disc text-xs text-yellow-300",children:n.missing?.map(r=>e.jsx("li",{children:r.field},r.field))})]}):e.jsxs("div",{className:"rounded-lg border border-theme-divider bg-theme-surface-light p-4",children:[e.jsx("div",{className:"mb-2 text-sm text-theme-text-muted",children:"Premium Analysis"}),e.jsxs("div",{className:"text-2xl font-semibold text-theme-text",children:[n.premium_to_unaffected_pct?.toFixed(1),"%"]}),e.jsx("div",{className:"text-xs text-theme-text-muted",children:"vs unaffected price"}),e.jsxs("div",{className:"mt-2 text-sm text-theme-text-secondary",children:["52wk high: ",n.premium_to_52wk_high_pct?.toFixed(1),"% · 30d VWAP:"," ",n.premium_to_30d_vwap_pct?.toFixed(1),"%"]}),typeof n.precedent_percentile=="number"&&e.jsxs("div",{className:"mt-2 text-sm text-theme-text-secondary",children:["Precedent: ",n.precedent_percentile,"th percentile",typeof n.is_at_or_below_median=="boolean"&&(n.is_at_or_below_median?e.jsx("span",{className:"text-green-400",children:" (at/below median)"}):e.jsx("span",{className:"text-yellow-400",children:" (above median)"}))]})]})}function vi({dealId:t,initial:s,isHypothetical:a}){const n=ui(t),[r,l]=i.useState(s??{});i.useEffect(()=>{s&&l(s)},[s]);const[o,m]=i.useState(()=>(s?.rivals??[]).map(p=>`${p.name}, ${p.share_pct}`).join(`
2`)),[c,f]=i.useState(null),d=Nn({mutationFn:p=>li(t,p),onSuccess:async()=>{f(null),await n()},onError:p=>f(p.message||"Save failed")}),u=p=>k=>{const b=k.target.value;l(v=>{const g={...v};return b===""?delete g[p]:g[p]=Number(b),g})},x=p=>k=>{const b=k.target.value;l(v=>{const g=v.financing_mix??{cash_pct:0,stock_pct:0,debt_pct:0};return{...v,financing_mix:{...g,[p]:b===""?0:Number(b)}
2}})},_=p=>k=>{const b=k.target.value;l(v=>{const g=v.market_definition??{industry:""};return{...v,market_definition:{...g,[p]:b}}})},D=p=>{m(p.target.value)},w=p=>{p.preventDefault();const k=o.split(`
3`).map(v=>v.trim()).filter(Boolean).map(v=>{const g=v.split(",").map(j=>j.trim());if(g.length<2)return null;const S=Number(g[g.length-1]);if(!Number.isFinite(S))return null;const E=g.slice(0,-1).join(", ").trim();return E?{name:E,share_pct:S}:null}).filter(v=>v!==null),b={...r};if(k.length>0?b.rivals=k:delete b.rivals,b.financing_mix){const v=b.financing_mix;v.cash_pct===0&&v.stock_pct===0&&v.debt_pct===0&&delete b.financing_mix}b.market_definition&&!b.market_definition.industry&&delete b.market_definition,d.mutate(b)};return e.jsxs("form",{onSubmit:w,className:"border-theme-divider bg-theme-surface-light rounded-lg border p-5","data-testid":"scenario-inputs-panel",children:[e.jsxs("div",{className:"mb-4 flex items-center gap-3",children:[e.jsx("span",{className:"rounded bg-[var(--theme-accent-tint)] px-2 py-0.5 text-[10px] font-bold tracking-wider text-[var(--theme-accent)] uppercase",children:"Scenario inputs"}),e.jsx("span",{className:"text-theme-text-muted text-[11px]",children:a?"Hypothetical scenario — values feed every engine on save":"Enter values directly to override or supplement Lane C artifacts"})]}),e.jsxs("p",{className:"text-theme-text-muted mb-4 text-xs leading-relaxed",children:["These fields populate the four engines for deals where no 8-K / announcement carries the offer price, synergy plan, or market shares. Saved inputs persist to"," ",e.jsx("code",{children:"research_seed_metadata"}),"; the four engine queries are invalidated automatically so the cockpit re-runs with the new values."]}),e.jsxs(nt,{title:"Pricing & reference levels",children:[e.jsx(se,{label:"Offer price / share ($)",value:r.offer_price_per_share,onChange:u("offer_price_per_share"),step:"0.01"}),e.jsx(se,{label:"Target unaffected price ($)",value:r.target_unaffected_price,onChange:u("target_unaffected_price"),step:"0.01"}),e.jsx(se,{label:"Target 52wk high ($)",value:r.target_52wk_high,onChange:u("target_52wk_high"),step:"0.01"}),e.jsx(se,{label:"Target 30d VWAP ($)",value:r.target_30d_vwap,onChange:u("target_30d_vwap"),step:"0.01"})]}),e.jsxs(nt,{title:"Offer structure",children:[e.jsx(se,{label:"Exchange ratio (shares/share)",value:r.exchange_ratio,onChange:u("exchange_ratio"),step:"0.0001"}),e.jsx(se,{label:"Breakup fee ($)",value:r.breakup_fee_usd,onChange:u("breakup_fee_usd"),step:"1000000"}),e.jsxs("div",{className:"col-span-2 mt-2 grid grid-cols-3 gap-2 text-xs",children:[e.jsx(se,{label:"Cash %",value:r.financing_mix?.cash_pct,onChange:x("cash_pct"),step:"1",min:"0",max:"100"}),e.jsx(se,{label:"Stock %",value:r.financing_mix?.stock_pct,onChange:x("stock_pct"),step:"1",min:"0",max:"100"}),e.jsx(se,{label:"Debt %",value:r.financing_mix?.debt_pct,onChange:x("debt_pct"),step:"1",min:"0",max:"100"})]})]}),e.jsxs(nt,{title:"EPS bridge inputs",children:[e.jsx(se,{label:"After-tax synergy run-rate ($M)",value:r.after_tax_synergy_runrate_million,onChange:u("after_tax_synergy_runrate_million"),step:"1"}),e.jsx(se,{label:"After-tax new debt interest ($M)",value:r.after_tax_new_debt_interest_million,onChange:u("after_tax_new_debt_interest_million"),step:"1"}),e.jsx(se,{label:"Tax rate (0-1)",value:r.tax_rate,onChange:u("tax_rate"),step:"0.01",min:"0",max:"1"})]}),e.jsxs(nt,{title:"Market share assumptions",children:[e.jsx(Ss,{label:"Industry (market definition)",value:r.market_definition?.industry??"",onChange:_("industry"),placeholder:"e.g. application software"}),e.jsx(Ss,{label:"Geography",value:r.market_definition?.geography??"",onChange:_("geography"),placeholder:"United States"}),e.jsx(se,{label:"Target share %",value:r.target_share_pct,onChange:u("target_share_pct"),step:"0.1",min:"0",max:"100"}),e.jsx(se,{label:"Acquirer share %",value:r.acquirer_share_pct,onChange:u("acquirer_share_pct"),step:"0.1",min:"0",max:"100"}),e.jsxs("div",{className:"col-span-2 mt-2",children:[e.jsx("label",{className:"text-theme-text-muted block text-xs",children:'Rivals (one per line: "name, share_pct")'}),e.jsx("textarea",{value:o,onChange:D,rows:3,className:"border-theme-divider bg-theme-surface text-theme-text placeholder:text-theme-text-secondary mt-1 w-full rounded border px-2 py-1 text-sm",placeholder:`Microsoft, 22.5
4Salesforce, 14.3
5Oracle, 9.1`})]})]}),e.jsxs("div",{className:"border-theme-divider mt-4 flex items-center justify-between border-t pt-3",children:[e.jsxs("div",{className:"text-theme-text-muted text-[11px]",children:[d.isSuccess&&!d.isPending&&e.jsx("span",{className:"text-emerald-400",children:"Saved · engines will refresh within a few seconds."}),c&&e.jsx("span",{className:"text-red-400",children:c})]}),e.jsx("button",{type:"submit",disabled:d.isPending,className:"rounded bg-[var(--theme-accent)] px-4 py-1.5 text-sm font-semibold text-white transition-colors hover:bg-[var(--theme-accent-hover)] disabled:cursor-not-allowed disabled:opacity-60",children:d.isPending?"Saving…":"Save scenario input
5s"})]})]})}function nt({title:t,children:s}){return e.jsxs("div",{className:"mb-4",children:[e.jsx("div",{className:"text-theme-text-muted mb-2 text-[11px] font-semibold tracking-wider uppercase",children:t}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:s})]})}function se({label:t,value:s,onChange:a,step:n,min:r,max:l}){return e.jsxs("label",{className:"text-theme-text-muted block text-xs",children:[t,e.jsx("input",{type:"number",value:s??"",onChange:a,step:n,min:r,max:l,className:"border-theme-divider bg-theme-surface text-theme-text placeholder:text-theme-text-secondary mt-1 block w-full rounded border px-2 py-1 text-sm"})]})}function Ss({label:t,value:s,onChange:a,placeholder:n}){return e.jsxs("label",{className:"text-theme-text-muted block text-xs",children:[t,e.jsx("input",{type:"text",value:s,onChange:a,placeholder:n,className:"border-theme-divider bg-theme-surface text-theme-text placeholder:text-theme-text-secondary mt-1 block w-full rounded border px-2 py-1 text-sm"})]})}function Cs({side:t,label:s,children:a}){const n=t==="target"?"bg-[var(--viz-1)]":"bg-[var(--viz-3)]";return e.jsxs("div",{className:"flex-1 rounded-lg border border-theme-divider bg-theme-surface p-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2 text-xs font-bold tracking-wider text-theme-text-muted uppercase",children:[e.jsx("span",{className:`inline-block h-2 w-2 rounded-full ${n}`,"aria-hidden":"true"}),s]}),e.jsx("div",{className:"space-y-3",children:a})]})}const ji=["target","acquirer","combined"];function Rs(t){return ji.some(s=>{const a=t[s]?.tier;return a==="missing"||a==="low"})}function _i(t){const s=Re({queryKey:["merger-readiness",t],queryFn:()=>ni(t),enabled:!!t,refetchInterval:n=>{const r=n.state.data;return r?Rs(r)?1e4:!1:5e3}}),a=!!s.data&&Rs(s.data);return{...s,hasLowOrMissingSide:a}}const Ni=["target","acquirer","combined"];function wi({dealId:t,onUploadClick:s}){const{data:a}=_i(t);if(!a)return null;const n=Ni.filter(r=>a[r].tier==="low"||a[r].tier==="missing");return n.length===0?null:e.jsx("div",{className:"mb-4 rounded-lg border border-yellow-700 bg-yellow-900/30 p-3",children:n.map(r=>e.jsxs("div",{className:"flex items-center justify-between py-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"mr-2 text-yellow-300","aria-hidden":"true",children:"⚠"}),e.jsxs("span",{className:"text-yellow-100",children:["Limited data for ",e.jsx("strong",{className:"uppercase",children:r})," (",a[r].tier,")"]})]}),e.jsxs("button",{type:"button",onClick:()=>s(r),className:"rounded bg-yellow-700 px-3 py-1 text-sm text-yellow-100 hover:bg-yellow-600",children:["Upload ",r," docs"]})]},r))})}function ki({dealId:t,onUploadClick:s}){const{data:a,isLoading:n}=Re({queryKey:["deal",t],queryFn:()=>me.getDeal(t),enabled:!!t}),r=i.useMemo(()=>Si(a?.research_seed_metadata),[a?.research_seed_metadata]);if(n)return e.jsx("div",{className:"p-4 text-sm text-theme-text-muted",children:"Loading cockpit…"});if(!a||a.perspective!=="third_party_merger")return null;const l=a.acquirer_company?.name??a.acquirer??"Acquirer",o=a.target,m=a.research_seed_metadata,c=m?.announced_date,f=m?.financing_type,d=!!m?.is_hypothetical,u=a.value?`$${a.value.toLocaleString()}M`:void 0;return e.jsxs("div",{className:"space-y-4 p-4",children:[e.jsx(ai,{perspective:"third_party_merger",acquirerName:l,targetName:o,announcedDate:c,dealValue:u,financingType:f}),e.jsx(gi,{dealId:a.id,acquirerName:l,targetName:o}),e.jsx(wi,{dealId:a.id,onUploadClick:x=>s?.(x)}),e.jsxs("div",{className:"my-4 grid grid-cols-2 gap-4",children:[e.jsx(fi,{dealId:a.id}),e.jsx(yi,{dealId:a.id}),e.jsx(mi,{dealId:a.id}),e.jsx(xi,{dealId:a.id})]}),e.jsx("div",{className:"my-4",children:e.jsx(pi,{dealId:a.id})}),e.jsx(vi,{dealId:a.id,initial:r,isHypothetical:d}),e.jsxs("div",{className:"my-4 flex gap-4",children:[e.jsx(Cs,{side:"target",label:`Target — ${o}`,children:e.jsx("div",{className:"text-xs text-theme-text-muted italic",children:"Target-scoped tiles (RiskMatrix, ForensicQoE, StandaloneDCF, Financial
5Snapshot) will render here once they are made side-aware."})}),e.jsx(Cs,{side:"acquirer",label:`Acquirer — ${l}`,children:e.jsx("div",{className:"text-xs text-theme-text-muted italic",children:"Acquirer-scoped tiles will render here."})})]})]})}function Si(t){if(!t)return;const s={},a=o=>{const m=t[o];return typeof m=="number"?m:void 0};s.offer_price_per_share=a("offer_price_per_share"),s.target_unaffected_price=a("target_unaffected_price"),s.target_52wk_high=a("target_52wk_high"),s.target_30d_vwap=a("target_30d_vwap"),s.exchange_ratio=a("exchange_ratio"),s.breakup_fee_usd=a("breakup_fee_usd"),s.after_tax_synergy_runrate_million=a("after_tax_synergy_runrate_million"),s.after_tax_new_debt_interest_million=a("after_tax_new_debt_interest_million"),s.tax_rate=a("tax_rate"),s.target_share_pct=a("target_share_pct"),s.acquirer_share_pct=a("acquirer_share_pct");const n=t.financing_mix;if(n&&typeof n=="object"){const o=n;typeof o.cash_pct=="number"&&typeof o.stock_pct=="number"&&typeof o.debt_pct=="number"&&(s.financing_mix={cash_pct:o.cash_pct,stock_pct:o.stock_pct,debt_pct:o.debt_pct})}const r=t.market_definition;if(r&&typeof r=="object"){const o=r;typeof o.industry=="string"&&(s.market_definition={industry:o.industry,geography:typeof o.geography=="string"?o.geography:void 0,product_segment:typeof o.product_segment=="string"?o.product_segment:void 0})}const l=t.rivals;return Array.isArray(l)&&(s.rivals=l.map(o=>{if(!o||typeof o!="object")return null;const m=o;return typeof m.name=="string"&&typeof m.share_pct=="number"?{name:m.name,share_pct:m.share_pct}:null}).filter(o=>o!==null)),s}const it={submitCorrection:async(t,s)=>be.post(`/deals/${t}
5/ai-financial/corrections`,s),getMetricsForCorrection:async t=>be.get(`/deals/${t}/ai-financial/metrics`),getReconciliationTargets:async(t,s)=>{const a=s?`?snapshot_id=${encodeURIComponent(s)}`:"";return be.get(`/deals/${t}/ai-financial/reconciliation-targets${a}`)}};function Ci(t,s=t){const[a,n]=i.useState({dealId:t,sessionScope:s,corrections:[],isSubmitting:!1,error:null}),r=a.dealId===t&&a.sessionScope===s,l=r?a.corrections:[],o=r?a.isSubmitting:!1,m=r?a.error:null,c=i.useCallback(async d=>{n(u=>({dealId:t,sessionScope:s,corrections:u.dealId===t&&u.sessionScope===s?u.corrections:[],isSubmitting:!0,error:null}));try{const u=await it.submitCorrection(t,d);return n(x=>x.dealId===t&&x.sessionScope===s?{...x,corrections:[...x.corrections,u]}:x),u}catch(u){let x="Failed to submit correction. Please try again.";throw u instanceof Ue?x=zt(u)||(u.status===404?"The requested metric or deal was not found.":u.message):u instanceof Error&&(x=u.message),n(_=>_.dealId===t&&_.sessionScope===s?{..._,error:x}:_),u}finally{n(u=>u.dealId===t&&u.sessionScope===s?{...u,isSubmitting:!1}:u)}},[t,s]),f=i.useCallback(()=>n(d=>({dealId:t,sessionScope:s,corrections:d.dealId===t&&d.sessionScope===s?d.corrections:[],isSubmitting:d.dealId===t&&d.sessionScope===s?d.isSubmitting:!1,error:null})),[t,s]);return{submitCorrection:c,corrections:l,isSubmitting:o,error:m,clearError:f}}const Ds={wrong_number:"Wrong Number",wrong_period:"Wrong Period",wrong_unit:"Wrong Unit",wrong_line_item:"Wrong Line Item",missing_adjustment:"Missing Adjustment",other:"Other"};function Ri(t,s){const a=s.toLowerCase();let n=t;return a.includes("thousand")||a==="k"?n=t*1e3:a.includes("million")||a==="m"?n=t*1e6:(a.includes("billion")||a==="b")&&(n=t*1e9),Math.abs(n)>=1e9?`$${(n/1e9).toFixed(1)}B`:Math.abs(n)>=1e6?`$${(n/1e6).toFixed(1)}M`:Math.abs(n)>=1e3?`$${(n/1e3).toFixed(0)}K`:`$${n.toFixed(0)}`}function Di(t){return t.replace(/_/g," ").replace(/\b\w/g,s=>s.toUpperCase())}const Ai=({metric:t,onSubmit:s,isSubmitting:a})=>{const[n,r]=i.useState(!1),[l,o]=i.useState(String(t.value)),[m,c]=i.useState("wrong_number"),[f,d]=i.useState(""),[u,x]=i.useState(!1),_=i.useId(),D=`${_}-value`,w=`${_}-reason`,p=`${_}-notes`,k=async()=>{const j=parseFloat(l);if(isNaN(j))return;const O=t.original_unit.toLowerCase();let F=j;const R="ACTUAL";O.includes("thousand")||O==="k"?F=j*1e3:O.includes("million")||O==="m"?F=j*1e6:(O.includes("billion")||O==="b")&&(F=j*1e9);try{await s({metric_id:t.id,corrected_value:F,corrected_unit:R,correction_reason:m,correction_notes:f.trim()||void 0,source_document_id:t.source_document_id,source_page:t.page_reference,reconciliation_snapshot_id:t.reconciliation_snapshot_id}),r(!1),x(!0)}catch{}},b=()=>{o(String(t.value)),c("wrong_number"),d(""),r(!1)},v=Math.round((t.ai_confidence_score??0)*100),g=v>=80?"text-green-400":v>=50?"text-yellow-400":"text-red-400",S=t.reconciliation_required===!0,E=a||l===""||S&&f.trim()==="";return e.jsxs("div",{className:`rounded-lg border p-4 transition-colors ${u?"border-green-700/40 bg-green-900/10":"border-theme-divider bg-theme-surface-light"}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-theme-text text-sm font-semibold",children:Di(t.metric_type)}),e.jsx("span",{className:"bg-theme-surface text-theme-text-muted rounded px-1.5 py-0.5 text-xs",children:t.period}),u&&e.jsxs("span",{className:"flex items-center gap-1 rounded bg-green-800/50 px-1.5 py-0.5 text-xs text-green-400",children:[e.jsx(Dt,{className:"h-3 w-3"}),"Corrected"]}),S&&!u&&e.jsx("span",{className:"rounded bg-amber-800/40 px-1.5 py-0.5 text-xs text-amber-300",children:"Reconciliation required"})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-3",children:[e.jsx("span",{className:"text-theme-text text-base font-bold",children:Ri(t.value,t.original_unit)}),!S&&e.jsxs("span",{className:`text-xs ${g}`,children:[v,"% confidence"]})]}),S&&e.jsx("p",{className:"mt-1.5 text-xs text-amber-300",children:"This source row was superseded after the current snapshot was created. Confirm the corrected value and add evidence notes to refresh the snapshot safely."}),t.source_text&&e.jsxs("div",{className:"mt-1.5 flex items-start gap-1.5",children:[e.jsx(ut,{className:"text-theme-text-muted mt-0.5 h-3 w-3 shrink-0"}),e.jsx("p",{className:"text-theme-text-muted line-clamp-2 text-xs",children:t.source_text})]}),t.page_reference&&e.jsxs("p",{className:"text-theme-text-muted mt-0.5 text-xs",children:["Page: ",t.page_reference]})]}),!u&&!n&&e.jsxs("button",{onClick:()=>r(!0),className:"border-theme-divider bg-theme-surface text-theme-text-secondary hover:bg-theme-hover hover:text-theme-text flex shrink-0 items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs transition-colors",children:[e.jsx(Mt,{className:"h-3 w-3"}),S?"Reconcile":"Edit"]})]}),n&&e.jsxs("div",{className:"border-theme-divider mt-4 space-y-3 border-t pt-4",children:[e.jsxs("div",{children:[e.jsxs("label",{htmlFor:D,className:"text-theme-text-muted mb-1 block text-xs font-medium",children:["Corrected Value (",t.original_unit,")"]}
5),e.jsx("input",{id:D,type:"number",value:l,onChange:j=>o(j.target.value),className:"border-theme-divider bg-theme-surface text-theme-text placeholder-theme-text-muted w-full rounded-md border px-3 py-2 text-sm focus:border-[var(--theme-accent)] focus:ring-1 focus:ring-[var(--theme-accent)] focus:outline-none",placeholder:"Enter corrected value",step:"any"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:w,className:"text-theme-text-muted mb-1 block text-xs font-medium",children:"Correction Reason"}),e.jsx("select",{id:w,value:m,onChange:j=>c(j.target.value),className:"border-theme-divider bg-theme-surface text-theme-text w-full rounded-md border px-3 py-2 text-sm focus:border-[var(--theme-accent)] focus:ring-1 focus:ring-[var(--theme-accent)] focus:outline-none",children:Object.keys(Ds).map(j=>e.jsx("option",{value:j,children:Ds[j]},j))})]}),e.jsxs("div",{children:[e.jsxs("label",{htmlFor:p,className:"text-theme-text-muted mb-1 block text-xs font-medium",children:["Notes"," ",e.jsxs("span",{className:"text-theme-text-muted font-normal",children:["(",S?"required for reconciliation":"optional",")"]})]}),e.jsx("textarea",{id:p,value:f,onChange:j=>d(j.target.value),rows:2,className:"border-theme-divider bg-theme-surface text-theme-text placeholder-theme-text-muted w-full resize-none rounded-md border px-3 py-2 text-sm focus:border-[var(--theme-accent)] focus:ring-1 focus:ring-[var(--theme-accent)] focus:outline-none",placeholder:S?"Describe the source evidence for this corrected value...":"Additional context..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:k,disabled:E,className:"bg-theme-accent flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium text-white transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50",children:[e.jsx(Dt,{className:"h-3 w-3"}),a?"Saving...":"Save"]}),e.jsxs("button",{onClick:b,disabled:a,className:"border-theme-divider text-theme-text-secondary hover:bg-theme-surface hover:text-theme-text flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs transition-colors disabled:opacity-50",children:[e.jsx(ge,{className:"h-3 w-3"}),"Cancel"]})]})]})]})};function Ei(t){return{id:t.metric_id,metric_type:t.metric_type,period:t.period,value:t.system_value,original_unit:t.unit,ai_confidence_score:0,page_reference:t.page_reference,source_document_id:t.document_id,reconciliation_snapshot_id:t.snapshot_id,reconciliation_required:!0,reconciliation_reason:t.reason}}function Ct(t){return t instanceof Ue?zt(t)||t.message:t instanceof Error?t.message:"Unknown error"}const Fi=({dealId:t,isOpen:s,onClose:a,reconciliationSnapshotId:n})=>{const[r,l]=i.useState({dealId:null,scope:null,rows:[]}),[o,m]=i.useState({dealId:null,scope:null,isLoading:!1,error:null}),[c,f]=i.useState(null),d=i.useRef(0),u=i.useRef(0),x=i.useRef({dealId:t,isOpen:s,reconciliationSnapshotId:n,scope:0});(x.current.dealId!==t||x.current.isOpen!==s||x.current.reconciliationSnapshotId!==n)&&(x.current={dealId:t,isOpen:s,reconciliationSnapshotId:n,scope:x.current.scope+1});const{submitCorrection:_,corrections:D,isSubmitting:w,clearError:p}=Ci(t,x.current.scope),k=r.dealId===t&&r.scope===x.current.scope?r.rows:[],b=o.dealId===t&&o.scope===x.current.scope,v=b?o.isLoading:!1,g=b?o.error:null,S=c?.dealId===t&&c.scope===x.current.scope?c.message:null,E=[S,g].filter(Boolean).join(" "),j=i.useCallback(async()=>{const F=++d.current,R=x.current.scope;m({dealId:t,scope:R,isLoading:!0,error:null});const[q,Q]=await Promise.allSettled([it.getMetricsForCorrection(t),n?it.getReconciliationTargets(t,n):it.getReconciliationTargets(t)]),C=x.current;if(F!==d.current||C.dealId!==t||!C.isOpen||C.scope!==R)return;const H=q.status==="fulfilled"?q.value:null,P=Q.status==="fulfilled"?Q.value:null;if(H||P){const $=P?.map(Ei)??[],G=new Set($.map(N=>N.id));l({dealId:t,scope:R,rows:[...$,...(H??[]).filter(N=>!G.has(N.id))]})}else l($=>({dealId:t,scope:R,rows:$.dealId===t&&$.scope===R?$.rows.filter(G=>!G.reconciliation_required):[]}));const A=[];q.status==="rejected"&&A.push(`Failed to load canonical correction metrics: ${Ct(q.reason)}`),Q.status==="rejected"&&(A.push(`Failed to load reconciliation targets: ${Ct(Q.reason)}`),l($=>({dealId:t,scope:R,rows:$.dealId===t&&$.scope===R?$.rows.filter(G=>!G.reconciliation_required):[]}))),m({dealId:t,scope:R,isLoading:!1,error:A.length>0?A.join(" "):null})},[t,n]);if(i.useEffect(()=>{if(!s){p(),f(null),u.current+=1,d.current+=1;return}const F=++u.current;return l({dealId:t,scope:x.current.scope,rows:[]}),p(),f(null),j(),()=>{u.current===F&&(u.current+=1),d.current+=1}},[p,t,s,j]),!s)return null;const O=async F=>{const R=u.current,q=x.current.scope,Q=()=>{const C=x.current;return C.dealId===t&&C.isOpen&&C.scope===q&&R===u.current};f(null);try{await _(F),F.reconciliation_snapshot_id&&Q()&&await j()}catch(C){const H=Q();throw H&&(f({dealId:t,scope:q,message:Ct(C)}),p()),C instanceof Ue&&C.status===409&&H&&await j(),C}};return e.jsxs("div",{className:"border-theme-divider bg-theme-surface fixed inset-y-0 right-0 z-50 w-full max-w-md border-l shadow-xl",children:[e.jsxs("div",{className:"border-theme-divider flex items-center justify-between border-b px-5 py-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-theme-text text-base font-semibold",children:"Correct Financial Metrics"}),D.length>0&&e.jsxs("p",{className:"text-theme-text-muted mt-0.5 text-xs",children:[D.length," correction",D.length===1?"":"s"," submitted this session"]})]}),e.jsx("button",{onClick:a,className:"text-theme-text-muted hover:bg-theme-surface-light hover:text-theme-text rounded-md p-1.5 transition-colors","aria-label":"Close drawer",children:e.jsx(ge,{className:"h-4 w-4"})})]}),E&&e.jsxs("div",{className:"mx-4 mt-4 flex items-start gap-2 rounded-lg border border-red-700/40 bg-red-900/20 px-4 py-3",children:[e.jsx(qe,{className:"mt-0.5 h-4 w-4 shrink-0 text-red-400"}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx("p",{className:"text-sm text-red-300",children:E})}),g?e.jsx("button",{onClick:()=>{j()},className:"shrink-0 text-xs font-medium text-red-300 hover:text-red-200",children:"Retry"}):S?e.jsx("button",{onClick:()=>{p(),f(null)},className:"shrink-0 text-red-400 hover:text-red-300",children:e.jsx(ge,{className:"h-3.5 w-3.5"})}):null]}),e.jsxs("div",{className:"h-[calc(100%-5rem)] overflow-y-auto",children:[v&&e.jsx("div",{className:"flex h-48 items-center justify-center",children:e.jsx("p",{className:"text-theme-text-muted text-sm",children:"Loading metrics..."})}),!v&&!g&&k.length===0&&e.jsxs("div",{className:"flex h-48 flex-col items-center justify-center gap-2 px-6 text-center",children:[e.jsx("p",{className:"text-theme-text-secondary text-sm",children:"No extracted metrics available"}),e.jsx("p",{className:"text-theme-text-muted text-xs",children:"Run financial data extraction first to generate metrics that can be corrected."})]}),!v&&k.length>0&&e.jsx("div",{className:"space-y-3 p-4",children:k.map(F=>e.jsx(Ai,{metric:F,onSubmit:O,isSubmitting:w},`${F.id}:${F.reconciliation_snapshot_id??"canonical"}`))})]}),!v&&k.length>0&&e.jsx("div",{className:"border-theme-divider border-t px-5 py-3",children:e.jsx("p",{className:"text-theme-text-muted text-xs",children:"Corrections are recorded to improve the AI extraction model over time. Eac
5h correction feeds into the institutional learning flywheel."})})]})},Ti=[{statement:"income_statement",keys:["total_revenue","revenue"],label:"Revenue",category:"revenue"},{statement:"income_statement",keys:["gross_profit"],label:"Gross Profit",category:"profitability"},{statement:"income_statement",keys:["operating_income"],label:"Operating Income",category:"profitability"},{statement:"income_statement",keys:["ebitda"],label:"EBITDA",category:"profitability"},{statement:"income_statement",keys:["net_income"],label:"Net Income",category:"profitability"},{statement:"balance_sheet",keys:["total_assets"],label:"Total Assets",category:"leverage"},{statement:"balance_sheet",keys:["total_liabilities"],label:"Total Liabilities",category:"leverage"},{statement:"balance_sheet",keys:["total_shareholders_equity","total_equity","shareholders_equity"],label:"Shareholders' Equity",category:"leverage"},{statement:"balance_sheet",keys:["cash_and_cash_equivalents","cash_and_equivalents"],label:"Cash & Equivalents",category:"liquidity"},{statement:"balance_sheet",keys:["total_current_assets","current_assets"],label:"Current Assets",category:"liquidity"},{statement:"balance_sheet",keys:["total_current_liabilities","current_liabilities"],label:"Current Liabilities",category:"liquidity"},{statement:"balance_sheet",keys:["total_debt"],sumOf:[["short_term_debt","current_portion_of_debt"],["long_term_debt"]],label:"Total Debt",category:"leverage"},{statement:"cash_flow_statement",keys:["net_cash_from_operating_activities","operating_cash_flow"],label:"Operating Cash Flow",category:"liquidity"},{statement:"cash_flow_statement",keys:["free_cash_flow"],label:"Free Cash Flow",category:"liquidity"}],As=t=>{const s=t.match(/(\d{4})/);if(!s)return NaN;const a=t.match(/Q([1-4])/i);return parseInt(s[1],10)*10+(a?parseInt(a[1],10):0)},It=(t,s)=>{const a=As(t),n=As(s);return!isNaN(a)&&!isNaN(n)?n-a:s.localeCompare(t,void 0,{numeric:!0})},Ks={thousands:1e3,millions:1e6,billions:1e9},Pi=(t,s)=>{const a=Array.isArray(t.periods)?[...t.periods].sort(It):[],n=typeof t.financial_unit=="string"&&Ks[t.financial_unit]||1;for(const r of s){const l=t[r];if(typeof l=="number")return l*n;if(l&&typeof l=="object"&&!Array.isArray(l)){const m=l;for(const f of a)if(typeof m[f]=="number")return m[f];const c=Object.entries(m).filter(f=>typeof f[1]=="number").sort((f,d)=>It(f[0],d[0]));if(c.length>0)return c[0][1]}const o=t[`${r}_current`];if(typeof o=="number")return o*n}return null},Ii=(t,s)=>{const a=Array.isArray(t.periods)?[...t.periods].sort(It):[],n=(o,m)=>{for(const c of o){const f=t[c];if(f&&typeof f=="object"&&!Array.isArray(f)){const d=f[m];if(typeof d=="number")return d}}return null};for(const o of a){const m=s.map(c=>n(c,o));if(m.some(c=>c!==null))return m.reduce((c,f)=>c+(f??0),0)}const r=typeof t.financial_unit=="string"&&Ks[t.financial_unit]||1,l=s.map(o=>{for(const m of o){const c=t[m];if(typeof c=="number")return c*r;const f=t[`${m}_current`];if(typeof f=="number")return f*r}return null});return l.some(o=>o!==null)?l.reduce((o,m)=>o+(m??0),0):null},Mi=({dealId:t,companyName:s="Company",reconciliationSnapshotId:a,onExtractionComplete:n,extractedData:r})=>{const[l,o]=i.useState(!1),[m,c]=i.useState(0),[f,d]=i.useState(""),[u,x]=i.useState(null),[_,D]=i.useState(!1),[w,p]=i.useState(r??null),[k,b]=i.useState([]),[v,g]=i.useState(null),S=Lt(),{usage:E,isLoading:j,creditsRemaining:O}=Bn(),{canPerform:F,operationCost:R}=zn("financial_extraction"),q=!!E&&!j&&!F,Q=q||(u?.toLowerCase().includes("credit")??!1),C=i.useRef(null),H=i.useRef(0),P=i.useCallback(h=>v?h.id===v:h.deal_id!==t?!1:h.task_type==="financial_data"||h.task_type==="financial_extraction"?!0:l&&(h.task_type==="table_extraction"||h.task_type==="comprehensive_financial_extraction"),[v,t,l]),A=i.useCallback(async h=>{if(!P(h))return;if(C.current===h.id){console.log("[FinancialDataExtractionSection] Task completion already handled:",h.id);return}if(C.current=h.id,h.result&&h.result.success===!1){console.log("[FinancialDataExtractionSection] Task completed with failed result"),g(null),o(!1),c(0),d(""),x(typeof h.result.error=="string"&&h.result.error||typeof h.result.message=="string"&&h.result.message||"Financial data extraction failed");return}console.log("[FinancialDataExtractionSection] Task completed via callback, refreshing financial data..."),g(null);const V=H.current,B=async(z=3)=>{try{await new Promise(re=>setTimeout(re,1e3));const W=await Nt.getComprehensiveFinancialData(t,{review_only:!0});if(H.current!==V)return;
5const J=W?.data?.financial_data;J&&Object.keys(J).length>0?(p(J),te(J),n?.(J),console.log("[FinancialDataExtractionSection] Financial data refreshed successfully")):z>1?setTimeout(()=>B(z-1),3e3):x("Extraction completed but no financial data was found. Please refresh the page.")}catch(W){console.error(`Failed to fetch final result (attempt ${4-z}):`,W),z>1?setTimeout(()=>B(z-1),2e3*(4-z)):x("Extraction completed but failed to fetch results. Please refresh the page.")}};B(),setTimeout(()=>{o(!1),c(0),d("")},3e3)},[P,t,s,n]),$=i.useCallback(h=>{P(h)&&(console.error("[FinancialDataExtractionSection] Task failed via callback:",h.message),o(!1),g(null),x(h.message||"Financial data extraction failed"),c(0),d(""),C.current=h.id)},[P]),{tasks:G}=Hn({dealId:t,onTaskComplete:A,onTaskFailed:$});i.useEffect(()=>{r&&(p(r),te(r))},[r]),i.useEffect(()=>{H.current+=1,p(null),b([]),x(null),g(null),o(!1),c(0),d(""),C.current=null,N()},[t]),i.useEffect(()=>{const h=()=>{document.visibilityState==="visible"&&t&&(console.log("[FinancialDataExtractionSection] Page became visible, refreshing data to prevent stale state"),setTimeout(()=>{N()},1e3))};return document.addEventListener("visibilitychange",h),()=>{document.removeEventListener("visibilitychange",h)}},[t]),i.useEffect(()=>{if(!G||G.length===0)return;const h=G.find(P);h&&(console.log("[FinancialDataExtractionSection] Syncing with task:",h.id,"progress:",h.progress,"status:",h.status),c(h.progress||0),d(h.current_step||h.message||"Processing..."),(h.status==="running"||h.status==="pending")&&o(!0))},[G,P]);const N=async()=>{const h=H.current;try{const V=await Nt.getComprehensiveFinancialData(t,{review_only:!0});if(H.current!==h)return;const B=V?.data?.financial_data;B&&Object.keys(B).length>0?(p(B),te(B),n?.(B)):(p(null),b([]))}catch(V){console.log("No existing financial data found:",V instanceof Error?V.message:String(V)),x(null)}},te=h=>{const V=[];for(const B of Ti){const z=h?.[B.statement],W=z?.data;if(!z||!W)continue;let J=Pi(W,B.keys);if(J===null&&B.sumOf&&(J=Ii(W,B.sumOf)),J===null)continue;const re=typeof W.currency=="string"?W.currency:void 0;V.push({label:B.label,value:I(J,re),category:B.category,confidence:z.confidence_score})}b(V)},I=(h,V)=>{if(typeof h=="string"){if(h.includes("$")||h.includes("%")||h.includes("x"))return h;const B=parseFloat(h.replace(/[^0-9.-]/g,""));return isNaN(B)?h:X(B,V)}return X(h,V)},X=(h,V)=>{if(typeof h=="number"){const B=h<0?"-":"",z=!V||V==="USD"?`${B}$`:`${V} ${B}`,W=Math.abs(h);return W>=1e9?`${z}${(W/1e9).toFixed(1)}B`:W>=1e6?`${z}${(W/1e6).toFixed(1)}M`:W>=1e3?`${z}${(W/1e3).toFixed(0)}K`:`${z}${W.toFixed(0)}`}return typeof h=="object"&&h!==null&&"amount"in h?I(h.amount,V):String(h)},T=h=>{switch(h){case"revenue":return rt;case"profitability":return Et;case"liquidity":return lt;case"leverage":return lt;case"growth":return Et;default:return rt}},Y=h=>{switch(h){case"revenue":return"text-blue-400 bg-blue-500/20";case"profitability":return"text-green-400 bg-green-500/20";case"liquidity":return"text-cyan-400 bg-cyan-500/20";case"leverage":return"text-yellow-400 bg-yellow-500/20";case"growth":return"text-purple-400 bg-purple-500/20";default:return"text-theme-text-secondary bg-theme-surface-light/20"}},ae=async()=>{if(q){const h=R?` (${R} credits required)`:"";x(`Not enough credits to run financial data extraction${h}. Upgrade your plan or buy credits to continue.`);return}o(!0),x(null),c(0),d("Initializing financial data extraction...");try{d("Starting financial data extraction..."),c(5);const h=await Nt.extractComprehensiveFinancial(t,{company_name:s,force_refresh:!0,include_market_data:!1,include_ai_insights:!0,include_risk_analysis:!0,top_k:15});if(!h.success)throw new Error(h.message||"Failed to start financial extraction");if(h.task_id){if(C.current===h.task_id)return;g(h.task_id),C.current=null,d(`${h.message} (Task ID: ${h.task_id.substring(0,8)}...)`),c(10)}else await N(),c(100),d("Financial data extraction complete!"),setTimeout(()=>{o(!1),c(0),d("")},2e3)}catch(h){x(h instanceof Error?h.message:"Failed to extract financial data"),o(!1),c(0),d("")}},ne=w?.income_statement?.extraction_timestamp??w?.balance_sheet?.extraction_timestamp??w?.cash_flow_statement?.extraction_timestamp;return e.jsxs("div",{className:"bg-theme-surface border-theme-divider rounded-lg border p-6",children:[e.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx(rt,{className:"mr-2 h-5 w-5 text-blue-400"}),e.jsx("h2",{className:"text-theme-text text-lg font-semibold",children:"Financial Data Extraction"})]}),e.jsxs("button",{onClick:()=>D(!0),className:"border-theme-divider text-theme-text-secondary hover:border-theme-divider hover:text-theme-text flex items-center gap-1.5 rounded-md border bg-zinc-800/50 px-3 py-1.5 text-xs font-medium transition-colors hover:bg-zinc-700/60",title:"Correct extracted financial metrics",children:[e.jsx(Mt,{className:"h-3.5 w-3.5"}),"Correct"]})]}),l&&e.jsxs("div",{className:"bg-app-bg mb-4 rounded-lg p-4",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[e.jsx("span",{className:"text-theme-text text-sm",children:f}),e.jsxs("span",{className:"text-theme-text-secondary text-sm",children:[m,"%"]})]}),e.jsx(Er,{value:m,className:"h-2"})]}),u&&e.jsx("div",{className:"mb-4 rounded-lg border border-red-500/20 bg-red-500/10 p-4",children:e.jsxs("div",{className:"flex items-start",children:[e.jsx(qe,{className:"mt-0.5 mr-2 h-5 w-5 flex-shrink-0 text-red-400"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-red-400",children:"Extraction Failed"}),e.jsx("p",{className:"mt-1 text-sm text-red-300",children:u}),Q&&e.jsx("button",{onClick:()=>S("/settings/billing"),className:"mt-2 text-sm font-medium text-red-300 underline underline-offset-4 hover:text-red-200",children:"Upgrade plan or buy credits"})]})]})}),q&&!u&&e.jsx("div",{className:"mb-4 rounded-lg border border-amber-500/20 bg-amber-500/10 p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-amber-400",children:"Credits required for financial extraction"}),e.jsxs("p",{className:"mt-1 text-sm text-amber-300",children:[O," credits remaining. Financial extraction requires"," ",R||"credits",". Upgrade your plan or buy credits to continue."]})]}),e.jsx("button",{onClick:()=>S("/settings/billing"),className:"shrink-0 rounded-md border border-amber-400/50 px-3 py-1 text-sm font-medium text-amber-300 hover:bg-amber-500/10",children:"Upgrade"})]})}),k.length>0?e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"border-theme-divider border-t pt-4",children:[e.jsx("h4",{className:"text-md text-theme-text mb-3 font-semibold",children:"Extracted Financial Metrics"}),e.jsx("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2 lg:grid-cols-3",children:k.map((h,V)=>{const B=T(h.category);return e.jsxs("div",{className:"bg-app-bg border-theme-divider rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[e.jsx(B,{className:"text-theme-accent h-4 w-4"}),e.jsx("p",{className:"text-theme-text-secondary text-xs",children:h.label})]}),e.jsx("p",{className:"text-theme-text text-lg font-bold",children:Gn(h.value)})]}),e.jsx("span",{className:`rounded px-2 py-0.5 text-xs ${Y(h.category)}`,children:h.category})]}),h.confidence&&e.jsx("div",{className:"mt-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-theme-text-muted text-xs",children:"Confidence:"}),e.jsx("div",{className:"bg-theme-surface-light h-1.5 max-w-[80px] flex-1 rounded-full",children:e.jsx("div",{className:"bg-theme-accent h-1.5 rounded-full",style:{width:`${h.confidence*100}%`}})}),e.jsxs("span",{className:"text-theme-text-muted text-xs",children:[Math.round(h.confidence*100),"%"]})]})})]},V)})}),e.jsxs("div",{className:"text-theme-text-secondary border-theme-divider mt-4 flex items-center justify-between border-t pt-4 text-sm",children:[e.jsxs("span",{children:["Total Metrics Extracted: ",k.length]}),ne&&e.jsxs("span",{className:"text-xs",children:["Extracted: ",new Date(ne).toLocaleStr
5ing()]})]})]})}):!l&&e.jsxs("div",{className:"py-12 text-center",children:[e.jsx(Ts,{className:"text-theme-text-muted mx-auto mb-4 h-12 w-12"}),e.jsx("p",{className:"text-theme-text-secondary mb-4",children:"No financial data extracted yet"}),e.jsx("button",{onClick:ae,disabled:q||l,className:"rounded bg-[var(--theme-button-primary-bg)] px-4 py-2 text-[var(--theme-button-primary-text)] hover:bg-[var(--theme-button-primary-hover)] disabled:cursor-not-allowed disabled:opacity-50",title:q?"Not enough credits":"Start financial data extraction",children:l?"Extracting...":"Start Financial Data Extraction"})]}),e.jsx(Fi,{dealId:t,isOpen:_,onClose:()=>D(!1),reconciliationSnapshotId:a})]})},$i=({dealId:t,companyName:s,isOpen:a,onClose:n,reconciliationSnapshotId:r})=>a?wn.createPortal(e.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Review extracted financials",className:"fixed inset-0 z-50 flex items-stretch justify-end bg-black/50",onClick:n,children:e.jsxs("div",{className:"bg-theme-surface h-full w-full overflow-y-auto p-6 md:w-[90vw]",onClick:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"border-theme-divider mb-4 flex items-center justify-between border-b pb-2",children:[e.jsx("h2",{className:"text-theme-text text-xl font-semibold",children:"Review extracted financials"}),e.jsx("button",{type:"button",onClick:n,className:"text-theme-text-secondary hover:bg-theme-surface-light hover:text-theme-text rounded px-3 py-1 text-sm",children:"Close"})]}),e.jsx(Mi,{dealId:t,companyName:s,reconciliationSnapshotId:r})]})}),document.body):null,Li={strong_buy:"Strong Buy",buy:"Buy",hold:"Hold",pass:"Pass"};function qi({deal:t,isFreshDeal:s,isDataReady:a,isGenerating:n,isResearchRunning:r=!1,tilesPopulated:l,hasAnalysisContent:o,hasUploadedDocuments:m,dataQualityConcern:c,dataQualityState:f,executiveSummary:d,isReanalyzing:u,isStaleAfterFailedRerun:x,lastCanonicalRunIncomplete:_}){const D=i.useMemo(()=>Bi({isFreshDeal:s,isDataReady:a,isGenerating:n,isResearchRunning:r,tilesPopulated:l,hasAnalysisContent:o,hasUploadedDocuments:m,dataQualityConcern:c,dataQualityState:f,executiveSummary:d,isReanalyzing:!!u,isStaleAfterFailedRerun:!!x,lastCanonicalRunIncomplete:!!_}),[s,a,n,r,l,o,m,c,f,d,u,x,_]),w=Hi(t.value),p=(t.status??"active").toString(),k=Ms(t.deal_mode);return e.jsxs("section",{className:"border-theme-divider bg-theme-surface/95 sticky top-0 z-30 -mx-2 mb-2 rounded-xl border px-6 py-5 shadow-[var(--shadow-card)] backdrop-blur-sm","aria-label":"Deal at a glance","data-overview-section":"summary",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-4 gap-y-2",children:[e.jsx("h1",{className:"text-theme-text text-3xl font-semibold tracking-tight",style:{fontFamily:"var(--font-family-display)"},children:t.name??t.target??"Untitled deal"}),e.jsx("span",{className:"text-theme-text-muted text-xs tracking-wider uppercase",children:p}),t.industry&&e.jsx("span",{className:"border-theme-divider text-theme-text-secondary rounded-full border px-2 py-0.5 text-[11px] tracking-wider uppercase",children:t.industry}),k&&e.jsx("span",{className:"border-theme-divider text-theme-text-secondary rounded-full border px-2 py-0.5 text-[11px] tracking-wider uppercase",children:k}),w&&e.jsx("span",{className:"text-theme-text-secondary ml-auto text-base",style:{fontFamily:"var(--font-family-mono)"},children:w})]}
5),e.jsx("div",{className:`mt-4 flex items-center gap-4 rounded-lg border-l-4 px-4 py-3 ${zi(D.severity)}`,children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-theme-text-secondary text-[10px] font-bold tracking-widest uppercase",children:"Verdict"}),e.jsx("div",{className:"text-theme-text mt-1 text-base font-semibold",style:{fontFamily:"var(--font-family-display)"},children:D.label}),e.jsx("div",{className:"text-theme-text-secondary mt-1 text-xs",children:D.rationale}),r&&D.label!=="Research in progress"&&e.jsx("p",{role:"status",className:"text-theme-text-secondary mt-2 text-xs",children:"Research in progress — collecting public context. Full Analysis runs separately."})]})})]})}function Ui(t){switch(t){case"strong_buy":case"buy":return"go";case"hold":return"watch";case"pass":return"block";default:return"neutral"}}function Oi(t,s,a){const n=t.recommendation?Li[t.recommendation]??t.recommendation:null,r=typeof t.dataCompletenessPct=="number"?` (${t.dataCompletenessPct}% data completeness)`:"",l=n?`AI recommendation: ${n}${r}.`:`Saved summary available${r}.`;return s?`${l} A new analysis is running — showing the previously saved summary.`:a?`${l} Showing the previously saved summary — the latest re-analysis did not complete.`:l}function Bi(t){const{isFreshDeal:s,isDataReady:a,isGenerating:n,isResearchRunning:r,tilesPopulated:l,hasAnalysisContent:o,hasUploadedDocuments:m,dataQualityConcern:c,dataQualityState:f,executiveSummary:d,isReanalyzing:u,isStaleAfterFailedRerun:x,lastCanonicalRunIncomplete:_}=t;return o&&c?{label:"Verify data quality",rationale:c,severity:"watch"}:o&&f==="no_data"?{label:"Financial data unavailable",rationale:"The quality check completed without supported financial metrics. Verify extraction inputs before IC review.",severity:"watch"}:o&&f==="error"?{label:"Quality check unavailable",rationale:"The revenue-quality check could not be completed. Retry or verify the financials manually before IC review.",severity:"watch"}:o&&f==="pending"?{label:"Verifying data quality",rationale:"The revenue-quality check is still loading or unavailable. IC readiness will update after it resolves.",severity:"neutral"}:d?.headline?{label:d.headline,rationale:Oi(d,u,x),severity:Ui(d.recommendation)}:r?{label:"Research in progress",rationale:"Collecting public context. Full Analysis is a separate step.",severity:"neutral"}:n?{label:"Analysis in progress",rationale:"Engines are running across the ingested documents. Verdict will refresh on completion.",severity:"neutral"}:l&&_?{label:"Analysis incomplete — review coverage before IC",rationale:"The last Full Analysis run did not complete fully, so some sections below may be missing or incomplete. Re-run the analysis or review the completed sections before IC.",severity:"watch"}:l?{label:"Ready for IC review",rationale:"Analysis complete. Drill into the spine sections below.",severity:"go"}:a&&m?{label:"Ready to run full analysis",rationale:"Documents are ingested. Kick off the risk extractor + valuation engines to populate tiles.",severity:"watch"}:s?{label:"Awaiting documents",rationale:"Upload the CIM, financial statements, or other DD materials to unblock ingestion.",severity:"block"}:{label:"Deal in flight",rationale:"No specific recommendation at this state.",severity:"neutral"}}function zi(t){switch(t){case"go":return"border-emerald-500 bg-emerald-50 dark:bg-emerald-950/40";case"watch":return"border-amber-500 bg-amber-50 dark:bg-amber-950/40";case"block":return"border-red-500 bg-red-50 dark:bg-red-950/40";default:return"border-theme-divider bg-theme-surface-light dark:bg-slate-900/40"}}function Hi(t){if(typeof t=="number"&&Number.isFinite(t))return t===0?null:t>=1e3?`$${(t/1e3).toFixed(1)}B`:`$${t.toFixed(0)}M`;if(typeof t=="string"){const s=t.trim();return!s||s.toLowerCase()==="tbd"?null:s}return null}const Gi=new Set(["full_pipeline","deal_summary"]);function Vi(t){return t.isGenerating||t.tilesPopulated?"none":t.isFreshDeal?"upload_documents":t.isDataReady&&t.hasUploadedDocuments?"run_full_analysis":t.isDataReady?"run_quick_summary":"none"}function Qs(t){return t.isFreshDeal||t.isDataReady||t.tileCount===0||t.bannerShowsRegenerateCta?"hidden":t.isFullAnalysisRunning?"busy":t.isGenerating?"blocked":"enabled"}function Ws(t){return t.serverHasExternalEvidence||t.comparableCount>0||t.precedentCount>0||t.aiHistoryCount>0}function Ys(t){return t.isGenerating||t.isFullAnalysisRunning||t.hasActiveFullPipelineRunRow}function Zs(t,s){return Ce(t)&&Ce(s)}function Xs(t,s,a){return a==="third_party_merger"?Ce(s)?"":s.trim():Ht(t,s)}function Js(t,s,a){return a==="third_party_merger"?Ce(t)||(t??"").trim()===(s??"").trim():Ce(t)||Ce(s)||(t??"").trim()===(s??"").trim()}async function ea(t,s,a,n){const r=Js(a.name,a.target,a.perspective)?{target:s,name:s}:{target:s},l=await n.updateDeal(t,r);return await Promise.all([n.invalidateQueries({queryKey:["deal",t]}),n.invalidateQueries({queryKey:["deal",t,"summary-metadata"]})]),n.showToast({title:"Company name updated",variant:"success"}),await n.onDealUpdated?.(l,{persist:!1}),l}function ta(t){return t(pr.OVERVIEW)}function sa(t){return{hasUploadedDocuments:t.hasUploadedDocuments,hasExternalEvidence:t.hasExternalEvidence,hasPendingDocumentUploads:t.hasPendingSessionUploads,isDataCollectionActive:t.isContextIndexing,isDocumentProcessing:t.is
5FileIndexingActive,processingDocumentCount:t.processingDocumentCount}}const aa=3e4;function na(t){const[s,a]=i.useState(!1);return i.useEffect(()=>{t&&a(!1)},[t,a]),i.useEffect(()=>{if(!s)return;const n=window.setTimeout(()=>a(!1),aa);return()=>window.clearTimeout(n)},[s,a]),[s,a]}function Ki(t){return t.isGenerating?"generating":t.tilesPopulated?"tiles_populated":t.isDataReady?"data_ready":"fresh_deal"}function Rt(t,s,a,n){const r=t.filter(c=>c.status==="completed").length,l=t.filter(c=>c.status==="pending").length,o=t.filter(c=>c.status==="failed").length,m=t.filter(c=>c.status==="generating").length;return{viewType:"deal_summary",viewTitle:"Deal Summary",metrics:[{label:"Tiles",value:t.length},{label:"Completed",value:r}],highlights:t.length>0?t.map(c=>c.title):["No tiles generated yet"],additionalData:{tileTypes:t.map(c=>c.tile_type),isGenerating:s,focusedTile:a??null,analysisState:Ki(n),tileStats:{total:t.length,completed:r,pending:l,failed:o,generating:m},evidenceSources:{hasDocuments:n.hasUploadedDocuments,hasComparables:n.comparableCount>0,hasPrecedents:n.precedentCount>0,documentCount:n.uploadedDocumentCount,comparableCount:n.comparableCount,precedentCount:n.precedentCount},ddProgress:n.ddProgress,recommendedAction:Vi(n)},updatedAt:new Date().toISOString()}}function Qi({tile:t,children:s,...a}){const{attributes:n,listeners:r,setNodeRef:l,transform:o,transition:m,isDragging:c}=In({id:t.id}),f={transform:Mn.Transform.toString(o),transition:m,opacity:c?.6:1,zIndex:c?10:void 0};return e.jsx("div",{ref:l,style:f,children:e.jsx(Tt,{tile:t,dragHandleProps:{...n,...r},...a,children:s})})}function ra(t,s){return t.filter(a=>!s.promotedTileIds.has(a.id))}function ia(t){return t.noTilesYet&&!t.isGenerating&&!t.hasActiveFullPipelineRun&&!t.hasError}function la(){return e.jsx("div",{className:"border-theme-divider bg-theme-surface flex flex-col items-center gap-2 rounded-xl border border-dashed px-6 py-10 text-center","data-testid":"zone3-empty-state",children:e.jsx("p",{className:"text-theme-text text-sm font-medium",children:"Run Full Analysis to populate this page — or ask the assistant anything now."})})}function oa(t){for(const s of t){const a=s.basis?.augmentation,n=a?.snapshot_id;if(a?.reason==="supersession_reconciliation_required"&&a.next_action==="reconcile_financial_snapshot"&&typeof n=="string"&&n.trim().length>0)return n}}function ca(t,s,a){return a||t.content!=null||!s||s.status!=="failed"&&s.status!=="partial"||t.status!=="failed"&&t.status!=="pending"&&t.status!=="generating"||!s.started_at||!t.updated_at?!1:Ft(t.updated_at)>=Ft(s.started_at)}function da(t){return t.isFullAnalysisRunning?"busy":t.isGenerating||t.canRunFullAnalysis===!1?"blocked":"enabled"}function ua({count:t,children:s,defaultOpen:a=!1,forceOpen:n=!1}){const[r,l]=i.useState(a);i.useEffect(()=>{a&&l(!0)},[a]);const o=n||r;return e.jsxs("div",{"data-testid":"zone3-collapsed-section",children:[e.jsxs("button",{type:"button",onClick:()=>{n||l(m=>!m)},"aria-expanded":o,"aria-disabled":n,"data-testid":"zone3-collapsed-toggle",className:"text-theme-text-muted flex w-full items-center justify-between gap-2 text-sm font-semibold",children:[e.jsx("span",{children:`All tiles · ${t}`}),e.jsx(Cn,{className:K("h-4 w-4 transition-transform",o&&"rotate-180")})]}),o&&e.jsx("div",{className:"mt-3 flex flex-col gap-3",children:s})]})}function ma({dealId:t,deal:s,tiles:a,visibleTiles:n,forceOpenAllTiles:r=!1,executiveSummary:l,executiveSummaryTileId:o,executiveSummaryOverride:m,isStale:c,latestTerminalRun:f,hasContent:d,isGenerating:u,canReorder:x,sortableSensors:_,onTileDragEnd:D,onRegenerate:w,onAskAI:p,onShowEvidence:k,onDeleteTile:b,onToggleVisibility:v,isRegenerating:g,regenerateDisabled:S,ddNotStarted:E,onOpenFinancialReview:j,onAddTile:O,publicationReadiness:F}){const R=i.useMemo(()=>n.find(N=>N.tile_type==="executive_summary")??null,[n]),q=R?.id===o,Q=i.useMemo(()=>q?l:Os(R?.content??null),[l,R,q]),C=i.useMemo(()=>n.find(N=>N.tile_type==="live_key_risks")??null,[n]),H=R!=null&&Q!=null&&pe("executive_summary",F,R.publication_id,R.content,R.title),P=i.useMemo(()=>{const N=new Set;return H&&R&&N.add(R.id),C&&N.add(C.id),N},[H,R,C]),A=i.useMemo(()=>ra(n,{promotedTileIds:P}),[n,P]),$=N=>ca(N,f,c)?e.jsxs("div",{className:"text-theme-text-muted flex flex-col items-center gap-1 py-6 text-center text-sm","data-testid":`zone3-content-lost-${N.id}`,children:[e.jsx("span",{className:"text-theme-text font-medium",children:"Content lost in a failed regeneration."}),e.jsx("span",{children:"Re-run to restore."})]}):e.jsx(Rr,{tile:N,deal:s,onOpenFinancialReview:j,publicationReadiness:F}),G=A.map(N=>x?e.jsx(Qi,{tile:N,onRegenerate:w,onAskAI:p,onShowEvidence:k,contentContextDisabled:!pe(N.tile_type,F,N.publication_id,N.content,N.title),onDelete:b,onHide:v,isRegenerating:g,regenerateDisabled:S,ddNotStarted:E,dealId:t,children:$(N)},N.id):e.jsx(Tt,{tile:N,onRegenerate:w,onAskAI:p,onShowEvidence:k,contentContextDisabled:!pe(N.tile_type,F,N.publication_id,N.content,N.title),onDelete:b,onHide:v,isRegenerating:g,regenerateDisabled:S,ddNotStarted:E,dealId:t,children:$(N)},N.id));return e.jsxs("div",{className:"flex flex-col gap-4","data-testid":"zone3-findings",children:[c&&e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-theme-accent bg-blue-50/60 px-3 py-2 text-xs text-blue-700 dark:bg-blue-500/10 dark:text-blue-300","data-testid":"zone3-stale-banner",children:[e.jsx(le,{size:12,className:"animate-spin"}),"A new Full Analysis run is in progress — findings below may be out of date."]}),H&&e.jsx(hr,{dealId:t,tileId:R.id,variant:"page",contentOverride:q?m:void 0}),C&&e.jsx("div",{"data-testid":"zone3-key-risks",children:e.jsx(Tt,{tile:C,onRegenerate:w,onAskAI:p,onShowEvidence:k,contentContextDisabled:!pe(C.tile_type,F,C.publication_id,C.content,C.title),onDelete:b,onHide:v,isRegenerating:g,regenerateDisabled:S,ddNotStarted:E,dealId:t,children:$(C)})}),e.jsxs(ua,{count:A.length,forceOpen:r,children:[d&&e.jsx("div",{className:"flex justify-end",children:e.jsx(Cr,{tiles:a,onAddTile:O,onToggleVisibility:v,onDeleteTile:b,disabled:u})}),A.length===0?e.jsx("p",{className:"text-theme-text-muted text-sm",children:"No other tiles."}):x?e.jsx(Rn,{sensors:_,collisionDetection:Dn,onDragEnd:D,children:e.jsx(An,{items:A.map(N=>N.id),strategy:En,children:e.jsx("div",{className:"flex flex-col gap-3",children:G})})}):e.jsx("div",{className:"flex flex-col gap-3",children:G})]})]})}
5function Wi({deal:t,onNavigate:s,inDock:a=!1,onDealUpdated:n}){const r=Vn(),{tiles:l,visibleTiles:o,hasContent:m,isGenerating:c,generationProgress:f,isLoading:d,error:u,mutationError:x,generateAll:_,isGenerateLoading:D,regenerateTile:w,isRegenerateLoading:p,addTile:k,toggleVisibility:b,updateLayouts:v,deleteTile:g,invalidate:S}=Kn(t.id),{data:E}=Qn(t.id),{generationInputs:j,error:O}=Fr(t.id),{episode:F,isLoading:R,isGenerating:q,progress:Q,generate:C}=Pr({type:"deal",dealId:t.id}),{status:H}=Wn(t.id,{refetchInterval:3e4}),{processingStatus:P,isProcessing:A,refreshStatus:$}=Tr({dealId:t.id}),{hasFeature:G}=Yn(),{reportViewData:N,clearViewData:te}=Zn(),{showToast:I}=Bt(),X=Lt(),T=mt(),{canEdit:Y}=Xn(t.id),[ae,ne]=i.useState(null),[h,V]=i.useState(!1),[B,z]=i.useState(!1),[W,J]=i.useState(!1),[re,ie]=i.useState(null),[ue,De]=i.useState(!1),[xe,ye]=i.useState(0),[ee,Ae]=i.useState(!1),je=i.useMemo(()=>new Set(["Closed","Passed","Exited","Withdrawn"]),[]),[L,oe]=i.useState(!1),Gt=i.useRef(t.status);i.useEffect(()=>{t.status!==Gt.current&&je.has(t.status)&&oe(!0),Gt.current=t.status},[t.status,je]);const Vt=i.useMemo(()=>new Set(["Closed","Exited"]),[]),[xa,xt]=i.useState(!1),Kt=i.useRef(t.status);i.useEffect(()=>{t.status!==Kt.current&&Vt.has(t.status)&&xt(!0),Kt.current=t.status},[t.status,Vt]);const ha=i.useCallback(()=>{T.invalidateQueries({queryKey:[Jn,t.id]})},[t.id,T]),{tasks:Qt,activeTasks:Wt}=Ot({dealId:t.id}),Yt=i.useMemo(()=>Wt.filter(y=>Gi.has(y.task_type)),[Wt]).some(y=>y.task_type==="full_pipeline"),[pa,Zt]=na(Yt),Oe=pa||Yt,{runs:Xt,activeFullPipelineRun:Ee,fullPipelineRuns:Jt,isLoading:ht,error:es,refetch:fa}=er(t.id),ve=i.useMemo(()=>Jt.find(y=>Ls.has(y.status)),[Jt]),ce=i.useMemo(()=>qs(Xt,ve),[Xt,ve]),ga=i.useMemo(()=>oa(ce),[ce]),Fe=Us({isFullAnalysisRunning:Oe,hasActiveFullPipelineRunRow:!!Ee,isLedgerLoading:ht}),ba=i.useMemo(()=>(re?ce.find(y=>y.id===re):null)??ce[0]??null,[ce,re]);i.useEffect(()=>{if(ce.length===0){re!==null&&ie(null);return}if(!re){ie(ce[0].id);return}ce.some(M=>M.id===re)||ie(ce[0].id)},[ce,re]);const{data:ya,refetch:ts}=Re({queryKey:["deal",t.id,"summary-metadata"],queryFn:()=>me.getDeal(t.id),enabled:!!t.id,refetchOnMount:"always",staleTime:0}),U=ya??t,{setupState:va}=tr(t.id),Te=(va??t.setup_state??null)?.steps.context,Be=Te?.ingest_status||U.data_collection_status,pt=Be==="phase1_running"||Be==="phase2_queued"||Be==="phase2_running";i.useEffect(()=>{$()},[$]);const ze=Ht(U.name,U.target),ja=Xs(U.name,U.target,U.perspective),_a=Zs(U.target,U.name),He=Te?.document_count??U.file_count??0,_e=He>0,Ge=U.compsDetails?.peerGroup?.length??0,Ve=U.precedentDetails?.transactions?.length??0,Na=Math.max(U.aiAnalysisHistory?.length??0,U.ai_analysis_history?.length??0),Ke=Ws({serverHasExternalEvidence:Te?.has_external_evidence??!1,comparableCount:Ge,precedentCount:Ve,aiHistoryCount:Na}),Pe=xe>0;i.useEffect(()=>{Pe&&$()},[Pe,$]),i.useEffect(()=>{!Pe||ee||!A||Ae(!0)},[Pe,ee,A]),i.useEffect(()=>{if(xe===0){Ae(!1);return}ee&&!A&&(ye(0),Ae(!1))},[xe,ee,A]),i.useEffect(()=>{if(xe===0||ee||A)return;const y=window.setTimeout(()=>{ye(0)},15e3);return()=>window.clearTimeout(y)},[xe,ee,A]);
5const ft=Te?.processing_document_count,ss=i.useMemo(()=>sr(ar(Qt),ft),[Qt,ft]),{canRunFullAnalysis:he,disabledReason:as}=nr(sa({hasUploadedDocuments:_e,hasExternalEvidence:Ke,hasPendingSessionUploads:Pe,isContextIndexing:Te?.status==="in_progress",isFileIndexingActive:ss,processingDocumentCount:ft})),Qe=i.useCallback(y=>{console.debug("[DealSummary] Refreshing deal summary metadata",{dealId:t.id,reason:y}),ts()},[t.id,ts]),ns=i.useRef(A);i.useEffect(()=>{ns.current&&!A&&Qe("document_processing_finished"),ns.current=A},[A,Qe]),i.useEffect(()=>{const y=()=>Qe("workspace_refresh_event");return window.addEventListener(vs,y),()=>{window.removeEventListener(vs,y)}},[Qe]);const rs=i.useRef(he);i.useEffect(()=>{!rs.current&&he&&(console.info("[DealSummary] Full Analysis unlocked",{dealId:t.id}),I({title:"Full Analysis unlocked",description:"Evidence detected. You can run Full Analysis now.",variant:"success",duration:3e3})),rs.current=he},[he,t.id,I]);const[is,wa]=i.useState(!1),Ne=o.length===0&&!d,Ie=Ne&&!he,Me=Ne&&he,gt=!Ne&&!d,ls=l.length>0,ka=i.useCallback(()=>{if(s)return s(`${t.id}_dataroom`);X(`/deals/${t.id}/dataroom`)},[s,X,t.id]),Sa=i.useCallback(()=>{if(s)return s(`${t.id}_val_comps`);X(`/deals/${t.id}/valuation/comps`)},[s,X,t.id]),Ca=i.useCallback(()=>{if(s)return s(`${t.id}_val_precedent`);X(`/deals/${t.id}/valuation/precedent`)},[s,X,t.id]),bt=i.useMemo(()=>{const y=ae?l.find(M=>M.id===ae)??null:null;return y&&pe(y.tile_type,E,y.publication_id,y.content,y.title)?y:null},[l,ae,E]),os=i.useMemo(()=>bt?_t(bt):null,[bt]),$e=H?.overall_progress??Math.round(Number(t.progress||0)),{data:We,isSuccess:Ra,isError:Da}=Sr(ls?t.id:void 0),Aa=Da?"error":Ra?We?.has_data===!0||We?.qoe_signals?.available===!0?"resolved":"no_data":"pending",Ea=i.useMemo(()=>{const y=We?.qoe_signals;if(!y?.available)return null;const M=y.revenue_quality_risk_level;if(M==="high"||M==="critical"){const Z=y.revenue_quality_score!=null?` (score ${Math.round(y.revenue_quality_score)}/100)`:"";return`The revenue-quality screen flagged ${M} risk${Z}. Verify the extracted financials against the data room before IC review.`}return null},[We]),de=i.useMemo(()=>l.find(y=>y.tile_type==="executive_summary")??null,[l]),Ye=i.useMemo(()=>Os(de?.content??null),[de]),cs=i.useRef(t.id),Ze=i.useRef(null);cs.current!==t.id&&(cs.current=t.id,Ze.current=null),Ye?Ze.current=Ye:de||(Ze.current=null);const{executiveSummary:Xe,retentionReason:Je}=Bs({parsedExecutiveSummary:Ye,retainedExecutiveSummary:Ze.current,executiveSummaryTileExists:de!=null,executiveSummaryTileStatus:de?.status,executiveSummaryContentUpdatedAt:de?.content_updated_at,activeFullPipelineRun:Ee!=null,latestTerminalFullPipeline:ve}),Fa=Je==="reanalyzing",Ta=Je==="failed_rerun",Pa=pe("executive_summary",E,de?.publication_id,de?.content,de?.title)?Xe:null,Ia=Ye==null&&Xe!=null&&Je?{content:Xe,reason:Je}:void 0,Ma=Ee!=null,ds=zs({isLedgerLoading:ht,isLedgerError:!!es,activeFullPipelineRun:Ee,latestTerminalFullPipeline:ve}),we=i.useMemo(()=>({isFreshDeal:Ie,isDataReady:Me,isGenerating:c,hasUploadedDocuments:_e,hasExternalEvidence:Ke,uploadedDocumentCount:He,comparableCount:Ge,precedentCount:Ve,ddProgress:$e,tilesPopulated:gt&&o.length>0}),[Ie,Me,c,_e,Ke,He,Ge,Ve,$e,gt,o.length]);i.useEffect(()=>(N(Rt(l,c,os,we)),()=>te()),[l,c,os,we,N,te]);const $a=i.useCallback(async()=>{V(!0);try{await me.startDataCollection(t.id),await T.invalidateQueries({queryKey:["deal",t.id]}),I({title:"Research started",description:"Gathering company data, web intelligence, and SEC filings...",variant:"success",duration:4e3})}catch(y){y instanceof Error&&"status"in y&&y.status===409?(await T.invalidateQueries({queryKey:["deal",t.id]}),I({title:"Research already running",variant:"info"})):I({title:"Failed to start research",variant:"error"})}finally{V(!1)}},[t.id,T,I]),yt=i.useCallback(y=>{I({title:"Regenerating all tiles...",variant:"success",duration:3e3}),_({custom_context:y}).catch(M=>{console.error("[DealSummary] Generation failed:",M),I({title:"Failed to start regeneration",variant:"error"})})},[_,I]),La=i.useCallback(async(y,M)=>{try{await w({tileId:y,body:M?{custom_prompt:M}:void 0})}catch(Z){console.error("[DealSummary] Regenerate tile failed:",Z),I({title:"Failed to regenerate tile",variant:"error"})}},[w,I]),qa=i.useCallback(async y=>{try{await g(y)}catch(M){console.error("[DealSummary] Delete tile failed:",M),I({title:"Failed to delete tile",variant:"error"})}},[g,I]),Ua=i.useCallback(async y=>{try{await k(y)}catch(M){console.error("[DealSummary] Add tile failed:",M),I({title:"Failed to add tile",variant:"error"})}},[k,I]),Oa=i.useCallback(async y=>{try{await b(y)}catch(M){console.error("[DealSummary] Toggle visibility failed:",M),I({title:"Failed to toggle tile visibility",variant:"error"})}},[b,I]),Ba=kn(ys(Pn,{activationConstraint:{distance:5}}),ys(Tn,{coordinateGetter:Fn})),za=i.useCallback(y=>{const{active:M,over:Z}=y;
5if(!Z||M.id===Z.id)return;const ke=o.map(st=>st.id),et=ke.indexOf(M.id),tt=ke.indexOf(Z.id);if(et===-1||tt===-1)return;const jt=[...o],[Ja]=jt.splice(et,1);jt.splice(tt,0,Ja),v(jt.map((st,xs)=>({tile_id:st.id,layout:st.layout??{x:0,y:xs,w:12,h:3},sort_order:xs})))},[o,v]),Ha=i.useCallback((y,M)=>{const Z=l.find(tt=>tt.id===y);if(!Z){I({title:"Tile not found",variant:"error"});return}if(!pe(Z.tile_type,E,Z.publication_id,Z.content,Z.title)){I({title:"Tile content is withheld",description:"Current publication evidence does not permit using this tile in AI context.",variant:"error"});return}const ke=_t(Z,M),et=M?.trim()?`${M.trim()} Use the "${Z.title}" tile as your primary evidence, reference the on-screen values, and call out one concrete next action.`:`Analyze the "${Z.title}" tile for our IC decision. Explain what the numbers imply, what drives them most, where evidence is weakest, and what we should do next.`;ne(y),N(Rt(l,c,ke,we)),typeof window<"u"&&window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("ai-prompt-trigger",{detail:{prompt:et,source:"deal_summary_tile",tileId:Z.id,tileType:Z.tile_type,tileTitle:Z.title}}))},40)},[l,E,c,we,N,I]),Ga=i.useCallback(y=>{const M=l.find(ke=>ke.id===y);if(!M){I({title:"Tile not found",variant:"error"});return}if(!pe(M.tile_type,E,M.publication_id,M.content,M.title)){I({title:"Tile content is withheld",description:"Current publication evidence does not permit using this tile as evidence.",variant:"error"});return}const Z=_t(M);ne(y),N(Rt(l,c,Z,we)),Ar({source:"tile_provenance",title:M.title,re
5commendation:`Evidence for ${M.title}`})},[l,E,c,we,N,I]),Va=o.length,us=!c&&!is&&o.length>0&&Vs({tiles:o,ddNotStarted:$e===0,deal:U}),Ka=Qs({isFreshDeal:Ie,isDataReady:Me,tileCount:Va,bannerShowsRegenerateCta:us,isFullAnalysisRunning:Oe,isGenerating:c}),vt=da({isFullAnalysisRunning:Oe,isGenerating:c,canRunFullAnalysis:he}),Qa=vt==="busy"?"A full analysis run is already in progress for this deal":vt==="blocked"?as||"Tile generation is in progress — wait for it to finish":void 0,Wa=i.useCallback(()=>{Zt(!0)},[Zt]),Ya=i.useCallback(()=>{if(typeof navigator<"u"&&typeof navigator.share=="function"){navigator.share({title:`${ze} — Deal Summary`,text:"Review this deal summary in Ololand.ai",url:typeof window<"u"?window.location.href:void 0}).catch(()=>{});return}I({title:"Share ready",description:"Copy the current URL to share this deal summary.",variant:"info"})},[ze,I]),Za=i.useCallback(()=>{I({title:"Use Reports for exports",description:"Open Investment Memo or Reports for PDF and presentation exports.",variant:"info"})},[I]),Xa=i.useCallback(async y=>{await ea(t.id,y,{name:U.name,target:U.target,perspective:U.perspective},{updateDeal:me.updateDeal,invalidateQueries:M=>T.invalidateQueries(M),showToast:I,onDealUpdated:n})},[t.id,U.name,U.target,U.perspective,T,I,n]),ms=ta(Y);return e.jsxs("div",{className:"mx-auto max-w-7xl space-y-6",children:[e.jsx(Ir,{deal:{id:t.id,name:ze,target:U.target,industry:t.industry,status:t.status,deal_mode:t.deal_mode},isPlaceholderIdentity:_a,identityEditValue:ja,onSaveIdentity:ms?Xa:void 0,onOpenAudioBrief:()=>J(!0),onOpenAnalysisStatus:()=>z(!0),onRunResearch:h||pt?void 0:$a,onRegenerateAll:us?void 0:()=>yt(),isRegenerateDisabled:Fe,onShare:Ya,onExport:Za,onRecordOutcome:()=>xt(!0),compact:a}),t.is_sample&&e.jsx(rr,{dealId:t.id}),t.perspective==="third_party_merger"&&e.jsx(ki,{dealId:t.id}),t.perspective!=="third_party_merger"&&e.jsxs(e.Fragment,{children:[e.jsx(qi,{deal:t,isFreshDeal:Ie,isDataReady:Me,isGenerating:Ys({isGenerating:c,isFullAnalysisRunning:Oe,hasActiveFullPipelineRunRow:!!Ee}),isResearchRunning:pt,tilesPopulated:!Ne,hasAnalysisContent:ls,hasUploadedDocuments:_e,dataQualityConcern:Ea,dataQualityState:Aa,executiveSummary:Pa,isReanalyzing:Fa,isStaleAfterFailedRerun:Ta,lastCanonicalRunIncomplete:ve?.status==="partial"||ve?.status==="failed"}),U.is_public!==!1&&(U.is_public!==!0||!!U.ticker)&&e.jsx(si,{dealId:U.id,knownPublic:U.is_public===!0,knownTicker:U.ticker,hasUploadedDocuments:_e,canEditIdentity:ms,isResearchRunning:pt,perspective:U.perspective,analysisPolicy:U.analysis_policy}),e.jsx("div",{"data-overview-section":"metrics","aria-hidden":"true"}),e.jsx("div",{"data-overview-section":"financials","aria-hidden":"true"}),e.jsx("div",{"data-overview-section":"risks","aria-hidden":"true"}),e.jsx("div",{"data-overview-section":"activity","aria-hidden":"true"}),d&&e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(le,{size:24,className:"text-theme-text-muted animate-spin"})}),!d&&(u||x)&&e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 rounded-xl border border-red-200 bg-red-50 py-8 dark:border-red-900/50 dark:bg-red-950/20",children:[e.jsx(qe,{size:24,className:"text-red-500"}),e.jsx("p",{className:"text-sm font-medium text-red-700 dark:text-red-400",children:u?"Failed to load deal summary":"An operation failed"}),e.jsx("p",{className:"max-w-md text-center text-xs text-red-600/80 dark:text-red-400/60",children:(u??x)?.message??"Please try again"}),e.jsx("button",{onClick:()=>S(),className:"mt-1 rounded-lg bg-red-100 px-4 py-1.5 text-xs font-medium text-red-700 transition-colors hover:bg-red-200 dark:bg-red-900/30 dark:text-red-400 dark:hover:bg-red-900/50",children:"Retry"})]}),(Ie||Me||c&&Ne)&&!u&&e.jsx(Yr,{deal:U,hasUploadedDocuments:_e,hasExternalEvidence:Ke,uploadedDocumentCount:He,externalComparableCount:Ge,externalPrecedentCount:Ve,onNavigateToComparables:Sa,onNavigateToPrecedents:Ca,onGenerateSummaryOnly:()=>yt(),isGenerateSummaryLoading:D,generationInputs:j,hasGenerationInputsError:!!O,hasActiveFullPipelineRun:Fe,isGenerating:c,generationProgress:f,onFileUploaded:ye,processingStatus:P,dataCollectionStatus:Be,canRunFullAnalysis:he,fullAnalysisDisabledReason:as}),ia({noTilesYet:Ne,isGenerating:c,hasActiveFullPipelineRun:Fe,hasError:!!u})&&e.jsx(la,{}),gt&&e.jsxs(e.Fragment,{children:[e.jsx(Hs,{view:ds,dealId:t.id,runFullAnalysisButtonState:Ka,suppressRunPercentage:G("chat_centric_deal_workspace"),launcher:e.jsx($s,{dealId:t.id,dealName:ze,disabled:vt!=="enabled",disabledReason:Qa,hasProcessingDocuments:ss,onDispatching:Wa,recoveryOptions:ds.run?.retry_suggestion}),onOpenAnalysisStatus:y=>{ie(y),z(!0)},onRetryLedger:()=>{fa()}}),!c&&!is&&o.length>0&&e.jsx(ti,{tiles:o,onNavigateToDataRoom:ka,onRerunAnalysis:()=>yt(),onDismiss:()=>wa(!0),ddNotStarted:$e===0,deal:U,isRunActive:Fe}),!o.some(y=>y.tile_type==="live_financial_review")&&e.jsxs("button",{type:"button",onClick:()=>De(!0),className:"border-theme-divider bg-theme-surface dark:bg-theme-surface/5 flex w-full items-center justify-between rounded-xl border px-4 py-3 text-left transition-colors hover:border-theme-accent hover:bg-indigo-50/40 dark:hover:bg-indigo-500/10",children:[e.jsxs("span",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-theme-text-secondary text-sm font-semibold",children:"Review extracted financials"}),e.jsx("span",{className:"text-theme-text-muted text-xs",children:"Inspect AI-extracted line items and submit c
5orrections that train the model."})]}),e.jsx("span",{className:"text-xs font-medium text-theme-accent-text dark:text-indigo-300",children:"Open drawer"})]}),e.jsx(ma,{dealId:t.id,deal:t,tiles:l,visibleTiles:o,forceOpenAllTiles:!!(r?.isActive&&(!r.currentDealId||r.currentDealId===t.id)),executiveSummary:Xe,executiveSummaryTileId:de?.id??null,executiveSummaryOverride:Ia,isStale:Ma,latestTerminalRun:ve,hasContent:m,isGenerating:c,canReorder:!c,sortableSensors:Ba,onTileDragEnd:za,onRegenerate:La,onAskAI:Ha,onShowEvidence:Ga,onDeleteTile:qa,onToggleVisibility:Oa,isRegenerating:p,regenerateDisabled:Fe,ddNotStarted:$e===0,onOpenFinancialReview:()=>De(!0),onAddTile:Ua,publicationReadiness:E})]}),e.jsx(ir,{open:W,onOpenChange:J,children:e.jsxs(lr,{className:"max-w-2xl",showCloseButton:!1,"aria-describedby":void 0,children:[e.jsx(or,{className:"sr-only",children:"Deal Street Podcast"}),R?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(le,{className:"h-6 w-6 animate-spin text-purple-500"})}):F?e.jsx(cr,{episode:F,compact:!0}):q?e.jsxs("div",{className:"flex flex-col items-center justify-center gap-4 py-12",children:[e.jsx(le,{className:"h-8 w-8 animate-spin text-purple-500"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-theme-text-secondary text-sm font-medium",children:"Generating podcast..."}),e.jsxs("p",{className:"text-theme-text-muted mt-1 text-xs",children:[Q,"% complete"]})]}),e.jsx("div",{className:"bg-theme-surface-light h-1.5 w-48 rounded-full",children:e.jsx("div",{className:"h-full rounded-full bg-purple-500 transition-all",style:{width:`${Q}%`}})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center gap-4 py-12",children:[e.jsx("div",{className:"rounded-full bg-purple-100 p-4 dark:bg-purple-900/30",children:e.jsx(Es,{className:"h-8 w-8 text-purple-500"})}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-theme-text-secondary text-sm font-medium",children:"No podcast episode yet"}),e.jsx("p",{className:"text-theme-text-muted mt-1 text-xs",children:"Generate an AI-powered audio brief for this deal"})]}),e.jsxs("button",{onClick:()=>{C().catch(y=>{console.error("[DealSummary] Podcast generation failed:",y),I({title:"Failed to generate podcast",variant:"error"})})},disabled:q,className:"flex items-center gap-2 rounded-lg bg-purple-600 px-5 py-2.5 text-sm font-medium text-white shadow-md transition-colors hover:bg-purple-700 disabled:opacity-50 dark:text-white",children:[e.jsx(Sn,{className:"h-4 w-4"}),"Generate Podcast"]})]})]})}),e.jsx(dr,{open:B,onOpenChange:z,dealId:t.id,runs:ce,runsError:es,runsLoading:ht,selectedRun:ba,onSelectRun:ie}),e.jsx(ur,{dealId:t.id,isOpen:L,onClose:()=>oe(!1)}),e.jsx(mr,{dealId:t.id,isOpen:xa,onClose:()=>xt(!1),onSubmitted:ha}),e.jsx($i,{dealId:t.id,companyName:t.target??t.companyName??t.name??void 0,isOpen:ue,onClose:()=>De(!1),reconciliationSnapshotId:ga}),e.jsx(xr,{dealId:t.id,onOpenAnalysisStatus:y=>{ie(y),z(!0)}})]})]})}const xl=Object.freeze(Object.defineProperty({__proto__:null,CollapsedTilesSection:ua,FULL_ANALYSIS_START_TIMEOUT_MS:aa,PopulatedRunStateBar:Hs,TERMINAL_FULL_PIPELINE_STATUSES:Ls,Zone3EmptyState:la,Zone3Findings:ma,default:Wi,getRunFullAnalysisButtonState:Qs,isTileContentLostAfterFailedRun:ca,mergeTerminalRunIntoDialogHistory:qs,parseBackendUtcTimestampMs:Ft,resolveCanEditDealIdentity:ta,resolveDealSummaryReadinessInputs:sa,resolveEffectiveExecutiveSummary:Bs,resolveFullAnalysisLaunchButtonState:da,resolveHasActiveFullPipelineRun:Us,resolveHasExternalEvidence:Ws,resolveHeroIsGenerating:Ys,resolveIdentityDisplayName:Ht,resolveIdentityEditValue:Xs,resolveIsPlaceholderCompanyIdentity:Zs,resolvePopulatedRunStateView:zs,saveDealIdentity:ea,selectCollapsedGridTiles:ra,selectFinancialReconciliationSnapshotId:oa,selectIncompleteStepLabels:fr,selectLatestTerminalFullPipeline:gr,shouldShowZone3EmptyState:ia,shouldSyncNameOnIdentitySave:Js,useStartingFullAnalysisFlag:na},Symbol.toStringTag,{value:"Module"}));export{xl as D,$i as F,oa as s};

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.