PageSourceSearch

https://app.ambiguous.ai/assets/CrmPage-CGapFAzX.js

js ambiguous.ai collected 2026-10-05 01:05:07 UTC 487,983 bytes, 71 lines download raw bytes

1import{b as Ie,j as e,r as o}from"./vendor-react-7kK5Bxv7.js";import{u as Vl,a9 as vo,aa as bo,ab as go,y as dt,z as xt,F as mt,G as be,H as ra,B as L,gd as dl,aY as me,aZ as ue,a_ as ve,a$ as pe,b0 as te,a1 as xl,aF as Bl,cC as hr,cv as yo,bn as fo,bu as qr,bo as es,ad as ml,L as J,D as Ke,r as Qe,t as He,v as Ye,x as nt,S as _e,bS as Q,E as De,aP as jo,w as vr,n as Tt,J as Ce,e as Je,U as No,I as Re,C as we,b9 as de,bt as Ul,ah as wo,bT as wt,ge as ts,T as br,b1 as Ae,aG as ko,aH as Co,aI as ul,aJ as pl,aj as So,d3 as cr,aU as _o,bR as Vr,W as Do,_ as zo,el as $o,b5 as Ao,dZ as bs,d_ as jt,fd as gs,fe as ys,d$ as fs,gf as To,e0 as Eo,g0 as Lo,cc as Zt,X as js,gg as ut,a2 as Io,a3 as Po,a4 as Ro,fc as Wl,e8 as Ns,g1 as ws,a5 as Gl,au as Fo}from"./index-CY_U-MX5.js";import{b as ks}from"./vendor-tanstack-Dd03GJo7.js";import{n as pa,bj as Mo,R as ye,C as Se,aV as fa,x as $a,z as We,T as he,p as oe,B as Fe,cl as Nt,aA as hl,Q as Oo,ai as ja,bp as Kl,bf as dr,a9 as Ne,dg as Ze,a_ as Xt,aZ as xr,a4 as Ee,U as ga,c6 as as,k as Na,b4 as wa,aj as ht,ax as ka,X as gr,a6 as Cs,be as ea,c as Ve,A as qo,$ as Ql,W as ze,bX as Ss,M as Be,dj as kt,u as sa,a8 as Ue,i as Vo,ag as ta,ao as ot,bW as Hl,L as _s,a3 as la,aw as Bo,t as ge,a0 as Yl,d as Uo,f as Wo,a1 as Go,bc as Ct,ab as mr,l as Jl,bu as Zl,y as Ca,bS as yr,b6 as Ko,a as Qo,bl as Ho,aC as Yo,j as Sa,ah as Xl,dz as Ds,e as zs,az as en,bb as tn,af as Jo,b8 as Zo,ak as Xo}from"./realtime-mux-D9UASGOE.js";import{P as ei}from"./PullToRefresh-Drf94SsU.js";import{u as ti}from"./useGlobalNewShortcut-ijAYZlxm.js";import{u as Br}from"./useEntityDetailPanel-DvcBBcy9.js";import{T as rs}from"./TextareaEmojiAutocomplete-C9r0qh4P.js";import{c as ai}from"./mergeSeed-CX9QGoEy.js";import{C as an}from"./eventModules-Jr1pGGHH.js";import{D as aa}from"./DetailPanelHeader-BxoemHK8.js";import{C as Xe,a as vt,b as rn,c as ri,u as si}from"./CrmSurfaceHeader-CitpEzeF.js";import{useCrmStore as G,LIFECYCLE_STAGES as It,CONTACT_GROUP_COLORS as li,billingIntervalSuffix as ur,PROPERTY_FIELD_TYPES as ni}from"./crmStore-BN-YBdBM.js";import{d as oi,o as ii}from"./download-CoxLfzn7.js";import{R as Ht,C as tr,X as ar,Y as rr,T as Yt}from"./CartesianChart-CdRBl1QB.js";import{B as ss,a as ha,C as ya}from"./BarChart-Bzp_iI1I.js";import{L as va}from"./Legend-SnNnG32B.js";import{R as sr,A as ci,a as Ur}from"./AreaChart-1EkZsvgY.js";import{P as sn,a as ln}from"./PieChart-DIvh7q1n.js";import{f as di}from"./camera-BK_01vqn.js";import{d as fr}from"./csv-BL7cbFD8.js";import{a as xi}from"./sanitize-DFtTX6mG.js";import{S as mi}from"./ShareDialog-Bv_zWSIU.js";import{t as vl}from"./humanize-OqMG-CRw.js";(function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};t.SENTRY_RELEASE={id:"266446510ecd5dbce76808c272265ca5e766a576"};var a=new t.Error().stack;a&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[a]="4d81ab7c-a815-4f08-b907-64963d5f4a90",t._sentryDebugIdIdentifier="sentry-dbid-4d81ab7c-a815-4f08-b907-64963d5f4a90")}catch{}})();function Le({value:t,onSave:a,placeholder:r="",emptyLabel:l="Add value",type:n="text",multiline:s=!1,className:i,textClassName:d,disabled:c=!1,ariaLabel:m,displayValue:p}){const[u,x]=Ie.useState(!1),[w,N]=Ie.useState(t),h=Ie.useRef(null);Ie.useEffect(()=>{u||N(t)},[t,u]),Ie.useEffect(()=>{u&&h.current&&(h.current.focus(),"select"in h.current&&h.current.select())},[u]);const v=async()=>{const y=w.trim();if(y===t.trim()){x(!1);return}try{await a(y)}finally{x(!1)}},j=()=>{N(t),x(!1)},f=y=>{y.key==="Enter"&&!s||y.key==="Enter"&&s&&(y.metaKey||y.ctrlKey)?(y.preventDefault(),v()):y.key==="Escape"&&(y.preventDefault(),y.stopPropagation(),j())};if(u){const y=pa("w-full rounded-[var(--radius-sm)] px-2 py-0.5 -mx-2","bg-[var(--color-bg-primary)] text-[var(--color-text-primary)]","border border-[var(--color-accent)]","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--color-accent)] focus-visible:ring-offset-0","pointer-coarse:min-h-11 pointer-coarse:text-base",d);return s?e.jsx("textarea",{ref:h,value:w,onChange:b=>N(b.target.value),onBlur:v,onKeyDown:f,placeholder:r,"aria-label":m,rows:Math.max(2,w.split(`
2`).length),className:pa(y,"resize-y",i)}):e.jsx("input",{ref:h,type:n,value:w,onChange:b=>N(b.target.value),onBlur:v,onKeyDown:f,placeholder:r,"aria-label":m,className:pa(y,i)})}const z=!t||!t.trim();return e.jsx("button",{type:"button",onClick:()=>!c&&x(!0),disabled:c,"aria-label":m??(z?l:`Edit ${t}`),className:pa("text-left rounded-[var(--radius-sm)] px-2 py-0.5 -mx-2","border border-transparent","transition-colors duration-[var(--duration-micro)]","hover:bg-[var(--color-bg-secondary)] hover:border-[var(--color-bg-tertiary)]","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--color-accent)]","disabled:opacity-50 disabled:pointer-events-none","cursor-text","pointer-coarse:min-h-11 pointer-coarse:inline-flex pointer-coarse:items-center pointer-coarse:text-base",d,i),children:z?e.jsxs("span",{className:"font-medium text-[var(--color-accent-text)]",children:["+ ",l]}):e.jsx("span",{className:"whitespace-pre-wrap",children:p??t})})}const ui=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),pi=ui?"⌘":"Ctrl+",hi=[{id:"crm:next-item",module:"crm",combo:"↓",description:"Next contact / deal",category:"navigation",when:"list"},{id:"crm:prev-item",module:"crm",combo:"↑",description:"Previous contact / deal",category:"navigation",when:"list"},{id:"crm:close-panel",module:"crm",combo:"Escape",description:"Close detail panel / dialog",category:"navigation",when:"always"},{id:"crm:search",module:"crm",combo:`${pi}F`,description:"Search contacts / companies",category:"navigation",when:"always"},{id:"crm:delete",module:"crm",combo:"Delete",description:"Delete selected record(s)",category:"editing",when:"list"}
2,{id:"crm:tab-dashboard",module:"crm",combo:"G 1",description:"Go to Dashboard tab",category:"view",when:"always"},{id:"crm:tab-contacts",module:"crm",combo:"G 2",description:"Go to Contacts tab",category:"view",when:"always"},{id:"crm:tab-companies",module:"crm",combo:"G 3",description:"Go to Companies tab",category:"view",when:"always"},{id:"crm:tab-deals",module:"crm",combo:"G 4",description:"Go to Deals tab",category:"view",when:"always"}];function vi(t){const a={"crm:tab-dashboard":"reports","crm:tab-contacts":"contacts","crm:tab-companies":"companies","crm:tab-deals":"deals"};return hi.map(r=>a[r.id]?{...r,action:()=>t.setView(a[r.id])}:r)}function $s({size:t,children:a,viewBox:r="0 0 240 160",...l}){return e.jsx("svg",{width:t??"100%",height:t?t*160/240:void 0,viewBox:r,fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"text-[var(--color-text-quaternary)]",...l,children:a})}function bi(t){return e.jsxs($s,{...t,children:[e.jsx("line",{x1:"20",y1:"142",x2:"220",y2:"142",opacity:"0.4"}),e.jsx("rect",{x:"28",y:"28",width:"56",height:"18",rx:"3"}),e.jsx("rect",{x:"28",y:"52",width:"56",height:"18",rx:"3"}),e.jsx("rect",{x:"28",y:"76",width:"56",height:"18",rx:"3",opacity:"0.6"}),e.jsx("rect",{x:"24",y:"20",width:"64",height:"110",rx:"6",opacity:"0.3"}),e.jsx("rect",{x:"96",y:"28",width:"56",height:"18",rx:"3"}),e.jsx("rect",{x:"96",y:"52",width:"56",height:"18",rx:"3",opacity:"0.6"}),e.jsx("rect",{x:"92",y:"20",width:"64",height:"110",rx:"6",opacity:"0.3"}),e.jsx("rect",{x:"164",y:"28",width:"56",height:"24",rx:"3",fill:"var(--color-module-crm, #FF7A59)",fillOpacity:"0.15",stroke:"var(--color-module-crm, #FF7A59)"}),e.jsx("path",{d:"M189 36v8M186 38.5h5a1.5 1.5 0 0 1 0 3h-4a1.5 1.5 0 0 0 0 3h5",stroke:"var(--color-module-crm, #FF7A59)",strokeWidth:"1.25"}),e.jsx("rect",{x:"160",y:"20",width:"64",height:"110",rx:"6",opacity:"0.3"})]})}function gi(t){return e.jsxs($s,{...t,children:[e.jsx("circle",{cx:"60",cy:"62",r:"14",opacity:"0.6"}),e.jsx("path",{d:"M38 104c0-11 10-20 22-20s22 9 22 20",opacity:"0.4"}),e.jsx("circle",{cx:"120",cy:"58",r:"16",stroke:"var(--color-module-crm, #FF7A59)",fill:"var(--color-module-crm, #FF7A59)",fillOpacity:"0.15"}),e.jsx("path",{d:"M94 104c0-13 12-24 26-24s26 11 26 24",stroke:"var(--color-module-crm, #FF7A59)"}),e.jsx("circle",{cx:"180",cy:"62",r:"14",opacity:"0.6"}),e.jsx("path",{d:"M158 104c0-11 10-20 22-20s22 9 22 20",opacity:"0.4"}),e.jsx("line",{x1:"20",y1:"130",x2:"220",y2:"130",opacity:"0.3"})]})}function yi(t){return e.jsxs($s,{...t,children:[e.jsx("rect",{x:"56",y:"28",width:"128",height:"104",rx:"8"}),e.jsx("line",{x1:"72",y1:"48",x2:"128",y2:"48",opacity:"0.7"}),e.jsx("line",{x1:"72",y1:"58",x2:"108",y2:"58",opacity:"0.4"}),e.jsx("line",{x1:"72",y1:"72",x2:"168",y2:"72",opacity:"0.3"}),e.jsx("line",{x1:"72",y1:"84",x2:"140",y2:"84",opacity:"0.4"}),e.jsx("line",{x1:"72",y1:"94",x2:"152",y2:"94",opacity:"0.4"}),e.jsx("line",{x1:"72",y1:"104",x2:"132",y2:"104",opacity:"0.4"}),e.jsx("line",{x1:"72",y1:"118",x2:"168",y2:"118",opacity:"0.3"}),e.jsx("path",{d:"M148 112v12",stroke:"var(--color-module-crm, #FF7A59)",strokeWidth:"2",strokeLinecap:"round"}),e.jsx("circle",{cx:"148",cy:"118",r:"10",stroke:"var(--color-module-crm, #FF7A59)",fill:"var(--color-module-crm, #FF7A59)",fillOpacity:"0.12"}),e.jsx("path",{d:"M144 114h6a1.5 1.5 0 0 1 0 3h-4a1.5 1.5 0 0 0 0 3h6",stroke:"var(--color-module-crm, #FF7A59)",strokeWidth:"1.1"})]})}function bl({entityType:t,currentLayout:a,onApplyLayout:r}){const l=Vl(P=>{var H;return(H=P.user)==null?void 0:H.id})??null,{savedViews:n,savedViewsLoading:s,activeViewId:i,loadSavedViews:d,applyView:c,clearActiveView:m,saveCurrentAsView:p,deleteSavedView:u,updateSavedView:x}=G(),[w,N]=o.useState(!1),[h,v]=o.useState(!1),[j,f]=o.useState(""),[z,y]=o.useState(null),[b,g]=o.useState("");o.useEffect(()=>{w&&d(t)},[w,t,d]);const E=n.filter(P=>P.entity_type===t),A=E.find(P=>P.id===i),U=async()=>{if(!j.trim())return;v(!0),await p(j.trim(),!1,a?{layout:a}:void 0)&&f(""),v(!1)},D=async P=>{b.trim()&&(await x(P,{name:b.trim()}),y(null),g(""))},O=P=>{c(P);const H=P.filters.layout;typeof H=="string"&&(r==null||r(H)),N(!1)};return e.jsxs(vo,{open:w,onOpenChange:N,children:[e.jsx(bo,{asChild:!0,children:e.jsxs("button",{"data-testid":"crm-saved-views-trigger",className:`inline-flex items-center gap-2 h-7 pointer-coarse:h-11 rounded-full border text-[length:var(--text-label-s)] font-medium cursor-pointer pl-3 pr-2 transition-colors max-[479px]:size-11 max-[479px]:shrink-0 max-[479px]:justify-center max-[479px]:px-0 ${A?"border-[var(--color-accent)] bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]":"border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[var(--color-text-secondary)] hover:border-[var(--color-text-quaternary)]"}`,"aria-label":"Views",title:"Open or save a search, filter, and layout",children:[e.jsx(Mo,{size:13}),e.jsxs("span",{className:"max-w-[120px] truncate max-[479px]:sr-only",children:[e.jsx("span",{className:"sm:hidden",children:"Views"}),e.jsx("span",{className:"hidden sm:inline",children:A?A.name:"Views"})]}),e.jsx(ye,{size:12,className:"opacity-60 max-lg:hidden"})]})}),e.jsxs(go,{align:"center",side:"bottom",sideOffset:4,avoidCollisions:!1,collisionPadding:16,className:"w-72 max-md:w-[calc(100vw-2rem)] p-0 rounded-[var(--radius-lg)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] shadow-lg max-md:max-h-[70vh] max-md:overflow-y-auto",children:[e.jsx("div",{className:"px-3 py-2 border-b border-[var(--color-bg-tertiary)]",children:e.jsx("h3",{className:"text-[length:var(--text-label-l)] font-semibold text-[var(--color-text-primary)]",children:t==="deals"?"Pipeline views":"People views"})}),e.jsxs("div",{className:"max-h-60 overflow-y-auto py-1",children:[e.jsxs("button",{onClick:()=>{m(),N(!1)},className:`w-full flex items-center gap-2 px-3 py-2 text-[length:var(--text-body-m)] text-left transition-colors ${i?"text-[var(--color-text-primary)] hover:bg-[var(--color-bg-secondary)]":"bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]"}`,children:[e.jsxs("span",{className:"flex-1",children:["All ",t]}),!i&&e.jsx(Se,{size:14,className:"text-[var(--color-accent)]"})]}),E.length===0&&!s&&e.jsx("div",{className:"px-3 py-3 text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] text-center",children:"No saved views yet."}),E.map(P=>e.jsx("div",{className:`group flex items-center gap-1 px-3 py-2 transition-colors ${i===P.id?"bg-[var(--color-accent-subtle)]":"hover:bg-[var(--color-bg-secondary)]"}`,children:z===P.id?e.jsxs("form",{onSubmit:H=>{H.preventDefault(),D(P.id)},className:"flex-1 flex items-center gap-1",children:[e.jsx("input",{type:"text",value:b,onChange:H=>g(H.target.value),className:"flex-1 h-6 px-2 rounded border border-[var(--color-accent)] bg-[var(--color-bg-primary)] text-[length:var(--text-body-m)] text-[var(--color-text-primary)] focus:outline-none",autoFocus:!0,onKeyDown:H=>{H.key==="Escape"&&(y(null),g(""))}}),e.jsx("button",{type:"submit",className:"p-0.5 rounded hover:bg-[var(--color-bg-tertiary)] text-[var(--color-accent)]",children:e.jsx(Se,{size:14})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>O(P),className:"flex-1 flex items-center gap-2 text-left min-w-0",children:[e.jsx("span",{className:`flex-1 truncate text-[length:var(--text-body-m)] ${i===P.id?"text-[var(--color-accent-text)] font-medium":"text-[var(--color-text-primary)]"}`,children:P.name}),P.is_shared&&e.jsx(fa,{size:12,className:"text-[var(--color-text-quaternary)] flex-shrink-0"}),i===P.id&&e.jsx(Se,{size:14,className:"text-[var(--color-accent)] flex-shrink-0"})]}),P.created_by===l&&e.jsxs(dt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{className:"p-0.5 rounded opacity-0 group-hover:opacity-100 pointer-coarse:opacity-100 hover:bg-[var(--color-bg-tertiary)] text-[var(--color-text-tertiary)] transition-opacity","aria-label":`Actions for ${P.name}`,children:e.jsx($a,{size:14})})}),e.jsxs(mt,{align:"end",sideOffset:4,children:[e.jsxs(be,{onClick:()=>{y(P.id),g(P.name)},children:[e.jsx(We,{size:14,className:"mr-2"}),"Rename"]}),e.jsxs(be,{onClick:()=>x(P.id,{is_shared:!P.is_shared}),children:[e.jsx(fa,{size:14,className:"mr-2"}),P.is_shared?"Make private":"Share with team"]}),e.jsx(ra,{}),e.jsxs(be,{onClick:()=>u(P.id),className:"text-[var(--color-error)]",children:[e.jsx(he,{size:14,className:"mr-2"}),"Delete"]})]})]})]})},P.id))]}),e.jsxs("div",{className:"border-t border-[var(--color-bg-tertiary)] px-3 py-2",children:[e.jsx("p",{className:"mb-2 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-secondary)]",children:"Save the current search, filters, and layout"}),e.jsxs("form",{onSubmit:P=>{P.preventDefault(),U()},className:"flex items-center gap-2",children:[e.jsx(oe,{size:14,className:"text-[var(--color-text-quaternary)] flex-shrink-0"}),e.jsx("input",{type:"text",placeholder:"View name","aria-label":"New view name",value:j,onChange:P=>f(P.target.value),className:"flex-1 min-w-0 h-7 px-2 rounded border border-[var(--color-text-tertiary)] bg-[var(--color-bg-primary)] text-[length:var(--text-body-m)] text-[var(--color-text-primary)] placeholder:text-[var(--color-text-secondary)] focus:outline-none focus:ring-1 focus:ring-[var(--color-accent)]"}),e.jsx(L,{type:"submit",variant:"primary",size:"compact",disabled:!j.trim()||h,children:"Save"})]})]})]})]})}const ma=t=>({className:r})=>e.jsx(t,{size:15,className:r}),Wr=[{value:"reports",label:"Overview",icon:dr,stripIcon:ma(dr)},{value:"people",label:"People",icon:Ne,stripIcon:ma(Ne)},{value:"deals",label:"Pipeline",icon:Ze,stripIcon:ma(Ze)},{value:"follow_ups",label:"Sequences",icon:Xt,stripIcon:ma(Xt)},{value:"tools",label:"Settings",icon:xr,stripIcon:ma(xr)}],gl=3,ls={contacts:"people",companies:"people",pipelines:"tools",products:"tools",scoring:"tools",templates:"tools",custom_fields:"tools",quotes:"deals",sequences:"follow_ups"};function fi({navigationTrigger:t,view:a,onViewChange:r,searchQuery:l,onSearchChange:n,filterLifecycle:s,onFilterLifecycleChange:i,onCreateContact:d,onCreateCompany:c,onImportCsv:m,onExportCsv:p,onExportVCard:u,onScanBusinessCard:x,pipelines:w,activePipelineId:N,onPipelineChange:h,filterDealStatus:v,onFilterDealStatusChange:j,dealCount:f,onCreateDeal:z,peopleViewMode:y,onPeopleModeChange:b,peopleSortKey:g,peopleSortDirection:E,onPeopleSort:A,peopleVisibleColumns:U,onTogglePeopleColumn:D,dealLayout:O,onDealLayoutChange:P}){const H=a==="people"||a==="contacts"||a==="companies"||a==="deals",ae=a==="deals"?"Pipeline":a==="companies"?"Companies":"People",I=a==="deals"?"Qualify, prioritize, and move deals toward close.":"Search, segment, and act on every relationship.";return e.jsxs("div",{className:"shrink-0",children:[e.jsx(ji,{view:a,onViewChange:r,dealCount:f}),H&&e.jsx(Xe,{title:ae,description:I,leading:t,actions:e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[(a==="people"||a==="contacts"||a==="companies")&&e.jsx(wi,{onImportCsv:m,onScanBusinessCard:x,onExportCsv:p,onExportVCard:u}),a==="people"&&e.jsxs(L,{size:"compact","aria-label":"Add contact","data-testid":"crm-people-new-trigger",onClick:d,className:"max-lg:h-11 max-lg:w-11 max-lg:min-w-11 max-lg:px-0 max-lg:rounded-full",children:[e.jsx(oe,{size:16}),e.jsx("span",{className:"hidden @[700px]/crmpage:inline",children:"Add contact"})]}),a==="contacts"&&e.jsxs(L,{onClick:d,size:"compact","aria-label":"Add contact",className:"max-lg:h-11 max-lg:w-11 max-lg:min-w-11 max-lg:px-0 max-lg:rounded-full",children:[e.jsx(oe,{size:16}),e.jsx("span",{className:"hidden @[700px]/crmpage:inline",children:"Add contact"})]}),a==="companies"&&e.jsxs(L,{onClick:c,size:"compact","aria-label":"New company",className:"max-lg:h-11 max-lg:w-11 max-lg:min-w-11 max-lg:px-0 max-lg:rounded-full",children:[e.jsx(oe,{size:16}),e.jsx("span",{className:"hidden @[700px]/crmpage:inline",children:"New company"})]}),a==="deals"&&e.jsxs(L,{onClick:z,size:"default","aria-label":"New deal","data-testid":"crm-ne
2w-deal-cta",className:"max-lg:h-11 max-lg:w-11 max-lg:min-w-11 max-lg:px-0 max-lg:rounded-full",children:[e.jsx(oe,{size:16}),e.jsx("span",{className:"hidden @[700px]/crmpage:inline",children:"New deal"})]})]})}),(a==="contacts"||a==="companies"||a==="people")&&e.jsxs(dl,{chips:[],"data-testid":"crm-people-filter-bar",className:"h-auto flex-wrap px-4 py-2 border-b border-[var(--color-bg-tertiary)] max-[479px]:flex-nowrap max-[479px]:gap-2 max-[479px]:overflow-x-auto max-[479px]:px-3 @[900px]/crmpage:h-10 @[900px]/crmpage:flex-nowrap @[900px]/crmpage:py-0",children:[b&&e.jsxs(e.Fragment,{children:[e.jsxs(me,{value:y,onValueChange:k=>b(k),children:[e.jsx(ue,{"aria-label":"People view layout",className:"hidden h-11 w-auto min-w-[116px] max-w-[145px] rounded-full max-[479px]:inline-flex",children:e.jsx(ve,{})}),e.jsxs(pe,{children:[e.jsx(te,{value:"by-company",children:"By company"}),e.jsx(te,{value:"by-stage",children:"Lifecycle"}),e.jsx(te,{value:"list",children:"List"})]})]}),e.jsx("div",{role:"tablist","aria-label":"People view layout",className:"flex w-full items-center gap-0.5 max-[479px]:hidden @[900px]/crmpage:w-auto",children:[["by-company","By company",Fe],["by-stage","Lifecycle",Nt],["list","List",hl]].map(([k,C,_])=>{const Z=y===k;return e.jsxs("button",{"data-testid":`people-view-toggle-${k}`,type:"button",role:"tab","aria-selected":Z,onClick:()=>b(k),className:`inline-flex flex-1 items-center justify-center gap-2 rounded-[var(--radius-sm)] border-b-2 px-3 py-1 text-[length:var(--text-label-m)] font-medium whitespace-nowrap cursor-pointer transition-colors max-[479px]:min-w-11 max-[479px]:flex-none max-[479px]:px-2 @[900px]/crmpage:flex-none ${Z?"border-[var(--color-accent)] bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]":"border-transparent text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-secondary)] hover:text-[var(--color-text-primary)]"}`,children:[e.jsx(_,{size:14}),e.jsx("span",{className:Z?void 0:"max-[479px]:sr-only",children:C})]},k)})})]}),e.jsx(bl,{entityType:a==="companies"?"companies":"contacts",currentLayout:y,onApplyLayout:k=>{(k==="by-company"||k==="by-stage"||k==="list")&&(b==null||b(k))}}),y==="list"&&A&&U&&D&&e.jsxs(dt,{children:[e.jsx(xt,{asChild:!0,children:e.jsxs(L,{variant:"ghost",size:"compact",className:"shrink-0 max-[479px]:hidden","aria-label":"Table options",children:[e.jsx(Nt,{size:14}),e.jsx("span",{className:"hidden @[700px]/crmpage:inline",children:"Table"}),e.jsx(ye,{size:12})]})}),e.jsxs(mt,{align:"start",className:"min-w-[220px]",children:[e.jsx(xl,{children:"Sort by"}),[["name","Name"],["company","Company"],["owner","Owner"],["last_contacted","Last contacted"]].map(([k,C])=>e.jsxs(be,{onSelect:()=>A(k),children:[e.jsx("span",{className:"w-4",children:g===k?e.jsx(Se,{size:14}):null}),e.jsx("span",{children:C}),g===k&&e.jsx("span",{className:"ml-auto text-[var(--color-text-tertiary)]",children:E==="asc"?"Ascending":"Descending"})]},k)),e.jsx(ra,{}),e.jsx(xl,{children:"Fields"}),[["email","Email"],["phone","Phone"],["company","Company"],["lists","Lists"],["stage","Stage"],["owner","Owner"],["last_contacted","Last contacted"]].map(([k,C])=>e.jsxs(be,{onSelect:_=>{_.preventDefault(),D(k)},children:[e.jsx("span",{className:"w-4",children:U.has(k)?e.jsx(Se,{size:14}):null}),C]},k))]})]}),e.jsx("div",{className:"flex-1 max-[479px]:hidden"}),e.jsx("div",{className:"hidden shrink-0 min-[480px]:block @[1000px]/crmpage:hidden",children:e.jsx(yl,{value:s,onChange:k=>i(k),options:[{value:"all",label:"All lifecycle stages"},...It.map(k=>({value:k,label:k==="mql"||k==="sql"?k.toUpperCase():k.charAt(0).toUpperCase()+k.slice(1)}))],"aria-label":"Filter by lifecycle stage"})}),e.jsxs(me,{value:s,onValueChange:k=>i(k),children:[e.jsxs(ue,{"aria-label":"Filters",className:"hidden h-11 w-auto min-w-[96px] rounded-full max-[479px]:inline-flex max-[479px]:w-11 max-[479px]:min-w-11 max-[479px]:justify-center max-[479px]:px-0",children:[e.jsx(Oo,{size:14}),e.jsx("span",{className:"max-[479px]:sr-only",children:"Filters"}),s!=="all"&&e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-[var(--color-accent)]","aria-hidden":"true"})]}),e.jsxs(pe,{children:[e.jsx(te,{value:"all",children:"All lifecycle stages"}),It.map(k=>e.jsx(te,{value:k,children:k==="mql"||k==="sql"?k.toUpperCase():k.charAt(0).toUpperCase()+k.slice(1)},k))]})]}),e.jsx("div",{className:"hidden items-center gap-1 @[1000px]/crmpage:flex",role:"group","aria-label":"Filter by lifecycle stage",children:It.map(k=>e.jsx("button",{"data-testid":`lifecycle-chip-${k}`,type:"button",onClick:()=>i(s===k?"all":k),"aria-pressed":s===k,className:`shrink-0 px-2 py-0.5 rounded-full text-[length:var(--text-label-m)
2] leading-[var(--lh-label-m)] tracking-[0.5px] font-medium cursor-pointer transition-colors ${s===k?"bg-[var(--color-accent)] text-[var(--color-text-on-accent)]":"text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-secondary)]"}`,children:k==="mql"||k==="sql"?k.toUpperCase():k.charAt(0).toUpperCase()+k.slice(1)},k))}),e.jsx("div",{className:"min-w-0 flex-1 max-[479px]:order-first max-[479px]:w-11 max-[479px]:flex-none @[800px]/crmpage:hidden",children:e.jsx(fl,{searchQuery:l,onSearchChange:n,placeholder:"Search people...",ariaLabel:"Search people",testId:"crm-people-search"})})]}),a==="deals"&&e.jsxs(dl,{chips:[],"data-testid":"crm-pipeline-filter-bar",className:"h-auto flex-wrap px-4 py-2 border-b border-[var(--color-bg-tertiary)] gap-2 max-[479px]:flex-nowrap max-[479px]:overflow-hidden max-[479px]:px-3 @[900px]/crmpage:h-10 @[900px]/crmpage:flex-nowrap @[900px]/crmpage:py-0",children:[e.jsx("div",{className:"min-w-0 shrink-0 [&:has(input)]:flex-1 @[800px]/crmpage:hidden",children:e.jsx(fl,{searchQuery:l,onSearchChange:n,placeholder:"Search deals...",ariaLabel:"Search deals",testId:"crm-deals-search"})}),P&&e.jsxs(e.Fragment,{children:[e.jsxs(me,{value:O,onValueChange:k=>P(k),children:[e.jsx(ue,{"aria-label":"Deal view layout",className:"hidden h-11 w-auto min-w-0 max-w-[180px] flex-1 rounded-full max-[479px]:inline-flex",children:e.jsx(ve,{})}),e.jsxs(pe,{children:[e.jsx(te,{value:"board",children:"Board"}),e.jsx(te,{value:"list",children:"List"}),e.jsx(te,{value:"owner",children:"By owner"}),e.jsx(te,{value:"risk",children:"At risk"})]})]}),e.jsx("div",{role:"tablist","aria-label":"Deal view layout",className:"flex w-auto items-center gap-0.5 max-[479px]:hidden",children:[["board","Board",Nt],["list","List",hl],["owner","By owner",ja],["risk","At risk",Kl]].map(([k,C,_])=>{const Z=O===k;return e.jsxs("button",{type:"button",role:"tab","aria-selected":Z,onClick:()=>P(k),className:`inline-flex shrink-0 items-center gap-2 whitespace-nowrap rounded-[var(--radius-sm)] border-b-2 px-3 py-1 text-[length:var(--text-label-m)] font-medium cursor-pointer transition-colors max-[479px]:min-w-11 max-[479px]:px-2 ${Z?"border-[var(--color-accent)] bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]":"border-transparent text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-secondary)]"}`,children:[e.jsx(_,{size:14}),e.jsx("span",{className:Z?void 0:"max-[479px]:sr-only",children:C})]},k)})})]}),e.jsx(bl,{entityType:"deals",currentLayout:O,onApplyLayout:k=>{(k==="board"||k==="list"||k==="owner"||k==="risk")&&(P==null||P(k))}}),e.jsx("div",{className:"flex-1"}),w.length>1&&e.jsx(yl,{value:N??"",onChange:h,options:w.map(k=>({value:k.id,label:k.name})),"aria-label":"Select pipeline"})]})]})}function yl({value:t,onChange:a,options:r,"aria-label":l}){const n=r.length>0&&t!==r[0].value;return e.jsxs(me,{value:t,onValueChange:a,children:[e.jsx(ue,{"aria-label":l,className:`inline-flex items-center gap-1 h-7 pointer-coarse:h-11 w-auto rounded-full border text-[length:var(--text-label-s)] font-medium cursor-pointer pl-3 pr-2 transition-colors ${n?"border-[var(--color-accent)] bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]":"border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[var(--color-text-secondary)]"}`,children:e.jsx(ve,{})}),e.jsx(pe,{children:r.map(s=>e.jsx(te,{value:s.value,children:s.label},s.value))})]})}function ji({view:t,onViewChange:a,dealCount:r}){const l=Bl();if(l)return null;const n=(l?Wr.slice(0,gl):Wr).map(i=>({id:i.value,label:i.label,icon:i.stripIcon,count:i.value==="deals"&&r>0?r:void 0}));
2return e.jsx(hr,{items:n,value:ls[t]??t,onChange:i=>a(i),"aria-label":"CRM views",countVariant:"text",className:"h-10 max-md:h-12 gap-0.5 px-4 max-[479px]:hidden md:hidden",itemClassName:"h-full max-md:px-2 max-[360px]:px-1 gap-2 max-[360px]:gap-1 text-[length:var(--text-label-l)] max-[360px]:text-[length:var(--text-label-m)]",children:e.jsx(Ni,{view:t,onViewChange:a,tabs:Wr.slice(gl)})})}function Ni({view:t,onViewChange:a,tabs:r}){const n=!!r.find(s=>t===s.value||ls[t]===s.value);return e.jsxs(dt,{children:[e.jsx(xt,{asChild:!0,children:e.jsxs("button",{role:"tab","aria-selected":n,"aria-label":"More tabs","data-testid":"crm-tabs-more",className:`
3            md:hidden inline-flex items-center gap-2 px-2 h-full min-h-11 shrink-0 whitespace-nowrap
4            max-[360px]:w-10 max-[360px]:justify-center max-[360px]:gap-0
5            text-[length:var(--text-label-l)] max-[360px]:text-[length:var(--text-label-m)] font-medium
6            border-b-2 -mb-px cursor-pointer
7            transition-colors duration-[var(--duration-micro)]
8            ${n?"text-[var(--color-text-primary)] border-[var(--color-accent)]":"text-[var(--color-text-tertiary)] border-transparent hover:text-[var(--color-text-primary)]"}
9          `,children:[e.jsx($a,{size:15}),e.jsx("span",{className:"max-[360px]:sr-only",children:"More"})]})}),e.jsx(mt,{align:"end",className:"min-w-[180px]",children:r.map(s=>{const i=s.icon,d=t===s.value||ls[t]===s.value;return e.jsxs(be,{role:"tab","aria-selected":d,"data-testid":`crm-tabs-more-item-${s.value}`,onSelect:()=>a(s.value),className:d?"text-[var(--color-accent)]":void 0,children:[e.jsx(i,{size:14}),s.label]},s.value)})})]})}function wi({onImportCsv:t,onScanBusinessCard:a,onExportCsv:r,onExportVCard:l}){return Bl()?e.jsxs(dt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx(L,{variant:"ghost",size:"icon-mobile","aria-label":"Import or export contacts","data-testid":"crm-data-menu",children:e.jsx(Ee,{size:16})})}),e.jsxs(mt,{align:"end",className:"min-w-[220px]",children:[e.jsxs(be,{onSelect:t,children:[e.jsx(ga,{size:14}),"Import CSV or vCard"]}),e.jsxs(be,{onSelect:a,children:[e.jsx(as,{size:14}),"Import business card image"]}),e.jsx(ra,{}),e.jsxs(be,{onSelect:r,children:[e.jsx(Ee,{size:14}),"Export CSV"]}),e.jsxs(be,{onSelect:l,children:[e.jsx(Ee,{size:14}),"Export vCard"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(dt,{children:[e.jsx(xt,{asChild:!0,children:e.jsxs(L,{variant:"ghost",size:"compact","aria-label":"Import contacts","data-testid":"crm-import-menu",children:[e.jsx(ga,{size:16}),e.jsx("span",{className:"hidden @[700px]/crmpage:inline",children:"Import"}),e.jsx(ye,{size:12,className:"hidden @[700px]/crmpage:block"})]})}),e.jsxs(mt,{align:"end",className:"min-w-[210px]",children:[e.jsxs(be,{onSelect:t,children:[e.jsx(ga,{size:14}),"CSV or vCard file"]}),e.jsxs(be,{onSelect:a,children:[e.jsx(as,{size:14}),"Business card image"]})]})]}),e.jsxs(dt,{children:[e.jsx(xt,{asChild:!0,children:e.jsxs(L,{variant:"ghost",size:"compact","aria-label":"Export contacts","data-testid":"crm-export-menu",children:[e.jsx(Ee,{size:16}),e.jsx("span",{className:"hidden @[700px]/crmpage:inline",children:"Export"}),e.jsx(ye,{size:12,className:"hidden @[700px]/crmpage:block"})]})}),e.jsxs(mt,{align:"end",className:"min-w-[180px]",children:[e.jsxs(be,{onSelect:r,children:[e.jsx(Ee,{size:14}),"CSV file"]}),e.jsxs(be,{onSelect:l,children:[e.jsx(Ee,{size:14}),"vCard file"]})]})]})]})}function fl({searchQuery:t,onSearchChange:a,placeholder:r,ariaLabel:l,testId:n}){const s=Ie.useRef(null),[i,d]=Ie.useState(!!t);return Ie.useEffect(()=>{t&&d(!0)},[t]),i?e.jsxs("div",{className:"relative min-w-0 flex-1 lg:max-w-80",children:[e.jsx(Na,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-[var(--color-text-quaternary)] pointer-events-none"}),e.jsx("input",{ref:s,type:"search",placeholder:r,"aria-label":l,"data-testid":n,value:t,onChange:c=>a(c.target.value),onKeyDown:c=>{var m;c.key==="Escape"&&(a(""),(m=s.current)==null||m.blur())},onBlur:()=>{t||d(!1)},autoFocus:!0,className:"h-7 pointer-coarse:h-11 pl-8 pr-3 w-full rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[length:var(--text-body-m)] max-lg:text-base text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)]"})]}):e.jsx(L,{variant:"ghost",size:"icon-sm",className:"icon-interactive","aria-label":l,onClick:()=>{d(!0),window.requestAnimationFrame(()=>{var c;return(c=s.current)==null?void 0:c.focus()})},children:e.jsx(Na,{size:16})})}
9const ki=["reports","people","deals"],Ci=["follow_ups"],nn=["pipelines","products","templates","scoring","custom_fields"];function on(t){return t==="contacts"||t==="companies"?"people":t==="quotes"?"deals":t==="sequences"?"follow_ups":t==="dashboard"?"reports":nn.includes(t)?"tools":t}function Gr({item:t,current:a,active:r,onSelect:l}){const n=t.icon,s=r??on(a)===t.view;return e.jsx(es,{label:t.label,active:s,icon:e.jsx(n,{size:16}),badge:t.count!==void 0&&t.count>0?t.count:void 0,onClick:()=>l(t.view),"data-testid":`crm-sidebar-${t.view}`})}function jl(t){const a=t.member_count-t.person_count;if(a<=0)return t.name;const r=t.person_count===1?"1 person":`${t.person_count} people`,l=a===1?"1 company":`${a} companies`;return`${t.name} — ${r}, plus ${l} not shown in People`}function Si({onCreateList:t,onEditList:a,onDeleteList:r}){const l=yo(),{view:n,setView:s,personsTotal:i,dealsTotal:d,contactGroups:c=[],contactGroupsLoading:m,contactGroupsLoaded:p,activeGroupId:u,loadContactGroups:x,setActiveGroupFilter:w,searchQuery:N,setSearchQuery:h}=G();o.useEffect(()=>{!p&&!m&&x()},[p,m,x]);const v={reports:{view:"reports",label:"Overview",icon:wa},people:{view:"people",label:"People",icon:Ne,count:i},deals:{view:"deals",label:"Pipeline",icon:Ze,count:d}},j={follow_ups:{view:"follow_ups",label:"Sequences",icon:ht}},f=ki.map(b=>v[b]),z=Ci.map(b=>j[b]),y=b=>{s(b),w(null)};return e.jsxs(fo,{label:"CRM navigation","data-testid":"crm-workspace-sidebar",className:"h-auto self-stretch",context:n==="people"||n==="deals"?e.jsxs("div",{className:"relative",children:[e.jsx(Na,{size:16,"aria-hidden":"true",className:"pointer-events-none absolute left-3 top-1/2 z-10 -translate-y-1/2 text-[var(--color-text-tertiary)]"}),e.jsx(J,{type:"search","aria-label":n==="deals"?"Search pipeline":"Search people and companies",placeholder:n==="deals"?"Search pipeline":"Search people",value:N,onChange:b=>h(b.target.value),onKeyDown:b=>{b.key==="Escape"&&N&&(b.preventDefault(),h(""))},className:"pl-9"})]}):void 0,footer:e.jsx(Gr,{item:{view:"tools",label:"CRM settings",icon:xr},current:n,active:n==="tools"||nn.includes(n),onSelect:y}),children:[e.jsx(qr,{title:"Workspace",children:f.map(b=>e.jsx(Gr,{item:b,current:n,active:b.view==="people"?on(n)==="people"&&u===null:void 0,onSelect:y},b.view))}),e.jsxs(qr,{title:"Lists",actions:e.jsx(ml,{size:"sm","aria-label":"Create list",onClick:()=>{l==null||l(),t()},children:e.jsx(oe,{size:14})}),children:[c.map(b=>e.jsx(es,{label:b.name,labelClassName:"whitespace-normal break-words leading-5","aria-label":jl(b),title:jl(b),onClick:()=>{w(b.id),n!=="people"&&s("people")},active:n==="people"&&u===b.id,icon:e.jsx("span",{className:"h-2 w-2 rounded-full bg-[var(--color-text-quaternary)]"}),badge:b.person_count,actions:e.jsxs(dt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx(ml,{size:"sm","aria-label":`Manage ${b.name}`,children:e.jsx($a,{size:14})})}),e.jsxs(mt,{align:"end",className:"min-w-[160px]",children:[e.jsxs(be,{onSelect:()=>{l==null||l(),a(b)},children:[e.jsx(We,{size:14}),"Rename list"]}),e.jsx(ra,{}),e.jsxs(be,{destructive:!0,onSelect:()=>{l==null||l(),r(b)},children:[e.jsx(he,{size:14}),"Delete list"]})]})]}),"data-testid":`crm-contact-groups-sidebar-row-${b.id}`},b.id)),c.length===0&&!m&&e.jsx(es,{label:"Create a list",icon:e.jsx(oe,{size:14}),onClick:()=>{l==null||l(),t()},"data-testid":"crm-sidebar-create-list"})]}),e.jsx(qr,{title:"Engage",children:z.map(b=>e.jsx(Gr,{item:b,current:n,onSelect:y},b.view))})]})}const Nl={gray:"var(--color-text-quaternary)",accent:"var(--color-accent)",purple:"var(--color-purple)",pink:"var(--color-pink)",cyan:"var(--color-cyan)",orange:"var(--color-orange)",success:"var(--color-success)",warning:"var(--color-warning)"},_i={gray:"Gray",accent:"Blue",purple:"Purple",pink:"Pink",cyan:"Cyan",orange:"Orange",success:"Green",warning:"Yellow"};function Di({open:t,onOpenChange:a,group:r,onCreate:l,onUpdate:n}
9){const s=!!r,[i,d]=o.useState(""),[c,m]=o.useState("gray"),[p,u]=o.useState(!1),[x,w]=o.useState(null),N=o.useRef(null);o.useEffect(()=>{if(!t)return;d((r==null?void 0:r.name)??""),m((r==null?void 0:r.color)??"gray"),u(!1),w(null);const v=window.setTimeout(()=>{var j;return(j=N.current)==null?void 0:j.focus()},0);return()=>window.clearTimeout(v)},[t,r]);const h=async v=>{v.preventDefault();const j=i.trim();if(!(!j||p)){u(!0),w(null);try{if(s&&r){if(!await n(r.id,{name:j,color:c})){w("Failed to update list");return}}else if(!await l({name:j,color:c})){w("Failed to create list");return}a(!1)}finally{u(!1)}}};return e.jsx(Ke,{open:t,onOpenChange:a,children:e.jsxs(Qe,{className:"max-w-md",children:[e.jsx(He,{children:e.jsx(Ye,{className:"text-[length:var(--text-title-m)]",children:s?"Edit list":"Create list"})}),e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"contact-group-name",className:"block text-[length:var(--text-label-m)] font-medium text-[var(--color-text-primary)] mb-2",children:"Name"}),e.jsx("input",{ref:N,id:"contact-group-name",type:"text",value:i,onChange:v=>d(v.target.value),placeholder:"e.g., Newsletter subscribers, VIP customers",required:!0,maxLength:255,className:"w-full h-9 px-3 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[length:var(--text-body-m)] text-[var(--color-text-primary)] placeholder:text-[var(--color-text-quaternary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)]"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[length:var(--text-label-m)] font-medium text-[var(--color-text-primary)] mb-2",children:"Color"}),e.jsx("div",{role:"radiogroup","aria-label":"List color",className:"flex items-center gap-2 flex-wrap",children:li.map(v=>{const j=c===v;return e.jsx("button",{type:"button",role:"radio","aria-checked":j,"aria-label":_i[v]??v,onClick:()=>m(v),className:pa("h-8 w-8 rounded-full flex items-center justify-center cursor-pointer","transition-transform duration-[var(--duration-micro)]","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-[var(--color-accent)]",j?"ring-2 ring-offset-2 ring-[var(--color-accent)]":"hover:scale-110"),"data-testid":`contact-group-color-${v}`,children:e.jsx("span",{className:"h-5 w-5 rounded-full block",style:{background:Nl[v]??Nl.gray}})},v)})})]}),x&&e.jsx("div",{className:"px-3 py-2 rounded-[var(--radius-md)] bg-[var(--color-error-subtle)] text-[var(--color-error-text)] text-[length:var(--text-body-s)]",children:x}),e.jsxs(nt,{children:[e.jsx(L,{type:"button",variant:"ghost",onClick:()=>a(!1),disabled:p,children:"Cancel"}),e.jsx(L,{type:"submit",disabled:!i.trim()||p,children:p?s?"Saving…":"Creating…":s?"Save changes":"Create list"})]})]})]})})}const Kr=[{key:"",label:"— Skip —"},{key:"name",label:"Name"},{key:"email",label:"Email"},{key:"phone",label:"Phone"},{key:"title",label:"Job Title"},{key:"company_name",label:"Company Name"},{key:"website",label:"Website"},{key:"industry",label:"Industry"},{key:"lifecycle_stage",label:"Lifecycle stage"},{key:"type",label:"Type (person/company)"}];function zi({open:t,onClose:a,initialTargetGroupId:r,contactGroups:l,onPreview:n,onImport:s}){const[i,d]=o.useState("upload"),[c,m]=o.useState(!1),[p,u]=o.useState(null),[x,w]=o.useState([]),[N,h]=o.useState("csv"),[v,j]=o.useState([]),[f,z]=o.useState(0),[y,b]=o.useState([]),[g,E]=o.useState({}),[A,U]=o.useState("skip"),[D,O]=o.useState(""),[P,H]=o.useState(null),[ae,I]=o.useState(null),[k,C]=o.useState(!1),_=o.useRef(null);o.useEffect(()=>{t&&(d("upload"),u(null),w([]),h("csv"),j([]),z(0),b([]),E({}),U("skip"),O(r??""),H(null),I(null),C(!1),m(!1))},[t,r]),o.useEffect(()=>{if(!t)return;const V=F=>{F.key==="Escape"&&(F.preventDefault(),a())};return document.addEventListener("keydown",V),()=>document.removeEventListener("keydown",V)},[t,a]);const Z=o.useCallback(async V=>{u(V),I(null),C(!0);const F=await n(V);if(C(!1),!F){I("Failed to parse contact file");return}if(F.headers.length===0){I("Contact file has no recognizable fields");return}w(F.headers),h(F.format),j(F.errors),z(F.total_rows),b(F.preview);const le={},X=Y=>Y.toLowerCase().replace(/[_\-\s]+/g,""),T=F.headers.map(Y=>({header:Y,norm:X(Y)})),W=Kr.filter(Y=>
9Y.key).map(Y=>({key:Y.key,normKey:X(Y.key),normLabel:X(Y.label)}));for(const{header:Y,norm:re}of T){const fe=W.find(Te=>Te.normKey===re||Te.normLabel===re);fe&&(le[Y]=fe.key)}const R=new Set(Object.values(le));for(const{header:Y,norm:re}of T){if(le[Y])continue;const fe=W.filter(Te=>!R.has(Te.key)&&(re.includes(Te.normKey)||Te.normKey.includes(re)||re.includes(Te.normLabel)||Te.normLabel.includes(re)));fe.length>0?(fe.sort((Te,St)=>St.normKey.length-Te.normKey.length),le[Y]=fe[0].key,R.add(fe[0].key)):le[Y]=""}E(le),d("mapping")},[n]),B=o.useCallback(async()=>{if(!p)return;const V=new Set(Object.values(g).filter(Boolean));if(N==="csv"&&!V.has("name")){I("You must map at least the 'Name' field");return}I(null),d("importing");const F=await s(p,g,A,D||void 0);F?(H(F),d("result")):(d("mapping"),I("Import failed"))},[p,N,g,A,D,s]);return t?e.jsx(Ke,{open:t,onOpenChange:V=>!V&&a(),children:e.jsxs(Qe,{className:"max-w-lg w-full max-h-[85vh] max-md:mb-[var(--mobile-tab-bar-clearance,0px)] flex flex-col animate-none duration-0","data-testid":"import-csv-dialog",children:[e.jsx(He,{className:"shrink-0 mb-4 pr-6",children:e.jsx(Ye,{id:"import-csv-dialog-title",children:i==="result"?"Import complete":"Import contacts from CSV or vCard"})}),ae&&e.jsx("div",{className:"mb-3 px-3 py-2 rounded-[var(--radius-md)] bg-[var(--color-error-subtle)] text-[var(--color-error-text)] text-[length:var(--text-body-s)] shrink-0",children:ae}),i==="upload"&&e.jsxs("div",{className:"flex-1",children:[e.jsx("input",{ref:_,type:"file",accept:".csv,.vcf,text/csv,text/vcard,text/x-vcard",className:"hidden",onChange:V=>{var le;const F=(le=V.target.files)==null?void 0:le[0];F&&Z(F)}}),e.jsxs("button",{onClick:()=>{var V;return(V=_.current)==null?void 0:V.click()},disabled:k,className:"flex w-full cursor-pointer flex-col items-center gap-3 rounded-[var(--radius-lg)] border-2 border-dashed border-[var(--color-text-tertiary)] py-10 transition-colors hover:border-[var(--color-accent)] hover:bg-[var(--color-accent-subtle)] focus-visible:border-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]",children:[e.jsx(ga,{size:32,className:"text-[var(--color-text-tertiary)]"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)]",children:k?"Parsing contact file...":"Click to upload a CSV or vCard file"}),e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] mt-1",children:"Max 5MB, up to 10,000 rows"})]})]}),e.jsx("button",{type:"button",onClick:()=>{const V=`Name,Email,Phone,Job Title,Company Name,Website,Industry,Lifecycle Stage,Type
10Jane Smith,[email protected],555-0100,VP Sales,Acme Inc,acme.com,Technology,lead,person
11`,F=new Blob([V],{type:"text/csv"});oi(F,"contacts-import-template.csv")},className:"mt-3 text-[length:var(--text-body-s)] text-[var(--color-accent)] hover:underline cursor-pointer mx-auto block",children:"Download CSV template"})]}),i==="mapping"&&(()=>{const V={};let F=0;for(const X of x){const T=g[X]||"";T?V[T]=(V[T]||0)+1:F++}const le=X=>{var T;return((T=Kr.find(W=>W.key===X))==null?void 0:T.label)??X};return e.jsxs("div",{className:"flex-1 flex flex-col min-h-0",children:[e.jsxs("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] mb-3 shrink-0",children:[f.toLocaleString()," ",f===1?"contact":"contacts"," found.",N==="csv"?" Map CSV columns to contact fields.":" vCard fields are mapped automatically."]}),v.length>0&&e.jsxs("div",{className:"mb-3 px-3 py-2 rounded-[var(--radius-md)] bg-[var(--color-warning-subtle)] text-[var(--color-warning-text)] text-[length:var(--text-body-s)] shrink-0",role:"status",children:[v.length," malformed ",v.length===1?"card":"cards"," will be reported without blocking valid cards."]}),N==="csv"&&F>0&&e.jsxs("div",{className:"mb-3 px-3 py-2 rounded-[var(--radius-md)] bg-[var(--color-warning-subtle)] text-[var(--color-warning-text)] text-[length:var(--text-body-s)] shrink-0",role:"status",children:[F," ",F===1?"column has":"columns have"," no match — verify before importing."]}),N==="csv"&&e.jsx("div",{className:"flex-1 overflow-y-auto mb-4 space-y-2 pr-1",children:x.map(X=>{const T=g[X]||"",W=T&&V[T]>1;return e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-3",children:[e.jsx("span",{className:"flex-1 min-w-0 text-[length:var(--text-body-m)] text-[var(--color-text-primary)] truncate font-medium",children:X}),e.jsx("span",{className:"hidden sm:inline text-[var(--color-text-quaternary)] text-[length:var(--text-body-s)] shrink-0",children:"→"}),e.jsx("select",{value:T,onChange:R=>E(Y=>({...Y,[X]:R.target.value})),className:`w-full sm:w-44 h-9 px-2 rounded-[var(--radius-md)] border bg-[var(--color-bg-primary)] text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)] cursor-pointer ${W?"border-[var(--color-warning)]":"border-[var(--color-bg-tertiary)]"}`,children:Kr.map(R=>e.jsx("option",{value:R.key,children:R.label},R.key))})]}),W&&e.jsxs("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-warning)] sm:ml-0",children:[V[T]," columns map to ",le(T)," — only the last will be used. Consider combining them before import."]})]},X)})}),y.length>0&&e.jsxs("div",{className:"mb-4 shrink-0",children:[e.jsxs("p",{className:"text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2",children:["Preview (first ",y.length," ",y.length===1?"row":"rows",")"]}),e.jsx("div",{className:"overflow-x-auto rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)]",children:e.jsxs("table",{className:"w-full text-[length:var(--text-body-s)]",children:[e.jsx("thead",{children:e.jsx("tr",{className:"bg-[var(--color-bg-secondary)]",children:x.map(X=>e.jsx("th",{className:"px-2 py-2 text-left font-medium text-[var(--color-text-tertiary)] whitespace-nowrap",children:X},X))})}),e.jsx("tbody",{children:y.map((X,T)=>e.jsx("tr",{className:"border-t border-[var(--color-bg-tertiary)]",children:x.map(W=>e.jsx("td",{className:"px-2 py-2 text-[var(--color-text-secondary)] whitespace-nowrap max-w-32 truncate",children:X[W]||""},W))},T))})]})})]}),e.jsxs("div",{className:"mb-4 shrink-0",children:[e.jsx("label",{htmlFor:"contact-import-target",className:"block text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2",children:"Add to group"}),e.jsxs("select",{id:"contact-import-target",value:D,onChange:X=>O(X.target.value),className:"w-full h-9 px-2 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)] cursor-pointer",children:[e.jsx("option",{value:"",children:"No group"}),l.map(X=>e.jsx("option",{value:X.id,children:X.name},X.id))]})]}),e.jsxs("div",{className:"mb-4 shrink-0",children:[e.jsx("p",{className:"text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2",children:"Duplicate handling (by email)"}),e.jsx("div",{className:"flex gap-2",children:[{value:"skip",label:"Skip"},{value:"update",label:"Update"},{value:"create",label:"Create new"}].map(X=>e.jsx("button",{onClick:()=>
11U(X.value),className:`px-3 py-2 rounded-[var(--radius-sm)] text-[length:var(--text-label-m)] font-medium cursor-pointer transition-colors ${A===X.value?"bg-[var(--color-accent-subtle)] text-[var(--color-accent)]":"text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-secondary)]"}`,children:X.label},X.value))})]}),e.jsxs(nt,{className:"mt-auto shrink-0 pt-2 border-t border-[var(--color-bg-tertiary)]",children:[e.jsx(L,{variant:"ghost",size:"compact",onClick:a,children:"Cancel"}),e.jsxs(L,{size:"compact",onClick:B,children:[e.jsx(ga,{size:14}),"Import ",f.toLocaleString()," ",f===1?"contact":"contacts"]})]})]})})(),i==="importing"&&e.jsxs("div",{className:"flex-1 py-4 space-y-3",role:"progressbar","aria-label":"Import contacts","aria-valuetext":`Importing ${f.toLocaleString()} contacts`,children:[e.jsxs("p",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-secondary)] text-center mb-4 animate-pulse",children:["Importing ",f.toLocaleString()," contacts..."]}),Array.from({length:4}).map((V,F)=>e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 rounded-md",role:"status","aria-label":"Loading",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-[var(--color-bg-tertiary)] animate-pulse shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("div",{className:"h-3 w-2/3 rounded bg-[var(--color-bg-tertiary)] animate-pulse"}),e.jsx("div",{className:"h-2.5 w-1/3 rounded bg-[var(--color-bg-tertiary)] animate-pulse"})]})]},F))]}),i==="result"&&P&&e.jsxs("div",{className:"flex-1 flex flex-col min-h-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4 shrink-0",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-[var(--color-success-subtle)] flex items-center justify-center",children:e.jsx(Se,{size:16,className:"text-[var(--color-success)]"})}),e.jsx("span",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)]",children:"Import complete"})]}),e.jsxs("div",{className:"space-y-2 mb-4 overflow-y-auto flex-1 pr-1",children:[e.jsxs("div",{className:"flex justify-between text-[length:var(--text-body-m)]",children:[e.jsx("span",{className:"text-[var(--color-text-secondary)]",children:"Total rows"}),e.jsx("span",{className:"text-[var(--color-text-primary)] tabular-nums",children:P.total})]}),e.jsxs("div",{className:"flex justify-between text-[length:var(--text-body-m)]",children:[e.jsx("span",{className:P.created>0?"text-[var(--color-success)]":"text-[var(--color-text-tertiary)]",children:"Created"}),e.jsx("span",{className:"text-[var(--color-text-primary)] tabular-nums",children:P.created})]}),P.updated>0&&e.jsxs("div",{className:"flex justify-between text-[length:var(--text-body-m)]",children:[e.jsx("span",{className:"text-[var(--color-accent)]",children:"Updated"}),e.jsx("span",{className:"text-[var(--color-text-primary)] tabular-nums",children:P.updated})]}),P.skipped>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between text-[length:var(--text-body-m)]",children:[e.jsx("span",{className:"text-[var(--color-text-tertiary)]",children:"Skipped"}),e.jsx("span",{className:"text-[var(--color-text-primary)] tabular-nums",children:P.skipped})]}),P.skippedRows&&P.skippedRows.length>0&&e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:()=>m(V=>!V),className:"text-[length:var(--text-body-s)] text-[var(--color-accent)] hover:underline cursor-pointer","aria-expanded":c,children:[c?"Hide":"View"," skipped rows"]}),c&&e.jsxs("div",{className:"mt-2 max-h-32 overflow-y-auto rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] p-2 space-y-1",children:[P.skippedRows.slice(0,50).map((V,F)=>e.jsxs("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:[e.jsxs("span",{className:"text-[var(--color-text-tertiary)]",children:["Row ",V.row,":"]})," ",V.email?e.jsx("span",{className:"tabular-nums",children:V.email}):e.jsx("em",{className:"text-[var(--color-text-tertiary)]",children:"no email"})," — ",V.reason]},F)),P.skippedRows.length>50&&e.jsxs("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] mt-1",children:["...and ",P.skippedRows.length-50," more"]})]})]})]}),P.errors.length>0&&e.jsxs("div",{className:"flex justify-between text-[length:var(--text-body-m)]",children:[e.jsx("span",{className:"text-[var(--color-error)]",children:"Errors"}),e.jsx("span",{className:"text-[var(--color-text-primary)] tabular-nums",children:P.errors.length})]}),P.errors.length>0&&e.jsxs("div",{className:"mb-4 max-h-32 overflow-y-auto rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] p-2",children:[P.errors.slice(0,20).map((V,F)=>e.jsxs("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-error)]",children:["Row ",V.row,": ",V.error]},F)),P.errors.length>20&&e.jsxs("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] mt-1",children:["...and ",P.errors.length-20," more errors"]})]})]}),e.jsx(nt,{className:"mt-auto shrink-0 pt-2 border-t border-[var(--color-bg-tertiary)]",children:e.jsx(L,{size:"compact",onClick:a,children:"Done"})})]})]})}):null}const Me=["var(--color-accent)","var(--color-success)","var(--color-warning)","var(--color-error)","var(--color-purple)","var(--color-cyan)","var(--color-orange)","var(--color-pink)"],cn={Open:"var(--color-accent)",Won:"var(--color-success)",Lost:"var(--color-error)"},wl={note:"var(--color-accent)",call:"var(--color-success)",email:"var(--color-warning)",meeting:"var(--color-purple)",task:"var(--color-cyan)",chat:"var(--color-orange)"},Jt={background:"var(--color-bg-primary)",border:"1px solid var(--color-bg-tertiary)",borderRadius:8,fontSize:12,boxShadow:"var(--shadow-lg)",padding:"8px 12px"},yt={fontSize:11,fill:"var(--color-text-tertiary)"},$t="var(--color-bg-tertiary)",lr="var(--color-text-tertiary)",Ya=[{value:"all_time",label:"All time"},{value:"this_year",label:"This year"},{value:"this_quarter",label:"This quarter"},{value:"this_month",label:"This month"}];function $i({current:t,previous:a,periodLabel:r,inverseColor:l=!1}){if(a===void 0||t===a||t===0&&a===0)return null;if(a===0)return e.jsxs("div",{"data-testid":"kpi-delta","data-direction":"new",className:"inline-flex items-center gap-1 text-[length:var(--text-label-s)] leading-[var(--lh-label-s)] font-medium text-[var(--color-success)] mt-2",children:[e.jsx(kl,{direction:"up"}),e.jsx("span",{className:"tabular-nums",children:"New"}),e.jsx("span",{className:"text-[var(--color-text-quaternary)]",children:r})]});const n=(t-a)/a*100,s=n>=0?"up":"down",i=Math.abs(n),d=`${s==="up"?"+":"−"}${i<10?i.toFixed(1).replace(/\.0$/,""):Math.round(i)}%`,m=(l?s==="down":s==="up")?"var(--color-success)":"var(--color-error)";return e.jsxs("div",{"data-testid":"kpi-delta","data-direction":s,
11className:"inline-flex items-center gap-1 text-[length:var(--text-label-s)] leading-[var(--lh-label-s)] font-medium mt-2",style:{color:m},children:[e.jsx(kl,{direction:s}),e.jsx("span",{className:"tabular-nums",children:d}),e.jsx("span",{className:"text-[var(--color-text-quaternary)]",children:r})]})}function kl({direction:t}){return t==="up"?e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none","aria-hidden":"true",children:e.jsx("path",{d:"M5 8V2M5 2L2 5M5 2L8 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}):e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none","aria-hidden":"true",children:e.jsx("path",{d:"M5 2V8M5 8L2 5M5 8L8 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function Oe({label:t,value:a,subValue:r,icon:l,accent:n,format:s="currency",delta:i}){const d=n||"var(--color-accent-subtle)",c=n?"var(--color-text-secondary)":"var(--color-accent)",m=p=>{if(typeof p=="string")return p;switch(s){case"currency":return Q(p);case"percent":return`${p}%`;case"days":return`${p}d`;case"number":return p.toLocaleString();default:return String(p)}};return e.jsx("div",{className:"bg-[var(--color-bg-secondary)] rounded-[var(--radius-lg)] p-[var(--spacing-4)] border border-[var(--color-bg-tertiary)] hover:border-[var(--color-accent)] transition-all duration-[var(--duration-micro)] group relative overflow-hidden",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{"data-testid":"kpi-label",className:"text-[length:var(--text-label-s)] min-[480px]:text-[length:var(--text-label-m)] text-[var(--color-text-tertiary)] mb-1 truncate",children:t}),e.jsx("div",{"data-testid":"kpi-value",className:"text-[length:var(--text-title-m)] min-[480px]:text-[length:var(--text-title-l)] leading-[var(--lh-title-m)] min-[480px]:leading-[var(--lh-title-l)] font-semibold text-[var(--color-text-primary)] tabular-nums tracking-tight",children:m(a)}),r&&e.jsx("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] [.dark_&]:text-[var(--color-text-secondary)] mt-2 truncate",children:r}),i&&e.jsx($i,{current:i.current,previous:i.previous,periodLabel:i.periodLabel,inverseColor:i.inverseColor})]}),l&&e.jsx("div",{className:"w-8 h-8 rounded-[var(--radius-md)] flex items-center justify-center opacity-60 group-hover:opacity-100 transition-opacity shrink-0 ml-2",style:{background:d,color:c},children:l})]})})}function At({title:t,children:a,className:r}){return e.jsxs("div",{className:`bg-[var(--color-bg-secondary)] rounded-[var(--radius-lg)] p-4 border border-[var(--color-bg-tertiary)] ${r||""}`,children:[e.jsx("h3",{className:"text-[length:var(--text-title-s)] font-semibold text-[var(--color-text-primary)] mb-4",children:t}),a]})}function Ai({value:t,onChange:a}){var l;const r=((l=Ya.find(n=>n.value===t))==null?void 0:l.label)??Ya[0].label;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"min-[960px]:hidden w-full max-w-[220px]","data-testid":"period-selector-mobile",children:e.jsxs(me,{value:t,onValueChange:n=>a(n),children:[e.jsx(ue,{"aria-label":"Analytics period","data-testid":"period-selector-trigger",children:e.jsx(ve,{"aria-label":r,children:r})}),e.jsx(pe,{children:Ya.map(n=>e.jsx(te,{value:n.value,children:n.label},n.value))})]})}),e.jsx("div",{className:"hidden min-[960px]:flex items-center gap-1 bg-[var(--color-bg-secondary)] rounded-[var(--radius-md)] p-0.5",role:"tablist","aria-label":"Analytics period","data-testid":"period-selector-desktop",children:Ya.map(n=>e.jsx("button",{role:"tab","aria-selected":t===n.value,onClick:()=>a(n.value),className:`px-3 py-2 rounded-[var(--radius-sm)] text-[length:var(--text-label-m)] font-medium transition-all duration-[var(--duration-micro)] ${t===n.value?"bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] shadow-sm":"text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]"}`,children:n.label},n.value))})]})}function Ti(t){const[a,r]=t.split("-");return`${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][parseInt(r,10)-1]} ${a.slice(2)}`}function Ei({onCreateDeal:t}={}){const{analytics:a,analyticsLoading:r,analyticsPeriod:l,setAnalyticsPeriod:n,loadAnalytics:s,metrics:i,metricsLoading:d,loadMetrics:c}
11=G(),[m,p]=o.useState(!1);return o.useEffect(()=>{p(!0),s(),c()},[]),r||!a&&d||!a&&!i?e.jsxs("div",{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(_e,{className:"h-8 w-48"}),e.jsx(_e,{className:"h-9 w-64"})]}),e.jsx("div",{className:"grid grid-cols-1 min-[480px]:grid-cols-2 min-[720px]:grid-cols-[repeat(auto-fill,minmax(180px,1fr))] gap-3",children:Array.from({length:8}).map((x,w)=>e.jsx(_e,{className:"h-[88px]"},w))}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsx(_e,{className:"h-[320px]"}),e.jsx(_e,{className:"h-[320px]"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsx(_e,{className:"h-[300px]"}),e.jsx(_e,{className:"h-[300px]"})]})]}):a?e.jsx(Li,{analytics:a,period:l,onPeriodChange:n,isMounted:m,onCreateDeal:t}):e.jsx(Ii,{metrics:i,isMounted:m,onCreateDeal:t})}function Li({analytics:t,period:a,onPeriodChange:r,isMounted:l,onCreateDeal:n}){const s=t.openDealsCount+t.wonDealsCount+t.lostDealsCount,i=s>0,d=[{name:"Open",value:t.openDealsCount},{name:"Won",value:t.wonDealsCount},{name:"Lost",value:t.lostDealsCount}].filter(u=>u.value>0),c=t.monthlyTrend.map(u=>({...u,label:Ti(u.month)})),m=t.previous,p=a==="this_month"?"vs last month":a==="this_quarter"?"vs last quarter":a==="this_year"?"vs last year":"";return e.jsxs("div",{className:"p-6 space-y-6 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-[length:var(--text-headline-s)] font-semibold text-[var(--color-text-primary)]",children:"Pipeline Analytics"}),e.jsxs("p",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-tertiary)] mt-0.5",children:[s," deal",s!==1?"s":""," in pipeline"]})]}),e.jsx(Ai,{value:a,onChange:r})]}),e.jsxs("div",{className:"grid grid-cols-1 min-[480px]:grid-cols-2 min-[720px]:grid-cols-[repeat(auto-fill,minmax(180px,1fr))] gap-3",children:[e.jsx(Oe,{label:"Total pipeline",value:t.totalPipelineValue,subValue:`${t.openDealsCount} open deal${t.openDealsCount!==1?"s":""}`,icon:e.jsx(Ze,{size:18}),delta:m&&{current:t.totalPipelineValue,previous:m.totalPipelineValue,periodLabel:p}}),e.jsx(Oe,{label:"Weighted pipeline",value:t.weightedPipeline,subValue:"Probability-adjusted",icon:e.jsx(wa,{size:18}),accent:"var(--color-accent-secondary-subtle)",delta:m&&{current:t.weightedPipeline,previous:m.weightedPipeline,periodLabel:p}}),e.jsx(Oe,{label:"Revenue won",value:t.dealsWonValue,subValue:`${t.wonDealsCount} deal${t.wonDealsCount!==1?"s":""} closed`,icon:e.jsx(ka,{size:18}),accent:"var(--color-success-subtle)",delta:m&&{current:t.dealsWonValue,previous:m.dealsWonValue,periodLabel:p}}),e.jsx(Oe,{label:"Revenue lost",value:t.dealsLostValue,subValue:`${t.lostDealsCount} deal${t.lostDealsCount!==1?"s":""}`,icon:e.jsx(gr,{size:18}),accent:"var(--color-error-subtle)",delta:m&&{current:t.dealsLostValue,previous:m.dealsLostValue,periodLabel:p,inverseColor:!0}}),e.jsx(Oe,{label:"Win rate",value:t.winRate,format:"percent",subValue:`${t.wonDealsCount}W / ${t.lostDealsCount}L`,icon:e.jsx(dr,{size:18}),accent:"var(--color-success-subtle)",delta:m&&{current:t.winRate,previous:m.winRate,periodLabel:p}}),e.jsx(Oe,{label:"Avg deal size",value:t.avgDealValue,icon:e.jsx(Ze,{size:18}),accent:"var(--color-accent-subtle)",delta:m&&{current:t.avgDealValue,previous:m.avgDealValue,periodLabel:p}}),e.jsx(Oe,{label:"Sales cycle",value:t.avgDealVelocityDays,format:"days",subValue:"Creation to close",icon:e.jsx(Cs,{size:18}),accent:"var(--color-warning-subtle)",delta:m&&{current:t.avgDealVelocityDays,previous:m.avgDealVelocityDays,periodLabel:p,inverseColor:!0}}),e.jsx(Oe,{label:"Forecast",value:t.forecast90d,subValue:"Weighted by probability",icon:e.jsx(Xt,{size:18}),accent:"var(--color-purple-subtle)",delta:m&&{current:t.forecast90d,previous:m.forecast90d,periodLabel:p}})]}),i?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[t.funnel.length>0&&e.jsxs(At,{title:"Pipeline by Stage",children:[e.jsx("div",{className:"h-[280px]",children:l&&e.jsx(Ht,{width:"100%",height:"100%",children:e.jsxs(ss,{data:t.funnel,margin:{top:12,right:20,bottom:20,left
11:8},barCategoryGap:"20%",children:[e.jsx(tr,{strokeDasharray:"3 3",stroke:$t,vertical:!1}),e.jsx(ar,{dataKey:"stage_name",tick:yt,axisLine:{stroke:$t},tickLine:!1}),e.jsx(rr,{tick:yt,axisLine:!1,tickLine:!1,tickFormatter:u=>u>=1e3?`$${(u/1e3).toFixed(0)}k`:`$${u}`,width:60}),e.jsx(Yt,{contentStyle:Jt,formatter:(u,x)=>{const w=Number(u)||0;return x==="value"?[Q(w),"Total Value"]:x==="weighted_value"?[Q(w),"Weighted Value"]:[w,String(x)]},cursor:{fill:"var(--color-bg-tertiary)",opacity:.4}}),e.jsx(va,{wrapperStyle:{fontSize:11,paddingTop:4},formatter:u=>e.jsx("span",{style:{color:"var(--color-text-secondary)"},children:u==="value"?"Total":"Weighted"})}),e.jsx(sr,{y:0,stroke:lr,strokeWidth:1,"data-testid":"chart-zero-axis"}),e.jsx(ha,{dataKey:"value",fill:"var(--color-accent)",radius:[4,4,0,0],animationDuration:600,animationEasing:"ease-out",children:t.funnel.map((u,x)=>e.jsx(ya,{fill:Me[x%Me.length],fillOpacity:.85},`cell-${x}`))}),e.jsx(ha,{dataKey:"weighted_value",fill:"var(--color-accent)",radius:[4,4,0,0],animationDuration:600,animationEasing:"ease-out",fillOpacity:.4,children:t.funnel.map((u,x)=>e.jsx(ya,{fill:Me[x%Me.length],fillOpacity:.35},`cell-w-${x}`))})]})})}),e.jsx("div",{className:"mt-3 border-t border-[var(--color-bg-tertiary)] pt-3",children:e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] gap-x-4 gap-y-2 text-[length:var(--text-body-s)]",children:[e.jsx("div",{className:"text-[var(--color-text-tertiary)] font-medium",children:"Stage"}),e.jsx("div",{className:"text-[var(--color-text-tertiary)] font-medium text-right",children:"Deals"}),e.jsx("div",{className:"text-[var(--color-text-tertiary)] font-medium text-right",children:"Value"}),e.jsx("div",{className:"text-[var(--color-text-tertiary)] font-medium text-right",children:"Prob"}),t.funnel.map((u,x)=>e.jsxs(Ie.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{background:Me[x%Me.length]}}),e.jsx("span",{className:"text-[var(--color-text-primary)] truncate",children:u.stage_name})]}),e.jsx("div",{className:"text-[var(--color-text-secondary)] text-right tabular-nums",children:u.count}),e.jsx("div",{className:"text-[var(--color-text-secondary)] text-right tabular-nums",children:Q(u.value)}),e.jsxs("div",{className:"text-[var(--color-text-tertiary)] text-right tabular-nums",children:[u.probability,"%"]})]},u.stage_id))]})})]}),d.length>0&&e.jsxs(At,{title:"Deal status distribution",children:[e.jsx("div",{className:"h-[280px]",children:l&&e.jsx(Ht,{width:"100%",height:"100%",children:e.jsxs(sn,{children:[e.jsx(ln,{data:d,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:"70%",innerRadius:"45%",paddingAngle:2,animationDuration:600,animationEasing:"ease-out",children:d.map((u,x)=>e.jsx(ya,{fill:cn[u.name]||Me[x%Me.length]},`cell-${x}`))}),e.jsx(Yt,{contentStyle:Jt,formatter:(u,x)=>{const w=Number(u)||0;return[`${w} deal${w!==1?"s":""}`,x]}}),e.jsx(va,{wrapperStyle:{fontSize:12,paddingTop:8},formatter:u=>e.jsx("span",{style:{color:"var(--color-text-secondary)"},children:u})})]})})}),e.jsxs("div",{className:"mt-3 border-t border-[var(--color-bg-tertiary)] pt-3 flex items-center justify-around text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[20px] font-semibold text-[var(--color-accent)] tabular-nums",children:t.openDealsCount}),e.jsx("div",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:"Open"})]}),e.jsx("div",{className:"w-px h-8 bg-[var(--color-bg-tertiary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[20px] font-semibold text-[var(--color-success)] tabular-nums",children:t.wonDealsCount}),e.jsx("div",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:"Won"})]}),e.jsx("div",{className:"w-px h-8 bg-[var(--color-bg-tertiary)]"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[20px] font-semibold text-[var(--color-error)] tabular-nums",children:t.lostDealsCount}),e.jsx("div",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:"Lost"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[c.length>0&&e.jsx(At,{title:"Revenue trend",children:e.jsx("div",{className:"h-[280px]",children:l&&e.jsx(Ht,{width:"100%",height:"100%",children:e.jsxs(ci,{data:c,margin:{top:12,right:20,bottom:20,left
11:8},children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"wonGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"var(--color-success)",stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:"var(--color-success)",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"createdGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"var(--color-accent)",stopOpacity:.2}),e.jsx("stop",{offset:"95%",stopColor:"var(--color-accent)",stopOpacity:0})]})]}),e.jsx(tr,{strokeDasharray:"3 3",stroke:$t,vertical:!1}),e.jsx(ar,{dataKey:"label",tick:yt,axisLine:{stroke:$t},tickLine:!1}),e.jsx(rr,{tick:yt,axisLine:!1,tickLine:!1,tickFormatter:u=>u>=1e3?`$${(u/1e3).toFixed(0)}k`:`$${u}`,width:60}),e.jsx(Yt,{contentStyle:Jt,formatter:(u,x)=>[Q(Number(u)||0),x==="created"?"Created":x==="won"?"Won":"Lost"]}),e.jsx(va,{wrapperStyle:{fontSize:11,paddingTop:4},formatter:u=>e.jsx("span",{style:{color:"var(--color-text-secondary)"},children:u==="created"?"Created":u==="won"?"Won":"Lost"})}),e.jsx(sr,{y:0,stroke:lr,strokeWidth:1,"data-testid":"chart-zero-axis"}),e.jsx(Ur,{type:"monotone",dataKey:"created",stroke:"var(--color-accent)",fill:"url(#createdGrad)",strokeWidth:2,animationDuration:600}),e.jsx(Ur,{type:"monotone",dataKey:"won",stroke:"var(--color-success)",fill:"url(#wonGrad)",strokeWidth:2,animationDuration:600}),e.jsx(Ur,{type:"monotone",dataKey:"lost",stroke:"var(--color-error)",fill:"transparent",strokeWidth:1.5,strokeDasharray:"4 3",animationDuration:600})]})})})}),t.revenueByOwner.length>0&&e.jsx(At,{title:"Revenue by Owner",children:e.jsx("div",{className:"h-[280px]",children:l&&e.jsx(Ht,{width:"100%",height:"100%",children:e.jsxs(ss,{data:t.revenueByOwner,layout:"vertical",margin:{top:12,right:20,bottom:12,left:8},barCategoryGap:"25%",children:[e.jsx(tr,{strokeDasharray:"3 3",stroke:$t,horizontal:!1}
11),e.jsx(ar,{type:"number",tick:yt,axisLine:!1,tickLine:!1,tickFormatter:u=>u>=1e3?`$${(u/1e3).toFixed(0)}k`:`$${u}`}),e.jsx(rr,{type:"category",dataKey:"owner_name",tick:yt,axisLine:!1,tickLine:!1,width:100}),e.jsx(Yt,{contentStyle:Jt,formatter:(u,x)=>[Q(Number(u)||0),x==="won_value"?"Won":"Open Pipeline"],cursor:{fill:"var(--color-bg-tertiary)",opacity:.4}}),e.jsx(va,{wrapperStyle:{fontSize:11,paddingTop:4},formatter:u=>e.jsx("span",{style:{color:"var(--color-text-secondary)"},children:u==="won_value"?"Won":"Open Pipeline"})}),e.jsx(sr,{x:0,stroke:lr,strokeWidth:1,"data-testid":"chart-zero-axis"}),e.jsx(ha,{dataKey:"won_value",fill:"var(--color-success)",radius:[0,4,4,0],animationDuration:600,stackId:"revenue"}),e.jsx(ha,{dataKey:"open_value",fill:"var(--color-accent)",radius:[0,4,4,0],animationDuration:600,stackId:"revenue",fillOpacity:.5})]})})})})]}),t.activityBreakdown.length>0&&e.jsx(At,{title:"Activity breakdown",children:e.jsx("div",{className:"grid grid-cols-[repeat(auto-fill,minmax(140px,1fr))] gap-3",children:t.activityBreakdown.map(u=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-[var(--radius-md)] bg-[var(--color-bg-secondary)]",children:[e.jsx("div",{className:"w-8 h-8 rounded-[var(--radius-md)] flex items-center justify-center shrink-0",style:{background:wl[u.type]||"var(--color-accent)",opacity:.15},children:e.jsx(ea,{size:16,style:{color:wl[u.type]||"var(--color-accent)"}})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[16px] font-semibold text-[var(--color-text-primary)] tabular-nums leading-none",children:u.count}),e.jsx("div",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)] capitalize mt-0.5",children:u.type==="email"?"Emails":`${u.type}s`})]})]},u.type))})})]}):e.jsx(dn,{onCreateDeal:n})]})}function dn({onCreateDeal:t}){return e.jsx("div",{className:"bg-[var(--color-surface-1)] rounded-[var(--radius-lg)] border border-[var(--color-bg-tertiary)]","data-testid":"crm-dashboard-empty-state",children:e.jsx(De,{illustration:e.jsx(bi,{}),title:"No deals yet",description:"Create your first deal to see pipeline analytics, win rates, forecasts, and revenue trends.",action:t?e.jsxs(L,{variant:"primary",onClick:t,"data-testid":"crm-dashboard-empty-state-create-deal",children:[e.jsx(oe,{size:16}),"Create deal"]}):void 0})})}function Ii({metrics:t,isMounted:a,onCreateDeal:r}){const l=t.pipelineByStage.length>0||t.dealStatusDistribution.length>0;return e.jsxs("div",{className:"p-6 space-y-6 overflow-y-auto",children:[e.jsxs("div",{className:"grid grid-cols-1 min-[480px]:grid-cols-2 min-[720px]:grid-cols-[repeat(auto-fill,minmax(200px,1fr))] gap-4",children:[e.jsx(Oe,{label:"Total pipeline",value:t.totalPipeline,icon:e.jsx(Ze,{size:20})}),e.jsx(Oe,{label:"Deals won",value:t.dealsWon,icon:e.jsx(ka,{size:20}),accent:"var(--color-success-subtle)"}),e.jsx(Oe,{label:"Deals lost",value:t.dealsLost,icon:e.jsx(gr,{size:20}),accent:"var(--color-error-subtle)"}),e.jsx(Oe,{label:"Avg deal size",value:t.avgDealSize,icon:e.jsx(wa,{size:20}),accent:"var(--color-accent-secondary-subtle)"})]}),l?e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[t.pipelineByStage.length>0&&e.jsx(At,{title:"Pipeline by Stage",children:e.jsx("div",{className:"h-[280px]",children:a&&e.jsx(Ht,{width:"100%",height:"100%",children:e.jsxs(ss,{data:t.pipelineByStage,margin:{top:12,right:20,bottom:20,left:8},barCategoryGap:"20%",children:[e.jsx(tr,{strokeDasharray:"3 3",stroke:$t,vertical:!1}
11),e.jsx(ar,{dataKey:"name",tick:yt,axisLine:{stroke:$t},tickLine:!1}),e.jsx(rr,{tick:yt,axisLine:!1,tickLine:!1,tickFormatter:n=>n>=1e3?`${(n/1e3).toFixed(0)}k`:`${n}`,width:60}),e.jsx(Yt,{contentStyle:Jt,formatter:n=>[Q(Number(n)||0),"Value"],cursor:{fill:"var(--color-bg-tertiary)",opacity:.4}}),e.jsx(sr,{y:0,stroke:lr,strokeWidth:1,"data-testid":"chart-zero-axis"}),e.jsx(ha,{dataKey:"value",fill:"var(--color-accent)",radius:[4,4,0,0],animationDuration:600,animationEasing:"ease-out",children:t.pipelineByStage.map((n,s)=>e.jsx(ya,{fill:Me[s%Me.length]},`cell-${s}`))})]})})})}),t.dealStatusDistribution.length>0&&e.jsx(At,{title:"Deal status",children:e.jsx("div",{className:"h-[280px]",children:a&&e.jsx(Ht,{width:"100%",height:"100%",children:e.jsxs(sn,{children:[e.jsx(ln,{data:t.dealStatusDistribution,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:"70%",innerRadius:"45%",paddingAngle:2,animationDuration:600,children:t.dealStatusDistribution.map((n,s)=>e.jsx(ya,{fill:cn[n.name]||Me[s%Me.length]},`cell-${s}`))}),e.jsx(Yt,{contentStyle:Jt,formatter:(n,s)=>{const i=Number(n)||0;return[`${i} deal${i!==1?"s":""}`,s]}}),e.jsx(va,{wrapperStyle:{fontSize:12,paddingTop:8},formatter:n=>e.jsx("span",{style:{color:"var(--color-text-secondary)"},children:n})})]})})})})]}):e.jsx(dn,{onCreateDeal:r})]})}function Pi({open:t,onClose:a,onCreate:r,onViewContact:l}){const[n,s]=o.useState("capture"),[i,d]=o.useState(null),[c,m]=o.useState(null),[p,u]=o.useState(null),[x,w]=o.useState(!1),N=o.useCallback(()=>{s("capture"),d(null),m(null),u(null),w(!1)},[]);o.useEffect(()=>{t||N()},[t,N]);const h=o.useCallback(async y=>{s("scanning"),d(y),u(null);try{const b=await Ve.images.scanBusinessCard({body:{image:y}});if(!Object.values(b.fields).some(E=>E!==null)){u("Could not read any contact details. Try a clearer photo."),s("error");return}m(b.fields),s("review")}catch(b){b instanceof qo?b.status===503?u("OCR is not available right now. Try again later."):b.status===4
1113?u("Image is too large. Try a smaller photo."):u(b.message||"Scanning failed. Try again."):u("Scanning failed. Try again."),s("error")}},[]),v=o.useCallback(async y=>{if(y)try{const b=await di(y);b&&await h(b)}catch{u("Couldn't read the image. Try again."),s("error")}},[h]),j=y=>{var g;const b=((g=y.target.files)==null?void 0:g[0])??null;y.target.value="",v(b)},f=async()=>{if(!(!c||!c.name)){w(!0);try{const y=[];c.address&&y.push(`Address: ${c.address}`),c.notes&&y.push(c.notes);const b={type:"person",name:c.name,email:c.email??void 0,phone:c.phone??void 0,title:c.title??void 0,website:c.website??void 0,lifecycle_stage:"lead"},g=await r(b);g?(c.company&&g.company_id,a(),l&&l(g.id)):(u("Couldn't save contact. Try again."),w(!1))}catch(y){u(y instanceof Error?y.message:"Could not save contact"),w(!1)}}},z=jo();return e.jsx(Ke,{open:t,onOpenChange:y=>{y||a()},children:e.jsxs(Qe,{className:"max-w-[520px]",fullScreenMobile:!0,children:[e.jsxs(He,{children:[e.jsx(Ye,{children:"Scan business card"}),e.jsx(vr,{children:"Take a photo of a business card and we'll pull the contact details."})]}),n==="capture"&&e.jsx("div",{className:"flex flex-col gap-4 py-2",children:e.jsxs("label",{className:"group flex min-h-44 cursor-pointer flex-col items-center justify-center rounded-[var(--radius-lg)] border border-dashed border-[var(--color-text-quaternary)] bg-[var(--color-bg-secondary)] px-6 py-8 text-center transition-colors hover:border-[var(--color-accent)] hover:bg-[var(--color-accent-subtle)] focus-within:border-[var(--color-accent)] focus-within:ring-2 focus-within:ring-[var(--color-accent)]",children:[e.jsx("input",{type:"file",accept:"image/jpeg,image/png,image/webp,image/heic,image/heif",...z?{capture:"environment"}:{},onChange:j,className:"sr-only"}),e.jsx("span",{className:"mb-3 inline-flex h-11 w-11 items-center justify-center rounded-[var(--radius-md)] bg-[var(--color-accent-subtle)] text-[var(--color-accent)]",children:e.jsx(as,{size:20,"aria-hidden":!0})}),e.jsx("span",{className:"text-[length:var(--text-body-m)] font-semibold text-[var(--color-text-primary)]",children:z?"Take or choose a photo":"Choose a card photo"}),e.jsx("span",{className:"mt-1 text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:"JPEG, PNG, WebP, or HEIC · up to 6 MB"}),e.jsx("span",{className:"mt-3 text-[length:var(--text-label-s)] text-[var(--color-text-secondary)]",children:"Scanning starts after you choose an image"})]})}),n==="scanning"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[i&&e.jsx("img",{src:i,alt:"Captured business card",className:"max-h-48 max-w-full rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] object-contain"}),e.jsxs("div",{className:"flex items-center gap-2 text-[var(--color-text-secondary)]",children:[e.jsx(Ql,{size:16,className:"animate-spin","aria-hidden":!0}),e.jsx("span",{children:"Reading contact details…"})]})]}),n==="error"&&e.jsxs("div",{className:"flex flex-col gap-4 py-4",children:[e.jsx("p",{className:"text-[length:var(--text-body-m)] text-[var(--color-error)]",children:p}),e.jsx(L,{variant:"primary",onClick:()=>N(),children:"Try again"})]}),n==="review"&&c&&e.jsx(Ri,{fields:c,imageData:i,onFieldsChange:m,onRetake:N,onCreate:f,submitting:x,errorMsg:p})]})})}
11function Gt({icon:t,label:a,value:r,onChange:l,placeholder:n,type:s="text",required:i}){return e.jsxs("label",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"flex h-9 w-5 shrink-0 items-center justify-center text-[var(--color-text-tertiary)]",children:t}),e.jsxs("span",{className:"flex-1",children:[e.jsxs("span",{className:"block text-base leading-6 font-medium text-[var(--color-text-secondary)] md:text-[length:var(--text-label-l)] md:leading-[var(--lh-label-l)]",children:[a,i&&e.jsx("span",{className:"ml-0.5 text-[var(--color-error-text)]",children:"*"})]}),e.jsx(J,{type:s,value:r,onChange:d=>l(d.target.value),placeholder:n,required:i,className:"mt-1"})]})]})}function Ri({fields:t,imageData:a,onFieldsChange:r,onRetake:l,onCreate:n,submitting:s,errorMsg:i}){const d=c=>m=>{r({...t,[c]:m.trim()===""?null:m})};return e.jsxs("div",{className:"flex flex-col gap-4",children:[a&&e.jsxs("div",{className:"flex items-center gap-3 rounded-[var(--radius-md)] bg-[var(--color-bg-secondary)] p-2",children:[e.jsx("img",{src:a,alt:"Scanned card preview",className:"h-16 w-20 rounded-[var(--radius-sm)] border border-[var(--color-bg-tertiary)] object-cover"}),e.jsxs("button",{type:"button",onClick:l,className:"flex items-center gap-1 text-[length:var(--text-body-s)] text-[var(--color-accent)] hover:underline",children:[e.jsx(ze,{size:14,"aria-hidden":!0})," Retake photo"]})]}),e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(Gt,{icon:e.jsx(Ne,{size:16,"aria-hidden":!0}),label:"Name",value:t.name??"",onChange:d("name"),required:!0,placeholder:"Full name"}),e.jsx(Gt,{icon:e.jsx(Ss,{size:16,"aria-hidden":!0}),label:"Title",value:t.title??"",onChange:d("title"),placeholder:"Job title"}),e.jsx(Gt,{icon:e.jsx(Fe,{size:16,"aria-hidden":!0}),label:"Company",value:t.company??"",onChange:d("company"),placeholder:"Company name"}),e.jsx(Gt,{icon:e.jsx(Be,{size:16,"aria-hidden":!0}),label:"Email",value:t.email??"",onChange:d("email"),type:"email",placeholder:"[email protected]"}),e.jsx(Gt,{icon:e.jsx(kt,{size:16,"aria-hidden":!0}),label:"Phone",value:t.phone??"",onChange:d("phone"),type:"tel",placeholder:"+1 555 123 4567"}),e.jsx(Gt,{icon:e.jsx(fa,{size:16,"aria-hidden":!0}),label:"Website",value:t.website??"",onChange:d("website"),placeholder:"example.com"})]}),i&&e.jsx("p",{role:"alert",className:"text-[length:var(--text-body-s)] text-[var(--color-error)]",children:i}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(L,{variant:"secondary",onClick:l,disabled:s,className:"flex-1",children:"Retake"}),e.jsx(L,{variant:"primary",onClick:n,disabled:s||!t.name||t.name.trim().length===0,className:"flex-1",children:s?"Saving…":"Create contact"})]})]})}const Fi=30,Mi=60;function xn(t,a){if(!t)return 1/0;const r=new Date(t).getTime();return Number.isNaN(r)?1/0:(a-r)/(1e3*60*60*24)}function Oi(t){return new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()}function qi(t){const a=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);return a?new Date(parseInt(a[1],10),parseInt(a[2],10)-1,parseInt(a[3],10)).getTime():new Date(t).getTime()}function mn(t,a=new Date){const r=Oi(a),l=[];for(const n of t){if(n.status!=="open"||!n.close_date)continue;const s=qi(n.close_date);Number.isNaN(s)||s>=r||l.push({deal:n,daysOverdue:Math.floor((r-s)/(1e3*60*60*24))})}return l.sort((n,s)=>s.daysOverdue-n.daysOverdue),l}function un(t,a=new Date,r=Fi){const l=a.getTime(),n=[];for(const s of t){if(s.status!=="open"||!s.updated_at)continue;const i=xn(s.updated_at,l);i<=r||n.push({deal:s,daysStuck:Math.floor(i)})}return n.sort((s,i)=>i.daysStuck-s.daysStuck),n}function Vi(t,a=new Date,r=Mi){const l=a.getTime(),n=[];for(const s of t){if(s.type!=="person")continue;const i=s.last_contacted_at??s.created_at,d=xn(i,l);d<=r||n.push({contact:s,daysSinceTouch:d===1/0?1/0:Math.floor(d),neverContacted:s.last_contacted_at==null})}return n.sort((s,i)=>s.daysSinceTouch===1/0&&i.daysSinceTouch!==1/0?-1:i.daysSinceTouch===1/0&&s.daysSinceTouch!==1/0?1:i.daysSinceTouch-s.daysSinceTouch),n}function pn(t){if(t<=0)return"Due today";if(t===1)return"1 day overdue";if(t<30)return`${t} days overdue`;const a=Math.floor(t/30);return a===1?"1 month overdue":`${a} months overdue`}function hn(t){if(t<30)return`${t}d in stage`;const a=Math.floor(t/30);return a===1?"1mo in stage":`${a}mo in stage`}function Bi(t){if(t.neverContacted)return"Never contacted";if(t.daysSinceTouch===1/0)return"No activity";if(t.daysSinceTouch<30)return`${t.daysSinceTouch}d no activity`;const a=Math.floor(t.daysSinceTouch/30);return a===1?"1mo no activity":`${a}mo no activity`}const ba=[{value:"ytd",label:"Year to date"},{value:"this_quarter",label:"This quarter"},{value:"this_month",label:"This month"},{value:"all_time",label:"All time"}],nr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Ui(t){const[,a]=t.split("-"),r=Math.max(0,Math.min(11,parseInt(a,10)-1));return nr[r]}function _a(t){return t===0?"$0":Math.abs(t)>=1e6?`$${(t/1e6).toFixed(1)}M`:Math.abs(t)>=1e3?`$${(t/1e3).toFixed(0)}k`:`$${t.toFixed(0)}`}function Wi(t,a=new Date){const r=a.getFullYear();if(t==="ytd")return{revenueLabel:`Revenue YTD ${r}`,revenueDescription:`Revenue closed-won from Jan 1, ${r} to today`,summaryLabel:`YTD ${r}`};if(t==="this_quarter"){const l=Math.floor(a.getMonth()/3),n=nr[l*3],s=nr[l*3+2];return{revenueLabel:`Revenue Q${l+1} ${r}`,revenueDescription:`Revenue closed-won from ${n} 1, ${r} to ${s} ${new Date(r,l*3+3,0).getDate()}, ${r}`,summaryLabel:`Q${l+1} ${r}`}}if(t==="this_month"){const l=nr[a.getMonth()];return{revenueLabel:`Revenue ${l} ${r}`,revenueDescription:`Revenue closed-won in ${l} ${r}`,summaryLabel:`${l} ${r}`}}return{revenueLabel:"Revenue (all time)",revenueDescription:"Total revenue closed-won",summaryLabel:"All time"}}function jr({title:t,subtitle:a,action:r,children:l,className:n,testId:s}){return e.jsxs("div",{"data-testid":s,className:`bg-[var(--color-surface-4)] rounded-[var(--radius-lg)] border border-[var(--color-bg-tertiary)] p-[var(--spacing-4)] relative ${n||""}`,children:[e.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2 bg-[var(--color-surface-4)] -mx-[var(--spacing-4)] px-[var(--spacing-4)] pt-1 pb-2 max-sm:flex-col max-sm:items-stretch sm:sticky sm:top-0 sm:z-10",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-[length:var(--text-title-m)] font-semibold text-[var(--color-text-primary)] leading-[var(--lh-title-m)]",children:t}),a&&e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] mt-0.5",children:a})]}),r&&e.jsx("div",{className:"flex shrink-0 max-sm:w-full",children:r})]}),l]})}function st({label:t,value:a,delta:r}){const l=(r==null?void 0:r.pct)!=null&&r.pct>=0;return e.jsxs("div",{children:[e.jsx("div",{className:"text-[length:var(--text-label-m)
11] text-[var(--color-text-tertiary)] mb-1",children:t}),e.jsx("div",{"data-testid":"kpi-value",className:"text-[length:var(--text-title-m)] leading-[var(--lh-title-m)] font-semibold tabular-nums tracking-tight text-[var(--color-text-primary)] sm:text-[length:var(--text-title-l)] sm:leading-[var(--lh-title-l)]",children:a}),r&&r.pct!=null&&e.jsxs("div",{className:"mt-2 text-[length:var(--text-body-s)] tabular-nums",style:{color:l?"var(--color-success)":"var(--color-error)"},children:[l?"+":"",r.pct.toFixed(1),"%",r.label?` ${r.label}`:""]})]})}function ns({value:t,onChange:a}){var l;const r=((l=ba.find(n=>n.value===t))==null?void 0:l.label)??ba[0].label;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"sm:hidden w-full max-w-[220px]","data-testid":"reports-period-mobile",children:e.jsxs(me,{value:t,onValueChange:n=>a(n),children:[e.jsx(ue,{"aria-label":"Reports period",children:e.jsx(ve,{"aria-label":r,children:r})}),e.jsx(pe,{children:ba.map(n=>e.jsx(te,{value:n.value,children:n.label},n.value))})]})}),e.jsx("div",{className:"hidden sm:flex items-center gap-1 bg-[var(--color-bg-secondary)] rounded-[var(--radius-md)] p-0.5",role:"tablist","aria-label":"Reports period","data-testid":"reports-period-desktop",children:ba.map(n=>e.jsx("button",{type:"button",role:"tab","aria-selected":t===n.value,onClick:()=>a(n.value),className:`px-3 py-2 rounded-[var(--radius-sm)] text-[length:var(--text-label-m)] font-medium transition-all duration-[var(--duration-micro)] whitespace-nowrap shrink-0 ${t===n.value?"bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] shadow-sm":"text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]"}`,children:n.label},n.value))})]})}function Nr({onClick:t,label:a="Export CSV"}){const[r,l]=o.useState(!1),n=()=>
11{if(!r){l(!0);try{t()}finally{window.setTimeout(()=>l(!1),500)}}};return e.jsxs(L,{variant:"ghost",size:"compact",onClick:n,disabled:r,className:"text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]","aria-label":a,"aria-busy":r||void 0,children:[r?e.jsx("span",{className:"inline-block w-3.5 h-3.5 rounded-full border-2 border-[var(--color-text-tertiary)] border-t-transparent animate-spin","aria-hidden":"true"}):e.jsx(Ee,{size:14}),e.jsx("span",{className:"ml-1",children:r?"Exporting…":a})]})}function As({message:t}){return e.jsx("div",{className:"flex items-center justify-center h-[200px] text-[length:var(--text-body-m)] text-[var(--color-text-tertiary)]",children:t})}function Gi({data:t}){const a=Math.max(1,...t.map(l=>l.revenue)),r=`repeat(${Math.max(1,t.length)}, minmax(0, 1fr))`;return e.jsxs("div",{role:"img","aria-label":"Revenue by month",className:"grid h-full w-full grid-cols-[52px_minmax(0,1fr)] grid-rows-[minmax(0,1fr)_28px]",children:[e.jsxs("div",{className:"flex h-full flex-col justify-between pr-2 text-right text-[length:var(--text-body-s)] leading-none text-[var(--color-text-tertiary)]","aria-hidden":"true",children:[e.jsx("span",{children:_a(a)}),e.jsx("span",{children:_a(a*.5)}),e.jsx("span",{children:"$0"})]}),e.jsxs("div",{className:"relative min-h-0","aria-hidden":"true",children:[e.jsx("div",{className:"absolute inset-x-0 top-0 border-t border-dashed border-[var(--color-bg-tertiary)]"}),e.jsx("div",{className:"absolute inset-x-0 top-1/2 border-t border-dashed border-[var(--color-bg-tertiary)]"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 border-t border-dashed border-[var(--color-bg-tertiary)]"}),e.jsx("div",{className:"absolute inset-0 grid",style:{gridTemplateColumns:r},children:t.map(l=>e.jsx("div",{className:"flex min-w-0 items-end justify-center",children:e.jsx("span",{className:`block w-[min(28px,48%)] rounded-t-[3px] ${l.revenue>0?"bg-[var(--color-success-text)]":"bg-[var(--color-bg-tertiary)]"}`,style:{height:`${Math.max(l.revenue>0?1.5:.5,l.revenue/a*100)}%`},title:`${l.month}: ${Q(l.revenue)}`})},l.month))})]}),e.jsx("div",{"aria-hidden":"true"}),e.jsx("div",{className:"grid items-end",style:{gridTemplateColumns:r},"aria-hidden":"true",children:t.map((l,n)=>e.jsx("span",{className:"text-center text-[length:var(--text-body-s)] leading-none text-[var(--color-text-tertiary)]",children:t.length<=8||n%2===0||n===t.length-1?l.month:""},l.month))})]})}function Ki({data:t}){const a=Math.max(1,...t.map(r=>r.total));return e.jsx("div",{className:"hidden h-[240px] space-y-3 overflow-y-auto py-2 md:block","aria-label":"Deals by source chart",children:t.map(r=>e.jsxs("div",{className:"grid grid-cols-[110px_minmax(0,1fr)_72px] items-center gap-3",children:[e.jsx("span",{className:"truncate text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:r.source}),e.jsxs("div",{className:"flex h-4 overflow-hidden rounded-[var(--radius-sm)] bg-[var(--color-bg-secondary)]",children:[e.jsx("span",{style:{width:`${r.won/a*100}%`,background:"var(--color-success)"}}),e.jsx("span",{style:{width:`${r.open/a*100}%`,background:"var(--color-text-tertiary)"}})]}),e.jsx("span",{className:"text-right tabular-nums text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:_a(r.total)})]},r.source))})}function Qi({data:t,stages:a}){const r=Math.max(1,...t.map(l=>l.total_open_value));return e.jsx("div",{className:"hidden max-h-[280px] space-y-3 overflow-y-auto py-2 md:block","aria-label":"Pipeline by owner chart",children:t.map(l=>e.jsxs("div",{className:"grid grid-cols-[120px_minmax(0,1fr)_72px] items-center gap-3",children:[e.jsx("span",{className:"truncate text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:l.owner_name}),e.jsx("div",{className:"flex h-4 overflow-hidden rounded-[var(--radius-sm)] bg-[var(--color-bg-secondary)]",children:a.map(n=>{var i;const s=((i=l.by_stage.find(d=>d.stage_id===n.id))==null?void 0:i.value)??0;return e.jsx("span",{title:`${n.name}: ${Q(s)}`,style:{width:`${s/r*100}%`,background:"var(--color-text-tertiary)"}},n.id)})}),e.jsx("span",{className:"text-right tabular-nums text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:_a(l.total_open_value)})]},l.owner_id))})}function Hi({data:t,period:a}){const r=new Date().getFullYear(),{revenueLabel:l,revenueDescription:n,summaryLabel:s}=Wi(a),i=o.useMemo(()=>t.months.map(m=>({month:Ui(m.month),revenue:m.revenue,deals:m.deals_closed})),[t.months]),d=i.some(m=>m.revenue>0),c=()=>{const m=[["Month","Revenue","Deals Closed"]];for(const x of t.months)m.push([x.month,x.revenue,x.deals_closed]);const p=a==="this_month"?"Total month":a==="this_quarter"?"Total quarter":a==="ytd"?"Total YTD":"Total (all time)";m.push([p,t.total_ytd,t.deals_closed_ytd]),m.push(["Total Previous Year",t.total_prev_year,""]);const u=a==="ytd"?String(r):a.replaceAll("_","-");fr(`revenue-ytd-${u}.csv`,m)};
11return e.jsxs(jr,{title:l,subtitle:n,action:e.jsx(Nr,{onClick:c}),className:"lg:col-span-2",testId:"crm-report-card-revenue-ytd",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 mb-5 pb-5 border-b border-[var(--color-bg-tertiary)]",children:[e.jsx(st,{label:s,value:Q(t.total_ytd),delta:a==="ytd"&&t.yoy_growth_pct!=null?{pct:t.yoy_growth_pct,label:"vs. last year"}:void 0}),e.jsx(st,{label:`Full-year ${r-1}`,value:Q(t.total_prev_year)}),e.jsx(st,{label:"Avg monthly",value:Q(t.avg_monthly_revenue)}),e.jsx(st,{label:"Deals closed",value:String(t.deals_closed_ytd)})]}),e.jsx("div",{className:"h-[190px] sm:h-[220px] md:h-[260px]",children:d?e.jsx(Gi,{data:i}):e.jsx(As,{message:"No revenue booked in the selected period"})})]})}function Yi({data:t,period:a}){const r=sa(),l=o.useMemo(()=>t.rows.slice(0,8).map(d=>({source:d.label,open:d.open_value,won:d.won_value,total:d.open_value+d.won_value,count:d.total_count})),[t.rows]),n=t.rows.length>0,s=n&&t.rows.every(d=>d.source==="unknown"||d.source===""),i=()=>{const d=[["Source","Open Count","Open Value","Won Count","Won Value","Lost Count","Total Deals"]];for(const c of t.rows)d.push([c.label,c.open_count,c.open_value,c.won_count,c.won_value,c.lost_count,c.total_count]);fr(`deals-by-source-${a}.csv`,d)};return e.jsx(jr,{title:"Deals by source",subtitle:"Pipeline attribution by lead source",action:n&&!s?e.jsx(Nr,{onClick:i}):void 0,testId:"crm-report-card-deals-by-source",children:n&&!s?e.jsxs(e.Fragment,{children:[e.jsx(Ki,{data:l}),e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"w-full text-[length:var(--text-body-s)]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left text-[var(--color-text-tertiary)]",children:[e.jsx("th",{className:"pb-2 font-medium",children:"Source"}),e.jsx("th",{className:"pb-2 font-medium text-right",children:"Deals"}),e.jsx("th",{className:"pb-2 font-medium text-right",children:"Open"}),e.jsx("th",{className:"pb-2 font-medium text-right",children:"Won"})]})}),e.jsx("tbody",{children:t.rows.map(d=>e.jsxs("tr",{className:"border-t border-[var(--color-bg-tertiary)]",children:[e.jsx("td",{className:"py-2 text-[var(--color-text-primary)]",children:d.label}),e.jsx("td",{className:"py-2 tabular-nums text-right text-[var(--color-text-secondary)]",children:d.total_count}),e.jsx("td",{className:"py-2 tabular-nums text-right text-[var(--color-text-primary)]",children:Q(d.open_value)}),e.jsx("td",{className:"py-2 tabular-nums text-right text-[var(--color-success-text)]",children:Q(d.won_value)})]},d.source))})]})})]}):s?e.jsx(De,{variant:"inline",icon:e.jsx(wa,{size:28}),title:"Tag deal sources to see attribution",description:`${t.total_deals} deal${t.total_deals===1?"":"s"} in this period — none have a source tagged.`,actions:[e.jsx(L,{variant:"secondary",size:"compact",onClick:()=>r("/crm/pipeline"),"data-testid":"deals-by-source-set-source-cta",children:"Tag deal sources"},"set-source"),e.jsx(L,{variant:"ghost",size:"compact",onClick:()=>window.open("https://knowledge.hubspot.com/contacts/use-original-source-properties","_blank","noopener,noreferrer"),children:"Why source matters"},"learn")]}):e.jsx(De,{variant:"inline",icon:e.jsx(wa,{size:28}),title:"No deals in the selected period",description:"Add a deal to start tracking which lead sources are driving revenue.",action:e.jsx(L,{variant:"primary",size:"compact",onClick:()=>r("/crm/pipeline"),"data-testid":"deals-by-source-add-deal-cta",children:"Add deal"})})})}function Ji({data:t,period:a}){const r=t.stages,l=t.rows.length>0&&t.total_open_value>0,n=()=>{const i=["Owner","Open Deals","Open Pipeline","Weighted",a==="this_month"?"Won this month":a==="this_quarter"?"Won this quarter":a==="ytd"?"Won YTD":"Won (all time)"];for(const c of r)i.push(c.name);const d=[i];for(const c of t.rows){const m=[c.owner_name,c.deal_count,c.total_open_value,c.weighted_value,c.won_value];for(const p of r){const u=c.by_stage.find(x=>x.stage_id===p.id);m.push(u?u.value:0)}d.push(m)}fr("pipeline-by-owner.csv",d)};return e.jsx(jr,{title:"Pipeline by owner",subtitle:"Open, weighted, and won value b
11y deal owner",action:e.jsxs("div",{className:"flex items-center gap-2",children:[t.rows.length>0&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full bg-[var(--color-bg-secondary)] text-[length:var(--text-label-s)] tabular-nums text-[var(--color-text-tertiary)]","aria-label":`${t.rows.length} owners`,children:t.rows.length}),l?e.jsx(Nr,{onClick:n}):null]}),testId:"crm-report-card-pipeline-by-owner",children:l?e.jsxs(e.Fragment,{children:[e.jsx(Qi,{data:t.rows.slice(0,10),stages:r}),e.jsxs("div",{className:"mt-4 space-y-3 sm:hidden","aria-label":"Pipeline by owner details",children:[t.rows.map(s=>e.jsxs("div",{className:"rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] p-3",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-2 font-medium text-[var(--color-text-primary)]",children:[e.jsx(Je,{src:s.owner_avatar_url,name:s.owner_name,size:"sm"}),e.jsx("span",{className:"truncate",children:s.owner_name})]}),e.jsxs("span",{className:"shrink-0 text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:[s.deal_count," open ",s.deal_count===1?"deal":"deals"]})]}),e.jsxs("dl",{className:"grid grid-cols-3 gap-3 text-right",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:"Open"}),e.jsx("dd",{className:"tabular-nums font-semibold text-[var(--color-text-primary)]",children:Q(s.total_open_value)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:"Weighted"}),e.jsx("dd",{className:"tabular-nums font-semibold text-[var(--color-text-primary)]",children:Q(s.weighted_value)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:"Won"}),e.jsx("dd",{className:"tabular-nums font-semibold text-[var(--color-success-text)]",children:Q(s.won_value)})]})]})]},s.owner_id)),e.jsxs("dl",{className:"grid grid-cols-3 gap-3 border-t border-[var(--color-bg-tertiary)] pt-3 text-right",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:"Total open"}),e.jsx("dd",{className:"tabular-nums font-semibold text-[var(--color-text-primary)]",children:Q(t.total_open_value)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:"Weighted"}),e.jsx("dd",{className:"tabular-nums font-semibold text-[var(--color-text-primary)]",children:Q(t.total_weighted_value)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:"Won"}),e.jsx("dd",{className:"tabular-nums font-semibold text-[var(--color-success-text)]",children:Q(t.total_won_value)})]})]})]}),e.jsx("div",{className:"mt-4 hidden max-h-[420px] overflow-x-auto overflow-y-auto sm:block",tabIndex:0,role:"region","aria-label":"Pipeline by owner table",children:e.jsxs("table",{className:"w-full text-[length:var(--text-body-s)]",children:[e.jsx("thead",{className:"sticky top-0 bg-[var(--color-bg-primary)]",children:e.jsxs("tr",{className:"text-left text-[var(--color-text-tertiary)]",children:[e.jsx("th",{className:"pb-2 font-medium",children:"Owner"}),e.jsx("th",{className:"pb-2 font-medium text-right",children:"Open deals"}),e.jsx("th",{className:"pb-2 font-medium text-right",children:"Open"}),e.jsx("th",{className:"pb-2 font-medium text-right",children:"Weighted"}),e.jsx("th",{className:"pb-2 font-medium text-right",children:"Won"})]})}),e.jsx("tbody",{children:t.rows.map(s=>e.jsxs("tr",{className:"border-t border-[var(--color-bg-tertiary)]",children:[e.jsx("td",{className:"py-2 text-[var(--color-text-primary)]",children:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Je,{src:s.owner_avatar_url,name:s.owner_name,size:"sm"}),e.jsx("span",{children:s.owner_name})]})}),e.jsx("td",{className:"py-2 tabular-nums text-right text-[var(--color-text-secondary)]",children:s.deal_count}),e.jsx("td",{className:"py-2 tabular-nums text-right text-[var(--color-text-primary)]",children:Q(s.total_open_value)}),e.jsx("td",{className:"py-2 tabular-nums text-right text-[var(--color-text-primary)]",children:Q(s.weighted_value)}),e.jsx("td",{className:"py-2 tabular-nums text-right text-[var(--color-success-text)]",children:Q(s.won_value)})]},s.owner_id))}),e.jsx("tfoot",{children:e.jsxs("tr",{className:"border-t-2 border-[var(--color-bg-tertiary)]",children:[e.jsx("td",{className:"pt-2 font-semibold text-[var(--color-text-primary)]",children:"Total"}),e.jsx("td",{className:"pt-2 tabular-nums text-right font-semibold text-[var(--color-text-primary)]",children:t.rows.reduce((s,i)=>s+i.deal_count,0)}),e.jsx("td",{className:"pt-2 tabular-nums text-right font-semibold text-[var(--color-text-primary)]",children:Q(t.total_open_value)}),e.jsx("td",{className:"pt-2 tabular-nums text-right font-semibold",children:Q(t.total_weighted_value)}),e.jsx("td",{className:"pt-2 tabular-nums text-right font-semibold text-[var(--color-success-text)]",children:Q(t.total_won_value)})]})})]})})]}):e.jsx(As,{message:"No open deals in the selected period"})})}function Zi({data:t,period:a}){const r=t.rows.length>0&&t.totals.total>0,l=()=>{const n=[["User","Email","Notes","Calls","Emails","Meetings","Tasks","Chats","Auto","Total","Duration (min)"]];for(const s of t.rows)n.push([s.user_name,s.user_email??"",s.notes,s.calls,s.emails,s.meetings,s.tasks,s.chats,s.auto_count,s.total,s.total_duration_minutes]);fr(`activity-metrics-${a}.csv`,n)};return e.jsxs(jr,{title:"Activity metrics",subtitle:"Engagement activity logged by each team member",action:r?e.jsx(Nr,{onClick:l}):void 0,className:"lg:col-span-2",testId:"crm-report-card-activity-metrics",children:[e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-6 gap-3 mb-5 pb-5 border-b border-[var(--color-bg-tertiary)]",children:[e.jsx(st,{label:"Total",value:String(t.totals.total)}),e.jsx(st,{label:"Notes",value:String(t.totals.notes)}),e.jsx(st,{label:"Calls",value:String(t.totals.calls)}),e.jsx(st,{label:"Emails",value:String(t.totals.emails)}),e.jsx(st,{label:"Meetings",value:String(t.totals.meetings)}),e.jsx(st,{label:"Tasks",value:String(t.totals.tasks)})]}),r?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-3 sm:hidden","aria-label":"Activity by team member",children:t.rows.map(n=>e.jsxs("div",{className:"rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] p-3",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-2 font-medium text-[var(--color-text-primary)]",children:[e.jsx(Je,{src:n.user_avatar_url,name:n.user_name,size:"sm"}),e.jsx("span",{className:"truncate",children:n.user_name})]}),e.jsxs("span",{className:"shrink-0 tabular-nums font-semibold text-[var(--color-text-primary)]",children:[n.total," total"]})]}),e.jsx("dl",{className:"grid grid-cols-3 gap-x-3 gap-y-2",children:[["Notes",n.notes],["Calls",n.calls],["Emails",n.emails],["Meetings",n.meetings],["Tasks",n.tasks],["Automated",n.auto_count]].map(([s,i])=>e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("dt",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:s}),e.jsx("dd",{className:"tabular-nums text-[var(--color-text-primary)]",children:i})]},String(s)))}
11),e.jsx("p",{className:"mt-2 text-[length:var(--text-label-m)] text-[var(--color-text-tertiary)]",children:"Automated activity is included in the total."})]},n.user_id))}),e.jsx("div",{className:"hidden overflow-x-auto sm:block",children:e.jsxs("table",{className:"w-full text-[length:var(--text-body-s)]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left text-[var(--color-text-tertiary)]",children:[e.jsx("th",{className:"pb-2 font-medium",children:"Team member"}),e.jsx("th",{className:"pb-2 font-medium text-right",children:"Notes"}),e.jsx("th",{className:"pb-2 font-medium text-right",children:"Calls"}),e.jsx("th",{className:"pb-2 font-medium text-right",children:"Emails"}),e.jsx("th",{className:"pb-2 font-medium text-right",children:"Meetings"}),e.jsx("th",{className:"pb-2 font-medium text-right",children:"Tasks"}),e.jsx("th",{className:"pb-2 font-medium text-right","aria-label":"Auto: activities logged automatically by integrations",children:e.jsx(No,{content:"Activities logged automatically by integrations (e.g., emails tracked via Mail, CRM automations). Included in the Total column.",side:"top",children:e.jsx("span",{tabIndex:0,className:"inline-flex items-center gap-1 cursor-help underline decoration-dotted decoration-[var(--color-text-quaternary)] underline-offset-2 focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] rounded-sm",children:"Automated"})})}),e.jsx("th",{className:"pb-2 font-medium text-right",children:"Total"})]})}),e.jsx("tbody",{children:t.rows.map(n=>e.jsxs("tr",{className:"border-t border-[var(--color-bg-tertiary)]",children:[e.jsx("td",{className:"py-2 text-[var(--color-text-primary)]",children:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Je,{src:n.user_avatar_url,name:n.user_name,size:"sm"}),e.jsx("span",{className:"truncate",children:n.user_name})]})}),e.jsx(ua,{count:n.notes}),e.jsx(ua,{count:n.calls}),e.jsx(ua,{count:n.emails}),e.jsx(ua,{count:n.meetings}),e.jsx(ua,{count:n.tasks}),e.jsx("td",{className:"py-2 tabular-nums text-right",children:n.auto_count>0?e.jsx("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-[var(--color-bg-secondary)] text-[var(--color-text-secondary)] text-[length:var(--text-label-s)] font-medium",children:n.auto_count}):e.jsx("span",{className:"text-[var(--color-text-quaternary)]",children:"0"})}),e.jsx("td",{className:"py-2 tabular-nums text-right font-semibold text-[var(--color-text-primary)]",children:n.total})]},n.user_id))})]})})]}):e.jsx(As,{message:"No activity logged in the selected period"})]})}function ua({count:t}){return e.jsx("td",{className:"py-2 tabular-nums text-right",children:e.jsx("span",{className:t>0?"text-[var(--color-text-primary)]":"text-[var(--color-text-quaternary)]",children:t})})}function Xi(t){var i,d,c,m;const a=((d=(i=t.user)==null?void 0:i.display_name)==null?void 0:d.trim())||"A teammate",r=((c=t.subject)==null?void 0:c.trim())||((m=t.body)==null?void 0:m.trim()),l=t.type==="task"?r==null?void 0:r.replace(/^Task completed:\s*/i,"").trim():r,n=l&&l.length>=3?l:null,s=t.type==="email"?"logged an email":t.type==="meeting"?"logged a meeting":t.type==="call"?"logged a call":t.type==="task"?"completed a CRM task":t.type==="chat"?"logged a chat":"added a note";return`${a} ${s}${n?` · ${n}`:""}`}function ec({overdue:t,stuck:a,cold:r,tasks:l,activities:n,tasksLoading:s,activityLoading:i,tasksError:d,activityError:c,onRetryCommandCenter:m,onOpenDeal:p,onOpenContact:u,onToggleTask:x,onViewTasks:w,onViewPeople:N,pipeline:h,onOpenPipeline:v}){const j=[...t.map(b=>({id:`overdue-${b.deal.id}`,title:b.deal.title,detail:`Deal overdue · ${pn(b.daysOverdue)}`,onClick:()=>p(b.deal.id)})),...a.map(b=>{var g;return{id:`stuck-${b.deal.id}`,title:b.deal.title,detail:`Stuck in ${((g=b.deal.stage)==null?void 0:g.name)??"stage"} · ${hn(b.daysStuck)}`,onClick:()=>p(b.deal.id)}}),...r.map(b=>({id:`cold-${b.contact.id}`,title:b.contact.name,detail:`Relationship is cold · ${Bi(b)}`,onClick:()=>
11u(b.contact.id)}))].slice(0,5),f=h.stages.filter(b=>!/^closed\b/i.test(b.name.trim())).map(b=>{let g=0,E=0;for(const A of h.rows){const U=A.by_stage.find(D=>D.stage_id===b.id);g+=(U==null?void 0:U.count)??0,E+=(U==null?void 0:U.value)??0}return{...b,count:g,value:E,color:"var(--color-text-tertiary)"}}),z=Math.max(1,...f.map(b=>b.value)),y=j.length===0&&!s&&!d&&l.length===0&&!i&&!c;return e.jsxs("div",{className:"grid grid-cols-1 items-stretch gap-4 xl:grid-cols-[minmax(0,1.7fr)_minmax(300px,1fr)] xl:grid-rows-[min-content_1fr]","data-testid":"crm-command-center-work",children:[y&&e.jsx("section",{className:"overflow-hidden rounded-[var(--radius-lg)] border border-[var(--color-bg-tertiary)] bg-[color-mix(in_srgb,var(--color-bg-secondary)_70%,var(--color-bg-tertiary))] sm:hidden",children:e.jsxs("div",{className:"flex min-h-14 items-center gap-2 px-3",children:[e.jsx(Se,{size:18,className:"shrink-0 text-[var(--color-success-text)]"}),e.jsx("span",{className:"min-w-0 flex-1 text-[length:var(--text-body-s)] font-medium text-[var(--color-text-primary)]",children:"Nothing needs attention"}),e.jsxs("div",{className:"flex shrink-0 items-center gap-3 text-[length:var(--text-label-m)] font-medium text-[var(--color-accent-text)]",children:[e.jsx("button",{type:"button",onClick:N,className:"hover:underline",children:"People"}),e.jsx("button",{type:"button",onClick:w,className:"hover:underline",children:"Tasks"})]})]})}),e.jsxs("section",{className:`flex flex-col overflow-hidden rounded-[var(--radius-lg)] border border-[var(--color-bg-tertiary)] bg-[color-mix(in_srgb,var(--color-bg-secondary)_70%,var(--color-bg-tertiary))] xl:col-start-1 xl:row-start-1 ${j.length>0?"min-h-[280px]":"self-start"} ${y?"max-sm:hidden":""}`,children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-[var(--color-bg-tertiary)] px-4 py-3 max-sm:py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-[length:var(--text-title-s)] font-semibold text-[var(--color-text-primary)]",children:"Act now"}),e.jsxs("span",{className:`rounded-full px-2 py-0.5 text-[length:var(--text-body-s)] font-medium ${j.length>0?"bg-[var(--color-warning-subtle)] text-[var(--color-warning-text)]":"bg-[var(--color-bg-tertiary)] text-[var(--color-text-secondary)]"}`,children:[j.length," open"]})]}),e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"Ordered by urgency"})]}),j.length===0?e.jsxs("div",{className:"flex items-center gap-2 px-4 py-4 text-left",children:[e.jsx(Se,{size:18,className:"shrink-0 text-[var(--color-success-text)]"}),e.jsx("p",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)]",children:"No relationship follow-ups"}),e.jsx("p",{className:"hidden text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] lg:block",children:"No overdue, stuck, or cold relationships."})]}):j.map(b=>e.jsxs("button",{type:"button",onClick:b.onClick,className:"flex w-full items-center gap-3 border-b border-[var(--color-bg-tertiary)] px-4 py-3 text-left last:border-b-0 hover:bg-[var(--color-bg-secondary)]",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-[var(--color-warning-subtle)] text-[var(--color-warning-text)]",children:e.jsx(Vo,{size:14})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)]",children:b.title}),e.jsx("span",{className:"block truncate text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:b.detail})]}),e.jsx(Ue,{size:14,className:"shrink-0 text-[var(--color-text-tertiary)]"})]},b.id))]}),e.jsxs("div",{className:"contents sm:grid sm:grid-cols-2 sm:gap-4 xl:col-start-2 xl:row-span-2 xl:row-start-1 xl:grid-cols-1",children:[e.jsxs("section",{className:`max-sm:order-2 overflow-hidden rounded-[var(--radius-lg)] border border-[var(--color-bg-tertiary)] bg-[color-mix(in_srgb,var(--color-bg-secondary)_70%,var(--color-bg-tertiary))] ${y?"max-sm:hidden":""}`,children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-[var(--color-bg-tertiary)] px-4 py-3 max-sm:py-2",children:[e.jsx("h3",{className:"text-[length:var(--text-title-s)] font-semibold text-[var(--color-text-primary)]",children:"My open CRM tasks"}),e.jsx("button",{type:"button",onClick:w,className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-accent-text)] hover:underline",children:"Open tasks"})]}),e.jsx("div",{className:s||d||l.length>0?"min-h-[116px] max-sm:min-h-0":"",children:s?e.jsxs("div",{className:"space-y-2 p-4",children:[e.jsx(_e,{className:"h-9"}),e.jsx(_e,{className:"h-9"})]}):d?e.jsxs("div",{className:"space-y-2 px-4 py-5 text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:[e.jsx("p",{children:d}),e.jsx("button",{type:"button",onClick:m,className:"font-medium text-[var(--color-accent-text)] hover:underline",children:"Try again"})]}):l.length===0?e.jsx("p",{className:"px-4 py-3 text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"No open CRM-linked tasks."}):l.slice(0,3).map(b=>e.jsxs("button",{type:"button",onClick:()=>x(b),className:"flex w-full items-start gap-3 border-b border-[var(--color-bg-tertiary)] px-4 py-2.5 text-left last:border-b-0 hover:bg-[var(--color-bg-secondary)]",children:[e.jsx("span",{className:"mt-0.5 h-4 w-4 shrink-0 rounded-[3px] border border-[var(--color-text-tertiary)]"}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[length:var(--text-body-s)] font-medium text-[var(--color-text-primary)]",children:b.title}),b.due_date&&e.jsxs("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:["Due ",Ce(b.due_date)]})]})]},b.id))})]}),e.jsxs("section",{className:"max-sm:order-4 overflow-hidden rounded-[var(--radius-lg)] border border-[var(--color-bg-tertiary)] bg-[color-mix(in_srgb,var(--color-bg-secondary)_70%,var(--color-bg-tertiary))]",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-[var(--color-bg-tertiary)] px-4 py-3",children:[e.jsx("h3",{className:"text-[length:var(--text-title-s)] font-semibold text-[var(--color-text-primary)]",children:"Recent activity"}),e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"CRM only"})]}),e.jsx("div",{className:"min-h-[132px]",children:i?e.jsxs("div",{className:"space-y-2 p-4",children:[e.jsx(_e,{className:"h-9"}),e.jsx(_e,{className:"h-9"})]}):c?e.jsxs("div",{className:"space-y-2 px-4 py-5 text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:[e.jsx("p",{children:c}),e.jsx("button",{type:"button",onClick:m,className:"font-medium text-[var(--color-accent-text)] hover:underline",children:"Try again"})]}):n.length===0?e.jsx("p",{className:"px-4 py-6 text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"No recent CRM activity."}):n.slice(0,4).map(b=>{const g=b.type==="email"?Be:b.type==="meeting"?ta:b.type==="note"?ot:ea,E=b.occurred_at??b.created_at;return e.jsxs("div",{className:"flex items-start gap-3 border-b border-[var(--color-bg-tertiary)] px-4 py-2.5 last:border-b-0",children:[e.jsx("span",{className:"mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-[var(--radius-sm)] bg-[var(--color-bg-secondary)] text-[var(--color-text-tertiary)]",children:e.jsx(g,{size:12})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"line-clamp-2 text-[length:var(--text-body-s)] font-medium text-[var(--color-text-primary)]",children:Xi(b)}),E&&e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:Ce(E)})]})]},b.id)})})]})]}),e.jsxs("section",{className:"max-sm:order-3 self-start overflow-hidden rounded-[var(--radius-lg)] border border-[var(--color-bg-tertiary)] bg-[color-mix(in_srgb,var(--color-bg-secondary)_70%,var(--color-bg-tertiary))] xl:col-start-1 xl:row-start-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-[var(--color-bg-tertiary)] px-4 py-3",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-[length:var(--text-title-s)] font-semibold text-[var(--color-text-primary)]",children:[e.jsx("span",{className:"sm:hidden",children:"Open pipeline by stage"}),e.jsx("span",{className:"max-sm:hidden",children:"Pipeline coverage"})]}),e.jsx("p",{className:"max-sm:hidden text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"Open value and deal count by stage"})]}),e.jsx("button",{type:"button",onClick:v,className:"shrink-0 text-[length:var(--text-body-s)] font-medium text-[var(--color-accent-text)] hover:underline",children:"Open pipeline"})]}),f.length===0?e.jsx("div",{className:"flex min-h-[176px] items-center justify-center px-6 text-center text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"Add pipeline stages to see coverage here."}):e.jsx("div",{className:"grid gap-x-8 gap-y-3 p-4 md:grid-cols-2 xl:grid-cols-1 2xl:grid-cols-2","aria-label":"Open pipeline coverage by stage",children:f.map(b=>e.jsxs("button",{type:"button",onClick:v,className:"group grid grid-cols-[minmax(88px,0.75fr)_minmax(120px,1.5fr)_auto] items-center gap-3 rounded-[var(--radius-sm)] text-left focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent)]",children:[e.jsx("span",{className:"truncate text-[length:var(--text-label-m)
11] font-medium text-[var(--color-text-secondary)] group-hover:text-[var(--color-text-primary)]",children:b.name}),e.jsx("span",{className:"h-2.5 overflow-hidden rounded-full bg-[var(--color-bg-secondary)]",children:e.jsx("span",{className:"block h-full min-w-0 rounded-full",style:{width:`${Math.max(b.value>0?4:0,b.value/z*100)}%`,background:b.color}})}),e.jsxs("span",{className:"min-w-[72px] text-right tabular-nums",children:[e.jsx("span",{className:"block text-[length:var(--text-label-m)] font-semibold text-[var(--color-text-primary)]",children:_a(b.value)}),e.jsxs("span",{className:"block text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:[b.count," ",b.count===1?"deal":"deals"]})]})]},b.id))})]})]})}function tc(){var T;const t=Vl(W=>{var R;return(R=W.user)==null?void 0:R.id})??null,{reports:a,reportsLoading:r,reportsPeriod:l,setReportsPeriod:n,loadReports:s,deals:i,loadDeals:d,contacts:c,personsTotal:m,companiesTotal:p,contactsLoading:u,loadContacts:x,activePipelineId:w,loadPipelines:N}=G(),h=sa(),[,v]=o.useState(0),[j,f]=o.useState("command"),[z,y]=o.useState([]),[b,g]=o.useState(0),[E,A]=o.useState(!0),[U,D]=o.useState(null),[O,P]=o.useState([]),[H,ae]=o.useState(!0),[I,k]=o.useState(null),C=o.useRef(0),_=o.useCallback(async()=>{const W=++C.current,R=()=>W===C.current;A(!0),ae(!0),D(null),k(null),await Promise.all([(async()=>{var Y;try{if(!t){R()&&(y([]),g(0));return}const re=await Ve.tasks.list({query:{limit:50,parent_task_id:"null",assignee_id:t,status:"todo,in_progress,blocked",crm_linked:"true",sort:"updated_at"}});R()&&(y(re.data??[]),g(re.total??((Y=re.data)==null?void 0:Y.length)??0))}catch{R()&&(g(0),D("Unable to load CRM-linked tasks."))}finally{R()&&A(!1)}})(),(async()=>{try{const Y=await Ve.crm.activities.list({query:{limit:20}});R()&&P(Y.data??[])}catch{R()&&k("Unable to load recent CRM activity.")}finally{R()&&ae(!1)}})()])},[t]);o.useEffect(()=>{s(),x(),_(),w?d():N()},[]);const Z=o.useCallback(async W=>{y(R=>R.filter(Y=>Y.id!==W.id)),g(R=>Math.max(0,R-1));try{await Ve.tasks.update({params:{id:W.id},body:{status:"done"}})}catch{await _()}},[_]);o.useEffect(()=>{w&&d()},[w,d]),o.useEffect(()=>{let W=null;const R=()=>{typeof document<"u"&&document.hidden||(W&&clearTimeout(W),W=setTimeout(()=>void _(),300))};Tt.retain(["tasks","activities"]);const Y=Tt.onFrame(fe=>{fe.table!=="tasks"&&fe.table!=="activities"||R()}),re=Tt.onReady(fe=>{!fe.includes("tasks")&&!fe.includes("activities")||R()});return()=>{Y(),re(),Tt.release(["tasks","activities"]),W&&clearTimeout(W)}
11},[_]);const B=o.useMemo(()=>{const W=new Date;return{overdue:mn(i,W),stuck:un(i,W),cold:Vi(c,W)}},[i,c]),V=W=>{h(`/crm/pipeline?deal=${W}`)},F=W=>{h(`/crm/people?contact=${encodeURIComponent(W)}`)},le=()=>h("/crm/people");if(o.useEffect(()=>{const W=window.setInterval(()=>v(R=>R+1),6e4);return()=>window.clearInterval(W)},[]),o.useEffect(()=>{let W=null;const R=()=>{W===null&&(W=window.setInterval(()=>{document.visibilityState==="visible"&&s()},3e4))},Y=()=>{W!==null&&(window.clearInterval(W),W=null)},re=()=>{document.visibilityState==="visible"?(s(),_(),R()):Y()};return document.visibilityState==="visible"&&R(),document.addEventListener("visibilitychange",re),()=>{Y(),document.removeEventListener("visibilitychange",re)}},[_,s]),r&&!a)return e.jsx(ac,{onPeriodChange:n,period:l});if(!a)return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col [--text-body-s:14px] [--text-label-s:14px] [--text-label-m:14px] [--text-title-m:18px] [--lh-title-m:24px]",children:[e.jsx(Xe,{title:"Overview",description:"Your CRM command center",actions:e.jsx(ns,{value:l,onChange:n})}),e.jsx("div",{className:"p-6 text-[length:var(--text-body-m)] text-[var(--color-text-secondary)]",children:"Unable to load reports right now."})]});const X=new Date(a.generated_at);return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col [--text-body-s:14px] [--text-label-s:14px] [--text-label-m:14px] [--text-title-m:18px] [--lh-title-m:24px]",children:[e.jsx(Xe,{title:"Overview",description:e.jsxs(e.Fragment,{children:["Your CRM command center · updated ",e.jsx("time",{dateTime:X.toISOString(),title:X.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}),"data-testid":"reports-updated-relative",children:Ce(a.generated_at).replace(/^Just now$/,"just now")})]}),actions:e.jsx(ns,{value:l,onChange:n}),children:e.jsx("div",{className:"px-4 md:px-6",children:e.jsx(hr,{"aria-label":"Overview sections",items:[{id:"command",label:"Command center"},{id:"reports",label:"Reports"}],value:j,onChange:W=>f(W)})})}),e.jsx("div",{className:"overflow-y-auto p-4 md:p-6",children:j==="command"?e.jsxs("div",{className:"grid grid-cols-2 gap-3 lg:grid-cols-4",children:[e.jsxs("div",{className:"contents","data-testid":"reports-kpi-strip",children:[e.jsx(Ja,{label:"People & companies",value:u?"—":String(m+p),icon:e.jsx(Ne,{size:18}),accent:"var(--color-text-secondary)",sub:u?"Loading relationship index":`${m} people · ${p} companies`,actionLabel:"Open people",onClick:le,className:"order-4 lg:order-1"}),e.jsx(Ja,{label:"Recent CRM activity",value:H||I?"—":String(a.activity_metrics.totals.total),icon:e.jsx(ea,{size:18}),accent:"var(--color-text-secondary)",sub:H?"Loading workspace signals":I?"Activity data unavailable":`${B.cold.length} cold · ${O.length} recent signals`,actionLabel:"View activity",onClick:le,className:"order-5 lg:order-2"}),e.jsx(Ja,{label:"Open pipeline value",value:Q(a.pipeline_by_owner.total_open_value),icon:e.jsx(Ze,{size:18}),accent:"var(--color-text-secondary)",sub:`${a.pipeline_by_owner.rows.reduce((W,R)=>W+R.deal_count,0)} open · ${B.overdue.length+B.stuck.length} need attention`,actionLabel:"Open pipeline",onClick:()=>h("/crm/pipeline"),className:"order-1 lg:order-3"}),e.jsx(Ja,{label:"Closed-won revenue",value:Q(a.revenue_ytd.total_ytd),icon:e.jsx(dr,{size:18}),accent:"var(--color-success-text)",sub:`${a.revenue_ytd.deals_closed_ytd} ${a.revenue_ytd.deals_closed_ytd===1?"deal":"deals"} in ${((T=ba.find(W=>W.value===l))==null?void 0:T.label.toLowerCase())??"this period"}`,actionLabel:"Open reports",onClick:()=>f("reports"),className:"order-2 lg:order-4"})]}),e.jsx("div",{className:"order-3 col-span-2 mt-3 lg:order-5 lg:col-span-4",children:e.jsx(ec,{overdue:B.overdue,stuck:B.stuck,cold:B.cold,tasks:z,activities:O,tasksLoading:E,activityLoading:H,tasksError:U,activityError:I,onRetryCommandCenter:_,onOpenDeal:V,onOpenContact:F,onToggleTask:Z,onViewTasks:()=>h("/tasks"),onViewPeople:le,pipeline:a.pipeline_by_owner,onOpenPipeline:()=>h("/crm/pipeline")})})]}):e.jsxs("section",{"aria-labelledby":"crm-reports-heading",className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"crm-reports-heading",className:"text-[length:var(--text-title-m)] font-semibold text-[var(--color-text-primary)]",children:"Performance reports"}
11),e.jsx("p",{className:"mt-0.5 text-[length:var(--text-label-m)] text-[var(--color-text-secondary)] sm:mt-1 sm:text-[length:var(--text-body-s)]",children:"Revenue, attribution, ownership, and CRM activity for the selected period."})]}),e.jsxs("div",{id:"crm-reports-grid",className:"grid grid-cols-1 gap-4 xl:grid-cols-2",children:[e.jsx(Hi,{data:a.revenue_ytd,period:l}),e.jsx(Yi,{data:a.deals_by_source,period:l}),e.jsx(Ji,{data:a.pipeline_by_owner,period:l}),e.jsx(Zi,{data:a.activity_metrics,period:l})]})]})})]})}function Ja({label:t,value:a,icon:r,accent:l,sub:n,actionLabel:s,onClick:i,className:d=""}){return e.jsxs("button",{type:"button",onClick:i,"aria-label":s,className:`flex h-full w-full flex-col text-left cursor-pointer bg-[color-mix(in_srgb,var(--color-bg-secondary)_70%,var(--color-bg-tertiary))] rounded-[var(--radius-lg)] p-2.5 sm:p-[var(--spacing-4)] border border-[var(--color-bg-tertiary)] hover:border-[var(--color-accent)] hover:bg-[var(--color-bg-secondary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] transition-colors duration-[var(--duration-micro)] ${d}`,children:[e.jsxs("div",{className:"mb-1 flex min-h-[2.5rem] items-start justify-between gap-2 sm:min-h-0",children:[e.jsx("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] min-w-0 flex-1",children:t}),e.jsx("div",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-[var(--radius-md)] sm:h-8 sm:w-8",style:{background:"var(--color-bg-tertiary)",color:l},children:r})]}),e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx("div",{"data-testid":"kpi-value",className:"text-[length:var(--text-title-l)] leading-[var(--lh-title-l)] font-semibold tabular-nums tracking-tight text-[var(--color-text-primary)]",children:a}),e.jsx(Ue,{size:16,"aria-hidden":"true",className:"shrink-0 text-[var(--color-text-tertiary)] sm:hidden"})]}),n&&e.jsx("div",{className:"mt-1 hidden text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] [.dark_&]:text-[var(--color-text-secondary)] sm:mt-2 sm:block",children:n}),e.jsxs("span",{className:"sr-only sm:not-sr-only sm:mt-auto sm:inline-flex sm:items-center sm:gap-1 sm:pt-3 sm:text-[length:var(--text-body-s)] sm:font-medium sm:text-[var(--color-accent-text)]",children:[s,e.jsx(Ue,{size:13})]})]})}function ac({period:t,onPeriodChange:a}){return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[e.jsx(Xe,{title:"Overview",description:"Your CRM command center",actions:e.jsx(ns,{value:t,onChange:a})}),e.jsxs("div",{className:"space-y-6 overflow-y-auto p-4 md:p-6",children:[e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:Array.from({length:4}).map((r,l)=>e.jsx(_e,{className:"h-[88px]"},l))}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsx(_e,{className:"h-[420px] lg:col-span-2"}),e.jsx(_e,{className:"h-[340px]"}),e.jsx(_e,{className:"h-[340px]"}),e.jsx(_e,{className:"h-[340px] lg:col-span-2"})]})]})]})}const rc=[{key:"contactName",label:"Contact Name"},{key:"contactEmail",label:"Contact Email"},{key:"companyName",label:"Company Name"},{key:"dealTitle",label:"Deal Title"},{key:"senderName",label:"Sender Name"},{key:"date",label:"Today's Date"}],sc=[{name:"Cold intro",subject:"Quick question for {{contactName}}",body:`Hi {{contactName}},
12
13I noticed your team at **{{companyName}}** is growing — congrats!
14
15I'd love to show you how we can help streamline your workflow. Would you have 15 minutes this week?
16
17Best,
18{{senderName}}`},{name:"Follow-up",subject:"Following up — {{companyName}}",body:`Hi {{contactName}},
19
20Just wanted to follow up on my previous message. I understand you're busy — even a quick reply letting me know if this isn't the right time would be helpful.
21
22Best,
23{{senderName}}`}
23,{name:"Thank you",subject:"Thank you, {{contactName}}!",body:`Hi {{contactName}},
24
25Thank you for your time today. I really enjoyed our conversation and I'm excited about the possibilities.
26
27As discussed, I'll send over the proposal by end of week.
28
29Best,
30{{senderName}}`},{name:"Meeting request",subject:"Let's connect — {{senderName}} × {{companyName}}",body:`Hi {{contactName}},
31
32Would you be available for a 30-minute call this week? I'd love to discuss how we can help {{companyName}} with [specific value prop].
33
34Feel free to pick a time that works: [scheduling link]
35
36Best,
37{{senderName}}`}];function lc({subject:t,body:a,onSubjectChange:r,onBodyChange:l}){const[n,s]=o.useState("edit"),[i,d]=o.useState(!1),[c,m]=o.useState(!1),p=o.useRef(null),u=o.useCallback(N=>{const h=p.current;if(!h){l(a+N);return}const v=h.selectionStart,j=h.selectionEnd,f=a.slice(0,v)+N+a.slice(j);l(f),requestAnimationFrame(()=>{h.focus(),h.selectionStart=h.selectionEnd=v+N.length})},[a,l]),x=o.useCallback(N=>{const h=p.current;if(!h)return;const v=h.selectionStart,j=h.selectionEnd,f=a.slice(v,j),z=a.slice(0,v)+N+f+N+a.slice(j);l(z),requestAnimationFrame(()=>{h.focus(),h.selectionStart=v+N.length,h.selectionEnd=j+N.length})},[a,l]),w=N=>{r(N.subject),l(N.body),m(!1),s("edit")};return e.jsxs("div",{className:"rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] overflow-hidden",children:[e.jsx("div",{className:"px-3 py-2 border-b border-[var(--color-bg-tertiary)]",children:e.jsx("input",{type:"text",value:t,onChange:N=>r(N.target.value),placeholder:"Email subject",className:"w-full bg-transparent text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)] border-none outline-none placeholder:text-[var(--color-text-quaternary)]"})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 border-b border-[var(--color-bg-tertiary)] bg-[var(--color-bg-secondary)] px-3 py-2",children:[e.jsx("button",{type:"button",onClick:()=>x("**"),className:"px-2 py-0.5 rounded-[var(--radius-sm)] text-[length:var(--text-label-m)] font-bold text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-tertiary)] cursor-pointer",title:"Bold",children:"B"}),e.jsx("button",{type:"button",onClick:()=>x("*"),className:"px-2 py-0.5 rounded-[var(--radius-sm)] text-[length:var(--text-label-m)] italic text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-tertiary)] cursor-pointer",title:"Italic",children:"I"}),e.jsx("div",{className:"w-px h-4 bg-[var(--color-bg-tertiary)] mx-1"}),e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:()=>{d(!i),m(!1)},className:"px-2 py-0.5 rounded-[var(--radius-sm)] text-[length:var(--text-label-s)] text-[var(--color-accent)] hover:bg-[var(--color-accent-subtle)] cursor-pointer font-mono",title:"Insert variable",children:"{{x}}"}),i&&e.jsx("div",{className:"absolute top-full left-0 mt-1 z-10 bg-[var(--color-bg-primary)] rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] shadow-[var(--shadow-lg)] py-1 min-w-[200px]",children:rc.map(N=>e.jsxs("button",{type:"button",onClick:()=>{u(`{{${N.key}}}`),d(!1)},className:"w-full px-3 py-2 text-left text-[length:var(--text-body-s)] hover:bg-[var(--color-bg-secondary)] cursor-pointer flex items-center gap-2",children:[e.jsx("code",{className:"text-[var(--color-accent)] font-mono text-[length:var(--text-label-s)]",children:`{{${N.key}}}`}),e.jsx("span",{className:"text-[var(--color-text-tertiary)]",children:N.label})]},N.key))})]}),e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:()=>{m(!c),d(!1)},className:"px-2 py-0.5 rounded-[var(--radius-sm)] text-[length:var(--text-label-s)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-tertiary)] cursor-pointer",children:"Templates"}),c&&e.jsx("div",{className:"absolute top-full left-0 mt-1 z-10 bg-[var(--color-bg-primary)] rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] shadow-[var(--shadow-lg)] py-1 min-w-[220px]",children:sc.map(N=>e.jsxs("button",{type:"button",onClick:()=>w(N),className:"w-full px-3 py-2 text-left hover:bg-[var(--color-bg-secondary)] cursor-pointer",children:[e.jsx("div",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-primary)]",children:N.name}),e.jsx("div",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)] truncate",children:N.subject})]},N.name))})]}),e.jsx("div",{className:"hidden flex-1 sm:block"}),e.jsxs("div",{className:"ml-auto flex overflow-hidden rounded-[var(--radius-sm)] border border-[var(--color-bg-tertiary)]",children:[e.jsx("button",{type:"button",onClick:()=>s("edit"),className:`px-2 py-0.5 text-[length:var(--text-label-s)] curs
37or-pointer transition-colors ${n==="edit"?"bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)] font-medium":"text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-secondary)]"}`,children:"Edit"}),e.jsx("button",{type:"button",onClick:()=>s("preview"),className:`px-2 py-0.5 text-[length:var(--text-label-s)] cursor-pointer transition-colors ${n==="preview"?"bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)] font-medium":"text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-secondary)]"}`,children:"Preview"})]})]}),n==="edit"?e.jsx("div",{className:"bg-[var(--color-bg-primary)] px-3",children:e.jsx("textarea",{ref:p,value:a,onChange:N=>l(N.target.value),placeholder:"Write your email in Markdown...",rows:8,className:"mx-auto block w-full max-w-[72ch] py-3 bg-transparent text-[length:var(--text-body-m)] text-[var(--color-text-primary)] leading-relaxed resize-y border-none outline-none placeholder:text-[var(--color-text-quaternary)] font-mono max-sm:h-28"})}):e.jsx("div",{className:"mx-auto min-h-28 w-full max-w-[72ch] px-3 py-3 sm:min-h-[160px] text-[length:var(--text-body-m)] text-[var(--color-text-primary)] leading-relaxed prose prose-sm",dangerouslySetInnerHTML:{__html:xi(nc(a))}})]})}function nc(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/\{\{(\w+)\}\}/g,'<code style="background: var(--color-accent-subtle); padding: 1px 4px; border-radius: var(--radius-sm); color: var(--color-accent); font-size: 0.85em;">{{$1}}</code>').replace(/\n/g,"<br />")}const Da={email:"Send email",wait:"Wait",task:"Create task",call:"Log call",branch:"Branch (if/else)"},pr={email:Be,wait:Cs,task:Bo,call:kt,branch:Hl},Cl={email_opened:"Opened the last email",email_not_opened:"Did not open the last email",email_replied:"Replied to the last email",email_not_replied:"Did not reply to the last email",email_bounced:"Last email bounced"},oc={active:"accent",completed:"success",paused:"default",bounced:"error",replied:"success"},Qr=[{id:"new-lead-nurture",name:"7-day lead nurture",description:"3-email cadence over 7 days to warm up a fresh lead.",icon:Ne,cadenceLabel:"3 emails · 7 days",build:()=>({name:"7-day lead nurture",description:"3-email cadence over 7 days to warm up a fresh lead.",steps:[{step_type:"email",delay_days:0,step_config:{emailSubject:"Nice to meet you, {{contactName}}",emailBody:`Hi {{contactName}},
38
39Saw you just signed up — welcome! Curious what brought you in today?
40
41Happy to send relevant examples if you share a bit about what you're working on.`},sort_order:1},{step_type:"wait",delay_days:3,step_config:{},sort_order:2},{step_type:"email",delay_days:0,step_config:{emailSubject:"A few ideas for {{contactName}}",emailBody:`Hi {{contactName}},
42
43Circling back with a couple of examples of teams like yours that might spark ideas.
44
45Let me know if any of these resonate.`},sort_order:3},{step_type:"wait",delay_days:4,step_config:{},sort_order:4},{step_type:"email",delay_days:0,step_config:{emailSubject:"Still the right time, {{contactName}}?",emailBody:`Hi {{contactName}},
46
47If now's not the right moment, totally understand — just let me know whether to close the loop or pick this up again next quarter.`},sort_order:5}]})},{id:"discovery-followup",name:"Post-discovery follow-up",description:"Recap → check-in → final nudge for contacts you just met.",icon:kt,cadenceLabel:"3 emails · 10 days",build:()=>({name:"Post-discovery follow-up",description:"Recap → check-in → final nudge for contacts you just met.",steps:[{step_type:"email",delay_days:0,step_config:{emailSubject:"Recap from our call, {{contactName}}",emailBody:`Hi {{contactName}},
48
49Great chatting today. Quick recap of what I heard and what I'll send over next:
50
51- 
52- 
53- 
54
55Let me know if I missed anything.`},sort_order:1},{step_type:"wait",delay_days:4,step_config:{},sort_order:2},{step_type:"task",delay_days:0,step_config:{taskTitle:"Check in with {{contactName}}",taskDescription:"Status check: send materials, share references, unblock next step.",taskPriority:"medium",taskDueDaysFromNow:1},sort_order:3},{step_type:"wait",delay_days:5,step_config:{},sort_order:4},{step_type:"email",delay_days:0,step_config:{emailSubject:"Keep moving, {{contactName}}?",emailBody:`Hi {{contactName}},
56
57Hoping the materials were useful. Want to lock in time to walk through next steps this week?`},sort_order:5}]})},{id:"cold-outreach-branch",name:"Cold outreach with branch",description:"Email, wait, then branch on open — call openers, retry non-openers.",icon:Hl,cadenceLabel:"3 steps · smart branch",build:()=>({name:"Cold outreach with branch",description:"Email, wait, then branch on open — call openers, retry non-openers.",steps:[{step_type:"email",delay_days:0,step_config:{emailSubject:"Quick question, {{contactName}}",emailBody:`Hi {{contactName}},
58
59We help teams like yours move faster without hiring. Worth a 15-minute look?`},sort_order:1},{step_type:"wait",delay_days:3,step_config:{},sort_order:2},{step_type:"branch",delay_days:0,step_config:{branchRules:[{condition:"email_opened",withinDays:3,target:4},{condition:"email_not_opened",target:5}]},sort_order:3},{step_type:"call",delay_days:0,step_config:{callNote:"Warm call: {{contactName}} opened the first email. Reference the note when you dial."},sort_order:4},{step_type:"email",delay_days:0,step_config:{emailSubject:"Different angle, {{contactName}}",emailBody:`Hi {{contactName}},
60
61Different subject line in case the first one missed — is this the right person to talk to about [topic]?`},sort_order:5}]})},{id:"reengage-cold",name:"Re-engage cold contacts",description:"Revive dormant contacts with a low-pressure 2-email check-in.",icon:Cs,cadence
61Label:"2 emails · 5 days",build:()=>({name:"Re-engage cold contacts",description:"Revive dormant contacts with a low-pressure 2-email check-in.",steps:[{step_type:"email",delay_days:0,step_config:{emailSubject:"Still on your radar, {{contactName}}?",emailBody:`Hi {{contactName}},
62
63It's been a while. Just checking whether this is still on your radar — happy to pick up where we left off or step back if priorities shifted.`},sort_order:1},{step_type:"wait",delay_days:5,step_config:{},sort_order:2},{step_type:"email",delay_days:0,step_config:{emailSubject:"Closing the loop, {{contactName}}",emailBody:`Hi {{contactName}},
64
65No pressure — if the timing isn't right, I'll close the loop here and reach out again in a few months. Just let me know.`},sort_order:3}]})}];function Sl(){const t=sa(),{sequences:a,sequencesLoading:r,loadSequences:l,deleteSequence:n,toggleSequence:s,activeSequence:i,selectSequence:d,clearActiveSequence:c}=G(),[m,p]=o.useState(!1),[u,x]=o.useState(null),[w,N]=o.useState(null),h=o.useCallback(g=>{const E=new URLSearchParams(window.location.search);g?E.set("id",g):E.delete("id");const A=E.toString();t(`/crm/automations${A?`?${A}`:""}`,{replace:!0})},[t]),v=o.useCallback(g=>{h(g),d(g)},[d,h]),j=o.useCallback(()=>{h(null),c()},[c,h]);o.useEffect(()=>{l()},[l]),o.useEffect(()=>{const E=new URLSearchParams(window.location.search).get("id");E&&a.length>0?(!i||i.id!==E)&&d(E):!E&&i&&c()},[a,i,d,c]),o.useEffect(()=>{const E=new URLSearchParams(window.location.search).get("template");if(E&&!m){const A=Qr.find(U=>U.id===E);A&&(x(A),p(!0))}},[m]);const f=o.useCallback(async()=>{w&&(await n(w),N(null))},[w,n]);if(i)return e.jsx(cc,{sequence:i,onClose:j});if(m)return e.jsx(uc,{template:u,onClose:()=>{p(!1),x(null);const g=new URLSearchParams(window.location.search);if(g.has("template")){g.delete("template");const E=g.toString();window.history.replaceState(null,"",`${window.location.pathname}${E?`?${E}`:""}`)}}});const z=g=>{x(g),p(!0)},y=a.filter(g=>g.is_active).length,b=a.reduce((g,E)=>g+E.enrollment_count,0);return e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsx(Xe,{title:"Sequences",description:"Multi-step automated outreach for contacts.",mobileActionsBelow:!0,actions:e.jsxs(e.Fragment,{children:[e.jsx(L,{asChild:!0,variant:"secondary",size:"compact",children:e.jsxs(_s,{to:an,"data-testid":"crm-view-automations",children:["View automations",e.jsx(la,{size:14})]})}),e.jsxs(L,{variant:"primary",size:"default",onClick:()=>p(!0),children:[e.jsx(oe,{size:16}),"Create sequence"]})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:r?e.jsx("div",{className:"p-6 space-y-2",children:Array.from({length:4}).map((g,E)=>e.jsx(Re,{},E))}):a.length===0?e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center min-h-[400px] px-6 py-10",children:[e.jsxs("div",{className:"text-center max-w-sm",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-[var(--color-accent-subtle)] flex items-center justify-center mx-auto mb-3",children:e.jsx(ht,{size:24,className:"text-[var(--color-accent)]"})}),e.jsx("h3",{className:"text-[length:var(--text-title-m)] font-semibold text-[var(--color-text-primary)] mb-1",children:"No sequences yet"}),e.jsx("p",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-secondary)] mb-4",children:"Start from a template or build one from scratch."}),e.jsxs(L,{variant:"primary",onClick:()=>p(!0),children:[e.jsx(oe,{size:16}),e.jsx("span",{className:"ml-2",children:"Start from scratch"})]})]}),e.jsxs("div",{className:"mt-10 w-full max-w-4xl","data-testid":"sequence-template-gallery","aria-label":"Sequence templates",children:[e.jsx("h4",{className:"text-[length:var(--text-label-l)] font-semibold text-[var(--color-text-primary)] mb-3",children:"Start from a template"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3",children:Qr.map(g=>e.jsx(_l,{template:g,onSelect:()=>z(g)},g.id))})]})]}):e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-6 p-4 md:p-6",children:[e.jsx("div",{className:"grid grid-cols-3 gap-3","aria-label":"Sequence summary",children:[["Total",a.length],["Active",y],["Enrolled",b]].map(([g,E])=>e.jsxs("div",{className:"rounded-[var(--radius-lg)] border border-[var(--color-bg-tertiary)] bg-[var(--color-surface-1)] p-4",children:[e.jsx("div",{className:"text-[length:var(--text-label-m)
65] text-[var(--color-text-tertiary)]",children:g}),e.jsx("div",{className:"mt-1 text-[length:var(--text-title-l)] font-semibold tabular-nums text-[var(--color-text-primary)]",children:E})]},g))}),e.jsxs("section",{className:"overflow-hidden rounded-[var(--radius-lg)] border border-[var(--color-bg-tertiary)] bg-[var(--color-surface-1)]",children:[e.jsxs("div",{className:"border-b border-[var(--color-bg-tertiary)] px-4 py-3 sm:px-6",children:[e.jsx("h2",{className:"text-[length:var(--text-title-s)] font-semibold text-[var(--color-text-primary)]",children:"All sequences"}),e.jsx("p",{className:"mt-0.5 text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:"Open a sequence to edit steps, enroll contacts, and review outcomes."})]}),e.jsx("div",{className:"divide-y divide-[var(--color-bg-tertiary)]",children:a.map(g=>e.jsx(ic,{sequence:g,onSelect:()=>v(g.id),onToggle:E=>s(g.id,E),onDelete:()=>N(g.id)},g.id))})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-[length:var(--text-title-s)] font-semibold text-[var(--color-text-primary)]",children:"Start from a template"}),e.jsx("p",{className:"mt-0.5 text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:"Create another sequence with a proven cadence, then tailor its steps."}),e.jsx("div",{className:"mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4",children:Qr.map(g=>e.jsx(_l,{template:g,onSelect:()=>z(g)},g.id))})]})]})}),e.jsx(we,{open:!!w,onOpenChange:g=>!g&&N(null),title:"Delete sequence",description:"This sequence, all its steps, and enrollment history will be permanently deleted. Active enrollments will stop.",confirmLabel:"Delete",variant:"destructive",onConfirm:f})]})}function _l({template:t,onSelect:a}){const r=t.icon;return e.jsxs("button",{type:"button",onClick:a,"data-testid":`sequence-template-card-${t.id}`,className:"group text-left rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] p-4 hover:border-[var(--color-accent)] hover:bg-[var(--color-accent-subtle)] transition-colors cursor-pointer focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)]",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-[var(--radius-md)] bg-[var(--color-bg-secondary)] flex items-center justify-center shrink-0 text-xl","aria-hidden":"true",children:e.jsx(r,{size:18,className:"text-[var(--color-accent)]"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[length:var(--text-body-m)] font-semibold text-[var(--color-text-primary)] leading-tight",children:t.name}),e.jsx("div",{className:"text-[length:var(--text-label-s)] text-[var(--color-accent)] mt-1 font-medium",children:t.cadenceLabel})]})]}),e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] leading-snug",children:t.description})]})}function ic({sequence:t,onSelect:a,onToggle:r,onDelete:l}){const n=t.steps.reduce((s,i)=>s+i.delay_days,0);return e.jsxs("div",{"data-testid":"crm-sequence-row",className:"grid grid-cols-[auto_minmax(0,1fr)] items-center gap-x-3 gap-y-2 px-4 py-4 hover:bg-[var(--color-bg-secondary)] cursor-pointer transition-colors sm:grid-cols-[auto_minmax(0,1fr)_auto] sm:px-6",onClick:a,children:[e.jsx("div",{className:"w-8 h-8 rounded-[var(--radius-md)] bg-[var(--color-accent-subtle)] flex items-center justify-center shrink-0",children:e.jsx(ht,{size:16,className:"text-[var(--color-accent)]"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)] truncate",children:t.name}),e.jsx(de,{variant:t.is_active?"success":"default",children:t.is_active?"Active":"Draft"})]}),e.jsxs("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] mt-0.5",children:[t.steps.length," step",t.steps.length!==1?"s":"",n>0&&` · ${n} day${n!==1?"s":""}`,t.enrollment_count>0&&` · ${t.enrollment_count} enrolled`]})]}),e.jsxs("div",{className:"col-start-2 flex items-center justify-between gap-2 sm:col-start-3 sm:row-start-1 sm:justify-end",children:[e.jsx("button",{className:"px-3 py-1 rounded-[var(--radius-md)] text-[length:var(--text-label-m)
65] font-medium transition-colors hover:bg-[var(--color-bg-tertiary)]",style:{color:t.is_active?"var(--color-text-secondary)":"var(--color-accent)"},onClick:s=>{s.stopPropagation(),r(!t.is_active)},children:t.is_active?"Pause":"Activate"}),e.jsx("button",{className:"p-2 rounded-[var(--radius-md)] text-[var(--color-text-tertiary)] hover:text-[var(--color-error)] hover:bg-[var(--color-error-subtle)] transition-colors","aria-label":`Delete ${t.name}`,onClick:s=>{s.stopPropagation(),l()},children:e.jsx(he,{size:14})}),e.jsx(Ue,{size:16,className:"text-[var(--color-text-tertiary)]"})]})]})}function cc({sequence:t,onClose:a}){const{sequenceEnrollments:r,sequenceEnrollmentsLoading:l,loadSequenceEnrollments:n,toggleSequence:s,updateSequence:i,deleteSequence:d,unenrollContact:c,contacts:m,loadContacts:p,enrollContact:u}=G(),[x,w]=o.useState(t.name),[N,h]=o.useState(t.description??""),[v,j]=o.useState([...t.steps].sort((B,V)=>B.sort_order-V.sort_order).map(B=>({stepType:B.step_type,delayDays:B.delay_days,config:B.step_config}))),[f,z]=o.useState(!1),[y,b]=o.useState(!1),[g,E]=o.useState(!1),[A,U]=o.useState(""),[D,O]=o.useState(!1);o.useEffect(()=>{n(t.id)},[t.id,n]);const P=async B=>{O(!0),await u(t.id,B),O(!1),E(!1),U("")},H=B=>{j([...v,{stepType:B,delayDays:B==="wait"?1:0,config:{}}])},ae=B=>{j(v.filter((V,F)=>F!==B))},I=(B,V,F)=>{j(v.map((le,X)=>X===B?{...le,config:{...le.config,[V]:F}}:le))},k=(B,V)=>{j(v.map((F,le)=>le===B?{...F,delayDays:V}:F))},C=async()=>{!x.trim()||v.length===0||(z(!0),await i(t.id,{name:x.trim(),description:N.trim()||void 0,steps:v.map((B,V)=>({step_type:B.stepType,delay_days:B.delayDays,step_config:B.config,sort_order:V+1}))}),z(!1),ge({title:"Sequence saved"}))},_=async()=>{await d(t.id),a()},Z=v.reduce((B,V,F)=>(B.push(F===0?V.delayDays:B[F-1]+V.delayDays),B),[]);return e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsx(vt,{onBack:a,backLabel:"Back to sequences",mobileActionsBelow:!0,title:e.jsx("input",{value:x,onChange:B=>w(B.target.value),placeholder:"Sequence name","aria-label":"Sequence name",className:"block w-full min-w-0 bg-transparent text-[length:var(--text-title-m)] font-semibold text-[var(--color-text-primary)] outline-none"}),description:e.jsx("input",{value:N,onChange:B=>h(B.target.value),placeholder:"Add description (optional)","aria-label":"Sequence description",className:"w-full bg-transparent text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] outline-none placeholder:text-[var(--color-text-tertiary)]"}),actions:e.jsxs(e.Fragment,{children:[e.jsx(rn,{compact:!0,label:"Sequence sections",items:[{id:"sequence-steps",label:"Steps"},{id:"sequence-enrollments",label:"Enrolled"}]}),e.jsx(de,{variant:t.is_active?"success":"default",children:t.is_active?"Active":"Draft"}),e.jsx(L,{variant:"secondary",size:"compact",onClick:C,disabled:f||!x.trim()||v.length===0,children:f?"Saving…":"Save"}),e.jsx(L,{variant:t.is_active?"secondary":"primary",size:"compact",onClick:()=>s(t.id,!t.is_active),children:t.is_active?"Pause":"Activate"})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4 pb-[calc(var(--mobile-tab-bar-clearance,0px)+2rem)] sm:p-6",children:e.jsxs("div",{className:"mx-auto w-full max-w-5xl space-y-6",children:[e.jsxs("section",{id:"sequence-steps",className:"scroll-mt-14",children:[e.jsxs("h3",{className:"text-[length:var(--text-label-l)] font-semibold text-[var(--color-text-primary)] mb-3",children:["Steps (",v.length,")",Z.length>0&&` · ${Z[Z.length-1]} days total`]}),e.jsxs("div",{className:"space-y-3",children:[v.map((B,V)=>e.jsx(vn,{index:V,step:B,stepCount:v.length,allSteps:v,cumulativeDay:Z[V]??0,onUpdateConfig:(F,le)=>I(V,F,le),onUpdateDelay:F=>k(V,F),onRemove:()=>ae(V)},V)),e.jsx("div",{className:"flex flex-wrap gap-2 pt-1",children:Object.entries(Da).map(([B,V])=>e.jsxs("button",{type:"button",onClick:()=>H(B),className:"px-3 py-2 rounded-[var(--radius-sm)] border border-dashed border-[var(--color-bg-tertiary)] text-[length:var(--text-label-m)] text-[var(--color-text-tertiary)] hover:border-[var(--color-accent)] hover:text-[var(--color-accent)] transition-colors cursor-pointer",children:["+ ",V]},B))})]})]}),e.jsxs("section",{id:"sequence-enrollments",className:"scroll-mt-14",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:"text-[length:var(--text-label-l)] font-semibold text-[var(--color-text-primary)]",children:["Enrolled contacts (",t.enrollment_count,")"]}),t.is_active&&e.jsxs(L,{variant:"secondary",size:"compact",onClick:()=>{E(!0),p()},children:[e.jsx(oe,{size:14}),e.jsx("span",{className:"ml-1",children:"Enroll contact"})]})]}),g&&e.jsxs("div",{className:"rounded-[var(--radius-md)] border border-[var(--color-accent)] p-4 mb-3 bg-[var(--color-bg-secondary)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-[length:var(--text-label-m)
65] font-medium text-[var(--color-text-primary)]",children:"Select a contact to enroll"}),e.jsx("button",{onClick:()=>{E(!1),U("")},className:"p-1 rounded-[var(--radius-sm)] text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-tertiary)] cursor-pointer",children:e.jsx(ze,{size:14})})]}),e.jsx("input",{type:"text",value:A,onChange:B=>U(B.target.value),placeholder:"Search contacts...",className:"w-full h-8 px-3 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] text-[length:var(--text-body-s)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)] placeholder:text-[var(--color-text-quaternary)] mb-2",autoFocus:!0}),e.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:m.filter(B=>B.type==="person").filter(B=>!A||B.name.toLowerCase().includes(A.toLowerCase())||B.email&&B.email.toLowerCase().includes(A.toLowerCase())).slice(0,10).map(B=>e.jsxs("button",{onClick:()=>P(B.id),disabled:D,className:"w-full flex items-center gap-2 px-3 py-2 rounded-[var(--radius-sm)] text-left hover:bg-[var(--color-bg-tertiary)] transition-colors disabled:opacity-50 cursor-pointer",children:[e.jsx(Ne,{size:14,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-primary)] truncate",children:B.name}),B.email&&e.jsx("div",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)] truncate",children:B.email})]})]},B.id))})]}),l?e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((B,V)=>e.jsx(Re,{},V))}):r.length===0?e.jsx("div",{className:"rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] p-6 text-center",children:e.jsx("p",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-secondary)]",children:t.is_active?"Enroll contacts to start the sequence.":"Activate the sequence first, then enroll contacts."})}):e.jsx("div",{className:"rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] divide-y divide-[var(--color-bg-tertiary)]",children:r.map(B=>e.jsx(mc,{enrollment:B,totalSteps:v.length,onUnenroll:()=>c(B.id)},B.id))})]}),e.jsx("div",{className:"flex items-center pt-4 border-t border-[var(--color-bg-tertiary)]",children:e.jsx(L,{type:"button",variant:"ghost",size:"compact",className:"text-[var(--color-error-text)] hover:text-[var(--color-error-text)]",onClick:()=>b(!0),children:"Delete sequence"})})]})}),e.jsx(we,{open:y,onOpenChange:b,title:"Delete sequence",description:"Active enrollments stop immediately. This cannot be undone.",variant:"destructive",onConfirm:_})]})}const dc={email_sent:"Email sent",email_opened:"Email opened",email_replied:"Email replied",email_bounced:"Email bounced",step_executed:"Step executed",branch_evaluated:"Branch evaluated"},xc={email_sent:"var(--color-accent)",email_opened:"var(--color-success)",email_replied:"var(--color-success)",email_bounced:"var(--color-error)",step_executed:"var(--color-text-tertiary)",branch_evaluated:"var(--color-purple)"};function mc({enrollment:t,totalSteps:a,onUnenroll:r}){var m;const{enrollmentEvents:l,loadEnrollmentEvents:n}=G(),[s,i]=o.useState(!1),d=l[t.id]??[],c=()=>{s||n(t.id),i(!s)};return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 flex items-center gap-3",children:[e.jsx(Ne,{size:16,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)] truncate",children:((m=t.contact)==null?void 0:m.name)??"Unknown contact"}),e.jsxs("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:["Step ",Math.min(t.current_step_index+1,a)," of ",a,t.next_execute_at&&t.status==="active"&&e.jsxs(e.Fragment,{children:[" · Next: ",Ce(t.next_execute_at)]})]})]}),e.jsx("button",{onClick:c,className:"px-2 py-1 rounded-[var(--radius-md)] text-[length:var(--text-label-s)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-tertiary)] transition-colors",title:"View activity",children:s?"Hide activity":"Activity"}),e.jsx(de,{variant:oc[t.status]??"default",children:t.status}),t.status==="active"&&e.jsx("button",{onClick:r,className:"p-2 rounded-[var(--radius-md)] text-[var(--color-text-tertiary)] hover:text-[var(--color-error)] hover:bg-[var(--color-error-subtle)] transition-colors",title:"Remove from sequence",children:e.jsx(ze,{size:14})})]}),s&&e.jsx("div",{className:"px-4 pb-3 pt-0 ml-6",children:d.length===0?e.jsx("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] italic py-2",children:"No events yet."}):e.jsx("div",{className:"space-y-1 border-l-2 border-[var(--color-bg-tertiary)] pl-3",children:d.map(p=>e.jsxs("div",{className:"flex items-center gap-2 text-[length:var(--text-body-s)]",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full shrink-0",style:{background:xc[p.event_type]}}),e.jsx("span",{className:"font-medium text-[var(--color-text-primary)]",children:dc[p.event_type]}),p.step_sort_order!=null&&e.jsxs("span",{className:"text-[var(--color-text-tertiary)]",children:["· Step ",p.step_sort_order]}),p.metadata&&typeof p.metadata.matched<"u"&&e.jsxs("span",{className:"text-[var(--color-text-tertiary)]",children:["· matched: ",(()=>{const u=p.metadata.matched;return u===null?"no rule (fall through)":u==="end"?"end sequence":`step ${u}`})()]}),p.created_at&&e.jsx("span",{className:"text-[var(--color-text-tertiary)] ml-auto",children:Ce(p.created_at)})]}
65,p.id))})})]})}function uc({template:t,onClose:a}){const{createSequence:r}=G(),l=t==null?void 0:t.build(),[n,s]=o.useState((l==null?void 0:l.name)??""),[i,d]=o.useState((l==null?void 0:l.description)??""),[c,m]=o.useState((l==null?void 0:l.steps.map(y=>({stepType:y.step_type,delayDays:y.delay_days,config:y.step_config})))??[]),[p,u]=o.useState(!1),[x,w]=o.useState(null),N=y=>{const b=c.length===0?0:y==="wait"?3:1,g=y==="branch"?{branchRules:[{condition:"email_opened",target:"end"}]}:{};m([...c,{stepType:y,delayDays:b,config:g}])},h=y=>{m(c.filter((b,g)=>g!==y))},v=(y,b)=>{m(c.map((g,E)=>E===y?{...g,...b,config:b.config?{...g.config,...b.config}:g.config}:g))},j=(y,b,g)=>{m(c.map((E,A)=>A===y?{...E,config:{...E.config,[b]:g}}:E))},f=async()=>{if(!n.trim()||c.length===0)return;w(null);for(let g=0;g<c.length;g++){const E=c[g];if(E.stepType!=="branch")continue;const A=E.config.branchRules??[];if(A.length===0){w(`Step ${g+1} (branch) needs at least one rule.`);return}for(const U of A)if(U.target!=="end"&&typeof U.target=="number"&&(U.target<1||U.target>c.length)){w(`Step ${g+1} (branch) has a rule targeting step ${U.target}, which doesn't exist.`);return}}u(!0);const y={name:n.trim(),description:i.trim()||void 0,steps:c.map((g,E)=>({step_type:g.stepType,delay_days:g.delayDays,step_config:g.config,sort_order:E+1}))},b=await r(y);u(!1),b?(ge({title:"Sequence created"}),a()):w("Failed to save sequence. Check the server response and try again.")},z=c.reduce((y,b,g)=>(y.push((y[g-1]??0)+b.delayDays),y),[]);return e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsx(vt,{title:t?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"max-sm:hidden",children:"Create sequence — "}),t.name]}):"Create sequence",titleLabel:t?`Create sequence — ${t.name}`:"Create sequence",onBack:a,backLabel:"Close sequence editor",mobileActionsBelow:!0,actions:e.jsx(L,{variant:"primary",size:"default",onClick:f,disabled:!n.trim()||c.length===0||p,children:p?"Saving...":"Save sequence"})}),e.jsxs("div",{className:"mx-auto w-full max-w-5xl flex-1 space-y-6 overflow-y-auto p-4 pb-[calc(var(--mobile-tab-bar-clearance,0px)+2rem)] sm:p-6",children:[e.jsx(rn,{label:"Sequence builder sections",items:[{id:"sequence-basics",label:"Basics"},{id:"sequence-builder-steps",label:"Steps"},{id:"sequence-preview",label:"Preview"}]}),e.jsxs("section",{id:"sequence-basics",className:"scroll-mt-14 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-base leading-6 font-medium text-[var(--color-text-primary)] mb-1 md:text-[length:var(--text-label-l)] md:leading-[var(--lh-label-l)]",children:["Name ",e.jsx("span",{className:"text-[var(--color-error-text)]","aria-hidden":"true",children:"*"})]}),e.jsx("input",{type:"text","aria-label":"Sequence name","aria-required":"true",required:!0,value:n,onChange:y=>s(y.target.value),placeholder:"e.g., New lead nurture sequence",className:"w-full h-9 px-3 rounded-[var(--radius-md)] border border-[var(--color-border-control)] bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] text-[length:var(--text-body-m)] pointer-coarse:text-base focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)] placeholder:text-[var(--color-text-quaternary)]"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-base leading-6 font-medium text-[var(--color-text-primary)] mb-1 md:text-[length:var(--text-label-l)] md:leading-[var(--lh-label-l)]",children:"Description (optional)"}),e.jsx("textarea",{"aria-label":"Sequence description",value:i,onChange:y=>d(y.target.value),placeholder:"What does this sequence do?",rows:2,className:"w-full resize-none px-3 py-2 rounded-[var(--radius-md)] border border-[var(--color-border-control)] bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] text-[length:var(--text-body-m)] pointer-coarse:text-base focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)] placeholder:text-[var(--color-text-tertiary)]"})]})]}),e.jsxs("section",{id:"sequence-builder-steps",className:"scroll-mt-14",children:[e.jsx("h3",{className:"text-[length:var(--text-label-l)] font-semibold text-[var(--color-text-primary)] mb-3",children:"Steps"}),x&&e.jsx("div",{className:"mb-3 rounded-[var(--radius-md)] border border-[var(--color-error)] bg-[var(--color-error-subtle)] px-3 py-2 text-[length:var(--text-body-s)] text-[var(--color-error-text)]",children:x}),c.length>0&&e.jsx("div",{className:"space-y-2 mb-3",children:c.map((y,b)=>e.jsx(vn,{index:b,step:y,stepCount:c.length,allSteps:c,cumulativeDay:z[b],onUpdateConfig:(g,E)=>j(b,g,E),onUpdateDelay:g=>v(b,{delayDays:g}),onRemove:()=>h(b)},b))}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(Da).map(([y,b])=>e.jsxs("button",{onClick:()=>N(y),className:"flex items-center gap-2 px-3 py-2 rounded-[var(--radius-md)] border border-dashed border-[var(--color-bg-tertiary)] text-[length:var(--text-label-m)
65] text-[var(--color-text-secondary)] hover:border-[var(--color-accent)] hover:text-[var(--color-accent)] transition-colors",children:[Ie.createElement(pr[y],{size:15}),b]},y))})]}),c.length>0&&e.jsxs("section",{id:"sequence-preview",className:"scroll-mt-14",children:[e.jsx("h3",{className:"text-[length:var(--text-label-l)] font-semibold text-[var(--color-text-primary)] mb-3",children:"Timeline preview"}),e.jsxs("div",{className:"rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] p-4 bg-[var(--color-bg-secondary)]",children:[e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:c.map((y,b)=>e.jsxs(Ie.Fragment,{children:[b>0&&y.delayDays>0&&e.jsxs("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-secondary)]",children:["→ ",y.delayDays,"d →"]}),b>0&&y.delayDays===0&&e.jsx("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-secondary)]",children:"→"}),e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-[var(--radius-md)] bg-[var(--color-bg-tertiary)] text-[length:var(--text-label-m)] text-[var(--color-text-primary)]",children:[Ie.createElement(pr[y.stepType],{size:14}),Da[y.stepType]]})]},b))}),e.jsxs("div",{className:"mt-2 text-[length:var(--text-label-s)] leading-[var(--lh-label-s)] text-[var(--color-text-secondary)]",children:["Total duration: ",z[z.length-1]??0," day",(z[z.length-1]??0)!==1?"s":""]})]})]})]})]})}function vn({index:t,step:a,stepCount:r,allSteps:l,cumulativeDay:n,onUpdateConfig:s,onUpdateDelay:i,onRemove:d}){const[c,m]=o.useState(t===0);return e.jsxs("div",{className:"rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] p-4 bg-[var(--color-bg-secondary)]",children:[e.jsxs("div",{className:`flex items-center justify-between ${c?"mb-3":""}`,children:[e.jsxs("button",{type:"button","aria-expanded":c,"aria-label":`${c?"Collapse":"Expand"} step ${t+1}`,onClick:()=>m(p=>!p),className:"flex min-h-9 min-w-0 flex-1 items-center gap-2 rounded-[var(--radius-sm)] text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]",children:[e.jsx(Ue,{size:15,className:`shrink-0 text-[var(--color-text-tertiary)] transition-transform ${c?"rotate-90":""}`}),Ie.createElement(pr[a.stepType],{size:17,className:"text-[var(--color-text-secondary)]"}),e.jsxs("span",{className:"truncate text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)]",children:[t+1,". ",Da[a.stepType]]}),e.jsxs(de,{variant:"default",className:"text-[length:var(--text-label-s)] leading-[var(--lh-label-s)] tracking-normal",children:["Day ",n]})]}),e.jsx("button",{type:"button",onClick:d,"aria-label":`Remove step ${t+1}`,className:"p-1 rounded-[var(--radius-md)] text-[var(--color-text-tertiary)] hover:text-[var(--color-error)] hover:bg-[var(--color-error-subtle)] transition-colors",children:e.jsx(he,{size:14})})]}),c&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-3 items-end",children:[e.jsxs("div",{className:"w-32",children:[e.jsx("label",{className:"mb-1 block text-[length:var(--text-label-l)] font-medium text-[var(--color-text-primary)]",children:"Delay (days)"}),e.jsx("input",{type:"number","aria-label":`Delay for step ${t+1} in days`,min:0,max:365,value:a.delayDays,onChange:p=>i(Math.max(0,Number(p.target.value)||0)),className:"w-full h-8 px-2 rounded-[var(--radius-md)] border border-[var(--color-text-tertiary)] bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] text-[length:var(--text-body-s)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)]"})]}),e.jsx("div",{className:"pb-2 text-[length:var(--text-label-s)] leading-[var(--lh-label-s)] text-[var(--color-text-secondary)]",children:a.delayDays===0?"Immediately":`Wait ${a.delayDays} day${a.delayDays!==1?"s":""} before this step`})]}),a.stepType==="email"&&e.jsx(lc,{subject:a.config.emailSubject??"",body:a.config.emailBody??"",onSubjectChange:p=>s("emailSubject",p),onBodyChange:p=>s("emailBody",p)}),a.stepType==="task"&&e.jsxs(e.Fragment,{children:[e.jsx(Hr,{label:"Task title",value:a.config.taskTitle??"",onChange:p=>s("taskTitle",p),placeholder:"Follow up with {{contactName}}"}),e.jsx(Hr,{label:"Description",value:a.config.taskDescription??"",onChange:p=>s("taskDescription",p),placeholder:"Optional description..."}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"block text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)] mb-1",children:"Priority"}),e.jsxs("select",{"aria-label":`Priority for step ${t+1}`,value:a.config.taskPriority??"medium",onChange:p=>s("taskPriority",p.target.value),className:"w-full h-8 px-2 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] text-[length:var(--text-body-s)]",children:[e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"medium",children:"Medium"}),e.jsx("option",{value:"high",children:"High"}),e.jsx("option",{value:"urgent",children:"Urgent"})]})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"block text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)] mb-1",children:"Due in (days)"}),e.jsx("input",{type:"number","aria-label":`Due date offset for step ${t+1} in days`,min:1,max:365,value:a.config.taskDueDaysFromNow??"",onChange:p=>s("taskDueDaysFromNow",p.target.value?Number(p.target.value):void 0),placeholder:"3",className:"w-full h-8 px-2 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] text-[length:var(--text-body-s)]"})]})]})]}),a.stepType==="call"&&e.jsx(Hr,{label:"Call note",value:a.config.callNote??"",onChange:p=>s("callNote",p),placeholder:"Discuss {{contactName}}'s needs..."}),a.stepType==="wait"&&e.jsxs("div",{className:"text-[length:var(--text-label-s)] leading-[var(--lh-label-s)] text-[var(--color-text-secondary)]",children:["This step pauses the sequence for ",a.delayDays," day",a.delayDays!==1?"s":""," before proceeding to the next step."]}),a.stepType==="branch"&&e.jsx(pc,{rules:a.config.branchRules??[],stepIndex:t,stepCount:r,allSteps:l,onChange:p=>s("branchRules",p)})]}),c&&(a.stepType==="email"||a.stepType==="task"||a.stepType==="call")?e.jsxs("div",{className:"mt-2 text-[length:var(--text-label-s)] leading-[var(--lh-label-s)] text-[var(--color-text-secondary)]",children:["Variables: ","{{contactName}}"," ","{{contactEmail}}"," ","{{date}}"]}):null]})}function pc({rules:t,stepIndex:a,stepCount:r,allSteps:l,onChange:n}){const s=()=>{n([...t,{condition:"email_opened",target:"end"}])},i=(m,p)=>{n(t.map((u,x)=>x===m?{...u,...p}:u))},d=m=>{n(t.filter((p,u)=>u!==m))},c=[];for(let m=a+1;m<r;m++){const p=l[m];c.push({value:m+1,label:`Step ${m+1} · ${pr[p.stepType]} ${Da[p.stepType]}`})}return c.push({value:"end",label:"End sequence"}),e.jsxs("div",{className:"space-y-2 mt-2",children:[e.jsx("div",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:"Rules are evaluated in order. The first match wins. If no rule matches, the sequence continues to the next step."}),t.map((m,p)=>e.jsxs("div",{className:"rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] shrink-0",children:"IF"}),e.jsx("select",{"aria-label":`Condition for branch rule ${p+1}`,value:m.condition,onChange:u=>i(p,{condition:u.target.value}),className:"flex-1 h-8 px-2 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] text-[length:var(--text-body-s)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)]",children:Object.keys(Cl).map(u=>e.jsx("option",{value:u,children:Cl[u]},u))}),e.jsx("button",{onClick:()=>d(p),className:"p-1 rounded-[var(--radius-md)] text-[var(--color-text-tertiary)] hover:text-[var(--color-error)] hover:bg-[var(--color-error-subtle)] transition-colors shrink-0",title:"Remove rule",children:e.jsx(he,{size:14})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] shrink-0",children:"GO TO"}),e.jsxs("select",{"aria-label":`Destination for branch rule ${p+1}`,value:typeof m.target=="number"?String(m.target):m.target,onCh
65ange:u=>i(p,{target:u.target.value==="end"?"end":Number(u.target.value)}),className:"flex-1 h-8 px-2 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] text-[length:var(--text-body-s)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)]",children:[c.length===0&&e.jsx("option",{value:"end",children:"End sequence"}),c.map(u=>e.jsx("option",{value:String(u.value),children:u.label},String(u.value)))]})]}),(m.condition==="email_opened"||m.condition==="email_not_opened"||m.condition==="email_replied"||m.condition==="email_not_replied")&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] shrink-0",children:"WITHIN"}),e.jsx("input",{type:"number","aria-label":`Time window for branch rule ${p+1} in days`,min:0,max:365,value:m.withinDays??"",onChange:u=>i(p,{withinDays:u.target.value===""?void 0:Number(u.target.value)}),placeholder:"any time",className:"w-24 h-8 px-2 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] text-[length:var(--text-body-s)]"}),e.jsx("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:"days (optional)"})]})]},p)),e.jsx("button",{onClick:s,className:"w-full px-3 py-2 rounded-[var(--radius-md)] border border-dashed border-[var(--color-bg-tertiary)] text-[length:var(--text-label-s)] text-[var(--color-text-secondary)] hover:border-[var(--color-accent)] hover:text-[var(--color-accent)] transition-colors",children:"+ Add rule"})]})}function Hr({label:t,value:a,onChange:r,placeholder:l}){return e.jsxs("div",{children:[e.jsx("label",{className:"block text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)] mb-1",children:t}),e.jsx("input",{type:"text","aria-label":t,value:a,onChange:n=>r(n.target.value),placeholder:l,className:"w-full h-8 px-2 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] text-[length:var(--text-body-s)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)] placeholder:text-[var(--color-text-tertiary)]"})]})}const os={equals:"Equals",not_equals:"Does not equal",contains:"Contains",not_contains:"Does not contain",is_set:"Is set",is_not_set:"Is not set",greater_than:"Greater than",less_than:"Less than"},bn=["equals","not_equals","contains","not_contains","greater_than","less_than"];function hc(){const{scoringRules:t,scoringRulesLoading:a,scorableFields:r,loadScoringRules:l,loadScorableFields:n,createScoringRule:s,updateScoringRule:i,deleteScoringRule:d,recalculateAllScores:c}=G(),m=Array.isArray(r)?r:[],[p,u]=o.useState(!1),[x,w]=o.useState(null),[N,h]=o.useState(null),[v,j]=o.useState(!1);o.useEffect(()=>{l(),n()},[l,n]);const f=async g=>{await s(g)&&u(!1)},z=async(g,E)=>{await i(g,E)&&w(null)},y=async()=>{N&&(await d(N),h(null))},b=async()=>{j(!0),await c(),j(!1)};return p||x?e.jsx(bc,{fields:m,editingRule:x,onSave:g=>{x?z(x.id,g):f(g)},onCancel:()=>{u(!1),w(null)}}):e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(Xe,{title:"Scoring rules",description:"Configure rules to automatically score contacts based on their attributes.",actions:e.jsxs(e.Fragment,{children:[e.jsxs(L,{variant:"secondary",size:"compact","aria-label":"Recalculate all scores",title:"Recalculate all scores",onClick:b,disabled:v,children:[e.jsx(Ql,{size:16,className:v?"animate-spin":void 0}),e.jsx("span",{className:"hidden sm:inline",children:v?"Recalculating…":"Recalculate all"})]}),e.jsxs(L,{variant:"primary",size:"compact","aria-label":"Add scoring rule",title:"Add scoring rule",onClick:()=>u(!0),children:[e.jsx(oe,{size:16}),e.jsx("span",{className:"hidden sm:inline",children:"Add rule"})]})]})}),e.jsx("div",{className:"divide-y divide-[var(--color-bg-tertiary)]",children:a?Array.from({length:3}).map((g,E)=>e.jsx(Re,{},E)):t.length===0?e.jsx(De,{icon:e.jsx(Yl,{size:24,className:"text-[var(--color-accent)]"}),title:"No scoring rules yet",description:"Create rules to automatically score contacts based on their properties like lifecycle stage, email, industry, and more.",action:e.jsxs(L,{variant:"primary",size:"default",className:"mt-4",onClick:()=>u(!0),children:[e.jsx(oe,{size:16}),e.jsx("span",{className:"ml-2",children:"Create first rule"})]})}):t.map(g=>e.jsx(vc,{rule:g,fields:m,onEdit:()=>w(g),onToggle:E=>i(g.id,{is_active:E}),onDelete:()=>
65h(g.id)},g.id))}),t.length>0&&e.jsx("div",{className:"p-4 bg-[var(--color-bg-secondary)] border-t border-[var(--color-bg-tertiary)]",children:e.jsxs("div",{className:"flex items-center gap-4 text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-[var(--color-text-primary)]",children:t.length})," rule",t.length!==1?"s":""]}),e.jsxs("span",{children:[e.jsx("strong",{className:"text-[var(--color-text-primary)]",children:t.filter(g=>g.is_active).length})," active"]}),e.jsxs("span",{children:["Max possible score: ",e.jsx("strong",{className:"text-[var(--color-text-primary)] tabular-nums",children:t.filter(g=>g.is_active&&g.points>0).reduce((g,E)=>g+E.points,0)})]})]})}),e.jsx(we,{open:!!N,title:"Delete scoring rule",description:"Contact scores will be recalculated.",confirmLabel:"Delete",onConfirm:y,onOpenChange:g=>{g||h(null)},variant:"destructive"})]})}function vc({rule:t,fields:a,onEdit:r,onToggle:l,onDelete:n}){var d;const s=((d=a.find(c=>c.key===t.field))==null?void 0:d.label)||t.field,i=bn.includes(t.operator);return e.jsxs("div",{className:"flex items-start md:items-center gap-3 px-4 py-3 hover:bg-[var(--color-bg-secondary)] transition-colors group",children:[e.jsx(Ul,{checked:t.is_active,onCheckedChange:l,"aria-label":t.is_active?`Disable ${t.name}`:`Enable ${t.name}`,title:t.is_active?"Disable rule":"Enable rule"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:`text-[length:var(--text-body-m)] font-medium max-md:line-clamp-2 ${t.is_active?"text-[var(--color-text-primary)]":"text-[var(--color-text-quaternary)]"}`,children:t.name})}),e.jsxs("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] mt-0.5",children:["If ",e.jsx("span",{className:"font-medium text-[var(--color-text-secondary)]",children:s})," ",e.jsx("span",{className:"text-[var(--color-text-secondary)]",children:os[t.operator].toLowerCase()}),i&&t.value&&e.jsxs(e.Fragment,{children:[" ",e.jsxs("span",{className:"font-medium text-[var(--color-text-secondary)]",children:['"',t.value,'"']})]})]})]}),e.jsx("div",{className:"shrink-0",children:e.jsxs(de,{variant:t.points>0?"success":t.points<0?"error":"default",children:[t.points>0?`+${t.points}`:t.points," pts"]})}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 pointer-coarse:opacity-100 transition-opacity",children:[e.jsx("button",{onClick:r,"aria-label":`Edit ${t.name}`,className:"p-2 rounded-[var(--radius-sm)] text-[var(--color-text-tertiary)] hover:text-[var(--color-accent)] hover:bg-[var(--color-accent-subtle)] cursor-pointer",title:"Edit rule",children:e.jsx(We,{size:14})}),e.jsx("button",{onClick:n,"aria-label":`Delete ${t.name}`,className:"p-2 rounded-[var(--radius-sm)] text-[var(--color-text-tertiary)] hover:text-[var(--color-error)] hover:bg-[var(--color-error-subtle)] cursor-pointer",title:"Delete rule",children:e.jsx(he,{size:14})})]})]})}function bc({fields:t=[],editingRule:a,onSave:r,onCancel:l}){var j,f,z;const[n,s]=o.useState((a==null?void 0:a.name)||""),[i,d]=o.useState((a==null?void 0:a.field)||((j=t[0])==null?void 0:j.key)||""),[c,m]=o.useState((a==null?void 0:a.operator)||"is_set"),[p,u]=o.useState((a==null?void 0:a.value)||""),[x,w]=o.useState(((f=a==null?void 0:a.points)==null?void 0:f.toString())||"10"),N=bn.includes(c),h=n.trim()&&i&&x.trim()&&(!N||p.trim()),v=y=>{y.preventDefault(),h&&r({name:n.trim(),field:i,operator:c,value:N?p.trim():void 0,points:parseInt(x,10)||0})};return e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(vt,{title:a?"Edit rule":"New scoring rule",onBack:l,backLabel:"Close scoring rule editor",actions:e.jsxs(L,{variant:"primary",size:"compact",onClick:v,disabled:!h,children:[e.jsx(Se,{size:16}),e.jsx("span",{className:"max-sm:hidden",children:a?"Save changes":"Create rule"}),e.jsx("span",{className:"sm:hidden",children:a?"Save":"Create"})]})}),e.jsxs("form",{onSubmit:v,className:"mx-auto max-w-3xl space-y-5 p-4 pb-[calc(var(--mobile-tab-bar-clearance,0px)+2rem)] sm:p-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-base leading-6 font-medium text-[var(--color-text-secondary)] md:text-[length:var(--text-label-l)] md:leading-[var(--lh-label-l)]",children:["Rule name ",e.jsx("span",{className:"text-[var(--color-error-text)]","aria-hidden":"true",children:"*"})]}),e.jsx(J,{"aria-label":"Rule name","aria-required":"true",required:!0,value:n,onChange:y=>s(y.target.value),placeholder:"e.g. Has email address",className:"w-full pointer-coarse:h-11 pointer-coarse:text-base"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-base leading-6 font-medium text-[var(--color-text-secondary)] md:text-[length:var(--text-label-l)] md:leading-[var(--lh-label-l)]",children:"Contact field"}),e.jsxs(me,{value:i,onValueChange:d,children:[e.jsx(ue,{"aria-label":"Contact field",className:"h-9 w-full rounded-[var(--radius-md)] pointer-coarse:h-11 pointer-coarse:text-base",children:e.jsx(ve,{placeholder:"Select a contact field"})}),e.jsx(pe,{children:t.map(y=>e.jsx(te,{value:y.key,children:y.label},y.key))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-base leading-6 font-medium text-[var(--color-text-secondary)] md:text-[length:var(--text-label-l)] md:leading-[var(--lh-label-l)]",children:"Condition"}),e.jsxs(me,{value:c,onValueChange:y=>m(y),children:[e.jsx(ue,{"aria-label":"Condition",className:"h-9 w-full rounded-[var(--radius-md)] pointer-coarse:h-11 pointer-coarse:text-base",children:e.jsx(ve,{})}),e.jsx(pe,{children:Object.entries(os).map(([y,b])=>e.jsx(te,{value:y,children:b},y))})]})]}),N&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-base leading-6 font-medium text-[var(--color-text-secondary)] md:text-[length:var(--text-label-l)] md:leading-[var(--lh-label-l)]",children:"Value"}),e.jsx(J,{"aria-label":"Rule value",value:p,onChange:y=>u(y.target.value),placeholder:"e.g. customer, SaaS, VP",className:"w-full pointer-coarse:h-11 pointer-coarse:text-base"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-base leading-6 font-medium text-[var(--color-text-secondary)] md:text-[length:var(--text-label-l)] md:leading-[var(--lh-label-l)]",children:"Points"}),e.jsxs("div",{className:"flex flex-col items-start gap-1.5",children:[e.jsx(J,{type:"number","aria-label":"Points",value:x,onChange:y=>w(y.target.value),placeholder:"10",className:"w-24 pointer-coarse:h-11 pointer-coarse:text-base tabular-nums"}),e.jsx("span",{className:"text-[length:var(--text-body-m)] leading-[var(--lh-body-m)] text-[var(--color-text-secondary)] pointer-coarse:text-base pointer-coarse:leading-6",children:"Positive = adds to score, Negative = subtracts"})]})]}),e.jsxs("div",{className:"mt-6 p-4 rounded-[var(--radius-default)] bg-[var(--color-bg-secondary)] border border-[var(--color-bg-tertiary)]",children:[e.jsx("div",{className:"text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2",children:"Rule preview"}),e.jsxs("p",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-primary)]",children:["If ",e.jsx("span",{className:"font-medium",children:((z=t.find(y=>y.key===i))==null?void 0:z.label)||i})," ",e.jsx("span",{className:"text-[var(--color-text-secondary)]",children:os[c].toLowerCase()}),N&&p.trim()&&e.jsxs(e.Fragment,{children:[" ",e.jsxs("span",{className:"font-medium",children:['"',p.trim(),'"']})]})," → ",e.jsxs(de,{variant:parseInt(x)>0?"success":parseInt(x)<0?"error":"default",children:[parseInt(x)>0?`+${x}`:x," pts"]})]})]})]})]})}function gc(t){const a=(t==null?void 0:t.trim().split(/\s+/)[0])??"";return`${a?`Hi ${a},`:"Hi there,"}
66
67Please find our quote attached. Let me know if you have any questions.`}function yc(t,a){return a&&!t.some(r=>r.id===a.id)?[a,...t]:t}const Qt=t=>
67Math.round(t*100)/100;function fc(t){return t>0&&t<=1?Qt(t*100):t}function jc(t,a){const r=Qt(t.reduce((m,p)=>m+(Number(p.quantity)||0)*(Number(p.unit_price)||0),0)),l=Number(a.discountValue)||0;let n=0;a.discountType==="percent"&&l>0?n=Qt(Math.min(r,r*l/100)):a.discountType==="fixed"&&l>0&&(n=Qt(Math.min(l,r)));const s=Math.max(0,r-n),i=fc(Number(a.taxRate)||0),d=Qt(s*(i/100)),c=Qt(s+d);return{subtotal:r,discountAmount:n,taxAmount:d,total:c}}const is={draft:"default",sent:"accent",viewed:"accent",accepted:"success",rejected:"error",expired:"warning"},Et={draft:"Draft",sent:"Sent",viewed:"Viewed",accepted:"Accepted",rejected:"Rejected",expired:"Expired"};function Nc(){const{quotes:t,quotesLoading:a,loadQuotes:r,deleteQuote:l,activeQuote:n,selectQuote:s,clearActiveQuote:i}=G(),[d,c]=Uo(),m=d.get("deal_id"),[p,u]=o.useState(!!m),[x,w]=o.useState(m),[N,h]=o.useState(null),[v,j]=o.useState(null),[f,z]=o.useState("all");o.useEffect(()=>{r()},[r]);const y=o.useCallback(async()=>{v&&(await l(v),j(null))},[v,l]),b=o.useMemo(()=>f==="all"?t:t.filter(g=>g.status===f),[t,f]);return n&&!p?e.jsx(kc,{quote:n,onClose:i,onEdit:()=>{h(n),u(!0)},onCloned:g=>{h(g),u(!0)}}):p?e.jsx(Sc,{initial:N,defaultDealId:x,onClose:()=>{u(!1),h(null),w(null),d.has("deal_id")&&(d.delete("deal_id"),c(d,{replace:!0}))}}):e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden","data-testid":"crm-quotes-index",children:[e.jsx(Xe,{title:"Quotes",description:"Create, send, and track proposals and quotes.",actions:e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden w-40 sm:block",children:e.jsxs(me,{value:f,onValueChange:g=>z(g),children:[e.jsx(ue,{"aria-label":"Filter quotes by status",children:e.jsx(ve,{placeholder:"All statuses"})}),e.jsxs(pe,{children:[e.jsx(te,{value:"all",children:"All statuses"}),Object.keys(Et).map(g=>e.jsx(te,{value:g,children:Et[g]},g))]})]})}),e.jsxs(L,{variant:"primary",size:"default","aria-label":"Create quote",className:"max-sm:h-11 max-sm:w-11 max-sm:min-w-11 max-sm:rounded-full max-sm:px-0",onClick:()=>{h(null),u(!0)},children:[e.jsx(oe,{size:16}),e.jsx("span",{className:"ml-2 hidden sm:inline",children:"Create quote"})]})]})}),e.jsx("div",{className:"border-b border-[var(--color-bg-tertiary)] px-4 py-2 sm:hidden",children:e.jsxs(me,{value:f,onValueChange:g=>z(g),children:[e.jsx(ue,{"aria-label":"Filter quotes by status",className:"h-11 w-full",children:e.jsx(ve,{placeholder:"All statuses"})}),e.jsxs(pe,{children:[e.jsx(te,{value:"all",children:"All statuses"}),Object.keys(Et).map(g=>e.jsx(te,{value:g,children:Et[g]},g))]})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:a?e.jsx("div",{className:"p-6 space-y-2",children:Array.from({length:4}).map((g,E)=>e.jsx(Re,{},E))}):b.length===0?e.jsx(De,{icon:e.jsx(ot,{size:24,className:"text-[var(--color-accent)]"}),title:f==="all"?"No quotes yet":"No matching quotes",description:f==="all"?"Create your first quote to send a proposal to a contact, with line items, tax, discounts, and PDF export.":"Try a different status filter or create a new quote.",action:e.jsxs(L,{variant:"primary",onClick:()=>{h(null),u(!0)},children:[e.jsx(oe,{size:16}),e.jsx("span",{className:"ml-2",children:"Create quote"})]})}):e.jsx("div",{className:"divide-y divide-[var(--color-bg-tertiary)]",children:b.map(g=>e.jsx(wc,{quote:g,onSelect:()=>s(g.id),onDelete:()=>j(g.id)},g.id))})}),e.jsx(we,{open:!!v,onOpenChange:g=>!g&&j(null),title:"Delete quote",description:"This quote and all its line items will be permanently deleted.",confirmLabel:"Delete",variant:"destructive",onConfirm:y})]})}function wc({quote:t,onSelect:a,onDelete:r}){return e.jsxs("div",{"data-testid":"crm-quote-row",className:"grid grid-cols-[32px_minmax(0,1fr)_auto] items-start gap-x-3 gap-y-2 px-4 py-4 hover:bg-[var(--color-bg-secondary)] cursor-pointer transition-colors sm:flex sm:items-center sm:gap-4 sm:px-6",onClick:a,children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-[var(--color-accent-subtle)] flex items-center justify-center shrink-0",children:e.jsx(ot,{size:16,className:"text-[var(--color-accent)]"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"min-w-0",children:e.jsx("span",{className:"line-clamp-2 min-w-0 text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)] sm:truncate",children:t.title})}),e.jsxs("div",{className:"mt-1 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] sm:hidden",children:[e.jsx("span",{className:"font-semibold tabular-nums text-[var(--color-text-primary)]",children:Q(t.total,t.currency)}),e.jsx(de,{variant:is[t.status],children:Et[t.status]}),e.jsx("span",{className:"font-mono",children:t.quote_number}),t.created_at&&e.jsx("span",{children:Ce(t.created_at)}),e.jsxs("span",{children:[t.line_items.length," item",t.line_items.length!==1?"s":""]})]}),(t.contact||t.deal)&&e.jsxs("div",{className:"mt-1 space-y-0.5 text-[length:var(--text-body-s)] leading-snug text-[var(--color-text-secondary)] sm:hidden",children:[t.contact&&e.jsx("div",{className:"break-words",children:t.contact.name}),t.deal&&e.jsx("div",{className:"break-words",children:t.deal.title})]}),e.jsxs("div",{className:"mt-1 hidden min-w-0 items-center gap-2 text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] sm:flex",children:[e.jsx(de,{variant:is[t.status],children:Et[t.status]}),e.jsx("span",{className:"font-mono",children:t.quote_number}),t.contact&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"hidden text-[var(--color-text-quaternary)] sm:inline",children:"·"}),e.jsx("span",{className:"truncate",children:t.contact.name})]}),t.deal&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"hidden text-[var(--color-text-quaternary)] sm:inline",children:"·"}),e.jsx("span",{className:"truncate",children:t.deal.title})]}),t.created_at&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"hidden text-[var(--color-text-quaternary)] sm:inline",children:"·"}),e.jsx("span",{children:Ce(t.created_at)})]})]})]}),e.jsxs("div",{className:"hidden text-right tabular-nums sm:block",children:[e.jsx("div",{className:"text-[length:var(--text-body-m)] font-semibold text-[var(--color-text-primary)]",children:Q(t.total,t.currency)}),e.jsxs("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:[t.line_items.length," item",t.line_items.length!==1?"s":""]})]}),e.jsx(L,{variant:"ghost",size:"icon-sm",className:"icon-interactive col-start-3 row-span-2 row-start-1 border border-[var(--color-bg-tertiary)] sm:border-transparent","aria-label":"Delete quote",onClick:l=>{l.stopPropagation(),r()},children:e.jsx(he,{size:16})})]})}function kc({quote:t,onClose:a,onEdit:r,onCloned:l}){var g,E,A,U;const{sendQuote:n,updateQuote:s,deleteQuote:i,createQuote:d}=G(),[c,m]=o.useState(!1),[p,u]=o.useState(!1),[x,w]=o.useState(!1),N=t.status==="accepted"||t.status==="rejected",h=!!t.sent_at,v=o.useCallback(async()=>{const D=await d({title:t.title,deal_id:t.deal_id,contact_id:t.contact_id,company_id:t.company_id,status:"draft",tax_rate:t.tax_rate,discount_type:t.discount_type,discount_value:t.discount_value,currency:t.currency,notes:t.notes,terms:t.terms,valid_until:t.valid_until,owner_id:t.owner_id,line_items:t.line_items.map(O=>({name:O.name,description:O.description,quantity:O.quantity,unit_price:O.unit_price,sort_order:O.sort_order}))});D&&l(D)},[d,t,l]),j=o.useCallback(async()=>{await i(t.id)&&a()},[i,t.id,a]),f=o.useCallback(async()=>{const D=Wo(),O=await fetch(`/api/crm/quotes/${t.id}/pdf`,{headers:D?{Authorization:`Bearer ${D}`}:{}});if(!O.ok){console.error("Failed to fetch quote PDF:",O.status);return}const P=await O.blob();ii(P)},[t.id]),z=o.useCallback(async()=>
67{if(await s(t.id,{status:"accepted"})){const O=t.quote_number?`Quote ${t.quote_number}`:"Quote";ge.success(`${O} marked as accepted`)}},[s,t.id,t.quote_number]),y=o.useCallback(async()=>{if(await s(t.id,{status:"rejected"})){const O=t.quote_number?`Quote ${t.quote_number}`:"Quote";ge.success(`${O} marked as rejected`)}},[s,t.id,t.quote_number]),b=D=>Q(D,t.currency);return e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden","data-testid":"crm-quote-detail",children:[e.jsx(vt,{onBack:a,backLabel:"Back to quotes",mobileActionsBelow:!0,title:t.title,description:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono",children:t.quote_number}),e.jsx(de,{variant:is[t.status],children:Et[t.status]})]}),actions:e.jsxs(e.Fragment,{children:[e.jsxs(L,{variant:"secondary",size:"default",onClick:f,"aria-label":"Download PDF",children:[e.jsx(Ee,{size:16}),e.jsx("span",{className:"ml-2",children:"Download PDF"})]}),N?e.jsxs(L,{variant:"primary",size:"default",onClick:v,children:[e.jsx(Go,{size:16}),e.jsx("span",{className:"ml-2",children:"Clone"})]}):e.jsxs(e.Fragment,{children:[e.jsxs(L,{variant:"secondary",size:"default",onClick:r,"aria-label":"Edit quote",children:[e.jsx(We,{size:16}),e.jsx("span",{className:"ml-2 max-sm:hidden",children:"Edit"})]}),e.jsxs(L,{variant:"primary",size:"default","aria-label":h?"Resend":"Send",onClick:()=>{h?w(!0):m(!0)},children:[e.jsx(ht,{size:16}),e.jsx("span",{className:"ml-2 max-sm:hidden",children:h?"Resend":"Send"})]})]})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsxs("div",{className:"mx-auto max-w-4xl space-y-8 px-4 py-6 pb-[calc(var(--mobile-tab-bar-clearance,0px)+2rem)] sm:px-6 md:p-8",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-5 sm:grid-cols-2 sm:gap-6",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[length:var(--text-label-s)] font-medium uppercase tracking-wide text-[var(--color-text-tertiary)] mb-2",children:"From"}),e.jsx("div",{className:"text-[length:var(--text-body-m)] font-semibold text-[var(--color-text-primary)]",children:((g=t.owner)==null?void 0:g.display_name)??"—"}),e.jsx("div",{className:"break-all text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:t.owner?wo(t.owner):""})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[length:var(--text-label-s)] font-medium uppercase tracking-wide text-[var(--color-text-tertiary)] mb-2",children:"To"}),e.jsx("div",{className:"text-[length:var(--text-body-m)] font-semibold text-[var(--color-text-primary)]",children:((E=t.contact)==null?void 0:E.name)??((A=t.company)==null?void 0:A.name)??"—"}),e.jsx("div",{className:"break-all text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:((U=t.contact)==null?void 0:U.email)??""})]})]}),t.deal&&e.jsxs("div",{className:"flex flex-col gap-1 rounded-lg bg-[var(--color-bg-secondary)] px-4 py-3 sm:flex-row sm:items-center sm:gap-3",children:[e.jsx("div",{className:"text-[length:var(--text-label-s)] font-medium uppercase tracking-wide text-[var(--color-text-tertiary)]",children:"Linked deal"}),e.jsx("div",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-primary)]",children:t.deal.title})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[length:var(--text-label-s)] font-medium uppercase tracking-wide text-[var(--color-text-tertiary)] mb-3",children:"Line items"}),e.jsx("div",{className:"space-y-2 md:hidden",children:t.line_items.map(D=>e.jsxs("div",{className:"rounded-lg border border-[var(--color-bg-tertiary)] p-3",children:[e.jsx("div",{className:"font-medium text-[var(--color-text-primary)]",children:D.name}),D.description&&e.jsx("div",{className:"mt-0.5 text-[var(--color-text-secondary)]",children:D.description}),e.jsxs("dl",{className:"mt-3 grid grid-cols-3 gap-2 text-[length:var(--text-label-s)] tabular-nums",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--color-text-tertiary)]",children:"Qty"}),e.jsx("dd",{className:"mt-1 text-[var(--color-text-primary)]",children:D.quantity})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--color-text-tertiary)]",children:"Unit price"}),e.jsx("dd",{className:"mt-1 text-[var(--color-text-primary)]",children:b(D.unit_price)})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("dt",{className:"text-[var(--color-text-tertiary)]",children:"Amount"}),e.jsx("dd",{className:"mt-1 font-semibold text-[var(--color-text-primary)]",children:b(D.amount)})]})]})]},D.id))}),e.jsx("div",{className:"hidden overflow-hidden rounded-lg border border-[var(--color-bg-tertiary)] md:block",children:e.jsxs("table",{className:"w-full text-[length:var(--text-body-s)] tabular-nums",children:[e.jsx("thead",{className:"bg-[var(--color-bg-secondary)]",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-3 py-2 font-medium text-[var(--color-text-tertiary)]",children:"Item"}),e.jsx("th",{className:"text-right px-3 py-2 font-medium text-[var(--color-text-tertiary)] w-20",children:"Qty"}),e.jsxs("th",{className:"text-right px-3 py-2 font-medium text-[var(--color-text-tertiary)] w-28",children:[e.jsx("span",{className:"md:hidden",children:"Price"}),e.jsx("span",{className:"hidden md:inline",children:"Unit price"})]}),e.jsx("th",{className:"text-right px-3 py-2 font-medium text-[var(--color-text-tertiary)] w-28",children:"Amount"})]})}),e.jsx("tbody",{children:t.line_items.map(D=>e.jsxs("tr",{className:"border-t border-[var(--color-bg-tertiary)]",children:[e.jsxs("td",{className:"px-3 py-3",children:[e.jsx("div",{className:"font-medium text-[var(--color-text-primary)]",children:D.name}),D.description&&e.jsx("div",{className:"text-[var(--color-text-secondary)] mt-0.5",children:D.description})]}),e.jsx("td",{className:"px-3 py-3 text-right",children:D.quantity}),e.jsx("td",{className:"px-3 py-3 text-right",children:b(D.unit_price)}),e.jsx("td",{className:"px-3 py-3 text-right font-medium",children:b(D.amount)})]},D.id))})]})})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs("div",{className:"w-full space-y-2 tabular-nums sm:w-80",children:[e.jsx(Yr,{label:"Subtotal",value:b(t.subtotal),muted:!0}
67),t.discount_amount>0&&e.jsx(Yr,{label:t.discount_type==="percent"?`Discount (${t.discount_value}%)`:"Discount",value:`-${b(t.discount_amount)}`,muted:!0}),t.tax_amount>0&&e.jsx(Yr,{label:`Tax (${t.tax_rate}%)`,value:b(t.tax_amount),muted:!0}),e.jsxs("div",{className:"pt-2 border-t-2 border-[var(--color-text-tertiary)] flex justify-between text-[length:var(--text-title-s)] font-semibold",children:[e.jsx("span",{children:"Total"}),e.jsx("span",{children:b(t.total)})]}),t.recurring_by_interval.map(D=>e.jsxs("div",{"data-testid":"quote-recurring-row",className:"flex justify-between text-[length:var(--text-body-m)] font-medium text-[var(--color-accent)]",children:[e.jsxs("span",{children:["Recurring",ur(D.billing_interval)]}),e.jsxs("span",{children:[b(D.amount),ur(D.billing_interval)]})]},D.billing_interval)),(()=>{const D=new Set(t.line_items.filter(P=>P.billing_interval&&P.billing_interval!=="one_time"&&P.contract_term_months!=null).map(P=>P.contract_term_months));if(D.size!==1)return null;const O=[...D][0];return e.jsxs("div",{"data-testid":"quote-contract-term",className:"flex justify-between text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:[e.jsx("span",{children:"Contract term"}),e.jsxs("span",{children:[O,"-month term"]})]})})()]})}),t.valid_until&&e.jsxs("div",{className:"text-center text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:["Valid until ",wt(t.valid_until)]}),t.notes&&e.jsxs("div",{className:"bg-[var(--color-bg-secondary)] rounded-lg p-4",children:[e.jsx("div",{className:"text-[length:var(--text-label-s)] font-medium uppercase tracking-wide text-[var(--color-text-tertiary)] mb-2",children:"Notes"}),e.jsx("div",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-primary)] whitespace-pre-wrap",children:t.notes})]}),t.terms&&e.jsxs("div",{className:"bg-[var(--color-bg-secondary)] rounded-lg p-4",children:[e.jsx("div",{className:"text-[length:var(--text-label-s)] font-medium uppercase tracking-wide text-[var(--color-text-tertiary)] mb-2",children:"Terms"}),e.jsx("div",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-primary)] whitespace-pre-wrap",children:t.terms})]}),(t.status==="sent"||t.status==="viewed")&&e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(L,{variant:"secondary",onClick:y,children:"Mark rejected"}),e.jsxs(L,{variant:"primary",onClick:z,children:[e.jsx(Se,{size:16}),e.jsx("span",{className:"ml-2",children:"Mark accepted"})]})]}),e.jsxs("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] space-y-1 pt-4 border-t border-[var(--color-bg-tertiary)]",children:[t.created_at&&e.jsxs("div",{children:["Created ",Ce(t.created_at)]}),t.sent_at&&e.jsxs("div",{children:["Sent ",Ce(t.sent_at)]}),t.accepted_at&&e.jsxs("div",{children:["Accepted ",Ce(t.accepted_at)]}),t.rejected_at&&e.jsxs("div",{children:["Rejected ",Ce(t.rejected_at)]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(L,{variant:"ghost",size:"default",onClick:()=>u(!0),className:"text-[var(--color-error-text)] hover:text-[var(--color-error-text)]",children:[e.jsx(he,{size:16}),e.jsx("span",{className:"ml-2",children:"Delete quote"})]})})]})}),e.jsx(Cc,{open:c,onOpenChange:m,quote:t,onSend:async D=>{const O=await n(t.id,D);return O&&m(!1),O}}),e.jsx(we,{open:p,onOpenChange:u,title:"Delete quote",description:"This quote and all its line items will be permanently deleted.",confirmLabel:"Delete",variant:"destructive",onConfirm:j}),e.jsx(we,{open:x,onOpenChange:w,title:"Resend quote",description:t.sent_at?`Quote ${t.quote_number} was already sent on ${Ce(t.sent_at)}${t.sent_to_email?` to ${t.sent_to_email}`:""}. Send again?`:`Send quote ${t.quote_number} again?`,confirmLabel:"Resend",onConfirm:()=>{w(!1),m(!0)}})]})}function Yr({label:t,value:a,muted:r}){return e.jsxs("div",{className:`flex justify-between text-[length:var(--text-body-m)] ${r?"text-[var(--color-text-secondary)]":"text-[var(--color-text-primary)]"}`,children:[e.jsx("span",{children:t}),e.jsx("span",{children:a})]})}function Cc({open:t,onOpenChange:a,quote:r,onSend:l}
67){const[n,s]=o.useState(""),[i,d]=o.useState(""),[c,m]=o.useState(""),[p,u]=o.useState(!1);return o.useEffect(()=>{var x,w;t&&(s(((x=r.contact)==null?void 0:x.email)??""),d(`Quote ${r.quote_number}: ${r.title}`),m(gc((w=r.contact)==null?void 0:w.name)))},[t,r]),e.jsx(Ke,{open:t,onOpenChange:a,children:e.jsxs(Qe,{className:"max-w-lg",children:[e.jsxs(He,{children:[e.jsx(Ye,{children:"Send quote"}),e.jsx(vr,{children:"The full quote summary (line items and total) is appended to the message body automatically."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[length:var(--text-label-s)] font-medium text-[var(--color-text-primary)] mb-2",children:"To"}),e.jsx(J,{"aria-label":"Quote title",type:"email",value:n,onChange:x=>s(x.target.value),placeholder:"[email protected]"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[length:var(--text-label-s)] font-medium text-[var(--color-text-primary)] mb-2",children:"Subject"}),e.jsx(J,{value:i,onChange:x=>d(x.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[length:var(--text-label-s)] font-medium text-[var(--color-text-primary)] mb-2",children:"Message"}),e.jsx(br,{value:c,onChange:x=>m(x.target.value),rows:6})]})]}),e.jsxs(nt,{children:[e.jsx(L,{variant:"secondary",size:"default",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(L,{variant:"primary",size:"default",disabled:!n.trim()||p,onClick:async()=>
67{u(!0),await l({recipient_email:n.trim(),subject:i.trim()||void 0,message:c.trim()||void 0}),u(!1)},children:[e.jsx(ht,{size:16}),e.jsx("span",{className:"ml-2",children:p?"Sending…":"Send"})]})]})]})})}function Sc({initial:t,defaultDealId:a,onClose:r}){const{deals:l,contacts:n,products:s,loadDeals:i,loadContacts:d,loadProducts:c,createQuote:m,updateQuote:p}=G(),u=Array.isArray(s)?s:[],[x,w]=o.useState((t==null?void 0:t.title)??""),[N,h]=o.useState((t==null?void 0:t.deal_id)??a??""),[v,j]=o.useState((t==null?void 0:t.contact_id)??""),[f,z]=o.useState(t?String(t.tax_rate):"0"),[y,b]=o.useState((t==null?void 0:t.discount_type)??"none"),[g,E]=o.useState(t?String(t.discount_value):"0"),[A,U]=o.useState((t==null?void 0:t.currency)??"USD"),[D,O]=o.useState((t==null?void 0:t.valid_until)??""),[P,H]=o.useState((t==null?void 0:t.notes)??""),[ae,I]=o.useState((t==null?void 0:t.terms)??""),[k,C]=o.useState((t==null?void 0:t.line_items.map(q=>({name:q.name,description:q.description,quantity:q.quantity,unit_price:q.unit_price,sort_order:q.sort_order})))??[{name:"",quantity:1,unit_price:0}]),[_,Z]=o.useState(!1),[B,V]=o.useState(null),[F,le]=o.useState(null);o.useEffect(()=>{i(),d(),c({activeOnly:!0})},[i,d,c]),o.useEffect(()=>{if(!N||l.some(ee=>ee.id===N)){le(null);return}let q=!1;return(async()=>{try{const ke=(await Ve.crm.deals.get({params:{id:N},query:{}})).deal;q||le(ke)}catch(ee){console.error("[crm] Failed to load linked deal for quote:",ee)}})(),()=>{q=!0}},[N,l]);const X=o.useMemo(()=>yc(l,F),[l,F]),{subtotal:T,discountAmount:W,taxAmount:R,total:Y}=o.useMemo(()=>jc(k,{discountType:y,discountValue:g,taxRate:f}),[k,y,g,f]),re=q=>Q(q,A),fe=!!(x.trim()&&k.length>0&&k.every(q=>q.name.trim()&&Number.isFinite(q.quantity)&&q.quantity>0)&&!_),Te=()=>{C(q=>[...q,{name:"",quantity:1,unit_price:0,sort_order:q.length}])},St=q=>{const ee=u.find(ke=>ke.id===q);ee&&(k.length===1&&!k[0].name.trim()&&k[0].unit_price===0?C([{name:ee.name,description:ee.description||null,quantity:1,unit_price:ee.unit_price,sort_order:0}]):C(ke=>[...ke,{name:ee.name,description:ee.description||null,quantity:1,unit_price:ee.unit_price,sort_order:ke.length}]))},Ea=q=>{C(ee=>ee.filter((ke,ce)=>ce!==q))},tt=(q,ee)=>{C(ke=>ke.map((ce,Rt)=>Rt===q?{...ce,...ee}:ce))},na=async q=>{if(V(null),!x.trim()){V("Title is required");return}if(k.length===0){V("Add at least one line item");return}for(const ce of k){if(!ce.name.trim()){V("Every line item needs a name");return}if(!Number.isFinite(ce.quantity)||ce.quantity<=0){V("Every line item needs a positive quantity");return}}Z(!0);const ee={title:x.trim(),deal_id:N||null,contact_id:v||null,tax_rate:Number(f)||0,discount_type:y==="none"?null:y,discount_value:Number(g)||0,currency:A,valid_until:D||null,notes:P||null,terms:ae||null,line_items:k.map((ce,Rt)=>({name:ce.name.trim(),description:ce.description||null,quantity:Number(ce.quantity)||0,unit_price:Number(ce.unit_price)||0,sort_order:Rt}))};let ke;t?ke=await p(t.id,ee):ke=!!await m(ee),Z(!1),ke&&r()};return e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsx(vt,{onBack:r,title:t?"Edit quote":"Create quote",description:"Add line items, pricing, and terms.",actions:e.jsx(L,{variant:"primary",size:"default",onClick:()=>na(),disabled:!fe,children:_?"Saving…":t?"Save changes":"Create quote"})}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-4 pb-[calc(var(--mobile-tab-bar-clearance,0px)+2rem)] sm:p-6",children:[B&&e.jsx("div",{className:"bg-[var(--color-error-subtle)] text-[var(--color-error-text)] px-4 py-2 rounded-lg text-[length:var(--text-body-s)]",children:B}),e.jsx(Pe,{label:"Title",required:!0,children:e.jsx(J,{required:!0,"aria-required":"true",value:x,onChange:q=>w(q.target.value),placeholder:"Acme Corp — Enterprise Plan",className:"placeholder:text-[var(--color-text-tertiary)]"})}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsx(Pe,{label:"Linked deal (optional)",children:e.jsxs(me,{value:N||"__none__",onValueChange:q=>h(q==="__none__"?"":q),children:[e.jsx(ue,{"aria-label":"Linked deal",children:e.jsx(ve,{placeholder:"None"})}),e.jsxs(pe,{children:[e.jsx(te,{value:"__none__",children:"None"}),X.map(q=>e.jsx(te,{value:q.id,children:q.title}
67,q.id))]})]})}),e.jsx(Pe,{label:"Recipient contact (optional)",children:e.jsxs(me,{value:v||"__none__",onValueChange:q=>j(q==="__none__"?"":q),children:[e.jsx(ue,{"aria-label":"Recipient contact",children:e.jsx(ve,{placeholder:"None"})}),e.jsxs(pe,{children:[e.jsx(te,{value:"__none__",children:"None"}),n.filter(q=>q.type==="person").map(q=>e.jsxs(te,{value:q.id,children:[q.name,q.email?` · ${q.email}`:""]},q.id))]})]})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-secondary)]",children:["Line items",e.jsx("span",{className:"ml-0.5 text-[var(--color-error-text)]","aria-hidden":"true",children:"*"})]}),e.jsxs(L,{variant:"ghost",size:"compact",onClick:Te,children:[e.jsx(oe,{size:14}),e.jsx("span",{className:"ml-1",children:"Add line item"})]})]}),e.jsx("div",{className:"space-y-3 md:hidden",children:k.map((q,ee)=>{const ke=(Number(q.quantity)||0)*(Number(q.unit_price)||0);return e.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-secondary)] p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"text-[length:var(--text-label-m)] font-semibold text-[var(--color-text-primary)]",children:["Item ",ee+1]}),e.jsx(L,{variant:"ghost",size:"icon-sm","aria-label":`Remove line item ${ee+1}`,onClick:()=>Ea(ee),disabled:k.length===1,children:e.jsx(he,{size:14})})]}),e.jsx(Pe,{label:"Item name",required:!0,children:e.jsx(J,{"aria-label":`Line item ${ee+1} name`,value:q.name,onChange:ce=>tt(ee,{name:ce.target.value}),placeholder:"Item name",className:"placeholder:text-[var(--color-text-tertiary)]"})}),e.jsx(J,{"aria-label":`Line item ${ee+1} description`,value:q.description??"",onChange:ce=>tt(ee,{description:ce.target.value}),placeholder:"Description (optional)",className:"placeholder:text-[var(--color-text-tertiary)]"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Pe,{label:"Quantity",children:e.jsx(J,{type:"number","aria-label":`Line item ${ee+1} quantity`,min:"0",step:"1",value:q.quantity,onChange:ce=>tt(ee,{quantity:Number(ce.target.value)})})}),e.jsx(Pe,{label:"Unit price",children:e.jsx(J,{type:"number","aria-label":`Line item ${ee+1} unit price`,min:"0",step:"0.01",value:q.unit_price,onChange:ce=>tt(ee,{unit_price:Number(ce.target.value)})})})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-[var(--color-bg-tertiary)] pt-3 text-[length:var(--text-body-s)]",children:[e.jsx("span",{className:"text-[var(--color-text-secondary)]",children:"Amount"}),e.jsx("span",{className:"font-semibold tabular-nums text-[var(--color-text-primary)]",children:re(ke)})]})]},ee)})}),e.jsxs("div",{className:"hidden overflow-x-auto rounded-lg border border-[var(--color-bg-tertiary)] md:block",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_80px_120px_120px_40px] gap-2 px-3 py-2 bg-[var(--color-bg-secondary)] text-[length:var(--text-label-l)] font-medium text-[var(--color-text-tertiary)] min-w-[600px]",children:[e.jsxs("div",{children:["Item name",e.jsx("span",{className:"ml-0.5 text-[var(--color-error-text)]","aria-hidden":"true",children:"*"})]}),e.jsx("div",{className:"text-right",children:"Qty"}),e.jsxs("div",{className:"text-right",children:[e.jsx("span",{className:"md:hidden",children:"Price"}),e.jsx("span",{className:"hidden md:inline",children:"Unit price"})]}),e.jsx("div",{className:"text-right",children:"Amount"}),e.jsx("div",{})]}),k.map((q,ee)=>{const ke=(Number(q.quantity)||0)*(Number(q.unit_price)||0);return e.jsxs("div",{className:"grid grid-cols-[1fr_80px_120px_120px_40px] gap-2 px-3 py-2 border-t border-[var(--color-bg-tertiary)] items-center min-w-[600px]",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{"aria-label":`Line item ${ee+1} name`,value:q.name,onChange:ce=>tt(ee,{name:ce.target.value}),placeholder:"Item name",className:"placeholder:text-[var(--color-text-tertiary)]"}),e.jsx(J,{"aria-label":`Line item ${ee+1} description`,value:q.description??"",onChange:ce=>tt(ee,{description:ce.target.value}),placeholder:"Description (optional)",className:"placeholder:text-[var(--color-text-tertiary)]"})]}),e.jsx(J,{type:"number","aria-label":`Line item ${ee+1} quantity`,min:"0",step:"1",value:q.quantity,onChange:ce=>tt(ee,{quantity:Number(ce.target.value)}),className:"text-right tabular-nums"}),e.jsx(J,{type:"number","aria-label":`Line item ${ee+1} unit price`,min:"0",step:"0.01",value:q.unit_price,onChange:ce=>tt(ee,{unit_price:Number(ce.target.value)}),className:"text-right tabular-nums"}),e.jsx("div",{className:"text-right text-[length:var(--text-body-m)] font-medium tabular-nums self-center",children:re(ke)}),e.jsx(L,{variant:"ghost",size:"icon-sm",className:"icon-interactive","aria-label":"Remove line item",onClick:()=>Ea(ee),disabled:k.length===1,children:e.jsx(he,{size:14})})]},ee)})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2 mt-3",children:e.jsxs(me,{value:"",onValueChange:q=>{q&&St(q)},children:[e.jsx(ue,{className:"w-56","aria-label":"Add product from catalog",children:e.jsx(ve,{placeholder:"Add from catalog…"})}),e.jsx(pe,{children:u.length===0?e.jsx(te,{value:"__none",disabled:!0,children:"No active products"}):u.map(q=>e.jsxs(te,{value:q.id,children:[q.name,q.sku?` · ${q.sku}`:""," · ",Q(q.unit_price,q.currency)]},q.id))})]})})]}),e.jsxs("details",{className:"group rounded-[var(--radius-lg)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)]",children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center gap-2 px-4 py-3 text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)] marker:hidden",children:[e.jsx("span",{children:"Pricing and terms"}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-[length:var(--text-body-m)] font-normal text-[var(--color-text-secondary)]",children:"Tax, discounts, validity, notes"}),e.jsx(ye,{size:16,className:"shrink-0 text-[var(--color-text-tertiary)] transition-transform group-open:rotate-180"})]}),e.jsxs("div",{className:"space-y-4 border-t border-[var(--color-bg-tertiary)] p-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-3",children:[e.jsx(Pe,{label:"Tax rate (%)",children:e.jsx(J,{type:"number","aria-label":"Tax rate",min:"0",max:"100",step:"0.01",value:f,onChange:q=>z(q.target.value)})}),e.jsx(Pe,{label:"Discount type",children:e.jsxs(me,{value:y,onValueChange:q=>b(q),children:[e.jsx(ue,{"aria-label":"Discount type",children:e.jsx(ve,{})}),e.jsxs(pe,{children:[e.jsx(te,{value:"none",children:"None"}),e.jsx(te,{value:"percent",children:"Percent (%)"}),e.jsx(te,{value:"fixed",children:"Fixed amount"})]})]})}),e.jsx(Pe,{label:"Discount value",children:e.jsx(J,{type:"number","aria-label":"Discount value",min:"0",step:"0.01",value:g,onChange:q=>E(q.target.value),disabled:y==="none"})})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsx(Pe,{label:"Currency",children:e.jsx(J,{"aria-label":"Currency",value:A,onChange:q=>U(q.target.value.toUpperCase()),maxLength:3})}),e.jsx(Pe,{label:"Valid until (optional)",children:e.jsx(J,{type:"date","aria-label":"Valid until",value:D,onChange:q=>O(q.target.value)})})]}),e.jsx(Pe,{label:"Notes (optional)",children:e.jsx(rs,{value:P,onChange:q=>H(q),rows:3,placeholder:"Anything the recipient should know about this quote",className:ts({className:"placeholder:text-[var(--color-text-tertiary)]"})})}),e.jsx(Pe,{label:"Terms (optional)",children:e.jsx(rs,{value:ae,onChange:q=>I(q),rows:3,placeholder:"Net 30, subject to signed MSA, etc.",className:ts({className:"placeholder:text-[var(--color-text-tertiary)]"})})})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs("div",{className:"w-80 space-y-2 tabular-nums bg-[var(--color-bg-secondary)] rounded-lg p-4",children:[e.jsxs("div",{className:"flex justify-between text-[length:var(--text-body-m)] text-[var(--color-text-secondary)]",children:[e.jsx("span",{children:"Subtotal"}),e.jsx("span",{children:re(T)})]}),W>0&&e.jsxs("div",{className:"flex justify-between text-[length:var(--text-body-m)] text-[var(--color-text-secondary)]",children:[e.jsx("span",{children:"Discount"}),e.jsxs("span",{children:["-",re(W)]})]}),R>0&&e.jsxs("div",{className:"flex justify-between text-[length:var(--text-body-m)] text-[var(--color-text-secondary)]",children:[e.jsx("span",{children:"Tax"}),e.jsx("span",{children:re(R)})]}),e.jsxs("div",{className:"pt-2 border-t-2 border-[var(--color-text-tertiary)] flex justify-between text-[length:var(--text-title-s)] font-semibold text-[var(--color-text-primary)]",children:[e.jsx("span",{children:"Total"}),e.jsx("span",{children:re(Y)})]})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(L,{variant:"secondary",size:"default",onClick:r,children:"Cancel"}),e.jsx(L,{variant:"primary",size:"default",onClick:()=>na(),disabled:!fe,children:_?"Saving…":t?"Save changes":"Create quote"})]})]})})]})}function Pe({label:t,children:a,required:r=!1}){return e.jsxs("div",{children:[e.jsxs("label",{className:"block text-base leading-6 font-medium text-[var(--color-text-primary)] mb-2 md:text-[length:var(--text-label-l)] md:leading-[var(--lh-label-l)]",children:[t,r&&e.jsx("span",{className:"ml-0.5 text-[var(--color-error-text)]","aria-hidden":"true",children:"*"})]}),a]})}function _c(){const{products:t,productsLoading:a,loadProducts:r,deleteProduct:l}
67=G(),[n,s]=o.useState(!1),[i,d]=o.useState(null),[c,m]=o.useState(null),[p,u]=o.useState(""),[x,w]=o.useState(!1);o.useEffect(()=>{r()},[r]);const N=o.useMemo(()=>{const v=p.trim().toLowerCase();return t.filter(j=>{var f,z;return!x&&!j.is_active?!1:v?j.name.toLowerCase().includes(v)||(((f=j.sku)==null?void 0:f.toLowerCase().includes(v))??!1)||(((z=j.description)==null?void 0:z.toLowerCase().includes(v))??!1):!0})},[t,p,x]),h=async()=>{c&&(await l(c),m(null))};return n||i?e.jsx(zc,{editing:i,onDone:()=>{s(!1),d(null)}}):e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(Xe,{title:"Products",description:"Catalog of products and services you sell. Add them to deals as line items.",actions:e.jsxs(L,{variant:"primary",size:"compact",onClick:()=>s(!0),children:[e.jsx(oe,{size:16}),"Add product"]})}),e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-[var(--color-bg-tertiary)] max-md:flex-col max-md:items-stretch",children:[e.jsxs("div",{className:"relative flex-1 max-w-md max-md:max-w-none",children:[e.jsx(Na,{size:16,className:"absolute left-3 top-1/2 -translate-y-1/2 text-[var(--color-text-tertiary)] pointer-events-none"}),e.jsx(J,{"aria-label":"Search products",value:p,onChange:v=>u(v.target.value),placeholder:"Search products by name or SKU…",className:"pl-9"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] cursor-pointer pointer-coarse:min-h-11",children:[e.jsx(Ae,{checked:x,onCheckedChange:v=>w(v===!0),"aria-label":"Show inactive products"}),"Show inactive"]})]}),e.jsxs("div",{className:"hidden md:grid grid-cols-[minmax(0,1fr)_140px_72px] items-center gap-4 border-b border-[var(--color-bg-tertiary)] bg-[var(--color-bg-secondary)] py-2 pl-16 pr-4 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)]",children:[e.jsx("span",{children:"Product"}),e.jsx("span",{className:"text-right",children:"Unit price"}),e.jsx("span",{className:"sr-only",children:"Actions"})]}),e.jsx("div",{className:"divide-y divide-[var(--color-bg-tertiary)]",children:a?Array.from({length:4}).map((v,j)=>e.jsx(Re,{},j)):N.length===0?e.jsx(De,{icon:e.jsx(Ct,{size:24,className:"text-[var(--color-accent)]"}),title:t.length>0?"No products match your filter":"No products yet",description:t.length>0?"Try clearing the search or toggling inactive products.":"Add your products and services so your team can attach them to deals with a click.",action:t.length===0?e.jsxs(L,{variant:"primary",size:"default",className:"mt-4",onClick:()=>s(!0),children:[e.jsx(oe,{size:16}),e.jsx("span",{className:"ml-2",children:"Add product"})]}):void 0}):N.map(v=>e.jsx(Dc,{product:v,onEdit:()=>d(v),onDelete:()=>m(v.id)},v.id))}),t.length>0&&e.jsx("div",{className:"p-4 bg-[var(--color-bg-secondary)] border-t border-[var(--color-bg-tertiary)]",children:e.jsxs("div",{className:"flex items-center gap-4 text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-[var(--color-text-primary)]",children:t.length})," total"]}),e.jsxs("span",{children:[e.jsx("strong",{className:"text-[var(--color-text-primary)]",children:t.filter(v=>v.is_active).length})," active"]})]})}),e.jsx(we,{open:!!c,title:"Delete product",description:"Existing deal line items referencing this product will keep their name and price but lose the catalog link.",confirmLabel:"Delete",onConfirm:h,onOpenChange:v=>{v||m(null)},variant:"destructive"})]})}function Dc({product:t,onEdit:a,onDelete:r}){return e.jsxs("div",{className:"flex items-center gap-4 px-4 py-3 hover:bg-[var(--color-bg-secondary)] transition-colors group max-md:grid max-md:grid-cols-[36px_minmax(0,1fr)_auto] max-md:gap-x-3 max-md:gap-y-1",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-[var(--color-accent-subtle)] flex items-center justify-center shrink-0",children:e.jsx(Ct,{size:18,className:"text-[var(--color-accent)]"})}),e.jsxs("button",{type:"button",onClick:a,className:"flex-1 min-w-0 text-left cursor-pointer",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx("span",{className:`text-[length:var(--text-body-m)] font-medium truncate ${t.is_active?"text-[var(--color-text-primary)]":"text-[var(--color-text-quaternary)]"}`,children:t.name}),!t.is_active&&e.jsx(de,{variant:"default",children:"Inactive"}),t.sku&&e.jsxs(de,{variant:"default",children:["SKU: ",t.sku]})]}),t.description&&e.jsx("div",{className:"mt-0.5 line-clamp-2 text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] md:line-clamp-1",children:t.description})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsx("div",{className:"text-[length:var(--text-body-m)] font-semibold text-[var(--color-text-primary)] tabular-nums",children:Q(t.unit_price,t.currency)}),e.jsx("div",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:"per unit"})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 pointer-coarse:opacity-100 transition-opacity shrink-0 max-md:col-start-3",onClick:l=>l.stopPropagation(),children:[e.jsx(L,{variant:"ghost",size:"icon-sm",onClick:a,"aria-label":"Edit product",className:"max-md:hidden",children:e.jsx(We,{size:14})}),e.jsx(L,{variant:"ghost",size:"icon-sm",onClick:r,"aria-label":"Delete product",className:"border border-[var(--color-bg-tertiary)] md:border-transparent",children:e.jsx(he,{size:14})})]})]})}function zc({editing:t,onDone:a}){const{createProduct:r,updateProduct:l}
67=G(),[n,s]=o.useState((t==null?void 0:t.name)??""),[i,d]=o.useState((t==null?void 0:t.sku)??""),[c,m]=o.useState((t==null?void 0:t.description)??""),[p,u]=o.useState(t?String(t.unit_price):"0"),[x,w]=o.useState((t==null?void 0:t.currency)??"USD"),[N,h]=o.useState((t==null?void 0:t.is_active)??!0),[v,j]=o.useState(!1),[f,z]=o.useState(null),y=n.trim().length>0&&!v,b=async()=>{z(null),j(!0);const g={name:n.trim(),sku:i.trim()||null,description:c.trim()||null,unit_price:Number(p)||0,currency:x,is_active:N};try{t?await l(t.id,g)?a():z("Unable to update product."):await r(g)?a():z("Unable to create product.")}finally{j(!1)}};return e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(vt,{title:t?"Edit product":"New product",onBack:a,actions:e.jsxs(e.Fragment,{children:[e.jsx(L,{variant:"secondary",size:"compact",onClick:a,className:"max-sm:hidden",children:"Cancel"}),e.jsx(L,{variant:"primary",size:"compact",onClick:b,disabled:!y,children:v?"Saving…":t?"Save":"Create"})]})}),e.jsxs("div",{className:"mx-auto max-w-4xl space-y-5 p-4 pb-[calc(var(--mobile-tab-bar-clearance,0px)+2rem)] sm:p-6",children:[f&&e.jsx("div",{className:"p-3 rounded-md bg-[var(--color-error-subtle)] text-[var(--color-error-text)] text-[length:var(--text-body-s)]",children:f}),e.jsx(Za,{label:"Name",required:!0,children:e.jsx(J,{value:n,onChange:g=>s(g.target.value),placeholder:"e.g. Enterprise Plan",className:"placeholder:text-[var(--color-text-tertiary)]",autoFocus:!0})}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsx(Za,{label:"SKU",hint:"Optional unique code",children:e.jsx(J,{value:i,onChange:g=>d(g.target.value),placeholder:"e.g. ENT-001",className:"placeholder:text-[var(--color-text-tertiary)]"})}),e.jsx(Za,{label:"Unit price",required:!0,children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(J,{type:"number","aria-label":"Unit price",min:"0",step:"0.01",value:p,onChange:g=>u(g.target.value),className:"flex-1 tabular-nums"}),e.jsx(J,{"aria-label":"Currency",value:x,onChange:g=>w(g.target.value.toUpperCase()),maxLength:3,className:"w-20 text-center uppercase"})]})})]}),e.jsx(Za,{label:"Description",hint:"Shown in line item details",children:e.jsx(br,{value:c,onChange:g=>m(g.target.value),rows:3,placeholder:"Describe what's included...",className:"placeholder:text-[var(--color-text-tertiary)]"})}),e.jsxs("label",{className:"flex cursor-pointer items-start gap-3 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] p-3",children:[e.jsx(Ae,{checked:N,onCheckedChange:g=>h(g===!0),"aria-label":"Active in catalog",className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-primary)]",children:"Active in catalog"}),e.jsx("div",{className:"max-w-[72ch] text-[length:var(--text-label-s)] leading-[var(--lh-label-s)] text-[var(--color-text-tertiary)]",children:"Inactive products are hidden from the line item picker but preserved on existing deals."})]})]})]})]})}function Za({label:t,required:a,hint:r,children:l}){return e.jsxs("div",{children:[e.jsxs("label",{className:"block text-base leading-6 font-medium text-[var(--color-text-primary)] mb-2 md:text-[length:var(--text-label-l)] md:leading-[var(--lh-label-l)]",children:[t,a&&e.jsx("span",{className:"text-[var(--color-error-text)] ml-1",children:"*"})]}),l,r&&e.jsx("div",{className:"mt-1 text-[length:var(--text-label-s)] leading-[var(--lh-label-s)] text-[var(--color-text-secondary)] pointer-coarse:text-base pointer-coarse:leading-6",children:r})]})}function $c(){const{pipelines:t,loadPipelines:a}=G(),[r,l]=o.useState(!0),[n,s]=o.useState(!1),[i,d]=o.useState(null),[c,m]=o.useState(null);o.useEffect(()=>{a().finally(()=>l(!1))},[a]);const p=async()=>{if(!c)return;const{deletePipeline:u}=G.getState();await u(c),m(null)};return n||i?e.jsx(Ec,{editing:i,onDone:()=>{s(!1),d(null)}}):e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(Xe,{title:"Pipelines",description:"Manage your deal pipelines and their stages. Each stage c
67arries a win probability.",actions:e.jsxs(L,{variant:"primary",size:"compact","aria-label":"New pipeline",onClick:()=>s(!0),children:[e.jsx(oe,{size:16}),"Create pipeline"]})}),e.jsx("div",{className:"space-y-3 p-4 pb-[calc(var(--mobile-tab-bar-clearance,0px)+1rem)] md:p-6",children:r?Array.from({length:3}).map((u,x)=>e.jsx(Re,{},x)):t.length===0?e.jsx(De,{icon:e.jsx(Nt,{size:24,className:"text-[var(--color-accent)]"}),title:"No pipelines yet",description:"Create a pipeline to track deals through their stages from lead to close.",action:e.jsxs(L,{variant:"primary",size:"default",className:"mt-4",onClick:()=>s(!0),children:[e.jsx(oe,{size:16}),e.jsx("span",{className:"ml-2",children:"New pipeline"})]})}):t.map(u=>e.jsx(Ac,{pipeline:u,onEdit:()=>d(u),onDelete:()=>m(u.id)},u.id))}),e.jsx(we,{open:!!c,title:"Delete pipeline",description:"All deals in this pipeline will need to be reassigned. This cannot be undone.",confirmLabel:"Delete",onConfirm:p,onOpenChange:u=>{u||m(null)},variant:"destructive"})]})}function Ac({pipeline:t,onEdit:a,onDelete:r}){return e.jsxs("div",{className:"group flex items-start gap-4 roun
67ded-[var(--radius-lg)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] p-4 transition-colors hover:border-[var(--color-text-quaternary)] hover:bg-[var(--color-bg-secondary)]",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-[var(--color-accent-subtle)] flex items-center justify-center shrink-0",children:e.jsx(Nt,{size:18,className:"text-[var(--color-accent)]"})}),e.jsxs("button",{type:"button",onClick:a,className:"min-w-0 flex-1 text-left cursor-pointer",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[t.visibility==="private"&&e.jsx(Jl,{size:12,className:"shrink-0 text-[var(--color-text-tertiary)]","aria-label":"Private pipeline"}),e.jsx("span",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)] truncate",children:t.name}),t.is_default&&e.jsx(de,{variant:"default",children:"Default"})]}),e.jsxs("div",{className:"mt-1 text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:[t.stages.length," stage",t.stages.length!==1?"s":""]}),t.stages.length>0&&e.jsx("div",{className:"mt-3 flex flex-col items-start sm:flex-row sm:items-center sm:overflow-x-auto","aria-label":"Pipeline stages",children:[...t.stages].sort((l,n)=>l.sort_order-n.sort_order).map((l,n)=>e.jsxs(Ie.Fragment,{children:[n>0&&e.jsx("span",{className:"ml-3 h-3 w-px bg-[var(--color-text-quaternary)] sm:ml-0 sm:h-px sm:w-5 sm:shrink-0","aria-hidden":"true"}),e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 whitespace-nowrap rounded-[var(--radius-sm)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-secondary)] px-2 py-1 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-primary)]",children:[l.name,e.jsxs("span",{className:"tabular-nums text-[var(--color-text-secondary)]",children:[l.probability??0,"%"]})]})]},l.id))})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",onClick:l=>l.stopPropagation(),children:[e.jsx(L,{variant:"ghost",size:"icon-sm",className:"border border-[var(--color-bg-tertiary)]",onClick:a,"aria-label":"Edit pipeline",children:e.jsx(We,{size:14})}),e.jsx(L,{variant:"ghost",size:"icon-sm",className:"border border-[var(--color-bg-tertiary)]",onClick:r,"aria-label":t.is_default?"Default pipeline cannot be deleted":"Delete pipeline",title:t.is_default?"Default pipeline cannot be deleted":"Delete pipeline",disabled:!!t.is_default,children:e.jsx(he,{size:14})})]})]})}let Tc=0;function zt(){return`new-${++Tc}-${Date.now()}`}function Ec({editing:t,onDone:a}){const{createPipeline:r,updatePipeline:l}=G(),n=G(I=>I.deals),[s,i]=o.useState((t==null?void 0:t.name)??""),[d,c]=o.useState(()=>{if(t&&t.stages.length>0)return[...t.stages].sort((k,C)=>k.sort_order-C.sort_order).map(k=>({id:k.id,name:k.name,probability:k.probability!=null?String(k.probability):"",requiredFields:k.required_fields??[],requiredDraft:""}));const I={requiredFields:[],requiredDraft:""};return[{id:zt(),name:"Lead",probability:"10",...I},{id:zt(),name:"Qualified",probability:"25",...I},{id:zt(),name:"Proposal",probability:"50",...I},{id:zt(),name:"Negotiation",probability:"75",...I},{id:zt(),name:"Closed Won",probability:"100",...I},{id:zt(),name:"Closed Lost",probability:"0",...I}]}),[m,p]=o.useState(()=>{var I;return((I=d[0])==null?void 0:I.id)??null}),u=o.useMemo(()=>{const I=new Set(["amount","close_date","contact_id","company_id"]);for(const k of n)for(const C of Object.keys(k.custom_properties??{}))I.add(C);return[...I].sort()},[n]),[x,w]=o.useState(!1),[N,h]=o.useState(null),[v,j]=o.useState(!1),[f,z]=o.useState(null),[y,b]=o.useState((t==null?void 0:t.visibility)??"workspace"),g=s.trim().length>0&&d.length>0&&d.every(I=>I.name.trim())&&!x,E=async()=>{h(null),w(!0);const I=d.map((k,C)=>({name:k.name.trim(),probability:k.probability?Number(k.probability):void 0,sort_order:C,required_fields:k.requiredFields}));try{t?await l(t.id,{name:s.trim(),stages:I,visibility:y})?a():h("Unable to update pipeline."):await r({name:s.trim(),stages:I,visibility:y})?a():h("Unable to create pipeline.")}finally{w(!1)}},A=()=>{const I=zt();c([...d,{id:I,name:"",probability:"",requiredFields:[],requiredDraft:""}]),p(I)},U=I=>{c(d.filter(k=>k.id!==I)),m===I&&p(null)},D=(I,k,C)=>{c(d.map(_=>_.id===I?{..._,[k]:C}:_))}
67,O=(I,k)=>{const C=k.trim();C&&c(d.map(_=>_.id===I?{..._,requiredFields:_.requiredFields.includes(C)?_.requiredFields:[..._.requiredFields,C],requiredDraft:""}:_))},P=(I,k)=>{c(d.map(C=>C.id===I?{...C,requiredFields:C.requiredFields.filter(_=>_!==k)}:C))},H=I=>{const k=I.requiredDraft.trim();k&&(O(I.id,k),z(null))},ae=(I,k)=>{if(k<0||k>=d.length)return;const C=[...d],[_]=C.splice(I,1);C.splice(k,0,_),c(C)};return e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(vt,{title:t?"Edit pipeline":"New pipeline",description:e.jsx("span",{className:"max-sm:hidden",children:"Configure stages, close probabilities, requirements, and access."}),onBack:a,actions:e.jsxs(e.Fragment,{children:[e.jsx(L,{variant:"secondary",size:"compact",onClick:a,children:"Cancel"}),e.jsx(L,{variant:"primary",size:"compact",onClick:E,disabled:!g,children:x?"Saving…":t?"Save":"Create"})]}),mobileActionsBelow:!0}),e.jsxs("div",{className:"mx-auto w-full max-w-5xl space-y-4 p-4 pb-[calc(var(--mobile-tab-bar-clearance,0px)+2rem)] sm:p-6",children:[N&&e.jsx("div",{className:"p-3 rounded-md bg-[var(--color-error-subtle)] text-[var(--color-error-text)] text-[length:var(--text-body-s)]",children:N}),e.jsxs("section",{className:"rounded-[var(--radius-lg)] border border-[var(--color-bg-tertiary)] bg-[var(--color-surface-1)] p-4 sm:p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h2",{className:"text-[length:var(--text-title-s)] font-semibold text-[var(--color-text-primary)]",children:"Pipeline details"}),e.jsx("p",{className:"mt-0.5 text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"Name this sales process and define who can work its deals."})]}),e.jsxs("label",{className:"block text-base leading-6 font-medium text-[var(--color-text-primary)] mb-2 md:text-[length:var(--text-label-l)] md:leading-[var(--lh-label-l)]",children:["Pipeline name ",e.jsx("span",{className:"text-[var(--color-error-text)]",children:"*"})]}),e.jsx(J,{value:s,onChange:I=>i(I.target.value),placeholder:"e.g. Sales Pipeline",autoFocus:!0})]}),e.jsxs("section",{className:"rounded-[var(--radius-lg)] border border-[var(--color-bg-tertiary)] bg-[var(--color-surface-1)] p-4 sm:p-5",children:[e.jsx("label",{className:"block text-base leading-6 font-medium text-[var(--color-text-primary)] mb-2 md:text-[length:var(--text-label-l)] md:leading-[var(--lh-label-l)]",children:"Visibility"}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>b("workspace"),"aria-pressed":y==="workspace",className:`w-full sm:flex-1 flex items-center gap-2 px-3 py-2 min-h-10 rounded-[var(--radius-md)] border cursor-pointer transition-all text-[length:var(--text-body-m)] ${y==="workspace"?"border-[var(--color-accent)] bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]":"border-[var(--color-bg-tertiary)] text-[var(--color-text-secondary)] hover:border-[var(--color-text-tertiary)]"}`,children:[e.jsx(ja,{size:16}),e.jsxs("div",{className:"text-left",children:[e.jsx("div",{className:"font-medium",children:"Workspace"}),e.jsx("div",{className:`text-[length:var(--text-label-s)] ${y==="workspace"?"text-[var(--color-text-primary)]":"text-[var(--color-text-secondary)]"}`,children:"Everyone can see its deals"})]}),y==="workspace"&&e.jsx(mr,{size:16,className:"ml-auto shrink-0"})]}),e.jsxs("button",{type:"button",onClick:()=>b("private"),"aria-pressed":y==="private",className:`w-full sm:flex-1 flex items-center gap-2 px-3 py-2 min-h-10 rounded-[var(--radius-md)] border cursor-pointer transition-all text-[length:var(--text-body-m)] ${y==="private"?"border-[var(--color-accent)] bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]":"border-[var(--color-bg-tertiary)] text-[var(--color-text-secondary)] hover:border-[var(--color-text-tertiary)]"}`,children:[e.jsx(Jl,{size:16}),e.jsxs("div",{className:"text-left",children:[e.jsx("div",{className:"font-medium",children:"Private"}),e.jsx("div",{className:`text-[length:var(--text-label-s)] ${y==="private"?"text-[var(--color-text-primary)]":"text-[var(--color-text-secondary)]"}`,children:"Only pipeline members"})]}),y==="private"&&e.jsx(mr,{size:16,className:"ml-auto shrink-0"})]})]})]}),e.jsx("section",{className:"rounded-[var(--radius-lg)] border border-[var(--color-bg-tertiary)] bg-[var(--color-surface-1)] p-4 sm:p-5",children:e.jsxs(ko,{defaultValue:"stages",children:[e.jsxs(Co,{"aria-label":"Pipeline settings",children:[e.jsx(ul,{value:"stages",children:"Stages"}),e.jsx(ul,{value:"members",children:"Members"})]}),e.jsxs(pl,{value:"stages",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("label",{className:"text-[13px] leading-5 font-medium text-[var(--color-text-primary)] md:text-[length:var(--text-label-l)]",children:["Stages ",e.jsx("span",{className:"text-[var(--color-error-text)]",children:"*"})]}),e.jsxs(L,{variant:"ghost",size:"compact",onClick:A,children:[e.jsx(oe,{size:14}),"Add stage"]})]}),e.jsxs("div",{className:"mb-1 hidden grid-cols-[24px_1fr_80px_32px] gap-2 px-2 sm:grid",children:[e.jsx("div",{}),e.jsx("div",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)] uppercase tracking-wider",children:"Name"}),e.jsx("div",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)] uppercase tracking-wider",children:"Win %"}),e.jsx("div",{})]}),e.jsx("div",{className:"space-y-2",children:d.map((I,k)=>e.jsxs("div",{className:"group rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] px-3 py-3 transition-colors hover:border-[var(--color-text-quaternary)]",children:[e.jsxs("button",{type:"button",className:"flex min-h-8 w-full items-center gap-2 text-left sm:hidden",onClick:()=>p(C=>C===I.id?null:I.id),"aria-expanded":m===I.id,children:[e.jsx("span",{className:"min-w-0 flex-1 truncate text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)]",children:I.name||`Stage ${k+1}`}
67),e.jsxs("span",{className:"text-[length:var(--text-label-m)] tabular-nums text-[var(--color-text-secondary)]",children:[I.probability||"0","%"]}),e.jsx(ye,{size:16,className:`shrink-0 text-[var(--color-text-tertiary)] transition-transform ${m===I.id?"rotate-180":""}`})]}),e.jsxs("div",{className:`${m===I.id?"grid":"hidden"} mt-3 grid-cols-[24px_1fr_72px_32px] items-center gap-2 sm:mt-0 sm:grid sm:grid-cols-[24px_1fr_80px_32px]`,children:[e.jsx("div",{className:"flex flex-col gap-0.5 items-center",children:e.jsx("button",{type:"button",className:"text-[var(--color-text-quaternary)] hover:text-[var(--color-text-secondary)] cursor-grab",title:"Drag to reorder",onClick:()=>ae(k,k-1),disabled:k===0,"aria-label":`Move ${I.name||"stage"} up`,children:e.jsx(Zl,{size:14})})}),e.jsx(J,{value:I.name,onChange:C=>D(I.id,"name",C.target.value),placeholder:`Stage ${k+1}`,className:"h-8 text-sm"}),e.jsx(J,{type:"number",min:"0",max:"100",value:I.probability,onChange:C=>D(I.id,"probability",C.target.value),placeholder:"0",className:"h-8 text-sm tabular-nums text-center"}),e.jsx(L,{variant:"ghost",size:"icon-sm",onClick:()=>U(I.id),disabled:d.length<=1,"aria-label":`Remove ${I.name||"stage"}`,className:"opacity-0 group-hover:opacity-100 pointer-coarse:opacity-100 transition-opacity",children:e.jsx(he,{size:14})})]}),e.jsxs("div",{className:`${m===I.id?"flex":"hidden"} mt-2 flex-col items-stretch gap-1.5 sm:ml-8 sm:mr-10 sm:flex sm:flex-row sm:flex-wrap sm:items-center`,children:[e.jsx("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:"Required fields"}),I.requiredFields.map(C=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded-[var(--radius-sm)] bg-[var(--color-accent-subtle)] text-[var(--color-accent)] text-[length:var(--text-label-s)]",children:[C,e.jsx("button",{type:"button",onClick:()=>P(I.id,C),"aria-label":`Remove required field ${C} from ${I.name||"stage"}`,className:"hover:opacity-70 leading-none",children:"×"})]},C)),f===I.id?e.jsx(J,{autoFocus:!0,value:I.requiredDraft,onChange:C=>D(I.id,"requiredDraft",C.target.value),onKeyDown:C=>{C.key==="Enter"?(C.preventDefault(),H(I)):C.key==="Escape"&&(D(I.id,"requiredDraft",""),z(null))},onBlur:()=>{I.requiredDraft.trim()?H(I):z(null)},"aria-label":`Custom required field for ${I.name||"stage"}`,placeholder:"Property key",className:"h-9 w-full text-[length:var(--text-label-s)] sm:h-7 sm:w-40"}):e.jsxs(me,{value:"",onValueChange:C=>{C==="__custom__"?z(I.id):O(I.id,C)},children:[e.jsx(ue,{"aria-label":`Add required field to ${I.name||"stage"}`,className:"h-9 w-full border-dashed text-[length:var(--text-label-s)] sm:h-7 sm:w-40",children:e.jsx(ve,{placeholder:"Choose property…"})}),e.jsxs(pe,{children:[u.filter(C=>!I.requiredFields.includes(C)).map(C=>e.jsx(te,{value:C,children:C.replaceAll("_"," ")},C)),e.jsx(te,{value:"__custom__",children:"Custom property…"})]})]})]})]},I.id))}),e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] mt-2",children:"A deal must have every required field filled before it can move into that stage."}),e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] mt-2",children:"Stages are ordered top-to-bottom. Deals progress through each stage toward close."})]}),e.jsx(pl,{value:"members",children:t?e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"Deals in this pipeline are visible to its members. Add people or teams as Member or Admin; admins can manage the pipeline and its members."}),e.jsxs(L,{variant:"secondary",size:"compact",onClick:()=>j(!0),children:[e.jsx(ja,{size:14}),"Manage members"]}),e.jsx(mi,{open:v,onOpenChange:j,documentId:t.id,documentTitle:t.name,apiBasePath:"/api/crm/pipelines",resourceType:"pipeline",roleOptions:["member","admin"],roleDescriptions:{member:"Can see deals in this pipeline.",admin:"Can see deals and manage the pipeline + its members."}})]}):e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"Save the pipeline first, then manage its members here. You become its first admin."})})]})})]})]})}function Lc(){const{dealTemplates:t,dealTemplatesLoading:a,loadDealTemplates:r,deleteDealTemplate:l}
67=G(),[n,s]=o.useState(!1),[i,d]=o.useState(null),[c,m]=o.useState(null),[p,u]=o.useState(""),[x,w]=o.useState(!1);o.useEffect(()=>{r()},[r]);const N=o.useMemo(()=>{const v=p.trim().toLowerCase();return t.filter(j=>{var f;return!x&&!j.is_active?!1:v?j.name.toLowerCase().includes(v)||(((f=j.description)==null?void 0:f.toLowerCase().includes(v))??!1):!0})},[t,p,x]),h=async()=>{c&&(await l(c),m(null))};return n||i?e.jsx(Pc,{editing:i,onDone:()=>{s(!1),d(null)}}):e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(Xe,{title:"Deal templates",description:"Predefined deal configurations — pipeline, stage, custom properties, and seeded products. Start a new deal with one click.",actions:e.jsxs(L,{variant:"primary",size:"compact",onClick:()=>s(!0),children:[e.jsx(oe,{size:16}),"New template"]})}),e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-[var(--color-bg-tertiary)] max-md:flex-col max-md:items-stretch",children:[e.jsxs("div",{className:"relative flex-1 max-w-md max-md:max-w-none",children:[e.jsx(Na,{size:16,className:"absolute left-3 top-1/2 -translate-y-1/2 text-[var(--color-text-tertiary)] pointer-events-none"}),e.jsx(J,{"aria-label":"Search deal templates",value:p,onChange:v=>u(v.target.value),placeholder:"Search templates…",className:"pl-9"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] cursor-pointer pointer-coarse:min-h-11",children:[e.jsx(Ae,{checked:x,onCheckedChange:v=>w(v===!0),"aria-label":"Show inactive deal templates"}),"Show inactive"]})]}),e.jsx("div",{className:"divide-y divide-[var(--color-bg-tertiary)]",children:a?Array.from({length:4}).map((v,j)=>e.jsx(Re,{},j)):N.length===0?e.jsx(De,{icon:e.jsx(Ca,{size:24,className:"text-[var(--color-accent)]"}),title:t.length>0?"No templates match your filter":"No deal templates yet",description:t.length>0?"Try clearing the search or toggling inactive templates.":"Save reusable templates for renewals, upsells, and proposals. Create with one click.",action:t.length===0?e.jsxs(L,{variant:"primary",size:"default",className:"mt-4",onClick:()=>s(!0),children:[e.jsx(oe,{size:16}),e.jsx("span",{className:"ml-2",children:"Create template"})]}):void 0}):N.map(v=>e.jsx(Ic,{template:v,onEdit:()=>d(v),onDelete:()=>m(v.id)},v.id))}),t.length>0&&e.jsx("div",{className:"p-4 bg-[var(--color-bg-secondary)] border-t border-[var(--color-bg-tertiary)]",children:e.jsxs("div",{className:"flex items-center gap-4 text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-[var(--color-text-primary)]",children:t.length})," ","total"]}),e.jsxs("span",{children:[e.jsx("strong",{className:"text-[var(--color-text-primary)]",children:t.filter(v=>v.is_active).length})," ","active"]})]})}),e.jsx(we,{open:!!c,title:"Delete template",description:"Existing deals that were created from this template will keep their data. Only the template itself is removed.",confirmLabel:"Delete",onConfirm:h,onOpenChange:v=>{v||m(null)},variant:"destructive"})]})}function Ic({template:t,onEdit:a,onDelete:r}){const l=t.line_items.reduce((n,s)=>{const i=s.quantity*s.unit_price*(1-s.discount_percent/100);return n+i},0);return e.jsxs("div",{className:"flex items-center gap-4 px-4 py-3 hover:bg-[var(--color-bg-secondary)] transition-colors group max-md:grid max-md:grid-cols-[36px_minmax(0,1fr)_auto] max-md:gap-x-3 max-md:gap-y-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-[var(--color-accent-subtle)] flex items-center justify-center shrink-0",children:e.jsx(Ca,{size:18,className:"text-[var(--color-accent)]"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx("span",{className:`text-[length:var(--text-body-m)] font-medium truncate ${t.is_active?"text-[var(--color-text-primary)]":"text-[var(--color-text-quaternary)]"}`,children:t.name}),!t.is_active&&e.jsx(de,{variant:"default",children:"Inactive"}),t.pipeline&&e.jsx(de,{variant:"default",children:t.pipeline.name}),t.stage&&e.jsx(de,{variant:"default",children:t.stage.name}),t.line_items.length>0&&e.jsxs(de,{variant:"default",children:[t.line_items.length," line item",t.line_items.length===1?"":"s"]})]}),t.description&&e.jsx("div",{className:"mt-0.5 text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] md:truncate",children:t.description})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsx("div",{className:"text-[length:var(--text-body-m)] font-semibold text-[var(--color-text-primary)] tabular-nums",children:Q(t.amount??l,t.currency)}),e.jsx("div",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:t.amount!=null?"fixed amount":"from line items"})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 pointer-coarse:opacity-100 transition-opacity shrink-0 max-md:col-start-2 max-md:col-span-2 max-md:justify-end",children:[e.jsx(L,{variant:"ghost",size:"icon-sm",onClick:a,"aria-label":"Edit template",className:"border border-[var(--color-bg-tertiary)] md:border-transparent",children:e.jsx(We,{size:14})}),e.jsx(L,{variant:"ghost",size:"icon-sm",onClick:r,"aria-label":"Delete template",className:"border border-[var(--color-bg-tertiary)] md:border-transparent",children:e.jsx(he,{size:14})})]})]})}function Pc({editing:t,onDone:a}){const{createDealTemplate:r,updateDealTemplate:l,pipelines:n,products:s,loadProducts:i}
67=G(),[d,c]=o.useState((t==null?void 0:t.name)??""),[m,p]=o.useState((t==null?void 0:t.description)??""),[u,x]=o.useState((t==null?void 0:t.title_template)??""),[w,N]=o.useState((t==null?void 0:t.pipeline_id)??""),[h,v]=o.useState((t==null?void 0:t.stage_id)??""),[j,f]=o.useState((t==null?void 0:t.amount)!=null?String(t.amount):""),[z,y]=o.useState((t==null?void 0:t.currency)??"USD"),[b,g]=o.useState((t==null?void 0:t.probability)!=null?String(t.probability):""),[E,A]=o.useState((t==null?void 0:t.close_date_offset_days)!=null?String(t.close_date_offset_days):""),[U,D]=o.useState((t==null?void 0:t.is_active)??!0),[O,P]=o.useState(((t==null?void 0:t.line_items)??[]).map(F=>({product_id:F.product_id,name:F.name,description:F.description,quantity:F.quantity,unit_price:F.unit_price,discount_percent:F.discount_percent,sort_order:F.sort_order}))),[H,ae]=o.useState(!1),[I,k]=o.useState(null);o.useEffect(()=>{s.length===0&&i({activeOnly:!0})},[s.length,i]);const C=n.find(F=>F.id===w),_=(C==null?void 0:C.stages)??[],Z=F=>{var X;N(F);const le=n.find(T=>T.id===F);if(!le){v("");return}le.stages.find(T=>T.id===h)||v(((X=le.stages[0])==null?void 0:X.id)??"")},B=d.trim().length>0&&!H,V=async()=>{k(null),ae(!0);const F={name:d.trim(),description:m.trim()||null,title_template:u.trim()||null,pipeline_id:w||null,stage_id:h||null,amount:j.trim()?Number(j):null,currency:z.trim().toUpperCase()||"USD",probability:b.trim()?Number(b):null,close_date_offset_days:E.trim()?Number(E):null,is_active:U,line_items:O};try{t?await l(t.id,F)?a():k("Unable to update template."):await r(F)?a():k("Unable to create template.")}finally{ae(!1)}};return e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(vt,{title:t?"Edit template":"New template",titleLabel:t?"Edit deal template":"New deal template",onBack:a,actions:e.jsxs(e.Fragment,{children:[e.jsx(L,{variant:"secondary",size:"compact",onClick:a,className:"max-sm:hidden",children:"Cancel"}),e.jsx(L,{variant:"primary",size:"compact",onClick:V,disabled:!B,children:H?"Saving…":t?"Save":"Create"})]})}),e.jsxs("div",{className:"mx-auto max-w-5xl space-y-5 p-4 pb-[calc(var(--mobile-tab-bar-clearance,0px)+2rem)] sm:p-6 [&_input::placeholder]:text-[var(--color-text-secondary)] [&_textarea::placeholder]:text-[var(--color-text-secondary)]",children:[I&&e.jsx("div",{className:"p-3 rounded-md bg-[var(--color-error-subtle)] text-[var(--color-error-text)] text-[length:var(--text-body-s)]",children:I}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(gt,{label:"Template name",required:!0,children:e.jsx(J,{value:d,onChange:F=>c(F.target.value),placeholder:"Enterprise Renewal",autoFocus:!0})}),e.jsx(gt,{label:"Description",hint:"Short summary shown in the template picker",children:e.jsx(br,{value:m,onChange:F=>p(F.target.value),rows:2,placeholder:"Annual renewal deal for enterprise customers"})}),e.jsx(gt,{label:"Deal title template",hint:"Default deal title. Supports {{date}}, {{year}}, {{month}}, {{day}}, {{template}}.",children:e.jsx(J,{value:u,onChange:F=>x(F.target.value),placeholder:"Enterprise Renewal — {{year}}"})})]}),e.jsxs("details",{className:"group rounded-[var(--radius-lg)] border border-[var(--color-bg-tertiary)]",open:t?!0:void 0,children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer list-none items-center justify-between gap-3 px-4 py-3 text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)] marker:hidden",children:[e.jsx("span",{children:"Advanced defaults"}),e.jsx("span",{className:"ml-auto text-[length:var(--text-label-s)] font-normal text-[var(--color-text-tertiary)] group-open:hidden",children:"Pipeline, value, products"}),e.jsx("span",{className:"ml-auto hidden text-[length:var(--text-label-s)] font-normal text-[var(--color-text-tertiary)] group-open:inline",children:"Hide"}),e.jsx(ye,{size:16,className:"shrink-0 text-[var(--color-text-tertiary)] transition-transform group-open:rotate-180"})]}),e.jsxs("div",{className:"space-y-5 border-t border-[var(--color-bg-tertiary)] p-4",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsx("h3",{className:"text-[length:var(--text-label-l)] font-semibold text-[var(--color-text-primary)]",children:"Pipeline & stage"}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsx(gt,{label:"Pipeline",children:e.jsx(Rc,{pipelines:n,value:w,onChange:Z})}),e.jsx(gt,{label:"Stage",children:e.jsxs(me,{value:h||"none",onValueChange:F=>v(F==="none"?"":F),disabled:_.length===0,children:[e.jsx(ue,{className:"w-full","aria-label":"Default stage",children:e.jsx(ve,{placeholder:_.length===0?"Select a pipeline first":"Any stage"})}),e.jsxs(pe,{children:[e.jsx(te,{value:"none",children:"No default stage"}),_.map(F=>e.jsx(te,{value:F.id,children:F.name},F.id))]})]})})]})]}),e.jsxs("section",{className:"space-y-4 pt-4 border-t border-[var(--color-bg-tertiary)]",children:[e.jsx("h3",{className:"text-[length:var(--text-label-l)] font-semibold text-[var(--color-text-primary)]",children:"Deal defaults"}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-3",children:[e.jsx(gt,{label:"Fixed amount",hint:"Leave blank to use line items",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(J,{type:"number","aria-label":"Fixed amount",min:"0",step:"0.01",value:j,onChange:F=>f(F.target.value),className:"flex-1 tabular-nums",placeholder:"0.00"}),e.jsx(J,{"aria-label":"Currency",value:z,onChange:F=>y(F.target.value.toUpperCase()),maxLength:3,className:"w-20 uppercase text-center"})]})}),e.jsx(gt,{label:"Probability %",hint:"0–100, optional",children:e.jsx(J,{type:"number","aria-label":"Probability percent",min:"0",max:"100",step:"1",value:b,onChange:F=>g(F.target.value),className:"tabular-nums",placeholder:"e.g. 60"})}),e.jsx(gt,{label:"Close date offset",hint:"Days from today (e.g. 30)",children:e.jsx(J,{type:"number","aria-label":"Close date offset in days",step:"1",value:E,onChange:F=>A(F.target.value),className:"tabular-nums",placeholder:"30"})})]})]}),e.jsxs("section",{className:"space-y-3 pt-4 border-t border-[var(--color-bg-tertiary)]",children:[e.jsxs("div",{className:"flex flex-col items-start gap-1 sm:flex-row sm:items-center sm:justify-between sm:gap-4",children:[e.jsx("h3",{className:"text-[length:var(--text-label-l)] font-semibold text-[var(--color-text-primary)]",children:"Seeded line items"}),e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"Products automatically added to every deal created from this template."})]}),e.jsx(Fc,{products:s,lineItems:O,onChange:P})]}),e.jsx("section",{className:"pt-4 border-t border-[var(--color-bg-tertiary)]",children:e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx(Ae,{checked:U,onCheckedChange:F=>D(F===!0),"aria-label":"Active template"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-primary)]",children:"Active"}),e.jsx("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"Inactive templates are hidden from the New Deal picker but are preserved for reference."})]})]})})]})]})]})]})}function Rc({pipelines:t,value:a,onChange:r}){return e.jsxs(me,{value:a||"none",onValueChange:l=>r(l==="none"?"":l),children:[e.jsx(ue,{className:"w-full","aria-label":"Default pipeline",children:e.jsx(ve,{placeholder:"Any pipeline"})}),e.jsxs(pe,{children:[e.jsx(te,{value:"none",children:"No default pipeline"}),t.map(l=>e.jsx(te,{value:l.id,children:l.name},l.id))]})]})}function Fc({products:t,lineItems:a,onChange:r}){const l=(c,m)=>{r(a.map((p,u)=>u===c?{...p,...m}:p))},n=c=>{r(a.filter((m,p)=>p!==c))},s=c=>{const m=t.find(p=>p.id===c);m&&r([...a,{product_id:m.id,name:m.name,description:m.description,quantity:1,unit_price:m.unit_price,discount_percent:0,sort_order:a.length}])},i=()=>{r([...a,{product_id:null,name:"",description:null,quantity:1,unit_price:0,discount_percent:0,sort_order:a.length}])},d=a.reduce((c,m)=>{const p=m.unit_price??0,u=m.quantity??0,x=m.discount_percent??0;return c+u*p*(1-x/100)},0);return e.jsxs("div",{className:"space-y-2",children:[a.length===0?e.jsxs("div",{className:"rounded-md border border-dashed border-[var(--color-bg-tertiary)] p-6 text-center",children:[e.jsx(Ze,{size:20,className:"mx-auto text-[var(--color-text-tertiary)]"}),e.jsx("p",{className:"mt-2 text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"No line items yet. Add products to auto-populate new deals."})]}):e.jsxs("div",{className:"rounded-md border border-[var(--color-bg-tertiary)] overflow-hidden",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_80px_100px_80px_100px_32px] gap-2 items-center px-3 py-2 bg-[var(--color-bg-secondary)] text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wide",children:[e.jsx("div",{children:"Item"}),e.jsx("div",{className:"text-right",children:"Qty"}),e.jsx("div",{className:"text-right",children:"Unit price"}),e.jsx("div",{className:"text-right",children:"Disc %"}),e.jsx("div",{className:"text-right",children:"Amount"}),e.jsx("div",{})]}),e.jsx("div",{className:"divide-y divide-[var(--color-bg-tertiary)]",children:a.map((c,m)=>{const p=(c.quantity??0)*(c.unit_price??0)*(1-(c.discount_percent??0)/100);return e.jsxs("div",{className:"grid grid-cols-[1fr_80px_100px_80px_100px_32px] gap-2 items-center px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(J,{"aria-label":`Line item ${m+1} name`,value:c.name??"",onChange:u=>l(m,{name:u.target.value}),placeholder:"Line item name",className:"text-[length:var(--text-body-m)]"}),c.product_id&&e.jsxs("div",{className:"flex items-center gap-1 mt-1 text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:[e.jsx(Ct,{size:10}),e.jsx("span",{className:"truncate",children:"From catalog"})]})]}),e.jsx(J,{type:"number","aria-label":`Line item ${m+1} quantity`,min:"0",step:"0.01",value:c.quantity??1,onChange:u=>l(m,{quantity:Number(u.target.value)}),className:"text-right tabular-nums"}),e.jsx(J,{type:"number","aria-label":`Line item ${m+1} unit price`,min:"0",step:"0.01",value:c.unit_price??0,onChange:u=>l(m,{unit_price:Number(u.target.value)}),className:"text-right tabular-nums"}),e.jsx(J,{type:"number","aria-label":`Line item ${m+1} discount percent`,min:"0",max:"100",step:"0.01",value:c.discount_percent??0,onChange:u=>l(m,{discount_percent:Number(u.target.value)}),className:"text-right tabular-nums"}),e.jsx("div",{className:"text-right text-[length:var(--text-body-m)] font-medium tabular-nums text-[var(--color-text-primary)]",children:Q(p)}),e.jsx(L,{variant:"ghost",size:"icon-sm",onClick:()=>n(m),"aria-label":"Remove line item",children:e.jsx(he,{size:14})})]},m)})}),e.jsxs("div",{className:"grid grid-cols-[1fr_80px_100px_80px_100px_32px] gap-2 items-center px-3 py-2 bg-[var(--color-bg-secondary)] border-t border-[var(--color-bg-tertiary)]",children:[e.jsx("div",{className:"col-span-4 text-right text-[length:var(--text-body-s)] font-medium text-[var(--color-text-secondary)]",children:"Total"}),e.jsx("div",{className:"text-right text-[length:var(--text-body-m)] font-semibold tabular-nums text-[var(--color-text-primary)]",children:Q(d)}),e.jsx("div",{})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(me,{value:"",onValueChange:c=>{c&&s(c)},children:[e.jsx(ue,{className:"w-56","aria-label":"Add product from catalog",children:e.jsx(ve,{placeholder:"Add from catalog…"})}),e.jsx(pe,{children:t.length===0?e.jsx(te,{value:"__none",disabled:!0,children:"No active products"}):t.map(c=>e.jsxs(te,{value:c.id,children:[c.name,c.sku?` · ${c.sku}`:""," · ",Q(c.unit_price,c.currency)]},c.id))})]}),e.jsxs(L,{variant:"secondary",size:"compact",onClick:i,children:[e.jsx(oe,{size:14}),"Custom line"]})]})]})}function Mc({onSelect:t,onBlank:a}){const{dealTemplates:r,dealTemplatesLoading:l,loadDealTemplates:n}=G();o.useEffect(()=>{n({activeOnly:!0})},[n]);const s=o.useMemo(()=>r.filter(i=>i.is_active),[r]);return l&&s.length===0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Re,{}),e.jsx(Re,{})]}):s.length===0?e.jsxs("div",{className:"rounded-md border border-dashed border-[var(--color-bg-tertiary)] p-5 text-center",children:[e.jsx(Ca,{size:20,className:"mx-auto text-[var(--color-text-tertiary)]"}),e.jsx("p",{className:"mt-2 text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"No templates yet. Start from scratch, or create a template from the Templates tab."}),e.jsx(L,{variant:"primary",size:"compact",className:"mt-3",onClick:a,children:"Start from scratch"})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[length:var(--text-label-s)] font-semibold text-[var(--color-text-tertiary)] uppercase tracking-wide",children:"Templates"}),e.jsx(L,{variant:"secondary",size:"compact",onClick:a,className:"w-full justify-center",children:"Start from scratch"}),e.jsx("div",{className:"grid grid-cols-1 gap-2",children:s.map(i=>{var d,c;return e.jsxs("button",{type:"button",onClick:()=>t(i),className:"flex items-center gap-3 p-3 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] hover:border-[var(--color-accent)] hover:bg-[var(--color-accent-subtle)] text-left transition-colors",children:[e.jsx("div",{className:"w-8 h-8 rounded-md bg-[var(--color-accent-subtle)] flex items-center justify-center shrink-0",children:e.jsx(Ca,{size:16,className:"text-[var(--color-accent)]"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)] truncate",children:i.name}),e.jsx("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] truncate",children:[(d=i.pi
67peline)==null?void 0:d.name,(c=i.stage)==null?void 0:c.name,i.line_items.length>0?`${i.line_items.length} line item${i.line_items.length===1?"":"s"}`:null,i.amount!=null?Q(i.amount,i.currency):null].filter(Boolean).join(" · ")||"No defaults set"})]})]},i.id)})})]})}function gt({label:t,required:a,hint:r,children:l}){return e.jsxs("div",{children:[e.jsxs("label",{className:"block text-base leading-6 font-medium text-[var(--color-text-primary)] mb-2 md:text-[length:var(--text-label-l)] md:leading-[var(--lh-label-l)]",children:[t,a&&e.jsx("span",{className:"text-[var(--color-error-text)] ml-1",children:"*"})]}),l,r&&e.jsx("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] mt-1",children:r})]})}function Oc(t,a){return t==="company"?`/crm/companies?company=${a}`:t==="deal"?`/crm/pipeline?deal=${a}`:`/crm/contacts?contact=${a}`}async function qc(t){if(t==="deal")return(await Ve.crm.deals.list({query:{limit:200,offset:0}})).data.map(n=>({id:n.id,name:n.title}));const a=t==="company"?"company":"person";return(await Ve.crm.contacts.list({query:{type:a,limit:200,offset:0}})).data.map(l=>({id:l.id,name:l.name}))}const Dl=[{key:"contact",label:"Contacts"},{key:"company",label:"Companies"},{key:"deal",label:"Deals"}],cs={text:"Text",number:"Number",select:"Select",multi_select:"Multi-select",date:"Date",checkbox:"Checkbox",url:"URL",email:"Email",phone:"Phone",relation:"Relation"},ds=["select","multi_select"];function Vc(t){return t==null||t===""||Array.isArray(t)&&t.length===0}function Bc(t,a){if(Vc(a))return t.required?{code:"property_required",message:`${t.label} is required.`}:null;switch(t.field_type){case"number":return typeof a!="number"&&Number.isNaN(Number(a))?{code:"property_type_mismatch",message:`${t.label} must be a number.`}:null;case"date":return typeof a!="string"||Number.isNaN(Date.parse(a))?{code:"property_type_mismatch",message:`${t.label} must be a date.`}:null;case"select":return typeof a!="string"||!t.options.includes(a)?{code:"property_option_invalid",message:`${t.label} must be one of its options.`}:null;case"multi_select":return(Array.isArray(a)?a.map(String):[]).some(l=>!t.options.includes(l))?{code:"property_option_invalid",message:`${t.label} must be one of its options.`}:null;default:return null}}function Uc({label:t,definition:a,value:r,onSave:l}){const n=a.relation_target??"contact",[s,i]=o.useState(!1),[d,c]=o.useState(null),[m,p]=o.useState(!1),[u,x]=o.useState(r??""),[w,N]=o.useState(!1),[h,v]=o.useState(null),[j,f]=o.useState(null);o.useEffect(()=>{!s||d!==null||m||(p(!0),qc(n).then(y=>c(y)).catch(()=>c([])).finally(()=>p(!1)))},[s,d,m,n]),o.useEffect(()=>{if(!r){v(null),f(null);return}let y=!0;return So("contacts",r).then(b=>{y&&(b.kind==="ok"?(v(b.preview.title),f("ok")):b.kind==="locked"?f("locked"):b.kind==="deleted"&&f("deleted"))}),()=>{y=!1}},[r]);const z=async()=>{N(!0);try{await l(u||null)&&i(!1)}finally{N(!1)}};return s?e.jsxs("div",{className:"group flex items-center gap-2 min-h-[28px]",children:[e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] truncate min-w-[80px]",children:t}),e.jsxs("select",{value:u,onChange:y=>x(y.target.value),"aria-label":`Select ${n} for ${t}`,"data-testid":"relation-property-select",className:"flex-1 h-7 px-1.5 rounded border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-secondary)] text-[length:var(--text-body-s)] text-[var(--color-text-primary)] min-w-0 focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)] cursor-pointer",children:[e.jsx("option",{value:"",children:m?"Loading…":`Choose a ${n}…`}),(d??[]).map(y=>e.jsx("option",{value:y.id,children:y.name},y.id))]}),e.jsx("button",{type:"button",onClick:z,disabled:w,className:"p-0.5 text-[var(--color-success)] disabled:opacity-50","aria-label":"Save relation",children:e.jsx(mr,{size:14})}),e.jsx("button",{type:"button",onClick:()=>{i(!1),x(r??"")},className:"p-0.5 text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]","aria-label":"Cancel",children:e.jsx(ze,{size:14})})]}):e.jsxs("div",{className:"group flex items-center gap-2 min-h-[28px]","data-testid":"relation-property-row",children:[e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] truncate min-w-[80px]",children:t}),e.jsx("span",{className:"flex-1 text-right truncate",children:r&&j==="deleted"?e.jsxs("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-quaternary)] italic",children:["Deleted ",n]}):r&&j==="locked"?e.jsxs("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-quaternary)] italic",children:["Restricted ",n]}):r?e.jsx(cr,{module:"CRM",entityId:r,children:e.jsx("a",{href:Oc(n,r),"data-testid":"relation-property-chip",className:"text-[length:var(--text-body-s)] text-[var(--color-module-crm)] underline decoration-transparent decoration-dotted underline-offset-2 hover:
67decoration-[var(--color-module-crm)] focus-visible:outline-2 focus-visible:outline-[var(--color-accent)] focus-visible:outline-offset-2",children:h??`View ${n}`})}):e.jsxs("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-quaternary)]",children:["No ",n," linked"]})}),e.jsx("button",{type:"button",onClick:()=>i(!0),className:"p-0.5 opacity-0 group-hover:opacity-100 pointer-coarse:opacity-100 text-[var(--color-text-tertiary)] hover:text-[var(--color-accent)] transition-opacity","aria-label":`Edit ${t}`,children:e.jsx(We,{size:12})})]})}function Wc({def:t,value:a,onCommit:r,invalid:l}){const n="h-8 flex-1 min-w-0 rounded-[var(--radius-sm)] border border-[var(--color-text-quaternary)] bg-[var(--color-bg-primary)] px-2 text-[length:var(--text-body-s)] text-[var(--color-text-primary)] focus:border-[var(--color-accent)] focus:outline-none pointer-coarse:h-11";switch(t.field_type){case"select":{const s=a==null?"":String(a);return e.jsxs(me,{value:s||void 0,onValueChange:i=>r(i),children:[e.jsx(ue,{"aria-label":t.label,"aria-invalid":l||void 0,"data-testid":`typed-property-${t.key}`,className:"h-8 flex-1 min-w-0 border-[var(--color-text-quaternary)] bg-[var(--color-bg-primary)] pointer-coarse:h-11",children:e.jsx(ve,{placeholder:"Select…"})}),e.jsx(pe,{children:t.options.map(i=>e.jsx(te,{value:i,children:i},i))})]})}case"multi_select":{const s=Array.isArray(a)?a.map(String):[],i=d=>{const c=s.includes(d)?s.filter(m=>m!==d):[...s,d];r(c)};return e.jsx("div",{className:"flex min-h-8 flex-1 flex-wrap items-center gap-1 pointer-coarse:min-h-11",role:"group","aria-label":t.label,"data-testid":`typed-property-${t.key}`,children:t.options.map(d=>{const c=s.includes(d);return e.jsx("button",{type:"button",onClick:()=>i(d),"aria-pressed":c,className:`px-1.5 py-0.5 rounded text-[length:var(--text-label-s)] border transition-colors ${c?"bg-[var(--color-accent-subtle)] border-[var(--color-accent)] text-[var(--color-accent)]":"bg-[var(--color-bg-secondary)] border-[var(--color-bg-tertiary)] text-[var(--color-text-tertiary)]"}`,children:d},d)})})}case"date":{const s=a==null?"":String(a);return e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(_o,{value:s,onChange:i=>r(i??""),"aria-label":t.label,"data-testid":`typed-property-${t.key}`,className:"h-7"})})}case"checkbox":{const s=a===!0||a==="true";return e.jsx("div",{className:"flex min-h-8 flex-1 items-center justify-end pointer-coarse:min-h-11",children:e.jsx(Ul,{checked:s,onCheckedChange:i=>r(i),"aria-label":t.label,"data-testid":`typed-property-${t.key}`})})}default:{const s=t.field_type==="number"?"number":t.field_type==="email"?"email":t.field_type==="url"?"url":t.field_type==="phone"?"tel":"text";return e.jsx(Gc,{def:t,inputType:s,inputClass:n,value:a==null?"":String(a),invalid:l,onCommit:r})}}}function Gc({def:t,inputType:a,inputClass:r,value:l,onCommit:n,invalid:s}){const[i,d]=o.useState(l);o.useEffect(()=>{d(l)},[l]);const c=()=>{i!==l&&n(i)};return e.jsx("input",{type:a,className:r,value:i,"aria-label":t.label,"aria-invalid":s||void 0,"data-testid":`typed-property-${t.key}`,onChange:m=>d(m.target.value),onBlur:c,onKeyDown:m=>{m.key==="Enter"&&(c(),m.target.blur()),m.key==="Escape"&&d(l)}})}function Ts({properties:t,onSave:a,entity:r}){const[l,n]=o.useState(!1),[s,i]=o.useState(""),[d,c]=o.useState(""),[m,p]=o.useState(null),[u,x]=o.useState(""),[w,N]=o.useState({}),h=o.useRef(null),v=G(D=>D.propertyDefinitions),j=G(D=>D.loadPropertyDefinitions);o.useEffect(()=>{r&&j()},[r,j]);const f=o.useMemo(()=>r?(v??[]).filter(D=>D.entity_type===r).sort((D,O)=>D.sort_order-O.sort_order||D.label.localeCompare(O.label)):[],[v,r]),z=o.useMemo(()=>new Set(f.map(D=>D.key)),[f]),y=async(D,O)=>{const P=f.find(ae=>ae.key===D),H=P?Bc(P,O):null;if(H){N(ae=>({...ae,[D]:H.message}));return}N(ae=>{if(!(D in ae))return ae;const{[D]:I,...k}=ae;return k}),await a({...t,[D]:O})};o.useEffect(()=>{var D;l&&((D=h.current)==null||D.focus())},[l]);const b=Object.entries(t).filter(([D])=>!z.has(D)),g=async()=>{const D=s.trim().toLowerCase().replace(/\s+/g,"_");if(!D||!d.trim())return;const O={...t,[D]:d.trim()};await a(O)&&(i(""),c(""),n(!1))},E=D=>{p(D),x(String(t[D]??""))},A=async()=>
67{if(!m)return;const D={...t,[m]:u.trim()};await a(D)&&p(null)},U=async D=>{const O={...t};delete O[D],await a(O)};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider",children:"Properties"}),!l&&e.jsxs("button",{type:"button",onClick:()=>n(!0),className:"text-[length:var(--text-body-m)] text-[var(--color-accent)] hover:text-[var(--color-accent-hover)] transition-colors flex items-center gap-1","aria-label":"Add custom property",children:[e.jsx(oe,{size:14}),"Add"]})]}),b.length===0&&f.length===0&&!l&&e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-quaternary)] py-1",children:"No custom properties"}),f.length>0&&e.jsx("div",{className:"space-y-1.5",children:f.map(D=>{const O=w[D.key];if(D.field_type==="relation"){const P=t[D.key];return e.jsx(Uc,{label:D.label,definition:D,value:typeof P=="string"?P:null,onSave:async H=>{const ae={...t};return H?ae[D.key]=H:delete ae[D.key],a(ae)}},D.id)}return e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"grid min-h-[32px] grid-cols-[minmax(96px,0.4fr)_minmax(0,1fr)] items-center gap-3",children:[e.jsxs("span",{className:"min-w-0 break-words text-[length:var(--text-body-m)] leading-[var(--lh-body-m)] text-[var(--color-text-tertiary)]",children:[D.label,D.required&&e.jsx("span",{className:"text-[var(--color-error)] ml-0.5","aria-hidden":!0,children:"*"})]}),e.jsx(Wc,{def:D,value:t[D.key],invalid:!!O,onCommit:P=>y(D.key,P)})]}),O&&e.jsx("p",{role:"alert","data-testid":`typed-property-error-${D.key}`,className:"text-[length:var(--text-label-s)] text-[var(--color-error)] sm:pl-[calc(40%+0.75rem)]",children:O})]},D.id)})}),e.jsx("div",{className:"space-y-1.5",children:b.map(([D,O])=>e.jsx("div",{className:"group flex items-center gap-2 min-h-[28px]",children:m===D?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] truncate min-w-[80px]",children:vl(D)}),e.jsx("input",{className:"flex-1 text-[length:var(--text-body-s)] text-[var(--color-text-primary)] bg-[var(--color-bg-secondary)] border border-[var(--color-bg-tertiary)] rounded px-1.5 py-0.5 min-w-0",value:u,onChange:P=>x(P.target.value),onKeyDown:P=>{P.key==="Enter"&&A(),P.key==="Escape"&&p(null)},autoFocus:!0}),e.jsx("button",{type:"button",onClick:A,className:"p-0.5 text-[var(--color-success)] hover:text-[var(--color-success)]",children:e.jsx(mr,{size:14})}),e.jsx("button",{type:"button",onClick:()=>p(null),className:"p-0.5 text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]",children:e.jsx(ze,{size:14})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] truncate min-w-[80px]",children:vl(D)}),e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] flex-1 text-right truncate",children:String(O)}),e.jsx("button",{type:"button",onClick:()=>E(D),className:"p-0.5 opacity-0 group-hover:opacity-100 pointer-coarse:opacity-100 text-[var(--color-text-tertiary)] hover:text-[var(--color-accent)] transition-opacity",children:e.jsx(We,{size:12})}),e.jsx("button",{type:"button",onClick:()=>U(D),className:"p-0.5 opacity-0 group-hover:opacity-100 pointer-coarse:opacity-100 text-[var(--color-text-tertiary)] hover:text-[var(--color-error)] transition-opacity",children:e.jsx(he,{size:12})})]})},D))}),l&&e.jsxs("div",{className:"space-y-2 pt-1 border-t border-[var(--color-bg-tertiary)]",children:[e.jsx("input",{ref:h,className:"w-full text-[length:var(--text-body-s)] text-[var(--color-text-primary)] bg-[var(--color-bg-secondary)] border border-[var(--color-bg-tertiary)] rounded px-2 py-1",placeholder:"Field name (e.g. department)",value:s,onChange:D=>i(D.target.value)}),e.jsx("input",{className:"w-full text-[length:var(--text-body-s)] text-[var(--color-text-primary)] bg-[var(--color-bg-secondary)] border border-[var(--color-bg-tertiary)] rounded px-2 py-1",placeholder:"Value",value:d,onChange:D=>c(D.target.value),onKeyDown:D=>{D.key==="Enter"&&g()}}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(L,{variant:"primary",size:"compact",onClick:g,disabled:!s.trim()||!d.trim(),children:"Save"}),e.jsx(L,{variant:"ghost",size:"compact",onClick:()=>{n(!1),i(""),c("")},children:"Cancel"})]})]})]})}function Kc(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}const Xa={label:"",field_type:"text",options:"",required:!1};function zl({draft:t,setDraft:a,onSubmit:r,onCancel:l,submitLabel:n}){const s=ds.includes(t.field_type),i=t.label.trim().length>0&&(!s||t.options.split(",").some(d=>d.trim()));return e.jsxs("div",{className:"space-y-3 p-3 border border-[var(--color-bg-tertiary)] rounded-lg bg-[var(--color-bg-secondary)]",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsxs("label",{htmlFor:"def-label",className:"block text-base leading-6 font-medium text-[var(--color-text-secondary)] mb-1 md:text-[length:var(--text-label-l)] md:leading-[var(--lh-label-l)]",children:["Property label ",e.jsx("span",{className:"text-[var(--color-error-text)]","aria-hidden":"true",children:"*"})]}),e.jsx(J,{id:"def-label","aria-required":"true",required:!0,placeholder:"e.g. Lead source",value:t.label,onChange:d=>
67a({...t,label:d.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"def-type",className:"block text-base leading-6 font-medium text-[var(--color-text-secondary)] mb-1 md:text-[length:var(--text-label-l)] md:leading-[var(--lh-label-l)]",children:"Type"}),e.jsxs(me,{value:t.field_type,onValueChange:d=>a({...t,field_type:d}),children:[e.jsx(ue,{id:"def-type","aria-label":"Field type",children:e.jsx(ve,{})}),e.jsx(pe,{children:ni.map(d=>e.jsx(te,{value:d,children:cs[d]},d))})]})]})]}),s&&e.jsxs("div",{children:[e.jsx("label",{htmlFor:"def-options",className:"block text-base leading-6 font-medium text-[var(--color-text-secondary)] mb-1 md:text-[length:var(--text-label-l)] md:leading-[var(--lh-label-l)]",children:"Options (comma-separated)"}),e.jsx(J,{id:"def-options",placeholder:"e.g. Referral, Ad, Event",value:t.options,onChange:d=>a({...t,options:d.target.value})})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] cursor-pointer",children:[e.jsx(Ae,{checked:t.required,onCheckedChange:d=>a({...t,required:d===!0}),"aria-label":"Required property"}),"Required"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(L,{variant:"primary",size:"compact",onClick:r,disabled:!i,children:n}),e.jsx(L,{variant:"ghost",size:"compact",onClick:l,children:"Cancel"})]})]})}function Qc(){var E;const{propertyDefinitions:t,loadPropertyDefinitions:a,createPropertyDefinition:r,updatePropertyDefinition:l,deletePropertyDefinition:n}=G(),[s,i]=o.useState("contact"),[d,c]=o.useState(!1),[m,p]=o.useState(Xa),[u,x]=o.useState(null),[w,N]=o.useState(Xa),[h,v]=o.useState(null);o.useEffect(()=>{a()},[a]);const j=o.useMemo(()=>(t??[]).filter(A=>A.entity_type===s).sort((A,U)=>A.sort_order-U.sort_order||A.label.localeCompare(U.label)),[t,s]),f=A=>A.split(",").map(U=>U.trim()).filter(Boolean),z=async()=>{const A=Kc(m.label);if(!A)return;await r({entity_type:s,key:A,label:m.label.trim(),field_type:m.field_type,options:ds.includes(m.field_type)?f(m.options):void 0,required:m.required})&&(c(!1),p(Xa))},y=A=>{x(A.id),N({label:A.label,field_type:A.field_type,options:A.options.join(", "),required:A.required})},b=async()=>{if(!u)return;await l(u,{label:w.label.trim(),options:ds.includes(w.field_type)?f(w.options):void 0,required:w.required})&&x(null)},g=()=>{c(!1),p(Xa)};return e.jsxs("div",{className:"flex-1 overflow-auto",children:[d?e.jsx(vt,{title:"New property",description:"Add a validated property to every record of this type.",onBack:g,backLabel:"Back to properties"}):e.jsx(Xe,{title:"Properties",description:"Define typed properties for contacts, companies, and deals.",actions:e.jsxs(L,{variant:"primary",size:"compact",onClick:()=>c(!0),children:[e.jsx(oe,{size:16}),"Create property"]})}),e.jsx(hr,{"aria-label":"Entity",items:Dl.map(A=>({id:A.key,label:A.label})),value:s,onChange:A=>i(A),className:"px-1 sm:px-3"}),e.jsxs("div",{className:"space-y-3 p-4 pb-[calc(var(--mobile-tab-bar-clearance,0px)+2rem)]",children:[d?e.jsx(zl,{draft:m,setDraft:p,onSubmit:z,onCancel:g,submitLabel:"Create property"}):j.length===0?e.jsx(De,{icon:e.jsx(xr,{size:24,className:"text-[var(--color-accent)]"}),title:`No ${(E=Dl.find(A=>A.key===s))==null?void 0:E.label.toLowerCase()} properties yet`,description:"Define a property to standardize what your team captures.",action:e.jsxs(L,{variant:"primary",size:"default",className:"mt-4",onClick:()=>c(!0),children:[e.jsx(oe,{size:16}),e.jsx("span",{className:"ml-2",children:"Create property"})]})}):e.jsxs("div",{className:"overflow-hidden rounded-lg border border-[var(--color-bg-tertiary)]",children:[e.jsxs("div",{className:"hidden grid-cols-[1fr_120px_1fr_80px_72px] gap-2 bg-[var(--color-bg-secondary)] px-4 py-2 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] md:grid",children:[e.jsx("span",{children:"Label"}),e.jsx("span",{children:"Type"}),e.jsx("span",{children:"Options"}),e.jsx("span",{children:"Required"}),e.jsx("span",{})]}),j.map(A=>u===A.id?e.jsx("div",{className:"px-4 py-3 border-t border-[var(--color-bg-tertiary)]",children:e.jsx(zl,{draft:w,setDraft:N,onSubmit:b,onCancel:()=>x(null),submitLabel:"Save"})},A.id):e.jsxs("div",{"data-testid":`property-definition-${A.key}`,className:"group relative border-t border-[var(--color-bg-tertiary)] px-4 py-3",children:[e.jsxs("div",{className:"pr-20 md:hidden",children:[e.jsx("span",{className:"block truncate text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)]",children:A.label}),e.jsxs("span",{className:"mt-0.5 block break-words text-[length:var(--text-body-s)] leading-[var(--lh-body-s)] text-[var(--color-text-secondary)]",children:[cs[A.field_type]," · ",A.options.length?A.options.join(", "):"No options"," · ",A.required?"Required":"Optional"]})]}),e.jsxs("div",{className:"hidden grid-cols-[1fr_120px_1fr_80px_72px] items-center gap-2 md:grid",children:[e.jsx("span",{className:"truncate text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)]",children:A.label}),e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:cs[A.field_type]}),e.jsx("span",{className:"truncate text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:A.options.length?A.options.join(", "):"—"}),e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:A.required?"Yes":"No"}),e.jsx("span",{"aria-hidden":"true"})]}),e.jsxs("div",{className:"absolute right-3 top-2.5 flex items-center justify-end gap-1 md:top-2",children:[e.jsx("button",{type:"button",onClick:()=>y(A),"aria-label":`Edit ${A.label}`,className:"rounded border border-[var(--color-bg-tertiary)] p-1.5 text-[var(--color-text-secondary)] opacity-0 transition-opacity hover:text-[var(--color-accent)] group-hover:opacity-100 pointer-coarse:opacity-100 focus-visible:opacity-100",children:e.jsx(We,{size:14})}),e.jsx("button",{type:"button",onClick:()=>v(A),"aria-label":`Delete ${A.label}`,className:"rounded border border-[var(--color-bg-tertiary)] p-1.5 text-[var(--color-text-secondary)] opacity-0 transition-opacity hover:text-[var(--color-error)] group-hover:opacity-100 pointer-coarse:opacity-100 focus-visible:opacity-100",children:e.jsx(he,{size:14})})]})]},A.id))]}),!d&&e.jsx("p",{className:"max-w-[72ch] rounded-[var(--radius-md)] bg-[var(--color-bg-secondary)] px-3 py-2 text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:"Deleting a property leaves existing values in place; they simply stop being validated. Values are entered from a record's detail panel."})]}),e.jsx(we,{open:!!h,onOpenChange:A=>{A||v(null)},title:"Delete property",description:`Delete "${(h==null?void 0:h.label)??""}"? Existing values stay on records but stop being validated. This cannot be undone.`,confirmLabel:"Delete property",onConfirm:()=>{h&&(n(h.id),v(null))}})]})}function Hc(t,a){if(a){const r=t.find(l=>l.id===a);if(r)return r}return t.find(r=>r.is_default)??t[0]}const Yc=["subscriber","lead","mql","sql","opportunity","customer","evangelist"];function $l(t,a){var r,l;return a==="name"?t.name:a==="email"?t.email:a==="phone"?t.phone:a==="company"?((r=t.company)==null?void 0:r.name)??null:a==="owner"?((l=t.owner)==null?void 0:l.display_name)??null:a==="last_contacted"?t.last_contacted_at:String(Yc.indexOf(t.lifecycle_stage??"lead")).padStart(2,"0")}function gn(t,a,r){const l=r==="asc"?1:-1;return t.map((n,s)=>({contact:n,index:s})).sort((n,s)=>{const i=$l(n.contact,a),d=$l(s.contact,a);if(i===null&&d!==null)return 1;if(i!==null&&d===null)return-1;if(i===null||d===null)return n.index-s.index;const c=i.localeCompare(d,void 0,{numeric:!0,sensitivity:"base"});return c===0?n.index-s.index:c*l}).map(({contact:n})=>n)}function xs(){ge.error("Stage move blocked",G.getState().error??"Failed to update deal")}const Es=["email","phone","company","lists","stage","owner","last_contacted"],yn="crm.peopleViewMode";
67function Jc(){if(typeof window>"u")return"by-company";try{const t=window.localStorage.getItem(yn);if(t==="by-company"||t==="by-stage"||t==="list")return t}catch{}return"by-company"}function Zc(t){try{window.localStorage.setItem(yn,t)}catch{}}const et={subscriber:"Subscriber",lead:"Lead",mql:"MQL",sql:"SQL",opportunity:"Opportunity",customer:"Customer",evangelist:"Evangelist"},Lt="no-stage";function ms(t){return t===Lt?"No stage":et[t]}const Pt={subscriber:"default",lead:"default",mql:"accent",sql:"accent",opportunity:"warning",customer:"success",evangelist:"success"},Xc={subscriber:"",lead:"",mql:"ring-2 ring-[var(--color-accent)]",sql:"ring-2 ring-[var(--color-accent)]",opportunity:"ring-2 ring-[var(--color-warning)]",customer:"ring-2 ring-[var(--color-success)]",evangelist:"ring-2 ring-[var(--color-success)]"};function Aa({name:t,lifecycleStage:a,size:r="xs",muted:l=!0,src:n}){const s=a??"lead",i=Xc[s]??"";return e.jsx("span",{className:"inline-flex shrink-0 rounded-full","data-testid":"person-avatar","data-lifecycle-ring":s,"data-lifecycle-variant":Pt[s]??"default",title:`${t} — ${et[s]??s}`,children:e.jsx(Je,{name:t,size:r,muted:l,src:n,className:i})})}const za={open:"Open",won:"Won",lost:"Lost"},Ls={open:"accent",won:"success",lost:"error"},fn={note:"Note",call:"Call",email:"Email",meeting:"Meeting",task:"Task",chat:"Chat"},lt="min-w-[6.5rem] shrink-0 flex-1 gap-2 px-3 text-[length:var(--text-body-m)]";function jn({score:t,size:a="sm"}){const l=(s=>s>=80?{bg:"var(--color-success-subtle)",text:"var(--color-success-text)",label:"Hot"}:s>=50?{bg:"var(--color-warning-subtle)",text:"var(--color-warning-text)",label:"Warm"}:s>=20?{bg:"var(--color-accent-subtle)",text:"var(--color-accent-text)",label:"Cool"}:{bg:"var(--color-bg-tertiary)",text:"var(--color-text-tertiary)",label:"Cold"})(t),n=a==="sm";return e.jsxs("span",{className:`inline-flex items-center gap-1 font-medium rounded-full tabular-nums ${n?"px-2 py-0.5 text-[length:var(--text-label-s)]":"px-2 py-0.5 text-[length:var(--text-label-m)]"}`,style:{backgroundColor:l.bg,color:l.text},title:`Lead score: ${t} (${l.label})`,"data-testid":"lead-score-badge",children:[e.jsx("span",{children:t}),!n&&e.jsxs(e.Fragment,{children:[e.jsx("span",{"aria-hidden":"true",style:{opacity:.5},children:"·"}),e.jsx("span",{children:l.label})]})]})}function ed({contactId:t}){const{scoreBreakdown:a,scoreBreakdownLoading:r,loadScoreBreakdown:l}=G(),[n,s]=o.useState(!1);return o.useEffect(()=>{n&&l(t)},[n,t,l]),e.jsxs("div",{children:[e.jsx("button",{onClick:()=>s(!n),className:"text-[length:var(--text-body-m)] text-[var(--color-accent)] hover:underline cursor-pointer",children:n?"Hide breakdown":"View breakdown"}),n&&e.jsx("div",{className:"mt-2 space-y-1",children:r?e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-quaternary)]",children:"Loading…"}):a&&a.length>0?a.map(i=>e.jsxs("div",{className:`flex items-center justify-between px-2 py-1 rounded-[var(--radius-sm)] text-[length:var(--text-label-s)] ${i.matched?"bg-[var(--color-success-subtle)] text-[var(--color-success)]":"bg-[var(--color-bg-secondary)] text-[var(--color-text-quaternary)]"}`,children:[e.jsx("span",{className:"truncate",children:i.ruleName}),e.jsx("span",{className:"font-medium tabular-nums shrink-0 ml-2",children:i.matched?`+${i.points}`:"—"})]},i.ruleId)):e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-quaternary)]",children:"No scoring rules configured"})})]})}function Al({allSelected:t,someSelected:a,onToggleAll:r}){return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-[var(--color-bg-tertiary)] bg-[var(--color-bg-secondary)]",children:[e.jsx("div",{className:"w-5 shrink-0 flex items-center justify-center",children:e.jsx(Ae,{checked:t?!0:a?"indeterminate":!1,onCheckedChange:r,"aria-label":"Select all contacts"})}),e.jsx("span",{className:"flex-[1.7] min-w-[4rem] text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)]",children:"Name"}),e.jsx("span",{className:"flex-[2] min-w-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] hidden @[560px]/contactlist:block",children:"Email"}),e.jsx("span",{className:"flex-1 min-w-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] hidden @[800px]/contactlist:block",children:"Phone"}),e.jsx("span",{className:"flex-1 min-w-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] hidden @[800px]/contactlist:block",children:"Company"}),e.jsx("span",{className:"w-[60px] shrink-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] text-right hidden @[800px]/contactlist:block",children:"Score"}),e.jsx("span",{className:"w-[100px] shrink-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] text-right",children:"Stage"})]})}function Tl({allSelected:t,someSelected:a,onToggleAll:r}){return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-[var(--color-bg-tertiary)] bg-[var(--color-bg-secondary)]",children:[e.jsx("div",{className:"w-5 shrink-0 flex items-center justify-center",children:e.jsx(Ae,{checked:t?!0:a?"indeterminate":!1,onCheckedChange:r,"aria-label":"Select all c
67ompanies"})}),e.jsx("span",{className:"flex-[2] min-w-[4rem] text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)]",children:"Company"}),e.jsx("span",{className:"flex-[2] min-w-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] hidden @[560px]/companylist:block",children:"Industry"}),e.jsx("span",{className:"flex-1 min-w-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] hidden @[800px]/companylist:block",children:"Website"}),e.jsx("span",{className:"flex-1 min-w-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] hidden @[800px]/companylist:block",children:"Email"}),e.jsx("span",{className:"w-[100px] shrink-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] text-right",children:"Stage"})]})}function Nn({contact:t,isActive:a,isSelected:r,onClick:l,onToggleSelect:n}){return e.jsxs("div",{className:`flex items-center gap-3 px-4 py-3 border-b border-[var(--color-bg-tertiary)] cursor-pointer transition-colors overflow-hidden ${r||a?"bg-[var(--color-accent-subtle)]":"hover:bg-[var(--color-bg-secondary)]"}`,onClick:l,children:[e.jsx("div",{className:"w-5 shrink-0 flex items-center justify-center",onClick:s=>s.stopPropagation(),children:e.jsx(Ae,{checked:r,onCheckedChange:n,"aria-label":`Select ${t.name}`})}),e.jsx("div",{className:"flex-[2] min-w-[4rem]",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-7 h-7 rounded-[var(--radius-md)] bg-[var(--color-accent-subtle)] flex items-center justify-center shrink-0",children:e.jsx(Fe,{size:14,className:"text-[var(--color-accent)]"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-[length:var(--text-body-m)] text-[var(--color-accent-text)] truncate font-medium hover:underline block",children:t.name}),t.industry&&e.jsx("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-quaternary)] truncate block @[560px]/companylist:hidden",children:t.industry})]})]})}),e.jsx("span",{className:"flex-[2] min-w-0 text-[length:var(--text-body-m)] text-[var(--color-text-secondary)] truncate hidden @[560px]/companylist:block",children:t.industry||"—"}),e.jsx("span",{className:"flex-1 min-w-0 hidden @[800px]/companylist:flex items-center gap-1",children:t.website?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[length:var(--text-body-m)] text-[var(--color-accent)] truncate hover:underline",children:t.website}),e.jsx(la,{size:12,className:"text-[var(--color-text-quaternary)] shrink-0"})]}):e.jsx("span",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-quaternary)]",children:"—"})}),e.jsx("span",{className:"flex-1 min-w-0 text-[length:var(--text-body-m)] text-[var(--color-text-secondary)] truncate hidden @[800px]/companylist:block",children:t.email||"—"}),e.jsx("div",{className:"w-[100px] shrink-0 flex justify-end",children:e.jsx(de,{variant:t.lifecycle_stage?Pt[t.lifecycle_stage]:"default",children:t.lifecycle_stage?et[t.lifecycle_stage]:"—"})})]})}function wn({contact:t,isActive:a,isSelected:r,onClick:l,onToggleSelect:n}){var s;return e.jsxs("div",{className:`flex items-center gap-3 px-4 py-3 border-b border-[var(--color-bg-tertiary)] cursor-pointer transition-colors overflow-hidden ${r||a?"bg-[var(--color-accent-subtle)]":"hover:bg-[var(--color-bg-secondary)]"}`,onClick:l,children:[e.jsx("div",{className:"w-5 shrink-0 flex items-center justify-center",onClick:i=>i.stopPropagation(),children:e.jsx(Ae,{checked:r,onCheckedChange:n,"aria-label":`Select ${t.name}`})}),e.jsx("div",{className:"flex-[2] min-w-[4rem]",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Aa,{name:t.name,lifecycleStage:t.lifecycle_stage,size:"sm"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-[length:var(--text-body-m)] text-[var(--color-accent)] truncate font-medium hover:underline block",children:t.name}),t.email&&e.jsx("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-secondary)] truncate block @[560px]/contactlist:hidden",children:t.email})]})]})}),e.jsx("span",{className:"flex-[2] min-w-0 hidden @[560px]/contactlist:flex items-center gap-1",children:t.email?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[length:var(--text-body-m)] text-[var(--color-accent)] truncate hover:underline",children:t.email}),e.jsx(la,{size:12,className:"text-[var(--color-text-quaternary)] shrink-0"})]}):e.jsx("span",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-quaternary)]",children:"—"})}),e.jsx("span",{className:"flex-1 min-w-0 text-[length:var(--text-body-m)] text-[var(--color-text-secondary)] truncate hidden @[800px]/contactlist:block",children:t.phone||"—"}),e.jsx("span",{className:"flex-1 min-w-0 text-[length:var(--text-body-m)] text-[var(--color-text-tertiary)] truncate hidden @[800px]/contactlist:block",children:((s=t.company)==null?void 0:s.name)||"—"}),e.jsx("div",{className:"w-[60px] shrink-0 hidden @[800px]/contactlist:flex justify-end",children:e.jsx(jn,{score:t.lead_score})}),e.jsx("div",{className:"w-[100px] shrink-0 flex justify-end",children:e.jsx(de,{variant:t.lifecycle_stage?Pt[t.lifecycle_stage]:"default",children:t.lifecycle_stage?et[t.lifecycle_stage]:"—"})})]})}function td({deal:t,isActive:a,isSelected:r,onClick:l,onToggleSelect:n,onMoveByKeyboard:s,draggable:i=!0}){const{attributes:d,listeners:c,setNodeRef:m,setActivatorNodeRef:p,isDragging:u}=ws({id:t.id,data:{stageId:t.stage_id},disabled:!i});return e.jsx("div",{ref:m,"data-testid":`deal-card-${t.id}`,"data-dragging":u?"true":"false",onClick:l,className:`group relative isolate p-3 rounded-[var(--radius-md)] border transition-colors touch-manipulation has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-[var(--color-accent)] has-[:focus-visible]:ring-offset-2 ${i?"cursor-grab active:cursor-grabbing":"cursor-pointer"} ${u?"opacity-30":""} ${a?"z-10 border-[var(--color-accent)] bg-[var(--color-accent-subtle)]":r?"z-10 border-[var(--color-accent)] border-dashed bg-[var(--color-bg-secondary)]":"border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] hover:border-[var(--color-text-quaternary)] hover:shadow-sm"}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"shrink-0 pt-0.5",onClick:x=>x.stopPropagation(),onPointerDown:x=>x.stopPropagation(),children:e.jsx(Ae,{checked:r,onCheckedChange:n,"aria-label":`Select ${t.title}`})}),e.jsxs("div",{ref:p,...i?d:{},...i?c:{},"aria-label":`Move ${t.title} between stages`,"aria-keyshortcuts":"ArrowLeft ArrowRight",onKeyDown:x=>{s&&(x.key==="ArrowLeft"||x.key==="ArrowRight")&&(x.preventDefault(),s(x.key==="ArrowRight"?"next":"previous"))},className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-primary)] mb-1 leading-snug lg:truncate max-lg:two-line-row-title font-medium",children:t.title}),e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[t.amount!=null&&e.jsx("p",{className:"text-[length:var(--text-body-m)] font-semibold text-[var(--color-text-primary)] tabular-nums",children:Q(t.amount,t.currency??void 0)}),t.owner&&e.jsx("span",{className:"ml-auto shrink-0","aria-label":`Owner: ${t.owner.dis
67play_name}`,children:e.jsx(Je,{src:t.owner.avatar_url,name:t.owner.display_name,size:"xs"})})]}),(t.company||t.contact)&&e.jsxs("div",{className:"mb-1 flex min-w-0 flex-col gap-0.5 text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:[t.company&&e.jsxs("span",{className:"flex min-w-0 items-center gap-1",children:[e.jsx(Fe,{size:12,className:"shrink-0"}),e.jsx("span",{className:"truncate",children:t.company.name})]}),t.contact&&e.jsxs("span",{className:"flex min-w-0 items-center gap-1",children:[e.jsx(Ne,{size:12,className:"shrink-0"}),e.jsx("span",{className:"truncate",children:t.contact.name})]})]}),t.close_date&&e.jsxs("div",{className:"flex items-center gap-1 text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:[e.jsx(ta,{size:12,className:"shrink-0"}),e.jsx("span",{children:wt(t.close_date)})]}),e.jsx(ad,{deal:t})]})]})})}const El={draft:"Quote draft",sent:"Quote sent",viewed:"Quote viewed",accepted:"Quote accepted",rejected:"Quote rejected",expired:"Quote expired"},Ll={draft:"bg-[var(--color-bg-tertiary)] text-[var(--color-text-secondary)]",sent:"bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]",viewed:"bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]",accepted:"bg-[var(--color-success-subtle)] text-[var(--color-success-text)]",rejected:"bg-[var(--color-error-subtle)] text-[var(--color-error-text)]",expired:"bg-[var(--color-warning-subtle)] text-[var(--color-warning-text)]"};function ad({deal:t}){const a=t.line_item_count??0,r=t.quote_status??null;return a===0&&!r?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mt-2","data-testid":"deal-context-chips",children:[a>0&&e.jsxs("span",{"data-testid":"deal-chip-products","data-line-item-count":a,className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)] text-[length:var(--text-label-s)] font-medium",title:`${a} product${a===1?"":"s"} on this deal`,children:[e.jsx(Ct,{size:10,className:"shrink-0"}),e.jsxs("span",{children:[a," product",a===1?"":"s"]})]}),r&&e.jsxs("span",{"data-testid":"deal-chip-quote","data-quote-status":r,className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[length:var(--text-label-s)] font-medium ${Ll[r]??Ll.draft}`,title:El[r]??"Quote",children:[e.jsx(ot,{size:10,className:"shrink-0"}),e.jsx("span",{children:El[r]??"Quote"})]})]})}function Il({allSelected:t,someSelected:a,onToggleAll:r}){return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-[var(--color-bg-tertiary)] bg-[var(--color-bg-secondary)]",children:[e.jsx("div",{className:"w-5 shrink-0 flex items-center justify-center",children:e.jsx(Ae,{checked:t?!0:a?"indeterminate":!1,onCheckedChange:r,"aria-label":"Select all deals"})}),e.jsx("span",{className:"flex-[2] min-w-[4rem] text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)]",children:"Deal"}),e.jsx("span",{className:"flex-[1.3] min-w-[10rem] text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] hidden @[720px]/deallist:block",children:"Company · Contact"}),e.jsx("span",{className:"w-[96px] min-[480px]:w-[110px] shrink-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] text-right tabular-nums",children:"Amount"}),e.jsx("span",{className:"w-[110px] shrink-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] hidden @[920px]/deallist:block",children:"Stage"}),e.jsx("span",{className:"w-[70px] shrink-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] text-right hidden @[820px]/deallist:block",children:"Status"}),e.jsx("span",{className:"w-[100px] shrink-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] hidden @[1000px]/deallist:block",children:"Close date"}),e.jsx("span",{className:"w-[28px] shrink-0 max-[479px]:hidden","aria-hidden":"true"})]})}function Is({deal:t,isActive:a,isSelected:r,onClick:l,onToggleSelect:n}){var s,i,d;return e.jsxs("div",{className:`flex items-center gap-3 px-4 py-3 border-b cursor-pointer transition-colors ${a?"bg-[var(--color-accent-subtle)] border-[var(--color-accent)]":r?"bg-[var(--color-bg-secondary)] border-[var(--color-accent)] border-dashed":"border-[var(--color-bg-tertiary)] hover:bg-[var(--color-bg-secondary)]"}`,onClick:l,children:[e.jsx("div",{className:"w-5 shrink-0 flex items-center justify-center",onClick:c=>c.stopPropagation(),children:e.jsx(Ae,{checked:r,onCheckedChange:n,"aria-label":`Select ${t.title}`})}),e.jsxs("div",{className:"flex-[1.7] min-w-[4rem]",children:[e.jsx("span",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-accent-text)] hover:underline line-clamp-2 whitespace-normal @[720px]/deallist:block @[720px]/deallist:truncate @[720px]/deallist:line-clamp-none @[720px]/deallist:whitespace-nowrap",children:t.title}),(t.company||t.contact||t.stage)&&e.jsxs("span",{className:`@[720px]/deallist:hidden flex items-center gap-1.5 text-[length:var(--text-label-s)] min-[480px]:truncate mt-0.5 ${a?"text-[var(--color-text-secondary)]":"text-[var(--color-text-tertiary)]"}`,children:[t.status!=="open"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:t.
67status==="lost"?"text-[var(--color-error-text)]":"text-[var(--color-success-text)]",children:za[t.status]||t.status}),e.jsx("span",{className:"text-[var(--color-text-quaternary)]",children:"·"})]}),t.stage&&e.jsxs("span",{className:"inline-flex items-center gap-1 shrink-0",children:[e.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-[var(--color-module-crm)]"}),e.jsx("span",{children:t.stage.name}),(t.company||t.contact)&&e.jsx("span",{className:"text-[var(--color-text-quaternary)]",children:"·"})]}),((s=t.company)==null?void 0:s.name)??((i=t.contact)==null?void 0:i.name)]})]}),e.jsx("div",{className:"flex-[1.3] min-w-[10rem] hidden @[720px]/deallist:flex flex-col items-start justify-center text-[length:var(--text-body-m)] text-[var(--color-text-secondary)]",children:t.company?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex w-full min-w-0 items-center gap-1",children:[e.jsx(Fe,{size:12,className:"shrink-0 text-[var(--color-text-quaternary)]"}),e.jsx("span",{className:"truncate",children:t.company.name})]}),t.contact&&e.jsx("span",{className:`w-full truncate pl-4 text-[length:var(--text-label-s)] ${a?"text-[var(--color-text-secondary)]":"text-[var(--color-text-tertiary)]"}`,children:t.contact.name})]}):t.contact?e.jsxs("span",{className:"flex w-full min-w-0 items-center gap-1",children:[e.jsx(Ne,{size:12,className:"shrink-0 text-[var(--color-text-quaternary)]"}),e.jsx("span",{className:"truncate",children:t.contact.name})]}):e.jsx("span",{className:"text-[var(--color-text-quaternary)]",children:"—"})}),e.jsx("span",{className:"w-[96px] min-[480px]:w-[110px] shrink-0 text-right text-[length:var(--text-body-m)] font-semibold text-[var(--color-text-primary)] tabular-nums",children:t.amount!=null?Q(t.amount,t.currency??void 0):"—"}),e.jsx("span",{className:"w-[110px] shrink-0 text-[length:var(--text-body-m)] text-[var(--color-text-secondary)] truncate hidden @[920px]/deallist:block",children:((d=t.stage)==null?void 0:d.name)||"—"}),e.jsx("div",{className:"w-[70px] shrink-0 hidden @[820px]/deallist:flex justify-end",children:e.jsx(de,{variant:Ls[t.status]||"default",className:t.status==="open"?"text-[var(--color-text-primary)]":void 0,children:za[t.status]||t.status})}),e.jsx("span",{className:"w-[100px] shrink-0 text-[length:var(--text-body-m)] text-[var(--color-text-tertiary)] tabular-nums hidden @[1000px]/deallist:block",children:t.close_date?wt(t.close_date):"—"}),e.jsx("div",{className:"w-[28px] shrink-0 flex justify-end max-[479px]:hidden",children:t.owner&&e.jsx("span",{"aria-label":`Owner: ${t.owner.dis
67play_name}`,children:e.jsx(Je,{src:t.owner.avatar_url,name:t.owner.display_name,size:"xs"})})})]})}function rd({deals:t,activeDealId:a,selectedDealIds:r,onSelectDeal:l,onToggleDealSelect:n,onToggleAll:s}){const i=o.useRef(null),d=ks({count:t.length,getScrollElement:()=>i.current,estimateSize:()=>48,overscan:10}),c=t.length>0&&t.every(p=>r.has(p.id)),m=!c&&t.some(p=>r.has(p.id));return t.length===0?e.jsxs("div",{className:"@container/deallist flex-1 flex flex-col",children:[e.jsx(Il,{allSelected:!1,someSelected:!1,onToggleAll:s}),e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx("p",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-quaternary)]",children:"No deals match your filters"})})]}):e.jsxs("div",{className:"@container/deallist flex-1 flex flex-col min-h-0",children:[e.jsx(Il,{allSelected:c,someSelected:m,onToggleAll:s}),e.jsx("div",{ref:i,className:"flex-1 overflow-y-auto",children:e.jsx("div",{style:{height:`${d.getTotalSize()}px`,width:"100%",position:"relative"},children:d.getVirtualItems().map(p=>{const u=t[p.index];return e.jsx("div",{ref:d.measureElement,"data-index":p.index,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${p.start}px) translateZ(0)`,willChange:"transform"},children:e.jsx(Is,{deal:u,isActive:a===u.id,isSelected:r.has(u.id),onClick:()=>l(u.id),onToggleSelect:()=>n(u.id)})},p.key)})})})]})}function Pl({groups:t,activeDealId:a,selectedDealIds:r,onSelectDeal:l,onToggleDealSelect:n,emptyMessage:s,onShowAll:i,totalLabel:d}){return t.length===0?e.jsx("div",{className:"flex-1 flex items-center justify-center p-6",children:e.jsx(De,{icon:e.jsx(Se,{size:28,className:"text-[var(--color-success)]"}),title:"Nothing needs attention",description:s,action:i?e.jsx(L,{variant:"secondary",onClick:i,children:"View all deals"}):void 0})}):e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-[var(--color-bg-secondary)] p-3 md:p-4 space-y-3","data-testid":"crm-pipeline-grouped-view",children:t.map(c=>{const m=c.deals.reduce((p,u)=>p+(u.amount??0),0);return e.jsxs("section",{className:"@container/deallist rounded-[var(--radius-lg)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 border-b border-[var(--color-bg-tertiary)]",children:[e.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[e.jsx("h3",{className:"truncate text-[length:var(--text-body-m)] font-semibold text-[var(--color-text-primary)]",children:c.label}),e.jsx(de,{variant:"default",children:c.deals.length}),c.meta&&e.jsx("span",{className:"hidden sm:inline text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:c.meta})]}),e.jsxs("span",{className:"shrink-0 text-right text-[length:var(--text-label-m)] font-medium tabular-nums text-[var(--color-text-secondary)]",children:[d&&e.jsx("span",{className:"mr-1 font-normal text-[var(--color-text-tertiary)]",children:d}),Q(m)]})]}),c.deals.map(p=>e.jsx(Is,{deal:p,isActive:a===p.id,isSelected:r.has(p.id),onClick:()=>l(p.id),onToggleSelect:()=>n(p.id)},p.id))]},c.id)})})}const sd=40;function Rl({contacts:t,activeContactId:a,selectedContactIds:r,selectContact:l,toggleContactSelect:n,rowComponent:s}){const i=o.useRef(null),d=G(p=>p.loadContacts),c=s==="company"?Nn:wn,m=ks({count:t.length,getScrollElement:()=>i.current,estimateSize:()=>sd,overscan:10});return e.jsx(ei,{onRefresh:d,scrollRef:i,children:e.jsx("div",{ref:i,className:"flex-1 overflow-y-auto",children:e.jsx("div",{style:{height:`${m.getTotalSize()}px`,width:"100%",position:"relative"},children:m.getVirtualItems().map(p=>{const u=t[p.index];return e.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:`${p.size}px`,transform:`translateY(${p.start}px) translateZ(0)`,willChange:"transform"},children:e.jsx(c,{contact:u,isActive:a===u.id,isSelected:r.has(u.id),onClick:()=>l(u.id),onToggleSelect:()=>n(u.id)})},p.key)})})})})}function ld({stage:t,deals:a,activeDealId:r,selectedDealIds:l,onSelectDeal:n,onToggleDealSelect:s,onMoveDealByKeyboard:i,onCreateDealInStage:d}){const c=a.reduce((x,w)=>x+(w.amount||0),0),{setNodeRef:m,isOver:p}=Ns({id:`stage:${t.id}`,data:{stageId:t.id}}),u=a.length===0;return e.jsxs("div",{className:"flex h-full min-h-0 min-w-[calc(100vw-2rem)] max-w-[calc(100vw-2rem)] flex-1 flex-col max-sm:flex-none max-sm:snap-center sm:min-w-[180px] sm:max-w-[300px]",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-3 mb-2 rounded-[var(--radius-md)] bg-[var(--color-bg-secondary)]",children:[e.jsx("span",{className:"text-[length:var(--text-title-s)] leading-[var(--lh-title-s)] font-semibold text-[var(--color-text-primary)] truncate",children:t.name}),e.jsx("span",{className:"inline-flex items-center justify-center min-w-[20px] h-5 px-2 rounded-full bg-[var(--color-bg-tertiary)] text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] tabular-nums shrink-0",children:a.length}),c>0&&e.jsx("span",{className:"text-[length:var(--text-title-s)] leading-[var(--lh-title-s)] text-[var(--color-text-primary)] ml-auto tabular-nums shrink-0 font-semibold",children:Q(c)})]}),e.jsxs("div",{ref:m,"data-testid":`stage-column-${t.id}`,"data-empty":u?"true":"false","data-over":p?"true":"false",className:`min-h-0 flex-1 overflow-y-auto rounded-[var(--radius-md)] transition-colors ${u?`flex flex-col items-center justify-start gap-2 py-3 px-2 border border-dashed max-sm:min-h-20 ${p?"bg-[var(--color-accent-subtle)] border-[var(--color-accent)]":"border-[var(--color-bg-tertiary)]"}`:`space-y-2 px-0.5 ${p?"bg-[var(--color-accent-subtle)] outline outline-2 outline-[var(--color-accent)]":""}`}`,children:[a.map(x=>e.jsx(td,{deal:x,isActive:r===x.id,isSelected:l.has(x.id),onClick:()=>n(x.id),onToggleSelect:()=>s(x.id),onMoveByKeyboard:w=>i==null?void 0:i(x,w)},x.id)),u&&(d?e.jsxs("button",{type:"button",onClick:()=>d(t.id),"data-testid":`stage-column-${t.id}-add-deal`,"aria-label":`Add deal to ${t.name}`,className:"inline-flex w-full items-center justify-center gap-2 px-3 py-2 pointer-coarse:min-h-11 pointer-coarse:h-11 pointer-coarse:py-0 rounded-[var(--radius-sm)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[length:var(--text-label-m)
67] font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-accent)] hover:border-[var(--color-accent)] hover:bg-[var(--color-accent-subtle)] transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]",children:[e.jsx(oe,{size:14}),e.jsx("span",{className:"truncate",children:"Add deal"})]}):e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-quaternary)] text-center py-2",children:"No deals"}))]})]})}function ft({icon:t,label:a,onClick:r,variant:l="default",disabled:n=!1}){return e.jsxs("button",{onClick:r,disabled:n,className:`flex pointer-coarse:min-h-11 items-center gap-2 px-3 py-2 md:py-1 rounded-[var(--radius-sm)] text-[length:var(--text-label-m)] font-medium transition-colors ${n?"bg-[var(--color-bg-tertiary)] opacity-50 cursor-not-allowed":l==="destructive"?"bg-[var(--color-error-subtle)] text-[var(--color-text-primary)] hover:bg-[var(--color-error-subtle-strong)] [&_svg]:text-[var(--color-error)] cursor-pointer":"bg-[var(--color-bg-primary)] hover:bg-[var(--color-bg-tertiary)] cursor-pointer"}`,children:[t,a]})}function qe({trigger:t,items:a}){return e.jsxs(dt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{className:"flex items-center gap-2 px-3 py-1 pointer-coarse:min-h-11 rounded-[var(--radius-sm)] text-[length:var(--text-label-m)] font-medium bg-[var(--color-bg-primary)] hover:bg-[var(--color-bg-tertiary)] transition-colors cursor-pointer",children:t})}),e.jsx(mt,{align:"end",sideOffset:4,className:"min-w-[200px]",children:a.map(r=>r.separator?e.jsx(ra,{},r.id):r.subItems?e.jsxs(Io,{children:[e.jsxs(Po,{className:"gap-2",children:[r.icon,r.label]}),e.jsx(Ro,{className:"max-h-[300px] overflow-y-auto",children:r.subItems.map(l=>e.jsxs(be,{onSelect:l.onClick,className:"gap-2",children:[l.icon,l.label]},l.id))})]},r.id):e.jsxs(be,{onSelect:r.onClick,disabled:r.disabled,className:`gap-2 ${r.destructive?"text-[var(--color-error)]":""}`,children:[r.icon,r.label]},r.id))})]})}const Fl={gray:"var(--color-text-quaternary)",accent:"var(--color-accent)",purple:"var(--color-purple)",pink:"var(--color-pink)",cyan:"var(--color-cyan)",orange:"var(--color-orange)",success:"var(--color-success)",warning:"var(--color-warning)"};function us({color:t}){return e.jsx("span",{"aria-hidden":!0,className:"h-2 w-2 rounded-full shrink-0",style:{background:Fl[t]??Fl.gray}})}function Ps({contact:t,compact:a=!1}){const r=G(x=>x.contactGroups),l=G(x=>x.contactGroupsLoaded),n=G(x=>x.contactGroupsLoading),s=G(x=>x.loadContactGroups),i=G(x=>x.setContactGroupMembership),[d,c]=o.useState(null);o.useEffect(()=>{!l&&!n&&s()},[l,n,s]);const m=new Set((t.groups??[]).map(x=>x.id)),p=r.filter(x=>m.has(x.id)),u=async x=>{const w=!m.has(x.id);c(x.id);const N=await i(x.id,t.id,w);c(null),N&&ge.success(w?`Added to ${x.name}`:`Removed from ${x.name}`)};return e.jsxs(dt,{children:[e.jsx(xt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:x=>x.stopPropagation(),className:a?"flex min-h-8 max-w-full items-center gap-1 rounded-[var(--radius-sm)] px-1.5 text-left text-[length:var(--text-label-s)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-tertiary)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent)]":"flex min-h-10 w-full items-center justify-between gap-2 rounded-[var(--radius-md)] border border-[var(--color-text-tertiary)] bg-[var(--color-bg-primary)] px-3 text-left text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] hover:border-[var(--color-text-secondary)] hover:bg-[var(--color-bg-secondary)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent)]","aria-label":`Edit lists for ${t.name}`,"data-testid":"contact-lists-editor",children:[e.jsx("span",{className:"flex min-w-0 items-center gap-1 overflow-hidden",children:p.length===0?e.jsx("span",{className:"text-[var(--color-text-secondary)]",children:"Add to list"}):e.jsxs(e.Fragment,{children:[p.slice(0,a?1:2).map(x=>e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1 rounded-[var(--radius-sm)] bg-[var(--color-bg-tertiary)] px-1.5 py-0.5",children:[e.jsx(us,{color:x.color}),e.jsx("span",{className:"truncate",children:x.name})]},x.id)),p.length>(a?1:2)&&e.jsxs("span",{className:"shrink-0",children:["+",p.length-(a?1:2)]})]})}),e.jsx(ye,{size:12,className:"shrink-0"})]})}),e.jsx(mt,{align:"start",className:"w-60",onClick:x=>x.stopPropagation(),children:n?e.jsx(be,{disabled:!0,children:"Loading lists…"}):r.length===0?e.jsx(be,{disabled:!0,children:"No lists yet — create one in the sidebar"}):r.map(x=>{const w=m.has(x.id);return e.jsxs(be,{role:"menuitemcheckbox","aria-checked":w,disabled:d===x.id,onSelect:()=>{u(x)},children:[w?e.jsx(Se,{size:14}):e.jsx(yr,{size:14}),e.jsx(us,{color:x.color}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:x.name}),e.jsx("span",{className:"text-[length:var(--text-label-s)] tabular-nums text-[var(--color-text-quaternary)]",children:x.member_count})]},x.id)})})]})}
67function nd({count:t,entityName:a,onClearSelection:r,onDelete:l,onAssignOwner:n,onSetLifecycle:s,onAddToGroup:i,onCreateGroup:d,onExport:c,onExportVCard:m,onSendEmail:p,sendEmailDisabled:u,onMailMerge:x,onMerge:w}){const{workspaceUsers:N,loadWorkspaceUsers:h,contactGroups:v,contactGroupsLoading:j,loadContactGroups:f}=G();o.useEffect(()=>{N.length===0&&h()},[N.length,h]);const z=o.useRef(!1);o.useEffect(()=>{i&&!z.current&&(z.current=!0,f())},[i,f]);const y=N.length===0?[{id:"empty",label:"No workspace users found"}]:N.map(E=>({id:E.id,label:E.is_self?`${E.display_name} (me)`:E.display_name,icon:e.jsx(Ne,{size:14}),onClick:()=>n(E.id)})),b=Object.keys(et).map(E=>({id:E,label:et[E],onClick:()=>s(E)})),g=(()=>{const E=v.length===0?[{id:"empty",label:j?"Loading lists…":"No lists — create one first"}]:v.map(A=>({id:A.id,label:`${A.name} (${A.member_count})`,icon:e.jsx(us,{color:A.color}),onClick:()=>i==null?void 0:i(A.id)}));return d&&(E.push({id:"sep-create-group",label:"",separator:!0}),E.push({id:"create-new-group",label:"Create new list…",icon:e.jsx(oe,{size:14}),onClick:d})),E})();return e.jsxs("div",{"data-testid":"contact-bulk-actions-bar",role:"toolbar","aria-label":`Bulk actions for ${t} selected ${a}${t!==1?"s":""}`,className:"flex items-center gap-3 px-4 py-2 border-y border-[var(--color-accent)] bg-[var(--color-accent-subtle)] text-[var(--color-text-primary)] max-md:flex-col max-md:items-stretch max-md:gap-2",children:[e.jsxs("div",{className:"flex min-h-8 items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-[length:var(--text-label-l)] font-medium tabular-nums",children:[t," ",a,t!==1?"s":""," selected"]}),e.jsxs("button",{onClick:r,className:"hidden max-md:flex min-h-11 items-center gap-1 rounded-[var(--radius-sm)] px-2 text-[length:var(--text-label-m)] hover:bg-[var(--color-bg-tertiary)] transition-colors cursor-pointer",children:[e.jsx(ze,{size:14}),"Clear"]})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-auto flex-wrap max-md:hidden",children:[e.jsx(qe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ne,{size:14}),"Assign owner",e.jsx(ye,{size:12})]}),items:y}),e.jsx(qe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ct,{size:14}),"Set lifecycle",e.jsx(ye,{size:12})]}),items:b}),i&&e.jsx(qe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(ja,{size:14}),"Add to list",e.jsx(ye,{size:12})]}),items:g}),p&&e.jsx(ft,{icon:e.jsx(Be,{size:14}),label:"Send email",onClick:p,disabled:u}),x&&e.jsx(ft,{icon:e.jsx(ht,{size:14}),label:"Mail merge",onClick:x,disabled:u}),e.jsx(ft,{icon:e.jsx(Ee,{size:14}),label:"Export CSV",onClick:c}),e.jsx(ft,{icon:e.jsx(Ee,{size:14}),label:"Export vCard",onClick:m}),t===2&&w&&e.jsx(ft,{icon:e.jsx(Sa,{size:14}),label:"Merge",onClick:w}),e.jsx(ft,{icon:e.jsx(he,{size:14}),label:"Delete",onClick:l,variant:"destructive"}),e.jsxs("button",{onClick:r,className:"flex items-center gap-1 px-2 py-1 rounded-[var(--radius-sm)] text-[length:var(--text-label-m)] hover:bg-[var(--color-bg-tertiary)] transition-colors cursor-pointer",children:[e.jsx(ze,{size:14}),"Clear"]})]}),e.jsxs("div",{className:"hidden max-md:flex items-center gap-2 overflow-x-auto mobile-toolbar-scroll whitespace-nowrap pb-0.5",children:[e.jsx(qe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ne,{size:14}),"Assign",e.jsx(ye,{size:12})]}),items:y}),e.jsx(qe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ct,{size:14}),"Lifecycle",e.jsx(ye,{size:12})]}),items:b}),e.jsx(qe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx($a,{size:14}),"More",e.jsx(ye,{size:12})]}),items:[...i?[{id:"groups",label:"Add to list",icon:e.jsx(ja,{size:14}),subItems:g}]:[],...p?[{id:"email",label:"Send email",icon:e.jsx(Be,{size:14}),onClick:p,disabled:u}]:[],...x?[{id:"mail-merge",label:"Mail merge",icon:e.jsx(ht,{size:14}),onClick:x,disabled:u}]:[],{id:"export-csv",label:"Export CSV",icon:e.jsx(Ee,{size:14}),onClick:c},{id:"export-vcard",label:"Export vCard",icon:e.jsx(Ee,{size:14}),onClick:m},...t===2&&w?[{id:"merge",label:"Merge",icon:e.jsx(Sa,{size:14}),onClick:w}]:[],{id:"delete",label:"Delete",icon:e.jsx(he,{size:14}),onClick:l,destructive:!0}]})]})]})}function od({count:t,stages:a,onClearSelection:r,onDelete:l,onAssignOwner:n,onChangeStage:s,onSetStatus:i,onExport:d}){const{workspaceUsers:c,loadWorkspaceUsers:m}=G();o.useEffect(()=>{c.length===0&&m()},[c.length,m]);const p=c.length===0?[{id:"empty",label:"No workspace users found"}]:c.map(w=>({id:w.id,label:w.is_self?`${w.display_name} (me)`:w.display_name,icon:e.jsx(Ne,{size:14}),onClick:()=>n(w.id)})),u=a.length===0?[{id:"empty",label:"No stages available"}]:a.map(w=>({id:w.id,label:w.name,onClick:()=>s(w.id)}
67)),x=[{id:"open",label:"Open",icon:e.jsx(yr,{size:14}),onClick:()=>i("open")},{id:"won",label:"Mark as Won",icon:e.jsx(Se,{size:14}),onClick:()=>i("won")},{id:"lost",label:"Mark as Lost",icon:e.jsx(gr,{size:14}),onClick:()=>i("lost")}];return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2 border-y border-[var(--color-accent)] bg-[var(--color-accent-subtle)] text-[var(--color-text-primary)] max-md:flex-col max-md:items-stretch max-md:gap-2",children:[e.jsxs("div",{className:"flex min-h-8 items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-[length:var(--text-label-l)] font-medium tabular-nums",children:[t," deal",t!==1?"s":""," selected"]}),e.jsxs("button",{onClick:r,className:"hidden max-md:flex min-h-11 items-center gap-1 rounded-[var(--radius-sm)] px-2 text-[length:var(--text-label-m)] hover:bg-[var(--color-bg-tertiary)] transition-colors cursor-pointer",children:[e.jsx(ze,{size:14}),"Clear"]})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-auto flex-wrap max-md:hidden",children:[e.jsx(qe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ne,{size:14}),"Assign owner",e.jsx(ye,{size:12})]}),items:p}),e.jsx(qe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Nt,{size:14}),"Move stage",e.jsx(ye,{size:12})]}),items:u}),e.jsx(qe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(ka,{size:14}),"Status",e.jsx(ye,{size:12})]}),items:x}),e.jsx(ft,{icon:e.jsx(Ee,{size:14}),label:"Export CSV",onClick:d}),e.jsx(ft,{icon:e.jsx(he,{size:14}),label:"Delete",onClick:l,variant:"destructive"}),e.jsxs("button",{onClick:r,className:"flex items-center gap-1 px-2 py-1 rounded-[var(--radius-sm)] text-[length:var(--text-label-m)] hover:bg-[var(--color-bg-tertiary)] transition-colors cursor-pointer",children:[e.jsx(ze,{size:14}),"Clear"]})]}),e.jsxs("div",{className:"hidden max-md:flex items-center gap-2 overflow-x-auto mobile-toolbar-scroll whitespace-nowrap pb-0.5",children:[e.jsx(qe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ne,{size:14}),"Assign",e.jsx(ye,{size:12})]}),items:p}),e.jsx(qe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Nt,{size:14}),"Stage",e.jsx(ye,{size:12})]}),items:u}),e.jsx(qe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx($a,{size:14}),"More",e.jsx(ye,{size:12})]}),items:[{id:"status",label:"Set status",icon:e.jsx(ka,{size:14}),subItems:x},{id:"export-csv",label:"Export CSV",icon:e.jsx(Ee,{size:14}),onClick:d},{id:"delete",label:"Delete",icon:e.jsx(he,{size:14}),onClick:l,destructive:!0}]})]})]})}function Jr({page:t,totalItems:a,perPage:r,onPageChange:l}){const n=Math.max(1,Math.ceil(a/r));if(a<=r)return null;const s=(t-1)*r+1,i=Math.min(t*r,a);return e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-t border-[var(--color-bg-tertiary)] bg-[var(--color-bg-secondary)]",children:[e.jsxs("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)] tabular-nums",children:[s,"–",i," of ",a]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>l(t-1),disabled:t<=1,className:"p-1 rounded-[var(--radius-sm)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-tertiary)] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition-colors","aria-label":"Previous page",children:e.jsx(Xl,{size:16})}),Array.from({length:n},(d,c)=>c+1).filter(d=>d===1||d===n||Math.abs(d-t)<=1).reduce((d,c,m,p)=>(m>0&&c-p[m-1]>1&&d.push("ellipsis"),d.push(c),d),[]).map((d,c)=>d==="ellipsis"?e.jsx("span",{className:"px-1 text-[length:var(--text-label-s)] text-[var(--color-text-quaternary)]",children:"…"},`e${c}`):e.jsx("button",{onClick:()=>l(d),className:`min-w-[28px] h-7 px-2 rounded-[var(--radius-sm)] text-[length:var(--text-label-m)] font-medium tabular-nums transition-colors cursor-pointer ${d===t?"bg-[var(--color-accent)] text-[var(--color-text-on-accent)]":"text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-tertiary)]"}`,children:d},d)),e.jsx("button",{onClick:()=>l(t+1),disabled:t>=n,className:"p-1 rounded-[var(--radius-sm)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-tertiary)] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition-colors","aria-label":"Next page",children:e.jsx(Ue,{size:16})})]})]})}function id({contact:t,companies:a,allPersons:r,activities:l,contactDeals:n,loading:s,contactDetailLoa
67ding:i,onClose:d,onUpdate:c,onDelete:m,onLogActivity:p,onSelectCompany:u,onSelectDeal:x,onCreateDeal:w,onMergeWith:N,backStack:h,onBackStackPop:v}){var F,le,X;const[j,f]=o.useState(!1),[z,y]=o.useState(!1),[b,g]=o.useState(!1),[E,A]=o.useState(!1),[U,D]=o.useState("details"),[O,P]=o.useState(0),H=G(T=>T.workspaceUsers),ae=G(T=>T.loadWorkspaceUsers);o.useEffect(()=>{H.length===0&&ae()},[H.length,ae]);const I=G(T=>T.propertyDefinitions),k=G(T=>T.loadPropertyDefinitions);o.useEffect(()=>{I.length===0&&k()},[I.length,k]);const C=[];if(h&&h.length>0&&v)for(let T=0;T<h.length;T++){const W=h[T];C.push({label:W.label||(W.kind==="deal"?"Deal":W.kind==="company"?"Company":"Contact"),onClick:()=>v(T)})}if(s)return e.jsx(Zt,{open:!0,title:"Contact details",onClose:d,size:"lg",resizable:!0,widthStorageKey:"crm-contact-detail-width",className:"max-md:!bottom-[var(--mobile-tab-bar-clearance,0px)] max-md:!h-auto max-md:!max-w-none md:max-w-[50%]",mobileBreakpoint:"md",mobileMode:"full-screen",hideCloseButton:!0,headerSlot:e.jsx(aa,{title:"Contact",breadcrumb:C.length>0?C:void 0,onClose:d}),children:e.jsx("div",{className:"p-4 space-y-4",children:e.jsx(js,{})})});const _=async()=>{d(),await m(t.id)&&ge.success("Contact deleted")},Z=T=>{c(t.id,{lifecycle_stage:T})},B=T=>{D(T)},V=n.filter(T=>T.status==="open").reduce((T,W)=>T+(W.amount||0),0);return e.jsx(Zt,{open:!0,title:"Contact details",onClose:d,size:"lg",resizable:!0,widthStorageKey:"crm-contact-detail-width",className:"max-md:!bottom-[var(--mobile-tab-bar-clearance,0px)] max-md:!h-auto max-md:!max-w-none md:max-w-[50%]",mobileBreakpoint:"md",mobileMode:"full-screen",mobileHeaderScrollsAway:!0,hideCloseButton:!0,headerSlot:e.jsx(aa,{title:e.jsx(Le,{value:t.name,onSave:T=>c(t.id,{name:T}).then(()=>{}),placeholder:"Contact name",emptyLabel:"Add name",ariaLabel:"Edit contact name",textClassName:"block w-full text-[length:var(--text-title-l)] max-md:text-[length:var(--text-headline-s)] font-semibold text-[var(--color-text-primary)]"}),contextLabel:"Contact",subtitle:((F=t.company)==null?void 0:F.name)||void 0,breadcrumb:C.length>0?C:void 0,onClose:d,extraActions:e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>B("activity"),className:"hidden h-8 items-center gap-1 rounded-md px-2 text-[length:var(--text-label-s)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-tertiary)] hover:text-[var(--color-text-primary)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent)] md:inline-flex",title:"Jump to activity","aria-label":"Jump to activity",children:[e.jsx(ea,{size:14}),"Timeline"]}),e.jsx("button",{onClick:()=>A(!0),className:"hidden h-8 w-8 items-center justify-center rounded-md text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-tertiary)] hover:text-[var(--color-text-primary)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent)] md:inline-flex",title:"Merge with another contact","aria-label":"Merge contact",children:e.jsx(Sa,{size:16})}),e.jsx("button",{onClick:()=>f(!0),className:"hidden h-8 w-8 items-center justify-center rounded-md text-[var(--color-text-tertiary)] hover:bg-[var(--color-error-subtle)] hover:text-[var(--color-error)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent)] md:inline-flex",title:"Delete contact","aria-label":"Delete contact",children:e.jsx(he,{size:16})})]}),mobileOverflowActions:e.jsxs(e.Fragment,{children:[e.jsxs(be,{onSelect:()=>B("activity"),children:[e.jsx(ea,{size:14})," Timeline"]}),e.jsxs(be,{onSelect:()=>A(!0),children:[e.jsx(Sa,{size:14})," Merge contact"]}),e.jsx(ra,{}),e.jsxs(be,{onSelect:()=>f(!0),className:"text-[var(--color-error-text)]",children:[e.jsx(he,{size:14})," Delete contact"]})]})}),children:e.jsxs("div",{className:"space-y-4 p-4 pb-[calc(var(--mobile-tab-bar-clearance,0px)+2rem)]",children:[e.jsxs("div",{className:"mobile-toolbar-scroll flex gap-2 overflow-x-auto pb-1","aria-label":"Contact actions",children:[e.jsxs(L,{variant:"primary",size:"compact",className:lt,disabled:!t.email,onClick:()=>t.email&&ut.getState().open("mail",{initialData:{to:t.email}}),children:[e.jsx(Be,{size:14,className:"shrink-0"}),e.jsx("span",{children:"Email"}
67),!t.email&&e.jsx(ze,{size:10,className:"shrink-0","aria-label":"Unavailable"})]}),e.jsxs(L,{variant:"secondary",size:"compact",className:lt,disabled:!t.phone,onClick:()=>{t.phone&&(window.location.href=`tel:${t.phone}`)},children:[e.jsx(kt,{size:14,className:"shrink-0"}),e.jsx("span",{children:"Call"}),!t.phone&&e.jsx(ze,{size:10,className:"shrink-0","aria-label":"Unavailable"})]}),e.jsxs(L,{variant:"secondary",size:"compact",className:lt,onClick:()=>ut.getState().open("calendar"),children:[e.jsx(ta,{size:14}),e.jsx("span",{children:"Meet"})]}),e.jsxs(L,{variant:"secondary",size:"compact",className:lt,onClick:()=>ut.getState().open("tasks",{initialData:{contact_id:t.id},onCreated:()=>P(T=>T+1)}),children:[e.jsx(Se,{size:14,className:"shrink-0"}),e.jsx("span",{children:"Task"})]}),e.jsxs(L,{variant:"secondary",size:"compact",className:lt,onClick:()=>y(!0),children:[e.jsx(Ds,{size:14}),e.jsx("span",{children:"Note"})]})]}),e.jsx("nav",{"aria-label":"Contact sections",role:"tablist",className:"sticky top-0 z-10 -mx-4 flex gap-1 border-b border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] px-4",children:["activity","details","related"].map(T=>e.jsx("button",{type:"button",id:`contact-${T}-tab`,role:"tab","aria-selected":U===T,"aria-controls":`contact-${T}-section`,onClick:()=>B(T),className:`h-10 border-b-2 px-3 text-[length:var(--text-body-m)] font-medium capitalize transition-colors ${U===T?"border-[var(--color-accent)] text-[var(--color-accent-text)]":"border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"}`,children:T},T))}),e.jsxs("div",{id:"contact-details-section",role:"tabpanel","aria-labelledby":"contact-details-tab",hidden:U!=="details",className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3 max-md:order-0",children:[e.jsx("div",{className:"w-10 h-10 rounded-[var(--radius-lg)] bg-[var(--color-accent-subtle)] flex items-center justify-center shrink-0",children:e.jsx(Ne,{size:22,className:"text-[var(--color-accent)]"})}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Le,{value:t.title??"",onSave:T=>c(t.id,{title:T||void 0}).then(()=>{}),placeholder:"Title",emptyLabel:"Add title",ariaLabel:"Edit contact title",textClassName:"text-[length:var(--text-body-m)] text-[var(--color-text-tertiary)] block w-full"})})]}),e.jsxs("div",{className:"space-y-1 max-md:order-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[length:var(--text-body-m)] text-[var(--color-text-secondary)]",children:[e.jsx(Be,{size:14,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsx(Le,{value:t.email??"",onSave:T=>c(t.id,{email:T||void 0}).then(()=>{}),type:"email",placeholder:"[email protected]",emptyLabel:"Add email",ariaLabel:"Edit contact email",textClassName:"text-[length:var(--text-body-m)] flex-1 min-w-0"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-[length:var(--text-body-m)] text-[var(--color-text-secondary)]",children:[e.jsx(kt,{size:14,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsx(Le,{value:t.phone??"",onSave:T=>c(t.id,{phone:T||void 0}).then(()=>{}),type:"tel",placeholder:"+1 555 0100",emptyLabel:"Add phone",ariaLabel:"Edit contact phone",textClassName:"text-[length:var(--text-body-m)] flex-1 min-w-0"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-[length:var(--text-body-m)] text-[var(--color-text-secondary)]",children:[e.jsx(fa,{size:14,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsx(Le,{value:t.website??"",onSave:T=>c(t.id,{website:T||void 0}).then(()=>{}),type:"url",placeholder:"https://example.com",emptyLabel:"Add website",ariaLabel:"Edit contact website",textClassName:"text-[length:var(--text-body-m)] flex-1 min-w-0"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-[length:var(--text-body-m)] text-[var(--color-text-secondary)]",children:[e.jsx(Ss,{size:14,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsx(Le,{value:t.industry??"",onSave:T=>c(t.id,{industry:T||void 0}).then(()=>{}),placeholder:"Industry",emptyLabel:"Add industry",ariaLabel:"Edit contact industry",textClassName:"text-[length:var(--text-body-m)] flex-1 min-w-0"})]})]}),e.jsxs("div",{className:"space-y-2 max-md:order-1",children:[e.jsx("label",{id:`person-lifecycle-label-${t.id}`,className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-tertiary)]",children:"Lifecycle stage"}),e.jsxs(me,{value:t.lifecycle_stage??void 0,onValueChange:T=>{T&&T!==t.lifecycle_stage&&Z(T)},children:[e.jsx(ue,{"data-testid":"person-lifecycle-select","data-lifecycle-variant":t.lifecycle_stage?Pt[t.lifecycle_stage]:"default","aria-labelledby":`person-lifecycle-label-${t.id}`,className:"w-full dark:border-[var(--color-text-quaternary)]",children:e.jsx(ve,{placeholder:"Select lifecycle stage"})}),e.jsx(pe,{children:It.map(T=>e.jsx(te,{value:T,"data-testid":`person-lifecycle-option-${T}`,"data-lifecycle-variant":Pt[T],children:et[T]},T))})]})]}),e.jsxs("div",{className:"space-y-2 max-md:order-2",children:[e.jsx("label",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-tertiary)]",children:"Lead score"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{score:t.lead_score,size:"md"}),e.jsx(ed,{contactId:t.id})]})]}),e.jsxs("div",{className:"space-y-2 max-md:order-3",children:[e.jsx("label",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-tertiary)]",children:"Owner"}),e.jsxs(me,{value:((le=t.owner)==null?void 0:le.id)??"none",onValueChange:async T=>{const W=G.getState().bulkUpdateContacts,R=G.getState().selectContact,Y=T==="none"?null:T;await W([t.id],{owner_id:Y})&&await R(t.id)},children:[e.jsx(ue,{"aria-label":"Contact owner","data-testid":"contact-detail-owner-select",className:"w-full dark:border-[var(--color-text-quaternary)]",children:e.jsx(ve,{placeholder:"Select owner..."})}),e.jsxs(pe,{children:[e.jsx(te,{value:"none",children:"No owner"}),H.map(T=>e.jsx(te,{value:T.id,"data-testid":`contact-detail-owner-option-${T.id}`,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Je,{src:T.avatar_url,name:T.dis
67play_name,size:"xs"}),e.jsx("span",{children:T.display_name||T.email})]})},T.id))]})]})]}),e.jsxs("div",{className:"space-y-2 max-md:order-5",children:[e.jsx("label",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-tertiary)]",children:"Lists"}),e.jsx(Ps,{contact:t})]}),e.jsxs("div",{className:"space-y-2 max-md:order-6",children:[e.jsx("label",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-tertiary)]",children:"Last contacted"}),e.jsx("p",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-secondary)]",children:t.last_contacted_at?wt(t.last_contacted_at):"Never"})]}),e.jsx("div",{className:"max-md:order-7",children:e.jsx(Ts,{entity:"contact",properties:t.custom_properties??{},onSave:T=>c(t.id,{custom_properties:T})})}),t.created_at&&e.jsxs("div",{className:"space-y-2 max-md:order-8",children:[e.jsx("label",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-tertiary)]",children:"Created"}),e.jsx("p",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-secondary)]",children:wt(t.created_at)})]})]}),e.jsxs("div",{id:"contact-related-section",role:"tabpanel","aria-labelledby":"contact-related-tab",hidden:U!=="related",className:"space-y-4",children:[t.type==="person"&&e.jsxs("div",{className:"space-y-2","data-testid":"contact-detail-company-section",children:[e.jsx("label",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-tertiary)]",children:"Company"}),t.company&&!b?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("button",{onClick:()=>u(t.company.id),title:"Open company detail","aria-label":`Open company detail for ${t.company.name}`,"data-testid":"contact-detail-company-card",className:"flex-1 min-w-0 flex items-center gap-2 px-2 py-2 rounded-[var(--radius-sm)] hover:bg-[var(--color-bg-secondary)] cursor-pointer transition-colors text-left group",children:[e.jsx("div",{"data-testid":"contact-detail-company-card-icon-wrapper",className:"w-7 h-7 rounded-[var(--radius-md)] bg-[var(--color-bg-tertiary)] flex items-center justify-center shrink-0",children:e.jsx(Fe,{"data-testid":"contact-detail-company-card-icon",size:14,className:"text-[var(--color-text-tertiary)]"})}),e.jsx("span",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-primary)] truncate",children:t.company.name}),e.jsx(la,{size:14,"data-testid":"contact-detail-company-card-nav-icon",className:"text-[var(--color-text-quaternary)] group-hover:text-[var(--color-text-tertiary)] shrink-0 ml-auto transition-colors"})]}),e.jsx("button",{onClick:()=>g(!0),title:"Change company","aria-label":"Change company","data-testid":"contact-detail-company-edit",className:"inline-flex items-center justify-center w-8 h-8 rounded-md text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-secondary)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent)]",children:e.jsx(We,{size:14})}),e.jsx("button",{onClick:()=>c(t.id,{company_id:null}),title:"Unlink company","aria-label":"Unlink company","data-testid":"contact-detail-company-unlink",className:"inline-flex items-center justify-center w-8 h-8 rounded-md text-[var(--color-text-tertiary)] hover:text-[var(--color-error)] hover:bg-[var(--color-error-subtle)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent)]",children:e.jsx(ze,{size:14})})]}):e.jsxs(me,{value:((X=t.company)==null?void 0:X.id)??void 0,onValueChange:T=>{var W;T&&T!==((W=t.company)==null?void 0:W.id)?c(t.id,{company_id:T}).finally(()=>g(!1)):g(!1)},children:[e.jsx(ue,{"data-testid":"contact-detail-company-picker","aria-label":"Add company",className:"w-full",children:e.jsx(ve,{placeholder:"Add company…"})}),e.jsx(pe,{children:a.length===0?e.jsx("div",{className:"px-3 py-2 text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"No companies yet"}):a.map(T=>e.jsx(te,{value:T.id,"data-testid":`contact-detail-company-option-${T.id}`,children:T.name},T.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] tabular-nums",children:["Deal
67s (",i?"...":n.length,")"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[V>0&&e.jsx("span",{className:"text-[length:var(--text-label-s)] font-medium text-[var(--color-text-secondary)] tabular-nums",children:Q(V)}),w&&e.jsxs("button",{onClick:w,className:"inline-flex items-center gap-1 h-6 px-1.5 rounded text-[length:var(--text-label-s)] text-[var(--color-accent)] hover:bg-[var(--color-accent-subtle)] transition-colors",title:"Add deal","aria-label":"Add deal for this contact","data-testid":"contact-detail-add-deal",children:[e.jsx(oe,{size:12}),"Add"]})]})]}),i?e.jsx("div",{className:"space-y-2",children:Array.from({length:2}).map((T,W)=>e.jsx("div",{className:"h-10 rounded-[var(--radius-sm)] bg-[var(--color-bg-secondary)] animate-pulse"},W))}):n.length===0?e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-quaternary)] py-1",children:"No deals yet"}):e.jsx("div",{className:"space-y-1",children:n.map(T=>e.jsxs("button",{onClick:()=>x(T.id),className:"w-full flex items-center gap-2 px-2 py-2 rounded-[var(--radius-sm)] hover:bg-[var(--color-bg-secondary)] cursor-pointer transition-colors text-left",children:[e.jsx(Ze,{size:14,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-primary)] truncate",children:T.title}),e.jsx("div",{className:"flex items-center gap-2",children:T.stage&&e.jsx("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:T.stage.name})})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsx("p",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-primary)] tabular-nums",children:Q(T.amount,T.currency??void 0)}),e.jsx(de,{variant:Ls[T.status]||"default",className:T.status==="open"?"text-[var(--color-text-primary)]":void 0,children:za[T.status]||T.status})]})]},T.id))})]}),e.jsx(Dn,{contactId:t.id,refreshKey:O}),e.jsx(hd,{contactId:t.id})]}),e.jsx("div",{id:"contact-activity-section",role:"tabpanel","aria-labelledby":"contact-activity-tab",hidden:U!=="activity",children:e.jsx(Rs,{activities:l,onLogActivity:()=>y(!0)})}),e.jsx(we,{open:j,onOpenChange:f,title:"Delete contact",description:`Permanently removes ${t.name} — associated deals unlinked.`,onConfirm:()=>{f(!1),_()}}),z&&e.jsx(Fs,{contactId:t.id,onClose:()=>y(!1),onSubmit:p}),e.jsx(cd,{open:E,onClose:()=>A(!1),currentContact:t,candidates:r.filter(T=>T.id!==t.id),onPick:T=>{A(!1),N(T)}})]})})}function cd({open:t,onClose:a,currentContact:r,candidates:l,onPick:n}){const[s,i]=o.useState("");o.useEffect(()=>{t&&i("")},[t]);const d=s.trim().toLowerCase(),c=d?l.filter(m=>(m.name??"").toLowerCase().includes(d)||(m.email??"").toLowerCase().includes(d)):l;return e.jsx(Ke,{open:t,onOpenChange:m=>{m||a()},children:e.jsxs(Qe,{children:[e.jsx(He,{children:e.jsx(Ye,{children:"Merge with…"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:["Pick a duplicate to merge into ",e.jsx("strong",{children:r.name||"this contact"}),". You'll choose which fields to keep next."]}),e.jsx("input",{type:"search",placeholder:"Search by name or email…",value:s,onChange:m=>i(m.target.value),className:"w-full h-9 px-3 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[length:var(--text-body-s)] text-[var(--color-text-primary)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent)]","aria-label":"Search contacts"}),e.jsx("div",{className:"max-h-72 overflow-y-auto rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)]",children:c.length===0?e.jsx("div",{className:"p-4 text-center text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"No contacts to merge."}):e.jsx("ul",{role:"listbox",className:"divide-y divide-[var(--color-bg-tertiary)]",children:c.slice(0,50).map(m=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>n(m),className:"w-full text-left px-3 py-2 hover:bg-[var(--color-bg-secondary)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent)]",children:[e.jsx("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-primary)] truncate",children:m.name||"Unnamed"}),m.email&&e.jsx("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] truncate",children:m.email})]})},m.id))})})]}),e.jsx(nt,{children:e.jsx(L,{variant:"secondary",onClick:a,children:"Cancel"})})]})})}function dd({contact:t,activities:a,companyContacts:r,companyDeals:l,loading:n,companyDetailLoa
67ding:s,onClose:i,onUpdate:d,onDelete:c,onLogActivity:m,onSelectContact:p,onSelectDeal:u,onAddContactToCompany:x,onCreateDeal:w,backStack:N,onBackStackPop:h}){var k;const[v,j]=o.useState(!1),[f,z]=o.useState(!1),[y,b]=o.useState("details"),[g,E]=o.useState(0),A=G(C=>C.workspaceUsers),U=G(C=>C.loadWorkspaceUsers);o.useEffect(()=>{A.length===0&&U()},[A.length,U]);const D=G(C=>C.propertyDefinitions),O=G(C=>C.loadPropertyDefinitions);o.useEffect(()=>{D.length===0&&O()},[D.length,O]);const P=[];if(N&&N.length>0&&h)for(let C=0;C<N.length;C++){const _=N[C];P.push({label:_.label||(_.kind==="deal"?"Deal":_.kind==="company"?"Company":"Contact"),onClick:()=>h(C)})}if(n)return e.jsx(Zt,{open:!0,title:"Company details",onClose:i,size:"lg",resizable:!0,widthStorageKey:"crm-company-detail-width",className:"max-md:!bottom-[var(--mobile-tab-bar-clearance,0px)] max-md:!h-auto max-md:!max-w-none md:max-w-[50%]",mobileBreakpoint:"md",mobileMode:"full-screen",hideCloseButton:!0,headerSlot:e.jsx(aa,{title:"Company",breadcrumb:P.length>0?P:void 0,onClose:i}),children:e.jsx("div",{className:"p-4 space-y-4",children:e.jsx(js,{})})});const H=async()=>{i(),await c(t.id)&&ge.success("Company deleted")},ae=C=>{b(C)},I=l.filter(C=>C.status==="open").reduce((C,_)=>C+(_.amount||0),0);return e.jsx(Zt,{open:!0,title:"Company details",onClose:i,size:"lg",resizable:!0,widthStorageKey:"crm-company-detail-width",className:"max-md:!bottom-[var(--mobile-tab-bar-clearance,0px)] max-md:!h-auto max-md:!max-w-none md:max-w-[50%]",mobileBreakpoint:"md",mobileMode:"full-screen",mobileHeaderScrollsAway:!0,hideCloseButton:!0,headerSlot:e.jsx(aa,{title:e.jsx(Le,{value:t.name,onSave:C=>d(t.id,{name:C}).then(()=>{}),placeholder:"Company name",emptyLabel:"Add company name",ariaLabel:"Edit company name",textClassName:"block w-full text-[length:var(--text-title-l)] font-semibold text-[var(--color-text-primary)]"}),contextLabel:"Company",breadcrumb:P.length>0?P:void 0,onClose:i,extraActions:e.jsx("button",{onClick:()=>j(!0),className:"inline-flex items-center justify-center w-8 h-8 rounded-md text-[var(--color-text-tertiary)] hover:text-[var(--color-error)] hover:bg-[var(--color-error-subtle)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent)]",title:"Delete company","aria-label":"Delete company",children:e.jsx(he,{size:16})})}),children:e.jsxs("div",{className:"space-y-4 p-4 pb-[calc(var(--mobile-tab-bar-clearance,0px)+2rem)]",children:[e.jsxs("div",{className:"mobile-toolbar-scroll flex gap-2 overflow-x-auto pb-1","aria-label":"Company actions",children:[e.jsxs(L,{variant:"primary",size:"compact",className:lt,disabled:!t.email,onClick:()=>t.email&&ut.getState().open("mail",{initialData:{to:t.email}}),children:[e.jsx(Be,{size:14,className:"shrink-0"}),e.jsx("span",{children:"Email"}),!t.email&&e.jsx(ze,{size:10,className:"shrink-0","aria-label":"Unavailable"})]}),e.jsxs(L,{variant:"secondary",size:"compact",className:lt,disabled:!t.phone,onClick:()=>{t.phone&&(window.location.href=`tel:${t.phone}`)},children:[e.jsx(kt,{size:14,className:"shrink-0"}),e.jsx("span",{children:"Call"}),!t.phone&&e.jsx(ze,{size:10,className:"shrink-0","aria-label":"Unavailable"})]}),e.jsxs(L,{variant:"secondary",size:"compact",className:lt,onClick:()=>ut.getState().open("calendar"),children:[e.jsx(ta,{size:14}),e.jsx("span",{children:"Meet"})]}),e.jsxs(L,{variant:"secondary",size:"compact",className:lt,onClick:()=>ut.getState().open("tasks",{initialData:{contact_id:t.id},onCreated:()=>E(C=>C+1)}),children:[e.jsx(Se,{size:14,className:"shrink-0"}),e.jsx("span",{children:"Task"})]}),e.jsxs(L,{variant:"secondary",size:"compact",className:lt,onClick:()=>z(!0),children:[e.jsx(Ds,{size:14}),e.jsx("span",{children:"Note"})]})]}),e.jsx("nav",{"aria-label":"Company sections",role:"tablist",className:"sticky top-0 z-10 -mx-4 flex gap-1 border-b border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] px-4",children:["activity","details","related"].map(C=>e.jsx("button",{type:"button",id:`company-${C}-tab`,role:"tab","aria-selected":y===C,"aria-controls":`company-${C}-section`,onClick:()=>ae(C),className:`h-10 border-b-2 px-3 text-[length:var(--text-body-m)] font-medium capitalize transition-colors ${y===C?"border-[var(--color-accent)] text-[var(--color-accent-text)]":"border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"}`,children:C},C))}
67),e.jsxs("div",{id:"company-details-section",role:"tabpanel","aria-labelledby":"company-details-tab",hidden:y!=="details",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-[var(--radius-lg)] bg-[var(--color-accent-subtle)] flex items-center justify-center shrink-0",children:e.jsx(Fe,{size:22,className:"text-[var(--color-accent)]"})}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Le,{value:t.industry??"",onSave:C=>d(t.id,{industry:C||void 0}).then(()=>{}),placeholder:"Industry",emptyLabel:"Add industry",ariaLabel:"Edit company industry",textClassName:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] block w-full"})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:[e.jsx(fa,{size:14,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsx(Le,{value:t.website??"",onSave:C=>d(t.id,{website:C||void 0}).then(()=>{}),type:"url",placeholder:"https://company.com",emptyLabel:"Add website",ariaLabel:"Edit company website",textClassName:"text-[length:var(--text-body-s)] flex-1 min-w-0"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:[e.jsx(Be,{size:14,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsx(Le,{value:t.email??"",onSave:C=>d(t.id,{email:C||void 0}).then(()=>{}),type:"email",placeholder:"[email protected]",emptyLabel:"Add email",ariaLabel:"Edit company email",textClassName:"text-[length:var(--text-body-s)] flex-1 min-w-0"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:[e.jsx(kt,{size:14,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsx(Le,{value:t.phone??"",onSave:C=>d(t.id,{phone:C||void 0}).then(()=>{}),type:"tel",placeholder:"+1 555 0100",emptyLabel:"Add phone",ariaLabel:"Edit company phone",textClassName:"text-[length:var(--text-body-s)] flex-1 min-w-0"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-tertiary)]",children:"Customer status"}),(()=>{const C=l.some(F=>F.status==="won"),_=l.some(F=>F.status==="open"),Z=C?"customer":_?"active-prospect":l.length>0?"past-lead":"prospect",B=Z==="customer"?"Customer":Z==="active-prospect"?"Active prospect":Z==="past-lead"?"Past lead":"Prospect",V=Z==="customer"?"success":Z==="past-lead"?"warning":"default";return e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(de,{variant:V,children:B}),e.jsx("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:"Auto-derived from deals"})]})})()]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)]",children:"Owner"}),e.jsxs(me,{value:((k=t.owner)==null?void 0:k.id)??"none",onValueChange:async C=>{const _=G.getState().bulkUpdateContacts,Z=G.getState().selectContact,B=C==="none"?null:C;await _([t.id],{owner_id:B})&&await Z(t.id)},children:[e.jsx(ue,{"aria-label":"Company owner","data-testid":"contact-detail-owner-select",className:"w-full",children:e.jsx(ve,{placeholder:"Select owner..."})}),e.jsxs(pe,{children:[e.jsx(te,{value:"none",children:"No owner"}),A.map(C=>e.jsx(te,{value:C.id,"data-testid":`contact-detail-owner-option-${C.id}`,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Je,{src:C.avatar_url,name:C.display_name,size:"xs"}),e.jsx("span",{children:C.display_name||C.email})]})},C.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)]",children:"Lists"}),e.jsx(Ps,{contact:t})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-tertiary)]",children:"Last contacted"}),e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:t.last_contacted_at?wt(t.last_contacted_at):"Never"})]}),e.jsx(Ts,{entity:"company",properties:t.custom_properties??{},onSave:C=>d(t.id,{custom_properties:C})}),t.created_at&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-tertiary)]",children:"Created"}),e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:wt(t.created_at)})]})]}),e.jsxs("div",{id:"company-related-section",role:"tabpanel","aria-labelledby":"
67company-related-tab",hidden:y!=="related",className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"normal-case text-[length:var(--text-body-s)] font-medium text-[var(--color-text-tertiary)] tabular-nums",children:["People (",s?"...":r.length,")"]}),e.jsxs("button",{type:"button",onClick:()=>x(t.id),className:"text-[length:var(--text-label-s)] font-medium text-[var(--color-accent)] hover:underline cursor-pointer flex items-center gap-1","aria-label":"Add contact to this company",children:[e.jsx(oe,{size:12}),"Add contact"]})]}),s?e.jsx("div",{className:"space-y-2",children:Array.from({length:2}).map((C,_)=>e.jsx("div",{className:"h-8 rounded-[var(--radius-sm)] bg-[var(--color-bg-secondary)] animate-pulse"},_))}):r.length===0?e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-quaternary)] py-1",children:"No associated contacts"}):e.jsx("div",{className:"space-y-1",children:r.map(C=>e.jsxs("button",{onClick:()=>p(C.id),className:"w-full flex items-center gap-2 px-2 py-2 rounded-[var(--radius-sm)] hover:bg-[var(--color-bg-secondary)] cursor-pointer transition-colors text-left",children:[e.jsx(Aa,{name:C.name,lifecycleStage:C.lifecycle_stage,size:"xs"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-primary)] truncate",children:C.name}),C.title&&e.jsx("p",{className:"text-[length:var(--text-label-s)] leading-snug text-[var(--color-text-secondary)] line-clamp-2 sm:truncate",children:C.title}),C.email&&e.jsx("p",{className:"mt-0.5 text-[length:var(--text-label-s)] text-[var(--color-text-secondary)] break-all",children:C.email})]})]},C.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"normal-case text-[length:var(--text-body-s)] font-medium text-[var(--color-text-tertiary)] tabular-nums",children:["Deals (",s?"...":l.length,")"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[I>0&&e.jsx("span",{className:"text-[length:var(--text-label-s)] font-medium text-[var(--color-text-secondary)] tabular-nums",children:Q(I)}),w&&e.jsxs("button",{onClick:w,className:"inline-flex items-center gap-1 h-6 px-1.5 rounded text-[length:var(--text-label-s)] text-[var(--color-accent)] hover:bg-[var(--color-accent-subtle)] transition-colors",title:"Add deal","aria-label":"Add deal for this company","data-testid":"company-detail-add-deal",children:[e.jsx(oe,{size:12}),"Add"]})]})]}),s?e.jsx("div",{className:"space-y-2",children:Array.from({length:2}).map((C,_)=>e.jsx("div",{className:"h-10 rounded-[var(--radius-sm)] bg-[var(--color-bg-secondary)] animate-pulse"},_))}):l.length===0?e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-quaternary)] py-1",children:"No deals yet"}):e.jsx("div",{className:"space-y-1",children:l.map(C=>e.jsxs("button",{onClick:()=>u(C.id),className:"w-full flex items-center gap-2 px-2 py-2 rounded-[var(--radius-sm)] hover:bg-[var(--color-bg-secondary)] cursor-pointer transition-colors text-left",children:[e.jsx(Ze,{size:14,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-primary)] truncate",children:C.title}),e.jsx("div",{className:"flex items-center gap-2",children:C.stage&&e.jsx("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:C.stage.name})})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsx("p",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-primary)] tabular-nums",children:Q(C.amount,C.currency??void 0)}),e.jsx(de,{variant:Ls[C.status]||"default",className:C.status==="open"?"text-[var(--color-text-primary)]":void 0,children:za[C.status]||C.status})]})]},C.id))})]}),e.jsx(Rd,{companyId:t.id,personIds:r.map(C=>C.id),refreshKey:g})]}),e.jsx("div",{id:"company-activity-section",role:"tabpanel","aria-labelledby":"
67company-activity-tab",hidden:y!=="activity",children:e.jsx(Rs,{activities:a,onLogActivity:()=>z(!0)})}),e.jsx(we,{open:v,onOpenChange:j,title:"Delete company",description:e.jsxs(e.Fragment,{children:['"',t.name,'" will be deleted and all associated contacts and deals unlinked.']}),onConfirm:()=>{j(!1),H()}}),f&&e.jsx(Fs,{contactId:t.id,onClose:()=>z(!1),onSubmit:m})]})})}function xd({value:t,onCommit:a}){const[r,l]=o.useState(t),n=o.useRef(t);o.useEffect(()=>{l(t),n.current=t},[t]);const s=o.useCallback(i=>{const d=Math.max(0,Math.min(100,Math.round(i)));d!==n.current&&(n.current=d,a(d))},[a]);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{htmlFor:"deal-probability-slider",className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-tertiary)]",children:"Probability"}),e.jsxs("span",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)] tabular-nums",children:[r,"%"]})]}),e.jsx("input",{id:"deal-probability-slider",type:"range",min:0,max:100,step:5,value:r,onChange:i=>l(Number(i.target.value)),onMouseUp:i=>s(Number(i.target.value)),onTouchEnd:i=>s(Number(i.target.value)),onKeyUp:i=>s(Number(i.target.value)),onBlur:i=>s(Number(i.target.value)),className:"h-2 w-full cursor-pointer accent-[var(--color-accent)]","aria-label":"Edit deal probability"})]})}function md({deal:t,pipelines:a,contacts:r,loading:l,activities:n,onClose:s,onUpdate:i,onDelete:d,onLogActivity:c,backStack:m,onBackStackPop:p}){var I,k,C;const u=sa(),[x,w]=o.useState(!1),[N,h]=o.useState(null),[v,j]=o.useState(!1),[f,z]=o.useState("details"),[y,b]=o.useState(0),g=G(_=>_.propertyDefinitions),E=G(_=>_.loadPropertyDefinitions);o.useEffect(()=>{g.length===0&&E()},[g.length,E]);const A=a.find(_=>_.id===t.pipeline_id),U=(A==null?void 0:A.stages)??[],D=`/crm/pipeline?deal=${t.id}`,O=[];if(m&&m.length>0&&p)for(let _=0;_<m.length;_++){const Z=m[_];O.push({label:Z.label||(Z.kind==="deal"?"Deal":Z.kind==="company"?"Company":"Contact"),onClick:()=>p(_)})}if(A&&O.push({label:A.name}),(I=t.company)!=null&&I.name&&O.push({label:t.company.name}),l)return e.jsx(Zt,{open:!0,title:"Deal details",onClose:s,size:"lg",resizable:!0,widthStorageKey:"crm-deal-detail-width",className:"max-md:!bottom-[var(--mobile-tab-bar-clearance,0px)] max-md:!h-auto max-md:!max-w-none md:max-w-[50%]",mobileBreakpoint:"md",mobileMode:"full-screen",hideCloseButton:!0,headerSlot:e.jsx(aa,{title:"Deal",breadcrumb:O.length>0?O:void 0,copyLinkUrl:D,openInNewUrl:D,onClose:s}),children:e.jsx("div",{className:"p-4 space-y-4",children:e.jsx(js,{})})});const P=async()=>{s(),await d(t.id)&&ge.success("Deal deleted")},H=_=>{const Z=U.find(V=>V.id===t.stage_id),B=U.find(V=>V.id===_);Z&&B&&B.sort_order<Z.sort_order?h(_):i(t.id,{stage_id:_}).then(V=>{V?ge.success("Stage updated"):xs()})},ae=_=>{t.status!==_&&i(t.id,{status:_}).then(Z=>{Z&&(_==="won"?ge.success("Deal won"):_==="lost"?ge.success("Deal lost"):ge.success("Status updated"))})};return e.jsx(Zt,{open:!0,title:"Deal details",onClose:s,size:"lg",resizable:!0,widthStorageKey:"crm-deal-detail-width",className:"max-md:!bottom-[var(--mobile-tab-bar-clearance,0px)] max-md:!h-auto max-md:!max-w-none md:max-w-[50%]",mobileBreakpoint:"md",mobileMode:"full-screen",mobileHeaderScrollsAway:!0,hideCloseButton:!0,headerSlot:e.jsx(aa,{title:e.jsx(Le,{value:t.title,onSave:_=>i(t.id,{title:_}).then(()=>{}),placeholder:"Deal title",emptyLabel:"Add title",ariaLabel:"Edit deal title",textClassName:"block w-full text-[length:var(--text-title-l)] font-semibold text-[var(--color-text-primary)]"}),breadcrumb:O.length>0?O:void 0,copyLinkUrl:D,openInNewUrl:D,onClose:s,extraActions:e.jsx("button",{onClick:()=>w(!0),"aria-label":"Delete deal",className:"inline-flex items-center justify-center w-8 h-8 pointer-coarse:w-11 pointer-coarse:h-11 rounded-md text-[var(--color-text-tertiary)] hover:text-[var(--color-error)] hover:bg-[var(--color-error-subtle)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent)]",t
67itle:"Delete deal",children:e.jsx(he,{size:16})})}),children:e.jsxs("div",{className:"space-y-4 p-4 pb-[calc(var(--mobile-tab-bar-clearance,0px)+2rem)]",children:[e.jsxs("div",{className:"grid grid-cols-[auto_repeat(3,minmax(0,1fr))] gap-2","aria-label":"Deal actions",children:[e.jsxs(L,{variant:"primary",size:"compact",className:"min-w-0 px-1 text-[length:var(--text-body-m)]","aria-label":"Add next step",onClick:()=>ut.getState().open("tasks",{initialData:{deal_id:t.id},onCreated:()=>b(_=>_+1)}),children:[e.jsx(Se,{size:14,className:"shrink-0"}),e.jsx("span",{className:"max-sm:hidden",children:"Add next step"}),e.jsx("span",{className:"sm:hidden",children:"Task"})]}),e.jsxs(L,{variant:"secondary",size:"compact",className:"min-w-0 px-1 text-[length:var(--text-body-m)]",disabled:!((k=t.contact)!=null&&k.email),onClick:()=>{var _;return((_=t.contact)==null?void 0:_.email)&&ut.getState().open("mail",{initialData:{to:t.contact.email}})},children:[e.jsx(Be,{size:14}),e.jsx("span",{children:"Email"}),!((C=t.contact)!=null&&C.email)&&e.jsx(ze,{size:10,"aria-label":"Unavailable"})]}),e.jsxs(L,{variant:"secondary",size:"compact",className:"min-w-0 px-1 text-[length:var(--text-body-m)]",onClick:()=>ut.getState().open("calendar"),children:[e.jsx(ta,{size:14}),e.jsx("span",{children:"Meet"})]}),e.jsxs(L,{variant:"secondary",size:"compact",className:"min-w-0 px-1 text-[length:var(--text-body-m)]",onClick:()=>u(`/crm/quotes?deal_id=${t.id}`),children:[e.jsx(ot,{size:14}),e.jsx("span",{children:"Quote"})]})]}),e.jsx("nav",{"aria-label":"Deal sections",role:"tablist",className:"-mx-4 px-4 sticky top-0 z-10 bg-[var(--color-bg-primary)] border-b border-[var(--color-bg-tertiary)] flex gap-1 overflow-x-auto mobile-toolbar-scroll",children:[{id:"activity",label:"Activity"},{id:"details",label:"Details"},{id:"files",label:"Files"},{id:"products",label:"Products"}].map(_=>e.jsx("button",{id:`deal-${_.id}-tab`,type:"button",role:"tab","aria-selected":f===_.id,"aria-controls":`deal-${_.id}-section`,onClick:()=>z(_.id),className:`shrink-0 px-3 py-2 pointer-coarse:py-0 pointer-coarse:h-11 pointer-coarse:flex pointer-coarse:items-center text-[length:var(--text-body-m)] font-medium hover:text-[var(--color-text-primary)] border-b-2 ${f===_.id?"border-[var(--color-accent)] text-[var(--color-accent-text)]":"border-transparent text-[var(--color-text-secondary)] hover:border-[var(--color-accent)]"}`,children:_.label},_.id))}),e.jsxs("div",{id:"deal-details-section",role:"tabpanel","aria-labelledby":"deal-details-tab",hidden:f!=="details",className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-tertiary)]",children:"Amount"}),e.jsx(Le,{value:t.amount!=null?String(t.amount):"",displayValue:t.amount!=null?Q(t.amount,t.currency??void 0):"",onSave:_=>{const Z=_===""?null:Number(_);return _!==""&&Number.isNaN(Z)?Promise.resolve():i(t.id,{amount:Z}).then(()=>{})},type:"number",placeholder:"0.00",emptyLabel:"Add amount",ariaLabel:"Edit deal amount",textClassName:"text-[length:var(--text-headline-s)] font-medium text-[var(--color-text-primary)] tabular-nums block w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-tertiary)]",children:"Status"}),e.jsx("div",{className:"flex gap-1 flex-wrap",children:["open","won","lost"].map(_=>e.jsxs("button",{"data-testid":`deal-detail-status-pill-${_}`,onClick:()=>ae(_),className:`px-3 py-1 rounded-[var(--radius-sm)] text-[length:var(--text-label-m)] leading-[var(--lh-label-m)] font-medium cursor-pointer transition-colors ${t.status===_?_==="won"?"bg-[var(--color-success-subtle)] text-[var(--color-success)]":_==="lost"?"bg-[var(--color-error-subtle)] text-[var(--color-error-text)]":"bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]":"text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-secondary)]"}`,children:[_==="won"&&e.jsx(ka,{size:14,className:"inline mr-1 -mt-0.5"}),_==="lost"&&e.jsx(gr,{size:14,className:"inline mr-1 -mt-0.5"}),za[_]]},_))})]}),U.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{id:`deal-detail-stage-label-${t.id}`,className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-tertiary)]",children:"Stage"}),e.jsxs(me,{value:t.stage_id??void 0,onValueChange:_=>{_&&_!==t.stage_id&&H(_)},children:[e.jsx(ue,{"data-testid":"deal-detail-stage-select","aria-labelledby":`deal-detail-stage-label-${t.id}`,className:"w-full",children:e.jsx(ve,{placeholder:"Select stage"})}),e.jsx(pe,{children:U.map(_=>e.jsx(te,{value:_.id,"data-testid":`deal-detail-stage-option-${_.id}`,children:_.name},_.id))})]})]}),e.jsx(Md,{deal:t,contacts:r.filter(_=>_.type==="person"),onUpdate:i}),t.company&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-tertiary)]",children:"Company"}),e.jsxs("div",{className:"flex items-center gap-2","data-testid":"deal-detail-company",children:[e.jsx(Fe,{size:16,className:"text-[var(--color-text-tertiary)]"}),e.jsx(cr,{module:"CRM",entityId:t.company.id,children:e.jsx("span",{"data-testid":"deal-detail-company-name",className:"text-[length:var(--text-body-m)] text-[var(--color-text-primary)] underline decoration-transparent decoration-dotted underline-offset-2 hover:
67decoration-[var(--color-text-tertiary)] cursor-default",children:t.company.name})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-tertiary)]",children:"Close date"}),e.jsxs("div",{className:"flex items-center gap-2 text-[length:var(--text-body-m)] text-[var(--color-text-secondary)]",children:[e.jsx(ta,{size:16,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsx(Le,{value:t.close_date??"",displayValue:t.close_date?wt(t.close_date):"",onSave:_=>i(t.id,{close_date:_||null}).then(()=>{}),type:"date",placeholder:"YYYY-MM-DD",emptyLabel:"Add close date",ariaLabel:"Edit close date",textClassName:"text-[length:var(--text-body-m)] flex-1 min-w-0"})]})]}),t.probability!=null&&e.jsx(xd,{value:t.probability,onCommit:_=>i(t.id,{probability:_}).then(()=>{})}),t.owner&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-tertiary)]",children:"Owner"}),e.jsx("div",{children:e.jsx(cr,{module:"People",entityId:t.owner.id,children:e.jsxs("span",{"data-testid":"deal-detail-owner",className:"inline-flex items-center gap-2 underline decoration-transparent decoration-dotted underline-offset-2 hover:
67decoration-[var(--color-text-tertiary)] cursor-default",children:[e.jsx(Je,{name:t.owner.display_name,src:t.owner.avatar_url,size:"sm"}),e.jsx("span",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-primary)]",children:t.owner.display_name})]})})})]}),e.jsx(Ts,{properties:t.custom_properties??{},onSave:_=>i(t.id,{custom_properties:_}),entity:"deal"})]}),e.jsxs("div",{id:"deal-products-section",role:"tabpanel","aria-labelledby":"deal-products-tab",hidden:f!=="products",className:"space-y-4",children:[e.jsx(ud,{dealId:t.id,currency:t.currency}),e.jsx(Pd,{dealId:t.id})]}),e.jsx("div",{id:"deal-files-section",role:"tabpanel","aria-labelledby":"deal-files-tab",hidden:f!=="files",children:e.jsx(pd,{dealId:t.id})}),e.jsxs("div",{id:"deal-activity-section",role:"tabpanel","aria-labelledby":"deal-activity-tab",hidden:f!=="activity",className:"space-y-4",children:[e.jsx(Fd,{deal:t,refreshKey:y}),e.jsx(Rs,{activities:n,onLogActivity:()=>j(!0)})]}),v&&e.jsx(Fs,{dealId:t.id,onClose:()=>j(!1),onSubmit:c}),e.jsx(we,{open:x,onOpenChange:w,title:"Delete deal",description:e.jsxs(e.Fragment,{children:['"',t.title,'" will be deleted. This cannot be undone.']}),onConfirm:()=>{w(!1),P()}}),e.jsx(we,{open:N!==null,onOpenChange:_=>{_||h(null)},title:"Move deal backward?",description:"Pipeline metrics and reports will reflect the change.",confirmLabel:"Move",variant:"primary",onConfirm:()=>{N&&(i(t.id,{stage_id:N}).then(_=>{_?ge.success("Stage updated"):xs()}),h(null))}})]})})}function Ta({icon:t,title:a,description:r,cta:l,testId:n}){const s=l?Array.isArray(l)?l:[l]:[];return e.jsxs("div",{"data-testid":n,className:"flex flex-col items-center text-center gap-2 py-4 px-3 rounded-[var(--radius-md)] border border-dashed border-[var(--color-bg-tertiary)] bg-[var(--color-bg-secondary)]",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-[var(--color-bg-tertiary)] flex items-center justify-center",children:e.jsx(t,{size:20,className:"text-[var(--color-text-tertiary)]"})}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("p",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-primary)]",children:a}),e.jsx("p",{className:"text-[length:var(--text-body-s)] leading-[var(--lh-body-s)] text-[var(--color-text-tertiary)]",children:r})]}),s.length>0&&e.jsx("div",{className:s.length>1?"flex flex-wrap items-center justify-center gap-3":"contents",children:s.map((i,d)=>e.jsx("button",{type:"button",onClick:i.onClick,"data-testid":n?s.length>1?`${n}-cta-${d}`:`${n}-cta`:void 0,className:"inline-flex min-h-6 pointer-coarse:min-h-11 items-center text-[length:var(--text-label-m)] font-medium text-[var(--color-accent)] hover:underline cursor-pointer",children:i.label},d))})]})}function ud({dealId:t,currency:a}){const{dealLineItems:r,dealLineItemsTotal:l,dealLineItemsRecurringTotal:n,dealLineItemsBillingInterval:s,dealLineItemsLoading:i,loadDealLineItems:d,addDealLineItem:c,updateDealLineItem:m,removeDealLineItem:p,products:u,loadProducts:x}=G(),[w,N]=o.useState(!1),[h,v]=o.useState(null);o.useEffect(()=>{d(t)},[t,d]),o.useEffect(()=>{w&&u.length===0&&x({activeOnly:!0})},[w,u.length,x]);const j=async()=>{h&&(await p(h),v(null))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)]",children:"Line items"}),!w&&e.jsx("button",{onClick:()=>N(!0),className:"text-[length:var(--text-label-m)] text-[var(--color-accent)] pointer-coarse:min-h-11 pointer-coarse:inline-flex pointer-coarse:items-center hover:underline cursor-pointer",children:"+ Add"})]}),i&&r.length===0?e.jsx("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"Loading…"}):r.length===0&&!w?e.jsx(Ta,{icon:Ct,title:"No line items yet",description:"Itemize products and services to auto-calculate deal amount and generate quote PDFs.",cta:{label:"+ Add line item",onClick:()=>N(!0)},testId:"deal-line-items-empty"}):e.jsx("div",{className:"space-y-2",children:r.map(f=>e.jsx(vd,{item:f,currency:a,onUpdate:z=>m(f.id,z),onRemove:()=>v(f.id)},f.id))}),w&&e.jsx(bd,{dealId:t,currency:a,onAdd:c,onClose:()=>N(!1)}),r.length>0&&e.jsxs("div",{className:"pt-2 mt-1 border-t border-[var(--color-bg-tertiary)] space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:"Total"}),e.jsx("span",{className:"text-[length:var(--text-body-m)] font-semibold text-[var(--color-text-primary)] tabular-nums",children:Q(l,a??void 0)})]}),n>0&&e.jsxs("div",{"data-testid":"deal-recurring-total",className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-accent)]",children:["Recurring",ur(s)]}),e.jsxs("span",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-accent)] tabular-nums",children:[Q(n,a??void 0),ur(s)]})]})]}),e.jsx(we,{open:!!h,title:"Remove line item",description:"The deal amount will be updated to reflect the removal.",confirmLabel:"Remove",variant:"destructive",onConfirm:j,onOpenChange:f=>{f||v(null)}})]})}function pd({dealId:t}){const{dealFiles:a,dealFilesLoading:r,loadDealFiles:l,attachFileToDeal:n,detachFileFromDeal
67:s}=G(),[i,d]=o.useState(!1),[c,m]=o.useState(null);o.useEffect(()=>{l(t)},[t,l]);const p=async x=>{await n(t,x)&&d(!1)},u=async()=>{c&&(await s(t,c.file_id),m(null))};return e.jsxs("div",{className:"space-y-2","data-testid":"deal-files-section",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-tertiary)]",children:"Files"}),!i&&e.jsx("button",{onClick:()=>d(!0),className:"text-[length:var(--text-label-m)] text-[var(--color-accent)] pointer-coarse:min-h-11 pointer-coarse:inline-flex pointer-coarse:items-center hover:underline cursor-pointer","data-testid":"deal-files-attach-button",children:"+ Attach"})]}),r&&a.length===0?e.jsx("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"Loading…"}):a.length===0&&!i?e.jsx(Ta,{icon:en,title:"No files attached",description:"Attach NDAs, contracts, and proposals from Drive so they live alongside this deal.",cta:{label:"+ Attach file",onClick:()=>d(!0)},testId:"deal-files-empty"}):e.jsx("div",{className:"space-y-2",children:a.map(x=>e.jsx(kn,{file:x,onRemove:()=>m(x)},x.id))}),i&&e.jsx(Cn,{onSelect:p,onCancel:()=>d(!1)}),e.jsx(we,{open:!!c,title:"Remove file",description:"The file will remain in Drive; only the link to this deal is removed.",confirmLabel:"Remove",variant:"destructive",onConfirm:u,onOpenChange:x=>{x||m(null)}})]})}function hd({contactId:t}){const{contactFiles:a,contactFilesLoading:r,loadContactFiles:l,attachFileToContact:n,detachFileFromContact:s}=G(),[i,d]=o.useState(!1),[c,m]=o.useState(null);o.useEffect(()=>{l(t)},[t,l]);const p=async x=>{await n(t,x)&&d(!1)},u=async()=>{c&&(await s(t,c.file_id),m(null))};return e.jsxs("div",{className:"space-y-2","data-testid":"contact-files-section",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-tertiary)]",children:"Files"}),!i&&e.jsx("button",{onClick:()=>d(!0),className:"text-[length:var(--text-label-m)] text-[var(--color-accent)] hover:underline cursor-pointer","data-testid":"contact-files-attach-button",children:"+ Attach"})]}),r&&a.length===0?e.jsx("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"Loading…"}):a.length===0&&!i?e.jsx(Ta,{icon:en,title:"No files attached",description:"Attach NDAs, contracts, and proposals from Drive so they live alongside this contact.",cta:{label:"+ Attach file",onClick:()=>d(!0)},testId:"contact-files-empty"}):e.jsx("div",{className:"space-y-2",children:a.map(x=>e.jsx(kn,{file:x,onRemove:()=>m(x)},x.id))}),i&&e.jsx(Cn,{onSelect:p,onCancel:()=>d(!1)}),e.jsx(we,{open:!!c,title:"Remove file",description:"The file will remain in Drive; only the link to this contact is removed.",confirmLabel:"Remove",variant:"destructive",onConfirm:u,onOpenChange:x=>{x||m(null)}})]})}function kn({file:t,onRemove:a}){return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-[var(--radius-sm)] border border-[var(--color-bg-tertiary)] hover:bg-[var(--color-bg-secondary)] group","data-testid":`deal-file-row-${t.file_id}`,children:[e.jsx(ot,{size:16,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsxs("button",{type:"button",className:"flex-1 min-w-0 text-left rounded-[var(--radius-sm)] focus-visible:outline-2 focus-visible:outline-[var(--color-accent)] pointer-coarse:min-h-11",onClick:()=>Fo.getState().open("drive",t.file_id),"aria-label":`Open ${t.name}`,"data-testid":`deal-file-open-${t.file_id}`,children:[e.jsx("div",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-primary)] truncate group-hover:underline",children:t.name}),e.jsxs("div",{className:"flex items-center gap-2 text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:[t.size_bytes!=null&&e.jsx("span",{className:"tabular-nums",children:Gl(t.size_bytes)}),t.attached_at&&e.jsxs("span",{children:["· ",Ce(t.attached_at)]}),t.attached_by&&e.jsxs("span",{className:"truncate",children:["· ",t.attached_by.display_name]})]})]}),e.jsx("button",{onClick:a,className:"opacity-0 group-hover:opacity-100 pointer-coarse:opacity-100 p-1 rounded hover:bg-[var(--color-bg-tertiary)] text-[var(--color-text-tertiary)] transition-opacity cursor-pointer","aria-label":`Remove ${t.name}`,"data-testid":`deal-file-remove-${t.file_id}`,children:e.jsx(ze,{size:14})})]})}function Cn({onSelect:t,onCancel:a}
67){const[r,l]=o.useState(""),[n,s]=o.useState([]),[i,d]=o.useState(!1),[c,m]=o.useState(!1),p=o.useRef(null);o.useEffect(()=>{let h=!1;async function v(){d(!0);try{const j=await Ve.drive.list({query:{}});h||s(j.data.filter(f=>!f.is_folder))}catch{h||s([])}finally{h||d(!1)}}return v(),()=>{h=!0}},[]);const u=r?n.filter(h=>h.name.toLowerCase().includes(r.toLowerCase())):n,x=h=>{h.key==="Escape"&&(h.stopPropagation(),h.preventDefault(),a())},w=()=>{var h;(h=p.current)==null||h.click()},N=async h=>{const v=h.target.files;if(!(!v||v.length===0)){m(!0);try{const j=v[0],f=new FormData;f.append("file",j);const z=await zs.upload("/api/drive/upload-proxy",f);t(z.id)}catch(j){const f=j instanceof Error?j.message:"Upload failed";ge.error("Upload failed",f)}finally{m(!1),p.current&&(p.current.value="")}}};return e.jsxs("div",{className:"p-2 rounded-[var(--radius-sm)] bg-[var(--color-bg-secondary)] border border-[var(--color-accent-subtle)] space-y-2","data-testid":"drive-picker-inline",onKeyDown:x,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"text",placeholder:"Search Drive files…",value:r,onChange:h=>l(h.target.value),autoFocus:!0,className:"flex-1 px-2 py-1 text-[length:var(--text-body-s)] rounded-[var(--radius-sm)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)]","data-testid":"drive-picker-search"}),e.jsx("button",{onClick:w,disabled:c,className:"px-2 py-1 text-[length:var(--text-label-m)] text-[var(--color-accent)] hover:underline cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"drive-picker-upload",children:c?"Uploading…":"Upload"}),e.jsx("input",{ref:p,type:"file",className:"hidden",onChange:N,"data-testid":"drive-picker-upload-input"}),e.jsx("button",{onClick:a,className:"px-2 py-1 text-[length:var(--text-label-m)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] cursor-pointer",children:"Cancel"})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-0.5",children:i?e.jsx("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] px-2 py-1",children:"Loading…"}):u.length===0?e.jsx("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] px-2 py-1","data-testid":"drive-picker-empty",children:r?`No files match "${r}"`:"No files in Drive yet. Click Upload to add one."}):u.slice(0,50).map(h=>e.jsxs("button",{onClick:()=>t(h.id),className:"w-full flex items-center gap-2 px-2 py-2 rounded-[var(--radius-sm)] hover:bg-[var(--color-bg-tertiary)] text-left cursor-pointer","data-testid":`drive-picker-option-${h.id}`,children:[e.jsx(ot,{size:14,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsx("span",{className:"flex-1 text-[length:var(--text-body-s)] text-[var(--color-text-primary)] truncate",children:h.name}),h.size_bytes!=null&&e.jsx("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)] tabular-nums shrink-0",children:Gl(h.size_bytes)})]},h.id))})]})}function vd({item:t,currency:a,onUpdate:r,onRemove:l}){var v;const[n,s]=o.useState(!1),[i,d]=o.useState(String(t.quantity)),[c,m]=o.useState(String(t.unit_price)),[p,u]=o.useState(String(t.discount_percent)),[x,w]=o.useState(!1),N=async()=>{w(!0);const j=await r({quantity:Number(i)||0,unit_price:Number(c)||0,discount_percent:Number(p)||0});w(!1),j&&s(!1)},h=()=>{d(String(t.quantity)),m(String(t.unit_price)),u(String(t.discount_percent)),s(!1)};return n?e.jsxs("div",{className:"p-2 rounded-[var(--radius-sm)] bg-[var(--color-bg-secondary)] border border-[var(--color-accent-subtle)] space-y-2",children:[e.jsx("div",{className:"font-medium text-[length:var(--text-body-m)] text-[var(--color-text-primary)] truncate",children:t.name}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("label",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:["Qty",e.jsx("input",{type:"number",min:"0",step:"1",value:i,onChange:j=>d(j.target.value),className:"w-full mt-0.5 px-2 py-1 text-[length:var(--text-body-s)] rounded-[var(--radius-sm)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] tabular-nums"})]}),e.jsxs("label",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:["Price",e.jsx("input",{type:"number",min:"0",step:"0.01",value:c,onChange:j=>m(j.target.value),className:"w-full mt-0.5 px-2 py-1 text-[length:var(--text-body-s)] rounded-[var(--radius-sm)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] tabular-nums"})]}),e.jsxs("label",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:["Disc %",e.jsx("input",{type:"number",min:"0",max:"100",step:"0.1",value:p,onChange:j=>u(j.target.value),className:"w-full mt-0.5 px-2 py-1 text-[length:var(--text-body-s)] rounded-[var(--radius-sm)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] tabular-nums"})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(L,{variant:"ghost",size:"compact",onClick:h,disabled:x,children:"Cancel"}),e.jsx(L,{variant:"primary",size:"compact",onClick:N,disabled:x,children:x?"Saving…":"Save"})]})]}):e.jsxs("div",{className:"group flex items-start gap-2 p-2 rounded-[var(--radius-sm)] hover:bg-[var(--color-bg-secondary)] transition-colors",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)] lg:truncate max-lg:two-line-row-title",children:t.name}),((v=t.product)==null?void 0:v.sku)&&e.jsx("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)] shrink-0",children:t.product.sku})]}),e.jsxs("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] tabular-nums",children:[t.quantity," × ",Q(t.unit_price,a??void 0),t.discount_percent>0&&e.jsxs("span",{className:"text-[var(--color-warning)] ml-1",children:["−",t.discount_percent,"%"]})]})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsx("div",{className:"text-[length:var(--text-body-m)] font-semibold text-[var(--color-text-primary)] tabular-nums",children:Q(t.amount,a??void 0)}),e.jsxs("div",{className:"flex items-center gap-0.5 opacity-0 group-hover:opacity-100 pointer-coarse:opacity-100 transition-opacity",children:[e.jsx("button",{onClick:()=>s(!0),"aria-label":`Edit ${t.name}`,className:"p-1 pointer-coarse:w-11 pointer-coarse:h-11 pointer-coarse:p-0 pointer-coarse:inline-flex pointer-coarse:items-center pointer-coarse:justify-center rounded-[var(--radius-sm)] text-[var(--color-text-tertiary)] hover:text-[var(--color-accent)] hover:bg-[var(--color-bg-tertiary)] cursor-pointer",title:"Edit",children:e.jsx(We,{size:12})}),e.jsx("button",{onClick:l,"aria-label":`Remove ${t.name}`,className:"p-1 pointer-coarse:w-11 pointer-coarse:h-11 pointer-coarse:p-0 pointer-coarse:inline-flex pointer-coarse:items-center pointer-coarse:justify-center rounded-[var(--radius-sm)] text-[var(--color-text-tertiary)] hover:text-[var(--color-error)] hover:bg-[var(--color-error-subtle)] cursor-pointer",title:"Remove",children:e.jsx(he,{size:12})})]})]})]})}function bd({dealId:t,currency:a,onAdd:r,onClose:l}){const{products:n}
67=G(),[s,i]=o.useState(""),[d,c]=o.useState(""),[m,p]=o.useState("1"),[u,x]=o.useState("0"),[w,N]=o.useState("0"),[h,v]=o.useState(!1),j=o.useMemo(()=>n.filter(b=>b.is_active),[n]),f=b=>{i(b);const g=j.find(E=>E.id===b);g&&(c(g.name),x(String(g.unit_price)))},z=async()=>{v(!0);const b=await r(t,{product_id:s||void 0,name:s?void 0:d,quantity:Number(m)||0,unit_price:Number(u)||0,discount_percent:Number(w)||0});v(!1),b&&(i(""),c(""),p("1"),x("0"),N("0"),l())},y=(s||d.trim().length>0)&&Number(m)>0&&Number(u)>=0&&!h;return e.jsxs("div",{className:"p-2 rounded-[var(--radius-sm)] bg-[var(--color-bg-secondary)] border border-[var(--color-accent-subtle)] space-y-2",children:[e.jsx("div",{className:"text-[length:var(--text-label-l)] font-medium text-[var(--color-text-primary)]",children:"Add line item"}),j.length>0&&e.jsxs("label",{className:"block text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:["From catalog",e.jsxs("select",{value:s,onChange:b=>f(b.target.value),className:"w-full mt-0.5 px-2 py-1 text-[length:var(--text-body-s)] rounded-[var(--radius-sm)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)]",children:[e.jsx("option",{value:"",children:"— Custom line item —"}),j.map(b=>e.jsxs("option",{value:b.id,children:[b.name,b.sku?` (${b.sku})`:""," — ",Q(b.unit_price,b.currency)]},b.id))]})]}),!s&&e.jsxs("label",{className:"block text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:["Name",e.jsx("input",{type:"text",value:d,onChange:b=>c(b.target.value),placeholder:"e.g. Custom integration",className:"w-full mt-0.5 px-2 py-1 text-[length:var(--text-body-s)] rounded-[var(--radius-sm)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)]"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("label",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:["Qty",e.jsx("input",{type:"number",min:"0",step:"1",value:m,onChange:b=>p(b.target.value),className:"w-full mt-0.5 px-2 py-1 text-[length:var(--text-body-s)] rounded-[var(--radius-sm)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] tabular-nums"})]}),e.jsxs("label",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:["Price (",a,")",e.jsx("input",{type:"number",min:"0",step:"0.01",value:u,onChange:b=>x(b.target.value),className:"w-full mt-0.5 px-2 py-1 text-[length:var(--text-body-s)] rounded-[var(--radius-sm)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] tabular-nums"})]}),e.jsxs("label",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:["Disc %",e.jsx("input",{type:"number",min:"0",max:"100",step:"0.1",value:w,onChange:b=>N(b.target.value),className:"w-full mt-0.5 px-2 py-1 text-[length:var(--text-body-s)] rounded-[var(--radius-sm)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] tabular-nums"})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(L,{variant:"ghost",size:"compact",onClick:l,disabled:h,children:"Cancel"}),e.jsx(L,{variant:"primary",size:"compact",onClick:z,disabled:!y,children:h?"Adding…":"Add"})]})]})}const gd={note:Ds,call:kt,email:Be,meeting:Zo,task:Ss,chat:Jo};function yd(t){return t.type==="email"?"/mail":t.type==="task"?"/tasks":t.type==="meeting"?"/calendar":t.type==="chat"?"/chat":null}const fd={email:"View in Mail",task:"View in Tasks",chat:"View in Chat",meeting:"View in Calendar"};function ps(t){return t?t.startsWith("Sent: ")?"sent":t.startsWith("Received: ")?"received":null:null}function jd(t){return t?t.startsWith("Sent: ")?t.slice(6):t.startsWith("Received: ")?t.slice(10):t:null}function Nd({activity:t}){const a=ps(t.subject),r=jd(t.subject),l=t.source==="auto",n=a==="received"?tn:ht,[s,i]=o.useState(!1),d=t.body??"",c=d.length>180||d.includes(`
68`);return e.jsxs("div",{className:"rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-secondary)] p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a&&e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-[var(--radius-sm)] text-[length:var(--text-label-s)] font-medium ${a==="sent"?"bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]":"bg-[var(--color-success-subtle)] text-[var(--color-success)]"}`,children:[e.jsx(n,{size:11}),a==="sent"?"Sent":"Received"]}),!a&&e.jsx(de,{variant:"default",children:"Email"}),l&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 px-2 py-0.5 rounded-[var(--radius-sm)] bg-[var(--color-purple-subtle)] text-[var(--color-purple)] text-[length:var(--text-label-s)] font-medium",children:[e.jsx(Xt,{size:10}),"Auto"]}),t.user&&e.jsx("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:t.user.display_name}),e.jsx("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-secondary)] ml-auto shrink-0",children:Ce(t.occurred_at||t.created_at)})]}),r&&e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-primary)] font-medium leading-snug",children:r}),t.body&&e.jsx("p",{className:`text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] whitespace-pre-wrap leading-relaxed ${c&&!s?"line-clamp-2":""}`,children:t.body}),t.opened_at&&e.jsxs("p",{className:"inline-flex items-center gap-1 text-[length:var(--text-label-s)] text-[var(--color-success)]",children:[e.jsx(Xo,{size:11}),"Opened ",Ce(t.opened_at)]}),c&&e.jsxs("button",{type:"button",onClick:()=>i(m=>!m),className:"inline-flex items-center gap-1 pointer-coarse:h-11 pointer-coarse:inline-flex pointer-coarse:items-center pointer-coarse:px-3 text-[length:var(--text-label-s)] font-medium text-[var(--color-accent)] hover:underline cursor-pointer",children:[s?e.jsx(ye,{size:12}):e.jsx(Ue,{size:12}),s?"Show less":"Show more"]}),e.jsxs(_s,{to:"/mail",className:"inline-flex items-center gap-1 px-2 py-0.5 pointer-coarse:h-11 pointer-coarse:px-3 pointer-coarse:inline-flex pointer-coarse:items-center rounded-[var(--radius-sm)] bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)] text-[length:var(--text-label-s)] font-medium hover:bg-[var(--color-accent)] hover:text-[var(--color-text-on-accent)] transition-colors duration-[var(--duration-micro)] no-underline",children:[e.jsx(la,{size:11}),"View in Mail"]})]})}function wd({activity:t}){const a=gd[t.type]||ea,r=yd(t),l=fd[t.type],n=t.source==="auto",[s,i]=o.useState(!1),d=t.body??"",c=d.length>180||d.includes(`
69`);return t.type==="email"?e.jsx(Nd,{activity:t}):e.jsxs("div",{className:"flex gap-2 py-2",children:[e.jsx("div",{className:"shrink-0 mt-0.5 text-[var(--color-text-tertiary)]",children:e.jsx(a,{size:14})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(de,{variant:"default",children:fn[t.type]}),n&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 px-2 py-0.5 rounded-[var(--radius-sm)] bg-[var(--color-purple-subtle)] text-[var(--color-purple)] text-[length:var(--text-label-s)] font-medium",children:[e.jsx(Xt,{size:10}),"Auto"]}),t.user&&e.jsx("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:t.user.display_name}),e.jsx("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)] ml-auto shrink-0",children:Ce(t.occurred_at||t.created_at)})]}),t.subject&&e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-primary)] mt-0.5",children:t.subject}),t.body&&e.jsx("p",{className:`text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] mt-0.5 whitespace-pre-wrap ${c&&!s?"line-clamp-2":""}`,children:t.body}),c&&e.jsxs("button",{type:"button",onClick:()=>i(m=>!m),className:"inline-flex items-center gap-1 mt-1 pointer-coarse:h-11 pointer-coarse:inline-flex pointer-coarse:items-center pointer-coarse:px-3 text-[length:var(--text-label-s)] font-medium text-[var(--color-accent)] hover:underline cursor-pointer",children:[s?e.jsx(ye,{size:12}):e.jsx(Ue,{size:12}),s?"Show less":"Show more"]}),t.duration_minutes!=null&&e.jsxs("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:[t.duration_minutes," min"]}),r&&l&&e.jsxs(_s,{to:r,className:"inline-flex items-center gap-1 mt-1 px-2 py-0.5 pointer-coarse:h-11 pointer-coarse:px-3 pointer-coarse:inline-flex pointer-coarse:items-center rounded-[var(--radius-sm)] bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)] text-[length:var(--text-label-s)] font-medium hover:bg-[var(--color-accent)] hover:text-[var(--color-text-on-accent)] transition-colors duration-[var(--duration-micro)] no-underline",children:[e.jsx(la,{size:11}),l]})]})]})}
69function kd({mode:t,onModeChange:a,contacts:r,activeContactId:l,selectedContactIds:n,selectContact:s,toggleContactSelect:i,onUpdate:d,onCreate:c,searchQuery:m,filterLifecycle:p,sortKey:u,sortDirection:x,onSort:w,visibleColumns:N}){const h=o.useMemo(()=>{let v=r;const j=m.trim().toLowerCase();return j&&(v=v.filter(f=>{var z;return f.name.toLowerCase().includes(j)||f.email&&f.email.toLowerCase().includes(j)||f.title&&f.title.toLowerCase().includes(j)||((z=f.company)==null?void 0:z.name)&&f.company.name.toLowerCase().includes(j)})),p!=="all"&&(v=v.filter(f=>f.type==="company"||f.lifecycle_stage===p)),v},[r,m,p]);return e.jsxs("div",{className:"@container/peopleview flex-1 flex flex-col overflow-hidden",children:[t==="by-company"&&e.jsx(Cd,{contacts:h,activeContactId:l,selectedContactIds:n,selectContact:s,toggleContactSelect:i,onUpdate:d}),t==="by-stage"&&e.jsx(_d,{contacts:h.filter(v=>v.type==="person"),activeContactId:l,selectContact:s,onUpdate:d}),t==="list"&&e.jsx(Ad,{contacts:h.filter(v=>v.type==="person"),activeContactId:l,selectedContactIds:n,selectContact:s,toggleContactSelect:i,sortKey:u,sortDirection:x,onSort:w,visibleColumns:N})]})}const Ml="Unknown company";function Cd({contacts:t,activeContactId:a,selectedContactIds:r,selectContact:l,toggleContactSelect:n,onUpdate:s}){var w,N;const i=t.filter(h=>h.type==="company"),d=t.filter(h=>h.type==="person"),c=new Map;for(const h of i)c.set(h.id,h.name);for(const h of d)h.company_id&&!c.has(h.company_id)&&c.set(h.company_id,((w=h.company)==null?void 0:w.name)??Ml);const m=new Map;for(const h of d){const v=h.company_id??null;m.has(v)||m.set(v,[]),m.get(v).push(h)}const p=Array.from(c.keys()).sort((h,v)=>(c.get(h)??"").localeCompare(c.get(v)??"")),u=bs(jt(ys,{activationConstraint:{distance:5}}),jt(gs,{activationConstraint:{delay:200,tolerance:5}}),jt(Wl)),x=h=>{var b,g;pt(!1);const v=String(h.active.id),j=(b=h.over)!=null&&b.id?String(h.over.id):null;if(!j||!j.startsWith("company:"))return;const f=j.slice(8),z=f==="unaffiliated"?null:f;(((g=h.active.data.current)==null?void 0:g.companyId)??null)!==z&&s(v,{company_id:z})};return e.jsx(fs,{sensors:u,onDragStart:()=>pt(!0),onDragEnd:x,onDragCancel:()=>pt(!1),children:e.jsxs("div",{className:"flex-1 overflow-y-auto max-md:mb-4",children:[p.map(h=>{const v=m.get(h)??[];return e.jsx(Ol,{company:{id:h,name:c.get(h)??Ml},people:v,activeContactId:a,selectedContactIds:r,selectContact:l,toggleContactSelect:n},h)}),(((N=m.get(null))==null?void 0:N.length)??0)>0&&e.jsx(Ol,{company:null,people:m.get(null)??[],activeContactId:a,selectedContactIds:r,selectContact:l,toggleContactSelect:n},"unaffiliated")]})})}function Ol({company:t,people:a,activeContactId:r,selectedContactIds:l,selectContact:n,toggleContactSelect:s}){const i=(t==null?void 0:t.id)??"unaffiliated",{setNodeRef:d,isOver:c}=Ns({id:`company:${i}`,data:{companyId:(t==null?void 0:t.id)??null}});return e.jsxs("div",{ref:d,className:`border-b border-[var(--color-bg-tertiary)] transition-colors ${c?"bg-[var(--color-accent-subtle)]":""}`,children:[e.jsxs("button",{type:"button",onClick:()=>t&&n(t.id),className:"w-full flex items-center gap-2 px-4 py-2 bg-[var(--color-bg-secondary)] hover:bg-[var(--color-bg-tertiary)] cursor-pointer text-left transition-colors",children:[e.jsx(Fe,{size:12,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsx("span",{"data-testid":"company-group-header",className:"text-[length:var(--text-label-s)] leading-[var(--lh-label-s)] font-medium text-[var(--color-text-secondary)] truncate",children:(t==null?void 0:t.name)??"Unaffiliated"}),e.jsx("span",{className:"text-[length:var(--text-label-s)] leading-[var(--lh-label-s)] font-medium text-[var(--color-text-tertiary)] tabular-nums px-2 py-0.5 rounded-full bg-[var(--color-bg-tertiary)]",children:a.length})]}),a.length>0&&e.jsx("div",{children:a.map(m=>e.jsx(Sd,{contact:m,isActive:r===m.id,isSelected:l.has(m.id),onClick:()=>n(m.id),onToggleSelect:()=>s(m.id)},m.id))})]})}function Sd({contact:t,isActive:a,isSelected:r,onClick:l,onToggleSelect:n}){const{attributes:s,listeners:i,setNodeRef:d,isDragging:c}=ws({id:t.id,data:{companyId:t.company_id}});return e.jsxs("div",{ref:d,onClick:l,...s,...i,role:"group",className:`group relative flex items-center gap-3 px-4 py-2 border-l-2 border-b border-b-[var(--color-bg-tertiary)] last:border-b-0 transition-colors touch-manipulation cursor-grab active:cursor-grabbing ${c?"opacity-30":""} ${a||r?"border-[var(--color-accent)] bg-[var(--color-accent-subtle)]":"border-transparent hover:bg-[var(--color-bg-secondary)]"}`,"aria-label":`${t.name}. Press space to drag between companies.`,children:[e.jsx("div",{onClick:m=>m.stopPropagation(),onPointerDown:m=>m.stopPropagation(),children:e.jsx(Ae,{checked:r,onCheckedChange:n,"aria-label":`Select ${t.name}`})}),e.jsx(Aa,{name:t.name,size:"xs"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block pr-24 text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)] truncate [@media(pointer:coarse)]:text-[18px] [@media(pointer:coarse)]:leading-6",children:t.name}),t.title&&e.jsx("span",{className:"block pr-24 mt-0.5 text-[length:var(--text-label-s)] leading-[var(--lh-label-s)] text-[var(--color-text-secondary)]",children:t.title}),t.email&&e.jsx("span",{className:"block text-[length:var(--text-label-s)] leading-[var(--lh-label-s)] text-[var(--color-text-tertiary)] break-all",children:t.email})]}),e.jsx(de,{className:"absolute right-3 top-3",variant:t.lifecycle_stage?Pt[t.lifecycle_stage]??"default":"default",children:t.lifecycle_stage?et[t.lifecycle_stage]??t.lifecycle_stage:"—"}),e.jsx(Ue,{size:16,"aria-hidden":"true",className:"absolute bottom-3 right-3 text-[var(--color-text-tertiary)]"})]})}function _d({contacts:t,activeContactId:a,selectContact:r,onUpdate:l}){var N;const[n,s]=o.useState(!0),i=new Map;for(const h of It)i.set(h,[]);i.set(Lt,[]);for(const h of t){const v=h.lifecycle_stage;i.get(v&&i.has(v)?v:Lt).push(h)}const d=(((N=i.get(Lt))==null?void 0:N.length)??0)>0?[Lt,...It]:[...It],c=bs(jt(ys,{activationConstraint:{distance:5}}),jt(gs,{activationConstraint:{delay:200,tolerance:5}}),jt(Wl)),m=h=>{var y,b;pt(!1);
69const v=String(h.active.id),j=(y=h.over)!=null&&y.id?String(h.over.id):null;if(!j||!j.startsWith("stage:"))return;const f=j.slice(6);((b=h.active.data.current)==null?void 0:b.stage)!==f&&l(v,{lifecycle_stage:f})},p=Math.max(0,d.findIndex(h=>{var v;return(((v=i.get(h))==null?void 0:v.length)??0)>0})),u=typeof window<"u"&&window.innerWidth<640?p:0,[x,w]=o.useState(u);return e.jsxs(fs,{sensors:c,onDragStart:()=>pt(!0),onDragEnd:m,onDragCancel:()=>pt(!1),children:[e.jsxs("div",{className:"relative shrink-0 border-b border-[var(--color-bg-tertiary)]",children:[e.jsx("div",{className:"overflow-x-auto mobile-toolbar-scroll","aria-label":"Lifecycle stage summary",role:"region",tabIndex:0,onScroll:h=>{const v=h.currentTarget;s(v.scrollLeft+v.clientWidth<v.scrollWidth-4)},children:e.jsx("div",{className:"flex w-max min-w-full items-center gap-1 px-4 py-2",children:d.map((h,v)=>{var j;return e.jsxs("div",{"aria-current":v===x?"step":void 0,className:`flex min-h-8 items-center gap-2 whitespace-nowrap rounded-[var(--radius-sm)] border-b-2 border-transparent px-2.5 text-[length:var(--text-label-s)] text-[var(--color-text-secondary)] max-sm:rounded-b-none ${v===x?"max-sm:border-[var(--color-accent)] max-sm:font-medium max-sm:text-[var(--color-text-primary)]":""}`,children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-[var(--color-accent)] opacity-70","aria-hidden":!0}),e.jsx("span",{children:ms(h)}),e.jsx("span",{className:"tabular-nums text-[var(--color-text-tertiary)]",children:((j=i.get(h))==null?void 0:j.length)??0})]},h)})})}),n&&e.jsx("div",{className:"pointer-events-none absolute inset-y-0 right-0 flex w-12 items-center justify-end bg-gradient-to-l from-[var(--color-bg-primary)] via-[var(--color-bg-primary)]/90 to-transparent pr-2 md:hidden","aria-hidden":"true",children:e.jsx(Ue,{size:16,className:"text-[var(--color-text-secondary)]"})})]}),e.jsx(_n,{initialIndex:u,columnLabels:d.map(ms),compactMobile:!0,onActiveIndexChange:w,children:e.jsx("div",{className:"flex gap-3 min-h-0 h-full",children:d.map((h,v)=>e.jsx(Dd,{stage:h,position:v+1,totalStages:d.length,people:i.get(h)??[],activeContactId:a,selectContact:r},h))})})]})}function Dd({stage:t,position:a,totalStages:r,people:l,activeContactId:n,selectContact:s}){const{setNodeRef:i,isOver:d}=Ns({id:`stage:${t}`,data:{stage:t},disabled:t===Lt});return e.jsxs("div",{"data-testid":`crm-people-stage-column-${t}`,className:"flex h-full min-h-0 min-w-[calc(100vw-2rem)] max-w-[calc(100vw-2rem)] flex-1 flex-col max-sm:flex-none max-sm:snap-center sm:min-w-[180px] sm:max-w-[300px]",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-3 mb-2 rounded-[var(--radius-md)] bg-[var(--color-bg-secondary)]",children:[e.jsx("span",{className:"text-[length:var(--text-title-s)] leading-[var(--lh-title-s)] font-semibold text-[var(--color-text-primary)]",children:ms(t)}),e.jsx("span",{className:"inline-flex items-center justify-center min-w-[20px] h-5 px-2 rounded-full bg-[var(--color-bg-tertiary)] text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] tabular-nums",children:l.length}),e.jsxs("span",{className:"ml-auto text-[length:var(--text-label-s)] tabular-nums text-[var(--color-text-tertiary)] sm:hidden",children:[a," of ",r]})]}),e.jsxs("div",{ref:i,className:`min-h-0 flex-1 space-y-2 overflow-y-auto rounded-[var(--radius-md)] px-0.5 transition-colors ${d?"bg-[var(--color-accent-subtle)] outline outline-2 outline-[var(--color-accent)]":""}`,children:[l.map(c=>e.jsx(zd,{person:c,isActive:n===c.id,onClick:()=>s(c.id)},c.id)),l.length===0&&e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] text-center py-6",children:"No people"}),t===Lt&&l.length>0&&e.jsx("p",{className:"px-1 pb-2 pt-1 text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)]",children:"Drag onto a stage to classify."})]})]})}function zd({person:t,isActive:a,onClick:r}){var c;const{attributes:l,listeners:n,setNodeRef:s,setActivatorNodeRef:i,isDragging:d}=ws({id:t.id,data:{stage:t.lifecycle_stage}});return e.jsxs("div",{ref:s,onClick:r,className:`group relative p-3 rounded-[var(--radius-md)] border transition-colors touch-manipulation cursor-pointer ${d?"opacity-30":""} ${a?"border-[var(--color-accent)] bg-[var(--color-accent-subtle)]":"border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] hover:border-[var(--color-text-quaternary)]"}`,children:[e.jsx("button",{type:"button",ref:i,...l,...n,"aria-label":`Move ${t.name} between lifecycle stages`,onClick:m=>m.stopPropagation(),className:"absolute top-0 right-0 inline-flex h-6 w-6 pointer-coarse:h-11 pointer-coarse:w-11 items-center justify-center text-[var(--color-text-quaternary)] opacity-0 group-hover:opacity-60 focus:opacity-100 [@media(hover:none)]:opacity-60 transition-opacity cursor-grab active:cursor-grabbing touch-none",children:e.jsx(Zl,{size:14})}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Aa,{name:t.name,lifecycleStage:t.lifecycle_stage,size:"xs"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)] truncate",children:t.name}),t.title&&e.jsx("p",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)] truncate",children:t.title}),((c=t.company)==null?void 0:c.name)&&e.jsx("p",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)] truncate",children:t.company.name})]})]})]})}function $d(t){if(!t)return"none";const a=(Date.now()-new Date(t).getTime())/864e5;return a<7?"recent":a<30?"stale":"cold"}function hs({allSelected:t,someSelected:a,onToggleAll:r,sortKey:l,sortDirection:n,onSort:s,visibleColumns:i=new Set(Es)}){return e.jsxs("div",{className:"group flex items-center gap-3 px-4 py-3 border-b border-[var(--color-bg-tertiary)] bg-[var(--color-bg-secondary)]",children:[e.jsx("div",{className:"w-5 shrink-0 flex items-center justify-center",children:e.jsx(Ae,{checked:t?!0:a?"indeterminate":!1,onCheckedChange:r,"aria-label":"Select all people"})}),e.jsx(Kt,{label:"Person",field:"name",sortKey:l,sortDirection:n,onSort:s,className:"flex-[3.2] min-w-[13rem] text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)]"}),i.has("phone")&&e.jsx(Kt,{label:"Phone",field:"phone",sortKey:l,sortDirection:n,onSort:s,className:"w-[120px] shrink-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] hidden @[1100px]/peoplelist:flex tabular-nums"}),i.has("company")&&e.jsx(Kt,{label:"Company",field:"company",sortKey:l,sortDirection:n,onSort:s,className:"flex-[2.2] min-w-[10rem] text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] hidden @[800px]/peoplelist:flex"}),i.has("lists")&&e.jsx("span",{className:"w-[120px] shrink-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] hidden @[800px]/peoplelist:block",children:"Lists"}),i.has("stage")&&e.jsx(Kt,{label:"Stage",field:"stage",sortKey:l,sortDirection:n,onSort:s,className:"w-[100px] shrink-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] hidden @[800px]/peoplelist:flex"}
69),i.has("owner")&&e.jsx(Kt,{label:"Owner",field:"owner",sortKey:l,sortDirection:n,onSort:s,className:"w-28 shrink-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] hidden @[800px]/peoplelist:flex"}),i.has("last_contacted")&&e.jsx(Kt,{label:"Last contacted",field:"last_contacted",sortKey:l,sortDirection:n,onSort:s,className:"w-[82px] shrink-0 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] tabular-nums hidden @[560px]/peoplelist:flex"}),e.jsx("span",{"aria-hidden":"true",className:"w-[18px] shrink-0"})]})}function Kt({label:t,field:a,sortKey:r,sortDirection:l,onSort:n,className:s}){const i=r===a;return e.jsxs("button",{type:"button",onClick:()=>n(a),"aria-label":`Sort by ${t}${i?`, currently ${l==="asc"?"ascending":"descending"}`:""}`,"aria-pressed":i,className:`${s} flex items-center justify-start gap-1 text-left hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] rounded-[var(--radius-sm)]`,children:[t,e.jsx(ye,{size:12,className:`transition-transform ${i&&l==="asc"?"rotate-180":""} ${i?"opacity-100":"opacity-0 group-hover:opacity-60"}`})]})}function Sn({contact:t,isActive:a,isSelected:r,onClick:l,onToggleSelect:n,visibleColumns:s=new Set(Es)}){var i,d;return e.jsxs("div",{className:`flex items-center gap-3 px-4 py-3 border-b cursor-pointer transition-colors ${a?"bg-[var(--color-accent-subtle)] border-[var(--color-accent)]":r?"bg-[var(--color-bg-secondary)] border-[var(--color-accent)] border-dashed":"border-[var(--color-bg-tertiary)] hover:bg-[var(--color-bg-secondary)]"}`,onClick:l,"data-testid":"person-list-row",children:[e.jsx("div",{className:"w-5 shrink-0 flex items-center justify-center",onClick:c=>c.stopPropagation(),children:e.jsx(Ae,{checked:r,onCheckedChange:n,"aria-label":`Select ${t.name}`})}),e.jsxs("div",{className:"flex-[3.2] min-w-[13rem] flex items-center gap-2",children:[e.jsx(Aa,{name:t.name,size:"xs"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{"data-testid":"person-list-row-name",className:"text-[length:var(--text-body-m)] text-[var(--color-text-primary)] truncate font-semibold hover:underline block [@media(pointer:coarse)]:text-[18px] [@media(pointer:coarse)]:leading-6",children:t.name}),s.has("email")&&e.jsx("span",{className:"truncate text-[length:var(--text-label-s)] leading-[var(--lh-label-s)] text-[var(--color-text-secondary)] block @[560px]/peoplelist:hidden",children:t.email??"No email"}),e.jsx("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)] truncate block @[560px]/peoplelist:hidden",children:[t.title||(t.type==="company"?"Company":"Contact"),t.lifecycle_stage?et[t.lifecycle_stage]??t.lifecycle_stage:null,(i=t.groups)!=null&&i.length?`${t.groups.length} ${t.groups.length===1?"list":"lists"}`:null].filter(Boolean).join(" · ")}),s.has("email")&&e.jsx("span",{className:"hidden whitespace-nowrap text-[length:var(--text-label-s)] leading-[var(--lh-label-s)] text-[var(--color-text-secondary)] @[560px]/peoplelist:block",children:t.email??"No email"})]})]}),s.has("phone")&&e.jsx("div",{className:"w-[120px] shrink-0 hidden @[1100px]/peoplelist:block text-[length:var(--text-body-m)] text-[var(--color-text-secondary)] truncate tabular-nums",children:t.phone??e.jsx("span",{className:"text-[var(--color-text-quaternary)]",children:"—"})}),s.has("company")&&e.jsx("div",{className:"flex-[2.2] min-w-[10rem] hidden @[800px]/peoplelist:flex items-center gap-1 text-[length:var(--text-body-m)] leading-5 text-[var(--color-text-secondary)]",children:(d=t.company)!=null&&d.name?e.jsxs(e.Fragment,{children:[e.jsx(Fe,{size:12,className:"shrink-0 text-[var(--color-text-quaternary)]"}),e.jsx("span",{className:"break-words",children:t.company.name})]}):e.jsx("span",{className:"font-medium text-[var(--color-text-primary)]",children:"—"})}),s.has("lists")&&e.jsx("div",{className:"hidden w-[120px] shrink-0 @[800px]/peoplelist:block",onClick:c=>c.stopPropagation(),children:e.jsx(Ps,{contact:t,compact:!0})}),s.has("stage")&&e.jsx("div",{className:"w-[100px] shrink-0 hidden @[800px]/peoplelist:block",children:e.jsx(de,{variant:t.lifecycle_stage?Pt[t.lifecycle_stage]??"default":"default",children:t.lifecycle_stage?et[t.lifecycle_stage]??t.lifecycle_stage:"—"})}),s.has("owner")&&e.jsx("div",{className:"w-28 shrink-0 hidden @[800px]/peoplelist:flex items-center gap-2",children:t.owner?e.jsxs(e.Fragment,{children:[e.jsx(Je,{src:t.owner.avatar_url,name:t.owner.dis
69play_name,size:"xs"}),e.jsx("span",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-secondary)] truncate",children:t.owner.display_name})]}):e.jsx("span",{className:"font-medium text-[var(--color-text-primary)]",children:"—"})}),(()=>{const c=$d(t.last_contacted_at),m=c==="cold"?"text-[var(--color-error-text)] font-medium":c==="stale"?"text-[var(--color-warning-text)] font-medium":c==="recent"?"text-[var(--color-text-secondary)]":"text-[var(--color-text-tertiary)]";return s.has("last_contacted")?e.jsx("div",{className:`w-[82px] shrink-0 hidden @[560px]/peoplelist:block text-[length:var(--text-body-m)] tabular-nums ${m}`,"data-last-contacted-status":c,children:t.last_contacted_at?Ce(t.last_contacted_at):e.jsx("span",{className:"font-medium text-[var(--color-text-primary)]",children:"—"})}):null})(),e.jsx(Ue,{size:18,"aria-hidden":"true",className:"shrink-0 text-[var(--color-text-secondary)]"})]})}function Ad({contacts:t,activeContactId:a,selectedContactIds:r,selectContact:l,toggleContactSelect:n,sortKey:s,sortDirection:i,onSort:d,visibleColumns:c}){const m=o.useMemo(()=>gn(t,s,i),[t,s,i]),p=o.useRef(null),u=ks({count:m.length,getScrollElement:()=>p.current,estimateSize:()=>52,overscan:10}),x=t.length>0&&t.every(h=>r.has(h.id)),w=!x&&t.some(h=>r.has(h.id)),N=()=>{if(x)for(const h of t)n(h.id);else for(const h of t)r.has(h.id)||n(h.id)};return t.length===0?e.jsxs("div",{className:"@container/peoplelist flex-1 flex flex-col",children:[e.jsx(hs,{allSelected:!1,someSelected:!1,onToggleAll:N,sortKey:s,sortDirection:i,onSort:d,visibleColumns:c}),e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx("p",{className:"text-[length:var(--text-body-m)] text-[var(--color-text-quaternary)]",children:"No people match your filters"})})]}):e.jsxs("div",{className:"@container/peoplelist flex-1 flex flex-col min-h-0",children:[e.jsx(hs,{allSelected:x,someSelected:w,onToggleAll:N,sortKey:s,sortDirection:i,onSort:d,visibleColumns:c}),e.jsx("div",{ref:p,className:"flex-1 overflow-y-auto max-md:mb-4",children:e.jsx("div",{style:{height:`${u.getTotalSize()}px`,width:"100%",position:"relative"},children:u.getVirtualItems().map(h=>{const v=m[h.index];return e.jsx("div",{ref:u.measureElement,"data-index":h.index,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${h.start}px) translateZ(0)`,willChange:"transform"},children:e.jsx(Sn,{contact:v,isActive:a===v.id,isSelected:r.has(v.id),onClick:()=>l(v.id),onToggleSelect:()=>n(v.id),visibleColumns:c})},h.key)})})})]})}function Zr({onRetry:t}){return e.jsx("div",{className:"flex flex-1 items-center justify-center",role:"alert","data-testid":"crm-people-error",children:e.jsx(De,{icon:e.jsx(Kl,{size:28,className:"text-[var(--color-error-text)]"}),title:"People couldn’t load",description:"Check your connection, then try again. Your CRM data is unchanged.",action:e.jsx(L,{variant:"secondary",onClick:t,className:"pointer-coarse:h-11",children:"Try again"})})})}const Td=["pipelines","products","scoring","templates","custom_fields"],ql=[{id:"pipelines",label:"Pipelines",icon:Nt},{id:"products",label:"Products",icon:Ct},{id:"templates",label:"Deal templates",icon:Ca},{id:"scoring",label:"Scoring",icon:Yl},{id:"custom_fields",label:"Properties",icon:ot}];function Ed(t){return Td.includes(t)}function Ld(){const{view:t,setView:a}=G(),r=si(),l=Ed(t)?t:"pipelines";return e.jsxs("div",{className:"flex flex-1 min-w-0 min-h-0 flex-col overflow-hidden max-md:[&:has([data-testid=crm-editor-header])>[data-testid=crm-settings-navigation]]:hidden max-md:[&_[data-testid=crm-surface-leading]]:hidden","data-testid":"crm-tools-content",children:[e.jsxs("div",{className:"shrink-0 bg-[var(--color-bg-primary)]","data-testid":"crm-settings-navigation",children:[e.jsx("div",{className:"hidden px-4 pt-3 text-[length:var(--text-label-s)] font-medium uppercase tracking-wide text-[var(--color-text-tertiary)] md:block",children:"CRM settings"}),e.jsxs("div",{className:"flex items-center gap-3 px-3 pt-2 md:hidden",children:[r,e.jsx("span",{className:"text-[length:var(--text-title-m)] font-semibold text-[var(--color-text-primary)]",children:"CRM settings"})]}),e.jsx("div",{className:"border-b border-[var(--color-bg-tertiary)] px-3 py-2 md:hidden",children:e.jsxs(me,{value:l,onValueChange:n=>a(n),children:[e.jsx(ue,{"aria-label":"CRM settings section",className:"h-11 w-full",children:e.jsx(ve,{})}),e.jsx(pe,{children:ql.map(n=>e.jsx(te,{value:n.id,children:n.label},n.id))})]})}
69),e.jsx(hr,{items:ql,value:l,onChange:n=>a(n),"aria-label":"CRM settings sections",className:"hidden px-2 pt-1 md:flex"})]}),e.jsx("div",{className:"flex min-h-0 flex-1 overflow-hidden bg-[var(--color-bg-primary)]",children:e.jsxs("div",{className:"flex h-full min-h-0 min-w-0 w-full flex-1 self-stretch overflow-hidden bg-[var(--color-bg-primary)]",children:[l==="pipelines"&&e.jsx($c,{}),l==="products"&&e.jsx(_c,{}),l==="scoring"&&e.jsx(hc,{}),l==="templates"&&e.jsx(Lc,{}),l==="custom_fields"&&e.jsx(Qc,{})]})})]})}function pt(t){typeof document>"u"||(t?document.body.classList.add("is-dragging"):document.body.classList.remove("is-dragging"))}function _n({children:t,initialIndex:a=0,columnLabels:r=[],compactMobile:l=!1,onActiveIndexChange:n}){const s=o.useRef(null),[i,d]=o.useState({left:!1,right:!1}),[c,m]=o.useState(0),[p,u]=o.useState(0);o.useEffect(()=>{const w=s.current;if(!w)return;const N=w.firstElementChild,h=()=>{const{scrollLeft:j,scrollWidth:f,clientWidth:z}=w;d({left:j>2,right:j+z<f-2});const y=(N==null?void 0:N.children.length)??0;if(m(y),y>0&&f>z){const b=(f-z)/Math.max(1,y-1),g=Math.max(0,Math.min(y-1,Math.round(j/Math.max(1,b))));u(g),n==null||n(g)}else u(0),n==null||n(0)};h(),a>0&&N&&requestAnimationFrame(()=>{const j=N.children.length;if(j<=1)return;const f=(w.scrollWidth-w.clientWidth)/Math.max(1,j-1);w.scrollLeft=f*Math.min(a,j-1),h()}),w.addEventListener("scroll",h,{passive:!0});const v=typeof ResizeObserver<"u"?new ResizeObserver(h):null;return v==null||v.observe(w),N&&(v==null||v.observe(N)),()=>{w.removeEventListener("scroll",h),v==null||v.disconnect()}},[a,n]);const x=w=>{const N=s.current;if(!N||c<=1)return;const h=(N.scrollWidth-N.clientWidth)/Math.max(1,c-1);N.scrollTo({left:h*w,behavior:"smooth"})};return e.jsxs("div",{className:`relative flex min-h-0 min-w-0 flex-1 flex-col ${l?"max-sm:flex-none":""}`,children:[e.jsxs("div",{className:`relative min-h-0 min-w-0 flex-1 ${l?"max-sm:flex-none":""}`,children:[e.jsx("div",{ref:s,"data-testid":"board-scroll",className:`h-full overflow-x-auto overflow-y-hidden p-4 max-sm:snap-x max-sm:snap-mandatory ${l?"max-sm:h-auto":""}`,children:t}),e.jsx("div",{"aria-hidden":!0,"data-testid":"board-fade-left","data-visible":i.left?"true":"false",className:"pointer-events-none absolute inset-y-0 left-0 w-8 transition-opacity duration-150",style:{background:"linear-gradient(to right, var(--color-bg-primary), transparent)",opacity:i.left?1:0}}),e.jsx("div",{"aria-hidden":!0,"data-testid":"board-fade-right","data-visible":i.right?"true":"false",className:"pointer-events-none absolute inset-y-0 right-0 w-8 transition-opacity duration-150",style:{background:"linear-gradient(to left, var(--color-bg-primary), transparent)",opacity:i.right?1:0}})]}),!l&&c>1&&(i.left||i.right)&&e.jsxs("div",{"data-testid":"board-position",className:"flex sm:hidden items-center justify-center gap-3 px-4 py-2 shrink-0 border-t border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)]","aria-label":`Column ${p+1} of ${c}`,children:[e.jsxs("button",{type:"button","aria-label":r[p-1]?`Previous column: ${r[p-1]}`:"Previous column",disabled:p===0,onClick:()=>x(p-1),className:"inline-flex h-11 min-w-11 max-w-[116px] items-center justify-center gap-1 rounded-full px-2 text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-secondary)] disabled:opacity-30",children:[e.jsx(Xl,{size:16}),e.jsx("span",{className:"truncate text-[length:var(--text-label-s)]",children:r[p-1]??"Previous"})]}),e.jsxs("span",{className:"min-w-20 max-w-[120px] truncate text-center text-[length:var(--text-label-m)] font-medium text-[var(--color-text-primary)]",children:[r[p]??`Column ${p+1}`,e.jsxs("span",{className:"block text-[length:var(--text-label-s)] font-normal tabular-nums text-[var(--color-text-tertiary)]",children:[p+1," of ",c]})]}),e.jsxs("button",{type:"button","aria-label":r[p+1]?`Next column: ${r[p+1]}`:"Next column",disabled:p===c-1,onClick:()=>x(p+1),className:"inline-flex h-11 min-w-11 max-w-[116px] items-center justify-center gap-1 rounded-full px-2 text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-secondary)] disabled:opacity-30",children:[e.jsx("span",{className:"truncate text-[length:var(--text-label-s)]",children:r[p+1]??"Next"}),e.jsx(Ue,{size:16})]})]})]})}function Id({stages:t,dealsByStage:a,activeDealId:r,selectedDealIds:l,onSelectDeal:n,onToggleDealSelect:s,onDealDropped:i,onCreateDealInStage:d}){const c=bs(jt(ys,{activationConstraint:{distance:5}}),jt(gs,{activationConstraint:{delay:200,tolerance:5}}
69)),[m,p]=o.useState(null),u=o.useMemo(()=>{const h=[];for(const v of t)h.push(...a[v.id]??[]);return h},[t,a]),x=m?u.find(h=>h.id===m):null,w=h=>{pt(!0),p(String(h.active.id))},N=h=>{var y,b;pt(!1),p(null);const v=String(h.active.id),j=(y=h.over)!=null&&y.id?String(h.over.id):null;if(!j||!j.startsWith("stage:"))return;const f=j.slice(6);((b=h.active.data.current)==null?void 0:b.stageId)!==f&&i(v,f)};return e.jsxs(fs,{sensors:c,collisionDetection:Eo,measuring:{droppable:{strategy:To.Always}},onDragStart:w,onDragEnd:N,onDragCancel:()=>{pt(!1),p(null)},children:[e.jsx(_n,{initialIndex:Math.max(0,t.findIndex(h=>{var v;return(((v=a[h.id])==null?void 0:v.length)??0)>0})),columnLabels:t.map(h=>h.name),children:e.jsx("div",{className:"flex gap-3 min-h-0 h-full",children:t.map(h=>e.jsx(ld,{stage:h,deals:a[h.id]||[],activeDealId:r,selectedDealIds:l,onSelectDeal:n,onToggleDealSelect:s,onMoveDealByKeyboard:(v,j)=>{const f=t.findIndex(b=>b.id===v.stage_id),y=t[f+(j==="next"?1:-1)];y&&i(v.id,y.id)},onCreateDealInStage:d},h.id))})}),e.jsx(Lo,{children:x&&e.jsxs("div",{className:"p-3 rounded-[var(--radius-md)] border border-[var(--color-accent)] bg-[var(--color-bg-primary)] shadow-[var(--shadow-lg)] max-w-[280px] cursor-grabbing",children:[e.jsx("p",{className:"text-[length:var(--text-body-m)] font-medium text-[var(--color-text-primary)] truncate",children:x.title}),x.amount!=null&&e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] tabular-nums",children:Q(x.amount,x.currency??void 0)})]})})]})}function Pd({dealId:t}){const a=sa(),[r,l]=o.useState([]),[n,s]=o.useState(!0);return o.useEffect(()=>{let i=!1;return(async()=>{try{const d=await Ve.crm.quotes.list({query:{deal_id:t}});i||l(d.data)}catch(d){console.error("[crm] Failed to load deal quotes:",d)}finally{i||s(!1)}})(),()=>{i=!0}},[t]),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-tertiary)]",children:["Quotes (",r.length,")"]}),e.jsxs("button",{type:"button",onClick:()=>a(`/crm/quotes?deal_id=${t}`),className:"text-[length:var(--text-label-s)] font-medium text-[var(--color-accent)] hover:underline cursor-pointer flex items-center gap-1 pointer-coarse:min-h-11 pointer-coarse:inline-flex pointer-coarse:items-center",children:[e.jsx(oe,{size:12}),"New quote"]})]}),n?e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-quaternary)]",children:"Loading…"}):r.length===0?e.jsx(Ta,{icon:ot,title:"No quotes yet",description:"Turn line items into a branded PDF quote you can send for e-signature.",cta:{label:"+ New quote",onClick:()=>a(`/crm/quotes?deal_id=${t}`)},testId:"deal-quotes-empty"}):e.jsx("div",{className:"space-y-1",children:r.map(i=>e.jsxs("button",{type:"button",onClick:()=>a(`/crm/quotes?id=${i.id}`),className:"w-full flex items-center gap-2 px-2 py-2 rounded-[var(--radius-sm)] hover:bg-[var(--color-bg-secondary)] cursor-pointer transition-colors text-left",children:[e.jsx(ot,{size:14,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-primary)] truncate flex-1",children:i.quote_number}),e.jsx("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)] capitalize",children:i.status}),e.jsx("span",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-primary)] tabular-nums",children:Q(i.total,i.currency)})]},i.id))})]})}function Dn(t){const[a,r]=o.useState([]),[l,n]=o.useState(!0),[s,i]=o.useState(""),[d,c]=o.useState(!1),m="contactId"in t?`contact_id=${t.contactId}`:`deal_id=${t.dealId}`,p="contactId"in t?{contact_id:t.contactId}:{deal_id:t.dealId},u=o.useCallback(async()=>{try{const v=await zs.get(`/api/tasks?${m}&limit=50`);r(v.data)}catch(v){console.error("[crm] Failed to load tasks:",v)}finally{n(!1)}},[m]);o.useEffect(()=>{u()},[u,t.refreshKey]);const x=async v=>{v.preventDefault();const j=s.trim();if(j){c(!0);try{await Ve.tasks.create({body:{title:j,...p}}),i(""),u()}catch(f){console.error("[crm] Failed to create task:",f)}finally{c(!1)}}},w=async(v,j)=>{const f=j==="done"?"todo":"done";r(z=>z.map(y=>y.id===v?{...y,status:f}:y));try{await Ve.tasks.update({params:{id:v},body:{status:f}})}catch(z){console.error("[crm] Failed to toggle task:",z),u()}},N=a.filter(v=>
69v.status!=="done"&&v.status!=="cancelled"),h=a.filter(v=>v.status==="done");return e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("label",{className:"text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)]",children:["Tasks (",N.length,")"]})}),l?e.jsx("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:"Loading…"}):e.jsxs("div",{className:"space-y-1",children:[N.map(v=>e.jsxs("button",{type:"button",onClick:()=>w(v.id,v.status),className:"w-full flex items-start gap-2 text-left px-2 py-1 -mx-2 rounded-[var(--radius-sm)] hover:bg-[var(--color-bg-secondary)] transition-colors duration-[var(--duration-micro)] cursor-pointer",children:[e.jsx(yr,{size:16,className:"text-[var(--color-text-tertiary)] shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-primary)] block truncate",children:v.title}),v.due_date&&e.jsxs("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:["Due ",Ce(v.due_date)]})]})]},v.id)),h.length>0&&e.jsxs("details",{className:"text-[length:var(--text-body-s)]",children:[e.jsxs("summary",{className:"cursor-pointer text-[var(--color-text-tertiary)] py-1",children:[h.length," completed"]}),e.jsx("div",{className:"space-y-1 mt-1",children:h.map(v=>e.jsxs("button",{type:"button",onClick:()=>w(v.id,v.status),className:"w-full flex items-start gap-2 text-left px-2 py-1 -mx-2 rounded-[var(--radius-sm)] hover:bg-[var(--color-bg-secondary)] transition-colors cursor-pointer",children:[e.jsx(Se,{size:16,className:"text-[var(--color-success)] shrink-0 mt-0.5"}),e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] line-through truncate",children:v.title})]},v.id))})]}),e.jsxs("form",{onSubmit:x,className:"flex items-center gap-2 pt-1","data-testid":"deal-tasks-inline-add",children:[e.jsx(oe,{size:14,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsx("input",{type:"text",value:s,onChange:v=>i(v.target.value),placeholder:N.length===0&&h.length===0?"Add the first task…":"Add a task…",disabled:d,className:"flex-1 min-w-0 bg-transparent border-none outline-none text-[length:var(--text-body-s)] text-[var(--color-text-primary)] placeholder:text-[var(--color-text-quaternary)] focus:outline-none focus-visible:outline-none"})]})]})]})}function Rd({companyId:t,personIds:a,refreshKey:r}){const[l,n]=o.useState([]),[s,i]=o.useState(!0),d=a.join(","),c=o.useCallback(async()=>{i(!0);try{const x=[t,...d.split(",").filter(Boolean)],w=await Promise.allSettled(x.map(h=>zs.get(`/api/tasks?contact_id=${h}&limit=50`))),N=new Map;for(const h of w)if(h.status==="fulfilled")for(const v of h.value.data)N.set(v.id,v);n(Array.from(N.values()))}catch(x){console.error("[crm] Failed to load company tasks:",x)}finally{i(!1)}},[t,d]);o.useEffect(()=>{c()},[c,r]);const m=async(x,w)=>{const N=w==="done"?"todo":"done";n(h=>h.map(v=>v.id===x?{...v,status:N}:v));try{await Ve.tasks.update({params:{id:x},body:{status:N}})}catch(h){console.error("[crm] Failed to toggle task:",h),c()}},p=l.filter(x=>x.status!=="done"&&x.status!=="cancelled"),u=l.filter(x=>x.status==="done");return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"normal-case text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)]",children:["Tasks (",p.length,")"]}),s?e.jsx("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-quaternary)]",children:"Loading…"}):p.length===0&&u.length===0?e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)]",children:"No tasks across company and people"}):e.jsxs("div",{className:"space-y-1",children:[p.map(x=>e.jsxs("button",{type:"button",onClick:()=>m(x.id,x.status),className:"w-full flex items-start gap-2 text-left px-2 py-1 -mx-2 rounded-[var(--radius-sm)] hover:bg-[var(--color-bg-secondary)] transition-colors cursor-pointer",children:[e.jsx(yr,{size:16,className:"text-[var(--color-text-tertiary)] shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-primary)] block truncate",children:x.title}),x.due_date&&e.jsxs("span",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:["Due ",Ce(x.due_date)]})]})]},x.id)),u.length>0&&e.jsxs("details",{className:"text-[length:var(--text-body-s)]",children:[e.jsxs("summary",{className:"cursor-pointer text-[var(--color-text-tertiary)] py-1",children:[u.length," completed"]}),e.jsx("div",{className:"space-y-1 mt-1",children:u.map(x=>e.jsxs("button",{type:"button",onClick:()=>m(x.id,x.status),className:"w-full flex items-start gap-2 text-left px-2 py-1 -mx-2 rounded-[var(--radius-sm)] hover:bg-[var(--color-bg-secondary)] transition-colors cursor-pointer",children:[e.jsx(Se,{size:16,className:"text-[var(--color-success)] shrink-0 mt-0.5"}),e.jsx("span",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-tertiary)] line-through truncate",children:x.title})]},x.id))})]})]})]})}function Fd({deal:t,refreshKey:a}){return e.jsx(Dn,{dealId:t.id,refreshKey:a})}function Md({deal:t,contacts:a,onUpdate:r}){const[l,n]=o.useState(!1),[s,i]=o.useState(""),[d,c]=o.useState(!1),m=async()=>
69{if(s){c(!0);try{await r(t.id,{contact_id:s})}finally{c(!1),n(!1),i("")}}};return e.jsxs("div",{className:"space-y-2","data-testid":"deal-contact-field",children:[e.jsx("label",{className:"text-[length:var(--text-body-s)] font-medium text-[var(--color-text-tertiary)]",children:"Contact"}),t.contact?e.jsxs("div",{className:"flex items-center gap-2","data-testid":"deal-contact-field-display",children:[e.jsx(Ne,{size:16,className:"text-[var(--color-text-tertiary)]"}),e.jsx(cr,{module:"CRM",entityId:t.contact.id,children:e.jsx("a",{href:`/crm/contacts?contact=${t.contact.id}`,"data-testid":"deal-contact-field-name",className:"text-[length:var(--text-body-m)] text-[var(--color-text-primary)] underline decoration-transparent decoration-dotted underline-offset-2 hover:decoration-[var(--color-text-tertiary)] focus-visible:outline-2 focus-visible:outline-[var(--color-accent)] focus-visible:outline-offset-2",children:t.contact.name})})]}):l?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("select",{value:s,onChange:p=>i(p.target.value),"aria-label":"Select contact","data-testid":"deal-contact-field-select",className:"flex-1 h-8 px-2 rounded-[var(--radius-sm)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[length:var(--text-body-s)] text-[var(--color-text-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)] cursor-pointer",children:[e.jsx("option",{value:"",children:"Choose a contact…"}),a.map(p=>e.jsx("option",{value:p.id,children:p.name},p.id))]}),e.jsx(L,{size:"compact",onClick:m,disabled:!s||d,"data-testid":"deal-contact-field-confirm",children:d?"Saving…":"Save"}),e.jsx(L,{size:"compact",variant:"ghost",onClick:()=>{n(!1),i("")},disabled:d,children:"Cancel"})]}):a.length>0?e.jsxs("button",{type:"button",onClick:()=>n(!0),className:"inline-flex items-center gap-2 text-[length:var(--text-body-s)] text-[var(--color-accent)] hover:text-[var(--color-accent-hover)] cursor-pointer","data-testid":"deal-contact-field-link-button",children:[e.jsx(Ne,{size:14}),"Link contact"]}):e.jsx("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-quaternary)]",children:"No contacts yet — create one first."})]})}const Xr={messages:["email","chat"],meetings:["meeting","call"]};function Rs({activities:t,onLogActivity:a}){const[r,l]=o.useState("all"),n=o.useMemo(()=>r==="all"?t:t.filter(d=>Xr[r].includes(d.type)),[t,r]),s=o.useMemo(()=>{const d=t.filter(x=>x.type==="email"),c=d.filter(x=>ps(x.subject)==="sent").length,m=d.filter(x=>ps(x.subject)==="received").length,p=d.filter(x=>x.source==="auto").length,u=d.length-p;return{total:d.length,sent:c,received:m,autoLogged:p,manualLogged:u}},[t]),i=[{key:"all",label:"All",count:t.length},{key:"messages",label:"Messages",count:t.filter(d=>Xr.messages.includes(d.type)).length},{key:"meetings",label:"Meetings",count:t.filter(d=>Xr.meetings.includes(d.type)).length}];return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] tabular-nums",children:r==="all"?`Activity (${t.length})`:`Activity (filtered ${n.length} of ${t.length})`}),e.jsx("button",{onClick:a,className:"text-[length:var(--text-label-s)] text-[var(--color-accent)] pointer-coarse:min-h-11 pointer-coarse:inline-flex pointer-coarse:items-center hover:underline cursor-pointer",children:"+ Log"})]}),s.total>0&&e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 rounded-[var(--radius-md)] bg-[var(--color-bg-secondary)] border border-[var(--color-bg-tertiary)]",children:[e.jsx(Be,{size:14,className:"text-[var(--color-text-tertiary)] shrink-0"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[length:var(--text-label-s)] text-[var(--color-text-secondary)]",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ht,{size:10,className:"text-[var(--color-accent)]"}),e.jsx("span",{className:"tabular-nums font-medium",children:s.sent})," sent"]}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:"text-[var(--color-bg-tertiary)]",children:"·"}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(tn,{size:10,
69className:"text-[var(--color-success)]"}),e.jsx("span",{className:"tabular-nums font-medium",children:s.received})," received"]})]}),s.autoLogged>0&&e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:"text-[var(--color-bg-tertiary)]",children:"·"}),e.jsxs("span",{className:"inline-flex items-center gap-1",title:"Auto-logged from Mail module",children:[e.jsx(Xt,{size:10,className:"text-[var(--color-purple)]"}),e.jsx("span",{className:"tabular-nums font-medium",children:s.autoLogged})," auto"]})]}),s.manualLogged>0&&s.autoLogged>0&&e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:"text-[var(--color-bg-tertiary)]",children:"·"}),e.jsxs("span",{className:"inline-flex items-center gap-1",title:"Manually logged via + Log",children:[e.jsx("span",{className:"tabular-nums font-medium",children:s.manualLogged})," manual"]})]})]})]}),t.length>0&&e.jsx("div",{className:"flex items-center gap-1 overflow-x-auto",children:i.map(d=>e.jsxs("button",{onClick:()=>l(d.key),className:`shrink-0 inline-flex items-center h-8 pointer-coarse:h-11 px-3 pointer-coarse:px-4 roun
69ded-[var(--radius-sm)] text-[length:var(--text-label-s)] cursor-pointer transition-colors ${r===d.key?"bg-[var(--color-accent-cta-bg)] text-[var(--color-text-on-accent)] font-semibold":"text-[var(--color-text-tertiary)] font-medium hover:bg-[var(--color-bg-secondary)] hover:text-[var(--color-text-secondary)]"}`,children:[d.label,e.jsx("span",{className:`ml-1 tabular-nums ${r===d.key?"":"opacity-60"}`,children:d.count})]},d.key))}),n.length===0&&r!=="all"?e.jsxs("p",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-quaternary)] py-2","data-testid":"activity-filter-empty",children:["No ",r," activity"]}):n.length>0?e.jsx("div",{className:"space-y-2",children:n.map(d=>e.jsx(wd,{activity:d},d.id))}):null]})}function Fs({contactId:t,dealId:a,onClose:r,onSubmit:l}){const[n,s]=o.useState("note"),[i,d]=o.useState(""),[c,m]=o.useState(""),[p,u]=o.useState(""),[x,w]=o.useState(()=>{const j=new Date,f=j.getTimezoneOffset()*6e4;return new Date(j.getTime()-f).toISOString().slice(0,16)}),[N,h]=o.useState(!1),v=async()=>{h(!0);const j=await l({type:n,subject:i.trim()||void 0,body:c.trim()||void 0,contact_id:t,deal_id:a,duration_minutes:p?parseInt(p,10):void 0,occurred_at:x?new Date(x).toISOString():void 0});h(!1),j&&r()};return e.jsx(Ke,{open:!0,onOpenChange:j=>!j&&r(),children:e.jsxs(Qe,{hideClose:!0,className:"max-w-md w-full","data-testid":"log-activity-dialog",children:[e.jsx(He,{children:e.jsx(Ye,{children:"Log activity"})}),e.jsx("div",{className:"flex gap-1 mb-3 overflow-x-auto pb-1",children:["note","call","email","meeting","task"].map(j=>e.jsx("button",{onClick:()=>s(j),className:`px-3 py-1 shrink-0 rounded-[var(--radius-sm)] text-[length:var(--text-label-m)] font-medium cursor-pointer transition-colors pointer-coarse:h-11 pointer-coarse:px-4 ${n===j?"bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]":"text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-secondary)]"}`,children:fn[j]},j))}),e.jsx("label",{htmlFor:"log-activity-subject",className:"block text-[length:var(--text-label-m)] font-medium text-[var(--color-text-secondary)] mb-1",children:"Subject"}),e.jsx(J,{id:"log-activity-subject",type:"text",placeholder:"Subject",value:i,onChange:j=>d(j.target.value),className:"mb-3"}),e.jsx("label",{htmlFor:"log-activity-details",className:"block text-[length:var(--text-label-m)] font-medium text-[var(--color-text-secondary)] mb-1",children:"Details"}),e.jsx(rs,{id:"log-activity-details",placeholder:"Details...",value:c,onChange:j=>m(j),rows:3,className:ts({className:"resize-none mb-3"})}),e.jsx("label",{htmlFor:"log-activity-occurred-at",className:"block text-[length:var(--text-label-m)] font-medium text-[var(--color-text-secondary)] mb-1",children:"Activity date"}),e.jsx(J,{id:"log-activity-occurred-at",type:"datetime-local",value:x,max:(()=>{const j=new Date,f=j.getTimezoneOffset()*6e4;return new Date(j.getTime()-f).toISOString().slice(0,16)})(),onChange:j=>w(j.target.value),className:"mb-3 [color-scheme:light] dark:[color-scheme:dark]"}),(n==="call"||n==="meeting")&&e.jsxs(e.Fragment,{children:[e.jsx("label",{htmlFor:"log-activity-duration",className:"block text-[length:var(--text-label-m)] font-medium text-[var(--color-text-secondary)] mb-1",children:"Duration (minutes)"}),e.jsx(J,{id:"log-activity-duration",type:"number",placeholder:"Duration (minutes)",value:p,onChange:j=>u(j.target.value),className:"mb-3"})]}),e.jsxs(nt,{className:"mt-4",children:[e.jsx(L,{variant:"ghost",onClick:r,className:"pointer-coarse:h-11",children:"Cancel"}),e.jsx(L,{onClick:v,disabled:N,className:"pointer-coarse:h-11",children:N?"Saving...":"Log activity"})]})]})})}function vs({open:t,onClose:a,onCreate:r,onViewContact:l,defaultType:n="person",defaultCompanyId:s}){const[i,d]=o.useState(n),[c,m]=o.useState(""),[p,u]=o.useState(""),[x,w]=o.useState(""),[N,h]=o.useState(""),v="lead",[j,f]=o.useState(!1),[z,y]=o.useState(null),[b,g]=o.useState(null),[E,A]=o.useState(!1),[U,D]=o.useState(""),O=Vr(k=>k.open),P=Vr(k=>k.sendMessage),H=Vr(k=>k.isLoading);o.useEffect(()=>{t&&d(n)},[t,n]);const ae=async()=>{if(!c.trim()){y("Name is required");return}f(!0),y(null),g(null);try{const k=await r({type:i,name:c.trim(),email:p.trim()||void 0,phone:x.trim()||void 0,title:N.trim()||void 0,lifecycle_stage:v,company_id:s});f(!1),k&&(m(""),u(""),w(""),h(""),d(n),a(),l&&l(k.id,i))}catch(k){f(!1),Yo(k,409)?(y(`A contact with this email already exists: ${k.body.contact_name}`),g(k.body.contact_id)):y(k instanceof Error?k.message:"Failed to create contact")}},I=()=>{const k=U.trim();!k||H||(O(),P(`Help me add this ${i==="company"?"company":"person"} to CRM. Extract the useful fields, check for likely duplicates, and show me the proposed record for review. Do not create or update anything until I explicitly confirm. Source:
70
71${k}`),D(""),A(!1),a())};return e.jsx(Ke,{open:t,onOpenChange:k=>!k&&a(),children:e.jsxs(Qe,{hideClose:!0,className:"max-w-md w-full","data-testid":"create-contact-dialog",children:[e.jsx(He,{children:e.jsx(Ye,{children:i==="company"?"New company":"New contact"})}),e.jsxs("div",{className:"mb-3 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-secondary)]",children:[e.jsxs("button",{type:"button",onClick:()=>A(k=>!k),"aria-expanded":E,className:"w-full min-h-11 px-3 py-2 flex items-center gap-2 text-left text-[length:var(--text-label-m)
71] font-medium text-[var(--color-text-primary)] hover:bg-[var(--color-accent-subtle)] rounded-[var(--radius-md)] transition-colors",children:[e.jsx(Ko,{size:15,className:"text-[var(--color-accent)]"}),e.jsx("span",{className:"whitespace-nowrap",children:"Create with Ambi"}),e.jsx("span",{className:"ml-auto truncate text-[length:var(--text-label-s)] font-normal text-[var(--color-text-primary)] max-sm:hidden",children:"Paste a bio, signature, or notes"})]}),E&&e.jsxs("div",{className:"px-3 pb-3 space-y-2",children:[e.jsx(br,{"aria-label":"Source text for Ambi",value:U,onChange:k=>D(k.target.value),placeholder:"Paste an email signature, LinkedIn bio, meeting notes, or company blurb…",className:"min-h-24"}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("p",{className:"text-[length:var(--text-label-s)] text-[var(--color-text-tertiary)]",children:"Ambi will propose fields and wait for your confirmation."}),e.jsx(L,{size:"compact",onClick:I,disabled:!U.trim()||H,children:"Review with Ambi"})]})]})]}),z&&e.jsxs("div",{className:"mb-3 px-3 py-2 rounded-[var(--radius-md)] bg-[var(--color-error-subtle)] text-[var(--color-error-text)] text-[length:var(--text-body-s)]",children:[z,b&&l&&e.jsx("button",{onClick:()=>{l(b,i),a()},className:"ml-2 underline font-medium hover:opacity-80 cursor-pointer",children:"View contact"})]}),e.jsxs("div",{className:"flex gap-1 mb-3",children:[e.jsxs("button",{onClick:()=>d("person"),className:`flex items-center gap-2 px-3 py-2 rounded-[var(--radius-sm)] text-[length:var(--text-label-m)] font-medium cursor-pointer transition-colors ${i==="person"?"bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]":"text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-secondary)]"}`,children:[e.jsx(Ne,{size:14})," Person"]}),e.jsxs("button",{onClick:()=>d("company"),className:`flex items-center gap-2 px-3 py-2 rounded-[var(--radius-sm)] text-[length:var(--text-label-m)] font-medium cursor-pointer transition-colors ${i==="company"?"bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]":"text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-secondary)]"}`,children:[e.jsx(Fe,{size:14})," Company"]})]}),e.jsxs("label",{className:"mb-3 block text-[13px] leading-5 text-[var(--color-text-secondary)] md:text-[length:var(--text-label-l)]",children:[e.jsxs("span",{className:"mb-1 block",children:[i==="company"?"Company name":"Full name",e.jsx("span",{className:"ml-0.5 text-[var(--color-error-text)]","aria-hidden":"true",children:"*"})]}),e.jsx(J,{type:"text",required:!0,"aria-required":"true","aria-label":i==="company"?"Company name":"Full name",placeholder:i==="company"?"Enter company name":"Enter full name",value:c,onChange:k=>m(k.target.value),className:"placeholder:text-[var(--color-text-tertiary)]",autoFocus:!0})]}),e.jsxs("label",{className:"mb-3 block text-[13px] leading-5 text-[var(--color-text-secondary)] md:text-[length:var(--text-label-l)]",children:[e.jsx("span",{className:"mb-1 block",children:"Email"}),e.jsx(J,{type:"email",placeholder:"[email protected]",value:p,onChange:k=>u(k.target.value),className:"placeholder:text-[var(--color-text-tertiary)]"})]}),e.jsxs("label",{className:"mb-3 block text-[13px] leading-5 text-[var(--color-text-secondary)] md:text-[length:var(--text-label-l)]",children:[e.jsx("span",{className:"mb-1 block",children:"Phone"}),e.jsx(J,{type:"tel",placeholder:"Phone number",value:x,onChange:k=>w(k.target.value),className:"placeholder:text-[var(--color-text-tertiary)]"})]}),i==="person"&&e.jsxs("label",{className:"mb-3 block text-[13px] leading-5 text-[var(--color-text-secondary)] md:text-[length:var(--text-label-l)]",children:[e.jsx("span",{className:"mb-1 block",children:"Job title"}),e.jsx(J,{type:"text",placeholder:"Role or title",value:N,onChange:k=>h(k.target.value),className:"placeholder:text-[var(--color-text-tertiary)]"})]}),e.jsxs(nt,{children:[e.jsx(L,{variant:"ghost",onClick:a,children:"Cancel"}),e.jsx(L,{onClick:ae,disabled:j||!c.trim(),children:j?i==="company"?"Creating company...":"Creating contact...":i==="company"?"Create company":"Create contact"})]})]})})}function zn({open:t,pipelines:a,contacts:r,activePipelineId:l,initialStageId:n,initialContactId:s,onClose:i,onCreate:d}){var W;
71const c=Hc(a,l),m=G(R=>R.applyDealTemplate),p=G(R=>R.dealTemplates),u=G(R=>R.workspaceUsers),x=G(R=>R.loadWorkspaceUsers),[w,N]=o.useState("pick"),[h,v]=o.useState(null),[j,f]=o.useState(""),[z,y]=o.useState(""),[b,g]=o.useState((c==null?void 0:c.id)??""),[E,A]=o.useState(((W=c==null?void 0:c.stages[0])==null?void 0:W.id)??""),[U,D]=o.useState(""),[O,P]=o.useState(""),[H,ae]=o.useState(""),[I,k]=o.useState(!1),[C,_]=o.useState(null),[Z,B]=o.useState(!1);if(o.useEffect(()=>{t&&u.length===0&&x()},[t,x,u.length]),o.useEffect(()=>{!t||!c||(b||g(c.id),!E&&c.stages[0]&&A(c.stages[0].id))},[t,c,b,E]),o.useEffect(()=>{if(!t||!n)return;const R=a.find(Y=>Y.stages.some(re=>re.id===n));R&&(g(R.id),A(n),N("form"))},[t,n]),o.useEffect(()=>{!t||!s||(D(s),N("form"))},[t,s]),o.useEffect(()=>{var R;t||(N("pick"),v(null),f(""),y(""),g((c==null?void 0:c.id)??""),A(((R=c==null?void 0:c.stages[0])==null?void 0:R.id)??""),D(""),P(""),ae(""),_(null))},[t,c]),o.useEffect(()=>{if(!t)return;const R=Y=>{Y.key==="Escape"&&(Y.preventDefault(),i())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[t,i]),!t)return null;const V=a.find(R=>R.id===b),F=(V==null?void 0:V.stages)??[],le=R=>{g(R);const Y=a.find(re=>re.id===R);Y&&Y.stages.length>0&&A(Y.stages[0].id)},X=async R=>{k(!0),_(null);const Y=await m(R,{contact_id:U||null});if(k(!1),Y)i();else{v(R);const re=p.find(fe=>fe.id===R);re&&(f(re.title_template??re.name),re.amount!=null&&y(String(re.amount)),re.pipeline_id&&g(re.pipeline_id),re.stage_id&&A(re.stage_id)),N("form")}},T=async()=>{if(!j.trim()){_("Title is required");return}if(z&&parseFloat(z)<0){_("Amount cannot be negative");return}if(z&&parseFloat(z)===0&&!Z){B(!0);return}const R=!!(z&&parseFloat(z)===0);B(!1),k(!0),_(null);const Y=await d({title:j.trim(),amount:z?parseFloat(z):void 0,pipeline_id:b||void 0,stage_id:E||void 0,contact_id:U||void 0,owner_id:O||void 0,close_date:H||void 0,confirm_zero:R?!0:void 0});k(!1),Y&&(ge.success("Deal created"),f(""),y(""),D(""),P(""),ae(""),v(null),i())};return w==="pick"?e.jsx(Ke,{open:t,onOpenChange:R=>!R&&i(),children:e.jsxs(Qe,{className:"max-w-md w-full max-h-[85vh] overflow-auto animate-none duration-0","data-testid":"create-deal-dialog",children:[e.jsxs(He,{children:[e.jsx(Ye,{children:"New deal"}),e.jsx(vr,{children:"Start from a template, or begin with a blank deal."})]}),C&&e.jsx("div",{className:"mb-3 px-3 py-2 rounded-[var(--radius-md)] bg-[var(--color-error-subtle)] text-[var(--color-error-text)] text-[length:var(--text-body-s)]",children:C}),e.jsx(Mc,{onSelect:R=>void X(R.id),onBlank:()=>N("form")})]})}):e.jsxs(Ke,{open:t,onOpenChange:R=>!R&&i(),children:[e.jsxs(Qe,{hideClose:!0,className:"max-w-md w-full max-h-[85vh] overflow-auto animate-none duration-0","data-testid":"create-deal-dialog",children:[e.jsx(He,{children:e.jsxs("div",{className:"flex items-center justify-between w-full pr-6",children:[e.jsx(Ye,{children:"New deal"}),p.some(R=>R.is_active)&&e.jsx("button",{type:"button",onClick:()=>{v(null),N("pick")},className:"text-[length:var(--text-body-s)] text-[var(--color-accent)] hover:underline cursor-pointer",children:"Use a template"})]})}),h&&e.jsx("div",{className:"mb-3 px-3 py-2 rounded-[var(--radius-md)] bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)] text-[length:var(--text-body-s)]",children:"Prefilled from template. Review and edit before creating."}),C&&e.jsx("div",{className:"mb-3 px-3 py-2 rounded-[var(--radius-md)] bg-[var(--color-error-subtle)] text-[var(--color-error-text)] text-[length:var(--text-body-s)]",children:C}),e.jsxs("div",{className:"mb-3",children:[e.jsx("label",{htmlFor:"new-deal-title",className:"block mb-1 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-secondary)]",children:"Deal title"}),e.jsx("input",{id:"new-deal-title",type:"text",value:j,onChange:R=>f(R.target.value),className:"w-full h-9 px-3 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[length:var(--text-body-m)] text-[var(--color-text-primary)] placeholder:text-[var(--color-text-quaternary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)]",autoF
71ocus:!0})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("label",{htmlFor:"new-deal-amount",className:"block mb-1 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-secondary)]",children:"Amount"}),e.jsx("input",{id:"new-deal-amount",type:"number",placeholder:"0.00",value:z,onChange:R=>y(R.target.value),className:"w-full h-9 px-3 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[length:var(--text-body-m)] text-[var(--color-text-primary)] placeholder:text-[var(--color-text-quaternary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)]"})]}),a.length>0&&e.jsx("select",{value:b,onChange:R=>le(R.target.value),"aria-label":"Pipeline",className:"w-full h-9 px-3 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[length:var(--text-body-m)] text-[var(--color-text-secondary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)] cursor-pointer mb-3",children:a.map(R=>e.jsx("option",{value:R.id,children:R.name},R.id))}),F.length>0&&e.jsx("select",{value:E,onChange:R=>A(R.target.value),"aria-label":"Stage",className:"w-full h-9 px-3 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[length:var(--text-body-m)] text-[var(--color-text-secondary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)] cursor-pointer mb-3",children:F.map(R=>e.jsx("option",{value:R.id,children:R.name},R.id))}),r.length>0&&e.jsxs("select",{value:U,onChange:R=>D(R.target.value),"aria-label":"Contact",className:"w-full h-9 px-3 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[length:var(--text-body-m)] text-[var(--color-text-secondary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)] cursor-pointer mb-3",children:[e.jsx("option",{value:"",children:"No contact"}),r.map(R=>e.jsx("option",{value:R.id,children:R.name},R.id))]}),u.length>0&&e.jsxs("select",{value:O,onChange:R=>P(R.target.value),"aria-label":"Deal owner",className:"w-full h-9 px-3 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[length:var(--text-body-m)] text-[var(--color-text-secondary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)] cursor-pointer mb-3",children:[e.jsx("option",{value:"",children:"Owner (defaults to you)"}),u.map(R=>e.jsx("option",{value:R.id,children:R.display_name||R.email},R.id))]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("label",{htmlFor:"new-deal-close-date",className:"block mb-1 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-secondary)]",children:"Close date"}),e.jsx("input",{id:"new-deal-close-date",type:"date",value:H,onChange:R=>ae(R.target.value),className:"w-full h-9 px-3 rounded-[var(--radius-md)] border border-[var(--color-bg-tertiary)] bg-[var(--color-bg-primary)] text-[length:var(--text-body-m)] text-[var(--color-text-secondary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent)] cursor-pointer"})]}),e.jsxs(nt,{children:[e.jsx(L,{variant:"ghost",onClick:i,children:"Cancel"}),e.jsx(L,{onClick:T,disabled:I||!j.trim(),children:I?"Creating...":"Create deal"})]})]}),e.jsx(we,{open:Z,onOpenChange:R=>{R||B(!1)},title:"Unusual deal amount",description:"A $0 deal amount is unusual. Are you sure you want to create this deal?",confirmLabel:"Create deal",variant:"primary",onConfirm:T})]})}const er=[{key:"name",label:"Name"},{key:"email",label:"Email"},{key:"phone",label:"Phone"},{key:"title",label:"Title"},{key:"website",label:"Website"},{key:"industry",label:"Industry"},{key:"lifecycle_stage",label:"Lifecycle stage"}];function Od({open:t,contactA:a,contactB:r,onClose:l,onMerge:n}){const[s,i]=o.useState("a"),[d,c]=o.useState(()=>{const f={};for(const z of er)f[z.key]="a";return f}),[m,p]=o.useState(!1),[u,x]=o.useState(null);if(o.useEffect(()=>{if(t){i("a");const f={};for(const z of er)f[z.key]="a";c(f),x(null)}},[t]),o.useEffect(()=>{if(!t)return;const f=z=>{z.key==="Escape"&&(z.preventDefault(),l())};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t,l]),!t||!a||!r)return null;const w=(f,z)=>{if(z==="lifecycle_stage")return f.lifecycle_stage?et[f.lifecycle_stage]||f.lifecycle_stage:"—";const y=f[z];return y!=null?String(y):"—"},N=(f,z)=>z==="lifecycle_stage"?f.lifecycle_stage:f[z],h=s==="a"?a:r,v=s==="a"?r:a,j=async()=>{p(!0);const f={};for(const y of er){const b=d[y.key],g=b==="a"?a:r;(s==="a"&&b==="b"||s==="b"&&b==="a")&&(f[y.key]=N(g,y.key))}const z=await n(h.id,v.id,Object.keys(f).length>0?f:void 0);p(!1),z&&x(z)};return u?e.jsx(Ke,{open:t,onOpenChange:f=>!f&&l(),children:e.jsxs(Qe,{hideClose:!0,className:"max-w-md w-full mx-4 text-center animate-none duration-0",children:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-3 rounded-full bg-[var(--color-success-subtle)] flex items-center justify-center",children:e.jsx(Se,{size:24,className:"text-[var(--color-success)]"})}),e.jsx(He,{children:e.jsx(Ye,{className:"text-center",children:"Contacts Merged"})}),e.jsxs("div",{className:"text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] space-y-1 mb-4",children:[u.activities_moved>0&&e.jsxs("p",{children:[u.activities_moved," ",u.activities_moved===1?"activity":"activities"," moved"]}),u.deals_moved>0&&e.jsxs("p",{children:[u.deals_moved," ",u.deals_moved===1?"deal":"deals"," moved"]}),u.contacts_relinked>0&&e.jsxs("p",{children:[u.contacts_relinked," ",u.contacts_relinked===1?"contact":"contacts"," relinked"]}
71),u.activities_moved===0&&u.deals_moved===0&&u.contacts_relinked===0&&e.jsx("p",{children:"No associated records to move"})]}),e.jsx(nt,{className:"justify-center",children:e.jsx(L,{onClick:l,children:"Done"})})]})}):e.jsx(Ke,{open:t,onOpenChange:f=>!f&&l(),children:e.jsxs(Qe,{hideClose:!0,className:"max-w-2xl w-full mx-auto my-4 sm:my-0 animate-none duration-0",children:[e.jsxs(He,{children:[e.jsx(Ye,{children:"Merge contacts"}),e.jsx(vr,{children:"Select which values to keep for the merged contact. The other contact will be deleted and its activities, deals, and linked contacts will be moved."})]}),e.jsxs("div",{"data-testid":"merge-keep-as-primary",role:"radiogroup","aria-label":"Keep as primary",className:"flex items-center gap-2 mb-4",children:[e.jsx("span",{className:"text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] shrink-0",children:"Keep as primary:"}),e.jsxs("button",{type:"button",role:"radio","aria-checked":s==="a",onClick:()=>i("a"),className:`flex items-center gap-2 px-3 py-1 rounded-[var(--radius-sm)] text-[length:var(--text-label-m)] font-medium cursor-pointer transition-colors ${s==="a"?"bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]":"text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-secondary)]"}`,children:[e.jsx("span",{"aria-hidden":"true",className:`inline-block h-3 w-3 rounded-full border ${s==="a"?"border-[var(--color-accent)] bg-[var(--color-accent)]":"border-[var(--color-text-quaternary)]"}`}),a.name]}),e.jsxs("button",{type:"button",role:"radio","aria-checked":s==="b",onClick:()=>i("b"),className:`flex items-center gap-2 px-3 py-1 rounded-[var(--radius-sm)] text-[length:var(--text-label-m)] font-medium cursor-pointer transition-colors ${s==="b"?"bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]":"text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-secondary)]"}`,children:[e.jsx("span",{"aria-hidden":"true",className:`inline-block h-3 w-3 rounded-full border ${s==="b"?"border-[var(--color-accent)] bg-[var(--color-accent)]":"border-[var(--color-text-quaternary)]"}`}),r.name]})]}),e.jsxs("div",{className:"border border-[var(--color-bg-tertiary)] rounded-[var(--radius-md)] overflow-hidden mb-4",children:[e.jsxs("div",{className:"flex items-center bg-[var(--color-bg-secondary)] border-b border-[var(--color-bg-tertiary)]",children:[e.jsx("div",{className:"w-[100px] shrink-0 px-3 py-2 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)]",children:"Field"}),e.jsxs("div",{role:"columnheader","aria-selected":s==="a",className:"flex-1 min-w-0 px-3 py-2 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:a.name}),s==="a"&&e.jsx(de,{variant:"accent",className:"shrink-0",children:"Primary"})]}),e.jsxs("div",{role:"columnheader","aria-selected":s==="b",className:"flex-1 min-w-0 px-3 py-2 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)] flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:r.name}),s==="b"&&e.jsx(de,{variant:"accent",className:"shrink-0",children:"Primary"})]})]}),er.map(f=>{const z=w(a,f.key),y=w(r,f.key),b=d[f.key];return e.jsxs("div",{className:"flex items-center border-b border-[var(--color-bg-tertiary)] last:border-b-0",children:[e.jsx("div",{className:"w-[100px] shrink-0 px-3 py-2 text-[length:var(--text-label-s)] font-medium text-[var(--color-text-tertiary)]",children:f.label}),e.jsx("button",{onClick:()=>c(g=>({...g,[f.key]:"a"})),className:`flex-1 min-w-0 px-3 py-2 text-[length:var(--text-body-s)] cursor-pointer transition-colors text-left ${b==="a"?"bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)] font-medium":"text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-secondary)]"}`,children:e.jsx("span",{className:"truncate block",children:z})}),e.jsx("button",{onClick:()=>c(g=>({...g,[f.key]:"b"})),className:`flex-1 min-w-0 px-3 py-2 text-[length:var(--text-body-s)] cursor-pointer transition-colors text-left ${b==="b"?"bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)] font-medium":"text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-secondary)]"}`,children:e.jsx("span",{className:"truncate block",children:y})})]},f.key)})]}),e.jsxs("div",{className:"px-3 py-2 rounded-[var(--radius-md)] bg-[var(--color-bg-secondary)] text-[length:var(--text-body-s)] text-[var(--color-text-secondary)] mb-4",children:[e.jsx("strong",{className:"text-[var(--color-text-primary)]",children:v.name})," will be deleted. All activities, deals, and linked contacts will be moved to ",e.jsx("strong",{className:"text-[var(--color-text-primary)]",children:h.name}),"."]}),e.jsxs(nt,{children:[e.jsx(L,{variant:"ghost",onClick:l,children:"Cancel"}),e.jsxs(L,{onClick:j,disabled:m,children:[e.jsx(Sa,{size:16}),m?"Merging...":"Merge contacts"]})]})]})})}
71const or=["reports","people","deals","follow_ups","tools","quotes","products","templates","sequences","scoring","scheduler","pipelines","custom_fields","dashboard"],$n={pipeline:"deals",dashboard:"reports",insights:"reports",overview:"reports",contacts:"people",companies:"people","follow-ups":"follow_ups",automations:"follow_ups",analytics:"dashboard"};function ir(t){return t==="deals"?"pipeline":t==="reports"?"overview":t==="follow_ups"?"automations":t==="dashboard"?"analytics":t}function qd(){const t=Qo(),a=sa(),{view:r,setView:l,loadTabCounts:n,contacts:s,contactsLoading:i,contactsError:d,contactsTotal:c,contactsPage:m,filterLifecycle:p,searchQuery:u,activeContact:x,activeContactLoading:w,activities:N,loadContacts:h,clearContactsError:v,setContactsPage:j,selectContact:f,clearActiveContact:z,createContact:y,updateContact:b,deleteContact:g,setFilterLifecycle:E,setSearchQuery:A,contactGroups:U,activeGroupId:D,deals:O,dealsLoading:P,dealsTotal:H,dealsPage:ae,pipelines:I,activePipelineId:k,filterDealStatus:C,activeDeal:_,activeDealLoading:Z,dealActivities:B,loadPipelines:V,loadDeals:F,setDealsPage:le,selectDeal:X,loadDealActivities:T,clearActiveDeal:W,createDeal:R,updateDeal:Y,deleteDeal:re,setActivePipeline:fe,setFilterDealStatus:Te,logActivity:St,contactDeals:Ea,contactDetailLoading:tt,loadContactDetail:na,clearContactDetail:q,companyContacts:ee,companyDeals:ke,companyDetailLoading:ce,loadCompanyDetail:Rt,clearCompanyDetail:oa,mergeContacts:An,importCsvPreview:Tn,importCsvContacts:En,bulkDeleteContacts:Ms,bulkUpdateContacts:La,bulkDeleteDeals:Os,bulkUpdateDeals:Ft,exportContactsCsv:Ia,exportContactsVCard:Pa,exportDealsCsv:qs,error:Vs,clearError:Ln}=G();Do((_==null?void 0:_.title)??(x==null?void 0:x.name)??null);const[Ra,it]=o.useState(!1),[Fa,_t]=o.useState(!1),[Ma,at]=o.useState(!1),[In,Bs]=o.useState(null),[Pn,wr]=o.useState(null),[Rn,Us]=o.useState(void 0);ti("crm",()=>it(!0));const[kr,Cr]=o.useState(!1),[Ws,Gs]=o.useState(!1),[Oa,Sr]=o.useState(!1),[ie,ct]=o.useState(new Set),[je,bt]=o.useState(new Set),Ks=o.useRef(r),Qs=o.useRef(t.pathname);o.useEffect(()=>{const $=t.pathname.split("/").pop()??"";if($==="workflows"){a(an,{replace:!0});return}const S=$n[$]??$,M=Ks.current!==r,K=Qs.current!==t.pathname;if(Ks.current=r,Qs.current=t.pathname,M){const ne=`/crm/${ir(r)}`;t.pathname!==ne&&a(`${ne}${S===r?t.search:""}`,{replace:!0})}else(K||S!==r&&or.includes(S))&&(or.includes(S)&&S!==r?l(S):!or.includes(S)&&$!=="crm"?a(`/crm/${ir(r)}`,{replace:!0}):$==="crm"&&a(`/crm/${ir(r)}`,{replace:!0}))},[t.pathname,t.search,r,a,l]);const qa=Br({queryParam:"deal"}),Hs=Br({queryParam:"contact"}),Ys=Br({queryParam:"company"});o.useEffect(()=>{r==="deals"&&(qa.entityId?qa.entityId!==(_==null?void 0:_.id)&&X(qa.entityId):_&&W())},[r,qa.entityId,_,X,W]),o.useEffect(()=>{if(!(r==="contacts"||r==="companies"||r==="people"))return;const S=Hs.entityId||Ys.entityId;S?S!==(x==null?void 0:x.id)&&f(S):x&&z()},[r,Hs.entityId,Ys.entityId,x,f,z]),o.useEffect(()=>{const S=new URLSearchParams(window.location.search).get("search")??"";S&&A(S)},[A]),o.useEffect(()=>{const $=setTimeout(()=>{const M=new URLSearchParams(t.search).get("search")??"";if(u!==M){const K=new URLSearchParams(t.search);u?K.set("search",u):K.delete("search");const ne=K.toString();a(`${t.pathname}${ne?`?${ne}`:""}`,{replace:!0})}},300);return()=>clearTimeout($)},[u,t.pathname,t.search,a]);const $e=o.useCallback(($,S,M)=>{const K=new URLSearchParams(t.search);K.delete("deal"),K.delete("contact"),K.delete("company"),S&&M&&K.set(S,M);const ne=K.toString();a(`${$}${ne?`?${ne}`:""}`,{replace:!0})},[t.search,a]),Va=o.useCallback($=>$e("/crm/pipeline","deal",$),[$e]),Mt=o.useCallback(()=>$e("/crm/pipeline",null,null),[$e]),Ot=o.useCallback($=>$e(t.pathname,"contact",$),[$e,t.pathname]),ia=o.useCallback($=>$e(t.pathname,"company",$),[$e,t.pathname]),qt=o.useCallback(()=>$e(t.pathname,null,null),[$e,t.pathname]),Fn=o.useCallback(()=>$e(t.pathname,null,null),[$e,t.pathname]),ca=o.useCallback($=>{const S=s.find(M=>M.id===$);(S==null?void 0:S.type)==="company"?ia($):Ot($)},[s,Ot,ia]),[_r,Dr]=o.useState([]),Ba=o.useCallback($=>{if($.kind==="deal")z(),q(),oa(),l("deals"),$e("/crm/pipeline","deal",$.id);else{W();const S=r==="people"?"people":$.kind==="company"?"companies":"contacts";l(S),$e(`/crm/${S==="companies"?"companies":S==="contacts"?"contacts":"people"}`,$.kind==="company"?"company":"contact",$.id),f($.id)}},[z,W,q,oa,f,l,r,$e]),Ua=o.useCallback(($,S)=>{Dr(M=>[...M,$]),Ba(S)},[Ba]),zr=o.useCallback($=>{Dr(S=>{const M=S[$];return M?(queueMicrotask(()=>Ba(M)),S.slice(0,$)):S})},[Ba]),$r=o.useCallback(()=>{Dr([])},[]);o.useEffect(()=>{ct(new Set),bt(new Set)},[r]),o.useEffect(()=>{h(),V(),n()},[h,V,n]),o.useEffect(()=>{let $=null;const S=new Set;Tt.retain(["contacts","deals"]);const M=Tt.onFrame(K=>{K.table!=="contacts"&&K.table!=="deals"||typeof document<"u"&&document.hidden||(S.add(K.table),$&&clearTimeout($),$=setTimeout(()=>{S.has("contacts")&&h(),S.has("deals")&&F(),S.clear()},400))});return()=>{M(),Tt.release(["contacts","deals"]),$&&clearTimeout($)}},[h,F]),o.useEffect(()=>{I.length>0&&(!k||!I.some($=>$.id===k))&&fe(I[0].id)},[I,k,fe]);const Ar=o.useRef(null);o.useEffect(()=>{r==="deals"&&k&&(Ar.current=G.getState().searchQuery,F())},[r,k,F]),o.useEffect(()=>{if(r!=="deals"||!k||u===Ar.current)return;const $=window.setTimeout(()=>{Ar.current=u,F()},250);return()=>window.clearTimeout($)},[k,F,u,r]),o.useEffect(()=>{Or(null)},[k]),o.useEffect(()=>{(r==="contacts"||r==="people")&&x&&x.type==="person"?na(x.id):q()},[r,x,na,q]),o.useEffect(()=>{(r==="companies"||r==="people")&&x&&x.type==="company"?Rt(x.id):oa()},[r,x,Rt,oa]);const Tr=I.find($=>
71$.id===k),Vt=(Tr==null?void 0:Tr.stages)??[],da={};Vt.forEach($=>{da[$.id]=[]}),O.forEach($=>{$.stage_id&&da[$.stage_id]&&da[$.stage_id].push($)});const Mn=o.useMemo(()=>{var S,M;const $=new Map;for(const K of O){const ne=((S=K.owner)==null?void 0:S.id)??K.owner_id??"unassigned",xe=((M=K.owner)==null?void 0:M.display_name)??"Unassigned",Ha=$.get(ne)??{id:ne,label:xe,deals:[]};Ha.deals.push(K),$.set(ne,Ha)}return Array.from($.values()).map(K=>({...K,deals:K.deals.sort((ne,xe)=>(xe.amount??0)-(ne.amount??0))})).sort((K,ne)=>K.id==="unassigned"?1:ne.id==="unassigned"?-1:K.label.localeCompare(ne.label))},[O]),On=o.useMemo(()=>{const $=new Date,S=mn(O,$),M=new Set(S.map(xe=>xe.deal.id)),K=un(O,$).filter(xe=>!M.has(xe.deal.id)),ne=[];return S.length>0&&ne.push({id:"overdue",label:"Past close date",meta:pn(S[0].daysOverdue),deals:S.map(xe=>xe.deal)}),K.length>0&&ne.push({id:"stalled",label:"Stalled",meta:hn(K[0].daysStuck),deals:K.map(xe=>xe.deal)}),ne},[O]),Er=o.useCallback($=>{ct(S=>{const M=new Set(S);return M.has($)?M.delete($):M.add($),M})},[]),Wa=o.useCallback(()=>{ct($=>$.size===s.length&&s.length>0?new Set:new Set(s.map(S=>S.id)))},[s]),Ga=o.useCallback($=>{bt(S=>{const M=new Set(S);return M.has($)?M.delete($):M.add($),M})},[]),[se,Bt]=o.useState(null),Lr=o.useCallback(()=>{Bt({kind:"deleteContacts",ids:Array.from(ie)})},[ie]),Ir=o.useCallback(()=>{Bt({kind:"deleteDeals",ids:Array.from(je)})},[je]),qn=o.useCallback(async()=>{se&&(se.kind==="deleteContacts"?(x&&se.ids.includes(x.id)&&(qt(),q()),await Ms(se.ids),ct(new Set)):se.kind==="deleteDeals"?(_&&se.ids.includes(_.id)&&Mt(),await Os(se.ids),bt(new Set)):se.kind==="deleteActiveContact"?(qt(),z(),q(),await g(se.id)&&ge.success("Contact deleted")):se.kind==="deleteActiveDeal"&&(Mt(),await re(se.id)&&ge.success("Deal deleted")),Bt(null))},[se,Ms,Os,g,re,qt,Mt,q,z,x,_]),Vn=o.useCallback(async $=>{const S=ie.size,M=await La(Array.from(ie),{owner_id:$});if(ct(new Set),M&&S>0){const K=G.getState().workspaceUsers.find(xe=>xe.id===$),ne=(K==null?void 0:K.display_name)??"owner";ge.success(`${S} contact${S!==1?"s":""} assigned to ${ne}`)}},[La,ie]),Bn=o.useCallback(async $=>{const S=ie.size,M=await La(Array.from(ie),{lifecycle_stage:$});ct(new Set),M&&S>0&&ge.success(`Lifecycle set for ${S} contact${S!==1?"s":""}`)},[La,ie]),Js=G($=>$.addContactsToGroup),Un=o.useCallback(async $=>{const S=ie.size;if(await Js($,Array.from(ie))){ct(new Set);const K=G.getState().contactGroups.find(xe=>xe.id===$),ne=(K==null?void 0:K.name)??"list";ge.success(`${S} contact${S!==1?"s":""} added to ${ne}`)}},[Js,ie]),Wn=G($=>$.createContactGroup),Gn=G($=>$.updateContactGroup),Zs=G($=>$.deleteContactGroup),[Kn,Pr]=o.useState(!1),[Qn,Xs]=o.useState(null),[Dt,Rr]=o.useState(null),el=o.useCallback(()=>{Xs(null),Pr(!0)},[]),Hn=o.useCallback($=>{Xs($),Pr(!0)},[]),Yn=o.useCallback(async()=>{Dt&&(await Zs(Dt.id),Rr(null))},[Dt,Zs]),Jn=o.useCallback(async()=>{await Ia(Array.from(ie))},[Ia,ie]),Zn=o.useCallback(async()=>{const $=s.map(S=>S.id);await Ia($)},[Ia,s]),Xn=o.useCallback(async()=>{await Pa(Array.from(ie))},[Pa,ie]),eo=o.useCallback(async()=>{await Pa(s.map($=>$.id))},[Pa,s]),to=o.useCallback(()=>{const S=s.filter(K=>ie.has(K.id)).map(K=>K.email).filter(K=>typeof K=="string"&&K.length>0);if(S.length===0)return;const M=S.length===1?`mailto:${encodeURIComponent(S[0])}`:`mailto:?bcc=${encodeURIComponent(S.join(","))}`;window.location.href=M},[s,ie]),ao=o.useCallback(()=>{const $=s.filter(M=>ie.has(M.id)),S=ai($);S.length!==0&&a("/mail/merge",{state:{recipients:S}})},[s,ie,a]),ro=o.useCallback(async $=>{const S=je.size,M=await Ft(Array.from(je),{owner_id:$});if(bt(new Set),M&&S>0){const K=G.getState().workspaceUsers.find(xe=>xe.id===$),ne=(K==null?void 0:K.display_name)??"owner";ge.success(`${S} deal${S!==1?"s":""} assigned to ${ne}`)}},[Ft,je]),so=o.useCallback(async $=>{var K;const S=je.size,M=await Ft(Array.from(je),{stage_id:$});if(bt(new Set),M&&S>0){const ne=((K=I.flatMap(xe=>xe.stages).find(xe=>xe.id===$))==null?void 0:K.name)??"stage";ge.success(`${S} deal${S!==1?"s":""} moved to ${ne}`)}},[Ft,je,I]),lo=o.useCallback(async $=>{const S=je.size,M=await Ft(Array.from(je),{status:$});if(bt(new Set),M&&S>0){const K=$==="won"?"Won":$==="lost"?"Lost":"Open";ge.success(`${S} deal${S!==1?"s":""} marked as ${K}`)}},[Ft,je]),no=o.useCallback(async()=>{await qs(Array.from(je))},[qs,je]),Ut=Ra||Fa||Ma||kr||Ws||Oa,[tl,al]=o.useState({a:null,b:null}),oo=Oa?tl.a:null,io=Oa?tl.b:null,Ge=r==="contacts"||r==="companies"||r==="people",rl=Ge&&d===Vs?null:Vs,[Ka,co]=o.useState(Jc),[Wt,xo]=o.useState("name"),[Qa,sl]=o.useState("asc"),[ll,mo]=o.use
71State(()=>new Set(Es)),nl=o.useCallback($=>{co($),Zc($)},[]),ol=o.useCallback($=>{if($===Wt){sl(S=>S==="asc"?"desc":"asc");return}xo($),sl("asc")},[Wt]),uo=o.useCallback($=>{mo(S=>{const M=new Set(S);return M.has($)?M.delete($):M.add($),M})},[]),rt=o.useMemo(()=>{if(Ka!=="list")return s;const $=u.trim().toLowerCase(),S=s.filter(M=>{var K,ne,xe;return M.type==="person"&&(p==="all"||M.lifecycle_stage===p)&&(!$||M.name.toLowerCase().includes($)||((K=M.email)==null?void 0:K.toLowerCase().includes($))||((ne=M.title)==null?void 0:ne.toLowerCase().includes($))||((xe=M.company)==null?void 0:xe.name.toLowerCase().includes($)))});return gn(S,Wt,Qa)},[s,p,Qa,Wt,Ka,u]),[il,Fr]=o.useState("board"),[cl,po]=o.useState(()=>typeof window<"u"?window.innerWidth>=768:!0);o.useEffect(()=>{if(typeof window>"u")return;const $=window.matchMedia("(min-width: 768px)"),S=()=>po(window.innerWidth>=768);return S(),$.addEventListener("change",S),window.addEventListener("resize",S),()=>{$.removeEventListener("change",S),window.removeEventListener("resize",S)}},[]);const Mr=il,[xa,Or]=o.useState(null),ho=o.useMemo(()=>vi({setView:l}),[l]);return zo(ho),$o({onEscape:o.useCallback(()=>{kr?Cr(!1):Ra?it(!1):Fa?_t(!1):Ma?at(!1):Ge&&x?qt():r==="deals"&&_&&Mt()},[Ra,Fa,Ma,Ge,r,x,_,qt,Mt]),onDelete:o.useCallback(()=>{Ut||(Ge&&ie.size>0?Lr():Ge&&x?Bt({kind:"deleteActiveContact",id:x.id}):r==="deals"&&je.size>0?Ir():r==="deals"&&_&&Bt({kind:"deleteActiveDeal",id:_.id}))},[Ut,Ge,r,ie,x,je,_,Lr,Ir]),onArrowUp:o.useCallback(()=>{if(Ut||!Ge||rt.length===0)return;const $=x?rt.findIndex(M=>M.id===x.id):-1,S=$<=0?rt.length-1:$-1;ca(rt[S].id)},[Ut,Ge,rt,x,ca]),onArrowDown:o.useCallback(()=>{if(Ut||!Ge||rt.length===0)return;const $=x?rt.findIndex(M=>M.id===x.id):-1,S=$>=rt.length-1?0:$+1;ca(rt[S].id)},[Ut,Ge,rt,x,ca])}),o.useEffect(()=>{function $(S){var ne;const M=S.target;if(!((M==null?void 0:M.tagName)==="INPUT"||(M==null?void 0:M.tagName)==="TEXTAREA"||(M==null?void 0:M.tagName)==="SELECT"||M!=null&&M.isContentEditable)){if((S.metaKey||S.ctrlKey)&&S.key==="f"){S.preventDefault();const xe=Array.from(document.querySelectorAll('input[aria-label="Search people and companies"], input[aria-label="Search pipeline"], [data-module="crm"] input[type="search"], [data-module="crm"] input[type="text"]')).find(Ha=>Ha.getClientRects().length>0);xe?xe.focus():(ne=document.querySelector('[data-module="crm"] button[aria-label^="Search"]'))==null||ne.click();return}if((S.metaKey||S.ctrlKey)&&S.key==="n"){S.preventDefault(),r==="deals"?at(!0):r==="companies"?_t(!0):it(!0);return}}}return document.addEventListener("keydown",$),()=>{document.removeEventListener("keydown",$)}},[r,it,_t,at]),e.jsx(Ao,{navigationLabel:"CRM navigation",sidebar:e.jsx(Si,{onCreateList:el,onEditList:Hn,onDeleteList:Rr}),className:"h-full",children:$=>e.jsxs(ri,{value:$,children:[e.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1",children:[e.jsxs("div",{className:"@container/crmpage flex min-h-0 min-w-0 flex-1 flex-col dark:[--color-bg-primary:#151523] dark:[--color-bg-secondary:#232340] dark:[--color-surface-1:#20203a] dark:[--color-text-tertiary:#a3a9b5] dark:[--color-text-quaternary:#8b92a0]","data-module":"crm",style:r==="people"?{"--text-body-s":"var(--text-label-s)","--text-label-m":"var(--text-label-s)"}:void 0,children:[e.jsx(fi,{navigationTrigger:$,view:r,onViewChange:S=>{l(S),S==="deals"?z():W()},searchQuery:u,onSearchChange:A,filterLifecycle:p,onFilterLifecycleChange:E,onCreateContact:()=>it(!0),onCreateCompany:()=>_t(!0),onImportCsv:()=>Cr(!0),onExportCsv:Zn,onExportVCard:eo,onScanBusinessCard:()=>Gs(!0),pipelines:I,activePipelineId:k,onPipelineChange:fe,filterDealStatus:C,onFilterDealStatusChange:Te,dealCount:O.length,onCreateDeal:()=>at(!0),peopleViewMode:Ka,onPeopleModeChange:nl,peopleSortKey:Wt,peopleSortDirection:Qa,onPeopleSort:ol,peopleVisibleColumns:ll,onTogglePeopleColumn:uo,dealLayout:il,onDealLayoutChange:Fr}),rl&&e.jsxs("div",{role:"alert",className:"mx-6 mt-3 px-3 py-2 rounded-[var(--radius-md)] bg-[var(--color-error-subtle)] text-[var(--color-error-text)] text-[length:var(--text-body-s)] flex items-center justify-between",children:[e.jsx("span",{children:rl}),e.jsx("button",{onClick:()=>{v(),Ln()},className:"font-medium text-[var(--color-error-text)] hover:underline cursor-pointer text-[length:var(--text-label-s)]",children:"Dismiss"})]}),Ge&&ie.size>0&&e.jsx(nd,{count:ie.size,entityName:r==="companies"?"company":"contact",onClearSelection:()=>ct(new Set),onDelete:Lr,onAssignOwner:Vn,onSetLifecycle:Bn,onAddToGroup:Un,onCreateGroup:el,onExport:Jn,onExportVCard:Xn,onSendEmail:to,onMailMerge:ao,sendEmailDisabled:s.filter(S=>ie.has(S.id)).every(S=>!S.email),onMerge:ie.size===2?()=>{const S=Array.from(ie);al({a:s.find(M=>M.id===S[0])??null,b:s.find(M=>M.id===S[1])??null}),Sr(!0)}:void 0}),r==="deals"&&je.size>0&&e.jsx(od,{count:je.size,stages:Vt,onClearSelection:()=>bt(new Set),onDelete:Ir,onAssignOwner:ro,onChangeStage:so,onSetStatus:lo,onExport:no}),r==="dashboard"?e.jsx(Ei,{onCreateDeal:()=>at(!0)}):r==="follow_ups"?e.jsx(Sl,{}):r==="reports"?e.jsx(tc,{}):r==="people"?e.jsx("div",{className:"flex flex-1 overflow-hidden",children:e.jsx("div",{className:"flex-1 flex flex-col min-w-0",children:d?e.jsx(Zr,{onRetry:()=>{v(),h()}}):i&&s.length===0?e.jsx("div",{className:"p-6 space-y-2",children:Array.from({length:6}).map((S,M)=>e.jsx(Re,{},M))}):s.length===0&&!i&&!u&&p==="all"?e.jsx("div",{className:"flex-1 flex items-center justify-center","data-testid":"crm-people-empty",children:e.jsx(De,{illustration:e.jsx(gi,{}),title:"No people yet",description:"Add contacts and companies to track every relationship in one place.",actions:[e.jsxs(L,{onClick:()=>it(!0),"data-testid":"crm-people-empty-create-contact",className:"pointer-coarse:h-11",children:[e.jsx(oe,{size:16}),"Create contact"]},"create"),e.jsxs(L,{variant:"secondary",onClick:()=>_t(!0),"data-testid":"crm-people-empty-create-company",className:"pointer-coarse:h-11",children:[e.jsx(Fe,{size:16}),"Create company"]},"company")]})}):e.jsx(kd,{mode:Ka,onModeChange:nl,contacts:s,activeContactId:(x==null?void 0:x.id)??null,selectedContactIds:ie,selectContact:ca,toggleContactSelect:Er,onUpdate:b,onCreate:y,searchQuery:u,filterLifecycle:p,sortKey:Wt,sortDirection:Q
71a,onSort:ol,visibleColumns:ll})})}):r==="contacts"?e.jsx("div",{className:"flex flex-1 overflow-hidden",children:e.jsx("div",{className:"@container/contactlist flex-1 flex flex-col min-w-0",children:d?e.jsx(Zr,{onRetry:()=>{v(),h()}}):i&&s.length===0?e.jsx("div",{className:"p-6 space-y-2",children:Array.from({length:6}).map((S,M)=>e.jsx(Re,{},M))}):s.length===0&&!i?e.jsxs(e.Fragment,{children:[e.jsx(Al,{allSelected:!1,someSelected:!1,onToggleAll:Wa}),e.jsx("div",{className:"flex-1 flex items-center justify-center","data-testid":"crm-contacts-empty",children:e.jsx(De,{icon:e.jsx(Ne,{size:28,className:"text-[var(--color-text-tertiary)]"}),title:p!=="all"||u?"No matching contacts":"No contacts yet",description:p!=="all"||u?"Try changing your filters to see more contacts.":"Create your first contact to get started.",action:p==="all"&&!u?e.jsxs(L,{onClick:()=>it(!0),children:[e.jsx(oe,{size:16}),"Create contact"]}):void 0})})]}):e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsx(Al,{allSelected:ie.size===s.length&&s.length>0,someSelected:ie.size>0&&ie.size<s.length,onToggleAll:Wa}),e.jsx(Rl,{contacts:s,activeContactId:(x==null?void 0:x.id)??null,selectedContactIds:ie,selectContact:Ot,toggleContactSelect:Er,rowComponent:"contact"}),e.jsx(Jr,{page:m,totalItems:c,perPage:25,onPageChange:j})]})})}):r==="companies"?d?e.jsx(Zr,{onRetry:()=>{v(),h()}}):i&&s.length===0?e.jsx("div",{className:"p-6 space-y-2",children:Array.from({length:6}).map((S,M)=>e.jsx(Re,{},M))}):s.length===0&&!i?e.jsxs("div",{className:"@container/companylist flex-1 flex flex-col",children:[e.jsx(Tl,{allSelected:!1,someSelected:!1,onToggleAll:Wa}),e.jsx("div",{className:"flex-1 flex items-center justify-center","data-testid":"crm-companies-empty",children:e.jsx(De,{icon:e.jsx(Fe,{size:28,className:"text-[var(--color-text-tertiary)]"}),title:p!=="all"||u?"No matching companies":"No companies yet",description:p!=="all"||u?"Try changing your filters to see more companies.":"Create your first company to get started.",action:p==="all"&&!u?e.jsxs(L,{onClick:()=>_t(!0),children:[e.jsx(oe,{size:16}),"Create Company"]}):void 0})})]}):e.jsxs("div",{className:"@container/companylist flex-1 flex flex-col overflow-hidden",children:[e.jsx(Tl,{allSelected:ie.size===s.length&&s.length>0,someSelected:ie.size>0&&ie.size<s.length,onToggleAll:Wa}),e.jsx(Rl,{contacts:s,activeContactId:(x==null?void 0:x.id)??null,selectedContactIds:ie,selectContact:ia,toggleContactSelect:Er,rowComponent:"company"}),e.jsx(Jr,{page:m,totalItems:c,perPage:25,onPageChange:j})]}):r==="deals"?P?e.jsx("div",{className:"p-6 space-y-2",children:Array.from({length:4}).map((S,M)=>e.jsx(Re,{},M))}):Vt.length===0?e.jsx("div",{className:"flex-1 flex items-center justify-center","data-testid":"crm-pipeline-no-stages",children:e.jsx(De,{icon:e.jsx(Ze,{size:32,className:"text-[var(--color-text-tertiary)]"}),title:"No pipelines configured",description:"Create a pipeline via the API to start tracking deals."})}):O.length===0&&!u?e.jsx("div",{className:"flex-1 flex items-center justify-center","data-testid":"crm-pipeline-empty",children:e.jsx(De,{illustration:e.jsx(yi,{}),title:"No deals yet",description:"Track opportunities through your pipeline from first touch to close.",action:e.jsxs(L,{onClick:()=>at(!0),"data-testid":"crm-pipeline-empty-create-deal",children:[e.jsx(oe,{size:16}),"Create your first deal"]})})}):e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[Mr==="list"?e.jsxs(e.Fragment,{children:[!cl&&Vt.length>0&&e.jsx("div",{className:"shrink-0 border-b border-[var(--color-bg-tertiary)] overflow-x-auto mobile-toolbar-scroll","data-testid":"crm-pipeline-mobile-stage-filter",children:e.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 w-max",children:[e.jsxs("button",{type:"button",onClick:()=>Or(null),"aria-pressed":xa===null,className:`inline-flex items-center gap-2 px-3 py-1 rounded-full text-[length:var(--text-label-m)] font-medium whitespace-nowrap cursor-pointer transition-colors ${xa===null?"bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]":"bg-[var(--color-bg-secondary)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-tertiary)]"}`,"data-testid":"crm-pipeline-mobile-stage-all",children:["All stages",e.jsx("span",{className:"tabular-nums text-[length:var(--text-label-s)] opacity-75",children:O.length})]}),Vt.map(S=>{var ne;const M=((ne=da[S.id])==null?void 0:ne.length)??0,K=xa===S.id;return e.jsxs("button",{type:"button",onClick:()=>Or(K?null:S.id),"aria-pressed":K,className:`inline-flex items-center gap-2 px-3 py-1 rounded-full text-[length:var(--text-label-m)
71] font-medium whitespace-nowrap cursor-pointer transition-colors ${K?"bg-[var(--color-accent-subtle)] text-[var(--color-accent-text)]":"bg-[var(--color-bg-secondary)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-tertiary)]"}`,"data-testid":`crm-pipeline-mobile-stage-${S.id}`,children:[S.name,e.jsx("span",{className:"tabular-nums text-[length:var(--text-label-s)] opacity-75",children:M})]},S.id)})]})}),e.jsx(rd,{deals:!cl&&xa?O.filter(S=>S.stage_id===xa):O,activeDealId:(_==null?void 0:_.id)??null,selectedDealIds:je,onSelectDeal:Va,onToggleDealSelect:Ga,onToggleAll:()=>{bt(S=>S.size===O.length&&O.length>0?new Set:new Set(O.map(M=>M.id)))}})]}):Mr==="board"?e.jsx(Id,{stages:Vt,dealsByStage:da,activeDealId:(_==null?void 0:_.id)??null,selectedDealIds:je,onSelectDeal:Va,onToggleDealSelect:Ga,onDealDropped:async(S,M)=>{await Y(S,{stage_id:M})||xs()},onCreateDealInStage:S=>{Bs(S),at(!0)}}):Mr==="owner"?e.jsx(Pl,{groups:Mn,activeDealId:(_==null?void 0:_.id)??null,selectedDealIds:je,onSelectDeal:Va,onToggleDealSelect:Ga,emptyMessage:"Assign an owner to an open deal to organize the pipeline by responsibility.",onShowAll:()=>Fr("list"),totalLabel:"All deals"}):e.jsx(Pl,{groups:On,activeDealId:(_==null?void 0:_.id)??null,selectedDealIds:je,onSelectDeal:Va,onToggleDealSelect:Ga,emptyMessage:"No open deals are past their close date or have been idle for more than 30 days.",onShowAll:()=>Fr("list")}),e.jsx(Jr,{page:ae,totalItems:H,perPage:50,onPageChange:le})]}):null,r==="quotes"&&e.jsx(Nc,{}),(r==="tools"||r==="pipelines"||r==="products"||r==="templates"||r==="scoring"||r==="custom_fields")&&e.jsx(Ld,{}),r==="sequences"&&e.jsx(Sl,{}),r==="scheduler"&&e.jsx(Ho,{to:"/calendar/scheduling",replace:!0})]}),(r==="contacts"||r==="people")&&x&&x.type==="person"&&e.jsx(id,{contact:x,companies:s.filter(S=>S.type==="company"),allPersons:s.filter(S=>S.type==="person"),activities:N,contactDeals:Ea,loading:w,contactDetailLoading:tt,onClose:()=>{qt(),q(),$r()},onUpdate:b,onDelete:g,onLogActivity:St,onCreateDeal:()=>{wr(x.id),at(!0)},onMergeWith:S=>{al({a:x,b:S}),Sr(!0)},onSelectCompany:S=>{Ua({kind:"person",id:x.id,label:x.name},{kind:"company",id:S,label:""})},onSelectDeal:S=>{Ua({kind:"person",id:x.id,label:x.name},{kind:"deal",id:S,label:""})},backStack:_r,onBackStackPop:zr}),(r==="companies"||r==="people")&&x&&x.type==="company"&&e.jsx(dd,{contact:x,activities:N,companyContacts:ee,companyDeals:ke,loading:w,companyDetailLoading:ce,onClose:()=>{Fn(),oa(),$r()},onUpdate:b,onDelete:g,onLogActivity:St,onSelectContact:S=>{Ua({kind:"company",id:x.id,label:x.name},{kind:"person",id:S,label:""})},onSelectDeal:S=>{Ua({kind:"company",id:x.id,label:x.name},{kind:"deal",id:S,label:""})},onAddContactToCompany:S=>{Us(S),it(!0)},onCreateDeal:()=>{wr(null),at(!0)},backStack:_r,onBackStackPop:zr}),r==="deals"&&_&&e.jsx(md,{deal:_,pipelines:I,contacts:s,loading:Z,activities:B,onClose:()=>{$r(),Mt()},onUpdate:Y,onDelete:re,onLogActivity:async S=>{const M=await St(S);return M&&_&&T(_.id),M},backStack:_r,onBackStackPop:zr})]}),e.jsx(vs,{open:Ra,onClose:()=>{it(!1),Us(void 0)},onCreate:y,onViewContact:(S,M)=>{l(M==="company"?"companies":"contacts"),M==="company"?ia(S):Ot(S)},defaultCompanyId:Rn}),e.jsx(vs,{open:Fa,onClose:()=>_t(!1),onCreate:y,onViewContact:(S,M)=>{l(M==="company"?"companies":"contacts"),M==="company"?ia(S):Ot(S)},defaultType:"company"}),e.jsx(zn,{open:Ma,pipelines:I,contacts:s,activePipelineId:k,initialStageId:In,initialContactId:Pn,onClose:()=>{at(!1),Bs(null),wr(null)},onCreate:R}),e.jsx(zi,{open:kr,onClose:()=>Cr(!1),initialTargetGroupId:D,contactGroups:U,onPreview:Tn,onImport:En}),e.jsx(Di,{open:Kn,onOpenChange:Pr,group:Qn,onCreate:Wn,onUpdate:Gn}),e.jsx(we,{open:Dt!==null,onOpenChange:S=>!S&&Rr(null),title:`Delete list "${Dt==null?void 0:Dt.name}"?`,description:e.jsx(e.Fragment,{children:"This will remove the list from your workspace. The contacts in it will not be deleted, but they will no longer be members of this list."}),confirmLabel:"Delete list",onConfirm:Yn}),e.jsx(Pi,{open:Ws,onClose:()=>Gs(!1),onCreate:y,onViewContact:S=>{l("contacts"),Ot(S)}}),e.jsx(Od,{open:Oa,contactA:oo,contactB:io,onClose:()=>{Sr(!1),ct(new Set)},onMerge:An}),e.jsx(we,{open:se!==null,onOpenChange:S=>!S&&Bt(null),title:(se==null?void 0:se.kind)==="deleteContacts"?`Delete ${se.ids.length} ${r==="companies"?"companies":"contacts"}
71`:(se==null?void 0:se.kind)==="deleteDeals"?`Delete ${se.ids.length} deals`:(se==null?void 0:se.kind)==="deleteActiveContact"?"Delete contact":(se==null?void 0:se.kind)==="deleteActiveDeal"?"Delete deal":"",description:(se==null?void 0:se.kind)==="deleteContacts"?`Permanently deletes ${se.ids.length} ${r==="companies"?"companies":"contacts"} — removes all related activities.`:(se==null?void 0:se.kind)==="deleteDeals"?`Permanently deletes ${se.ids.length} deals — removes all related activities.`:(se==null?void 0:se.kind)==="deleteActiveContact"?"Permanently deletes this contact and all related activities.":(se==null?void 0:se.kind)==="deleteActiveDeal"?"Permanently deletes this deal and all related activities.":"",confirmLabel:"Delete",variant:"destructive",onConfirm:qn})]})})}const mx=Object.freeze(Object.defineProperty({__proto__:null,CRM_VIEWS:or,CRM_VIEW_ALIASES:$n,CompanyRow:Nn,ContactRow:wn,CreateContactDialog:vs,CreateDealDialog:zn,CrmPage:qd,DealRow:Is,DealSectionEmptyState:Ta,PeopleTableHeader:hs,PersonListRow:Sn,crmDisplayFor:ir},Symbol.toStringTag,{value:"Module"}));export{vs as C,Le as I,hs as P,zn as a,Sn as b,mx as c,jl as l};

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.