1import{j as e}from"./vendor-radix-BnNg3BH5.js";import{L as ke,r as g,Q as ns}from"./vendor-react-67mgcWXU.js";import{C as D,d as R,a as ne,b as ie,c as Ce}from"./card-DpKBVi42.js";import{k as z,a9 as is,n as Fe,H as os,L as Y,a7 as ge,T as fe,l as je,B as P,m as we,E as Be,b as Se,s as k,u as ls,v as le,I as ce,D as cs,aa as ds,e as ms,f as xs,g as ps,h as us,a4 as hs,G as gs,F as fs,a0 as Me}from"./index-Epr9psQo.js";import{B as G}from"./badge-Cl7apleB.js";import{T as js,a as ws,b as Ne,c as ae,d as Ns,e as Z}from"./table-023rHGnC.js";import{S as bs}from"./scroll-area-OnGFamwr.js";import{S as ys,C as vs}from"./skeleton-patterns-BEEjmRD3.js";import{a as _s}from"./formatLabel-C4RR0vUw.js";import{u as ks,V as Cs}from"./usePersistedView-DQR3z3CM.js";import{C as Ss,a as Ts,b as Es}from"./collapsible-CKRfPF8i.js";import{m as Is}from"./vendor-motion-CSzk-Fqg.js";import{C as As}from"./clock-BYWbH6MV.js";import{S as pe}from"./swords-b82pQzfy.js";import{E as Te}from"./external-link-DnfaRxEP.js";import{B as $e}from"./building-2-DODpaxwc.js";import{C as Le}from"./circle-check-Cv8aCTuA.js";import{T as Ee}from"./target-CyHaUH9t.js";import{D as He}from"./dollar-sign-CC-jyV1q.js";import{U as Ds}from"./users-uAR6_Qvs.js";import{T as ze}from"./trending-up-CXZcoU_y.js";import{T as be}from"./triangle-alert-C6ISfBPd.js";import{C as ve}from"./crosshair-jBDXSHWT.js";import{M as Rs}from"./message-square-7cL_4-It.js";import{S as _e}from"./shield-BI9NGrnO.js";import{C as Ge}from"./circle-x-HEsvXgN2.js";import{S as qe}from"./sparkles-BcySMUTB.js";import{f as Ue}from"./format-Bw8okCdv.js";import{M as me}from"./metric-DK0Tcl4m.js";import{S as Ws}from"./skeleton-CXDkv5zX.js";import{T as xe}from"./trophy-DDLL3U1f.js";import{T as Ms}from"./trending-down-CFwiQb3W.js";import{a as Ls}from"./vendor-query-PMAhJHCS.js";import{u as Vs}from"./useStreamingAI-P9mQEfIN.js";import{u as Os}from"./useCompetitorWinRate-Dx2TDFe0.js";import{f as Ve}from"./firecrawl-ByFAwZpN.js";import{R as Ps}from"./refresh-cw-j1umLsSM.js";import{S as Fs}from"./search-BnpyGpZl.js";import{P as Bs}from"./plus-DRTmwF2W.js";import{G as ye}from"./globe-DQzIP_ik.js";import"./vendor-supabase-CTlrDMdV.js";import"./vendor-charts-Dck3qfzI.js";import"./layout-grid-ShDyZi0i.js";import"./list-Cd7HYcio.js";import"./index-Jdtl9AIN.js";import"./en-US-DJiZ5LCQ.js";function $s({wins:t,losses:x,className:y}){const w=t+x,u=w>0?Math.round(t/w*100):0,f=2*Math.PI*18,p=f,h=f-u/100*f;return e.jsxs("div",{className:z("relative flex items-center justify-center",y),children:[e.jsxs("svg",{className:"w-14 h-14 -rotate-90",viewBox:"0 0 40 40",children:[e.jsx("circle",{className:"text-muted/30",strokeWidth:"4",stroke:"currentColor",fill:"transparent",r:"18",cx:"20",cy:"20"}),e.jsx("circle",{className:z("transition-all duration-500",u>=50?"text-success":u>0?"text-warning":"text-muted-foreground"),strokeWidth:"4",strokeDasharray:p,strokeDashoffset:h,strokeLinecap:"round",stroke:"currentColor",fill:"transparent",r:"18",cx:"20",cy:"20"})]}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("span",{className:"text-xs font-bold",children:[t,"-",x]})})]})}function Hs({strengths:t,weaknesses:x}){const y=t-x;let w="low",u="LOW THREAT";return y>3?(w="high",u="HIGH THREAT"):y>0&&(w="medium",u="MODERATE"),e.jsx("div",{className:z("px-2 py-1 rounded text-caption font-bold tracking-wider uppercase",w==="high"&&"bg-destructive/20 text-destructive",w==="medium"&&"bg-warning/20 text-warning",w==="low"&&"bg-success/20 text-success"),children:u})}function Oe({competitor:t,isExpanded:x,onToggle:y,onGeneratePositioning:w,isGenerating:u,onGeneratePlaybook:f,isGeneratingPlaybook:p,defensivePlaybook:h,streamingContent:q,winRateData:v}){const C=v?.wins??Math.floor((t.proposal_count||0)*.6),W=v?.losses??(t.proposal_count||0)-C;return e.jsx(Is.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"relative",children:e.jsxs(D,{className:"overflow-hidden border-0 bg-gradient-to-br from-card to-card/80 shadow-lg",children:[e.jsxs("div",{className:"bg-muted/30 border-b px-4 py-2 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-caption font-mono uppercase tracking-widest text-muted-foreground",children:"COMPETITIVE INTELLIGENCE DOSSIER"}),e.jsxs("span",{className:"text-caption font-mono text-muted-foreground",children:["ID: ",t.id.slice(0,8).toUpperCase()]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.last_scraped_at&&e.jsxs("span",{className:"text-caption font-mono text-muted-foreground flex items-center gap-1",children:[e.jsx(As,{className:"h-3 w-3"}),Ue(new Date(t.last_scraped_at),"yyyy-MM-dd HH:mm")]}),e.jsx(Hs,{strengths:t.strengths.length,weaknesses:t.weaknesses.length})]})]}),e.jsxs(Ss,{open:x,onOpenChange:y,children:[e.jsx(Ts,{asChild:!0,children:e.jsxs("div",{className:"cursor-pointer hover:bg-muted/30 transition-colors p-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-4 flex-1 min-w-0",children:[e.jsx("div",{className:z("h-16 w-16 rounded-xl flex items-center justify-center flex-shrink-0","bg-gradient-to-br from-destructive/20 to-destructive/5 border border-destructive/20"),children:e.jsx(pe,{className:"h-8 w-8 text-destructive"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-1",children:[e.jsx("h3",{className:"text-xl font-bold tracking-tight truncate",children:t.company_name}),t.website&&e.jsx("a",{href:t.website,target:"_blank",rel:"noopener noreferrer",className:"text-muted-foreground hover:text-primary transition-colors",onClick:l=>l.stopPropagation(),children:e.jsx(Te,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.industry&&e.jsxs(G,{variant:"outline",className:"text-xs font-normal",children:[e.jsx($e,{className:"h-3 w-3 mr-1"}),t.industry]}),t.scrape_status==="completed"&&e.jsxs(G,{variant:"outline",className:"text-xs text-success border-success/30",children:[e.jsx(Le,{className:"h-3 w-3 mr-1"}),"Intel Verified"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[(t.proposal_count||0)>0&&e.jsxs("div",{className:"text-center",children:[e.jsx($s,{wins:C,losses:W}),e.jsx("p",{className:"text-caption text-muted-foreground mt-1 uppercase tracking-wider",children:"Win Rate"})]}),e.jsx("div",{className:"p-2 rounded-lg hover:bg-muted/50 transition-colors",children:x?e.jsx(is,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(Fe,{className:"h-5 w-5 text-muted-foreground"})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 mt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-muted/30 min-w-0",children:[e.jsx(Ee,{className:"h-4 w-4 text-primary flex-shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-lg font-bold",children:t.proposal_count||0}),e.jsx("p",{className:"text-caption text-muted-foreground uppercase tracking-wider",children:"Encounters"})]})]}),t.estimated_revenue&&e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-muted/30 min-w-0",children:[e.jsx(He,{className:"h-4 w-4 text-success flex-shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-bold truncate",children:t.estimated_revenue}),e.jsx("p",{className:"text-caption text-muted-foreground uppercase tracking-wider",children:"Revenue"})]})]}),t.estimated_headcount&&e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-muted/30 min-w-0",children:[e.jsx(Ds,{className:"h-4 w-4 text-info flex-shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-bold truncate",children:t.estimated_headcount}),e.jsx("p",{className:"text-caption text-muted-foreground uppercase tracking-wider",children:"Headcount"})]})]}),t.pricing_model&&e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-muted/30 min-w-0",children:[e.jsx(ze,{className:"h-4 w-4 text-warning flex-shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-bold truncate max-w-full",title:t.pricing_model,children:t.pricing_model}),e.jsx("p",{className:"text-caption text-muted-foreground uppercase tracking-wider",children:"Pricing"})]})]})]})]})}),e.jsx(Es,{children:e.jsxs(R,{className:"pt-0 space-y-6 pb-6",children:[e.jsx("div",{className:"border-t border-dashed"}),t.description&&e.jsxs("section",{children:[e.jsxs("h4",{className:"text-xs font-mono uppercase tracking-widest text-muted-foreground mb-3 flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"1.0"})," OVERVIEW"]}),e.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed text-justify",children:t.description})]}),(t.strengths.length>0||t.weaknesses.length>0)&&e.jsxs("section",{children:[e.jsxs("h4",{className:"text-xs font-mono uppercase tracking-widest text-muted-foreground mb-4 flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"2.0"})," THREAT ASSESSMENT"]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[t.strengths.length>0&&e.jsxs("div",{className:"rounded-xl border-l-4 border-destructive bg-destructive/5 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(be,{className:"h-4 w-4 text-destructive"}),e.jsx("p",{className:"text-sm font-semibold text-destructive uppercase tracking-wide",children:"Their Strengths"})]}),e.jsx("ul",{className:"space-y-2",children:t.strengths.slice(0,5).map((l,m)=>e.jsxs("li",{className:"text-sm text-muted-foreground flex items-start gap-2",children:[e.jsx("span",{className:"text-destructive font-mono text-xs mt-0.5",children:String(m+1).padStart(2,"0")}),e.jsx("span",{className:"break-words",children:l})]},m))})]}),t.weaknesses.length>0&&e.jsxs("div",{className:"rounded-xl border-l-4 border-success bg-success/5 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ve,{className:"h-4 w-4 text-success"}),e.jsx("p",{className:"text-sm font-semibold text-success uppercase tracking-wide",children:"Exploitable Weaknesses"})]}),e.jsx("ul",{className:"space-y-2",children:t.weaknesses.slice(0,5).map((l,m)=>e.jsxs("li",{className:"text-sm text-muted-foreground flex items-start gap-2",children:[e.jsx("span",{className:"text-success font-mono text-xs mt-0.5",children:String(m+1).padStart(2,"0")}),e.jsx("span",{className:"break-words",children:l})]},m))})]})]})]}),t.win_themes&&t.win_themes.length>0&&e.jsxs("section",{children:[e.jsxs("h4",{className:"text-xs font-mono uppercase tracking-widest text-muted-foreground mb-4 flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"3.0"})," WIN THEMES"]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-3",children:t.win_themes.map((l,m)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-primary/5 border border-primary/20",children:[e.jsx(os,{className:"h-4 w-4 text-primary mt-0.5 flex-shrink-0"}),e.jsx("p",{className:"text-sm break-words",children:l})]},m))})]}),t.objection_handlers&&t.objection_handlers.length>0&&e.jsxs("section",{children:[e.jsxs("h4",{className:"text-xs font-mono uppercase tracking-widest text-muted-foreground mb-4 flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"4.0"})," OBJECTION HANDLERS"]}),e.jsx("div",{className:"space-y-3",children:t.objection_handlers.map((l,m)=>e.jsxs("div",{className:"rounded-lg border bg-card overflow-hidden",children:[e.jsx("div",{className:"bg-warning/10 border-b border-warning/20 px-4 py-2",children:e.jsxs("p",{className:"text-sm font-medium flex items-start gap-2",children:[e.jsx(Rs,{className:"h-4 w-4 text-warning mt-0.5 flex-shrink-0"}),e.jsxs("span",{className:"break-words",children:['"',l.objection,'"']})]})}),e.jsx("div",{className:"px-4 py-3",children:e.jsx("p",{className:"text-sm text-muted-foreground break-words",children:l.response})})]},m))})]}),t.positioning_notes&&t.positioning_notes.length>0&&e.jsxs("section",{children:[e.jsxs("h4",{className:"text-xs font-mono uppercase tracking-widest text-muted-foreground mb-4 flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"5.0"})," STRATEGIC POSITIONING"]}),e.jsx("div",{className:"space-y-3",children:t.positioning_notes.slice(0,2).map((l,m)=>e.jsx("div",{className:"p-4 rounded-lg bg-muted/30 border-l-4 border-primary text-sm text-muted-foreground text-justify leading-relaxed break-words",children:l},m))})]}),t.services.length>0&&e.jsxs("section",{children:[e.jsxs("h4",{className:"text-xs font-mono uppercase tracking-widest text-muted-foreground mb-3 flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"6.0"})," CAPABILITIES"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.services.slice(0,10).map((l,m)=>e.jsx(G,{variant:"outline",className:"text-xs font-normal",children:l},m)),t.services.length>10&&e.jsxs(G,{variant:"secondary",className:"text-xs",children:["+",t.services.length-10," more"]})]})]}),(h||q)&&e.jsxs("section",{children:[e.jsxs("h4",{className:"text-xs font-mono uppercase tracking-widest text-muted-foreground mb-4 flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"7.0"})," DEFENSIVE PLAYBOOK",p&&e.jsxs("span",{className:"flex items-center gap-1.5 text-primary ml-2",children:[e.jsx(Y,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{className:"text-caption",children:"Generating..."})]})]}),p&&q&&e.jsx("div",{className:"rounded-xl border bg-muted/30 p-4 mb-4",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Y,{className:"h-4 w-4 animate-spin text-primary mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm text-muted-foreground font-mono whitespace-pre-wrap break-all leading-relaxed max-h-48 overflow-y-auto",children:[q.slice(-500),e.jsx("span",{className:"inline-block w-1.5 h-4 ml-0.5 bg-primary animate-pulse"})]})]})}),h&&!p&&e.jsxs("div",{className:"space-y-4",children:[h.counter_strategies.length>0&&e.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[e.jsx("div",{className:"bg-primary/10 border-b border-primary/20 px-4 py-2",children:e.jsxs("p",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(pe,{className:"h-4 w-4 text-primary"}),"Counter-Attack Strategies"]})}),e.jsx("div",{className:"divide-y",children:h.counter_strategies.map((l,m)=>e.jsxs("div",{className:"p-4",children:[e.jsxs("p",{className:"text-xs text-destructive font-medium mb-1 flex items-center gap-2",children:[e.jsx(be,{className:"h-3 w-3"}),'When they claim: "',l.their_strength,'"']}
1),e.jsxs("p",{className:"text-sm text-muted-foreground break-words",children:["â ",l.our_counter]})]},m))})]}),h.trap_questions.length>0&&e.jsxs("div",{className:"rounded-xl border-l-4 border-warning bg-warning/5 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ve,{className:"h-4 w-4 text-warning"}),e.jsx("p",{className:"text-sm font-semibold text-warning uppercase tracking-wide",children:"Trap Questions to Ask"})]}),e.jsx("ul",{className:"space-y-2",children:h.trap_questions.map((l,m)=>e.jsxs("li",{className:"text-sm text-muted-foreground flex items-start gap-2",children:[e.jsx("span",{className:"text-warning font-mono text-xs mt-0.5",children:String(m+1).padStart(2,"0")}),e.jsxs("span",{className:"break-words italic",children:['"',l,'"']})]},m))})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[h.defensive_talking_points.length>0&&e.jsxs("div",{className:"rounded-xl border-l-4 border-info bg-info/5 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(_e,{className:"h-4 w-4 text-info"}),e.jsx("p",{className:"text-sm font-semibold text-info uppercase tracking-wide",children:"Defensive Talking Points"})]}),e.jsx("ul",{className:"space-y-2",children:h.defensive_talking_points.map((l,m)=>e.jsxs("li",{className:"text-sm text-muted-foreground flex items-start gap-2",children:[e.jsx(Le,{className:"h-3.5 w-3.5 text-info mt-0.5 flex-shrink-0"}),e.jsx("span",{className:"break-words",children:l})]},m))})]}),h.red_flags.length>0&&e.jsxs("div",{className:"rounded-xl border-l-4 border-destructive bg-destructive/5 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(be,{className:"h-4 w-4 text-destructive"}),e.jsx("p",{className:"text-sm font-semibold text-destructive uppercase tracking-wide",children:"Red Flags to Watch"})]}),e.jsx("ul",{className:"space-y-2",children:h.red_flags.map((l,m)=>e.jsxs("li",{className:"text-sm text-muted-foreground flex items-start gap-2",children:[e.jsx(Ge,{className:"h-3.5 w-3.5 text-destructive mt-0.5 flex-shrink-0"}),e.jsx("span",{className:"break-words",children:l})]},m))})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-4 border-t border-dashed",children:[e.jsx(ge,{children:e.jsxs(fe,{children:[e.jsx(je,{asChild:!0,children:e.jsx(P,{onClick:l=>{l.stopPropagation(),w()},disabled:u||p,className:"flex-1 sm:flex-none",children:u?e.jsxs(e.Fragment,{children:[e.jsx(Y,{className:"h-4 w-4 mr-2 animate-spin"}),"Analyzing Intel..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"h-4 w-4 mr-2"}),"Generate Positioning"]})})}),e.jsx(we,{children:e.jsx("p",{children:"Generate AI-powered positioning strategy, win themes, and objection handlers"})})]})}),e.jsx(ge,{children:e.jsxs(fe,{children:[e.jsx(je,{asChild:!0,children:e.jsx(P,{variant:"outline",size:"icon",className:"flex-shrink-0",onClick:l=>{l.stopPropagation(),f()},disabled:p||u,children:p?e.jsx(Y,{className:"h-4 w-4 animate-spin"}):e.jsx(_e,{className:"h-4 w-4"})})}),e.jsx(we,{children:e.jsx("p",{children:"Generate defensive playbook with counter-strategies and trap questions"})})]})}),e.jsx(ge,{children:e.jsxs(fe,{children:[e.jsx(je,{asChild:!0,children:e.jsx(ke,{to:`/intelligence/competitive/${t.id}`,onClick:l=>l.stopPropagation(),children:e.jsxs(P,{variant:"secondary",size:"sm",className:"gap-2",children:[e.jsx(Be,{className:"h-4 w-4"}),"Full Dossier"]})})}),e.jsx(we,{children:e.jsx("p",{children:"View complete competitor intelligence profile"})})]})})]})]})})]})]})})}function zs(){const{currentTenant:t}=Se(),[x,y]=g.useState([]),[w,u]=g.useState(!0),[f,p]=g.useState("wins");g.useEffect(()=>{t?.id&&h()},[t?.id]);const h=async()=>{try{const{data:a}=await k.from("prospect_competitors").select(` 2 competitor_id, 3 prospect_id, 4 is_winner 5 `).eq("tenant_id",t.id);if(!a||a.length===0){y([]),u(!1);return}const d=[...new Set(a.map(o=>o.competitor_id))],j=[...new Set(a.map(o=>o.prospect_id))],[S,V]=await Promise.all([k.from("company_intelligence").select("id, company_name, industry").in("id",d),k.from("deal_outcomes").select("prospect_id, outcome, deal_value, outcome_date, competitor_won_id").in("prospect_id",j).eq("tenant_id",t.id)]),F=new Map((S.data||[]).map(o=>[o.id,o])),K=new Map((V.data||[]).map(o=>[o.prospect_id,o])),{data:J}=await k.from("prospects").select("id, company_name").in("id",j),T=new Map((J||[]).map(o=>[o.id,o.company_name])),_=new Map;for(const o of a){const B=F.get(o.competitor_id);if(!B)continue;_.has(o.competitor_id)||_.set(o.competitor_id,{competitor_id:o.competitor_id,company_name:B.company_name,industry:B.industry,wins:0,losses:0,winRate:0,totalDealValue:0,wonDealValue:0,lostDealValue:0,recentTrend:"stable",deals:[]});const N=_.get(o.competitor_id),b=K.get(o.prospect_id);if(!b)continue;const E=b.deal_value||0;b.outcome==="won"?(N.wins++,N.wonDealValue+=E):(b.outcome==="lost"&&b.competitor_won_id===o.competitor_id||b.outcome==="lost")&&(N.losses++,N.lostDealValue+=E),N.totalDealValue+=E,N.deals.push({outcome:b.outcome,deal_value:b.deal_value,outcome_date:b.outcome_date,prospect_name:T.get(o.prospect_id)||"Unknown"})}for(const o of _.values()){const B=o.wins+o.losses;
5o.winRate=B>0?Math.round(o.wins/B*100):0;const N=o.deals.filter(b=>b.outcome_date).sort((b,E)=>new Date(E.outcome_date).getTime()-new Date(b.outcome_date).getTime());if(N.length>=4){const b=N.slice(0,3),E=N.slice(3,6),X=b.filter(se=>se.outcome==="won").length/b.length,ee=E.length>0?E.filter(se=>se.outcome==="won").length/E.length:.5;X>ee+.1?o.recentTrend="improving":X<ee-.1&&(o.recentTrend="declining")}}y(Array.from(_.values()))}catch(a){console.error("Error loading scoreboard:",a)}finally{u(!1)}},q=g.useMemo(()=>[...x].sort((a,d)=>{switch(f){case"wins":return d.wins-a.wins;case"losses":return d.losses-a.losses;case"winRate":return d.winRate-a.winRate;case"value":return d.totalDealValue-a.totalDealValue;default:return 0}}),[x,f]),v=g.useMemo(()=>{const a=new Map;for(const d of x){const j=d.industry||"Unknown",S=a.get(j)||{wins:0,losses:0,value:0};S.wins+=d.wins,S.losses+=d.losses,S.value+=d.totalDealValue,a.set(j,S)}return Array.from(a.entries()).map(([d,j])=>({industry:d,...j})).sort((d,j)=>j.wins+j.losses-(d.wins+d.losses))},[x]);if(w)return e.jsxs(D,{children:[e.jsx(ne,{children:e.jsxs(ie,{className:"flex items-center gap-2",children:[e.jsx(xe,{className:"h-5 w-5"}),"Competitive Scoreboard"]})}),e.jsx(R,{children:e.jsx("div",{className:"space-y-3",children:[1,2,3].map(a=>e.jsx(Ws,{className:"h-16"},a))})})]});if(x.length===0)return e.jsxs(D,{children:[e.jsxs(ne,{children:[e.jsxs(ie,{className:"flex items-center gap-2",children:[e.jsx(xe,{className:"h-5 w-5"}),"Competitive Scoreboard"]}),e.jsx(Ce,{children:"Win/loss record against competitors"})]}),e.jsx(R,{children:e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No competitive deal data yet. Close deals with competitors linked to see your scoreboard."})})]});const C=x.reduce((a,d)=>a+d.wins,0),W=x.reduce((a,d)=>a+d.losses,0),l=C+W>0?Math.round(C/(C+W)*100):0,m=x.reduce((a,d)=>a+d.totalDealValue,0);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(D,{className:"bg-success/5 border-success/20",children:e.jsxs(R,{className:"pt-4 pb-3 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(xe,{className:"h-4 w-4 text-success"}),e.jsx("span",{className:"text-xs text-muted-foreground font-medium uppercase tracking-wider",children:"Wins"})]}),e.jsx(me,{size:"md",children:C})]})}),e.jsx(D,{className:"bg-destructive/5 border-destructive/20",children:e.jsxs(R,{className:"pt-4 pb-3 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ge,{className:"h-4 w-4 text-destructive"}),e.jsx("span",{className:"text-xs text-muted-foreground font-medium uppercase tracking-wider",children:"Losses"})]}),e.jsx(me,{size:"md",children:W})]})}),e.jsx(D,{children:e.jsxs(R,{className:"pt-4 pb-3 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(pe,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-xs text-muted-foreground font-medium uppercase tracking-wider",children:"Win Rate"})]}),e.jsxs(me,{size:"md",children:[l,"%"]})]})}),e.jsx(D,{children:e.jsxs(R,{className:"pt-4 pb-3 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(He,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-xs text-muted-foreground font-medium uppercase tracking-wider",children:"Total Value"})]}),e.jsxs(me,{size:"md",children:["$",(m/1e3).toFixed(0),"K"]})]})})]}),e.jsxs(D,{children:[e.jsx(ne,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ie,{className:"text-lg flex items-center gap-2",children:[e.jsx(xe,{className:"h-5 w-5"}),"Head-to-Head Records"]}),e.jsx("div",{className:"flex gap-1",children:["wins","losses","winRate","value"].map(a=>e.jsx(P,{variant:f===a?"default":"ghost",size:"sm",className:"text-xs h-7",onClick:()=>p(a),children:a==="winRate"?"Win %":a==="value"?"Value":a.charAt(0).toUpperCase()+a.slice(1)},a))})]})}),e.jsx(R,{children:e.jsx("div",{className:"space-y-2",children:q.map(a=>{const d=a.wins+a.losses,j=d>0?a.wins/d*100:0;return e.jsxs(ke,{to:`/intelligence/competitive/${a.competitor_id}`,className:"flex items-center gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors group",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium text-sm truncate group-hover:text-primary transition-colors",children:a.company_name}),a.industry&&e.jsx(G,{variant:"outline",className:"text-caption shrink-0",children:a.industry}),a.recentTrend==="improving"&&e.jsx(ze,{className:"h-3 w-3 text-success shrink-0"}),a.recentTrend==="declining"&&e.jsx(Ms,{className:"h-3 w-3 text-destructive shrink-0"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 h-2 rounded-full bg-destructive/20 overflow-hidden",children:e.jsx("div",{className:"h-full bg-success rounded-full transition-all",style:{width:`${j}%`}})}),e.jsxs("span",{className:"text-xs text-muted-foreground font-mono shrink-0",children:[a.wins,"W-",a.losses,"L"]})]})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsxs("p",{className:z("text-lg font-bold",a.winRate>=60?"text-success":a.winRate<=40?"text-destructive":"text-foreground"),children:[a.winRate,"%"]}),a.totalDealValue>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["$",(a.totalDealValue/1e3).toFixed(0),"K"]})]}),e.jsx(Te,{className:"h-4 w-4 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity shrink-0"})]},a.competitor_id)})})})]}),v.length>1&&e.jsxs(D,{children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"text-lg flex items-center gap-2",children:[e.jsx($e,{className:"h-5 w-5"}),"By Industry"]})}),e.jsx(R,{children:e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-3",children:v.map(({industry:a,wins:d,losses:j,value:S})=>{const V=d+j,F=V>0?Math.round(d/V*100):0;return e.jsxs("div",{className:"p-3 rounded-lg border bg-muted/20",children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:a}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"font-mono",children:[d,"W-",j,"L"]}),e.jsxs("span",{className:z("font-bold",F>=60?"text-success":F<=40?"text-destructive":""),children:[F,"%"]}),S>0&&e.jsxs("span",{children:["$",(S/1e3).toFixed(0),"K"]})]})]},a)})})})]})]})}const Pe=30,de=2e3;function re(t){return t.total>0?Math.round(t.wins/t.total*100):null}function Gs(){const{currentTenant:t}=Se(),x=t?.id,{data:y,isLoading:w}=Ls({queryKey:["battlecard-efficacy",x],enabled:!!x,queryFn:async()=>{const[{data:l,error:m},{data:a,error:d}]=await Promise.all([k.from("deal_outcomes").select("prospect_id, outcome, outcome_date").eq("tenant_id",x).order("outcome_date",{ascending:!1}).limit(de),k.from("battlecards").select("prospect_id, created_at, updated_at").eq("tenant_id",x).not("prospect_id","is",null).order("created_at",{ascending:!1}).limit(de)]);if(m)throw m;if(d)throw d;const j=new Map;for(const T of a||[]){if(!T.prospect_id)continue;const _={created:new Date(T.created_at).getTime(),updated:new Date(T.updated_at).getTime()},o=j.get(T.prospect_id);o?o.push(_):j.set(T.prospect_id,[_])}const S={wins:0,total:0},V={wins:0,total:0},F={wins:0,total:0},K={wins:0,total:0};for(const T of l||[]){if(T.outcome!=="won"&&T.outcome!=="lost")continue;const _=T.outcome==="won",o=new Date(T.outcome_date).getTime(),B=(j.get(T.prospect_id)||[]).filter(N=>N.created<=o);if(B.length>0){S.total++,_&&S.wins++;const N=Pe*24*60*60*1e3,E=B.some(X=>X.updated<=o&&o-X.updated<=N)?F:K;E.total++,_&&E.wins++}else V.total++,_&&V.wins++}const J=(l?.length||0)>=de||(a?.length||0)>=de;return{withCard:S,withoutCard:V,freshCard:F,staleCard:K,truncated:J}}});if(w||!y)return null;const{withCard:u,withoutCard:f,freshCard:p,staleCard:h,truncated:q}=y;if(u.total+f.total===0)return null;const v=re(u),C=re(f),W=v!==null&&C!==null?v-C:null;return e.jsxs(D,{children:[e.jsxs(ne,{children:[e.jsxs(ie,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ee,{className:"h-4 w-4 text-primary"}),"Battlecard Efficacy"]}),e.jsx(Ce,{children:"Win rates on closed deals, split by whether a battlecard existed before close â the feedback loop on whether your competitive intelligence is paying off."})]}),e.jsxs(R,{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"With battlecard"}),e.jsxs("p",{className:"text-2xl font-semibold",children:[v!==null?`${v}%`:"â",e.jsxs("span",{className:"ml-2 text-xs font-normal text-muted-foreground",children:[u.wins,"W / ",u.total-u.wins,"L"]})]}),W!==null&&e.jsxs(G,{variant:W>=0?"secondary":"destructive",className:"mt-1 text-xs",children:[W>=0?"+":"",W," pts vs without"]}),(p.total>0||h.total>0)&&e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Fresh (â¤",Pe,"d before close): ",re(p)!==null?`${re(p)}%`:"â"," (",p.total,")"," · ","Stale: ",re(h)!==null?`${re(h)}%`:"â"," (",h.total,")"]})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Without battlecard"}),e.jsxs("p",{className:"text-2xl font-semibold",children:[C!==null?`${C}%`:"â",e.jsxs("span",{className:"ml-2 text-xs font-normal text-muted-foreground",children:[f.wins,"W / ",f.total-f.wins,"L"]})]}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"Small samples move these numbers a lot â treat as directional until you have 10+ closed deals per bucket."})]}),q&&e.jsxs("p",{className:"text-xs text-muted-foreground sm:col-span-2",children:["Computed from the most recent ",de.toLocaleStr
5ing()," records â figures may exclude older deals."]})]})]})}function qs({totalCompetitors:t,totalVulnerabilities:x,totalEncounters:y,winRate:w=0,onCardClick:u}){const f=[{key:"hostiles",label:"Tracked Hostiles",value:t,icon:pe,color:"text-destructive",bgColor:"bg-destructive/10",borderColor:"border-destructive/20"},{key:"vulnerabilities",label:"Vulnerabilities",value:x,icon:ve,color:"text-success",bgColor:"bg-success/10",borderColor:"border-success/20"},{key:"encounters",label:"Encounters",value:y,icon:Ee,color:"text-primary",bgColor:"bg-primary/10",borderColor:"border-primary/20"},{key:"winrate",label:"Win Rate",value:`${w}%`,icon:xe,color:w>=50?"text-success":"text-warning",bgColor:w>=50?"bg-success/10":"bg-warning/10",borderColor:w>=50?"border-success/20":"border-warning/20"}];return e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:f.map(p=>e.jsx(D,{className:z("border overflow-hidden transition-all hover:shadow-md cursor-pointer hover:scale-[1.02] active:scale-[0.98]",p.borderColor),onClick:()=>u?.(p.key),children:e.jsx(R,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:z("h-10 w-10 rounded-lg flex items-center justify-center flex-shrink-0",p.bgColor),children:e.jsx(p.icon,{className:z("h-5 w-5",p.color)})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(me,{size:"md",className:"tracking-tight",children:p.value}),e.jsx("p",{className:"text-caption text-muted-foreground uppercase tracking-widest truncate",children:p.label})]})]})})},p.label))})}function Pt(){const{currentTenant:t}=Se(),[x,y]=g.useState([]),[w,u]=g.useState(!0),[f,p]=g.useState(""),[h,q]=g.useState(""),[v,C]=g.useState(null),[W,l]=ks("competitive-intel","card"),[m,a]=g.useState(null),[d,j]=g.useState(null),[S,V]=g.useState({}),[F,K]=g.useState({}),[J,T]=g.useState(!1),[_,o]=g.useState([]),[B,N]=g.useState(!1),[b,E]=g.useState(null),[X,ee]=g.useState(!1),[se,Ie]=g.useState(!1),[$,oe]=g.useState({company_name:"",website:"",industry:"",description:""}),{toast:M}=ls(),{stream:Ke}=Vs(),{data:Qe}=Os();g.useEffect(()=>{t?.id&&ue()},[t?.id]);const ue=async()=>{if(t?.id){u(!0);try{const{data:s,error:r}=await k.from("company_intelligence").select("*").eq("tenant_id",t.id).eq("entity_type","competitor").order("company_name");if(r)throw r;const{data:i,error:c}=await k.from("proposal_competitors").select(` 6 id, 7 proposal_id, 8 company_name, 9 website, 10 positioning_notes, 11 strengths, 12 weaknesses, 13 intelligence_id, 14 proposal:proposals!inner(id, title, status, tenant_id) 15 `).eq("proposal.tenant_id",t.id).order("company_name");if(c)throw c;const O=new Map;for(const n of s||[]){const te=n.company_name.toLowerCase().trim(),I=Array.isArray(n.services)?n.services.map(H=>String(H)):[],A=Array.isArray(n.key_differentiators)?n.key_differentiators.map(H=>String(H)):[],L=Array.isArray(n.strengths)?n.strengths.map(H=>String(H)):[],es=Array.isArray(n.weaknesses)?n.weaknesses.map(H=>String(H)):[],ss=Array.isArray(n.positioning_notes)?n.positioning_notes.map(H=>String(H)):[],ts=Array.isArray(n.objection_handlers)?n.objection_handlers:[],as=Array.isArray(n.win_themes)?n.win_themes.map(H=>String(H)):[],rs=n.defensive_playbook;O.set(te,{id:n.id,company_name:n.company_name,website:n.website,description:n.description,industry:n.industry,services:I,key_differentiators:A,strengths:L,weaknesses:es,pricing_model:n.pricing_model,estimated_revenue:n.estimated_revenue,estimated_headcount:n.estimated_headcount,competitive_position:n.competitive_position,last_scraped_at:n.last_scraped_at,scrape_status:n.scrape_status,proposal_count:0,positioning_notes:ss,objection_handlers:ts,win_themes:as,defensive_playbook:rs})}for(const n of i||[]){const te=n.company_name.toLowerCase().trim();let I=O.get(te);I||(I={id:n.id,company_name:n.company_name,website:n.website,description:null,industry:null,services:[],key_differentiators:[],strengths:Array.isArray(n.strengths)?n.strengths:[],weaknesses:Array.isArray(n.weaknesses)?n.weaknesses:[],pricing_model:null,estimated_revenue:null,estimated_headcount:null,competitive_position:null,last_scraped_at:null,scrape_status:null,proposal_count:0,positioning_notes:[],objection_handlers:[],win_themes:[]},O.set(te,I)),I.proposal_count=(I.proposal_count||0)+1,n.positioning_notes&&(I.positioning_notes=[...I.positioning_notes||[],n.positioning_notes]);const A=Array.isArray(n.strengths)?n.strengths:[],L=Array.isArray(n.weaknesses)?n.weaknesses:[];I.strengths=[...new Set([...I.strengths||[],...A])],I.weaknesses=[...new Set([...I.weaknesses||[],...L])]}const U=Array.from(O.values());y(U);const Q={};for(const n of U)n.defensive_playbook&&(Q[n.id]=n.defensive_playbook);V(Q)}catch(s){console.error("Error loading competitors:",s),M({title:"Error loading competitors",description:"Could not load competitive intelligence data.",variant:"destructive"})}finally{u(!1)}}},Ae=async s=>{if(!t?.id){M({title:"Error",description:"No tenant context available",variant:"destructive"});return}a(s.id);try{const{data:r,error:i}=await k.functions.invoke("generate-competitive-positioning",{body:{competitor:{company_name:s.company_name,description:s.description,services:s.services,strengths:s.strengths,weaknesses:s.weaknesses,key_differentiators:s.key_differentiators,pricing_model:s.pricing_model}}});if(i)throw i;if(!r?.success)throw new Error(r?.error||"Failed to generate positioning");const c=r.data,O={tenant_id:t.id,battlecard_type:"competitor",competitor_id:s.id,company_name:s.company_name,website:s.website,industry:s.industry||null,executive_summary:s.description||null,strengths:s.strengths||[],challenges:s.weaknesses||[],key_talking_points:s.key_differentiators||[],positioning_notes:c.positioning_notes?[{note:c.positioning_notes}]:[],objection_handlers:c.objection_handlers||[],win_themes:c.win_themes||[],web_research:{our_advantages:c.our_advantages||[],their_vulnerabilities:c.their_vulnerabilities||[],risk_areas:c.risk_areas||[],generatedAt:new Date().toISOString(),source:"generate-competitive-positioning"}},{data:U}=await k.from("battlecards").select("id, version").eq("tenant_id",t.id).eq("competitor_id",s.id).maybeSingle();let Q;if(U){const{error:A}
15=await k.from("battlecards").update({...O,version:(U.version||1)+1,updated_at:new Date().toISOString()}).eq("id",U.id);if(A)throw A;Q=U.id}else{const{data:A,error:L}=await k.from("battlecards").insert(O).select("id").single();if(L)throw L;Q=A.id}const n=[`Competitor: ${s.company_name}`,s.description?`Description: ${s.description}`:"",c.positioning_notes?`Positioning: ${c.positioning_notes}`:"",c.win_themes?.length?`Win Themes: ${c.win_themes.join(", ")}`:"",c.our_advantages?.length?`Our Advantages: ${c.our_advantages.join(", ")}`:"",c.their_vulnerabilities?.length?`Their Vulnerabilities: ${c.their_vulnerabilities.join(", ")}`:"",c.objection_handlers?.length?`Objection Handlers: ${c.objection_handlers.map(A=>`${A.objection}: ${A.response}`).join("; ")}`:""].filter(Boolean).join(` 16 17`);try{await k.functions.invoke("embed-content",{body:{source_type:"battlecard",source_id:Q,tenant_id:t.id,content:n,industry:s.industry||null,force:!0}}),Me.info("Battlecard embedded for vector search")}catch(A){console.error("Error embedding battlecard (non-critical):",A)}const te={positioning_notes:c.positioning_notes?[c.positioning_notes]:[],objection_handlers:c.objection_handlers||[],win_themes:c.win_themes||[],updated_at:new Date().toISOString()},{error:I}=await k.from("company_intelligence").update(te).eq("id",s.id);I&&console.error("Error saving positioning to dossier:",I),y(A=>A.map(L=>L.id===s.id?{...L,positioning_notes:c.positioning_notes?[c.positioning_notes]:L.positioning_notes,objection_handlers:c.objection_handlers||L.objection_handlers,win_themes:c.win_themes||L.win_themes}:L)),M({title:"Battlecard Created",description:"AI has analyzed the competitor and saved the battlecard."})}catch(r){console.error("Error generating positioning:",r),M({title:"Generation failed",description:r.message||"Could not generate competitive positioning.",variant:"destructive"})}finally{a(null)}},De=async s=>{j(s.id),K(r=>({...r,[s.id]:""}));try{const r=await Ke({functionName:"generate-defensive-playbook",body:{competitor:{company_name:s.company_name,description:s.description,services:s.services,strengths:s.strengths,weaknesses:s.weaknesses,key_differentiators:s.key_differentiators,pricing_model:s.pricing_model},stream:!0},onPartial:i=>{K(c=>({...c,[s.id]:i}))},onComplete:i=>{try{const c=typeof i=="string"?JSON.parse(i):i;V(O=>({...O,[s.id]:c}))}catch{Me.info("Playbook complete, parsing result")}}});if(r){V(c=>({...c,[s.id]:r}));const{error:i}=await k.from("company_intelligence").update({defensive_playbook:JSON.parse(JSON.stringify(r)),updated_at:new Date().toISOString()}).eq("id",s.id);i&&console.error("Error saving playbook to dossier:",i)}M({title:"Defensive Playbook Generated",description:"AI has created tactical counter-strategies and saved to dossier."})}catch(r){console.error("Error generating playbook:",r);const i=r instanceof Error?r.message:"Could not generate defensive playbook.";M({title:"Generation failed",description:i,variant:"destructive"})}finally{j(null),K(r=>{const i={...r};return delete i[s.id],i})}},Re=async()=>{if(!h.trim()){M({title:"Enter a search term",description:"Enter your company, market, or a competitor to discover alternatives",variant:"destructive"});return}T(!0),N(!0),o([]);try{const s=await Ve.search(`${h} competitors alternatives professional services`,{limit:10,scrapeOptions:{formats:["markdown"]}});if(!s.success)throw new Error(s.error||"Web search failed");const r=s.data||[];o(r),r.length===0&&M({title:"No results found",description:`Could not find web results for "${h}"`})}catch(s){console.error("Web search error:",s),M({title:"Search failed",description:s.message||"Could not search the web. Make sure Firecrawl is connected.",variant:"destructive"})}finally{T(!1)}},Ye=async s=>{if(t?.id){E(s.url);try{const r=await Ve.analyzeCompany(s.url);if(!r.success)throw new Error(r.error||"Failed to analyze competitor");const i=r.data,c={tenant_id:t.id,entity_type:"competitor",entity_id:null,company_name:i.companyName||s.title||"Unknown Competitor",website:s.url,description:i.description||s.description||null,industry:i.industry||null,services:i.services||[],products:i.products||[],key_differentiators:i.keyDifferentiators||[],target_market:i.targetMarket||null,team_size:i.teamSize||null,locations:i.locations||[],technologies:i.technologies||[],recent_news:i.recentNews||[],last_scraped_at:new Date().toISOString(),scrape_status:"completed",scrape_error:null,estimated_revenue:i.estimatedRevenue||null,estimated_headcount:i.estimatedHeadcount||null,funding_status:i.fundingStatus||null,founded_year:i.foundedYear||null,leadership:i.leadership||[],clients:i.clients||[],partnerships:i.partnerships||[],certifications:i.certifications||[],awards:i.awards||[],strengths:i.strengths||[],weaknesses:i.weaknesses||[],pricing_model:i.pricingModel||null,competitive_position:i.competitivePosition||null},{error:O}=await k.from("company_intelligence").insert(c);if(O)throw O;M({title:"Competitor added",description:`Successfully analyzed ${i.companyName||s.title}`}),o(U=>U.filter(Q=>Q.url!==s.url)),ue()}catch(r){console.error("Error scraping web result:",r),M({title:"Analysis failed",description:r.message||"Could not analyze this competitor",variant:"destructive"})}finally{E(null)}}},Je=async()=>
17{if(!(!t?.id||!$.company_name.trim())){Ie(!0);try{const{error:s}=await k.from("company_intelligence").insert({tenant_id:t.id,entity_type:"competitor",entity_id:null,company_name:$.company_name.trim(),website:$.website.trim()||null,industry:$.industry.trim()||null,description:$.description.trim()||null,services:[],products:[],key_differentiators:[],strengths:[],weaknesses:[],scrape_status:"completed",scrape_error:null,last_scraped_at:new Date().toISOString()});if(s)throw s;M({title:"Competitor added",description:`${$.company_name.trim()} is now in your known competitor list.`}),oe({company_name:"",website:"",industry:"",description:""}),ee(!1),await ue()}catch(s){M({title:"Could not add competitor",description:s.message||"Please try again.",variant:"destructive"})}finally{Ie(!1)}}},he=x.filter(s=>s.company_name.toLowerCase().includes(f.toLowerCase())||s.industry?.toLowerCase().includes(f.toLowerCase())||s.description?.toLowerCase().includes(f.toLowerCase())),Xe=x.reduce((s,r)=>s+r.weaknesses.length,0),We=x.reduce((s,r)=>s+(r.proposal_count||0),0),Ze=Qe?.overallWinRate??(We>0?60:0);return w?e.jsxs("div",{className:"space-y-6 p-4",children:[e.jsx(ys,{count:3}),e.jsx(vs,{count:6,cols:3})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsx("div",{children:e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-destructive/10 flex items-center justify-center",children:e.jsx(_e,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Competitive Intelligence"}),e.jsx("p",{className:"text-xs font-mono uppercase tracking-widest text-muted-foreground",children:"STRATEGIC THREAT ANALYSIS & WIN TACTICS"})]})]})}),e.jsxs(P,{onClick:ue,variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(Ps,{className:"h-4 w-4"}),"Refresh Intel"]})]}),e.jsx("div",{id:"competitive-scoreboard",children:e.jsx(zs,{})}),e.jsx(Gs,{}),e.jsx(qs,{totalCompetitors:x.length,totalVulnerabilities:Xe,totalEncounters:We,winRate:Ze,onCardClick:s=>{(s==="winrate"?document.getElementById("competitive-scoreboard"):document.getElementById("competitor-dossiers"))?.scrollIntoView({behavior:"smooth",block:"start"})}}),e.jsx(D,{children:e.jsxs(R,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between",children:[e.jsxs("div",{className:"space-y-1.5 lg:max-w-lg lg:flex-1",children:[e.jsx(le,{htmlFor:"known-competitor-search",children:"Known competitors"}),e.jsxs("div",{className:"relative",children:[e.jsx(Fs,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(ce,{id:"known-competitor-search",placeholder:"Filter your competitor list...",value:f,onChange:s=>p(s.target.value),className:"pl-10 bg-background"})]})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsxs(cs,{open:X,onOpenChange:ee,children:[e.jsx(ds,{asChild:!0,children:e.jsxs(P,{className:"gap-2",children:[e.jsx(Bs,{className:"h-4 w-4"}),"Add Known Competitor"]})}),e.jsxs(ms,{children:[e.jsxs(xs,{children:[e.jsx(ps,{children:"Add known competitor"}),e.jsx(us,{children:"Add a company directly to your intelligence library. You can enrich it later."})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"competitor-name",children:"Company name"}),e.jsx(ce,{id:"competitor-name",value:$.company_name,onChange:s=>oe(r=>({...r,company_name:s.target.value})),placeholder:"Acme Advisory"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"competitor-website",children:"Website"}),e.jsx(ce,{id:"competitor-website",value:$.website,onChange:s=>oe(r=>({...r,website:s.target.value})),placeholder:"https://example.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"competitor-industry",children:"Industry"}),e.jsx(ce,{id:"competitor-industry",value:$.industry,onChange:s=>oe(r=>({...r,industry:s.target.value})),placeholder:"Consulting"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(le,{htmlFor:"competitor-notes",children:"Notes"}),e.jsx(hs,{id:"competitor-notes",value:$.description,onChange:s=>oe(r=>({...r,description:s.target.value})),placeholder:"Why this competitor matters...",rows:4})]})]}),e.jsxs(gs,{children:[e.jsx(P,{variant:"outline",onClick:()=>ee(!1),children:"Cancel"}),e.jsxs(P,{onClick:Je,disabled:se||!$.company_name.trim(),children:[se&&e.jsx(Y,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Competitor"]})]})]})]}),e.jsx(Cs,{view:W,onViewChange:l})]})]}),e.jsxs("div",{className:"flex flex-col gap-2 border-t pt-4 sm:flex-row",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ye,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(ce,{placeholder:"Find competitors for your company, market, or service...",value:h,onChange:s=>{q(s.target.value),N(!1)},onKeyDown:s=>s.key==="Enter"&&Re(),className:"pl-10 bg-background"})]}),e.jsxs(P,{onClick:Re,disabled:J||!h.trim(),variant:"secondary",size:"default",children:[J?e.jsx(Y,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(ye,{className:"h-4 w-4 mr-2"}),"Find Competitors"]})]})]})}),B&&e.jsxs(D,{className:"border-primary/50",children:[e.jsxs(ne,{className:"pb-3",children:[e.jsxs(ie,{className:"text-lg flex items-center gap-2",children:[e.jsx(ye,{className:"h-5 w-5 text-primary"}),"Web Search Results",_.length>0&&e.jsxs(G,{variant:"secondary",children:[_.length," found"]}
17)]}),e.jsx(Ce,{children:'Click "Add Competitor" to analyze a company and add it to your intelligence database'})]}),e.jsxs(R,{children:[J?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(Y,{className:"h-6 w-6 animate-spin mr-2"}),e.jsx("span",{className:"text-muted-foreground",children:"Searching the web..."})]}):_.length>0?e.jsx("div",{className:"space-y-3",children:_.map((s,r)=>e.jsxs("div",{className:"flex items-start justify-between gap-4 p-3 rounded-lg border bg-card hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-medium truncate",children:s.title}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:s.description}),e.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1 mt-1",children:[e.jsx(Te,{className:"h-3 w-3"}),s.url]})]}),e.jsxs(P,{size:"sm",onClick:()=>Ye(s),disabled:b===s.url,children:[b===s.url?e.jsx(Y,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(qe,{className:"h-4 w-4 mr-1"}),"Add Competitor"]})]},r))}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No results found. Try a different search term."}),e.jsx("div",{className:"flex justify-end mt-4",children:e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>N(!1),children:"Close Web Results"})})]})]}),e.jsx("div",{id:"competitor-dossiers",children:he.length===0?e.jsx(D,{className:"border-dashed",children:e.jsxs(R,{className:"py-16 text-center",children:[e.jsx("div",{className:"h-16 w-16 rounded-xl bg-muted/50 flex items-center justify-center mx-auto mb-4",children:e.jsx(fs,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Intelligence Files"}),e.jsx("p",{className:"text-muted-foreground max-w-md mx-auto",children:"Add competitors to proposals to start building your competitive intelligence library. Each encounter enriches your strategic database."})]})}):W==="card"?e.jsx("div",{className:"space-y-4",children:he.map(s=>e.jsx(Oe,{competitor:s,isExpanded:v===s.id,onToggle:()=>C(v===s.id?null:s.id),onGeneratePositioning:()=>Ae(s),isGenerating:m===s.id,onGeneratePlaybook:()=>De(s),isGeneratingPlaybook:d===s.id,defensivePlaybook:S[s.id]||null,streamingContent:F[s.id]},s.id))}):e.jsxs(D,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 border-b px-4 py-2",children:e.jsx("span",{className:"text-caption font-mono uppercase tracking-widest text-muted-foreground",children:"COMPETITOR REGISTRY"})}),e.jsx(bs,{className:"w-full",children:e.jsxs(js,{children:[e.jsx(ws,{children:e.jsxs(Ne,{className:"bg-muted/20",children:[e.jsx(ae,{className:"font-mono text-xs uppercase tracking-wider",children:"Company"}),e.jsx(ae,{className:"font-mono text-xs uppercase tracking-wider",children:"Industry"}),e.jsx(ae,{className:"font-mono text-xs uppercase tracking-wider text-center",children:"Encounters"}),e.jsx(ae,{className:"font-mono text-xs uppercase tracking-wider text-center",children:"Threats"}),e.jsx(ae,{className:"font-mono text-xs uppercase tracking-wider text-center",children:"Vulnerabilities"}),e.jsx(ae,{className:"font-mono text-xs uppercase tracking-wider",children:"Last Intel"})]})}),e.jsx(Ns,{children:he.map(s=>e.jsxs(ns.Fragment,{children:[e.jsxs(Ne,{className:z("cursor-pointer hover:bg-muted/30 transition-colors",v===s.id&&"bg-muted/20"),onClick:()=>C(v===s.id?null:s.id),children:[e.jsx(Z,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-destructive/10 flex items-center justify-center flex-shrink-0",children:e.jsx(pe,{className:"h-4 w-4 text-destructive"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:s.company_name}),s.website&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:s.website.replace(/^https?:\/\//,"")})]})]})}),e.jsx(Z,{children:e.jsx("span",{className:"text-sm",children:_s(s.industry)||"â"})}),e.jsx(Z,{className:"text-center",children:s.proposal_count?e.jsx(G,{variant:"outline",className:"font-mono",children:s.proposal_count}):e.jsx("span",{className:"text-muted-foreground",children:"â"})}),e.jsx(Z,{className:"text-center",children:e.jsx(G,{variant:"outline",className:"border-destructive/30 text-destructive font-mono",children:s.strengths.length})}),e.jsx(Z,{className:"text-center",children:e.jsx(G,{variant:"outline",className:"border-success/30 text-success font-mono",children:s.weaknesses.length})}),e.jsx(Z,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:s.last_scraped_at?Ue(new Date(s.last_scraped_at),"yyyy-MM-dd"):"â"}),e.jsx(ke,{to:`/intelligence/competitive/${s.id}`,onClick:r=>r.stopPropagation(),children:e.jsx(P,{variant:"ghost",size:"icon",className:"h-7 w-7","aria-label":"View",children:e.jsx(Be,{className:"h-4 w-4"})})}),e.jsx(Fe,{className:z("h-4 w-4 text-muted-foreground transition-transform",v===s.id&&"rotate-180")}
17)]})})]}),v===s.id&&e.jsx(Ne,{className:"bg-muted/10 hover:bg-muted/10",children:e.jsx(Z,{colSpan:6,className:"p-0",children:e.jsx(Oe,{competitor:s,isExpanded:!0,onToggle:()=>C(null),onGeneratePositioning:()=>Ae(s),isGenerating:m===s.id,onGeneratePlaybook:()=>De(s),isGeneratingPlaybook:d===s.id,defensivePlaybook:S[s.id]||null,streamingContent:F[s.id]})})})]},s.id))})]})})]})})]})}export{Pt as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.