PageSourceSearch

https://app.controlgtm.com/assets/layout-DiGnXO2n.js

js controlgtm.com collected 2026-10-10 00:05:38 UTC 303,306 bytes, 27 lines download raw bytes

1import{E as Se,j as e,r as k,n as b,R as be,p as z,x as ne,v as sr,l as $e,b as Ee,P as nr,S as ar,N as Es,T as ze,q as xe,U as _t,w as Ce,W as rr,z as se,k as je,B as yt,t as ir,V as or,X as Y,a as Le,Y as Ve,Z as ta,$ as St,K as Fs,a0 as es,u as at,L as Us,a1 as ts,M as ss,a2 as sa,F as lr,g as na,a3 as cr,a4 as aa,a5 as dr,a6 as ra,O as ur,a7 as mr,a8 as pr,a9 as tn,f as xr,aa as qs,ab as Ks,ac as hr,ad as fr,ae as sn,af as gr,ag as br,ah as yr,ai as jr,aj as wr}from"./index-CRToEYL8.js";import{S as vr,u as ia}from"./socket-D2GHxcBh.js";import{U as Nr,u as Ye}from"./user-BUfcfMhc.js";import{u as oa,N as kr,a as _r}from"./NewWorkspaceDialog-CjghtK5f.js";import{A as ge}from"./index-BaHmauR5.js";import{u as Sr}from"./useTimezones-CYCl_ZM2.js";import{C as Cr,u as Bs}from"./confirm-CUU2gy6F.js";import{X as ve}from"./x-Bb6COv32.js";import{u as Ct,g as rt,P as st,i as nn,p as Wt,a as la,b as Ue}from"./useFeatureAccess-BvqTstaL.js";import{u as Er,a as Ar,B as Tr,P as Mr,T as an,d as Rr,E as Ir,U as Lr,b as Pr,c as Dr,e as ca,f as da,g as Or}from"./useUsageOverview-DLVhlgrV.js";import{T as qe,C as ua,N as $r,S as zr}from"./field-GAGfV8zy.js";import{u as ma,D as Et}from"./dither-BSHMaIDA.js";import{C as ke}from"./check-OF12l-JJ.js";import{S as ns}from"./shield-check-Cx7Nznq9.js";import{A as ot}from"./arrow-right-CujXqlWD.js";import{A as jt}from"./arrow-up-right-CzKljXqK.js";import{u as as,c as Fr}from"./usePermission-Bfn5ojbj.js";import{S as Ur,u as nt,A as qr,K as tt,a as Kr,P as Br}from"./AIEditPopover--G7nlVXM.js";import{u as Wr,A as rn,a as on,b as ln,P as We,c as wt,d as Hr}from"./PresenceProvider-DGrbt3oE.js";import{u as rs}from"./useClickOutside-D5mxUqBl.js";import{R as pa}from"./reply-CBnRRL_7.js";import{E as Gr}from"./eye-CZUtZpMf.js";import{u as Ut,c as Vr,M as Yr,F as Qr,A as Xr,a as Jr,b as Zr,d as ei,e as ti,C as hs,f as si,T as ni,g as ai,h as ri,I as ii,p as oi,r as li}from"./body-CW-g7dMb.js";import{u as Ie}from"./useComposeStore-v54eZvvf.js";import{u as ci,a as di,b as ui}from"./useNotifications-D6UMnQKm.js";import{B as As,D as xa}from"./database-Cxt-iKMd.js";import{S as ha}from"./settings-2-zdpxvTUB.js";import{C as mi}from"./circle-pause-DCK3LSTi.js";import{U as Ws}from"./users-CIojquQq.js";import{C as fa}from"./credit-card-2M3mQPEG.js";import{S as pi}from"./shield-alert-CLIRzW4G.js";import{C as is}from"./clock-DhXgMgCu.js";import{u as ga}from"./useSwitchOrganization-D5cEQ510.js";import{P as Ht,a as Gt,b as Vt,c as Ts,d as He,e as Yt}from"./popover-menu-DitpGZdK.js";import{C as vt}from"./chevron-down-DlCDVOPH.js";import{P as os}from"./plus-Cqb5CeTZ.js";import{S as ls}from"./sparkles-DFjVmTNN.js";import{G as lt}from"./git-branch-bSJXSKiT.js";import{S as ba}from"./server-BU6GDrc5.js";import{E as Nt}from"./external-link-CKayLj3e.js";import{R as xi}from"./refresh-cw-BGwPJlRI.js";import{C as hi}from"./chevron-left-FPcCpE3F.js";import{A as Ke}from"./AnimatedNumber-CdUelEw9.js";import{u as ya}from"./useAiMetered-DhGQXbwr.js";import{C as ja}from"./chevron-right-D3FQ1yKh.js";import{S as cs}from"./search-FkOt3V6f.js";import{u as fi}from"./useCampaigns-CNhi_KjL.js";import{u as gi,g as bi}from"./useEmails-wm5MlXnY.js";import{u as yi,E as ji,S as wi}from"./SearchTasks-C9jn3vQv.js";import{u as vi}from"./useMeetingsSummary-BIsetSoE.js";import{u as Ni,E as ki}from"./SearchDeals-CPWHKiiJ.js";import{u as _i}from"./useSearchContacts-BaTXCvzy.js";import{u as Si}from"./usePipelines-CgjM-s3l.js";import{u as wa}from"./useTemplates-BozbWnPR.js";import{u as Ci}
1from"./useDashboard-BEb2JBNO.js";import{m as Ei,c as Ai,v as Qt,d as va,a as Na,u as Ti,o as Mi,S as cn}from"./useCloudPool-C6KdtAaK.js";import{K as Ms,u as Ri}from"./useAPIKeys-Bm3u17aQ.js";import{u as Ii}from"./useIntegrationConnections-DNH93875.js";import{u as Li}from"./useAdvisor-BIqjKvPM.js";import{S as ds}from"./settings-BE1W-QjF.js";import{L as Pi}from"./log-out-D9vyWL_u.js";import{M as ka}from"./megaphone-5C6XqyO5.js";import{C as Di}from"./clipboard-list-CtDs0gEC.js";import{C as _a}from"./circle-dollar-sign-D0WtOj0z.js";import{S as Sa}from"./square-check-big-DfVMZzON.js";import{C as Oi}from"./calendar-clock-Cn5b9X1c.js";import{F as Hs}from"./file-text-DPWV5OlK.js";import{C as $i}from"./cable--pT7-K_j.js";import{Z as zi}from"./zap-C6Fcw4Ff.js";import{L as Fi}from"./list-checks-XyvpKLaM.js";import{u as Ui,a as qi,b as Ki,c as Bi,U as Wi}from"./useCancelAccountDeletion-Bgdjwjha.js";import{O as Ca}from"./octagon-alert-vzo0C1PG.js";import{O as Hi,F as Ea}from"./octagon-x-BA6PEl2H.js";import{R as Gi}from"./refresh-ccw-DtwXTtE5.js";import{D as Gs,a as Vs,b as Ys,c as Qs,R as Vi,P as Yi,O as Qi,C as Xi,d as Aa,e as Ji}from"./dialog-BqisZd-_.js";import{G as Zi}from"./GlobalCursors-DPVN1A7Y.js";import{u as eo}from"./useInfiniteQuery-Brwnlpi2.js";import{M as Ta}from"./minus-ChgigZc2.js";import{T as dn}from"./trash-2-DoHrzBEG.js";import{W as to}from"./wrench-BIa5Pqd3.js";import{m as so,H as Rs}from"./selfActivity-gXhhtN8H.js";import{a as no}from"./campaignDeleted-DggMRmgT.js";import{u as ao}from"./useOrganizations-K8QRECMo.js";import{T as un}from"./trash-DCugHQVu.js";import{f as ro,s as io,c as oo,d as lo}from"./useCloudLink-tm9Z_VDu.js";import{s as co,c as uo}from"./cancelLimitRequest-RNl_ABPx.js";import{d as Ma}from"./exportContacts-Dg-fvUjM.js";import{U as mn}from"./upload-C-uRWIo5.js";import{D as pn}from"./download-Bc5uxt3i.js";import{R as mo}from"./rotate-ccw-CzzBbIHE.js";import{C as Ra}from"./cloud-BpxGdgv5.js";import{T as po}from"./tag-BqvWFo3K.js";import{D as xo}from"./DateTimePicker-BcseDG1B.js";import{l as ho}from"./listCredentials-ZrXHrmg5.js";import"./briefcase-DYoZ8bUZ.js";import"./permissions-B5mEHaYf.js";import"./useDebouncedValue-C-kfAzfP.js";import"./undo-2-GShAi3Iq.js";import"./wand-sparkles-DyQ9ovGc.js";import"./Integration-42s0N-nb.js";import"./calendar-plus-JBCFH2Yt.js";import"./sliders-horizontal-MehAvRqk.js";import"./user-plus-DszRErsY.js";import"./user-CYQPJn6d.js";import"./arrow-up-down-CnsBqCQm.js";import"./DatePicker-DGb0ImTI.js";import"./Calendar-KwgMXx8R.js";import"./calendar-BOwWJymX.js";import"./select-menu-gApW-H07.js";const fo=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],go=Se("arrow-down",fo);const bo=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16 12-4-4-4 4",key:"177agl"}],["path",{d:"M12 16V8",key:"1sbj14"}]],us=Se("circle-arrow-up",bo);const yo=[["path",{d:"m15 12-9.373 9.373a1 1 0 0 1-3.001-3L12 9",key:"1hayfq"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172v-.344a2 2 0 0 0-.586-1.414l-1.657-1.657A6 6 0 0 0 12.516 3H9l1.243 1.243A6 6 0 0 1 12 8.485V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"15ts47"}]],Xs=Se("hammer",yo);const jo=[["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m16.2 7.8 2.9-2.9",key:"r700ao"}],["path",{d:"M18 12h4",key:"wj9ykh"}],["path",{d:"m16.2 16.2 2.9 2.9",key:"1bxg5t"}],["path",{d:"M12 18v4",key:"jadmvz"}],["path",{d:"m4.9 19.1 2.9-2.9",key:"bwix9q"}],["path",{d:"M2 12h4",key:"j09sii"}],["path",{d:"m4.9 4.9 2.9 2.9",key:"giyufr"}]],wo=Se("loader",jo);const vo=[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"12jkf8"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M19 16v6",key:"tddt3s"}],["path",{d:"M16 19h6",key:"xwg31i"}]],No=Se("mail-plus",vo);const ko=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],_o=Se("maximize-2",ko);const So=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],Co=Se("menu",So);const Eo=[["path",{d:"M16 10a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 14.286V4a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z",key:"1n2ejm"}],["path",{d:"M20 9a2 2 0 0 1 2 2v10.286a.71.71 0 0 1-1.212.502l-2.202-2.202A2 2 0 0 0 17.172 19H10a2 2 0 0 1-2-2v-1",key:"1qfcsi"}]],Ao=Se("messages-square",Eo);const To=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],Mo=Se("minimize-2",To);const Ro=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],xn=Se("panel-left",Ro);const Io=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],hn=Se("panel-right",Io);const Lo=[["path",{d:"M21 9V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h4",key:"daa4of"}],["rect",{width:"10",height:"7",x:"12",y:"13",rx:"2",key:"1nb8gs"}]],Po=Se("picture-in-picture-2",Lo);const Do=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]],Is=Se("rotate-cw",Do);const Oo=[["path",{d:"M6 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-2",key:"4b9dqc"}],["path",{d:"M6 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-2",key:"22nnkd"}],["path",{d:"M6 6h.01",key:"1utrut"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"m13 6-4 6h6l-4 6",key:"14hqih"}]],$o=Se("server-crash",Oo);const zo=[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71",key:"1jlk70"}],["path",{d:"M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264",key:"18rp1v"}]],Fo=Se("shield-off",zo);const Uo=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",ke
1y:"oel41y"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}],["path",{d:"M12 17h.01",key:"p32p05"}]],qo=Se("shield-question-mark",Uo),fn=({onChange:t,placeholder:s,value:n,id:a,name:r})=>e.jsx(e.Fragment,{children:e.jsx("input",{className:"w-full font-sans text-[15px] bg-transparent placeholder:text-slate-400 text-slate-700 border border-slate-200 rounded-md px-3 py-2.5 transition duration-300 ease focus:outline-none focus:border-slate-300 hover:border-slate-300 shadow-sm focus:shadow",type:"text",onChange:t,placeholder:s,value:n,id:a,name:r})}),Ko=k.createContext(void 0);function gn({children:t}){return e.jsx("h1",{className:"text-lg font-medium font-sans",children:t})}function Bo({children:t}){const[s,n]=b.useState(!1),[a,r]=b.useState(""),[i,l]=b.useState(""),d=b.useRef(null),h=(m,w)=>{r(m),l(""),n(!0),d.current=w},[o,x]=b.useState(!1),c=()=>x(!0),f=()=>{o&&n(!1),x(!1)};return e.jsx(e.Fragment,{children:e.jsxs(Ko.Provider,{value:{show:h},children:[t,e.jsx("div",{className:`bg-black/30 fixed flex inset-0 z-101 items-center justify-center p-1 transition ${s?"opacity-100 visible":"opacity-0 invisible"}`,onMouseDown:c,onMouseUp:f,children:e.jsxs("div",{className:`bg-white max-w-xl w-full flex flex-col gap-2 p-5 rounded-md transition ease-bezier duration-300 ${s?"scale-100":"scale-90"}`,onMouseDown:m=>m.stopPropagation(),onMouseUp:m=>m.stopPropagation(),children:[e.jsx(gn,{children:"Display Name"}),e.jsx(fn,{placeholder:"Display Name",value:a,onChange:m=>r(m.target.value)}),e.jsx(gn,{children:"URL"}),e.jsx(fn,{placeholder:"https://example.com",value:i,onChange:m=>l(m.target.value)}),e.jsxs("div",{className:"flex justify-end mt-2 gap-2",children:[e.jsx("button",{onClick:()=>n(!1),className:"ripple bg-gray-200 text-gray-500 py-2.5 p-8 rounded-md cursor-pointer",children:"Cancel"}),e.jsx("button",{onClick:()=>{d.current&&d.current(a,i),n(!1)},className:"ripple bg-blue-100 text-blue-500 py-2.5 p-8 rounded-md cursor-pointer",children:"Submit"})]})]})})]})})}async function Wo(){return await be({method:"POST",url:"/getaway",authorization:!0})}const Ho=25e3,Go=8e3,Rt=[120,350,800,1500,3e3,5e3,1e4],bn=[1e3,2e3,5e3,1e4,2e4,3e4],Vo=8,Yo=3e4,yn=1e3,Qo=6e4,Pe={JOIN:"phx_join",LEAVE:"phx_leave",REPLY:"phx_reply",ERROR:"phx_error",CLOSE:"phx_close",HEARTBEAT:"heartbeat"};function Xo({children:t,onOpen:s,onClose:n,onError:a}){const[r,i]=k.useState(!1),[l,d]=k.useState(0),h=k.useRef(0),o=k.useRef(null),x=k.useRef(null),c=k.useRef(null),f=k.useRef(0),m=k.useRef(new Map),[w,E]=k.useState({}),_=k.useCallback((A,L)=>{E($=>{if(L===null){if(!(A in $))return $;const p={...$};return delete p[A],p}return $[A]===L?$:{...$,[A]:L}})},[]),M=k.useRef(new Map),S=k.useRef(new Map),j=k.useRef(new Map),I=k.useRef(new Map),P=k.useRef(!1),R=k.useRef(null),C=k.useRef(new Map);k.useEffect(()=>{h.current=l},[l]);const u=k.useCallback(()=>(f.current+=1,String(f.current)),[]),g=k.useCallback(A=>o.current?.readyState!==WebSocket.OPEN?(console.warn("[WS] Not connected - queuing message"),!1):(o.current.send(JSON.stringify(A)),!0),[]),y=k.useCallback(A=>{const L=S.current.get(A);L?.timer&&clearTimeout(L.timer),S.current.delete(A)},[]),T=k.useCallback(A=>{const L=S.current.get(A);L?.timer&&(clearTimeout(L.timer),S.current.set(A,{...L,timer:null}))},[]),v=k.useCallback(()=>{S.current.forEach(A=>{A.timer&&clearTimeout(A.timer)}),S.current.clear()},[]),Q=k.useCallback((A,L)=>{if(!j.current.has(A))return;const $=S.current.get(A);if($?.timer)return;const p=Date.now(),F=$&&p-$.lastAttemptAt<Yo?$.attempts:0;if(F>=Vo)return;const q=L??bn[Math.min(F,bn.length-1)],V=Math.round(q*(1+Math.random()*.25)),oe=setTimeout(()=>{const W=S.current.get(A);if(W&&S.current.set(A,{...W,timer:null}),!j.current.has(A)||o.current?.readyState!==WebSocket.OPEN)return;const X=m.current.get(A);if(X&&(X.state==="joined"||X.state==="joining"))return;const le=j.current.get(A)||{},ue=u();m.current.set(A,{topic:A,state:"joining",joinRef:ue,params:le,handlers:X?.handlers||new Map}),_(A,"joining"),g({topic:A,event:Pe.JOIN,payload:le,ref:ue,join_ref:ue})},V);S.current.set(A,{timer:oe,attempts:F+1,lastAttemptAt:p})},[u,g,_]),ae=k.useRef(new Map),re=z(A=>A.setWsLatencyMs),ce=k.useCallback(()=>{const A=u();ae.current.set(A,performance.now()),g({topic:"phoenix",event:Pe.HEARTBEAT,payload:{},ref:A})&&(R.current&&clearTimeout(R.current),R.current=setTimeout(()=>{try{o.current?.close()}catch{}},Go))},[g,u]),Z=k.useCallback(()=>{c.current&&clearInterval(c.current),c.current=setInterval(ce,Ho)},[ce]),ie=k.useCallback(()=>{c.current&&(clearInterval(c.current),c.current=null)},[]),te=k.useCallback(A=>{let L;try{L=JSON.parse(A)}catch{console.warn("[WS] Failed to parse message:",A);return}const{topic:$,event:p,payload:F,ref:q}=L;if(p===Pe.REPLY&&$==="phoenix"&&q){R.current&&(clearTimeout(R.current),R.current=null);const X=ae.current.get(q);if(X!=null){const le=Math.round(performance.now()-X);ae.current.delete(q),re(le)}return}if(p===Pe.REPLY){const X=m.current.get($);if(X&&q===X.joinRef){const le=F;if(le.status==="ok")X.state="joined",T($);else{X.state="errored";const ue=le.response??{};if(ue.reason==="rate_limited"){const me=Number(ue.retry_after_ms),_e=Number.isFinite(me)?Math.min(Math.max(me,yn),Qo):yn;Q($,_e)}else y($)}_($,X.state)}return}if(p===Pe.ERROR){const X=m.current.get($),le=X?.state==="joined";X&&(X.state="errored",_($,"errored")),le&&Q($);return}if(p===Pe.CLOSE){const X=m.current.get($);X&&(X.state="closed",_($,"closed"));return}const V=m.current.get($);if(V){const X=V.handlers.get(p);
1X&&X.forEach(ue=>{try{ue(F)}catch(me){console.error("[WS] Handler error:",me)}});const le=V.handlers.get("*");le&&le.forEach(ue=>{try{ue({...F,_event:p})}catch(me){console.error("[WS] Wildcard handler error:",me)}})}const oe=F.type||F.event_type||p,W=C.current.get(oe);W&&W.forEach(X=>{try{X(F)}catch(le){console.error("[WS] Legacy handler error:",le)}})},[re,_,Q,y,T]),de=k.useCallback((A,L={})=>{I.current.set(A,(I.current.get(A)??0)+1),j.current.set(A,L);const $=m.current.get(A);if($&&($.state==="joined"||$.state==="joining"))return;const p=u(),F={topic:A,state:"joining",joinRef:p,params:L,handlers:$?.handlers||new Map};m.current.set(A,F),_(A,"joining"),o.current?.readyState===WebSocket.OPEN?g({topic:A,event:Pe.JOIN,payload:L,ref:p,join_ref:p}):M.current.set(A,L)},[u,g,_]),B=k.useCallback(A=>{const L=(I.current.get(A)??0)-1;if(L>0){I.current.set(A,L);return}I.current.delete(A),j.current.delete(A),y(A),M.current.delete(A);const $=m.current.get(A);$&&(o.current?.readyState===WebSocket.OPEN&&($.state==="joined"||$.state==="joining")&&g({topic:A,event:Pe.LEAVE,payload:{},ref:u(),join_ref:$.joinRef}),$.handlers.size===0?m.current.delete(A):($.state="closed",$.joinRef=""),_(A,null))},[u,g,_,y]),N=k.useCallback(A=>m.current.get(A)?.state||"closed",[]),O=k.useCallback((A,L,$)=>{let p=m.current.get(A);p||(p={topic:A,state:"closed",joinRef:"",params:{},handlers:new Map},m.current.set(A,p));let F=p.handlers.get(L);return F||(F=new Set,p.handlers.set(L,F)),F.add($),()=>{if(F?.delete($),F?.size!==0)return;p?.handlers.delete(L);const q=m.current.get(A);q&&q.handlers.size===0&&!I.current.has(A)&&!j.current.has(A)&&m.current.delete(A)}},[]),J=k.useCallback((A,L,$)=>{const p=m.current.get(A);if(!p||p.state!=="joined"){console.warn("[WS] Cannot push to channel - not joined:",A);return}g({topic:A,event:L,payload:$,ref:u(),join_ref:p.joinRef})},[g,u]),U=k.useCallback((A,L)=>{let $=C.current.get(A);return $||($=new Set,C.current.set(A,$)),$.add(L),()=>{$?.delete(L),$?.size===0&&C.current.delete(A)}},[]),D=k.useCallback(A=>{if(o.current?.readyState!==WebSocket.OPEN){console.warn("[WS] Not open - dropping message");return}const L=typeof A=="string"?A:JSON.stringify(A);o.current.send(L)},[]),K=k.useCallback(()=>{j.current.forEach((A,L)=>{const $=m.current.get(L),p=u(),F={topic:L,state:"joining",joinRef:p,params:A,handlers:$?.handlers||new Map};m.current.set(L,F),_(L,"joining"),g({topic:L,event:Pe.JOIN,payload:A,ref:p,join_ref:p})}),M.current.clear()},[u,g,_]),H=k.useCallback(async()=>{if(!(o.current&&(o.current.readyState===WebSocket.OPEN||o.current.readyState===WebSocket.CONNECTING))){x.current&&(clearTimeout(x.current),x.current=null);try{const A=await Wo(),L=new URL(A.url);L.searchParams.set("vsn","1.0.0"),o.current=new WebSocket(L.toString()),o.current.onopen=$=>{i(!0),d(0),Z(),K(),s?.($)},o.current.onmessage=$=>{te($.data)},o.current.onclose=$=>{if(i(!1),ie(),R.current&&(clearTimeout(R.current),R.current=null),re(null),ae.current.clear(),n?.($),v(),m.current.forEach(p=>{p.state==="joined"&&(p.state="closed",_(p.topic,"closed"))}),!P.current){const p=h.current,F=Rt[Math.min(p,Rt.length-1)],q=Math.round(F*(.75+Math.random()*.5));x.current=setTimeout(()=>{d(V=>V+1),H()},q)}},o.current.onerror=$=>{console.error("[WS] Error:",$),a?.($)}}catch(A){if(console.error("[WS] Init failed:",A),!P.current){const $=h.current,p=Rt[Math.min($,Rt.length-1)],F=Math.round(p*(.75+Math.random()*.5));x.current=setTimeout(()=>{d(q=>q+1),H()},F)}}}},[s,n,a,te,Z,ie,K,re,_,v]);k.useEffect(()=>{P.current=!1,H();const A=()=>{if(o.current?.readyState===WebSocket.OPEN)return;const $=o.current;if($&&$.readyState!==WebSocket.CLOSED){$.onclose=null,$.onerror=null;try{$.close()}catch{}}o.current=null,x.current&&(clearTimeout(x.current),x.current=null),i(!1),h.current=0,d(0),H()},L=()=>{document.visibilityState==="visible"&&A()};return window.addEventListener("online",A),document.addEventListener("visibilitychange",L),()=>{P.current=!0,window.removeEventListener("online",A),document.removeEventListener("visibilitychange",L),x.current&&clearTimeout(x.current),R.current&&clearTimeout(R.current),v(),ie(),o.current?.close()}},[H,ie,v]);const ee=k.useMemo(()=>({isConnected:r,reconnectAttempt:l,joinChannel:de,leaveChannel:B,getChannelState:N,channelStates:w,subscribeToChannel:O,pushToChannel:J,subscribe:U,sendMessage:D}),[r,l,de,B,N,w,O,J,U,D]);return e.jsx(vr.Provider,{value:ee,children:t})}function Jo({errorTitle:t,errorMessage:s}){return e.jsxs(ne.div,{className:"fixed inset-0 z-50 bg-white flex items-center justify-center",initial:{opacity:1}
1,animate:{opacity:1},exit:{opacity:0},transition:{duration:.3,ease:"easeInOut"},children:[!(t&&s)&&e.jsx(ne.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2},children:e.jsx(wo,{className:"w-4 h-4 text-zinc-400 animate-spin"})}),e.jsx(ge,{mode:"wait",children:(t||s)&&e.jsxs(ne.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},exit:{opacity:0,y:8},transition:{duration:.3},className:"flex flex-col items-center text-center px-4 max-w-md",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-red-50 flex items-center justify-center mb-3",children:e.jsx(sr,{className:"w-4 h-4 text-red-600"})}),e.jsx("h1",{className:"text-sm font-semibold text-zinc-900 mb-1",children:t}),e.jsx("p",{className:"text-[13px] text-zinc-500 leading-relaxed",children:s})]},"error")})]},"loader")}const Zo={roles:[],permissions:[]};function el(){return $e({queryKey:["admin","roles"],queryFn:async()=>Zo,staleTime:1/0})}const tl={roles:[],permissions:[]},sl=[],nl=({children:t})=>{const s=Ee(),n=oa(),a=el(),r=Sr(),[i,l]=b.useState(!1),[d,h]=b.useState(!1),[o,x]=b.useState(!1),c=k.useMemo(()=>n.data?{...n.data,tags:Array.isArray(n.data.tags)?n.data.tags:[],categories:Array.isArray(n.data.categories)?n.data.categories:[],folders:Array.isArray(n.data.folders)?n.data.folders:[],roles:Array.isArray(n.data.roles)?n.data.roles:[]}:null,[n.data]),f=k.useMemo(()=>
1{const w=[n.error,a.error,r.error].filter(Boolean);for(const E of w){if(E instanceof nr)return{redirect:!0,title:"Authentication Required",message:E.message};const _=E;if(_.status===401||_.redirect)return{redirect:!0,title:"Authentication Required",message:_.message??"Session expired."}}if(n.error){const E=n.error;return{title:`${E.error??"Error"}${E.status?` (${E.status})`:""}`,message:E.message??"An unexpected error occurred."}}},[n.error,a.error,r.error]),m=b.useCallback(w=>{s.setQueryData(["auth","me"],E=>typeof w=="function"?w(E??null):w)},[s]);return f?.redirect?(ar(),e.jsx(Es,{to:"/auth/login",replace:!0})):c&&!c.onboarding_completed_at?e.jsx(Es,{to:"/onboarding",replace:!0}):c?e.jsx(Nr.Provider,{value:{user:c,access:a.data??tl,timezones:r.data??sl,setUser:m,tagsEdit:i,setTagsEdit:l,foldersEdit:d,setFoldersEdit:h,addEmail:o,setAddEmail:x},children:t}):e.jsx(ge,{children:e.jsx(Jo,{errorTitle:f?.title,errorMessage:f?.message})})};function al({children:t}){const[s,n]=b.useState(!1),[a,r]=b.useState(!1),i=b.useRef(null),[l,d]=b.useState(""),h=b.useCallback((x,c)=>{d(x),i.current=c,n(!0)},[]),o=async()=>{if(!(a||!i.current))try{r(!0),await i.current(),n(!1),i.current=null}catch{}finally{r(!1)}};return b.useEffect(()=>{if(!s)return;const x=c=>{c.key==="Escape"&&!a&&n(!1)};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[s,a]),e.jsxs(Cr.Provider,{value:{show:h,setShow:n,setLoading:r},children:[t,e.jsx(ge,{children:s&&e.jsx(ne.div,{initial:{opacity:0}
1,animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:()=>!a&&n(!1),className:"fixed inset-0 z-[200] flex items-center justify-center bg-slate-900/30 backdrop-blur-[2px] px-4",children:e.jsxs(ne.div,{initial:{y:8,opacity:0},animate:{y:0,opacity:1},exit:{y:8,opacity:0},transition:{duration:.16},onClick:x=>x.stopPropagation(),role:"alertdialog","aria-modal":"true",className:"w-full max-w-[400px] rounded-lg bg-white border border-slate-200 shadow-[0_24px_48px_-12px_rgba(15,23,42,0.18),0_8px_16px_-8px_rgba(15,23,42,0.1)] overflow-hidden",children:[e.jsxs("div",{className:"h-12 px-4 border-b border-slate-200 flex items-center gap-2.5",children:[e.jsx("div",{className:"size-5 rounded bg-red-50 text-red-600 flex items-center justify-center",children:e.jsx(ze,{className:"w-3 h-3"})}),e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium",children:"Confirm"}),e.jsx("div",{className:"h-4 w-px bg-slate-200"}),e.jsx("span",{className:"text-[12.5px] text-slate-900 font-medium truncate",children:"Are you sure?"}),e.jsx("button",{type:"button",onClick:()=>!a&&n(!1),disabled:a,"aria-label":"Close",className:"ml-auto size-7 rounded-md text-slate-500 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center justify-center transition-colors disabled:opacity-50",children:e.jsx(ve,{className:"w-3.5 h-3.5"})})]}),e.jsx("div",{className:"px-4 py-4",children:e.jsx("p",{className:"text-[12.5px] text-slate-700 leading-relaxed",children:l})}),e.jsxs("div",{className:"px-3 h-12 border-t border-slate-200 flex items-center gap-1.5",children:[e.jsx("button",{type:"button",onClick:()=>!a&&n(!1),disabled:a,className:"ml-auto h-7 px-2.5 rounded-md text-[12px] text-slate-700 hover:text-slate-900 hover:bg-slate-100 transition-colors disabled:opacity-50",children:"Cancel"}),e.jsxs("button",{type:"button",onClick:o,disabled:a,className:"h-7 px-2.5 rounded-md bg-red-600 hover:bg-red-700 text-white text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors disabled:opacity-60",children:[a&&e.jsx(xe,{className:"w-3 h-3 animate-spin"}),"Confirm"]})]})]},"card")},"overlay")})]})}const qt=[.22,1,.36,1];function rl({open:t,request:s,onClose:n}){const a=Ct(),r=Er(),i=Ar(),l=ma(),[d,h]=b.useState("annual"),[o,x]=b.useState(!1),[c,f]=b.useState(""),[m,w]=b.useState(null),[E,_]=b.useState(!1),M=rt(s.minPlan??"starter"),S=rt(a.plan).id,j=r.pending!==null||r.portalPending,I=st.find(y=>nn(y,M.id)&&Wt(y)>Wt(S))??st.find(y=>nn(y,M.id))??"starter",P=b.useRef(null);b.useEffect(()=>{if(!t)return;const y=document.activeElement;P.current?.focus();const T=v=>{if(v.key!=="Tab")return;const Q=P.current;if(!Q||document.querySelector("[data-nested-modal], [role='alertdialog']"))return;const ae=Q.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])');if(ae.length===0)return;const re=ae[0],ce=ae[ae.length-1],Z=document.activeElement;v.shiftKey&&(Z===re||Z===Q)?(v.preventDefault(),ce.focus()):!v.shiftKey&&Z===ce&&(v.preventDefault(),re.focus())};return document.addEventListener("keydown",T),()=>
1{document.removeEventListener("keydown",T),y?.focus?.()}},[t]),b.useEffect(()=>{if(!t)return;const y=T=>{T.key!=="Escape"||Array.from(document.querySelectorAll("[data-floating]")).some(Q=>Q!==P.current)||document.querySelector("[data-nested-modal], [role='alertdialog']")||j||n()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[t,j,n]),b.useEffect(()=>{if(!t)return;const y=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=y}},[t]);async function R(){const y=c.trim();if(y)try{const T=await i.mutateAsync({code:y});T.valid?(w(T),se.success("Promo code applied")):(w(null),se.error(T.reason||"That code can't be applied"))}catch(T){se.error(je(T))}}async function C(y){const T=await r.upgrade(y,{interval:d,discountCode:m?.valid?m.code:void 0,returnTo:window.location.pathname+window.location.search});T==="changed"&&n(),T==="contact"&&_(!0)}const u=()=>{j||n()},g="upgrade-dialog-title";return _t.createPortal(e.jsxs(ge,{children:[t&&e.jsx(ne.div,{initial:{opacity:0}
1,animate:{opacity:1},exit:{opacity:0},transition:{duration:.2},onMouseDown:y=>{y.target===y.currentTarget&&u()},className:"fixed inset-0 z-[150] flex items-center justify-center bg-slate-900/45 backdrop-blur-[4px] p-3 sm:p-6",children:e.jsxs(ne.div,{role:"dialog","aria-modal":"true","aria-labelledby":g,"data-floating":!0,ref:P,tabIndex:-1,initial:l?{opacity:0}:{opacity:0,y:24,scale:.97},animate:{opacity:1,y:0,scale:1},exit:l?{opacity:0}:{opacity:0,y:16,scale:.98},transition:{duration:.28,ease:qt},onMouseDown:y=>y.stopPropagation(),className:"relative w-full max-w-[1120px] max-h-[calc(100dvh-1.5rem)] sm:max-h-[calc(100dvh-3rem)] overflow-y-auto rounded-2xl bg-white border border-slate-200 shadow-[0_1px_2px_rgba(15,23,42,0.06),0_40px_90px_-30px_rgba(15,23,42,0.5)]",children:[e.jsx(il,{request:s,planLabel:M.label,titleId:g,onClose:u,busy:j}),e.jsxs("div",{className:"px-5 md:px-10 pt-6 flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium",children:"Choose a plan"}),e.jsx("div",{className:"relative h-[18px] mt-0.5 overflow-hidden",children:e.jsx(ge,{initial:!1,mode:"popLayout",children:e.jsx(ne.p,{initial:l?{opacity:0}:{opacity:0,y:14},animate:{opacity:1,y:0},exit:l?{opacity:0}:{opacity:0,y:-14},transition:{duration:.26,ease:qt},className:"absolute inset-0 text-[12.5px] text-slate-500",children:d==="annual"?"Annual billing, two months free every year.":"Monthly billing, switch or cancel any time."},d)})})]}),e.jsx(Tr,{interval:d,onChange:h,size:"md"})]}),e.jsx("div",{className:"px-5 md:px-10 pt-4 pb-6 grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-3 items-stretch",children:st.map((y,T)=>e.jsx(Mr,{id:y,index:T,feature:s.feature,minPlan:M.id,current:S,recommended:y===I,interval:d,discount:m,canAct:a.isOwner,pending:r.pending===y,busy:j,onChoose:()=>C(y)},y))}),e.jsx("div",{className:"px-5 md:px-10 pb-5",children:!o&&!m?e.jsxs("button",{type:"button",onClick:()=>x(!0),className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-slate-900 transition-colors",children:[e.jsx(an,{className:"w-3 h-3"}),"Have a promo code?"]}):e.jsxs(ne.div,{initial:l?!1:{opacity:0,y:-4},animate:{opacity:1,y:0},transition:{duration:.18,ease:qt},className:"flex flex-wrap items-center gap-2",children:[e.jsx(qe,{value:c,onChange:y=>f(y.toUpperCase()),placeholder:"WELCOME10",disabled:!!m,autoFocus:!m,onKeyDown:y=>{y.key==="Enter"&&R()},className:"w-[180px] font-mono uppercase"}),m?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-[11.5px] text-emerald-700 bg-emerald-50 border border-emerald-100 rounded-md px-2 h-7 inline-flex items-center gap-1.5",children:[e.jsx(ke,{className:"w-3 h-3 shrink-0"}),e.jsx("span",{className:"font-mono font-medium",children:m.code}),e.jsxs("span",{children:["· ",Rr(m)]})]}),e.jsxs("button",{type:"button",onClick:()=>{w(null),f("")},className:"h-7 px-2.5 rounded-md border border-slate-200 hover:border-slate-300 text-[12px] text-slate-700 hover:text-slate-900 transition-colors inline-flex items-center gap-1",children:[e.jsx(ve,{className:"w-3 h-3"}),"Clear"]})]}):e.jsxs("button",{type:"button",onClick:R,disabled:i.isPending||!c.trim(),className:"h-7 px-3 rounded-md bg-slate-900 hover:bg-slate-800 text-white text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors disabled:opacity-50",children:[i.isPending?e.jsx(xe,{className:"w-3 h-3 animate-spin"}):e.jsx(an,{className:"w-3 h-3"}),"Apply"]})]})}),e.jsxs("div",{className:"px-5 md:px-10 py-4 border-t border-slate-200 bg-slate-50/60 flex flex-col md:flex-row md:items-center gap-3 text-[12px] text-slate-500",children:[a.isOwner?e.jsxs("ul",{className:"flex flex-wrap items-center gap-x-4 gap-y-1",children:[e.jsxs("li",{className:"inline-flex items-center gap-1.5",children:[e.jsx(ns,{className:"w-3.5 h-3.5 text-emerald-600"}),"Secure checkout by Stripe"]}),e.jsxs("li",{className:"inline-flex items-center gap-1.5",children:[e.jsx(ke,{className:"w-3.5 h-3.5 text-emerald-600"}),"Cancel anytime"]}),e.jsxs("li",{className:"inline-flex items-center gap-1.5",children:[e.jsx(ke,{className:"w-3.5 h-3.5 text-emerald-600"}),"Plan changes are prorated"]})]}):e.jsxs("p",{className:"leading-relaxed",children:["Only the workspace owner can change the plan. Ask them to upgrade to"," ",e.jsx("span",{className:"font-medium text-slate-900",children:M.label}
1),", or see who does what in"," ",e.jsx(Ce,{to:"/app/settings/roles",onClick:n,className:"font-medium text-slate-700 hover:text-slate-900 underline underline-offset-2",children:"Roles and access"}),"."]}),e.jsxs("div",{className:"md:ml-auto flex flex-wrap items-center gap-x-4 gap-y-1",children:[a.isOwner&&e.jsxs(Ce,{to:"/app/settings/billing/plans",onClick:n,className:"inline-flex items-center gap-1 font-medium text-slate-600 hover:text-slate-900 transition-colors",children:["Full billing page",e.jsx(ot,{className:"w-3 h-3"})]}),e.jsxs("a",{href:`${rr}/pricing`,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 font-medium text-slate-600 hover:text-slate-900 transition-colors",children:["Compare every feature",e.jsx(jt,{className:"w-3 h-3"})]}),e.jsx("button",{type:"button",onClick:u,disabled:j,className:"h-7 px-2.5 rounded-md border border-slate-200 hover:border-slate-300 bg-white text-[12px] font-medium text-slate-700 hover:text-slate-900 transition-colors disabled:opacity-50",children:"Not now"})]})]})]},"upgrade-card")},"upgrade-backdrop"),E&&e.jsx(Ir,{open:E,onClose:()=>_(!1)},"enterprise-inquiry")]}),document.body)}function il({request:t,planLabel:s,titleId:n,onClose:a,busy:r}){const i=ma(),l=t.bullets?.slice(0,4),d=h=>i?{}:{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.4,ease:qt,delay:h}};return e.jsxs("div",{className:"relative overflow-hidden px-5 pt-9 pb-8 md:px-10 md:pt-12 md:pb-10 text-center text-white",children:[e.jsxs("div",{className:"absolute inset-0","aria-hidden":"true",children:[e.jsx("div",{className:"sky-base"}),e.jsx("div",{className:"sky-breathe"}),e.jsx("div",{className:"sun-glow"}),e.jsx("img",{src:"/backdrops/cloud-3.webp",alt:"",decoding:"async",className:"cloud-drift cloud-1 absolute select-none",style:{top:"-4%",left:"-6%",width:340,opacity:.5,height:"auto"}}),e.jsx("img",{src:"/backdrops/cloud-4.webp",alt:"",decoding:"async",className:"cloud-drift cloud-2 absolute select-none",style:{bottom:"-10%",right:"-4%",width:300,opacity:.45,height:"auto"}}),e.jsx("img",{src:"/backdrops/cloud-1.webp",alt:"",decoding:"async",className:"cloud-drift cloud-1 absolute select-none",style:{top:"30%",right:"18%",width:200,opacity:.3,height:"auto"}}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-16 bg-gradient-to-t from-slate-900/25 to-transparent"})]}),e.jsx("button",{type:"button",onClick:a,disabled:r,"aria-label":"Close",className:"absolute top-3 right-3 z-10 size-8 rounded-md bg-white/15 hover:bg-white/25 text-white inline-flex items-center justify-center transition-colors disabled:opacity-50",children:e.jsx(ve,{className:"w-4 h-4"})}),e.jsxs("div",{className:"relative z-10 max-w-2xl mx-auto",children:[e.jsxs(ne.span,{...d(.05),className:"inline-flex items-center gap-1.5 h-6 px-2.5 rounded-full bg-white/15 border border-white/25 text-[11px] font-medium backdrop-blur-sm",children:[e.jsx(yt,{className:"w-3 h-3"}),t.feature," · ",s," and up"]}),e.jsxs(ne.h2,{...d(.12),id:n,className:"mt-4 text-[26px] md:text-[36px] font-semibold tracking-[-0.03em] leading-[1.08]",children:[t.feature," unlocks with ",s,"."]}),e.jsx(ne.p,{...d(.2),className:"mt-3 text-[14px] md:text-[15px] text-sky-50/90 leading-relaxed max-w-xl mx-auto",children:t.blurb??`Pick a plan and ${t.feature.toLowerCase()} turns on for your whole workspace the moment checkout completes.`}),l&&l.length>0&&e.jsx(ne.ul,{...d(.28),className:"mt-5 flex flex-wrap justify-center gap-x-4 gap-y-1.5 text-[12.5px] text-white/90",children:l.map(h=>e.jsxs("li",{className:"inline-flex items-center gap-1.5",children:[e.jsx(ke,{className:"w-3 h-3 text-emerald-200 shrink-0"}),h]},h))})]})]})}function ol({children:t}){const[s,n]=b.useState(null),[a,r]=b.useState(!1),i=b.useCallback(h=>{n(h),r(!0)},[]),l=b.useCallback(()=>r(!1),[]);ll();const d=b.useMemo(()=>({open:i,close:l}),[i,l]);return e.jsxs(Lr.Provider,{value:d,children:[t,s&&e.jsx(rl,{open:a,request:s,onClose:l})]})}function ll(){const[t,s]=ir(),n=Ee(),a=t.get("checkout");b.useEffect(()=>{if(a!=="success"&&a!=="cancel")return;a==="success"?(n.invalidateQueries({queryKey:["subscription"]}),n.invalidateQueries({queryKey:["organizations"]}),se.success("Your plan is active. Everything it includes is unlocked.")):se("Checkout canceled. Your workspace is unchanged.");
1const r=new URLSearchParams(t);r.delete("checkout"),s(r,{replace:!0})},[a])}function cl({children:t}){return e.jsx(e.Fragment,{children:t})}function dl(){return e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-[#f5f6f8]"}),e.jsx("div",{className:"absolute",style:{top:"-80px",left:"-60px",width:"520px",height:"240px",background:"rgba(255,255,255,0.95)",borderRadius:"50% 50% 18% 18%",filter:"blur(60px)",opacity:.7}}),e.jsx("div",{className:"absolute",style:{top:"10%",right:"8%",width:"380px",height:"180px",background:"rgba(255,255,255,0.85)",borderRadius:"50% 50% 18% 18%",filter:"blur(70px)",opacity:.55}}),e.jsx("div",{className:"absolute",style:{top:"32%",left:"26%",width:"300px",height:"140px",background:"rgba(255,255,255,0.9)",borderRadius:"50% 50% 22% 22%",filter:"blur(70px)",opacity:.45}})]})}function kt({className:t}){return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,className:t,children:[e.jsx("path",{d:"M9.5 4c.62 4.7 3.3 7.38 8 8-4.7.62-7.38 3.3-8 8-.62-4.7-3.3-7.38-8-8 4.7-.62 7.38-3.3 8-8Z"}),e.jsx("path",{d:"M18.5 2c.31 2.35 1.65 3.69 4 4-2.35.31-3.69 1.65-4 4-.31-2.35-1.65-3.69-4-4 2.35-.31 3.69-1.65 4-4Z"})]})}function ul(){const{status:t,quality:s}=or();return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:Y("w-2 h-2 rounded-full",t==="connected"&&s==="good"&&"bg-emerald-500 animate-pulse",t==="connected"&&s==="degraded"&&"bg-amber-500",t==="connected"&&s==="poor"&&"bg-red-500",t==="connecting"&&"bg-amber-500",t==="disconnected"&&"bg-red-500")}),e.jsxs("span",{className:"text-xs text-muted-foreground hidden sm:inline",children:[t==="connected"&&s==="good"&&"Live",t==="connecting"&&"Reconnecting...",t==="disconnected"&&"Disconnected",t==="connected"&&s==="degraded"&&"Slow connection",t==="connected"&&s==="poor"&&"Poor connection"]})]})}const ml=4;function jn(t){return t?t.split(/\s+/).filter(Boolean).slice(0,2).map(s=>s[0]?.toUpperCase()).join(""):"?"}function wn(t){switch(t?.split(":")[0]){case"automation":return"an automation";case"campaign":return"a campaign";case"contact":return"a contact";case"thread":return"a conversation";default:return""}}function pl(t){if(t.action==="replying")return{label:"Replying to a message",tone:"hot",Icon:pa};if(t.action==="editing"){const s=wn(t.resource);return{label:s?`Editing ${s}`:"Editing",tone:"hot",Icon:ta}}if(t.action==="viewing"&&t.resource){const s=wn(t.resource);return{label:s?`Viewing ${s}`:"Viewing",tone:"cool",Icon:Gr}}if(t.page){const s=t.page.split("/").filter(Boolean)[1];if(s)return{label:`In ${s.replace(/-/g," ")}`,tone:"idle",Icon:null}}return{label:"Online",tone:"idle",Icon:null}}const xl={hot:"text-amber-600",cool:"text-sky-600",idle:"text-slate-400"};function hl(){const t=Wr(),[s,n]=k.useState(!1),a=k.useRef(null),r=Le(),{pathname:i}=Ve();if(rs(a,()=>n(!1)),t.length===0)return null;const l=t.slice(0,ml),d=t.length-l.length,h=t.filter(o=>o.action==="editing"||o.action==="replying").length;return e.jsxs("div",{ref:a,className:"relative hidden sm:block",children:[e.jsxs("button",{type:"button","aria-label":`${t.length} teammate${t.length===1?"":"s"} online`,className:"flex items-center -space-x-1.5 rounded-full focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-200",onClick:()=>n(o=>!o),children:[l.map(o=>{const x=o.action==="editing"||o.action==="replying";return e.jsxs(rn,{size:"sm",className:Y("ring-2 ring-white border",x?"border-amber-300":"border-emerald-300/70"),children:[o.avatar?e.jsx(on,{src:o.avatar,alt:o.name??""}):null,e.jsx(ln,{className:Y("text-[9.5px] font-semibold",x?"bg-amber-50 text-amber-700":"bg-emerald-50 text-emerald-700"),children:jn(o.name)})]},o.userId)}),d>0&&e.jsxs("span",{className:"relative z-10 inline-flex size-6 items-center justify-center rounded-full bg-slate-100 ring-2 ring-white text-[9.5px] font-semibold text-slate-500",children:["+",d]})]}),e.jsx(ge,{children:s&&e.jsxs(ne.div,{initial:{opacity:0,y:4,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:4,scale:.98},transition:{duration:.12},className:"absolute right-0 top-full mt-2 w-[260px] max-h-[60vh] overflow-y-auto rounded-md border border-slate-200 bg-white shadow-lg z-50 py-1.5",children:[e.jsxs("div",{className:"px-3 pb-1.5 pt-0.5 flex items-center gap-1.5",children:[e.jsxs("span",{className:"relative flex size-1.5",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-60"}),e.jsx("span",{className:"relative inline-flex size-1.5 rounded-full bg-emerald-500"})]}),e.jsxs("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400",children:[t.length," online"]}),h>0&&e.jsxs("span",{className:"ml-auto text-[10px] font-medium text-amber-600",children:[h," editing"]})]}),t.map(o=>{const x=pl(o),c=!!o.page&&o.page.startsWith("/app");return e.jsxs("button",{type:"button",disabled:!c,title:c?"Go where they are":void 0,onClick:()=>{n(!1),!(!c||o.page===i)&&r(o.page)},className:Y("group w-full px-3 py-1.5 flex items-center gap-2.5 text-left",c?"hover:bg-slate-50":"cursor-default"),children:[e.jsxs(rn,{size:"sm",children:[o.avatar?e.jsx(on,{src:o.avatar,alt:o.name??""}):null,e.jsx(ln,{className:"bg-sky-50 text-sky-700 text-[9.5px] font-semibold",children:jn(o.name)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[12.5px] text-slate-900 font-medium truncate",children:o.name??"Teammate"}),e.jsxs("div",{className:Y("text-[10.5px] truncate flex items-center gap-1",xl[x.tone]),children:[x.Icon&&e.jsx(x.Icon,{className:"w-3 h-3 shrink-0"}),x.label]})]}),c&&e.jsx(ot,{className:"w-3 h-3 shrink-0 text-slate-300 opacity-0 transition-opacity group-hover:opacity-100"})]},o.userId)})]})})]})}function vn(t,s){return Math.max(0,Math.ceil((t.scheduledAt-s)/1e3))}function fl(){const t=Ut(j=>j.entries),s=Ut(j=>j.remove),n=Le(),a=Ee(),[r,i]=b.useState(()=>Date.now()),[l,d]=b.useState(!1),[h,o]=b.useState(null),[x,c]=b.useState(()=>new Set),f=b.useRef(x);f.current=x;const m=b.useRef(null),w=b.useRef(null);b.useEffect(()=>{if(t.length===0)return;i(Date.now());const j=window.setInterval(()=>i(Date.now()),500);return()=>window.clearInterval(j)},[t.length]),b.useEffect(()=>{for(const j of t)j.scheduledAt<=r&&!f.current.has(j.taskId)&&s(j.taskId)},[r,t,s]),b.useEffect(()=>{t.length===0&&d(!1)},[t.length]),b.useEffect(()=>{if(!l)return;const j=P=>{const R=P.target;m.current?.contains(R)||w.current?.contains(R)||d(!1)},I=P=>{P.key==="Escape"&&(P.stopPropagation(),d(!1))};return document.addEventListener("mousedown",j,!0),document.addEventListener("touchstart",j,!0),document.addEventListener("keydown",I,!0),()=>{document.removeEventListener("mousedown",j,!0),document.removeEventListener("touchstart",j,!0),document.removeEventListener("keydown",I,!0)}},[l]);const E=b.useMemo(()=>[...t].sort((j,I)=>j.scheduledAt-I.scheduledAt),[t]),_=E[0],M=()=>{const j=m.current;if(!j)return;const I=j.getBoundingClientRect();
1o({top:I.bottom+6,right:Math.max(8,document.documentElement.clientWidth-I.right)}),d(P=>!P)},S=async j=>{if(!f.current.has(j.taskId)){c(I=>new Set(I).add(j.taskId));try{await Vr(j.taskId),s(j.taskId),a.invalidateQueries({queryKey:["unibox"]}),j.kind==="compose"&&j.seed?(Ie.getState().openDraft(j.seed),se.success("Send cancelled, back to your draft")):j.kind==="reply"&&j.reply?(Ut.getState().setReplyRestore(j.reply),n(`/app/unibox/all/${encodeURIComponent(j.reply.threadId)}`),se.success("Send cancelled, back to your reply")):se.success("Send cancelled")}catch(I){const P=I;P?.status===404?(s(j.taskId),a.invalidateQueries({queryKey:["unibox"]}),se.error("Already sent")):se.error(je(P))}finally{c(I=>{const P=new Set(I);return P.delete(j.taskId),P})}}};return e.jsxs(e.Fragment,{children:[e.jsx(ge,{children:_&&e.jsxs(ne.div,{initial:{opacity:0,scale:.94},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.94},transition:{duration:.14,ease:[.16,1,.3,1]},ref:m,className:"h-7 pl-2 pr-1 rounded-md border border-amber-200 bg-amber-50 flex items-center gap-1 shrink-0",children:[e.jsxs("button",{type:"button",onClick:M,title:"Pending sends",className:"h-full flex items-center gap-1.5 text-[12.5px] text-amber-800 hover:text-amber-950 transition-colors",children:[e.jsx(St,{className:"w-3.5 h-3.5 shrink-0"}),e.jsxs("span",{className:"font-medium tabular-nums whitespace-nowrap",children:["Sending in ",vn(_,r),"s"]}),E.length>1&&e.jsxs("span",{className:"h-4 px-1 rounded bg-amber-100 text-[10px] font-semibold text-amber-800 inline-flex items-center",children:["+",E.length-1]})]}),e.jsx("button",{type:"button",onClick:()=>{S(_)},disabled:x.has(_.taskId),className:"h-5 px-1.5 rounded bg-white/70 border border-amber-200 text-[10.5px] font-medium text-amber-900 hover:bg-white transition-colors disabled:opacity-50",children:x.has(_.taskId)?e.jsx(xe,{className:"w-3 h-3 animate-spin"}):"Cancel"})]})}),_t.createPortal(e.jsx(ge,{children:l&&h&&E.length>0&&e.jsxs(ne.div,{ref:w,"data-floating":"",initial:{opacity:0,y:-4,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98},transition:{duration:.12,ease:[.16,1,.3,1]},style:{position:"fixed",top:h.top,right:h.right,zIndex:130},className:"w-[300px] max-w-[calc(100vw-16px)] max-h-[300px] overflow-y-auto rounded-md border border-slate-200 bg-white shadow-xl py-1",children:[e.jsx("div",{className:"px-2.5 pt-1 pb-1.5 text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium",children:"Pending sends"}),E.map(j=>e.jsxs("div",{className:"px-2.5 py-1.5 flex items-center gap-2 hover:bg-slate-50 transition-colors",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-[11.5px] text-slate-800 truncate",children:[j.to[0]??"(no recipient)",j.to.length>1&&e.jsxs("span",{className:"text-slate-400",children:[" +",j.to.length-1]})]}),e.jsx("div",{className:"text-[10.5px] text-slate-400 truncate",children:j.subject||"(no subject)"})]}),e.jsxs("span",{className:"shrink-0 tabular-nums text-[11px] font-medium text-amber-700",children:[vn(j,r),"s"]}),e.jsx("button",{type:"button",onClick:()=>{S(j)},disabled:x.has(j.taskId),className:"shrink-0 h-6 px-2 rounded-md border border-slate-200 hover:border-slate-300 text-[11px] text-slate-700 hover:text-slate-900 transition-colors disabled:opacity-50 inline-flex items-center",children:x.has(j.taskId)?e.jsx(xe,{className:"w-3 h-3 animate-spin"}):"Cancel"})]},j.taskId))]})}),document.body)]})}const gl={inbound_reply:{icon:pa,tone:"bg-sky-50 text-sky-600"},inbound_out_of_office:{icon:is,tone:"bg-slate-100 text-slate-500"},health_bounce:{icon:ze,tone:"bg-amber-50 text-amber-600"},health_complaint:{icon:pi,tone:"bg-rose-50 text-rose-600"},health_worker_downtime:{icon:$o,tone:"bg-rose-50 text-rose-600"},security_new_signin:{icon:Fs,tone:"bg-violet-50 text-violet-600"},billing_alert:{icon:fa,tone:"bg-amber-50 text-amber-600"},team_activity:{icon:Ws,tone:"bg-emerald-50 text-emerald-600"},campaign_paused:{icon:mi,tone:"bg-rose-50 text-rose-600"},health_domain_auth:{icon:Fo,tone:"bg-rose-50 text-rose-600"}},bl={icon:As,tone:"bg-slate-100 text-slate-500"},yl={today:"Today",yesterday:"Yesterday",earlier:"Earlier"};function jl(){const t=new Date;return new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()}function Ia(t){const s=jl(),n=s-1440*60*1e3,a=t.getTime();return a>=s?"today":a>=n?"yesterday":"earlier"}function wl(t){const s=new Date(t),n=Math.max(0,Math.floor((Date.now()-s.getTime())/1e3));if(n<60)return"now";const a=Math.floor(n/60);if(a<60)return`${a}m`;const r=Math.floor(a/60);return r<24?`${r}h`:Ia(s)==="yesterday"?"Yesterday":s.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function vl(){const{data:t,isLoading:s}=ci(),n=di(),a=ui(),[r,i]=b.useState(!1),[l,d]=b.useState("all"),h=b.useRef(null),o=b.useCallback(()=>i(!1),[]);rs(h,o);const x=t?.unread??0,c=t?.notifications??[],f=l==="unread"?c.filter(S=>!S.read_at):c,m=b.useMemo(()=>{const S=[];for(const j of f){const I=Ia(new Date(j.created_at)),P=S[S.length-1];P&&P.bucket===I?P.rows.push(j):S.push({bucket:I,rows:[j]})}return S},[f]),w=S=>{const j=gl[S.category]??bl,I=j.icon;return e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("span",{className:`mt-0.5 flex size-6 shrink-0 items-center justify-center rounded-md ${j.tone}`,children:e.jsx(I,{className:"size-3.5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:`text-[12px] truncate ${S.read_at?"font-normal text-slate-600":"font-semibold text-slate-900"}`,children:S.title}),S.body&&e.jsx("div",{className:`text-[11px] truncate ${S.read_at?"text-slate-400":"text-slate-500"}`,children:S.body})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5 pt-0.5",children:[e.jsx("span",{className:"text-[10px] text-slate-400",children:wl(S.created_at)}),!S.read_at&&e.jsx("span",{className:"size-1.5 rounded-full bg-sky-500"})]})]})},E=S=>`block w-full text-left px-3 py-2 border-l-2 transition-colors hover:bg-slate-50 ${S.read_at?"border-l-transparent":"border-l-sky-500 bg-sky-50/40"}`,_=e.jsxs("div",{className:"px-3 py-8 flex flex-col items-center gap-2 text-center",children:[e.jsx("span",{className:"flex size-8 items-center justify-center rounded-full bg-slate-100 text-slate-400",children:e.jsx(As,{className:"size-4"})}),e.jsx("span",{className:"text-[12px] text-slate-400",children:"You're all caught up."})]}),M=e.jsx("div",{className:"px-3 py-2.5 space-y-3 animate-pulse","aria-hidden":"true",children:[0,1,2,3].map(S=>e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:"size-6 rounded-md bg-slate-100"}),e.jsxs("div",{className:"flex-1 space-y-1.5 pt-0.5",children:[e.jsx("div",{className:"h-2.5 w-2/3 rounded bg-slate-100"}
1),e.jsx("div",{className:"h-2 w-1/2 rounded bg-slate-100"})]})]},S))});return e.jsxs("div",{ref:h,className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>i(S=>!S),"aria-label":"Notifications",className:"relative w-7 h-7 rounded-md flex items-center justify-center text-slate-500 hover:text-slate-900 hover:bg-slate-200/60 transition-colors",children:[e.jsx(As,{className:"w-4 h-4"}),x>0&&e.jsx("span",{className:"absolute -top-0.5 -right-0.5 min-w-[14px] h-[14px] px-1 rounded-full bg-rose-500 text-white text-[9px] font-semibold flex items-center justify-center",children:x>9?"9+":x})]}),e.jsx(ge,{children:r&&e.jsxs(ne.div,{initial:{opacity:0,y:-4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.12},className:"absolute right-0 top-full mt-1.5 w-[340px] max-w-[90vw] rounded-md border border-slate-200 bg-white shadow-[0_12px_32px_-8px_rgba(15,23,42,0.18)] z-50 overflow-hidden",children:[e.jsxs("div",{className:"h-9 px-3 flex items-center gap-2 border-b border-slate-200",children:[e.jsx("span",{className:"text-[12px] font-medium text-slate-900",children:"Notifications"}),e.jsx("div",{className:"ml-auto flex items-center gap-0.5 rounded-md bg-slate-100 p-0.5",children:["all","unread"].map(S=>e.jsx("button",{type:"button",onClick:()=>d(S),className:`h-5 px-1.5 rounded text-[10.5px] font-medium transition-colors ${l===S?"bg-white text-slate-900 shadow-sm":"text-slate-500 hover:text-slate-900"}`,children:S==="all"?"All":"Unread"},S))}),x>0&&e.jsx("button",{type:"button",onClick:()=>n.mutate(),className:"text-[11px] text-sky-600 hover:text-sky-700 shrink-0",children:"Mark all read"})]}),e.jsx("div",{className:"max-h-96 overflow-y-auto",children:s?M:f.length===0?_:m.map(S=>e.jsxs("div",{children:[e.jsx("div",{className:"sticky top-0 z-10 px-3 pt-2 pb-1 bg-white text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-400",children:yl[S.bucket]}),S.rows.map(j=>{const I=()=>{j.read_at||a.mutate(j.id),i(!1)};return j.link?e.jsx(Ce,{to:j.link,onClick:I,className:E(j),children:w(j)},j.id):e.jsx("button",{type:"button",onClick:I,className:E(j),children:w(j)},j.id)})]},S.bucket))}),e.jsx("div",{className:"border-t border-slate-200 bg-slate-50/60",children:e.jsxs(Ce,{to:"/app/settings/notifications",onClick:o,className:"flex h-8 items-center justify-center gap-1.5 text-[11.5px] text-slate-500 hover:text-slate-900 transition-colors",children:[e.jsx(ha,{className:"size-3.5"}),"Notification settings"]})})]})})]})}function Nn(t){return t.split(" ").filter(Boolean).map(s=>s[0]).join("").toUpperCase().slice(0,2)}function Nl(){const t=Le(),s=z(x=>x.organizations),n=z(x=>x.currentOrganization),a=z(x=>x.setCurrentOrganization),r=ga(),[i,l]=b.useState(!1),d=n?.name??"Workspace",h=n?.avatar_url??n?.avatar,o=async x=>{if(x!==n?.id)try{await r.mutateAsync(x);const c=s.find(f=>f.id===x);c&&a(c)}catch(c){se.error(je(c))}};return e.jsxs(e.Fragment,{children:[e.jsxs(Ht,{align:"start",children:[e.jsx(Gt,{asChild:!0,children:e.jsxs("button",{type:"button",className:"group w-full flex items-center gap-2 pl-1 pr-2 h-8 rounded-md hover:bg-slate-200/60 transition-colors text-left",children:[e.jsx("span",{className:`size-6 rounded-md ring-1 ring-slate-200 flex items-center justify-center shrink-0 overflow-hidden ${h?"bg-white p-0.5":"bg-slate-900"}`,children:h?e.jsx("img",{src:h,alt:"",className:"w-full h-full object-cover rounded-[4px]"}):e.jsx("span",{className:"text-[10px] font-bold text-white leading-none tracking-tight",children:Nn(d)})}),e.jsx("span",{className:"text-[12.5px] font-medium text-slate-900 truncate flex-1 min-w-0",children:d}),e.jsx(vt,{className:"w-3.5 h-3.5 text-slate-400 shrink-0 group-hover:text-slate-700 transition-colors"})]})}),e.jsxs(Vt,{minWidth:232,children:[e.jsx(Ts,{children:"Workspaces"}),s.length===0?e.jsx("div",{className:"px-3 py-2 text-[11.5px] text-slate-400",children:"No workspaces yet."}):s.map(x=>{const c=x.avatar_url??x.avatar;return e.jsx(He,{onSelect:()=>o(x.id),disabled:r.isPending,selected:x.id===n?.id,icon:e.jsx("span",{className:`size-5 rounded-md ring-1 ring-slate-200 flex items-center justify-center shrink-0 overflow-hidden ${c?"bg-white p-px":"bg-slate-900"}`,children:c?e.jsx("img",{src:c,alt:"",className:"w-full h-full object-cover rounded-[3px]"}):e.jsx("span",{className:"text-[9px] font-bold text-white leading-none tracking-tight",children:Nn(x.name)})}),children:x.name},x.id)}),e.jsx(Yt,{}),e.jsx(He,{onSelect:()=>l(!0),icon:e.jsx(os,{className:"w-3 h-3"}),children:"New workspace"}),e.jsx(He,{onSelect:()=>t("/select-org"),icon:e.jsx(ha,{className:"w-3 h-3"}),children:"Manage workspaces"})]})]}),e.jsx(kr,{open:i,onClose:()=>l(!1)})]})}function kl(){const t=Ct();if(t.loading)return e.jsx("div",{className:"h-6 w-16 rounded border border-slate-200 bg-slate-100 animate-pulse"});
1if(!t.billing)return e.jsx(It,{to:t.isOwner?"/app/settings/workspace":"/app/settings/profile",className:"bg-indigo-50 text-indigo-700 border-indigo-100",dot:"bg-indigo-500",label:"Self-hosted",title:"Self-hosted deployment: every feature is unlocked",icon:!0});if(t.status==="past_due")return e.jsx(It,{to:t.isOwner?"/app/settings/billing":"/app/settings/roles",className:"bg-red-50 text-red-700 border-red-100",dot:"bg-red-500",label:"Past due",title:"Subscription is past due — open billing"});if(t.status==="canceled")return e.jsx(It,{to:t.isOwner?"/app/settings/billing":"/app/settings/roles",className:"bg-slate-100 text-slate-500 border-slate-200",dot:"bg-slate-400",label:"Canceled",title:"Subscription is canceled"});const s=rt(t.plan),n=la[s.accent],a=t.status==="trialing"?`${s.label} · Trial`:s.label,r=t.isOwner?"/app/settings/billing":"/app/settings/roles";return e.jsx(It,{to:r,className:n.pill,dot:n.dot,label:a,title:`Workspace plan: ${s.label}${t.isOwner?" — manage":""}`,icon:s.id==="enterprise"||s.id==="business"})}function It({to:t,className:s,dot:n,label:a,title:r,icon:i}){return e.jsxs(Ce,{to:t,title:r,className:Y("inline-flex items-center gap-1.5 h-6 px-2 rounded border text-[11px] font-semibold uppercase tracking-[0.08em] transition-colors hover:brightness-105",s),children:[i?e.jsx(ls,{className:"w-2.5 h-2.5"}):e.jsx("span",{className:Y("size-1.5 rounded-full",n)}),a]})}async function _l(){return await be({method:"GET",url:"/auth/instance",authorization:!0})}function Sl(){return $e({queryKey:["auth","instance"],queryFn:_l,staleTime:5*6e4,refetchInterval:t=>t.state.error?.status===404?!1:5*6e4,retry:!1})}async function La(t=!1){return await be({method:"GET",baseURL:es,url:t?"/admin/instance/update?log=1":"/admin/instance/update",authorization:!0})}async function Cl(){return await be({method:"POST",baseURL:es,url:"/admin/instance/update/check",authorization:!0})}async function El(t="latest"){return await be({method:"POST",baseURL:es,url:"/admin/instance/update/apply",data:{target:t},authorization:!0})}const Ls=["admin","instance","update"],Ps=["admin","instance","update","log"];function ms(t){return t?.updater.job?.status==="running"}function Pa(t){return $e({queryKey:Ls,queryFn:()=>La(!1),refetchInterval:s=>ms(s.state.data)?3e3:6e4,retry:!1,enabled:t})}function Al(t){return $e({queryKey:Ps,queryFn:()=>La(!0),refetchInterval:s=>ms(s.state.data)?1500:1e4,retry:!1,enabled:t})}function ps(t){if(!t)return"";const s=t.running.version;if(s&&s!=="dev")return s;const n=t.running.commit??t.updater.checkout?.commit??"";return n?`dev ${n.slice(0,7)}`:"dev"}const Xt="warmbly.update.started";function Tl(t,s){try{sessionStorage.setItem(Xt,JSON.stringify({fromVersion:t,fromCommit:s,startedAt:Date.now()}))}catch{}}function Da(){try{const t=sessionStorage.getItem(Xt);if(!t)return null;const s=JSON.parse(t);return Date.now()-s.startedAt>60*6e4?(sessionStorage.removeItem(Xt),null):s}catch{return null}}function Jt(){try{sessionStorage.removeItem(Xt)}catch{}}const Oa="https://docs.controlgtm.com/development/updates/",Ml=[{id:"fetch",label:"Fetch",hint:"Reading the remote repository",icon:lt},{id:"checkout",label:"Pull",hint:"Moving the checkout to the new version",icon:us},{id:"build",label:"Build",hint:"Rebuilding every image, usually the longest step",icon:Xs},{id:"restart",label:"Restart",hint:"Recreating the services that changed",icon:Is},{id:"prune",label:"Clean up",hint:"Removing images nothing uses any more",icon:xa},{id:"wait",label:"Reconnect",hint:"Waiting for the backend to answer again",icon:ba}],Rl=[{id:"fetch",label:"Fetch",hint:"Reading the remote repository",icon:lt},{id:"checkout",label:"Pull",hint:"Moving the checkout to the new version",icon:us},{id:"command",label:"Build and restart",hint:"Running the upgrade script",icon:Xs},{id:"wait",label:"Reconnect",hint:"Waiting for the backend to answer again",icon:ba}];function Il({open:t,onClose:s}){const n=Ee(),a=Pa(t),r=Al(t),i=r.data??a.data,l=Da(),[d,h]=b.useState("overview"),[o,x]=b.useState(1),c=b.useCallback(I=>{const P=["overview","confirm","progress","done","failed"];x(P.indexOf(I)>=P.indexOf(d)?1:-1),h(I)},[d]),f=ms(i),m=!!l&&(r.isError||a.isError),w=i?.updater.last_job,E=!!l&&!f&&!m&&w&&w.status!=="running";b.useEffect(()=>{if(t){if(f||m)d!=="progress"&&c("progress");else if(E){const I=w?.status==="succeeded"?"done":"failed";d!==I&&c(I)}}},[t,f,m,E,w?.status,d,c]),b.useEffect(()=>{t||h("overview")},[t]),b.useEffect(()=>{if(!t)return;const I=P=>{P.key==="Escape"&&(document.querySelector("[data-floating], [role='alertdialog']")||(P.preventDefault(),s()))};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[t,s]);const _=at({mutationFn:Cl,onSuccess:I=>{n.setQueryData(Ls,I),n.setQueryData(Ps,I),se.success(I.update_available?"A newer version is available":"This instance is up to date")},onError:I=>se.error(je(I))}),M=at({mutationFn:()=>El("latest"),onSuccess:I=>
1{Tl(i?.running.version??"",i?.running.commit??I.from_commit),c("progress"),n.invalidateQueries({queryKey:Ls}),n.invalidateQueries({queryKey:Ps})},onError:I=>se.error(je(I))}),S=i?.updater.job??i?.updater.last_job,j=i?.updater.mode==="command"?Rl:Ml;return e.jsx(ge,{children:t&&e.jsx(ne.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onMouseDown:s,className:"fixed inset-0 z-[110] flex items-center justify-center bg-slate-900/30 backdrop-blur-[2px] px-4",children:e.jsxs(ne.div,{role:"dialog","aria-modal":"true","aria-label":"Update Control",initial:{y:8,opacity:0,scale:.985},animate:{y:0,opacity:1,scale:1},exit:{y:8,opacity:0,scale:.985},transition:{duration:.18,ease:[.22,1,.36,1]},onMouseDown:I=>I.stopPropagation(),className:"w-full max-w-[560px] rounded-lg bg-white border border-slate-200 shadow-[0_24px_48px_-12px_rgba(15,23,42,0.18),0_8px_16px_-8px_rgba(15,23,42,0.1)] overflow-hidden flex flex-col max-h-[88dvh]",children:[e.jsx(Pl,{state:i,pane:d,onClose:s}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto overflow-x-hidden",children:e.jsx(ge,{mode:"wait",initial:!1,custom:o,children:e.jsxs(ne.div,{custom:o,variants:Ll,initial:"enter",animate:"center",exit:"exit",transition:{duration:.18,ease:[.22,1,.36,1]},className:"px-5 py-5",children:[d==="overview"&&e.jsx(Dl,{state:i,loading:a.isLoading&&!i}),d==="confirm"&&e.jsx(Ol,{state:i}),d==="progress"&&e.jsx($l,{steps:j,job:S,backendDown:m}),d==="done"&&e.jsx(zl,{state:i,job:S,onAcknowledge:()=>Jt()}),d==="failed"&&e.jsx(Fl,{job:S})]},d)})}),e.jsx(Ul,{pane:d,state:i,checking:_.isPending,applying:M.isPending,onCheck:()=>_.mutate(),onContinue:()=>c("confirm"),onBack:()=>c("overview"),onApply:()=>M.mutate(),onRetry:()=>{Jt(),c("confirm")},onClose:s})]},"card")},"overlay")})}const Ll={enter:t=>({x:t*28,opacity:0}
1),center:{x:0,opacity:1},exit:t=>({x:t*-28,opacity:0})};function Pl({state:t,pane:s,onClose:n}){const a=t?.latest?.tag,r=s==="progress"?"Updating this instance":s==="done"?"Update finished":s==="failed"?"Update failed":t?`Running ${ps(t)}${a?` · latest ${a}`:""}`:"Reading the running version";return e.jsxs("div",{className:"flex items-center gap-3 px-5 h-14 border-b border-slate-200 shrink-0",children:[e.jsx("span",{className:"size-8 rounded-md bg-sky-50 text-sky-700 flex items-center justify-center shrink-0",children:e.jsx(us,{className:"w-4 h-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[13.5px] font-semibold text-slate-900 leading-tight",children:"Update Control"}),e.jsx("div",{className:"text-[12px] text-slate-500 truncate",children:r})]}),e.jsx("button",{type:"button",onClick:n,"aria-label":"Close",className:"size-7 rounded-md flex items-center justify-center text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition-colors",children:e.jsx(ve,{className:"w-4 h-4"})})]})}function Dl({state:t,loading:s}){if(s||!t)return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"h-20 rounded-md bg-slate-100 animate-pulse"}),e.jsx("div",{className:"h-4 w-2/3 rounded bg-slate-100 animate-pulse"}
1),e.jsx("div",{className:"h-4 w-1/2 rounded bg-slate-100 animate-pulse"})]});const{latest:n,updater:a}=t,r=a.checkout,i=t.update_available;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:Y("rounded-md border p-4 flex items-center gap-4",i?"border-amber-200 bg-amber-50/60":"border-emerald-200 bg-emerald-50/50"),children:[e.jsx(kn,{label:"Running",value:ps(t),muted:i}),e.jsx(ot,{className:Y("w-4 h-4 shrink-0",i?"text-amber-500":"text-emerald-500")}),e.jsx(kn,{label:i?"Available":"Latest",value:n?.tag??(r&&!r.detached?`${r.branch} head`:"unknown"),accent:i}),e.jsx("div",{className:"ml-auto text-right",children:e.jsx("span",{className:Y("inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-[10.5px] font-semibold uppercase tracking-[0.1em]",i?"border-amber-300 bg-white text-amber-700":"border-emerald-300 bg-white text-emerald-700"),children:i?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"size-1.5 rounded-full bg-amber-500 animate-pulse"}),"Update"]}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"w-3 h-3"}),"Current"]})})})]}),e.jsxs("dl",{className:"text-[12.5px] divide-y divide-slate-100 border-y border-slate-100",children:[e.jsx(Lt,{label:"Release",children:n?e.jsxs("span",{className:"inline-flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"font-medium text-slate-900",children:n.name||n.tag}),n.published_at&&e.jsxs("span",{className:"text-slate-500",children:["published ",Sn(n.published_at)]}),n.html_url&&e.jsxs("a",{href:n.html_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-sky-700 hover:underline",children:["Release notes",e.jsx(Nt,{className:"w-3 h-3"})]})]}):t.check_error?e.jsxs("span",{className:"text-amber-700",children:["Could not read releases: ",t.check_error]}):e.jsx("span",{className:"text-slate-500",children:t.enabled?`No release found for ${t.repo}`:"Release check is off"})}),r&&e.jsx(Lt,{label:"Checkout",children:e.jsxs("span",{className:"inline-flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 font-mono text-[11.5px] text-slate-700",children:[e.jsx(lt,{className:"w-3 h-3 text-slate-400"}),r.detached?"pinned":r.branch,"@",r.commit.slice(0,7)]}),!r.detached&&e.jsx("span",{className:"text-slate-500",children:r.behind>0?`${r.behind} commit${r.behind===1?"":"s"} behind`:"matches the remote"}),r.dirty&&e.jsx("span",{className:"text-amber-700",children:"local changes present"})]})}),e.jsxs(Lt,{label:"Updater",children:[a.status==="ok"&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-slate-700",children:[e.jsx("span",{className:"size-1.5 rounded-full bg-emerald-500"}),"ready",e.jsxs("span",{className:"text-slate-400",children:["(",a.mode," mode)"]})]}),a.status==="off"&&e.jsx("span",{className:"text-slate-500",children:"not configured"}),a.status==="unreachable"&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-amber-700",children:[e.jsx("span",{className:"size-1.5 rounded-full bg-amber-500"}),"unreachable"]})]}),e.jsx(Lt,{label:"Checked",children:e.jsx("span",{className:"text-slate-500",children:t.checked_at?`${Sn(t.checked_at)}, every ${t.interval}`:"not yet"})})]}),a.status!=="ok"&&e.jsxs(_n,{tone:a.status==="unreachable"?"warning":"info",children:[e.jsx("div",{className:"font-medium text-slate-900",children:a.status==="unreachable"?"The updater is not answering":"Updates run from a shell here"}),e.jsx("div",{className:"mt-0.5",children:a.status==="unreachable"?a.error:"No updater is configured on this instance, so apply updates on the host:"}),e.jsx("code",{className:"mt-1.5 block rounded bg-white/80 border border-slate-200 px-2 py-1 font-mono text-[11.5px] text-slate-800",children:"git pull && make up"}),e.jsxs("a",{href:Oa,target:"_blank",rel:"noreferrer",className:"mt-1.5 inline-flex items-center gap-1 text-sky-700 hover:underline",children:["How to enable the updater",e.jsx(Nt,{className:"w-3 h-3"})]})]}),r?.dirty&&a.status==="ok"&&e.jsx(_n,{tone:"warning",children:"The checkout has local modifications. The updater refuses to move it until they are committed or stashed."})]})}function Ol({state:t}){const s=t?.latest?.tag,n=[{icon:lt,title:s?`Pull ${s} from the repository`:"Pull the latest changes from the repository",text:"The checkout moves forward; nothing is overwritten that was committed."},{icon:Xs,title:"Rebuild and restart every service",text:"Takes a few minutes. Postgres, Redis and NATS stay up; only what changed is recreated."},{icon:St,title:"Sending and syncing pause, then resume",text:"Nothing in flight is lost: campaigns and warmup pick up from the database when the workers are back."},{icon:xa,title:"Migrations apply when the backend comes back",text:"They are forward-only and safe with data in place. A backup before an update is still the one you are glad to have."},{icon:ns,title:"You stay signed in",text:"This tab reconnects on its own and reloads once the new version answers."}];return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"text-[13px] text-slate-700",children:"Here is what happens when you continue."}),e.jsx("ul",{className:"space-y-2.5",children:n.map((a,r)=>
1e.jsxs(ne.li,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},transition:{delay:.04*r,duration:.2},className:"flex items-start gap-3",children:[e.jsx("span",{className:"mt-0.5 size-7 rounded-md bg-slate-50 border border-slate-200 text-slate-600 flex items-center justify-center shrink-0",children:e.jsx(a.icon,{className:"w-3.5 h-3.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[12.5px] font-medium text-slate-900",children:a.title}),e.jsx("div",{className:"text-[12px] text-slate-500 leading-relaxed",children:a.text})]})]},a.title))})]})}function $l({steps:t,job:s,backendDown:n}){const a=n?"wait":s?.step??"starting",r=Math.max(0,t.findIndex(o=>o.id===a)),i=Math.round(n?(t.length-.5)/t.length*100:(r+.5)/t.length*100),[l,d]=b.useState(!1),h=s?.log??[];return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-[12px] mb-1.5",children:[e.jsxs("span",{className:"font-medium text-slate-900 inline-flex items-center gap-2",children:[e.jsx(xe,{className:"w-3.5 h-3.5 animate-spin text-sky-600"}),n?"Reconnecting to the backend":t[r]?.label??"Starting"]}),e.jsxs("span",{className:"text-slate-500 tabular-nums",children:[i,"%"]})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-100 overflow-hidden",children:e.jsx(ne.div,{className:"h-full rounded-full bg-sky-500",initial:{width:0},animate:{width:`${i}%`},transition:{duration:.5,ease:[.22,1,.36,1]}})}),e.jsx("div",{className:"mt-1.5 text-[12px] text-slate-500",children:n?"The services are restarting. This can take a minute; keep the tab open or come back later, the result is kept.":"You can close this and keep working. The pill in the header follows the update."})]}),e.jsx("ol",{className:"space-y-1",children:t.map((o,x)=>{const c=x<r||n&&o.id!=="wait",f=x===r&&!c;return e.jsxs("li",{className:Y("flex items-center gap-3 rounded-md px-2 py-1.5 transition-colors",f&&"bg-sky-50/70"),children:[e.jsx("span",{className:Y("size-6 rounded-full flex items-center justify-center shrink-0 border transition-colors",c&&"bg-emerald-500 border-emerald-500 text-white",f&&"bg-white border-sky-400 text-sky-600",!c&&!f&&"bg-white border-slate-200 text-slate-300"),children:e.jsx(ge,{mode:"wait",initial:!1,children:c?e.jsx(ne.span,{initial:{scale:.4,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.4,opacity:0},transition:{type:"spring",stiffness:500,damping:30},children:e.jsx(ke,{className:"w-3.5 h-3.5"})},"done"):f?e.jsx(ne.span,{initial:{opacity:0}
1,animate:{opacity:1},children:e.jsx(xe,{className:"w-3.5 h-3.5 animate-spin"})},"active"):e.jsx(ne.span,{initial:{opacity:0},animate:{opacity:1},children:e.jsx(o.icon,{className:"w-3 h-3"})},"idle")})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:Y("text-[12.5px] leading-tight",c?"text-slate-500":f?"text-slate-900 font-medium":"text-slate-400"),children:o.label}),f&&e.jsx(ne.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},className:"text-[11.5px] text-slate-500",children:n&&o.id==="wait"?"Waiting for the new backend to answer":o.hint})]})]},o.id)})}),e.jsx($a,{open:l,onToggle:()=>d(o=>!o),count:h.length}),e.jsx(ge,{initial:!1,children:l&&e.jsx(ne.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},transition:{duration:.18},className:"overflow-hidden",children:e.jsx(Js,{lines:h})},"log")})]})}function zl({state:t,job:s,onAcknowledge:n}){const[a,r]=b.useState(8),[i,l]=b.useState(!1);return b.useEffect(()=>{if(a<=0){n(),window.location.reload();return}const d=setTimeout(()=>r(h=>h-1),1e3);return()=>clearTimeout(d)},[a,n]),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col items-center text-center py-2",children:[e.jsx(ne.span,{initial:{scale:.5,opacity:0},animate:{scale:1,opacity:1},transition:{type:"spring",stiffness:380,damping:22},className:"size-14 rounded-full bg-emerald-50 border border-emerald-200 text-emerald-600 flex items-center justify-center",children:e.jsx(ne.span,{initial:{opacity:0}
1,animate:{opacity:1},transition:{delay:.15},children:e.jsx(ke,{className:"w-7 h-7",strokeWidth:2.5})})}),e.jsxs("div",{className:"mt-3 text-[15px] font-semibold text-slate-900",children:["Updated to ",t?ps(t):"the new version"]}),e.jsxs("div",{className:"mt-1 text-[12.5px] text-slate-500 max-w-[36ch]",children:["Every service is back and sending has resumed. Reloading in ",a,"s to pick up the new dashboard."]}),s?.from_commit&&s?.to_commit&&e.jsxs("div",{className:"mt-2 font-mono text-[11px] text-slate-400",children:[s.from_commit.slice(0,7)," ",e.jsx("span",{className:"text-slate-300",children:"→"})," ",s.to_commit.slice(0,7)]})]}),e.jsx($a,{open:i,onToggle:()=>l(d=>!d),count:s?.log?.length??0}),i&&e.jsx(Js,{lines:s?.log??[]})]})}function Fl({job:t}){return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3 rounded-md border border-red-200 bg-red-50/60 p-3",children:[e.jsx(ne.span,{initial:{scale:.6,opacity:0},animate:{scale:1,opacity:1},transition:{type:"spring",stiffness:380,damping:22},className:"size-8 rounded-full bg-white border border-red-200 text-red-600 flex items-center justify-center shrink-0",children:e.jsx(ve,{className:"w-4 h-4"})}),e.jsxs("div",{className:"min-w-0 text-[12.5px] leading-relaxed text-red-900",children:[e.jsx("div",{className:"font-semibold",children:"The update did not finish"}),e.jsx("div",{className:"mt-0.5",children:t?.error??"See the log below."}),e.jsx("div",{className:"mt-1 text-red-800/80",children:t?.step&&t.step!=="restart"&&t.step!=="wait"?"It stopped before anything restarted, so the previous version is still running.":"Check the services on the host before trying again."})]})]}),e.jsx(Js,{lines:t?.log??[]})]})}function Ul({pane:t,state:s,checking:n,applying:a,onCheck:r,onContinue:i,onBack:l,onApply:d,onRetry:h,onClose:o}){const x=!!s&&s.updater.status==="ok"&&s.update_available&&!s.updater.checkout?.dirty;return e.jsxs("div",{className:"flex items-center gap-2 px-5 h-14 border-t border-slate-200 bg-slate-50/60 shrink-0",children:[e.jsxs("a",{href:Oa,target:"_blank",rel:"noreferrer",className:"text-[12px] text-slate-500 hover:text-slate-900 inline-flex items-center gap-1",children:["How updates work",e.jsx(Nt,{className:"w-3 h-3"})]}),e.jsx("div",{className:"flex-1"}),t==="overview"&&e.jsxs(e.Fragment,{children:[e.jsxs(mt,{onClick:r,disabled:n,children:[e.jsx(xi,{className:Y("w-3.5 h-3.5",n&&"animate-spin")}),n?"Checking":"Check now"]}),x?e.jsxs(pt,{onClick:i,children:["Update and restart",e.jsx(ot,{className:"w-3.5 h-3.5"})]}):e.jsx(pt,{onClick:o,children:"Done"})]}),t==="confirm"&&e.jsxs(e.Fragment,{children:[e.jsxs(mt,{onClick:l,disabled:a,children:[e.jsx(hi,{className:"w-3.5 h-3.5"}),"Back"]}),e.jsxs(pt,{onClick:d,disabled:a,tone:"amber",children:[a?e.jsx(xe,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Is,{className:"w-3.5 h-3.5"}),a?"Starting":"Update now"]})]}),t==="progress"&&e.jsx(mt,{onClick:o,children:"Keep running in the background"}),t==="done"&&e.jsxs(e.Fragment,{children:[e.jsx(mt,{onClick:o,children:"Later"}),e.jsx(pt,{onClick:()=>window.location.reload(),children:"Reload now"})]}),t==="failed"&&e.jsxs(e.Fragment,{children:[e.jsx(mt,{onClick:o,children:"Close"}),e.jsxs(pt,{onClick:h,children:[e.jsx(Is,{className:"w-3.5 h-3.5"}),"Try again"]})]})]})}function kn({label:t,value:s,accent:n,muted:a}){return e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-500",children:t}),e.jsx("div",{className:Y("text-[15px] font-semibold tracking-tight truncate",n?"text-amber-800":a?"text-slate-500":"text-slate-900"),children:s})]})}function Lt({label:t,children:s}){return e.jsxs("div",{className:"grid grid-cols-[6rem_1fr] gap-3 py-2",children:[e.jsx("dt",{className:"text-slate-500",children:t}),e.jsx("dd",{className:"min-w-0 text-slate-800",children:s})]})}function _n({tone:t,children:s}){return e.jsxs("div",{className:Y("flex items-start gap-3 rounded-md border p-3 text-[12.5px] leading-relaxed",t==="warning"?"border-amber-200 bg-amber-50/60 text-amber-900":"border-sky-200 bg-sky-50/60 text-sky-900"),children:[e.jsx(ze,{className:"mt-0.5 w-4 h-4 shrink-0"}),e.jsx("div",{className:"min-w-0 flex-1",children:s})]})}function $a({open:t,onToggle:s,count:n}){return e.jsxs("button",{type:"button",onClick:s,className:"inline-flex items-center gap-1 text-[12px] text-slate-500 hover:text-slate-900 transition-colors",children:[e.jsx(vt,{className:Y("w-3.5 h-3.5 transition-transform",t&&"rotate-180")}
1),t?"Hide log":"Show log",n>0&&e.jsxs("span",{className:"text-slate-400 tabular-nums",children:["(",n,")"]})]})}function Js({lines:t}){const s=b.useRef(null);return b.useEffect(()=>{const n=s.current;n&&(n.scrollTop=n.scrollHeight)},[t.length]),e.jsx("pre",{ref:s,className:"max-h-56 overflow-auto rounded-md border border-slate-200 bg-slate-950 p-3 text-[11px] leading-relaxed text-slate-200",children:t.length>0?t.join(`
2`):"Waiting for output"})}function mt({children:t,onClick:s,disabled:n}){return e.jsx("button",{type:"button",onClick:s,disabled:n,className:"inline-flex items-center gap-1.5 h-8 px-3 rounded-md text-[12.5px] font-medium text-slate-600 hover:text-slate-900 hover:bg-slate-200/60 transition-colors disabled:opacity-50 disabled:pointer-events-none",children:t})}function pt({children:t,onClick:s,disabled:n,tone:a="dark"}){return e.jsx("button",{type:"button",onClick:s,disabled:n,className:Y("inline-flex items-center gap-1.5 h-8 px-3.5 rounded-md text-[12.5px] font-medium text-white transition-colors disabled:opacity-60 disabled:pointer-events-none",a==="amber"?"bg-amber-600 hover:bg-amber-700":"bg-slate-900 hover:bg-slate-800"),children:t})}function Sn(t){const s=Date.now()-new Date(t).getTime(),n=Math.round(s/6e4);if(n<1)return"just now";if(n<60)return`${n} min ago`;const a=Math.round(n/60);if(a<24)return`${a} hour${a===1?"":"s"} ago`;const r=Math.round(a/24);return r<30?`${r} day${r===1?"":"s"} ago`:new Date(t).toLocaleDateString()}const Cn=2048,En=16384;function ql(){const t=Sl(),{data:s}=oa(),n=s?.admin_permissions??0,a=(n&Cn)===Cn,r=(n&En)===En,i=t.data,l=!!i?.self_hosted,d=Pa(a&&l),h=d.data,o=Ee(),[x,c]=b.useState(!1),f=Da(),m=ms(h),w=!!f&&(d.isError||t.isError);if(b.useEffect(()=>{if(!f||!h||m||x)return;const C=h.updater.last_job,u=h.running.commit&&h.running.commit!==f.fromCommit||h.running.version&&h.running.version!==f.fromVersion;C?.status==="failed"?(Jt(),se.error(`The update failed: ${C.error??"open the version pill for the log"}`)):(u||C?.status==="succeeded")&&(Jt(),se.success(`Updated to ${ps(h)}`),o.invalidateQueries())},[f,h,m,x,o]),!i||!l)return null;const E=i.version&&i.version!=="dev"?i.version:i.commit?`dev ${i.commit.slice(0,7)}`:"dev",_=i.update_available,M=i.latest?.tag;let S=_?M?`Update to ${M}`:"Update available":E,j=_?e.jsxs("span",{className:"relative flex size-2.5 items-center justify-center",children:[e.jsx("span",{className:"absolute inline-flex size-full rounded-full bg-amber-400 opacity-60 animate-ping"}),e.jsx(us,{className:"relative w-3 h-3"})]}):e.jsx("span",{className:"size-1.5 rounded-full bg-slate-400"}),I=_?"bg-amber-50 text-amber-800 border-amber-200":"bg-white/70 text-slate-500 border-slate-200",P=_?r?`Control ${M??"newer"} is available; this instance runs ${E}. Click to update.`:`Control ${M??"newer"} is available; this instance runs ${E}. Ask a platform admin to update.`:r?`Control ${E}, up to date. Click for details.`:`Control ${E}, up to date.`;r&&(m||w)&&(S=w?"Reconnecting":"Updating",j=e.jsx(xe,{className:"w-3 h-3 animate-spin"}),I="bg-sky-50 text-sky-700 border-sky-200",P=w?"The backend is restarting after an update":`Update in progress: ${h?.updater.job?.step??""}`);const R=Y("inline-flex items-center gap-1.5 h-6 px-2 rounded border text-[11px] font-semibold tracking-[0.02em] transition-colors",I,r&&(_?"hover:bg-amber-100":"hover:text-slate-900 hover:bg-white"));return r?e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>c(!0),title:P,className:R,children:[j,S]}),e.jsx(Il,{open:x,onClose:()=>c(!1)})]}):e.jsxs("span",{title:P,className:Y(R,"cursor-default"),children:[j,S]})}function Kl(){const t=as("MANAGE_BILLING"),s=ya(),n=Pr(),a=Dr(),r=ca(),[i,l]=b.useState(!1),d=b.useRef(null),h=b.useCallback(()=>l(!1),[]);if(rs(d,h),!t||!s||n.isPending||!n.data||n.data.unlimited)return null;const o=n.data,x=o.balance,c=a.data?.low_balance_threshold??25,f=x<=0,m=!f&&x<=c,w=r.data,E=w?.limit_daily!=null?{spent:w.spent_today,limit:w.limit_daily,word:"today"}:w?.limit_weekly!=null?{spent:w.spent_week,limit:w.limit_weekly,word:"this week"}:w?.limit_monthly!=null?{spent:w.spent_month,limit:w.limit_monthly,word:"this month"}:null,_=E?Math.max(0,1-E.spent/Math.max(1,E.limit)):o.monthly_allowance>0?Math.min(1,o.monthly_balance/o.monthly_allowance):x>
20?1:0,M=E?`${E.spent.toLocaleString()} of ${E.limit.toLocaleString()} credits used ${E.word}`:`${o.monthly_balance.toLocaleString()} of ${o.monthly_allowance.toLocaleString()} plan credits left`,S=o.purchased_balance>0?`, plus ${o.purchased_balance.toLocaleString()} extra`:"";return e.jsxs("div",{ref:d,className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>l(j=>!j),"aria-label":M+S,title:i?void 0:M+S,className:Y("flex items-center gap-1.5 px-2 h-7 rounded-md text-[11.5px] font-medium tabular-nums transition-colors",f?"text-red-600 hover:bg-red-50":m?"text-amber-600 hover:bg-amber-50":"text-slate-500 hover:text-slate-900 hover:bg-slate-200/60"),children:[e.jsx(Wl,{fraction:_}),E?e.jsxs("span",{className:"flex items-baseline gap-1",children:[e.jsxs("span",{className:"flex items-baseline",children:[e.jsx(Ke,{value:E.spent,format:j=>Xe(Math.round(j))}),e.jsxs("span",{className:"opacity-60 font-normal",children:["/",Xe(E.limit)]})]}),e.jsx("span",{className:"opacity-60 font-normal",children:E.word==="today"?"today":E.word==="this week"?"wk":"mo"})]}):o.monthly_allowance>0?e.jsxs("span",{className:"flex items-baseline",children:[e.jsx(Ke,{value:o.monthly_balance,format:j=>Xe(Math.round(j))}),e.jsxs("span",{className:"opacity-60 font-normal",children:["/",Xe(o.monthly_allowance)]})]}):e.jsx(Ke,{value:x,format:j=>Xe(Math.round(j))}),o.purchased_balance>0&&e.jsxs("span",{className:"opacity-70 font-normal",children:["+",Xe(o.purchased_balance)]})]}),e.jsx(ge,{children:i&&e.jsxs(ne.div,{initial:{opacity:0,y:-4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.12},className:"absolute right-0 top-full mt-1.5 w-72 rounded-md border border-slate-200 bg-white shadow-[0_12px_32px_-8px_rgba(15,23,42,0.18)] z-50 overflow-hidden",children:[e.jsx(Bl,{credits:o,settings:a.data,low:m,empty:f}),e.jsxs(Ce,{to:"/app/settings/billing/ai-credits",onClick:h,className:"flex items-center gap-1 px-3 h-9 border-t border-slate-200 text-[11.5px] font-medium text-slate-600 hover:text-slate-900 hover:bg-slate-50 transition-colors",children:["Usage & spend controls",e.jsx(jt,{className:"w-3 h-3"})]})]})})]})}function Bl({credits:t,settings:s,low:n,empty:a}){const r=ca(),i=Math.max(0,t.monthly_allowance-t.monthly_balance),l=t.monthly_allowance>0?t.monthly_balance/t.monthly_allowance:0,d=Hl(t.next_reset_at),h=t.packs.find(o=>o.key===s?.auto_topup_pack);return e.jsxs("div",{className:"px-3 pt-3 pb-2.5 space-y-3.5",children:[e.jsxs("div",{className:"flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium",children:"AI credits"}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-1.5",children:[e.jsx(Ke,{value:t.balance,className:Y("text-[22px] leading-none font-semibold tracking-tight tabular-nums",a?"text-red-600":"text-slate-900")}),e.jsx("span",{className:"text-[11px] text-slate-400",children:"left"})]})]}),(a||n||s?.auto_topup_enabled&&h)&&e.jsxs("div",{className:Y("flex items-center gap-1.5 text-[10.5px] font-medium pb-0.5",a?"text-red-600":n?"text-amber-600":"text-slate-500"),children:[e.jsx("span",{className:Y("size-1.5 rounded-full shrink-0",a?"bg-red-500":n?"bg-amber-500":"bg-emerald-500")}),a?"Out of credits":n?"Running low":"Auto top-up on"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline justify-between text-[11.5px]",children:[e.jsx("span",{className:"text-slate-600",children:"Plan credits"}),e.jsxs("span",{className:"tabular-nums text-slate-900 font-medium",children:[t.monthly_balance.toLocaleString(),e.jsxs("span",{className:"text-slate-400 font-normal",children:[" ","/ ",t.monthly_allowance.toLocaleString()]})]})]}),e.jsx(Et,{frac:Math.min(1,Math.max(0,l)),tone:a?"rose":n?"amber":"slate",height:4,className:"mt-1.5"}),e.jsxs("div",{className:"mt-1 flex justify-between text-[10.5px] text-slate-400",children:[e.jsxs("span",{children:[i.toLocaleString()," used this cycle"]}),d&&e.jsx("span",{children:d})]})]}),e.jsxs("div",{className:"flex items-baseline justify-between text-[11.5px]",children:[e.jsx("span",{className:"text-slate-600",children:"Extra credits"}),e.jsxs("span",{className:Y("tabular-nums font-medium",t.purchased_balance>0?"text-slate-900":"text-slate-400"),children:[t.purchased_balance.toLocaleStr
2ing(),e.jsx("span",{className:"text-slate-400 font-normal",children:" never expire"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium",children:"Spent"}),r.isPending||!r.data?e.jsxs("div",{className:"space-y-1.5 animate-pulse",children:[e.jsx("div",{className:"h-3.5 rounded bg-slate-100"}),e.jsx("div",{className:"h-3.5 rounded bg-slate-100"}),e.jsx("div",{className:"h-3.5 rounded bg-slate-100"})]}):e.jsxs(e.Fragment,{children:[e.jsx(fs,{label:"Today",spent:r.data.spent_today,limit:r.data.limit_daily}),e.jsx(fs,{label:"This week",spent:r.data.spent_week,limit:r.data.limit_weekly}),e.jsx(fs,{label:"This month",spent:r.data.spent_month,limit:r.data.limit_monthly})]})]}),s?.auto_topup_enabled&&h&&e.jsxs("div",{className:"text-[10.5px] text-slate-400",children:["Buys ",h.credits.toLocaleString()," credits automatically when the balance drops below"," ",s.auto_topup_threshold.toLocaleString(),"."]})]})}function fs({label:t,spent:s,limit:n}){const a=n?Math.min(1,s/n):null;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline justify-between text-[11.5px]",children:[e.jsx("span",{className:"text-slate-600",children:t}),e.jsxs("span",{className:"tabular-nums text-slate-900 font-medium",children:[s.toLocaleString(),n!=null&&e.jsxs("span",{className:"text-slate-400 font-normal",children:[" of ",n.toLocaleString()]})]})]}),a!=null&&e.jsx(Et,{frac:Math.min(1,a),tone:a>=1?"rose":a>=.8?"amber":"slate",height:4,className:"mt-1"})]})}function Wl({fraction:t}){const n=2*Math.PI*5.5;return e.jsxs("svg",{viewBox:"0 0 14 14",className:"w-3.5 h-3.5 -rotate-90 shrink-0","aria-hidden":!0,children:[e.jsx("circle",{cx:"7",cy:"7",r:5.5,fill:"none",stroke:"currentColor",strokeWidth:"2",opacity:"0.2"}),e.jsx("circle",{cx:"7",cy:"7",r:5.5,fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeDasharray:n,strokeDashoffset:n*(1-Math.max(0,Math.min(1,t))),className:"transition-[stroke-dashoffset] duration-300"})]})}function Xe(t){return t>=1e6?`${(t/1e6).toFixed(1).replace(/\.0$/,"")}M`:t>=1e4?`${(t/1e3).toFixed(1).replace(/\.0$/,"")}k`:t.toLocaleString()}function Hl(t){if(!t)return null;const s=Math.ceil((new Date(t).getTime()-Date.now())/864e5);return s<=0?"Resets soon":s===1?"Resets tomorrow":`Resets in ${s} days`}const Gl={app:"Home",emails:"Accounts",unibox:"Inbox",contacts:"Contacts",segments:"Segments",categories:"Categories",campaigns:"Campaigns",analytics:"Analytics",crm:"CRM",pipelines:"Pipelines",deals:"Deals",tasks:"Tasks",templates:"Templates","api-keys":"API Keys",settings:"Settings",billing:"Billing",team:"Team",admin:"Admin",workers:"Workers",credentials:"Credentials",audit:"Audit",leads:"Leads",preferences:"Preferences",schedule:"Schedule",steps:"Steps"};function An(t){return Gl[t]??t.charAt(0).toUpperCase()+t.slice(1)}function Vl({onMenu:t}){const{pathname:s}=Ve(),n=z(l=>l.setCommandPaletteOpen),a=s.split("/").filter(Boolean).filter(l=>l!=="app"),r=a.map((l,d)=>({seg:l,to:`/app/${a.slice(0,d+1).join("/")}`})).filter(({seg:l})=>!/^[0-9a-f]{8}-[0-9a-f]{4}/i.test(l)),i=`/app/${a.join("/")}`;return e.jsxs("div",{className:"h-14 flex items-center shrink-0",children:[e.jsx("button",{type:"button",onClick:t,"aria-label":"Open menu",className:"md:hidden ml-1.5 w-9 h-9 rounded-md flex items-center justify-center text-slate-600 hover:text-slate-900 hover:bg-slate-200/60 transition-colors shrink-0",children:e.jsx(Co,{className:"w-5 h-5"})}),e.jsxs(Ce,{to:"/app/emails",className:"h-full flex items-center gap-2.5 shrink-0 group pl-2 pr-3 md:w-64 md:px-5",children:[e.jsx(Us,{className:"w-7 text-slate-900 group-hover:text-slate-700 transition-colors duration-150"}),e.jsx("span",{style:{fontFamily:"var(--font-display)"},className:"hidden md:inline font-medium text-[15.5px] tracking-tight text-[#14110F]",children:"Control"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 flex-1 pr-2 md:pr-4",children:[e.jsx(Yl,{children:e.jsx(Nl,{})}),r.map(({seg:l,to:d})=>e.jsxs("div",{className:"hidden md:flex items-center gap-2 min-w-0",children:[e.jsx(ja,{className:"w-3.5 h-3.5 text-slate-300 shrink-0"}),d===i?e.jsx("span",{className:"text-[13px] font-medium text-slate-900 truncate",children:An(l)}):e.jsx(Ce,{to:d,className:"text-[13px] text-slate-500 hover:text-slate-900 truncate transition-colors",children:An(l)})]},d))]}),e.jsxs("div",{className:"flex items-center gap-2 px-2 sm:px-4 shrink-0",children:[e.jsxs("div",{className:"hidden sm:flex items-center gap-2",children:[e.jsx(kl,{}),e.jsx(ql,{}),e.jsx(Kl,{}),e.jsx("div",{className:"h-4 w-px bg-slate-200/80"})]}),e.jsx(fl,{}),e.jsx(hl,{}),e.jsx(ul,{}),e.jsx(vl,{}),e.jsx(Ql,{}),e.jsxs("button",{onClick:()=>n(!0),className:"flex items-center gap-2 px-2 h-7 rounded-md text-slate-500 hover:text-slate-900 hover:bg-slate-200/60 transition-colors text-[12.5px]",children:[e.jsx(cs,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Search"}),e.jsx("kbd",{className:"hidden md:inline-flex h-4 items-center px-1 rounded border border-slate-300/70 bg-white/60 font-mono text-[10px] text-slate-500 ml-0.5",children:"⌘K"})]})]})]})}function Yl({children:t}){return e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:t})}function Ql(){const t=z(o=>o.aiAssistantOpen),s=z(o=>o.agentMinimized),n=z(o=>o.setAIAssistantOpen),a=z(o=>o.setAgentMinimized),r=z(o=>o.agentTabs);if(!as("USE_AI"))return null;const l=r.some(o=>o.running),d=r.some(o=>o.pending),h=r.some(o=>o.unseen);return e.jsx(Ur,{label:"AI assistant",combo:"mod+I",side:"bottom",children:e.jsxs("button",{onClick:()=>{t&&s?a(!1):t?n(!1):(a(!1),n(!0))},"aria-label":"AI assistant",className:"relative flex items-center justify-center size-7 rounded-md text-slate-500 hover:text-sky-700 hover:bg-sky-50 transition-colors",children:[e.jsx(kt,{className:"w-4 h-4"}),(l||d||h)&&e.jsx("span",{className:"absolute top-0.5 right-0.5 size-1.5 rounded-full ring-2 ring-white "+(l?"bg-sky-500 animate-pulse":d?"bg-amber-500":"bg-sky-500")})]})})}function Xl({open:t,onClose:s,feature:n,permissionLabel:a="the required"}){return _t.createPortal(e.jsx(ge,{children:t&&e.jsx(ne.div,{initial:{opacity:0}
2,animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[60] bg-slate-900/30 flex items-center justify-center p-4",onMouseDown:r=>{r.target===r.currentTarget&&s()},children:e.jsxs(ne.div,{initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:8,scale:.98},className:"w-full max-w-sm rounded-lg bg-white border border-slate-200 shadow-xl p-5 text-center",children:[e.jsx("div",{className:"flex justify-end -mt-1 -mr-1",children:e.jsx("button",{type:"button",onClick:s,"aria-label":"Close",className:"size-7 rounded-md text-slate-400 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center justify-center",children:e.jsx(ve,{className:"w-4 h-4"})})}),e.jsx("div",{className:"mx-auto mb-3 size-11 rounded-xl bg-amber-50 border border-amber-200 text-amber-600 flex items-center justify-center",children:e.jsx(yt,{className:"w-5 h-5"})}),e.jsxs("h3",{className:"text-[14px] font-semibold text-slate-900",children:["You don't have access to ",n]}),e.jsxs("p",{className:"text-[12.5px] text-slate-500 leading-relaxed mt-1.5",children:["Your role in this workspace doesn't include the"," ",e.jsx("span",{className:"font-medium text-slate-700",children:a})," permission. Ask a workspace admin or the owner to grant it from Settings → Roles & access."]}),e.jsx("button",{type:"button",onClick:s,className:"mt-4 inline-flex items-center h-8 px-4 rounded-md bg-slate-900 hover:bg-slate-800 text-white text-[12.5px] font-medium transition-colors",children:"Got it"})]})})}),document.body)}function Jl({surface:t}){const{data:s}=Li(),n=k.useMemo(()=>{const r=s?.surfaces?.find(l=>l.surface===t);if(!r)return null;const i=r.critical+r.high;return i>0?{urgent:i,critical:r.critical}:null},[s,t]);if(!n)return null;const a=n.critical>0?`${n.urgent} ${n.urgent===1?"issue":"issues"} needing attention, ${n.critical} critical`:`${n.urgent} ${n.urgent===1?"issue":"issues"} needing attention`;return e.jsx(ne.span,{initial:{scale:.7,opacity:0},animate:{scale:1,opacity:1},transition:{type:"spring",stiffness:500,damping:26},title:a,"aria-label":a,className:`inline-flex h-4 min-w-[16px] items-center justify-center rounded-full px-1 text-[10px] font-semibold tabular-nums ring-1 ${n.critical>0?"bg-rose-500/15 text-rose-600 ring-rose-500/25":"bg-orange-500/15 text-orange-600 ring-orange-500/25"}`,children:n.urgent>99?"99+":n.urgent})}function Zl(){const t=Le(),s=z(l=>l.user),n=_r();if(!s)return null;const a=async()=>{await n.mutateAsync(),t("/auth/login",{replace:!0})},r=s.email.slice(0,2).toUpperCase(),i=s.first_name&&s.last_name?`${s.first_name} ${s.last_name}`:s.email;return e.jsxs(Ht,{side:"top",align:"start",children:[e.jsx(Gt,{asChild:!0,children:e.jsxs("button",{className:"flex items-center gap-2.5 mx-3 my-2 px-1.5 py-1 rounded-md hover:bg-slate-200/40 transition-colors w-[calc(100%-1.5rem)] cursor-pointer",children:[e.jsx("div",{className:"w-7 h-7 rounded-full bg-slate-900 flex items-center justify-center shrink-0 overflow-hidden",children:s.avatar_url?e.jsx("img",{src:s.avatar_url,alt:"",className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-[11px] font-medium text-white leading-none",children:r})}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("div",{className:"text-[13px] text-slate-900 truncate",children:i}),e.jsx("div",{className:"text-[10.5px] text-slate-500 truncate",children:s.email})]})]})}),e.jsxs(Vt,{minWidth:232,children:[e.jsxs("div",{className:"px-3 py-2",children:[e.jsx("div",{className:"text-[12.5px] font-medium text-slate-900 truncate",children:i}),e.jsx("div",{className:"text-[11px] text-slate-400 truncate font-mono",children:s.email})]}),e.jsx(Yt,{}),e.jsx(He,{onSelect:()=>t("/app/settings"),icon:e.jsx(ds,{className:"w-3 h-3"}),children:"Settings"}),e.jsx(Yt,{}),e.jsx(He,{onSelect:a,icon:e.jsx(Pi,{className:"w-3 h-3"}),disabled:n.isPending,danger:!0,children:n.isPending?"Signing out…":"Log out"})]})]})}const ec={query:"",filters:[],campaign_ids:[],sort_by:"created_at",reverse:!1},tc={subscription:"starter",advanced:"business"},Tn=[{title:"Inbox",url:"/app/unibox",icon:ts,badgeStoreKey:"unseenCount",permission:"ACCESS_UNIBOX",permissionLabel:"Use unified inbox"}],sc=[{label:"Email",items:[{title:"Accounts",url:"/app/emails",icon:ss,indicator:"accounts",advisorSurface:"emails",permission:"MANAGE_EMAILS",permissionLabel:"Manage mailboxes"},{title:"Campaigns",url:"/app/campaigns",icon:ka,indicator:"campaigns",advisorSurface:"campaigns",permission:"VIEW_CAMPAIGNS",permissionLabel:"View campaigns"},{title:"Contacts",url:"/app/contacts",icon:Ws,indicator:"contacts",advisorSurface:"contacts",permission:"VIEW_CONTACTS",permissionLabel:"View contacts"},{title:"Forms",url:"/app/forms",icon:Di,permission:"VIEW_CONTACTS",permissionLabel:"View contacts"},{title:"Analytics",url:"/app/analytics",icon:sa,indicator:"analytics",permission:"VIEW_ANALYTICS",permissionLabel:"View analytics"},{title:"Deliverability",url:"/app/deliverability",icon:ns,advisorSurface:"deliverability",permission:"VIEW_ANALYTICS",permissionLabel:"View analytics"}]},{label:"CRM",items:[{title:"Pipelines",url:"/app/crm/pipelines",icon:lt,indicator:"pipelines",permission:"VIEW_CONTACTS",permissionLabel:"View contacts"},{title:"Deals",url:"/app/crm/deals",icon:_a,indicator:"deals",permission:"VIEW_CONTACTS",permissionLabel:"View contacts"},{title:"Tasks",url:"/app/crm/tasks",icon:Sa,indicator:"tasks",permission:"VIEW_CONTACTS",permissionLabel:"View contacts"},{title:"Meetings",url:"/app/crm/meetings",icon:Oi,indicator:"meetings",permission:"VIEW_CONTACTS",permissionLabel:"View contacts"}]},{label:"Resources",items:[{title:"Templates",url:"/app/templates",icon:Hs,indicator:"templates"},{title:"Integrations",url:"/app/integrations",icon:$i,indicator:"integrations",permission:"USE_INTEGRATIONS",permissionLabel:"Use integrations"},{title:"Automations",url:"/app/automations",icon:zi,permission:"USE_INTEGRATIONS",permissionLabel:"Use integrations"},{title:"API Keys",url:"/app/api-keys",icon:Ms,indicator:"apikeys",permission:"MANAGE_API_KEYS",permissionLabel:"Manage API keys"},{title:"Audit log",url:"/app/audit",icon:Fi,rolesAllowed:"manage"}]}];function Ds({item:t}){const{pathname:s}=Ve(),n=z(w=>w.unseenCount),a=Ct(),r=as(t.permission??"VIEW_CAMPAIGNS"),[i,l]=k.useState(!1),d=da(),h=s===t.url||s.startsWith(t.url+"/"),o=t.badgeStoreKey==="unseenCount"?n:void 0;if(t.rolesAllowed==="manage"&&!a.canManage)return null;if(!!t.permission&&!r)return e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>l(!0),title:`${t.title} · no access`,className:"group w-[calc(100%-1rem)] mx-2 flex items-center gap-2.5 px-2.5 h-7 rounded-md text-[12.5px] text-slate-400 hover:text-slate-600 hover:bg-slate-200/40 transition-colors duration-100",children:[e.jsx(yt,{className:"w-[13px] h-[13px] shrink-0 text-slate-300 group-hover:text-slate-500",strokeWidth:1.8}),e.jsx("span",{className:"truncate flex-1 min-w-0 text-left",children:t.title})]}),e.jsx(Xl,{open:i,onClose:()=>l(!1),feature:t.title,permissionLabel:t.permissionLabel??"the required"})]});const c=t.requires==="advanced"&&!a.hasAdvanced||t.requires==="subscription"&&a.locked,f=c&&t.requires?tc[t.requires]:null,m=f?{label:rt(f).label,classes:la[rt(f).accent].pill}:null;return c&&f&&m?e.jsxs("button",{type:"button",onClick:()=>d.open({feature:t.title,minPlan:f}),title:`${t.title} · ${m.label} plan`,className:"group w-[calc(100%-1rem)] mx-2 flex items-center gap-2.5 px-2.5 h-7 rounded-md text-[12.5px] text-slate-400 hover:text-slate-700 hover:bg-slate-200/40 transition-colors duration-100",children:[e.jsx(yt,{className:"w-[13px] h-[13px] shrink-0 text-slate-300 group-hover:text-slate-500",strokeWidth:1.8}),e.jsx("span",{className:"truncate flex-1 min-w-0 text-left",children:t.title}),e.jsx("span",{className:Y("h-4 px-1.5 rounded text-[9.5px] font-semibold uppercase tracking-[0.06em] border inline-flex items-center",m.classes),children:m.label})]}):e.jsxs(Ce,{to:t.url,title:m?`${t.title} · ${m.label} plan`:void 0,className:Y("group mx-2 flex items-center gap-2.5 px-2.5 h-7 rounded-md text-[12.5px] transition-colors duration-100",h?"bg-slate-200/70 text-slate-900 font-medium":c?"text-slate-400 hover:text-slate-700 hover:bg-slate-200/40":"text-slate-600 hover:text-slate-900 hover:bg-slate-200/40"),children:[e.jsx(t.icon,{className:Y("w-[14px] h-[14px] shrink-0 transition-colors",h?"text-slate-700":c?"text-slate-300 group-hover:text-slate-500":"text-slate-400 group-hover:text-slate-600"),strokeWidth:h?2:1.6}),e.jsx("span",{className:"truncate flex-1 min-w-0",children:t.title}),t.advisorSurface&&!c&&e.jsx(Jl,{surface:t.advisorSurface}),t.indicator==="campaigns"&&!c&&e.jsx(nc,{}),t.indicator==="accounts"&&!c&&e.jsx(ac,{}),t.indicator==="tasks"&&!c&&e.jsx(rc,{}),t.indicator==="meetings"&&!c&&e.jsx(ic,{}),t.indicator==="contacts"&&!c&&e.jsx(oc,{}),t.indicator==="deals"&&!c&&e.jsx(lc,{}),t.indicator==="pipelines"&&!c&&e.jsx(cc,{}),t.indicator==="templates"&&!c&&e.jsx(dc,{}),t.indicator==="analytics"&&!c&&e.jsx(uc,{}),t.indicator==="apikeys"&&!c&&e.jsx(mc,{}),t.indicator==="integrations"&&!c&&e.jsx(pc,{}),m?e.jsx("span",{className:Y("h-4 px-1.5 rounded text-[9.5px] font-semibold uppercase tracking-[0.06em] border inline-flex items-center",m.classes),children:m.label}):o!=null&&o>0&&e.jsx("span",{className:"text-[10px] font-medium bg-red-500 text-white rounded-full min-w-[16px] h-4 flex items-center justify-center px-1 tabular-nums",children:o>99?"99+":o})]})}function Zt(t){const s=Math.round(t);return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e4?`${Math.round(s/1e3)}
2k`:s>=1e3?`${(s/1e3).toFixed(1)}k`:String(s)}const za="text-[10.5px] font-medium tabular-nums leading-none text-slate-300 transition-colors group-hover:text-slate-500";function ct({total:t,glyph:s,format:n=Zt,title:a}){return e.jsxs("span",{className:"ml-auto inline-flex items-center gap-1.5 shrink-0",title:a,children:[s,e.jsx(Ke,{value:t,format:n,className:za})]})}function At({total:t,active:s,activeGlyph:n,activeClass:a,title:r}){return e.jsxs("span",{className:"ml-auto inline-flex items-center gap-2.5 shrink-0",title:r,children:[e.jsx(Ke,{value:t,format:Zt,className:za}),e.jsx("span",{className:"h-3 w-px shrink-0 bg-slate-200","aria-hidden":!0}),e.jsxs("span",{className:`inline-flex items-center gap-1 ${s>0?a:"text-slate-300"}`,children:[s>0&&n,e.jsx(Ke,{value:s,format:Zt,className:"text-[10.5px] font-semibold tabular-nums leading-none"})]})]})}function nc(){const{campaigns:t}=fi({query:"",folder:""}),s=k.useMemo(()=>t.filter(n=>n.status==="active").length,[t]);return e.jsx(At,{total:t.length,active:s,activeClass:"text-sky-600",activeGlyph:e.jsx("span",{className:"campaign-grid","aria-hidden":!0}),title:`${t.length} campaign${t.length===1?"":"s"}${s>0?`, ${s} sending now`:""}`})}function ac(){const{emails:t}=gi({query:"",tag:""}),s=k.useMemo(()=>t.filter(n=>!!n.warmup&&!n.warmup_paused_at).length,[t]);return e.jsx(At,{total:t.length,active:s,activeClass:"text-orange-500",activeGlyph:e.jsx(lr,{className:"w-3.5 h-3.5 flame-flicker",strokeWidth:2.2}),title:`${t.length} mailbox${t.length===1?"":"es"}${s>0?`, ${s} warming up`:""}`})}function rc(){const{data:t}=yi(ji),s=t?.overdue_count??0,n=(t?.pending_count??0)+(t?.in_progress_count??0);return e.jsx(At,{total:n,active:s,activeClass:"text-red-600",activeGlyph:e.jsxs("span",{className:"relative inline-flex shrink-0",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-red-500"}),e.jsx("span",{className:"absolute inset-0 rounded-full bg-red-500/40 animate-ping"})]}),title:`${n} open task${n===1?"":"s"}${s>0?`, ${s} overdue`:""}`})}function ic(){const{data:t}=vi(),s=t?.upcoming??0,n=t?.today??0;return e.jsx(At,{total:s,active:n,activeClass:"text-sky-600",activeGlyph:e.jsxs("span",{className:"relative inline-flex shrink-0",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-sky-500"}),e.jsx("span",{className:"absolute inset-0 rounded-full bg-sky-500/40 animate-ping"})]}),title:`${s} upcoming meeting${s===1?"":"s"}${n>0?`, ${n} today`:""}`})}function oc(){const{data:t}=_i({options:ec,limit:10}),s=t?.pages?.[0]?.pagination?.total??0;return e.jsx(ct,{total:s,title:`${s.toLocaleString()} contacts`})}function lc(){const{data:t}=Ni(ki),s=t?.open_count??0;return e.jsx(ct,{total:s,title:`${s} open deal${s===1?"":"s"}`})}function cc(){const{data:t}=Si(),s=t?.length??0;return e.jsx(ct,{total:s,title:`${s} pipeline${s===1?"":"s"}`})}function dc(){const{data:t}=wa(),s=t?.length??0;return e.jsx(ct,{total:s,title:`${s} template${s===1?"":"s"}`})}function uc(){const{data:t}=Or(),s=t?.campaigns?.emails_sent??0;return e.jsx(ct,{total:s,format:Zt,title:`${s.toLocaleString()} emails sent this period`})}function mc(){const{data:t}=Ri(),s=(t?.data??[]).filter(n=>n.status==="active").length;return e.jsx(ct,{total:s,format:n=>String(Math.round(n)),title:`${s} active API key${s===1?"":"s"}`})}function pc(){const{data:t}=Ii(),s=t?.connections??[],n=s.filter(a=>a.status==="degraded"||a.status==="reauth_required"||a.health==="down").length;return e.jsx(At,{total:s.length,active:n,activeClass:"text-amber-600",activeGlyph:e.jsxs("span",{className:"relative inline-flex shrink-0",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-500"}),e.jsx("span",{className:"absolute inset-0 rounded-full bg-amber-500/40 animate-ping"})]}),title:`${s.length} connected${n>0?`, ${n} need attention`:""}`})}function xc({section:t,first:s=!1}){return e.jsxs("div",{className:s?"":"mt-4 pt-4 border-t border-slate-200/50",children:[e.jsx("div",{className:"px-4 mb-1.5",children:e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium",children:t.label})}),e.jsx("div",{className:"space-y-px",children:t.items.map(n=>e.jsx(Ds,{item:n},n.url))})]})}function hc(){const t=z(f=>f.emails),s=z(f=>f.unseenCount),n=Ci("30d"),[a,r]=k.useState(null),{active:i,mailboxes:l,capacity:d}=k.useMemo(()=>{const f=t.length,m=t.filter(E=>{const _=Ei(E);return _==="healthy"||_==="warming"}).length,w=t.reduce((E,_)=>E+(_.campaign_limit??50),0);return{active:m,mailboxes:f,capacity:w}},[t]),{sentToday:h,trend:o}=k.useMemo(()=>{const f=new Map((n.data?.daily_trend??[]).map(E=>[E.date?.slice(0,10),E.sent])),m=[],w=new Date;for(let E=13;E>=0;E--){const _=new Date(w);_.setUTCDate(w.getUTCDate()-E);const M=_.toISOString().slice(0,10);m.push({date:M,sent:f.get(M)??0})}return{sentToday:m[m.length-1].sent,trend:m}},[n.data]),x=a!=null?o[a]:void 0,c=d>0?Math.min(100,h/d*100):0;return e.jsxs(Ce,{to:"/app/analytics",className:"group block mx-2 mt-2 mb-3 rounded-md bg-white/80 hover:bg-white border border-slate-200/70 hover:border-slate-300 pt-2 overflow-hidden transition-colors",children:[e.jsx("div",{className:"px-2.5 flex items-baseline gap-1.5 whitespace-nowrap",children:x?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[19px] font-semibold text-slate-900 leading-none",children:x.sent.toLocaleStr
2ing()}),e.jsxs("span",{className:"text-[10.5px] text-slate-500",children:["sent ",fc(x.date)]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ke,{value:h,className:"text-[19px] font-semibold text-slate-900 leading-none"}),e.jsx("span",{className:"text-[10.5px] text-slate-500",children:d>0?`of ${d.toLocaleString()} sent today`:"sent today"})]})}),e.jsx("div",{className:"mt-1.5 px-2.5",title:d>0?`${h} of ${d} daily capacity used`:"Connect a mailbox to start sending",children:e.jsx("div",{className:"h-1 rounded-full bg-sky-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-sky-500 transition-[width] duration-700 ease-out",style:{width:`${c}%`}})})}),e.jsx(gc,{points:o,hovered:a,onHover:r}),e.jsxs("div",{className:"border-t border-slate-100 px-2.5 py-1.5 flex items-center gap-3 text-[10.5px]",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-slate-500",title:`${l} ${l===1?"mailbox":"mailboxes"} connected`,children:[e.jsx(ss,{className:"w-3 h-3 text-slate-400"}),e.jsx("span",{className:"font-mono tabular-nums",children:l})]}),i>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-emerald-600",title:`${i} warming or sending`,children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500"}),e.jsx("span",{className:"font-mono tabular-nums",children:i})]}),e.jsxs("span",{className:Y("ml-auto inline-flex items-center gap-1",s>0?"text-sky-600":"text-slate-400"),title:`${s} unread in inbox`,children:[e.jsx(ts,{className:"w-3 h-3"}),e.jsx("span",{className:"font-mono tabular-nums",children:s>99?"99+":s})]})]})]})}function fc(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleDateString(void 0,{month:"short",day:"numeric",timeZone:"UTC"})}const gs=238,Pt=34,Dt=6,bs=6,Mn=3;function gc({points:t,hovered:s,onHover:n}){const{linePath:a,areaPath:r,dots:i,hasVolume:l}=k.useMemo(()=>{const c=t.length,f=Pt-Mn;if(c<2)return{linePath:"",areaPath:"",dots:[],hasVolume:!1};const m=Math.max(...t.map(j=>j.sent),1),w=gs-Dt*2,E=f-bs,_=t.map((j,I)=>({x:Dt+I/(c-1)*w,y:f-j.sent/m*E})),M=j=>Math.min(f,Math.max(bs,j));let S=`M ${_[0].x} ${_[0].y}`;for(let j=0;j<c-1;j++){const I=_[j-1]??_[j],P=_[j],R=_[j+1],C=_[j+2]??R,u=P.x+(R.x-I.x)/6,g=M(P.y+(R.y-I.y)/6),y=R.x-(C.x-P.x)/6,T=M(R.y-(C.y-P.y)/6);S+=` C ${u} ${g}, ${y} ${T}, ${R.x} ${R.y}`}return{linePath:S,areaPath:`${S} L ${_[c-1].x} ${f} L ${_[0].x} ${f} Z`,dots:_,hasVolume:t.some(j=>j.sent>0)}},[t]),d=t.length,h=d>1?(gs-Dt*2)/(d-1):0,o=s!=null?i[s]:void 0,x=i[i.length-1];return e.jsxs("svg",{viewBox:`0 0 ${gs} ${Pt}`,preserveAspectRatio:"none","aria-hidden":!0,className:Y("mt-1 block w-full h-[34px]",l?"text-sky-500":"text-slate-300"),onMouseLeave:()=>n(null),children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"livepanel-spark-fill",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:"0.18"}),e.jsx("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:"0.02"})]})}),a&&l&&e.jsx("path",{d:r,fill:"url(#livepanel-spark-fill)"}),a&&e.jsx("path",{d:a,fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:"non-scaling-stroke"}),o&&e.jsxs(e.Fragment,{children:[e.jsx("line",{x1:o.x,y1:bs-4,x2:o.x,y2:Pt-Mn,className:"stroke-slate-200",strokeWidth:"1",vectorEffect:"non-scaling-stroke"}),e.jsx("circle",{cx:o.x,cy:o.y,r:"3",fill:"currentColor",className:"stroke-white",strokeWidth:"1.5"})]}),x&&s==null&&e.jsx("circle",{cx:x.x,cy:x.y,r:"2.5",fill:"currentColor",className:"stroke-white",strokeWidth:"1.5"}),d>=2&&t.map((c,f)=>e.jsx("rect",{x:Dt+f*h-h/2,y:0,width:h,height:Pt,fill:"transparent",onMouseEnter:()=>n(f)},f))]})}function bc({open:t=!1,onClose:s}){return e.jsxs(e.Fragment,{children:[e.jsx("div",{"aria-hidden":!0,onClick:s,className:Y("fixed inset-0 z-40 bg-slate-900/40 transition-opacity duration-300 md:hidden",t?"opacity-100":"pointer-events-none opacity-0")}),e.jsxs("aside",{className:Y("fixed inset-y-0 left-0 z-50 w-64 flex flex-col text-slate-900 bg-white shadow-2xl transition-transform duration-300 ease-out",t?"translate-x-0":"-translate-x-full","md:static md:z-auto md:translate-x-0 md:bg-transparent md:shadow-none md:transition-none shrink-0"),children:[e.jsxs("div",{className:"md:hidden flex items-center justify-between px-3 h-14 border-b border-slate-200/70",children:[e.jsxs(Ce,{to:"/app/emails",onClick:s,className:"flex items-center gap-2.5",children:[e.jsx(Us,{className:"w-6 text-slate-900"}),e.jsx("span",{style:{fontFamily:"var(--font-display)"},className:"font-medium text-[15px] tracking-tight text-[#14110F]",children:"Control"})]}),e.jsx("button",{type:"button",onClick:s,"aria-label":"Close menu",className:"w-8 h-8 -mr-1 rounded-md flex items-center justify-center text-slate-500 hover:text-slate-900 hover:bg-slate-100 transition-colors",children:e.jsx(ve,{className:"w-4 h-4"})})]}),e.jsx(hc,{}),e.jsxs("nav",{className:"flex-1 overflow-y-auto pb-3",children:[e.jsx("div",{className:"space-y-px",children:T
2n.map(n=>e.jsx(Ds,{item:n},n.url+n.title))}),sc.map((n,a)=>e.jsx(xc,{section:n,first:a===0&&Tn.length===0},n.label))]}),e.jsx("div",{className:"border-t border-slate-200/60 py-1 shrink-0",children:e.jsx(Ds,{item:{title:"Settings",url:"/app/settings",icon:ds}})}),e.jsx("div",{className:"border-t border-slate-200/60 shrink-0",children:e.jsx(Zl,{})})]})]})}function yc(){const[,t]=b.useState(0);b.useEffect(()=>{const s=window.setInterval(()=>t(n=>n+1),6e4);return()=>window.clearInterval(s)},[])}function Rn(t){const s=t.getTime()-Date.now();if(s<=0)return"any moment now";const n=Math.floor(s/6e4),a=Math.floor(n/1440),r=Math.floor(n%1440/60),i=n%60;return a>0?`${a}d ${r}h`:r>0?`${r}h ${i}m`:`${i}m`}function jc(){yc();const t=Ct(),s=Ui(),n=qi(),a=Ki(),r=Bi(),i=s.data?.pending_deletion,l=n.data?.pending_deletion;return!i&&!l?null:e.jsxs("div",{className:"relative z-20",children:[i&&s.data&&e.jsx(In,{title:e.jsxs(e.Fragment,{children:["This workspace will be permanently deleted in"," ",e.jsx("strong",{className:"tabular-nums",children:Rn(new Date(i.execute_after))}),"."]}),detail:e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:s.data.resource_name})," is scheduled for deletion on"," ",new Date(i.execute_after).toLocaleString(),".",t.isOwner?" Cancel below to keep it.":" Only the workspace owner can cancel — reach out to them now."]}),showCancel:t.isOwner,onCancel:async()=>{try{await a.mutateAsync(void 0),se.success("Workspace deletion cancelled")}catch(d){se.error(je(d))}},cancelLoading:a.isPending}),l&&n.data&&e.jsx(In,{title:e.jsxs(e.Fragment,{children:["Your account will be permanently deleted in"," ",e.jsx("strong",{className:"tabular-nums",children:Rn(new Date(l.execute_after))}),"."]}),detail:e.jsxs(e.Fragment,{children:["All workspaces you own and every campaign / contact / mailbox in them will be removed on"," ",new Date(l.execute_after).toLocaleString(),"."]}),showCancel:!0,onCancel:async()=>{try{await r.mutateAsync(void 0),se.success("Account deletion cancelled")}catch(d){se.error(je(d))}},cancelLoading:r.isPending})]})}function In({title:t,detail:s,showCancel:n,onCancel:a,cancelLoading:r}){return e.jsxs("div",{role:"alert",className:"bg-red-600 text-white px-4 py-2 flex flex-wrap items-center gap-3 md:flex-nowrap border-b border-red-800/50 shadow-[0_1px_0_rgba(0,0,0,0.05)]",children:[e.jsx("div",{className:"size-5 rounded bg-white/15 flex items-center justify-center shrink-0",children:e.jsx(Ca,{className:"w-3 h-3"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[12.5px] font-medium leading-tight",children:t}),e.jsx("div",{className:"text-[11.5px] text-white/85 leading-tight mt-0.5",children:s})]}),e.jsxs("div",{className:"flex items-center gap-1.5 w-full justify-end md:w-auto md:shrink-0",children:[n&&e.jsxs("button",{type:"button",onClick:()=>a(),disabled:r,className:"h-7 px-2.5 rounded-md bg-white text-red-700 hover:bg-red-50 text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors disabled:opacity-70",children:[r?e.jsx(xe,{className:"w-3 h-3 animate-spin"}):e.jsx(Wi,{className:"w-3 h-3"}),"Cancel deletion"]}),e.jsx(Ce,{to:"/app/settings/danger",className:"h-7 px-2.5 rounded-md bg-red-700 hover:bg-red-800 text-white text-[12px] font-medium inline-flex items-center transition-colors",children:"Settings"})]})]})}async function wc(){return await be({method:"GET",url:"/organizations/current/risk",authorization:!0})}function vc(){return $e({queryKey:["organizations","risk"],queryFn:wc,staleTime:6e4})}function Nc(){const{data:t}=vc();if(!t||!t.restricted&&!t.suspended)return null;const s=t.suspended,n=s?Hi:ze;return e.jsxs("div",{role:"status",className:`flex items-start gap-2 px-4 py-2.5 border-b ${s?"bg-rose-50 border-rose-200 text-rose-900":"bg-amber-50 border-amber-200 text-amber-900"}`,children:[e.jsx(n,{className:`w-4 h-4 mt-px shrink-0 ${s?"text-rose-600":"text-amber-600"}`}),e.jsxs("div",{className:"min-w-0 text-[12.5px] leading-relaxed",children:[e.jsx("span",{className:"font-medium",children:s?"Sending is paused for this workspace while it is reviewed.":"Sending from this workspace is limited while it is reviewed."})," ",!s&&e.jsxs(e.Fragment,{children:["Daily volume per mailbox is reduced and warmup runs in the shared free pool."," "]}),t.reason?e.jsxs(e.Fragment,{children:["Reason: ",t.reason,". "]}):null,"Contact support if you think this is wrong."]})]})}class kc extends b.Component{state={error:null,info:null};static getDerivedStateFromError(s){return{error:s}}componentDidCatch(s,n){this.setState({info:n}),typeof window<"u"&&window.Sentry&&window.Sentry?.captureException(s),console.error("[ErrorBoundary]",s,n?.componentStack)}reset=()=>{this.setState({error:null,info:null}),this.props.onReset?.()};render(){return this.state.error?e.jsx(_c,{error:this.state.error,info:this.state.info,reset:this.reset}):this.props.children}}function _c({error:t,info:s,reset:n}){const a=Le();return e.jsxs("div",{className:"flex flex-col min-h-full bg-white",children:[e.jsxs("div",{className:"min-h-12 md:h-12 px-5 py-1.5 md:py-0 border-b border-slate-200 flex flex-wrap md:flex-nowrap items-center gap-3 gap-y-1.5 
2shrink-0 bg-white",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-red-500 font-medium",children:"Page error"}),e.jsx("div",{className:"h-4 w-px bg-slate-200"}),e.jsx("span",{className:"text-[12.5px] text-slate-600 truncate",children:t.message||"Something broke while rendering this page"}),e.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[e.jsx("button",{onClick:()=>a(-1),className:"h-7 px-2.5 rounded-md border border-slate-200 hover:border-slate-300 text-slate-700 hover:text-slate-900 text-[12px] font-medium transition-colors",children:"Back"}),e.jsxs("button",{onClick:n,className:"h-7 px-2.5 rounded-md bg-sky-600 hover:bg-sky-700 text-white text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors",children:[e.jsx(Gi,{className:"w-3 h-3"}),"Retry"]})]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto px-5 py-6",children:e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ze,{className:"w-3.5 h-3.5 text-red-500 shrink-0"}),e.jsx("span",{className:"text-[12.5px] font-semibold text-slate-900",children:t.name||"Error"})]}),e.jsx("p",{className:"text-[12px] text-slate-700 mb-4 leading-relaxed",children:t.message||"No message provided."}),(t.stack||s?.componentStack)&&e.jsxs("details",{className:"border border-slate-200 rounded-md bg-slate-50 overflow-hidden",children:[e.jsx("summary",{className:"px-3 py-2 text-[11px] font-medium text-slate-700 cursor-pointer hover:bg-slate-100 transition-colors",children:"Stack"}),e.jsxs("pre",{className:"px-3 py-3 text-[10.5px] font-mono text-slate-700 leading-relaxed overflow-x-auto whitespace-pre-wrap border-t border-slate-200",children:[t.stack||"",s?.componentStack?`
3
4Component stack:${s.componentStack}`:""]})]})]})})]})}function Sc({children:t}){const{pathname:s}=Ve();return e.jsx(kc,{children:t},s)}function Cc(){const t=Le(),s=z(c=>c.keySequence),n=z(c=>c.addToSequence),a=z(c=>c.clearSequence),r=z(c=>c.moveSelection),i=z(c=>c.setShortcutsModalOpen),l=z(c=>c.setCommandPaletteOpen),d=z(c=>c.toggleSidebar),h=z(c=>c.toggleAIAssistant),o={"g,e":"/app/emails","g,c":"/app/contacts","g,m":"/app/campaigns","g,u":"/app/unibox","g,a":"/app/analytics","g,p":"/app/crm/pipelines","g,d":"/app/crm/deals","g,t":"/app/crm/tasks","g,l":"/app/templates","g,k":"/app/api-keys","g,s":"/app/settings"},x=k.useCallback(c=>{if((c.ctrlKey||c.metaKey)&&c.key.toLowerCase()==="i"){if(c.preventDefault(),!Fr("USE_AI"))return;const E=z.getState();E.aiAssistantOpen&&E.agentMinimized?E.setAgentMinimized(!1):(E.aiAssistantOpen||E.setAgentMinimized(!1),h());return}const f=c.target;if(f.tagName==="INPUT"||f.tagName==="TEXTAREA"||f.isContentEditable||f.closest('[role="textbox"]'))return;const w=c.key.toLowerCase();if((c.ctrlKey||c.metaKey)&&w==="k"){c.preventDefault(),l(!0);return}if(w==="escape"){a();return}if(w==="?"||c.shiftKey&&w==="/"){c.preventDefault(),i(!0);return}if(w==="b"&&!c.ctrlKey&&!c.metaKey){c.preventDefault(),d();return}if(w==="n"&&!c.ctrlKey&&!c.metaKey&&!c.shiftKey){c.preventDefault(),Ie.getState().openCompose();return}if(w==="/"){c.preventDefault(),document.querySelector("[data-search-input]")?.focus();return}if(w==="j"){c.preventDefault(),r("down");return}if(w==="k"){c.preventDefault(),r("up");return}if(w==="g"&&s.length===1&&s[0]==="g"){c.preventDefault(),r("first"),a();return}if(c.shiftKey&&w==="g"){c.preventDefault(),r("last");return}if(w.match(/^[a-z]$/)){n(w);const E=[...s,w].join(","),_=o[E];_&&(c.preventDefault(),t(_),a())}},[s,n,a,t,r,i,l,d,h,o]);k.useEffect(()=>(window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)),[x])}const Ot={navigation:[{keys:["g","e"],description:"Go to Email Accounts"},{keys:["g","c"],description:"Go to Contacts"},{keys:["g","m"],description:"Go to Campaigns"},{keys:["g","u"],description:"Go to Unibox"},{keys:["g","a"],description:"Go to Analytics"},{keys:["g","p"],description:"Go to Pipelines"},{keys:["g","d"],description:"Go to Deals"},{keys:["g","t"],description:"Go to Tasks"},{keys:["g","l"],description:"Go to Templates"},{keys:["g","k"],description:"Go to API Keys"},{keys:["g","s"],description:"Go to Settings"}],list:[{keys:["j"],description:"Move down in list"},{keys:["k"],description:"Move up in list"},{keys:["g","g"],description:"Go to first item"},{keys:["G"],description:"Go to last item"},{keys:["Enter"],description:"Open selected item"},{keys:["Escape"],description:"Close modal / Deselect"},{keys:["x"],description:"Select/deselect item"}],actions:[{keys:["/"],description:"Focus search"},{keys:["n"],description:"Compose a new email"},{keys:["e"],description:"Edit selected item"},{keys:["b"],description:"Toggle sidebar"},{keys:["?"],description:"Show shortcuts"},{keys:["Ctrl","k"],description:"Command palette"}],assistant:[{keys:["Ctrl","i"],description:"Open / close the assistant"},{keys:["Ctrl","]"],description:"Next conversation tab"},{keys:["Ctrl","["],description:"Previous conversation tab"},{keys:["Alt","n"],description:"New chat"},{keys:["Alt","w"],description:"Close tab"},{keys:["Alt","m"],description:"Minimize to dock"},{keys:["Alt","p"],description:"Pop out / dock the panel"},{keys:["Esc"],description:"Close the panel"}]};function Fa({children:t}){return e.jsx("kbd",{className:"inline-flex h-6 min-w-6 items-center justify-center rounded border border-border bg-muted px-1.5 font-mono text-xs font-medium text-muted-foreground",children:t})}function Ec({keys:t,description:s}){return e.jsxs("div",{className:"flex items-center justify-between py-1.5",children:[e.jsx("span",{className:"text-sm text-foreground",children:s}),e.jsx("div",{className:"flex items-center gap-1",children:t.map((n,a)=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fa,{children:n}),a<t.length-1&&e.jsx("span",{className:"text-muted-foreground",children:"+"})]},a))})]})}function $t({title:t,shortcuts:s}){return e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"text-sm font-medium text-muted-foreground uppercase tracking-wider",children:t}),e.jsx("div",{className:"divide-y divide-border",children:s.map((n,a)=>e.jsx(Ec,{keys:n.keys,description:n.description},a))})]})}function Ac(){const t=z(n=>n.shortcutsModalOpen),s=z(n=>n.setShortcutsModalOpen);return e.jsx(Gs,{open:t,onOpenChange:s,children:e.jsxs(Vs,{className:"sm:max-w-2xl max-h-[80dvh] overflow-y-auto",children:[e.jsx(Ys,{children:e.jsx(Qs,{children:"Keyboard Shortcuts"})}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx($t,{title:"Navigation",shortcuts:Ot.navigation}),e.jsx($t,{title:"Assistant",shortcuts:Ot.assistant})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsx($t,{title:"List Navigation",shortcuts:Ot.list}),e.jsx($t,{title:"Actions",shortcuts:Ot.actions})]})]}),e.jsxs("div",{className:"mt-4 text-center text-sm text-muted-foreground",children:["Press ",e.jsx(Fa,{children:"?"})," anytime to show this dialog"]})]})})}var Ln=1,Tc=.9,Mc=.8,Rc=.17,ys=.1,js=.999,Ic=.9999,Lc=.99,Pc=/[\\\/_+.#"@\[\(\{&]/,Dc=/[\\\/_+.#"@\[\(\{&]/g,Oc=/[\s-]/,Ua=/[\s-]/g;function Os(t,s,n,a,r,i,l){if(i===s.length)return r===t.length?Ln:Lc;var d=`${r},${i}`;if(l[d]!==void 0)return l[d];for(var h=a.charAt(i),o=n.indexOf(h,r),x=0,c,f,m,w;o>=0;
vendor: 4,744 bytes, line 4
4)c=Os(t,s,n,a,o+1,i+1,l),c>x&&(o===r?c*=Ln:Pc.test(t.charAt(o-1))?(c*=Mc,m=t.slice(r,o-1).match(Dc),m&&r>0&&(c*=Math.pow(js,m.length))):Oc.test(t.charAt(o-1))?(c*=Tc,w=t.slice(r,o-1).match(Ua),w&&r>0&&(c*=Math.pow(js,w.length))):(c*=Rc,r>0&&(c*=Math.pow(js,o-r))),t.charAt(o)!==s.charAt(i)&&(c*=Ic)),(c<ys&&n.charAt(o-1)===a.charAt(i+1)||a.charAt(i+1)===a.charAt(i)&&n.charAt(o-1)!==a.charAt(i))&&(f=Os(t,s,n,a,o+1,i+2,l),f*ys>c&&(c=f*ys)),c>x&&(x=c),o=n.indexOf(h,o+1);return l[d]=x,x}function Pn(t){return t.toLowerCase().replace(Ua," ")}function $c(t,s,n){return t=n&&n.length>0?`${t+" "+n.join(" ")}`:t,Os(t,s,Pn(t),Pn(s),0,0,{})}var xt='[cmdk-group=""]',ws='[cmdk-group-items=""]',zc='[cmdk-group-heading=""]',qa='[cmdk-item=""]',Dn=`${qa}:not([aria-disabled="true"])`,$s="cmdk-item-select",Ze="data-value",Fc=(t,s,n)=>$c(t,s,n),Ka=k.createContext(void 0),Tt=()=>k.useContext(Ka),Ba=k.createContext(void 0),Zs=()=>k.useContext(Ba),Wa=k.createContext(void 0),Ha=k.forwardRef((t,s)=>{let n=et(()=>{var N,O;return{search:"",value:(O=(N=t.value)!=null?N:t.defaultValue)!=null?O:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),a=et(()=>new Set),r=et(()=>new Map),i=et(()=>new Map),l=et(()=>new Set),d=Ga(t),{label:h,children:o,value:x,onValueChange:c,filter:f,shouldFilter:m,loop:w,disablePointerSelection:E=!1,vimBindings:_=!0,...M}=t,S=nt(),j=nt(),I=nt(),P=k.useRef(null),R=Xc();Ge(()=>{if(x!==void 0){let N=x.trim();n.current.value=N,C.emit()}},[x]),Ge(()=>{R(6,Q)},[]);let C=k.useMemo(()=>({subscribe:N=>(l.current.add(N),()=>l.current.delete(N)),snapshot:()=>n.current,setState:(N,O,J)=>{var U,D,K,H;if(!Object.is(n.current[N],O)){if(n.current[N]=O,N==="search")v(),y(),R(1,T);else if(N==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let ee=document.getElementById(I);ee?ee.focus():(U=document.getElementById(S))==null||U.focus()}if(R(7,()=>{var ee;n.current.selectedItemId=(ee=ae())==null?void 0:ee.id,C.emit()}),J||R(5,Q),((D=d.current)==null?void 0:D.value)!==void 0){let ee=O??"";(H=(K=d.current).onValueChange)==null||H.call(K,ee);return}}C.emit()}},emit:()=>{l.current.forEach(N=>N())}}),[]),u=k.useMemo(()=>({value:(N,O,J)=>{var U;O!==((U=i.current.get(N))==null?void 0:U.value)&&(i.current.set(N,{value:O,keywords:J}),n.current.filtered.items.set(N,g(O,J)),R(2,()=>{y(),C.emit()}))},item:(N,O)=>(a.current.add(N),O&&(r.current.has(O)?r.current.get(O).add(N):r.current.set(O,new Set([N]))),R(3,()=>{v(),y(),n.current.value||T(),C.emit()}),()=>{i.current.delete(N),a.current.delete(N),n.current.filtered.items.delete(N);let J=ae();R(4,()=>{v(),J?.getAttribute("id")===N&&T(),C.emit()})}),group:N=>(r.current.has(N)||r.current.set(N,new Set),()=>{i.current.delete(N),r.current.delete(N)}),filter:()=>d.current.shouldFilter,label:h||t["aria-label"],getDisablePointerSelection:()=>d.current.disablePointerSelection,listId:S,inputId:I,labelId:j,listInnerRef:P}),[]);function g(N,O){var J,U;let D=(U=(J=d.current)==null?void 0:J.filter)!=null?U:Fc;return N?D(N,n.current.search,O):0}function y(){if(!n.current.search||d.current.shouldFilter===!1)return;let N=n.current.filtered.items,O=[];n.current.filtered.groups.forEach(U=>{let D=r.current.get(U),K=0;D.forEach(H=>{let ee=N.get(H);K=Math.max(ee,K)}),O.push([U,K])});let J=P.current;re().sort((U,D)=>{var K,H;let ee=U.getAttribute("id"),A=D.getAttribute("id");return((K=N.get(A))!=null?K:0)-((H=N.get(ee))!=null?H:0)}).forEach(U=>{let D=U.closest(ws);D?D.appendChild(U.parentElement===D?U:U.closest(`${ws} > *`)):J.appendChild(U.parentElement===J?U:U.closest(`${ws} > *`))}),O.sort((U,D)=>D[1]-U[1]).forEach(U=>{var D;let K=(D=P.current)==null?void 0:D.querySelector(`${xt}[${Ze}="${encodeURIComponent(U[0])}"]`);K?.parentElement.appendChild(K)})}function T(){let N=re().find(J=>J.getAttribute("aria-disabled")!=="true"),O=N?.getAttribute(Ze);C.setState("value",O||void 0)}function v(){var N,O,J,U;if(!n.current.search||d.current.shouldFilter===!1){n.current.filtered.count=a.current.size;return}n.current.filtered.groups=new Set;let D=0;for(let K of a.current){let H=(O=(N=i.current.get(K))==null?void 0:N.value)!=null?O:"",ee=(U=(J=i.current.get(K))==null?void 0:J.keywords)!=null?U:[],A=g(H,ee);n.current.filtered.items.set(K,A),A>0&&D++}for(let[K,H]of r.current)for(let ee of H)if(n.current.filtered.items.get(ee)>0){n.current.filtered.groups.add(K);break}n.current.filtered.count=D}function Q(){var N,O,J;let U=ae();U&&(((N=U.parentElement)==null?void 0:N.firstChild)===U&&((J=(O=U.closest(xt))==null?void 0:O.querySelector(zc))==null||J.scrollIntoView({block:"nearest"})),U.scrollIntoView({block:"nearest"}))}function ae(){var N;return(N=P.current)==null?void 0:N.querySelector(`${qa}
4[aria-selected="true"]`)}function re(){var N;return Array.from(((N=P.current)==null?void 0:N.querySelectorAll(Dn))||[])}function ce(N){let O=re()[N];O&&C.setState("value",O.getAttribute(Ze))}function Z(N){var O;let J=ae(),U=re(),D=U.findIndex(H=>H===J),K=U[D+N];(O=d.current)!=null&&O.loop&&(K=D+N<0?U[U.length-1]:D+N===U.length?U[0]:U[D+N]),K&&C.setState("value",K.getAttribute(Ze))}function ie(N){let O=ae(),J=O?.closest(xt),U;for(;J&&!U;)J=N>0?Yc(J,xt):Qc(J,xt),U=J?.querySelector(Dn);U?C.setState("value",U.getAttribute(Ze)):Z(N)}let te=()=>ce(re().length-1),de=N=>{N.preventDefault(),N.metaKey?te():N.altKey?ie(1):Z(1)},B=N=>{N.preventDefault(),N.metaKey?ce(0):N.altKey?ie(-1):Z(-1)};return k.createElement(We.div,{ref:s,tabIndex:-1,...M,"cmdk-root":"",onKeyDown:N=>{var O;(O=M.onKeyDown)==null||O.call(M,N);let J=N.nativeEvent.isComposing||N.keyCode===229;if(!(N.defaultPrevented||J))switch(N.key){case"n":case"j":{_&&N.ctrlKey&&de(N);break}case"ArrowDown":{de(N);break}case"p":case"k":{_&&N.ctrlKey&&B(N);break}case"ArrowUp":{B(N);break}case"Home":{N.preventDefault(),ce(0);break}case"End":{N.preventDefault(),te();break}case"Enter":{N.preventDefault();let U=ae();if(U){let D=new Event($s);U.dispatchEvent(D)}}}}},k.createElement("label",{"cmdk-label":"",htmlFor:u.inputId,id:u.labelId,style:Zc},h),xs(t,N=>k.createElement(Ba.Provider,{value:C},k.createElement(Ka.Provider,{value:u},N))))}),Uc=k.forwardRef((t,s)=>{var n,a;let r=nt(),i=k.useRef(null),l=k.useContext(Wa),d=Tt(),h=Ga(t),o=(a=(n=h.current)==null?void 0:n.forceMount)!=null?a:l?.forceMount;Ge(()=>{if(!o)return d.item(r,l?.id)},[o]);let x=Va(r,i,[t.value,t.children,i],t.keywords),c=Zs(),f=Be(R=>R.value&&R.value===x.current),m=Be(R=>o||d.filter()===!1?!0:R.search?R.filtered.items.get(r)>0:!0);k.useEffect(()=>{let R=i.current;if(!(!R||t.disabled))return R.addEventListener($s,w),()=>R.removeEventListener($s,w)},[m,t.onSelect,t.disabled]);function w(){var R,C;E(),(C=(R=h.current).onSelect)==null||C.call(R,x.current)}function E(){c.setState("value",x.current,!0)}if(!m)return null;let{disabled:_,value:M,onSelect:S,forceMount:j,keywords:I,...P}=t;return k.createElement(We.div,{ref:wt(i,s),...P,id:r,"cmdk-item":"",role:"option","aria-disabled":!!_,"aria-selected":!!f,"data-disabled":!!_,"data-selected":!!f,onPointerMove:_||d.getDisablePointerSelection()?void 0:E,onClick:_?void 0:w},t.children)}),qc=k.forwardRef((t,s)=>{let{heading:n,children:a,forceMount:r,...i}=t,l=nt(),d=k.useRef(null),h=k.useRef(null),o=nt(),x=Tt(),c=Be(m=>r||x.filter()===!1?!0:m.search?m.filtered.groups.has(l):!0);Ge(()=>x.group(l),[]),Va(l,d,[t.value,t.heading,h]);let f=k.useMemo(()=>({id:l,forceMount:r}),[r]);return k.createElement(We.div,{ref:wt(d,s),...i,"cmdk-group":"",role:"presentation",hidden:c?void 0:!0},n&&k.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:o},n),xs(t,m=>k.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?o:void 0},k.createElement(Wa.Provider,{value:f},m))))}),Kc=k.forwardRef((t,s)=>{let{alwaysRender:n,...a}=t,r=k.useRef(null),i=Be(l=>!l.search);return!n&&!i?null:k.createElement(We.div,{ref:wt(r,s),...a,"cmdk-separator":"",role:"separator"})}),Bc=k.forwardRef((t,s)=>{let{onValueChange:n,...a}=t,r=t.value!=null,i=Zs(),l=Be(o=>o.search),d=Be(o=>o.selectedItemId),h=Tt();return k.useEffect(()=>{t.value!=null&&i.setState("search",t.value)},[t.value]),k.createElement(We.input,{ref:s,...a,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":d,id:h.inputId,type:"text",value:r?t.value:l,onChange:o=>{r||i.setState("search",o.target.value),n?.(o.target.value)}})}),Wc=k.forwardRef((t,s)=>{let{children:n,label:a="Suggestions",...r}=t,i=k.useRef(null),l=k.useRef(null),d=Be(o=>o.selectedItemId),h=Tt();return k.useEffect(()=>{if(l.current&&i.current){let o=l.current,x=i.current,c,f=new ResizeObserver(()=>{c=requestAnimationFrame(()=>{let m=o.offsetHeight;x.style.setProperty("--cmdk-list-height",m.toFixed(1)+"px")})});return f.observe(o),()=>{cancelAnimationFrame(c),f.unobserve(o)}}},[]),k.createElement(We.div,{ref:wt(i,s),...r,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":d,"aria-label":a,id:h.listId},xs(t,o=>k.createElement("div",{ref:wt(l,h.listInnerRef),"cmdk-list-sizer":""},o)))}),Hc=k.forwardRef((t,s)=>{let{open:n,onOpenChange:a,overlayClassName:r,contentClassName:i,container:l,...d}=t;return k.createElement(Vi,{open:n,onOpenChange:a}
vendor: 5,029 bytes, line 4
4,k.createElement(Yi,{container:l},k.createElement(Qi,{"cmdk-overlay":"",className:r}),k.createElement(Xi,{"aria-label":t.label,"cmdk-dialog":"",className:i},k.createElement(Ha,{ref:s,...d}))))}),Gc=k.forwardRef((t,s)=>Be(n=>n.filtered.count===0)?k.createElement(We.div,{ref:s,...t,"cmdk-empty":"",role:"presentation"}):null),Vc=k.forwardRef((t,s)=>{let{progress:n,children:a,label:r="Loading...",...i}=t;return k.createElement(We.div,{ref:s,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":r},xs(t,l=>k.createElement("div",{"aria-hidden":!0},l)))}),Qe=Object.assign(Ha,{List:Wc,Item:Uc,Input:Bc,Group:qc,Separator:Kc,Dialog:Hc,Empty:Gc,Loading:Vc});function Yc(t,s){let n=t.nextElementSibling;for(;n;){if(n.matches(s))return n;n=n.nextElementSibling}}function Qc(t,s){let n=t.previousElementSibling;for(;n;){if(n.matches(s))return n;n=n.previousElementSibling}}function Ga(t){let s=k.useRef(t);return Ge(()=>{s.current=t}),s}var Ge=typeof window>"u"?k.useEffect:k.useLayoutEffect;function et(t){let s=k.useRef();return s.current===void 0&&(s.current=t()),s}function Be(t){let s=Zs(),n=()=>t(s.snapshot());return k.useSyncExternalStore(s.subscribe,n,n)}function Va(t,s,n,a=[]){let r=k.useRef(),i=Tt();return Ge(()=>{var l;let d=(()=>{var o;for(let x of n){if(typeof x=="string")return x.trim();if(typeof x=="object"&&"current"in x)return x.current?(o=x.current.textContent)==null?void 0:o.trim():r.current}})(),h=a.map(o=>o.trim());i.value(t,d,h),(l=s.current)==null||l.setAttribute(Ze,d),r.current=d}),r}var Xc=()=>{let[t,s]=k.useState(),n=et(()=>new Map);return Ge(()=>{n.current.forEach(a=>a()),n.current=new Map},[t]),(a,r)=>{n.current.set(a,r),s({})}};function Jc(t){let s=t.type;return typeof s=="function"?s(t.props):"render"in s?s.render(t.props):t}function xs({asChild:t,children:s},n){return t&&k.isValidElement(s)?k.cloneElement(Jc(s),{ref:s.ref},n(s.props.children)):n(s)}var Zc={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function ed({className:t,...s}){return e.jsx(Qe,{"data-slot":"command",className:Y("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",t),...s})}function td({title:t="Command Palette",description:s="Search for a command to run...",children:n,className:a,showCloseButton:r=!0,...i}){return e.jsxs(Gs,{...i,children:[e.jsxs(Ys,{className:"sr-only",children:[e.jsx(Qs,{children:t}),e.jsx(Aa,{children:s})]}),e.jsx(Vs,{className:Y("overflow-hidden p-0",a),showCloseButton:r,children:e.jsx(ed,{className:"[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:n})})]})}function sd({className:t,...s}){return e.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[e.jsx(cs,{className:"size-4 shrink-0 opacity-50"}),e.jsx(Qe.Input,{"data-slot":"command-input",className:Y("placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",t),...s})]})}function nd({className:t,...s}){return e.jsx(Qe.List,{"data-slot":"command-list",className:Y("max-h-[min(300px,55dvh)] scroll-py-1 overflow-x-hidden overflow-y-auto",t),...s})}function ad({...t}){return e.jsx(Qe.Empty,{"data-slot":"command-empty",className:"py-6 text-center text-sm",...t})}function On({className:t,...s}){return e.jsx(Qe.Group,{"data-slot":"command-group",className:Y("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",t),...s})}function rd({className:t,...s}){return e.jsx(Qe.Separator,{"data-slot":"command-separator",className:Y("bg-border -mx-1 h-px",t),...s})}function $n({className:t,...s}){return e.jsx(Qe.Item,{"data-slot":"command-item",className:Y("data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...s})}function id(){const t=Le(),s=z(l=>l.commandPaletteOpen),n=z(l=>l.setCommandPaletteOpen),a=z(l=>l.setShortcutsModalOpen),r=l=>{n(!1),l()},i=[{icon:ss,label:"Email Accounts",shortcut:"g e",onSelect:()=>t("/app/emails")},{icon:Ws,label:"Contacts",shortcut:"g c",onSelect:()=>t("/app/contacts")}
4,{icon:ka,label:"Campaigns",shortcut:"g m",onSelect:()=>t("/app/campaigns")},{icon:ts,label:"Unibox",shortcut:"g u",onSelect:()=>t("/app/unibox")},{icon:sa,label:"Analytics",shortcut:"g a",onSelect:()=>t("/app/analytics")},{icon:lt,label:"Pipelines",shortcut:"g p",onSelect:()=>t("/app/crm/pipelines")},{icon:_a,label:"Deals",shortcut:"g d",onSelect:()=>t("/app/crm/deals")},{icon:Sa,label:"Tasks",shortcut:"g t",onSelect:()=>t("/app/crm/tasks")},{icon:Hs,label:"Templates",shortcut:"g l",onSelect:()=>t("/app/templates")},{icon:Ms,label:"API Keys",shortcut:"g k",onSelect:()=>t("/app/api-keys")},{icon:ds,label:"Settings",shortcut:"g s",onSelect:()=>t("/app/settings")},{icon:fa,label:"Billing",onSelect:()=>t("/app/settings/billing")}];return e.jsxs(td,{open:s,onOpenChange:n,className:"top-[10%] translate-y-0 md:top-[50%] md:translate-y-[-50%]",children:[e.jsx(sd,{placeholder:"Type a command or search..."}),e.jsxs(nd,{children:[e.jsx(ad,{children:"No results found."}),e.jsx(On,{heading:"Navigation",children:i.map(l=>e.jsxs($n,{onSelect:()=>r(l.onSelect),children:[e.jsx(l.icon,{className:"mr-2 size-4"}),e.jsx("span",{children:l.label}),l.shortcut&&e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:l.shortcut})]},l.label))}),e.jsx(rd,{}),e.jsx(On,{heading:"Actions",children:e.jsxs($n,{onSelect:()=>r(()=>a(!0)),children:[e.jsx(Ms,{className:"mr-2 size-4"}),e.jsx("span",{children:"Keyboard shortcuts"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:"?"})]})})]})]})}async function od(t){return await be({method:"POST",url:"/ai/sessions",data:t,authorization:!0})}async function ld(t){await be({method:"DELETE",url:`/ai/sessions/${t}`,authorization:!0})}async function cd(){return await be({method:"DELETE",url:"/ai/sessions",authorization:!0})}async function dd(t){return await be({method:"GET",url:`/ai/sessions/${t}/messages`,authorization:!0})}async function ud(t,s,n,a){const r=na();let i;try{i=await fetch(`${cr}${t}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...r?.access_token?{Authorization:`Bearer ${r.access_token}`}:{}},body:JSON.stringify(s),signal:a})}catch(o){if(o?.name==="AbortError")return;n({type:"error",message:"Could not reach the assistant."});return}if(!i.ok||!i.body){try{const o=await i.json();n({type:"error",code:o.code,message:o.message||"The assistant is unavailable."})}catch{n({type:"error",message:"The assistant is unavailable."})}return}const l=i.body.getReader(),d=new TextDecoder;let h="";try{for(;;){const{done:o,value:x}=await l.read();if(o)break;h+=d.decode(x,{stream:!0});let c;for(;(c=h.indexOf(`
5
6`))>=0;){const f=h.slice(0,c);h=h.slice(c+2);const m=f.split(`
7`).find(E=>E.startsWith("data:"));if(!m)continue;const w=m.slice(5).trim();if(w)try{n(JSON.parse(w))}catch{}}}}catch(o){o?.name!=="AbortError"&&n({type:"error",message:"The connection was interrupted."})}}async function md(t=20,s){const n=new URLSearchParams({limit:String(t)});return s&&n.set("cursor",s),await be({method:"GET",url:`/ai/sessions?${n.toString()}`,authorization:!0})}function pd(t=20){return eo({queryKey:["ai","sessions",t],queryFn:({pageParam:s})=>md(t,s),initialPageParam:void 0,getNextPageParam:s=>s.pagination.next_cursor??void 0,staleTime:3e4})}const vs=/(`[^`\n]+`)|(\*\*[^*\n]+\*\*)|(\*[^*\n]+\*)|\[([^\]\n]+)\]\(([^)\s]+)\)/g;function Ns(t,s){const n=[];let a=0,r=0;vs.lastIndex=0;for(let i=vs.exec(t);i;i=vs.exec(t)){if(i.index>a&&n.push(t.slice(a,i.index)),i[1])n.push(e.jsx("code",{className:"rounded border border-slate-200 bg-slate-100 px-1 py-px font-mono text-[11.5px] text-slate-700",children:i[1].slice(1,-1)},r++));else if(i[2])n.push(e.jsx("strong",{className:"font-semibold text-slate-900",children:i[2].slice(2,-2)},r++));else if(i[3])n.push(e.jsx("em",{children:i[3].slice(1,-1)},r++));else{const l=i[4],d=i[5],h=d.startsWith("/");!h&&!/^https?:\/\//.test(d)?n.push(l):n.push(e.jsx("a",{href:d,target:h?void 0:"_blank",rel:h?void 0:"noreferrer",onClick:o=>{h&&s&&(o.preventDefault(),s(d))},className:"text-sky-700 underline decoration-sky-300 underline-offset-2 hover:
7decoration-sky-500",children:l},r++))}a=i.index+i[0].length}return a<t.length&&n.push(t.slice(a)),n}function zn(){return e.jsx("span",{"aria-hidden":!0,className:"ai-caret ml-0.5 inline-block h-[1em] w-[2px] translate-y-[0.15em] rounded-sm bg-sky-500"})}function Ya({text:t,onOpen:s,caret:n=!1}){const a=[];if(t.split(/```[^\n]*\n?/).forEach((i,l)=>{if(l%2===1){if(!i.trim())return;a.push(e.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap break-words rounded-md border border-slate-200 bg-slate-50 px-2.5 py-2 font-mono text-[11.5px] leading-relaxed text-slate-700",children:i.replace(/\n$/,"")},`c${l}`));return}let d=[],h=null;const o=()=>{d.length&&(a.push(e.jsx("p",{className:"whitespace-pre-wrap",children:Ns(d.join(`
8`),s)},a.length)),d=[])},x=()=>{if(!h)return;const c=h.ordered?"ol":"ul";a.push(e.jsx(c,{className:(h.ordered?"list-decimal":"list-disc")+" space-y-1 pl-4 marker:text-slate-400",children:h.items.map((f,m)=>e.jsx("li",{children:Ns(f,s)},m))},a.length)),h=null};for(const c of i.split(`
9`)){const f=/^\s*[-*]\s+(.*)$/.exec(c),m=/^\s*\d+[.)]\s+(.*)$/.exec(c),w=/^\s*#{1,4}\s+(.*)$/.exec(c);if(f||m){o();const E=!!m;(!h||h.ordered!==E)&&(x(),h={ordered:E,items:[]}),h.items.push((m??f)[1])}else w?(o(),x(),a.push(e.jsx("p",{className:"font-semibold text-slate-900",children:Ns(w[1],s)},a.length))):c.trim()?(x(),d.push(c)):(o(),x())}o(),x()}),n){const i=a[a.length-1];if(b.isValidElement(i)&&i.type==="p"){const l=i;a[a.length-1]=b.cloneElement(l,{},...b.Children.toArray(l.props.children),e.jsx(zn,{},"caret"))}else a.push(e.jsx("p",{children:e.jsx(zn,{})},"caret-line"))}return e.jsx("div",{className:"space-y-2 break-words text-[13px] leading-relaxed text-slate-800",children:a})}const ht=new Map;let xd=0;const it=()=>`m${++xd}`;function hd(t){const s=t.trim().replace(/\s+/g," ");return s.length>40?s.slice(0,40).trimEnd()+"…":s||"New chat"}function gt(t){const s=document.documentElement.clientWidth,n=window.innerHeight,a=Math.min(Math.max(t.w,aa),Math.min(dr,s-16)),r=Math.min(Math.max(t.h,ra),n-16);return{w:a,h:r,x:Math.min(Math.max(t.x,8),s-a-8),y:Math.min(Math.max(t.y,8),n-r-8)}}function Fn(){const t=document.documentElement.clientWidth,s=window.innerHeight,n=460,a=Math.min(640,s-48);return gt({x:t-n-24,y:s-a-24,w:n,h:a})}function fd(){const t=z(p=>p.aiAssistantOpen),s=z(p=>p.setAIAssistantOpen),n=z(p=>p.agentExpanded),a=z(p=>p.setAgentExpanded),r=z(p=>p.agentMinimized),i=z(p=>p.setAgentMinimized),l=z(p=>p.agentSide),d=z(p=>p.setAgentSide),h=z(p=>p.agentWidth),o=z(p=>p.agentFloating),x=z(p=>p.setAgentFloating),c=z(p=>p.agentFloatRect),f=z(p=>p.agentTabs),m=z(p=>p.agentActiveKey),w=t&&!r,[E,_]=b.useState(()=>typeof window<"u"&&window.matchMedia("(min-width: 640px)").matches);b.useEffect(()=>{const p=window.matchMedia("(min-width: 640px)"),F=()=>_(p.matches);return p.addEventListener("change",F),()=>p.removeEventListener("change",F)},[]);const M=o&&!n&&E,S=b.useMemo(()=>M?gt(c??Fn()):null,[M,c]),j=Le(),I=Ve(),P=b.useRef(null),R=b.useRef(null),C=b.useRef(new Set),[u,g]=b.useState(!0),y=as("USE_AI"),T=ya(),v=f.find(p=>p.key===m)??null,Q=v?.draft??"",ae=!v?.hydrated||!!v?.pending,re=b.useMemo(()=>Ad(I.pathname),[I.pathname]),ce=b.useCallback(p=>j(Td(p)),[j]);function Z(p="auto"){const F=P.current;F&&F.scrollTo({top:F.scrollHeight,behavior:p})}const ie=b.useCallback(()=>{const p=R.current;p&&(p.style.height="0px",p.style.height=Math.min(p.scrollHeight,128)+"px")},[]);b.useEffect(()=>{if(!w)return;z.getState().agentEnsureTab();const p=window.setTimeout(()=>R.current?.focus(),80);return()=>window.clearTimeout(p)},[w]),b.useEffect(()=>{w&&v?.unseen&&z.getState().agentPatchTab(v.key,{unseen:!1})},[w,v?.key,v?.unseen]),b.useEffect(()=>{g(!0),requestAnimationFrame(()=>Z()),w&&R.current?.focus()},[m]),b.useEffect(()=>{ie()},[Q,m,ie]),b.useEffect(()=>{if(!v||!v.sessionId||v.hydrated||C.current.has(v.key))return;const p=v.key,F=v.sessionId;C.current.add(p),dd(F).then(q=>{z.getState().agentUpdateTab(p,V=>({...V,turns:vd(q.turns),pending:q.pending?{toolCallId:q.pending.tool_call_id,tool:q.pending.tool_name,risk:q.pending.risk,argsSummary:q.pending.args_summary}:null,title:q.title||V.title,freeModel:q.free_model??V.freeModel,hydrated:!0}))}).catch(()=>{z.getState().agentUpdateTab(p,q=>({...q,hydrated:!0,turns:ks(q.turns,{type:"error",message:"Could not load this conversation."})}))}).finally(()=>C.current.delete(p))},[v]),b.useEffect(()=>{u&&Z()},[v?.turns,v?.pending,u]);function te(){const p=P.current;p&&g(p.scrollHeight-p.scrollTop-p.clientHeight<48)}async function de(p,F,q){z.getState().agentPatchTab(p,{running:!0,pending:null,iteration:0});const oe=new AbortController;ht.set(p,oe);try{await ud(F,q,W=>{const X=z.getState();if(W.type==="iteration"){X.agentPatchTab(p,{...typeof W.credits_remaining=="number"?{credits:W.credits_remaining}:{},...typeof W.budget=="number"?{budget:W.budget}:{},...typeof W.iteration=="number"?{iteration:W.iteration}:{},...W.free_model?{freeModel:!0}:{}});return}if(W.type==="approval_required"){X.agentPatchTab(p,{pending:{toolCallId:W.tool_call_id||"",tool:W.tool||"",risk:W.risk||"write",argsSummary:W.args_summary}});return}if(W.type==="done"){typeof W.credits_remaining=="number"&&X.agentPatchTab(p,{credits:W.credits_remaining});return}X.agentUpdateTab(p,le=>({...le,turns:ks(le.turns,W)})),W.type==="error"&&typeof W.credits_remaining=="number"&&X.agentPatchTab(p,{credits:W.credits_remaining})},oe.signal)}finally{ht.delete(p);const W=z.getState();W.agentPatchTab(p,{running:!1}),(!W.aiAssistantOpen||W.agentMinimized||W.agentActiveKey!==p)&&W.agentPatchTab(p,{unseen:!0})}}async function B(){const p=v;if(!p||p.running||p.pending||!p.hydrated)return;const F=Q.trim();if(!F)return;const q=z.getState();q.agentUpdateTab(p.key,oe=>({...oe,running:!0,draft:"",title:oe.sessionId||oe.title!=="New chat"?oe.title:hd(F),turns:[...oe.turns,{id:it(),role:"user",blocks:[{kind:"text",text:F}]}]}));let V=p.sessionId;if(!V)try{V=(await od({page:I.pathname,resource:re})).id,q.agentPatchTab(p.key,{sessionId:V})}catch{q.agentUpdateTab(p.key,oe=>({...oe,running:!1,turns:ks(oe.turns,{type:"error",message:"Could not start a session."})}));return}await de(p.key,`/ai/sessions/${V}/messages`,{message_id:it()+":"+Date.now(),text:F,page:I.pathname,resource:re})}async function N(p,F){const q=z.getState().agentTabs.find(V=>V.key===p);!q||!q.sessionId||!q.pending||(z.getState().agentPatchTab(p,{pending:null}),await de(p,`/ai/sessions/${q.sessionId}/approve`,{decision:F}))}function O(p){ht.get(p)?.abort(),z.getState().agentPatchTab(p,{running:!1})}function J(p){ht.get(p)?.abort(),ht.delete(p),z.getState().agentCloseTab(p)}function U(p){z.getState().agentOpenSession(p.id,p.title||"Conversation")}function D(p){v&&z.getState().agentPatchTab(v.key,{draft:p})}function K(){s(!1),i(!1)}function H(p){const F=f.findIndex(V=>V.key===m);if(F===-1||f.length<2)return;const q=f[(F+p+f.length)%f.length];z.getState().agentSetActive(q.key)}
9function ee(p){if(p.key==="Escape"){p.stopPropagation(),K();return}const F=p.metaKey||p.ctrlKey;if(F&&!p.altKey&&(p.key==="]"||p.key==="[")){p.preventDefault(),p.stopPropagation(),H(p.key==="]"?1:-1);return}if(p.altKey&&!F)switch(p.code){case"KeyN":p.preventDefault(),z.getState().agentNewTab();return;case"KeyW":p.preventDefault(),v&&J(v.key);return;case"KeyM":p.preventDefault(),i(!0);return;case"KeyP":p.preventDefault(),E&&!n&&x(!o);return}}function A(p){if(n||M)return;p.preventDefault();const F=V=>{const oe=l==="right"?window.innerWidth-V.clientX:V.clientX;z.getState().setAgentWidth(oe)},q=()=>{window.removeEventListener("pointermove",F),window.removeEventListener("pointerup",q)};window.addEventListener("pointermove",F),window.addEventListener("pointerup",q)}b.useEffect(()=>{if(!M)return;const p=()=>{const F=z.getState().agentFloatRect;F&&z.getState().setAgentFloatRect(gt(F))};return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[M]);function L(p){if(n||!E||p.button!==0||p.target.closest("button, input, textarea, a"))return;const F=p.clientX,q=p.clientY;let V=M&&S?S:null,oe=V?F-V.x:0,W=V?q-V.y:0,X=M;const le=me=>{if(!X){if(Math.abs(me.clientX-F)+Math.abs(me.clientY-q)<16)return;const _e=Fn();V={..._e,w:Math.min(_e.w,z.getState().agentWidth)},oe=Math.min(V.w/2,200),W=24,X=!0,z.getState().setAgentFloating(!0)}V&&(me.preventDefault(),z.getState().setAgentFloatRect(gt({...V,x:me.clientX-oe,y:me.clientY-W})))},ue=()=>{window.removeEventListener("pointermove",le),window.removeEventListener("pointerup",ue)};window.addEventListener("pointermove",le),window.addEventListener("pointerup",ue)}function $(p,F){if(!M||!S)return;p.preventDefault(),p.stopPropagation();const q={...S},V=p.clientX,oe=p.clientY,W=le=>{le.preventDefault();const ue=le.clientX-V,me=le.clientY-oe;let{x:_e,y:fe,w:we,h:he}=q;F.includes("e")&&(we=q.w+ue),F.includes("s")&&(he=q.h+me),F.includes("w")&&(we=q.w-ue,_e=q.x+Math.min(ue,q.w-aa)),F.includes("n")&&(he=q.h-me,fe=q.y+Math.min(me,q.h-ra)),z.getState().setAgentFloatRect(gt({x:_e,y:fe,w:we,h:he}))},X=()=>{window.removeEventListener("pointermove",W),window.removeEventListener("pointerup",X)};window.addEventListener("pointermove",W),window.addEventListener("pointerup",X)}return y?e.jsxs(e.Fragment,{children:[w&&e.jsx("div",{onClick:K,className:"fixed inset-0 z-40 bg-slate-900/20 md:hidden"}),t&&r&&e.jsx(bd,{tabs:f,activeKey:m,side:l,onRestore:p=>{p&&z.getState().agentSetActive(p),i(!1)},onClose:K}),e.jsxs(ne.aside,{initial:!1,animate:M?{x:0,opacity:w?1:0,scale:w?1:.97}:{x:w?0:l==="right"?"101%":"-101%",opacity:1,scale:1},transition:{type:"spring",stiffness:380,damping:40},inert:!w,onKeyDown:ee,style:M&&S?{"--agent-w":`${h}px`,left:S.x,top:S.y,width:S.w,height:S.h}:{"--agent-w":`${h}px`},className:Y("fixed z-50 bg-white flex",M?"rounded-xl border border-slate-200 shadow-2xl overflow-hidden":Y("top-0 h-full shadow-[0_0_60px_-12px_rgba(15,23,42,0.3)]",l==="right"?"right-0 border-l border-slate-200":"left-0 border-r border-slate-200",n?"w-full sm:w-[min(1080px,94vw)]":"w-full sm:w-[min(var(--agent-w),94vw)]")),"aria-hidden":!w,children:[M&&e.jsx(e.Fragment,{children:[["n","top-0 left-3 right-3 h-1.5 cursor-ns-resize"],["s","bottom-0 left-3 right-3 h-1.5 cursor-ns-resize"],["e","right-0 top-3 bottom-3 w-1.5 cursor-ew-resize"],["w","left-0 top-3 bottom-3 w-1.5 cursor-ew-resize"],["nw","top-0 left-0 size-3 cursor-nwse-resize"],["se","bottom-0 right-0 size-3 cursor-nwse-resize"],["ne","top-0 right-0 size-3 cursor-nesw-resize"],["sw","bottom-0 left-0 size-3 cursor-nesw-resize"]].map(([p,F])=>e.jsx("div",{onPointerDown:q=>$(q,p),className:Y("absolute z-20 touch-none",F)},p))}),!n&&!M&&e.jsx("div",{onPointerDown:A,title:"Drag to resize",className:Y("hidden sm:block absolute top-0 h-full w-1.5 cursor-col-resize touch-none z-10 hover:bg-sky-400/40 active:bg-sky-500/50 transition-colors",l==="right"?"left-0":"right-0")}),n&&e.jsx(jd,{activeSessionId:v?.sessionId??null,onOpen:U,onNew:()=>z.getState().agentNewTab()}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col",children:[e.jsxs("div",{onPointerDown:L,className:Y("shrink-0 px-3 h-12 flex items-center gap-2 border-b border-slate-200",!n&&E&&"touch-none select-none",M?"cursor-grab active:cursor-grabbing":!n&&E&&"sm:cursor-grab"),children:[e.jsx(kt,{className:"w-4 h-4 text-sky-600"}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:"Assistant"}),e.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[!M&&e.jsx("button",{onClick:()=>
9d(l==="right"?"left":"right"),title:l==="right"?"Move to the left edge":"Move to the right edge","aria-label":"Switch panel side",className:"size-7 rounded-md text-slate-500 hover:text-slate-900 hover:bg-slate-100 hidden sm:inline-flex items-center justify-center transition-colors",children:l==="right"?e.jsx(xn,{className:"w-4 h-4"}):e.jsx(hn,{className:"w-4 h-4"})}),!n&&e.jsx("button",{onClick:()=>x(!o),title:M?`Dock to the ${l} edge (⌥P)`:"Pop out into a window (⌥P)","aria-label":M?"Dock panel":"Pop out into a floating window",className:"size-7 rounded-md text-slate-500 hover:text-slate-900 hover:bg-slate-100 hidden sm:inline-flex items-center justify-center transition-colors",children:M?l==="right"?e.jsx(hn,{className:"w-4 h-4"}):e.jsx(xn,{className:"w-4 h-4"}):e.jsx(Po,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>i(!0),title:"Minimize to dock (⌥M)","aria-label":"Minimize to dock",className:"size-7 rounded-md text-slate-500 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center justify-center transition-colors",children:e.jsx(Ta,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>a(!n),title:n?"Collapse":"Expand to workspace","aria-label":n?"Collapse":"Expand to workspace",className:"size-7 rounded-md text-slate-500 hover:text-slate-900 hover:bg-slate-100 hidden sm:inline-flex items-center justify-center transition-colors",children:n?e.jsx(Mo,{className:"w-4 h-4"}):e.jsx(_o,{className:"w-4 h-4"})}),e.jsx("button",{onClick:K,title:"Close","aria-label":"Close assistant",className:"size-7 rounded-md text-slate-500 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center justify-center transition-colors",children:e.jsx(ve,{className:"w-4 h-4"})})]})]}),e.jsx(gd,{tabs:f,activeKey:m,onSelect:p=>z.getState().agentSetActive(p),onClose:J,onNew:()=>z.getState().agentNewTab()}),e.jsxs("div",{className:"relative flex-1 min-h-0",children:[e.jsx("div",{ref:P,onScroll:te,className:"h-full overflow-y-auto",children:e.jsxs("div",{className:Y("min-h-full flex flex-col px-4 py-4 space-y-4",n&&"mx-auto w-full max-w-[760px]"),children:[v&&!v.hydrated&&e.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-slate-400",children:[e.jsx(xe,{className:"w-3.5 h-3.5 animate-spin"}),"Loading conversation…"]}),v&&v.hydrated&&v.turns.length===0&&!v.running&&e.jsx(Ed,{onPick:p=>{D(p),R.current?.focus()}}),v?.turns.map((p,F)=>e.jsx(Nd,{turn:p,onOpen:ce,streaming:!!v.running&&!v.pending&&F===v.turns.length-1},p.id)),v?.pending&&e.jsx(Sd,{pending:v.pending,onDecide:p=>N(v.key,p)}),v?.running&&!v.pending&&e.jsxs(ne.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.16},className:"flex items-center gap-2 text-[12px]",children:[e.jsx(kt,{className:"w-3.5 h-3.5 text-sky-500 animate-pulse"}),e.jsx("span",{className:"ai-shimmer-text font-medium",children:"Working…"}),v.iteration>0&&e.jsxs("span",{className:"font-mono tabular-nums text-slate-300",children:["step ",v.iteration,"/",v.budget]})]})]})}),!u&&v?.running&&e.jsxs("button",{onClick:()=>{g(!0),Z("smooth")},className:"absolute bottom-3 left-1/2 -translate-x-1/2 h-7 px-3 rounded-full bg-white border border-slate-200 shadow-sm text-[11.5px] text-slate-600 hover:text-slate-900 inline-flex items-center gap-1.5 transition-colors",children:[e.jsx(go,{className:"w-3 h-3"}),"Latest"]})]}),e.jsx("div",{className:"shrink-0 border-t border-slate-200 p-3",children:e.jsxs("div",{className:Y(n&&"mx-auto w-full max-w-[760px]"),children:[e.jsxs("div",{className:"flex items-end gap-2 rounded-lg border border-slate-200 focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100 px-2.5 py-1.5 transition-colors",children:[e.jsx("textarea",{ref:R,value:Q,onChange:p=>D(p.target.value),onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&!p.nativeEvent.isComposing&&(p.preventDefault(),B())},rows:1,placeholder:v?.pending?"Respond to the approval above first":"Ask about contacts, campaigns, your inbox…",disabled:ae,className:"flex-1 resize-none bg-transparent py-1 text-[13px] leading-5 text-slate-900 placeholder:text-slate-400 outline-none max-h-32 disabled:opacity-60"}),v?.running?e.jsx("button",{onClick:()=>O(v.key),title:"Stop","aria-label":"Stop run",className:"size-7 rounded-md bg-slate-900 hover:bg-slate-700 text-white inline-flex items-center justify-center transition-colors",children:e.jsx(wi,{className:"w-3 h-3",fill:"
9currentColor"})}):e.jsx("button",{onClick:B,disabled:!Q.trim()||ae,title:"Send","aria-label":"Send message",className:"size-7 rounded-md bg-sky-600 hover:bg-sky-700 text-white inline-flex items-center justify-center transition-colors disabled:opacity-40",children:e.jsx(qr,{className:"w-4 h-4"})})]}),v?.freeModel&&e.jsxs("div",{className:"mt-2 flex items-center gap-1.5 text-[10.5px] text-amber-600",children:[e.jsx(ze,{className:"w-3 h-3 shrink-0"}),e.jsx("span",{children:"Free local model. Responses may be lower quality, and nothing is charged."})]}),e.jsxs("div",{className:"mt-2 flex items-center justify-between text-[10.5px] text-slate-400",children:[e.jsx("span",{children:"Read actions run automatically. Writes ask first."}),!v?.freeModel&&T&&v?.credits!=null&&e.jsxs("span",{className:"font-mono tabular-nums",children:[v.credits.toLocaleString()," credits"]})]})]})})]})]})]}):null}function gd({tabs:t,activeKey:s,onSelect:n,onClose:a,onNew:r}){const i=b.useRef(null);return b.useEffect(()=>{i.current?.querySelector('[data-active="true"]')?.scrollIntoView({block:"nearest",inline:"nearest"})},[s,t.length]),t.length===0?null:e.jsxs("div",{ref:i,role:"tablist","aria-label":"Conversations",className:"shrink-0 flex items-stretch gap-1 px-2 h-9 border-b border-slate-200 overflow-x-auto no-scrollbar",children:[t.map(l=>{const d=l.key===s;return e.jsxs("div",{role:"tab","aria-selected":d,tabIndex:0,"data-active":d||void 0,title:l.title,onClick:()=>n(l.key),onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),n(l.key))},onMouseDown:h=>{h.button===1&&h.preventDefault()},onAuxClick:h=>{h.button===1&&a(l.key)},className:Y("group shrink-0 max-w-[160px] h-7 my-1 pl-2.5 pr-1.5 rounded-md inline-flex items-center gap-1.5 cursor-pointer text-[12px] transition-colors",d?"bg-slate-100 text-slate-900":"text-slate-500 hover:bg-slate-50 hover:text-slate-700"),children:[l.running?e.jsx(xe,{className:"w-3 h-3 shrink-0 animate-spin text-sky-500"}):e.jsx("span",{className:Y("size-1.5 shrink-0 rounded-full",l.pending?"bg-amber-500":l.unseen?"bg-sky-500":"bg-slate-300")}),e.jsx("span",{className:"truncate",children:l.title}),e.jsx("button",{onClick:h=>{h.stopPropagation(),a(l.key)},tabIndex:-1,className:"size-4 shrink-0 rounded inline-flex items-center justify-center text-slate-400 hover:text-slate-900 hover:bg-slate-200 opacity-100 md:opacity-0 md:group-hover:opacity-100 md:group-focus-within:opacity-100 transition-opacity","aria-label":`Close ${l.title}`,children:e.jsx(ve,{className:"w-3 h-3"})})]},l.key)}),e.jsx("button",{onClick:r,title:"New chat","aria-label":"New chat",className:"shrink-0 size-7 my-1 rounded-md text-slate-400 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center justify-center transition-colors",children:e.jsx(os,{className:"w-4 h-4"})})]})}function bd({tabs:t,activeKey:s,side:n,onRestore:a,onClose:r}){const i=t.find(d=>d.running)??t.find(d=>d.pending)??t.find(d=>d.unseen)??t.find(d=>d.key===s)??t[0]??null;let l;return i?.running?l=e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-slate-500",children:[e.jsx(xe,{className:"w-3 h-3 animate-spin text-sky-500"}),"Working",i.iteration>0&&e.jsxs("span",{className:"font-mono tabular-nums text-slate-400",children:[i.iteration,"/",i.budget]})]}):i?.pending?l=e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-amber-700",children:[e.jsx("span",{className:"size-1.5 rounded-full bg-amber-500"}),"Needs approval"]}):i?.unseen?l=e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sky-700",children:[e.jsxs("span",{className:"relative flex size-1.5",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-sky-400 opacity-60"}),e.jsx("span",{className:"relative inline-flex size-1.5 rounded-full bg-sky-500"})]}),"Response ready"]}):l=e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-slate-400",children:[e.jsx("span",{className:"size-1.5 rounded-full bg-slate-300"}),"Idle"]}),e.jsx(ne.div,{initial:{y:16,opacity:0},animate:{y:0,opacity:1},transition:{type:"spring",stiffness:420,damping:34},className:Y("fixed bottom-4 z-50",n==="right"?"right-4":"left-4"),children:e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>a(i?.key??null),onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),a(i?.key??null))},className:"h-10 pl-2.5 pr-1 rounded-lg border border-slate-200 bg-white shadow-lg shadow-slate-900/10 flex items-center gap-2 cursor-pointer hover:border-slate-300 transition-colors",children:[e.jsx(kt,{className:"w-4 h-4 text-sky-600 shrink-0"}),e.jsx("span",{className:"max-w-[160px] truncate text-[12.5px] font-medium text-slate-800",children:i?.title??"Assistant"}),e.jsx("span",{className:"text-[11.5px]",children:l}),e.jsxs("span",{className:"flex items-center gap-0.5 pl-1",children:[e.jsx("button",{onClick:d=>{d.stopPropagation(),a(i?.key??null)},title:"Restore","aria-label":"Restore assistant",className:"size-6 rounded inline-flex items-center justify-center text-slate-400 hover:text-slate-900 hover:bg-slate-100 transition-colors",children:e.jsx(ua,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:d=>{d.stopPropagation(),r()},title:"Close","aria-label":"Close assistant",className:"size-6 rounded inline-flex items-center justify-center text-slate-400 hover:text-slate-900 hover:bg-slate-100 transition-colors",children:e.jsx(ve,{className:"w-3.5 h-3.5"})})]})]})})}function yd(t){const s=new Date(t).getTime(),n=new Date,a=new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime();return s>=a?"Today":s>=a-1440*60*1e3?"Yesterday":s>=a-8640*60*1e3?"This week":"Earlier"}
9function jd({activeSessionId:t,onOpen:s,onNew:n}){const a=pd(20),r=Ee(),i=Bs(),[l,d]=b.useState(""),h=b.useMemo(()=>(a.data?.pages??[]).flatMap(f=>f.data),[a.data]),o=b.useMemo(()=>{const f=l.trim().toLowerCase();return f?h.filter(m=>(m.title||"Conversation").toLowerCase().includes(f)):h},[l,h]),x=b.useMemo(()=>{const f=[];for(const m of o){const w=yd(m.updated_at||m.created_at),E=f[f.length-1];E&&E.label===w?E.rows.push(m):f.push({label:w,rows:[m]})}return f},[o]),c=f=>{i.show(`Delete "${f.title||"this conversation"}"? Its transcript is removed for good.`,async()=>{await ld(f.id);const m=z.getState().agentTabs.find(w=>w.sessionId===f.id);m&&z.getState().agentCloseTab(m.key),await r.invalidateQueries({queryKey:["ai","sessions"]})})};return e.jsxs("div",{className:"hidden sm:flex w-64 shrink-0 flex-col border-r border-slate-200 bg-slate-50/50",children:[e.jsxs("div",{className:"shrink-0 px-3 pt-3 pb-2 space-y-2 border-b border-slate-200",children:[e.jsxs("button",{onClick:n,className:"w-full h-8 rounded-md bg-sky-600 hover:bg-sky-700 text-white text-[12.5px] font-medium inline-flex items-center justify-center gap-1.5 transition-colors",children:[e.jsx(os,{className:"w-3.5 h-3.5"}),"New chat",e.jsx(tt,{combo:"alt+n",variant:"dark"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 px-2 h-7 rounded-md border border-slate-200 bg-white focus-within:border-sky-300 focus-within:ring-1 focus-within:ring-sky-100 transition-colors",children:[e.jsx(cs,{className:"w-3 h-3 text-slate-400 shrink-0"}),e.jsx("input",{value:l,onChange:f=>d(f.target.value),placeholder:"Search history…",className:"flex-1 min-w-0 bg-transparent text-[11.5px] text-slate-900 placeholder:text-slate-400 outline-none"}),l&&e.jsx("button",{onClick:()=>d(""),"aria-label":"Clear search",className:"size-4 shrink-0 inline-flex items-center justify-center rounded text-slate-400 hover:text-slate-600",children:e.jsx(ve,{className:"w-3 h-3"})})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-2 py-2",children:[o.length===0&&!a.isLoading&&e.jsx("p",{className:"px-1.5 py-3 text-[11.5px] text-slate-400 leading-relaxed",children:l?"No conversations match.":"Your past conversations show up here."}),x.map(f=>e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"px-1.5 pb-1 text-[10px] uppercase tracking-[0.14em] text-slate-400 font-semibold",children:f.label}),e.jsx("div",{className:"space-y-0.5",children:f.rows.map(m=>e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>s(m),onKeyDown:w=>{w.key==="Enter"&&s(m)},className:Y("group w-full text-left px-2 py-1.5 rounded-md flex items-start gap-2 cursor-pointer transition-colors",m.id===t?"bg-white ring-1 ring-slate-200":"hover:bg-white"),children:[e.jsx(is,{className:"w-3 h-3 mt-0.5 shrink-0 text-slate-400"}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[12px] text-slate-700",children:m.title||"Conversation"}),e.jsxs("span",{className:"block truncate text-[10.5px] text-slate-400",children:[Md(m.updated_at||m.created_at),m.user_name&&` · ${m.user_name}`]})]}),e.jsx("button",{onClick:w=>{w.stopPropagation(),c(m)},title:"Delete conversation","aria-label":`Delete ${m.title||"conversation"}`,className:"size-5 mt-0.5 shrink-0 inline-flex items-center justify-center rounded text-slate-400 hover:text-rose-600 hover:bg-rose-50 transition-colors opacity-100 md:opacity-0 md:group-hover:opacity-100",children:e.jsx(dn,{className:"w-3 h-3"})})]},m.id))})]},f.label)),a.hasNextPage&&e.jsx("button",{onClick:()=>a.fetchNextPage(),disabled:a.isFetchingNextPage,className:"mt-1 w-full h-7 rounded-md text-[11.5px] text-slate-500 hover:text-slate-800 hover:bg-white transition-colors",children:a.isFetchingNextPage?"Loading…":"Load more"})]}),h.length>0&&e.jsx("div",{className:"shrink-0 px-2 py-2 border-t border-slate-200",children:e.jsxs("button",{onClick:()=>i.show("Clear your entire assistant history in this workspace? Every conversation and transcript is removed for good.",async()=>{await cd();const f=z.getState();for(const m of f.agentTabs.filter(w=>w.sessionId))f.agentCloseTab(m.key);await r.invalidateQueries({queryKey:["ai","sessions"]})}),className:"w-full h-7 rounded-md inline-flex items-center justify-center gap-1.5 text-[11.5px] text-slate-500 hover:text-rose-600 hover:bg-rose-50 transition-colors",children:[e.jsx(dn,{className:"w-3 h-3"}),"Clear history"]})})]})}function ks(t,s){const n=t.slice();let a=n[n.length-1];return!a||a.role!=="assistant"?(a={id:it(),role:"assistant",blocks:[]},n.push(a)):(a={...a,blocks:[...a.blocks]},n[n.length-1]=a),wd(a,s),n}function wd(t,s){switch(s.type){case"text_delta":{const n=t.blocks[t.blocks.length-1];n&&n.kind==="text"&&n.live?t.blocks[t.blocks.length-1]={kind:"text",text:n.text+(s.text||""),live:!0}:t.blocks.push({kind:"text",text:s.text||"",live:!0});break}case"text":{const n=t.blocks[t.blocks.length-1];n&&n.kind==="text"&&n.live?t.blocks[t.blocks.length-1]={kind:"text",text:s.text||""}:n&&n.kind==="text"?t.blocks[t.blocks.length-1]={kind:"text",text:n.text+(s.text||"")}:t.blocks.push({kind:"text",text:s.text||""});break}case"tool_start":{t.blocks.push({kind:"tool",step:{id:it(),tool:s.tool||"",argsSummary:s.args_summary,done:!1}});break}case"tool_result":{for(let n=t.blocks.length-1;n>=0;n--){const a=t.blocks[n];if(a.kind==="tool"&&a.step.tool===s.tool&&!a.step.done){t.blocks[n]={kind:"tool",step:{...a.step,done:!0,result:s.result,entityType:s.entity_type,entityId:s.entity_id,openURL:s.open_url}};break}}break}case"error":{t.blocks.push({kind:"error",code:s.code,message:s.message||"Something went wrong."});break}}}function vd(t){return t.map(s=>({id:it(),role:s.role,blocks:s.blocks.map(n=>n.kind==="tool"?{kind:"tool",step:{id:it(),tool:n.tool??"",argsSummary:n.args_summary,result:n.result,done:n.done,entityType:n.entity_type,entityId:n.entity_id,openURL:n.open_url}}:{kind:"text",text:n.text??""})}))}const Nd=b.memo(function({turn:s,onOpen:n,streaming:a=!1}){if(s.role==="user"){const i=s.blocks.map(l=>l.kind==="text"?l.text:"").join("");return e.jsx(ne.div,{initial:{opacity:0,y:6,scale:.98}
9,animate:{opacity:1,y:0,scale:1},transition:{type:"spring",stiffness:500,damping:36},className:"flex justify-end",children:e.jsx("div",{className:"max-w-[85%] rounded-2xl rounded-br-sm bg-sky-600 text-white px-3 py-2 text-[13px] whitespace-pre-wrap break-words",children:i})})}const r=s.blocks.length-1;return e.jsx("div",{className:"space-y-2",children:s.blocks.map((i,l)=>i.kind==="text"?i.text?a&&l===r?e.jsx(kd,{text:i.text,onOpen:n},l):e.jsx(Ya,{text:i.text,onOpen:n},l):null:i.kind==="tool"?e.jsx(_d,{step:i.step,onOpen:n},l):e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-red-50 border border-red-100 px-2.5 py-2 text-[12px] text-red-700",children:[e.jsx(ze,{className:"w-3.5 h-3.5 mt-0.5 shrink-0"}),e.jsx("span",{children:i.message})]},l))})});function kd({text:t,onOpen:s}){const[n,a]=b.useState(0);return b.useEffect(()=>{if(n>=t.length)return;const r=requestAnimationFrame(()=>{a(i=>i>=t.length?i:Math.min(t.length,i+Math.max(1,Math.ceil((t.length-i)/12))))});return()=>cancelAnimationFrame(r)},[n,t]),e.jsx(Ya,{text:t.slice(0,Math.min(n,t.length)),onOpen:s,caret:!0})}function _d({step:t,onOpen:s}){return e.jsxs(ne.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.16,ease:[.16,1,.3,1]},className:"rounded-md border border-slate-200 bg-slate-50/60 px-2.5 py-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11.5px] text-slate-600",children:[t.done?e.jsx(ne.span,{initial:{scale:.5,opacity:0},animate:{scale:1,opacity:1},transition:{type:"spring",stiffness:600,damping:24},className:"shrink-0 inline-flex",children:e.jsx(ke,{className:"w-3 h-3 text-emerald-600"})}):e.jsx(xe,{className:"w-3 h-3 animate-spin text-slate-400 shrink-0"}),e.jsx(to,{className:"w-3 h-3 text-slate-400 shrink-0"}),e.jsx("span",{className:"font-medium text-slate-700",children:Qa(t.tool)}),t.result&&e.jsxs("span",{className:"text-slate-400 truncate",title:t.result,children:["— ",t.result]})]}),t.done&&t.openURL&&(t.entityType==="campaign"||t.entityType==="automation")&&e.jsxs("button",{onClick:()=>s(t.openURL),className:"mt-1.5 h-7 px-2.5 rounded-md bg-white border border-slate-200 hover:border-sky-400 hover:text-sky-700 text-[12px] text-slate-700 inline-flex items-center gap-1.5 transition-colors",children:[e.jsx(Nt,{className:"w-3 h-3"}),"Open ",t.entityType==="campaign"?"campaign":"automation"," ","draft"]})]})}function Sd({pending:t,onDecide:s}){const n=t.risk==="send";return e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50/70 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[12px] font-medium text-amber-800",children:[e.jsx(qo,{className:"w-3.5 h-3.5"}),n?"Send this?":"Approve this action?"]}),e.jsxs("div",{className:"mt-1 text-[12px] text-slate-700",children:[e.jsx("span",{className:"font-medium",children:Qa(t.tool)}),t.argsSummary&&e.jsxs("span",{className:"text-slate-500",children:[" — ",t.argsSummary]})]}),e.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center gap-2",children:[e.jsxs("button",{onClick:()=>s("approve"),className:"h-7 px-3 rounded-md bg-slate-900 hover:bg-slate-800 text-white text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors",children:[e.jsx(ke,{className:"w-3 h-3"}),n?"Send":"Approve"]}),e.jsx("button",{onClick:()=>s("deny"),className:"h-7 px-3 rounded-md border border-slate-200 hover:border-slate-300 text-[12px] text-slate-700 transition-colors",children:"Skip"}),!n&&e.jsx("button",{onClick:()=>s("always_allow"),className:"h-7 px-2.5 rounded-md text-[12px] text-slate-500 hover:text-slate-800 transition-colors",children:"Always allow"})]})]})}const Cd=["Which leads went cold and need a follow-up?","Summarize replies in my inbox from this week","Draft a reply to my latest positive reply","How are my campaigns performing?"];function Ed({onPick:t}){return e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-center px-6 py-10",children:[e.jsx(kt,{className:"w-6 h-6 text-sky-600 mb-3"}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:"How can I help?"}),e.jsx("p",{className:"text-[12px] text-slate-500 mt-1 leading-relaxed max-w-[280px]",children:"Ask me to find contacts, check a campaign, draft a reply, or set up a draft campaign. I ask before changing anything."}),e.jsx("div",{className:"mt-4 w-full max-w-[320px] space-y-1.5",children:Cd.map(s=>e.jsx("button",{onClick:()=>t(s),className:"w-full text-left px-3 py-2 rounded-md border border-slate-200 hover:border-sky-300 hover:bg-sky-50/50 text-[12px] text-slate-600 hover:text-slate-900 transition-colors",children:s},s))}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center justify-center gap-x-3 gap-y-1.5 text-[10.5px] text-slate-400",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(tt,{combo:"mod+i",variant:"light"})," toggle"]}),e.jsxs("span",{className:"hidden sm:inline-flex items-center gap-1",children:[e.jsx(tt,{combo:"alt+n",variant:"light"})," new chat"]}),e.jsxs("span",{className:"hidden sm:inline-flex items-center gap-1",children:[e.jsx(tt,{combo:"alt+p",variant:"light"})," pop out"]}),e.jsxs("span",{className:"hidden sm:inline-flex items-center gap-1",children:[e.jsx(tt,{combo:"alt+m",variant:"light"})," minimize"]}),e.jsx("button",{onClick:()=>z.getState().setShortcutsModalOpen(!0),className:"underline decoration-dotted underline-offset-2 hover:text-slate-600 transition-colors",children:"all shortcuts"})]})]})}function Qa(t){return{search_contacts:"Searched contacts",get_contact:"Read contact",update_contact_fields:"Update contact",add_tag:"Add tag",remove_tag:"Remove tag",list_campaigns:"Listed campaigns",get_campaign_stats:"Campaign stats",create_campaign_draft:"Create campaign draft",create_automation_draft:"Create automation draft",create_task:"Create task",create_deal:"Create deal",list_threads:"Listed threads",get_thread:"Read thread",draft_reply:"Drafted reply",search_web:"Searched the web",fetch_url:"Fetched a page"}[t]||t.replace(/_/g," ")}function Ad(t){const s=t.match(/\/app\/(campaigns|contacts|automations)\/([0-9a-f-]{8,})/i);return s?`${s[1]==="campaigns"?"campaign":s[1]==="contacts"?"contact":"automation"}:${s[2]}`:""}function Td(t){try{const s=new URL(t,window.location.origin);return s.pathname+s.search}catch{return t}}function Md(t){const s=typeof t=="string"?new Date(t):t,n=Date.now()-s.getTime(),a=Math.round(n/1e3);if(a<60)return"just now";const r=Math.floor(a/60);if(r<60)return`${r}m ago`;const i=Math.floor(r/60);if(i<24)return`${i}h ago`;const l=Math.floor(i/24);return l<7?`${l}d ago`:s.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function Rd(){Cc();const[t,s]=k.useState(!1),{pathname:n}=Ve();k.useEffect(()=>s(!1),[n]);const a=k.useRef(null);return k.useLayoutEffect(()=>{a.current?.scrollTo({top:0,left:0})},[n]),e.jsxs("div",{className:"fixed inset-0 flex flex-col",children:[e.jsx(dl,{}),e.jsxs("div",{className:"relative z-10 flex flex-col h-full",children:[e.jsx(Nc,{}),e.jsx(jc,{}),e.jsx(Vl,{onMenu:()=>s(!0)}),e.jsxs("div",{className:"flex-1 flex min-h-0",children:[e.jsx(bc,{open:t,onClose:()=>s(!1)}),e.jsx("main",{className:"flex-1 min-w-0 bg-white overflow-hidden border-t border-slate-200/70 md:rounded-tl-2xl md:border-l",children:e.jsx(Zi,{scrollRef:a,children:e.jsx("div",{ref:a,className:"h-full overflow-auto",children:e.jsx(Sc,{children:e.jsx(k.Suspense,{fallback:e.jsx(Id,{}),children:e.jsx(cl,{children:e.jsx(ur,{})})})})})})})]})]}),e.jsx(Ac,{}),e.jsx(id,{}),e.jsx(fd,{})]})}function Id(){return e.jsxs("div",{className:"px-5 pt-5 space-y-4",role:"status","aria-label":"Loading",children:[e.jsx("div",{className:"h-6 w-56 bg-slate-100 rounded-md animate-pulse"}),e.jsx("div",{className:"h-3 w-40 bg-slate-100 rounded animate-pulse"}),e.jsx("div",{className:"h-56 bg-slate-100 rounded-md animate-pulse"})]})}function Ld({children:t}){const s=z(n=>n.setResolvedTheme);return k.useEffect(()=>{document.documentElement.classList.remove("dark"),s("light")},[s]),e.jsx(e.Fragment,{children:t})}function Pd(){return e.jsx(Ld,{children:e.jsx(Rd,{})})}function Dd(t){return JSON.stringify(t,(s,n)=>n instanceof Date?n.toISOString():n)}function ft(t,s){const n=k.useRef(s),a=k.useRef(null);n.current=s,k.useEffect(()=>{if(t!==void 0){const r=Dd(t);if(a.current===r)return;a.current=r,n.current(t)}},[t])}async function Od(){const t=[];let s=null;for(let n=0;n<20;n++){const a=await bi("",s,null,200);if(t.push(...a.data??[]),!a.pagination.has_more||!a.pagination.next_cursor)break;s=a.pagination.next_cursor}return t}function $d({children:t}){const{user:s,access:n,timezones:a}=Ye(),r=z(c=>c.setUser),i=z(c=>c.setAccess),l=z(c=>c.setTimezones),d=z(c=>c.setIsLoading),h=z(c=>c.setEmails),o=z(c=>c.setTags),x=$e({queryKey:["emails","list","directory"],queryFn:Od,staleTime:6e4,gcTime:1800*1e3});return ft(s,c=>{r(c),d(!1)}),ft(n,i),ft(a,l),ft(s?.tags,o),ft(x.data,h),e.jsx(e.Fragment,{children:t})}function zd(){const{isConnected:t,subscribeToChannel:s}=ia(),{user:n}=Ye(),a=n?.id??null,r=Ee(),i=z(m=>m.currentOrganization),l=z(m=>m.updateCampaign),d=z(m=>m.addUniboxEmail),h=z(m=>m.incrementUnseenCount),o=z(m=>m.updateDeal),x=z(m=>m.setSubscription),c=k.useCallback(m=>
9{for(const w of m)r.invalidateQueries({queryKey:w})},[r]),f=k.useCallback(m=>{const E=String(m.event_type??m.type??m._event??"").replace(/[.:\s-]+/g,"_").toUpperCase();if(!E||E.startsWith("PRESENCE")||E==="RATE_LIMITED"||E.startsWith("LIVE_"))return;const _=C=>{const u=m[C];return typeof u=="string"&&u.length>0?u:null},M=(...C)=>C.some(u=>E.includes(u)),S=_("campaign_id"),j=_("contact_id"),I=_("deal_id"),P=_("thread_id"),R=_("email_id")??_("message_id");if(M("AI_DRAFT")){c([["unibox"],["unibox","overview"],["unibox","agent-drafts"]]),P&&c([["unibox","thread",P]]);return}if(M("EMAIL_RECEIVED","NEW_EMAIL","INBOX_NEW")){d(m),h(),c([["unibox"],["analytics"],["emails","list"]]),P&&c([["unibox","thread",P]]),R&&c([["unibox","email",R]]);return}if(M("EMAIL_UPDATED","EMAIL_DELETED","INBOX_UPDATE")){c([["unibox"],["analytics"]]),P&&c([["unibox","thread",P]]),R&&c([["unibox","email",R]]);return}if(M("CREDITS_LOW")){const C=typeof m.balance=="number"?m.balance:null;se(C!==null?`AI credits are running low: ${C} left. Top up or enable auto top-up in Billing.`:"AI credits are running low. Top up or enable auto top-up in Billing.",{icon:"⚠️",duration:8e3,id:"credits-low"}),c([["subscription","credits"]]);return}if(M("CREDITS_CHANGED")){c([["subscription","credits"]]);return}if(M("FORM_SUBMISSION")){c([["forms"],["contacts"]]);return}if(M("AI_RESEARCH","RESEARCH_PROGRESS")){c([["contacts"]]),j&&c([["contacts",j],["contacts",j,"research"]]);return}if(M("CONTACT")){c([["contacts"],["campaigns","list"],["analytics"],["organizations","limits"]]),j&&c([["contacts",j]]);return}if(E==="CAMPAIGN_DELETED"&&S){_("user_id")!==a&&no({id:S,name:_("name")??""}),r.removeQueries({queryKey:["campaigns",S]}),r.removeQueries({queryKey:["analytics","campaigns",S]}),c([["campaigns","list"],["analytics"],["contacts"]]);return}if(E==="PAGE_HIT"){j&&c([["contacts",j,"timeline"]]);return}if(M("CAMPAIGN","EMAIL_SENT","EMAIL_OPENED","EMAIL_CLICKED","EMAIL_REPLIED","EMAIL_BOUNCED","TASK_PROGRESS")){if(S){const C=_("status");l(S,C?{status:C}:{}),c([["campaigns",S],["campaigns",S,"logs"],["analytics","campaigns",S],["analytics","campaigns",S,"daily"],["analytics","campaigns",S,"hourly"]])}c([["campaigns","list"],["analytics"],["contacts"]]),j&&c([["contacts",j]]);return}if(E==="ERROR"){const C=m.data,u=typeof C?.title=="string"&&C.title?C.title:_("message")??"Something went wrong",g=typeof C?.message=="string"?C.message:"";se.error(g?`${u}: ${g}`:u,{id:`email-error-${_("task_id")??_("email_id")??"general"}`,duration:8e3}),c([["emails","list"],["unibox"]]);return}if(M("ACCOUNT","EMAIL_STATUS","EMAIL_ERROR","WARMUP")){const C=_("email_account_id");C&&c([["emails",C,"sync"]]),c([["emails","list"],["analytics","accounts"],["analytics","warmup"],["analytics","dashboard"]]);return}if(M("DEAL")){I&&o(I,m),c([["crm","deals"],["crm","pipelines"],["contacts"]]);return}if(M("PIPELINE","STAGE")){c([["crm","pipelines"],["crm","deals"]]);return}if(M("CRM_TASK","TASK")){c([["crm","tasks"],["crm","deals"]]);return}if(M("SUBSCRIPTION","PLAN","BILLING","LIMIT")){x(m),c([["subscription"],["organizations","current"],["organizations","limits"],["auth","me"]]);return}if(M("MEMBER","INVITATION","ORGANIZATION","SETTINGS")){c([["organizations"],["organizations","current"],["organizations","invitations"],["auth","me"]]);return}if(M("API_KEY")){c([["api-keys"]]);return}if(M("MEETING","BOOKING")){c([["meetings"],["meetings","summary"],["integrations","bookings"]]),j&&c([["contacts",j,"timeline"]]);return}if(M("NOTIFICATION")){c([["notifications","feed"]]);return}if(M("AUTOMATION")){c([["automations"]]);const C=_("automation_id");C&&c([["automations",C],["automations",C,"runs"]]);return}if(M("INTEGRATION","CONNECTION")){c([["integrations","connections"],["integrations","catalog"],["integrations","bookings"]]);const C=_("connection_id");C&&c([["integrations","connection",C]]);return}if(M("TEMPLATE")){c([["templates"]]);return}if(M("WEBHOOK")){c([["webhooks","list"],["webhooks","deliveries"]]);return}if(M("AUDIT")){c([["audit"]]);const C=_("entity_type")??"",u=_("entity_id");u&&_("user_id")===a&&so(C,u);const y={contact:[["contacts"],["segments"]],suppression:[["suppressions"],["contacts"],["analytics"]],segment:[["segments"],["contacts","list"]],form:[["forms"]],campaign:[["campaigns"],["analytics"]],step:[["campaigns"]],email_account:[["emails"],["analytics","accounts"]],api_key:[["api-keys"]],webhook:[["webhooks"],["
9integrations","connections"]],template:[["templates"]],organization:[["organizations"]],org_risk:[["organizations"],["emails"],["analytics"]],organization_member:[["organizations"],["organizations","members"]],invitation:[["organizations","invitations"]],team:[["teams"]],role:[["organizations"]],automation:[["automations"]],integration:[["integrations","connections"]],lead_sync_source:[["lead-sync","sources"]],meeting:[["meetings"],["meetings","summary"]],subscription:[["subscription"],["organizations","limits"]],referral:[["subscription","referral"]],referral_credit:[["subscription","referral"],["subscription"]],credit_purchase:[["subscription","credits"],["subscription"]],credit_grant:[["subscription","credits"],["subscription"]],ai_session:[["ai","sessions"]],ai_skill:[["ai","skills"]],mcp_server:[["ai","connections"]],advisor_finding:[["advisor"]],settings:[["organizations","current"],["website-tracking"]],org_archive:[["organizations","exports"],["organizations","imports"]],unibox:[["unibox"]],crm_note:[["crm"],["contacts"]],crm_pipeline:[["crm","pipelines"],["crm","deals"]],crm_stage:[["crm","pipelines"],["crm","deals"]],crm_deal:[["crm","deals"],["contacts"]],crm_task:[["crm","tasks"],["crm","deals"]],warmup_routing_rule:[["analytics","warmup"]],cloud_link:[["cloud-link"],["emails"]],pool_link:[["pool-link"],["emails"]],folder:[["auth","me"]],tag:[["auth","me"]],category:[["auth","me"],["contacts"]]}[C];y&&c(y),u&&C==="contact"&&c([["contacts",u]]),u&&C==="segment"&&c([["segments",u]]),u&&C==="form"&&c([["forms",u]]),u&&C==="campaign"&&(c([["campaigns",u],["segments","campaign",u]]),r.invalidateQueries({predicate:T=>{const[v,Q,ae]=T.queryKey;return v==="contacts"&&Q==="list"&&!!ae?.campaign_ids?.includes(u)}})),u&&C==="automation"&&c([["automations",u]]);return}if(M("DANGER","DELETION")){c([["dangerzone"],["auth","me"],["organizations","current"]]);return}c([["analytics","dashboard"],["auth","me"]])},[d,h,c,a,r,x,l,o]);k.useEffect(()=>{if(!t||!n?.id)return;const m=`user:${n.id}`;return s(m,"*",f)},[t,n?.id,s,f]),k.useEffect(()=>{if(!t||!i?.id)return;const m=`org:${i.id}`;return s(m,"*",f)},[t,i?.id,s,f])}async function Fd(){return await be({method:"GET",url:"/unibox/count",authorization:!0})}function Ud({enabled:t=!0}={}){return $e({queryKey:["unibox","unseen-count"],queryFn:()=>Fd(),staleTime:6e4,enabled:t})}const qd=500,Kd=2e3;function Bd({children:t}){const{isConnected:s,reconnectAttempt:n,joinChannel:a,leaveChannel:r}=ia(),{user:i}=Ye(),l=z(j=>j.currentOrganization),d=z(j=>j.setConnectionStatus),h=z(j=>j.setReconnectAttempt),o=z(j=>j.setConnectionQuality),x=z(j=>j.addJoinedChannel),c=z(j=>j.removeJoinedChannel),f=z(j=>j.setUnseenCount),m=z(j=>j.wsLatencyMs),w=Ee(),E=k.useRef(!1),_=k.useRef(null),M=k.useRef(0);k.useEffect(()=>{if(!s){E.current&&_.current===null&&(_.current=Date.now());return}if(E.current&&_.current!==null){const j=Date.now()-_.current,I=Date.now()-M.current;j>5e3&&I>3e4&&(M.current=Date.now(),w.invalidateQueries())}E.current=!0,_.current=null},[s,w]),k.useEffect(()=>{s?(d("connected"),o("good"),h(0)):n>0?(d("connecting"),o("poor"),h(n)):(d("disconnected"),o("disconnected"))},[s,n,d,o,h]),k.useEffect(()=>{if(s&&i?.id){const j=`user:${i.id}`;return a(j),x(j),()=>{r(j),c(j)}}},[s,i?.id,a,r,x,c]),k.useEffect(()=>{if(!s||!l?.id)return;const j=`org:${l.id}`;return a(j),x(j),()=>{r(j),c(j)}},[s,l?.id,a,r,x,c]),k.useEffect(()=>{if(s){if(m===null){o("good");return}m>Kd?o("poor"):m>qd?o("degraded"):o("good")}},[s,m,o]);const S=Ud({enabled:!!l});return k.useEffect(()=>{const j=S.data?.count;typeof j=="number"&&f(j)},[S.data,f]),zd(),e.jsx(Hr,{children:t})}function Wd(){const t=Le(),s=ao(),n=z(o=>o.setOrganizations),a=z(o=>o.setCurrentOrganization),r=z(o=>o.currentOrganization),{mutate:i}=ga({mode:"sync"}),l=k.useRef(!1),d=k.useRef(null),h=k.useRef(null);return k.useEffect(()=>{if(s.isPending)return;const o=s.data??[];if(n(o),(r?o.some(f=>f.id===r.id):!1)&&r){d.current=null,h.current!==r.id&&(h.current=r.id,i(r.id,{onError:()=>{h.current=null}}));return}if(o.length===0){const f="empty";if(d.current===f)return;d.current=f,t("/select-org",{replace:!0});return}if(o.length===1){if(l.current)return;l.current=!0;const f=o[0];i(f.id,{onSuccess:()=>{h.current=f.id,a(f)},onError:()=>t("/select-org",{replace:!0}),onSettled:()=>{l.current=!1}});return}const c=`multi:${o.map(f=>f.id).join(",")}`;d.current!==c&&(d.current=c,t("/select-org",{replace:!0}))},[s.isPending,s.data,r,n,a,i,t]),null}async function Hd(t,s){return await be({method:"PATCH",url:`/tags/${t}`,data:s,authorization:!0})}async function Gd(t){return await be({method:"DELETE",url:`/tags/${t}`,authorization:!0})}const Kt=["#94a3b8","#38bdf8","#10b981","#f59e0b","#ef4444","#a855f7","#e
9c4899","#14b8a6"];function Vd({value:t,onChange:s}){return e.jsx("div",{className:"flex items-center gap-1.5",children:Kt.map(n=>{const a=t.toLowerCase()===n.toLowerCase();return e.jsx("button",{type:"button",onClick:()=>s(n),"aria-label":`Color ${n}`,"aria-pressed":a,className:Y("size-5 rounded-full flex items-center justify-center transition-shadow",a?"ring-2 ring-slate-900 ring-offset-1 ring-offset-white":"hover:ring-2 hover:ring-slate-300 hover:ring-offset-1 hover:ring-offset-white"),children:e.jsx("span",{className:"size-4 rounded-full",style:{backgroundColor:n}})},n)})})}function Xa({title:t,onTitleChange:s,color:n,onColorChange:a,onSubmit:r,onCancel:i,actions:l}){return e.jsxs("div",{className:"px-4 py-3 bg-slate-50/60 space-y-2.5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium w-12 shrink-0",children:"Name"}),e.jsx(qe,{value:t,onChange:s,placeholder:"Name…",autoFocus:!0,className:"flex-1",onKeyDown:d=>{d.key==="Enter"&&r(),d.key==="Escape"&&i()}})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium w-12 shrink-0",children:"Color"}),e.jsx(Vd,{value:n,onChange:a})]}),e.jsx("div",{className:"flex items-center gap-1.5 pt-1.5",children:l})]})}function Ja({open:t,onClose:s,eyebrow:n,subtitle:a,items:r,onCreate:i,onUpdate:l,onDelete:d,addCta:h,max:o=50}){const[x,c]=b.useState(!1),[f,m]=b.useState(""),[w,E]=b.useState(Kt[0]),[_,M]=b.useState(!1);b.useEffect(()=>{t||(c(!1),m(""))},[t]),b.useEffect(()=>{x&&E(Kt[r.length%Kt.length])},[x,r.length]);async function S(){const I=f.trim();if(I.length<1){se.error("Name is required");return}M(!0);try{await se.promise(i(I,w),{loading:"Creating…",success:"Created",error:P=>je(P)}),m(""),c(!1)}catch{}finally{M(!1)}}const j=b.useMemo(()=>[...r].sort((I,P)=>I.position-P.position),[r]);return e.jsx(ge,{children:t&&e.jsx(ne.div,{initial:{opacity:0}
9,animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:s,className:"fixed inset-0 z-[110] flex items-center justify-center bg-slate-900/30 backdrop-blur-[2px] px-4",children:e.jsxs(ne.div,{initial:{y:8,opacity:0},animate:{y:0,opacity:1},exit:{y:8,opacity:0},transition:{duration:.16},onClick:I=>I.stopPropagation(),className:"w-full max-w-[480px] rounded-lg bg-white border border-slate-200 shadow-[0_24px_48px_-12px_rgba(15,23,42,0.18),0_8px_16px_-8px_rgba(15,23,42,0.1)] overflow-hidden flex flex-col max-h-[80dvh]",children:[e.jsxs("div",{className:"h-12 px-4 border-b border-slate-200 flex items-center gap-2.5 shrink-0",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium",children:n}),e.jsx("div",{className:"h-4 w-px bg-slate-200"}),e.jsx("span",{className:"text-[12px] text-slate-600 truncate",children:a}),e.jsx("button",{type:"button",onClick:s,"aria-label":"Close",className:"ml-auto size-7 rounded-md text-slate-500 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center justify-center transition-colors",children:e.jsx(ve,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[j.length===0&&!x&&e.jsxs("div",{className:"px-5 py-10 text-center",children:[e.jsx("p",{className:"text-[12.5px] text-slate-700 font-medium mb-1",children:"Nothing here yet"}),e.jsx("p",{className:"text-[11.5px] text-slate-400",children:"Add your first to get started."})]}),e.jsxs("div",{className:"divide-y divide-slate-200/60",children:[j.map(I=>e.jsx(Yd,{item:I,onUpdate:l,onDelete:d},I.id)),x&&e.jsx(Xa,{title:f,onTitleChange:m,color:w,onColorChange:E,onSubmit:S,onCancel:()=>{c(!1),m("")},actions:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>{c(!1),m("")},className:"ml-auto h-7 px-2.5 rounded-md text-[12px] text-slate-700 hover:text-slate-900 hover:bg-slate-100 transition-colors",children:"Cancel"}),e.jsxs("button",{type:"button",onClick:S,disabled:_,className:"h-7 px-2.5 rounded-md bg-slate-900 hover:bg-slate-800 text-white text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors disabled:opacity-60",children:[_?e.jsx(xe,{className:"w-3 h-3 animate-spin"}):e.jsx(ke,{className:"w-3 h-3"}),"Add"]})]})})]})]}),e.jsxs("div",{className:"px-3 h-12 border-t border-slate-200 flex items-center gap-1.5 shrink-0",children:[!x&&j.length<o&&e.jsxs("button",{type:"button",onClick:()=>c(!0),className:"h-7 px-2.5 rounded-md text-[12px] text-slate-700 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center gap-1.5 transition-colors",children:[e.jsx(os,{className:"w-3 h-3"}),h]}),j.length>=o&&e.jsxs("span",{className:"text-[11px] text-slate-400",children:["Maximum of ",o," items reached"]}),e.jsx("button",{type:"button",onClick:s,className:"ml-auto h-7 px-2.5 rounded-md bg-slate-900 hover:bg-slate-800 text-white text-[12px] font-medium transition-colors",children:"Done"})]})]},"card")},"overlay")})}function Yd({item:t,onUpdate:s,onDelete:n}){const a=Bs(),[r,i]=b.useState(!1),[l,d]=b.useState(t.title),[h,o]=b.useState(t.color),[x,c]=b.useState(!1),[f,m]=b.useState(!1);b.useEffect(()=>{r||(d(t.title),o(t.color))},[r,t.title,t.color]);const w=l.trim()!==t.title||h!==t.color;async function E(){if(!w){i(!1);return}const M=l.trim();if(M.length<1){se.error("Name is required");return}c(!0);try{await se.promise(s(t.id,{title:M!==t.title?M:void 0,color:h!==t.color?h:void 0}),{loading:"Saving…",success:"Saved",error:S=>je(S)}),i(!1)}catch{}finally{c(!1)}}async function _(){m(!0);try{await se.promise(n(t.id),{loading:"Deleting…",success:"Deleted",error:M=>je(M)})}catch{}finally{m(!1),a?.setShow(!1)}}return r?e.jsx(Xa,{title:l,onTitleChange:d,color:h,onColorChange:o,onSubmit:E,onCancel:()=>i(!1),actions:e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>a?.show(`Delete "${t.title}"?`,_),disabled:f,className:"h-7 px-2.5 rounded-md text-[12px] text-red-600 hover:text-white hover:bg-red-600 font-medium inline-flex items-center gap-1.5 transition-colors disabled:opacity-60",children:[f?e.jsx(xe,{className:"w-3 h-3 animate-spin"}):e.jsx(un,{className:"w-3 h-3"}),"Delete"]}),e.jsx("button",{type:"button",onClick:()=>i(!1),className:"ml-auto h-7 px-2.5 rounded-md text-[12px] text-slate-700 hover:text-slate-900 hover:bg-slate-100 transition-colors",children:"Cancel"}),e.jsxs("button",{type:"button",onClick:E,disabled:x||!w,className:"h-7 px-2.5 rounded-md bg-slate-900 hover:bg-slate-800 text-white text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors disabled:opacity-60",children:[x?e.jsx(xe,{className:"w-3 h-3 animate-spin"}):e.jsx(ke,{className:"w-3 h-3"}),"Save"]})]})}):e.jsxs("div",{className:"group px-3 h-10 flex items-center gap-2.5 hover:bg-slate-50/80 transition-colors",children:[e.jsx("span",{"aria-hidden":!0,
9className:"size-2 rounded-full shrink-0",style:{backgroundColor:t.color}}),e.jsx("span",{className:"text-[12.5px] text-slate-900 font-medium truncate flex-1",children:t.title}),e.jsxs("div",{className:"flex items-center gap-0.5 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity",children:[e.jsx("button",{type:"button",onClick:()=>i(!0),className:"size-6 rounded text-slate-400 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center justify-center transition-colors","aria-label":"Edit",children:e.jsx(ta,{className:"w-3 h-3"})}),e.jsx("button",{type:"button",onClick:()=>a?.show(`Delete "${t.title}"?`,_),disabled:f,className:"size-6 rounded text-slate-400 hover:text-red-600 hover:bg-red-50 inline-flex items-center justify-center transition-colors disabled:opacity-50","aria-label":"Delete",children:f?e.jsx(xe,{className:"w-3 h-3 animate-spin"}):e.jsx(un,{className:"w-3 h-3"})})]})]})}function Qd(){const t=Ye(),s=Ee();function n(a){s.setQueryData(["auth","me"],r=>r&&a(r))}return e.jsx(Ja,{open:t?.tagsEdit??!1,onClose:()=>t?.setTagsEdit(!1),eyebrow:"Tags",subtitle:"Label email accounts by purpose, region or audience",addCta:"New tag",items:t?.user.tags??[],onCreate:async(a,r)=>{const i=await Ai(a,r);n(l=>({...l,tags:[...l.tags,i]}))},onUpdate:async(a,r)=>{const i=await Hd(a,r);n(l=>({...l,tags:l.tags.map(d=>d.id===i.id?i:d)}))},onDelete:async a=>{await Gd(a),n(r=>({...r,tags:r.tags.filter(i=>i.id!==a)}))}})}async function Xd(t,s){return await be({method:"POST",url:"/folders",data:s?{title:t,color:s}:{title:t},authorization:!0})}async function Jd(t,s){return await be({method:"PATCH",url:`/folders/${t}`,data:s,authorization:!0})}async function Zd(t){return await be({method:"DELETE",url:`/folders/${t}`,authorization:!0})}function eu(){const t=Ye(),s=Ee();function n(a){s.setQueryData(["auth","me"],r=>r&&a(r))}return e.jsx(Ja,{open:t?.foldersEdit??!1,onClose:()=>t?.setFoldersEdit(!1),eyebrow:"Folders",subtitle:"Group campaigns by goal, audience or region",addCta:"New folder",items:t?.user.folders??[],onCreate:async(a,r)=>{const i=await Xd(a,r);n(l=>({...l,folders:[...l.folders,i]}))},onUpdate:async(a,r)=>{const i=await Jd(a,r);n(l=>({...l,folders:l.folders.map(d=>d.id===i.id?i:d)}))},onDelete:async a=>{await Zd(a),n(r=>({...r,folders:r.folders.filter(i=>i.id!==a)}))}})}async function tu(t){return await be({method:"POST",url:"/emails/onboarding/smtp-imap",data:t,authorization:!0})}async function su(t){return await be({method:"POST",url:"/emails/onboarding/oauth/start",data:{provider:t},authorization:!0})}async function nu(){return await be({method:"GET",url:"/emails/allowance",authorization:!0})}const Za=["emails","allowance"];function er(t=!0){return $e({queryKey:Za,queryFn:nu,enabled:t,staleTime:15e3})}function Un(t){return!!t&&t.allowance!=null&&(t.remaining??0)<=0}const au=[.22,1,.36,1];function bt(t,s){const n=Ue[t].sendsPerDay;return!Number.isFinite(n)||n<=0?null:Math.ceil(n/Math.max(1,s))}function ru(t,s){const n=t.allowance??Number.POSITIVE_INFINITY;for(const a of st){if(Wt(a)<=Wt(s))continue;const r=bt(a,t.sends_per_mailbox);if(r==null||r>n)return a}return null}function tr(t){return t<=1?"one mailbox for every send a day":`one mailbox for every ${t} sends a day`}function iu(t){const s=Math.ceil(t*1.5),n=s>=1e3?500:s>=100?50:10;return Math.ceil(s/n)*n}function ou({open:t,onClose:s,allowance:n,reached:a,currentPlan:r}){const i=b.useRef(null);return b.useEffect(()=>{if(!t)return;const l=document.activeElement;i.current?.focus();const d=h=>{h.key==="Escape"&&(document.querySelector("[role='alertdialog']")||(h.stopPropagation(),s()))};return document.addEventListener("keydown",d,!0),()=>{document.removeEventListener("keydown",d,!0),l?.focus?.()}},[t,s]),_t.createPortal(e.jsx(ge,{children:t&&e.jsx(ne.div,{initial:{opacity:0}
9,animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onMouseDown:l=>{l.stopPropagation(),s()},onClick:l=>l.stopPropagation(),className:"fixed inset-0 z-[140] flex items-center justify-center bg-slate-900/40 backdrop-blur-[2px] px-4",children:e.jsxs(ne.div,{ref:i,tabIndex:-1,role:"dialog","aria-modal":"true","aria-label":"Mailbox allowance","data-floating":!0,"data-nested-modal":!0,initial:{y:10,opacity:0,scale:.98},animate:{y:0,opacity:1,scale:1},exit:{y:10,opacity:0,scale:.98},transition:{duration:.2,ease:au},onMouseDown:l=>l.stopPropagation(),className:"w-full max-w-[540px] rounded-lg bg-white border border-slate-200 shadow-[0_24px_48px_-12px_rgba(15,23,42,0.22),0_8px_16px_-8px_rgba(15,23,42,0.12)] overflow-hidden flex flex-col max-h-[88dvh] outline-none",children:[e.jsxs("div",{className:"h-12 px-4 border-b border-slate-200 flex items-center gap-2.5 shrink-0",children:[e.jsx(Yr,{className:"w-3.5 h-3.5 text-slate-500"}),e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium",children:"Mailbox allowance"}),e.jsx("button",{type:"button",onClick:s,"aria-label":"Close",className:"ml-auto size-7 rounded-md text-slate-500 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center justify-center transition-colors",children:e.jsx(ve,{className:"w-3.5 h-3.5"})})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:n?e.jsx(lu,{allowance:n,reached:!!a,currentPlan:r,onClose:s}):e.jsx("div",{className:"p-6 flex items-center justify-center text-slate-400",children:e.jsx(xe,{className:"w-4 h-4 animate-spin"})})})]},"allowance-card")},"allowance-overlay")}),document.body)}function lu({allowance:t,reached:s,currentPlan:n,onClose:a}){const r=da(),i=t.allowance,l=i!=null&&(t.remaining??0)<=0,d=i?Math.min(100,Math.round(t.used/i*100)):0,h=d>=90?"rose":d>=70?"amber":"sky",o=t.plan_name||rt(n).label,x=t.paid?ru(t,n):null,c=s?l?"You've reached your mailbox allowance":"This connect would pass your mailbox allowance":i==null?"This workspace holds unlimited mailboxes":"Your mailbox allowance";function f(m,w,E){a(),r.open({feature:m,minPlan:w,blurb:E,bullets:st.filter(_=>_!=="enterprise").map(_=>{const M=bt(_,t.sends_per_mailbox);return`${Ue[_].label}: ${M==null?"unlimited":M.toLocaleString()} mailboxes`})})}return e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-[15px] font-semibold text-slate-900 leading-snug",children:c}),e.jsx("p",{className:"text-[12.5px] text-slate-600 mt-1 leading-relaxed",children:e.jsx(cu,{a:t,planLabel:o})})]}),i!=null&&e.jsxs("div",{className:"rounded-md border border-slate-200 p-3",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2 mb-1.5",children:[e.jsx("span",{className:"text-[12px] text-slate-700 font-medium",children:"Connected mailboxes"}),e.jsxs("span",{className:"text-[11.5px] font-mono tabular-nums text-slate-700",children:[t.used.toLocaleString(),e.jsxs("span",{className:"text-slate-400",children:[" / ",i.toLocaleString()]})]})]}),e.jsx(Et,{frac:d/100,tone:h,height:4}),e.jsx("div",{className:"text-[10.5px] text-slate-400 mt-1.5",children:t.basis==="fair_use"&&t.plan_daily_sends!=null?`${t.plan_daily_sends.toLocaleString()} sends a day on ${o}, ${tr(t.sends_per_mailbox)}`:t.basis==="override"?"Raised for this workspace by an approved request":t.basis==="free"?"Free workspace":`Set by ${o}`})]}),t.paid?e.jsxs(e.Fragment,{children:[x&&e.jsxs("button",{type:"button",onClick:()=>f("More mailboxes",x,`${Ue[x].label} includes ${Ue[x].sendsPerDay.toLocaleString()} sends a day, which holds ${bt(x,t.sends_per_mailbox)?.toLocaleString()??"unlimited"} mailboxes under fair use.`),className:"w-full rounded-md border border-slate-200 hover:border-slate-300 hover:bg-slate-50 p-3 text-left flex items-center gap-3 transition-colors group",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-[12.5px] font-medium text-slate-900",children:["Move to ",Ue[x].label," for"," ",bt(x,t.sends_per_mailbox)?.toLocaleString()??"unlimited"," mailboxes"]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:[Ue[x].sendsPerDay.toLocaleStr
9ing()," sends a day. Prorated, takes effect immediately."]})]}),e.jsx(jt,{className:"w-4 h-4 text-slate-300 group-hover:text-slate-500 shrink-0"})]}),i!=null&&e.jsx(du,{a:t,cap:i})]}):e.jsxs("div",{className:"rounded-md border border-sky-200 bg-sky-50 p-3",children:[e.jsx("p",{className:"text-[12.5px] font-medium text-sky-900",children:"A paid plan holds one mailbox for every send a day it includes"}),e.jsx("ul",{className:"mt-1.5 space-y-0.5",children:st.filter(m=>m!=="enterprise").map(m=>{const w=bt(m,t.sends_per_mailbox);return e.jsxs("li",{className:"text-[12px] text-sky-800 flex items-center gap-1.5",children:[e.jsx(ke,{className:"w-3 h-3 text-sky-600 shrink-0"}),e.jsx("span",{className:"font-medium",children:Ue[m].label}),e.jsxs("span",{className:"text-sky-700/80",children:[Ue[m].sendsPerDay.toLocaleString()," sends a day, ",w==null?"unlimited":w.toLocaleString()," mailboxes"]})]},m)})}),e.jsxs("button",{type:"button",onClick:()=>f("More mailboxes","starter",`A free workspace holds ${i?.toLocaleString()??"10"} mailboxes. A paid plan holds one for every send a day it includes, and more on request.`),className:"mt-2.5 h-7 px-3 rounded-md bg-slate-900 hover:bg-slate-800 text-white text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors",children:[e.jsx(ls,{className:"w-3 h-3"}),"Choose a plan"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsxs(Ce,{to:"/app/settings/limits",onClick:a,className:"text-[11.5px] text-slate-500 hover:text-slate-900 inline-flex items-center gap-1 transition-colors",children:["All limit requests",e.jsx(ot,{className:"w-3 h-3"})]}),e.jsxs("a",{href:"https://docs.controlgtm.com/guides/mailboxes/#mailbox-allowance",target:"_blank",rel:"noreferrer",className:"text-[11.5px] text-slate-500 hover:text-slate-900 inline-flex items-center gap-1 transition-colors",children:["How fair use works",e.jsx(jt,{className:"w-3 h-3"})]})]})]})}function cu({a:t,planLabel:s}){switch(t.basis){case"unlimited":return e.jsx(e.Fragment,{children:"There is no cap on mailboxes here. Connect as many as you need."});case"free":return e.jsxs(e.Fragment,{children:["A free workspace holds up to ",t.allowance?.toLocaleString()," mailboxes for warmup. Sending, and mailboxes without a fixed cap, come with a plan."]});case"override":return e.jsxs(e.Fragment,{children:["This workspace's allowance was raised to ",t.allowance?.toLocaleString()," mailboxes by an approved request. Ask again when you need more."]});case"plan":return e.jsxs(e.Fragment,{children:[s," holds ",t.allowance?.toLocaleString()," mailboxes. Ask for more below or move to a bigger plan."]});default:return e.jsxs(e.Fragment,{children:["Mailboxes are unlimited on ",s," under fair use: ",tr(t.sends_per_mailbox)," the plan includes. ",t.plan_daily_sends?.toLocaleString()," sends a day holds ",t.allowance?.toLocaleString()," ","mailboxes, far more than safe sending ever needs. Need more? Ask below and we usually answer within a business day."]})}}function du({a:t,cap:s}){const n=Ee(),a=Bs(),r=mr(),[i,l]=b.useState(iu(s)),[d,h]=b.useState(""),o=t.pending_request??null,x=()=>{n.invalidateQueries({queryKey:Za}),n.invalidateQueries({queryKey:["organizations"]}),n.invalidateQueries({queryKey:["app","organizations"]})},c=at({mutationFn:()=>co(r.id,{field:"max_email_accounts",requested:i,reason:d.trim()}),onSuccess:()=>{se.success("Request sent. We usually answer within a business day."),h(""),x()},onError:w=>se.error(je(w))}),f=at({mutationFn:w=>uo(w),onSuccess:()=>{se.success("Request withdrawn"),x()},onError:w=>se.error(je(w))});if(o)return e.jsx("div",{className:"rounded-md border border-amber-200 bg-amber-50 p-3",children:e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx(is,{className:"w-3.5 h-3.5 text-amber-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-[12.5px] font-medium text-amber-900",children:["You asked for ",o.requested.toLocaleString()," mailboxes on"," ",new Date(o.submitted_at).toLocaleDateString()]}),e.jsx("p",{className:"text-[11.5px] text-amber-800/90 mt-0.5 leading-relaxed",children:"It is waiting for review. Once approved the new allowance applies here straight away, and anything you could not connect in the meantime goes through on a retry."}),e.jsx("button",{type:"button",disabled:f.isPending,onClick:()=>a.show("Withdraw this request? You can submit a new one at any time.",async()=>{await f.mutateAsync(o.id)}),className:"mt-2 h-6 px-2 rounded text-[11px] text-amber-900 hover:bg-amber-100 inline-flex items-center gap-1 transition-colors disabled:opacity-50",children:"Withdraw request"})]})]})});const m=Number.isInteger(i)&&i>s&&d.trim().length>=10;return e.jsxs("form",{onSubmit:w=>{w.preventDefault(),!(!m||!r?.id)&&c.mutate()},className:"rounded-md border border-slate-200 p-3 space-y-2.5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[12.5px] font-medium text-slate-900",children:"Request an increase"}),e.jsx("p",{className:"text-[11.5px] text-slate-500 mt-0.5 leading-relaxed",children:"Keep your plan and ask for a higher allowance. Say how many mailboxes you need and what you are sending, so review takes one pass."})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium w-20 shrink-0",children:"Mailboxes"}),e.jsx($r,{min:s+1,value:i,onChange:l,className:"w-32"}),e.jsxs("span",{className:"text-[11px] text-slate-400",children:["now ",s.toLocaleStr
vendor: 22,520 bytes, lines 9-18
9ing()]})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium w-20 shrink-0 pt-1.5",children:"Why"}),e.jsx("textarea",{value:d,onChange:w=>h(w.target.value),rows:2,placeholder:"Onboarding 40 client domains, 25 mailboxes each, at 5 to 10 sends a day per mailbox.",className:"flex-1 min-w-0 rounded-md border border-slate-200 bg-white px-2.5 py-1.5 text-[12.5px] text-slate-900 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100 transition-colors resize-none"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[10.5px] text-slate-400",children:i<=s?`Ask for more than ${s.toLocaleString()}`:d.trim().length<10?"A sentence on what you are sending helps":"Reviewed by a person, usually within a business day"}),e.jsxs("button",{type:"submit",disabled:!m||c.isPending||!r?.id,className:Y("h-7 px-3 rounded-md text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors","bg-slate-900 hover:bg-slate-800 text-white disabled:opacity-50 disabled:cursor-not-allowed"),children:[c.isPending?e.jsx(xe,{className:"w-3 h-3 animate-spin"}):e.jsx(ot,{className:"w-3 h-3"}),"Send request"]})]})]})}const qn=50;async function uu(t){return await be({method:"POST",url:"/emails/onboarding/smtp-imap/bulk",data:{accounts:t},authorization:!0,timeout:18e4})}var Bt={exports:{}};var mu=Bt.exports,Kn;function pu(){return Kn||(Kn=1,(function(t,s){((n,a)=>{t.exports=a()})(mu,function n(){var a=typeof self<"u"?self:typeof window<"u"?window:a!==void 0?a:{},r,i=!a.document&&!!a.postMessage,l=a.IS_PAPA_WORKER||!1,d={},h=0,o={};function x(u){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},(function(g){var y=P(g);y.chunkSize=parseInt(y.chunkSize),g.step||g.chunk||(y.chunkSize=null),this._handle=new E(y),(this._handle.streamer=this)._config=y}).call(this,u),this.parseChunk=function(g,y){var T=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0<T){let Q=this._config.newline;Q||(v=this._config.quoteChar||'"',Q=this._handle.guessLineEndings(g,v)),g=[...g.split(Q).slice(T)].join(Q)}this.isFirstChunk&&C(this._config.beforeFirstChunk)&&(v=this._config.beforeFirstChunk(g))!==void 0&&(g=v),this.isFirstChunk=!1,this._halted=!1;var T=this._partialLine+g,v=(this._partialLine="",this._handle.parse(T,this._baseIndex,!this._finished));if(!this._handle.paused()&&!this._handle.aborted()){if(g=v.meta.cursor,T=(this._finished||(this._partialLine=T.substring(g-this._baseIndex),this._baseIndex=g),v&&v.data&&(this._rowCount+=v.data.length),this._finished||this._config.preview&&this._rowCount>=this._config.preview),l)a.postMessage({results:v,workerId:o.WORKER_ID,finished:T});else if(C(this._config.chunk)&&!y){if(this._config.chunk(v,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=v=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(v.data),this._completeResults.errors=this._completeResults.errors.concat(v.errors),this._completeResults.meta=v.meta),this._completed||!T||!C(this._config.complete)||v&&v.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),T||v&&v.meta.paused||this._nextChunk(),v}this._halted=!0},this._sendError=function(g){C(this._config.error)?this._config.error(g):l&&this._config.error&&a.postMessage({workerId:o.WORKER_ID,error:g,finished:!1})}}function c(u){var g;(u=u||{}).chunkSize||(u.chunkSize=o.RemoteChunkSize),x.call(this,u),this._nextChunk=i?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(y){this._input=y,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(g=new XMLHttpRequest,this._config.withCredentials&&(g.withCredentials=this._config.withCredentials),i||(g.onload=R(this._chunkLoaded,this),g.onerror=R(this._chunkError,this)),g.open(this._config.downloadRequestBody?"POST":"GET",this._input,!i),this._config.downloadRequestHeaders){var y,T=this._config.downloadRequestHeaders;for(y in T)g.setRequestHeader(y,T[y])}var v;this._config.chunkSize&&(v=this._start+this._config.chunkSize-1,g.setRequestHeader("Range","bytes="+this._start+"-"+v));try{g.send(this._config.downloadRequestBody)}catch(Q){this._chunkError(Q.message)}i&&g.status===0&&this._chunkError()}},this._chunkLoaded=function(){g.readyState===4&&(g.status<200||400<=g.status?this._chunkError():(this._start+=this._config.chunkSize||g.responseText.length,this._finished=!this._config.chunkSize||this._start>=(y=>(y=y.getResponseHeader("Content-Range"))!==null?parseInt(y.substring(y.lastIndexOf("/")+1)):-1)(g),this.parseChunk(g.responseText)))},this._chunkError=function(y){y=g.statusText||y,this._sendError(new Error(y))}}function f(u){(u=u||{}).chunkSize||(u.chunkSize=o.LocalChunkSize),x.call(this,u);var g,y,T=typeof FileReader<"u";this.stream=function(v){this._input=v,y=v.slice||v.webkitSlice||v.mozSlice,T?((g=new FileReader).onload=R(this._chunkLoaded,this),g.onerror=R(this._chunkError,this)):g=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount<this._config.preview)||this._readChunk()},this._readChunk=function(){var v=this._input,Q=(this._config.chunkSize&&(Q=Math.min(this._start+this._config.chunkSize,this._input.size),v=y.call(v,this._start,Q)),g.readAsText(v,this._config.encoding));T||this._chunkLoaded({target:{result:Q}})},this._chunkLoaded=function(v){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(v.target.result)},this._chunkError=function(){this._sendError(g.error)}}function m(u){var g;x.call(this,u=u||{}),this.stream=function(y){return g=y,this._nextChunk()},this._nextChunk=function(){var y,T;if(!this._finished)return y=this._config.chunkSize,g=y?(T=g.substring(0,y),g.substring(y)):(T=g,""),this._finished=!g,this.parseChunk(T)}}function w(u){x.call(this,u=u||{});var g=[],y=!0,T=!1;this.pause=function(){x.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){x.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(v){this._input=v,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){T&&g.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),g.length?this.parseChunk(g.shift()):y=!0},this._streamData=R(function(v){try{g.push(typeof v=="string"?v:v.toString(this._config.encoding)),y&&(y=!1,this._checkIsFinished(),this.parseChunk(g.shift()))}catch(Q){this._streamError(Q)}},this),this._streamError=R(function(v){this._streamCleanUp(),this._sendError(v)},this),this._streamEnd=R(function(){this._streamCleanUp(),T=!0,this._streamData("")},this),this._streamCleanUp=R(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function E(u){var g,y,T,v,Q=Math.pow(2,53),ae=-Q,re=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,ce=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,Z=this,ie=0,te=0,de=!1,B=!1,N=[],O={data:[],errors:[],meta:{}};function J(H){return u.skipEmptyLines==="greedy"?H.join("").trim()==="":H.length===1&&H[0].length===0}function U(){if(O&&T&&(K("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+o.DefaultDelimiter+"'"),T=!1),u.skipEmptyLines&&(O.data=O.data.filter(function(L){return!J(L)})),D()){let L=function($,p){C(u.transformHeader)&&($=u.transformHeader($,p)),N.push($)};if(O)if(Array.isArray(O.data[0])){for(var H=0;D()&&H<O.data.length;H++)O.data[H].forEach(L);O.data.splice(0,1)}else O.data.forEach(L)}function ee(L,$){for(var p=u.header?{}:[],F=0;F<L.length;F++){var q=F,V=L[F],V=((oe,W)=>(X=>(u.dynamicTypingFunction&&u.dynamicTyping[X]===void 0&&(u.dynamicTyping[X]=u.dynamicTypingFunction(X)),(u.dynamicTyping[X]||u.dynamicTyping)===!0))(oe)?W==="true"||W==="TRUE"||W!=="false"&&W!=="FALSE"&&((X=>{if(re.test(X)&&(X=parseFloat(X),ae<X&&X<Q))return 1})(W)?parseFloat(W):ce.test(W)?new Date(W):W===""?null:W):W)(q=u.header?F>=N.length?"__parsed_extra":N[F]:q,V=u.transform?u.transform(V,q):V);q==="__parsed_extra"?(p[q]=p[q]||[],p[q].push(V)):p[q]=V}return u.header&&(F>N.length?K("FieldMismatch","TooManyFields","Too many fields: expected "+N.length+" fields but parsed "+F,te+$):F<N.length&&K("FieldMismatch","TooFewFields","Too few fields: expected "+N.length+" fields but parsed "+F,te+$)),p}var A;O&&(u.header||u.dynamicTyping||u.transform)&&(A=1,!O.data.length||Array.isArray(O.data[0])?(O.data=O.data.map(ee),A=O.data.length):O.data=ee(O.data,0),u.header&&O.meta&&(O.meta.fields=N),te+=A)}function D(){return u.header&&N.length===0}function K(H,ee,A,L){H={type:H,code:ee,message:A},L!==void 0&&(H.row=L),O.errors.push(H)}C(u.step)&&(v=u.step,u.step=function(H){O=H,D()?U():(U(),O.data.length!==0&&(ie+=H.data.length,u.preview&&ie>u.preview?y.abort():(O.data=O.data[0],v(O,Z))))}),this.parse=function(H,ee,A){var L=u.quoteChar||'"',L=(u.newline||(u.newline=this.guessLineEndings(H,L)),T=!1,u.delimiter?C(u.delimiter)&&(u.delimiter=u.delimiter(H),O.meta.delimiter=u.delimiter):((L=(($,p,F,q,V)=>{var oe,W,X,le;V=V||[",","	","|",";",o.RECORD_SEP,o.UNIT_SEP];for(var ue=0;ue<V.length;ue++){for(var me,_e=V[ue],fe=0,we=0,he=0,ye=(X=void 0,new M({comments:q,delimiter:_e,newline:p,preview:10}).parse($)),Ae=0;Ae<ye.data.length;Ae++)F&&J(ye.data[Ae])?he++:(me=ye.data[Ae].length,we+=me,X===void 0?X=me:0<me&&(fe+=Math.abs(me-X),X=me));0<ye.data.length&&(we/=ye.data.length-he),(W===void 0||fe<=W)&&(le===void 0||le<we)&&1.99<we&&(W=fe,oe=_e,le=we)}return{successful:!!(u.delimiter=oe),bestDelimiter:oe}})(H,u.newline,u.skipEmptyLines,u.comments,u.delimitersToGuess)).successful?u.delimiter=L.bestDelimiter:(T=!0,u.delimiter=o.DefaultDelimiter),O.meta.delimiter=u.delimiter),P(u));return u.preview&&u.header&&L.preview++,g=H,y=new M(L),O=y.parse(g,ee,A),U(),de?{meta:{paused:!0}}:O||{meta:{paused:!1}}},this.paused=function(){return de},this.pause=function(){de=!0,y.abort(),g=C(u.chunk)?"":g.substring(y.getCharIndex())},this.resume=function(){Z.streamer._halted?(de=!1,Z.streamer.parseChunk(g,!0)):setTimeout(Z.resume,3)},this.aborted=function(){return B},this.abort=function(){B=!0,y.abort(),O.meta.aborted=!0,C(u.complete)&&u.complete(O),g=""},this.guessLineEndings=function($,L){$=$.substring(0,1048576);var L=new RegExp(_(L)+"([^]*?)"+_(L),"gm"),A=($=$.replace(L,"")).split("\r"),L=$.split(`
10`),$=1<L.length&&L[0].length<A[0].length;if(A.length===1||$)return`
11`;for(var p=0,F=0;F<A.length;F++)A[F][0]===`
12`&&p++;return p>=A.length/2?`\r
13`:"\r"}}function _(u){return u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function M(u){var g=(u=u||{}).delimiter,y=u.newline,T=u.comments,v=u.step,Q=u.preview,ae=u.fastMode,re=null,ce=!1,Z=u.quoteChar==null?'"':u.quoteChar,ie=Z;if(u.escapeChar!==void 0&&(ie=u.escapeChar),(typeof g!="string"||-1<o.BAD_DELIMITERS.indexOf(g))&&(g=","),T===g)throw new Error("Comment character same as delimiter");T===!0?T="#":(typeof T!="string"||-1<o.BAD_DELIMITERS.indexOf(T))&&(T=!1),y!==`
14`&&y!=="\r"&&y!==`\r
15`&&(y=`
16`);var te=0,de=!1;this.parse=function(B,N,O){if(typeof B!="string")throw new Error("Input must be a string");var J=B.length,U=g.length,D=y.length,K=T.length,H=C(v),ee=[],A=[],L=[],$=te=0;if(!B)return fe();if(ae||ae!==!1&&B.indexOf(Z)===-1){for(var p=B.split(y),F=0;F<p.length;F++){if(L=p[F],te+=L.length,F!==p.length-1)te+=y.length;else if(O)return fe();if(!T||L.substring(0,K)!==T){if(H){if(ee=[],le(L.split(g)),we(),de)return fe()}else le(L.split(g));if(Q&&Q<=F)return ee=ee.slice(0,Q),fe(!0)}}return fe()}for(var q=B.indexOf(g,te),V=B.indexOf(y,te),oe=new RegExp(_(ie)+_(Z),"g"),W=B.indexOf(Z,te);;)if(B[te]===Z)for(W=te,te++;;){if((W=B.indexOf(Z,W+1))===-1)return O||A.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:ee.length,index:te}),me();if(W===J-1)return me(B.substring(te,W).replace(oe,Z));if(Z===ie&&B[W+1]===ie)W++;else if(Z===ie||W===0||B[W-1]!==ie){q!==-1&&q<W+1&&(q=B.indexOf(g,W+1));var X=ue((V=V!==-1&&V<W+1?B.indexOf(y,W+1):V)===-1?q:Math.min(q,V));if(B.substr(W+1+X,U)===g){L.push(B.substring(te,W).replace(oe,Z)),B[te=W+1+X+U]!==Z&&(W=B.indexOf(Z,te)),q=B.indexOf(g,te),V=B.indexOf(y,te);break}if(X=ue(V),B.substring(W+1+X,W+1+X+D)===y){if(L.push(B.substring(te,W).replace(oe,Z)),_e(W+1+X+D),q=B.indexOf(g,te),W=B.indexOf(Z,te),H&&(we(),de))return fe();if(Q&&ee.length>=Q)return fe(!0);break}A.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:ee.length,index:te}),W++}}else if(T&&L.length===0&&B.substring(te,te+K)===T){if(V===-1)return fe();te=V+D,V=B.indexOf(y,te),q=B.indexOf(g,te)}else if(q!==-1&&(q<V||V===-1))L.push(B.substring(te,q)),te=q+U,q=B.indexOf(g,te);else{if(V===-1)break;if(L.push(B.substring(te,V)),_e(V+D),H&&(we(),de))return fe();if(Q&&ee.length>=Q)return fe(!0)}return me();function le(he){ee.push(he),$=te}function ue(he){var ye=0;return ye=he!==-1&&(he=B.substring(W+1,he))&&he.trim()===""?he.length:ye}function me(he){return O||(he===void 0&&(he=B.substring(te)),L.push(he),te=J,le(L),H&&we()),fe()}function _e(he){te=he,le(L),L=[],V=B.indexOf(y,te)}function fe(he){if(u.header&&!N&&ee.length&&!ce){var ye=ee[0],Ae=Object.create(null),dt=new Set(ye);let ut=!1;for(let Me=0;Me<ye.length;Me++){let Te=ye[Me];if(Ae[Te=C(u.transformHeader)?u.transformHeader(Te,Me):Te]){let Fe,G=Ae[Te];for(;Fe=Te+"_"+G,G++,dt.has(Fe););dt.add(Fe),ye[Me]=Fe,Ae[Te]++,ut=!0,(re=re===null?{}:re)[Fe]=Te}else Ae[Te]=1,ye[Me]=Te;dt.add(Te)}ut&&console.warn("Duplicate headers found and renamed."),ce=!0}return{data:ee,errors:A,meta:{delimiter:g,linebreak:y,aborted:de,truncated:!!he,cursor:$+(N||0),renamedHeaders:re}}}function we(){v(fe()),ee=[],A=[]}},this.abort=function(){de=!0},this.getCharIndex=function(){return te}}function S(u){var g=u.data,y=d[g.workerId],T=!1;if(g.error)y.userError(g.error,g.file);else if(g.results&&g.results.data){var v={abort:function(){T=!0,j(g.workerId,{data:[],errors:[],meta:{aborted:!0}})},pause:I,resume:I};if(C(y.userStep)){for(var Q=0;Q<g.results.data.length&&(y.userStep({data:g.results.data[Q],errors:g.results.errors,meta:g.results.meta},v),!T);Q++);delete g.results}else C(y.userChunk)&&(y.userChunk(g.results,v,g.file),delete g.results)}g.finished&&!T&&j(g.workerId,g.results)}function j(u,g){var y=d[u];C(y.userComplete)&&y.userComplete(g),y.terminate(),delete d[u]}function I(){throw new Error("Not implemented.")}function P(u){if(typeof u!="object"||u===null)return u;var g,y=Array.isArray(u)?[]:{};for(g in u)y[g]=P(u[g]);return y}function R(u,g){return function(){u.apply(g,arguments)}}function C(u){return typeof u=="function"}return o.parse=function(u,g){var y=(g=g||{}).dynamicTyping||!1;if(C(y)&&(g.dynamicTypingFunction=y,y={}),g.dynamicTyping=y,g.transform=!!C(g.transform)&&g.transform,!g.worker||!o.WORKERS_SUPPORTED)return y=null,o.NODE_STREAM_INPUT,typeof u=="string"?(u=(T=>T.charCodeAt(0)!==65279?T:T.slice(1))(u),y=new(g.download?c:m)(g)):u.readable===!0&&C(u.read)&&C(u.on)?y=new w(g):(a.File&&u instanceof File||u instanceof Object)&&(y=new f(g)),y.stream(u);(y=(()=>{var T;return!!o.WORKERS_SUPPORTED&&(T=(()=>{var v=a.URL||a.webkitURL||null,Q=n.toString();return o.BLOB_URL||(o.BLOB_URL=v.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",Q,")();"],{type:"text/javascript"})))})(),(T=new a.Worker(T)).onmessage=S,T.id=h++,d[T.id]=T)})()).userStep=g.step,y.userChunk=g.chunk,y.userComplete=g.complete,y.userError=g.error,g.step=C(g.step),g.chunk=C(g.chunk),g.complete=C(g.complete),g.error=C(g.error),delete g.worker,y.postMessage({input:u,config:g,workerId:y.id})},o.unparse=function(u,g){var y=!1,T=!0,v=",",Q=`\r
17`,ae='"',re=ae+ae,ce=!1,Z=null,ie=!1,te=((()=>{if(typeof g=="object"){if(typeof g.delimiter!="string"||o.BAD_DELIMITERS.filter(function(N){return g.delimiter.indexOf(N)!==-1}).length||(v=g.delimiter),typeof g.quotes!="boolean"&&typeof g.quotes!="function"&&!Array.isArray(g.quotes)||(y=g.quotes),typeof g.skipEmptyLines!="boolean"&&typeof g.skipEmptyLines!="string"||(ce=g.skipEmptyLines),typeof g.newline=="string"&&(Q=g.newline),typeof g.quoteChar=="string"&&(ae=g.quoteChar),typeof g.header=="boolean"&&(T=g.header),Array.isArray(g.columns)){if(g.columns.length===0)throw new Error("Option columns is empty");Z=g.columns}g.escapeChar!==void 0&&(re=g.escapeChar+ae),g.escapeFormulae instanceof RegExp?ie=g.escapeFormulae:typeof g.escapeFormulae=="boolean"&&g.escapeFormulae&&(ie=/^[=+\-@\t\r].*$/)}})(),new RegExp(_(ae),"g"));if(typeof u=="string"&&(u=JSON.parse(u)),Array.isArray(u)){if(!u.length||Array.isArray(u[0]))return de(null,u,ce);if(typeof u[0]=="object")return de(Z||Object.keys(u[0]),u,ce)}else if(typeof u=="object")return typeof u.data=="string"&&(u.data=JSON.parse(u.data)),Array.isArray(u.data)&&(u.fields||(u.fields=u.meta&&u.meta.fields||Z),u.fields||(u.fields=Array.isArray(u.data[0])?u.fields:typeof u.data[0]=="object"?Object.keys(u.data[0]):[]),Array.isArray(u.data[0])||typeof u.data[0]=="object"||(u.data=[u.data])),de(u.fields||[],u.data||[],ce);throw new Error("Unable to serialize unrecognized input");function de(N,O,J){var U="",D=(typeof N=="string"&&(N=JSON.parse(N)),typeof O=="string"&&(O=JSON.parse(O)),Array.isArray(N)&&0<N.length),K=!Array.isArray(O[0]);if(D&&T){for(var H=0;H<N.length;H++)0<H&&(U+=v),U+=B(N[H],H);0<O.length&&(U+=Q)}for(var ee=0;ee<O.length;ee++){var A=(D?N:O[ee]).length,L=!1,$=D?Object.keys(O[ee]).length===0:O[ee].length===0;if(J&&!D&&(L=J==="greedy"?O[ee].join("").trim()==="":O[ee].length===1&&O[ee][0].length===0),J==="greedy"&&D){for(var p=[],F=0;F<A;F++){var q=K?N[F]:F;p.push(O[ee][q])}L=p.join("").trim()===""}if(!L){for(var V=0;V<A;V++){0<V&&!$&&(U+=v);var oe=D&&K?N[V]:V;U+=B(O[ee][oe],V)}ee<O.length-1&&(!J||0<A&&!$)&&(U+=Q)}}return U}function B(N,O){var J,U;return N==null?"":N.constructor===Date?JSON.stringify(N).slice(1,25):(U=!1,ie&&typeof N=="string"&&ie.test(N)&&(N="'"+N,U=!0),J=N.toString().replace(te,re),(U=U||y===!0||typeof y=="function"&&y(N,O)||Array.isArray(y)&&y[O]||((D,K)=>{for(var H=0;H<K.length;H++)if(-1<D.indexOf(K[H]))return!0;return!1})(J,o.BAD_DELIMITERS)||-1<J.indexOf(v)||J.charAt(0)===" "||J.charAt(J.length-1)===" ")?ae+J+ae:J)}},o.RECORD_SEP="�",o.UNIT_SEP="�",o.BYTE_ORDER_MARK="\uFEFF",o.BAD_DELIMITERS=["\r",`
18`,'"',o.BYTE_ORDER_MARK],o.WORKERS_SUPPORTED=!i&&!!a.Worker,o.NODE_STREAM_INPUT=1,o.LocalChunkSize=10485760,o.RemoteChunkSize=5242880,o.DefaultDelimiter=",",o.Parser=M,o.ParserHandle=E,o.NetworkStreamer=c,o.FileStreamer=f,o.StringStreamer=m,o.ReadableStreamStreamer=w,a.jQuery&&((r=a.jQuery).fn.parse=function(u){var g=u.config||{},y=[];return this.each(function(Q){if(!(r(this).prop("tagName").toUpperCase()==="INPUT"&&r(this).attr("type").toLowerCase()==="file"&&a.FileReader)||!this.files||this.files.length===0)return!0;for(var ae=0;ae<this.files.length;ae++)y.push({file:this.files[ae],inputElem:this,instanceConfig:r.extend({},g)})}),T(),this;function T(){if(y.length===0)C(u.complete)&&u.complete();else{var Q,ae,re,ce,Z=y[0];if(C(u.before)){var ie=u.before(Z.file,Z.inputElem);if(typeof ie=="object"){if(ie.action==="abort")return Q="AbortError",ae=Z.file,re=Z.inputElem,ce=ie.reason,void(C(u.error)&&u.error({name:Q},ae,re,ce));if(ie.action==="skip")return void v();typeof ie.config=="object"&&(Z.instanceConfig=r.extend(Z.instanceConfig,ie.config))}else if(ie==="skip")return void v()}var te=Z.instanceConfig.complete;Z.instanceConfig.complete=function(de){C(te)&&te(de,Z.file,Z.inputElem),v()},o.parse(Z.file,Z.instanceConfig)}}function v(){y.splice(0,1),T()}}),l&&(a.onmessage=function(u){u=u.data,o.WORKER_ID===void 0&&u&&(o.WORKER_ID=u.workerId),typeof u.input=="string"?a.postMessage({workerId:o.WORKER_ID,results:o.parse(u.input,u.config),finished:!0}):(a.File&&u.input instanceof File||u.input instanceof Object)&&(u=o.parse(u.input,u.config))&&a.postMessage({workerId:o.WORKER_ID,results:u,finished:!0})}),(c.prototype=Object.create(x.prototype)).constructor=c,(f.prototype=Object.create(x.prototype)).constructor=f,(m.prototype=Object.create(m.prototype)).constructor=m,(w.prototype=Object.create(x.prototype)).constructor=w,o})})(Bt)),Bt.exports}var xu=pu();const en=pr(xu),hu=["email","name","smtp_host","smtp_port","smtp_user","smtp_password","smtp_security","imap_host","imap_port","imap_user","imap_password","imap_security"],fu=["[email protected]","Alex Rivera","smtp.company.com","587","[email protected]","app-password","starttls","imap.company.com","993","[email protected]","app-password","tls"],gu={email:"email",address:"email",email_address:"email",name:"name",display_name:"name",from_name:"name",sender_name:"name",first_name:"first_name",last_name:"last_name",smtp_host:"smtp_host",smtp_server:"smtp_host",smtp_port:"smtp_port",smtp_user:"smtp_user",smtp_username:"smtp_user",smtp_login:"smtp_user",smtp_password:"smtp_password",smtp_pass:"smtp_password",smtp_security:"smtp_security",smtp_encryption:"smtp_security",imap_host:"imap_host",imap_server:"imap_host",imap_port:"imap_port",imap_user:"imap_user",imap_username:"imap_user",imap_login:"imap_user",imap_password:"imap_password",imap_pass:"imap_password",imap_security:"imap_security",imap_encryption:"imap_security",password:"password",app_password:"password",username:"username",user:"username",login:"username"};function bu(t){const s=t.trim().toLowerCase().replace(/[\s-]+/g,"_");return gu[s]??s}function Bn(t,s,n){const a=(t??"").trim().toLowerCase();return a===""?n==="smtp"?va(s):Na(s):a==="tls"||a==="ssl"||a==="ssl/tls"||a==="implicit"?"tls":a==="starttls"||a==="start_tls"||a==="start-tls"?"starttls":null}function yu(t){return(t.split("@")[0]??"").split(/[._-]+/).filter(
18Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}const ju=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function wu(t,s){const n=_=>(s[_]??"").trim(),a=n("email"),r=_=>({line:t,raw:s,account:null,problem:_,status:"invalid"});if(!a)return r("Missing email address");if(!ju.test(a))return r("Not a valid email address");let i=n("name");i||(i=[n("first_name"),n("last_name")].filter(Boolean).join(" ")),i||(i=yu(a));const l=n("username")||a,d=n("password"),h=n("smtp_host"),o=n("imap_host");if(!h)return r("Missing smtp_host");if(!o)return r("Missing imap_host");const x=Number(n("smtp_port")||"587"),c=Number(n("imap_port")||"993");if(!Qt(x))return r("smtp_port must be between 1 and 65535");if(!Qt(c))return r("imap_port must be between 1 and 65535");const f=n("smtp_password")||d,m=n("imap_password")||d;if(!m)return r("Missing imap_password (or a shared password column)");if(!f)return r("Missing smtp_password (or a shared password column)");const w=Bn(s.smtp_security,x,"smtp"),E=Bn(s.imap_security,c,"imap");return w?E?{line:t,raw:s,status:"ready",account:{email:a,name:i,smtp:{host:h,port:x,username:n("smtp_user")||l,password:f,security:w},imap:{host:o,port:c,username:n("imap_user")||l,password:m,security:E}}}:r("imap_security must be tls or starttls"):r("smtp_security must be tls or starttls")}function vu(t){return new Promise((s,n)=>{en.parse(t,{header:!0,skipEmptyLines:"greedy",transformHeader:bu,complete:a=>{const r=(a.meta.fields??[]).filter(l=>l!=="");if(!r.includes("email")){n(new Error("The file needs an email column. Download the template to see the expected headers."));return}const i=a.data.map((l,d)=>wu(d+2,l));if(i.length===0){n(new Error("The file has a header but no rows."));return}s({rows:i,columns:r})},error:a=>n(new Error(a.message||"Could not read the file."))})})}function Nu(){const t=en.unparse([hu,fu]);Ma(new Blob(["\uFEFF"+t],{type:"text/csv;charset=utf-8"}),"warmbly-mailboxes-template.csv")}const ku=new Set(["password","smtp_password","imap_password"]);function _u(t,s){const n=s.filter(i=>!ku.has(i)),a=[...n,"error"],r=t.map(i=>[...n.map(l=>i.raw[l]??""),i.problem??i.message??i.code??""]);return en.unparse([a,...r])}function Su({onDone:t,onAllowance:s}){const n=Ee(),a=er(),[r,i]=b.useState("upload"),[l,d]=b.useState(""),[h,o]=b.useState([]),[x,c]=b.useState([]),[f,m]=b.useState(!1),[w,E]=b.useState(!1),_=b.useRef(!1),[M,S]=b.useState(!1),[j,I]=b.useState(0),P=b.useRef(null),R=x.filter(D=>D.status==="ready"||D.status==="pending").length,C=x.filter(D=>D.status==="invalid").length,u=a.data?.remaining??null,g=u!==null&&u<=0,y=u!==null&&R>u?R-u:0;async function T(D){m(!0);try{const K=await vu(D);d(D.name),o(K.columns),c(K.rows),i("preview")}catch(K){se.error(K.message)}finally{m(!1)}}async function v(){if(R===0)return;_.current=!1,S(!1),I(Date.now()),i("run"),c(K=>K.map(H=>H.status==="ready"?{...H,status:"pending"}
18:H));const D=x.map((K,H)=>({r:K,i:H})).filter(({r:K})=>K.status==="ready");for(let K=0;K<D.length&&!_.current;K+=qn){const H=D.slice(K,K+qn);let ee;try{ee=(await uu(H.map(({r:L})=>L.account))).data}catch(A){const L=je(A);ee=H.map(($,p)=>({row:p,email:H[p].r.account.email,status:"failed",code:"request_failed",message:L}))}c(A=>{const L=[...A];for(const $ of ee){const p=H[$.row];p&&(L[p.i]={...L[p.i],status:$.status,code:$.code,message:$.message})}return L}),n.invalidateQueries({queryKey:["emails"]}),n.invalidateQueries({queryKey:["analytics","accounts"]})}c(K=>K.map(H=>H.status==="pending"?{...H,status:"ready"}:H)),i("result")}function Q(){c(D=>D.map(K=>K.status==="failed"&&K.account?{...K,status:"ready",code:void 0,message:void 0}:K)),i("preview")}function ae(){c([]),o([]),d(""),i("upload")}if(r==="upload")return e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsxs("div",{onDragOver:D=>{D.preventDefault(),E(!0)},onDragLeave:()=>E(!1),onDrop:D=>{D.preventDefault(),E(!1);const K=D.dataTransfer.files?.[0];K&&T(K)},onClick:()=>P.current?.click(),className:Y("rounded-md border border-dashed p-6 flex flex-col items-center justify-center text-center cursor-pointer transition-colors",w?"border-sky-400 bg-sky-50":"border-slate-300 hover:border-slate-400 hover:bg-slate-50/60"),children:[e.jsx("input",{ref:P,type:"file",accept:".csv,text/csv",className:"hidden",onChange:D=>{const K=D.target.files?.[0];K&&T(K),D.target.value=""}}),f?e.jsx(xe,{className:"w-5 h-5 text-slate-400 animate-spin"}):e.jsx(mn,{className:"w-5 h-5 text-slate-400"}),e.jsx("p",{className:"text-[13px] font-medium text-slate-900 mt-2",children:"Drop a CSV here, or click to choose one"}),e.jsx("p",{className:"text-[11.5px] text-slate-500 mt-0.5",children:"One mailbox per row. Any provider that speaks SMTP and IMAP."})]}),e.jsxs("div",{className:"rounded-md border border-slate-200 bg-slate-50/40 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-500 font-medium",children:"Columns"}),e.jsxs("button",{type:"button",onClick:Nu,className:"h-6 px-2 rounded text-[11px] text-slate-700 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center gap-1 transition-colors",children:[e.jsx(pn,{className:"w-3 h-3"}),"Download template"]})]}),e.jsxs("p",{className:"text-[11.5px] text-slate-600 leading-relaxed mt-1.5",children:[e.jsx("code",{className:"font-mono text-[11px]",children:"email"}),", ",e.jsx("code",{className:"font-mono text-[11px]",children:"smtp_host"})," and"," ",e.jsx("code",{className:"font-mono text-[11px]",children:"imap_host"})," are required, plus a password. Everything else has a default: ports 587 and 993, security from the port, the address as the login, the name from the address. One ",e.jsx("code",{className:"font-mono text-[11px]",children:"password"})," column covers both legs when they share a login."]})]}),e.jsx(Cu,{allowance:a.data,onAllowance:s})]});if(r==="preview"){const D=x.slice(0,6);return e.jsxs("div",{className:"flex flex-col min-h-0",children:[e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ea,{className:"w-4 h-4 text-slate-500 shrink-0"}),e.jsx("span",{className:"text-[12.5px] text-slate-900 font-medium truncate",children:l}),e.jsxs("button",{type:"button",onClick:ae,className:"ml-auto h-6 px-2 rounded text-[11px] text-slate-500 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center gap-1 transition-colors shrink-0",children:[e.jsx(ve,{className:"w-3 h-3"}),"Choose another file"]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(De,{label:"Rows",value:x.length,accent:"slate"}),e.jsx(De,{label:"Ready",value:R,accent:"emerald"}),e.jsx(De,{label:"Invalid",value:C,accent:C>0?"red":"slate"})]}),g?e.jsxs(zt,{tone:"red",title:"Your mailbox allowance is full",children:["Nothing in this file can be connected until the allowance is raised."," ",e.jsx("button",{type:"button",onClick:s,className:"underline font-medium",children:"Request more"})," ","and come back to this file; it can be re-uploaded as it is."]}):y>
180?e.jsxs(zt,{tone:"amber",title:`Room for ${u.toLocaleString()} more mailboxes, ${R.toLocaleString()} in this file`,children:["The first ",u.toLocaleString()," rows will be connected and the remaining"," ",y.toLocaleString()," listed as failed so you can"," ",e.jsx("button",{type:"button",onClick:s,className:"underline font-medium",children:"request more"})," ","and re-upload only those."]}):null,C>0&&e.jsx(zt,{tone:"amber",title:`${C.toLocaleString()} rows cannot be sent`,children:"They are missing something the connect needs. They are left out of the run and included in the failed rows download at the end, with the reason."}),e.jsx(Eu,{rows:D,more:x.length-D.length})]}),e.jsxs("div",{className:"px-4 py-2.5 border-t border-slate-200 bg-slate-50/60 flex items-center gap-2 min-w-0 sticky bottom-0",children:[e.jsx("div",{className:"text-[11px] text-slate-500 min-w-0 flex-1 truncate",children:"Every credential is verified against its server before it is saved."}),e.jsxs(ne.button,{type:"button",onClick:()=>{v()},disabled:R===0||g,whileTap:R>0&&!g?{scale:.97}:void 0,className:Y("shrink-0 h-7 px-3 rounded-md text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors","bg-slate-900 hover:bg-slate-800 text-white disabled:opacity-50 disabled:cursor-not-allowed"),children:[e.jsx(mn,{className:"w-3 h-3"}),"Connect ",R.toLocaleString()," ",R===1?"mailbox":"mailboxes"]})]})]})}const re=x.filter(D=>D.status==="connected").length,ce=x.filter(D=>D.status==="skipped").length,Z=x.filter(D=>D.status==="failed").length,ie=x.filter(D=>D.status==="pending").length,de=x.filter(D=>D.status==="ready").length+re+ce+Z+ie;if(r==="run"){const D=re+ce+Z,K=de>0?D/de:0;return e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xe,{className:"w-5 h-5 text-sky-600 animate-spin shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-[13.5px] text-slate-900 font-semibold",children:["Connecting ",de.toLocaleString()," ",de===1?"mailbox":"mailboxes"]}),e.jsx("p",{className:"text-[11.5px] text-slate-500 leading-snug mt-0.5",children:"Each one is verified against its server, so this takes a few seconds per mailbox. You can keep this open in the background; the list fills in live."})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2 mb-1",children:[e.jsx("span",{className:"text-[12px] text-slate-700 font-medium",children:"Progress"}),e.jsxs("span",{className:"text-[11.5px] font-mono tabular-nums text-slate-700",children:[D.toLocaleString(),e.jsxs("span",{className:"text-slate-400",children:[" / ",de.toLocaleString()]})]})]}),e.jsx(Et,{frac:K,tone:"sky",height:6})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(De,{label:"Connected",value:re,accent:"emerald"}),e.jsx(De,{label:"Skipped",value:ce,accent:"slate"}),e.jsx(De,{label:"Failed",value:Z,accent:Z>0?"red":"slate"})]}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsxs("button",{type:"button",disabled:M,onClick:()=>{_.current=!0,S(!0)},className:"h-7 px-3 rounded-md border border-slate-200 text-[12px] text-slate-700 hover:bg-slate-50 inline-flex items-center gap-1.5 transition-colors disabled:opacity-50",children:[e.jsx(ve,{className:"w-3 h-3"}),M?"Stopping after this batch…":"Stop"]})})]})}const B=x.filter(D=>D.status==="failed"||D.status==="invalid"),N=x.filter(D=>D.status==="ready").length,O=x.some(D=>D.status==="failed"&&D.account),J=j?Date.now()-j:0;function U(){if(B.length===0)return;const D=_u(B,h);Ma(new Blob(["\uFEFF"+D],{type:"text/csv;charset=utf-8"}),l.replace(/\.[^.]+$/,"")+"-failed.csv")}return e.jsxs("div",{className:"flex flex-col min-h-0",children:[e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[B.length===0&&N===0?e.jsx(tn,{className:"w-7 h-7 text-emerald-600 shrink-0"}):e.jsx(ze,{className:"w-7 h-7 text-amber-600 shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[13.5px] text-slate-900 font-semibold",children:N>0?"Stopped early":B.length===0?"All mailboxes connected":"Finished with some failures"}),e.jsxs("p",{className:"text-[11.5px] text-slate-500 leading-snug mt-0.5",children:[re.toLocaleStr
18ing()," connected",ce>0?`, ${ce.toLocaleString()} already here`:"",B.length>0?`, ${B.length.toLocaleString()} did not connect`:"",N>0?`, ${N.toLocaleString()} not attempted`:"",J>0?` in ${Au(J)}`:"","."]})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(De,{label:"Connected",value:re,accent:"emerald"}),e.jsx(De,{label:"Skipped",value:ce,accent:"slate"}),e.jsx(De,{label:"Failed",value:B.length,accent:B.length>0?"red":"slate"})]}),B.some(D=>D.code==="mailbox_allowance_reached")&&e.jsxs(zt,{tone:"amber",title:"Some rows were past your mailbox allowance",children:["They were not tried."," ",e.jsx("button",{type:"button",onClick:s,className:"underline font-medium",children:"Request more"}),", then re-upload the failed rows download; everything already connected is skipped."]}),B.length>0&&e.jsxs("div",{className:"rounded-md border border-slate-200 overflow-hidden",children:[e.jsxs("div",{className:"px-3 h-9 border-b border-slate-200 bg-slate-50/60 flex items-center gap-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-[0.14em] text-slate-500 font-medium",children:"Did not connect"}),e.jsx("span",{className:"text-[11px] text-slate-500",children:B.length.toLocaleString()}),e.jsxs("button",{type:"button",onClick:U,title:"The rows as you uploaded them, minus passwords, plus an error column",className:"ml-auto h-6 px-2 rounded text-[11px] text-slate-700 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center gap-1 transition-colors",children:[e.jsx(pn,{className:"w-3 h-3"}),"Download failed rows"]})]}),e.jsx("div",{className:"max-h-52 overflow-y-auto",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{className:"bg-white sticky top-0",children:e.jsxs("tr",{className:"border-b border-slate-100",children:[e.jsx("th",{className:"px-3 py-1.5 text-[10px] font-medium text-slate-400 uppercase tracking-[0.14em] w-12",children:"Line"}),e.jsx("th",{className:"px-3 py-1.5 text-[10px] font-medium text-slate-400 uppercase tracking-[0.14em]",children:"Email"}),e.jsx("th",{className:"px-3 py-1.5 text-[10px] font-medium text-slate-400 uppercase tracking-[0.14em]",children:"Reason"})]})}),e.jsx("tbody",{children:B.slice(0,200).map(D=>e.jsxs("tr",{className:"border-b border-slate-100 last:border-b-0",children:[e.jsx("td",{className:"px-3 py-1.5 text-[11px] text-slate-500 font-mono",children:D.line}),e.jsx("td",{className:"px-3 py-1.5 text-[11.5px] text-slate-700 truncate max-w-[200px]",children:D.raw.email||e.jsx("span",{className:"text-slate-300",children:"—"})}),e.jsx("td",{className:"px-3 py-1.5 text-[11.5px] text-slate-700 leading-snug",children:D.problem??D.message??D.code})]},D.line))})]})})]})]}),e.jsxs("div",{className:"px-4 py-2.5 border-t border-slate-200 bg-slate-50/60 flex items-center gap-2 min-w-0 sticky bottom-0",children:[e.jsx("div",{className:"text-[11px] text-slate-500 min-w-0 flex-1 truncate",children:B.length>0?"Retry keeps the passwords in memory. The download leaves them out; add them back before re-uploading.":"Warmup and sync start on every new mailbox right away."}),(O||N>0)&&e.jsxs("button",{type:"button",onClick:Q,className:"shrink-0 h-7 px-3 rounded-md border border-slate-200 text-[12px] text-slate-700 hover:bg-slate-50 inline-flex items-center gap-1.5 transition-colors",children:[e.jsx(mo,{className:"w-3 h-3"}),N>0?"Continue":"Retry failed"]}),e.jsxs("button",{type:"button",onClick:t,className:"shrink-0 h-7 px-3 rounded-md bg-slate-900 hover:bg-slate-800 text-white text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors",children:[e.jsx(tn,{className:"w-3 h-3"}),"Done"]})]})]})}function Cu({allowance:t,onAllowance:s}){if(!t||t.allowance==null)return null;const n=t.remaining??0;return e.jsxs("p",{className:"text-[11.5px] text-slate-500 leading-relaxed",children:["This workspace holds ",t.used.toLocaleString()," of ",t.allowance.toLocaleString()," mailboxes, so ",n.toLocaleString()," more fit right now."," ",e.jsx("button",{type:"button",onClick:s,className:"underline text-slate-700 hover:text-slate-900",children:n===0?"Request more before uploading":"Need more?"})]})}function Eu({rows:t,more:s}){return e.jsxs("div",{className:"rounded-md border border-slate-200 overflow-hidden",children:[e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{className:"bg-slate-50/60",children:e.jsxs("tr",{className:"border-b border-slate-200",children:[e.jsx("th",{className:"px-3 py-1.5 text-[10px] font-medium text-slate-400 uppercase tracking-[0.14em] w-12",children:"Line"}),e.jsx("th",{className:"px-3 py-1.5 text-[10px] font-medium text-slate-400 uppercase tracking-[0.14em]",children:"Email"}),e.jsx("th",{className:"hidden md:table-cell px-3 py-1.5 text-[10px] font-medium text-slate-400 uppercase tracking-[0.14em]",children:"SMTP"}),e.jsx("th",{className:"hidden md:table-cell px-3 py-1.5 text-[10px] font-medium text-slate-400 uppercase tracking-[0.14em]",children:"IMAP"}),e.jsx("th",{className:"px-3 py-1.5 text-[10px] font-medium text-slate-400 uppercase tracking-[0.14em]",children:"Status"})]})}),e.jsx("tbody",{children:t.map(n=>e.jsxs("tr",{className:"border-b border-slate-100 last:border-b-0",children:[e.jsx("td",{className:"px-3 py-1.5 text-[11px] text-slate-500 font-mono",children:n.line}),e.jsx("td",{className:"px-3 py-1.5 text-[11.5px] text-slate-800 truncate max-w-[180px]",children:n.raw.email}),e.jsx("td",{className:"hidden md:table-cell px-3 py-1.5 text-[11.5px] text-slate-600 truncate max-w-[160px]",children:n.account?`${n.account.smtp.host}:${n.account.smtp.port}`:"—"}),e.jsx("td",{className:"hidden md:table-cell px-3 py-1.5 text-[11.5px] text-slate-600 truncate max-w-[160px]",children:n.account?`${n.account.imap.host}:${n.account.imap.port}`:"—"}),e.jsx("td",{className:"px-3 py-1.5 text-[11.5px]",children:n.status==="invalid"?e.jsx("span",{className:"text-red-600",title:n.problem,children:n.problem}):e.jsx("span",{className:"text-emerald-600",children:"Ready"})})]},n.line))})]}),s>0&&e.jsxs("div",{className:"px-3 py-1.5 text-[11px] text-slate-400 border-t border-slate-100 bg-slate-50/40",children:["and ",s.toLocaleStr
18ing()," more"]})]})}function zt({tone:t,title:s,children:n}){const a=t==="red"?"border-red-200 bg-red-50 text-red-900 [&_p]:text-red-800/90":"border-amber-200 bg-amber-50 text-amber-900 [&_p]:text-amber-800/90";return e.jsxs("div",{className:Y("rounded-md border px-3 py-2.5 flex items-start gap-2",a),children:[e.jsx(ze,{className:"w-3.5 h-3.5 mt-px shrink-0 opacity-80"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[12.5px] font-medium !text-current",children:s}),e.jsx("p",{className:"text-[11.5px] leading-relaxed mt-0.5",children:n})]})]})}function De({label:t,value:s,accent:n}){const a={emerald:"ring-emerald-200 bg-emerald-50 text-emerald-700",slate:"ring-slate-200 bg-slate-50 text-slate-700",red:"ring-red-200 bg-red-50 text-red-700"}[n];return e.jsxs("div",{className:`rounded-md ring-1 p-2.5 ${a}`,children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.14em] font-medium opacity-75",children:t}),e.jsx("div",{className:"text-[18px] font-semibold tabular-nums mt-0.5",children:s.toLocaleString()})]})}function Au(t){if(t<1e3)return`${t} ms`;const s=t/1e3;return s<60?`${s.toFixed(0)} s`:`${(s/60).toFixed(1)} min`}function _s(t){return t?.code==="mailbox_allowance_reached"}function Wn(t){if(!t)return null;try{return new URL(t,window.location.href).origin}catch{return null}}function Tu(){return[Wn(hr),Wn(es),window.location.origin].filter(t=>!!t)}function Hn(t,s){const r=window.screenLeft??window.screenX,i=window.screenTop??window.screenY,l=window.innerWidth??document.documentElement.clientWidth??screen.width,d=window.innerHeight??document.documentElement.clientHeight??screen.height,h=r+(l-520)/2,o=i+(d-640)/2,x=window.open(t,s,`width=520,height=640,left=${h},top=${o}`);return x?.focus(),x}function Mu(){const t=Ye(),s=Ee(),[n,a]=b.useState("pick"),[r,i]=b.useState(null),[l,d]=b.useState(null),h=b.useRef(null),o=b.useRef(null),x=Ti(),c=x.connected,f=Ct(),m=er(t.addEmail),[w,E]=b.useState(!1),[_,M]=b.useState(!1),S=b.useCallback((P=!1)=>{M(P),E(!0)},[]),j=b.useCallback(P=>{_s(P)&&S(!0)},[S]);b.useEffect(()=>{t.addEmail||(a("pick"),i(null),d(null),E(!1),h.current=null,o.current=null)},[t.addEmail]),b.useEffect(()=>{function P(R){if(R.origin!==window.location.origin)return;const C=R.data;if(!C||C.type!=="cloud_oauth_callback")return;const u=o.current;if(!(!u||u.session!==C.session)){if(o.current=null,C.status!=="ok"){i(null),C.error!=="access_denied"&&se.error(C.message||(C.error?`Provider error: ${C.error}`:"Connection was cancelled."));return}se.promise(ro(C.session).then(g=>(s.invalidateQueries({queryKey:["emails","list"]}),s.invalidateQueries({queryKey:["cloud-link"]}),t.setAddEmail(!1),g)),{loading:"Adding the mailbox…",success:"Mailbox connected. Control Cloud warms it from now on.",error:g=>je(g)}).catch(j).finally(()=>i(null))}}return window.addEventListener("message",P),()=>window.removeEventListener("message",P)},[s,t,j]),b.useEffect(()=>{function P(R){if(R.origin&&!Tu().includes(R.origin))return;const C=R.data;if(!C||C.type!=="email_oauth_callback")return;const u=h.current;if(!(!u||u.state!==C.state)){if(h.current=null,C.error||!C.code){i(null),C.error!=="access_denied"&&se.error(C.error?`Provider error: ${C.error}`:"Connection was cancelled.");return}se.promise(Mi(C.code,C.state).then(g=>(s.invalidateQueries({queryKey:["emails","list"]}),t.setAddEmail(!1),g)),{loading:"Connecting…",success:"Mailbox connected",error:g=>je(g)}).catch(j).finally(()=>i(null))}}return window.addEventListener("message",P),()=>window.removeEventListener("message",P)},[s,t,j]);async function I(P){if(!r){if(i(P),d(null),c){try{const{url:R,session:C}=await io(P);o.current={provider:P,session:C},Hn(R,`connect-${P}`)||(o.current=null,i(null),se.error("Could not open the authorization window. Please allow popups and try again."))}catch(R){if(o.current=null,i(null),_s(R)){S(!0);return}se.error(je(R))}return}try{const{url:R,state:C}=await su(P);h.current={provider:P,state:C},Hn(R,`connect-${P}`)||(h.current=null,i(null),se.error("Could not open the authorization window. Please allow popups and try again."))}catch(R){h.current=null,i(null);const C=R;if(C.code==="mailbox_provider_not_configured"){d(P);return}if(_s(C)){S(!0);return}se.error(je(C))}}}return e.jsx(ge,{children:t.addEmail&&e.jsxs(ne.div,{initial:{opacity:0}
18,animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:()=>t.setAddEmail(!1),className:"fixed inset-0 z-[110] flex items-center justify-center bg-slate-900/30 backdrop-blur-[2px] px-4",children:[e.jsxs(ne.div,{initial:{y:8,opacity:0},animate:{y:0,opacity:1},exit:{y:8,opacity:0},transition:{duration:.16},onClick:P=>P.stopPropagation(),className:Y("w-full rounded-lg bg-white border border-slate-200 shadow-[0_24px_48px_-12px_rgba(15,23,42,0.18),0_8px_16px_-8px_rgba(15,23,42,0.1)] overflow-hidden flex flex-col max-h-[88dvh] transition-[max-width] duration-200",n==="bulk"?"max-w-[760px]":"max-w-[560px]"),children:[e.jsx(Iu,{view:n,onBack:()=>{d(null),a("pick")},onClose:()=>t.setAddEmail(!1)}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto overflow-x-hidden relative",children:e.jsx(ge,{mode:"wait",initial:!1,children:e.jsxs(ne.div,{initial:{opacity:0,x:n==="pick"?-12:12},animate:{opacity:1,x:0},exit:{opacity:0,x:n==="pick"?12:-12},transition:{duration:.18,ease:[.32,.72,0,1]},children:[n==="pick"&&e.jsxs(e.Fragment,{children:[e.jsx(Ru,{allowance:m.data,onOpen:()=>S(Un(m.data))}),e.jsx(Pu,{onPick:a,viaCloud:c,onAdopted:()=>{s.invalidateQueries({queryKey:["emails","list"]}),t.setAddEmail(!1)}})]}),n==="gmail"&&(l==="gmail"?e.jsx(Gn,{provider:"gmail",selfHosted:x.selfHosted}):e.jsx(Vn,{provider:"gmail",busy:r==="gmail",viaCloud:c,onConnect:()=>I("gmail")})),n==="outlook"&&(l==="outlook"?e.jsx(Gn,{provider:"outlook",selfHosted:x.selfHosted}):e.jsx(Vn,{provider:"outlook",busy:r==="outlook",viaCloud:c,onConnect:()=>I("outlook")})),n==="smtp_imap"&&e.jsx(Ou,{onDone:()=>{s.invalidateQueries({queryKey:["emails","list"]}),t.setAddEmail(!1)},onError:j}),n==="bulk"&&e.jsx(Su,{onDone:()=>{s.invalidateQueries({queryKey:["emails","list"]}),t.setAddEmail(!1)},onAllowance:()=>S(Un(m.data))})]},n)})})]},"card"),e.jsx(ou,{open:w,onClose:()=>E(!1),allowance:m.data,reached:_,currentPlan:f.plan})]},"overlay")})}function Ru({allowance:t,onOpen:s}){if(!t||t.allowance==null)return null;const n=t.allowance,a=t.remaining??0,r=Math.min(100,Math.round(t.used/n*100)),i=a<=0,l=!i&&(r>=80||a<=5);if(!i&&!l)return e.jsxs("div",{className:"px-4 py-2 border-b border-slate-200/60 flex items-center gap-2 text-[11px] text-slate-500",children:[e.jsxs("span",{className:"font-mono tabular-nums text-slate-700",children:[t.used.toLocaleString()," / ",n.toLocaleString()]}),e.jsx("span",{children:"mailboxes on this workspace"}),t.pending_request&&e.jsx("span",{className:"text-amber-600",children:"· increase requested"}),e.jsx("button",{type:"button",onClick:s,className:"ml-auto underline hover:text-slate-900 transition-colors",children:"Need more?"})]});const d=i?"rose":"amber";return e.jsxs("div",{className:Y("px-4 py-2.5 border-b",i?"bg-rose-50/60 border-rose-200/60":"bg-amber-50/60 border-amber-200/60"),children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2 mb-1",children:[e.jsx("span",{className:Y("text-[12px] font-medium",i?"text-rose-900":"text-amber-900"),children:i?"Every mailbox slot is used":`${a.toLocaleString()} ${a===1?"slot":"slots"} left`}),e.jsxs("span",{className:"text-[11px] font-mono tabular-nums text-slate-700",children:[t.used.toLocaleString()," / ",n.toLocaleString()]})]}),e.jsx(Et,{frac:r/100,tone:d,height:4}),e.jsxs("div",{className:"flex items-center justify-between gap-2 mt-1.5",children:[e.jsx("span",{className:Y("text-[11px]",i?"text-rose-800/90":"text-amber-800/90"),children:t.pending_request?`Increase to ${t.pending_request.requested.toLocaleString()} requested, pending review`:i?"New connects are refused until the allowance is raised":"Ask for more before a large batch"}),e.jsx("button",{type:"button",onClick:s,className:Y("h-6 px-2 rounded text-[11px] font-medium transition-colors shrink-0",i?"bg-rose-600 hover:bg-rose-700 text-white":"bg-amber-600 hover:bg-amber-700 text-white"),children:t.pending_request?"View request":i?"Get more mailboxes":"Request more"})]})]})}function Iu({view:t,onBack:s,onClose:n}){const a={pick:"Connect a sending account",gmail:"Gmail or Google Workspace",outlook:"Outlook or Microsoft 365",smtp_imap:"Any provider via SMTP / IMAP",bulk:"Many mailboxes from one CSV"};return e.jsxs("div",{className:"h-12 px-3 border-b border-slate-200 flex items-center gap-2.5 shrink-0",children:[t!=="pick"&&e.jsx("button",{type:"button",onClick:s,"aria-label":"Back",className:"size-7 rounded-md text-slate-500 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center justify-center transition-colors",children:e.jsx(xr,{className:"w-3.5 h-3.5"})}),e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium",children:"Mailbox"}),e.jsx("div",{className:"h-4 w-px bg-slate-200"}),e.jsx("span",{className:"text-[12px] text-slate-600 truncate",children:a[t]}),e.jsx("button",{type:"button",onClick:n,"aria-label":"Close",className:"ml-auto size-7 rounded-md text-slate-500 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center justify-center transition-colors",children:e.jsx(ve,{className:"w-3.5 h-3.5"})})]})}
18const Lu={gmail:{label:"Gmail and Google Workspace",vars:["BOX_GOOGLE_CLIENT_ID","BOX_GOOGLE_CLIENT_SECRET"]},outlook:{label:"Outlook and Microsoft 365",vars:["BOX_OUTLOOK_CLIENT_ID","BOX_OUTLOOK_CLIENT_SECRET"]}};function Gn({provider:t,selfHosted:s}){const{label:n,vars:a}=Lu[t];return e.jsxs("div",{className:"p-4",children:[s&&e.jsxs("div",{className:"mb-3 rounded-md border border-sky-200 bg-sky-50 p-3 flex items-start gap-2.5",children:[e.jsx(Ra,{className:"w-4 h-4 text-sky-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[12.5px] font-medium text-sky-900",children:"Skip the OAuth setup: connect Control Cloud"}),e.jsx("p",{className:"text-[12.5px] text-sky-800 mt-1",children:"Linked instances sign mailboxes in through Control's own Google and Microsoft apps, and the cloud warms them. Free for 10 mailboxes."}),e.jsx("a",{href:"/app/settings/control-cloud",className:"mt-2 inline-flex h-7 px-2.5 items-center gap-1.5 rounded-md bg-sky-600 hover:bg-sky-700 text-white text-[12px] font-medium transition-colors",children:"Connect Control Cloud"})]})]}),e.jsx("div",{className:"rounded-md border border-amber-200 bg-amber-50 p-3",children:e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx(ds,{className:"w-4 h-4 text-amber-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"text-[12.5px] font-medium text-amber-900",children:[n," is not configured on this deployment"]}),e.jsxs("p",{className:"text-[12.5px] text-amber-800 mt-1",children:["Connecting these mailboxes needs an OAuth client. Add both values to the ",e.jsx("code",{className:"bg-white/70 px-1 rounded",children:".env"})," at the root of your Control install, then restart with"," ",e.jsx("code",{className:"bg-white/70 px-1 rounded",children:"make up"}),"."]}),e.jsx("ul",{className:"mt-2 space-y-1",children:a.map(r=>e.jsxs("li",{className:"text-[12px] font-mono text-amber-900 bg-white/70 rounded px-1.5 py-1",children:[r,"="]},r))})]})]})}),e.jsxs("a",{href:"https://docs.controlgtm.com/development/deployment-guide/#connect-mailboxes",target:"_blank",rel:"noreferrer",className:"mt-3 h-7 px-2.5 inline-flex items-center gap-1.5 rounded-md border border-slate-200 text-[12.5px] text-slate-700 hover:bg-slate-50 transition-colors",children:[e.jsx(Nt,{className:"w-3.5 h-3.5"}),"Full environment setup guide"]}),e.jsx("p",{className:"mt-3 text-[12px] text-slate-500",children:"No setup needed for any other provider: connect it over SMTP and IMAP instead."})]})}function Pu({onPick:t,viaCloud:s,onAdopted:n}){const a=[{key:"gmail",icon:e.jsx(qs,{className:"w-5 h-5"}),title:"Gmail / Google Workspace",sub:s?"Sign in through Control Cloud. Warmup included, no OAuth app needed.":"OAuth via Google. Best deliverability for Gmail.",tone:"primary"},{key:"outlook",icon:e.jsx(Ks,{className:"w-5 h-5"}),title:"Outlook / Microsoft 365",sub:s?"Sign in through Control Cloud. Warmup included, no OAuth app needed.":"OAuth via Microsoft. Native sync for Outlook accounts.",tone:"primary"},{key:"smtp_imap",icon:e.jsx(Us,{className:"w-4 h-5 text-slate-700"}),title:"Other (SMTP / IMAP)",sub:"Any provider with manual host, port, and app password.",tone:"neutral"},{key:"bulk",icon:e.jsx(Ea,{className:"w-4 h-4 text-slate-700"}),title:"Bulk import from CSV",sub:"Hundreds or thousands of SMTP / IMAP mailboxes in one go, with a report of anything that failed.",tone:"neutral"}];return e.jsxs("div",{className:"divide-y divide-slate-200/60",children:[a.map((r,i)=>e.jsxs(ne.button,{type:"button",onClick:()=>t(r.key),initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{delay:.04+i*.04,duration:.18,ease:"easeOut"},className:"w-full px-4 py-3.5 flex items-center gap-3 text-left group hover:bg-slate-50 transition-colors",children:[e.jsx("div",{className:"size-9 rounded-md border border-slate-200 bg-white flex items-center justify-center shrink-0 transition-colors group-hover:border-slate-300",children:r.icon}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[13px] font-medium text-slate-900 truncate",children:r.title}),e.jsx("div",{className:"text-[11.5px] text-slate-500 truncate",children:r.sub})]}),e.jsx(ja,{className:"w-4 h-4 text-slate-300 shrink-0 group-hover:text-slate-500 group-hover:translate-x-0.5 transition-all"})]},r.key)),s&&e.jsx(Du,{onAdopted:n})]})}function Du({onAdopted:t}){const s=oo(),n=lo(),[a,r]=b.useState(null),i=s.data??[];if(s.isLoading||i.length===0)return null;const l=async(d,h)=>{r(d);try{await n.mutateAsync(d),se.success(`${h} connected`),t()}catch(o){se.error(je(o))}finally{r(null)}};return e.jsxs("div",{className:"px-4 py-3 bg-sky-50/40",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx(Ra,{className:"w-3.5 h-3.5 text-sky-600"}),e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium",children:"In your Control Cloud workspace"})]}),e.jsx("div",{className:"space-y-1.5",children:i.map(d=>e.jsxs("div",{className:"flex items-center gap-2.5 rounded-md border border-slate-200 bg-white px-2.5 py-2",children:[e.jsx("div",{className:"size-7 rounded-md border border-slate-200 bg-white flex items-center justify-center shrink-0",children:d.provider==="gmail"?e.jsx(qs,{className:"w-4 h-4"}):e.jsx(Ks,{className:"w-4 h-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[12.5px] text-slate-900 truncate",children:d.email}),e.jsx("div",{className:"text-[11px] text-slate-500 truncate",children:"Connected on the cloud. Add it here to send campaigns from it."})]}),e.jsxs("button",{type:"button",disabled:a===d.id,onClick:()=>{l(d.id,d.email)},className:"shrink-0 h-7 px-2.5 rounded-md bg-slate-900 hover:bg-slate-800 text-white text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors disabled:opacity-60",children:[a===d.id?e.jsx(xe,{className:"w-3 h-3 animate-spin"}):e.jsx(ke,{className:"w-3 h-3"}),"Connect"]})]},d.id))})]})}function Vn({provider:t,busy:s,viaCloud:n,onConnect:a}){const r=t==="gmail"?"Google":"Microsoft",i=t==="gmail"?qs:Ks;return e.jsxs("div",{className:"px-5 py-6 space-y-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-11 rounded-md border border-slate-200 bg-white flex items-center justify-center shrink-0",children:e.jsx(i,{className:"w-6 h-6"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-[13.5px] font-medium text-slate-900",children:["Connect with ",r]}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:n?`Control Cloud opens the ${r} window on its own app. Approve and you're done.`:`We'll open a ${r} window. Approve the scopes and you're done.`})]})]}),n?e.jsxs("ul",{className:"text-[11.5px] text-slate-600 space-y-1.5 px-1",children:[e.jsx(Je,{children:"Sends campaigns and syncs replies from this server, as usual"}),e.jsx(Je,{children:"Control Cloud keeps the sign-in and warms the mailbox in its pool"}),e.jsx(Je,{children:"The mailbox also appears in your cloud workspace; remove it from either side"})]}):e.jsxs("ul",{className:"text-[11.5px] text-slate-600 space-y-1.5 px-1",children:[e.jsx(Je,{children:"Send and read mail on your behalf"}),e.jsx(Je,{children:"Track replies and deliveries"}),e.jsx(Je,{children:"Refresh tokens are stored encrypted; revoke any time"})]}),e.jsxs(ne.button,{type:"button",onClick:a,disabled:s,whileTap:s?void 0:{scale:.985},className:"w-full h-9 rounded-md bg-slate-900 hover:bg-slate-800 text-white text-[12.5px] font-medium inline-flex items-center justify-center gap-2 transition-colors disabled:opacity-60",children:[s?e.jsx(xe,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(ns,{className:"w-3.5 h-3.5"}),s?"Waiting for authorization…":`Continue with ${r}`]})]})}function Je({children:t}){return e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(ke,{className:"w-3 h-3 text-slate-400 mt-1 shrink-0"}),e.jsx("span",{children:t})]})}function Ou({onDone:t,onError:s}){const[n,a]=b.useState(""),[r,i]=b.useState(""),[l,d]=b.useState(""),[h,o]=b.useState("993"),[x,c]=b.useState(""),[f,m]=b.useState(""),[w,E]=b.useState("tls"),[_,M]=b.useState(""),[S,j]=b.useState("587"),[I,P]=b.useState(""),[R,C]=b.useState(""),[u,g]=b.useState("starttls"),y=b.useRef(!1),T=b.useRef(!1);b.useEffect(()=>{y.current||E(Na(Number(h)))},[h]),b.useEffect(()=>{T.current||g(va(Number(S)))},[S]);const[v,Q]=b.useState(!0),[ae,re]=b.useState(!1),ce=b.useRef(!1),Z=b.useRef(!1);b.useEffect(()=>{ce.current||c(r),!Z.current&&!v&&P(r)},[r,v]);function ie(){return v?{user:x,pass:f,host:_,port:Number(S)}:{user:I,pass:R,host:_,port:Number(S)}}function te(){return!(!n.trim()||!r.trim()||!l.trim()||!h.trim()||!x.trim()||!f||!_.trim()||!S.trim()||!v&&(!I.trim()||!R)||!Qt
18(Number(S))||!Qt(Number(h)))}async function de(){if(ae||!te())return;re(!0);const B=ie();try{await se.promise(tu({name:n.trim(),email:r.trim(),imap:{username:x.trim(),password:f,host:l.trim(),port:Number(h),security:w},smtp:{username:B.user.trim(),password:B.pass,host:B.host.trim(),port:B.port,security:u}}),{loading:"Verifying credentials…",success:"Mailbox connected",error:N=>je(N)}),t()}catch(N){s(N)}finally{re(!1)}}return e.jsxs("div",{children:[e.jsxs(Ss,{title:"Account",sub:"Name and address you send from",icon:e.jsx(ss,{className:"w-3.5 h-3.5"}),children:[e.jsx(Re,{label:"Name",children:e.jsx(qe,{value:n,onChange:a,placeholder:"Alex Rivera"})}),e.jsx(Re,{label:"Email",children:e.jsx(qe,{value:r,onChange:i,placeholder:"[email protected]"})})]}),e.jsxs(Ss,{title:"IMAP",sub:"Incoming, usually 993",icon:e.jsx(ts,{className:"w-3.5 h-3.5"}),children:[e.jsx(Re,{label:"Server",children:e.jsx(Yn,{host:l,onHost:d,hostPlaceholder:"imap.example.com",port:h,onPort:o,portPlaceholder:"993"})}),e.jsx(Re,{label:"Security",children:e.jsx(cn,{value:w,onChange:B=>{y.current=!0,E(B)}})}),e.jsx(Re,{label:"Username",children:e.jsx(qe,{value:x,onChange:B=>{ce.current=!0,c(B)},placeholder:r||"[email protected]"})}),e.jsx(Re,{label:"Password",children:e.jsx(qe,{value:f,onChange:m,placeholder:"App password",type:"password"})})]}),e.jsxs(Ss,{title:"SMTP",sub:"Outgoing, usually 587 or 465",icon:e.jsx(St,{className:"w-3.5 h-3.5"}),children:[e.jsx(Re,{label:"Server",children:e.jsx(Yn,{host:_,onHost:M,hostPlaceholder:"smtp.example.com",port:S,onPort:j,portPlaceholder:"587"})}),e.jsx(Re,{label:"Security",children:e.jsx(cn,{value:u,onChange:B=>{T.current=!0,g(B)}})}),e.jsxs("label",{className:"flex items-center gap-2 pl-[76px] pt-0.5 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:v,onChange:B=>Q(B.target.checked),className:"size-3.5 rounded border-slate-300 accent-slate-900"}),e.jsx("span",{className:"text-[11.5px] text-slate-600",children:"Use the same login as IMAP"})]}),e.jsx(ge,{initial:!1,children:!v&&e.jsx(ne.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.32,.72,0,1]},className:"overflow-hidden",children:e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx(Re,{label:"Username",children:e.jsx(qe,{value:I,onChange:B=>{Z.current=!0,P(B)},placeholder:r||"[email protected]"})}),e.jsx(Re,{label:"Password",children:e.jsx(qe,{value:R,onChange:C,placeholder:"App password",type:"password"})})]})},"smtp-creds")})]}),e.jsxs("div",{className:"px-4 py-2.5 border-t border-slate-200 bg-slate-50/60 flex items-center gap-2 min-w-0 sticky bottom-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-slate-500 min-w-0 flex-1",children:[e.jsx(Fs,{className:"w-3 h-3 shrink-0"}),e.jsx("span",{className:"truncate",children:"Verified against your server before saving."})]}),e.jsxs(ne.button,{type:"button",onClick:de,disabled:!te()||ae,whileTap:te()&&!ae?{scale:.97}:void 0,className:Y("shrink-0 h-7 px-3 rounded-md text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors","bg-slate-900 hover:bg-slate-800 text-white disabled:opacity-50 disabled:cursor-not-allowed"),children:[ae?e.jsx(xe,{className:"w-3 h-3 animate-spin"}):e.jsx(ke,{className:"w-3 h-3"}),"Connect"]})]})]})}function Ss({title:t,sub:s,icon:n,children:a}){return e.jsxs("div",{className:"px-4 py-3 border-b border-slate-200/60 last:border-b-0 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2 min-w-0",children:[e.jsx("span",{className:"text-slate-500 shrink-0",children:n}),e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium shrink-0",children:t}),e.jsx("div",{className:"h-3 w-px bg-slate-200 shrink-0"}),e.jsx("span",{className:"text-[11.5px] text-slate-500 truncate min-w-0",children:s})]}),e.jsx("div",{className:"space-y-2 min-w-0",children:a})]})}function Re({label:t,children:s}){return e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium w-16 shrink-0",children:t}),e.jsx("div",{className:"flex-1 min-w-0",children:s})]})}function Yn({host:t,onHost:s,hostPlaceholder:n,port:a,onPort:r,portPlaceholder:i}){return e.jsxs("div",{className:"flex items-stretch h-7 rounded-md border border-slate-200 bg-white focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100 transition-colors min-w-0 overflow-hidden",children:[e.jsx("input",{value:t,onChange:l=>s(l.target.value),placeholder:n,className:"flex-1 min-w-0 px-2.5 bg-transparent outline-none text-[12.5px] text-slate-900 placeholder:text-slate-400"}),e.jsx("div",{className:"w-px bg-slate-200 shrink-0"}),e.jsx("input",{value:a,onChange:l=>r(l.target.value),placeholder:i,inputMode:"numeric",className:"w-14 shrink-0 px-2 bg-slate-50/60 outline-none text-[12.5px] text-slate-900 placeholder:text-slate-400 tabular-nums text-center"})]})}async function $u(t=""){const s=new URLSearchParams;t&&s.set("to",t);const n=s.toString();return await be({method:"GET",url:`/unibox/compose/candidates${n?`?${n}`:""}`,authorization:!0})}function zu(t,s=!0){return $e({queryKey:["unibox","compose","candidates",t],queryFn:()=>$u(t),staleTime:15e3,placeholderData:fr,enabled:s})}async function Fu(t){return await be({method:"POST",url:"/unibox/compose",data:t,authorization:!0})}function Uu(){const t=Ee();return at({mutationFn:s=>Fu(s),onSuccess:()=>{t.invalidateQueries({queryKey:["unibox"]})}})}async function qu(t){const{idempotency_key:s,...n}=t;return await be({method:"POST",url:"/unibox/compose/draft",data:n,authorization:!0,headers:s?{"Idempotency-Key":s}:void 0})}function Ku(){const t=Ee();return at({mutationFn:s=>qu(s),onSuccess:()=>{t.invalidateQueries({queryKey:["subscription","credits"]})}})}const Qn=300;function Bu({value:t,autoTag:s,onChange:n,candidates:a,loading:r}){const[i,l]=b.useState(!1),[d,h]=b.useState(""),[o,x]=b.useState(null),[c,f]=b.useState(null),m=b.useRef(null);rs(m,()=>l(!1));const w=z(y=>y.emails),E=z(y=>y.tags),_=b.useCallback(()=>{const y=m.current;if(!y)return;const T=y.getBoundingClientRect(),v=document.documentElement.clientWidth,Q=window.innerHeight,ae=Math.min(Math.max(T.left,8),v-Qn-8),re=Q-T.bottom<300&&T.top>Q-T.bottom;f({top:re?T.top-4:T.bottom+4,left:ae,up:re})},[]);b.useEffect(()=>{if(!i){h(""),x(null);return}return _(),window.addEventListener("scroll",_,!0),window.addEventListener("resize",_),()=>{window.removeEventListener("scroll",_,!0),window.removeEventListener("resize",_)}},[i,_]);const M=b.useMemo(()=>a?.accounts??[],[a]),S=b.useMemo(()=>{const y=new Map;for(const T of w)y.set(T.id,T.tags??[]);return y},[w]),j=M.find(y=>y.recommended)??M[0],I=b.useCallback(y=>M.find(T=>(S.get(T.id)??[]).includes(y)),[M,S]),P=t==="auto"?s?I(s)??j:j:M.find(y=>y.id===t),R=s?E.find(y=>y.id===s)?.title:void 0,C=b.useMemo(()=>[...E].sort((y,T)=>y.position-T.position),[E]),u=b.useMemo(()=>{const y=d.trim().toLowerCase();return M.filter(T=>o&&!(S.get(T.id)??[]).includes(o)?!1:y?`${T.email} ${T.name}`.toLowerCase().includes(y):!0)},[M,d,o,S]),g=(y,T=null)=>{n(y,T),l(!1)};return e.jsxs("div",{ref:m,className:"relative min-w-0 flex-1",children:[e.jsxs("button",{type:"button",onClick:()=>l(y=>!y),className:"group max-w-full inline-flex items-center gap-1.5 h-6 pl-1 pr-1 -ml-1 rounded-md hover:bg-slate-50 transition-colors min-w-0",children:[t==="auto"?e.jsxs(e.Fragment,{children:[P?e.jsx("span",{className:"text-[12.5px] text-slate-800 truncate",children:P.email}):e.jsx("span",{className:"text-[12px] text-slate-400",children:r?"picking a mailbox…":"no active mailbox"}),e.jsx("span",{className:"h-4 px-1 rounded bg-slate-100 text-slate-500 text-[9.5px] font-medium uppercase tracking-wide shrink-0 max-w-[120px] truncate",children:R?`auto · ${R}`:"auto"})]}):P?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[12.5px] text-slate-900 font-medium truncate",children:P.name||P.email}),e.jsx("span",{className:"font-mono text-[10.5px] text-slate-500 truncate",children:P.email})]}):e.jsx("span",{className:"text-[12px] text-amber-700",children:"mailbox unavailable"}),e.jsx(vt,{className:"w-3 h-3 text-slate-300 shrink-0 group-hover:text-slate-500 transition-colors"})]}),_t.createPortal(e.jsx(ge,{children:i&&c&&e.jsxs(ne.div,{"data-floating":"",initial:{opacity:0,y:c.up?4:-4,scale:.98}
18,animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:c.up?4:-4,scale:.98},transition:{duration:.14,ease:[.16,1,.3,1]},style:{position:"fixed",left:c.left,width:Qn,zIndex:120,...c.up?{bottom:window.innerHeight-c.top}:{top:c.top}},className:"max-w-[calc(100vw-16px)] rounded-lg border border-slate-200 bg-white shadow-xl overflow-hidden",children:[e.jsxs("div",{className:"px-1.5 pt-1.5 pb-1 border-b border-slate-100 flex items-center gap-1",children:[e.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-1.5 px-1.5 h-6 rounded-md border border-slate-200 bg-white focus-within:border-sky-300 focus-within:ring-1 focus-within:ring-sky-100 transition-colors",children:[r?e.jsx(xe,{className:"w-3 h-3 animate-spin text-sky-500 shrink-0"}):e.jsx(cs,{className:"w-3 h-3 text-slate-400 shrink-0"}),e.jsx("input",{autoFocus:!0,value:d,onChange:y=>h(y.target.value),placeholder:"Search mailboxes…",className:"flex-1 min-w-0 bg-transparent text-[11.5px] text-slate-900 placeholder:text-slate-400 outline-none"})]}),C.length>0&&e.jsx(Qr,{icon:po,allLabel:"All tags",options:C.map(y=>({id:y.id,label:y.title,color:y.color})),value:o,onChange:x})]}),(()=>{const y=o?C.find(Q=>Q.id===o):void 0,T=o?I(o):j,v=t==="auto"&&(s??null)===(o??null);return e.jsxs("button",{type:"button",onClick:()=>g("auto",o),title:y?`Picks the best mailbox tagged ${y.title}`:j?`Picks ${j.email}${a?.recommended_reason?`: ${a.recommended_reason}`:""}`:"Picks the best mailbox for each recipient",className:Y("w-full h-8 px-2.5 flex items-center gap-2 text-left transition-colors hover:bg-slate-50",v&&"bg-sky-50/60"),children:[e.jsx(ls,{className:"w-3 h-3 text-sky-500 shrink-0"}),e.jsx("span",{className:"text-[11.5px] font-medium text-slate-900 whitespace-nowrap",children:y?`Auto in ${y.title}`:"Auto"}),e.jsx("span",{className:"min-w-0 flex-1 text-[10.5px] text-slate-400 truncate",children:T?T.email:y?"no mailbox carries this tag":"best mailbox per recipient"}),v&&e.jsx(ke,{className:"w-3 h-3 text-sky-600 shrink-0"})]})})(),e.jsx(Xr,{className:"border-t border-slate-100 max-h-52 overflow-y-auto",children:r&&M.length===0?e.jsxs(e.Fragment,{children:[e.jsx(Cs,{}),e.jsx(Cs,{}),e.jsx(Cs,{})]}):e.jsxs(e.Fragment,{children:[u.length===0&&e.jsx("div",{className:"px-3 py-3 text-[11px] text-slate-400",children:M.length===0?"No active mailboxes. Connect one under Emails.":"No mailboxes match."}),u.map(y=>e.jsx(Wu,{candidate:y,active:t===y.id,onPick:()=>g(y.id)},y.id))]})})]})}),document.body)]})}function Wu({candidate:t,active:s,onPick:n}){const a=t.daily_limit>0&&t.sent_today>=t.daily_limit;return e.jsxs("button",{type:"button",onClick:n,title:[t.name,...t.reasons].filter(Boolean).join(" · "),className:Y("w-full h-8 px-2.5 flex items-center gap-2 text-left transition-colors hover:bg-slate-50",s&&"bg-sky-50/60"),children:[e.jsx("span",{className:Y("size-1.5 rounded-full shrink-0",t.auth_state==="failing"?"bg-rose-500":t.auth_state==="passing"?"bg-emerald-500":"bg-slate-300")}),e.jsxs("span",{className:"min-w-0 flex-1 text-[11.5px] text-slate-800 truncate",children:[t.email,t.recommended&&e.jsx("span",{className:"ml-1.5 text-[9px] font-semibold uppercase tracking-wide text-sky-600",children:"best"})]}),t.history_messages>0&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] text-emerald-700 shrink-0",children:[e.jsx(Ao,{className:"w-2.5 h-2.5"}),t.history_messages]}),e.jsxs("span",{className:Y("font-mono text-[10px] tabular-nums shrink-0",a?"text-rose-500":"text-slate-400"),children:[t.sent_today,"/",t.daily_limit]}),s&&e.jsx(ke,{className:"w-3 h-3 text-sky-600 shrink-0"})]})}function Cs(){return e.jsxs("div",{className:"px-2.5 h-8 flex items-center gap-2",children:[e.jsx("span",{className:"size-1.5 rounded-full bg-slate-200 animate-pulse shrink-0"}),e.jsx("span",{className:"h-2 w-2/5 rounded bg-slate-100 animate-pulse"}),e.jsx("span",{className:"ml-auto h-2 w-8 rounded bg-slate-100/70 animate-pulse"})]})}function Hu(t){const s=t.match(/<([^>]+)>/);return s?s[1].trim():t.trim()}function Gu(t){const s=new Date(t),n=new Date,a=s.getFullYear()===n.getFullYear();return a&&s.getMonth()===n.getMonth()&&s.getDate()===n.getDate()?s.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):s.toLocaleDateString(void 0,{month:"short",day:"numeric",...a?{}
18:{year:"2-digit"}})}function Vu({address:t,displayName:s,affinityLine:n}){const a=Le(),r=z(f=>f.emails),[i,l]=b.useState("all"),[d,h]=b.useState(""),o=Jr({address:t,direction:i==="sent"?"sent":void 0,query:d.trim()||void 0,snoozed:"any"},!!t),x=b.useMemo(()=>new Set(r.map(f=>f.email.toLowerCase())),[r]),c=b.useCallback(f=>(f.from_addr??[]).some(m=>x.has(Hu(m).toLowerCase())),[x]);return e.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[e.jsxs("div",{className:"shrink-0 px-3 pt-2.5 pb-2 border-b border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] uppercase tracking-[0.14em] text-slate-400 font-semibold",children:[e.jsx(Rs,{className:"w-3 h-3"}),e.jsxs("span",{className:"truncate",children:["History with ",s||t]})]}),n&&e.jsx("div",{className:"mt-1 text-[10.5px] text-emerald-700",children:n}),e.jsx("div",{className:"mt-2 flex items-center gap-1",children:["all","sent"].map(f=>e.jsx("button",{type:"button",onClick:()=>l(f),className:Y("h-6 px-2 rounded-md text-[11px] font-medium transition-colors",i===f?"bg-slate-200/80 text-slate-800":"text-slate-500 hover:text-slate-800 hover:bg-slate-100"),children:f==="all"?"Conversations":"Sent"},f))}),e.jsx("div",{className:"mt-2",children:e.jsx(zr,{value:d,onChange:h,placeholder:"Search subjects…"})})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[o.isPending&&e.jsx("div",{className:"px-3 py-6 flex items-center justify-center text-slate-400",children:e.jsx(xe,{className:"w-4 h-4 animate-spin"})}),!o.isPending&&o.emails.length===0&&e.jsxs("div",{className:"px-3 py-6 text-center",children:[e.jsx("p",{className:"text-[12px] font-medium text-slate-600",children:i==="sent"?"Nothing sent yet":"No conversations yet"}),e.jsx("p",{className:"text-[10.5px] text-slate-400 mt-1 leading-relaxed",children:i==="sent"?"Emails you send to this address will show up here.":"This will be your first exchange with this address."})]}),o.emails.map(f=>{const m=c(f);return e.jsxs("button",{type:"button",onClick:()=>a(`/app/unibox/all/${encodeURIComponent(f.thread_id||f.id)}`),className:"w-full px-3 py-2 flex items-start gap-2 text-left border-b border-slate-50 hover:bg-slate-50 transition-colors group",children:[e.jsx("span",{className:Y("size-5 rounded-md inline-flex items-center justify-center shrink-0 mt-0.5",m?"bg-sky-50 text-sky-600":"bg-slate-100 text-slate-400"),title:m?"Latest message from you":"Latest message from them",children:m?e.jsx(St,{className:"w-2.5 h-2.5"}):e.jsx(Rs,{className:"w-2.5 h-2.5"})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"flex items-baseline gap-1.5 min-w-0",children:[e.jsx("span",{className:Y("text-[11.5px] truncate",f.has_unread?"font-semibold text-slate-900":"font-medium text-slate-700"),children:f.subject||"(no subject)"}),f.message_count>1&&e.jsxs("span",{className:"font-mono text-[9.5px] text-slate-400 shrink-0",children:["×",f.message_count]}),e.jsx("span",{className:"ml-auto font-mono text-[9.5px] text-slate-400 tabular-nums shrink-0",children:Gu(f.internal_date)})]}),f.snippet&&e.jsx("span",{className:"block text-[10.5px] text-slate-400 truncate leading-snug",children:f.snippet})]}),e.jsx(jt,{className:"w-3 h-3 text-slate-300 opacity-0 group-hover:opacity-100 transition-opacity shrink-0 mt-1"})]},f.id)}),o.hasNextPage&&e.jsx("button",{type:"button",onClick:()=>o.fetchNextPage(),disabled:o.isFetchingNextPage,className:"w-full h-8 text-[11px] text-slate-500 hover:text-slate-900 hover:bg-slate-50 transition-colors",children:o.isFetchingNextPage?"Loading…":"Load more"})]})]})}const Oe=4e3,Yu=696*60*60*1e3;function Xn(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())}function Qu(t){const s=t.match(/<([^>]+)>/);return s?s[1].trim():t.trim()}function zs(t){const s=new Date;return s.setHours(s.getHours()+t),s}function Jn(t,s){const n=new Date;return n.setDate(n.getDate()+t),n.setHours(s,0,0,0),n}function Xu(t){const s=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${s(t.getMonth()+1)}-${s(t.getDate())}T${s(t.getHours())}:${s(t.getMinutes())}`}function Ju(t){const s=new Date,n=t.getFullYear()===s.getFullYear()&&t.getMonth()===s.getMonth()&&t.getDate()===s.getDate(),a=t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"});return n?`today, ${a}
18`:t.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Zn(t){return JSON.stringify([t.to,t.cc,t.bcc,t.subject,t.body,t.email_account_id??"auto"])}const Zu=[{label:"In 1 hour",at:()=>zs(1)},{label:"In 3 hours",at:()=>zs(3)},{label:"Tomorrow 9:00",at:()=>Jn(1,9)},{label:"Tomorrow 17:00",at:()=>Jn(1,17)}];function em(){const t=Ie(l=>l.open),s=Ie(l=>l.prefillTo),n=Ie(l=>l.seed),a=Ie(l=>l.session),{pathname:r}=Ve(),i=b.useRef(r);return b.useEffect(()=>{if(i.current===r)return;i.current=r;const l=Ie.getState();l.open&&!l.minimized&&l.setMinimized(!0)},[r]),e.jsx(ge,{children:t&&e.jsx(tm,{prefillTo:s,seed:n},a)})}function tm({prefillTo:t,seed:s}){const n=Ie(G=>G.closeCompose),a=Ie(G=>G.minimized),r=Ie(G=>G.setMinimized),i=z(G=>G.emails),{user:l}=Ye(),d=Ut(G=>G.add),[h,o]=b.useState(s?s.to:t?[t]:[]),[x,c]=b.useState(s?.cc??[]),[f,m]=b.useState(s?.bcc??[]),[w,E]=b.useState((s?.cc?.length??0)>0),[_,M]=b.useState((s?.bcc?.length??0)>0),[S,j]=b.useState(s?.subject??""),[I,P]=b.useState(s?.body??""),[R,C]=b.useState(s?.email_account_id||"auto"),[u,g]=b.useState(null),[y,T]=b.useState(!1),[v,Q]=b.useState(!1),[ae,re]=b.useState(!1),[ce,Z]=b.useState(!1),[ie,te]=b.useState(()=>Xu(zs(2))),[de,B]=b.useState(!1),N=wa(),O=G=>{const pe=G.body_plain??"";P(Ne=>(Ne.trim()?`${Ne.trimEnd()}
19
20${pe}`:pe).slice(0,Oe)),G.subject&&!S.trim()&&j(G.subject),B(!1),se.success(`Inserted "${G.name}"`)},J=b.useRef(null),U=h.length>0?Qu(h[0]):"",D=zu(U),K=D.data,H=K?.contact??null,ee=H?`${H.first_name??""} ${H.last_name??""}`.trim()||H.email:"",A=!!K?.suppression&&h.length>0,L=b.useMemo(()=>{const G=K?.accounts??[];let pe;if(R==="auto"?pe=u?G.find(Ne=>(i.find(Mt=>Mt.id===Ne.id)?.tags??[]).includes(u)):G.find(Ne=>Ne.recommended)??G[0]:pe=G.find(Ne=>Ne.id===R),!!pe)return i.find(Ne=>Ne.id===pe.id)},[i,R,u,K]),$=b.useMemo(()=>{const G=(K?.accounts??[]).filter(Ne=>Ne.history_messages>0);return G.length===0?void 0:`Usually from ${G.reduce((Ne,Mt)=>Mt.history_messages>Ne.history_messages?Mt:Ne).email}`},[K]),p=Ku(),F=b.useCallback(G=>p.mutateAsync({to:U||void 0,subject:S.trim()||void 0,instruction:G,idempotency_key:crypto.randomUUID()}),[p,U,S]),q=Zr({value:I,onChange:P,generate:F,maxLen:Oe}),V=Kr(),oe=async()=>{if(!(!I.trim()||V.isPending))try{const pe=(await V.mutateAsync({prompt:`Write ONE short email subject line (max 8 words) for the email below. Return only the subject text, no quotes.
21
22${I.trim().slice(0,2e3)}`})).text.trim().split(`
23`)[0].replace(/^["']|["']$/g,"");pe&&j(pe)}catch(G){const pe=G;se.error(pe?.status===402?"You're out of AI credits.":je(pe))}},W=Uu(),X=I.trim(),le=h.length>0&&h.every(Xn)&&!!S.trim()&&!!X&&!A&&!v,ue=h.length>0||x.length>0||f.length>0||!!S.trim()||!!X,me=b.useRef(s?.id??crypto.randomUUID()),_e=b.useRef(!!s),fe=b.useRef(s?Zn(s):""),we=ei(),he=ti(),ye=Zn({to:h,cc:x,bcc:f,subject:S,body:I,email_account_id:R}),Ae=b.useCallback(()=>{ue&&ye!==fe.current&&(fe.current=ye,_e.current=!0,we.mutate({id:me.current,data:{email_account_id:R==="auto"?void 0:R,to:h,cc:x,bcc:f,subject:S,body:I}}))},[R,f,I,x,ye,ue,we,S,h]);b.useEffect(()=>{if(!ue||ye===fe.current)return;const G=window.setTimeout(Ae,1200);return()=>window.clearTimeout(G)},[ye,ue,Ae]);const dt=ue&&ye===fe.current&&!we.isPending,ut=b.useCallback(()=>{ue?(Ae(),se.success("Saved to Drafts")):_e.current&&he.mutate(me.current),n()},[n,he,ue,Ae]),Me=async G=>{if(!le){h.length===0?se.error("Add a recipient"):h.every(Xn)?A?se.error("This recipient is suppressed"):S.trim()?X||se.error("Body is empty"):se.error("Add a subject"):se.error("Recipient email looks invalid");return}Q(!0);try{const pe=await W.mutateAsync({email_account_id:R==="auto"?void 0:R,from_tag_id:R==="auto"&&u?u:void 0,to:h,cc:x.length?x:void 0,bcc:f.length?f:void 0,subject:S.trim(),body_plain:X,body_html:oi(X),...G?{send_mode:"scheduled",scheduled_at:G.toISOString()}:{send_mode:"instant"}});if(!G&&pe.send_mode==="instant"){const Ne=new Date().toISOString();d({taskId:pe.task_id,scheduledAt:li(pe.scheduled_at,l.undo_send_seconds||30),kind:"compose",to:h,subject:S.trim(),seed:{id:crypto.randomUUID(),email_account_id:R==="auto"?null:R,to:h,cc:x,bcc:f,subject:S.trim(),body:X,updated_at:Ne,created_at:Ne}})}else se.success(G?`Scheduled for ${Ju(G)} from ${pe.account_email}`:`Sent from ${pe.account_email}${pe.auto?" · picked automatically":""}`);_e.current&&he.mutate(me.current),n()}catch(pe){se.error(je(pe))}finally{Q(!1)}},Te=G=>{if(!Number.isFinite(G.getTime())||G.getTime()<=Date.now()+5e3){se.error("Pick a future time (a few seconds out, please)");return}if(G.getTime()-Date.now()>Yu){se.error("Scheduled send can't be more than 29 days out");return}re(!1),Z(!1),Me(G)},Fe=y&&!!U&&!a;return e.jsxs(ne.div,{initial:{opacity:0,y:24,scale:.98}
23,animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:16,scale:.98},transition:{type:"spring",stiffness:480,damping:38},className:"fixed z-[70] inset-x-2 bottom-2 sm:inset-x-auto sm:right-4 sm:bottom-4 flex items-stretch rounded-xl border border-slate-200 bg-white shadow-2xl overflow-hidden max-h-[min(660px,calc(100dvh-1rem))]",onKeyDown:G=>{G.key==="Escape"&&(G.stopPropagation(),ut())},children:[e.jsxs("div",{className:Y("flex flex-col w-full min-h-0",a?"sm:w-[280px]":"sm:w-[540px]"),children:[e.jsxs("div",{className:Y("shrink-0 h-8 pl-3 pr-1.5 flex items-center gap-2 bg-slate-100/80 select-none",a?"cursor-pointer hover:bg-slate-100":"border-b border-slate-200"),onClick:a?()=>r(!1):void 0,children:[e.jsx(No,{className:"w-3.5 h-3.5 text-slate-500 shrink-0"}),e.jsxs("span",{className:"min-w-0 flex-1 text-[11.5px] text-slate-500 truncate",children:[e.jsx("span",{className:"font-semibold text-slate-800",children:"New email"}),H?e.jsxs(e.Fragment,{children:[" ","to ",ee,H.company?`, ${H.company}`:""]}):U?e.jsxs(e.Fragment,{children:[" to ",U]}):null]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[!a&&ue&&e.jsx("span",{className:"mr-1 text-[10px] text-slate-400 select-none",children:we.isPending?"Saving…":dt?"Saved":""}),!a&&e.jsx("button",{type:"button",onClick:()=>T(G=>!G),disabled:!U,title:U?"Conversations and sent mail with this recipient":"Add a recipient to see your history with them",className:Y("hidden sm:inline-flex size-6 rounded-md items-center justify-center transition-colors disabled:opacity-30",Fe?"bg-slate-200 text-slate-700":"text-slate-400 hover:text-slate-700 hover:bg-slate-200/60"),children:e.jsx(Rs,{className:"w-3.5 h-3.5"})}),e.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),r(!a)},"aria-label":a?"Restore composer":"Minimize composer",title:a?"Restore":"Minimize; your draft stays while you work elsewhere",className:"size-6 inline-flex items-center justify-center rounded-md text-slate-400 hover:text-slate-700 hover:bg-slate-200/60 transition-colors",children:a?e.jsx(ua,{className:"w-3.5 h-3.5"}):e.jsx(Ta,{className:"w-3.5 h-3.5"})}),e.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),ut()},"aria-label":"Close composer",className:"size-6 inline-flex items-center justify-center rounded-md text-slate-400 hover:text-slate-700 hover:bg-slate-200/60 transition-colors",children:e.jsx(ve,{className:"w-3.5 h-3.5"})})]})]}),!a&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"shrink-0",children:[e.jsxs(Ft,{label:"To",children:[e.jsx(hs,{value:h,onChange:o,placeholder:"Search contacts or type an email",autoFocus:!t}),(!w||!_)&&e.jsxs("div",{className:"ml-auto flex items-center gap-0.5 shrink-0 self-start pt-px",children:[!w&&e.jsx("button",{type:"button",onClick:()=>E(!0),className:"h-5 px-1 rounded text-[11px] text-slate-400 hover:text-slate-700 transition-colors",children:"Cc"}),!_&&e.jsx("button",{type:"button",onClick:()=>M(!0),className:"h-5 px-1 rounded text-[11px] text-slate-400 hover:text-slate-700 transition-colors",children:"Bcc"})]})]}),w&&e.jsx(Ft,{label:"Cc",onRemove:()=>{c([]),E(!1)},children:e.jsx(hs,{value:x,onChange:c,placeholder:"Add Cc recipients"})}),_&&e.jsx(Ft,{label:"Bcc",onRemove:()=>{m([]),M(!1)},children:e.jsx(hs,{value:f,onChange:m,placeholder:"Add Bcc recipients"})}),e.jsx(Ft,{label:"From",children:e.jsx(Bu,{value:R,autoTag:u,onChange:(G,pe)=>{C(G),g(G==="auto"?pe:null)},candidates:K,loading:D.isPending})}),e.jsxs("div",{className:"flex items-center gap-2 px-3.5 border-b border-slate-100",children:[e.jsx("input",{type:"text",value:S,onChange:G=>j(G.target.value),placeholder:"Subject",className:"flex-1 min-w-0 h-9 bg-transparent text-[13px] font-medium text-slate-900 placeholder:text-slate-400 placeholder:font-normal outline-none"}),I.trim()&&!S.trim()&&e.jsxs("button",{type:"button",onClick:oe,disabled:V.isPending,title:"Suggest a subject from the body (from 1 credit)",className:"shrink-0 h-5 px-1.5 rounded inline-flex items-center gap-1 text-[10.5px] text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition-colors disabled:opacity-50",children:[V.isPending&&e.jsx(xe,{className:"w-2.5 h-2.5 animate-spin"}),"Suggest"]})]})]}),A&&e.jsxs("div",{className:"shrink-0 mx-3.5 mt-2 px-2.5 py-1.5 rounded-md border border-rose-200 bg-rose-50 flex items-start gap-1.5 text-[11.5px] text-rose-800",children:[e.jsx(Ca,{className:"w-3 h-3 mt-0.5 shrink-0"}),e.jsxs("span",{className:"leading-snug",children:[U," is suppressed for this workspace",K?.suppression?.reason?` (${K.suppression.reason})`:"",". Sending is blocked to protect your reputation."]})]}),e.jsxs("div",{className:"relative flex-1 min-h-0 flex flex-col",children:[e.jsx("textarea",{ref:J,value:I,onChange:G=>P(G.target.value.slice(0,Oe)),placeholder:"Write your email…",onKeyDown:G=>{(G.metaKey||G.ctrlKey)&&G.key==="Enter"&&(G.preventDefault(),Me())},className:"w-full flex-1 min-h-[160px] px-3.5 py-3 text-[13px] text-slate-800 placeholder:text-slate-400 bg-transparent resize-none focus:outline-none"}),q.phase==="busy"&&e.jsx("div",{className:"ai-sheen pointer-events-none absolute inset-0","aria-hidden":!0}),e.jsx(si,{ctrl:q,busyLabels:[ee?`Thinking about ${ee}…`:"Thinking about your recipient…","Writing your email…","Polishing…"]})]}),e.jsx(ni,{textareaRef:J,value:I,onChange:G=>P(G.slice(0,Oe)),getContext:()=>`Subject: ${S}
24
25${I}`,maxLen:Oe}),e.jsx(ai,{textareaRef:J,value:I,onChange:G=>P(G.slice(0,Oe)),onDraftReply:()=>q.start(),draftLabel:"Draft this email with AI",draftCost:"from 2 credits",contextHint:`It is a new outbound email${ee?` to ${ee}`:""}${S.trim()?` with the subject "${S.trim()}"`:""}.`,maxLen:Oe}),q.grounding&&!q.grounding.voice_profile&&e.jsxs("div",{className:"shrink-0 mx-3.5 mb-1.5 px-2.5 py-1.5 rounded-md border border-amber-200/60 bg-amber-50/60 text-[10.5px] text-amber-800 leading-snug",children:["AI doesn't know your product yet."," ",e.jsx(Ce,{to:"/app/sett
25ings/workspace",className:"font-medium underline underline-offset-2 hover:text-amber-950",children:"Set your voice profile"})," ","(what you sell, who to, how you sound) and drafts will stop being generic."]}),e.jsxs("div",{className:"shrink-0 px-3 py-2 border-t border-slate-200/60 flex flex-wrap items-center gap-1.5",children:[e.jsxs("button",{type:"button",onClick:()=>{Me()},disabled:!le,title:"Send now (⌘Enter)",className:"h-7 px-2.5 rounded-md bg-sky-600 hover:bg-sky-700 text-white text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[v?e.jsx(xe,{className:"w-3 h-3 animate-spin"}):e.jsx(St,{className:"w-3 h-3"}),v?"Sending":"Send",!v&&e.jsx(tt,{combo:"mod+enter"})]}),e.jsxs(Ht,{align:"start",side:"top",open:ae,onOpenChange:G=>{re(G),G||Z(!1)},children:[e.jsx(Gt,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:!le,title:"Send later, up to 29 days out",className:"h-7 px-2 rounded-md border border-slate-200 hover:border-slate-300 text-slate-700 hover:text-slate-900 text-[12px] inline-flex items-center gap-1 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(is,{className:"w-3 h-3"}),"Schedule",e.jsx(vt,{className:"w-3 h-3 text-slate-400"})]})}),e.jsx(Vt,{minWidth:240,children:ce?e.jsxs("div",{className:"px-1 py-1 w-[260px]",children:[e.jsx(Ts,{children:"Send at"}),e.jsx("div",{className:"mt-1",children:e.jsx(xo,{value:ie,onChange:te,stepMinutes:15})}),e.jsxs("div",{className:"mt-2 flex items-center gap-1.5",children:[e.jsxs("button",{type:"button",onClick:()=>Te(new Date(ie)),disabled:v,className:"h-7 px-2.5 rounded-md bg-sky-600 hover:bg-sky-700 text-white text-[12px] font-medium inline-flex items-center gap-1 transition-colors disabled:opacity-50",children:[e.jsx(ke,{className:"w-3 h-3"}),"Schedule"]}),e.jsx("button",{type:"button",onClick:()=>Z(!1),className:"h-7 px-2 rounded-md text-slate-500 hover:text-slate-900 hover:bg-slate-100 text-[12px] transition-colors",children:"Back"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ts,{children:"Send at"}),Zu.map(G=>e.jsx(He,{onSelect:()=>Te(G.at()),children:G.label},G.label)),e.jsx(Yt,{}),e.jsx(He,{onSelect:()=>Z(!0),closeOnSelect:!1,children:"Pick a time"})]})})]}),e.jsxs(Ht,{align:"start",side:"top",open:de,onOpenChange:B,children:[e.jsx(Gt,{asChild:!0,children:e.jsxs("button",{type:"button",title:"Drop a saved template into the email",className:"h-7 px-2 rounded-md border border-slate-200 hover:border-slate-300 text-slate-700 hover:text-slate-900 text-[12px] inline-flex items-center gap-1 transition-colors",children:[e.jsx(Hs,{className:"w-3 h-3"}),"Template",e.jsx(vt,{className:"w-3 h-3 text-slate-400"})]})}),e.jsx(Vt,{minWidth:340,className:"max-w-[92vw]",children:e.jsx(ri,{query:N,onPick:O,onClose:()=>B(!1)})})]}),e.jsx(ii,{email:h[0],onInsert:G=>P(pe=>(pe.trim()?`${pe.trimEnd()}
26
27${G}`:G).slice(0,Oe))}),I&&e.jsx("button",{type:"button",onClick:()=>P(""),className:"h-7 px-2 rounded-md text-slate-500 hover:text-slate-900 hover:bg-slate-100 text-[12px] transition-colors",children:"Discard"}),e.jsxs("span",{className:Y("ml-auto inline-flex items-center gap-1 h-5 px-1.5 rounded text-[10px] font-medium",L?.signature_sync&&L.signature_plain?.trim()?"bg-emerald-50 text-emerald-700":"bg-slate-100 text-slate-500"),title:L?.signature_sync&&L.signature_plain?.trim()?`The ${L.email} signature is appended on send.`:"No signature will be appended for the sending mailbox.",children:[e.jsx(Br,{className:"w-2.5 h-2.5"}),L?.signature_sync&&L.signature_plain?.trim()?"Signature on":"No signature"]}),e.jsxs("span",{className:"font-mono text-[10px] text-slate-400 tabular-nums",children:[I.length,"/",Oe]})]})]})]}),e.jsx(ge,{children:Fe&&e.jsx(ne.div,{initial:{width:0,opacity:0},animate:{width:300,opacity:1},exit:{width:0,opacity:0},transition:{duration:.2,ease:[.16,1,.3,1]},className:"hidden sm:block border-l border-slate-200 bg-slate-50/40 overflow-hidden",children:e.jsx("div",{className:"w-[300px] h-full",children:e.jsx(Vu,{address:U,displayName:ee||void 0,affinityLine:$})})})})]})}function Ft({label:t,onRemove:s,children:n}){return e.jsxs("div",{className:"flex items-start gap-2 px-3.5 py-[7px] border-b border-slate-100",children:[e.jsx("span",{className:"w-9 shrink-0 pt-[3px] text-[11px] text-slate-400",children:t}),e.jsx("div",{className:"flex-1 min-w-0 flex flex-wrap items-center gap-1.5",children:n}),s&&e.jsx("button",{type:"button",onClick:s,"aria-label":`Remove ${t}`,className:"size-5 inline-flex items-center justify-center rounded text-slate-300 hover:text-slate-600 hover:bg-slate-100 transition-colors shrink-0",children:e.jsx(ve,{className:"w-3 h-3"})})]})}const ea="warmbly:passkey-nudge-dismissed";function sm(){const[t,s]=k.useState(!1),[n,a]=k.useState(!1);k.useEffect(()=>{let l=!1;return(async()=>{try{if(sessionStorage.getItem(sn)!=="1"||(sessionStorage.removeItem(sn),localStorage.getItem(ea)==="1")||!gr()||!await br())return;const d=await ho();!l&&d.length===0&&s(!0)}catch{}})(),()=>{l=!0}},[]);const r=async()=>{a(!0);try{await jr(),se.success("Passkey added — use it to sign in next time."),s(!1)}catch(l){l instanceof wr||se.error(l?.message||"Couldn't create a passkey.")}finally{a(!1)}},i=()=>{try{localStorage.setItem(ea,"1")}catch{}s(!1)};return e.jsx(Gs,{open:t,onOpenChange:l=>{l||s(!1)},children:e.jsxs(Vs,{className:"sm:max-w-md bg-white",children:[e.jsxs(Ys,{children:[e.jsx("div",{className:"mx-auto 
27sm:mx-0 w-12 h-12 rounded-2xl bg-sky-50 flex items-center justify-center mb-1",children:e.jsx(Fs,{className:"w-6 h-6 text-sky-500"})}),e.jsx(Qs,{children:"Sign in faster with a passkey"}),e.jsx(Aa,{children:"Next time, use Touch ID, Face ID, or your device PIN to sign in instantly — no password, no email code. Your passkey stays on your device."})]}),e.jsxs(Ji,{className:"mt-2",children:[e.jsx("button",{type:"button",onClick:i,className:"h-9 px-3 rounded-md text-[13px] font-medium text-slate-500 hover:bg-slate-100 transition-colors",children:"Not now"}),e.jsxs("button",{type:"button",onClick:r,disabled:n,className:"h-9 px-4 rounded-md text-[13px] font-semibold text-white bg-gradient-to-b from-sky-500 to-sky-600 hover:from-sky-500 hover:to-sky-700 shadow-sm inline-flex items-center justify-center gap-2 disabled:opacity-60 disabled:pointer-events-none",children:[n&&e.jsx(yr,{className:"!w-4 h-4 text-white"}),"Set up passkey"]})]})]})})}function nm(){const[t,s]=b.useState(!1),[n,a]=b.useState("");b.useEffect(()=>{const l=d=>{const h=d.detail;a(h?.message?.trim()||"You don't have permission to do that."),s(!0)};return window.addEventListener("permission-denied",l),()=>window.removeEventListener("permission-denied",l)},[]);const r=/\b(plan|upgrade|trial|subscription|paid)\b/i.test(n),i=()=>s(!1);return e.jsx(ge,{children:t&&e.jsx(ne.div,{initial:{opacity:0}
27,animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[70] bg-slate-900/30 flex items-center justify-center p-4",onMouseDown:l=>{l.target===l.currentTarget&&i()},children:e.jsxs(ne.div,{initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:8,scale:.98},className:"w-full max-w-sm rounded-lg bg-white border border-slate-200 shadow-xl p-5 text-center",children:[e.jsx("div",{className:"flex justify-end -mt-1 -mr-1",children:e.jsx("button",{type:"button",onClick:i,"aria-label":"Close",className:"size-7 rounded-md text-slate-400 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center justify-center",children:e.jsx(ve,{className:"w-4 h-4"})})}),e.jsx("div",{className:`mx-auto mb-3 size-11 rounded-xl border flex items-center justify-center ${r?"bg-violet-50 border-violet-200 text-violet-600":"bg-amber-50 border-amber-200 text-amber-600"}`,children:r?e.jsx(ls,{className:"w-5 h-5"}):e.jsx(yt,{className:"w-5 h-5"})}),e.jsx("h3",{className:"text-[14px] font-semibold text-slate-900",children:r?"Upgrade required":"You don't have permission"}),e.jsxs("p",{className:"text-[12.5px] text-slate-500 leading-relaxed mt-1.5",children:[n,!r&&e.jsxs(e.Fragment,{children:[" ","Ask a workspace admin or the owner to grant you access from"," ",e.jsx("span",{className:"font-medium text-slate-700",children:"Settings → Roles & access"}),"."]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-2",children:[r&&e.jsx(Ce,{to:"/app/settings/billing",onClick:i,className:"inline-flex items-center h-8 px-3 rounded-md bg-violet-600 hover:bg-violet-700 text-white text-[12.5px] font-medium transition-colors",children:"View plans"}),e.jsx("button",{type:"button",onClick:i,className:`inline-flex items-center h-8 px-4 rounded-md text-[12.5px] font-medium transition-colors ${r?"border border-slate-200 bg-white hover:bg-slate-50 text-slate-700":"bg-slate-900 hover:bg-slate-800 text-white"}`,children:"Got it"})]})]})})})}function rx(){return na()?e.jsx(nl,{children:e.jsx($d,{children:e.jsxs(al,{children:[e.jsx(ol,{children:e.jsx(Bo,{children:e.jsx(Xo,{children:e.jsxs(Bd,{children:[e.jsx(Wd,{}),e.jsx(Pd,{})]})})})}),e.jsx(Qd,{}),e.jsx(eu,{}),e.jsx(Mu,{}),e.jsx(em,{}),e.jsx(sm,{}),e.jsx(nm,{})]})})}):e.jsx(Es,{to:"/auth/login",replace:!0})}export{rx as default};

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