PageSourceSearch

https://trybrain.io/assets/_authenticated.clients-CIQFeEcj.js

js trybrain.io collected 2026-09-24 15:05:48 UTC 150,515 bytes, 2 lines download raw bytes

1import{y as Ne,z as L,D as A,E as U,au as ae,e as $,r as v,f as J,K,al as _,j as e,k as O,$ as St,I as Z,B as C,bm as st,C as se,a as ue,b as he,c as nt,d as ne,am as xe,c8 as be,an as ge,ao as je,ap as pe,aq as ve,ab as V,ac as W,ad as Y,ae as G,af as M,as as we,aE as kt,at as Se,h as Qe,b_ as Ue,cg as _t,aN as Ft,bi as He,a5 as ze,aJ as qe,dm as es,N as de,i as at,bv as $t,bw as Mt,bx as Dt,by as Pt,bz as Tt,bA as qt,bB as Et,bC as Ot,ak as $e,az as Re,aA as Ie,aB as ee,aC as te,ay as ts,S as ss,cU as Lt,L as ns,P as as,eT as is}from"./index-DHwBXtP2.js";import{u as rs,F as ls}from"./FilterPresetBar-DoRtQ0_h.js";import{s as os,g as it,r as At,d as cs,a as ds}from"./clients.functions-X2jvOsIP.js";import{a as ms,D as us}from"./DuplicateClientsPanel-BkoxTdZL.js";import{S as hs}from"./separator-C1UieVNp.js";import{S as xs}from"./search-Cl67PjLD.js";import{U as Ut}from"./user-check-CFtJ1L1k.js";import{U as gs}from"./upload-D6q4E55j.js";import{B as Rt}from"./building-2-xDElWjUt.js";import{F as ps}from"./file-text-CzX-qSj6.js";import{Q as rt}from"./quote-CrVq_lXE.js";import{U as Me}from"./users-Cd2QSwK4.js";import{C as fs}from"./clock-Rzb6aUHV.js";import{T as It}from"./timer-DyoLSnLZ.js";import{E as js}from"./eye-off-DsgAiuJq.js";import{T as vs}from"./trending-up-BjyiYEVM.js";import{H as ys}from"./history-DdO_7tcu.js";import{U as Ns}from"./undo-2-AHg6Dlwc.js";import{I as bs}from"./inbox-rIGfZx91.js";import{C as Kt}from"./credit-card-CLqCDBfS.js";import{P as ws}from"./phone-call-C7561n5Q.js";import{D as Cs}from"./download-Dm0Bb9aW.js";import{R as Ss}from"./rotate-ccw-BX_fy5UX.js";import{g as ks,m as _s,s as Fs,c as $s,a as Ms}from"./clients-unmapped.functions-daX2Uhgc.js";import{C as Bt}from"./calendar-clock-mAoTkiAu.js";import{L as Ds}from"./link-2-CcwU8aas.js";import"./useRouterState-B72FMm8a.js";import"./arrow-right-Ck7Z4gCN.js";const Ps=[["path",{d:"m16 3 4 4-4 4",key:"1x1c3m"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"m8 21-4-4 4-4",key:"h9nckh"}],["path",{d:"M4 17h16",key:"g4d7ey"}]],Ts=Ne("arrow-right-left",Ps);const qs=[["path",{d:"M11 14h2a2 2 0 0 0 0-4h-3c-.6 0-1.1.2-1.4.6L3 16",key:"1v1a37"}],["path",{d:"m14.45 13.39 5.05-4.694C20.196 8 21 6.85 21 5.75a2.75 2.75 0 0 0-4.797-1.837.276.276 0 0 1-.406 0A2.75 2.75 0 0 0 11 5.75c0 1.2.802 2.248 1.5 2.946L16 11.95",key:"fhfbnt"}],["path",{d:"m2 15 6 6",key:"10dquu"}],["path",{d:"m7 20 1.6-1.4c.3-.4.8-.6 1.4-.6h4c1.1 0 2.1-.4 2.8-1.2l4.6-4.4a1 1 0 0 0-2.75-2.91",key:"1x6kdw"}]],Es=Ne("hand-heart",qs);const Os=[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]],Ls=Ne("layout-grid",Os);const As=[["path",{d:"M9 17H7A5 5 0 0 1 7 7",key:"10o201"}],["path",{d:"M15 7h2a5 5 0 0 1 4 8",key:"1d3206"}],["line",{x1:"8",x2:"12",y1:"12",y2:"12",key:"rvw6j4"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]],Us=Ne("link-2-off",As);const Rs=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],Is=Ne("list",Rs);const Ks=[["path",{d:"M22 10.5V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h12.5",key:"e61zoh"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M20 14v4",key:"1hm744"}],["path",{d:"M20 22v.01",key:"12bgn6"}]],Bs=Ne("mail-warning",Ks);const Hs=[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]],zs=Ne("repeat",Hs);const Qs=[["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m14.305 16.53.923-.382",key:"1itpsq"}],["path",{d:"m15.228 13.852-.923-.383",key:"eplpkm"}],["path",{d:"m16.852 12.228-.383-.923",key:"13v3q0"}],["path",{d:"m16.852 17.772-.383.924",key:"1i8mnm"}],["path",{d:"m19.148 12.228.383-.923",key:"1q8j1v"}],["path",{d:"m19.53 18.696-.382-.924",key:"vk1qj3"}],["path",{d:"m20.772 13.852.924-.383",key:"n880s0"}],["path",{d:"m20.772 16.148.924.383",key:"1g6xey"}],["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],Ht=Ne("user-cog",Qs);const Vs=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]],Ke=Ne("user-minus",Vs),Ws=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-risk_functions_ts--explainClientRisk_createServerFn_handler")),Ys=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-risk_functions_ts--removeClientRiskExplanation_createServerFn_handler")),Gs=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-identity_functions_ts--findClientByOneIdentifier_createServerFn_handler")),Xs=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-identity_functions_ts--listIdentifiersForClient_createServerFn_handler")),Zs=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-identity_functions_ts--addIdentifierToClient_createServerFn_handler")),zt=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-identity_functions_ts--removeIdentifierFromClient_createServerFn_handler")),Js=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-mapping_functions_ts--getClientMapping_createServerFn_handler")),en=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-mapping_functions_ts--bulkAssignClients_createServerFn_handler")),tn=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-mapping_functions_ts--moveClientBook_createServerFn_handler")),sn=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-mapping_functions_ts--getClientMappingHistory_createServerFn_handler")),nn=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-mapping_functions_ts--revertClientMappingChange_createServerFn_handler")),an=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-mapping_functions_ts--findClientOutsideMyBook_createServerFn_handler")),Qt=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-mapping_functions_ts--searchClientsByNameFn_createServerFn_handler")),rn={email:"email",phone:"phone",domain:"domain",stripe_customer:"stripe",lead_event:"lead"};function ln({workspaceId:t,clientId:s}){const a=ae(),l=$(Xs),m=$(Zs),o=$(zt),[c,r]=v.useState(""),i=["client-identifiers",t,s],{data:x,isLoading:p}=J({queryKey:i,queryFn:()=>l({data:{workspaceId:t,clientId:s}})}),j=n=>{const d=n.trim().toLowerCase();return d?d.includes("@")?"email":d.startsWith("cus_")?"stripe_customer":d.replace(/\D/g,"").length>=10?"phone":d.includes(".")?"domain":null:null},u=K({mutationFn:async n=>{const d=j(n);
1if(!d)throw new Error("Enter an email, phone number, company domain or Stripe customer id");return m({data:{workspaceId:t,clientId:s,kind:d,value:n.trim()}})},onSuccess:()=>{r(""),_.success("Identifier saved — future activity will match automatically"),a.invalidateQueries({queryKey:i})},onError:n=>_.error(n.message)}),h=K({mutationFn:n=>o({data:{workspaceId:t,clientId:s,identifierId:n}}),onSuccess:()=>{a.invalidateQueries({queryKey:i})},onError:n=>_.error(n.message)});return e.jsxs("div",{className:"space-y-2 border-t pt-3",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Known identifiers"}),p?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading…"}):(x?.length??0)===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"None yet — add one so this client stops needing manual mapping."}):e.jsx("div",{className:"flex flex-wrap gap-1.5",children:x.map(n=>e.jsxs(O,{variant:"secondary",className:"gap-1 font-mono text-[11px]",children:[e.jsx("span",{className:"font-sans text-muted-foreground",children:rn[n.kind]??n.kind}),n.value,e.jsx("button",{type:"button","aria-label":`Remove ${n.value}`,onClick:()=>h.mutate(n.id),className:"ml-0.5 opacity-60 hover:opacity-100",children:e.jsx(St,{className:"h-3 w-3"})})]},n.id))}),e.jsxs("form",{className:"flex gap-2",onSubmit:n=>{n.preventDefault(),u.mutate(c)},children:[e.jsx(Z,{value:c,onChange:n=>r(n.target.value),placeholder:"Add email, phone, domain or cus_…","aria-label":"New identifier",className:"h-8 text-xs"}),e.jsxs(C,{type:"submit",size:"sm",variant:"outline",disabled:u.isPending||!c.trim(),children:[e.jsx(st,{className:"mr-1 h-3.5 w-3.5"})," Add"]})]})]})}const on={email:"email address",phone:"phone number",domain:"company domain",stripe_customer:"Stripe customer",lead_event:"CRM lead"},cn={contact_email:"matched on contact email",contact_phone:"matched on phone number",client_domain:"matched on company domain",lead_link:"matched on CRM lead",stripe_customer:"matched on Stripe customer",participant_name:"matched on attendee name",manual:"mapped by hand",none:"no match"};function lt({workspaceId:t}){const[s,a]=v.useState(""),l=$(Gs),m=$(Qt),o=K({mutationFn:async i=>{const[x,p]=await Promise.all([l({data:{workspaceId:t,query:i}}),m({data:{workspaceId:t,query:i}})]);return{byIdentifier:x,byName:p}}}),c=o.data?.byIdentifier,r=o.data?.byName;return e.jsxs(se,{children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs(he,{className:"flex items-center gap-2 text-base",children:[e.jsx(xs,{className:"h-4 w-4"})," Find a client"]}),e.jsx(nt,{children:"A client name, email, phone number, company domain, Stripe customer id or CRM lead id is enough. You get the client plus its strategist and Head of Strategy — or a straight answer that the card sits in someone else’s book, or was never added."})]}),e.jsxs(ne,{className:"space-y-3",children:[e.jsxs("form",{className:"flex gap-2",onSubmit:i=>{i.preventDefault(),s.trim().length>=2&&o.mutate(s.trim())},children:[e.jsx(Z,{value:s,onChange:i=>a(i.target.value),placeholder:"Brian Kelly · [email protected] · (415) 555-0134 · acme.com · cus_123","aria-label":"Client name or identifier"}),e.jsx(C,{type:"submit",disabled:o.isPending||s.trim().length<2,children:o.isPending?"Looking…":"Find"})]}),o.isError?e.jsx("p",{className:"text-sm text-destructive",children:o.error.message}):null,c?.client?e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[c.kind?e.jsx(O,{variant:"secondary",children:on[c.kind]}):null,c.normalized?e.jsx("code",{className:"font-mono",children:c.normalized}):null,e.jsx("span",{children:cn[c.method]??c.method})]}),c.client?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:c.client.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.client.primaryDomain??"no company domain saved",c.client.status?` · ${c.client.status}`:""]})]}),e.jsx("div",{className:"space-y-1",children:c.owners.length===0&&!c.chainHeadOfStrategy?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No strategist or Head of Strategy assigned yet."}):[...c.owners,...c.chainHeadOfStrategy?[c.chainHeadOfStrategy]:[]].map(i=>e.jsxs("p",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Ut,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"capitalize",children:i.role.replace(/_/g," ")}),e.jsx("span",{className:"text-muted-foreground",children:i.name??i.email??i.userId})]},`${i.role}:${i.userId}`))}),e.jsx(ln,{workspaceId:t,clientId:c.client.id})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:c.reason??"No client carries this identifier yet."})]}):null,r&&!c?.client?e.jsxs("div",{className:"space-y-2 rounded-md border p-3 text-sm",children:[r.inBook.length>0?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium",children:"In your book by that name"}),r.inBook.map(i=>e.jsxs("p",{className:"text-muted-foreground",children:[i.name,i.primaryDomain?` · ${i.primaryDomain}`:""]},i.clientId))]}):null,r.outsideBook.length>0?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium",children:"Found outside your book"}),r.outsideBook.map(i=>e.jsxs("p",{className:"text-muted-foreground",children:[i.name,i.primaryDomain?` · ${i.primaryDomain}`:""," — held by ",i.ownerLabel," (matched on ",i.matchedOn,"). Ask an admin to move it to you."]},i.clientId))]}):null,r.inBook.length===0&&r.outsideBook.length===0?e.jsx("p",{className:"text-muted-foreground",children:r.existsAnywhere?"A card matching this exists but you cannot see it — ask an admin.":"Nothing by that name, website, email or phone exists anywhere in this workspace, so this client was never added."}):null]}):null]})]})}const Vt=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-owners_functions_ts--listOwnerCandidates_createServerFn_handler")),dn=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-owners_functions_ts--setClientOwners_createServerFn_handler")),mn=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-owners_functions_ts--requestOwnershipRemoval_createServerFn_handler")),un=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-owners_functions_ts--listUnownedPool_createServerFn_handler")),hn=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-owners_functions_ts--claimClientFromPool_createServerFn_handler"));L({method:"POST"}).middleware([A]).handler(U("src_lib_client-owners_functions_ts--listOwnershipRemovals_createServerFn_handler"));L({method:"POST"}).middleware([A]).handler(U("src_lib_client-owners_functions_ts--resolveOwnershipRemoval_createServerFn_handler"));const re="__none__";function xn({workspaceId:t,clientId:s,clientName:a,currentStrategistUserId:l,currentHosUserId:m,currentAccountOwnerUserId:o}){const c=ae(),[r,i]=v.useState(!1),[x,p]=v.useState(l??re),[j,u]=v.useState(m??re),[h,n]=v.useState(o??re),d=$(Vt),T=$(dn),{data:f}=J({queryKey:["owner-candidates",t],queryFn:()=>d({data:{workspaceId:t}}),enabled:r,staleTime:300*1e3}),b=K({mutationFn:()=>T({data:{workspaceId:t,clientId:s,strategistUserId:x===re?null:x,hosUserId:j===re?null:j,accountOwnerUserId:h===re?null:h}}),onSuccess:()=>{_.success("Ownership updated"),i(!1),c.invalidateQueries({queryKey:["client-book"]}),c.invalidateQueries({queryKey:["client-chain-rollup"]}),c.invalidateQueries({queryKey:["client-owner-suggestions"]})},onError:F=>_.error(F instanceof Error?F.message:"Could not update ownership")}),q=f??[],D=q.filter(F=>F.isHos);return e.jsxs(xe,{open:r,onOpenChange:F=>{i(F),F&&(p(l??re),u(m??re),n(o??re))},children:[e.jsx(be,{asChild:!0,children:e.jsxs(C,{variant:"outline",size:"sm",className:"h-7 px-2 text-xs",children:[e.jsx(Ht,{className:"mr-1 h-3.5 w-3.5"}),"Edit owners"]})}),e.jsxs(ge,{children:[e.jsxs(je,{children:[e.jsxs(pe,{children:["Ownership · ",a]}),e.jsx(ve,{children:"Set who owns this client. This overrides anything Brain inferred from meetings or email."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Account owner"}),e.jsxs(V,{value:h,onValueChange:n,children:[e.jsx(W,{children:e.jsx(Y,{placeholder:"Follows the strategist"})}),e.jsxs(G,{children:[e.jsx(M,{value:re,children:"Follows the strategist"}),q.filter(F=>F.userId===x||F.userId===j).map(F=>e.jsx(M,{value:F.userId,children:F.name},F.userId))]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"The account owner is always the strategist or the Head of Strategy on this client. Change the strategist below and the account owner moves with it, so the client leaves the old owner's list."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Strategist"}),e.jsxs(V,{value:x,onValueChange:F=>{p(F),h!==re&&h!==F&&h!==j&&n(re)},children:[e.jsx(W,{children:e.jsx(Y,{placeholder:"Unassigned"})}),e.jsxs(G,{children:[e.jsx(M,{value:re,children:"Unassigned"}),q.map(F=>e.jsxs(M,{value:F.userId,children:[F.name,F.isStrategist?" · strategist":""]},F.userId))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Head of Strategy"}),e.jsxs(V,{value:j,onValueChange:u,children:[e.jsx(W,{children:e.jsx(Y,{placeholder:"Unassigned"})}),e.jsxs(G,{children:[e.jsx(M,{value:re,children:"Unassigned"}),(D.length?D:q).map(F=>e.jsxs(M,{value:F.userId,children:[F.name,F.isHos?" · HoS":""]},F.userId))]})]})]})]}),e.jsxs(we,{children:[e.jsx(C,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(C,{onClick:()=>b.mutate(),disabled:b.isPending,children:b.isPending?"Saving…":"Save ownership"})]})]})]})}function Wt({workspaceId:t,clientId:s,clientName:a,churned:l=!1,compact:m=!1}){const o=ae(),[c,r]=v.useState(!1),[i,x]=v.useState(""),p=$(mn),j=K({mutationFn:()=>p({data:{workspaceId:t,clientId:s,note:i.trim()||void 0}}),onSuccess:()=>{_.success(l?"Taken off your churned list — an admin can still see the account":"Removed from your list — it is now in the unowned pool"),r(!1),x(""),o.invalidateQueries({queryKey:["client-book"]}),o.invalidateQueries({queryKey:["churned-clients"]}),o.invalidateQueries({queryKey:["client-chain-rollup"]}),o.invalidateQueries({queryKey:["ownership-removals"]}
1),o.invalidateQueries({queryKey:["client-pool"]})},onError:u=>_.error(u instanceof Error?u.message:"Could not remove this client")});return e.jsxs(xe,{open:c,onOpenChange:r,children:[e.jsx(be,{asChild:!0,children:m?e.jsx(C,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Not my client — take it off my list",children:e.jsx(Ke,{className:"h-3.5 w-3.5"})}):e.jsxs(C,{variant:"outline",size:"sm",className:"h-7 px-2 text-xs",children:[e.jsx(Ke,{className:"mr-1 h-3.5 w-3.5"}),"Not my client"]})}),e.jsxs(ge,{children:[e.jsxs(je,{children:[e.jsxs(pe,{children:["Remove ",a," from your list?"]}),e.jsx(ve,{children:l?"This account has already left. Taking it off your list only stops it showing on your Churned board. Its history is kept, admins keep seeing it, and nobody else's view changes.":"You come off this account right away and it goes into the unowned pool, where any Head of Strategy can pick it up. If you are the Head of Strategy, the strategist under you comes off it too. Nothing is deleted."})]}),e.jsx(kt,{value:i,onChange:u=>x(u.target.value),placeholder:l?"Optional: why is this not yours?":"Optional: who should own this instead?",rows:3}),e.jsxs(we,{children:[e.jsx(C,{variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(C,{onClick:()=>j.mutate(),disabled:j.isPending,children:j.isPending?"Removing…":"Remove from my list"})]})]})]})}const gn=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-transcript-upload_functions_ts--uploadClientTranscript_createServerFn_handler")),pn=["failed to fetch","load failed","networkerror","network request failed","err_network","err_internet_disconnected","connection closed","the network connection was lost","fetch failed"];function fn(t){const s=(t instanceof Error?t.message:String(t??"")).toLowerCase();return s?pn.some(a=>s.includes(a)):!1}function Je(t,s){if(fn(t)){const l=typeof navigator<"u"&&navigator.onLine===!1?"You're offline, so Brain never received this.":"Brain couldn't be reached — the connection dropped before this request arrived.";return s?.action?`${l} ${s.action} was not saved. Check your internet and try again.`:`${l} Nothing on this screen is up to date. Check your internet and reload.`}return t instanceof Error&&t.message?t.message:"Something went wrong. Please try again."}const jn=/\.(txt|md|csv|tsv|json|vtt|srt|html?)$/i,vn=/\.(pdf|docx)$/i;function yn(t){const s=new Uint8Array(t);let a="";const l=32768;for(let m=0;m<s.length;m+=l)a+=String.fromCharCode(...s.subarray(m,m+l));return btoa(a)}function et({workspaceId:t,clientId:s,clientName:a}){const l=ae(),m=$(gn),o=v.useRef(null),[c,r]=v.useState(!1),[i,x]=v.useState(""),[p,j]=v.useState(""),[u,h]=v.useState(""),[n,d]=v.useState(!1),[T,f]=v.useState(null);v.useEffect(()=>{if(!T)return;const F=setTimeout(()=>f(null),Math.max(0,T-Date.now())),N=setInterval(()=>{l.invalidateQueries({queryKey:["client-book"]})},8e3);return()=>{clearTimeout(F),clearInterval(N)}},[T,l]);const b=F=>{_.success(F),r(!1),h(""),x(""),j(""),f(Date.now()+15e4),l.invalidateQueries({queryKey:["client-book"]}),l.invalidateQueries({queryKey:["voc-coverage",t]})},q=async()=>{if(u.trim().length<40){_.error("Paste the full conversation — that is too short to read.");return}d(!0);try{await m({data:{workspaceId:t,clientId:s,label:i.trim()||`${a} call`,text:u,...p?{meetingDate:p}:{}}}),b("Transcript saved — the health score is being recalculated.")}catch(F){_.error(Je(F,{action:"This transcript"}),{duration:8e3})}finally{d(!1)}},D=async F=>{const N=Array.from(F??[]);if(N.length===0)return;d(!0);let I=0;const g=[];for(const P of N)try{if(vn.test(P.name))await m({data:{workspaceId:t,clientId:s,fileName:P.name,base64:yn(await P.arrayBuffer()),label:i.trim()||P.name,...p?{meetingDate:p}:{}}});else if(jn.test(P.name)||P.type.startsWith("text/"))await m({data:{workspaceId:t,clientId:s,fileName:P.name,text:await P.text(),label:i.trim()||P.name,...p?{meetingDate:p}:{}}});else{g.push(`${P.name} (unsupported file)`);continue}I+=1}catch(z){g.push(`${P.name} — ${Je(z,{action:"It"})}`)}d(!1),o.current&&(o.current.value=""),I>0&&b(`Added ${I} transcript${I===1?"":"s"} — recalculating the score.`),g.length>0&&_.error(`Not saved: ${g.slice(0,3).join(" · ")}`,{duration:8e3})};return e.jsxs(xe,{open:c,onOpenChange:r,children:[e.jsx(be,{asChild:!0,children:e.jsx(C,{size:"sm",variant:"outline",className:"h-7 text-xs",children:T?e.jsxs(e.Fragment,{children:[e.jsx(Se,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"})," Recalculating the score…"]}):e.jsxs(e.Fragment,{children:[e.jsx(gs,{className:"mr-1.5 h-3.5 w-3.5"})," Upload transcript"]})})}),e.jsxs(ge,{className:"max-w-lg",children:[e.jsxs(je,{children:[e.jsxs(pe,{children:["Upload a call transcript · ",a]}),e.jsx(ve,{children:"For calls held on the client's own Zoom, Teams or phone bridge. Brain reads it like any other call: it counts towards this client's health score, evidence quotes and plays."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Qe,{htmlFor:"ctu-label",className:"text-xs",children:"Call name"}),e.jsx(Z,{id:"ctu-label",value:i,onChange:F=>x(F.target.value),placeholder:`${a} — monthly review`,className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Qe,{htmlFor:"ctu-date",className:"text-xs",children:"Call date"}),e.jsx(Z,{id:"ctu-date",type:"date",value:p,onChange:F=>j(F.target.value),className:"h-8 text-xs"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Qe,{htmlFor:"ctu-text",className:"text-xs",children:"Paste the transcript"}),e.jsx(kt,{id:"ctu-text",value:u,onChange:F=>h(F.target.value),rows:8,placeholder:"Paste the transcript or meeting notes here…",className:"text-xs"})]}),e.jsxs("div",{className:"rounded-md border border-dashed p-3 text-xs text-muted-foreground",children:["Or upload a file — .txt, .vtt, .srt, .docx or .pdf.",e.jsx("input",{ref:o,type:"file",multiple:!0,accept:".txt,.md,.csv,.tsv,.json,.vtt,.srt,.html,.htm,.pdf,.docx",className:"mt-2 block w-full text-xs",disabled:n,onChange:F=>{D(F.target.files)}})]})]}),e.jsxs(we,{children:[e.jsx(C,{variant:"ghost",size:"sm",onClick:()=>r(!1),disabled:n,children:"Cancel"}),e.jsx(C,{size:"sm",onClick:()=>{q()},disabled:n||u.trim().length<40,children:n?"Saving…":"Save transcript"})]})]})]})}function Nn({workspaceId:t,clientId:s,clientName:a,isAgency:l,servesNiche:m}){const o=ae(),[c,r]=v.useState(!1),[i,x]=v.useState(l?"agency":"direct"),[p,j]=v.useState(m??""),u=$(os),h=K({mutationFn:()=>u({data:{workspaceId:t,clientId:s,isAgency:i==="agency",servesNiche:p.trim()?p.trim():null}}),onSuccess:()=>{_.success("Client profile updated"),r(!1),o.invalidateQueries({queryKey:["client-book"]}),o.invalidateQueries({queryKey:["growth-hub"]}),o.invalidateQueries({queryKey:["suggested-plays"]})},onError:n=>_.error(n instanceof Error?n.message:"Could not update the profile")});return e.jsxs(xe,{open:c,onOpenChange:n=>{r(n),n&&(x(l?"agency":"direct"),j(m??""))},children:[e.jsx(be,{asChild:!0,children:e.jsxs(C,{variant:"outline",size:"sm",className:"h-7 px-2 text-xs",children:[e.jsx(Rt,{className:"mr-1 h-3.5 w-3.5"}),m?`Serves ${m}`:"Who they serve"]})}),e.jsxs(ge,{children:[e.jsxs(je,{children:[e.jsxs(pe,{children:["Who they are · ",a]}),e.jsx(ve,{children:"Brain uses this when it picks plays to pitch and writes the brief, so an example from another niche gets translated instead of dism
1issed."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Type of business"}),e.jsxs(V,{value:i,onValueChange:x,children:[e.jsx(W,{children:e.jsx(Y,{})}),e.jsxs(G,{children:[e.jsx(M,{value:"agency",children:"Agency — sells services to its own clients"}),e.jsx(M,{value:"direct",children:"Direct business — sells to end customers"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:i==="agency"?"The clients they serve":"Their customers"}),e.jsx(Z,{value:p,onChange:n=>j(n.target.value),placeholder:"e.g. lash salons, dentists, roofers, B2B SaaS"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank if you are not sure — Brain will work it out from their calls."})]})]}),e.jsxs(we,{children:[e.jsx(C,{variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(C,{onClick:()=>h.mutate(),disabled:h.isPending,children:h.isPending?"Saving…":"Save"})]})]})]})}const bn=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-contacts_functions_ts--listClientContacts_createServerFn_handler")),wn=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-contacts_functions_ts--saveClientContact_createServerFn_handler")),Cn=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-contacts_functions_ts--deleteClientContactFn_createServerFn_handler")),Sn={contactId:null,name:"",email:"",phone:"",title:""};function kn({workspaceId:t,clientId:s,clientName:a}){const l=ae(),[m,o]=v.useState(!1),[c,r]=v.useState(null),i=$(bn),x=$(wn),p=$(Cn),j=["client-contacts",t,s],{data:u,isLoading:h}=J({queryKey:j,queryFn:()=>i({data:{workspaceId:t,clientId:s}}),enabled:m}),n=()=>{l.invalidateQueries({queryKey:j}),l.invalidateQueries({queryKey:["client-book"]}),l.invalidateQueries({queryKey:["client-identifiers",t,s]})},d=K({mutationFn:b=>
1x({data:{workspaceId:t,clientId:s,contactId:b.contactId,name:b.name,email:b.email,phone:b.phone,title:b.title}}),onSuccess:()=>{_.success("Contact saved — future meetings and emails will follow this address"),r(null),n()},onError:b=>_.error(b.message)}),T=K({mutationFn:b=>p({data:{workspaceId:t,clientId:s,contactId:b}}),onSuccess:()=>{_.success("Contact removed"),n()},onError:b=>_.error(b.message)}),f=b=>r({contactId:b.id,name:b.name??"",email:b.email??"",phone:b.phone??"",title:b.title??""});return e.jsxs(xe,{open:m,onOpenChange:b=>{o(b),b||r(null)},children:[e.jsx(be,{asChild:!0,children:e.jsxs(C,{variant:"outline",size:"sm",className:"h-7 px-2 text-xs",children:[e.jsx(Ue,{className:"mr-1 h-3.5 w-3.5"})," Edit contacts"]})}),e.jsxs(ge,{className:"max-w-lg",children:[e.jsxs(je,{children:[e.jsxs(pe,{className:"text-base",children:["Contacts · ",a]}),e.jsx(ve,{className:"text-xs",children:"Fix a wrongly-mapped email here. The corrected address takes over identity matching straight away; the old one stops matching."})]}),e.jsxs("div",{className:"space-y-2",children:[h?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading…"}):(u?.length??0)===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No contacts on this client yet."}):u.map(b=>e.jsx("div",{className:"rounded-md border p-2 text-xs",children:c?.contactId===b.id?e.jsx(ot,{draft:c,setDraft:r,onCancel:()=>r(null),onSave:()=>d.mutate(c),busy:d.isPending}):e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"font-medium",children:b.name||"Unnamed contact"}),b.isPrimary?e.jsx(O,{variant:"secondary",className:"text-[10px]",children:"primary"}):null,b.needsReview?e.jsx(O,{variant:"outline",className:"text-[10px] text-destructive",children:"needs review"}):null]}),e.jsxs("div",{className:"mt-0.5 break-all font-mono text-[11px] text-muted-foreground",children:[b.email||"no email",b.phone?` · ${b.phone}`:""]})]}),e.jsxs("div",{className:"flex shrink-0 gap-1",children:[e.jsx(C,{size:"icon",variant:"ghost",className:"h-7 w-7","aria-label":`Edit ${b.email||b.name||"contact"}`,onClick:()=>f(b),children:e.jsx(_t,{className:"h-3.5 w-3.5"})}),e.jsx(C,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive","aria-label":`Remove ${b.email||b.name||"contact"}`,disabled:T.isPending,onClick:()=>T.mutate(b.id),children:e.jsx(Ft,{className:"h-3.5 w-3.5"})})]})]})},b.id)),c&&c.contactId===null?e.jsx("div",{className:"rounded-md border p-2 text-xs",children:e.jsx(ot,{draft:c,setDraft:r,onCancel:()=>r(null),onSave:()=>d.mutate(c),busy:d.isPending})}):e.jsxs(C,{size:"sm",variant:"outline",className:"h-7 px-2 text-xs",onClick:()=>r({...Sn}),children:[e.jsx(st,{className:"mr-1 h-3.5 w-3.5"})," Add contact"]})]})]})]})}function ot({draft:t,setDraft:s,onCancel:a,onSave:l,busy:m}){return e.jsxs("form",{className:"space-y-2",onSubmit:o=>{o.preventDefault(),l()},children:[e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(Z,{value:t.name,onChange:o=>s({...t,name:o.target.value}),placeholder:"Full name","aria-label":"Contact name",className:"h-8 text-xs"}),e.jsx(Z,{value:t.title,onChange:o=>s({...t,title:o.target.value}),placeholder:"Title (optional)","aria-label":"Contact title",className:"h-8 text-xs"}),e.jsx(Z,{value:t.email,onChange:o=>s({...t,email:o.target.value}),placeholder:"[email protected]","aria-label":"Contact email",className:"h-8 text-xs"}),e.jsx(Z,{value:t.phone,onChange:o=>s({...t,phone:o.target.value}),placeholder:"Phone (optional)","aria-label":"Contact phone",className:"h-8 text-xs"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(C,{type:"submit",size:"sm",className:"h-7 px-2 text-xs",disabled:m,children:"Save"}),e.jsx(C,{type:"button",size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:a,children:"Cancel"})]})]})}function _n(t,s,a){const l=`${s} meeting${s===1?"":"s"} and ${a} email thread${a===1?"":"s"}`;return t==="high"?`Read ${l} with plenty of real conversation, so this result is dependable.`:t==="medium"?`Read ${l}. Enough to form a view, but a fresh conversation would firm it up.`:`Only ${l} to go on, and the conversation in them was thin — treat this as a hint, not a verdict.`}function Fn(t){return t==="high"?"border-emerald-500/40 text-emerald-700 dark:text-emerald-400":t==="medium"?"border-amber-500/40 text-amber-700 dark:text-amber-400":"border-muted-foreground
1/40 text-muted-foreground"}function Ve(t){if(!t)return"";const s=new Date(t);return Number.isNaN(s.getTime())?"":s.toLocaleDateString()}function $n(t){const[s,a]=v.useState(!1),{confidence:l,transcriptsUsed:m,emailsUsed:o,sourceDocs:c,quotes:r,ignoredMeetings:i}=t,x=c.map(u=>({doc:u,quotes:r.filter(h=>h.source_id&&h.source_id===u.id||!!h.source_ref&&h.source_ref===u.ref)})),p=r.filter(u=>!x.some(h=>h.quotes.includes(u))),j=m+o;return e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"Evidence behind this result"}),e.jsxs(O,{variant:"outline",className:`text-[10px] ${Fn(l)}`,children:[l," confidence"]}),e.jsxs(O,{variant:"outline",className:"text-[10px]",children:[j," source",j===1?"":"s"," read"]}),e.jsxs(C,{variant:"ghost",size:"sm",className:"ml-auto h-7 px-2 text-[11px]",onClick:()=>a(u=>!u),children:[s?e.jsx(He,{className:"mr-1 h-3.5 w-3.5"}):e.jsx(ze,{className:"mr-1 h-3.5 w-3.5"}),s?"Hide":"Show"," meetings & excerpts"]})]}),e.jsx("div",{className:"mt-1.5 text-xs text-muted-foreground",children:_n(l,m,o)}),e.jsxs("div",{className:"mt-1 text-[11px] text-muted-foreground",children:[t.matchedAllTime," source",t.matchedAllTime===1?"":"s"," matched to this client all-time · mood ",t.sentimentTrend,t.computedAt?` · scored ${new Date(t.computedAt).toLocaleString()}`:""]}),s?e.jsxs("div",{className:"mt-3 space-y-2",children:[x.length===0&&p.length===0?e.jsx("div",{className:"text-xs text-muted-foreground",children:"No individual meetings or threads were recorded for this result. Recompute the client to rebuild the evidence list."}):null,x.map(u=>e.jsxs("div",{className:"rounded-md border p-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[u.doc.type==="email"?e.jsx(Ue,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(ps,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:u.doc.label}),u.doc.occurredAt?e.jsxs("span",{className:"text-muted-foreground",children:["· ",Ve(u.doc.occurredAt)]}):null,e.jsxs(O,{variant:"outline",className:"text-[10px]",children:[u.quotes.length," excerpt",u.quotes.length===1?"":"s"," used"]}),t.workspaceId&&t.onDetach&&u.doc.id?e.jsx(C,{size:"sm",variant:"ghost",className:"ml-auto h-6 px-2 text-[11px]",disabled:t.detachPending,onClick:()=>t.onDetach?.(u.doc.type,u.doc.id),children:"Not this client"}):null]}),u.quotes.length===0?e.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:"Read for context, but nothing from it was quoted in the result."}):e.jsx("ul",{className:"mt-1.5 space-y-1.5",children:u.quotes.map((h,n)=>e.jsxs("li",{className:"text-xs",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-muted-foreground",children:[e.jsx(rt,{className:"h-3 w-3"}),e.jsx("span",{children:h.label||h.kind}),h.source_email?e.jsxs("span",{children:["· from ",h.source_email]}):null]}),e.jsxs("div",{className:"mt-0.5 italic",children:["“",h.quote,"”"]})]},n))})]},u.doc.ref||u.doc.id)),p.length?e.jsxs("div",{className:"rounded-md border p-2",children:[e.jsx("div",{className:"text-xs font-medium",children:"Other excerpts"}),e.jsx("ul",{className:"mt-1.5 space-y-1.5",children:p.map((u,h)=>e.jsxs("li",{className:"text-xs",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-muted-foreground",children:[e.jsx(rt,{className:"h-3 w-3"}),e.jsx("span",{children:u.label||u.kind}),u.source_label?e.jsxs("span",{children:["· ",u.source_label]}):null,u.occurred_at?e.jsxs("span",{children:["· ",Ve(u.occurred_at)]}):null]}),e.jsxs("div",{className:"mt-0.5 italic",children:["“",u.quote,"”"]})]},h))})]}):null,i.length?e.jsxs("div",{className:"rounded-md border border-dashed p-2 text-xs text-muted-foreground",children:[e.jsxs("div",{className:"font-medium text-foreground",children:["Left out: ",i.length," meeting",i.length===1?"":"s"," with empty or too-short audio"]}),e.jsx("ul",{className:"mt-1 space-y-1",children:i.map(u=>e.jsxs("li",{children:[u.label,u.occurredAt?` · ${Ve(u.occurredAt)}`:""," — ",u.reason]},u.id||u.label))})]}):null]}):null]})}function ct(t,s){const a=new Map;for(const l of t){const m=l.owners?.find(r=>r.role===s);if(!m?.userId)continue;const o=m.userId,c=a.get(o);c?c.clients+=1:a.set(o,{name:m.name??"Unnamed",clients:1})}return[...a.entries()].map(([,l])=>({name:l.name,clients:l.clients})).sort((l,m)=>m.clients-l.clients)}function Mn({clients:t}){const s=v.useMemo(()=>{const a=ct(t,"head_of_strategy"),l=ct(t,"strategist");return{hos:a,strat:l}},[t]);return s.hos.length===0&&s.strat.length===0?null:e.jsxs(se,{children:[e.jsxs(ue,{className:"pb-2",children:[e.jsx(he,{className:"text-sm font-medium",children:"Client load by team member"}),e.jsx(nt,{className:"text-xs",children:"How many client accounts each person owns right now."})]}),e.jsxs(ne,{className:"space-y-4 pt-2",children:[e.jsx(dt,{title:"Head of Strategy",rows:s.hos,accentClass:"text-chart-2"}),e.jsx(dt,{title:"Strategists",rows:s.strat,accentClass:"text-chart-1"})]})]})}function dt({title:t,rows:s,accentClass:a}
1){if(s.length===0)return e.jsxs("div",{children:[e.jsx("p",{className:"mb-1 text-xs font-medium text-muted-foreground",children:t}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"No one in this role owns a client yet."})]});const l=s.reduce((o,c)=>o+c.clients,0),m=Math.max(...s.map(o=>o.clients),1);return e.jsxs("div",{children:[e.jsxs("p",{className:"mb-2 flex items-baseline gap-2 text-xs font-medium text-muted-foreground",children:[t,e.jsxs("span",{className:"text-muted-foreground/70",children:[s.length," ",s.length===1?"person":"people"," · ",l," clients"]})]}),e.jsx("div",{className:"grid gap-1.5",style:{gridTemplateColumns:"repeat(auto-fill, minmax(7rem, 1fr))"},children:s.map(o=>{const c=o.clients/m;return e.jsxs("div",{className:"flex items-center justify-between gap-1.5 rounded-md border border-border/50 bg-card/40 px-2 py-1.5",title:`${o.name} — ${o.clients} clients`,children:[e.jsx("span",{className:"min-w-0 flex-1 text-[0.6875rem] leading-tight text-foreground/80 line-clamp-2 break-words",children:o.name}),e.jsx("span",{className:`shrink-0 text-sm font-bold leading-none tabular-nums ${a}`,style:{opacity:.5+c*.5},children:o.clients})]},o.name)})})]})}const Dn=3,Pn=5,Tn=864e5;function qn(t){if(!t)return null;const s=Date.parse(t);return Number.isNaN(s)?null:Math.max(0,Math.floor((Date.now()-s)/Tn))}function Yt(t){return!t.health||t.health.state==="no_evidence"}function En(t){return qn(t.health?.lastContactAt)??t.tenureDays??1}const mt={add_domain:{reason:"No company domain on file — email threads and Meet attendees can't match.",action:"Add domain"},add_email:{reason:"No contact email on file — client email threads can't be found.",action:"Add contact email"},assign_owner:{reason:"No owner assigned — nobody's Google account is supplying transcripts.",action:"Assign owner"},upload_transcript:{reason:"Mapping looks fine but nothing matched. Meeting on the client's own Zoom/Teams? Drop the transcript in.",action:"Upload transcript"},run_analysis:{reason:"Evidence exists but health has never been computed.",action:"Run analysis"}};function On(t){return t.evidenceCounts.transcripts+t.evidenceCounts.emails>0&&!t.health?"run_analysis":t.primaryDomain?t.contacts.some(a=>!!a.email)?t.owners.length===0?"assign_owner":"upload_transcript":"add_email":"add_domain"}function _e(t){const s=En(t),a=Dn-s,l=On(t);return{days:s,dueInDays:a,overdue:a<0,escalated:s>=Pn,fix:l,reason:mt[l].reason,action:mt[l].action,weight:Math.max(t.mrrUsd,1)*Math.max(s,1)}}function Gt(t){return t.dueInDays>0?`due in ${t.dueInDays}d`:t.dueInDays===0?"due today":`${Math.abs(t.dueInDays)}d overdue`}function Ln(t){const s=t.filter(Yt).map(a=>({c:a,s:_e(a)}));return{count:s.length,overdue:s.filter(a=>a.s.overdue).length,escalated:s.filter(a=>a.s.escalated).length,invisibleMrr:s.reduce((a,l)=>a+(l.c.mrrUsd||0),0),nearestDueInDays:s.length?Math.min(...s.map(a=>a.s.dueInDays)):null}}const An=[{key:"red",label:"At risk",hint:"Act this week",accent:"border-t-destructive",chip:"border-destructive/40 bg-destructive/10 text-destructive"},{key:"yellow",label:"Caution",hint:"Watch closely",accent:"border-t-amber-500",chip:"border-amber-500/40 bg-amber-500/10 text-amber-600 dark:text-amber-400"},{key:"green",label:"Healthy",hint:"Look for upside",accent:"border-t-emerald-500",chip:"border-emerald-500/40 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"},{key:"unscored",label:"Blind — fix now",hint:"Brain can't see these accounts",accent:"border-t-destructive",chip:"border-destructive/40 bg-destructive/10 text-destructive"}],Be=t=>t>=1e3?`$${Math.round(t/100)/10}k`:`$${Math.round(t).toLocaleString()}`;function Un(t){const s=t.health?.state==="scored"?t.health.color:null;return s==="red"||s==="yellow"||s==="green"?s:"unscored"}function Rn(t){if(!t)return null;const s=Date.parse(t);return Number.isNaN(s)?null:Math.max(0,Math.floor((Date.now()-s)/864e5))}
1function In({rows:t,workspaceId:s,renderDetail:a}){const[l,m]=v.useState(null),o=v.useMemo(()=>{const r={red:[],yellow:[],green:[],unscored:[]};for(const i of t??[])(r[Un(i)]??=[]).push(i);return r.unscored.sort((i,x)=>_e(x).weight-_e(i).weight),r},[t]),c=t.find(r=>r.id===l)??null;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-4 lg:grid-cols-4",children:An.map(r=>{const i=o[r.key],x=r.key==="unscored",p=i.reduce((h,n)=>h+(n.atRiskUsd||0),0),j=i.reduce((h,n)=>h+(n.mrrUsd||0),0),u=x?i.filter(h=>_e(h).overdue).length:0;return e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:`rounded-t-lg border border-b-0 border-t-2 bg-card px-3 py-2 ${r.accent}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:r.label}),e.jsx(O,{variant:"outline",className:`text-[10px] ${r.chip}`,children:i.length})]}),e.jsxs("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:[r.hint,x?j>0?` · ${Be(j)} invisible${u?` · ${u} overdue`:""}`:u?` · ${u} overdue`:"":r.key!=="green"&&p>0?` · ${Be(p)} at risk`:""]})]}),e.jsx("div",{className:`max-h-[70vh] space-y-2 overflow-y-auto rounded-b-lg border p-2 ${x&&i.length>0?"border-destructive/30 bg-destructive/5":"bg-muted/20"}`,children:i.length===0?e.jsx("div",{className:"px-1 py-6 text-center text-[11px] text-muted-foreground",children:x?"Every client has evidence — nice.":"Nothing here"}):x?i.map(h=>e.jsx(Bn,{c:h,workspaceId:s,onOpen:()=>m(h.id)},h.id)):i.map(h=>e.jsx(Hn,{c:h,onOpen:()=>m(h.id)},h.id))})]},r.key)})}),e.jsx(xe,{open:!!c,onOpenChange:r=>!r&&m(null),children:e.jsx(ge,{className:"max-h-[92vh] max-w-5xl overflow-y-auto p-0",children:c?e.jsxs(e.Fragment,{children:[e.jsx(pe,{className:"sr-only",children:c.name}),e.jsx("div",{className:"p-2 sm:p-4",children:a(c)})]}):null})})]})}function Kn({s:t}){return e.jsxs("span",{className:`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-medium ${t.overdue?"border-destructive/50 bg-destructive/15 text-destructive":"border-amber-500/40 bg-amber-500/10 text-amber-600 dark:text-amber-400"}`,children:[e.jsx(It,{className:"h-3 w-3"}),"Blind ",t.days,"d · ",Gt(t)]})}function Bn({c:t,workspaceId:s,onOpen:a}){const l=_e(t),m=t.owners.find(o=>o.role==="strategist")?.name;return e.jsxs("div",{className:`rounded-lg border bg-card p-3 ${l.overdue?"border-destructive/60":"border-amber-500/40"}`,children:[e.jsxs("button",{type:"button",onClick:a,className:"w-full text-left",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:t.name}),t.primaryDomain?e.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:t.primaryDomain}):null]}),e.jsxs("span",{className:"shrink-0 font-mono text-[11px] text-muted-foreground",children:[Be(t.mrrUsd),"/mo"]})]}),e.jsx("div",{className:"mt-2",children:e.jsx(Kn,{s:l})}),e.jsx("p",{className:"mt-2 text-[11px] leading-snug text-muted-foreground",children:l.reason}),l.escalated?e.jsxs("div",{className:"mt-2 flex items-start gap-1.5 text-[11px] text-destructive",children:[e.jsx(qe,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsx("span",{children:"Escalated to your Head of Strategy"})]}):null,e.jsxs("div",{className:"mt-2 flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(Me,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:m??"unassigned"})]})]}),e.jsx("div",{className:"mt-2 border-t pt-2",children:l.fix==="upload_transcript"?e.jsx(et,{workspaceId:s,clientId:t.id,clientName:t.name}):e.jsx(C,{size:"sm",variant:"secondary",className:"h-7 w-full text-xs",onClick:a,children:l.action})})]})}function Hn({c:t,onOpen:s}){const a=t.health,l=a?.state==="scored",m=t.owners.find(r=>r.role==="strategist")?.name,o=Rn(a?.lastMeetingAt),c=l?(a.churnSignals??[]).find(r=>r.severity==="high"):void 0;return e.jsxs("button",{type:"button",onClick:s,className:"w-full rounded-lg border bg-card p-3 text-left transition-colors hover:border-primary/50",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:t.name}),t.primaryDomain?e.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:t.primaryDomain}):null]}),l?e.jsx("span",{className:"shrink-0 font-mono text-sm font-semibold",children:a.score}):null]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-x-2 gap-y-1 text-[11px] text-muted-foreground",children:[l?e.jsxs("span",{children:[a.churnRiskPct,"% churn"]}):e.jsx("span",{children:"Not scored"}),e.jsxs("span",{children:["MRR ",Be(t.mrrUsd)]}),o!==null?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fs,{className:"h-3 w-3"}),o,"d since meeting"]}):null]}),c?.detail?e.jsxs("div",{className:"mt-2 flex items-start gap-1.5 text-[11px] text-destructive",children:[e.jsx(qe,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsx("span",{className:"line-clamp-2",children:c.detail})]}):null,e.jsxs("div",{className:"mt-2 flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(Me,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:m??"unassigned"})]})]})}const ut=t=>t>=1e3?`$${Math.round(t/100)/10}
1k`:`$${Math.round(t).toLocaleString()}`;function zn({rows:t}){const s=Ln(t);if(s.count===0)return null;const a=t.filter(Yt).map(l=>({c:l,b:_e(l)})).sort((l,m)=>m.b.weight-l.b.weight)[0];return e.jsxs("div",{className:`rounded-lg border p-3 ${s.overdue>0?"border-destructive/60 bg-destructive/10":"border-amber-500/40 bg-amber-500/10"}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(js,{className:`mt-0.5 h-4 w-4 shrink-0 ${s.overdue>0?"text-destructive":"text-amber-600 dark:text-amber-400"}`}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-semibold",children:[ut(s.invisibleMrr),"/mo of client revenue is invisible to Brain"]}),e.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[s.count," account",s.count===1?"":"s"," have no usable meeting or email evidence, so churn risk can't be read."," ",s.overdue>0?`${s.overdue} past the 3-day fix deadline${s.escalated>0?`, ${s.escalated} escalated to your Head of Strategy`:""}.`:"Upload the transcript or fix the mapping to clear them."]})]})]}),s.nearestDueInDays!==null?e.jsxs("div",{className:"flex items-center gap-1.5 rounded border border-border bg-card px-2 py-1 text-xs",children:[e.jsx(It,{className:"h-3.5 w-3.5"}),e.jsxs("span",{className:"font-medium",children:["Next deadline: ",Gt({...a.b,dueInDays:s.nearestDueInDays})]})]}):null]}),a?e.jsxs("div",{className:"mt-2 text-[11px] text-muted-foreground",children:["Biggest gap: ",e.jsx("span",{className:"font-medium text-foreground",children:a.c.name})," —"," ",ut(a.c.mrrUsd),"/mo, blind ",a.b.days,"d · ",a.b.action.toLowerCase()]}):null]})}const Qn={email:"Email",domain:"Website",phone:"Phone",lead_event:"Linked lead"};function Vn({workspaceId:t,clientId:s,clientName:a,details:l,onClose:m}){const o=ae(),c=$(zt),[r,i]=v.useState([]),x=K({mutationFn:async()=>{for(const p of l)r.includes(p.id)||await c({data:{workspaceId:t,clientId:s,identifierId:p.id}})},onSuccess:()=>{_.success("Details removed — they go back to Needs mapping."),o.invalidateQueries({queryKey:["client-book"]}),o.invalidateQueries({queryKey:["client-identifiers"]}),m()},onError:p=>_.error(p.message)});return e.jsx(xe,{open:!0,onOpenChange:p=>p?null:m(),children:e.jsxs(ge,{className:"max-w-lg",children:[e.jsxs(je,{children:[e.jsx(pe,{children:"These details may belong to the old account"}),e.jsxs(ve,{children:["“",a,"” still carries details that do not match its new name. Leaving them here means both accounts read wrong — meetings, emails and texts from the other business will keep landing on this card."]})]}),e.jsx("ul",{className:"space-y-2 text-sm",children:l.map(p=>e.jsxs("li",{className:"flex items-start justify-between gap-3 rounded border p-2",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:Qn[p.kind]??p.kind}),e.jsx("span",{className:"block truncate font-medium",children:p.value}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:p.reason})]}),e.jsx(C,{size:"sm",variant:r.includes(p.id)?"secondary":"ghost",onClick:()=>i(j=>j.includes(p.id)?j.filter(u=>u!==p.id):[...j,p.id]),children:r.includes(p.id)?"Keeping":"Keep this"})]},p.id))}),e.jsxs(we,{className:"gap-2",children:[e.jsx(C,{variant:"outline",onClick:m,disabled:x.isPending,children:"Keep everything"}),e.jsx(C,{onClick:()=>x.mutate(),disabled:x.isPending||r.length===l.length,children:x.isPending?"Removing…":"Remove the rest"})]})]})})}const We=(t,s=140)=>t.length>s?`${t.slice(0,s-1).trimEnd()}…`:t;function Wn(t){if(t.color!=="yellow")return null;if(t.transcriptsUsed===0&&t.emailsUsed===0)return"Not enough real conversation to read — no usable meeting recording or client email was found, so this is a caution flag, not a verdict.";const s=t.churnSignals.find(m=>m.severity==="high");if(s?.detail)return`Warning sign in the last conversations: ${We(s.detail)}`;if(t.daysSinceContact!==null&&t.daysSinceContact>30)return`No contact in ${t.daysSinceContact} days — the relationship has gone quiet.`;const a=t.commitments.find(m=>m.status==="broken"&&m.who==="us");if(a?.commitment)return`We did not deliver something we promised: ${We(a.commitment)}`;if(t.cadenceSlowing)return"Meetings are getting further apart than they used to be.";const l=t.churnSignals.find(m=>m.severity==="medium");return l?.detail?`Something to watch: ${We(l.detail)}`:t.transcriptsUsed+t.emailsUsed<=1||t.confidence==="low"?"Only one piece of evidence to go on, so Brain is being cautious rather than calling this healthy.":"Mixed signals in recent conversations — nothing critical, but not clean either."}const ht={hos:"all",strategist:"all",score:"all",sort:"risk",q:""},Fe=t=>t>=1e3?`$${Math.round(t/100)/10}
1k`:`$${Math.round(t).toLocaleString()}`;function Yn(t){return t==="red"?"border-destructive/50 bg-destructive/10 text-destructive":t==="yellow"?"border-amber-500/50 bg-amber-500/10 text-amber-600 dark:text-amber-400":t==="green"?"border-emerald-500/50 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400":"border-border bg-muted text-muted-foreground"}function Gn(t){return t==="high"?"border-destructive/40 text-destructive":t==="medium"?"border-amber-500/40 text-amber-600 dark:text-amber-400":"border-border text-muted-foreground"}function xt({workspaceId:t,strategistUserId:s}){const a=ae(),l=$(it),m=$(At),{values:o,setValue:c,setValues:r}=rs(ht,{enabled:!s}),i=o.sort,x=o.score,p=o.q,j=o.hos,u=o.strategist,h=k=>c("sort",k),n=k=>c("score",k),d=k=>c("q",k),T=k=>c("hos",k),f=k=>c("strategist",k),[b,q]=v.useState(null),[D,F]=es("clients-view","board");v.useEffect(()=>{if(!b)return;const k=b-Date.now();if(k<=0){q(null);return}const Q=setTimeout(()=>q(null),k);return()=>clearTimeout(Q)},[b]);const{data:N,isLoading:I,error:g}=J({queryKey:["client-book",t,s??"me"],queryFn:()=>l({data:s?{workspaceId:t,strategistUserId:s}:{workspaceId:t}}),enabled:!!t,staleTime:6e4,refetchInterval:b?8e3:!1}),P=K({mutationFn:k=>m({data:k?{workspaceId:t,clientId:k}:{workspaceId:t}}),onSuccess:k=>{const Q=k.clients;_.success(Q===1?"Recompute started — this client's score updates in a moment.":`Recompute started in the background${Q?` for ${Q} client(s)`:""}. Scores appear as they land — you can leave this page.`),q(Date.now()+(Q===1?9e4:5*6e4)),a.invalidateQueries({queryKey:["client-book",t]})},onError:k=>_.error(k.message)}),z=v.useMemo(()=>{const k=new Map,Q=new Map;for(const S of N?.clients??[])for(const E of S.owners??[])E.userId&&(E.role==="head_of_strategy"&&k.set(E.userId,E.name??"Unnamed"),E.role==="strategist"&&Q.set(E.userId,E.name??"Unnamed"));const ye=S=>[...S.entries()].sort((E,B)=>E[1].localeCompare(B[1]));return{hos:ye(k),strategists:ye(Q)}},[N]),w=v.useMemo(()=>{const k=p.trim().toLowerCase(),Q=(N?.clients??[]).filter(B=>{const le=me=>B.owners?.find(De=>De.role===me)?.userId??null;if(j!=="all"){const me=le("head_of_strategy");if(j==="unassigned"?me:me!==j)return!1}if(u!=="all"){const me=le("strategist");if(u==="unassigned"?me:me!==u)return!1}return k&&![B.name,B.primaryDomain??"",...(B.owners??[]).map(De=>De.name??"")].join(" ").toLowerCase().includes(k)?!1:x==="all"?!0:x==="unscored"?!B.health||B.health.state==="no_evidence":B.health?.state==="scored"&&B.health.color===x}),ye=B=>B.health?.state==="scored"?B.health.churnRiskPct:-1,S=B=>B.health?.state==="scored"?B.health.score:999,E=B=>B.health?.daysSinceContact??-1;return[...Q].sort((B,le)=>i==="risk"?ye(le)-ye(B):i==="health"?S(B)-S(le):i==="mrr"?le.mrrUsd-B.mrrUsd||le.contractValueUsd-B.contractValueUsd:i==="silent"?E(le)-E(B):B.name.localeCompare(le.name))},[N,x,i,p,j,u]),R=v.useMemo(()=>{const k=N?.clients??[],Q=k.filter(oe=>oe.health?.state==="scored"),ye=Q.filter(oe=>oe.health.color==="red"||oe.health.color==="yellow").sort((oe,Ce)=>Ce.health.churnRiskPct-oe.health.churnRiskPct),S=k.filter(oe=>(oe.health?.daysSinceContact??-1)>30).sort((oe,Ce)=>(Ce.health.daysSinceContact??0)-(oe.health.daysSinceContact??0));let E=0,B=0,le=0;for(const oe of k){const Ce=(oe.health?.commitments??[]).filter(Pe=>Pe.who==="us"&&Pe.status!=="kept"&&Pe.status!=="done");Ce.length&&(le+=1),E+=Ce.length,B+=Ce.filter(Pe=>Pe.status==="broken").length}const me=Q.length,De=k.length?Math.round(me/k.length*100):0;return{all:k,scored:Q,attention:ye,quiet:S,owed:E,broken:B,owedClients:le,covered:me,pct:De}},[N]);if(I)return e.jsx(de,{className:"h-64 w-full"});if(g)return e.jsx(se,{children:e.jsxs(ne,{className:"space-y-3 p-6",children:[e.jsx("p",{className:"text-sm text-destructive",children:Je(g)}),e.jsx(C,{size:"sm",variant:"outline",onClick:()=>{a.invalidateQueries({queryKey:["client-book",t]})},children:"Try again"})]})});if(!N)return null;const H=N.totals,y=R.attention[0],X=R.quiet[0],fe=H.mrr>0||H.contractValue>0;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(Te,{label:"Needs attention",value:`${H.red+H.yellow}`,sub:y?`Worst: ${y.name} — ${Math.round(y.health.churnRiskPct)}% chance of leaving`:R.scored.length?"Every scored client is healthy right now":"No client has enough call or email evidence to score yet",danger:H.red>0,onClick:H.red>0?()=>n("red"):H.yellow>0?()=>n("yellow"):void 0}),e.jsx(Te,{label:"Gone quiet",value:`${R.quiet.length}`,sub:X?`Longest: ${X.name} — ${X.health.daysSinceContact}
1 days with no contact`:"Nobody has been silent for more than 30 days",danger:R.quiet.length>0,onClick:R.quiet.length>0?()=>h("silent"):void 0}),e.jsx(Te,{label:"Promises we owe",value:`${R.owed}`,sub:R.owed?`Across ${R.owedClients} client${R.owedClients===1?"":"s"}${R.broken?` · ${R.broken} already missed`:""}`:"No open promises found in recent calls or email",danger:R.broken>0}),fe?e.jsx(Te,{label:"Revenue at risk",value:Fe(H.atRisk),sub:`Out of ${Fe(H.mrr)} monthly · ${Fe(H.contractValue)} contracted`,danger:H.atRisk>0}):e.jsx(Te,{label:"Evidence coverage",value:`${R.pct}%`,sub:`${R.covered} of ${H.clients} clients scored · ${H.unscored} still waiting on a call recording or client email`,onClick:H.unscored>0?()=>n("unscored"):void 0})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:N.scope==="all"?"Showing every client in the workspace.":N.scope==="chain"?"Showing your clients plus your strategists’ clients.":"Showing the clients assigned to you."}),e.jsx(Mn,{clients:N.clients}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Z,{value:p,onChange:k=>d(k.target.value),placeholder:"Search client, domain or owner…",className:"w-[240px]","aria-label":"Search clients"}),e.jsxs(V,{value:j,onValueChange:T,children:[e.jsx(W,{className:"w-[200px]","aria-label":"Filter by Head of Strategy",children:e.jsx(Y,{})}),e.jsxs(G,{children:[e.jsx(M,{value:"all",children:"All Heads of Strategy"}),e.jsx(M,{value:"unassigned",children:"No HoS assigned"}),z.hos.map(([k,Q])=>e.jsx(M,{value:k,children:Q},k))]})]}),e.jsxs(V,{value:u,onValueChange:f,children:[e.jsx(W,{className:"w-[190px]","aria-label":"Filter by strategist",children:e.jsx(Y,{})}),e.jsxs(G,{children:[e.jsx(M,{value:"all",children:"All strategists"}),e.jsx(M,{value:"unassigned",children:"No strategist assigned"}),z.strategists.map(([k,Q])=>e.jsx(M,{value:k,children:Q},k))]})]}),e.jsxs(V,{value:x,onValueChange:k=>n(k),children:[e.jsx(W,{className:"w-[180px]",children:e.jsx(Y,{})}),e.jsxs(G,{children:[e.jsx(M,{value:"all",children:"All health"}),e.jsx(M,{value:"red",children:"Red only"}),e.jsx(M,{value:"yellow",children:"Yellow only"}),e.jsx(M,{value:"green",children:"Green only"}),e.jsx(M,{value:"unscored",children:"No signal yet"})]})]}),e.jsxs(V,{value:i,onValueChange:k=>h(k),children:[e.jsx(W,{className:"w-[200px]",children:e.jsx(Y,{})}),e.jsxs(G,{children:[e.jsx(M,{value:"risk",children:"Highest churn risk first"}),e.jsx(M,{value:"health",children:"Worst health first"}),e.jsx(M,{value:"mrr",children:"Largest revenue first"}),e.jsx(M,{value:"silent",children:"Longest silent first"}),e.jsx(M,{value:"name",children:"Name"})]})]}),e.jsxs(C,{variant:"outline",size:"sm",onClick:()=>P.mutate(void 0),disabled:P.isPending,children:[e.jsx(Se,{className:`mr-2 h-4 w-4 ${P.isPending||b?"animate-spin":""}`}),b?"Recomputing in background…":"Recompute health"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-1 rounded-md border p-0.5",children:[e.jsxs(C,{size:"sm",variant:D==="board"?"secondary":"ghost",className:"h-7 px-2 text-xs",onClick:()=>F("board"),children:[e.jsx(Ls,{className:"mr-1.5 h-3.5 w-3.5"})," Board"]}),e.jsxs(C,{size:"sm",variant:D==="list"?"secondary":"ghost",className:"h-7 px-2 text-xs",onClick:()=>F("list"),children:[e.jsx(Is,{className:"mr-1.5 h-3.5 w-3.5"})," List"]})]})]}),s?null:e.jsx(ls,{pageKey:"clients-book",values:o,defaults:ht,onApply:k=>r(k),labels:{hos:z.hos.find(([k])=>k===j)?.[1]??(j==="unassigned"?"No HoS":j),strategist:z.strategists.find(([k])=>k===u)?.[1]??(u==="unassigned"?"No strategist":u),score:x==="unscored"?"no score":x,sort:`sorted by ${i}`,q:`“${p}”`}}),w.length===0?e.jsxs(e.Fragment,{children:[e.jsx(lt,{workspaceId:t}),e.jsx(se,{children:e.jsx(ne,{className:"p-6 text-sm text-muted-foreground",children:N.emptyReason==="no_role"?e.jsx(e.Fragment,{children:"You don't have a job role in this workspace yet, so no client accounts are shared with you. Ask your workspace admin to add you on Settings → Team, roles & access and assign your accounts — they'll appear here straight away."}):N.emptyReason==="no_assignments"?e.jsx(e.Fragment,{children:"No client accounts are assigned to you yet. Ask your workspace admin or your Head of Strategy to assign your accounts — they'll show up here as soon as they do."}):e.jsx(e.Fragment,{children:"No clients here yet. Clients are created automatically when a lead reaches won / paid / contract signed, and are deduped by company domain."})})})]}):e.jsxs(e.Fragment,{children:[e.jsx(lt,{workspaceId:t}),e.jsx(zn,{rows:w}
1),D==="board"?e.jsx(In,{rows:w,workspaceId:t,renderDetail:k=>e.jsx(gt,{client:k,workspaceId:t,onRecompute:()=>P.mutate(k.id),busy:P.isPending})}):w.map(k=>e.jsx(gt,{client:k,workspaceId:t,onRecompute:()=>P.mutate(k.id),busy:P.isPending},k.id))]})]})}function Te({label:t,value:s,sub:a,danger:l,onClick:m}){return e.jsx(se,{onClick:m,role:m?"button":void 0,tabIndex:m?0:void 0,onKeyDown:m?o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),m())}:void 0,className:m?"cursor-pointer transition-colors hover:border-primary/40":void 0,children:e.jsxs(ne,{className:"p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:t}),e.jsx("div",{className:`mt-1 text-2xl font-semibold ${l?"text-destructive":""}`,children:s}),a?e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:a}):null]})})}function gt({client:t,workspaceId:s,onRecompute:a,busy:l}){const[m,o]=v.useState(!1),c=ae(),r=$(cs),i=$(ds),[x,p]=v.useState(!1),[j,u]=v.useState(t.name),[h,n]=v.useState([]),d=K({mutationFn:y=>i({data:{workspaceId:s,clientId:t.id,name:y}}),onSuccess:y=>{_.success("Client name updated"),p(!1),n(y?.mismatched??[]),c.invalidateQueries({queryKey:["client-book"]}),c.invalidateQueries({queryKey:["clients"]})},onError:y=>_.error(y.message)}),T=$(ms),f=K({mutationFn:y=>T({data:{workspaceId:s,clientId:t.id,detail:y}}),onSuccess:()=>{_.success("Marked resolved — it stops counting when the score next refreshes."),c.invalidateQueries({queryKey:["client-book"]})},onError:y=>_.error(y.message)}),[b,q]=v.useState(!1),[D,F]=v.useState(""),N=$(Ws),I=$(Ys),g=K({mutationFn:y=>N({data:{workspaceId:s,clientId:t.id,note:y}}),onSuccess:()=>{_.success("Saved — this client stops showing as a worry until they go quiet again."),q
1(!1),F(""),c.invalidateQueries({queryKey:["client-book"]})},onError:y=>_.error(y.message)}),P=K({mutationFn:()=>I({data:{workspaceId:s,clientId:t.id}}),onSuccess:()=>{_.success("Note removed — this client is scored on the conversations again."),c.invalidateQueries({queryKey:["client-book"]})},onError:y=>_.error(y.message)}),z=K({mutationFn:y=>r({data:{workspaceId:s,clientId:t.id,...y}}),onSuccess:()=>{_.success("Removed from this client — the score is being recalculated."),c.invalidateQueries({queryKey:["client-book"]})},onError:y=>_.error(y.message)}),w=t.health,R=w?.state==="scored",H=w&&R?Wn(w):null;return e.jsxs(se,{children:[e.jsx(ue,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(he,{className:"flex flex-wrap items-center gap-2 text-base",children:[x?e.jsxs("span",{className:"flex w-full items-center gap-1.5 sm:w-auto",children:[e.jsx(Z,{autoFocus:!0,value:j,onChange:y=>u(y.target.value),onKeyDown:y=>{y.key==="Enter"&&j.trim()&&d.mutate(j.trim()),y.key==="Escape"&&(u(t.name),p(!1))},className:"h-8 w-full min-w-0 sm:w-64","aria-label":"Client name"}),e.jsx(C,{size:"icon",variant:"ghost",className:"h-8 w-8",disabled:d.isPending||!j.trim(),onClick:()=>d.mutate(j.trim()),"aria-label":"Save client name",children:e.jsx(at,{className:"h-4 w-4"})}),e.jsx(C,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>{u(t.name),p(!1)},"aria-label":"Cancel rename",children:e.jsx(St,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[t.name,s?e.jsx(C,{size:"icon",variant:"ghost",className:"h-6 w-6 text-muted-foreground",onClick:()=>{u(t.name),p(!0)},"aria-label":`Rename ${t.name}`,title:"Rename client",children:e.jsx(_t,{className:"h-3.5 w-3.5"})}):null]}),!x&&t.primaryDomain?e.jsx("span",{className:"font-normal text-xs text-muted-foreground",children:t.primaryDomain}):null,t.status?e.jsx(O,{variant:"outline",className:"text-[10px]",children:t.status}):null,s&&h.length?e.jsx(Vn,{workspaceId:s,clientId:t.id,clientName:t.name,details:h,onClose:()=>n([])}):null]}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[t.services.length," service",t.services.length===1?"":"s"]}),e.jsxs("span",{children:["MRR ",Fe(t.mrrUsd)]}),e.jsxs("span",{children:["Contract ",Fe(t.contractValueUsd)]}),R?e.jsxs("span",{className:"text-destructive",children:["At risk ",Fe(t.atRiskUsd)]}):null,t.tenureDays!==null?e.jsxs("span",{children:["Tenure ",t.tenureDays,"d"]}):null,w?.daysSinceContact!==null&&w?.daysSinceContact!==void 0?e.jsxs("span",{children:["Silent ",w.daysSinceContact,"d"]}):null,w?.lastMeetingAt?e.jsxs("span",{className:"font-medium text-foreground",children:["Last meeting"," ",new Date(w.lastMeetingAt).toLocaleDateString(void 0,{month:"short",day:"numeric",year:new Date(w.lastMeetingAt).getFullYear()===new Date().getFullYear()?void 0:"numeric"}),` (${Math.max(0,Math.floor((Date.now()-Date.parse(w.lastMeetingAt))/864e5))}d ago)`]}):null,w?.meetingCount?e.jsxs("span",{children:[w.meetingCount," meeting",w.meetingCount===1?"":"s",w.cadenceDays!==null?` · ~${w.cadenceDays}d apart`:"",w.cadenceSlowing?" · slowing":""]}):null]}),e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Me,{className:"h-3 w-3"}),e.jsxs("span",{children:["Account owner:"," ",e.jsx("span",{className:"font-medium text-foreground",children:t.owners.find(y=>y.role==="account_owner")?.name??t.owners.find(y=>y.role==="strategist")?.name??t.owners.find(y=>y.role==="head_of_strategy")?.name??"unassigned"})," · ","Strategist:"," ",e.jsx("span",{className:"font-medium text-foreground",children:t.owners.find(y=>y.role==="strategist")?.name??"unassigned"})," · ","Head of Strategy:"," ",e.jsx("span",{className:"font-medium text-foreground",children:t.owners.find(y=>y.role==="head_of_strategy")?.name??"unassigned"})]})]}),s?e.jsx(kn,{workspaceId:s,clientId:t.id,clientName:t.name}):null,s?e.jsx(Nn,{workspaceId:s,clientId:t.id,clientName:t.name,isAgency:t.isAgency,servesNiche:t.servesNiche}):null,s?e.jsx(xn,{workspaceId:s,clientId:t.id,clientName:t.name,currentStrategistUserId:t.owners.find(y=>y.role==="strategist")?.userId??null,currentHosUserId:t.owners.find(y=>y.role==="head_of_strategy")?.userId??null,currentAccountOwnerUserId:t.owners.find(y=>y.role==="account_owner")?.userId??null}):null,s?e.jsx(Wt,{workspaceId:s,clientId:t.id,clientName:t.name}):null]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[R?e.jsxs("div",{className:`rounded-md border px-3 py-1.5 text-right ${Yn(w.color)}`,children:[e.jsxs("div",{className:"text-sm font-semibold capitalize",children:[w.color," · ",w.score]}),e.jsxs("div",{className:"text-[11px]",children:[w.churnRiskPct,"% churn risk",w.churnTimeline?` · ${w.churnTimeline}`:""]})]}):e.jsx(O,{variant:"outline",className:"text-[11px]",children:"No signal yet"}),R?e.jsxs(C,{variant:"outline",size:"sm",onClick:a,disabled:l,children:[e.jsx(Se,{className:`mr-2 h-3.5 w-3.5 ${l?"animate-spin":""}`}),"Rescore"]}):null,e.jsxs(C,{variant:"ghost",size:"sm",onClick:()=>o(y=>!y),children:[m?e.jsx(He,{className:"h-4 w-4"}):e.jsx(ze,{className:"h-4 w-4"}),"Why"]})]})]})}),e.jsx(ne,{className:"space-y-3 pt-0 text-sm",children:R?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-muted-foreground",children:w.summary}),H?e.jsxs("div",{className:"rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-xs text-amber-700 dark:text-amber-300",children:[e.jsx("div",{className:"text-[11px] font-medium uppercase tracking-wide",children:"Why this is yellow"}),e.jsx("div",{className:"mt-1 text-[12px] leading-relaxed",children:H})]}):null,w.riskExplanation?e.jsxs("div",{className:"rounded-md border border-emerald-500/40 bg-emerald-500/10 p-3 text-xs text-emerald-800 dark:text-emerald-300",children:[e.jsx("div",{className:"text-[11px] font-medium uppercase tracking-wide",children:"Why this is fine"}),e.jsx("div",{className:"mt-1 text-[12px] leading-relaxed",children:w.riskExplanation.note}),e.jsxs("div",{className:"mt-1 text-[11px] opacity-80",children:[w.riskExplanation.by?`${w.riskExplanation.by} · `:"",w.riskExplanation.at?new Date(w.riskExplanation.at).toLocaleDateString():""," · stays until this client goes quiet again"]}),s?e.jsx(C,{size:"sm",variant:"ghost",className:"mt-1 h-6 px-2 text-[11px]",disabled:P.isPending,onClick:()=>P.mutate(),children:"Remove this note"}):null]}):s&&(w.color==="red"||w.color==="yellow")?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-xs",children:b?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"Why is this client actually fine?"}),e.jsx(Z,{autoFocus:!0,value:D,maxLength:1e3,placeholder:"e.g. She is travelling this week, which is why she moved the meeting.",onChange:y=>F(y.target.value),onKeyDown:y=>{y.key==="Enter"&&D.trim().length>=4&&g.mutate(D.trim()),y.key==="Escape"&&q(!1)},"aria-label":"Why this client is fine"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C,{size:"sm",disabled:D.trim().length<4||g.isPending,onClick:()=>g.mutate(D.trim()),children:"Save"}),e.jsx(C,{size:"sm",variant:"ghost",onClick:()=>q(!1),children:"Cancel"})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Brain will stop flagging this client until they go quiet again or something new comes up."})]}):e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(C,{size:"sm",variant:"outline",onClick:()=>q(!0),children:"Explain why this is fine"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Checked with the client and there is a good reason? Say so here and this stops showing as a worry."})]})}):null,w.ignoredMeetings.length>0?e.jsxs("div",{className:"rounded-md border border-dashed p-3 text-xs text-muted-foreground",children:[e.jsxs("div",{className:"text-[11px] font-medium uppercase tracking-wide",children:["Not used for scoring · ",w.ignoredMeetings.length," meeting",w.ignoredMeetings.length===1?"":"s"]}),e.jsx("ul",{className:"mt-1.5 space-y-1",children:w.ignoredMeetings.slice(0,4).map(y=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(O,{variant:"outline",className:"text-[10px]",children:"Empty / too short"}),e.jsx("span",{className:"font-medium text-foreground",children:y.label}),y.occurredAt?e.jsx("span",{children:new Date(y.occurredAt).toLocaleDateString()}):null,e.jsxs("span",{children:["· ",y.reason]})]},y.id||y.label))}),e.jsx("div",{className:"mt-1.5",children:"These meetings happened, but there was not enough recorded conversation to read, so they never move this client's score up or down."})]}):null,e.jsxs("div",{className:"rounded-md border border-primary/30 bg-primary/5 p-3",children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:["Next best action · ",w.nextActionUrgency]}),e.jsx("div",{className:"mt-1",children:w.nextBestAction}),s?e.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center gap-2 border-t border-primary/20 pt-2.5",children:[e.jsx(et,{workspaceId:s,clientId:t.id,clientName:t.name}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Had the call on the client's Zoom or Teams? Add the transcript so this recommendation is based on it."})]}):null]}),e.jsx($n,{confidence:w.confidence,sentimentTrend:w.sentimentTrend,transcriptsUsed:w.transcriptsUsed,emailsUsed:w.emailsUsed,matchedAllTime:t.evidenceCounts.transcripts+t.evidenceCounts.emails,computedAt:w.computedAt,sourceDocs:w.sourceDocs,quotes:w.evidence,ignoredMeetings:w.ignoredMeetings,workspaceId:s,detachPending:z.isPending,onDetach:(y,X)=>z.mutate({sourceType:y,sourceId:X})}),m?e.jsxs("div",{className:"space-y-3",children:[e.jsx(hs,{}),e.jsxs(Ee,{title:"Churn signals",icon:e.jsx(qe,{className:"h-3.5 w-3.5"}),children:[w.churnSignals.length===0?e.jsx(Ye,{children:"No churn signals detected in the window."}):w.churnSignals.map((y,X)=>e.jsxs("div",{className:"rounded-md border p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{variant:"outline",className:`text-[10px] ${Gn(y.severity)}`,children:y.severity}),e.jsx("span",{className:"text-xs font-medium",children:y.type.replace(/_/g," ")})]}),e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:y.detail}),e.jsx(Ge,{items:y.evidence}),e.jsx(C,{size:"sm",variant:"ghost",className:"mt-1 h-6 px-2 text-[11px]",disabled:f.isPending,onClick:()=>f.mutate(y.detail),title:"This is already sorted — stop it counting against this client",children:"Resolved / not relevant"})]},X)),w.droppedConcerns.length>0&&e.jsx("div",{className:"mt-2 space-y-2 rounded-md border border-dashed p-2",children:[{kind:"settled",label:"Settled in the same conversation"},{kind:"context",label:"Client-side context, not a risk signal"},{kind:"first_request",label:"Requests we owe them (asked once)"},{kind:"other",label:"No longer counting"}].map(({kind:y,label:X})=>{const fe=w.droppedConcerns.filter(k=>y==="other"?!["settled","context","first_request"].includes(k.kind??""):k.kind===y);return fe.length?e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-[11px] font-medium text-muted-foreground",children:[X," (",fe.length,")"]}),fe.map((k,Q)=>e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[e.jsx("span",{className:"line-through",children:k.detail})," — ",k.reason]},Q))]},y):null})})]}
1),e.jsx(Ee,{title:"Commitments",children:w.commitments.length===0?e.jsx(Ye,{children:"No commitments captured."}):w.commitments.map((y,X)=>e.jsxs("div",{className:"rounded-md border p-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(O,{variant:"outline",className:"text-[10px]",children:y.status}),e.jsx("span",{className:"text-muted-foreground",children:y.who==="us"?"Ours":"Client"}),y.due?e.jsxs("span",{className:"text-muted-foreground",children:["· due ",y.due]}):null]}),e.jsx("div",{className:"mt-1 text-xs",children:y.commitment}),e.jsx(Ge,{items:y.evidence})]},X))}),e.jsxs(Ee,{title:"Upsell opportunities",icon:e.jsx(vs,{className:"h-3.5 w-3.5"}),children:[w.upsellCues.length===0?e.jsx(Ye,{children:"No upsell cues heard in conversations."}):w.upsellCues.map((y,X)=>e.jsxs("div",{className:"rounded-md border p-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(O,{variant:"outline",className:"text-[10px]",children:y.strength}),y.suggested_service?e.jsx("span",{className:"font-medium",children:y.suggested_service}):null]}),e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:y.need}),e.jsx(Ge,{items:y.evidence})]},X)),t.upsellOffers.length?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Offers this client does not have: ",t.upsellOffers.join(", ")]}):null]}),w.positives.length?e.jsx(Ee,{title:"What's going well",children:e.jsx("ul",{className:"list-disc pl-5 text-xs text-muted-foreground",children:w.positives.map((y,X)=>e.jsx("li",{children:y},X))})}):null,e.jsx("div",{children:e.jsxs(C,{size:"sm",variant:"outline",onClick:a,disabled:l,children:[e.jsx(Se,{className:`mr-2 h-3.5 w-3.5 ${l?"animate-spin":""}`})," Recompute this client"]})})]}):null]}):e.jsxs("div",{className:"rounded-md border border-dashed p-3 text-xs text-muted-foreground",children:["No transcripts or client emails matched this account yet, so there is no score — not a healthy one either. Connect the strategist's Google account in"," ",e.jsx("span",{className:"font-medium",children:"Voice of Customer"})," so Meet transcripts sync, and add a contact email on the account so client email threads match by domain.",e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsxs(C,{size:"sm",variant:"outline",onClick:a,disabled:l,children:[e.jsx(Se,{className:`mr-2 h-3.5 w-3.5 ${l?"animate-spin":""}`})," Check again"]}),s?e.jsx(et,{workspaceId:s,clientId:t.id,clientName:t.name}):null]})]})})]})}function Ee({title:t,icon:s,children:a}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[s,t]}),a]})}function Ye({children:t}){return e.jsx("div",{className:"text-xs text-muted-foreground",children:t})}function Ge({items:t}){return t?.length?e.jsx("div",{className:"mt-2 space-y-1",children:t.map((s,a)=>e.jsxs("div",{className:"border-l-2 border-muted pl-2 text-xs italic text-muted-foreground",children:["“",s.quote,"”"]},a))}):null}const tt=["churned","recontacted","meeting_booked","won_back","closed_lost"],Xt={churned:"Churned",recontacted:"Re-contacted",meeting_booked:"Meeting booked",won_back:"Won back",closed_lost:"Gone for good"},Xn=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-churn_functions_ts--listChurnedClients_createServerFn_handler")),Zn=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-churn_functions_ts--markClientChurned_createServerFn_handler")),Zt=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-churn_functions_ts--reactivateChurnedClient_createServerFn_handler")),Jn=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-churn_functions_ts--setWinbackStage_createServerFn_handler")),ea={strategist:"Strategist",head_of_strategy:"Head of Strategy",identifier:"Identifier"},ta={email:"email",domain:"domain",phone:"phone number",stripe_customer:"Stripe customer",lead_event:"lead record"};function sa(t){const s=new Date(t),a=Math.round((Date.now()-s.getTime())/6e4);return a<1?"just now":a<60?`${a} min ago`:a<1440?`${Math.round(a/60)}h ago`:s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function pt(t){if(t.kind==="identifier"){const a=`${ta[t.identifierKind??""]??t.identifierKind??"identifier"} ${t.identifierValue??""}`.trim();return t.action==="identifier_added"?`${a} now points at ${t.clientName??"this client"}`:t.action==="identifier_removed"?`${a} no longer points at ${t.fromName??"that client"}`:`${a} moved from ${t.fromName??"nobody"} to ${t.toName??"nobody"}`}const s=ea[t.kind]??t.kind;return t.action==="assigned"?`${s} set to ${t.toName??"someone"}`:t.action==="unassigned"?`${s} cleared (was ${t.fromName??"someone"})`:`${s} changed from ${t.fromName??"nobody"} to ${t.toName??"nobody"}`}function na({workspaceId:t,clientId:s,compact:a=!1}){const l=ae(),m=$(sn),o=$(nn),[c,r]=v.useState(""),[i,x]=v.useState(null),{data:p,isLoading:j}=J({queryKey:["client-mapping-history",t,s??"all"],queryFn:()=>m({data:{workspaceId:t,...s?{clientId:s}:{},limit:a?40:200}}),staleTime:3e4}),u=K({mutationFn:n=>o({data:{workspaceId:t,...n}}),onSuccess:n=>{n.reverted===0?_.error("Nothing was put back — those clients are outside your book."):_.success(`${n.reverted} change${n.reverted===1?"":"s"} put back`+(n.skipped?` · ${n.skipped}
1 skipped (outside your book)`:"")),x(null),l.invalidateQueries({queryKey:["client-mapping"]}),l.invalidateQueries({queryKey:["client-mapping-history"]}),l.invalidateQueries({queryKey:["client-book"]}),l.invalidateQueries({queryKey:["client-chain-rollup"]})},onError:n=>_.error(n instanceof Error?n.message:"Could not put that change back")});if(j)return e.jsx(de,{className:"h-40 w-full"});const h=(p?.entries??[]).filter(n=>{const d=c.trim().toLowerCase();return d?`${n.clientName??""} ${n.actorName??""} ${n.fromName??""} ${n.toName??""} ${n.identifierValue??""}`.toLowerCase().includes(d):!0});return e.jsxs("div",{className:"space-y-3",children:[a?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Z,{value:c,onChange:n=>r(n.target.value),placeholder:"Search by client, person or email…",className:"h-9 w-full sm:w-72"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Every ownership and identifier change, newest first — including the ones Brain made on its own."})]}),e.jsx("div",{className:"divide-y rounded-md border",children:h.length===0?e.jsxs("div",{className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[e.jsx(ys,{className:"h-4 w-4"})," No changes recorded yet."]}):h.map(n=>e.jsxs("div",{className:"flex flex-col gap-1.5 p-3 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-sm",children:[!s&&n.clientName?e.jsx("span",{className:"font-medium",children:n.clientName}):null,e.jsx("span",{className:"text-muted-foreground",children:pt(n)}),n.source&&n.source!=="manual"?e.jsx(O,{variant:"outline",className:"h-4 px-1 text-[10px]",children:"by Brain"}):null,n.revertedAt?e.jsxs(O,{variant:"secondary",className:"h-4 px-1 text-[10px]",children:["put back",n.revertedByName?` by ${n.revertedByName}`:""]}):null]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[n.actorName?`${n.actorName} · `:"",sa(n.at),n.batchSize>1?` · part of a ${n.batchSize}-client action`:""]})]}),n.canRevert?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(C,{size:"sm",variant:"outline",className:"h-8",onClick:()=>x({entry:n,wholeBatch:!1}),children:[e.jsx(Ns,{className:"mr-1.5 h-3.5 w-3.5"})," Put back"]}),n.batchId&&n.batchSize>1?e.jsxs(C,{size:"sm",variant:"ghost",className:"h-8 text-xs",onClick:()=>x({entry:n,wholeBatch:!0}),children:["Undo all ",n.batchSize]}):null]}):null]},n.id))}),e.jsx($t,{open:!!i,onOpenChange:n=>!n&&x(null),children:e.jsxs(Mt,{children:[e.jsxs(Dt,{children:[e.jsx(Pt,{children:i?.wholeBatch?`Undo this ${i.entry.batchSize}-client action?`:"Put this change back?"}),e.jsx(Tt,{children:i?i.wholeBatch?"Every client in that action goes back to the owner it had before. Their calls, emails and leads move back too.":`${i.entry.clientName??"This client"} goes back to how it was: ${pt(i.entry)} will be reversed. Calls, emails and leads follow.`:""})]}),e.jsxs(qt,{children:[e.jsx(Et,{children:"Cancel"}),e.jsx(Ot,{disabled:u.isPending,onClick:()=>i&&u.mutate({auditId:i.entry.id,wholeBatch:i.wholeBatch}),children:u.isPending?"Putting back…":"Yes, put it back"})]})]})})]})}const Xe=3;function aa({workspaceId:t}){const s=ae(),a=$(un),l=$(hn),[m,o]=v.useState(""),[c,r]=v.useState(null),{data:i,isLoading:x,error:p}=J({queryKey:["client-pool",t],queryFn:()=>a({data:{workspaceId:t}}),staleTime:3e4}),j=K({mutationFn:n=>l({data:{workspaceId:t,clientId:n}}),onMutate:n=>r(n),onSettled:()=>r(null),onSuccess:()=>{_.success("Client is yours — set a strategist on it in Ownership"),s.invalidateQueries({queryKey:["client-pool"]}),s.invalidateQueries({queryKey:["client-mapping"]}),s.invalidateQueries({queryKey:["client-book"]})},onError:n=>_.error(n instanceof Error?n.message:"Could not pick up this client")}),u=v.useMemo(()=>{const n=i??[],d=m.trim().toLowerCase();return d?n.filter(T=>(T.clientName??"").toLowerCase().includes(d)||(T.domain??"").toLowerCase().includes(d)):n},[i,m]),h=(i??[]).filter(n=>(n.daysWaiting??0)>=Xe);return x?e.jsx(de,{className:"h-40 w-full"}):p?e.jsx("p",{className:"text-sm text-muted-foreground",children:p instanceof Error?p.message:"Could not load the pool."}):e.jsxs("div",{className:"space-y-3",children:[h.length>0?e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 p-3 text-sm",children:[e.jsx(qe,{className:"mt-0.5 h-4 w-4 text-destructive"}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:[h.length," client",h.length===1?"":"s"," waiting more than"," ",Xe," days"]}),e.jsx("p",{className:"text-muted-foreground",children:"Nobody is working these accounts. Pick one up, or ask an admin to hand it to someone."})]})]}):null,e.jsx(Z,{value:m,onChange:n=>o(n.target.value),placeholder:"Search the pool by name or domain",className:"max-w-sm"}),u.length===0?e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-dashed p-6 text-sm text-muted-foreground",children:[e.jsx(bs,{className:"h-4 w-4"}),"Nothing in the pool — every client has an owner."]}
1):e.jsx("ul",{className:"divide-y rounded-md border",children:u.map(n=>{const d=n.daysWaiting??0;return e.jsxs("li",{className:"flex flex-wrap items-center gap-3 p-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"flex items-center gap-1.5 truncate text-sm font-medium",children:[n.clientName??"Unnamed client",n.cameFromPayment?e.jsxs(O,{variant:"secondary",className:"gap-1 font-normal",children:[e.jsx(Kt,{className:"h-3 w-3"})," Came from a payment"]}):null]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[n.domain??"no domain",n.lastOwnerEmail?` · handed back by ${n.lastOwnerEmail}`:"",n.note?` · “${n.note}”`:""]})]}),e.jsx(O,{variant:d>=Xe?"destructive":"secondary",children:d<=0?"free today":`waiting ${d}d`}),e.jsxs(C,{size:"sm",onClick:()=>j.mutate(n.clientId),disabled:c===n.clientId,children:[e.jsx(Es,{className:"mr-1 h-3.5 w-3.5"}),c===n.clientId?"Picking up…":"Pick this up"]})]},n.clientId)})})]})}const ia=L({method:"POST"}).middleware([A]).handler(U("src_lib_team-departure_functions_ts--listDepartureCandidates_createServerFn_handler")),ra=L({method:"POST"}).middleware([A]).handler(U("src_lib_team-departure_functions_ts--markMemberLeft_createServerFn_handler"));function la({workspaceId:t,onDone:s}){const a=ae(),[l,m]=v.useState(!1),[o,c]=v.useState(new Set),r=$(ia),i=$(ra),{data:x,isLoading:p}=J({queryKey:["departure-candidates",t],queryFn:()=>r({data:{workspaceId:t}}),enabled:l,staleTime:6e4}),j=x??[],u=K({mutationFn:async()=>{let n=0;for(const d of o){const T=await i({data:{workspaceId:t,userId:d}});n+=T.clientsHandedOver}return{count:o.size,moved:n}},onSuccess:n=>{_.success(`${n.count} ${n.count===1?"person":"people"} marked as left the company`+(n.moved?` · ${n.moved} client${n.moved===1?"":"s"} handed to their Head of Strategy`:"")),c(new Set),m(!1);for(const d of["departure-candidates","client-mapping","client-book","owner-candidates","client-chain-rollup","workspace-team"])a.invalidateQueries({queryKey:[d]});s?.()},onError:n=>_.error(n instanceof Error?n.message:"Could not mark that person as left")}),h=n=>c(d=>{const T=new Set(d);return T.has(n)?T.delete(n):T.add(n),T});return e.jsxs(xe,{open:l,onOpenChange:n=>{m(n),n||c(new Set)},children:[e.jsx(be,{asChild:!0,children:e.jsxs(C,{variant:"outline",size:"sm",className:"h-9",children:[e.jsx(Ke,{className:"mr-1.5 h-3.5 w-3.5"}),"Someone left"]})}),e.jsxs(ge,{className:"max-w-lg",children:[e.jsxs(je,{children:[e.jsx(pe,{children:"Mark someone as left the company"}),e.jsx(ve,{children:"They disappear from every strategist and Head of Strategy list, anything they still hold moves to the Head of Strategy they reported to, and their access to this workspace is switched off. Their past calls, emails and notes stay exactly where they are."})]}),e.jsx("div",{className:"max-h-72 space-y-1 overflow-y-auto rounded-md border p-2",children:p?e.jsx("p",{className:"p-2 text-xs text-muted-foreground",children:"Loading your team…"}):j.length===0?e.jsx("p",{className:"p-2 text-xs text-muted-foreground",children:"Nobody here you can retire. Only people who report to you appear in this list."}):j.map(n=>e.jsxs("label",{className:"flex items-start gap-2 rounded-md p-2 text-sm hover:bg-muted/50",children:[e.jsx($e,{className:"mt-0.5",checked:o.has(n.userId),onCheckedChange:()=>h(n.userId),"aria-label":`Mark ${n.name} as left`}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"truncate font-medium",children:n.name}),e.jsx(O,{variant:"secondary",className:"text-[10px]",children:n.jobRole}),n.activeClients>
10?e.jsxs(O,{variant:"outline",className:"text-[10px]",children:[n.activeClients," client",n.activeClients===1?"":"s"," to hand over"]}):null]}),e.jsxs("span",{className:"block truncate text-[11px] text-muted-foreground",children:[n.email??"no email on file",n.reportsToName?` · reports to ${n.reportsToName}`:""]})]})]},n.userId))}),e.jsxs(we,{children:[e.jsx(C,{variant:"outline",onClick:()=>m(!1),children:"Cancel"}),e.jsx(C,{onClick:()=>u.mutate(),disabled:o.size===0||u.isPending,variant:"destructive",children:u.isPending?"Working…":`Mark ${o.size||""} as left`.trim()})]})]})]})}const ie="__none__",ce="__keep__",ke="__all__";function oa({workspaceId:t,onReviewDuplicates:s}){const a=ae(),l=$(Js),m=$(en),{data:o,isLoading:c}=J({queryKey:["client-mapping",t],queryFn:()=>l({data:{workspaceId:t}}),staleTime:6e4}),[r,i]=v.useState(""),[x,p]=v.useState("all"),[j,u]=v.useState(ke),[h,n]=v.useState(ke),[d,T]=v.useState(new Set),[f,b]=v.useState(ce),[q,D]=v.useState(ce),[F,N]=v.useState(!1),I=o?.people??[],g=v.useMemo(()=>{const S=new Map(I.map(E=>[E.userId,E.name]));return E=>E?S.get(E)??"Unknown":null},[I]),P=I.filter(S=>S.isHos),z=$(an),w=J({queryKey:["client-outside-book",t,r.trim().toLowerCase()],queryFn:()=>z({data:{workspaceId:t,query:r.trim()}}),enabled:r.trim().length>=3,staleTime:6e4}),R=$(Qt),H=J({queryKey:["client-name-search",t,r.trim().toLowerCase()],queryFn:()=>R({data:{workspaceId:t,query:r.trim()}}),enabled:r.trim().length>=3,staleTime:6e4}),y=v.useMemo(()=>new Set((H.data?.inBook??[]).map(S=>S.clientId)),[H.data]),X=v.useMemo(()=>{const S=r.trim().toLowerCase();return(o?.rows??[]).filter(E=>!(S&&!`${E.name} ${E.primaryDomain??""}`.toLowerCase().includes(S)&&!y.has(E.clientId)||j!==ke&&(E.hosUserId??ie)!==j||h!==ke&&(E.strategistUserId??ie)!==h||x==="unassigned"&&E.strategistUserId&&E.hosUserId||x==="auto"&&E.assignedBy==="manual"||x==="no-signal"&&E.lastSignalAt))},[o?.rows,r,x,j,h,y]),fe=()=>{a.invalidateQueries({queryKey:["client-mapping"]}),a.invalidateQueries({queryKey:["client-book"]}),a.invalidateQueries({queryKey:["client-chain-rollup"]})},k=K({mutationFn:S=>m({data:{workspaceId:t,...S}}),onSuccess:S=>{const E=S.skipped.length;_.success(`${S.updated} client${S.updated===1?"":"s"} re-assigned${E?` · ${E} skipped (not in your book)`:""}`),S.churnedNames?.length&&_.warning(`${S.churnedNames.join(", ")} ${S.churnedNames.length===1?"is":"are"} marked as having left us, so ${S.churnedNames.length===1?"it":"they"} won't show in anyone's book. Use "Bring back" on the row to put ${S.churnedNames.length===1?"it":"them"} back on a live book.`,{duration:12e3}),T(new Set),b(ce),D(ce),fe()},onError:S=>_.error(S instanceof Error?S.message:"Could not re-assign those clients")}),Q=S=>T(E=>{const B=new Set(E);return B.has(S)?B.delete(S):B.add(S),B}),ye=X.length>0&&X.every(S=>d.has(S.clientId));return c?e.jsx(de,{className:"h-64 w-full"}):o?e.jsx("div",{className:"space-y-4",children:e.jsxs(se,{children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs(he,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ht,{className:"h-4 w-4"})," Client mapping"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Put every client on the right strategist and Head of Strategy. Anything you set here beats what Brain guessed from meetings and email, and it moves the client's calls, emails and leads with it."})]}),e.jsx(ne,{className:"space-y-3",children:e.jsxs(Re,{defaultValue:"ownership",children:[e.jsxs(Ie,{children:[e.jsx(ee,{value:"ownership",children:"Ownership"}),e.jsx(ee,{value:"pool",children:"Unowned pool"}),e.jsx(ee,{value:"history",children:"Change log"})]}),e.jsxs(te,{value:"ownership",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Z,{value:r,onChange:S=>i(S.target.value),placeholder:"Search client or domain…",className:"h-9 w-full sm:w-64"}),e.jsxs(V,{value:x,onValueChange:S=>p(S),children:[e.jsx(W,{className:"h-9 w-[190px]",children:e.jsx(Y,{})}),e.jsxs(G,{children:[e.jsx(M,{value:"all",children:"All clients"}),e.jsx(M,{value:"unassigned",children:"Missing an owner"}),e.jsx(M,{value:"auto",children:"Guessed by Brain"}),e.jsx(M,{value:"no-signal",children:"No calls or email yet"})]})]}),e.jsxs(V,{value:j,onValueChange:u,children:[e.jsx(W,{className:"h-9 w-[200px]",children:e.jsx(Y,{placeholder:"Head of Strategy"})}),e.jsxs(G,{children:[e.jsx(M,{value:ke,children:"Any Head of Strategy"}),e.jsx(M,{value:ie,children:"No Head of Strategy"}),P.map(S=>e.jsx(M,{value:S.userId,children:S.name},S.userId))]})]}),e.jsxs(V,{value:h,onValueChange:n,children:[e.jsx(W,{className:"h-9 w-[200px]",children:e.jsx(Y,{placeholder:"Strategist"})}),e.jsxs(G,{children:[e.jsx(M,{value:ke,children:"Any strategist"}),e.jsx(M,{value:ie,children:"No strategist"}),I.map(S=>e.jsx(M,{value:S.userId,children:S.name},S.userId))]})]}),o.canMoveBooks?e.jsx(da,{workspaceId:t,board:o,onDone:fe}):null,o.isAdmin||o.isHos?e.jsx(la,{workspaceId:t,onDone:fe}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-md border bg-muted/40 p-2",children:[e.jsx($e,{checked:ye,onCheckedChange:S=>T(S?new Set(X.map(E=>E.clientId)):new Set),"aria-label":"Select all shown clients"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:d.size?`${d.size} selected`:"Select clients to move in bulk"}),e.jsxs("div",{className:"ml-auto flex flex-wrap items-center gap-2",children:[e.jsxs(V,{value:f,onValueChange:b,children:[e.jsx(W,{className:"h-8 w-[180px] text-xs",children:e.jsx(Y,{placeholder:"Strategist"})}),e.jsxs(G,{children:[e.jsx(M,{value:ce,children:"Strategist · leave as is"}),e.jsx(M,{value:ie,children:"Strategist · clear"}),I.map(S=>e.jsx(M,{value:S.userId,children:S.name},S.userId))]})]}),e.jsxs(V,{value:q,onValueChange:D,children:[e.jsx(W,{className:"h-8 w-[190px] text-xs",children:e.jsx(Y,{placeholder:"Head of Strategy"})}),e.jsxs(G,{children:[e.jsx(M,{value:ce,children:"Head of Strategy · leave as is"}),e.jsx(M,{value:ie,children:"Head of Strategy · clear"}),(P.length?P:I).map(S=>e.jsx(M,{value:S.userId,children:S.name},S.userId))]})]}),e.jsx(C,{size:"sm",className:"h-8",disabled:k.isPending||d.size===0||f===ce&&q===ce,onClick:()=>
1N(!0),children:k.isPending?"Applying…":"Apply to selected"}),e.jsx($t,{open:F,onOpenChange:N,children:e.jsxs(Mt,{children:[e.jsxs(Dt,{children:[e.jsxs(Pt,{children:["Re-assign ",d.size," client",d.size===1?"":"s","?"]}),e.jsxs(Tt,{children:[f===ce?"The strategist stays as it is.":f===ie?"The strategist will be cleared.":`Strategist becomes ${g(f)}.`," ",q===ce?"The Head of Strategy stays as it is.":q===ie?"The Head of Strategy will be cleared.":`Head of Strategy becomes ${g(q)}.`," ","Their calls, emails and leads move with them. Every change is written to the change log, so you can put it back."]})]}),e.jsxs(qt,{children:[e.jsx(Et,{children:"Cancel"}),e.jsx(Ot,{onClick:()=>{N(!1),k.mutate({clientIds:Array.from(d),...f===ce?{}:{strategistUserId:f===ie?null:f},...q===ce?{}:{hosUserId:q===ie?null:q}})},children:"Yes, re-assign"})]})]})})]})]}),e.jsx("div",{className:"divide-y rounded-md border",children:X.length===0?e.jsxs("div",{className:"space-y-2 p-6 text-center text-sm text-muted-foreground",children:[e.jsx("p",{children:"No clients match these filters."}),r.trim().length>=3?w.isFetching?e.jsx("p",{className:"text-xs",children:"Checking the rest of the workspace…"}):(w.data?.length??0)>0?e.jsxs("div",{className:"mx-auto max-w-md space-y-1 rounded-md border border-amber-500/40 bg-amber-500/5 p-3 text-left text-xs",children:[e.jsx("p",{className:"font-medium text-foreground",children:"Found outside your book — ask an admin to move it to you:"}),w.data.map(S=>e.jsxs("p",{children:[e.jsx("span",{className:"font-medium text-foreground",children:S.name}),S.primaryDomain?` (${S.primaryDomain})`:""," — currently"," ",S.ownerLabel,"; matched on ",S.matchedOn,"."]},S.clientId))]}):e.jsx("p",{className:"text-xs",children:"Nothing by that name anywhere in this workspace either — the client has not been added to Brain yet."}):null]}):X.map(S=>e.jsx(ca,{row:S,people:I,heads:P,checked:d.has(S.clientId),onToggle:()=>Q(S.clientId),nameOf:g,busy:k.isPending,onChange:E=>k.mutate({clientIds:[S.clientId],...E}),onReviewDuplicates:s,workspaceId:t,canRevive:o.isAdmin||o.isHos,onRevived:fe},S.clientId))}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Showing ",X.length," of ",o.rows.length," clients you can map."]})]}),e.jsx(te,{value:"pool",className:"mt-3",children:e.jsx(aa,{workspaceId:t})}),e.jsx(te,{value:"history",className:"mt-3",children:e.jsx(na,{workspaceId:t})})]})})]})}):null}function ca({row:t,people:s,heads:a,checked:l,onToggle:m,nameOf:o,busy:c,onChange:r,onReviewDuplicates:i,workspaceId:x,canRevive:p,onRevived:j}){const u=$(Zt),h=t.status==="churned",n=K({mutationFn:()=>u({data:{workspaceId:x,clientId:t.clientId,strategistUserId:t.strategistUserId,hosUserId:t.hosUserId}}),onSuccess:()=>{_.success(`${t.name} is back on the live book`),j()},onError:d=>_.error(d instanceof Error?d.message:"Could not bring this client back")});return e.jsxs("div",{className:"flex flex-col gap-2 p-3 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-start gap-2",children:[e.jsx($e,{checked:l,onCheckedChange:m,"aria-label":`Select ${t.name}`,className:"mt-0.5"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:t.name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[11px] text-muted-foreground",children:[t.primaryDomain?e.jsx("span",{className:"truncate",children:t.primaryDomain}):null,h?e.jsxs(e.Fragment,{children:[e.jsx(O,{variant:"outline",className:"h-4 border-amber-500/40 bg-amber-500/10 px-1 text-[10px] text-amber-600",children:"left us — not in any book"}),p?e.jsx("button",{type:"button",disabled:n.isPending,onClick:()=>n.mutate(),className:"rounded border px-1 text-[10px] hover:bg-muted disabled:opacity-50",children:n.isPending?"Bringing back…":"Bring back"}):null]}):null,t.assignedBy&&t.assignedBy!=="manual"?e.jsx(O,{variant:"outline",className:"h-4 px-1 text-[10px]",children:"guessed"}):null,t.lastSignalAt?null:e.jsx(O,{variant:"outline",className:"h-4 px-1 text-[10px]",children:"no signal"}),e.jsxs("span",{children:[t.identifierCount," identifier",t.identifierCount===1?"":"s"]}),!t.strategistUserId&&!t.hosUserId?e.jsx(O,{variant:"destructive",className:"h-4 px-1 text-[10px]",children:"unowned"}):null,!t.strategistUserId&&!t.hosUserId&&t.lastSignalAt?e.jsx(O,{className:"h-4 border-amber-500/40 bg-amber-500/10 px-1 text-[10px] text-amber-600",variant:"outline",children:"has activity — assign first"}):null,t.looksDuplicated?e.jsx("button",{type:"button",onClick:i,className:"rounded border border-amber-500/40 px-1 text-[10px] text-amber-500 hover:bg-amber-500/10",children:"Looks duplicated — review duplicates"}):null]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(V,{value:t.strategistUserId??ie,disabled:c,onValueChange:d=>r({strategistUserId:d===ie?null:d}),children:[e.jsx(W,{className:"h-8 w-[180px] text-xs",children:e.jsx(Y,{placeholder:"Strategist"})}),e.jsxs(G,{children:[e.jsx(M,{value:ie,children:"No strategist"}),s.map(d=>e.jsx(M,{value:d.userId,children:d.name},d.userId)),t.strategistUserId&&!s.some(d=>d.userId===t.strategistUserId)?e.jsx(M,{value:t.strategistUserId,children:o(t.strategistUserId)}):null]})]}),e.jsxs(V,{value:t.hosUserId??ie,disabled:c,onValueChange:d=>r({hosUserId:d===ie?null:d}),children:[e.jsx(W,{className:"h-8 w-[190px] text-xs",children:e.jsx(Y,{placeholder:"Head of Strategy"})}),e.jsxs(G,{children:[e.jsx(M,{value:ie,children:"No Head of Strategy"}),(a.length?a:s).map(d=>e.jsx(M,{value:d.userId,children:d.name},d.userId)),t.hosUserId&&!a.some(d=>d.userId===t.hosUserId)&&!s.some(d=>d.userId===t.hosUserId)?e.jsx(M,{value:t.hosUserId,children:o(t.hosUserId)}):null]})]})]})]})}function da({workspaceId:t,board:s,onDone:a}){const l=$(tn),[m,o]=v.useState(!1),[c,r]=v.useState(""),[i,x]=v.useState(""),[p,j]=v.useState(!0),[u,h]=v.useState(new Set),n=s.people.filter(f=>f.isHos),d=s.rows.filter(f=>c&&f.hosUserId===c),T=K({mutationFn:()=>l({data:{workspaceId:t,fromHosUserId:c,toHosUserId:i,moveStrategists:p,...u.size?{clientIds:Array.from(u)}:{}}}),onSuccess:f=>{_.success(`${f.clientsMoved} client${f.clientsMoved===1?"":"s"} moved`+(f.strategistsMoved?` · ${f.strategistsMoved} strategist${f.strategistsMoved===1?"":"s"} now report to the new head`:"")),o(!1),h(new Set),a()},onError:f=>_.error(f instanceof Error?f.message:"Could not move that book")});return e.jsxs(xe,{open:m,onOpenChange:o,children:[e.jsx(be,{asChild:!0,children:e.jsxs(C,{variant:"outline",size:"sm",className:"h-9",children:[e.jsx(Ts,{className:"mr-1.5 h-3.5 w-3.5"}),"Move a book"]})}),e.jsxs(ge,{className:"max-w-lg",children:[e.jsxs(je,{children:[e.jsxs(pe,{className:"flex items-center gap-2",children:[e.jsx(Me,{className:"h-4 w-4"})," Move clients between Heads of Strategy"]}
1),e.jsx(ve,{children:"Use this when management re-shuffles who runs which accounts. Every client picked here moves to the new head, along with its calls, emails and leads."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"From"}),e.jsxs(V,{value:c,onValueChange:r,children:[e.jsx(W,{children:e.jsx(Y,{placeholder:"Current head"})}),e.jsx(G,{children:n.map(f=>e.jsx(M,{value:f.userId,children:f.name},f.userId))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"To"}),e.jsxs(V,{value:i,onValueChange:x,children:[e.jsx(W,{children:e.jsx(Y,{placeholder:"New head"})}),e.jsx(G,{children:n.filter(f=>f.userId!==c).map(f=>e.jsx(M,{value:f.userId,children:f.name},f.userId))})]})]})]}),c?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Clients to move"}),e.jsx("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:e.jsxs("button",{type:"button",className:"underline",onClick:()=>h(new Set),children:["move all ",d.length]})})]}),e.jsx("div",{className:"max-h-48 space-y-1 overflow-y-auto rounded-md border p-2",children:d.length===0?e.jsx("p",{className:"p-2 text-xs text-muted-foreground",children:"This head has no clients right now."}):d.map(f=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx($e,{checked:u.has(f.clientId),onCheckedChange:()=>h(b=>{const q=new Set(b);return q.has(f.clientId)?q.delete(f.clientId):q.add(f.clientId),q})}),e.jsx("span",{className:"truncate",children:f.name})]},f.clientId))}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Tick nothing to move this head's whole book (",d.length," clients)."]})]}):null,e.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Move their strategists too"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Re-points every strategist reporting to the old head at the new one, so future auto-assignment follows the new structure. Leave off to keep reporting lines as they are and only change who oversees these accounts."})]}),e.jsx(ts,{checked:p,onCheckedChange:j})]})]}),e.jsxs(we,{children:[e.jsx(C,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(C,{disabled:!c||!i||T.isPending,onClick:()=>T.mutate(),children:T.isPending?"Moving…":"Move clients"})]})]})]})}const ma=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-contact-review_functions_ts--listContactsUnderReview_createServerFn_handler")),ua=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-contact-review_functions_ts--remapContactUnderReview_createServerFn_handler")),ha=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-contact-review_functions_ts--keepContactUnderReview_createServerFn_handler")),xa=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-contact-review_functions_ts--discardContactUnderReview_createServerFn_handler")),ga=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-contact-review_functions_ts--createClientForContactUnderReview_createServerFn_handler"));function pa({workspaceId:t}){const s=ae(),a=$(ma),l=$(ua),m=$(ha),o=$(xa),c=$(ga),r=["client-contact-review",t],{data:i,isLoading:x,error:p}=J({queryKey:r,queryFn:()=>a({data:{workspaceId:t}}),retry:!1}),[j,u]=v.useState(""),[h,n]=v.useState({}),d=()=>{s.invalidateQueries({queryKey:r}),s.invalidateQueries({queryKey:["client-book",t]})},T=N=>_.error(N.message),f=K({mutationFn:N=>l({data:{workspaceId:t,...N}}),onSuccess:()=>{_.success("Email moved to the right client"),d()},onError:T}),b=K({mutationFn:N=>m({data:{workspaceId:t,contactId:N}}),onSuccess:()=>{_.success("Confirmed — this client keeps the address"),d()},onError:T}),q=K({mutationFn:N=>o({data:{workspaceId:t,contactId:N}}),onSuccess:()=>{_.success("Address removed"),d()},onError:T}),D=K({mutationFn:N=>c({data:{workspaceId:t,...N}}),onSuccess:()=>{_.success("Client created and email attached"),d()},onError:T}),F=v.useMemo(()=>{const N=i?.contacts??[],I=j.trim().toLowerCase();return I?N.filter(g=>(g.email??"").toLowerCase().includes(I)||g.clientName.toLowerCase().includes(I)):N},[i,j]);return p?null:e.jsxs(se,{children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs(he,{className:"flex flex-wrap items-center gap-2 text-base",children:[e.jsx(Bs,{className:"h-4 w-4 shrink-0"})," Emails to check",i?e.jsx(O,{variant:"secondary",children:i.total}):null]}),e.jsx(nt,{children:"These addresses came in on a client whose identity we could not prove — usually a shifted import sheet. Until you map one, it is ignored by call, email and payment matching, so no wrong strategist gets credit for it."})]}),e.jsx(ne,{className:"space-y-3",children:x?e.jsx(de,{className:"h-24 w-full"}):F.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing to check — every client email is on a confirmed client."}):e.jsxs(e.Fragment,{children:[e.jsx(Z,{value:j,onChange:N=>u(N.target.value),placeholder:"Search an address or client…","aria-label":"Search emails to check",className:"h-9"}),e.jsx("ul",{className:"divide-y",children:F.map(N=>{const I=(i?.clients??[]).filter(g=>N.suggestedClientIds.includes(g.id));return e.jsxs("li",{className:"space-y-2 py-3",children:[e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx("p",{className:"break-words font-mono text-sm",children:N.email??N.phone??"—"}),e.jsxs("p",{className:"break-words text-xs text-muted-foreground",children:["Currently on ",e.jsx("span",{className:"font-medium",children:N.clientName}),N.reviewReason?` · ${N.reviewReason}`:""]})]}),I.length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:I.slice(0,3).map(g=>e.jsxs(C,{size:"sm",variant:"outline",disabled:f.isPending,onClick:()=>f.mutate({contactId:N.contactId,targetClientId:g.id}),children:["Move to ",g.name]},g.id))}):null,e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsxs("select",{"aria-label":`Move ${N.email??"contact"} to a client`,className:"h-9 w-full rounded-md border bg-background px-2 text-sm sm:max-w-xs",defaultValue:"",onChange:g=>{const P=g.target.value;P&&f.mutate({contactId:N.contactId,targetClientId:P})},children:[e.jsx("option",{value:"",children:"Move to client…"}),(i?.clients??[]).map(g=>e.jsx("option",{value:g.id,children:g.name},g.id))]}),e.jsxs(C,{size:"sm",variant:"secondary",className:"w-full sm:w-auto",disabled:b.isPending,onClick:()=>b.mutate(N.contactId),children:[e.jsx(at,{className:"mr-1 h-3.5 w-3.5"})," Correct as-is"]}),e.jsxs(C,{size:"sm",variant:"ghost",className:"w-full sm:w-auto",disabled:q.isPending,onClick:()=>q.mutate(N.contactId),children:[e.jsx(Ft,{className:"mr-1 h-3.5 w-3.5"})," Not a client"]})]}),e.jsxs("form",{className:"flex flex-col gap-2 sm:flex-row",onSubmit:g=>{g.preventDefault();const P=(h[N.contactId]??"").trim();P&&D.mutate({contactId:N.contactId,clientName:P})},children:[e.jsx(Z,{value:h[N.contactId]??"",onChange:g=>n(P=>({...P,[N.contactId]:g.target.value})),placeholder:"…or create a new client by name","aria-label":`Create a client for ${N.email??"this contact"}`,className:"h-9 sm:max-w-xs"}),e.jsxs(C,{type:"submit",size:"sm",variant:"outline",className:"w-full sm:w-auto",disabled:D.isPending||!(h[N.contactId]??"").trim(),children:[e.jsx(st,{className:"mr-1 h-3.5 w-3.5"})," Create & attach"]})]})]}
1,N.contactId)})})]})})]})}const fa=L({method:"POST"}).middleware([A]).handler(U("src_lib_clients-coverage_functions_ts--getClientsCoverage_createServerFn_handler")),Ze=t=>{if(!t)return"never";const s=Math.floor((Date.now()-Date.parse(t))/864e5);return s<=0?"today":s===1?"1 day ago":`${s} days ago`};function ft({fresh:t,aging:s,stale:a,never:l}){return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[11px]",children:[e.jsxs("span",{className:"rounded border border-emerald-500/40 bg-emerald-500/10 px-1.5 text-emerald-600 dark:text-emerald-400",children:[t," in last 7 days"]}),e.jsxs("span",{className:"rounded border border-amber-500/40 bg-amber-500/10 px-1.5 text-amber-600 dark:text-amber-400",children:[s," in last 30 days"]}),e.jsxs("span",{className:"rounded border border-orange-500/40 bg-orange-500/10 px-1.5 text-orange-600 dark:text-orange-400",children:[a," older than 30 days"]}),e.jsxs("span",{className:"rounded border border-destructive/40 bg-destructive/10 px-1.5 text-destructive",children:[l," no calls at all"]})]})}function jt({workspaceId:t}){const s=$(fa),{data:a,isLoading:l,error:m}=J({queryKey:["clients-coverage",t],queryFn:()=>s({data:{workspaceId:t}}),enabled:!!t,staleTime:6e4,retry:!1}),[o,c]=v.useState(null);return l?e.jsx(de,{className:"h-64 w-full"}):m?e.jsx(se,{children:e.jsx(ne,{className:"p-6 text-sm text-muted-foreground",children:m.message})}):a?e.jsxs("div",{className:"space-y-4",children:[e.jsxs(se,{children:[e.jsxs(ue,{className:"pb-2",children:[e.jsxs(he,{className:"flex items-center gap-2 text-base",children:[e.jsx(ws,{className:"h-4 w-4"})," Call coverage"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"How many accounts each person carries, how many synced calls and email threads Brain has attached to them, and how old the newest call is. Open a row to see which accounts have no call yet and what is stopping the match."})]}),e.jsxs(ne,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4",children:[e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"text-[11px] uppercase text-muted-foreground",children:"Accounts in view"}),e.jsx("div",{className:"text-lg font-semibold",children:a.totals.clients})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"text-[11px] uppercase text-muted-foreground",children:"Calls synced"}),e.jsx("div",{className:"text-lg font-semibold",children:a.totals.transcripts})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"text-[11px] uppercase text-muted-foreground",children:"Email threads"}),e.jsx("div",{className:"text-lg font-semibold",children:a.totals.emails})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"text-[11px] uppercase text-muted-foreground",children:"Accounts with no call"}),e.jsx("div",{className:"text-lg font-semibold",children:a.totals.never})]})]}),e.jsx(ft,{fresh:a.totals.fresh,aging:a.totals.aging,stale:a.totals.stale,never:a.totals.never}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Totals count each account once, under the strategist who carries it, so Head of Strategy rows don't double up the same accounts."})]})]}),a.unmatched.transcripts>0?e.jsxs(se,{className:"border-amber-500/40",children:[e.jsxs(ue,{className:"pb-2",children:[e.jsxs(he,{className:"flex items-center gap-2 text-base",children:[e.jsx(Us,{className:"h-4 w-4 text-amber-600 dark:text-amber-400"})," Calls waiting to be attached"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[a.unmatched.transcripts," synced meetings across the workspace that Brain could not tie to a client on its own — newest ",Ze(a.unmatched.latestAt),". Fix the reason below, or attach them by hand in the “Unmapped meetings” list on the My book tab."]})]}),e.jsx(ne,{className:"flex flex-wrap gap-1.5 text-[11px]",children:a.unmatched.reasons.map(r=>e.jsxs("span",{className:"rounded border bg-muted px-1.5 py-0.5 text-muted-foreground",children:[r.reason," · ",r.count]},r.reason))})]}):null,a.owners.length===0?e.jsx(se,{children:e.jsx(ne,{className:"p-6 text-sm text-muted-foreground",children:"No Head of Strategy or strategist rows to show for your access yet."})}):null,a.owners.map(r=>{const i=o===`${r.role}:${r.userId}`;return e.jsx(se,{children:e.jsxs(ne,{className:"p-4",children:[e.jsxs("button",{type:"button",className:"flex w-full items-start justify-between gap-3 text-left",onClick:()=>c(i?null:`${r.role}:${r.userId}`),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:r.name}),e.jsx(O,{variant:"outline",children:r.role==="head_of_strategy"?"Head of Strategy":"Strategist"}),r.reportsTo?e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["reports to ",r.reportsTo]}):null]}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-foreground",children:r.clients})," accounts"]}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-foreground",children:r.transcripts})," calls synced"]}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-foreground",children:r.emails})," email threads"]}),e.jsxs("span",{children:["Newest call ",Ze(r.lastCallAt)]}),r.clientsWithoutCalls>
10?e.jsxs("span",{className:"text-destructive",children:[r.clientsWithoutCalls," with no call"]}):null]}),e.jsx("div",{className:"mt-2",children:e.jsx(ft,{fresh:r.fresh,aging:r.aging,stale:r.stale,never:r.never})}),r.blockedNoDomain>0||r.blockedNoEmail>0?e.jsxs("p",{className:"mt-2 text-[11px] text-muted-foreground",children:["Likely blockers: ",r.blockedNoDomain," accounts have no company domain saved,"," ",r.blockedNoEmail," have no contact email. Without one of those a synced meeting has nothing to match on."]}):null]}),e.jsx("span",{className:"mt-1 shrink-0 text-muted-foreground",children:i?e.jsx(He,{className:"h-4 w-4"}):e.jsx(ze,{className:"h-4 w-4"})})]}),i?e.jsxs("div",{className:"mt-3 space-y-1.5 border-t pt-3",children:[r.rows.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No accounts assigned."}):null,r.rows.map(x=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-md border p-2 text-xs",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium",children:x.name}),x.blockers.length?e.jsx("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:x.blockers.join(" · ")}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:[x.transcripts," calls"]}),e.jsxs("span",{children:[x.emails," email"]}),e.jsxs("span",{className:x.freshness==="fresh"?"text-emerald-600 dark:text-emerald-400":x.freshness==="aging"?"text-amber-600 dark:text-amber-400":"text-destructive",children:["Last call ",Ze(x.lastCallAt)]})]})]},x.clientId))]}):null]})},`${r.role}:${r.userId}`)}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Nothing here changes access: you only see the people and accounts inside your own chain."," ",e.jsx(C,{variant:"link",className:"h-auto p-0 text-[11px]",asChild:!0,children:e.jsx("a",{href:"/settings/access",children:"Check the access grid"})})]})]}):null}const ja=L({method:"POST"}).middleware([A]).handler(U("src_lib_clients-owner-suggest_functions_ts--suggestClientOwners_createServerFn_handler")),va=L({method:"POST"}).middleware([A]).handler(U("src_lib_clients-owner-suggest_functions_ts--acceptOwnerSuggestion_createServerFn_handler")),Oe={no_domain:"Domain not recorded in Brain",no_contact_email:"No contact email recorded in Brain",no_owner:"No owner assigned",no_evidence_matched:"No transcripts/emails matched yet",never_scored:"Not analysed yet"},ya=new Set(["gmail.com","googlemail.com","yahoo.com","hotmail.com","outlook.com","live.com","icloud.com","aol.com","proton.me","protonmail.com"]),vt={no_domain:"Add the client's company domain so email threads and Meet attendees match.",no_contact_email:"Add at least one contact email on the account.",no_owner:"Assign a strategist / account owner — their Google account supplies transcripts.",no_evidence_matched:"Mapping looks fine, but nothing matched yet — connect the owner's Google account in Voice of Customer.",never_scored:"Health has never been computed for this client — run a recompute."};function Na(t){const s=[];return t.primaryDomain||s.push("no_domain"),t.contacts.some(l=>!!l.email)||s.push("no_contact_email"),t.owners.length===0&&s.push("no_owner"),t.evidenceCounts.transcripts+t.evidenceCounts.emails===0&&s.length===0&&s.push("no_evidence_matched"),t.health||s.push("never_scored"),s.length?s:["no_evidence_matched"]}function yt({workspaceId:t}){const[s,a]=v.useState(!0),[l,m]=v.useState(""),[o,c]=v.useState("all"),r=ae(),i=$(it),{data:x,isLoading:p}=J({queryKey:["client-book",t,"me"],queryFn:()=>i({data:{workspaceId:t}}),enabled:!!t,staleTime:6e4}),j=x?.clients??[],u=$(ja),{data:h}=J({queryKey:["client-owner-suggestions",t],queryFn:()=>u({data:{workspaceId:t}}),enabled:!!t,staleTime:12e4,retry:!1}),n=v.useMemo(()=>{const g=new Map;for(const P of h??[])g.set(P.clientId,P);return g},[h]),d=$(va),T=K({mutationFn:g=>d({data:{workspaceId:t,clientId:g.clientId,userId:g.userId,hosUserId:g.hosUserId}}),onSuccess:()=>{_.success("Owner assigned from the email chain"),r.invalidateQueries({queryKey:["client-book",t]}),r.invalidateQueries({queryKey:["client-owner-suggestions",t]})},onError:g=>_.error(g.message)}),f=$(At),b=K({mutationFn:g=>f({data:g?{workspaceId:t,clientId:g}:{workspaceId:t}}),onSuccess:()=>{_.success("Recompute started — scores appear as they land."),r.invalidateQueries({queryKey:["client-book",t]})},onError:g=>_.error(g.message)}),q=v.useMemo(()=>j.filter(g=>!g.health||g.health.state==="no_evidence").map(g=>({client:g,reasons:Na(g)})).sort((g,P)=>P.client.mrrUsd-g.client.mrrUsd||g.client.name.localeCompare(P.client.name)),[j]),D=v.useMemo(()=>{const g=new Map;for(const P of q)for(const z of P.reasons)g.set(z,(g.get(z)??0)+1);return g},[q]),F=v.useMemo(()=>{const g=l.trim().toLowerCase();return q.filter(P=>o!=="all"&&!P.reasons.includes(o)?!1:g?P.client.name.toLowerCase().includes(g)||(P.client.primaryDomain??"").toLowerCase().includes(g):!0)},[q,l,o]);if(p)return e.jsx(de,{className:"h-40 w-full"});if(q.length===0)return e.jsx(se,{children:e.jsx(ne,{className:"p-6 text-sm text-muted-foreground",children:"Every account in your book has signal — no missing domains, owners, or unmatched evidence. Nothing to map here."})});const N=q.filter(g=>n.has(g.client.id)).length,I=()=>{const P=[["Client","Domain","MRR USD","Owners","Contact emails","Missing"].join(",")].concat(F.map(R=>[R.client.name,R.client.primaryDomain??"",String(Math.round(R.client.mrrUsd)),R.client.owners.map(H=>`${H.name} (${H.role})`).join(" | "),R.client.contacts.map(H=>
1H.email).filter(Boolean).join(" | "),R.reasons.map(H=>Oe[H]).join(" | ")].map(H=>`"${String(H).replace(/"/g,'""')}"`).join(","))),z=URL.createObjectURL(new Blob([P.join(`
2`)],{type:"text/csv"})),w=document.createElement("a");w.href=z,w.download="clients-no-signal.csv",w.click(),URL.revokeObjectURL(z)};return e.jsxs(se,{className:"border-dashed",children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs(he,{className:"text-base",children:[q.length," client",q.length===1?"":"s"," with no signal"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(C,{variant:"outline",size:"sm",onClick:I,children:[e.jsx(Cs,{className:"mr-2 h-3.5 w-3.5"})," CSV"]}),e.jsxs(C,{variant:"ghost",size:"sm",onClick:()=>a(g=>!g),children:[s?e.jsx(He,{className:"h-4 w-4"}):e.jsx(ze,{className:"h-4 w-4"}),s?"Hide list":"Show list"]})]})]}),N>0?e.jsxs("p",{className:"mt-2 flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Ue,{className:"h-3.5 w-3.5"}),N," of these have a suggested owner from the email chain — accept it inline below."]}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[Object.keys(Oe).filter(g=>(D.get(g)??0)>0).map(g=>e.jsx("button",{type:"button",onClick:()=>{c(o===g?"all":g),a(!0)},children:e.jsxs(O,{variant:o===g?"default":"outline",className:"cursor-pointer text-[11px]",children:[Oe[g]," · ",D.get(g)]})},g)),o!=="all"?e.jsx(C,{variant:"ghost",size:"sm",className:"h-6 px-2 text-[11px]",onClick:()=>c("all"),children:"Clear filter"}):null]})]}),s?e.jsxs(ne,{className:"space-y-2 pt-0",children:[e.jsx(Z,{value:l,onChange:g=>m(g.target.value),placeholder:"Search name or domain…",className:"h-8 max-w-xs"}),o!=="all"?e.jsx("p",{className:"text-xs text-muted-foreground",children:vt[o]}):null,e.jsxs("div",{className:"divide-y rounded-md border",children:[F.map(({client:g,reasons:P})=>{const z=n.get(g.id);return e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 p-2.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm font-medium",children:[g.name,g.primaryDomain?e.jsx("span",{className:"text-xs font-normal text-muted-foreground",children:g.primaryDomain}):null]}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap gap-x-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["MRR $",Math.round(g.mrrUsd).toLocaleString()]}),e.jsx("span",{children:g.owners.length?g.owners.map(w=>w.name).join(", "):"no owner"}),e.jsxs("span",{children:[g.contacts.filter(w=>w.email).length," contact email(s)"]})]}),e.jsx("div",{className:"mt-1 flex flex-wrap gap-1",children:P.map(w=>e.jsx(O,{variant:"outline",className:"text-[10px]",title:vt[w],children:Oe[w]},w))}),P.includes("no_domain")?(()=>{const w=g.contacts.map(R=>R.email?.split("@")[1]?.toLowerCase()).find(R=>!!R&&!ya.has(R));return w?e.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground",children:["Contact emails suggest ",e.jsx("span",{className:"font-medium",children:w})," — add it on the account so threads and Meet attendees match."]}):null})():null,z&&g.owners.length===0?e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2 text-xs",children:[e.jsx(Ue,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("span",{children:["Suggested owner: ",e.jsx("span",{className:"font-medium",children:z.name})," ·"," ",z.transcripts," matched transcript",z.transcripts===1?"":"s",z.hosName?` · HoS ${z.hosName}`:""]})]}):null]}),e.jsxs("div",{className:"flex items-center gap-2",children:[z&&g.owners.length===0?e.jsxs(C,{size:"sm",disabled:T.isPending,onClick:()=>T.mutate(z),children:[e.jsx(at,{className:"mr-2 h-3.5 w-3.5"})," Accept owner"]}):null,e.jsxs(C,{variant:"outline",size:"sm",disabled:b.isPending,onClick:()=>b.mutate(g.id),children:[e.jsx(Se,{className:`mr-2 h-3.5 w-3.5 ${b.isPending?"animate-spin":""}`})," Check"]})]})]},g.id)}),F.length===0?e.jsx("div",{className:"p-3 text-xs text-muted-foreground",children:"No clients match this filter."}):null]})]}):null]})}const Jt=t=>t>
20?`$${Math.round(t).toLocaleString()}/mo`:"no recorded fee",ba=t=>t?new Date(t).toLocaleDateString(void 0,{day:"numeric",month:"short",year:"numeric"}):"date not recorded";function Nt({workspaceId:t}){const s=ae(),a=$(Xn),l=$(it),m=$(Vt),o=$(Zn),c=$(Jn),r=$(Zt),{data:i,isLoading:x}=J({queryKey:["churned-clients",t],queryFn:()=>a({data:{workspaceId:t}})}),[p,j]=v.useState(!1),[u,h]=v.useState(null),[n,d]=v.useState(""),{data:T}=J({queryKey:["client-book",t],queryFn:()=>l({data:{workspaceId:t}}),enabled:p}),f=()=>{s.invalidateQueries({queryKey:["churned-clients",t]}),s.invalidateQueries({queryKey:["client-book",t]})},b=K({mutationFn:N=>o({data:{workspaceId:t,clientId:N.clientId,reason:N.reason||void 0}}),onSuccess:()=>{_.success("Marked churned — it has left every live book."),j(!1),h(null),d(""),f()},onError:N=>_.error(N.message)}),q=K({mutationFn:N=>c({data:{workspaceId:t,clientId:N.clientId,stage:N.stage}}),onSuccess:()=>f(),onError:N=>_.error(N.message)}),D=v.useMemo(()=>{const N=new Map;for(const I of tt)N.set(I,[]);for(const I of i?.clients??[])N.get(I.winbackStage)?.push(I);return N},[i]);if(x)return e.jsx(de,{className:"h-64 w-full"});const F=!!i?.canEdit;return e.jsx("div",{className:"space-y-4",children:e.jsxs(se,{children:[e.jsxs(ue,{className:"flex flex-row items-start justify-between gap-3 pb-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-base",children:"Churned clients"}),e.jsxs("p",{className:"mt-1 text-sm text-muted-foreground",children:[i?.clients.length??0," account",(i?.clients.length??0)===1?"":"s"," have left",(i?.lostMrr??0)>0?` — ${Jt(i.lostMrr)} of lost fees`:"",". They no longer count towards anyone's book, health scores or automated outreach."]})]}),F?e.jsxs(xe,{open:p,onOpenChange:j,children:[e.jsx(be,{asChild:!0,children:e.jsxs(C,{size:"sm",variant:"outline",children:[e.jsx(Ke,{className:"mr-2 h-4 w-4"})," Mark a client churned"]})}),e.jsxs(ge,{children:[e.jsxs(je,{children:[e.jsx(pe,{children:"Mark a client as churned"}),e.jsx(ve,{children:"The account leaves the strategist's and Head of Strategy's books straight away. Their names are kept here so you know who ran it."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs(V,{value:u??"",onValueChange:h,children:[e.jsx(W,{children:e.jsx(Y,{placeholder:"Choose a client"})}),e.jsx(G,{children:(T?.clients??[]).map(N=>e.jsx(M,{value:N.id,children:N.name},N.id))})]}),e.jsx(Z,{placeholder:"Why did they leave? (optional)",value:n,onChange:N=>d(N.target.value)})]}),e.jsx(we,{children:e.jsx(C,{disabled:!u||b.isPending,onClick:()=>u&&b.mutate({clientId:u,reason:n}),children:"Mark churned"})})]})]}):null]}),e.jsx(ne,{children:(i?.clients.length??0)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No churned clients in your book. When an account leaves, mark it here so it stops counting."}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-5",children:tt.map(N=>e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-2",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between px-1",children:[e.jsx("span",{className:"text-xs font-medium",children:Xt[N]}),e.jsx(O,{variant:"outline",className:"text-[10px]",children:D.get(N)?.length??0})]}),e.jsx("div",{className:"space-y-2",children:(D.get(N)??[]).map(I=>e.jsx(wa,{row:I,canEdit:F,workspaceId:t,onStage:g=>q.mutate({clientId:I.id,stage:g}),onRevived:f,candidatesFn:m,reviveFn:r},I.id))})]},N))})})]})})}function wa({row:t,canEdit:s,workspaceId:a,onStage:l,onRevived:m,candidatesFn:o,reviveFn:c}){const[r,i]=v.useState(!1),[x,p]=v.useState(null),[j,u]=v.useState(null),{data:h}=J({queryKey:["owner-candidates",a],queryFn:()=>o({data:{workspaceId:a}}),enabled:r}),n=K({mutationFn:()=>c({data:{workspaceId:a,clientId:t.id,strategistUserId:x,hosUserId:j}}),onSuccess:()=>{_.success(`${t.name} is back in the book.`),i(!1),m()},onError:d=>_.error(d.message)});return e.jsxs("div",{className:"rounded-md border bg-background p-2 text-xs",children:[e.jsx("div",{className:"font-medium",children:t.name}),t.primaryDomain?e.jsx("div",{className:"text-muted-foreground",children:t.primaryDomain}):null,e.jsxs("div",{className:"mt-1 text-muted-foreground",children:["Left ",ba(t.churnedAt)," · ",Jt(t.mrrUsd)]}),e.jsxs("div",{className:"mt-1 text-muted-foreground",children:["Strategist: ",t.formerStrategist?.name??"—"," · Head of Strategy: ",t.formerHos?.name??"—"]}),t.churnReason?e.jsxs("div",{className:"mt-1 italic text-muted-foreground",children:["“",t.churnReason,"”"]}
2):null,e.jsxs("div",{className:"mt-2 flex items-center gap-1",children:[e.jsxs(V,{value:t.winbackStage,onValueChange:d=>l(d),children:[e.jsx(W,{className:"h-7 text-xs",children:e.jsx(Y,{})}),e.jsx(G,{children:tt.map(d=>e.jsx(M,{value:d,className:"text-xs",children:Xt[d]},d))})]}),s?e.jsxs(xe,{open:r,onOpenChange:i,children:[e.jsx(be,{asChild:!0,children:e.jsx(C,{size:"icon",variant:"ghost",className:"h-7 w-7",title:"Bring this client back",children:e.jsx(Ss,{className:"h-3.5 w-3.5"})})}),e.jsxs(ge,{children:[e.jsxs(je,{children:[e.jsxs(pe,{children:["Bring ",t.name," back"]}),e.jsx(ve,{children:"Choose who runs the account now. It returns to their book and starts being scored again."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs(V,{value:x??"",onValueChange:p,children:[e.jsx(W,{children:e.jsx(Y,{placeholder:"Strategist"})}),e.jsx(G,{children:(h??[]).filter(d=>d.isStrategist).map(d=>e.jsx(M,{value:d.userId,children:d.name},d.userId))})]}),e.jsxs(V,{value:j??"",onValueChange:u,children:[e.jsx(W,{children:e.jsx(Y,{placeholder:"Head of Strategy"})}),e.jsx(G,{children:(h??[]).filter(d=>d.isHos).map(d=>e.jsx(M,{value:d.userId,children:d.name},d.userId))})]})]}),e.jsx(we,{children:e.jsx(C,{disabled:!x&&!j||n.isPending,onClick:()=>n.mutate(),children:"Bring back"})})]})]}):null,t.viewerWasOwner?e.jsx(Wt,{workspaceId:a,clientId:t.id,clientName:t.name,churned:!0,compact:!0}):null]})]})}const Ca=t=>t?new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"}):"—";function Sa({workspaceId:t,ownerUserId:s=null}){const[a,l]=v.useState(""),[m,o]=v.useState("client"),c=ae(),r=$(ks),i=$(_s),x=$(Fs),p=$($s),{data:j,isLoading:u}=J({queryKey:["clients-unmapped-meetings",t,m,s],queryFn:()=>r({data:{workspaceId:t,bucket:m,ownerUserId:s}}),enabled:!!t,staleTime:6e4}),h=K({mutationFn:f=>x({data:{workspaceId:t,...f}}),onSuccess:(f,b)=>{_.success(b.kind==="prospect"?"Marked as a prospect sales call — it no longer counts as client evidence.":b.kind==="internal"?"Marked as an internal team meeting — it's off the worklist and never counts as client evidence.":"Marked as a client meeting — it can be attached to a client."),c.invalidateQueries({queryKey:["clients-unmapped-meetings",t]})},onError:f=>_.error(f.message)}),n=K({mutationFn:f=>i({data:{workspaceId:t,...f}}),onSuccess:f=>{_.success(f.learned.length?`Meeting attached — also learned ${f.learned.join(" + ")} so future meetings match automatically.`:"Meeting attached to the client."),c.invalidateQueries({queryKey:["clients-unmapped-meetings",t]}),c.invalidateQueries({queryKey:["client-book",t]})},onError:f=>_.error(f.message)}),d=K({mutationFn:f=>p({data:{workspaceId:t,...f}}),onSuccess:f=>{_.success(f.created?"Client created and the meeting attached. Set the strategist and Head of Strategy on the client card.":"That client already existed — the meeting is attached to it."),c.invalidateQueries({queryKey:["clients-unmapped-meetings",t]}),c.invalidateQueries({queryKey:["client-book",t]})},onError:f=>_.error(f.message)}),T=v.useMemo(()=>{const f=j?.meetings??[],b=a.trim().toLowerCase();return b?f.filter(q=>(q.title??"").toLowerCase().includes(b)||q.attendees.some(D=>D.includes(b))):f},[j,a]);return e.jsxs(se,{children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs(he,{className:"flex items-center gap-2 text-base",children:[e.jsx(Bt,{className:"h-4 w-4 text-muted-foreground"}),"Unmapped meetings",j?e.jsx(O,{variant:"outline",children:j.total}):null]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Synced Meet transcripts Brain couldn't attach to a client on its own. Sales calls with prospects are labelled and kept out of client health — switch to the Prospect calls tab to review or correct them. Attach a client meeting here and, if you tick the learn box, the attendee's company domain or address is saved on the client so the next meeting matches by itself."})]}),e.jsxs(ne,{className:"space-y-3",children:[e.jsx(Re,{value:m,onValueChange:f=>o(f),children:e.jsxs(Ie,{children:[e.jsx(ee,{value:"client",children:"Client meetings"}),e.jsx(ee,{value:"prospect",children:"Prospect calls"})]})}),e.jsx(Z,{value:a,onChange:f=>l(f.target.value),placeholder:"Search meeting title or attendee…",className:"max-w-sm"}),u?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading meetings…"}):(j?.clients.length??0)===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"No clients in your book yet — nothing to map meetings to."}):T.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:m==="prospect"?"
2No prospect sales calls in this window.":"Every synced client meeting is attached to a client. Nothing to do here."}):T.map(f=>e.jsx(ka,{meeting:f,clients:j?.clients??[],busy:n.isPending||h.isPending||d.isPending,onAttach:b=>n.mutate({transcriptId:f.transcriptId,...b}),onRelabel:b=>h.mutate({transcriptId:f.transcriptId,kind:b}),onCreateClient:b=>d.mutate({transcriptId:f.transcriptId,clientName:b})},f.transcriptId))]})]})}function ka({meeting:t,clients:s,busy:a,onAttach:l,onRelabel:m,onCreateClient:o}){const c=t.suggestedClientIds[0]??"",[r,i]=v.useState(c),[x,p]=v.useState(t.candidateDomains.length>0),[j,u]=v.useState(!1),h=t.candidateDomains[0]??null,n=t.candidateEmails[0]??null,d=(t.title??"").split(/<>|[|\u2013-]/)[0]?.trim().slice(0,120)??"",[T,f]=v.useState(!1),[b,q]=v.useState(d);return e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:t.title||"Untitled meeting"}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:Ca(t.occurredAt)}),e.jsxs(O,{variant:t.meetingKind==="prospect"?"secondary":"outline",children:[t.meetingKind==="prospect"?"prospect call":t.meetingKind==="client"?"client meeting":"unclassified",t.meetingKindManual?" · set by hand":""]}),t.candidateDomains.map(D=>e.jsx(O,{variant:"outline",children:D},D)),t.reason?e.jsxs("span",{children:["· ",t.reason.replace(/_/g," ")]}):null]}),t.participants.length>0?e.jsxs("div",{className:"mt-1.5 space-y-1 text-xs",children:[e.jsx("div",{className:"text-muted-foreground",children:"Who was on this call"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.participants.map((D,F)=>e.jsxs(O,{variant:D.role==="guest"?"secondary":"outline",className:"max-w-full whitespace-normal break-words font-normal",children:[e.jsx("span",{className:"font-medium",children:D.name}),e.jsxs("span",{className:"ml-1 text-muted-foreground",children:[D.role==="host"?"· host":D.role==="team"?"· our team":D.role==="guest"?"· guest":"· unknown",D.email?` · ${D.email}`:""]})]},`${D.name}-${D.email??""}-${F}`))})]}):null,t.candidateEmails.length>0?e.jsx("div",{className:"mt-1 truncate text-xs text-muted-foreground",children:t.candidateEmails.slice(0,4).join(", ")}):null,t.sourceEmail?e.jsxs("div",{className:"mt-1 truncate text-xs text-muted-foreground",children:["Pulled from: ",t.sourceEmail]}):null,t.meetingKindReason?e.jsxs("div",{className:"mt-1 text-xs text-muted-foreground",children:["Why: ",t.meetingKindReason]}):null]}),c?e.jsxs(O,{variant:"outline",className:"gap-1",children:[e.jsx(ss,{className:"h-3 w-3"})," suggested match"]}):null]}),e.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:t.meetingKind==="prospect"?e.jsx(C,{size:"sm",variant:"outline",disabled:a,onClick:()=>m("client"),children:"This is a client meeting"}):e.jsxs(e.Fragment,{children:[e.jsxs(V,{value:r,onValueChange:i,children:[e.jsx(W,{className:"w-[260px]",children:e.jsx(Y,{placeholder:"Pick a client…"})}),e.jsx(G,{children:s.map(D=>e.jsxs(M,{value:D.id,children:[D.name,D.primaryDomain?` · ${D.primaryDomain}`:""]},D.id))})]}),e.jsxs(C,{size:"sm",disabled:!r||a,onClick:()=>l({clientId:r,learnDomain:x&&h?h:null,learnEmail:j&&n?n:null}),children:[e.jsx(Ds,{className:"mr-2 h-4 w-4"})," Attach"]}),e.jsx(C,{size:"sm",variant:"ghost",disabled:a,onClick:()=>m("prospect"),children:"Not a client — prospect call"}),e.jsxs(C,{size:"sm",variant:"ghost",disabled:a,onClick:()=>m("internal"),children:[e.jsx(Me,{className:"mr-2 h-4 w-4"})," Internal meeting"]}),e.jsxs(C,{size:"sm",variant:"outline",disabled:a,onClick:()=>f(D=>!D),children:[e.jsx(Lt,{className:"mr-2 h-4 w-4"})," New client from this meeting"]})]})}),T&&t.meetingKind!=="prospect"?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2 rounded-md border bg-muted/40 p-2",children:[e.jsx(Z,{value:b,onChange:D=>q(D.target.value),placeholder:"Client name",className:"h-8 max-w-[260px]"}),e.jsx(C,{size:"sm",disabled:a||b.trim().length<2,onClick:()=>{o(b.trim()),f(!1)},children:"Create and attach"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Creates the client card, attaches this meeting and remembers the guest's company so future meetings match on their own."})]}):null,e.jsxs("div",{className:`mt-2 flex flex-wrap gap-4 text-xs ${t.meetingKind==="prospect"?"hidden":""}`,children:[h?e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx($e,{checked:x,onCheckedChange:D=>p(D===!0)}),e.jsxs("span",{children:["Add ",e.jsx("span",{className:"font-medium",children:h})," to this client (future meetings auto-match)"]})]}):null,n?e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx($e,{checked:j,onCheckedChange:D=>u(D===!0)}),e.jsxs("span",{children:["Save ",e.jsx("span",{className:"font-medium",children:n})," as a client contact"]})]}):null]})]})}const _a=t=>t?new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"}):"—",Fa=t=>t?Math.max(0,Math.round((Date.now()-new Date(t).getTime())/864e5)):null;function bt({workspaceId:t}){const[s,a]=v.useState(null),l=$(Ms),{data:m,isLoading:o}=J({queryKey:["clients-mapping-backlog",t],queryFn:()=>l({data:{workspaceId:t}}),enabled:!!t,staleTime:6e4}),c=m?.rows??[],r=c.find(i=>i.userId===s)??null;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(se,{children:[e.jsxs(ue,{className:"pb-3",children:[e.jsxs(he,{className:"flex items-center gap-2 text-base",children:[e.jsx(Me,{className:"h-4 w-4"}),"Who still has meetings to map"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each recording comes from one person's connected calendar — that person maps it. Heads of Strategy also see their strategists here."})]}),e.jsx(ne,{className:"space-y-2",children:o?e.jsxs(e.Fragment,{children:[e.jsx(de,{className:"h-14 w-full"}),e.jsx(de,{className:"h-14 w-full"})]}):c.length===0?e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"Nothing waiting — every synced meeting is attached to a client."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted/50 px-3 py-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:m?.seesOthers?"Team backlog":"Your backlog"}),e.jsxs("span",{className:"font-semibold",children:[m?.totalPending??0," meetings"]})]}),c.map(i=>{const x=Fa(i.oldestAt),p=i.userId===s;return e.jsxs("div",{className:`flex flex-wrap items-center justify-between gap-3 rounded-md border px-3 py-2 ${p?"border-primary bg-primary/5":""}`,children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate font-medium",children:i.name}),i.isMe?e.jsx(O,{variant:"secondary",children:"You"}):null,e.jsx(O,{variant:"outline",children:i.roleLabel})]}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-x-3 text-xs text-muted-foreground",children:[i.email?e.jsx("span",{className:"truncate",children:i.email}):null,i.headOfStrategyName?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ut,{className:"h-3 w-3"}),"Reports to ",i.headOfStrategyName]}):null,e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bt,{className:"h-3 w-3"}),"Oldest ",_a(i.oldestAt),x!==null?` (${x}d)`:""]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-lg font-semibold tabular-nums",children:i.pending}),i.userId?e.jsx(C,{size:"sm",variant:p?"default":"outline",onClick:()=>a(p?null:i.userId),children:p?"Clear filter":"View list"}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"No owner on the sync"})]})]},i.userId??"unowned")})]})})]}),r?e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing meetings pulled from ",e.jsx("span",{className:"font-medium",children:r.name}),"'s calendar."]}):null,e.jsx(Sa,{workspaceId:t,ownerUserId:s})]})}const $a=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-payments_functions_ts--listClientPayments_createServerFn_handler")),Ma=L({method:"POST"}).middleware([A]).handler(U("src_lib_client-payments_functions_ts--syncStripePaymentsNow_createServerFn_handler")),Le=t=>
2t.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:0}),wt=t=>new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"});function Ct({workspaceId:t}){const s=ae(),a=$($a),l=$(Ma),[m,o]=v.useState("365"),[c,r]=v.useState(""),{data:i,isLoading:x,error:p}=J({queryKey:["client-payments",t,m],queryFn:()=>a({data:{workspaceId:t,days:Number(m)}}),staleTime:6e4}),j=K({mutationFn:n=>l({data:{workspaceId:t,backfill:n}}),onSuccess:n=>{n.error?_.error(n.error):_.success(`Stripe synced — ${n.events} money events, ${n.clientsCreated} new client${n.clientsCreated===1?"":"s"} from payments`),s.invalidateQueries({queryKey:["client-payments"]}),s.invalidateQueries({queryKey:["client-pool"]}),s.invalidateQueries({queryKey:["client-book"]})},onError:n=>_.error(n instanceof Error?n.message:"Could not pull payments from Stripe")}),u=v.useMemo(()=>{const n=i?.rows??[],d=c.trim().toLowerCase();return d?n.filter(T=>(T.clientName??"").toLowerCase().includes(d)||(T.payerEmail??"").toLowerCase().includes(d)||(T.payerName??"").toLowerCase().includes(d)):n},[i,c]);if(x)return e.jsx(de,{className:"h-64 w-full"});if(p)return e.jsx("p",{className:"text-sm text-destructive",children:p instanceof Error?p.message:"Could not load payments"});if(!i)return null;const h=i.totals;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2 text-sm font-semibold",children:[e.jsx(Kt,{className:"h-4 w-4"})," Payments"]}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Live from Stripe. Payments land on the client card automatically; a payer we have never seen opens a new account with no owner, ready to be claimed in Client mapping.",i.lastSyncedAt?` Last pull ${wt(i.lastSyncedAt)}.`:" Never pulled yet."]})]}),i.canSync?e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(C,{variant:"outline",size:"sm",disabled:j.isPending,onClick:()=>j.mutate(!1),children:[e.jsx(Se,{className:`mr-2 h-3.5 w-3.5 ${j.isPending?"animate-spin":""}`}),"Sync now"]}),e.jsx(C,{variant:"secondary",size:"sm",disabled:j.isPending,onClick:()=>j.mutate(!0),children:"Backfill history"})]}):null]}),i.syncError?e.jsxs("p",{className:"flex items-center gap-2 rounded-md border border-destructive/40 bg-destructive/10 p-2 text-xs text-destructive",children:[e.jsx(qe,{className:"h-3.5 w-3.5"})," Stripe said: ",i.syncError]}):null,e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(Ae,{label:"Collected",value:Le(h.collectedUsd),hint:`${h.payments} payments`}),e.jsx(Ae,{label:"Recurring",value:Le(h.recurringUsd),hint:"Invoices & subscriptions"}),e.jsx(Ae,{label:"One-off",value:Le(h.oneOffUsd),hint:"Checkouts & manual charges"}),e.jsx(Ae,{label:"Needs a client",value:String(h.unmatched),hint:`${h.unownedClients} client${h.unownedClients===1?"":"s"}
2 with no owner`})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Z,{value:c,onChange:n=>r(n.target.value),placeholder:"Search client, payer name or email",className:"h-9 max-w-xs"}),e.jsxs(V,{value:m,onValueChange:o,children:[e.jsx(W,{className:"h-9 w-[150px]",children:e.jsx(Y,{})}),e.jsxs(G,{children:[e.jsx(M,{value:"30",children:"Last 30 days"}),e.jsx(M,{value:"90",children:"Last 90 days"}),e.jsx(M,{value:"365",children:"Last 12 months"}),e.jsx(M,{value:"1100",children:"All time"})]})]}),i.canSeeUnmatched?null:e.jsx("span",{className:"text-xs text-muted-foreground",children:"Showing payments for your clients only."})]}),u.length===0?e.jsx("p",{className:"rounded-md border border-dashed p-6 text-center text-sm text-muted-foreground",children:"No payments in this window yet."}):e.jsx("div",{className:"overflow-hidden rounded-md border",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/50 text-xs uppercase text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left",children:"Date"}),e.jsx("th",{className:"px-3 py-2 text-left",children:"Client"}),e.jsx("th",{className:"px-3 py-2 text-left",children:"Payer"}),e.jsx("th",{className:"px-3 py-2 text-left",children:"What"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Amount"})]})}),e.jsx("tbody",{children:u.map(n=>e.jsxs("tr",{className:"border-t",children:[e.jsx("td",{className:"whitespace-nowrap px-3 py-2 text-muted-foreground",children:wt(n.occurredAt)}),e.jsx("td",{className:"px-3 py-2",children:n.clientId?e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx(ns,{to:"/clients",className:"font-medium underline-offset-2 hover:underline",children:n.clientName??"Client"}),n.cameFromPayment?e.jsxs(O,{variant:"secondary",className:"gap-1",children:[e.jsx(Lt,{className:"h-3 w-3"})," New from payment"]}):null,n.clientHasOwner?null:e.jsx(O,{variant:"outline",className:"text-amber-600",children:"Needs an owner"})]}):e.jsx(O,{variant:"outline",className:"text-muted-foreground",children:"Not linked yet"})}),e.jsx("td",{className:"px-3 py-2",children:e.jsxs("div",{className:"leading-tight",children:[e.jsx("div",{children:n.payerName??"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:n.payerEmail??"no email"})]})}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground",children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[n.recurring?e.jsx(zs,{className:"h-3.5 w-3.5"}):null,n.description??(n.recurring?"Recurring payment":"Payment")]})}),e.jsx("td",{className:"whitespace-nowrap px-3 py-2 text-right font-medium",children:Le(n.amountUsd)})]},n.id))})]})})]})}function Ae({label:t,value:s,hint:a}){return e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:t}),e.jsx("div",{className:"mt-1 text-lg font-semibold",children:s}),e.jsx("div",{className:"text-xs text-muted-foreground",children:a})]})}function ii(){const t=$(as),{data:s}=J({queryKey:["workspaces"],queryFn:()=>t({})}),a=s?.[0]?.id,l=s?.[0]?.current_role??null,m=l==="owner"||l==="admin",o=$(is),{data:c}=J({queryKey:["am-i-strategy-head",a],queryFn:()=>o({data:{workspaceId:a}}),enabled:!!a,staleTime:3e5}),r=m||!!c?.isStrategyHead,[i,x]=v.useState("book");return e.jsxs("div",{className:"mx-auto max-w-6xl space-y-4 p-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"flex items-center gap-2 text-xl font-semibold",children:[e.jsx(Rt,{className:"h-5 w-5"})," Clients"]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Accounts you own, ranked so the danger zone surfaces first. Every score is backed by quotes from real calls and email — expand “Why” to see them."})]}),a?r?e.jsxs(Re,{value:i,onValueChange:x,children:[e.jsxs(Ie,{children:[e.jsx(ee,{value:"book",children:"My book"}),e.jsx(ee,{value:"payments",children:"Payments"}),e.jsx(ee,{value:"mapping",children:"Client mapping"}),e.jsx(ee,{value:"no-signal",children:"Clients with no signal"}),e.jsx(ee,{value:"churned",children:"Churned"}),e.jsx(ee,{value:"coverage",children:"Call coverage"}),e.jsx(ee,{value:"unmapped",children:"Unmapped meetings"}),e.jsx(ee,{value:"emails",children:"Emails to check"}),e.jsx(ee,{value:"duplicates",children:"Duplicates"})]}),e.jsx(te,{value:"book",className:"mt-4",children:e.jsx(xt,{workspaceId:a})}),e.jsx(te,{value:"payments",className:"mt-4",children:e.jsx(Ct,{workspaceId:a})}),e.jsx(te,{value:"mapping",className:"mt-4",children:e.jsx(oa,{workspaceId:a,onReviewDuplicates:()=>x("duplicates")})}),e.jsx(te,{value:"no-signal",className:"mt-4",children:e.jsx(yt,{workspaceId:a})}),e.jsx(te,{value:"churned",className:"mt-4",children:e.jsx(Nt,{workspaceId:a})}),e.jsx(te,{value:"coverage",className:"mt-4",children:e.jsx(jt,{workspaceId:a})}),e.jsx(te,{value:"unmapped",className:"mt-4",children:e.jsx(bt,{workspaceId:a})}),e.jsx(te,{value:"emails",className:"mt-4",children:e.jsx(pa,{workspaceId:a})}),e.jsx(te,{value:"duplicates",className:"mt-4",children:e.jsx(us,{workspaceId:a})})]}):e.jsxs(Re,{defaultValue:"book",children:[e.jsxs(Ie,{children:[e.jsx(ee,{value:"book",children:"My book"}),e.jsx(ee,{value:"payments",children:"Payments"}),e.jsx(ee,{value:"no-signal",children:"Clients with no signal"}),e.jsx(ee,{value:"churned",children:"Churned"}),e.jsx(ee,{value:"coverage",children:"Call coverage"}),e.jsx(ee,{value:"unmapped",children:"Unmapped meetings"})]}),e.jsx(te,{value:"book",className:"mt-4",children:e.jsx(xt,{workspaceId:a})}),e.jsx(te,{value:"payments",className:"mt-4",children:e.jsx(Ct,{workspaceId:a})}),e.jsx(te,{value:"no-signal",className:"mt-4",children:e.jsx(yt,{workspaceId:a})}),e.jsx(te,{value:"churned",className:"mt-4",children:e.jsx(Nt,{workspaceId:a})}),e.jsx(te,{value:"coverage",className:"mt-4",children:e.jsx(jt,{workspaceId:a})}),e.jsx(te,{value:"unmapped",className:"mt-4",children:e.jsx(bt,{workspaceId:a})})]}):e.jsx(de,{className:"h-64 w-full"})]})}
2export{ii as component};

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.