1import{r,cE as ve,j as e,c7 as pa,dp as ul,e_ as Ds,cF as ue,c9 as Ls,dm as yt,ce as B,ch as xl,cc as pl,fC as fa,eu as sa,cf as fl,cg as gl,c6 as yl,Z as jt,dt as ta,dZ as aa,d0 as ga,fF as jl,gv as bl,gc as lt,eE as Es,dR as la,fs as na,d9 as ya,fY as vl,fZ as ra,dH as ia,cH as oa,cm as Nl,eX as ca,fk as wl,fl as Cl,dY as Sl,gw as kl,gx as Al}from"./vendor-BOPbLW7a.js";import{j as re,k as ie,l as oe,m as ce,q as xe,D as Je,a as We,b as Ge,c as pe,aG as bt,O as q,aH as Il,o as ja,n as J,p as Le,B as g,V as Ts,I,S as W,e as G,f as Y,h as Z,i as w,u as Fl,M as $s,d as $e,aI as ne,T as nt,F as rt,G as Ve,H as _,C as vt,J as it,L as N,K as H,P as El,ai as Tl,w as da,y as Fs,al as Pl,am as Dl,an as Ll,ao as $l,aC as Kl}from"./index-CCPRxbLk.js";import{A as ba,a as va}from"./avatar-BQuu4_F4.js";import{A as ot,a as ct,b as dt,c as mt,d as ht,e as ut,f as xt,g as pt}from"./alert-dialog-C4m06njz.js";import{g as Ml}from"./formError-KtRBom-m.js";import{u as Bl,C as Ol,i as zl}from"./useChunkedContactImport-Cuivtq7o.js";import{T as is}from"./tag-multi-select-BNJrrt6c.js";import{g as Na,a as Nt}from"./avatar-colors-8l0VClD5.js";import{u as Rl}from"./useCustomFields-BwKl25SY.js";import{C as _l}from"./ContactDetailsPanel-BHuf9n5T.js";import{d as Hl,e as ql}from"./sheet-BR4f69qC.js";import"./vendor-dates-CMWWcCEi.js";import"./vendor-voice-CjAdQv9k.js";import"./vendor-tiptap-BoiEPFyJ.js";import"./tabs-Blemm4Jm.js";import"./switch-C-FJsOjw.js";import"./separator-jHZD-mQA.js";import"./useContact-sWYYJJj5.js";import"./textarea-BBpK6nZ_.js";function ma(a,o){return o===0?0:Math.round(a/o*100)}function Ul({action:a,onClose:o}){var T,D;const[v,C]=r.useState("all"),[m,c]=r.useState(1),x=ve({queryKey:["bulk-action-items",a.id,v,m],queryFn:async()=>{const i=new URLSearchParams({page:String(m),pageSize:"20"});v!=="all"&&i.set("status",v);const h=await fetch(`/api/bulk-actions/${a.id}/items?${i}`,{credentials:"include"});if(!h.ok)throw new Error("Failed to load statistics");return h.json()}}),f=((T=x.data)==null?void 0:T.rows)??[];return e.jsx(re,{open:!0,onOpenChange:i=>{i||o()},children:e.jsxs(ie,{className:"max-w-3xl",children:[e.jsxs(oe,{children:[e.jsxs(ce,{children:["Bulk ",a.operation," stats"]}),e.jsx(xe,{children:"Per-contact results for this bulk action, broken down by outcome."})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{"data-testid":"stat-all",className:"rounded-lg border border-slate-200 p-3",children:[e.jsx("div",{className:"text-xs text-slate-500",children:"All"}),e.jsx("div",{className:"text-xl font-semibold",children:a.totalCount})]}),e.jsxs("div",{"data-testid":"stat-success",className:"rounded-lg border border-slate-200 p-3",children:[e.jsx("div",{className:"text-xs text-slate-500",children:"Success"}),e.jsxs("div",{className:"flex items-baseline justify-between",children:[e.jsx("span",{className:"text-xl font-semibold",children:a.successCount}),e.jsxs("span",{className:"text-xs text-emerald-600",children:[ma(a.successCount,a.totalCount)," %"]})]})]}),e.jsxs("div",{"data-testid":"stat-error",className:"rounded-lg border border-slate-200 p-3",children:[e.jsx("div",{className:"text-xs text-slate-500",children:"Error"}),e.jsxs("div",{className:"flex items-baseline justify-between",children:[e.jsx("span",{className:"text-xl font-semibold",children:a.errorCount}),e.jsxs("span",{className:"text-xs text-amber-600",children:[ma(a.errorCount,a.totalCount)," %"]})]})]})]}),e.jsx("div",{className:"flex gap-4 border-b border-slate-200 mt-4",children:["all","success","error"].map(i=>e.jsx("button",{type:"button",onClick:()=>{C(i),c(1)},className:`pb-2 text-sm capitalize ${v===i?"border-b-2 border-[var(--brand-primary)] font-semibold":"text-slate-500"}`,children:i},i))}),e.jsxs("table",{className:"w-full text-sm mt-3",children:[e.jsx("thead",{className:"bg-slate-50 text-left text-xs font-semibold text-slate-600",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"Action ID"}),e.jsx("th",{className:"px-3 py-2",children:"Identifier"}),e.jsx("th",{className:"px-3 py-2",children:"Status"})]})}),e.jsxs("tbody",{children:[f.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:3,className:"px-3 py-6 text-center text-slate-400",children:"No items."})}),f.map(i=>e.jsxs("tr",{className:"border-t border-slate-100",children:[e.jsx("td",{className:"px-3 py-2 font-mono text-xs",children:i.contactId??"â"}),e.jsx("td",{className:"px-3 py-2",children:i.identifier}),e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("span",{className:`rounded px-2 py-0.5 text-xs font-medium ${i.status==="success"?"bg-emerald-100 text-emerald-700":"bg-rose-100 text-rose-700"}`,children:i.status==="success"?"Success":"Error"}),i.error&&e.jsx("span",{className:"ml-2 text-xs text-slate-500",children:i.error})]})]},i.id))]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 text-sm mt-2",children:[e.jsx("button",{type:"button",disabled:m===1,onClick:()=>c(i=>i-1),className:"rounded border border-slate-200 px-3 py-1 disabled:opacity-40",children:"Previous"}),e.jsx("span",{className:"text-slate-500",children:m}),e.jsx("button",{type:"button",disabled:!((D=x.data)!=null&&D.hasMore),onClick:()=>c(i=>i+1),className:"rounded border border-slate-200 px-3 py-1 disabled:opacity-40",children:"Next"})]})]})})}const Ql={complete:"bg-emerald-100 text-emerald-700",pending:"bg-amber-100 text-amber-700",error:"bg-rose-100 text-rose-700",restored:"bg-slate-100 text-slate-700"};function ha(a){return a.charAt(0).toUpperCase()+a.slice(1)}
1function ua(a){if(!a)return"â";const o=new Date(a);return`${o.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} ${o.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}`}function Vl(){var j,E;const[a,o]=r.useState({dateFrom:"",dateTo:"",status:"",operation:""}),[v,C]=r.useState(1),[m,c]=r.useState(null),[x,f]=r.useState(null),[T,D]=r.useState(!1),i=pa(),h=ve({queryKey:["bulk-actions",a,v],queryFn:async()=>{const p=new URLSearchParams({page:String(v),pageSize:"20"});a.dateFrom&&p.set("dateFrom",a.dateFrom),a.dateTo&&p.set("dateTo",a.dateTo),a.status&&p.set("status",a.status),a.operation&&p.set("operation",a.operation);const Q=await fetch(`/api/bulk-actions?${p}`,{credentials:"include"});if(!Q.ok)throw new Error("Failed to load bulk actions");return Q.json()},staleTime:0,refetchOnMount:"always"}),K=((j=h.data)==null?void 0:j.rows)??[],U=async()=>{if(x){D(!0);try{const p=await fetch(`/api/bulk-actions/${x.id}/restore`,{method:"POST",credentials:"include"});if(!p.ok)throw await bt(p);f(null),await h.refetch(),i.invalidateQueries({queryKey:["/api/contacts"]})}catch(p){q(p instanceof Error?p:Il(),"Couldn't restore bulk action")}finally{D(!1)}}},d=p=>{o(Q=>({...Q,...p})),C(1)};return e.jsxs("div",{className:"px-5 pb-8",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-900",children:"Bulk actions"}),e.jsx("p",{className:"text-sm text-slate-500 mb-4",children:"Track progress and results for bulk actions."}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-4",children:[e.jsx("span",{className:"text-xs font-medium text-slate-500",children:"Filters"}),e.jsx("input",{type:"date","aria-label":"From date",value:a.dateFrom,onChange:p=>d({dateFrom:p.target.value}),className:"h-9 rounded-md border border-slate-200 px-2 text-sm"}),e.jsx("input",{type:"date","aria-label":"To date",value:a.dateTo,onChange:p=>d({dateTo:p.target.value}),className:"h-9 rounded-md border border-slate-200 px-2 text-sm"}),e.jsxs("select",{"aria-label":"Status",value:a.status,onChange:p=>d({status:p.target.value}),className:"h-9 rounded-md border border-slate-200 px-2 text-sm",children:[e.jsx("option",{value:"",children:"All statuses"}),e.jsx("option",{value:"pending",children:"Pending"}),e.jsx("option",{value:"complete",children:"Complete"}),e.jsx("option",{value:"error",children:"Error"}),e.jsx("option",{value:"restored",children:"Restored"})]}),e.jsxs("select",{"aria-label":"Operation",value:a.operation,onChange:p=>d({operation:p.target.value}),className:"h-9 rounded-md border border-slate-200 px-2 text-sm",children:[e.jsx("option",{value:"",children:"All actions"}),e.jsx("option",{value:"delete",children:"Delete"})]})]}),e.jsx("div",{className:"rounded-lg border border-slate-200",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 text-left text-xs font-semibold text-slate-600",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2",children:"Action label"}),e.jsx("th",{className:"px-4 py-2",children:"Operation"}),e.jsx("th",{className:"px-4 py-2",children:"Status"}),e.jsx("th",{className:"px-4 py-2",children:"User"}),e.jsx("th",{className:"px-4 py-2",children:"Created"}),e.jsx("th",{className:"px-4 py-2",children:"Completed"}),e.jsx("th",{className:"px-4 py-2",children:"Statistics"}),e.jsx("th",{className:"px-4 py-2",children:"Actions"})]})}),e.jsxs("tbody",{children:[h.isLoading&&e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"px-4 py-6 text-center text-slate-400",children:"Loadingâ¦"})}),!h.isLoading&&K.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"px-4 py-6 text-center text-slate-400",children:"No bulk actions yet."})}),K.map(p=>e.jsxs("tr",{className:"border-t border-slate-100",children:[e.jsx("td",{className:"px-4 py-2 text-[var(--brand-primary)] font-medium",children:p.label}),e.jsx("td",{className:"px-4 py-2",children:ha(p.operation)}),e.jsx("td",{className:"px-4 py-2",children:e.jsx("span",{className:`rounded px-2 py-0.5 text-xs font-medium ${Ql[p.status]??"bg-slate-100 text-slate-700"}`,children:ha(p.status)})}),e.jsx("td",{className:"px-4 py-2",children:p.userName}),e.jsx("td",{className:"px-4 py-2 text-slate-600",children:ua(p.createdAt)}),e.jsx("td",{className:"px-4 py-2 text-slate-600",children:ua(p.completedAt)}),e.jsx("td",{className:"px-4 py-2",children:e.jsx("button",{type:"button","aria-label":`Statistics for ${p.label}`,onClick:()=>c(p),className:"text-slate-500 hover:text-slate-900",children:e.jsx(ul,{className:"h-4 w-4"})})}),e.jsx("td",{className:"px-4 py-2",children:e.jsxs(Je,{children:[e.jsx(We,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":`Actions for ${p.label}`,className:"text-slate-500 hover:text-slate-900",children:e.jsx(Ds,{className:"h-4 w-4"})})}),e.jsxs(Ge,{align:"end",children:[e.jsx(pe,{onClick:()=>c(p),children:"View details"}),e.jsx(pe,{disabled:p.status==="restored"||p.operation!=="delete",onClick:()=>f(p),children:"Restore"})]})]})})]}
1,p.id))]})]})}),e.jsxs("div",{className:"flex items-center justify-between mt-3 text-sm",children:[e.jsxs("span",{className:"text-slate-500",children:["Page ",v]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{type:"button",disabled:v===1,onClick:()=>C(p=>p-1),className:"rounded border border-slate-200 px-3 py-1 disabled:opacity-40",children:"Previous"}),e.jsx("button",{type:"button",disabled:!((E=h.data)!=null&&E.hasMore),onClick:()=>C(p=>p+1),className:"rounded border border-slate-200 px-3 py-1 disabled:opacity-40",children:"Next"})]})]}),m&&e.jsx(Ul,{action:m,onClose:()=>c(null)}),e.jsx(re,{open:x!==null,onOpenChange:p=>{p||f(null)},children:e.jsxs(ie,{className:"max-w-md",children:[e.jsxs(oe,{children:[e.jsxs(ce,{children:["Restore bulk action ",x==null?void 0:x.operation]}),e.jsx(xe,{children:"This action will restore the bulk action to its original state."})]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx("button",{type:"button",onClick:()=>f(null),className:"rounded border border-slate-200 px-3 py-1.5 text-sm",children:"Cancel"}),e.jsx("button",{type:"button",onClick:U,disabled:T,className:"rounded bg-[var(--brand-primary)] px-3 py-1.5 text-sm text-white disabled:opacity-40",children:T?"Restoringâ¦":"Restore"})]})]})})]})}function Jl({contactIds:a,open:o,onOpenChange:v,onAdded:C}){const{toast:m}=ja(),[c,x]=r.useState(null),{data:f,isLoading:T}=ve({queryKey:["/api/campaigns/sms-campaigns?limit=200"],enabled:o}),D=(f==null?void 0:f.campaigns)??[];r.useEffect(()=>{o&&x(null)},[o]);const i=ue({mutationFn:async()=>{if(!c)throw new Error("Pick a campaign");return(await J("POST",`/api/campaigns/sms-campaigns/${c}/add-recipients`,{selection:{selection_type:"ids",contact_ids:a}})).json()},onSuccess:h=>{m({title:h!=null&&h.added?`Added ${h.added} contact${h.added===1?"":"s"} to the campaign`:(h==null?void 0:h.message)||"No new contacts added (already in the campaign)",description:h!=null&&h.added?"They were added as pending â use âSend pendingâ on the campaign to text them.":void 0}),v(!1),C==null||C()},onError:h=>q(h,"Couldn't add contacts to the campaign")});return e.jsx(re,{open:o,onOpenChange:v,children:e.jsxs(ie,{className:"max-w-md max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(oe,{children:[e.jsxs(ce,{children:["Add ",a.length.toLocaleString()," contact",a.length===1?"":"s"," to a campaign"]}),e.jsxs(xe,{children:["Pick an existing SMS campaign. The selected contacts are added as ",e.jsx("strong",{children:"pending"})," (not sent)."]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto rounded-md border divide-y divide-slate-100",children:T?e.jsxs("div",{className:"flex items-center justify-center gap-2 py-10 text-sm text-slate-400",children:[e.jsx(Ls,{className:"h-4 w-4 animate-spin"}),"Loading campaignsâ¦"]}):D.length===0?e.jsx("div",{className:"py-10 text-center text-sm text-slate-400",children:"No campaigns yet. Create one first."}):D.map(h=>e.jsxs("label",{className:`flex cursor-pointer items-center gap-3 px-3 py-2.5 hover:bg-slate-50 ${c===h.id?"bg-blue-50":""}`,children:[e.jsx("input",{type:"radio",name:"campaign",checked:c===h.id,onChange:()=>x(h.id)}),e.jsx("span",{className:"flex-1 truncate text-sm text-slate-700",children:h.name}),e.jsx("span",{className:"rounded-full border px-2 py-0.5 text-[10px] capitalize text-slate-500",children:h.status})]},h.id))}),e.jsxs(Le,{children:[e.jsx(g,{variant:"outline",onClick:()=>v(!1),disabled:i.isPending,children:"Cancel"}),e.jsxs(g,{onClick:()=>i.mutate(),disabled:i.isPending||c==null||a.length===0,children:[i.isPending?e.jsx(Ls,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(yt,{className:"mr-2 h-4 w-4"}),"Add to campaign"]})]})]})})}function Wl({value:a,onChange:o,placeholder:v="Add a tag...",className:C,id:m,disabled:c}){const[x,f]=r.useState(""),T=r.useRef(null),D=j=>{const E=j.split(",").map(Q=>Q.trim()).filter(Boolean);if(E.length===0)return;const p=[...a];for(const Q of E)p.some(we=>we.toLowerCase()===Q.toLowerCase())||p.push(Q);o(p),f("")},i=j=>{var p;const E=a.filter((Q,we)=>we!==j);o(E),(p=T.current)==null||p.focus()},h=j=>
1{j.key==="Enter"||j.key===","?(j.preventDefault(),D(x)):j.key==="Backspace"&&x===""&&a.length>0&&(j.preventDefault(),i(a.length-1))},K=j=>{const E=j.target.value;E.includes(",")?D(E):f(E)},U=()=>{x.trim()&&D(x)},d=j=>{const E=j.clipboardData.getData("text");(E.includes(",")||E.includes(` 2`))&&(j.preventDefault(),D(E.replace(/\n/g,",")))};return e.jsxs("div",{className:Ts("flex min-h-10 w-full flex-wrap items-center gap-1.5 rounded-md border border-input bg-background px-2 py-1.5 text-sm ring-offset-background focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2",c&&"cursor-not-allowed opacity-50",C),onClick:()=>{var j;return(j=T.current)==null?void 0:j.focus()},children:[a.map((j,E)=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md bg-neutral-100 px-2 py-0.5 text-sm text-neutral-800",children:[e.jsx("span",{className:"max-w-[12rem] truncate",children:j}),e.jsx("button",{type:"button","aria-label":`Remove ${j}`,disabled:c,onClick:p=>{p.stopPropagation(),i(E)},className:"-mr-0.5 inline-flex h-4 w-4 items-center justify-center rounded-full text-neutral-500 hover:bg-neutral-200 hover:text-neutral-900 focus:outline-none focus:ring-2 focus:ring-ring",children:e.jsx(B,{className:"h-3 w-3"})})]},`${j}-${E}`)),e.jsx("input",{ref:T,id:m,type:"text",value:x,onChange:K,onKeyDown:h,onBlur:U,onPaste:d,disabled:c,placeholder:a.length===0?v:"",className:"flex-1 min-w-[8rem] bg-transparent px-1 py-0.5 outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed"})]})}const ft=[{id:"createdDate",label:"Created date",fields:["createdAfter","createdBefore"]},{id:"lastActivity",label:"Last Activity",fields:["lastActivityAfter","lastActivityBefore"]},{id:"tags",label:"Tags",fields:["tags"]},{id:"contactData",label:"Contact data",fields:["hasEmail","hasPhone","hasAddress","customField"]},{id:"location",label:"Location",fields:["state","city"]},{id:"meta",label:"Meta",fields:["source","businessName","birthdayMonth"]}],Ps={createdAfter:{label:"Created after",type:"date",groupId:"createdDate"},createdBefore:{label:"Created before",type:"date",groupId:"createdDate"},lastActivityAfter:{label:"Last activity after",type:"date",groupId:"lastActivity"},lastActivityBefore:{label:"Last activity before",type:"date",groupId:"lastActivity"},tags:{label:"Tags",type:"tag-multiselect",groupId:"tags"},hasEmail:{label:"Has email",type:"tristate-enum",groupId:"contactData"},hasPhone:{label:"Has phone",type:"tristate-enum",groupId:"contactData"},hasAddress:{label:"Has address",type:"tristate-enum",groupId:"contactData"},customField:{label:"Has custom field",type:"custom-field",groupId:"contactData"},state:{label:"State",type:"text",groupId:"location"},city:{label:"City",type:"text",groupId:"location"},source:{label:"Source",type:"text",groupId:"meta"},businessName:{label:"Business name",type:"text",groupId:"meta"},birthdayMonth:{label:"Birthday month",type:"enum",groupId:"meta"}},Gl=[{value:"1",label:"January"},{value:"2",label:"February"},{value:"3",label:"March"},{value:"4",label:"April"},{value:"5",label:"May"},{value:"6",label:"June"},{value:"7",label:"July"},{value:"8",label:"August"},{value:"9",label:"September"},{value:"10",label:"October"},{value:"11",label:"November"},{value:"12",label:"December"}];function xa(){return{createdAfter:"",createdBefore:"",lastActivityAfter:"",lastActivityBefore:"",tags:[],hasEmail:"",hasPhone:"",hasAddress:"",customField:"",state:"",city:"",source:"",businessName:"",birthdayMonth:""}}function Yl({fieldKey:a,value:o,onChange:v,availableTags:C,customFields:m}){const c=Ps[a];if(!c)return null;switch(c.type){case"date":return e.jsx(I,{type:"date",value:o,onChange:x=>v(x.target.value),className:"h-9 text-sm"});case"text":return e.jsx(I,{type:"text",placeholder:`Enter ${c.label.toLowerCase()}â¦`,value:o,onChange:x=>v(x.target.value),className:"h-9 text-sm"});case"tristate-enum":{const x=o===""?"any":o;return e.jsxs(W,{value:x,onValueChange:f=>v(f==="any"?"":f),children:[e.jsx(G,{className:"h-9 text-sm",children:e.jsx(Y,{})}),e.jsxs(Z,{children:[e.jsx(w,{value:"any",children:"Any"}),e.jsx(w,{value:"yes",children:"Yes"}),e.jsx(w,{value:"no",children:"No"})]})]})}case"custom-field":{const[x="",f=""]=(o||"").split("::"),T=x,D=f==="no"?"no":"yes",i=(h,K)=>v(h?`${h}::${K}`:"");return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(W,{value:T||"none",onValueChange:h=>i(h==="none"?"":h,D),children:[e.jsx(G,{className:"h-9 text-sm",children:e.jsx(Y,{placeholder:"Select a custom fieldâ¦"})}),e.jsxs(Z,{children:[e.jsx(w,{value:"none",children:"Select a custom fieldâ¦"}),m.map(h=>e.jsx(w,{value:h.fieldKey,children:h.fieldLabel},h.fieldKey))]})]}),e.jsxs(W,{value:D,onValueChange:h=>i(T,h),disabled:!T,children:[e.jsx(G,{className:"h-9 text-sm",children:e.jsx(Y,{})}),e.jsxs(Z,{children:[e.jsx(w,{value:"yes",children:"Has value"}),e.jsx(w,{value:"no",children:"Is empty / missing"})]})]}),m.length===0&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No custom fields yet â import
2contacts with custom columns to create them."})]})}case"tag-multiselect":{let x=[];try{x=JSON.parse(o||"[]")}catch{x=[]}return e.jsx(is,{value:x,onChange:f=>v(JSON.stringify(f)),availableTags:C,placeholder:"Filter by tagsâ¦",allowCreate:!1})}case"enum":return e.jsxs(W,{value:o||"any",onValueChange:x=>v(x==="any"?"":x),children:[e.jsx(G,{className:"h-9 text-sm",children:e.jsx(Y,{placeholder:"Any month"})}),e.jsxs(Z,{children:[e.jsx(w,{value:"any",children:"Any month"}),Gl.map(x=>e.jsx(w,{value:x.value,children:x.label},x.value))]})]});default:return null}}function Zl({open:a,onClose:o,onApply:v,availableTags:C=[],customFields:m=[],initialFilters:c}){var Ke;const[x,f]=r.useState("groups"),[T,D]=r.useState(null),[i,h]=r.useState(null),[K,U]=r.useState(""),[d,j]=r.useState("");function E(l){for(const[L,se]of Object.entries(l))if(L==="tags"){if(Array.isArray(se)&&se.length>0)return{fieldKey:L,rawValue:JSON.stringify(se)}}else if(typeof se=="string"&&se!==""&&se!=="any")return{fieldKey:L,rawValue:se};return null}r.useEffect(()=>{var l;if(a){if(j(""),c){const L=E(c);if(L){const se=((l=Ps[L.fieldKey])==null?void 0:l.groupId)??null;D(se),h(L.fieldKey),U(L.rawValue),f("configure");return}}f("groups"),D(null),h(null),U("")}},[a]);function p(l){D(l),h(null),U(""),j(""),f("fields")}function Q(l){h(l),U(""),f("configure")}function we(){x==="configure"?f("fields"):x==="fields"&&(j(""),f("groups"))}function ae(){const l=xa();if(i)if(i==="tags")try{l.tags=JSON.parse(K||"[]")}catch{l.tags=[]}else K!==""&&(l[i]=K);v(l),o()}function de(){v(xa()),o()}const X=ft.find(l=>l.id===T)??null,Ye=i?Ps[i]:null,y=c?(Ke=E(c))==null?void 0:Ke.fieldKey:null,Ce=T?Object.entries(Ps).filter(([,l])=>l.groupId===T).filter(([,l])=>d.trim()?l.label.toLowerCase().includes(d.trim().toLowerCase()):!0):[],ee=d.trim()?ft.filter(l=>l.label.toLowerCase().includes(d.trim().toLowerCase())):ft,Ks={groups:"Advanced Filters",fields:(X==null?void 0:X.label)??"Select field",configure:(Ye==null?void 0:Ye.label)??"Configure filter"};return e.jsx(xl,{open:a,onOpenChange:l=>{l||o()},children:e.jsxs(Hl,{children:[e.jsx(ql,{}),e.jsxs(pl,{className:Ts("fixed inset-y-0 right-0 z-50 flex h-full flex-col bg-background shadow-xl","transition ease-in-out","data-[state=open]:animate-in data-[state=open]:slide-in-from-right data-[state=open]:duration-500","data-[state=closed]:animate-out data-[state=closed]:slide-out-to-right data-[state=closed]:duration-300"),style:{width:"420px",maxWidth:"100vw"},children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border px-4 py-3",children:[x!=="groups"&&e.jsx("button",{type:"button",onClick:we,className:"flex items-center justify-center rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground","aria-label":"Go back",children:e.jsx(fa,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-sm font-semibold text-foreground",children:Ks[x]})]}),(x==="groups"||x==="fields")&&e.jsx("div",{className:"border-b border-border px-4 py-2.5",children:e.jsx(I,{value:d,onChange:l=>j(l.target.value),placeholder:x==="groups"?"Search filter groupsâ¦":"Search fieldsâ¦",className:"h-8 text-sm",autoFocus:!0})}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[x==="groups"&&e.jsx("div",{children:ee.length===0?e.jsxs("p",{className:"px-4 py-6 text-center text-sm text-muted-foreground",children:["No groups match â",d,"â"]}):ee.map(l=>{const L=!!y&&l.fields.includes(y);return e.jsxs("button",{type:"button",onClick:()=>p(l.id),className:Ts("flex w-full items-center justify-between px-4 py-3.5 text-sm text-foreground","border-b border-border/50 transition-colors hover:bg-muted/60"),children:[e.jsxs("span",{className:"flex items-center gap-2",children:[l.label,L&&e.jsx("span",{className:"flex h-4 min-w-4 items-center justify-center rounded-full bg-blue-600 px-1 text-[10px] font-semibold leading-none text-white",children:"1"})]}),e.jsx(sa,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]},l.id)})}),x==="fields"&&e.jsx("div",{children:Ce.length===0?e.jsx("p",{className:"px-4 py-6 text-center text-sm text-muted-foreground",children:d.trim()?`No fields match "${d}"`:"No fields in this group."}):Ce.map(([l,L])=>e.jsxs("button",{type:"button",onClick:()=>Q(l),className:Ts("flex w-full items-center justify-between px-4 py-3.5 text-sm text-foreground","border-b border-border/50 transition-colors hover:bg-muted/60"),
2children:[e.jsx("span",{children:L.label}),e.jsx(sa,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]},l))}),x==="configure"&&i&&e.jsxs("div",{className:"px-4 py-5 space-y-3",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Value"}),e.jsx(Yl,{fieldKey:i,value:K,onChange:U,availableTags:C,customFields:m})]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border bg-background px-4 py-3",children:[e.jsx("button",{type:"button",className:"text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline",onClick:de,children:"Clear filter"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(g,{variant:"outline",size:"sm",onClick:o,children:"Cancel"}),x==="configure"&&e.jsx(g,{size:"sm",onClick:ae,children:"Apply"})]})]}),e.jsx(fl,{className:"sr-only",children:"Advanced Filters"}),e.jsx(gl,{className:"sr-only",children:"Refine your contact list by selecting a filter group, field, and value."})]})]})})}function Pn(a){a.prefetchQuery({queryKey:["/api/tags"]}),a.prefetchQuery({queryKey:["/api/smart-lists"]})}const De=()=>({createdAfter:"",createdBefore:"",lastActivityAfter:"",lastActivityBefore:"",tags:[],hasEmail:"any",hasPhone:"any",hasAddress:"any",customFieldKey:"",customFieldHas:"any",state:"",city:"",businessName:"",source:"",birthdayMonth:""}),wa=()=>`contacts:list-state:${Kl()??"global"}`,Xl=()=>{try{const a=sessionStorage.getItem(wa());if(!a)return null;const o=JSON.parse(a);return o&&typeof o=="object"?o:null}catch{return null}},en=a=>{try{sessionStorage.setItem(wa(),JSON.stringify(a))}catch{}},gt=a=>(a.createdAfter?1:0)+(a.createdBefore?1:0)+(a.lastActivityAfter?1:0)+(a.lastActivityBefore?1:0)+(a.tags.length>0?1:0)+(a.hasEmail!=="any"?1:0)+(a.hasPhone!=="any"?1:0)+(a.hasAddress!=="any"?1:0)+(a.customFieldKey&&a.customFieldHas!=="any"?1:0)+(a.state.trim()?1:0)+(a.city.trim()?1:0)+(a.businessName.trim()?1:0)+(a.source?1:0)+(a.birthdayMonth?1:0),sn=[{value:"01",label:"January"},{value:"02",label:"February"},{value:"03",label:"March"},{value:"04",label:"April"},{value:"05",label:"May"},{value:"06",label:"June"},{value:"07",label:"July"},{value:"08",label:"August"},{value:"09",label:"September"},{value:"10",label:"October"},{value:"11",label:"November"},{value:"12",label:"December"}],tn=a=>({createdAfter:a.createdAfter,createdBefore:a.createdBefore,lastActivityAfter:a.lastActivityAfter,lastActivityBefore:a.lastActivityBefore,tagIds:a.tags.map(o=>o.id).filter(o=>o!=null),hasEmail:a.hasEmail,hasPhone:a.hasPhone,hasAddress:a.hasAddress,customFieldKey:a.customFieldKey,customFieldHas:a.customFieldHas,state:a.state,city:a.city,businessName:a.businessName,source:a.source,birthdayMonth:a.birthdayMonth}),an=(a,o)=>({createdAfter:a.createdAfter??"",createdBefore:a.createdBefore??"",lastActivityAfter:a.lastActivityAfter??"",lastActivityBefore:a.lastActivityBefore??"",tags:(a.tagIds??[]).map(v=>o.find(C=>C.id===v)).filter(v=>v!=null),hasEmail:a.hasEmail??"any",hasPhone:a.hasPhone??"any",hasAddress:a.hasAddress??"any",customFieldKey:a.customFieldKey??"",customFieldHas:a.customFieldHas??"any",state:a.state??"",city:a.city??"",businessName:a.businessName??"",source:a.source??"",birthdayMonth:a.birthdayMonth??""});function ln({value:a,onChange:o,availableTags:v,customFields:C}){const m=(c,x)=>o({...a,[c]:x});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"text-xs font-medium",children:"Created after"}),e.jsx(I,{type:"date",value:a.createdAfter,onChange:c=>m("createdAfter",c.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"text-xs font-medium",children:"Created before"}),e.jsx(I,{type:"date",value:a.createdBefore,onChange:c=>m("createdBefore",c.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"text-xs font-medium",children:"Last activity after"}
2),e.jsx(I,{type:"date",value:a.lastActivityAfter,onChange:c=>m("lastActivityAfter",c.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"text-xs font-medium",children:"Last activity before"}),e.jsx(I,{type:"date",value:a.lastActivityBefore,onChange:c=>m("lastActivityBefore",c.target.value)})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"text-xs font-medium",children:"Tags"}),e.jsx(is,{value:a.tags,onChange:c=>m("tags",c),availableTags:v,placeholder:"Filter by tags..."}),e.jsx("p",{className:"text-[11px] text-gray-500",children:"Matches contacts that have any of the selected tags."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"text-xs font-medium",children:"Has email"}),e.jsxs(W,{value:a.hasEmail,onValueChange:c=>m("hasEmail",c),children:[e.jsx(G,{children:e.jsx(Y,{})}),e.jsxs(Z,{children:[e.jsx(w,{value:"any",children:"Any"}),e.jsx(w,{value:"yes",children:"Has email"}),e.jsx(w,{value:"no",children:"No email"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"text-xs font-medium",children:"Has phone"}),e.jsxs(W,{value:a.hasPhone,onValueChange:c=>m("hasPhone",c),children:[e.jsx(G,{children:e.jsx(Y,{})}),e.jsxs(Z,{children:[e.jsx(w,{value:"any",children:"Any"}),e.jsx(w,{value:"yes",children:"Has phone"}),e.jsx(w,{value:"no",children:"No phone"})]})]})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"text-xs font-medium",children:"Has address"}),e.jsxs(W,{value:a.hasAddress,onValueChange:c=>m("hasAddress",c),children:[e.jsx(G,{children:e.jsx(Y,{})}),e.jsxs(Z,{children:[e.jsx(w,{value:"any",children:"Any"}),e.jsx(w,{value:"yes",children:"Has address"}),e.jsx(w,{value:"no",children:"No address"})]})]})]})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"text-xs font-medium",children:"Custom field"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs(W,{value:a.customFieldKey||"none",onValueChange:c=>o({...a,customFieldKey:c==="none"?"":c,customFieldHas:c==="none"?"any":a.customFieldHas==="any"?"yes":a.customFieldHas}),children:[e.jsx(G,{children:e.jsx(Y,{placeholder:"Select fieldâ¦"})}),e.jsxs(Z,{children:[e.jsx(w,{value:"none",children:"None"}),C.map(c=>e.jsx(w,{value:c.fieldKey,children:c.fieldLabel},c.fieldKey))]})]}),e.jsxs(W,{value:a.customFieldHas,onValueChange:c=>m("customFieldHas",c),disabled:!a.customFieldKey,children:[e.jsx(G,{children:e.jsx(Y,{})}),e.jsxs(Z,{children:[e.jsx(w,{value:"any",children:"Any"}),e.jsx(w,{value:"yes",children:"Has value"}),e.jsx(w,{value:"no",children:"Is empty / missing"})]})]})]}),e.jsx("p",{className:"text-[11px] text-gray-500",children:"Matches contacts by presence of a custom field value."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"text-xs font-medium",children:"State"}),e.jsx(I,{placeholder:"e.g. California",value:a.state,onChange:c=>m("state",c.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"text-xs font-medium",children:"City"}),e.jsx(I,{placeholder:"e.g. Los Angeles",value:a.city,onChange:c=>m("city",c.target.value)})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"text-xs font-medium",children:"Business name"}),e.jsx(I,{placeholder:"Contains...",value:a.businessName,onChange:c=>m("businessName",c.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"text-xs font-medium",children:"Source"}),e.jsxs(W,{value:a.source||"any",onValueChange:c=>m("source",c==="any"?"":c),children:[e.jsx(G,{children:e.jsx(Y,{})}),e.jsxs(Z,{children:[e.jsx(w,{value:"any",children:"Any source"}),e.jsx(w,{value:"manual",children:"Manual"}),e.jsx(w,{value:"import",children:"Import"}),e.jsx(w,{value:"sms",children:"SMS"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"text-xs font-medium",children:"Birthday month"}),e.jsxs(W,{value:a.birthdayMonth||"any",onValueChange:c=>m("birthdayMonth",c==="any"?"":c),children:[e.jsx(G,{children:e.jsx(Y,{})}),e.jsxs(Z,{children:[e.jsx(w,{value:"any",children:"Any month"}),sn.map(c=>e.jsx(w,{value:c.value,children:c.label},c.value))]})]})]})]})]})}const nn=500;function rn(a,o){const v=[];for(let C=0;C<a.length;C+=o)v.push(a.slice(C,C+o));return v}const Ca=a=>a?a.startsWith("+1")&&a.length===12?`+1 (${a.substring(2,5)}) ${a.substring(5,8)}-${a.substring(8)}`:a:"-",on=[],cn=jt.memo(function({contact:o,isSelected:v,visibleColumns:C,visibleCustomFields:m,rowTags:c,onToggleSelect:x,onOpenContact:f,onEditContact:T,onDeleteContact:D}){return e.jsxs(Ve,{className:"hover:bg-rose-50/20 border-b border-slate-100/60 transition-all duration-150 group",children:[e.jsx(H,{className:"w-[50px] min-w-[50px] align-middle",style:{padding:0},children:e.jsx("div",{className:"flex justify-center items-center w-full h-full",children:e.jsx(vt,{checked:v,onCheckedChange:()=>x(o.id),className:"border-slate-300 rounded-[6px] data-[state=checked]:bg-[var(--brand-primary)] data-[state=checked]:border-[var(--brand-primary)]"})})}),C.name&&e.jsx(H,{className:"py-2.5 px-4 text-left align-middle",children:e.jsxs("div",{className:"flex items-center justify-start gap-3 w-full",children:[e.jsx(ba,{className:"h-8 w-8 shrink-0 border border-slate-100 shadow-sm",children:e.jsx(va,{className:`${Nt(o.firstName||o.phoneNumber||"")} text-white text-[10px] font-bold flex items-center justify-center`,children:Na([o.firstName,o.lastName].filter(
2Boolean).join(" "))})}),e.jsx("button",{className:"font-semibold text-sm text-slate-800 hover:text-[var(--brand-primary)] hover:underline text-left transition-colors",onClick:()=>f(o),children:o.firstName||o.lastName?`${o.firstName||""} ${o.lastName||""}`.trim():"-"})]})}),C.phone&&e.jsx(H,{className:"py-2.5 px-4 text-left align-middle",children:e.jsxs("div",{className:"flex items-center justify-start text-sm text-slate-600 w-full font-medium",children:[o.phoneNumber&&e.jsx(Sl,{className:"h-3.5 w-3.5 mr-2 text-slate-400"}),Ca(o.phoneNumber)||"-"]})}),C.email&&e.jsx(H,{className:"py-2.5 px-4 text-left align-middle",children:e.jsxs("div",{className:"flex items-center justify-start text-sm text-slate-600 w-full",children:[o.email&&e.jsx(ya,{className:"h-3.5 w-3.5 mr-2 text-slate-400"}),o.email||""]})}),C.businessName&&e.jsx(H,{className:"py-2.5 px-4 text-sm text-slate-600 text-left align-middle",children:o.businessName||"-"}),C.location&&e.jsx(H,{className:"py-2.5 px-4 text-sm text-slate-600 text-left align-middle",children:[o.city,o.state,o.zipCode].filter(Boolean).join(", ")||"-"}
2),C.createdAt&&e.jsxs(H,{className:"py-2.5 px-4 text-sm text-slate-600 text-left align-middle font-medium",children:[Fs(o.createdAt,{month:"short",day:"numeric",year:"numeric"},"en-US")," ",Fs(o.createdAt,{hour:"2-digit",minute:"2-digit"},"en-US")]}),C.lastActivity&&e.jsx(H,{className:"py-2.5 px-4 text-sm text-slate-600 text-left align-middle font-medium",children:o.lastMessageAt?e.jsxs("div",{className:"flex items-center justify-start w-full",children:[e.jsx(ga,{className:"h-3.5 w-3.5 mr-2 text-slate-400"}),Fs(o.lastMessageAt,{month:"short",day:"numeric",year:"numeric"},"en-US")," ",Fs(o.lastMessageAt,{hour:"2-digit",minute:"2-digit"},"en-US")]}):e.jsx("span",{className:"text-slate-400",children:"â"})}),C.tags&&e.jsx(H,{className:"py-2.5 px-4 text-left align-middle",children:(()=>{const i="#94a3b8",K=c.slice(0,3),U=c.length-3;return e.jsxs("div",{className:"flex flex-wrap justify-start gap-1 w-full",children:[K.map(d=>e.jsx($s,{variant:"outline",className:"font-semibold px-2.5 py-0.5 text-[11px] rounded-full whitespace-nowrap shadow-none border transition-all",style:{borderColor:d.color||i,color:d.color||i,backgroundColor:`${d.color||i}12`},children:d.name},d.id)),U>0&&e.jsx(Pl,{children:e.jsxs(Dl,{children:[e.jsx(Ll,{asChild:!0,children:e.jsxs($s,{variant:"secondary",tabIndex:0,className:"font-semibold px-2.5 py-0.5 text-[11px] rounded-full whitespace-nowrap bg-slate-100 text-slate-500 border-0 shadow-none cursor-default",children:["+",U," more"]},"tag-overflow")}),e.jsx($l,{children:e.jsx("div",{className:"flex flex-col gap-0.5",children:c.slice(3).map(d=>e.jsx("span",{children:d.name},d.id))})})]})})]})})()}),m.map(i=>{const h=o.customFields,K=h==null?void 0:h[i.fieldKey];return e.jsx(H,{className:"py-2.5 px-4 text-sm whitespace-nowrap text-left align-middle",children:K!=null&&K!==""?K:e.jsx("span",{className:"text-slate-400",children:"â"})},i.fieldKey)}),e.jsx(H,{className:"w-12 p-0 align-middle",children:e.jsx("div",{className:"flex justify-center items-center w-full h-full",children:e.jsxs(Je,{children:[e.jsx(We,{asChild:!0,children:e.jsx(g,{variant:"ghost",className:"h-8 w-8 p-0 text-slate-500 hover:bg-slate-100 hover:text-slate-900 rounded-lg","aria-label":"Contact actions",children:e.jsx(Ds,{className:"h-4 w-4"})})}),e.jsxs(Ge,{align:"end",children:[e.jsxs(pe,{onClick:()=>T(o),className:"cursor-pointer",children:[e.jsx(kl,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx($e,{}),e.jsxs(pe,{onClick:()=>D(o.id),className:"text-red-600 focus:bg-red-50 focus:text-red-600 cursor-pointer",children:[e.jsx(Es,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})})]},o.id)});function Dn({openContactId:a}={}){var Jt,Wt,Gt,Yt,Zt,Xt,ea;const{user:o,isLoading:v}=Fl(),C=(o==null?void 0:o.id)??1,{toast:m}=ja(),[c,x]=yl(),f=r.useRef(Xl()).current,[T,D]=r.useState(()=>(f==null?void 0:f.search)??""),[i,h]=r.useState(new Set),[K,U]=r.useState(!1),[d,j]=r.useState({mode:"ids",ids:[],excludedIds:[]}),[E,p]=jt.useState(""),[Q,we]=jt.useState(!1),[ae,de]=r.useState(()=>{const s=new URLSearchParams(window.location.search).get("page"),t=parseInt(s||"",10);if(!isNaN(t)&&t>0)return t;const n=f==null?void 0:f.page;return n&&n>0?n:1}),[X,Ye]=r.useState(()=>{const s=new URLSearchParams(window.location.search).get("limit"),t=parseInt(s||"",10);if([10,25,50,100].includes(t))return t;const n=f==null?void 0:f.pageSize;return n&&[10,25,50,100].includes(n)?n:10}),[y,Ce]=r.useState(()=>{const s=new URLSearchParams(window.location.search),t=s.get("sortKey"),n=s.get("sortDirection");return t&&(n==="asc"||n==="desc")?{key:t,direction:n}:(f==null?void 0:f.sort)??null}),[ee,Ks]=r.useState(()=>(f==null?void 0:f.search)??""),Ke=T.trim()!==ee,[l,L]=r.useState(De),se=gt(l),Ms=se>0,me=s=>{L(t=>{const n=De();return{...t,[s]:n[s]}}),de(1)},[fe,wt]=r.useState("all"),Sa=[{id:"all",name:"All"},{id:"recent",name:"Recently Added"},{id:"bulk-actions",name:"Bulk Actions"}],[ka,os]=r.useState(!1),[cs,Ct]=r.useState(""),[ds,St]=r.useState(De),[Ne,Fe]=r.useState(null),[Aa,ms]=r.useState(!1),[Ia,hs]=r.useState(!1),[Bs,Os]=r.useState(null),[Me,zs]=r.useState(null),[dn,mn]=r.useState(!1),[Rs,us]=r.useState(!1),[Fa,_s]=r.useState(!1),[Ea,Hs]=r.useState(!1),[Ta,Ze]=r.useState(!1),[Xe,qs]=r.useState([]),[xs,ps]=r.useState([]),[fs,gs]=r.useState(!1),[Pa,es]=r.useState(null),[ss,Be]=r.useState(""),[kt,ys]=r.useState(!1),[Oe,Us]=r.useState(""),[js,bs]=r.useState(""),[At,vs]=r.useState(!1),[ts,Qs]=r.useState(""),[Se,Ns]=r.useState(!1),[O,ke]=r.useState({name:!0,phone:!0,email:!0,businessName:!0,location:!0,createdAt:!0,lastActivity:!0,tags:!0}),[ws,It]=r.useState(new Set),[Ee,Vs]=r.useState(null),[Da,Ft]=r.useState(!1),[Et,as]=r.useState(null),[ls,ze]=r.useState(""),[M,Ae]=r.useState(null),[he,Re]=r.useState({}),[b,le]=r.useState({firstName:"",lastName:"",phoneNumber:"",email:"",businessName:"",birthday:"",address:"",city:"",state:"",zipCode:"",tags:"",customFields:{}}),[_e,La]=r.useState([]),[ge,Cs]=r.useState(new Set),[$a,Tt]=r.useState(!1),{importing:Ka,progress:Te,run:Ma}=Bl(),[Ba,Js]=r.useState(null),[je,Ws]=r.useState(null),{data:V}=Rl(),P=pa(),Gs=ue({mutationFn:({id:s})=>J("DELETE",`/api/custom-fields/${s}`),onSuccess:(s,{key:t})=>{It(n=>{const u=new Set(n);return u.delete(t),u}),P.invalidateQueries({queryKey:["custom-fields"]}),Vs(null),m({title:"Custom field deleted"})},onError:s=>q(s,"Couldn't delete custom field")}),Ys=ue({mutationFn:({id:s,label:t})=>J("PATCH",`/api/custom-fields/${s}`,{fieldLabel:t}),onSuccess:()=>{P.invalidateQueries({queryKey:["custom-fields"]}),as(null),ze(""),m({title:"Custom field renamed"})},onError:s=>q(s,"Couldn't rename custom field")}),{data:Ss}=ve({queryKey:["/api/tags"]}),Ie=r.useMemo(()=>(Ss==null?void 0:Ss.tags)??[],[Ss]),He=(M==null?void 0:M.id)??null,Pt=((Jt=ve({queryKey:[`/api/tags/contact/${He}`],enabled:He!=null}).data)==null?void 0:Jt.tags)??[],Dt=ue({mutationFn:({contactId:s,tagIds:t,tagNames:n})=>J("POST",`/api/tags/contact/${s}`,{tagIds:t,tagNames:n}),onSuccess:(s,t)=>{P.invalidateQueries({queryKey:[`/api/tags/contact/${t.contactId}`]}),P.invalidateQueries({queryKey:["/api/tags"]}),P.invalidateQueries({queryKey:["/api/tags/contacts/batch"]})}}),Oa=ue({mutationFn:({contactId:s,tagId:t})=>J("DELETE",`/api/tags/contact/${s}/${t}`),onSuccess:(s,t)=>{P.invalidateQueries({queryKey:[`/api/tags/contact/${t.contactId}`]}),P.invalidateQueries({queryKey:["/api/tags"]}),P.invalidateQueries({queryKey:["/api/tags/contacts/batch"]})}}),Lt=()=>{P.invalidateQueries({queryKey:["/api/tags"]}),P.invalidateQueries({queryKey:["/api/tags/contacts/batch"]})},ns=ue({mutationFn:({tagId:s,name:t})=>J("PATCH",`/api/tags/${s}`,{name:t}),onSuccess:()=>{Lt(),es(null),Be(""),m({title:"Tag renamed"})},onError:s=>q(s,"Couldn't rename tag")}),Zs=ue({mutationFn:s=>J("DELETE",`/api/tags/${s}`),onSuccess:(s,t)=>{Lt(),ps(n=>n.filter(u=>u.id!==t)),m({title:"Tag deleted",description:"Removed from all contacts."})},onError:s=>q(s,"Couldn't delete tag")}),{data:Xs}=ve({queryKey:["/api/smart-lists"]}),za=(Xs==null?void 0:Xs.smartLists)??[],{data:Ra}=ve({queryKey:["/api/pipelines"],enabled:kt}),$t=Ra??[],_a=((Wt=$t.find(s=>
2s.id===Number(Oe)))==null?void 0:Wt.stages)??[],{data:Ha}=ve({queryKey:["/api/team/assignable-reps"],enabled:At}),qa=Ha??[],et=ue({mutationFn:s=>J("POST","/api/smart-lists",s),onSuccess:()=>P.invalidateQueries({queryKey:["/api/smart-lists"]})}),Ua=ue({mutationFn:s=>J("DELETE",`/api/smart-lists/${s}`),onSuccess:()=>P.invalidateQueries({queryKey:["/api/smart-lists"]})}),Kt=s=>{wt(s),L(De()),de(1)},Qa=s=>{wt(`user:${s.id}`),L(an(s.filters,Ie)),de(1)},Va=s=>{if(He==null)return;const t=Pt;for(const n of s)t.some(S=>n.id!=null?S.id===n.id:S.name===n.name)||(n.id!=null?Dt.mutate({contactId:He,tagIds:[n.id],tagNames:[]}):Dt.mutate({contactId:He,tagIds:[],tagNames:[n.name]}));for(const n of t)!s.some(S=>n.id!=null?S.id===n.id:S.name===n.name)&&n.id!=null&&Oa.mutate({contactId:He,tagId:n.id})},st=r.useMemo(()=>{const s=new URLSearchParams({page:ae.toString(),pageSize:X.toString()});y&&(s.set("sortKey",y.key==="name"?"firstName":y.key),s.set("sortDirection",y.direction)),ee&&s.set("search",ee),(fe==="recent"||fe==="customers")&&s.set("smartList",fe),l.createdAfter&&s.set("createdAfter",l.createdAfter),l.createdBefore&&s.set("createdBefore",l.createdBefore),l.lastActivityAfter&&s.set("lastActivityAfter",l.lastActivityAfter),l.lastActivityBefore&&s.set("lastActivityBefore",l.lastActivityBefore);const t=l.tags.map(n=>n.id).filter(n=>n!=null);return t.length>0&&s.set("tagIds",t.join(",")),l.hasEmail!=="any"&&s.set("hasEmail",l.hasEmail),l.hasPhone!=="any"&&s.set("hasPhone",l.hasPhone),l.hasAddress!=="any"&&s.set("hasAddress",l.hasAddress),l.customFieldKey&&l.customFieldHas!=="any"&&(s.set("customFieldKey",l.customFieldKey),s.set("customFieldHas",l.customFieldHas)),l.state.trim()&&s.set("state",l.state.trim()),l.city.trim()&&s.set("city",l.city.trim()),l.businessName.trim()&&s.set("businessName",l.businessName.trim()),l.source&&s.set("source",l.source),l.birthdayMonth&&s.set("birthdayMonth",l.birthdayMonth),s.toString()},[ae,X,y,ee,fe,l]),Ja=r.useMemo(()=>["/api/contacts",st,C],[st,C]),be=ve({queryKey:Ja,queryFn:async()=>{const s=await fetch(`/api/contacts?${st}`,{credentials:"include"});if(!s.ok)throw await bt(s);return s.json()},enabled:!v,placeholderData:Al,staleTime:3e4}),z=r.useMemo(()=>{var s;return((s=be.data)==null?void 0:s.data)??[]},[be.data]),te=((Yt=(Gt=be.data)==null?void 0:Gt.pagination)==null?void 0:Yt.total)??z.length,rs=Math.max(1,((Xt=(Zt=be.data)==null?void 0:Zt.pagination)==null?void 0:Xt.totalPages)??1),tt=be.isPending;r.useEffect(()=>{be.error&&q(be.error,"Couldn't load contacts")},[be.error]);const Mt=r.useMemo(()=>z.map(s=>s.id),[z]),Bt=Mt.join(","),{data:ks}=ve({queryKey:["/api/tags/contacts/batch",Bt],queryFn:async()=>{const s=await J("GET",`/api/tags/contacts/batch?ids=${Bt}`);if(!s)throw new Error("No response from server");return s.json()},enabled:Mt.length>0,staleTime:3e4}),at=r.useMemo(()=>{const s=(ks==null?void 0:ks.tagsByContact)??{},t={};for(const[n,u]of Object.entries(s))t[Number(n)]=u;return t},[ks]),Ot=r.useRef(!0);r.useEffect(()=>{if(Ot.current){Ot.current=!1;return}(d.mode==="all"||i.size>0)&&m({description:"Filter changed â selection cleared."}),h(new Set),j({mode:"ids",ids:[],excludedIds:[]})},[ee,l,X,fe]),r.useEffect(()=>{Rs&&Wa()},[Rs]);const zt=r.useRef(!0);r.useEffect(()=>{const s=setTimeout(()=>{Ks(T),zt.current?zt.current=!1:de(1)},400);return()=>clearTimeout(s)},[T]),r.useEffect(()=>{be.isFetching||de(s=>s>rs?rs:s)},[rs,be.isFetching]),r.useEffect(()=>{const s=new URLSearchParams(window.location.search);s.set("page",ae.toString()),s.set("limit",X.toString()),y?(s.set("sortKey",String(y.key)),s.set("sortDirection",y.direction)):(s.delete("sortKey"),s.delete("sortDirection"));const t=s.toString();window.location.search.replace("?","")!==t&&window.history.replaceState(null,"","?"+t)},[ae,X,y]),r.useEffect(()=>{en({search:ee,page:ae,pageSize:X,sort:y})},[ee,ae,X,y]),r.useEffect(()=>{if(!a)return;const s=z.find(t=>t.id===a);s?Fe(s):z.length>0&&fetch(`/api/modules/contacts/${a}`,{credentials:"include"}).then(t=>t.ok?t.json():null).then(t=>{t&&Fe(t)}).catch(()=>{})},[a,z]),r.useEffect(()=>{Ne&&!c.includes("/detail/")&&Fe(null)},[c]);const Pe=()=>{P.invalidateQueries({queryKey:["/api/contacts"]})},Wa=async()=>{Tt(!0);try{const s=await fetch("/api/conversations?limit=100",{credentials:"include"});if(s.ok){const n=((await s.json()).conversations||[]).map(F=>
2({phone:F.contactPhone,name:F.contactName||F.contactPhone,lastMessage:F.lastMessage||"",lastMessageTime:F.lastMessageTime||""})),u=new Set(z.map(F=>F.phoneNumber)),S=n.filter(F=>!u.has(F.phone));La(S)}}catch{}finally{Tt(!1)}},Rt=ue({mutationFn:async()=>{const s=await fetch("/api/contacts",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({userId:1,firstName:b.firstName||null,lastName:b.lastName||null,phoneNumber:b.phoneNumber||null,email:b.email||null,businessName:b.businessName||null,birthday:b.birthday||null,address:b.address||null,city:b.city||null,state:b.state||null,zipCode:b.zipCode||null,tags:b.tags?b.tags.split(",").map(t=>t.trim()):null,customFields:b.customFields||{},source:"manual"})});if(!s.ok)throw await bt(s)},onSuccess:()=>{m({title:"Contact Added",description:`${b.firstName||"Contact"} has been added`}),ms(!1),le({firstName:"",lastName:"",phoneNumber:"",email:"",businessName:"",birthday:"",address:"",city:"",state:"",zipCode:"",tags:"",customFields:{}}),Pe()},onError:s=>{const t=Ml(s);t?Re(t):q(s,"Couldn't add contact")}}),Ga=()=>{if(!b.phoneNumber&&!b.email){m({title:"Error",description:"Please provide at least a phone number or email",variant:"destructive"});return}Re({}),Rt.mutate()},_t=ue({mutationFn:async s=>{if(!(await fetch(`/api/contacts/${s.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({firstName:s.firstName,lastName:s.lastName,phoneNumber:s.phoneNumber,email:s.email,businessName:s.businessName,tags:s.tags,customFields:s.customFields??{}})})).ok)throw new Error("Failed to update contact")},onSuccess:()=>{m({title:"Contact Updated",description:"Contact has been updated successfully"}),hs(!1),Ae(null),Pe()},onError:s=>{q(s,"Couldn't update contact")}}),Ya=()=>{M&&_t.mutate(M)},As=ue({mutationFn:async s=>{if(!(await fetch(`/api/contacts/${s}`,{method:"DELETE",credentials:"include"})).ok)throw new Error("Failed to delete contact")},onSuccess:()=>{m({title:"Contact Deleted",description:"Contact has been removed"}),Os(null),Pe()},onError:s=>{q(s,"Couldn't delete contact")}}),Za=async()=>{const s=d.mode==="all",t=s?te-d.excludedIds.length:i.size;if(!s&&t===0||!confirm(`Are you sure you want to delete ${t} contact${t!==1?"s":""}? You can restore this from the Bulk Actions tab.`))return;let n;if(s)try{const ye=await fetch("/api/contacts/resolve-ids",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({selection_type:"all",filters:Qe(),...d.excludedIds.length>0?{excluded_ids:d.excludedIds}:{}})});if(!ye.ok){q(new Error("Failed to resolve contacts"),"Bulk delete failed");return}const $=await ye.json();n=Array.isArray($==null?void 0:$.ids)?$.ids:[]}catch(ye){q(ye instanceof Error?ye:new Error("Failed to resolve contacts"),"Bulk delete failed");return}else n=Array.from(i);const u=rn(n,nn);Ws({done:0,total:n.length});let S=0,F=0,k=null,A=null;for(const ye of u){try{const $=await fetch("/api/contacts/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({contactIds:ye,...A?{bulkActionId:A}:{}})}),R=await $.json().catch(()=>null);if(!$.ok)throw new Error((R==null?void 0:R.message)??"Delete failed");A??(A=(R==null?void 0:R.bulkActionId)??null),S+=Array.isArray(R==null?void 0:R.deleted)?R.deleted.length:0}catch($){F+=ye.length,k??(k=$ instanceof Error?$.message:String($))}Ws($=>$&&{...$,done:Math.min($.done+ye.length,$.total)})}Ws(null),A&&(await fetch(`/api/contacts/bulk-delete/${A}/complete`,{method:"POST",credentials:"include"}).catch(()=>{}),P.invalidateQueries({queryKey:["bulk-actions"]})),m(F===0?{title:"Bulk Delete Complete",description:`Deleted ${S} contact${S!==1?"s":""}`}:{variant:"destructive",title:`Deleted ${S} of ${n.length} contacts`,description:`${F} failed: ${k}`}),h(new Set),j({mode:"ids",ids:[],excludedIds:[]}),Pe()},Xa=async()=>{if(fs)return;const s=d.mode==="all";if(!s&&i.size===0||Xe.length===0)return;const t=Xe.filter(u=>u.id!=null).map(u=>u.id),n=Xe.filter(u=>u.id==null).map(u=>u.name);gs(!0);try{const u=te-d.excludedIds.length,S=s?{selection_type:"all",filters:Qe(),tagIds:t,newTagNames:n,...d.excludedIds.length>
20?{excluded_ids:d.excludedIds}:{}}:{contactIds:Array.from(i),tagIds:t,newTagNames:n},F=await J("POST","/api/tags/bulk-assign",S);if(!F)throw new Error("No response from server");const k=await F.json();P.invalidateQueries({queryKey:["/api/tags"]}),P.invalidateQueries({queryKey:["/api/tags/contacts/batch"]}),P.invalidateQueries({queryKey:["/api/contacts"]}),h(new Set),j({mode:"ids",ids:[],excludedIds:[]}),qs([]),Ze(!1);const A=k.assigned??(s?u:i.size);m({title:"Tags Added",description:`Added tags to ${A} contact${A!==1?"s":""}`})}catch(u){m({title:"Error",description:(u==null?void 0:u.message)??"Failed to add tags",variant:"destructive"})}finally{gs(!1)}},Ht=()=>d.mode==="all"?{selection_type:"all",filters:Qe(),...d.excludedIds.length>0?{excluded_ids:d.excludedIds}:{}}:{contactIds:Array.from(i)},qt=()=>{h(new Set),j({mode:"ids",ids:[],excludedIds:[]})},el=async()=>{if(!Se&&!(d.mode!=="all"&&i.size===0)&&!(!Oe||!js)){Ns(!0);try{const s=await J("POST","/api/contacts/bulk-move-pipeline",{...Ht(),pipelineId:Number(Oe),stageId:Number(js)});if(!s)throw new Error("No response from server");const t=await s.json();P.invalidateQueries({queryKey:["/api/pipelines"]}),qt(),ys(!1),Us(""),bs(""),m({title:"Moved to pipeline",description:`Moved ${t.moved??0} contact${(t.moved??0)!==1?"s":""}.`})}catch(s){m({title:"Error",description:(s==null?void 0:s.message)??"Failed to move contacts",variant:"destructive"})}finally{Ns(!1)}}},sl=async()=>{if(!Se&&!(d.mode!=="all"&&i.size===0)&&ts){Ns(!0);try{const s=ts==="none"?null:Number(ts),t=await J("POST","/api/contacts/bulk-assign-owner",{...Ht(),ownerUserId:s});if(!t)throw new Error("No response from server");const n=await t.json();P.invalidateQueries({queryKey:["/api/contacts"]}),qt(),vs(!1),Qs(""),m({title:"Owner updated",description:`Updated ${n.assigned??0} contact${(n.assigned??0)!==1?"s":""}.`})}catch(s){m({title:"Error",description:(s==null?void 0:s.message)??"Failed to assign owner",variant:"destructive"})}finally{Ns(!1)}}},tl=async()=>{if(fs)return;const s=d.mode==="all";if(!s&&i.size===0||xs.length===0)return;const t=xs.filter(n=>n.id!=null).map(n=>n.id);if(t.length!==0){gs(!0);try{const n=te-d.excludedIds.length,u=s?{selection_type:"all",filters:Qe(),tagIds:t,...d.excludedIds.length>0?{excluded_ids:d.excludedIds}:{}}:{contactIds:Array.from(i),tagIds:t},S=await J("POST","/api/tags/bulk-remove",u);if(!S)throw new Error("No response from server");const F=await S.json();P.invalidateQueries({queryKey:["/api/tags"]}),P.invalidateQueries({queryKey:["/api/tags/contacts/batch"]}),P.invalidateQueries({queryKey:["/api/contacts"]}),h(new Set),j({mode:"ids",ids:[],excludedIds:[]}),ps([]),Ze(!1);const k=F.removed??(s?n:i.size);m({title:"Tags Removed",description:`Removed tags from ${k} contact${k!==1?"s":""}`})}catch(n){m({title:"Error",description:(n==null?void 0:n.message)??"Failed to remove tags",variant:"destructive"})}finally{gs(!1)}}};async function Is(){const s=parseInt(E,10);if(!Number.isFinite(s)||s<1)return;const t=l.tags.filter(u=>u.id!=null).map(u=>u.id);if(t.length===0){m({description:"Please select a tag filter first."});return}const n=new URLSearchParams({tagIds:t.join(","),sortKey:"createdAt",sortDirection:"asc",page:"1",pageSize:String(Math.min(s,1e4))});we(!0);try{const u=await fetch(`/api/contacts?${n.toString()}`,{credentials:"include"});if(!u.ok)throw new Error("Failed to load contacts");const F=(await u.json()).data.slice(0,s).map(k=>k.id);h(new Set(F)),j({mode:"ids",ids:F,excludedIds:[]}),p(""),m({description:`Selected ${F.length} contact${F.length!==1?"s":""} from tag filter.`})}catch{m({variant:"destructive",description:"Failed to load contacts for selection."})}finally{we(!1)}}const qe=s=>{let t="asc";y&&y.key===s&&y.direction==="asc"&&(t="desc"),Ce({key:s,direction:t})},Ue=({colKey:s})=>!y||y.key!==s?e.jsx(ra,{className:"h-3.5 w-3.5 text-gray-300"}):y.direction==="asc"?e.jsx(wl,{className:"h-3.5 w-3.5 text-blue-500"}):e.jsx(Cl,{className:"h-3.5 w-3.5 text-blue-500"}),al=async()=>{if(ge.size===0){m({title:"No Selection",description:"Please select at least one conversation to import",variant:"destructive"});return}let s=0,t=0;for(const n of Array.from(ge)){const u=_e.find(k=>k.phone===n);if(!u)continue;let S="",F="";if(u.name&&!u.name.startsWith("+")){const k=u.name.split(" ");S=k[0]||"",F=k.slice(1).join(" ")||""}try{(await fetch("/api/contacts",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({userId:1,firstName:S||null,lastName:F||null,phoneNumber:n,email:null,tags:["imported-from-sms"]}
2)})).ok?s++:t++}catch{t++}}m({title:"Import Complete",description:`Imported ${s} contacts${t>0?`, ${t} failed`:""}`}),us(!1),Cs(new Set),Pe()};async function ll(s){try{const t=await Ma(s);if(!t)return;m({title:"Import complete",description:zl(t)}),P.invalidateQueries({queryKey:["/api/tags"]}),P.invalidateQueries({queryKey:["/api/tags/contacts/batch"]}),P.invalidateQueries({queryKey:["custom-fields"]}),Js({created:t.created,updated:t.updated,skipped:t.skipped,errorCount:t.errorCount,ownedByOthers:t.ownedByOthers,duplicates:t.duplicates}),Pe()}catch(t){const n=t==null?void 0:t.partialTotals,u=n?n.created+n.updated:0;if(u>0){q(t instanceof Error?t:new Error("Import failed"),`Import stopped after ${u} contacts`),Pe();return}q(t instanceof Error?t:new Error("Import failed"),"Import failed")}}const Qe=()=>{const s=l.tags.map(t=>t.id).filter(t=>t!=null);return{search:ee||void 0,smartList:fe==="recent"?fe:void 0,tagIds:s.length>0?s:void 0,hasEmail:l.hasEmail!=="any"?l.hasEmail:void 0,hasPhone:l.hasPhone!=="any"?l.hasPhone:void 0,state:l.state.trim()||void 0,city:l.city.trim()||void 0,businessName:l.businessName.trim()||void 0,source:l.source||void 0,birthdayMonth:l.birthdayMonth||void 0,hasAddress:l.hasAddress!=="any"?l.hasAddress:void 0,customFieldKey:l.customFieldKey&&l.customFieldHas!=="any"?l.customFieldKey:void 0,customFieldHas:l.customFieldKey&&l.customFieldHas!=="any"?l.customFieldHas:void 0,createdAfter:l.createdAfter||void 0,createdBefore:l.createdBefore||void 0}},nl=r.useMemo(()=>{const s=new Map;for(const t of Array.from(i))for(const n of at[t]??[])n.id!=null&&!s.has(n.id)&&s.set(n.id,n);return Array.from(s.values())},[i,at]),rl=()=>{const s=z.map(n=>n.id),t=d.mode==="all"?d.excludedIds.length===0:s.length>0&&s.every(n=>i.has(n));if(d.mode==="all"||t)if(d.mode==="all")h(new Set),j({mode:"ids",ids:[],excludedIds:[]});else{const n=new Set(i);s.forEach(u=>n.delete(u)),h(n),j({mode:"ids",ids:Array.from(n),excludedIds:[]})}else{const n=new Set([...Array.from(i),...s]);h(n),j({mode:"ids",ids:Array.from(n),excludedIds:[]})}},Ut=s=>{if(d.mode==="all")j(t=>{const n=new Set(t.excludedIds);return n.has(s)?n.delete(s):n.add(s),{...t,excludedIds:Array.from(n)}});else{const t=new Set(i);t.has(s)?t.delete(s):t.add(s),h(t),j({mode:"ids",ids:Array.from(t),excludedIds:[]})}},Qt=r.useRef(Ut);Qt.current=Ut;const il=r.useCallback(s=>{Qt.current(s)},[]),ol=r.useCallback(s=>{Fe(s);const t=window.location.pathname.replace(/\/contacts(\/.*)?$/,"");x(`${t}/contacts/detail/${s.id}`)},[x]),cl=r.useCallback(s=>{Ae(s),hs(!0)},[]),dl=r.useCallback(s=>{Os(s)},[]),ml=r.useMemo(()=>(V??[]).filter(s=>!ws.has(s.fieldKey)),[V,ws]),Vt=async()=>{if(d.mode==="all"){try{const A=await J("POST","/api/contacts/bulk-export",{selection_type:"all",filters:Qe(),...d.excludedIds.length>0?{excluded_ids:d.excludedIds}:{}});if(!A)throw new Error("No response from server");const ye=await A.blob(),$=URL.createObjectURL(ye),R=document.createElement("a");R.href=$,R.download=`contacts_export_${new Date().toISOString().split("T")[0]}.csv`,R.style.visibility="hidden",document.body.appendChild(R),R.click(),document.body.removeChild(R),URL.revokeObjectURL($),m({title:"Export Successful",description:"Exported the full selection to CSV."})}catch(A){m({title:"Export Failed",description:(A==null?void 0:A.message)??"Could not export contacts",variant:"destructive"})}return}if(z.length===0){m({title:"No Contacts",description:"There are no contacts to export.",variant:"destructive"});return}const s=i.size>0?z.filter(A=>i.has(A.id)):z,t=["First Name","Last Name","Phone Number","Email","Business Name","Created At","Tags"],n=s.map(A=>[`"${A.firstName||""}"`,`"${A.lastName||""}"`,`"${A.phoneNumber||""}"`,`"${A.email||""}"`,`"${A.businessName||""}"`,`"${new Date(A.createdAt).toISOString()}"`,`"${(A.tags||[]).join(", ")}"`]),u=[t.join(","),...n.map(A=>A.join(","))].join(` 3`),S=new Blob([u],{type:"text/csv;charset=utf-8;"}),F=URL.createObjectURL(S),k=document.createElement("a");k.setAttribute("href",F),k.setAttribute("download",`contacts_export_${new Date().toISOString().split("T")[0]}.csv`),k.style.visibility="hidden",document.body.appendChild(k),k.click(),document.body.removeChild(k),m({title:"Export Successful",description:`Exported ${s.length} contacts.`})},hl=()=>{if(d.mode==="all"){const t=Qe();try{sessionStorage.removeItem("campaign:prefillContactIds"),sessionStorage.setItem("campaign:prefillContactSelection",JSON.stringify({selection_type:"filter",filters:{search:t.search,smartList:t.smartList,tag_ids:t.tagIds,has_email:t.hasEmail,has_phone:"yes",has_address:l.hasAddress!=="any"?l.hasAddress:void 0,state:t.state,city:t.city,business_name:t.businessName,source:t.source,birthday_month:t.birthdayMonth,custom_field_key:t.customFieldKey,custom_field_has:t.customFieldHas,created_after:t.createdAfter,created_before:t.createdBefore,last_activity_after:l.lastActivityAfter||void 0,last_activity_before:l.lastActivityBefore||void 0},exclude_ids:d.excludedIds}))}catch{m({title:"Could not prepare campaign recipients",description:"Your browser could not store the selected contacts. Please try again.",variant:"destructive"});return}x(da("/sms-campaigns?openCreate=1"));return}const s=Array.from(i);if(s.length===0){m({title:"No contacts selected",description:"Select at least one contact to create a campaign.",variant:"destructive"});return}try{sessionStorage.removeItem("campaign:prefillContactSelection"),sessionStorage.setItem("campaign:prefillContactIds",JSON.stringify(s))}catch{}x(da("/sms-campaigns?openCreate=1"))};return e.jsxs("div",{className:"w-full h-[calc(100vh-4rem)] bg-slate-50/60 p-4 gap-4 flex flex-row overflow-hidden relative",children:[e.jsxs("div",{className:"flex-1 flex flex-col bg-white rounded-2xl border border-slate-100 shadow-[0_8px_30px_rgb(0,0,0,0.01)] overflow-hidden relative",children:[e.jsx("div",{className:"p-5 pb-0",children:e.jsxs("div",{className:"flex flex-col gap-3 mb-5 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("div",{className:"flex items-center space-x-4",children:e.jsx("h1",{className:"text-2xl font-bold text-slate-800 tracking-tight",children:"Contacts"})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>_s(!0),className:"text-slate-600 border-slate-200 hover:bg-slate-50 hover:text-slate-800 h-9 px-4 font-semibold rounded-full shadow-sm transition-all",children:[e.jsx(ta,{className:"h-4 w-4 mr-2"}),"Import"]}),e.jsxs(g,{size:"sm",onClick:()=>ms(!0),className:"bg-[var(--brand-primary)] hover:bg-[var(--brand-primary-hover)] text-white border-0 h-9 px-4 font-semibold rounded-full shadow-sm transition-all",children:[e.jsx(aa,{className:"h-4 w-4 mr-2"}),"Add Contact"]}),e.jsxs(Je,{children:[e.jsx(We,{asChild:!0,children:e.jsx(g,{variant:"outline",size:"icon",className:"border-slate-200 h-9 w-9 text-slate-500 rounded-full hover:bg-slate-50 hover:text-slate-700 transition-all",children:e.jsx(Ds,{className:"h-4 w-4"})})}),e.jsxs(Ge,{align:"end",children:[e.jsxs(pe,{onClick:()=>us(!0),className:"cursor-pointer",children:[e.jsx(ga,{className:"h-4 w-4 mr-2"}),"Import from SMS"]}),e.jsxs(pe,{onClick:Vt,className:"cursor-pointer",children:[e.jsx(jl,{className:"h-4 w-4 mr-2"}),"Export Contacts"]})]})]})]})]})}),e.jsx("div",{className:"px-5 pb-3 pt-3",children:e.jsxs("div",{className:"flex items-center gap-1 p-1 bg-slate-50 border border-slate-200/50 rounded-full w-fit mb-5 overflow-x-auto max-w-full",children:[Sa.map(s=>e.jsxs("button",{type:"button",onClick:()=>Kt(s.id),className:`flex items-center px-4 py-1.5 rounded-full text-xs font-semibold transition-all duration-200 cursor-pointer whitespace-nowrap ${fe===s.id?"bg-[var(--brand-primary)] text-white shadow-sm":"text-slate-600 hover:text-[var(--brand-primary)] hover:bg-rose-50/50"}`,children:[s.id==="all"&&e.jsx(bl,{className:"h-3.5 w-3.5 mr-1.5 shrink-0"}),s.name]},s.id)),za.map(s=>{const t=`user:${s.id}`,n=fe===t;return e.jsxs("div",{onClick:()=>Qa(s),className:`group flex items-center px-4 py-1.5 rounded-full text-xs font-semibold transition-all duration-200 cursor-pointer whitespace-nowrap ${n?"bg-[var(--brand-primary)] text-white shadow-sm":"text-slate-600 hover:text-[var(--brand-primary)] hover:bg-rose-50/50"}`,children:[s.name,e.jsx("button",{type:"button",title:"Delete smart list",className:`ml-1.5 rounded-full p-0.5 transition-colors ${n?"text-white/60 hover:text-white hover:bg-white/10":"text-slate-400 hover:text-red-500 hover:bg-red-50"}`,onClick:u=>{u.stopPropagation(),confirm(`Delete smart list "${s.name}"? This cannot be undone.`)&&Ua.mutate(s.id,{onSuccess:()=>{fe===t&&Kt("all"),m({title:"Smart List deleted",description:`Removed "${s.name}".`})},onError:S=>q(S,"Couldn't delete smart list")})},children:e.jsx(B,{className:"h-3 w-3"})})]},t)}),e.jsxs("button",{type:"button",className:"flex items-center px-4 py-1.5 rounded-full text-xs font-semibold text-slate-500 hover:text-[var(--brand-primary)] hover:bg-rose-50/50 transition-all duration-200 cursor-pointer whitespace-nowrap",onClick:()=>{Ct(""),St(De()),os(!0)},children:[e.jsx(aa,{className:"h-3.5 w-3.5 mr-1.5 text-slate-400"}),"Add smart list"]})]})}),fe==="bulk-actions"?e.jsx(Vl,{}):e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[e.jsx("div",{className:"px-5 pb-3",children:e.jsxs("div",{className:"flex flex-col gap-3 mb-4 lg:flex-row lg:items-center lg:justify-between",children:[e.jsx("div",{className:"flex items-center gap-3 overflow-x-auto",children:d.mode==="all"||i.size>0?e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx($s,{variant:"secondary",className:"bg-rose-50/50 text-[var(--brand-primary)] border border-rose-100/50 px-3 py-1 font-semibold rounded-full text-xs shadow-none",children:d.mode==="all"?`All ${te-d.excludedIds.length} selected`:`${i.size} selected`}),d.mode==="all"?e.jsxs(g,{variant:"outline",className:"h-9 px-3 text-[13px] font-medium bg-white border-slate-200 hover:bg-slate-50 text-slate-600 rounded-full cursor-pointer",onClick:()=>{h(new Set),j({mode:"ids",ids:[],excludedIds:[]})},children:[e.jsx(B,{className:"h-4 w-4 mr-1.5"}),"Clear selection"]}):te>z.length?e.jsxs(g,{variant:"outline",className:"h-9 px-3 text-[13px] font-medium bg-white border-rose-200 hover:bg-rose-50 text-[var(--brand-primary)] rounded-full cursor-pointer",onClick:()=>j({mode:"all",ids:[],excludedIds:[]}),children:["Select all ",te]}):null,l.tags.length>0&&e.jsxs("div",{className:"flex items-center gap-1 border-l border-slate-200 pl-3 ml-1",children:[e.jsx("span",{className:"text-xs text-slate-500
3whitespace-nowrap",children:"Select first"}),e.jsx("input",{type:"number",min:1,max:1e4,value:E,onChange:s=>p(s.target.value),onKeyDown:s=>{s.key==="Enter"&&Is()},className:"w-16 h-7 border border-slate-200 rounded px-2 text-sm text-center focus:outline-none focus:ring-1 focus:ring-[var(--brand-primary)] focus:border-[var(--brand-primary)]",placeholder:"N"}),e.jsx(g,{size:"sm",variant:"outline",className:"h-7 text-xs px-2 cursor-pointer",onClick:()=>void Is(),disabled:!E||parseInt(E)<1||Q||l.tags.length===0,children:"Select"})]}),e.jsxs(g,{variant:"ghost",className:"h-9 px-3 text-[13px] font-semibold text-slate-700 hover:bg-slate-50 hover:text-slate-900 rounded-full cursor-pointer",onClick:hl,children:[e.jsx(yt,{className:"h-4 w-4 mr-1.5"}),"Create Campaign"]}),e.jsxs(g,{variant:"ghost",className:"h-9 px-3 text-[13px] font-semibold text-slate-700 hover:bg-slate-50 hover:text-slate-900 rounded-full cursor-pointer",onClick:()=>Ze(!0),children:[e.jsx(lt,{className:"h-4 w-4 mr-1.5"}),"Add Tags"]}),e.jsxs(g,{variant:"ghost",className:"h-9 px-3 text-[13px] font-semibold text-red-600 hover:bg-red-50 hover:text-red-700 rounded-full cursor-pointer",onClick:Za,children:[e.jsx(Es,{className:"h-4 w-4 mr-1.5"}),"Delete"]}),e.jsxs(Je,{children:[e.jsx(We,{asChild:!0,children:e.jsxs(g,{variant:"ghost",className:"h-9 px-3 text-[13px] font-semibold text-slate-700 hover:bg-slate-50 hover:text-slate-900 rounded-full cursor-pointer",children:[e.jsx(Ds,{className:"h-4 w-4 mr-1.5"}),"More"]})}),e.jsxs(Ge,{align:"start",className:"w-56",children:[e.jsxs(pe,{onClick:()=>U(!0),className:"cursor-pointer",children:[e.jsx(yt,{className:"h-4 w-4 mr-2 text-slate-500"}),"Add to campaign"]}),e.jsxs(pe,{onClick:()=>ys(!0),className:"cursor-pointer",children:[e.jsx(la,{className:"h-4 w-4 mr-2 text-slate-500"}),"Move to pipeline"]}),e.jsxs(pe,{onClick:()=>vs(!0),className:"cursor-pointer",children:[e.jsx(na,{className:"h-4 w-4 mr-2 text-slate-500"}),"Assign owner"]}),e.jsxs(pe,{onClick:()=>m({title:"Coming soon",description:"Bulk email sending is not available yet."}),className:"cursor-pointer",children:[e.jsx(ya,{className:"h-4 w-4 mr-2 text-slate-500"}),"Send email"]}),e.jsx($e,{}),e.jsxs(pe,{onClick:()=>Ze(!0),className:"cursor-pointer",children:[e.jsx(lt,{className:"h-4 w-4 mr-2 text-slate-500"}),"Remove tags"]}),e.jsx($e,{}),e.jsxs(pe,{onClick:Vt,className:"cursor-pointer",children:[e.jsx(ta,{className:"h-4 w-4 mr-2 text-slate-500"}),"Export"]})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(g,{variant:"outline",className:`h-9 px-3.5 text-[13px] font-semibold rounded-full shadow-sm transition-all duration-200 cursor-pointer ${Ms?"text-[var(--brand-primary)] bg-rose-50/50 border-rose-200 hover:bg-rose-100/60":"text-slate-600 bg-white border-slate-200 hover:bg-slate-50"}`,onClick:()=>Hs(!0),children:[e.jsx(vl,{className:"h-3.5 w-3.5 mr-2"}),"Advanced filters",se>0&&e.jsx($s,{className:"ml-2 h-5 min-w-5 px-1.5 bg-[var(--brand-primary)] text-white text-[10px] rounded-full flex items-center justify-center font-bold",children:se})]}),e.jsxs(Je,{children:[e.jsx(We,{asChild:!0,children:e.jsxs(g,{variant:"ghost",className:"text-slate-600 h-9 px-3 text-[13px] font-semibold hover:bg-slate-50 rounded-full cursor-pointer",children:[e.jsx(ra,{className:"h-3.5 w-3.5 mr-2"}),"Sort"]})}),e.jsxs(Ge,{align:"start",className:"w-56",children:[e.jsx("div",{className:"px-2 py-1.5 text-sm font-semibold text-slate-900",children:"Sort By"}),e.jsx($e,{}),e.jsx(ne,{checked:(y==null?void 0:y.key)==="name"&&(y==null?void 0:y.direction)==="asc",onCheckedChange:()=>Ce({key:"name",direction:"asc"}),className:"cursor-pointer",children:"Name (A-Z)"}),e.jsx(ne,{checked:(y==null?void 0:y.key)==="name"&&(y==null?void 0:y.direction)==="desc",onCheckedChange:()=>Ce({key:"name",direction:"desc"}),className:"cursor-pointer",children:"Name (Z-A)"}),e.jsx($e,{}),e.jsx(ne,{checked:(y==null?void 0:y.key)==="createdAt"&&(y==null?void 0:y.direction)==="desc",onCheckedChange:()=>Ce({key:"createdAt",direction:"desc"}),className:"cursor-pointer",children:"Newest First"}),e.jsx(ne,{checked:(y==null?void 0:y.key)==="createdAt"&&(y==null?void 0:y.direction)==="asc",onCheckedChange:()=>Ce({key:"createdAt",direction:"asc"}),className:"cursor-pointer",children:"Oldest First"})]})]})]})}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"relative w-full lg:w-72",children:[e.jsx(ia,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-slate-400"}),e.jsx(I,{placeholder:"Search Contacts",value:T,onChange:s=>D(s.target.value),className:"pl-9 h-9 bg-slate-50 border-slate-200/60 text-xs rounded-full focus-visible:ring-1 focus-visible:ring-[var(--brand-primary)] focus-visible:border-[var(--brand-primary)] shadow-sm placeholder:text-slate-400 text-slate-700 transition-all"})]}),e.jsxs(Je,{children:[e.jsx(We,{asChild:!0,children:e.jsxs(g,{variant:"ghost",className:"text-slate-600 h-9 px-3 text-[13px] font-semibold hover:bg-slate-50 rounded-full cursor-pointer",children:[e.jsx(oa,{className:"h-3.5 w-3.5 mr-2"}),"Manage fields"]})}),e.jsxs(Ge,{align:"end",className:"w-56",children:[e.jsx("div",{className:"px-2 py-1.5 text-sm font-semibold text-slate-900",children:"Visible Columns"}),e.jsx($e,{}),e.jsx(ne,{checked:O.name,onCheckedChange:s=>ke(t=>({...t,name:s})),className:"cursor-pointer",children:"Contact name"}),e.jsx(ne,{checked:O.phone,onCheckedChange:s=>ke(t=>({...t,phone:s})),className:"cursor-pointer",children:"Phone"}),e.jsx(ne,{checked:O.email,onCheckedChange:s=>ke(t=>({...t,email:s})),className:"cursor-pointer",children:"Email"}),e.jsx(ne,{checked:O.businessName,onCheckedChange:s=>ke(t=>({...t,businessName:s})),className:"cursor-pointer",children:"Business name"}),e.jsx(ne,{checked:O.location,onCheckedChange:s=>ke(t=>({...t,location:s})),className:"cursor-pointer",children:"Location"}),e.jsx(ne,{checked:O.createdAt,onCheckedChange:s=>ke(t=>({...t,createdAt:s})),className:"cursor-pointer",children:"Created (EDT)"}),e.jsx(ne,{checked:O.lastActivity,onCheckedChange:s=>ke(t=>({...t,lastActivity:s})),className:"cursor-pointer",children:"Last activity (EDT)"}),e.jsx(ne,{checked:O.tags,onCheckedChange:s=>ke(t=>({...t,tags:s})),className:"cursor-pointer",children:"Tags"}),(V??[]).length>0&&e.jsxs(e.Fragment,{children:[e.jsx($e,{}),e.jsx("div",{className:"px-2 py-1.5 text-xs text-slate-400",children:"Custom fields"}),(V??[]).map(s=>e.jsx(ne,{checked:!ws.has(s.fieldKey),onCheckedChange:t=>It(n=>{const u=new Set(n);return t?u.delete(s.fieldKey):u.add(s.fieldKey),u}),className:"cursor-pointer",children:s.fieldLabel},s.fieldKey))]})]})]}),(V??[]).length>0&&e.jsxs(g,{variant:"ghost",className:"text-slate-600 h-9 px-3 text-[13px] font-semibold hover:bg-slate-50 rounded-full cursor-pointer",onClick:()=>Ft(!0),children:[e.jsx(oa,{className:"h-3.5 w-3.5 mr-2"}),"Manage custom fields"]})]})]})}),se>0&&e.jsxs("div",{className:"px-5 pb-3 flex flex-wrap gap-1.5",children:[l.tags.length>0&&l.tags.map(s=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-rose-50/50 border border-rose-100/50 text-[var(--brand-primary)] text-xs font-semibold",children:["Tag: ",s.name,e.jsx("button",{onClick:()=>{L(t=>({...t,tags:t.tags.filter(n=>(n.id??n.name)!==(s.id??s.name))})),de(1)},className:"ml-0.5 text-rose-400 hover:text-rose-700 transition-colors",children:e.jsx(B,{className:"h-3 w-3"})})]},String(s.id??s.name))),l.tags.length>0&&i.size===0&&e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx("span",{className:"text-xs text-slate-500",children:"Select first"}),e.jsx("input",{type:"number",min:1,max:1e4,value:E,onChange:s=>p(s.target.value),onKeyDown:s=>{s.key==="Enter"&&Is()},className:"w-16 h-7 border border-slate-200 rounded px-2 text-sm text-center focus:outline-none focus:ring-1 focus:ring-[var(--brand-primary)] focus:border-[var(--brand-primary)]",placeholder:"N"}),e.jsx(g,{size:"sm",variant:"outline",className:"h-7 text-xs cursor-pointer",onClick:()=>void Is(),disabled:!E||parseInt(E)<1||Q||l.tags.length===0,children:"Select"})]}),l.createdAfter&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-rose-50/50 border border-rose-100/50 text-[var(--brand-primary)] text-xs font-semibold",children:["Created after: ",l.createdAfter,e.jsx("button",{onClick:()=>me("createdAfter"),className:"ml-0.5 text-rose-400 hover:text-rose-700 transition-colors",children:e.jsx(B,{className:"h-3 w-3"})})]}),l.createdBefore&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-rose-50/50 border border-rose-100/50 text-[var(--brand-primary)] text-xs font-semibold",children:["Created before: ",l.createdBefore,e.jsx("button",{onClick:()=>me("createdBefore"),className:"ml-0.5 text-rose-400 hover:text-rose-700 transition-colors",children:e.jsx(B,{className:"h-3 w-3"})})]}),l.lastActivityAfter&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-rose-50/50 border border-rose-100/50 text-[var(--brand-primary)] text-xs font-semibold",children:["Last activity after: ",l.lastActivityAfter,e.jsx("button",{onClick:()=>me("lastActivityAfter"),className:"ml-0.5 text-rose-400 hover:text-rose-700 transition-colors",children:e.jsx(B,{className:"h-3 w-3"})})]}),l.lastActivityBefore&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-rose-50/50 border border-rose-100/50 text-[var(--brand-primary)] text-xs font-semibold",children:["Last activity before: ",l.lastActivityBefore,e.jsx("button",{onClick:()=>me("lastActivityBefore"),className:"ml-0.5 text-rose-400 hover:text-rose-700 transition-colors",children:e.jsx(B,{className:"h-3 w-3"})})]}),l.hasPhone!=="any"&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-rose-50/50 border border-rose-100/50 text-[var(--brand-primary)] text-xs font-semibold",children:[l.hasPhone==="yes"?"Has phone":"No phone",e.jsx("button",{onClick:()=>me("hasPhone"),className:"ml-0.5 text-rose-400 hover:text-rose-700 transition-colors",children:e.jsx(B,{className:"h-3 w-3"})})]}),l.hasAddress!=="any"&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-rose-50/50 border border-rose-100/50 text-[var(--brand-primary)] text-xs font-semibold",children:[l.hasAddress==="yes"?"Has address":"No address",e.jsx("button",{onClick:()=>me("hasAddress"),className:"ml-0.5 text-rose-400 hover:text-rose-700 transition-colors",children:e.jsx(B,{className:"h-3 w-3"})})]}),l.customFieldKey&&l.customFieldHas!=="any"&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-rose-50/50 border border-rose-100/50 text-[var(--brand-primary)] text-xs font-semibold",children:[((ea=(V??[]).find(s=>s.fieldKey===l.customFieldKey))==null?void 0:ea.fieldLabel)??l.customFieldKey,l.customFieldHas==="yes"?": has value":": empty",e.jsx("button",{onClick:()=>L(s=>({...s,customFieldKey:"",customFieldHas:"any"})),className:"ml-0.5 text-rose-400 hover:text-rose-700 transition-colors",children:e.jsx(B,{className:"h-3 w-3"})})]}),l.hasEmail!=="any"&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-rose-50/50 border border-rose-100/50 text-[var(--brand-primary)] text-xs font-semibold",children:[l.hasEmail==="yes"?"Has email":"No email",e.jsx("button",{onClick:()=>me("hasEmail"),className:"ml-0.5 text-rose-400 hover:text-rose-700 transition-colors",children:e.jsx(B,{className:"h-3 w-3"})})]}),l.state&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-rose-50/50 border border-rose-100/50 text-[var(--brand-primary)] text-xs font-semibold",children:["State: ",l.state,e.jsx("button",{onClick:()=>me("state"),className:"ml-0.5 text-rose-400 hover:text-rose-700 transition-colors",children:e.jsx(B,{className:"h-3 w-3"})})]}),l.city&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-rose-50/50 border border-rose-100/50 text-[var(--brand-primary)] text-xs font-semibold",children:["City: ",l.city,e.jsx("button",{onClick:()=>me("city"),className:"ml-0.5 text-rose-400 hover:text-rose-700 transition-colors",children:e.jsx(B,{className:"h-3 w-3"})})]}),l.businessName&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-rose-50/50 border border-rose-100/50 text-[var(--brand-primary)] text-xs font-semibold",children:["Business name: ",l.businessName,e.jsx("button",{onClick:()=>me("businessName"),className:"ml-0.5 text-rose-400 hover:text-rose-700 transition-colors",children:e.jsx(B,{className:"h-3 w-3"})})]}),l.source&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-rose-50/50 border border-rose-100/50 text-[var(--brand-primary)] text-xs font-semibold",children:["Source: ",l.source,e.jsx("button",{onClick:()=>me("source"),className:"ml-0.5 text-rose-400 hover:text-rose-700 transition-colors",children:e.jsx(B,{className:"h-3 w-3"})})]}),l.birthdayMonth&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-rose-50/50 border border-rose-100/50 text-[var(--brand-primary)] text-xs font-semibold",children:["Birthday month: ",l.birthdayMonth,e.jsx("button",{onClick:()=>me("birthdayMonth"),className:"ml-0.5 text-rose-400 hover:text-rose-700 transition-colors",children:e.jsx(B,{className:"h-3 w-3"})})]}),e.jsx("button",{onClick:()=>{L(De()),de(1)},className:"inline-flex items-center gap-1 px-3 py-1 rounded-full bg-slate-100 border border-slate-200 text-slate-600 text-xs font-semibold hover:bg-slate-200 hover:text-slate-800 transition-all cursor-pointer",children:"Clear all"})]}),e.jsxs("div",{className:"flex-1 overflow-auto min-h-0 border-t border-slate-100",children:[e.jsxs(nt,{children:[e.jsx(rt,{children:e.jsxs(Ve,{className:"hover:bg-transparent border-b border-slate-100/80 bg-slate-50/50",children:[e.jsx(_,{className:"w-[50px] min-w-[50px] align-middle border-r-0",style:{padding:0},children:e.jsx("div",{className:"flex justify-center items-center w-full h-full",children:e.jsx(vt,{checked:d.mode==="all"&&d.excludedIds.length===0?!0:d.mode==="all"&&d.excludedIds.length>0?"indeterminate":z.length>0&&z.every(s=>i.has(s.id))?!0:z.some(s=>i.has(s.id))?"indeterminate":!1,onCheckedChange:rl,className:"border-slate-300 rounded-[6px] data-[state=checked]:bg-[var(--brand-primary)] data-[state=checked]:border-[var(--brand-primary)]"})})}),O.name&&e.jsx(_,{className:"font-bold text-slate-400 text-[10px] uppercase tracking-wider h-10 py-2 px-4 border-r-0 whitespace-nowrap min-w-[200px] text-left align-middle",children:e.jsx("div",{className:"flex items-center w-full h-full resize-x overflow-hidden pr-2",style:{minWidth:"100px"},children:e.jsxs("div",{className:"flex items-center justify-start gap-2 cursor-pointer flex-1 h-full",onClick:()=>qe("name"),children:["Contact name",e.jsx(Ue,{colKey:"name"})]})})}),O.phone&&e.jsx(_,{className:"font-bold text-slate-400 text-[10px] uppercase tracking-wider h-10 py-2 px-4 border-r-0 whitespace-nowrap min-w-[220px] text-left align-middle",children:e.jsx("div",{className:"flex items-center w-full h-full resize-x overflow-hidden pr-2",style:{minWidth:"100px"},children:e.jsxs("div",{className:"flex items-center justify-start gap-2 cursor-pointer flex-1 h-full",onClick:()=>qe("phoneNumber"),children:["Phone",e.jsx(Ue,{colKey:"phoneNumber"})]})})}),O.email&&e.jsx(_,{className:"font-bold text-slate-400 text-[10px] uppercase tracking-wider h-10 py-2 px-4 border-r-0 whitespace-nowrap min-w-[250px] text-left align-middle",children:e.jsx("div",{className:"flex items-center w-full h-full resize-x overflow-hidden pr-2",style:{minWidth:"100px"},children:e.jsxs("div",{className:"flex items-center justify-start gap-2 cursor-pointer flex-1 h-full",onClick:()=>qe("email"),children:["Email",e.jsx(Ue,{colKey:"email"})]})})}),O.businessName&&e.jsx(_,{className:"font-bold text-slate-400 text-[10px] uppercase tracking-wider h-10 py-2 px-4 border-r-0 whitespace-nowrap min-w-[200px] text-left align-middle",children:e.jsx("div",{className:"flex items-center w-full h-full resize-x overflow-hidden pr-2",style:{minWidth:"100px"},children:e.jsxs("div",{className:"flex items-center justify-start gap-2 cursor-pointer flex-1 h-full",onClick:()=>qe("businessName"),children:["Business name",e.jsx(Ue,{colKey:"businessName"})]})})}),O.location&&e.jsx
3(_,{className:"font-bold text-slate-400 text-[10px] uppercase tracking-wider h-10 py-2 px-4 border-r-0 whitespace-nowrap min-w-[180px] text-left align-middle",children:e.jsx("div",{className:"flex items-center justify-start gap-2 resize-x overflow-hidden",style:{minWidth:"100px"},children:"Location"})}),O.createdAt&&e.jsx(_,{className:"font-bold text-slate-400 text-[10px] uppercase tracking-wider h-10 py-2 px-4 border-r-0 whitespace-nowrap min-w-[200px] text-left align-middle",children:e.jsx("div",{className:"flex items-center w-full h-full resize-x overflow-hidden pr-2",style:{minWidth:"100px"},children:e.jsxs("div",{className:"flex items-center justify-start gap-2 cursor-pointer flex-1 h-full",onClick:()=>qe("createdAt"),children:["Created (EDT)",e.jsx(Ue,{colKey:"createdAt"})]})})}),O.lastActivity&&e.jsx(_,{className:"font-bold text-slate-400 text-[10px] uppercase tracking-wider h-10 py-2 px-4 border-r-0 whitespace-nowrap min-w-[200px] text-left align-middle",children:e.jsx("div",{className:"flex items-center w-full h-full resize-x overflow-hidden pr-2",style:{minWidth:"100px"},children:e.jsxs("div",{className:"flex items-center justify-start gap-2 cursor-pointer flex-1 h-full",onClick:()=>qe("lastMessageAt"),children:["Last activity (EDT)",e.jsx(Ue,{colKey:"lastMessageAt"})]})})}),O.tags&&e.jsx(_,{className:"font-bold text-slate-400 text-[10px] uppercase tracking-wider h-10 py-2 px-4 border-r-0 whitespace-nowrap min-w-[150px] text-left align-middle",children:e.jsx("div",{className:"flex items-center justify-start gap-2 resize-x overflow-hidden",style:{minWidth:"100px"},children:"Tags"})}),(V??[]).filter(s=>!ws.has(s.fieldKey)).map(s=>e.jsx(_,{className:"font-bold text-slate-400 text-[10px] uppercase tracking-wider h-10 py-2 px-4 border-r-0 whitespace-nowrap min-w-[180px] text-left align-middle",children:e.jsx("div",{className:"flex items-center justify-start gap-2 resize-x overflow-hidden",style:{minWidth:"100px"},children:s.fieldLabel})},s.fieldKey)),e.jsx(_,{className:"w-12 px-4 border-r-0"})]})}),e.jsx(it,{children:!tt&&!Ke&&z.map(s=>e.jsx(cn,{contact:s,isSelected:d.mode==="all"?!d.excludedIds.includes(s.id):i.has(s.id),visibleColumns:O,visibleCustomFields:ml,rowTags:at[s.id]??on,onToggleSelect:il,onOpenContact:ol,onEditContact:cl,onDeleteContact:dl},s.id))})]}),(tt||Ke)&&e.jsxs("div",{className:"sticky left-0 w-full flex items-center justify-center gap-2 py-16 text-sm text-slate-500",children:[e.jsx(Ls,{className:"h-4 w-4 animate-spin text-[#800000]"}),"Loading contactsâ¦"]}),!tt&&!Ke&&z.length===0&&e.jsxs("div",{className:"sticky left-0 w-full flex flex-col items-center justify-center gap-3 py-20 px-6 text-center",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-slate-50 border border-slate-100",children:e.jsx(ia,{className:"h-5 w-5 text-slate-300"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-600",children:ee||Ms?"No matching contacts":"No contacts yet"}),e.jsx("p",{className:"text-[13px] text-slate-400 max-w-sm",children:ee?`Nothing matches â${ee}â. Try a different name, email, or phone number.`:Ms?"No contacts match the active filters.":"Add or import
3contacts to get started."})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-t border-slate-100 bg-white text-xs font-medium text-slate-500 rounded-b-2xl mt-auto",children:[e.jsx("div",{children:te===0?"Showing 0 of 0 contacts":`Showing ${(ae-1)*X+1}â${Math.min(ae*X,te)} of ${te} contacts`}),e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsxs(W,{value:X.toString(),onValueChange:s=>Ye(Number(s)),children:[e.jsx(G,{className:"w-[75px] h-8 text-xs bg-white border-slate-200 rounded-lg shadow-sm",children:e.jsx(Y,{placeholder:"10"})}),e.jsxs(Z,{children:[e.jsx(w,{value:"10",children:"10"}),e.jsx(w,{value:"25",children:"25"}),e.jsx(w,{value:"50",children:"50"}),e.jsx(w,{value:"100",children:"100"})]})]}),e.jsxs("div",{className:"flex items-center border border-slate-200 rounded-lg bg-white overflow-hidden shadow-sm",children:[e.jsx(g,{variant:"ghost",size:"sm",className:"h-8 px-4 text-slate-600 rounded-none border-r border-slate-200 hover:bg-slate-50 hover:text-slate-800 disabled:opacity-50 transition-colors",disabled:ae===1,onClick:()=>de(s=>s-1),children:"Prev"}),e.jsx("div",{className:"h-8 px-4 flex items-center justify-center border-r border-slate-200 text-[var(--brand-primary)] bg-rose-50/20 font-bold text-xs",children:ae}),e.jsx(g,{variant:"ghost",size:"sm",className:"h-8 px-4 text-slate-600 rounded-none hover:bg-slate-50 hover:text-slate-800 disabled:opacity-50 transition-colors",disabled:ae>=rs||rs===0,onClick:()=>de(s=>s+1),children:"Next"})]})]})]})]})]}),Ne&&e.jsxs("div",{className:"w-[420px] shrink-0 border border-slate-100 bg-white rounded-2xl shadow-[0_8px_30px_rgb(0,0,0,0.015)] flex flex-col overflow-hidden h-full",children:[e.jsx("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-slate-100 bg-slate-50/50 shrink-0",children:e.jsxs("button",{onClick:()=>{Fe(null);const s=window.location.pathname.replace(/\/contacts(\/.*)?$/,"");x(`${s}/contacts`)},className:"flex items-center gap-1.5 text-xs font-semibold text-slate-500 hover:text-slate-800 transition-colors cursor-pointer",children:[e.jsx(fa,{className:"h-4 w-4"}),"Contacts"]})}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx(_l,{contact:{id:Ne.id,phone:Ne.phoneNumber||"",firstName:Ne.firstName||void 0,lastName:Ne.lastName||void 0,email:Ne.email||void 0,businessName:Ne.businessName||void 0,isSaved:!0},onClose:()=>{Fe(null);const s=window.location.pathname.replace(/\/contacts(\/.*)?$/,"");x(`${s}/contacts`)},onPatchLocal:s=>{const{phone:t,isSaved:n,...u}=s,S={...u,...t!==void 0?{phoneNumber:t}:{}},F=Ne.id;Fe(k=>k&&{...k,...S}),P.setQueriesData({queryKey:["/api/contacts"]},k=>k&&{...k,data:k.data.map(A=>A.id===F?{...A,...S}:A)})},onSavedToContacts:()=>{},getAvatarColor:Nt,getInitials:Na})})]}),e.jsx(Jl,{contactIds:Array.from(i),open:K,onOpenChange:U}),e.jsx(re,{open:kt,onOpenChange:s=>{ys(s),s||(Us(""),bs(""))},children:e.jsxs(ie,{className:"max-w-md",children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(la,{className:"h-5 w-5"})," Move to pipeline"]}),e.jsxs(xe,{children:["Create a deal for ",d.mode==="all"?`all ${te-d.excludedIds.length}`:i.size," selected contact",(d.mode==="all"?te-d.excludedIds.length:i.size)!==1?"s":""," in the chosen pipeline and stage."]})]}),e.jsxs("div",{className:"space-y-3 py-1",children:[e.jsxs("div",{children:[e.jsx(N,{className:"text-xs",children:"Pipeline"}),e.jsxs(W,{value:Oe,onValueChange:s=>{Us(s),bs("")},children:[e.jsx(G,{className:"mt-1",children:e.jsx(Y,{placeholder:"Select a pipelineâ¦"})}),e.jsx(Z,{children:$t.map(s=>e.jsx(w,{value:String(s.id),children:s.name},s.id))})]})]}),e.jsxs("div",{children:[e.jsx(N,{className:"text-xs",children:"Stage"}),e.jsxs(W,{value:js,onValueChange:bs,disabled:!Oe,children:[e.jsx(G,{className:"mt-1",children:e.jsx(Y,{placeholder:"Select a stageâ¦"})}),e.jsx(Z,{children:_a.map(s=>e.jsx(w,{value:String(s.id),children:s.name},s.id))})]})]})]}),e.jsxs(Le,{children:[e.jsx(g,{variant:"outline",onClick:()=>ys(!1),disabled:Se,children:"Cancel"}),e.jsx(g,{onClick:el,disabled:!Oe||!js||Se,children:Se?"Movingâ¦":"Move"})]})]})}),e.jsx(re,{open:At,onOpenChange:s=>{vs(s),s||Qs("")},children:e.jsxs(ie,{className:"max-w-md",children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(na,{className:"h-5 w-5"})," Assign owner"]}),e.jsxs(xe,{children:["Set the owner for ",d.mode==="all"?`all ${te-d.excludedIds.length}`:i.size," selected contact",(d.mode==="all"?te-d.excludedIds.length:i.size)!==1?"s":"","."]})]}),e.jsx("div",{className:"space-y-3 py-1",children:e.jsxs("div",{children:[e.jsx(N,{className:"text-xs",children:"Owner"}),e.jsxs(W,{value:ts,onValueChange:Qs,children:[e.jsx(G,{className:"mt-1",children:e.jsx(Y,{placeholder:"Select an ownerâ¦"})}),e.jsxs(Z,{children:[e.jsx(w,{value:"none",children:"â Unassigned â"}),qa.map(s=>e.jsx(w,{value:String(s.id),children:[s.firstName,s.lastName].filter(
3Boolean).join(" ")||s.username||s.email||`User #${s.id}`},s.id))]})]})]})}),e.jsxs(Le,{children:[e.jsx(g,{variant:"outline",onClick:()=>vs(!1),disabled:Se,children:"Cancel"}),e.jsx(g,{onClick:sl,disabled:!ts||Se,children:Se?"Savingâ¦":"Assign"})]})]})}),e.jsx(re,{open:Ta,onOpenChange:s=>{Ze(s),s||(qs([]),ps([]),es(null),Be(""))},children:e.jsxs(ie,{className:"max-w-lg max-h-[85vh] flex flex-col",children:[e.jsxs(oe,{children:[e.jsx(ce,{children:"Tag Manager"}),e.jsxs(xe,{children:["Rename or delete tags globally, or add/remove tags on"," ",d.mode==="all"?`all ${te} contacts`:`${i.size} selected contact${i.size!==1?"s":""}`,"."]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto -mx-6 px-6",children:Ie.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 text-gray-400 gap-2",children:[e.jsx(lt,{className:"h-8 w-8 opacity-30"}),e.jsx("p",{className:"text-sm",children:"No tags yet. Create tags in Settings â Tags."})]}):e.jsxs(nt,{children:[e.jsx(rt,{children:e.jsxs(Ve,{className:"hover:bg-transparent",children:[e.jsx(_,{className:"w-8"}),e.jsx(_,{children:"Name"}),e.jsx(_,{className:"w-28 text-right",children:"Actions"})]})}),e.jsx(it,{children:Ie.map(s=>{const t=Pa===s.id,u=s.color||"#94a3b8";return e.jsxs(Ve,{className:"hover:bg-gray-50/50",children:[e.jsx(H,{className:"py-2",children:e.jsx("span",{className:"inline-block h-3 w-3 rounded-full",style:{backgroundColor:u}})}),e.jsx(H,{className:"py-2",children:t?e.jsx(I,{autoFocus:!0,value:ss,onChange:S=>Be(S.target.value),onKeyDown:S=>{S.key==="Enter"&&ss.trim()&&ns.mutate({tagId:s.id,name:ss}),S.key==="Escape"&&(es(null),Be(""))},className:"h-7 text-sm",disabled:ns.isPending}):e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",style:{backgroundColor:`${u}22`,color:u,border:`1px solid ${u}55`},children:s.name})}),e.jsx(H,{className:"py-2 text-right",children:t?e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(g,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-green-600 hover:text-green-700",disabled:!ss.trim()||ns.isPending,onClick:()=>ns.mutate({tagId:s.id,name:ss}),title:"Save",children:ns.isPending?e.jsx(Ls,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Nl,{className:"h-3.5 w-3.5"})}),e.jsx(g,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-gray-400",onClick:()=>{es(null),Be("")},title:"Cancel",children:e.jsx(B,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(g,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-gray-400 hover:text-gray-700",onClick:()=>{es(s.id),Be(s.name)},title:"Rename tag",children:e.jsx(ca,{className:"h-3.5 w-3.5"})}),e.jsx(g,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-gray-400 hover:text-red-600",disabled:Zs.isPending,title:"Delete tag",onClick:()=>zs({id:s.id,name:s.name}),children:e.jsx(Es,{className:"h-3.5 w-3.5"})})]})})]},s.id)})})]})}),e.jsxs("div",{className:"border-t border-gray-100 pt-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(is,{value:Xe,onChange:qs,availableTags:Ie,placeholder:"Add tags to selection...",allowCreate:!0}),e.jsx(g,{size:"sm",className:"shrink-0 bg-blue-600 hover:bg-blue-700 text-white",disabled:Xe.length===0||fs,onClick:Xa,children:"Add"})]}),(()=>{const s=d.mode==="all"?Ie:nl;return s.length===0?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(is,{value:xs,onChange:ps,availableTags:s,placeholder:"Remove tags from selection...",allowCreate:!1}),e.jsx(g,{size:"sm",variant:"outline",className:"shrink-0 text-red-600 border-red-200 hover:bg-red-50",disabled:xs.length===0||fs,onClick:tl,children:"Remove"})]})})()]})]})}),e.jsx(re,{open:Aa,onOpenChange:ms,children:e.jsxs(ie,{className:"max-h-[90vh] flex flex-col",children:[e.jsxs(oe,{children:[e.jsx(ce,{children:"Add New Contact"}),e.jsx(xe,{children:"Add a new contact to your database"})]}),e.jsxs("div",{className:"space-y-4 py-4 overflow-y-auto flex-1 -mx-6 px-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(N,{children:"First Name"}),e.jsx(I,{value:b.firstName,onChange:s=>{le({...b,firstName:s.target.value}),he.firstName&&Re(t=>({...t,firstName:""}))},placeholder:"John"}),he.firstName&&e.jsx("p",{className:"text-xs text-red-600 mt-1",children:he.firstName})]}),e.jsxs("div",{children:[e.jsx(N,{children:"Last Name"}),e.jsx(I,{value:b.lastName,onChange:s=>{le({...b,lastName:s.target.value}),he.lastName&&Re(t=>({...t,lastName:""}))},placeholder:"Doe"}),he.lastName&&e.jsx("p",{className:"text-xs text-red-600 mt-1",children:he.lastName})]})]}),e.jsxs("div",{children:[e.jsx(N,{children:"Phone Number"}),e.jsx(I,{value:b.phoneNumber,onChange:s=>{le({...b,phoneNumber:s.target.value}),he.phoneNumber&&Re(t=>({...t,phoneNumber:""}))},placeholder:"+1234567890"}),he.phoneNumber&&e.jsx("p",{className:"text-xs text-red-600 mt-1",children:he.phoneNumber})]}),e.jsxs("div",{children:[e.jsx(N,{children:"Email"}
3),e.jsx(I,{type:"email",value:b.email,onChange:s=>{le({...b,email:s.target.value}),he.email&&Re(t=>({...t,email:""}))},placeholder:"[email protected]"}),he.email&&e.jsx("p",{className:"text-xs text-red-600 mt-1",children:he.email})]}),e.jsxs("div",{children:[e.jsx(N,{children:"Business Name"}),e.jsx(I,{value:b.businessName,onChange:s=>le({...b,businessName:s.target.value}),placeholder:"Acme Inc."})]}),e.jsxs("div",{children:[e.jsx(N,{children:"Birthday"}),e.jsx(I,{type:"date",value:b.birthday,onChange:s=>le({...b,birthday:s.target.value})})]}),e.jsxs("div",{children:[e.jsx(N,{children:"Address"}),e.jsx(I,{value:b.address,onChange:s=>le({...b,address:s.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(N,{children:"City"}),e.jsx(I,{value:b.city,onChange:s=>le({...b,city:s.target.value}),placeholder:"New York"})]}),e.jsxs("div",{children:[e.jsx(N,{children:"State"}),e.jsx(I,{value:b.state,onChange:s=>le({...b,state:s.target.value}),placeholder:"NY"})]})]}),e.jsxs("div",{children:[e.jsx(N,{children:"ZIP Code"}),e.jsx(I,{value:b.zipCode,onChange:s=>le({...b,zipCode:s.target.value}),placeholder:"10001"})]}),e.jsxs("div",{children:[e.jsx(N,{children:"Tags"}),e.jsx(Wl,{value:b.tags?b.tags.split(",").map(s=>s.trim()).filter(Boolean):[],onChange:s=>le({...b,tags:s.join(",")}),placeholder:"Add a tag and press comma or Enter"}),e.jsx("p",{className:"text-xs text-neutral-500 mt-1",children:"Press Enter or add a comma after each tag"})]}),(V??[]).length>0&&e.jsxs("div",{className:"space-y-4 border-t pt-4 mt-2",children:[e.jsx("p",{className:"text-xs font-semibold text-slate-500 uppercase tracking-widest",children:"Custom Fields"}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:(V??[]).map(s=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(N,{children:s.fieldLabel}),e.jsx(I,{value:b.customFields[s.fieldKey]||"",onChange:t=>le(n=>({...n,customFields:{...n.customFields,[s.fieldKey]:t.target.value}})),placeholder:`Enter ${s.fieldLabel.toLowerCase()}`})]},s.fieldKey))})]})]}),e.jsxs(Le,{children:[e.jsx(g,{variant:"outline",onClick:()=>ms(!1),children:"Cancel"}),e.jsx(g,{onClick:Ga,loading:Rt.isPending,className:"bg-[#991b1b] hover:bg-[#7f1d1d] text-white",children:"Add Contact"})]})]})}),e.jsx(re,{open:Ia,onOpenChange:hs,children:e.jsxs(ie,{className:"max-w-lg max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(oe,{className:"flex-shrink-0",children:[e.jsx(ce,{children:"Edit Contact"}),e.jsx(xe,{children:"Update contact information"})]}),M&&e.jsxs("div",{className:"space-y-4 py-4 flex-1 overflow-y-auto -mx-6 px-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(N,{children:"First Name"}),e.jsx(I,{value:M.firstName||"",onChange:s=>Ae({...M,firstName:s.target.value})})]}),e.jsxs("div",{children:[e.jsx(N,{children:"Last Name"}),e.jsx(I,{value:M.lastName||"",onChange:s=>Ae({...M,lastName:s.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(N,{children:"Phone Number"}),e.jsx(I,{value:M.phoneNumber||"",onChange:s=>Ae({...M,phoneNumber:s.target.value})})]}),e.jsxs("div",{children:[e.jsx(N,{children:"Email"}),e.jsx(I,{type:"email",value:M.email||"",onChange:s=>Ae({...M,email:s.target.value})})]}),e.jsxs("div",{children:[e.jsx(N,{children:"Business Name"}),e.jsx(I,{value:M.businessName||"",onChange:s=>Ae({...M,businessName:s.target.value}),placeholder:"Acme Inc."})]}),e.jsxs("div",{children:[e.jsx(N,{children:"Tags"}
3),e.jsx(is,{value:Pt,onChange:Va,availableTags:Ie,placeholder:"Add tags...",allowCreate:!0})]}),(V??[]).length>0&&e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-gray-500",children:"Custom fields"}),(V??[]).map(s=>{const t=M.customFields??{},n=t[s.fieldKey]??"";return e.jsxs("div",{children:[e.jsx(N,{children:s.fieldLabel}),e.jsx(I,{value:n,onChange:u=>Ae({...M,customFields:{...t,[s.fieldKey]:u.target.value}}),placeholder:s.fieldLabel})]},s.fieldKey)})]})]}),e.jsxs(Le,{className:"flex-shrink-0",children:[e.jsx(g,{variant:"outline",onClick:()=>hs(!1),children:"Cancel"}),e.jsx(g,{onClick:Ya,loading:_t.isPending,className:"bg-blue-600 hover:bg-blue-700 text-white",children:"Save Changes"})]})]})}),e.jsx(re,{open:Fa,onOpenChange:s=>{_s(s),s||Js(null)},children:e.jsxs(ie,{className:"max-w-7xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(oe,{children:[e.jsx(ce,{children:"Import Contacts from CSV"}),e.jsx(xe,{children:"Upload a CSV file and map your columns to contact fields"})]}),e.jsx(Ol,{onImportComplete:s=>{ll(s)},onCancel:()=>{_s(!1),Js(null)},isImporting:Ka,importProgress:Te,importResult:Ba})]})}),e.jsx(Zl,{open:Ea,onClose:()=>Hs(!1),onApply:s=>{const t=De();L({...t,createdAfter:s.createdAfter,createdBefore:s.createdBefore,lastActivityAfter:s.lastActivityAfter,lastActivityBefore:s.lastActivityBefore,tags:s.tags,hasEmail:s.hasEmail||"any",hasPhone:s.hasPhone||"any",state:s.state,city:s.city,source:s.source,businessName:s.businessName,birthdayMonth:s.birthdayMonth,hasAddress:s.hasAddress||"any",customFieldKey:s.customField?s.customField.split("::")[0]:"",customFieldHas:s.customField&&s.customField.split("::")[1]||"any"}),de(1),Hs(!1)},availableTags:Ie,customFields:(V??[]).map(s=>({fieldKey:s.fieldKey,fieldLabel:s.fieldLabel})),initialFilters:{createdAfter:l.createdAfter,createdBefore:l.createdBefore,lastActivityAfter:l.lastActivityAfter,lastActivityBefore:l.lastActivityBefore,tags:l.tags,hasEmail:l.hasEmail,hasPhone:l.hasPhone,state:l.state,city:l.city,source:l.source,businessName:l.businessName,birthdayMonth:l.birthdayMonth,hasAddress:l.hasAddress,customField:l.customFieldKey&&l.customFieldHas!=="any"?`${l.customFieldKey}::${l.customFieldHas}`:""}}),e.jsx(re,{open:ka,onOpenChange:os,children:e.jsxs(ie,{className:"max-w-lg",children:[e.jsxs(oe,{children:[e.jsx(ce,{children:"Create Smart List"}),e.jsx(xe,{children:"Save a named, reusable filter. Everyone in your workspace can use it."})]}),e.jsxs("div",{className:"max-h-[60vh] overflow-y-auto py-1 pr-1 space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"text-xs font-medium",children:"List name"}),e.jsx(I,{placeholder:"e.g. California leads",value:cs,onChange:s=>Ct(s.target.value),maxLength:80})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(ln,{value:ds,onChange:St,availableTags:Ie,customFields:(V??[]).map(s=>({fieldKey:s.fieldKey,fieldLabel:s.fieldLabel}))})})]}),e.jsxs(Le,{children:[e.jsx(g,{variant:"outline",onClick:()=>os(!1),children:"Cancel"}),e.jsx(g,{disabled:!cs.trim()||gt(ds)===0||et.isPending,onClick:()=>{const s=cs.trim();s&&et.mutate({name:s,filters:tn(ds)},{onSuccess:()=>{os(!1),m({title:"Smart List created",description:`"${s}" is ready to use.`})},onError:t=>q(t,"Couldn't create smart list")})},children:et.isPending?"Creatingâ¦":"Create list"})]}),cs.trim()&>(ds)===0&&e.jsx("p",{className:"text-[11px] text-red-500 text-center mt-1",children:"Please select at least one filter criterion in the form above before saving."})]})}),e.jsx(re,{open:Rs,onOpenChange:us,children:e.jsxs(ie,{className:"max-w-2xl",children:[e.jsxs(oe,{children:[e.jsx(ce,{children:"Import Contacts from SMS Conversations"}),e.jsx(xe,{children:"Select conversations to add as contacts. Only new contacts (not already in your database) are shown."})]}),e.jsx(El,{className:"h-96",children:$a?e.jsx("div",{className:"flex items-center justify-center py-8 text-gray-500",children:"Loading conversations..."}):_e.length===0?e.jsx("div",{className:"flex items-center justify-center py-8 text-gray-500",children:"No new contacts to import. All conversation contacts are already in your database."}):e.jsxs("div",{className:"space-y-2 p-2",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx(g,{variant:"outline",size:"sm",onClick:()=>{ge.size===_e.length?Cs(new Set):Cs(new Set(_e.map(s=>s.phone)))},children:ge.size===_e.length?"Deselect All":"Select All"}),e.jsxs("span",{className:"text-sm text-gray-500",children:[ge.size," selected"]})]}),_e.map(s=>e.jsxs("div",{className:`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${ge.has(s.phone)?"bg-blue-50 border-blue-200":"hover:bg-gray-50"}`,onClick:()=>{const t=new Set(ge);t.has(s.phone)?t.delete(s.phone):t.add(s.phone),Cs(t)},children:[e.jsx(vt,{checked:ge.has(s.phone)}),e.jsx(ba,{className:"h-10 w-10",children:e.jsx(va,{className:`${Nt(s.name)} text-white text-sm font-semibold`,children:s.name.startsWith("+")?s.phone.slice(-2):s.name.slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:s.name}),e.jsx("p",{className:"text-sm text-gray-500",children:Ca(s.phone)})]}),e.jsx("div",{className:"text-right",children:e.jsx("p",{className:"text-xs text-gray-400 truncate max-w-[200px]",children:s.lastMessage})})]},s.phone))]})}),e.jsxs(Le,{children:[e.jsx(g,{variant:"outline",onClick:()=>us(!1),children:"Cancel"}),e.jsxs(g,{onClick:al,disabled:ge.size===0,children:["Import ",ge.size," Contact",ge.size!==1?"s":""]})]})]})}),e.jsx(ot,{open:Bs!==null,onOpenChange:s=>{s||Os(null)},children:e.jsxs(ct,{children:[e.jsxs(dt,{children:[e.jsx(mt,{children:"Delete Contact"}),e.jsx(ht,{children:"Are you sure you want to delete this contact? This action cannot be undone."})]}),e.jsxs(ut,{children:[e.jsx(xt,{disabled:As.isPending,children:"Cancel"}),e.jsxs(pt,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:As.isPending,onClick:s=>{s.preventDefault(),Bs!==null&&As.mutate(Bs)},children:[As.isPending&&e.jsx("span",{className:"mr-2",children:e.jsxs("svg",{className:"h-4 w-4 animate-spin inline",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8v8z"})]})}),"Delete"]})]})]})}),e.jsx(ot,{open:Ee!==null,onOpenChange:s=>{s||Vs(null)},children:e.jsxs(ct,{children:[e.jsxs(dt,{children:[e.jsxs(mt,{children:['Delete custom field "',Ee==null?void 0:Ee.label,'"?']}),e.jsx(ht,{children:"This permanently removes the field definition from the database. All contact data stored under this field will no longer be accessible from the table. This action cannot be undone."})]}),e.jsxs(ut,{children:[e.jsx(xt,{children:"Cancel"}),e.jsx(pt,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:Gs.isPending,onClick:s=>{s.preventDefault(),Ee&&Gs.mutate({id:Ee.id,key:Ee.key})},children:"Delete permanently"})]})]})}),e.jsx(ot,{open:Me!==null,onOpenChange:s=>{s||zs(null)},children:e.jsxs(ct,{children:[e.jsxs(dt,{children:[e.jsxs(mt,{children:['Delete "',Me==null?void 0:Me.name,'"?']}),e.jsx(ht,{children:"This removes the tag from all contacts globally and cannot be undone."})]}),e.jsxs(ut,{children:[e.jsx(xt,{children:"Cancel"}),e.jsx(pt,{className:"bg-red-600 hover:bg-red-700 text-white",disabled:Zs.isPending,onClick:()=>{Me&&(Zs.mutate(Me.id),zs(null))},children:"Delete"})]})]})}),e.jsx(re,{open:Da,onOpenChange:s=>{Ft(s),s||(as(null),ze(""))},children:e.jsxs(ie,{className:"max-w-lg max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(oe,{className:"flex-shrink-0",children:[e.jsx(ce,{children:"Manage custom fields"}),e.jsx(xe,{children:"Edit or delete custom fields. Deleting a field removes its definition but does not erase contact data stored under that key."})]}),(V??[]).length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No custom fields yet."}):e.jsx("div",{className:"flex-1 overflow-y-auto -mx-6 px-6",children:e.jsxs(nt,{children:[e.jsx(rt,{children:e.jsxs(Ve,{className:"hover:bg-transparent",children:[e.jsx(_,{children:"Field name"}),e.jsx(_,{className:"text-muted-foreground font-normal",children:"Key"}),e.jsx(_,{className:"w-24 text-right",children:"Actions"})]})}),e.jsx(it,{children:(V??[]).map(s=>e.jsxs(Ve,{className:"hover:bg-gray-50/50",children:[e.jsx(H,{className:"py-2",children:Et===s.id?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{value:ls,onChange:t=>ze(t.target.value),onKeyDown:t=>{t.key==="Enter"&&ls.trim()&&Ys.mutate({id:s.id,label:ls}),t.key==="Escape"&&(as(null),ze(""))},className:"h-7 text-sm",autoFocus:!0}),e.jsx(g,{size:"sm",variant:"default",className:"h-7 px-2 text-xs",disabled:!ls.trim()||Ys.isPending,onClick:()=>Ys.mutate({id:s.id,label:ls}),children:"Save"}),e.jsx(g,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>{as(null),ze("")},children:"Cancel"})]}):e.jsx("span",{className:"text-sm font-medium",children:s.fieldLabel})}),e.jsx(H,{className:"py-2 text-xs text-muted-foreground font-mono",children:s.fieldKey}),e.jsx(H,{className:"py-2 text-right",children:Et!==s.id&&e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(g,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-gray-400 hover:text-gray-700",onClick:()=>{as(s.id),ze(s.fieldLabel)},title:"Rename field",children:e.jsx(ca,{className:"h-3.5 w-3.5"})}),e.jsx(g,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-gray-400 hover:text-red-600",disabled:Gs.isPending,title:"Delete field",onClick:()=>Vs({id:s.id,key:s.fieldKey,label:s.fieldLabel}),children:e.jsx(Es,{className:"h-3.5 w-3.5"})})]})})]},s.id))})]})})]})}),Te&&(()=>{const s=Te.total>0?Math.round(Te.current/Te.total*100):0;return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40",children:e.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl p-8 w-80 flex flex-col gap-5",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-800 dark:text-gray-100",children:"Importing contactsâ¦"}),e.jsx("div",{className:"w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2 overflow-hidden",children:e.jsx("div",{className:"bg-blue-600 h-2 rounded-full transition-all duration-300 ease-out",style:{width:`${s}%`}})}),e.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 text-center tabular-nums",children:["Importing contacts ",Te.current.toLocaleStr
3ing()," out of ",Te.total.toLocaleString()," · ",s,"%"]})]})})})(),e.jsx(re,{open:je!==null,children:e.jsxs(ie,{className:"sm:max-w-md",onInteractOutside:s=>s.preventDefault(),children:[e.jsx(oe,{children:e.jsx(ce,{children:"Deleting contactsâ¦"})}),e.jsx(Tl,{value:je?je.done/Math.max(je.total,1)*100:0}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Deleting ",(je==null?void 0:je.done)??0," of ",(je==null?void 0:je.total)??0," contacts"]})]})})]})}export{Dn as default,Pn as prefetch};
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.