1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AdminTab-B7PuUhR0.js","assets/index-CzN0SCRv.js","assets/index-BAFf3ThT.css","assets/quantize-CffF34jF.js","assets/updateReasons-DcBkwFe5.js","assets/alert-dialog-DKsBrdjF.js","assets/index-WHCh_nVM.js","assets/mouse-pointer-click-C-ey7TxR.js","assets/textarea-DQIOaA43.js","assets/trash-2-DDVV4j3L.js","assets/copy-Ck9EyizL.js","assets/ReferralsTab-BlGCfeDM.js","assets/separator-D4iB1MgG.js","assets/dollar-sign-C_AIPh1-.js","assets/info-C9EYMW2H.js","assets/shopping-cart-lzpE31eD.js","assets/circle-check-big-DprBC3pd.js","assets/lightbulb-CCZNbvsf.js","assets/All_USA_50_states_1758449688422-CUfRVtca.js","assets/coinstack_1772976590166-gSmCXnOr.js","assets/form-DjdG-3ns.js","assets/thumbs-up-CMGm13xt.js","assets/plug-D3vCfDID.js","assets/crown-C9Esy2hA.js","assets/building-2-D4uT8NEb.js"])))=>i.map(i=>d[i]); 2import{Q as kc,i as Ri,h as Fc,a as Pc,u as Ic,c as ds,r as o,b as Gn,j as e,R as Ol,A as Zn,P as va,d as As,e as un,f as Cr,g as Dl,k as kr,l as Fr,D as Ml,C as $l,m as Kl,n as Fs,o as Qe,p as Ys,B as ie,S as Kt,q as ua,s as Tc,t as Ac,v as Lc,w as Rc,x as Oc,F as Dc,y as os,z as cs,E as as,G as rs,T as ps,H as $s,I as er,J as N,K as Ss,L as Ne,M as z,N as ue,O as Oi,U as tr,V as Ua,W as Pr,X as Xn,Y as ce,Z as Ul,_ as Ue,$ as _e,a0 as ea,a1 as zt,a2 as Vt,a3 as Lt,a4 as _l,a5 as Ee,a6 as Ut,a7 as Qs,a8 as Ks,a9 as sa,aa as ya,ab as ei,ac as ti,ad as si,ae as ai,af as La,ag as Ls,ah as sr,ai as Mc,aj as ar,ak as _a,al as $c,am as Kc,an as Uc,ao as zl,ap as _c,aq as zc,ar as vr,as as Di,at as ri,au as xe,av as Qa,aw as Ra,ax as Oa,ay as Da,az as Vc,aA as Ga,aB as Za,aC as qc,aD as Vl,aE as Hc,aF as yr,aG as Ya,aH as _n,aI as zn,aJ as Vs,aK as Us,aL as da,aM as Wc,aN as Bc,aO as Jc,aP as ql,aQ as Yc,aR as Hl,aS as Wl,aT as Bl,aU as Qc,aV as ni,aW as Mi,aX as $i,aY as Gc,aZ as Zc,a_ as Jl,a$ as oa,b0 as Yl,b1 as Ba,b2 as Xc,b3 as sn,b4 as Pa,b5 as Or,b6 as Yr,b7 as Ki,b8 as Ui,b9 as ed,ba as td,bb as _i,bc as sd,bd as ad,be as Ql,bf as rd,bg as nd,bh as id,bi as ld,bj as od,bk as cd,bl as dd,bm as md,bn as ud,bo as pd,bp as Bs,bq as Dr,br as xd,bs as hd,bt as gd,bu as yd,bv as Pn,bw as fd,bx as Mr,by as bd,bz as wd}from"./index-CzN0SCRv.js";import{c as ii}from"./coinstack_1772976590166-gSmCXnOr.js";import{u as ja,i as Xs,m as vd,a as jd}from"./All_USA_50_states_1758449688422-CUfRVtca.js";import{T as Ma}from"./textarea-DQIOaA43.js";import{L as ca,B as Xa,O as Nd,F as $a,a as Ed,K as Ta}from"./updateReasons-DcBkwFe5.js";import{E as aa,C as Ws,R as Sd}from"./ReferralsTab-BlGCfeDM.js";import{e as Gl,u as Cd,s as fr,o as Zl,a as Xl,b as kd,F as Fd,c as $r,d as Kr,f as Ur,g as In,h as _r,t as Pd,l as zi}from"./form-DjdG-3ns.js";import{T as Hs}from"./trash-2-DDVV4j3L.js";import{A as li,S as Jt,a as Yt,b as Qt,c as Gt,d as Ie,e as xs,C as Vn,f as pn,g as xn,h as hn,i as gn,j as yn,k as fn,l as bn,m as oi}from"./alert-dialog-DKsBrdjF.js";import{u as Id}from"./index-WHCh_nVM.js";import{I as br}from"./info-C9EYMW2H.js";import{T as Vi,a as qi}from"./thumbs-up-CMGm13xt.js";import{C as jr}from"./copy-Ck9EyizL.js";import{P as wr}from"./plug-D3vCfDID.js";import{C as Td}from"./crown-C9Esy2hA.js";import{B as Ad}from"./building-2-D4uT8NEb.js";var Ld=class extends kc{constructor(t,r){super(t,r)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(t,r){super.setOptions({...t,behavior:Ri()},r)}getOptimisticResult(t){return t.behavior=Ri(),super.getOptimisticResult(t)}fetchNextPage(t){return this.fetch({...t,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(t){return this.fetch({...t,meta:{fetchMore:{direction:"backward"}}})}createResult(t,r){var E,A;const{state:s}=t,i=super.createResult(t,r),{isFetching:l,isRefetching:c,isError:d,isRefetchError:u}=i,g=(A=(E=s.fetchMeta)==null?void 0:E.fetchMore)==null?void 0:A.direction,f=d&&g==="forward",C=l&&g==="forward",F=d&&g==="backward",w=l&&g==="backward";return{...i,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Pc(r,s.data),hasPreviousPage:Fc(r,s.data),isFetchNextPageError:f,isFetchingNextPage:C,isFetchPreviousPageError:F,isFetchingPreviousPage:w,isRefetchError:u&&!f&&!F,isRefetching:c&&!C&&!w}}};function Rd(t,r){return Ic(t,Ld)}/** 3 * @license lucide-react v0.453.0 - ISC 4 * 5 * This source code is licensed under the ISC license. 6 * See the LICENSE file in the root directory of this source tree. 7 */const Tn=ds("Bell",[["path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9",key:"1qo2s2"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}]]);/** 8 * @license lucide-react v0.453.0 - ISC 9 * 10 * This source code is licensed under the ISC license. 11 * See the LICENSE file in the root directory of this source tree. 12 */const eo=ds("Bookmark",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]]);/** 13 * @license lucide-react v0.453.0 - ISC 14 * 15 * This source code is licensed under the ISC license. 16 * See the LICENSE file in the root directory of this source tree. 17 */const ci=ds("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);/** 18 * @license lucide-react v0.453.0 - ISC 19 * 20 * This source code is licensed under the ISC license. 21 * See the LICENSE file in the root directory of this source tree. 22 */const rr=ds("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** 23 * @license lucide-react v0.453.0 - ISC 24 * 25 * This source code is licensed under the ISC license. 26 * See the LICENSE file in the root directory of this source tree.
27 */const Hi=ds("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/** 28 * @license lucide-react v0.453.0 - ISC 29 * 30 * This source code is licensed under the ISC license. 31 * See the LICENSE file in the root directory of this source tree. 32 */const qn=ds("Combine",[["path",{d:"M10 18H5a3 3 0 0 1-3-3v-1",key:"ru65g8"}],["path",{d:"M14 2a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2",key:"e30een"}],["path",{d:"M20 2a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2",key:"2ahx8o"}],["path",{d:"m7 21 3-3-3-3",key:"127cv2"}],["rect",{x:"14",y:"14",width:"8",height:"8",rx:"2",key:"1b0bso"}],["rect",{x:"2",y:"2",width:"8",height:"8",rx:"2",key:"1x09vl"}]]);/** 33 * @license lucide-react v0.453.0 - ISC 34 * 35 * This source code is licensed under the ISC license. 36 * See the LICENSE file in the root directory of this source tree. 37 */const Od=ds("FileJson",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"1oajmo"}],["path",{d:"M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"mpwhp6"}]]);/** 38 * @license lucide-react v0.453.0 - ISC 39 * 40 * This source code is licensed under the ISC license. 41 * See the LICENSE file in the root directory of this source tree. 42 */const Dd=ds("FileSpreadsheet",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]]);/** 43 * @license lucide-react v0.453.0 - ISC 44 * 45 * This source code is licensed under the ISC license. 46 * See the LICENSE file in the root directory of this source tree. 47 */const Md=ds("Gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]);/** 48 * @license lucide-react v0.453.0 - ISC 49 * 50 * This source code is licensed under the ISC license. 51 * See the LICENSE file in the root directory of this source tree. 52 */const $d=ds("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** 53 * @license lucide-react v0.453.0 - ISC 54 * 55 * This source code is licensed under the ISC license. 56 * See the LICENSE file in the root directory of this source tree. 57 */const di=ds("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/** 58 * @license lucide-react v0.453.0 - ISC 59 * 60 * This source code is licensed under the ISC license. 61 * See the LICENSE file in the root directory of this source tree. 62 */const Wi=ds("Link",[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]]);/** 63 * @license lucide-react v0.453.0 - ISC 64 * 65 * This source code is licensed under the ISC license. 66 * See the LICENSE file in the root directory of this source tree. 67 */const wn=ds("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);/** 68 * @license lucide-react v0.453.0 - ISC 69 * 70 * This source code is licensed under the ISC license. 71 * See the LICENSE file in the root directory of this source tree. 72 */const Kd=ds("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);/** 73 * @license lucide-react v0.453.0 - ISC 74 * 75 * This source code is licensed under the ISC license. 76 * See the LICENSE file in the root directory of this source tree. 77 */const ns=ds("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** 78 * @license lucide-react v0.453.0 - ISC 79 * 80 * This source code is licensed under the ISC license. 81 * See the LICENSE file in the root directory of this source tree. 82 */const ba=ds("RefreshCcw",[["path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"14sxne"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16",key:"1hlbsb"}],["path",{d:"M16 16h5v5",key:"ccwih5"}]]);/** 83 * @license lucide-react v0.453.0 - ISC 84 * 85 * This source code is licensed under the ISC license. 86 * See the LICENSE file in the root directory of this source tree. 87 */const to=ds("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/** 88 * @license lucide-react v0.453.0 - ISC 89 * 90 * This source code is licensed under the ISC license. 91 * See the LICENSE file in the root directory of this source tree. 92 */const nr=ds("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/** 93 * @license lucide-react v0.453.0 - ISC 94 * 95 * This source code is licensed under the ISC license. 96 * See the LICENSE file in the root directory of this source tree. 97 */const Ud=ds("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]);/** 98 * @license lucide-react v0.453.0 - ISC 99 * 100 * This source code is licensed under the ISC license. 101 * See the LICENSE file in the root directory of this source tree. 102 */const _d=ds("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]);/** 103 * @license lucide-react v0.453.0 - ISC 104 * 105 * This source code is licensed under the ISC license. 106 * See the LICENSE file in the root directory of this source tree. 107 */const Bi=ds("Target",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/** 108 * @license lucide-react v0.453.0 - ISC 109 * 110 * This source code is licensed under the ISC license. 111 * See the LICENSE file in the root directory of this source tree. 112 */const Ji=ds("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/** 113 * @license lucide-react v0.453.0 - ISC 114 * 115 * This source code is licensed under the ISC license. 116 * See the LICENSE file in the root directory of this source tree. 117 */const zd=ds("Webhook",[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]]);function Wt(t){const r=Object.prototype.toString.call(t);return t instanceof Date||typeof t=="object"&&r==="[object Date]"?new t.constructor(+t):typeof t=="number"||r==="[object Number]"||typeof t=="string"||r==="[object String]"?new Date(t):new Date(NaN)}function wa(t,r){return t instanceof Date?new t.constructor(r):new Date(r)}const so=6048e5,Vd=864e5,zr=43200,Yi=1440;let qd={};function Ir(){return qd}function Nr(t,r){var u,g,f,C;const s=Ir(),i=(r==null?void 0:r.weekStartsOn)??((g=(u=r==null?void 0:r.locale)==null?void 0:u.options)==null?void 0:g.weekStartsOn)??s.weekStartsOn??((C=(f=s.locale)==null?void 0:f.options)==null?void 0:C.weekStartsOn)??0,l=Wt(t),c=l.getDay(),d=(c<i?7:0)+c-i;return l.setDate(l.getDate()-d),l.setHours(0,0,0,0),l}function an(t){return Nr(t,{weekStartsOn:1}
117)}function ao(t){const r=Wt(t),s=r.getFullYear(),i=wa(t,0);i.setFullYear(s+1,0,4),i.setHours(0,0,0,0);const l=an(i),c=wa(t,0);c.setFullYear(s,0,4),c.setHours(0,0,0,0);const d=an(c);return r.getTime()>=l.getTime()?s+1:r.getTime()>=d.getTime()?s:s-1}function Qi(t){const r=Wt(t);return r.setHours(0,0,0,0),r}function rn(t){const r=Wt(t),s=new Date(Date.UTC(r.getFullYear(),r.getMonth(),r.getDate(),r.getHours(),r.getMinutes(),r.getSeconds(),r.getMilliseconds()));return s.setUTCFullYear(r.getFullYear()),+t-+s}function Hd(t,r){const s=Qi(t),i=Qi(r),l=+s-rn(s),c=+i-rn(i);return Math.round((l-c)/Vd)}function Wd(t){const r=ao(t),s=wa(t,0);return s.setFullYear(r,0,4),s.setHours(0,0,0,0),an(s)}function Qr(t,r){const s=Wt(t),i=Wt(r),l=s.getTime()-i.getTime();return l<0?-1:l>0?1:l}function Bd(t){return wa(t,Date.now())}function Jd(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function Yd(t){if(!Jd(t)&&typeof t!="number")return!1;const r=Wt(t);return!isNaN(Number(r))}function Qd(t,r){const s=Wt(t),i=Wt(r),l=s.getFullYear()-i.getFullYear(),c=s.getMonth()-i.getMonth();return l*12+c}function Gd(t){return r=>{const i=(t?Math[t]:Math.trunc)(r);return i===0?0:i}}function Zd(t,r){return+Wt(t)-+Wt(r)}function Xd(t){const r=Wt(t);return r.setHours(23,59,59,999),r}function em(t){const r=Wt(t),s=r.getMonth();return r.setFullYear(r.getFullYear(),s+1,0),r.setHours(23,59,59,999),r}function tm(t){const r=Wt(t);return+Xd(r)==+em(r)}function sm(t,r){const s=Wt(t),i=Wt(r),l=Qr(s,i),c=Math.abs(Qd(s,i));let d;if(c<1)d=0;else{s.getMonth()===1&&s.getDate()>27&&s.setDate(30),s.setMonth(s.getMonth()-l*c);let u=Qr(s,i)===-l;tm(Wt(t))&&c===1&&Qr(t,i)===1&&(u=!1),d=l*(c-Number(u))}return d===0?0:d}function am(t,r,s){const i=Zd(t,r)/1e3;return Gd(s==null?void 0:s.roundingMethod)(i)}function rm(t){const r=Wt(t),s=wa(t,0);return s.setFullYear(r.getFullYear(),0,1),s.setHours(0,0,0,0),s}const nm={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},im=(t,r,s)=>{let i;const l=nm[t];return typeof l=="string"?i=l:r===1?i=l.one:i=l.other.replace("{{count}}
117",r.toString()),s!=null&&s.addSuffix?s.comparison&&s.comparison>0?"in "+i:i+" ago":i};function An(t){return(r={})=>{const s=r.width?String(r.width):t.defaultWidth;return t.formats[s]||t.formats[t.defaultWidth]}}const lm={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},om={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},cm={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},dm={date:An({formats:lm,defaultWidth:"full"}),time:An({formats:om,defaultWidth:"full"}),dateTime:An({formats:cm,defaultWidth:"full"})},mm={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},um=(t,r,s,i)=>mm[t];function mr(t){return(r,s)=>{const i=s!=null&&s.context?String(s.context):"standalone";let l;if(i==="formatting"&&t.formattingValues){const d=t.defaultFormattingWidth||t.defaultWidth,u=s!=null&&s.width?String(s.width):d;l=t.formattingValues[u]||t.formattingValues[d]}else{const d=t.defaultWidth,u=s!=null&&s.width?String(s.width):t.defaultWidth;l=t.values[u]||t.values[d]}const c=t.argumentCallback?t.argumentCallback(r):r;return l[c]}}const pm={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},xm={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},hm={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},gm={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},ym={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},fm={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},bm=(t,r)=>{const s=Number(t),i=s%100;if(i>20||i<10)switch(i%10){case 1:return s+"st";case 2:return s+"nd";case 3:return s+"rd"}return s+"th"},wm={ordinalNumber:bm,era:mr({values:pm,defaultWidth:"wide"}),quarter:mr({values:xm,defaultWidth:"wide",argumentCallback:t=>t-1}),month:mr({values:hm,defaultWidth:"wide"}),day:mr({values:gm,defaultWidth:"wide"}),dayPeriod:mr({values:ym,defaultWidth:"wide",formattingValues:fm,defaultFormattingWidth:"wide"})};function ur(t){return(r,s={})=>{const i=s.width,l=i&&t.matchPatterns[i]||t.matchPatterns[t.defaultMatchWidth],c=r.match(l);if(!c)return null;const d=c[0],u=i&&t.parsePatterns[i]||t.parsePatterns[t.defaultParseWidth],g=Array.isArray(u)?jm(u,F=>F.test(d)):vm(u,F=>F.test(d));let f;f=t.valueCallback?t.valueCallback(g):g,f=s.valueCallback?s.valueCallback(f):f;const C=r.slice(d.length);return{value:f,rest:C}}}function vm(t,r){for(const s in t)if(Object.prototype.hasOwnProperty.call(t,s)&&r(t[s]))return s}function jm(t,r){for(let s=0;s<t.length;s++)if(r(t[s]))return s}function Nm(t){return(r,s={})=>{const i=r.match(t.matchPattern);if(!i)return null;const l=i[0],c=r.match(t.parsePattern);if(!c)return null;let d=t.valueCallback?t.valueCallback(c[0]):c[0];d=s.valueCallback?s.valueCallback(d):d;const u=r.slice(l.length);return{value:d,rest:u}}}const Em=/^(\d+)(th|st|nd|rd)?/i,Sm=/\d+/i,Cm={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},km={any:[/^b/i,/^(a|c)/i]},Fm={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},Pm={any:[/1/i,/2/i,/3/i,/4/i]},Im={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},Tm={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},Am={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},Lm={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},Rm={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},Om={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},Dm={ordinalNumber:Nm({matchPattern:Em,parsePattern:Sm,valueCallback:t=>parseInt(t,10)}),era:ur({matchPatterns:Cm,defaultMatchWidth:"wide",parsePatterns:km,defaultParseWidth:"any"}),quarter:ur({matchPatterns:Fm,defaultMatchWidth:"wide",parsePatterns:Pm,defaultParseWidth:"any",valueCallback:t=>t+1}),month:ur({matchPatterns:Im,defaultMatchWidth:"wide",parsePatterns:Tm,defaultParseWidth:"any"}),day:ur({matchPatterns:Am,defaultMatchWidth:"wide",parsePatterns:Lm,defaultParseWidth:"any"}),dayPeriod:ur({matchPatterns:Rm,defaultMatchWidth:"any",parsePatterns:Om,defaultParseWidth:"any"})},ro={code:"en-US",formatDistance:im,formatLong:dm,formatRelative:um,localize:wm,match:Dm,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Mm(t){const r=Wt(t);return Hd(r,rm(r))+1}function $m(t){const r=Wt(t),s=+an(r)-+Wd(r);return Math.round(s/so)+1}function no(t,r){var C,F,w,j;const s=Wt(t),i=s.getFullYear(),l=Ir(),c=(r==null?void 0:r.firstWeekContainsDate)??((F=(C=r==null?void 0:r.locale)==null?void 0:C.options)==null?void 0:F.firstWeekContainsDate)??l.firstWeekContainsDate??((j=(w=l.locale)==null?void 0:w.options)==null?void 0:j.firstWeekContainsDate)??1,d=wa(t,0);d.setFullYear(i+1,0,c),d.setHours(0,0,0,0);const u=Nr(d,r),g=wa(t,0);g.setFullYear(i,0,c),g.setHours(0,0,0,0);const f=Nr(g,r);return s.getTime()>=u.getTime()?i+1:s.getTime()>=f.getTime()?i:i-1}function Km(t,r){var u,g,f,C;const s=Ir(),i=(r==null?void 0:r.firstWeekContainsDate)??((g=(u=r==null?void 0:r.locale)==null?void 0:u.options)==null?void 0:g.firstWeekContainsDate)??s.firstWeekContainsDate??((C=(f=s.locale)==null?void 0:f.options)==null?void 0:C.firstWeekContainsDate)??1,l=no(t,r),c=wa(t,0);return c.setFullYear(l,0,i),c.setHours(0,0,0,0),Nr(c,r)}function Um(t,r){const s=Wt(t),i=+Nr(s,r)-+Km(s,r);return Math.round(i/so)+1}function $t(t,r){const s=t<0?"-":"",i=Math.abs(t).toString().padStart(r,"0");return s+i}const ga={y(t,r){const s=t.getFullYear(),i=s>0?s:1-s;return $t(r==="yy"?i%100:i,r.length)},M(t,r){const s=t.getMonth();return r==="M"?String(s+1):$t(s+1,2)},d(t,r){return $t(t.getDate(),r.length)},a(t,r){const s=t.getHours()/12>=1?"pm":"am";switch(r){case"a":case"aa":return s.toUpperCase();case"aaa":return s;case"aaaaa":return s[0];case"aaaa":default:return s==="am"?"a.m.":"p.m."}},h(t,r){return $t(t.getHours()%12||12,r.length)},H(t,r){return $t(t.getHours(),r.length)},m(t,r){return $t(t.getMinutes(),r.length)},s(t,r){return $t(t.getSeconds(),r.length)},S(t,r){const s=r.length,i=t.getMilliseconds(),l=Math.trunc(i*Math.pow(10,s-3));return $t(l,r.length)}},Ja={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Gi={G:function(t,r,s){const i=t.getFullYear()>0?1:0;switch(r){case"G":case"GG":case"GGG":return s.era(i,{width:"abbreviated"});case"GGGGG":return s.era(i,{width:"narrow"});case"GGGG":default:return s.era(i,{width:"wide"})}},y:function(t,r,s){if(r==="yo"){const i=t.getFullYear(),l=i>0?i:1-i;return s.ordinalNumber(l,{unit:"year"})}return ga.y(t,r)},Y:function(t,r,s,i){const l=no(t,i),c=l>0?l:1-l;if(r==="YY"){const d=c%100;return $t(d,2)}return r==="Yo"?s.ordinalNumber(c,{unit:"year"}):$t(c,r.length)},R:function(t,r){const s=ao(t);return $t(s,r.length)},u:function(t,r){const s=t.getFullYear();return $t(s,r.length)},Q:function(t,r,s){const i=Math.ceil((t.getMonth()+1)/3);switch(r){case"Q":return String(i);case"QQ":return $t(i,2);case"Qo":return s.ordinalNumber(i,{unit:"quarter"});case"QQQ":return s.quarter(i,{width:"abbreviated",context:"formatting"});case"QQQQQ":return s.quarter(i,{width:"narrow",context:"formatting"});case"QQQQ":default:return s.quarter(i,{width:"wide",context:"formatting"})}},q:function(t,r,s){const i=Math.ceil((t.getMonth()+1)/3);switch(r){case"q":return String(i);case"qq":return $t(i,2);case"qo":return s.ordinalNumber(i,{unit:"quarter"});case"qqq":return s.quarter(i,{width:"abbreviated",context:"standalone"});case"qqqqq":return s.quarter(i,{width:"narrow",context:"standalone"});case"qqqq":default:return s.quarter(i,{width:"wide",context:"standalone"})}},M:function(t,r,s){const i=t.getMonth();switch(r){case"M":case"MM":return ga.M(t,r);case"Mo":return s.ordinalNumber(i+1,{unit:"month"});case"MMM":return s.month(i,{width:"abbreviated",context:"formatting"});case"MMMMM":return s.month(i,{width:"narrow",context:"formatting"});case"MMMM":default:return s.month(i,{width:"wide",context:"formatting"})}},L:function(t,r,s){const i=t.getMonth();switch(r){case"L":return String(i+1);case"LL":return $t(i+1,2);case"Lo":return s.ordinalNumber(i+1,{unit:"month"});case"LLL":return s.month(i,{width:"abbreviated",context:"standalone"});case"LLLLL":return s.month(i,{width:"narrow",context:"standalone"});case"LLLL":default:return s.month(i,{width:"wide",context:"standalone"})}},w:function(t,r,s,i){const l=Um(t,i);return r==="wo"?s.ordinalNumber(l,{unit:"week"}):$t(l,r.length)},I:function(t,r,s){const i=$m(t);return r==="Io"?s.ordinalNumber(i,{unit:"week"}):$t(i,r.length)},d:function(t,r,s){return r==="do"?s.ordinalNumber(t.getDate(),{unit:"date"}):ga.d(t,r)},D:function(t,r,s){const i=Mm(t);return r==="Do"?s.ordinalNumber(i,{unit:"dayOfYear"}):$t(i,r.length)},E:function(t,r,s){const i=t.getDay();switch(r){case"E":case"EE":case"EEE":return s.day(i,{width:"abbreviated",context:"formatting"});case"EEEEE":return s.day(i,{width:"narrow",context:"formatting"});case"EEEEEE":return s.day(i,{width:"short",context:"formatting"});case"EEEE":default:return s.day(i,{width:"wide",context:"formatting"})}},e:function(t,r,s,i){const l=t.getDay(),c=(l-i.weekStartsOn+8)%7||7;switch(r){case"e":return String(c);case"ee":return $t(c,2);case"eo":return s.ordinalNumber(c,{unit:"day"});case"eee":return s.day(l,{width:"abbreviated",context:"formatting"});case"eeeee":return s.day(l,{width:"narrow",context:"formatting"});case"eeeeee":return s.day(l,{width:"short",context:"formatting"});case"eeee":default:return s.day(l,{width:"wide",context:"formatting"})}},c:function(t,r,s,i){const l=t.getDay(),c=(l-i.weekStartsOn+8)%7||7;switch(r){case"c":return String(c);case"cc":return $t(c,r.length);case"co":return s.ordinalNumber(c,{unit:"day"});case"ccc":return s.day(l,{width:"abbreviated",context:"standalone"});case"ccccc":return s.day(l,{width:"narrow",context:"standalone"});case"cccccc":return s.day(l,{width:"short",context:"standalone"});case"cccc":default:return s.day(l,{width:"wide",context:"standalone"})}},i:function(t,r,s){const i=t.getDay(),l=i===0?7:i;switch(r){case"i":return String(l);case"ii":return $t(l,r.length);case"io":return s.ordinalNumber(l,{unit:"day"});case"iii":return s.day(i,{width:"abbreviated",context:"formatting"});case"iiiii":return s.day(i,{width:"narrow",context:"formatting"});case"iiiiii":return s.day(i,{width:"short",context:"formatting"});case"iiii":default:return s.day(i,{width:"wide",context:"formatting"})}},a:function(t,r,s){const l=t.getHours()/12>=1?"pm":"am";switch(r){case"a":case"aa":return s.dayPeriod(l,{width:"abbreviated",context:"formatting"});case"aaa":return s.dayPeriod(l,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return s.dayPeriod(l,{width:"narrow",context:"formatting"});case"aaaa":default:return s.dayPeriod(l,{width:"wide",context:"formatting"})}},b:function(t,r,s){const i=t.getHours();let l;
vendor: 4,453 bytes, line 117
117switch(i===12?l=Ja.noon:i===0?l=Ja.midnight:l=i/12>=1?"pm":"am",r){case"b":case"bb":return s.dayPeriod(l,{width:"abbreviated",context:"formatting"});case"bbb":return s.dayPeriod(l,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return s.dayPeriod(l,{width:"narrow",context:"formatting"});case"bbbb":default:return s.dayPeriod(l,{width:"wide",context:"formatting"})}},B:function(t,r,s){const i=t.getHours();let l;switch(i>=17?l=Ja.evening:i>=12?l=Ja.afternoon:i>=4?l=Ja.morning:l=Ja.night,r){case"B":case"BB":case"BBB":return s.dayPeriod(l,{width:"abbreviated",context:"formatting"});case"BBBBB":return s.dayPeriod(l,{width:"narrow",context:"formatting"});case"BBBB":default:return s.dayPeriod(l,{width:"wide",context:"formatting"})}},h:function(t,r,s){if(r==="ho"){let i=t.getHours()%12;return i===0&&(i=12),s.ordinalNumber(i,{unit:"hour"})}return ga.h(t,r)},H:function(t,r,s){return r==="Ho"?s.ordinalNumber(t.getHours(),{unit:"hour"}):ga.H(t,r)},K:function(t,r,s){const i=t.getHours()%12;return r==="Ko"?s.ordinalNumber(i,{unit:"hour"}):$t(i,r.length)},k:function(t,r,s){let i=t.getHours();return i===0&&(i=24),r==="ko"?s.ordinalNumber(i,{unit:"hour"}):$t(i,r.length)},m:function(t,r,s){return r==="mo"?s.ordinalNumber(t.getMinutes(),{unit:"minute"}):ga.m(t,r)},s:function(t,r,s){return r==="so"?s.ordinalNumber(t.getSeconds(),{unit:"second"}):ga.s(t,r)},S:function(t,r){return ga.S(t,r)},X:function(t,r,s){const i=t.getTimezoneOffset();if(i===0)return"Z";switch(r){case"X":return Xi(i);case"XXXX":case"XX":return Sa(i);case"XXXXX":case"XXX":default:return Sa(i,":")}},x:function(t,r,s){const i=t.getTimezoneOffset();switch(r){case"x":return Xi(i);case"xxxx":case"xx":return Sa(i);case"xxxxx":case"xxx":default:return Sa(i,":")}},O:function(t,r,s){const i=t.getTimezoneOffset();switch(r){case"O":case"OO":case"OOO":return"GMT"+Zi(i,":");case"OOOO":default:return"GMT"+Sa(i,":")}},z:function(t,r,s){const i=t.getTimezoneOffset();switch(r){case"z":case"zz":case"zzz":return"GMT"+Zi(i,":");case"zzzz":default:return"GMT"+Sa(i,":")}},t:function(t,r,s){const i=Math.trunc(t.getTime()/1e3);return $t(i,r.length)},T:function(t,r,s){const i=t.getTime();return $t(i,r.length)}};function Zi(t,r=""){const s=t>0?"-":"+",i=Math.abs(t),l=Math.trunc(i/60),c=i%60;return c===0?s+String(l):s+String(l)+r+$t(c,2)}function Xi(t,r){return t%60===0?(t>0?"-":"+")+$t(Math.abs(t)/60,2):Sa(t,r)}function Sa(t,r=""){const s=t>0?"-":"+",i=Math.abs(t),l=$t(Math.trunc(i/60),2),c=$t(i%60,2);return s+l+r+c}const el=(t,r)=>{switch(t){case"P":return r.date({width:"short"});case"PP":return r.date({width:"medium"});case"PPP":return r.date({width:"long"});case"PPPP":default:return r.date({width:"full"})}},io=(t,r)=>{switch(t){case"p":return r.time({width:"short"});case"pp":return r.time({width:"medium"});case"ppp":return r.time({width:"long"});case"pppp":default:return r.time({width:"full"})}},_m=(t,r)=>{const s=t.match(/(P+)(p+)?/)||[],i=s[1],l=s[2];if(!l)return el(t,r);let c;switch(i){case"P":c=r.dateTime({width:"short"});break;case"PP":c=r.dateTime({width:"medium"});break;case"PPP":c=r.dateTime({width:"long"});break;case"PPPP":default:c=r.dateTime({width:"full"});break}return c.replace("{{date}}",el(i,r)).replace("{{time}}",io(l,r))},zm={p:io,P:_m},Vm=/^D+$/,qm=/^Y+$/,Hm=["D","DD","YY","YYYY"];function Wm(t){return Vm.test(t)}function Bm(t){return qm.test(t)}function Jm(t,r,s){const i=Ym(t,r,s);if(console.warn(i),Hm.includes(t))throw new RangeError(i)}function Ym(t,r,s){const i=t[0]==="Y"?"years":"days of the month";return`Use \`${t.toLowerCase()}\` instead of \`${t}\` (in \`${r}\`) for formatting ${i} to the input \`${s}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const Qm=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Gm=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Zm=/^'([^]*?)'?$/,Xm=/''/g,eu=/[a-zA-Z]/;function Ka(t,r,s){var C,F,w,j;const i=Ir(),l=i.locale??ro,c=i.firstWeekContainsDate??((F=(C=i.locale)==null?void 0:C.options)==null?void 0:F.firstWeekContainsDate)??1,d=i.weekStartsOn??((j=(w=i.locale)==null?void 0:w.options)==null?void 0:j.weekStartsOn)??0,u=Wt(t);if(!Yd(u))throw new RangeError("Invalid time value");let g=r.match(Gm).map(E=>{const A=E[0];if(A==="p"||A==="P"){const T=zm[A];return T(E,l.formatLong)}return E}).join("").match(Qm).map(E=>{if(E==="''")return{isToken:!1,value:"'"};const A=E[0];if(A==="'")return{isToken:!1,value:tu(E)};if(Gi[A])return{isToken:!0,value:E};
117if(A.match(eu))throw new RangeError("Format string contains an unescaped latin alphabet character `"+A+"`");return{isToken:!1,value:E}});l.localize.preprocessor&&(g=l.localize.preprocessor(u,g));const f={firstWeekContainsDate:c,weekStartsOn:d,locale:l};return g.map(E=>{if(!E.isToken)return E.value;const A=E.value;(Bm(A)||Wm(A))&&Jm(A,r,String(t));const T=Gi[A[0]];return T(u,A,l.localize,f)}).join("")}function tu(t){const r=t.match(Zm);return r?r[1].replace(Xm,"'"):t}function su(t,r,s){const i=Ir(),l=(s==null?void 0:s.locale)??i.locale??ro,c=2520,d=Qr(t,r);if(isNaN(d))throw new RangeError("Invalid time value");const u=Object.assign({},s,{addSuffix:s==null?void 0:s.addSuffix,comparison:d});let g,f;d>0?(g=Wt(r),f=Wt(t)):(g=Wt(t),f=Wt(r));const C=am(f,g),F=(rn(f)-rn(g))/1e3,w=Math.round((C-F)/60);let j;if(w<2)return s!=null&&s.includeSeconds?C<5?l.formatDistance("lessThanXSeconds",5,u):C<10?l.formatDistance("lessThanXSeconds",10,u):C<20?l.formatDistance("lessThanXSeconds",20,u):C<40?l.formatDistance("halfAMinute",0,u):C<60?l.formatDistance("lessThanXMinutes",1,u):l.formatDistance("xMinutes",1,u):w===0?l.formatDistance("lessThanXMinutes",1,u):l.formatDistance("xMinutes",w,u);if(w<45)return l.formatDistance("xMinutes",w,u);if(w<90)return l.formatDistance("aboutXHours",1,u);if(w<Yi){const E=Math.round(w/60);return l.formatDistance("aboutXHours",E,u)}else{if(w<c)return l.formatDistance("xDays",1,u);if(w<zr){const E=Math.round(w/Yi);return l.formatDistance("xDays",E,u)}else if(w<zr*2)return j=Math.round(w/zr),l.formatDistance("aboutXMonths",j,u)}if(j=sm(f,g),j<12){const E=Math.round(w/zr);return l.formatDistance("xMonths",E,u)}else{const E=j%12,A=Math.trunc(j/12);return E<3?l.formatDistance("aboutXYears",A,u):E<9?l.formatDistance("overXYears",A,u):l.formatDistance("almostXYears",A+1,u)}}function nn(t,r){return su(t,Bd(t),r)}var Ln,mi="HoverCard",[lo]=kr(mi,[un]),vn=un(),[au,jn]=lo(mi),oo=t=>{const{__scopeHoverCard:r,children:s,open:i,defaultOpen:l,onOpenChange:c,openDelay:d=700,closeDelay:u=300}=t,g=vn(r),f=o.useRef(0),C=o.useRef(0),F=o.useRef(!1),w=o.useRef(!1),[j=!1,E]=Gn({prop:i,defaultProp:l,onChange:c}),A=o.useCallback(()=>{clearTimeout(C.current),f.current=window.setTimeout(()=>E(!0),d)},[d,E]),T=o.useCallback(()=>{clearTimeout(f.current),!F.current&&!w.current&&(C.current=window.setTimeout(()=>E(!1),u))},[u,E]),J=o.useCallback(()=>E(!1),[E]);return o.useEffect(()=>()=>{clearTimeout(f.current),clearTimeout(C.current)},[]),e.jsx(au,{scope:r,open:j,onOpenChange:E,onOpen:A,onClose:T,onDismiss:J,hasSelectionRef:F,isPointerDownOnContentRef:w,children:e.jsx(Ol,{...g,children:s})})};oo.displayName=mi;var co="HoverCardTrigger",mo=o.forwardRef((t,r)=>{const{__scopeHoverCard:s,...i}=t,l=jn(co,s),c=vn(s);return e.jsx(Zn,{asChild:!0,...c,children:e.jsx(va.a,{"data-state":l.open?"open":"closed",...i,ref:r,onPointerEnter:As(t.onPointerEnter,on(l.onOpen)),onPointerLeave:As(t.onPointerLeave,on(l.onClose)),onFocus:As(t.onFocus,l.onOpen),onBlur:As(t.onBlur,l.onClose),onTouchStart:As(t.onTouchStart,d=>d.preventDefault())})})});mo.displayName=co;var ui="HoverCardPortal",[ru,nu]=lo(ui,{forceMount:void 0}),uo=t=>{const{__scopeHoverCard:r,forceMount:s,children:i,container:l}=t,c=jn(ui,r);return e.jsx(ru,{scope:r,forceMount:s,children:e.jsx(Cr,{present:s||c.open,children:e.jsx(Dl,{asChild:!0,container:l,children:i})})})};uo.displayName=ui;var ln="HoverCardContent",po=o.forwardRef((t,r)=>{const s=nu(ln,t.__scopeHoverCard),{forceMount:i=s.forceMount,...l}=t,c=jn(ln,t.__scopeHoverCard);return e.jsx(Cr,{present:i||c.open,children:e.jsx(iu,{"data-state":c.open?"open":"closed",...l,onPointerEnter:As(t.onPointerEnter,on(c.onOpen)),onPointerLeave:As(t.onPointerLeave,on(c.onClose)),ref:r})})});po.displayName=ln;var iu=o.forwardRef((t,r)=>{const{__scopeHoverCard:s,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:c,onInteractOutside:d,...u}=t,g=jn(ln,s),f=vn(s),C=o.useRef(null),F=Fr(r,C),[w,j]=o.useState(!1);return o.useEffect(()=>{if(w){const E=document.body;return Ln=E.style.userSelect||E.style.webkitUserSelect,E.style.userSelect="none",E.style.webkitUserSelect="none",()=>{E.style.userSelect=Ln,E.style.webkitUserSelect=Ln}}},[w]),o.useEffect(()=>{if(C.current){const E=()=>{j(!1),g.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var T;((T=document.getSelection())==null?void 0:T.toString())!==""&&(g.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",E),()=>{document.removeEventListener("pointerup",E),g.hasSelectionRef.current=!1,g.isPointerDownOnContentRef.current=!1}}},[g.isPointerDownOnContentRef,g.hasSelectionRef]),o.useEffect(()=>{C.current&&cu(C.current).forEach(A=>A.setAttribute("tabindex","-1"))}),e.jsx(Ml,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:d,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:As(c,E=>{E.preventDefault()}),onDismiss:g.onDismiss,children:e.jsx($l,{...f,...u,onPointerDown:As(u.onPointerDown,E=>{E.currentTarget.contains(E.target)&&j(!0),g.hasSelectionRef.current=!1,g.isPointerDownOnContentRef.current=!0}),ref:F,style:{...u.style,userSelect:w?"text":void 0,WebkitUserSelect:w?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})}),lu="HoverCardArrow",ou=o.forwardRef((t,r)=>{const{__scopeHoverCard:s,...i}=t,l=vn(s);return e.jsx(Kl,{...l,...i,ref:r})});ou.displayName=lu;function on(t){return r=>r.pointerType==="touch"?void 0:t()}function cu(t){const r=[],s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:i=>i.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;s.nextNode();)r.push(s.currentNode);return r}
117var du=oo,mu=mo,uu=uo,xo=po;const pu=du,xu=mu,ho=o.forwardRef(({className:t,align:r="center",sideOffset:s=4,...i},l)=>e.jsx(uu,{children:e.jsx(xo,{ref:l,align:r,sideOffset:s,className:Fs("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-hover-card-content-transform-origin]",t),...i})}));ho.displayName=xo.displayName;function go(t){return(t??[]).filter(r=>r.amountRemaining>0).slice().sort((r,s)=>new Date(r.expiresAt).getTime()-new Date(s.expiresAt).getTime())}function hu(t,r=Date.now()){return(t??[]).reduce((s,i)=>s+(i.amountRemaining>0&&Er(i.expiresAt,r)>0?i.amountRemaining:0),0)}function gu(t){return go(t)[0]??null}function Er(t,r=Date.now()){const s=new Date(t).getTime()-r;return Math.max(0,Math.floor(s/1e3))}function yo(t,r=Date.now()){return go(t).filter(s=>Er(s.expiresAt,r)>0)}function cn(t){return t>=86400?`${Math.floor(t/86400)}d ${Math.floor(t%86400/3600)}h`:t>=3600?`${Math.floor(t/3600)}h ${Math.floor(t%3600/60)}m`:t>=60?`${Math.floor(t/60)}m ${t%60}s`:`${t}s`}const yu={onboarding_bonus:"Welcome bonus",admin_grant:"Bonus credits",email_campaign:"Campaign reward"};function Hn(t){return yu[t]??"Bonus credits"}function fu({user:t}){const{data:r}=Qe({queryKey:["/api/me/temporary-credits"],enabled:Ys(t.subscriptionPlan),staleTime:3e4}),s=gu(r==null?void 0:r.grants),[i,l]=o.useState(()=>Date.now());o.useEffect(()=>{const E=setInterval(()=>l(Date.now()),1e3);return()=>clearInterval(E)},[]);const[c,d]=o.useState(!1);if(!Ys(t.subscriptionPlan))return null;const u=Math.max(0,(t.monthlyCredits||0)-(t.monthlyCreditsUsed||0)),g=t.permanentCredits||0,f=hu(r==null?void 0:r.grants,i),C=u+g+f,F=yo(r==null?void 0:r.grants,i),w=s?Er(s.expiresAt,i):null,j=e.jsxs(e.Fragment,{children:[C," credits",f>0&&e.jsxs("span",{className:"ml-0.5 text-amber-500 font-semibold",children:["+",f]}),e.jsx("img",{src:ii,alt:"",className:"h-3.5 w-3.5"}),f>0&&w!==null&&w>0&&e.jsxs("span",{className:"ml-1 inline-flex items-center gap-0.5 text-amber-500","data-testid":"text-temp-credit-expiry",children:[e.jsx(ua,{className:"h-3 w-3"}),e.jsx("span",{className:"font-mono font-medium",children:cn(w)})]})]});return F.length===0?e.jsx(ie,{className:"bg-amber-50 text-amber-700 border border-amber-200 text-xs flex items-center gap-1","data-testid":"badge-credit-balance",children:j}):e.jsxs(pu,{open:c,onOpenChange:d,openDelay:100,closeDelay:100,children:[e.jsx(xu,{asChild:!0,children:e.jsx("div",{className:"inline-flex items-center gap-1 rounded-full border border-amber-200 bg-amber-50 px-2.5 py-0.5 text-xs font-semibold text-amber-700 cursor-pointer",title:`${f} temporary bonus credit${f===1?"":"s"} across ${F.length} grant${F.length===1?"":"s"}`,"data-testid":"badge-credit-balance",role:"button","aria-haspopup":"dialog","aria-expanded":c,onPointerDown:E=>{E.stopPropagation(),(E.pointerType==="touch"||E.pointerType==="pen")&&(E.preventDefault(),d(A=>!A))},onClick:E=>{E.stopPropagation()},children:j})}),e.jsxs(ho,{align:"end",className:"w-72 p-3","data-testid":"popover-bonus-credits-breakdown",children:[e.jsxs("p",{className:"text-xs font-semibold text-gray-700 mb-2",children:["Temporary bonus credits (",f," total)"]}),e.jsx("div",{className:"space-y-1.5","data-testid":"list-header-bonus-credits-expiry",children:F.map(E=>{const A=Er(E.expiresAt,i);return e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-amber-200 bg-amber-50 px-2.5 py-1.5 text-xs","data-testid":`row-header-bonus-credits-expiry-${E.id}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5 font-medium text-amber-700",children:[e.jsx(Kt,{className:"h-3.5 w-3.5"}),E.amountRemaining,e.jsx("span",{className:"font-normal text-amber-500",children:Hn(E.source)})]}),e.jsxs("span",{className:"flex items-center gap-1 text-amber-600",children:[e.jsx(ua,{className:"h-3 w-3"}),e.jsx("span",{className:"font-mono font-medium","data-testid":`text-header-bonus-credits-countdown-${E.id}`,children:cn(A)})]})]},E.id)})})]})]})}const bu=["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","N
117orth Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"],wu=["New York, NY","Los Angeles, CA","Chicago, IL","Houston, TX","Phoenix, AZ","Philadelphia, PA","San Antonio, TX","San Diego, CA","Dallas, TX","San Jose, CA","Austin, TX","Jacksonville, FL","Fort Worth, TX","Columbus, OH","Charlotte, NC","San Francisco, CA","Indianapolis, IN","Seattle, WA","Denver, CO","Washington, DC","Boston, MA","El Paso, TX","Nashville, TN","Detroit, MI","Oklahoma City, OK","Portland, OR","Las Vegas, NV","Memphis, TN","Louisville, KY"],Ca=[{key:"lastUpdated",label:"Last Updated"},{key:"lastUpdatedReason",label:"Update Reason"},{key:"ylprProfileUrl",label:"Profile URL"},{key:"ylprProfileName",label:"Company Name"},{key:"ylprStars",label:"Stars"},{key:"ylprReviewCount",label:"Review Count"},{key:"ylprCategories",label:"Categories"},{key:"ylprAddressFull",label:"Address Full"},{key:"ylprAddressStreet",label:"Street"},{key:"ylprAddressCity",label:"Address City"},{key:"ylprAddressState",label:"Address State"},{key:"ylprAddressZip",label:"Address Zip"},{key:"ylprPhone",label:"Phone",sensitive:!0},{key:"ylprDescription",label:"Description"},{key:"ylprFeaturedReview",label:"Review Snippet"},{key:"ylprTimeScraped",label:"Time Scraped"}],ka=[{key:"lastUpdated",label:ca},{key:"lastUpdatedReason",label:Xa},{key:"wOgrequestedUrl",label:"Registered URL"},{key:"wProfileDate",label:"Registration Date"},{key:"wRedirectYn",label:"Redirect"},{key:"wSimpleCrawledUrl",label:"Crawled URL"},{key:"wCompanyName",label:"Company Name"},{key:"aiCategoryEstimation",label:"Categories (AI Enrichment)"},{key:"wPhonePrimary",label:"Phone Primary",sensitive:!0},{key:"wPhoneTotal",label:"Total Phones",sensitive:!0},{key:"wEmailPrimary",label:"Email Primary",sensitive:!0},{key:"wEmailPrimaryMx",label:"Email Primary Provider"},{key:"wEmailTier1",label:"Tier 1 Emails",sensitive:!0},{key:"wEmailTier2",label:"Tier 2 Emails",sensitive:!0},{key:"wEmailTier3",label:"Tier 3 Emails",sensitive:!0},{key:"wEmailTier4",label:"Tier 4 Emails",sensitive:!0},{key:"wEmailTier5",label:"Tier 5 Emails",sensitive:!0},{key:"wEmailTier6",label:"Tier 6 Emails",sensitive:!0},{key:"wEmailDomainMx",label:"Website Email Provider"},{key:"wEmailSecurity",label:"Website Email Security"},{key:"wProfileCategory",label:"Website Schema"},{key:"wProfileDescriptionShort",label:"Description Short"},{key:"wProfileDescriptionLong",label:"Description Long"},{key:"wAddressFull",label:"Address Full"},{key:"wAddressStreet",label:"Street"},{key:"wAddressCity",label:"City"},{key:"wAddressState",label:"State"},{key:"wAddressZip",label:"Zip"},{key:"wAddressSource",label:"Address Source"},{key:"wPlatform",label:"Platform"},{key:"wBookingOpsCrmSoftware",label:"Booking/Ops/CRM Software"},{key:"wReputationChatSoftware",label:"Reputation/Chat Software"},{key:"wMarketingEmailSoftware",label:"Marketing/Email Software"},{key:"wAdPixels",label:"Ad Pixels"},{key:"wPaymentFinancingSoftware",label:"Payment/Financing Software"},{key:"wEmployeeCount",label:"Employees"},{key:"wOpenPositions",label:"Number of Job Postings"},{key:"wFoundingDate",label:"Founding Date"},{key:"wNumLocations",label:"Number of Locations"},{key:"wIsChain",label:"Is Chain?"},{key:"wRatingValue",label:"Rating Value"},{key:"wReviewCount",label:"Review Count"},{key:"wPriceRange",label:"Price Range"},{key:"wLegalName",label:"Legal Name"},{key:"wIndustryNaics",label:"NAICS Code"},{key:"wDuns",label:"DUNS Number"},{key:"wFounder",label:"Founder Name(s)"},{key:"wFounderEmail",label:"Founder Email(s)",sensitive:!0},{key:"wFounderPhone",label:"Founder Phone(s)",sensitive:!0},{key:"wGeoLat",label:"Latitude"},{key:"wGeoLong",label:"Longitude"},{key:"wOpeningHours",label:"Opening Hours"},{key:"wAreaServed",label:"Area Served"},{key:"wOffers",label:"Offers"},{key:"wBrand",label:"Brand"},{key:"wSlogan",label:"Slogan"},{key:"wLogoUrl",label:"Logo URL"},{key:"wSocialProfiles",label:"Social Profiles"},{key:"wTimeScraped",label:"Time Scraped"}],tl=[{key:"company",label:"Company"},{key:"phone",label:"Phone",sensitive:!0},{key:"email",label:"Email",sensitive:!0},{key:"city",label:"City"},{key:"state",label:"State"}],vu="wLogoUrl",ju=Object.fromEntries(Ca.map(t=>[t.key,t.label])),Nu=Object.fromEntries(ka.map(t=>[t.key,t.label])),sl=32767,Eu=8192,Su=/^\s*(data|javascript|vbscript|blob|about|file):/i,Cu=/\/data:[a-z0-9.+-]+\/[a-z0-9.+-]+[;,]/i;function ku(t){return typeof t=="string"&&(Su.test(t)||Cu.test(t))}function Fu(t){return ku(t)||t.length>Eu}function Pu(t){if(t==null)return"";const r=String(t);return Fu(r)?"":r}function Iu(t){if(t.length<=sl)return t;let r=sl;const s=t.charCodeAt(r-1);return s>=55296&&s<=56319&&(r-=1),t.slice(0,r)}function Vr(t,r=!1){if(t==null)return"";const s=Iu(String(t));return r||/[",\r\n]/.test(s)?`"${s.replace(/"/g,'""')}"`:s}function fo(t,r,s={}){if(!t.length)return"";const i=Object.keys(r),l=new Set(s.alwaysQuoteColumns??[]),c=i.map(u=>Vr(r[u])).join(","),d=t.map(u=>i.map(g=>{const f=u[g];return s.logoUrlColumn!==void 0&&g===s.logoUrlColumn?Vr(Pu(f)):l.has(g)?f?Vr(f,!0):"":Vr(f)}).join(","));return[c,...d].join(` 118`)}const Nn=o.forwardRef(({className:t,...r},s)=>e.jsx("div",{className:"relative w-full",children:e.jsx("table",{ref:s,className:Fs("w-full caption-bottom text-sm",t),...r})}));Nn.displayName="Table";const En=o.forwardRef(({className:t,...r},s)=>e.jsx("thead",{ref:s,className:Fs("[&_tr]:border-b",t),...r}));En.displayName="TableHeader";const Sn=o.forwardRef(({className:t,...r},s)=>e.jsx("tbody",{ref:s,className:Fs("[&_tr:last-child]:border-0",t),...r}));Sn.displayName="TableBody";const Tu=o.forwardRef(({className:t,...r},s)=>e.jsx("tfoot",{ref:s,className:Fs("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",t),...r}));Tu.displayName="TableFooter";const za=o.forwardRef(({className:t,...r},s)=>e.jsx("tr",{ref:s,className:Fs("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",t),...r}));za.displayName="TableRow";const Ke=o.forwardRef(({className:t,...r},s)=>e.jsx("th",{ref:s,className:Fs("h-12 px-4 text-left align-middle font-medium text-muted-foreground",t),...r}));Ke.displayName="TableHead";const Fe=o.forwardRef(({className:t,...r},s)=>e.jsx("td",{ref:s,className:Fs("p-3 align-middle",t),...r}));Fe.displayName="TableCell";const Au=o.forwardRef(({className:t,...r},s)=>e.jsx("caption",{ref:s,className:Fs("mt-4 text-sm text-muted-foreground",t),...r}));Au.displayName="TableCaption";var pi="Popover",[bo]=kr(pi,[un]),Tr=un(),[Lu,Na]=bo(pi),wo=t=>{const{__scopePopover:r,children:s,open:i,defaultOpen:l,onOpenChange:c,modal:d=!1}=t,u=Tr(r),g=o.useRef(null),[f,C]=o.useState(!1),[F=!1,w]=Gn({prop:i,defaultProp:l,onChange:c});return e.jsx(Ol,{...u,children:e.jsx(Lu,{scope:r,contentId:Tc(),triggerRef:g,open:F,onOpenChange:w,onOpenToggle:o.useCallback(()=>w(j=>!j),[w]),hasCustomAnchor:f,onCustomAnchorAdd:o.useCallback(()=>C(!0),[]),onCustomAnchorRemove:o.useCallback(()=>C(!1),[]),modal:d,children:s})})};wo.displayName=pi;var vo="PopoverAnchor",Ru=o.forwardRef((t,r)=>{const{__scopePopover:s,...i}=t,l=Na(vo,s),c=Tr(s),{onCustomAnchorAdd:d,onCustomAnchorRemove:u}=l;return o.useEffect(()=>(d(),()=>u()),[d,u]),e.jsx(Zn,{...c,...i,ref:r})});Ru.displayName=vo;var jo="PopoverTrigger",No=o.forwardRef((t,r)=>{const{__scopePopover:s,...i}=t,l=Na(jo,s),c=Tr(s),d=Fr(r,l.triggerRef),u=e.jsx(va.button,{type:"button","aria-haspopup":"dialog","aria-expanded":l.open,"aria-controls":l.contentId,"data-state":Fo(l.open),...i,ref:d,onClick:As(t.onClick,l.onOpenToggle)});return l.hasCustomAnchor?u:e.jsx(Zn,{asChild:!0,...c,children:u})});No.displayName=jo;var xi="PopoverPortal",[Ou,Du]=bo(xi,{forceMount:void 0}),Eo=t=>{const{__scopePopover:r,forceMount:s,children:i,container:l}=t,c=Na(xi,r);return e.jsx(Ou,{scope:r,forceMount:s,children:e.jsx(Cr,{present:s||c.open,children:e.jsx(Dl,{asChild:!0,container:l,children:i})})})};Eo.displayName=xi;var ir="PopoverContent",So=o.forwardRef((t,r)=>{const s=Du(ir,t.__scopePopover),{forceMount:i=s.forceMount,...l}=t,c=Na(ir,t.__scopePopover);return e.jsx(Cr,{present:i||c.open,children:c.modal?e.jsx($u,{...l,ref:r}):e.jsx(Ku,{...l,ref:r})})});So.displayName=ir;var Mu=Rc("PopoverContent.RemoveScroll"),$u=o.forwardRef((t,r)=>{const s=Na(ir,t.__scopePopover),i=o.useRef(null),l=Fr(r,i),c=o.useRef(!1);return o.useEffect(()=>{const d=i.current;if(d)return Ac(d)},[]),e.jsx(Lc,{as:Mu,allowPinchZoom:!0,children:e.jsx(Co,{...t,ref:l,trapFocus:s.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:As(t.onCloseAutoFocus,d=>{var u;d.preventDefault(),c.current||(u=s.triggerRef.current)==null||u.focus()}),onPointerDownOutside:As(t.onPointerDownOutside,d=>{const u=d.detail.originalEvent,g=u.button===0&&u.ctrlKey===!0,f=u.button===2||g;c.current=f},{checkForDefaultPrevented:!1}),onFocusOutside:As(t.onFocusOutside,d=>d.preventDefault(),{checkForDefaultPrevented:!1})})})}),Ku=o.forwardRef((t,r)=>{const s=Na(ir,t.__scopePopover),i=o.useRef(!1),l=o.useRef(!1);return e.jsx(Co,{...t,ref:r,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:c=>{var d,u;(d=t.onCloseAutoFocus)==null||d.call(t,c),c.defaultPrevented||(i.current||(u=s.triggerRef.current)==null||u.focus(),c.preventDefault()),i.current=!1,l.current=!1},onInteractOutside:c=>{var g,f;(g=t.onInteractOutside)==null||g.call(t,c),c.defaultPrevented||(i.current=!0,
118c.detail.originalEvent.type==="pointerdown"&&(l.current=!0));const d=c.target;((f=s.triggerRef.current)==null?void 0:f.contains(d))&&c.preventDefault(),c.detail.originalEvent.type==="focusin"&&l.current&&c.preventDefault()}})}),Co=o.forwardRef((t,r)=>{const{__scopePopover:s,trapFocus:i,onOpenAutoFocus:l,onCloseAutoFocus:c,disableOutsidePointerEvents:d,onEscapeKeyDown:u,onPointerDownOutside:g,onFocusOutside:f,onInteractOutside:C,...F}=t,w=Na(ir,s),j=Tr(s);return Oc(),e.jsx(Dc,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:l,onUnmountAutoFocus:c,children:e.jsx(Ml,{asChild:!0,disableOutsidePointerEvents:d,onInteractOutside:C,onEscapeKeyDown:u,onPointerDownOutside:g,onFocusOutside:f,onDismiss:()=>w.onOpenChange(!1),children:e.jsx($l,{"data-state":Fo(w.open),role:"dialog",id:w.contentId,...j,...F,ref:r,style:{...F.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),ko="PopoverClose",Uu=o.forwardRef((t,r)=>{const{__scopePopover:s,...i}=t,l=Na(ko,s);return e.jsx(va.button,{type:"button",...i,ref:r,onClick:As(t.onClick,()=>l.onOpenChange(!1))})});Uu.displayName=ko;var _u="PopoverArrow",zu=o.forwardRef((t,r)=>{const{__scopePopover:s,...i}=t,l=Tr(s);return e.jsx(Kl,{...l,...i,ref:r})});zu.displayName=_u;function Fo(t){return t?"open":"closed"}var Vu=wo,qu=No,Hu=Eo,Po=So;const Ns=Vu,Es=qu,ys=o.forwardRef(({className:t,align:r="center",sideOffset:s=4,...i},l)=>e.jsx(Hu,{children:e.jsx(Po,{ref:l,align:r,sideOffset:s,className:Fs("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-popover-content-transform-origin]",t),...i})}));ys.displayName=Po.displayName;function Io({open:t,remainingAfterExport:r,onConfirm:s,onCancel:i}){return e.jsx(os,{open:t,onOpenChange:l=>{l||i()},children:e.jsxs(cs,{onInteractOutside:l=>l.preventDefault(),onEscapeKeyDown:l=>l.preventDefault(),className:"sm:max-w-md",children:[e.jsxs(as,{children:[e.jsxs(rs,{className:"flex items-center gap-2 text-amber-600",children:[e.jsx(ps,{className:"h-5 w-5"}),"Export Warning"]}),e.jsxs($s,{className:"text-sm text-muted-foreground pt-2 space-y-3",children:[e.jsxs("p",{children:["After this export you will only have"," ",e.jsx("span",{className:"font-bold text-foreground",children:r})," ","lead export",r!==1?"s":""," remaining before you need to upgrade."]}),e.jsx("p",{className:"text-red-500 dark:text-red-400 font-medium",children:"Once you reach 0 remaining, you will permanently have no more exports unless you upgrade to a paid plan."})]})]}),e.jsxs(er,{className:"flex-row gap-2 sm:gap-0",children:[e.jsx(N,{variant:"outline",onClick:i,children:"Cancel"}),e.jsx(N,{onClick:s,className:"bg-amber-600 hover:bg-amber-700 text-white",children:"Yes, Continue"})]})]})})}function Wu(){const t=new URL(window.location.href);t.searchParams.set("tab","integrations"),window.history.pushState(null,"",t.toString()),window.dispatchEvent(new PopStateEvent("popstate"))}function To({selectedIds:t,disabled:r,onSuccess:s}){const{toast:i}=Ss(),[l,c]=o.useState(!1),[d,u]=o.useState(new Set),{data:g}=Qe({queryKey:["/api/integrations"],retry:!1}),{data:f}=Qe({queryKey:["/api/integrations/providers"],retry:!1}),C=o.useMemo(()=>{const p=new Map;return((f==null?void 0:f.providers)||[]).forEach(v=>p.set(v.id,v)),p},[f]),F=o.useMemo(()=>((g==null?void 0:g.integrations)||[]).filter(v=>v.status==="connected").map(v=>{const y=C.get(v.provider),k=y?y.available:!0;return{integration:v,available:k,unavailableReason:(y==null?void 0:y.reason)||null}}),[g,C]),w=o.useMemo(()=>F.filter(p=>p.available).map(p=>p.integration),[F]),j=w.length>0,E=t.length,A=o.useMemo(()=>d.size===0?new Set(w.map(p=>p.id)):new Set(Array.from(d).filter(p=>w.some(v=>v.id===p))),[d,w]),T=Ne({mutationFn:async()=>{const p=Array.from(A);return(await ue("POST","/api/leads/push-to-crm",{selectedIds:t,integrationIds:p})).json()},onSuccess:p=>{const v=((p==null?void 0:p.perIntegration)||[]).reduce((k,a)=>k+(a.successCount||0),0),y=((p==null?void 0:p.perIntegration)||[]).reduce((k,a)=>k+(a.failureCount||0),0);v>0&&y===0?i({title:"Pushed to CRM",description:`${p.attemptedCount} lead${p.attemptedCount===1?"":"s"} pushed to ${p.perIntegration.length} integration${p.perIntegration.length===1?"":"s"}.`}):v>0&&y>
1180?i({title:"Partially pushed",description:`${v} succeeded, ${y} failed. Check integration logs.`,variant:"destructive"}):i({title:"Push failed",description:"No leads were successfully pushed. Check integration credentials.",variant:"destructive"}),z.invalidateQueries({queryKey:["/api/leads"]}),z.invalidateQueries({queryKey:["/api/lead-export-history"]}),z.invalidateQueries({queryKey:["/api/auth/user"]}),z.invalidateQueries({queryKey:["/api/me/temporary-credits"]}),c(!1),s==null||s()},onError:p=>{const v=(p==null?void 0:p.message)||"Failed to push leads to CRM";i({title:"Push to CRM failed",description:v,variant:"destructive"})}}),J=r||E===0;return e.jsxs(Ns,{open:l,onOpenChange:c,children:[e.jsx(Es,{asChild:!0,children:e.jsxs(N,{size:"sm",variant:j?"default":"secondary",disabled:J&&j,className:j?"text-xs bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-700 hover:to-teal-700 text-white border-0":"text-xs bg-gray-200 text-gray-500 hover:bg-gray-300 dark:bg-gray-800 dark:text-gray-400 border-0","data-testid":"button-push-to-crm",children:[e.jsx(Oi,{className:"h-3.5 w-3.5 mr-1"}),"Push to CRM",j&&E>0?` (${E.toLocaleString()})`:""]})}),e.jsx(ys,{align:"end",className:"w-72 p-3",children:j?e.jsxs("div",{className:"space-y-3","data-testid":"popover-push-crms",children:[e.jsxs("div",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:["Push ",E.toLocaleString()," lead",E===1?"":"s"," to:"]}),e.jsx("div",{className:"space-y-1 max-h-48 overflow-y-auto pr-1",children:F.map(({integration:p,available:v,unavailableReason:y})=>{const k=v&&A.has(p.id);return e.jsxs("label",{className:`flex items-center gap-2 px-2 py-1.5 rounded ${v?"hover:bg-gray-50 dark:hover:bg-gray-800 cursor-pointer":"opacity-50 cursor-not-allowed"}`,"data-testid":`row-integration-${p.id}`,title:v?void 0:y||"Coming soon",children:[e.jsx(Ws,{checked:k,disabled:!v,onCheckedChange:a=>{v&&u(q=>{const $=new Set(q);return $.size===0&&w.forEach(X=>$.add(X.id)),a?$.add(p.id):$.delete(p.id),$})}}),e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsxs("span",{className:"text-xs font-medium text-gray-800 dark:text-gray-100 truncate",children:[p.displayName||p.providerName||p.provider,!v&&e.jsx("span",{className:"ml-1 text-[10px] font-normal text-amber-600 dark:text-amber-400",children:"(coming soon)"})]}),e.jsx("span",{className:"text-[10px] text-gray-500 truncate",children:p.provider})]})]},p.id)})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1 border-t border-gray-100 dark:border-gray-800",children:[e.jsxs("span",{className:"text-[10px] text-gray-500",children:[A.size," CRM",A.size===1?"":"s"," selected"]}),e.jsx(N,{size:"sm",disabled:T.isPending||E===0||A.size===0,onClick:()=>T.mutate(),className:"h-7 text-xs bg-emerald-600 hover:bg-emerald-700 text-white","data-testid":"button-confirm-push",children:T.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ua,{className:"h-3 w-3 mr-1 animate-spin"}),"Pushingâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(Oi,{className:"h-3 w-3 mr-1"}),"Push ",E.toLocaleString()," lead",E===1?"":"s"]})})]})]}):e.jsxs("div",{className:"space-y-2 text-sm","data-testid":"popover-no-crms",children:[e.jsxs("div",{className:"flex items-start gap-2 text-gray-700 dark:text-gray-300",children:[e.jsx(tr,{className:"h-4 w-4 mt-0.5 text-amber-500 flex-shrink-0"}),e.jsx("p",{children:"No CRMs connected yet. Connect HubSpot, Salesforce, Zapier, or a webhook to push leads."})]}),e.jsxs("button",{type:"button",onClick:()=>{c(!1),Wu()},className:"inline-flex items-center gap-1 text-xs font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400 hover:underline","data-testid":"link-connect-crm",children:[e.jsx(aa,{className:"h-3 w-3"}),"Connect a CRM in Integrations"]})]})})]})}const Bu=Gl(["contains","starts","ends"]),Ju=Cd([fr(),Zl({v:fr(),m:Bu.optional()})]);Xl(Ju);function Sr(t){if(typeof t=="string")return{value:t,mode:"contains"};if(!t||typeof t!="object"||typeof t.v!="string")return{value:"",mode:"contains"};const r=t.m==="starts"||t.m==="ends"?t.m:"contains";return{value:t.v,mode:r}}function fa(t){return typeof t=="string"?t:t.v}function dn(t){return Sr(t).mode}function je(t){const{value:r,mode:s}=Sr(t);switch(s){case"starts":return`starts with "${r}"`;case"ends":return`ends with "${r}"`;default:return`contains "${r}"`}}function lr(t){const{value:r,mode:s}=Sr(t);switch(s){case"starts":return`${r}*`;case"ends":return`*${r}`;default:return r}}function ke(t){if(!t)return[];try{const r=JSON.parse(t);if(!Array.isArray(r))return[];const s=[];for(const i of r)if(typeof i=="string")s.push(i);else if(i&&typeof i=="object"&&typeof i.v=="string"){const l=i.m==="starts"||i.m==="ends"?i.m:void 0;s.push(l?{v:i.v,m:l}:{v:i.v})}return s}catch{return[]}}function ta(t,r){const s=Sr(t),i=Sr(r);return s.value===i.value&&s.mode===i.mode}const Yu=["ylprProfileName","ylprCategories","ylprDescription","ylprProfileUrl"],Qu=[{key:"ylprProfileName",label:"Company Name"},{key:"ylprCategories",label:"Categories"},{key:"ylprDescription",label:"Description"},{key:"ylprFeaturedReview",label:"Review Snippet"},{key:"ylprProfileUrl",label:"Profile URL"},{key:"ylprAddressStreet",label:"Street"},{key:"ylprAddressCity",label:"City"},{key:"ylprAddressState",label:"State"},{key:"ylprAddressZip",label:"Zip"},{key:"ylprPhone",label:"Phone"}],qr={nameKeywordListIds:[],categoriesKeywordListIds:[],descriptionKeywordListIds:[],reviewSnippetKeywordListIds:[],profileUrlKeywordListIds:[],nameIncludeTerms:[],nameExcludeTerms:[],categoriesIncludeTerms:[],categoriesExcludeTerms:[],descriptionIncludeTerms:[],descriptionExcludeTerms:[],reviewSnippetIncludeTerms:[],reviewSnippetExcludeTerms:[],profileUrlIncludeTerms:[],profileUrlExcludeTerms:[],stateInclude:[],stateExclude:[],cityInclude:[],cityExclude:[],zipInclude:[],zipExclude:[],streetInclude:[],streetExclude:[],phoneInclude:[],phoneExclude:[],streetEmptyFilter:"any",cityEmptyFilter:"any",stateEmptyFilter:"any",zipEmptyFilter:"any",de
118scriptionEmptyFilter:"any",minStars:"",maxStars:"",minReviewCount:"",maxReviewCount:"",search:"",sortBy:"lastUpdated",sortOrder:"desc",lastUpdatedFrom:"",lastUpdatedTo:"",timeScrapedFrom:"",timeScrapedTo:"",orColumns:Yu,updateReasonFilter:[]};function Ds(t){if(!t)return[];try{const r=JSON.parse(t);return Array.isArray(r)?r:[]}catch{return[]}}function Hr(t){var i,l,c;const r=new URLSearchParams;t.nameKeywordListIds.length>0&&r.set("nkl",t.nameKeywordListIds.join(",")),t.categoriesKeywordListIds.length>0&&r.set("ckl",t.categoriesKeywordListIds.join(",")),(((i=t.descriptionKeywordListIds)==null?void 0:i.length)??0)>0&&r.set("dkl",t.descriptionKeywordListIds.join(",")),t.reviewSnippetKeywordListIds.length>0&&r.set("rskl",t.reviewSnippetKeywordListIds.join(",")),t.profileUrlKeywordListIds.length>0&&r.set("pukl",t.profileUrlKeywordListIds.join(",")),t.stateInclude.length>0&&r.set("si",t.stateInclude.join(",")),t.stateExclude.length>0&&r.set("se",t.stateExclude.join(",")),t.cityInclude.length>0&&r.set("ci",JSON.stringify(t.cityInclude)),t.cityExclude.length>0&&r.set("ce",JSON.stringify(t.cityExclude)),t.zipInclude.length>0&&r.set("zi",JSON.stringify(t.zipInclude)),t.zipExclude.length>0&&r.set("ze",JSON.stringify(t.zipExclude)),t.streetInclude.length>0&&r.set("sti",JSON.stringify(t.streetInclude)),t.streetExclude.length>0&&r.set("ste",JSON.stringify(t.streetExclude)),t.phoneInclude.length>0&&r.set("pi",JSON.stringify(t.phoneInclude)),t.phoneExclude.length>0&&r.set("pe",JSON.stringify(t.phoneExclude)),t.streetEmptyFilter!=="any"&&r.set("stef",t.streetEmptyFilter==="only_empty"?"1":"0"),t.cityEmptyFilter!=="any"&&r.set("cief",t.cityEmptyFilter==="only_empty"?"1":"0"),t.stateEmptyFilter!=="any"&&r.set("sef",t.stateEmptyFilter==="only_empty"?"1":"0"),t.zipEmptyFilter!=="any"&&r.set("zief",t.zipEmptyFilter==="only_empty"?"1":"0"),t.nameIncludeTerms.length>0&&r.set("ni",JSON.stringify(t.nameIncludeTerms)),t.nameExcludeTerms.length>0&&r.set("ne",JSON.stringify(t.nameExcludeTerms)),t.categoriesIncludeTerms.length>0&&r.set("cti",JSON.stringify(t.categoriesIncludeTerms)),t.categoriesExcludeTerms.length>0&&r.set("cte",JSON.stringify(t.categoriesExcludeTerms)),(((l=t.descriptionIncludeTerms)==null?void 0:l.length)??0)>0&&r.set("di",JSON.stringify(t.descriptionIncludeTerms)),(((c=t.descriptionExcludeTerms)==null?void 0:c.length)??0)>0&&r.set("de",JSON.stringify(t.descriptionExcludeTerms)),(t.descriptionEmptyFilter??"any")!=="any"&&r.set("def",t.descriptionEmptyFilter==="only_empty"?"1":"0"),t.reviewSnippetIncludeTerms.length>0&&r.set("rsi",JSON.stringify(t.reviewSnippetIncludeTerms)),t.reviewSnippetExcludeTerms.length>0&&r.set("rse",JSON.stringify(t.reviewSnippetExcludeTerms)),t.profileUrlIncludeTerms.length>0&&r.set("pui",JSON.stringify(t.profileUrlIncludeTerms)),t.profileUrlExcludeTerms.length>0&&r.set("pue",JSON.stringify(t.profileUrlExcludeTerms)),t.minStars&&r.set("ms",t.minStars),t.maxStars&&r.set("xs",t.maxStars),t.minReviewCount&&r.set("mr",t.minReviewCount),t.maxReviewCount&&r.set("xr",t.maxReviewCount),t.search&&r.set("q",t.search),t.sortBy&&t.sortBy!=="lastUpdated"&&r.set("sb",t.sortBy),t.sortOrder==="asc"&&r.set("so","asc"),t.lastUpdatedFrom&&r.set("luf",t.lastUpdatedFrom),t.lastUpdatedTo&&r.set("lut",t.lastUpdatedTo),t.timeScrapedFrom&&r.set("tsf",t.timeScrapedFrom),t.timeScrapedTo&&r.set("tst",t.timeScrapedTo),r.set("orc",t.orColumns.join(",")),t.updateReasonFilter.length>0&&r.set("urf",t.updateReasonFilter.join(","));const s=r.toString();return s?`#${s}`:""}function Gu(t,r){if(!t||t.length<=1)return[];const s=new URLSearchParams(t.substring(1)),i=new Set(r.map(d=>d.id)),l=["nkl","ckl","dkl","rskl","pukl","kl"],c=new Set;for(const d of l){const u=s.get(d);if(u)for(const g of u.split(",")){const f=Number(g);!isNaN(f)&&!i.has(f)&&c.add(f)}}return Array.from(c)}function Rn(t,r){if(!t||t.length<=1)return{};const s=new URLSearchParams(t.substring(1)),i={},l=new Set(r.map(B=>B.id)),c=B=>{if(!B)return;const K=B.split(",").map(Number).filter(ae=>!isNaN(ae)).filter(ae=>l.has(ae));return K.length>0?K:void 0},d=c(s.get("nkl"));d&&(i.nameKeywordListIds=d);const u=c(s.get("ckl"));u&&(i.categoriesKeywordListIds=u);const g=c(s.get("dkl"));g&&(i.descriptionKeywordListIds=g);const f=c(s.get("rskl"));f&&(i.reviewSnippetKeywordListIds=f);const C=c(s.get("pukl"));C&&(i.profileUrlKeywordListIds=C);const F=s.get("kl");if(F&&!d&&!u){const B=F.split(",").map(Number).filter(K=>!isNaN(K)).filter(K=>l.has(K));B.length>0&&(i.nameKeywordListIds=B,i.categoriesKeywordListIds=B)}const w=s.get("si");
118w&&(i.stateInclude=w.split(",").filter(Boolean));const j=s.get("se");j&&(i.stateExclude=j.split(",").filter(Boolean)),i.cityInclude=Ds(s.get("ci")),i.cityExclude=Ds(s.get("ce")),i.zipInclude=Ds(s.get("zi")),i.zipExclude=Ds(s.get("ze")),i.streetInclude=Ds(s.get("sti")),i.streetExclude=Ds(s.get("ste")),i.phoneInclude=ke(s.get("pi")),i.phoneExclude=ke(s.get("pe"));const E=B=>{if(B==="1")return"only_empty";if(B==="0")return"exclude_empty"},A=E(s.get("stef"));A&&(i.streetEmptyFilter=A);const T=E(s.get("cief"));T&&(i.cityEmptyFilter=T);const J=E(s.get("sef"));J&&(i.stateEmptyFilter=J);const p=E(s.get("zief"));p&&(i.zipEmptyFilter=p),i.nameIncludeTerms=Ds(s.get("ni")),i.nameExcludeTerms=Ds(s.get("ne")),i.categoriesIncludeTerms=Ds(s.get("cti")),i.categoriesExcludeTerms=Ds(s.get("cte")),i.descriptionIncludeTerms=Ds(s.get("di")),i.descriptionExcludeTerms=Ds(s.get("de"));const v=E(s.get("def"));v&&(i.descriptionEmptyFilter=v),i.reviewSnippetIncludeTerms=Ds(s.get("rsi")),i.reviewSnippetExcludeTerms=Ds(s.get("rse")),i.profileUrlIncludeTerms=Ds(s.get("pui")),i.profileUrlExcludeTerms=Ds(s.get("pue")),s.get("ms")&&(i.minStars=s.get("ms")),s.get("xs")&&(i.maxStars=s.get("xs")),s.get("mr")&&(i.minReviewCount=s.get("mr")),s.get("xr")&&(i.maxReviewCount=s.get("xr")),s.get("q")&&(i.search=s.get("q")),s.get("sb")&&(i.sortBy=s.get("sb")),s.get("so")==="asc"&&(i.sortOrder="asc");const y=s.get("luf");y&&(i.lastUpdatedFrom=y);const k=s.get("lut");k&&(i.lastUpdatedTo=k);const a=s.get("tsf");a&&(i.timeScrapedFrom=a);const q=s.get("tst");q&&(i.timeScrapedTo=q);const $=s.get("orc");if($){const B=new Set(Qu.map(ae=>ae.key)),K=$.split(",").filter(ae=>B.has(ae));K.length>0&&(i.orColumns=K)}const X=s.get("urf");return X&&(i.updateReasonFilter=X.split(",").filter(Boolean)),i}const al=["AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"],Zu=ju,Xu=["ylprProfileName","ylprStars","ylprReviewCount","ylprCategories","ylprAddressCity","ylprAddressState","ylprAddressZip","ylprPhone","ylprTimeScraped","lastUpdated"];function rl(t){const r=new Date(t),s=r.getUTCFullYear(),i=String(r.getUTCMonth()+1).padStart(2,"0"),l=String(r.getUTCDate()).padStart(2,"0"),c=String(r.getUTCHours()).padStart(2,"0"),d=String(r.getUTCMinutes()).padStart(2,"0"),u=String(r.getUTCSeconds()).padStart(2,"0");return`${s}-${i}-${l} ${c}:${d}:${u}`}function nl(t){const r=[];let s="",i=!1;for(let c=0;c<t.length;c++){const d=t[c];if(!(d==="["||d==="]")){if(d==="'"){i=!i;continue}if(d===","&&!i){const u=s.trim();u&&r.push(u),s="";continue}s+=d}}const l=s.trim();return l&&r.push(l),r}const ep={ylprDescription:"descriptionEmptyFilter",ylprAddressStreet:"streetEmptyFilter",ylprAddressCity:"cityEmptyFilter",ylprAddressState:"stateEmptyFilter",ylprAddressZip:"zipEmptyFilter"};function tp({value:t,onChange:r,label:s}){const i=[{value:"any",label:"Any"},{value:"only_empty",label:"Only empty"},{value:"exclude_empty",label:"Non-empty"}];return e.jsxs("div",{className:"border-t pt-2 space-y-1.5",children:[e.jsx("label",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300",children:s}),e.jsx("div",{className:"grid grid-cols-3 gap-1",children:i.map(l=>e.jsx("button",{type:"button",onClick:()=>r(l.value),className:`text-[10px] px-1 py-1 rounded border transition-colors ${t===l.value?"bg-blue-600 text-white border-blue-600":"bg-transparent border-gray-300 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-800"}`,children:l.label},l.value))})]})}function Ao(t,r){const s={ylprProfileName:new Set(t.nameKeywordListIds),ylprCategories:new Set(t.categoriesKeywordListIds),ylprDescription:new Set(t.descriptionKeywordListIds??[]),ylprFeaturedReview:new Set(t.reviewSnippetKeywordListIds),ylprProfileUrl:new Set(t.profileUrlKeywordListIds)},i=t.orColumns.filter(v=>v in s),l=new Set(t.orColumns),c=Array.from(new Set(t.nameKeywordListIds.concat(t.categoriesKeywordListIds,t.descriptionKeywordListIds??[],t.reviewSnippetKeywordListIds,t.profileUrlKeywordListIds))),d=[],u=[],g=[...t.nameIncludeTerms],f=[...t.nameExcludeTerms],C=[...t.categoriesIncludeTerms],F=[...t.categoriesExcludeTerms],w=[...t.descriptionIncludeTerms??[]],j=[...t.descriptionExcludeTerms??[]],E=[...t.reviewSnippetIncludeTerms],A=[...t.reviewSnippetExcludeTerms],T=[...t.profileUrlIncludeTerms],J=[...t.profileUrlExcludeTerms],p=(v,y,k)=>{v==="ylprProfileName"?k==="positive"?g.push(...y):f.push(...y):v==="ylprCategories"?k==="positive"?C.push(...y):F.push(...y):v==="ylprDescription"?k==="positive"?w.push(...y):j.push(...y):v==="ylprFeaturedReview"?k==="positive"?E.push(...y):A.push(...y):v==="ylprProfileUrl"&&(k==="positive"?T.push(...y):J.push(...y))};for(const v of r){if(!c.includes(v.id))continue;const y=Array.isArray(v.keywords)?v.keywords:[];if(i.length>0&&i.every(a=>s[a].has(v.id))){v.type==="positive"?d.push(...y):u.push(...y);for(const[a,q]of Object.entries(s))!l.has(a)&&q.has(v.id)&&p(a,y,v.type)}else for(const[a,q]of Object.entries(s))q.has(v.id)&&p(a,y,v.type)}return{positiveKeywords:d,negativeKeywords:u,nameInclude:g,nameExclude:f,catInclude:C,catExclude:F,descriptionInclude:w,descriptionExclude:j,reviewSnippetInclude:E,reviewSnippetExclude:A,profileUrlInclude:T,profileUrlExclude:J}}function sp(t,r,s,i){const l=new URLSearchParams;l.set("page",String(r)),l.set("limit",String(s));const c=Array.from(new Set(t.nameKeywordListIds.concat(t.categoriesKeywordListIds,t.descriptionKeywordListIds??[],t.reviewSnippetKeywordListIds,t.profileUrlKeywordListIds)));c.length>0&&l.set("keywordListIds",c.join(","));const d=Ao(t,i);return d.positiveKeywords.length>0&&l.set("positiveKeywords",JSON.stringify(d.positiveKeywords)),d.negativeKeywords.length>0&&l.set("negativeKeywords",JSON.stringify(d.negativeKeywords)),d.nameInclude.length>0&&l.set("nameIncludeTerms",JSON.stringify(d.nameInclude)),d.nameExclude.length>0&&l.set("nameExcludeTerms",JSON.stringify(d.nameExclude)),d.catInclude.length>0&&l.set("categoriesIncludeTerms",JSON.stringify(d.catInclude)),d.catExclude.length>0&&l.set("categoriesExcludeTerms",JSON.stringify(d.catExclude)),d.descriptionInclude.length>0&&l.set("descriptionIncludeTerms",JSON.stringify(d.descriptionInclude)),d.descriptionExclude.length>0&&l.set("descriptionExcludeTerms",JSON.stringify(d.descriptionExclude)),d.reviewSnippetInclude.length>0&&l.set("reviewSnippetIncludeTerms",JSON.stringify(d.reviewSnippetInclude)),d.reviewSnippetExclude.length>0&&l.set("reviewSnippetExcludeTerms",JSON.stringify(d.reviewSnippetExclude)),d.profileUrlInclude.length>0&&l.set("profileUrlIncludeTerms",JSON.stringify(d.profileUrlInclude)),d.profileUrlExclude.length>0&&l.set("profileUrlExcludeTerms",JSON.stringify(d.profileUrlExclude)),t.stateInclude.length>0&&l.set("stateInclude",t.stateInclude.join(",")),t.stateExclude.length>0&&l.set("stateExclude",t.stateExclude.join(",")),t.cityInclude.length>0&&l.set("cityInclude",JSON.stringify(t.cityInclude)),t.cityExclude.length>0&&l.set("cityExclude",JSON.stringify(t.cityExclude)),t.zipInclude.length>0&&l.set("zipInclude",JSON.stringify(t.zipInclude)),t.zipExclude.length>0&&l.set("zipExclude",JSON.stringify(t.zipExclude)),t.streetInclude.length>0&&l.set("streetInclude",JSON.stringify(t.streetInclude)),t.streetExclude.length>0&&l.set("streetExclude",JSON.stringify(t.streetExclude)),t.phoneInclude.length>0&&l.set("phoneInclude",JSON.stringify(t.phoneInclude)),t.phoneExclude.length>
1180&&l.set("phoneExclude",JSON.stringify(t.phoneExclude)),t.streetEmptyFilter!=="any"&&l.set("streetEmptyFilter",t.streetEmptyFilter),t.cityEmptyFilter!=="any"&&l.set("cityEmptyFilter",t.cityEmptyFilter),t.stateEmptyFilter!=="any"&&l.set("stateEmptyFilter",t.stateEmptyFilter),t.zipEmptyFilter!=="any"&&l.set("zipEmptyFilter",t.zipEmptyFilter),(t.descriptionEmptyFilter??"any")!=="any"&&l.set("descriptionEmptyFilter",t.descriptionEmptyFilter),t.minStars&&l.set("minStars",t.minStars),t.maxStars&&l.set("maxStars",t.maxStars),t.minReviewCount&&l.set("minReviewCount",t.minReviewCount),t.maxReviewCount&&l.set("maxReviewCount",t.maxReviewCount),t.search&&l.set("search",t.search),t.sortBy&&t.sortBy!=="lastUpdated"&&l.set("sortBy",t.sortBy),t.sortOrder==="asc"&&l.set("sortOrder","asc"),t.lastUpdatedFrom&&l.set("lastUpdatedFrom",t.lastUpdatedFrom),t.lastUpdatedTo&&l.set("lastUpdatedTo",t.lastUpdatedTo),t.timeScrapedFrom&&l.set("timeScrapedFrom",t.timeScrapedFrom),t.timeScrapedTo&&l.set("timeScrapedTo",t.timeScrapedTo),l.set("orColumns",t.orColumns.join(",")),t.updateReasonFilter.length>0&&l.set("updateReasonFilter",t.updateReasonFilter.join(",")),l.toString()}function il(t){const r=t.match(/^rel:(\d+)([hdwmy])$/);if(!r)return t;const s=r[1],l={h:"hour",d:"day",w:"week",m:"month",y:"year"}[r[2]]||r[2];return`Last ${s} ${l}${parseInt(s)!==1?"s":""}`}function ap(t){if(!t)return null;const r=parseFloat(t);if(isNaN(r))return t;const s=Math.floor(r),i=r%1>=.3;return e.jsxs("span",{className:"flex items-center gap-0.5",children:[Array.from({length:5},(l,c)=>e.jsx(Mc,{className:`h-3.5 w-3.5 ${c<s?"fill-yellow-400 text-yellow-400":c===s&&i?"fill-yellow-400/50 text-yellow-400":"text-gray-300"}`},c)),e.jsx("span",{className:"ml-1 text-sm text-gray-700",children:r})]})}function rp({options:t,selected:r,onApply:s}){const[i,l]=o.useState(!1),[c,d]=o.useState(r),u=r.length>0,g=f=>{d(C=>C.includes(f)?C.filter(F=>F!==f):[...C,f])};return e.jsxs(Ns,{open:i,onOpenChange:f=>{l(f),f&&d(r)},children:[e.jsx(Es,{asChild:!0,children:e.jsx("button",{className:`ml-1 p-0.5 rounded transition-colors ${u?"text-blue-600":"text-gray-400 hover:text-gray-600"}`,children:e.jsx(Ls,{className:"h-3 w-3"})})}),e.jsxs(ys,{className:"w-52 p-3",align:"start",children:[e.jsx("div",{className:"text-xs font-medium mb-2",children:"Filter by Update Reason"}),e.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(f=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer text-xs",children:[e.jsx(Ws,{checked:c.includes(f),onCheckedChange:()=>g(f)}),f]},f))}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx("button",{className:"flex-1 text-xs px-2 py-1 rounded bg-blue-600 text-white hover:bg-blue-700",onClick:()=>{s(c),l(!1)},children:"Apply"}),e.jsx("button",{className:"flex-1 text-xs px-2 py-1 rounded border hover:bg-gray-50 dark:hover:bg-gray-800",onClick:()=>{s([]),d([]),l(!1)},children:"Clear"})]})]})]})}function pr({column:t,label:r,filters:s,onApply:i,orColumns:l,columnKey:c}){const[d,u]=o.useState(!1),g=o.useCallback(()=>{switch(t){case"ylprAddressState":return{include:[...s.stateInclude],exclude:[...s.stateExclude]};case"ylprAddressCity":return{include:[...s.cityInclude],exclude:[...s.cityExclude]};case"ylprAddressZip":return{include:[...s.zipInclude],exclude:[...s.zipExclude]};case"ylprAddressStreet":return{include:[...s.streetInclude],exclude:[...s.streetExclude]};case"ylprPhone":return{include:[...s.phoneInclude],exclude:[...s.phoneExclude]};default:return{include:[],exclude:[]}}},[t,s]),f=ep[t],C=f?s[f]:"any",[F,w]=o.useState(C),[j,E]=o.useState(g),[A,T]=o.useState(""),[J,p]=o.useState(""),[v,y]=o.useState(""),[k,a]=o.use
118State(""),[q,$]=o.useState(l.includes(c)),X=t==="ylprPhone",[B,K]=o.useState("contains"),[ae,Y]=o.useState("contains"),fe=ee=>ee.replace(/\*/g,"").length,U=(ee,O)=>X&&O!=="contains"?{v:ee,m:O}:ee,te=(ee,O)=>ee.some(I=>ta(I,O)),ne=t==="ylprAddressState";o.useEffect(()=>{d&&(E(g()),T(""),p(""),y(""),a(""),K("contains"),Y("contains"),$(l.includes(c)),f&&w(s[f]))},[d,g]);const Q=f?s[f]!=="any":!1,V=(()=>{switch(t){case"ylprAddressState":return s.stateInclude.length>0||s.stateExclude.length>0||Q;case"ylprAddressCity":return s.cityInclude.length>0||s.cityExclude.length>0||Q;case"ylprAddressZip":return s.zipInclude.length>0||s.zipExclude.length>0||Q;case"ylprAddressStreet":return s.streetInclude.length>0||s.streetExclude.length>0||Q;case"ylprPhone":return s.phoneInclude.length>0||s.phoneExclude.length>0||Q;default:return!1}})(),R=ee=>{const O=ee.trim();if(!O){T("");return}if(!ne&&fe(O)<3){y("Include terms must be at least 3 characters (excluding *)");return}y("");const I=U(O,B);te(j.include,I)||E(re=>({...re,include:[...re.include,I]})),T("")},pe=ee=>{const O=ee.trim();if(!O){p("");return}if(!ne&&fe(O)<2){a("Exclude terms must be at least 2 characters (excluding *)");return}a("");const I=U(O,ae);te(j.exclude,I)||E(re=>({...re,exclude:[...re.exclude,I]})),p("")},Se=ee=>{E(O=>({...O,include:O.include.filter(I=>!ta(I,ee))}))},Ze=ee=>{E(O=>
118({...O,exclude:O.exclude.filter(I=>!ta(I,ee))}))},Me=()=>{let ee=[...j.include],O=[...j.exclude];const I=A.trim();if(I&&!ne){if(fe(I)<3){y("Include terms must be at least 3 characters (excluding *)");return}const W=U(I,B);ee.some(Le=>ta(Le,W))||ee.push(W)}const re=J.trim();if(re&&!ne){if(fe(re)<2){a("Exclude terms must be at least 2 characters (excluding *)");return}const W=U(re,ae);O.some(Le=>ta(Le,W))||O.push(W)}const Pe=X?[]:ee,tt=X?[]:O,$e={};switch(t){case"ylprAddressState":$e.stateInclude=Pe,$e.stateExclude=tt;break;case"ylprAddressCity":$e.cityInclude=Pe,$e.cityExclude=tt;break;case"ylprAddressZip":$e.zipInclude=Pe,$e.zipExclude=tt;break;case"ylprAddressStreet":$e.streetInclude=Pe,$e.streetExclude=tt;break;case"ylprPhone":$e.phoneInclude=ee,$e.phoneExclude=O;break}f&&($e[f]=F),q&&!l.includes(c)?$e.orColumns=[...l,c]:!q&&l.includes(c)&&($e.orColumns=l.filter(W=>W!==c)),i($e),u(!1)},He=()=>{E({include:[],exclude:[]}),$(!1),w("any")};return e.jsxs(Ns,{open:d,onOpenChange:u,children:[e.jsx(Es,{asChild:!0,children:e.jsx("button",{className:`ml-1 p-0.5 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors ${V?"text-blue-600":"text-gray-400 opacity-50"}`,children:e.jsx(Ls,{className:"h-3 w-3"})})}),e.jsx(ys,{className:"w-72 p-3",align:"start",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx("input",{type:"checkbox",id:`or-group-${c}`,checked:q,onChange:ee=>$(ee.target.checked),className:"rounded border-gray-300"}),e.jsx("label",{htmlFor:`or-group-${c}`,className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:"Include in OR group search"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-semibold text-blue-700 flex items-center gap-1",children:[e.jsx(ns,{className:"h-3 w-3"})," Include ",r]}),ne?e.jsxs(Ns,{children:[e.jsx(Es,{asChild:!0,children:e.jsxs("button",{type:"button",className:"h-7 w-full text-xs flex items-center justify-between rounded-md border border-input bg-transparent px-2 hover:bg-accent hover:text-accent-foreground",children:[e.jsx("span",{className:j.include.length===0?"text-muted-foreground":"",children:"Add state to include..."}),e.jsx(sr,{className:"h-3 w-3 opacity-50"})]})}),e.jsx(ys,{className:"w-56 p-0",align:"start",children:e.jsx("div",{className:"max-h-60 overflow-y-auto py-1",children:al.map(ee=>{const O=j.include.includes(ee);return e.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1.5 text-xs text-left hover:bg-accent hover:text-accent-foreground",onClick:()=>{E(O?I=>({...I,include:I.include.filter(re=>re!==ee)}):I=>({...I,include:[...I.include,ee]}))},children:[e.jsx(sa,{className:`h-3 w-3 ${O?"opacity-100":"opacity-0"}`}),e.jsx("span",{children:ee})]},ee)})})})]}):e.jsxs("div",{className:"flex gap-1",children:[X&&e.jsxs("select",{value:B,onChange:ee=>K(ee.target.value),className:"h-7 text-xs rounded-md border border-input bg-transparent px-1","aria-label":"Include match mode","data-testid":`select-include-mode-${c}`,children:[e.jsx("option",{value:"contains",children:"contains"}),e.jsx("option",{value:"starts",children:"starts with"}),e.jsx("option",{value:"ends",children:"ends with"})]}),e.jsx(Ee,{placeholder:`Add ${r.toLowerCase()}...`,value:A,onChange:ee=>{T(ee.target.value),y("")},onKeyDown:ee=>{ee.key==="Enter"&&(ee.preventDefault(),R(A))},className:"h-7 text-xs flex-1"}),e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>R(A),children:e.jsx(ns,{className:"h-3 w-3"})})]}),j.include.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:j.include.map(ee=>{const O=`${fa(ee)}|${dn(ee)}`;return e.jsxs(ie,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-blue-100 text-blue-800 hover:bg-blue-200 cursor-pointer",onClick:()=>Se(ee),title:je(ee),children:[X?lr(ee):fa(ee)," ",e.jsx(Ut,{className:"h-2.5 w-2.5 ml-0.5"})]},O)})}),v&&e.jsx("p",{className:"text-[10px] text-red-500",children:v})]}),e.jsxs("div",{className:"border-t pt-2 space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-semibold text-red-700 flex items-center gap-1",children:[e.jsx(wn,{className:"h-3 w-3"})," Exclude ",r]}),ne?e.jsxs(Ns,{children:[e.jsx(Es,{asChild:!0,children:e.jsxs("button",{type:"button",className:"h-7 w-full text-xs flex items-center justify-between rounded-md border border-input bg-transparent px-2 hover:bg-accent hover:text-accent-foreground",children:[e.jsx("span",{className:j.exclude.length===0?"text-muted-foreground":"",children:"Add state to exclude..."}),e.jsx(sr,{className:"h-3 w-3 opacity-50"})]})}),e.jsx(ys,{className:"w-56 p-0",align:"start",children:e.jsx("div",{className:"max-h-60 overflow-y-auto py-1",children:al.map(ee=>{const O=j.exclude.includes(ee);return e.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1.5 text-xs text-left hover:bg-accent hover:text-accent-foreground",onClick:()=>{E(O?I=>
118({...I,exclude:I.exclude.filter(re=>re!==ee)}):I=>({...I,exclude:[...I.exclude,ee]}))},children:[e.jsx(sa,{className:`h-3 w-3 ${O?"opacity-100":"opacity-0"}`}),e.jsx("span",{children:ee})]},ee)})})})]}):e.jsxs("div",{className:"flex gap-1",children:[X&&e.jsxs("select",{value:ae,onChange:ee=>Y(ee.target.value),className:"h-7 text-xs rounded-md border border-input bg-transparent px-1","aria-label":"Exclude match mode","data-testid":`select-exclude-mode-${c}`,children:[e.jsx("option",{value:"contains",children:"contains"}),e.jsx("option",{value:"starts",children:"starts with"}),e.jsx("option",{value:"ends",children:"ends with"})]}),e.jsx(Ee,{placeholder:`Add ${r.toLowerCase()} to exclude...`,value:J,onChange:ee=>{p(ee.target.value),a("")},onKeyDown:ee=>{ee.key==="Enter"&&(ee.preventDefault(),pe(J))},className:"h-7 text-xs flex-1"}),e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>pe(J),children:e.jsx(ns,{className:"h-3 w-3"})})]}),j.exclude.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:j.exclude.map(ee=>{const O=`${fa(ee)}|${dn(ee)}`;return e.jsxs(ie,{variant:"destructive",className:"text-[10px] px-1.5 py-0 cursor-pointer",onClick:()=>Ze(ee),title:je(ee),children:[X?lr(ee):fa(ee)," ",e.jsx(Ut,{className:"h-2.5 w-2.5 ml-0.5"})]},O)})}),k&&e.jsx("p",{className:"text-[10px] text-red-500",children:k})]}),f&&e.jsx(tp,{value:F,onChange:w,label:`${r} content`}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t",children:[e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 text-xs text-gray-500",onClick:He,children:"Clear"}),e.jsx(N,{size:"sm",className:"h-7 text-xs bg-blue-600 hover:bg-blue-700 text-white",onClick:Me,children:"Apply"})]})]})})]})}function ll({column:t,label:r,filters:s,onApply:i}){const[l,c]=o.useState(!1),d=o.useCallback(()=>{switch(t){case"ylprStars":return{min:s.minStars,max:s.maxStars};case"ylprReviewCount":return{min:s.minReviewCount,max:s.maxReviewCount};default:return{min:"",max:""}}},[t,s]),[u,g]=o.useState(d);o.useEffect(()=>{l&&g(d())},[l,d]);const f=(()=>{switch(t){case"ylprStars":return!!s.minStars||!!s.maxStars;case"ylprReviewCount":return!!s.minReviewCount||!!s.maxReviewCount;default:return!1}})(),C=()=>{const w={};switch(t){case"ylprStars":w.minStars=u.min,w.maxStars=u.max;break;case"ylprReviewCount":w.minReviewCount=u.min,w.maxReviewCount=u.max;break}i(w),c(!1)},F=t==="ylprStars";return e.jsxs(Ns,{open:l,onOpenChange:c,children:[e.jsx(Es,{asChild:!0,children:e.jsx("button",{className:`ml-1 p-0.5 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors ${f?"text-blue-600":"text-gray-400 opacity-50"}`,children:e.jsx(Ls,{className:"h-3 w-3"})})}),e.jsx(ys,{className:"w-56 p-3",align:"start",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-xs font-medium",children:[r," Range"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ee,{type:"number",min:"0",max:F?"5":void 0,step:F?"0.1":"1",placeholder:"Min",value:u.min,onChange:w=>g(j=>({...j,min:w.target.value})),className:"h-8 text-xs w-20"}),e.jsx("span",{className:"text-xs text-gray-400",children:"to"}),e.jsx(Ee,{type:"number",min:"0",max:F?"5":void 0,step:F?"0.1":"1",placeholder:"Max",value:u.max,onChange:w=>g(j=>({...j,max:w.target.value})),className:"h-8 text-xs w-20"})]}),e.jsxs("div",{className:"flex items-center justify-between pt-1",children:[e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 text-xs text-gray-500",onClick:()=>{g({min:"",max:""})},children:"Clear"}),e.jsx(N,{size:"sm",className:"h-7 text-xs bg-blue-600 hover:bg-blue-700 text-white",onClick:C,children:"Apply"})]})]})})]})}function xr({column:t,label:r,filters:s,keywordLists:i,onApply:l,orColumns:c,columnKey:d}){const[u,g]=o.useState(!1),f=o.useMemo(()=>i.filter(U=>U.type==="positive"),[i]),C=o.useMemo(()=>i.filter(U=>U.type==="negative"),[i]),F=o.useCallback(()=>{let U=[],te=[],ne=[];switch(t){case"ylprProfileName":U=[...s.nameIncludeTerms],te=[...s.nameExcludeTerms],ne=[...s.nameKeywordListIds];break;case"ylprCategories":U=[...s.categoriesIncludeTerms],te=[...s.categoriesExcludeTerms],ne=[...s.categoriesKeywordListIds];break;case"ylprDescription":U=[...s.descriptionIncludeTerms??[]],te=[...s.descriptionExcludeTerms??[]],ne=[...s.descriptionKeywordListIds??[]];break;case"ylprFeaturedReview":U=[...s.reviewSnippetIncludeTerms],te=[...s.reviewSnippetExcludeTerms],ne=[...s.reviewSnippetKeywordListIds];break;case"ylprProfileUrl":U=[...s.profileUrlIncludeTerms],te=[...s.profileUrlExcludeTerms],ne=[...s.profileUrlKeywordListIds];break}return{activeListIds:ne,includeTerms:U,excludeTerms:te}},[t,s]),[w,j]=o.useState(F),[E,A]=o.useState(""),[T,J]=o.useState(""),[p,v]=o.useState(""),[y,k]=o.useState(""),[a,q]=o.useState(c.includes(d)),$=U=>U.replace(/\*/g,"").length;o.useEffect(()=>{u&&(j(F()),A(""),J(""),v(""),k(""),q(c.includes(d)))},[u,F]);const X=(()=>{var U,te,ne;switch(t){case"ylprProfileName":return s.nameKeywordListIds.length>0||s.nameIncludeTerms.length>0||s.nameExcludeTerms.length>0;case"ylprCategories":return s.categoriesKeywordListIds.length>0||s.categoriesIncludeTerms.length>0||s.categoriesExcludeTerms.length>0;case"ylprDescription":return(((U=s.descriptionKeywordListIds)==null?void 0:U.length)??0)>0||(((te=s.descriptionIncludeTerms)==null?void 0:te.length)??0)>0||(((ne=s.descriptionExcludeTerms)==null?void 0:ne.length)??0)>0;case"ylprFeaturedReview":return s.reviewSnippetKeywordListIds.length>0||s.reviewSnippetIncludeTerms.length>0||s.reviewSnippetExcludeTerms.length>0;case"ylprProfileUrl":return s.profileUrlKeywordListIds.length>0||s.profileUrlIncludeTerms.length>0||s.profileUrlExcludeTerms.length>0;default:return!1}})(),B=U=>{j(te=>{const ne=te.activeListIds.includes(U);return{...te,activeListIds:ne?te.activeListIds.filter(Q=>Q!==U):[...te.activeListIds,U]}})},K=U=>{const te=U.trim();if(!te){A("");return}if($(te)<3){v("Include terms must be at least 3 characters (excluding *)");return}v(""),w.includeTerms.includes(te)||j(ne=>({...ne,includeTerms:[...ne.includeTerms,te]})),A("")},ae=U=>{const te=U.trim();if(!te){J("");return}if($(te)<2){k("Exclude terms must be at least 2 characters (excluding *)");return}k(""),w.excludeTerms.includes(te)||j(ne=>({...ne,excludeTerms:[...ne.excludeTerms,te]})),J("")},Y=()=>{let U=[...w.includeTerms],te=[...w.excludeTerms];const ne=E.trim();if(ne){if($(ne)<3){v("Include terms must be at least 3 characters (excluding *)");return}U.includes(ne)||U.push(ne)}const Q=T.trim();if(Q){if($(Q)<2){k("Exclude terms must be at least 2 characters (excluding *)");return}te.includes(Q)||te.push(Q)}const V={};switch(t){case"ylprProfileName":V.nameKeywordListIds=w.activeListIds,V.nameIncludeTerms=U,V.nameExcludeTerms=te;break;case"ylprCategories":V.categoriesKeywordListIds=w.activeListIds,V.categoriesIncludeTerms=U,V.categoriesExcludeTerms=te;break;case"ylprDescription":V.descriptionKeywordListIds=w.activeListIds,V.descriptionIncludeTerms=U,V.descriptionExcludeTerms=te;break;case"ylprFeaturedReview":V.reviewSnippetKeywordListIds=w.activeListIds,V.reviewSnippetIncludeTerms=U,V.reviewSnippetExcludeTerms=te;break;case"ylprProfileUrl":V.profileUrlKeywordListIds=w.activeListIds,V.profileUrlIncludeTerms=U,V.profileUrlExcludeTerms=te;break}a&&!c.includes(d)?V.orColumns=[...c,d]:!a&&c.includes(d)&&(V.orColumns=c.filter(R=>R!==d)),l(V),g(!1)},fe=()=>{j({activeListIds:[],includeTerms:[],excludeTerms:[]}),q(!1)};return e.jsxs(Ns,{open:u,onOpenChange:g,children:[e.jsx(Es,{asChild:!0,children:e.jsx("button",{className:`ml-1 p-0.5 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors ${X?"text-blue-600":"text-gray-400 opacity-50"}`,children:e.jsx(Ls,{className:"h-3 w-3"})})}),e.jsx(ys,{className:"w-80 p-0",align:"start",children:e.jsxs("div",{className:"space-y-3 max-h-[60vh] overflow-y-auto p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx("input",{type:"checkbox",id:`or-group-${d}`,checked:a,onChange:U=>q(U.target.checked),className:"rounded border-gray-300"}),e.jsx("label",{htmlFor:`or-group-${d}`,className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:"Include in OR group search"})]}),f.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-semibold text-blue-700 flex items-center gap-1",children:[e.jsx(Kt,{className:"h-3 w-3"})," Positive Keyword Lists"]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:f.map(U=>e.jsxs(ie,{variant:w.activeListIds.includes(U.id)?"default":"outline",className:`curs
118or-pointer text-[10px] px-1.5 py-0.5 ${w.activeListIds.includes(U.id)?"bg-blue-600 hover:bg-blue-700":""}`,onClick:()=>B(U.id),children:["+ ",U.name,U.isDefault&&e.jsx("span",{className:"ml-0.5 opacity-60",children:"(default)"})]},U.id))})]}),C.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-semibold text-red-700 flex items-center gap-1",children:[e.jsx(Kt,{className:"h-3 w-3"})," Negative Keyword Lists"]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:C.map(U=>e.jsxs(ie,{variant:w.activeListIds.includes(U.id)?"destructive":"outline",className:"cursor-pointer text-[10px] px-1.5 py-0.5",onClick:()=>B(U.id),children:["- ",U.name,U.isDefault&&e.jsx("span",{className:"ml-0.5 opacity-60",children:"(default)"})]},U.id))})]}),e.jsxs("div",{className:"border-t pt-2 space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-semibold text-blue-700 flex items-center gap-1",children:[e.jsx(ns,{className:"h-3 w-3"})," Include Search Terms"]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(Ee,{placeholder:`Add term to include in ${r}...`,value:E,onChange:U=>{A(U.target.value),v("")},onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),K(E))},className:"h-7 text-xs flex-1"}),e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>K(E),children:e.jsx(ns,{className:"h-3 w-3"})})]}),w.includeTerms.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:w.includeTerms.map(U=>e.jsxs(ie,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-blue-100 text-blue-800 hover:bg-blue-200 cursor-pointer",onClick:()=>j(te=>({...te,includeTerms:te.includeTerms.filter(ne=>ne!==U)})),children:[U," ",e.jsx(Ut,{className:"h-2.5 w-2.5 ml-0.5"})]},U))}),p&&e.jsx("p",{className:"text-[10px] text-red-500",children:p})]}),e.jsxs("div",{className:"border-t pt-2 space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-semibold text-red-700 flex items-center gap-1",children:[e.jsx(wn,{className:"h-3 w-3"})," Exclude Search Terms"]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(Ee,{placeholder:`Add term to exclude from ${r}...`,value:T,onChange:U=>{J(U.target.value),k("")},onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),ae(T))},className:"h-7 text-xs flex-1"}),e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>ae(T),children:e.jsx(ns,{className:"h-3 w-3"})})]}),w.excludeTerms.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:w.excludeTerms.map(U=>e.jsxs(ie,{variant:"destructive",className:"text-[10px] px-1.5 py-0 cursor-pointer",onClick:()=>j(te=>({...te,excludeTerms:te.excludeTerms.filter(ne=>ne!==U)})),children:[U," ",e.jsx(Ut,{className:"h-2.5 w-2.5 ml-0.5"})]},U))}),y&&e.jsx("p",{className:"text-[10px] text-red-500",children:y})]}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t",children:[e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 text-xs text-gray-500",onClick:fe,children:"Clear All"}),e.jsx(N,{size:"sm",className:"h-7 text-xs bg-blue-600 hover:bg-blue-700 text-white",onClick:Y,children:"Apply"})]})]})})]})}function ol({column:t,label:r,filters:s,onApply:i}){const[l,c]=o.useState(!1),d=o.useCallback(()=>t==="lastUpdated"?{from:s.lastUpdatedFrom,to:s.lastUpdatedTo}:{from:s.timeScrapedFrom,to:s.timeScrapedTo},[t,s]),u=v=>{const y=v.match(/^rel:(\d+)([hdwmy])$/);return y?{amount:y[1],unit:y[2]}:{amount:"7",unit:"d"}},g=d(),f=g.from.startsWith("rel:"),[C,F]=o.useState(f?"relative":"range"),[w,j]=o.useState(g),[E,A]=o.useState(u(f?g.from:"rel:7d"));o.useEffect(()=>{if(l){const v=d(),y=v.from.startsWith("rel:");F(y?"relative":"range"),j(v),A(u(y?v.from:"rel:7d"))}},[l,d]);const T=t==="lastUpdated"?!!s.lastUpdatedFrom||!!s.lastUpdatedTo:!!s.timeScrapedFrom||!!s.timeScrapedTo,J=()=>{const v={};if(C==="relative"){const y=`rel:${E.amount}${E.unit}`;t==="lastUpdated"?(v.lastUpdatedFrom=y,v.lastUpdatedTo=""):(v.timeScrapedFrom=y,v.timeScrapedTo="")}else t==="lastUpdated"?(v.lastUpdatedFrom=w.from,v.lastUpdatedTo=w.to):(v.timeScrapedFrom=w.from,v.timeScrapedTo=w.to);i(v),c(!1)},p=t==="lastUpdated"?[{value:"h",label:"Hours"},{value:"d",label:"Days"},{value:"w",label:"Weeks"},{value:"m",label:"Months"},{value:"y",label:"Years"}]:[{value:"d",label:"Days"},{value:"w",label:"Weeks"},{value:"m",label:"Months"},{value:"y",label:"Years"}];return e.jsxs(Ns,{open:l,onOpenChange:c,children:[e.jsx(Es,{asChild:!0,children:e.jsx("button",{className:`ml-1 p-0.5 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors ${T?"text-blue-600":"text-gray-400 opacity-50"}`,children:e.jsx(La,{className:"h-3 w-3"})})}),e.jsx(ys,{className:"w-72 p-3",align:"start",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-xs font-medium",children:[r," Filter"]}),e.jsxs("div",{className:"flex gap-1 border rounded p-0.5",children:[e.jsx("button",{className:`flex-1 text-xs py-1 rounded transition-colors ${C==="range"?"bg-blue-100 dar
118k:bg-blue-900 text-blue-700 dark:text-blue-300 font-medium":"text-gray-500 hover:text-gray-700"}`,onClick:()=>F("range"),children:"Date Range"}),e.jsx("button",{className:`flex-1 text-xs py-1 rounded transition-colors ${C==="relative"?"bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 font-medium":"text-gray-500 hover:text-gray-700"}`,onClick:()=>F("relative"),children:"Relative"})]}),C==="range"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-gray-500 w-10",children:"From"}),e.jsx("input",{type:"date",value:w.from.startsWith("rel:")?"":w.from,onChange:v=>j(y=>({...y,from:v.target.value})),className:"h-8 text-xs border rounded px-2 flex-1 bg-white dark:bg-gray-800 dark:border-gray-600"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-gray-500 w-10",children:"To"}),e.jsx("input",{type:"date",value:w.to,onChange:v=>j(y=>({...y,to:v.target.value})),className:"h-8 text-xs border rounded px-2 flex-1 bg-white dark:bg-gray-800 dark:border-gray-600"})]})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-gray-500",children:"Last"}),e.jsx("input",{type:"number",min:"1",max:"999",value:E.amount,onChange:v=>A(y=>({...y,amount:v.target.value})),className:"h-8 text-xs border rounded px-2 w-16 bg-white dark:bg-gray-800 dark:border-gray-600"}),e.jsx("select",{value:E.unit,onChange:v=>A(y=>({...y,unit:v.target.value})),className:"h-8 text-xs border rounded px-2 flex-1 bg-white dark:bg-gray-800 dark:border-gray-600",children:p.map(v=>e.jsx("option",{value:v.value,children:v.label},v.value))})]}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t",children:[e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 text-xs text-gray-500",onClick:()=>{j({from:"",to:""}),A({amount:"7",unit:"d"})},children:"Clear All"}),e.jsx(N,{size:"sm",className:"h-7 text-xs bg-blue-600 hover:bg-blue-700 text-white",onClick:J,children:"Apply"})]})]})})]})}const On=250;function np(){const t=o.useMemo(()=>({waveDuration:3+Math.random()*2,initialDelay:Math.random()*5}),[]),r=t.waveDuration/On;return e.jsx("div",{className:"or-col-overlay",children:Array.from({length:On},(s,i)=>e.jsx("div",{className:"or-col-bar",style:{animationName:"or-col-bar",animationDuration:`${t.waveDuration}s`,animationTimingFunction:"ease-in-out",animationIterationCount:"infinite",animationDelay:`-${t.initialDelay+(On-1-i)*r}s`}},i))})}function Zs({columnKey:t,isActive:r,className:s,children:i}){return e.jsxs(Ke,{className:`${s||""} relative select-none transition-colors ${r?"bg-gradient-to-b from-blue-50/80 to-purple-50/60 dark:from-blue-950/40 dark:to-purple-950/30":""}`,style:r?{borderLeft:"1px solid rgba(96,165,250,0.35)",borderRight:"1px solid rgba(167,139,250,0.35)"}:void 0,children:[r&&e.jsx(np,{}),e.jsx("div",{className:"relative z-[2] whitespace-nowrap",children:r?e.jsx("div",{className:"bg-white/90 dark:bg-gray-950/90 rounded-sm px-1 py-0.5 inline-block",children:i}):i})]})}function cl({isSubscribed:t,subscriptionPlan:r,userId:s,freeLeadsUsed:i=0,monthlyCredits:l=0,monthlyCreditsUsed:c=0,permanentCredits:d=0,isVisible:u=!0,onOpenGenerateDialog:g,keywordGenerationJobs:f,onboardingCategoryFilter:C,onSwitchDatabase:F}){var _s,hs,us,Ms;const w=["pro"].includes(r||""),j=["starter","growth","scale","platinum","enterprise"].includes(r||""),E=!w,{toast:A}=Ss(),{user:T}=Pr(),J=ja();Xn();const[p,v]=o.useState(1),[y,k]=o.useState(1e3),[a,q]=o.useState({...qr}),[$,X]=o.useState(new Set),[B,K]=o.useState(!1),[ae,Y]=o.useState(!1),fe=o.useRef(!1),U=o.useRef(""),[te,ne]=o.useState(""),[Q,V]=o.useState(null),[R,pe]=o.useState(!1),[Se,Ze]=o.useState(""),[Me,He]=o.useState(!1),[ee,O]=o.useState(!1),[I,re]=o.useState(void 0),[Pe,tt]=o.useState(void 0),[$e,W]=o.useState(null),[Le,ve]=o.useState(""),[Oe,vt]=o.useState(!1),Rt=o.useRef(null),At=o.useRef(null),{data:at}=Qe({queryKey:["/api/leads/export-freshness"],refetchInterval:3e4,enabled:E&&!!s,queryFn:async()=>{const n=await fetch("/api/leads/export-freshness",{credentials:"include"});if(!n.ok)throw new Error("Failed");return n.json()}});o.useEffect(()=>{if(!at)return;const n=at.lastExportTs;if(At.current===null){At.current=n;return}n!==At.current&&(At.current=n,z.invalidateQueries({queryKey:["/api/leads"]}))},[at]);const{data:Je=[],isFetched:Te}=Qe({queryKey:["/api/keyword-lists"]}),{data:Ct=[]}
118=Qe({queryKey:["/api/filter-presets"]}),lt=Ct.filter(n=>n.databaseType==="home_improvement"),kt=Ne({mutationFn:async n=>(await ue("POST","/api/filter-presets",n)).json(),onSuccess:()=>{z.invalidateQueries({queryKey:["/api/filter-presets"]}),pe(!1),Ze(""),A({title:"Filter preset saved"})},onError:n=>{ce("HomeImprovementLeadsTable","Failed to save preset",n),A({title:"Failed to save preset",variant:"destructive"})}}),ft=Ne({mutationFn:async n=>{await ue("DELETE",`/api/filter-presets/${n}`)},onSuccess:()=>{z.invalidateQueries({queryKey:["/api/filter-presets"]}),A({title:"Preset deleted"})},onError:n=>{ce("HomeImprovementLeadsTable","Failed to delete preset",n),A({title:"Failed to delete preset",variant:"destructive"})}}),qt=o.useMemo(()=>Je.filter(n=>n.type==="positive"),[Je]),et=o.useMemo(()=>Je.filter(n=>n.type==="negative"),[Je]),Ot=o.useCallback(n=>{const b=n.filter(h=>h.isDefault);return b.length===0?"":b.sort((h,L)=>h.id-L.id).map(h=>`${h.id}:${(Array.isArray(h.keywords)?h.keywords:[]).join(",")}`).join("|")},[]);o.useEffect(()=>{if(ae||!Te)return;const n=window.location.hash;if(n&&n.length>1){const L=Gu(n,Je);L.length>0&&A({title:"Some keyword lists not found",description:`${L.length} keyword list${L.length>1?"s":""} referenced in the URL ${L.length>1?"no longer exist":"no longer exists"} and ${L.length>1?"were":"was"} removed from the filters.`,variant:"destructive"});const _=Rn(n,Je);if(_.nameKeywordListIds&&_.nameKeywordListIds.length>0||_.categoriesKeywordListIds&&_.categoriesKeywordListIds.length>0||_.descriptionKeywordListIds&&_.descriptionKeywordListIds.length>0||_.reviewSnippetKeywordListIds&&_.reviewSnippetKeywordListIds.length>0||_.profileUrlKeywordListIds&&_.profileUrlKeywordListIds.length>0||_.nameIncludeTerms&&_.nameIncludeTerms.length>0||_.categoriesIncludeTerms&&_.categoriesIncludeTerms.length>0||_.descriptionIncludeTerms&&_.descriptionIncludeTerms.length>0||_.reviewSnippetIncludeTerms&&_.reviewSnippetIncludeTerms.length>0||_.profileUrlIncludeTerms&&_.profileUrlIncludeTerms.length>0){const We={...qr,..._};q(We),ne(We.search||""),fe.current=!1,Y(!0);return}}const b=qt.filter(L=>L.isDefault),h=et.filter(L=>L.isDefault);if(b.length>0||h.length>0){const L=[];for(const _ of b)L.push(_.id);for(const _ of h)L.push(_.id);q(_=>({..._,nameKeywordListIds:L,categoriesKeywordListIds:L,descriptionKeywordListIds:L,profileUrlKeywordListIds:L}))}else C&&C.length>0&&q(L=>({...L,categoriesIncludeTerms:C}));fe.current=!0,U.current=Ot(Je),Y(!0)},[Je,Te,qt,et,ae,C,Ot,A]),o.useEffect(()=>{if(!ae||!fe.current||Je.length===0)return;const n=Ot(Je);if(n&&n!==U.current){U.current=n;const b=qt.filter(_=>_.isDefault),h=et.filter(_=>_.isDefault),L=[];for(const _ of b)L.push(_.id);for(const _ of h)L.push(_.id);q(_=>({..._,nameKeywordListIds:L,categoriesKeywordListIds:L,descriptionKeywordListIds:L,profileUrlKeywordListIds:L})),v(1)}},[Je,qt,et,ae,Ot]);const Xe=o.useRef("");o.useEffect(()=>{if(!ae)return;const n=C?JSON.stringify(C.slice().sort()):"";n&&n!==Xe.current&&(Xe.current=n,!(qt.some(h=>h.isDefault)||et.some(h=>h.isDefault))&&C&&(q(h=>({...h,categoriesIncludeTerms:C})),v(1)))},[ae,C,qt,et]),o.useEffect(()=>{if(!ae||!Te)return;const n=new Set(Je.map(L=>L.id)),b=["nameKeywordListIds","categoriesKeywordListIds","descriptionKeywordListIds","reviewSnippetKeywordListIds","profileUrlKeywordListIds"];let h=!1;for(const L of b)if((a[L]??[]).some(_=>!n.has(_))){h=!0;break}h&&q(L=>{const _={...L};for(const G of b)_[G]=(L[G]??[]).filter(We=>n.has(We));return _})},[Je,Te,ae]),o.useEffect(()=>{if(!ae||!u)return;const n=Hr(a),b=window.location.hash;if(n!==b){const h=window.location.pathname+window.location.search+n;window.history.replaceState(null,"",h)}},[a,ae,u]);const mt=a.nameIncludeTerms.length>0||a.categoriesIncludeTerms.length>0||(((_s=a.descriptionIncludeTerms)==null?void 0:_s.length)??0)>0||a.reviewSnippetIncludeTerms.length>0||a.profileUrlIncludeTerms.length>0||Array.from(new Set(a.nameKeywordListIds.concat(a.categoriesKeywordListIds,a.descriptionKeywordListIds??[],a.reviewSnippetKeywordListIds,a.profileUrlKeywordListIds))).some(n=>{const b=Je.find(h=>h.id===n);return(b==null?void 0:b.type)==="positive"&&Array.isArray(b.keywords)&&b.keywords.length>0}),ut=o.useRef(Je),ot=o.useMemo(()=>new Set([...a.nameKeywordListIds,...a.categoriesKeywordListIds,...a.descriptionKeywordListIds??[],...a.reviewSnippetKeywordListIds,...a.profileUrlKeywordListIds]),[a.nameKeywordListIds,a.categoriesKeywordListIds,a.descriptionKeywordListIds,a.reviewSnippetKeywordListIds,a.profileUrlKeywordListIds]),St=o.useMemo(()=>Je.some(n=>ot.has(n.id)&&n.refinementStatus==="running"),[Je,ot]),Pt=o.useMemo(()=>((!St||ut.current.length===0)&&(ut.current=Je),ut.current),[Je,St]),it=o.useMemo(()=>mt?sp(a,p,y,Pt):null,[a,p,y,mt,Pt]),ze=o.useRef(void 0),_t=o.useRef(!1);o.useEffect(()=>{ze.current===void 0?it!==null&&(ze.current=it):it!==null&&it!==ze.current&&(_t.current=!0)},[it]);const{data:de,isLoading:gt,isFetching:It,isError:Ge,refetch:Ce}=Qe({queryKey:["/api/leads",it],queryFn:async({signal:n})=>{if(!it)return{leads:[],pagination:{page:1,limit:100,total:0,pages:0},requiresKeywords:!0};const b=_t.current?"&refresh=true":"",h=await fetch(`/api/leads?${it}${b}`,{credentials:"include",signal:n});if(!h.ok)throw new Error("Failed to fetch leads");return h.json()},enabled:ae&&mt,retry:1,retryDelay:2e3}),P=((hs=de==null?void 0:de.pagination)==null?void 0:hs.total)!=null?{total:de.pagination.total}:void 0,le=It,De=Ne({mutationFn:async n=>{const b=n==null?void 0:n.selectedIds,h=n==null?void 0:n.maxLeads,L={eventId:`export-${Date.now()}`};if(b&&b.length>0)L.selectedIds=b;else{const G=Ao(a,Je),We=Array.from(new Set(a.nameKeywordListIds.concat(a.categoriesKeywordListIds,a.descriptionKeywordListIds??[],a.reviewSnippetKeywordListIds,a.profileUrlKeywordListIds)));L.filters={keywordListIds:We.length>0?We.join(","):void 0,positiveKeywords:G.positiveKeywords.length>0?G.positiveKeywords:void 0,negativeKeywords:G.negativeKeywords.length>0?G.negativeKeywords:void 0,nameIncludeTerms:G.nameInclude.length>0?G.nameInclude:void 0,nameExcludeTerms:G.nameExclude.length>0?G.nameExclude:void 0,categoriesIncludeTerms:G.catInclude.length>0?G.catInclude:void 0,categoriesExcludeTerms:G.catExclude.length>0?G.catExclude:void 0,descriptionIncludeTerms:G.descriptionInclude.length>0?G.descriptionInclude:void 0,descriptionExcludeTerms:G.descriptionExclude.length>0?G.descriptionExclude:void 0,descriptionEmptyFilter:(a.descriptionEmptyFilter??"any")!=="any"?a.descriptionEmptyFilter:void 0,reviewSnippetIncludeTerms:G.reviewSnippetInclude.length>0?G.reviewSnippetInclude:void 0,reviewSnippetExcludeTerms:G.reviewSnippetExclude.length>0?G.reviewSnippetExclude:void 0,profileUrlIncludeTerms:G.profileUrlInclude.length>0?G.profileUrlInclude:void 0,profileUrlExcludeTerms:G.profileUrlExclude.length>0?G.profileUrlExclude:void 0,stateInclude:a.stateInclude.length>0?a.stateInclude.join(","):void 0,stateExclude:a.stateExclude.length>0?a.stateExclude.join(","):void 0,cityInclude:a.cityInclude.length>0?a.cityInclude:void 0,cityExclude:a.cityExclude.length>0?a.cityExclude:void 0,zipInclude:a.zipInclude.length>0?a.zipInclude:void 0,zipExclude:a.zipExclude.length>0?a.zipExclude:void 0,streetInclude:a.streetInclude.length>0?a.streetInclude:void 0,streetExclude:a.streetExclude.length>0?a.streetExclude:void 0,phoneInclude:a.phoneInclude.length>0?a.phoneInclude:void 0,phoneExclude:a.phoneExclude.length>0?a.phoneExclude:void 0,streetEmptyFilter:a.streetEmptyFilter!=="any"?a.streetEmptyFilter:void 0,cityEmptyFilter:a.cityEmptyFilter!=="any"?a.cityEmptyFilter:void 0,stateEmptyFilter:a.stateEmptyFilter!=="any"?a.stateEmptyFilter:void 0,zipEmptyFilter:a.zipEmptyFilter!=="any"?a.zipEmptyFilter:void 0,minStars:a.minStars||void 0,maxStars:a.maxStars||void 0,minReviewCount:a.minReviewCount||void 0,maxReviewCount:a.maxReviewCount||void 0,sortBy:a.sortBy,sortOrder:a.sortOrder,lastUpdatedFrom:a.lastUpdatedFrom||void 0,lastUpdatedTo:a.lastUpdatedTo||void 0,timeScrapedFrom:a.timeScrapedFrom||void 0,timeScrapedTo:a.timeScrapedTo||void 0},h&&h>0&&(L.maxLeads=h)}return(await ue("POST","/api/leads/export",L)).json()},onSuccess:n=>{if(n.leads&&n.leads.length>0){const b=st(n.leads),h=new Blob([b],{type:"text/csv"}),L=URL.createObjectURL(h),_=document.createElement("a");_.href=L,_.download=`leads-home-improvement-${new Date().toISOString().split("T")[0]}.csv`,_.click(),URL.revokeObjectURL(L);const G=!w&&n.remaining!==void 0&&n.remaining>=0?` (${n.remaining} exports remaining)`:"";A({title:"Export Complete",description:`Exported ${n.leads.length} leads.${G}`}),Ul(n,T,"home_improvement"),z.invalidateQueries({queryKey:["/api/leads"]}),z.invalidateQueries({queryKey:["/api/auth/user"]}),z.invalidateQueries({queryKey:["/api/me/temporary-credits"]}),X(new Set),W(null),ve("")}else ce("HomeImprovementLeadsTable","No leads to export"),A({title:"No Leads",description:"No leads to export.",variant:"destructive"})},onError:n=>{ce("HomeImprovementLeadsTable","Export failed",n),A({title:"Export Failed",description:"Could not export leads.",variant:"destructive"})}}),st=n=>fo(n,Zu),Ft=o.useCallback(n=>{q(b=>({...b,sortBy:n,sortOrder:b.sortBy===n&&b.sortOrder==="desc"?"asc":"desc"})),K(!1),X(new Set),v(1)},[]),oe=o.useCallback(n=>{fe.current=!1,q(b=>({...b,...n})),K(!1),X(new Set),v(1)},[]),Ye=o.useCallback(()=>{q(n=>({...n,search:te})),K(!1),X(new Set),v(1)}
118,[te]),pt=j?Math.max(0,l-c)+Math.max(0,d):0,jt=j?pt:((us=de==null?void 0:de.exportLimits)==null?void 0:us.remaining)??(t?-1:Math.max(0,20-i)),ye=w?1/0:Math.max(0,jt);o.useEffect(()=>{($.size>0||B)&&$e!==null&&W(null)},[$,B,$e]),o.useEffect(()=>{W(null),ve("")},[a]);const Xt=o.useCallback(()=>{if(!(de!=null&&de.leads))return;if(B){K(!1),X(new Set);return}const n=de.leads.map(h=>h.id);if(n.every(h=>$.has(h))||$.size>0&&!w)K(!1),X(new Set);else if(w)K(!0),X(new Set(n));else{const h=Math.min(n.length,ye);X(new Set(n.slice(0,h)))}},[de,$,w,ye,B]),rt=o.useRef(null),fs=o.useCallback((n,b)=>{B&&K(!1);const h=(de==null?void 0:de.leads)||[],L=$.has(n);if(b&&rt.current&&h.length>0){const _=h.findIndex(We=>We.id===rt.current.id),G=h.findIndex(We=>We.id===n);if(_!==-1&&G!==-1){const We=Math.min(_,G),gs=Math.max(_,G),ts=h.slice(We,gs+1).map(nt=>nt.id),Zt=!L;X(nt=>{const ss=new Set(nt);for(const x of ts)if(Zt){if(!w&&ss.size>=ye)break;ss.add(x)}else ss.delete(x);return ss}),rt.current={id:n,wasSelected:Zt};return}}X(_=>{const G=new Set(_);if(G.has(n))G.delete(n);else{if(!w&&G.size>=ye)return _;G.add(n)}return G}),rt.current={id:n,wasSelected:!L}},[w,ye,B,de,$]),Tt=j?"Export to reveal contact details (1 credit per lead)":"Export to get the phone number â phone numbers are not hidden for paid users",yt=(de==null?void 0:de.leads)||[],is=(P==null?void 0:P.total)??((Ms=de==null?void 0:de.pagination)==null?void 0:Ms.total)??null,Dt=is!==null,Ae=de!=null&&de.pagination?{...de.pagination,total:Dt?is:0,pages:Dt?Math.ceil(is/de.pagination.limit):yt.length>=de.pagination.limit?p+1:p}:void 0,bt=B||yt.length>0&&yt.every(n=>$.has(n.id)),Nt=!B&&$.size===0&&!!$e&&$e>0,ls=o.useCallback(()=>{const n=parseInt(Le,10);if(!Number.isFinite(n)||n<=0){W(null);return}let b=n;if(!w&&ye!==1/0&&b>ye&&(b=ye,ve(String(b)),A({title:"Adjusted to your remaining allowance",description:`You can export up to ${ye.toLocaleString()} leads right now.`})),b<=0){W(null),A({title:"No exports remaining",description:"You have no export allowance left.",variant:"destructive"});return}X(new Set),K(!1),W(b)},[Le,w,ye,A]),es=o.useCallback(()=>{vt(!0),Rt.current&&clearTimeout(Rt.current),Rt.current=setTimeout(()=>vt(!1),700)},[]);o.useEffect(()=>()=>{Rt.current&&clearTimeout(Rt.current)},[]);const Rs=o.useCallback(()=>{const n=parseInt(Le,10);!w&&ye!==1/0&&Number.isFinite(n)&&n>ye&&(es(),ls())},[Le,w,ye,es,ls]),bs=o.useCallback(()=>{const n=B||Nt?void 0:Array.from($),b=Nt?$e:void 0;if(!w&&jt>=0){const h=B?(Ae==null?void 0:Ae.total)??0:Nt?$e:$.size,L=jt-h;if(L<=20&&L>=0){re(n),tt(b),O(!0);return}}De.mutate({selectedIds:n,maxLeads:b})},[B,Nt,$e,$,w,jt,Ae,De]),Ps=o.useMemo(()=>{var h,L;const n=[];a.stateInclude.length>0&&n.push({label:`State: ${a.stateInclude.join(", ")}`,filterKey:"stateInclude",resetValue:[]}),a.stateExclude.length>0&&n.push({label:`Not State: ${a.stateExclude.join(", ")}`,filterKey:"stateExclude",resetValue:[]}),a.cityInclude.length>0&&n.push({label:`City: ${a.cityInclude.join(", ")}`,filterKey:"cityInclude",resetValue:[]}),a.cityExclude.length>0&&n.push({label:`Not City: ${a.cityExclude.join(", ")}`,filterKey:"cityExclude",resetValue:[]}),a.zipInclude.length>0&&n.push({label:`Zip: ${a.zipInclude.join(", ")}`,filterKey:"zipInclude",resetValue:[]}),a.zipExclude.length>0&&n.push({label:`Not Zip: ${a.zipExclude.join(", ")}`,filterKey:"zipExclude",resetValue:[]}),(a.minStars||a.maxStars)&&n.push({label:`Stars: ${a.minStars||"0"}-${a.maxStars||"5"}`,filterKey:"minStars",resetValue:"__stars__"}),(a.minReviewCount||a.maxReviewCount)&&n.push({label:`Reviews: ${a.minReviewCount||"0"}-${a.maxReviewCount||"â"}`,filterKey:"minReviewCount",resetValue:"__reviews__"}),a.search&&n.push({label:`Search: "${a.search}"`,filterKey:"search",resetValue:""}),a.streetInclude.length>0&&n.push({label:`Street: ${a.streetInclude.join(", ")}`,filterKey:"streetInclude",resetValue:[]}),a.streetExclude.length>0&&n.push({label:`Not Street: ${a.streetExclude.join(", ")}`,filterKey:"streetExclude",resetValue:[]}),a.phoneInclude.length>0&&n.push({label:`Phone: ${a.phoneInclude.map(_=>lr(_)).join(", ")}`,filterKey:"phoneInclude",resetValue:[]}),a.phoneExclude.length>0&&n.push({label:`Not Phone: ${a.phoneExclude.map(_=>lr(_)).join(", ")}`,filterKey:"phoneExclude",resetValue:[]});const b=_=>_==="only_empty"?"only empty":"non-empty";if(a.streetEmptyFilter!=="any"&&n.push({label:`Street: ${b(a.streetEmptyFilter)}`,filterKey:"streetEmptyFilter",resetValue:"any"}),a.cityEmptyFilter!=="any"&&n.push({label:`City: ${b(a.cityEmptyFilter)}`,filterKey:"cityEmptyFilter",resetValue:"any"}),a.stateEmptyFilter!=="any"&&n.push({label:`State: ${b(a.stateEmptyFilter)}`,filterKey:"stateEmptyFilter",resetValue:"any"}),a.zipEmptyFilter!=="any"&&n.push({label:`Zip: ${b(a.zipEmptyFilter)}`,filterKey:"zipEmptyFilter",resetValue:"any"}),a.nameIncludeTerms.length>0&&n.push({label:`Name includes: ${a.nameIncludeTerms.join(", ")}`,filterKey:"nameIncludeTerms",resetValue:[]}),a.nameExcludeTerms.length>0&&n.push({label:`Name excludes: ${a.nameExcludeTerms.join(", ")}`,filterKey:"nameExcludeTerms",resetValue:[]}),a.categoriesIncludeTerms.length>0&&n.push({label:`Categories includes: ${a.categoriesIncludeTerms.map(_=>`*${_.trim().replace(/\s+/g,"*")}*`).join(", ")}`,filterKey:"categoriesIncludeTerms",resetValue:[]}),a.categoriesExcludeTerms.length>0&&n.push({label:`Categories excludes: ${a.categoriesExcludeTerms.join(", ")}`,filterKey:"categoriesExcludeTerms",resetValue:[]}),a.reviewSnippetIncludeTerms.length>0&&n.push({label:`Review includes: ${a.reviewSnippetIncludeTerms.join(", ")}`,filterKey:"reviewSnippetIncludeTerms",resetValue:[]}),a.reviewSnippetExcludeTerms.length>0&&n.push({label:`Review excludes: ${a.reviewSnippetExcludeTerms.join(", ")}`,filterKey:"reviewSnippetExcludeTerms",resetValue:[]}),a.profileUrlIncludeTerms.length>0&&n.push({label:`Profile URL includes: ${a.profileUrlIncludeTerms.join(", ")}`,filterKey:"profileUrlIncludeTerms",resetValue:[]}),a.profileUrlExcludeTerms.length>0&&n.push({label:`Profile URL excludes: ${a.profileUrlExcludeTerms.join(", ")}`,filterKey:"profileUrlExcludeTerms",resetValue:[]}),a.lastUpdatedFrom||a.lastUpdatedTo){const _=(h=a.lastUpdatedFrom)!=null&&h.startsWith("rel:")?il(a.lastUpdatedFrom):`${a.lastUpdatedFrom||"â"} â ${a.lastUpdatedTo||"â"}`;n.push({label:`Updated: ${_}`,filterKey:"lastUpdatedFrom",resetValue:"__lastUpdated__"})}if(a.timeScrapedFrom||a.timeScrapedTo){const _=(L=a.timeScrapedFrom)!=null&&L.startsWith("rel:")?il(a.timeScrapedFrom):`${a.timeScrapedFrom||"â"} â ${a.timeScrapedTo||"â"}`;n.push({label:`Scraped: ${_}`,filterKey:"timeScrapedFrom",resetValue:"__timeScraped__"})}return a.updateReasonFilter.length>0&&n.push({label:`Update Reason: ${a.updateReasonFilter.join(", ")}`,filterKey:"updateReasonFilter",resetValue:[]}),n},[a]),ms={name:"Company Name",categories:"Categories",description:"Description",reviewSnippet:"Review Snippet",profileUrl:"Profile URL"},Bt=o.useMemo(()=>{const n=[],b=Array.from(new Set(a.nameKeywordListIds.concat(a.categoriesKeywordListIds,a.descriptionKeywordListIds??[],a.reviewSnippetKeywordListIds,a.profileUrlKeywordListIds)));for(const h of Je.filter(L=>
118b.includes(L.id)))a.nameKeywordListIds.includes(h.id)&&n.push({id:h.id,name:h.name,type:h.type,isDefault:h.isDefault,scope:"name"}),a.categoriesKeywordListIds.includes(h.id)&&n.push({id:h.id,name:h.name,type:h.type,isDefault:h.isDefault,scope:"categories"}),(a.descriptionKeywordListIds??[]).includes(h.id)&&n.push({id:h.id,name:h.name,type:h.type,isDefault:h.isDefault,scope:"description"}),a.reviewSnippetKeywordListIds.includes(h.id)&&n.push({id:h.id,name:h.name,type:h.type,isDefault:h.isDefault,scope:"reviewSnippet"}),a.profileUrlKeywordListIds.includes(h.id)&&n.push({id:h.id,name:h.name,type:h.type,isDefault:h.isDefault,scope:"profileUrl"});return n},[Je,a.nameKeywordListIds,a.categoriesKeywordListIds,a.descriptionKeywordListIds,a.reviewSnippetKeywordListIds,a.profileUrlKeywordListIds]),he=({column:n,children:b})=>{if(!Xu.includes(n))return e.jsx("span",{children:b});const h=a.sortBy===n;return e.jsxs("button",{onClick:()=>Ft(n),className:"flex items-center gap-1 hover:text-gray-900 dark:hover:text-white transition-colors font-medium",children:[b,h?a.sortOrder==="asc"?e.jsx(si,{className:"h-3.5 w-3.5"}):e.jsx(ai,{className:"h-3.5 w-3.5"}):e.jsx(li,{className:"h-3.5 w-3.5 opacity-40"})]})};return ae?e.jsxs("div",{className:"space-y-4",children:[St&&mt&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 rounded-lg bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-800 text-sm text-blue-700 dark:text-blue-300",children:[e.jsx(Kt,{className:"h-4 w-4 flex-shrink-0 animate-pulse"}),e.jsx("span",{children:"Our AI auto refiner is optimizing your keywords right now - expect even more relevant results in a few minutes!"})]}),e.jsxs(Ue,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs(Vt,{className:"text-lg flex items-center gap-2",children:["Lead Results",e.jsx(ie,{variant:"secondary",className:"text-xs font-normal","data-testid":"badge-active-database",children:"Home Improvement/Contractor"}),mt&&e.jsx("span",{className:"text-sm font-normal text-gray-500",children:le&&!P?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," ",e.jsx("span",{className:"text-sm text-muted-foreground",children:"Calculating total results"})]}):P?e.jsxs(e.Fragment,{children:["(",(is??0).toLocaleString()," total)"]}):null}),It&&!gt&&e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," ",e.jsx("span",{className:"text-sm text-muted-foreground",children:"Refreshing results"})]})]}),F&&e.jsx(N,{variant:"outline",size:"sm",onClick:()=>F("other"),"data-testid":"button-switch-other-leads",children:J.switchButtonLabel})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("div",{className:"relative flex items-center gap-1",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_l,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-gray-400"}),e.jsx(Ee,{placeholder:"Search all fields...",value:te,onChange:n=>ne(n.target.value),onKeyDown:n=>{n.key==="Enter"&&Ye()},className:"pl-7 h-8 text-xs w-40 sm:w-52"}),te&&e.jsx("button",{onClick:()=>{ne(""),q(n=>({...n,search:""})),K(!1),X(new Set),v(1)},className:"absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:e.jsx(Ut,{className:"h-3 w-3"})})]}),e.jsx(N,{size:"sm",className:"h-8 text-xs px-3 bg-blue-600 hover:bg-blue-700 text-white",onClick:Ye,children:"Apply"})]}),e.jsx(To,{selectedIds:Array.from($),disabled:De.isPending,onSuccess:()=>X(new Set)}),e.jsx(N,{size:"sm",onClick:bs,disabled:De.isPending||!B&&$.size===0&&!Nt,className:"text-xs bg-gradient-to-r from-blue-600 via-purple-600 to-pink-600 hover:from-blue-700 hover:via-purple-700 hover:to-pink-700 border-0",children:De.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Qs,{className:"h-3.5 w-3.5 mr-1"}),"Export",B&&Ae?` (${Ae.total.toLocaleString()})`:$.size>0?` (${$.size.toLocaleString()})`:Nt?` (${$e.toLocaleString()})`:""]})})]})]})}),e.jsxs(_e,{className:"space-y-3 pt-0",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[e.jsxs(Ns,{open:Me,onOpenChange:He,children:[e.jsx(Es,{asChild:!0,children:e.jsxs(N,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1",children:[e.jsx(eo,{className:"h-3 w-3"}),"Saved Filters",lt.length>0&&e.jsx("span",{className:"ml-0.5 bg-blue-100 text-blue-700 rounded-full px-1.5 text-[10px] font-medium",children:lt.length})]})}),e.jsx(ys,{align:"start",className:"w-72 p-2",children:lt.length===0?e.jsx("p",{className:"text-xs text-gray-500 text-center py-3",children:"No saved filters yet"}):e.jsx("div",{className:"space-y-1 max-h-60 overflow-y-auto",children:lt.map(n=>{var ts;const b=typeof n.filters=="string"?n.filters:((ts=n.filters)==null?void 0:ts.hash)||"",h=b?Rn(b,Je):{},L=[];let _=!1,G=!1;h.streetInclude&&h.streetInclude.length>0&&(_=!0,L.push(`Street: ${h.streetInclude.join(", ")}`)),h.streetExclude&&h.streetExclude.length>0&&(_=!0,L.push(`Not Street: ${h.streetExclude.join(", ")}`));const We=[{key:"streetEmptyFilter",label:"Street"},{key:"cityEmptyFilter",label:"City"},{key:"stateEmptyFilter",label:"State"},{key:"zipEmptyFilter",label:"Zip"}];for(const Zt of We){const nt=h[Zt.key];nt&&nt!=="any"&&(G=!0,L.push(`${Zt.label}: ${nt==="only_empty"?"only empty":"non-empty"}`))}const gs=L.length>0?`${n.name} 119${L.join(` 120`)}`:n.name;return e.jsxs("div",{className:"flex items-center gap-1 group",children:[e.jsxs("button",{className:"flex-1 text-left text-xs px-2 py-1.5 rounded hover:bg-gray-100 dark:hover:bg-gray-800 truncate flex items-center gap-1 min-w-0",title:gs,onClick:()=>
120{if(b){const Zt=Rn(b,Je),nt={...qr,...Zt};q(nt),ne(nt.search||""),K(!1),X(new Set),v(1),z.removeQueries({queryKey:["/api/leads"]});const ss=window.location.pathname+window.location.search+b;window.history.replaceState(null,"",ss)}He(!1)},children:[e.jsx("span",{className:"truncate flex-1 min-w-0",children:n.name}),_&&e.jsx("span",{className:"shrink-0 bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300 rounded px-1 text-[9px] font-medium uppercase tracking-wide",children:"Street"}),G&&e.jsx("span",{className:"shrink-0 bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-300 rounded px-1 text-[9px] font-medium uppercase tracking-wide",children:"Empty"})]}),e.jsx("button",{className:"opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-red-50 hover:text-red-600 transition-opacity",onClick:Zt=>{Zt.stopPropagation(),ft.mutate(n.id)},children:e.jsx(Hs,{className:"h-3 w-3"})})]},n.id)})})})]}),e.jsxs(N,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1",onClick:()=>{if(!Hr(a)){A({title:"No active filters to save"});return}Ze(""),pe(!0)},children:[e.jsx(nr,{className:"h-3 w-3"}),"Save Filters"]}),e.jsxs(N,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1",onClick:()=>{const n=qt.filter(L=>L.isDefault),b=et.filter(L=>L.isDefault),h=[...n,...b].map(L=>L.id);q({...qr,nameKeywordListIds:h,categoriesKeywordListIds:h,descriptionKeywordListIds:h,profileUrlKeywordListIds:h}),ne(""),v(1),X(new Set),K(!1),fe.current=!0,_t.current=!0,z.removeQueries({queryKey:["/api/leads"]}),window.history.replaceState(null,"",window.location.pathname),A({title:"Filters reset to defaults"})},children:[e.jsx(to,{className:"h-3 w-3"}),"Reset Filters"]}),e.jsxs(N,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1",onClick:()=>{_t.current=!0,z.removeQueries({queryKey:["/api/leads"]}),A({title:"Refreshing results..."})},disabled:It||le,children:[e.jsx(Ks,{className:`h-3 w-3 ${It||le?"animate-spin":""}`}),"Refresh Results"]}),e.jsxs("div",{className:"flex items-center gap-1",title:"Select the first N leads by the current sort (default newest first)",children:[e.jsx("span",{className:"text-xs text-gray-500",children:"Select first"}),e.jsx(Ee,{type:"number",min:1,placeholder:"N",value:Le,onChange:n=>ve(n.target.value),onKeyDown:n=>{n.key==="Enter"&&ls()},onBlur:Rs,disabled:!mt,className:`h-7 w-16 text-xs ${Oe?"animate-border-flash":""}`}),e.jsxs(N,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1",onClick:ls,disabled:!mt||!Le.trim(),children:[e.jsx(sa,{className:"h-3 w-3"}),"Apply"]}),Nt&&e.jsxs(ie,{variant:"secondary",className:"text-[10px] px-1.5 py-0.5 flex items-center gap-0.5",children:["First ",$e.toLocaleString(),e.jsx("button",{onClick:()=>{W(null),ve("")},className:"ml-0.5 hover:opacity-70",children:e.jsx(Ut,{className:"h-2.5 w-2.5"})})]})]}),(Bt.length>0||Ps.length>0)&&e.jsx("span",{className:"w-px h-5 bg-gray-200 dark:bg-gray-700 mx-0.5"}),Bt.map((n,b)=>e.jsxs(ie,{variant:n.type==="positive"?"default":"destructive",className:`text-[10px] px-1.5 py-0.5 flex items-center gap-0.5 ${n.type==="positive"?"bg-blue-600 hover:bg-blue-700":""}`,children:[e.jsx(Kt,{className:"h-2.5 w-2.5 mr-0.5"}),n.type==="positive"?"+":"-"," ",n.name,e.jsxs("span",{className:"ml-0.5 opacity-60",children:["(",ms[n.scope],")"]}),n.isDefault&&e.jsx("span",{className:"opacity-60",children:"(default)"}),e.jsx("button",{onClick:()=>{const h={...a};switch(n.scope){case"name":h.nameKeywordListIds=h.nameKeywordListIds.filter(L=>L!==n.id);break;case"categories":h.categoriesKeywordListIds=h.categoriesKeywordListIds.filter(L=>L!==n.id);break;case"description":h.descriptionKeywordListIds=(h.descriptionKeywordListIds??[]).filter(L=>L!==n.id);break;case"reviewSnippet":h.reviewSnippetKeywordListIds=h.reviewSnippetKeywordListIds.filter(L=>L!==n.id);break;case"profileUrl":h.profileUrlKeywordListIds=h.profileUrlKeywordListIds.filter(L=>L!==n.id);break}q(h),K(!1),X(new Set),v(1),z.removeQueries({queryKey:["/api/leads"]})},className:"ml-0.5 hover:opacity-70",children:e.jsx(Ut,{className:"h-2.5 w-2.5"})})]},`kl-${n.id}-${n.scope}`)),Ps.map((n,b)=>e.jsxs(ie,{variant:"secondary",className:"text-[10px] px-1.5 py-0.5 flex items-center gap-0.5",children:[n.label,e.jsx("button",{onClick:()=>{const h={...a};n.resetValue==="__stars__"?(h.minStars="",h.maxStars=""):n.resetValue==="__reviews__"?(h.minReviewCount="",h.maxReviewCount=""):n.resetValue==="__lastUpdated__"?(h.lastUpdatedFrom="",h.lastUpdatedTo=""):n.resetValue==="__timeScraped__"?(h.timeScrapedFrom="",h.timeScrapedTo=""):h[n.filterKey]=n.resetValue,n.filterKey==="search"&&ne(""),q(h),K(!1),X(new Set),v(1),z.removeQueries({queryKey:["/api/leads"]})},className:"ml-0.5 hover:opacity-70",children:e.jsx(Ut,{className:"h-2.5 w-2.5"})})]},`f-${b}`))]}),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border rounded-lg overflow-auto max-h-[70vh]",children:e.jsxs(Nn,{children:[e.jsx(En,{className:"sticky top-0 z-20 bg-white dark:bg-gray-950 leads-table-headers shadow-[inset_0_-2px_0_0_rgba(229,231,235,1)] dark:shadow-[inset_0_-2px_0_0_rgba(55,65,81,1)]",children:e.jsxs(za,{children:[e.jsx(Ke,{className:"w-20 sticky left-0 z-30 bg-white dark:bg-gray-950 text-center shadow-[inset_-2px_0_0_0_rgba(229,231,235,1)] dark:shadow-[inset_-2px_0_0_0_rgba(55,65,81,1)]",children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx(Ws,{checked:bt,onCheckedChange:Xt,disabled:!mt||yt.length===0||gt})})}),e.jsx(Ke,{className:"min-w-[130px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"lastUpdated",children:"Last Updated"}),e.jsx(ol,{column:"lastUpdated",label:"Last Updated",filters:a,onApply:oe})]})}),e.jsx(Ke,{className:"min-w-[130px]",children:e.jsxs("div",{className:"flex items-center gap-1",children:["Update Reason",e.jsx(rp,{options:["Newly Added","Phone"],selected:a.updateReasonFilter,onApply:n=>oe({updateReasonFilter:n})})]})}),e.jsx(Zs,{columnKey:"ylprProfileUrl",isActive:a.orColumns.includes("ylprProfileUrl"),className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:["Profile URL",e.jsx(xr,{column:"ylprProfileUrl",label:"Profile URL",filters:a,keywordLists:Je,onApply:oe,orColumns:a.orColumns,columnKey:"ylprProfileUrl"})]})}),e.jsx(Zs,{columnKey:"ylprProfileName",isActive:a.orColumns.includes("ylprProfileName"),className:"min-w-[200px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"ylprProfileName",children:"Company Name"}),e.jsx(xr,{column:"ylprProfileName",label:"Company Name",filters:a,keywordLists:Je,onApply:oe,orColumns:a.orColumns,columnKey:"ylprProfileName"})]})}),e.jsx(Ke,{className:"min-w-[100px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"ylprStars",children:"Stars"}),e.jsx(ll,{column:"ylprStars",label:"Stars",filters:a,onApply:oe})]})}),e.jsx(Ke,{className:"min-w-[90px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"ylprReviewCount",children:"Reviews"}),e.jsx(ll,{column:"ylprReviewCount",label:"Reviews",filters:a,onApply:oe})]})}),e.jsx(Zs,{columnKey:"ylprCategories",isActive:a.orColumns.includes("ylprCategories"),className:"min-w-[180px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"ylprCategories",children:"Categories"}),e.jsx(xr,{column:"ylprCategories",label:"Categories",filters:a,keywordLists:Je,onApply:oe,orColumns:a.orColumns,columnKey:"ylprCategories"})]})}),e.jsx(Ke,{className:"min-w-[150px]",children:"Address Full"}),e.jsx(Zs,{columnKey:"ylprAddressStreet",isActive:a.orColumns.includes("ylprAddressStreet"),className:"min-w-[130px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"ylprAddressStreet",children:"Street"}),e.jsx(pr,{column:"ylprAddressStreet",label:"Street",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"ylprAddressStreet"})]})}),e.jsx(Zs,{columnKey:"ylprAddressCity",isActive:a.orColumns.includes("ylprAddressCity"),className:"min-w-[120px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"ylprAddressCity",children:"City"}),e.jsx(pr,{column:"ylprAddressCity",label:"City",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"ylprAddressCity"})]})}),e.jsx(Zs,{columnKey:"ylprAddressState",isActive:a.orColumns.includes("ylprAddressState"),className:"min-w-[60px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"ylprAddressState",children:"State"}
120),e.jsx(pr,{column:"ylprAddressState",label:"State",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"ylprAddressState"})]})}),e.jsx(Zs,{columnKey:"ylprAddressZip",isActive:a.orColumns.includes("ylprAddressZip"),className:"min-w-[70px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"ylprAddressZip",children:"Zip"}),e.jsx(pr,{column:"ylprAddressZip",label:"Zip",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"ylprAddressZip"})]})}),e.jsx(Zs,{columnKey:"ylprPhone",isActive:a.orColumns.includes("ylprPhone"),className:"min-w-[120px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"ylprPhone",children:"Phone"}),e.jsx(pr,{column:"ylprPhone",label:"Phone",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"ylprPhone"})]})}),e.jsx(Zs,{columnKey:"ylprDescription",isActive:a.orColumns.includes("ylprDescription"),className:"min-w-[200px]",children:e.jsxs("div",{className:"flex items-center",children:["Description",e.jsx(xr,{column:"ylprDescription",label:"Description",filters:a,keywordLists:Je,onApply:oe,orColumns:a.orColumns,columnKey:"ylprDescription"})]})}),e.jsx(Zs,{columnKey:"ylprFeaturedReview",isActive:a.orColumns.includes("ylprFeaturedReview"),className:"min-w-[200px]",children:e.jsxs("div",{className:"flex items-center",children:["Review Snippet",e.jsx(xr,{column:"ylprFeaturedReview",label:"Review Snippet",filters:a,keywordLists:Je,onApply:oe,orColumns:a.orColumns,columnKey:"ylprFeaturedReview"})]})}),e.jsx(Ke,{className:"min-w-[130px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"ylprTimeScraped",children:"Time Scraped"}),e.jsx(ol,{column:"ylprTimeScraped",label:"Time Scraped",filters:a,onApply:oe})]})})]})}),e.jsx(Sn,{children:mt&&!gt&&yt.length>0?yt.map((n,b)=>{const h=(p-1)*y+b,L=$.has(n.id)||Nt&&h<$e;return e.jsxs(za,{className:L?"bg-blue-50 dark:bg-blue-950":"",children:[e.jsx(Fe,{className:`p-2 sticky left-0 z-10 text-center shadow-[inset_-2px_0_0_0_rgba(229,231,235,1)] dark:shadow-[inset_-2px_0_0_0_rgba(55,65,81,1)] ${L?"bg-blue-50 dark:bg-blue-950":"bg-white dark:bg-gray-950"}`,children:e.jsx(Ws,{checked:L,onClick:_=>{_.stopPropagation(),fs(n.id,_.shiftKey)},onCheckedChange:()=>{},disabled:!w&&!$.has(n.id)&&$.size>=ye})}),e.jsx(Fe,{className:"text-xs text-gray-500 whitespace-nowrap cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>V({title:"Last Updated",value:n.lastUpdated?rl(n.lastUpdated):" - "}),children:n.lastUpdated?rl(n.lastUpdated):" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>V({title:"Update Reason",value:Array.isArray(n.lastUpdatedReason)?n.lastUpdatedReason.join(", "):n.lastUpdatedReason||" - "}),children:e.jsx("div",{className:"flex flex-col gap-0.5",children:Array.isArray(n.lastUpdatedReason)&&n.lastUpdatedReason.length>0?n.lastUpdatedReason.map((_,G)=>e.jsx(ie,{className:`text-[10px] px-1.5 py-0.5 leading-none font-normal w-fit whitespace-nowrap border-0 ${_==="Newly Added"?"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200":"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"}`,children:_},G)):e.jsx("span",{className:"text-xs text-gray-400",children:" - "})})}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>V({title:"Profile URL",value:n.ylprProfileUrl||" - "}),children:n.ylprProfileUrl?e.jsxs("a",{href:n.ylprProfileUrl.startsWith("http")?n.ylprProfileUrl:`https://${n.ylprProfileUrl}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-blue-600 hover:text-blue-800 text-xs",onClick:_=>_.stopPropagation(),children:[e.jsx(aa,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate max-w-[140px]",children:n.ylprProfileUrl.replace(/^https?:\/\//,"")})]}):" - "}),e.jsx(Fe,{className:"font-medium cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>V({title:"Company Name",value:n.ylprProfileName||" - "}),children:e.jsx("span",{className:"block truncate max-w-[200px]",children:n.ylprProfileName||" - "})}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>V({title:"Stars",value:n.ylprStars!=null?String(n.ylprStars):" - "}),children:ap(n.ylprStars)}),e.jsx(Fe,{className:"text-center cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>V({title:"Review Count",value:n.ylprReviewCount!=null?String(n.ylprReviewCount):" - "}),children:n.ylprReviewCount||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>
120V({title:"Categories",value:n.ylprCategories||" - "}),children:n.ylprCategories?(()=>{const _=nl(n.ylprCategories),G=_.slice(0,3),We=_.length-3;return e.jsxs("div",{className:"flex flex-col gap-1",children:[G.map((gs,ts)=>e.jsx(ie,{variant:"outline",className:"text-[10px] px-1.5 py-0.5 leading-none font-normal w-fit whitespace-nowrap",children:gs},ts)),We>0&&e.jsxs("span",{className:"text-[10px] text-gray-400",children:["+",We," more"]})]})})():" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>V({title:"Address Full",value:n.ylprAddressFull||" - "}),children:e.jsx("span",{className:"text-xs text-gray-500 line-clamp-1",children:n.ylprAddressFull||" - "})}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>V({title:"Street",value:n.ylprAddressStreet||" - "}),children:e.jsx("span",{className:"text-xs text-gray-500",children:n.ylprAddressStreet||" - "})}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>V({title:"City",value:n.ylprAddressCity||" - "}),children:n.ylprAddressCity||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>V({title:"State",value:n.ylprAddressState||" - "}),children:n.ylprAddressState||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>V({title:"Zip",value:n.ylprAddressZip||" - "}),children:n.ylprAddressZip||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>V({title:"Phone",value:n.ylprPhone||" - ",contactExported:n.contactExported}),children:n.ylprPhone?E&&!n.contactExported?e.jsxs("span",{title:Tt,className:"flex items-center gap-1 text-gray-500 cursor-default text-sm",children:[e.jsx(ya,{className:"h-3 w-3"}),n.ylprPhone]}):e.jsxs("span",{className:"flex items-center gap-1 text-blue-600 text-sm",children:[e.jsx(ei,{className:"h-3 w-3"}),n.ylprPhone]}):" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>V({title:"Description",value:n.ylprDescription||" - "}),children:e.jsx("span",{className:"text-xs text-gray-500 line-clamp-2",children:n.ylprDescription||" - "})}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>V({title:"Review Snippet",value:n.ylprFeaturedReview||" - "}),children:e.jsx("span",{className:"text-xs text-gray-500 line-clamp-2",children:n.ylprFeaturedReview||" - "})}),e.jsx(Fe,{className:"text-xs text-gray-500 whitespace-nowrap cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>V({title:"Time Scraped",value:n.ylprTimeScraped||" - "}),children:n.ylprTimeScraped||" - "})]},n.id)}):null})]})}),mt?gt?e.jsx("div",{className:"py-12 flex items-center justify-center",children:e.jsx(ea,{size:"lg",text:"Loading leads..."})}):Ge?e.jsxs("div",{className:"py-12 flex flex-col items-center justify-center",children:[e.jsx(tr,{className:"h-10 w-10 text-red-600 mb-3"}),e.jsx("p",{className:"text-gray-700 text-lg",children:"Leads failed to load"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"The search took too long or the server had a hiccup. Your filters are unchanged."}),e.jsx(N,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>Ce(),"data-testid":"hi-leads-error-retry",children:"Retry search"})]}):yt.length===0?e.jsxs("div",{className:"py-12 flex flex-col items-center justify-center",children:[e.jsx(tr,{className:"h-10 w-10 text-gray-400 mb-3"}),e.jsx("p",{className:"text-gray-700 text-lg",children:"No leads found"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"Try adjusting your keywords or filters"})]}):null:e.jsx("div",{className:"py-12 flex items-center justify-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(Kt,{className:"h-8 w-8 text-blue-400"}),e.jsxs("p",{className:"text-gray-700",children:["Apply positive keyword filters or include terms to the ",e.jsx("span",{className:"font-semibold",children:"Company Name"}),", ",e.jsx("span",{className:"font-semibold",children:"Categories"}),", ",e.jsx("span",{className:"font-semibold",children:"Review Snippet"}),", or ",e.jsx("span",{className:"font-semibold",children:"Profile URL"})," columns to see results."]}),e.jsx("p",{className:"text-sm text-gray-400",children:"Click the filter icon on Company Name, Categories, Review Snippet, or Profile URL to get started."})]})}),mt&&Ae&&(Ae.pages>1||yt.length>0&&!Dt)&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3 pt-2",children:[e.jsxs("div",{className:"flex items-center gap-3 text-xs text-gray-500",children:[e.jsx("span",{children:Dt?e.jsxs(e.Fragment,{children:["Showing ",Math.min((Ae.page-1)*Ae.limit+1,Ae.total)," to"," ",Math.min(Ae.page*Ae.limit,Ae.total)," of"," ",Ae.total.toLocaleStr
120ing()," leads"]}):e.jsxs(e.Fragment,{children:["Page ",p," · ",yt.length," leads loaded · ",e.jsx(Lt,{size:12})," calculating total..."]})}),e.jsxs("select",{value:y,onChange:n=>{k(Number(n.target.value)),v(1)},className:"h-7 rounded border border-gray-300 bg-white px-1.5 text-xs dark:border-gray-600 dark:bg-gray-800",children:[e.jsx("option",{value:100,children:"100 / page"}),e.jsx("option",{value:500,children:"500 / page"}),e.jsx("option",{value:1e3,children:"1000 / page"})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(N,{variant:"outline",size:"sm",disabled:p<=1,onClick:()=>v(n=>n-1),className:"h-7 text-xs",children:e.jsx(ci,{className:"h-3.5 w-3.5"})}),Array.from({length:Math.min(7,Ae.pages)},(n,b)=>{let h;return Ae.pages<=7||p<=4?h=b+1:p>=Ae.pages-3?h=Ae.pages-6+b:h=p-3+b,e.jsx(N,{variant:h===p?"default":"outline",size:"sm",onClick:()=>v(h),className:"h-7 w-7 text-xs p-0",children:h},h)}),e.jsx(N,{variant:"outline",size:"sm",disabled:p>=Ae.pages,onClick:()=>v(n=>n+1),className:"h-7 text-xs",children:e.jsx(ti,{className:"h-3.5 w-3.5"})})]})]})]})]})]}),e.jsx(os,{open:!!Q,onOpenChange:n=>{n||V(null)},children:e.jsxs(cs,{className:"max-w-md",children:[e.jsx(as,{children:e.jsx(rs,{children:Q==null?void 0:Q.title})}),e.jsx("div",{className:"text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap break-words max-h-[60vh] overflow-auto",children:(Q==null?void 0:Q.title)==="Categories"&&(Q!=null&&Q.value)&&Q.value!==" - "?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:nl(Q.value).map((n,b)=>e.jsx(ie,{variant:"outline",className:"text-xs px-2 py-0.5 leading-none font-normal",children:n},b))}):(Q==null?void 0:Q.title)==="Phone"&&E&&!(Q!=null&&Q.contactExported)&&(Q!=null&&Q.value)&&Q.value!==" - "?e.jsxs("span",{className:"flex items-center gap-1 text-gray-500",children:[e.jsx(ya,{className:"h-3.5 w-3.5"}),Q.value]}):Q==null?void 0:Q.value})]})}),e.jsx(os,{open:R,onOpenChange:pe,children:e.jsxs(cs,{className:"max-w-sm",children:[e.jsx(as,{children:e.jsx(rs,{children:"Save Current Filters"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ee,{placeholder:"Preset name",value:Se,onChange:n=>Ze(n.target.value),onKeyDown:n=>{if(n.key==="Enter"&&Se.trim()){const b=Hr(a);kt.mutate({name:Se.trim(),filters:{hash:b},databaseType:"home_improvement"})}},autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(N,{variant:"outline",size:"sm",onClick:()=>pe(!1),children:"Cancel"}),e.jsx(N,{size:"sm",disabled:!Se.trim()||kt.isPending,onClick:()=>{const n=Hr(a);kt.mutate({name:Se.trim(),filters:{hash:n},databaseType:"home_improvement"})},children:kt.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(nr,{className:"h-3 w-3 mr-1"}),"Save"]})})]})]})]})}),e.jsx(Io,{open:ee,remainingAfterExport:jt-(B?(Ae==null?void 0:Ae.total)??0:$.size>0?$.size:$e??0),onConfirm:()=>{O(!1),De.mutate({selectedIds:I,maxLeads:Pe}),re(void 0),tt(void 0)},onCancel:()=>{O(!1),re(void 0),tt(void 0)}})]}):e.jsx(Ue,{children:e.jsx(_e,{className:"p-8 flex items-center justify-center",children:e.jsx(ea,{size:"lg",text:"Loading keywords..."})})})}const hi=["wOgrequestedUrl","wSimpleCrawledUrl","wCompanyName","aiCategoryEstimation"],Gr={nameKeywordListIds:[],urlKeywordListIds:[],crawledUrlKeywordListIds:[],descriptionKeywordListIds:[],categoryKeywordListIds:[],nameIncludeTerms:[],nameExcludeTerms:[],urlIncludeTerms:[],urlExcludeTerms:[],crawledUrlIncludeTerms:[],crawledUrlExcludeTerms:[],descriptionIncludeTerms:[],descriptionExcludeTerms:[],categoryIncludeTerms:[],categoryExcludeTerms:[],stateInclude:[],stateExclude:[],cityInclude:[],cityExclude:[],zipInclude:[],zipExclude:[],streetInclude:[],streetExclude:[],emailPrimaryInclude:[],emailPrimaryExclude:[],emailTier1Include:[],emailTier1Exclude:[],emailTier2Include:[],emailTier2Exclude:[],emailTier3Include:[],emailTier3Exclude:[],emailTier4Include:[],emailTier4Exclude:[],emailTier5Include:[],emailTier5Exclude:[],emailTier6Include:[],emailTier6Exclude:[],phonePrimaryInclude:[],phonePrimaryExclude:[],phoneTotalInclude:[],phoneTotalExclude:[],phonePrimaryEmptyFilter:"any",phoneTotalEmptyFilter:"any",emailPrimaryEmptyFilter:"any",emailTier1EmptyFilter:"any",emailTier2EmptyFilter:"any",emailTier3EmptyFilter:"any",emailTier4EmptyFilter:"any",emailTier5EmptyFilter:"any",emailTier6EmptyFilter:"any",streetEmptyFilter:"any",cityEmptyFilter:"any",stateEmptyFilter:"any",zipEmptyFilter:"any",de
120scriptionEmptyFilter:"any",employeeCountInclude:[],employeeCountExclude:[],foundingDateInclude:[],foundingDateExclude:[],isChainInclude:[],isChainExclude:[],priceRangeInclude:[],priceRangeExclude:[],legalNameInclude:[],legalNameExclude:[],industryNaicsInclude:[],industryNaicsExclude:[],dunsInclude:[],dunsExclude:[],sloganInclude:[],sloganExclude:[],logoUrlInclude:[],logoUrlExclude:[],founderInclude:[],founderExclude:[],founderEmailInclude:[],founderEmailExclude:[],founderPhoneInclude:[],founderPhoneExclude:[],openingHoursInclude:[],openingHoursExclude:[],areaServedInclude:[],areaServedExclude:[],offersInclude:[],offersExclude:[],brandInclude:[],brandExclude:[],socialProfilesInclude:[],socialProfilesExclude:[],platformInclude:[],platformExclude:[],bookingOpsCrmSoftwareInclude:[],bookingOpsCrmSoftwareExclude:[],reputationChatSoftwareInclude:[],reputationChatSoftwareExclude:[],marketingEmailSoftwareInclude:[],marketingEmailSoftwareExclude:[],adPixelsInclude:[],adPixelsExclude:[],paymentFinancingSoftwareInclude:[],paymentFinancingSoftwareExclude:[],employeeCountEmptyFilter:"any",foundingDateEmptyFilter:"any",isChainEmptyFilter:"any",priceRangeEmptyFilter:"any",legalNameEmptyFilter:"any",industryNaicsEmptyFilter:"any",dunsEmptyFilter:"any",sloganEmptyFilter:"any",logoUrlEmptyFilter:"any",founderEmptyFilter:"any",founderEmailEmptyFilter:"any",founderPhoneEmptyFilter:"any",openingHoursEmptyFilter:"any",areaServedEmptyFilter:"any",offersEmptyFilter:"any",brandEmptyFilter:"any",socialProfilesEmptyFilter:"any",platformEmptyFilter:"any",bookingOpsCrmSoftwareEmptyFilter:"any",reputationChatSoftwareEmptyFilter:"any",marketingEmailSoftwareEmptyFilter:"any",adPixelsEmptyFilter:"any",paymentFinancingSoftwareEmptyFilter:"any",emailPrimaryMxValues:[],emailPrimaryMxEmptyFilter:"any",emailDomainMxValues:[],emailDomainMxEmptyFilter:"any",emailSecurityValues:[],emailSecurityEmptyFilter:"any",addressSourceValues:[],addressSourceEmptyFilter:"any",minNumLocations:"",maxNumLocations:"",minOpenPositions:"",maxOpenPositions:"",openPositionsEmptyFilter:"any",minRatingValue:"",maxRatingValue:"",minReviewCount:"",maxReviewCount:"",redirectFilter:"",updateReasonFilter:[],websiteSchemaFilter:[],search:"",sortBy:"lastUpdated",sortOrder:"desc",timeScrapedFrom:"",timeScrapedTo:"",registrationDateFrom:"",registrationDateTo:"",lastUpdatedFrom:"",lastUpdatedTo:"",orColumns:hi};function Wn(t){const r=t.filter(s=>s.isDefault);return r.length===0?"":r.slice().sort((s,i)=>s.id-i.id).map(s=>`${s.id}:${(Array.isArray(s.keywords)?s.keywords:[]).join(",")}`).join("|")}function ip(t){return!!(t.nameKeywordListIds&&t.nameKeywordListIds.length>0||t.urlKeywordListIds&&t.urlKeywordListIds.length>0||t.crawledUrlKeywordListIds&&t.crawledUrlKeywordListIds.length>0||t.descriptionKeywordListIds&&t.descriptionKeywordListIds.length>0||t.categoryKeywordListIds&&t.categoryKeywordListIds.length>0||t.nameIncludeTerms&&t.nameIncludeTerms.length>0||t.urlIncludeTerms&&t.urlIncludeTerms.length>0||t.crawledUrlIncludeTerms&&t.crawledUrlIncludeTerms.length>0||t.descriptionIncludeTerms&&t.descriptionIncludeTerms.length>0||t.categoryIncludeTerms&&t.categoryIncludeTerms.length>0)}function lp(t){const{hash:r,keywordLists:s,parsed:i,onboardingCategoryFilter:l}=t;if(r&&r.length>1&&ip(i)){const u={...Gr,...i};return{kind:"fromHash",nextFilters:u,searchDraft:u.search||""}}const c=s.filter(u=>u.type==="positive"&&u.isDefault),d=s.filter(u=>u.type==="negative"&&u.isDefault);if(c.length>0||d.length>0){const u=[];for(const g of c)u.push(g.id);for(const g of d)u.push(g.id);return{kind:"withDefaults",partial:{orColumns:[...hi],nameKeywordListIds:u,urlKeywordListIds:u,crawledUrlKeywordListIds:u,categoryKeywordListIds:u,redirectFilter:"no"}}}return l&&l.length>0?{kind:"withOnboarding",partial:{categoryIncludeTerms:l,redirectFilter:"no"}}:{kind:"fallback",partial:{redirectFilter:"no"}}}function op(t){const{keywordLists:r,prevFingerprint:s,prevDefaultIds:i}=t,l=Wn(r);if(l===s)return null;const c=new Set(r.filter(F=>F.isDefault).map(F=>F.id)),d=[...c].some(F=>!i.has(F));if(!l)return{newFingerprint:l,newDefaultIds:c,patch:null,hasNewlyAddedId:d};const u=r.filter(F=>F.type==="positive"&&F.isDefault),g=r.filter(F=>F.type==="negative"&&F.isDefault),f=[];for(const F of u)f.push(F.id);for(const F of g)f.push(F.id);const C={nameKeywordListIds:f,urlKeywordListIds:f,crawledUrlKeywordListIds:f,categoryKeywordListIds:f,...d?{redirectFilter:"no"}:{}};return{newFingerprint:l,newDefaultIds:c,patch:C,hasNewlyAddedId:d}}const cp=[{key:"wOgrequestedUrl",label:"Registered URL"},{key:"wSimpleCrawledUrl",label:"Crawled URL"},{key:"wCompanyName",label:"Company Name"},{key:"aiCategoryEstimation",label:"Categories (AI Enrichment)"},{key:"wProfileDescriptionShort",label:"Description Short"},{key:"wAddressStreet",label:"Street"},{key:"wAddressCity",label:"City"},{key:"wAddressState",label:"State"},{key:"wAddressZip",label:"Zip"},{key:"wPhonePrimary",label:"Phone Primary"},{key:"wPhoneTotal",label:"Total Phones"},{key:"wEmailPrimary",label:"Email Primary"},{key:"wEmailTier1",label:"Tier 1 Emails"},{key:"wEmailTier2",label:"Tier 2 Emails"},{key:"wEmailTier3",label:"Tier 3 Emails"},{key:"wEmailTier4",label:"Tier 4 Emails"},{key:"wEmailTier5",label:"Tier 5 Emails"},{key:"wEmailTier6",label:"Tier 6 Emails"}];function js(t){if(!t)return[];try{const r=JSON.parse(t);return Array.isArray(r)?r:[]}catch{return[]}}
120function Wr(t){const r=new URLSearchParams;t.nameKeywordListIds.length>0&&r.set("nkl",t.nameKeywordListIds.join(",")),t.urlKeywordListIds.length>0&&r.set("ukl",t.urlKeywordListIds.join(",")),t.crawledUrlKeywordListIds.length>0&&r.set("ckl",t.crawledUrlKeywordListIds.join(",")),t.descriptionKeywordListIds.length>0&&r.set("dkl",t.descriptionKeywordListIds.join(",")),t.categoryKeywordListIds.length>0&&r.set("catkl",t.categoryKeywordListIds.join(",")),t.stateInclude.length>0&&r.set("si",t.stateInclude.join(",")),t.stateExclude.length>0&&r.set("se",t.stateExclude.join(",")),t.cityInclude.length>0&&r.set("ci",JSON.stringify(t.cityInclude)),t.cityExclude.length>0&&r.set("ce",JSON.stringify(t.cityExclude)),t.zipInclude.length>0&&r.set("zi",JSON.stringify(t.zipInclude)),t.zipExclude.length>0&&r.set("ze",JSON.stringify(t.zipExclude)),t.nameIncludeTerms.length>0&&r.set("ni",JSON.stringify(t.nameIncludeTerms)),t.nameExcludeTerms.length>0&&r.set("ne",JSON.stringify(t.nameExcludeTerms)),t.urlIncludeTerms.length>0&&r.set("ui",JSON.stringify(t.urlIncludeTerms)),t.urlExcludeTerms.length>0&&r.set("ue",JSON.stringify(t.urlExcludeTerms)),t.crawledUrlIncludeTerms.length>0&&r.set("cli",JSON.stringify(t.crawledUrlIncludeTerms)),t.crawledUrlExcludeTerms.length>0&&r.set("cle",JSON.stringify(t.crawledUrlExcludeTerms)),t.descriptionIncludeTerms.length>0&&r.set("di",JSON.stringify(t.descriptionIncludeTerms)),t.descriptionExcludeTerms.length>0&&r.set("de",JSON.stringify(t.descriptionExcludeTerms)),t.categoryIncludeTerms.length>0&&r.set("cati",JSON.stringify(t.categoryIncludeTerms)),t.categoryExcludeTerms.length>0&&r.set("cate",JSON.stringify(t.categoryExcludeTerms)),t.emailPrimaryInclude.length>0&&r.set("epi",JSON.stringify(t.emailPrimaryInclude)),t.emailPrimaryExclude.length>0&&r.set("epe",JSON.stringify(t.emailPrimaryExclude)),t.emailTier1Include.length>0&&r.set("et1i",JSON.stringify(t.emailTier1Include)),t.emailTier1Exclude.length>0&&r.set("et1e",JSON.stringify(t.emailTier1Exclude)),t.emailTier2Include.length>0&&r.set("et2i",JSON.stringify(t.emailTier2Include)),t.emailTier2Exclude.length>0&&r.set("et2e",JSON.stringify(t.emailTier2Exclude)),t.emailTier3Include.length>0&&r.set("et3i",JSON.stringify(t.emailTier3Include)),t.emailTier3Exclude.length>0&&r.set("et3e",JSON.stringify(t.emailTier3Exclude)),t.emailTier4Include.length>0&&r.set("et4i",JSON.stringify(t.emailTier4Include)),t.emailTier4Exclude.length>0&&r.set("et4e",JSON.stringify(t.emailTier4Exclude)),t.emailTier5Include.length>0&&r.set("et5i",JSON.stringify(t.emailTier5Include)),t.emailTier5Exclude.length>0&&r.set("et5e",JSON.stringify(t.emailTier5Exclude)),t.emailTier6Include.length>0&&r.set("et6i",JSON.stringify(t.emailTier6Include)),t.emailTier6Exclude.length>0&&r.set("et6e",JSON.stringify(t.emailTier6Exclude)),t.phonePrimaryInclude.length>0&&r.set("ppi",JSON.stringify(t.phonePrimaryInclude)),t.phonePrimaryExclude.length>0&&r.set("ppe",JSON.stringify(t.phonePrimaryExclude)),t.phoneTotalInclude.length>0&&r.set("pti",JSON.stringify(t.phoneTotalInclude)),t.phoneTotalExclude.length>0&&r.set("pte",JSON.stringify(t.phoneTotalExclude)),t.streetInclude.length>0&&r.set("sti",JSON.stringify(t.streetInclude)),t.streetExclude.length>0&&r.set("ste",JSON.stringify(t.streetExclude)),t.streetEmptyFilter!=="any"&&r.set("stef",t.streetEmptyFilter),t.cityEmptyFilter!=="any"&&r.set("cief",t.cityEmptyFilter),t.stateEmptyFilter!=="any"&&r.set("sef",t.stateEmptyFilter),t.zipEmptyFilter!=="any"&&r.set("zief",t.zipEmptyFilter),t.phonePrimaryEmptyFilter!=="any"&&r.set("ppef",t.phonePrimaryEmptyFilter),t.phoneTotalEmptyFilter!=="any"&&r.set("ptef",t.phoneTotalEmptyFilter),t.emailPrimaryEmptyFilter!=="any"&&r.set("epef",t.emailPrimaryEmptyFilter),t.emailTier1EmptyFilter!=="any"&&r.set("et1ef",t.emailTier1EmptyFilter),t.emailTier2EmptyFilter!=="any"&&r.set("et2ef",t.emailTier2EmptyFilter),t.emailTier3EmptyFilter!=="any"&&r.set("et3ef",t.emailTier3EmptyFilter),t.emailTier4EmptyFilter!=="any"&&r.set("et4ef",t.emailTier4EmptyFilter),t.emailTier5EmptyFilter!=="any"&&r.set("et5ef",t.emailTier5EmptyFilter),t.emailTier6EmptyFilter!=="any"&&r.set("et6ef",t.emailTier6EmptyFilter),t.descriptionEmptyFilter!=="any"&&r.set("def",t.descriptionEmptyFilter),t.employeeCountInclude.length>0&&r.set("ecI",JSON.stringify(t.employeeCountInclude)),t.employeeCountExclude.length>0&&r.set("ecE",JSON.stringify(t.employeeCountExclude)),t.foundingDateInclude.length>0&&r.set("fdI",JSON.stringify(t.foundingDateInclude)),t.foundingDateExclude.length>0&&r.set("fdE",JSON.stringify(t.foundingDateExclude)),t.isChainInclude.length>0&&r.set("icI",JSON.stringify(t.isChainInclude)),t.isChainExclude.length>0&&r.set("icE",JSON.stringify(t.isChainExclude)),t.priceRangeInclude.length>0&&r.set("prI",JSON.stringify(t.priceRangeInclude)),t.priceRangeExclude.length>0&&r.set("prE",JSON.stringify(t.priceRangeExclude)),t.legalNameInclude.length>0&&r.set("lnI",JSON.stringify(t.legalNameInclude)),t.legalNameExclude.length>0&&r.set("lnE",JSON.stringify(t.legalNameExclude)),t.industryNaicsInclude.length>0&&r.set("naI",JSON.stringify(t.industryNaicsInclude)),t.industryNaicsExclude.length>0&&r.set("naE",JSON.stringify(t.industryNaicsExclude)),t.dunsInclude.length>0&&r.set("duI",JSON.stringify(t.dunsInclude)),t.dunsExclude.length>0&&r.set("duE",JSON.stringify(t.dunsExclude)),t.sloganInclude.length>0&&r.set("slI",JSON.stringify(t.sloganInclude)),t.sloganExclude.length>0&&r.set("slE",JSON.stringify(t.sloganExclude)),t.logoUrlInclude.length>
1200&&r.set("loI",JSON.stringify(t.logoUrlInclude)),t.logoUrlExclude.length>0&&r.set("loE",JSON.stringify(t.logoUrlExclude)),t.founderInclude.length>0&&r.set("foI",JSON.stringify(t.founderInclude)),t.founderExclude.length>0&&r.set("foE",JSON.stringify(t.founderExclude)),t.founderEmailInclude.length>0&&r.set("feI",JSON.stringify(t.founderEmailInclude)),t.founderEmailExclude.length>0&&r.set("feE",JSON.stringify(t.founderEmailExclude)),t.founderPhoneInclude.length>0&&r.set("fpI",JSON.stringify(t.founderPhoneInclude)),t.founderPhoneExclude.length>0&&r.set("fpE",JSON.stringify(t.founderPhoneExclude)),t.openingHoursInclude.length>0&&r.set("ohI",JSON.stringify(t.openingHoursInclude)),t.openingHoursExclude.length>0&&r.set("ohE",JSON.stringify(t.openingHoursExclude)),t.areaServedInclude.length>0&&r.set("asI",JSON.stringify(t.areaServedInclude)),t.areaServedExclude.length>0&&r.set("asE",JSON.stringify(t.areaServedExclude)),t.offersInclude.length>0&&r.set("ofI",JSON.stringify(t.offersInclude)),t.offersExclude.length>0&&r.set("ofE",JSON.stringify(t.offersExclude)),t.brandInclude.length>0&&r.set("brI",JSON.stringify(t.brandInclude)),t.brandExclude.length>0&&r.set("brE",JSON.stringify(t.brandExclude)),t.socialProfilesInclude.length>0&&r.set("spI",JSON.stringify(t.socialProfilesInclude)),t.socialProfilesExclude.length>0&&r.set("spE",JSON.stringify(t.socialProfilesExclude)),t.platformInclude.length>0&&r.set("plI",JSON.stringify(t.platformInclude)),t.platformExclude.length>0&&r.set("plE",JSON.stringify(t.platformExclude)),t.bookingOpsCrmSoftwareInclude.length>0&&r.set("boI",JSON.stringify(t.bookingOpsCrmSoftwareInclude)),t.bookingOpsCrmSoftwareExclude.length>0&&r.set("boE",JSON.stringify(t.bookingOpsCrmSoftwareExclude)),t.reputationChatSoftwareInclude.length>0&&r.set("rcsI",JSON.stringify(t.reputationChatSoftwareInclude)),t.reputationChatSoftwareExclude.length>0&&r.set("rcsE",JSON.stringify(t.reputationChatSoftwareExclude)),t.marketingEmailSoftwareInclude.length>0&&r.set("meI",JSON.stringify(t.marketingEmailSoftwareInclude)),t.marketingEmailSoftwareExclude.length>0&&r.set("meE",JSON.stringify(t.marketingEmailSoftwareExclude)),t.adPixelsInclude.length>0&&r.set("apI",JSON.stringify(t.adPixelsInclude)),t.adPixelsExclude.length>0&&r.set("apE",JSON.stringify(t.adPixelsExclude)),t.paymentFinancingSoftwareInclude.length>0&&r.set("pfI",JSON.stringify(t.paymentFinancingSoftwareInclude)),t.paymentFinancingSoftwareExclude.length>0&&r.set("pfE",JSON.stringify(t.paymentFinancingSoftwareExclude)),t.employeeCountEmptyFilter!=="any"&&r.set("ecF",t.employeeCountEmptyFilter),t.foundingDateEmptyFilter!=="any"&&r.set("fdF",t.foundingDateEmptyFilter),t.isChainEmptyFilter!=="any"&&r.set("icF",t.isChainEmptyFilter),t.priceRangeEmptyFilter!=="any"&&r.set("prF",t.priceRangeEmptyFilter),t.legalNameEmptyFilter!=="any"&&r.set("lnF",t.legalNameEmptyFilter),t.industryNaicsEmptyFilter!=="any"&&r.set("naF",t.industryNaicsEmptyFilter),t.dunsEmptyFilter!=="any"&&r.set("duF",t.dunsEmptyFilter),t.sloganEmptyFilter!=="any"&&r.set("slF",t.sloganEmptyFilter),t.logoUrlEmptyFilter!=="any"&&r.set("loF",t.logoUrlEmptyFilter),t.founderEmptyFilter!=="any"&&r.set("foF",t.founderEmptyFilter),t.founderEmailEmptyFilter!=="any"&&r.set("feF",t.founderEmailEmptyFilter),t.founderPhoneEmptyFilter!=="any"&&r.set("fpF",t.founderPhoneEmptyFilter),t.openingHoursEmptyFilter!=="any"&&r.set("ohF",t.openingHoursEmptyFilter),t.areaServedEmptyFilter!=="any"&&r.set("asF",t.areaServedEmptyFilter),t.offersEmptyFilter!=="any"&&r.set("ofF",t.offersEmptyFilter),t.brandEmptyFilter!=="any"&&r.set("brF",t.brandEmptyFilter),t.socialProfilesEmptyFilter!=="any"&&r.set("spF",t.socialProfilesEmptyFilter),t.platformEmptyFilter!=="any"&&r.set("plF",t.platformEmptyFilter),t.bookingOpsCrmSoftwareEmptyFilter!=="any"&&r.set("boF",t.bookingOpsCrmSoftwareEmptyFilter),t.reputationChatSoftwareEmptyFilter!=="any"&&r.set("rcsF",t.reputationChatSoftwareEmptyFilter),t.marketingEmailSoftwareEmptyFilter!=="any"&&r.set("meF",t.marketingEmailSoftwareEmptyFilter),t.adPixelsEmptyFilter!=="any"&&r.set("apF",t.adPixelsEmptyFilter),t.paymentFinancingSoftw
120areEmptyFilter!=="any"&&r.set("pfF",t.paymentFinancingSoftwareEmptyFilter),t.emailPrimaryMxValues.length>0&&r.set("epmxv",JSON.stringify(t.emailPrimaryMxValues)),t.emailPrimaryMxEmptyFilter!=="any"&&r.set("epmxf",t.emailPrimaryMxEmptyFilter),t.emailDomainMxValues.length>0&&r.set("edmxv",JSON.stringify(t.emailDomainMxValues)),t.emailDomainMxEmptyFilter!=="any"&&r.set("edmxf",t.emailDomainMxEmptyFilter),t.emailSecurityValues.length>0&&r.set("esecv",JSON.stringify(t.emailSecurityValues)),t.emailSecurityEmptyFilter!=="any"&&r.set("esecf",t.emailSecurityEmptyFilter),t.addressSourceValues.length>0&&r.set("asrcv",JSON.stringify(t.addressSourceValues)),t.addressSourceEmptyFilter!=="any"&&r.set("asrcf",t.addressSourceEmptyFilter),t.minNumLocations&&r.set("nlMin",t.minNumLocations),t.maxNumLocations&&r.set("nlMax",t.maxNumLocations),t.minOpenPositions&&r.set("opMin",t.minOpenPositions),t.maxOpenPositions&&r.set("opMax",t.maxOpenPositions),t.openPositionsEmptyFilter!=="any"&&r.set("opf",t.openPositionsEmptyFilter),t.minRatingValue&&r.set("rvMin",t.minRatingValue),t.maxRatingValue&&r.set("rvMax",t.maxRatingValue),t.minReviewCount&&r.set("rcMin",t.minReviewCount),t.maxReviewCount&&r.set("rcMax",t.maxReviewCount),t.redirectFilter&&r.set("rf",t.redirectFilter),t.updateReasonFilter.length>0&&r.set("urf",t.updateReasonFilter.join(",")),t.websiteSchemaFilter.length>0&&r.set("wsf",t.websiteSchemaFilter.join(",")),t.search&&r.set("q",t.search),t.sortBy&&t.sortBy!=="lastUpdated"&&r.set("sb",t.sortBy),t.sortOrder==="asc"&&r.set("so","asc"),t.timeScrapedFrom&&r.set("tsf",t.timeScrapedFrom),t.timeScrapedTo&&r.set("tst",t.timeScrapedTo),t.registrationDateFrom&&r.set("rdf",t.registrationDateFrom),t.registrationDateTo&&r.set("rdt",t.registrationDateTo),t.lastUpdatedFrom&&r.set("luf",t.lastUpdatedFrom),t.lastUpdatedTo&&r.set("lut",t.lastUpdatedTo),r.set("orc",t.orColumns.join(","));const s=r.toString();return s?`#${s}`:""}function Dn(t,r){if(!t||t.length<=1)return{};const s=new URLSearchParams(t.substring(1)),i={},l=new Set(r.map(Ge=>Ge.id)),c=Ge=>{if(!Ge)return;const Ce=Ge.split(",").map(Number).filter(P=>!isNaN(P)).filter(P=>l.has(P));return Ce.length>0?Ce:void 0},d=c(s.get("nkl"));d&&(i.nameKeywordListIds=d);const u=c(s.get("ukl"));u&&(i.urlKeywordListIds=u);const g=c(s.get("ckl"));g&&(i.crawledUrlKeywordListIds=g);const f=c(s.get("dkl"));f&&(i.descriptionKeywordListIds=f);const C=c(s.get("catkl"));C&&(i.categoryKeywordListIds=C),i.categoryIncludeTerms=js(s.get("cati")),i.categoryExcludeTerms=js(s.get("cate"));const F=s.get("si");F&&(i.stateInclude=F.split(",").filter(Boolean));const w=s.get("se");w&&(i.stateExclude=w.split(",").filter(Boolean)),i.cityInclude=js(s.get("ci")),i.cityExclude=js(s.get("ce")),i.zipInclude=js(s.get("zi")),i.zipExclude=js(s.get("ze")),i.nameIncludeTerms=js(s.get("ni")),i.nameExcludeTerms=js(s.get("ne")),i.urlIncludeTerms=js(s.get("ui")),i.urlExcludeTerms=js(s.get("ue")),i.crawledUrlIncludeTerms=js(s.get("cli")),i.crawledUrlExcludeTerms=js(s.get("cle")),i.descriptionIncludeTerms=js(s.get("di")),i.descriptionExcludeTerms=js(s.get("de")),i.emailPrimaryInclude=ke(s.get("epi")),i.emailPrimaryExclude=ke(s.get("epe")),i.emailTier1Include=ke(s.get("et1i")),i.emailTier1Exclude=ke(s.get("et1e")),i.emailTier2Include=ke(s.get("et2i")),i.emailTier2Exclude=ke(s.get("et2e")),i.emailTier3Include=ke(s.get("et3i")),i.emailTier3Exclude=ke(s.get("et3e")),i.emailTier4Include=ke(s.get("et4i")),i.emailTier4Exclude=ke(s.get("et4e")),i.emailTier5Include=ke(s.get("et5i")),i.emailTier5Exclude=ke(s.get("et5e")),i.emailTier6Include=ke(s.get("et6i")),i.emailTier6Exclude=ke(s.get("et6e")),i.phonePrimaryInclude=ke(s.get("ppi")),i.phonePrimaryExclude=ke(s.get("ppe")),i.phoneTotalInclude=ke(s.get("pti")),i.phoneTotalExclude=ke(s.get("pte")),i.streetInclude=js(s.get("sti")),i.streetExclude=js(s.get("ste"));const j=Ge=>{if(Ge==="only_empty"||Ge==="exclude_empty"||Ge==="any")return Ge},E=j(s.get("stef"));E&&(i.streetEmptyFilter=E);const A=j(s.get("cief"));A&&(i.cityEmptyFilter=A);const T=j(s.get("sef"));T&&(i.stateEmptyFilter=T);const J=j(s.get("zief"));J&&(i.zipEmptyFilter=J);const p=j(s.get("ppef"));p&&(i.phonePrimaryEmptyFilter=p);const v=j(s.get("ptef"));v&&(i.phoneTotalEmptyFilter=v);const y=j(s.get("epef"));
120y&&(i.emailPrimaryEmptyFilter=y);const k=j(s.get("et1ef"));k&&(i.emailTier1EmptyFilter=k);const a=j(s.get("et2ef"));a&&(i.emailTier2EmptyFilter=a);const q=j(s.get("et3ef"));q&&(i.emailTier3EmptyFilter=q);const $=j(s.get("et4ef"));$&&(i.emailTier4EmptyFilter=$);const X=j(s.get("et5ef"));X&&(i.emailTier5EmptyFilter=X);const B=j(s.get("et6ef"));B&&(i.emailTier6EmptyFilter=B);const K=j(s.get("def"));K&&(i.descriptionEmptyFilter=K),i.employeeCountInclude=ke(s.get("ecI")),i.employeeCountExclude=ke(s.get("ecE")),i.foundingDateInclude=ke(s.get("fdI")),i.foundingDateExclude=ke(s.get("fdE")),i.isChainInclude=ke(s.get("icI")),i.isChainExclude=ke(s.get("icE")),i.priceRangeInclude=ke(s.get("prI")),i.priceRangeExclude=ke(s.get("prE")),i.legalNameInclude=ke(s.get("lnI")),i.legalNameExclude=ke(s.get("lnE")),i.industryNaicsInclude=ke(s.get("naI")),i.industryNaicsExclude=ke(s.get("naE")),i.dunsInclude=ke(s.get("duI")),i.dunsExclude=ke(s.get("duE")),i.sloganInclude=ke(s.get("slI")),i.sloganExclude=ke(s.get("slE")),i.logoUrlInclude=ke(s.get("loI")),i.logoUrlExclude=ke(s.get("loE")),i.founderInclude=ke(s.get("foI")),i.founderExclude=ke(s.get("foE")),i.founderEmailInclude=ke(s.get("feI")),i.founderEmailExclude=ke(s.get("feE")),i.founderPhoneInclude=ke(s.get("fpI")),i.founderPhoneExclude=ke(s.get("fpE")),i.openingHoursInclude=ke(s.get("ohI")),i.openingHoursExclude=ke(s.get("ohE")),i.areaServedInclude=ke(s.get("asI")),i.areaServedExclude=ke(s.get("asE")),i.offersInclude=ke(s.get("ofI")),i.offersExclude=ke(s.get("ofE")),i.brandInclude=ke(s.get("brI")),i.brandExclude=ke(s.get("brE")),i.socialProfilesInclude=ke(s.get("spI")),i.socialProfilesExclude=ke(s.get("spE")),i.platformInclude=ke(s.get("plI")),i.platformExclude=ke(s.get("plE")),i.bookingOpsCrmSoftwareInclude=ke(s.get("boI")),i.bookingOpsCrmSoftwareExclude=ke(s.get("boE")),i.reputationChatSoftwareInclude=ke(s.get("rcsI")),i.reputationChatSoftwareExclude=ke(s.get("rcsE")),i.marketingEmailSoftwareInclude=ke(s.get("meI")),i.marketingEmailSoftwareExclude=ke(s.get("meE")),i.adPixelsInclude=ke(s.get("apI")),i.adPixelsExclude=ke(s.get("apE")),i.paymentFinancingSoftwareInclude=ke(s.get("pfI")),i.paymentFinancingSoftwareExclude=ke(s.get("pfE"));const ae=j(s.get("ecF"));ae&&(i.employeeCountEmptyFilter=ae);const Y=j(s.get("fdF"));Y&&(i.foundingDateEmptyFilter=Y);const fe=j(s.get("icF"));fe&&(i.isChainEmptyFilter=fe);const U=j(s.get("prF"));U&&(i.priceRangeEmptyFilter=U);const te=j(s.get("lnF"));te&&(i.legalNameEmptyFilter=te);const ne=j(s.get("naF"));ne&&(i.industryNaicsEmptyFilter=ne);const Q=j(s.get("duF"));Q&&(i.dunsEmptyFilter=Q);const V=j(s.get("slF"));V&&(i.sloganEmptyFilter=V);const R=j(s.get("loF"));R&&(i.logoUrlEmptyFilter=R);const pe=j(s.get("foF"));pe&&(i.founderEmptyFilter=pe);const Se=j(s.get("feF"));Se&&(i.founderEmailEmptyFilter=Se);const Ze=j(s.get("fpF"));Ze&&(i.founderPhoneEmptyFilter=Ze);const Me=j(s.get("ohF"));Me&&(i.openingHoursEmptyFilter=Me);const He=j(s.get("asF"));He&&(i.areaServedEmptyFilter=He);const ee=j(s.get("ofF"));ee&&(i.offersEmptyFilter=ee);const O=j(s.get("brF"));O&&(i.brandEmptyFilter=O);const I=j(s.get("spF"));I&&(i.socialProfilesEmptyFilter=I);const re=j(s.get("plF"));re&&(i.platformEmptyFilter=re);const Pe=j(s.get("boF"));Pe&&(i.bookingOpsCrmSoftwareEmptyFilter=Pe);const tt=j(s.get("rcsF"));tt&&(i.reputationChatSoftwareEmptyFilter=tt);const $e=j(s.get("meF"));$e&&(i.marketingEmailSoftwareEmptyFilter=$e);const W=j(s.get("apF"));W&&(i.adPixelsEmptyFilter=W);const Le=j(s.get("pfF"));Le&&(i.paymentFinancingSoftwareEmptyFilter=Le);const ve=js(s.get("epmxv"));ve.length>0&&(i.emailPrimaryMxValues=ve);const Oe=j(s.get("epmxf"));Oe&&(i.emailPrimaryMxEmptyFilter=Oe);const vt=js(s.get("edmxv"));vt.length>0&&(i.emailDomainMxValues=vt);const Rt=j(s.get("edmxf"));Rt&&(i.emailDomainMxEmptyFilter=Rt);const At=js(s.get("esecv"));At.length>0&&(i.emailSecurityValues=At);const at=j(s.get("esecf"));at&&(i.emailSecurityEmptyFilter=at);const Je=js(s.get("asrcv"));Je.length>0&&(i.addressSourceValues=Je);const Te=j(s.get("asrcf"));Te&&(i.addressSourceEmptyFilter=Te);const Ct=s.get("nlMin");Ct&&(i.minNumLocations=Ct);const lt=s.get("nlMax");lt&&(i.maxNumLocations=lt);const kt=s.get("opMin");kt&&(i.minOpenPositions=kt);
120const ft=s.get("opMax");ft&&(i.maxOpenPositions=ft);const qt=j(s.get("opf"));qt&&(i.openPositionsEmptyFilter=qt);const et=s.get("rvMin");et&&(i.minRatingValue=et);const Ot=s.get("rvMax");Ot&&(i.maxRatingValue=Ot);const Xe=s.get("rcMin");Xe&&(i.minReviewCount=Xe);const mt=s.get("rcMax");mt&&(i.maxReviewCount=mt);const ut=s.get("rf");(ut==="yes"||ut==="no")&&(i.redirectFilter=ut);const ot=s.get("urf");ot&&(i.updateReasonFilter=ot.split(",").filter(Boolean));const St=s.get("wsf");St&&(i.websiteSchemaFilter=St.split(",").filter(Boolean)),s.get("q")&&(i.search=s.get("q")),s.get("sb")&&(i.sortBy=s.get("sb")),s.get("so")==="asc"&&(i.sortOrder="asc");const Pt=s.get("tsf");Pt&&(i.timeScrapedFrom=Pt);const it=s.get("tst");it&&(i.timeScrapedTo=it);const ze=s.get("rdf");ze&&(i.registrationDateFrom=ze);const _t=s.get("rdt");_t&&(i.registrationDateTo=_t);const de=s.get("luf");de&&(i.lastUpdatedFrom=de);const gt=s.get("lut");gt&&(i.lastUpdatedTo=gt);const It=s.get("orc");if(It){const Ge=new Set(cp.map(P=>P.key)),Ce=It.split(",").filter(P=>Ge.has(P));Ce.length>0&&(i.orColumns=Ce)}return i}const dl=["AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"],dp=Nu,mp=["wOgrequestedUrl","wProfileDate","wRedirectYn","wSimpleCrawledUrl","wCompanyName","wAddressCity","wAddressState","wAddressZip","wPhonePrimary","wEmailPrimary","wEmailPrimaryMx","wEmailDomainMx","wEmailSecurity","wAddressSource","wTimeScraped","lastUpdated","wEmployeeCount","wFoundingDate","wIsChain","wPriceRange","wLegalName","wIndustryNaics","wDuns","wSlogan","wNumLocations","wOpenPositions","wRatingValue","wReviewCount"];function ml(t){return t.replace(/^\[|\]$/g,"").replace(/'/g,"").split(/[,;|]/).map(s=>s.trim()).filter(s=>s.length>0)}function Lo(t){return t.split(/[,;|]/).map(r=>r.trim()).filter(r=>r.length>0)}function Ro(t){const r=t.trim();if(r.startsWith("[")&&r.endsWith("]")){const s=r.slice(1,-1),i=[];let l="",c=null;for(let u=0;u<s.length;u++){const g=s[u];if(c){if(g==="\\"&&u+1<s.length){l+=s[u+1],u++;continue}if(g===c){c=null;continue}l+=g}else if(g==='"'||g==="'")c=g;else if(g===","){const f=l.trim();f&&f.toLowerCase()!=="none"&&i.push(f),l=""}else l+=g}const d=l.trim();return d&&d.toLowerCase()!=="none"&&i.push(d),i}return r.split(/[,;|]/).map(s=>s.trim()).filter(s=>s.length>0&&s.toLowerCase()!=="none")}function up({value:t,onOpen:r}){const[s,i]=o.useState(!1),l=t==null?void 0:t.trim();o.useEffect(()=>{i(!1)},[l]);const c=!!l&&!s;return e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:r,children:c?e.jsx("img",{src:l,alt:"Logo",loading:"lazy",referrerPolicy:"no-referrer",onError:()=>i(!0),className:"h-6 w-6 rounded object-contain border border-gray-200 dark:border-gray-700 bg-white"}):" - "})}function Js({value:t,onOpen:r}){const s=t?Lo(t):[];return e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:r,children:s.length>0?e.jsxs("div",{className:"flex flex-wrap gap-1 max-w-[220px]",children:[s.slice(0,3).map((i,l)=>e.jsx(ie,{variant:"outline",className:"text-[10px] px-1.5 py-0 leading-none font-normal whitespace-nowrap",children:i},l)),s.length>3&&e.jsxs("span",{className:"text-[10px] text-gray-400",children:["+",s.length-3," more"]})]}):" - "})}function pp({value:t,onOpen:r}){const s=t?Ro(t):[];return e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:r,children:s.length>0?e.jsxs("div",{className:"flex flex-wrap gap-1 max-w-[220px]",children:[s.slice(0,3).map((i,l)=>e.jsx(ie,{variant:"outline",className:"text-[10px] px-1.5 py-0 leading-none font-normal whitespace-nowrap max-w-[200px] truncate",children:i},l)),s.length>3&&e.jsxs("span",{className:"text-[10px] text-gray-400",children:["+",s.length-3," more"]})]}):" - "})}function la({title:t,value:r,kind:s,shouldMaskContacts:i,contactExported:l,maskedTooltipText:c,onOpen:d}){const u=r?Lo(r):[],g=i&&!l;return e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:d,children:u.length>0?(()=>{const f=u.slice(0,3),C=u.length-3;return e.jsxs("div",{className:"flex flex-col gap-1",children:[f.map((F,w)=>g?e.jsxs("span",{title:c,className:"flex items-center gap-1 text-gray-500 cursor-default text-xs",children:[e.jsx(ya,{className:"h-3 w-3"}),F]},w):s==="email"?e.jsxs("a",{href:`mailto:${F}`,className:"flex items-center gap-1 text-blue-600 hover:text-blue-800 text-xs",onClick:j=>j.stopPropagation(),children:[e.jsx(_a,{className:"h-3 w-3"}),F]},w):e.jsxs("span",{className:"flex items-center gap-1 text-blue-600 text-sm",children:[e.jsx(ei,{className:"h-3 w-3"}),F]},w)),C>0&&e.jsxs("span",{className:"text-[10px] text-gray-400",children:["+",C," more"]})]})})():" - "})}function ul(t){const r=new Date(t),s=r.getUTCFullYear(),i=String(r.getUTCMonth()+1).padStart(2,"0"),l=String(r.getUTCDate()).padStart(2,"0"),c=String(r.getUTCHours()).padStart(2,"0"),d=String(r.getUTCMinutes()).padStart(2,"0"),u=String(r.getUTCSeconds()).padStart(2,"0");return`${s}-${i}-${l} ${c}:${d}:${u}`}const Oo={wAddressStreet:"streetEmptyFilter",wAddressCity:"cityEmptyFilter",wAddressState:"stateEmptyFilter",wAddressZip:"zipEmptyFilter",wPhonePrimary:"phonePrimaryEmptyFilter",wPhoneTotal:"phoneTotalEmptyFilter",wEmailPrimary:"emailPrimaryEmptyFilter",wEmailTier1:"emailTier1EmptyFilter",wEmailTier2:"emailTier2EmptyFilter",wEmailTier3:"emailTier3EmptyFilter",wEmailTier4:"emailTier4EmptyFilter",wEmailTier5:"emailTier5EmptyFilter",wEmailTier6:"emailTier6EmptyFilter",wProfileDescriptionShort:"descriptionEmptyFilter",wEmployeeCount:"employeeCountEmptyFilter",wFoundingDate:"foundingDateEmptyFilter",wIsChain:"isChainEmptyFilter",wPriceRange:"priceRangeEmptyFilter",wLegalName:"legalNameEmptyFilter",wIndustryNaics:"industryNaicsEmptyFilter",wDuns:"dunsEmptyFilter",wSlogan:"sloganEmptyFilter",wLogoUrl:"logoUrlEmptyFilter",wFounder:"founderEmptyFilter",wFounderEmail:"founderEmailEmptyFilter",wFounderPhone:"founderPhoneEmptyFilter",wOpeningHours:"openingHoursEmptyFilter",wAreaServed:"areaServedEmptyFilter",wOffers:"offersEmptyFilter",wBrand:"brandEmptyFilter",wSocialProfiles:"socialProfilesEmptyFilter",wPlatform:"platformEmptyFilter",wBookingOpsCrmSoftw
120are:"bookingOpsCrmSoftwareEmptyFilter",wReputationChatSoftware:"reputationChatSoftwareEmptyFilter",wMarketingEmailSoftware:"marketingEmailSoftwareEmptyFilter",wAdPixels:"adPixelsEmptyFilter",wPaymentFinancingSoftware:"paymentFinancingSoftwareEmptyFilter"};function Cn({value:t,onChange:r,label:s}){const i=[{value:"any",label:"Any"},{value:"only_empty",label:"Only empty"},{value:"exclude_empty",label:"Non-empty"}];return e.jsxs("div",{className:"border-t pt-2 space-y-1.5",children:[e.jsx("label",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300",children:s}),e.jsx("div",{className:"grid grid-cols-3 gap-1",children:i.map(l=>e.jsx("button",{type:"button",onClick:()=>r(l.value),className:`text-[10px] px-1 py-1 rounded border transition-colors ${t===l.value?"bg-blue-600 text-white border-blue-600":"bg-transparent border-gray-300 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-800"}`,children:l.label},l.value))})]})}function xp(t,r){switch(r){case"wCompanyName":return t.nameKeywordListIds;case"wOgrequestedUrl":return t.urlKeywordListIds;case"wSimpleCrawledUrl":return t.crawledUrlKeywordListIds;case"wProfileDescriptionShort":return t.descriptionKeywordListIds;case"aiCategoryEstimation":return t.categoryKeywordListIds}}function Do(t,r){const s={wCompanyName:new Set(t.nameKeywordListIds),wOgrequestedUrl:new Set(t.urlKeywordListIds),wSimpleCrawledUrl:new Set(t.crawledUrlKeywordListIds),wProfileDescriptionShort:new Set(t.descriptionKeywordListIds),aiCategoryEstimation:new Set(t.categoryKeywordListIds)},i=t.orColumns.filter(v=>v in s),l=new Set(t.orColumns),c=Array.from(new Set(t.nameKeywordListIds.concat(t.urlKeywordListIds,t.crawledUrlKeywordListIds,t.descriptionKeywordListIds,t.categoryKeywordListIds))),d=[],u=[],g=[...t.nameIncludeTerms],f=[...t.nameExcludeTerms],C=[...t.urlIncludeTerms],F=[...t.urlExcludeTerms],w=[...t.crawledUrlIncludeTerms],j=[...t.crawledUrlExcludeTerms],E=[...t.descriptionIncludeTerms],A=[...t.descriptionExcludeTerms],T=[...t.categoryIncludeTerms],J=[...t.categoryExcludeTerms],p=(v,y,k)=>{v==="wCompanyName"?k==="positive"?g.push(...y):f.push(...y):v==="wOgrequestedUrl"?k==="positive"?C.push(...y):F.push(...y):v==="wSimpleCrawledUrl"?k==="positive"?w.push(...y):j.push(...y):v==="wProfileDescriptionShort"?k==="positive"?E.push(...y):A.push(...y):v==="aiCategoryEstimation"&&(k==="positive"?T.push(...y):J.push(...y))};for(const v of r){if(!c.includes(v.id))continue;const y=Array.isArray(v.keywords)?v.keywords:[];if(i.length>0&&i.every(a=>s[a].has(v.id))){v.type==="positive"?d.push(...y):u.push(...y);for(const[a,q]of Object.entries(s))!l.has(a)&&q.has(v.id)&&p(a,y,v.type)}else for(const[a,q]of Object.entries(s))q.has(v.id)&&p(a,y,v.type)}return{positiveKeywords:d,negativeKeywords:u,nameInclude:g,nameExclude:f,urlInclude:C,urlExclude:F,crawledUrlInclude:w,crawledUrlExclude:j,descInclude:E,descExclude:A,catInclude:T,catExclude:J}}function hp(t,r,s,i){const l=new URLSearchParams;l.set("page",String(r)),l.set("limit",String(s));const c=Array.from(new Set(t.nameKeywordListIds.concat(t.urlKeywordListIds,t.crawledUrlKeywordListIds,t.descriptionKeywordListIds,t.categoryKeywordListIds)));c.length>0&&l.set("keywordListIds",c.join(","));const d=Do(t,i);return d.positiveKeywords.length>0&&l.set("positiveKeywords",JSON.stringify(d.positiveKeywords)),d.negativeKeywords.length>0&&l.set("negativeKeywords",JSON.stringify(d.negativeKeywords)),d.nameInclude.length>0&&l.set("nameIncludeTerms",JSON.stringify(d.nameInclude)),d.nameExclude.length>0&&l.set("nameExcludeTerms",JSON.stringify(d.nameExclude)),d.urlInclude.length>0&&l.set("urlIncludeTerms",JSON.stringify(d.urlInclude)),d.urlExclude.length>0&&l.set("urlExcludeTerms",JSON.stringify(d.urlExclude)),d.crawledUrlInclude.length>0&&l.set("crawledUrlIncludeTerms",JSON.stringify(d.crawledUrlInclude)),d.crawledUrlExclude.length>0&&l.set("crawledUrlExcludeTerms",JSON.stringify(d.crawledUrlExclude)),d.descInclude.length>0&&l.set("descriptionIncludeTerms",JSON.stringify(d.descInclude)),d.descExclude.length>0&&l.set("descriptionExcludeTerms",JSON.stringify(d.descExclude)),d.catInclude.length>0&&l.set("categoryIncludeTerms",JSON.stringify(d.catInclude)),d.catExclude.length>0&&l.set("categoryExcludeTerms",JSON.stringify(d.catExclude)),t.stateInclude.length>0&&l.set("stateInclude",t.stateInclude.join(",")),t.stateExclude.length>0&&l.set("stateExclude",t.stateExclude.join(",")),t.cityInclude.length>0&&l.set("cityInclude",JSON.stringify(t.cityInclude)),t.cityExclude.length>0&&l.set("cityExclude",JSON.stringify(t.cityExclude)),t.zipInclude.length>0&&l.set("zipInclude",JSON.stringify(t.zipInclude)),t.zipExclude.length>0&&l.set("zipExclude",JSON.stringify(t.zipExclude)),t.streetInclude.length>0&&l.set("streetInclude",JSON.stringify(t.streetInclude)),t.streetExclude.length>0&&l.set("streetExclude",JSON.stringify(t.streetExclude)),t.emailPrimaryInclude.length>0&&l.set("emailPrimaryInclude",JSON.stringify(t.emailPrimaryInclude)),t.emailPrimaryExclude.length>0&&l.set("emailPrimaryExclude",JSON.stringify(t.emailPrimaryExclude)),t.emailTier1Include.length>0&&l.set("emailTier1Include",JSON.stringify(t.emailTier1Include)),t.emailTier1Exclude.length>0&&l.set("emailTier1Exclude",JSON.stringify(t.emailTier1Exclude)),t.emailTier2Include.length>0&&l.set("emailTier2Include",JSON.stringify(t.emailTier2Include)),t.emailTier2Exclude.length>0&&l.set("emailTier2Exclude",JSON.stringify(t.emailTier2Exclude)),t.emailTier3Include.length>0&&l.set("emailTier3Include",JSON.stringify(t.emailTier3Include)),t.emailTier3Exclude.length>0&&l.set("emailTier3Exclude",JSON.stringify(t.emailTier3Exclude)),t.emailTier4Include.length>0&&l.set("emailTier4Include",JSON.stringify(t.emailTier4Include)),t.emailTier4Exclude.length>0&&l.set("emailTier4Exclude",JSON.stringify(t.emailTier4Exclude)),t.emailTier5Include.length>0&&l.set("emailTier5Include",JSON.stringify(t.emailTier5Include)),t.emailTier5Exclude.length>0&&l.set("emailTier5Exclude",JSON.stringify(t.emailTier5Exclude)),t.emailTier6Include.length>0&&l.set("emailTier6Include",JSON.stringify(t.emailTier6Include)),t.emailTier6Exclude.length>0&&l.set("emailTier6Exclude",JSON.stringify(t.emailTier6Exclude)),t.phonePrimaryInclude.length>0&&l.set("phonePrimaryInclude",JSON.stringify(t.phonePrimaryInclude)),t.phonePrimaryExclude.length>0&&l.set("phonePrimaryExclude",JSON.stringify(t.phonePrimaryExclude)),t.phoneTotalInclude.length>0&&l.set("phoneTotalInclude",JSON.stringify(t.phoneTotalInclude)),t.phoneTotalExclude.length>0&&l.set("phoneTotalExclude",JSON.stringify(t.phoneTotalExclude)),t.streetEmptyFilter!=="any"&&l.set("streetEmptyFilter",t.streetEmptyFilter),t.cityEmptyFilter!=="any"&&l.set("cityEmptyFilter",t.cityEmptyFilter),t.stateEmptyFilter!=="any"&&l.set("stateEmptyFilter",t.stateEmptyFilter),t.zipEmptyFilter!=="any"&&l.set("zipEmptyFilter",t.zipEmptyFilter),t.phonePrimaryEmptyFilter!=="any"&&l.set("phonePrimaryEmptyFilter",t.ph
120onePrimaryEmptyFilter),t.phoneTotalEmptyFilter!=="any"&&l.set("phoneTotalEmptyFilter",t.phoneTotalEmptyFilter),t.emailPrimaryEmptyFilter!=="any"&&l.set("emailPrimaryEmptyFilter",t.emailPrimaryEmptyFilter),t.emailTier1EmptyFilter!=="any"&&l.set("emailTier1EmptyFilter",t.emailTier1EmptyFilter),t.emailTier2EmptyFilter!=="any"&&l.set("emailTier2EmptyFilter",t.emailTier2EmptyFilter),t.emailTier3EmptyFilter!=="any"&&l.set("emailTier3EmptyFilter",t.emailTier3EmptyFilter),t.emailTier4EmptyFilter!=="any"&&l.set("emailTier4EmptyFilter",t.emailTier4EmptyFilter),t.emailTier5EmptyFilter!=="any"&&l.set("emailTier5EmptyFilter",t.emailTier5EmptyFilter),t.emailTier6EmptyFilter!=="any"&&l.set("emailTier6EmptyFilter",t.emailTier6EmptyFilter),t.descriptionEmptyFilter!=="any"&&l.set("descriptionEmptyFilter",t.descriptionEmptyFilter),t.redirectFilter&&l.set("redirectFilter",t.redirectFilter),t.updateReasonFilter.length>0&&l.set("updateReasonFilter",t.updateReasonFilter.join(",")),t.websiteSchemaFilter.length>0&&l.set("websiteSchemaFilter",t.websiteSchemaFilter.join(",")),t.search&&l.set("search",t.search),t.sortBy&&t.sortBy!=="lastUpdated"&&l.set("sortBy",t.sortBy),t.sortOrder==="asc"&&l.set("sortOrder","asc"),t.timeScrapedFrom&&l.set("timeScrapedFrom",t.timeScrapedFrom),t.timeScrapedTo&&l.set("timeScrapedTo",t.timeScrapedTo),t.registrationDateFrom&&l.set("registrationDateFrom",t.registrationDateFrom),t.registrationDateTo&&l.set("registrationDateTo",t.registrationDateTo),t.lastUpdatedFrom&&l.set("lastUpdatedFrom",t.lastUpdatedFrom),t.lastUpdatedTo&&l.set("lastUpdatedTo",t.lastUpdatedTo),t.employeeCountInclude.length>0&&l.set("employeeCountInclude",JSON.stringify(t.employeeCountInclude)),t.employeeCountExclude.length>0&&l.set("employeeCountExclude",JSON.stringify(t.employeeCountExclude)),t.foundingDateInclude.length>0&&l.set("foundingDateInclude",JSON.stringify(t.foundingDateInclude)),t.foundingDateExclude.length>0&&l.set("foundingDateExclude",JSON.stringify(t.foundingDateExclude)),t.isChainInclude.length>0&&l.set("isChainInclude",JSON.stringify(t.isChainInclude)),t.isChainExclude.length>0&&l.set("isChainExclude",JSON.stringify(t.isChainExclude)),t.priceRangeInclude.length>0&&l.set("priceRangeInclude",JSON.stringify(t.priceRangeInclude)),t.priceRangeExclude.length>0&&l.set("priceRangeExclude",JSON.stringify(t.priceRangeExclude)),t.legalNameInclude.length>0&&l.set("legalNameInclude",JSON.stringify(t.legalNameInclude)),t.legalNameExclude.length>0&&l.set("legalNameExclude",JSON.stringify(t.legalNameExclude)),t.industryNaicsInclude.length>0&&l.set("industryNaicsInclude",JSON.stringify(t.industryNaicsInclude)),t.industryNaicsExclude.length>0&&l.set("industryNaicsExclude",JSON.stringify(t.industryNaicsExclude)),t.dunsInclude.length>0&&l.set("dunsInclude",JSON.stringify(t.dunsInclude)),t.dunsExclude.length>0&&l.set("dunsExclude",JSON.stringify(t.dunsExclude)),t.sloganInclude.length>0&&l.set("sloganInclude",JSON.stringify(t.sloganInclude)),t.sloganExclude.length>0&&l.set("sloganExclude",JSON.stringify(t.sloganExclude)),t.logoUrlInclude.length>0&&l.set("logoUrlInclude",JSON.stringify(t.logoUrlInclude)),t.logoUrlExclude.length>
1200&&l.set("logoUrlExclude",JSON.stringify(t.logoUrlExclude)),t.founderInclude.length>0&&l.set("founderInclude",JSON.stringify(t.founderInclude)),t.founderExclude.length>0&&l.set("founderExclude",JSON.stringify(t.founderExclude)),t.founderEmailInclude.length>0&&l.set("founderEmailInclude",JSON.stringify(t.founderEmailInclude)),t.founderEmailExclude.length>0&&l.set("founderEmailExclude",JSON.stringify(t.founderEmailExclude)),t.founderPhoneInclude.length>0&&l.set("founderPhoneInclude",JSON.stringify(t.founderPhoneInclude)),t.founderPhoneExclude.length>0&&l.set("founderPhoneExclude",JSON.stringify(t.founderPhoneExclude)),t.openingHoursInclude.length>0&&l.set("openingHoursInclude",JSON.stringify(t.openingHoursInclude)),t.openingHoursExclude.length>0&&l.set("openingHoursExclude",JSON.stringify(t.openingHoursExclude)),t.areaServedInclude.length>0&&l.set("areaServedInclude",JSON.stringify(t.areaServedInclude)),t.areaServedExclude.length>0&&l.set("areaServedExclude",JSON.stringify(t.areaServedExclude)),t.offersInclude.length>0&&l.set("offersInclude",JSON.stringify(t.offersInclude)),t.offersExclude.length>0&&l.set("offersExclude",JSON.stringify(t.offersExclude)),t.brandInclude.length>0&&l.set("brandInclude",JSON.stringify(t.brandInclude)),t.brandExclude.length>0&&l.set("brandExclude",JSON.stringify(t.brandExclude)),t.socialProfilesInclude.length>0&&l.set("socialProfilesInclude",JSON.stringify(t.socialProfilesInclude)),t.socialProfilesExclude.length>0&&l.set("socialProfilesExclude",JSON.stringify(t.socialProfilesExclude)),t.platformInclude.length>0&&l.set("platformInclude",JSON.stringify(t.platformInclude)),t.platformExclude.length>0&&l.set("platformExclude",JSON.stringify(t.platformExclude)),t.bookingOpsCrmSoftwareInclude.length>0&&l.set("bookingOpsCrmSoftwareInclude",JSON.stringify(t.bookingOpsCrmSoftwareInclude)),t.bookingOpsCrmSoftwareExclude.length>0&&l.set("bookingOpsCrmSoftwareExclude",JSON.stringify(t.bookingOpsCrmSoftwareExclude)),t.reputationChatSoftwareInclude.length>0&&l.set("reputationChatSoftwareInclude",JSON.stringify(t.reputationChatSoftwareInclude)),t.reputationChatSoftwareExclude.length>0&&l.set("reputationChatSoftwareExclude",JSON.stringify(t.reputationChatSoftwareExclude)),t.marketingEmailSoftwareInclude.length>0&&l.set("marketingEmailSoftwareInclude",JSON.stringify(t.marketingEmailSoftwareInclude)),t.marketingEmailSoftwareExclude.length>0&&l.set("marketingEmailSoftwareExclude",JSON.stringify(t.marketingEmailSoftwareExclude)),t.adPixelsInclude.length>0&&l.set("adPixelsInclude",JSON.stringify(t.adPixelsInclude)),t.adPixelsExclude.length>0&&l.set("adPixelsExclude",JSON.stringify(t.adPixelsExclude)),t.paymentFinancingSoftwareInclude.length>0&&l.set("paymentFinancingSoftwareInclude",JSON.stringify(t.paymentFinancingSoftwareInclude)),t.paymentFinancingSoftwareExclude.length>0&&l.set("paymentFinancingSoftwareExclude",JSON.stringify(t.paymentFinancingSoftwareExclude)),t.employeeCountEmptyFilter!=="any"&&l.set("employeeCountEmptyFilter",t.employeeCountEmptyFilter),t.foundingDateEmptyFilter!=="any"&&l.set("foundingDateEmptyFilter",t.foundingDateEmptyFilter),t.isChainEmptyFilter!=="any"&&l.set("isChainEmptyFilter",t.isChainEmptyFilter),t.priceRangeEmptyFilter!=="any"&&l.set("priceRangeEmptyFilter",t.priceRangeEmptyFilter),t.legalNameEmptyFilter!=="any"&&l.set("legalNameEmptyFilter",t.legalNameEmptyFilter),t.industryNaicsEmptyFilter!=="any"&&l.set("industryNaicsEmptyFilter",t.industryNaicsEmptyFilter),t.dunsEmptyFilter!=="any"&&l.set("dunsEmptyFilter",t.dunsEmptyFilter),t.sloganEmptyFilter!=="any"&&l.set("sloganEmptyFilter",t.sloganEmptyFilter),t.logoUrlEmptyFilter!=="any"&&l.set("logoUrlEmptyFilter",t.logoUrlEmptyFilter),t.founderEmptyFilter!=="any"&&l.set("founderEmptyFilter",t.founderEmptyFilter),t.founderEmailEmptyFilter!=="any"&&l.set("founderEmailEmptyFilter",t.founderEmailEmptyFilter),t.founderPhoneEmptyFilter!=="any"&&l.set("founderPhoneEmptyFilter",t.founderPhoneEmptyFilter),t.openingHoursEmptyFilter!=="any"&&l.set("openingHoursEmptyFilter",t.openingHoursEmptyFilter),t.areaServedEmptyFilter!=="any"&&l.set("areaServedEmptyFilter",t.areaServedEmptyFilter),t.offersEmptyFilter!=="any"&&l.set("offersEmptyFilter",t.offersEmptyFilter),t.brandEmptyFilter!=="any"&&l.set("brandEmptyFilter",t.brandEmptyFilter),t.socialProfilesEmptyFilter!=="any"&&l.set("socialProfilesEmptyFilter",t.socialProfilesEmptyFilter),t.platformEmptyFilter!=="any"&&l.set("platformEmptyFilter",t.platformEmptyFilter),t.bookingOpsCrmSoftw
120areEmptyFilter!=="any"&&l.set("bookingOpsCrmSoftwareEmptyFilter",t.bookingOpsCrmSoftwareEmptyFilter),t.reputationChatSoftwareEmptyFilter!=="any"&&l.set("reputationChatSoftwareEmptyFilter",t.reputationChatSoftwareEmptyFilter),t.marketingEmailSoftwareEmptyFilter!=="any"&&l.set("marketingEmailSoftwareEmptyFilter",t.marketingEmailSoftwareEmptyFilter),t.adPixelsEmptyFilter!=="any"&&l.set("adPixelsEmptyFilter",t.adPixelsEmptyFilter),t.paymentFinancingSoftwareEmptyFilter!=="any"&&l.set("paymentFinancingSoftwareEmptyFilter",t.paymentFinancingSoftwareEmptyFilter),t.emailPrimaryMxValues.length>0&&l.set("emailPrimaryMxValues",JSON.stringify(t.emailPrimaryMxValues)),t.emailDomainMxValues.length>0&&l.set("emailDomainMxValues",JSON.stringify(t.emailDomainMxValues)),t.emailSecurityValues.length>0&&l.set("emailSecurityValues",JSON.stringify(t.emailSecurityValues)),t.addressSourceValues.length>0&&l.set("addressSourceValues",JSON.stringify(t.addressSourceValues)),t.emailPrimaryMxEmptyFilter!=="any"&&l.set("emailPrimaryMxEmptyFilter",t.emailPrimaryMxEmptyFilter),t.emailDomainMxEmptyFilter!=="any"&&l.set("emailDomainMxEmptyFilter",t.emailDomainMxEmptyFilter),t.emailSecurityEmptyFilter!=="any"&&l.set("emailSecurityEmptyFilter",t.emailSecurityEmptyFilter),t.addressSourceEmptyFilter!=="any"&&l.set("addressSourceEmptyFilter",t.addressSourceEmptyFilter),t.minNumLocations&&l.set("minNumLocations",t.minNumLocations),t.maxNumLocations&&l.set("maxNumLocations",t.maxNumLocations),t.minOpenPositions&&l.set("minOpenPositions",t.minOpenPositions),t.maxOpenPositions&&l.set("maxOpenPositions",t.maxOpenPositions),t.openPositionsEmptyFilter!=="any"&&l.set("openPositionsEmptyFilter",t.openPositionsEmptyFilter),t.minRatingValue&&l.set("minRatingValue",t.minRatingValue),t.maxRatingValue&&l.set("maxRatingValue",t.maxRatingValue),t.minReviewCount&&l.set("minReviewCount",t.minReviewCount),t.maxReviewCount&&l.set("maxReviewCount",t.maxReviewCount),l.set("orColumns",t.orColumns.join(",")),l.toString()}function Mn(t){const r=t.match(/^rel:(\d+)([hdwmy])$/);if(!r)return t;const s=r[1],l={h:"hour",d:"day",w:"week",m:"month",y:"year"}[r[2]]||r[2];return`Last ${s} ${l}${parseInt(s)!==1?"s":""}`}function gp(t,r){if(!t||t.length<=1)return[];const s=new URLSearchParams(t.substring(1)),i=new Set(r.map(d=>d.id)),l=["nkl","ukl","ckl","dkl","catkl"],c=new Set;for(const d of l){const u=s.get(d);if(u)for(const g of u.split(",")){const f=Number(g);!isNaN(f)&&!i.has(f)&&c.add(f)}}return Array.from(c)}const yp={"Newly Added":"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200","Phone Primary":"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200","Total Phones":"bg-sky-100 text-sky-800 dark:bg-sky-900 dark:text-sky-200","Email Primary":"bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200","Tier 1 Emails":"bg-violet-100 text-violet-800 dark:bg-violet-900 dark:text-violet-200","Tier 2 Emails":"bg-fuchsia-100 text-fuchsia-800 dark:bg-fuchsia-900 dark:text-fuchsia-200","Address Full":"bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200",Instagram:"bg-pink-100 text-pink-800 dark:bg-pink-900 dark:text-pink-200",LinkedIn:"bg-cyan-100 text-cyan-800 dark:bg-cyan-900 dark:text-cyan-200",Facebook:"bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-200",YouTube:"bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200",TikTok:"bg-teal-100 text-teal-800 dark:bg-teal-900 dark:text-teal-200","X (Twitter)":"bg-slate-200 text-slate-800 dark:bg-slate-700 dark:text-slate-200","Google Maps":"bg-lime-100 text-lime-800 dark:bg-lime-900 dark:text-lime-200",Yelp:"bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200",Pinterest:"bg-rose-100 text-rose-800 dark:bg-rose-900 dark:text-rose-200","Other Social":"bg-stone-200 text-stone-800 dark:bg-stone-700 dark:text-stone-200"},fp="bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200";function bp({options:t,selected:r,onApply:s}){const[i,l]=o.useState(!1),[c,d]=o.useState(r),u=r.length>0,g=f=>{d(C=>C.includes(f)?C.filter(F=>F!==f):[...C,f])};return e.jsxs(Ns,{open:i,onOpenChange:f=>{l(f),f&&d(r)},children:[e.jsx(Es,{asChild:!0,children:e.jsx("button",{className:`ml-1 p-0.5 rounded transition-colors ${u?"text-blue-600":"text-gray-400 hover:text-gray-600"}`,children:e.jsx(Ls,{className:"h-3 w-3"})})}),e.jsxs(ys,{className:"w-56 p-3",align:"start",children:[e.jsxs("div",{className:"text-xs font-medium mb-2",children:["Filter by ",Xa]}),e.jsx("div",{className:"flex flex-col gap-1.5 max-h-64 overflow-y-auto pr-1",children:t.map(f=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer text-xs",children:[e.jsx(Ws,{checked:c.includes(f),onCheckedChange:()=>g(f)}),f]},f))}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx("button",{className:"flex-1 text-xs px-2 py-1 rounded bg-blue-600 text-white hover:bg-blue-700",onClick:()=>{s(c),l(!1)},children:"Apply"}),e.jsx("button",{className:"flex-1 text-xs px-2 py-1 rounded border hover:bg-gray-50 dark:hover:bg-gray-800",onClick:()=>{s([]),d([]),l(!1)},children:"Clear"})]})]})]})}function wp({selected:t,onApply:r}){const[s,i]=o.useState(!1),[l,c]=o.useState(t),[d,u]=o.useState(""),g=t.length>0,{data:f=[]}
120=Qe({queryKey:["/api/leads/other/schema-types"]}),C=f.filter(w=>w.toLowerCase().includes(d.toLowerCase())),F=w=>{c(j=>j.includes(w)?j.filter(E=>E!==w):[...j,w])};return e.jsxs(Ns,{open:s,onOpenChange:w=>{i(w),w&&(c(t),u(""))},children:[e.jsx(Es,{asChild:!0,children:e.jsx("button",{className:`ml-1 p-0.5 rounded transition-colors ${g?"text-blue-600":"text-gray-400 hover:text-gray-600"}`,children:e.jsx(Ls,{className:"h-3 w-3"})})}),e.jsxs(ys,{className:"w-64 p-3",align:"start",children:[e.jsx("div",{className:"text-xs font-medium mb-2",children:"Filter by Website Schema"}),e.jsx("input",{type:"text",placeholder:"Search schemas...",value:d,onChange:w=>u(w.target.value),className:"w-full text-xs px-2 py-1.5 mb-2 border rounded bg-white dark:bg-gray-900 dark:border-gray-700 outline-none focus:ring-1 focus:ring-blue-500"}),e.jsx("div",{className:"flex flex-col gap-1 max-h-48 overflow-y-auto",children:C.length>0?C.map(w=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer text-xs",children:[e.jsx(Ws,{checked:l.includes(w),onCheckedChange:()=>F(w)}),w]},w)):e.jsx("span",{className:"text-xs text-gray-400",children:"No matching schemas"})}),l.length>0&&e.jsxs("div",{className:"text-[10px] text-gray-500 mt-1.5",children:[l.length," selected"]}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx("button",{className:"flex-1 text-xs px-2 py-1 rounded bg-blue-600 text-white hover:bg-blue-700",onClick:()=>{r(l),i(!1)},children:"Apply"}),e.jsx("button",{className:"flex-1 text-xs px-2 py-1 rounded border hover:bg-gray-50 dark:hover:bg-gray-800",onClick:()=>{r([]),c([]),i(!1)},children:"Clear"})]})]})]})}function Br({field:t,label:r,valuesKey:s,emptyKey:i,filters:l,onApply:c}){const[d,u]=o.useState(!1),g=l[s],f=l[i],[C,F]=o.useState(g),[w,j]=o.useState(f),[E,A]=o.useState(""),T=g.length>0||f!=="any",{data:J=[]}=Qe({queryKey:[`/api/leads/other/field-values?field=${t}`]}),p=J.filter(y=>y.toLowerCase().includes(E.toLowerCase())),v=y=>{F(k=>k.includes(y)?k.filter(a=>a!==y):[...k,y])};return e.jsxs(Ns,{open:d,onOpenChange:y=>{u(y),y&&(F(g),j(f),A(""))},children:[e.jsx(Es,{asChild:!0,children:e.jsx("button",{className:`ml-1 p-0.5 rounded transition-colors ${T?"text-blue-600":"text-gray-400 hover:text-gray-600"}`,children:e.jsx(Ls,{className:"h-3 w-3"})})}),e.jsxs(ys,{className:"w-64 p-3",align:"start",children:[e.jsxs("div",{className:"text-xs font-medium mb-2",children:["Filter by ",r]}),e.jsx("input",{type:"text",placeholder:"Search values...",value:E,onChange:y=>A(y.target.value),className:"w-full text-xs px-2 py-1.5 mb-2 border rounded bg-white dark:bg-gray-900 dark:border-gray-700 outline-none focus:ring-1 focus:ring-blue-500"}),e.jsx("div",{className:"flex flex-col gap-1 max-h-48 overflow-y-auto",children:p.length>0?p.map(y=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer text-xs",children:[e.jsx(Ws,{checked:C.includes(y),onCheckedChange:()=>v(y)}),y]},y)):e.jsx("span",{className:"text-xs text-gray-400",children:"No matching values"})}),C.length>0&&e.jsxs("div",{className:"text-[10px] text-gray-500 mt-1.5",children:[C.length," selected"]}),e.jsx(Cn,{value:w,onChange:j,label:"Empty values"}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx("button",{className:"flex-1 text-xs px-2 py-1 rounded bg-blue-600 text-white hover:bg-blue-700",onClick:()=>{c({[s]:C,[i]:w}),u(!1)},children:"Apply"}),e.jsx("button",{className:"flex-1 text-xs px-2 py-1 rounded border hover:bg-gray-50 dark:hover:bg-gray-800",onClick:()=>{c({[s]:[],[i]:"any"}),F([]),j("any"),u(!1)},children:"Clear"})]})]})]})}function Jr({column:t,label:r,filters:s,onApply:i}){const[l,c]=o.useState(!1),d=o.useCallback(()=>{switch(t){case"wNumLocations":return{min:s.minNumLocations,max:s.maxNumLocations};case"wOpenPositions":return{min:s.minOpenPositions,max:s.maxOpenPositions};case"wRatingValue":return{min:s.minRatingValue,max:s.maxRatingValue};case"wReviewCount":return{min:s.minReviewCount,max:s.maxReviewCount};default:return{min:"",max:""}}},[t,s]),[u,g]=o.useState(d),f=t==="wOpenPositions",C=o.useCallback(()=>t==="wOpenPositions"?s.openPositionsEmptyFilter:"any",[t,s]),[F,w]=o.useState(C);o.useEffect(()=>{l&&(g(d()),w(C()))},[l,d,C]);const j=(()=>{switch(t){case"wNumLocations":return!!s.minNumLocations||!!s.maxNumLocations;case"wOpenPositions":return!!s.minOpenPositions||!!s.maxOpenPositions||s.openPositionsEmptyFilter!=="any";case"wRatingValue":return!!s.minRatingValue||!!s.maxRatingValue;case"wReviewCount":return!!s.minReviewCount||!!s.maxReviewCount;default:return!1}})(),E=()=>{const T={};switch(t){case"wNumLocations":T.minNumLocations=u.min,T.maxNumLocations=u.max;break;case"wOpenPositions":T.minOpenPositions=u.min,T.maxOpenPositions=u.max,T.openPositionsEmptyFilter=F;break;case"wRatingValue":T.minRatingValue=u.min,T.maxRatingValue=u.max;break;case"wReviewCount":T.minReviewCount=u.min,T.maxReviewCount=u.max;break}i(T),c(!1)},A=t==="wRatingValue";return e.jsxs(Ns,{open:l,onOpenChange:c,children:[e.jsx(Es,{asChild:!0,children:e.jsx("button",{className:`ml-1 p-0.5 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors ${j?"text-blue-600":"text-gray-400 opacity-50"}`,children:e.jsx(Ls,{className:"h-3 w-3"})})}),e.jsx(ys,{className:"w-56 p-3",align:"start",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-xs font-medium",children:[r," Range"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ee,{type:"number",min:"0",max:A?"5":void 0,step:A?"0.1":"1",placeholder:"Min",value:u.min,onChange:T=>g(J=>({...J,min:T.target.value})),className:"h-8 text-xs w-20"}),e.jsx("span",{className:"text-xs text-gray-400",children:"to"}),e.jsx(Ee,{type:"number",min:"0",max:A?"5":void 0,step:A?"0.1":"1",placeholder:"Max",value:u.max,onChange:T=>g(J=>({...J,max:T.target.value})),className:"h-8 text-xs w-20"})]}),f&&e.jsx(Cn,{value:F,onChange:w,label:"Empty values"}),e.jsxs("div",{className:"flex items-center justify-between pt-1",children:[e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 text-xs text-gray-500",onClick:()=>{g({min:"",max:""}),w("any")},children:"Clear"}),e.jsx(N,{size:"sm",className:"h-7 text-xs bg-blue-600 hover:bg-blue-700 text-white",onClick:E,children:"Apply"})]})]})})]})}function wt({column:t,label:r,filters:s,onApply:i,orColumns:l,columnKey:c,supportsOrGroup:d=!0}){const[u,g]=o.useState(!1),f=o.useCallback(()=>{switch(t){case"wAddressState":return{include:[...s.stateInclude],exclude:[...s.stateExclude]};case"wAddressCity":return{include:[...s.cityInclude],exclude:[...s.cityExclude]};case"wAddressZip":return{include:[...s.zipInclude],exclude:[...s.zipExclude]};case"wAddressStreet":return{include:[...s.streetInclude],exclude:[...s.streetExclude]};case"wEmailPrimary":return{include:[...s.emailPrimaryInclude],exclude:[...s.emailPrimaryExclude]};case"wEmailTier1":return{include:[...s.emailTier1Include],exclude:[...s.emailTier1Exclude]};case"wEmailTier2":return{include:[...s.emailTier2Include],exclude:[...s.emailTier2Exclude]};case"wEmailTier3":return{include:[...s.emailTier3Include],exclude:[...s.emailTier3Exclude]};case"wEmailTier4":return{include:[...s.emailTier4Include],exclude:[...s.emailTier4Exclude]};case"wEmailTier5":return{include:[...s.emailTier5Include],exclude:[...s.emailTier5Exclude]};case"wEmailTier6":return{include:[...s.emailTier6Include],exclude:[...s.emailTier6Exclude]};case"wPhonePrimary":return{include:[...s.phonePrimaryInclude],exclude:[...s.phonePrimaryExclude]};case"wPhoneTotal":return{include:[...s.phoneTotalInclude],exclude:[...s.phoneTotalExclude]};case"wEmployeeCount":return{include:[...s.employeeCountInclude],exclude:[...s.employeeCountExclude]};case"wFoundingDate":return{include:[...s.foundingDateInclude],exclude:[...s.foundingDateExclude]};case"wIsChain":return{include:[...s.isChainInclude],exclude:[...s.isChainExclude]};case"wPriceRange":return{include:[...s.priceRangeInclude],exclude:[...s.priceRangeExclude]};case"wLegalName":return{include:[...s.legalNameInclude],exclude:[...s.legalNameExclude]};case"wIndustryNaics":return{include:[...s.industryNaicsInclude],exclude:[...s.industryNaicsExclude]};case"wDuns":return{include:[...s.dunsInclude],exclude:[...s.dunsExclude]};case"wSlogan":return{include:[...s.sloganInclude],exclude:[...s.sloganExclude]};case"wLogoUrl":return{include:[...s.logoUrlInclude],exclude:[...s.logoUrlE
120xclude]};case"wFounder":return{include:[...s.founderInclude],exclude:[...s.founderExclude]};case"wFounderEmail":return{include:[...s.founderEmailInclude],exclude:[...s.founderEmailExclude]};case"wFounderPhone":return{include:[...s.founderPhoneInclude],exclude:[...s.founderPhoneExclude]};case"wOpeningHours":return{include:[...s.openingHoursInclude],exclude:[...s.openingHoursExclude]};case"wAreaServed":return{include:[...s.areaServedInclude],exclude:[...s.areaServedExclude]};case"wOffers":return{include:[...s.offersInclude],exclude:[...s.offersExclude]};case"wBrand":return{include:[...s.brandInclude],exclude:[...s.brandExclude]};case"wSocialProfiles":return{include:[...s.socialProfilesInclude],exclude:[...s.socialProfilesExclude]};case"wPlatform":return{include:[...s.platformInclude],exclude:[...s.platformExclude]};case"wBookingOpsCrmSoftware":return{include:[...s.bookingOpsCrmSoftwareInclude],exclude:[...s.bookingOpsCrmSoftwareExclude]};case"wReputationChatSoftware":return{include:[...s.reputationChatSoftwareInclude],exclude:[...s.reputationChatSoftwareExclude]};case"wMarketingEmailSoftware":return{include:[...s.marketingEmailSoftwareInclude],exclude:[...s.marketingEmailSoftwareExclude]};case"wAdPixels":return{include:[...s.adPixelsInclude],exclude:[...s.adPixelsExclude]};case"wPaymentFinancingSoftware":return{include:[...s.paymentFinancingSoftwareInclude],exclude:[...s.paymentFinancingSoftwareExclude]};default:return{include:[],exclude:[]}}},[t,s]),C=Oo[t],F=C?s[C]:"any",[w,j]=o.useState(F),[E,A]=o.useState(f),[T,J]=o.useState(""),[p,v]=o.useState(""),[y,k]=o.useState(""),[a,q]=o.useState(""),[$,X]=o.useState(l.includes(c)),B=t==="wEmailPrimary"||t==="wEmailTier1"||t==="wEmailTier2"||t==="wEmailTier3"||t==="wEmailTier4"||t==="wEmailTier5"||t==="wEmailTier6"||t==="wPhonePrimary"||t==="wPhoneTotal"||t==="wEmployeeCount"||t==="wFoundingDate"||t==="wIsChain"||t==="wPriceRange"||t==="wLegalName"||t==="wIndustryNaics"||t==="wDuns"||t==="wSlogan"||t==="wLogoUrl"||t==="wFounder"||t==="wFounderEmail"||t==="wFounderPhone"||t==="wOpeningHours"||t==="wAreaServed"||t==="wOffers"||t==="wBrand"||t==="wSocialProfiles"||t==="wPlatform"||t==="wBookingOpsCrmSoftware"||t==="wReputationChatSoftware"||t==="wMarketingEmailSoftware"||t==="wAdPixels"||t==="wPaymentFinancingSoftware",[K,ae]=o.useState("contains"),[Y,fe]=o.useState("contains"),U=O=>O.replace(/\*/g,"").length,te=(O,I)=>B&&I!=="contains"?{v:O,m:I}:O,ne=(O,I)=>O.some(re=>ta(re,I));o.useEffect(()=>{u&&(A(f()),J(""),v(""),k(""),q(""),ae("contains"),fe("contains"),X(l.includes(c)),C&&j(s[C]))},[u,f]);const Q=C?s[C]!=="any":!1,V=(()=>{switch(t){case"wAddressState":return s.stateInclude.length>0||s.stateExclude.length>0||Q;case"wAddressCity":return s.cityInclude.length>0||s.cityExclude.length>0||Q;case"wAddressZip":return s.zipInclude.length>0||s.zipExclude.length>0||Q;case"wAddressStreet":return s.streetInclude.length>0||s.streetExclude.length>0||Q;case"wEmailPrimary":return s.emailPrimaryInclude.length>0||s.emailPrimaryExclude.length>0||Q;case"wEmailTier1":return s.emailTier1Include.length>0||s.emailTier1Exclude.length>0||Q;case"wEmailTier2":return s.emailTier2Include.length>0||s.emailTier2Exclude.length>0||Q;case"wEmailTier3":return s.emailTier3Include.length>0||s.emailTier3Exclude.length>0||Q;case"wEmailTier4":return s.emailTier4Include.length>0||s.emailTier4Exclude.length>0||Q;case"wEmailTier5":return s.emailTier5Include.length>0||s.emailTier5Exclude.length>0||Q;case"wEmailTier6":return s.emailTier6Include.length>0||s.emailTier6Exclude.length>0||Q;case"wPhonePrimary":return s.phonePrimaryInclude.length>0||s.phonePrimaryExclude.length>0||Q;case"wPhoneTotal":return s.phoneTotalInclude.length>0||s.phoneTotalExclude.length>0||Q;case"wEmployeeCount":return s.employeeCountInclude.length>0||s.employeeCountExclude.length>0||Q;case"wFoundingDate":return s.foundingDateInclude.length>0||s.foundingDateExclude.length>0||Q;case"wIsChain":return s.isChainInclude.length>0||s.isChainExclude.length>0||Q;case"wPriceRange":return s.priceRangeInclude.length>0||s.priceRangeExclude.length>0||Q;case"wLegalName":return s.legalNameInclude.length>0||s.legalNameExclude.length>0||Q;case"wIndustryNaics":return s.industryNaicsInclude.length>0||s.industryNaicsExclude.length>0||Q;case"wDuns":return s.dunsInclude.length>0||s.dunsExclude.length>0||Q;case"wSlogan":return s.sloganInclude.length>0||s.sloganExclude.length>0||Q;case"wLogoUrl":return s.logoUrlInclude.length>
1200||s.logoUrlExclude.length>0||Q;case"wFounder":return s.founderInclude.length>0||s.founderExclude.length>0||Q;case"wFounderEmail":return s.founderEmailInclude.length>0||s.founderEmailExclude.length>0||Q;case"wFounderPhone":return s.founderPhoneInclude.length>0||s.founderPhoneExclude.length>0||Q;case"wOpeningHours":return s.openingHoursInclude.length>0||s.openingHoursExclude.length>0||Q;case"wAreaServed":return s.areaServedInclude.length>0||s.areaServedExclude.length>0||Q;case"wOffers":return s.offersInclude.length>0||s.offersExclude.length>0||Q;case"wBrand":return s.brandInclude.length>0||s.brandExclude.length>0||Q;case"wSocialProfiles":return s.socialProfilesInclude.length>0||s.socialProfilesExclude.length>0||Q;case"wPlatform":return s.platformInclude.length>0||s.platformExclude.length>0||Q;case"wBookingOpsCrmSoftware":return s.bookingOpsCrmSoftwareInclude.length>0||s.bookingOpsCrmSoftwareExclude.length>0||Q;case"wReputationChatSoftware":return s.reputationChatSoftwareInclude.length>0||s.reputationChatSoftwareExclude.length>0||Q;case"wMarketingEmailSoftware":return s.marketingEmailSoftwareInclude.length>0||s.marketingEmailSoftwareExclude.length>0||Q;case"wAdPixels":return s.adPixelsInclude.length>0||s.adPixelsExclude.length>0||Q;case"wPaymentFinancingSoftware":return s.paymentFinancingSoftwareInclude.length>0||s.paymentFinancingSoftwareExclude.length>0||Q;default:return!1}})(),R=t==="wAddressState",pe=O=>{const I=O.trim();if(!I){J("");return}if(!R&&U(I)<3){k("Include terms must be at least 3 characters (excluding *)");return}k("");const re=te(I,K);ne(E.include,re)||A(Pe=>({...Pe,include:[...Pe.include,re]})),J("")},Se=O=>{const I=O.trim();if(!I){v("");return}if(!R&&U(I)<2){q("Exclude terms must be at least 2 characters (excluding *)");return}q("");const re=te(I,Y);ne(E.exclude,re)||A(Pe=>({...Pe,exclude:[...Pe.exclude,re]})),v("")},Ze=O=>{A(I=>({...I,include:I.include.filter(re=>!ta(re,O))}))},Me=O=>{A(I=>({...I,exclude:I.exclude.filter(re=>!ta(re,O))}))},He=()=>{let O=[...E.include],I=[...E.exclude];const re=T.trim();if(re&&!R){if(U(re)<3){k("Include terms must be at least 3 characters (excluding *)");return}const Le=te(re,K);O.some(ve=>ta(ve,Le))||O.push(Le)}const Pe=p.trim();if(Pe&&!R){if(U(Pe)<2){q("Exclude terms must be at least 2 characters (excluding *)");return}const Le=te(Pe,Y);I.some(ve=>ta(ve,Le))||I.push(Le)}const tt=B?[]:O,$e=B?[]:I,W={};switch(t){case"wAddressState":W.stateInclude=tt,W.stateExclude=$e;break;case"wAddressCity":W.cityInclude=tt,W.cityExclude=$e;break;case"wAddressZip":W.zipInclude=tt,W.zipExclude=$e;break;case"wAddressStreet":W.streetInclude=tt,W.streetExclude=$e;break;case"wEmailPrimary":W.emailPrimaryInclude=O,W.emailPrimaryExclude=I;break;case"wEmailTier1":W.emailTier1Include=O,W.emailTier1Exclude=I;break;case"wEmailTier2":W.emailTier2Include=O,W.emailTier2Exclude=I;break;case"wEmailTier3":W.emailTier3Include=O,W.emailTier3Exclude=I;break;case"wEmailTier4":W.emailTier4Include=O,W.emailTier4Exclude=I;break;case"wEmailTier5":W.emailTier5Include=O,W.emailTier5Exclude=I;break;case"wEmailTier6":W.emailTier6Include=O,W.emailTier6Exclude=I;break;case"wPhonePrimary":W.phonePrimaryInclude=O,W.phonePrimaryExclude=I;break;case"wPhoneTotal":W.phoneTotalInclude=O,W.phoneTotalExclude=I;break;case"wEmployeeCount":W.employeeCountInclude=O,W.employeeCountExclude=I;break;case"wFoundingDate":W.foundingDateInclude=O,W.foundingDateExclude=I;break;case"wIsChain":W.isChainInclude=O,W.isChainExclude=I;break;case"wPriceRange":W.priceRangeInclude=O,W.priceRangeExclude=I;break;case"wLegalName":W.legalNameInclude=O,W.legalNameExclude=I;break;case"wIndustryNaics":W.industryNaicsInclude=O,W.industryNaicsExclude=I;break;case"wDuns":W.dunsInclude=O,W.dunsExclude=I;break;case"wSlogan":W.sloganInclude=O,W.sloganExclude=I;break;case"wLogoUrl":W.logoUrlInclude=O,W.logoUrlExclude=I;break;case"wFounder":W.founderInclude=O,W.founderExclude=I;break;case"wFounderEmail":W.founderEmailInclude=O,W.founderEmailExclude=I;break;case"wFounderPhone":W.founderPhoneInclude=O,W.founderPhoneExclude=I;break;case"wOpeningHours":W.openingHoursInclude=O,W.openingHoursExclude=I;break;case"wAreaServed":W.areaServedInclude=O,W.areaServedExclude=I;break;case"wOffers":W.offersInclude=O,W.offersExclude=I;break;case"wBrand":W.brandInclude=O,W.brandExclude=I;break;case"wSocialProfiles":W.socialProfilesInclude=O,W.socialProfilesExclude=I;break;case"wPlatform":W.platformInclude=O,W.platformExclude=I;break;
120case"wBookingOpsCrmSoftware":W.bookingOpsCrmSoftwareInclude=O,W.bookingOpsCrmSoftwareExclude=I;break;case"wReputationChatSoftware":W.reputationChatSoftwareInclude=O,W.reputationChatSoftwareExclude=I;break;case"wMarketingEmailSoftware":W.marketingEmailSoftwareInclude=O,W.marketingEmailSoftwareExclude=I;break;case"wAdPixels":W.adPixelsInclude=O,W.adPixelsExclude=I;break;case"wPaymentFinancingSoftware":W.paymentFinancingSoftwareInclude=O,W.paymentFinancingSoftwareExclude=I;break}C&&(W[C]=w),d&&($&&!l.includes(c)?W.orColumns=[...l,c]:!$&&l.includes(c)&&(W.orColumns=l.filter(Le=>Le!==c))),i(W),g(!1)},ee=()=>{A({include:[],exclude:[]}),X(!1),j("any")};return e.jsxs(Ns,{open:u,onOpenChange:g,children:[e.jsx(Es,{asChild:!0,children:e.jsx("button",{className:`ml-1 p-0.5 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors ${V?"text-blue-600":"text-gray-400 opacity-50"}`,children:e.jsx(Ls,{className:"h-3 w-3"})})}),e.jsx(ys,{className:"w-72 p-3",align:"start",children:e.jsxs("div",{className:"space-y-3",children:[d&&e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx("input",{type:"checkbox",id:`or-group-${c}`,checked:$,onChange:O=>X(O.target.checked),className:"rounded border-gray-300"}),e.jsx("label",{htmlFor:`or-group-${c}`,className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:"Include in OR group search"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-semibold text-blue-700 flex items-center gap-1",children:[e.jsx(ns,{className:"h-3 w-3"})," Include ",r]}),R?e.jsxs(Ns,{children:[e.jsx(Es,{asChild:!0,children:e.jsxs("button",{type:"button",className:"h-7 w-full text-xs flex items-center justify-between rounded-md border border-input bg-transparent px-2 hover:bg-accent hover:text-accent-foreground",children:[e.jsx("span",{className:E.include.length===0?"text-muted-foreground":"",children:"Add state to include..."}),e.jsx(sr,{className:"h-3 w-3 opacity-50"})]})}),e.jsx(ys,{className:"w-56 p-0",align:"start",children:e.jsx("div",{className:"max-h-60 overflow-y-auto py-1",children:dl.map(O=>{const I=E.include.includes(O);return e.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1.5 text-xs text-left hover:bg-accent hover:text-accent-foreground",onClick:()=>{A(I?re=>({...re,include:re.include.filter(Pe=>Pe!==O)}):re=>({...re,include:[...re.include,O]}))},children:[e.jsx(sa,{className:`h-3 w-3 ${I?"opacity-100":"opacity-0"}`}),e.jsx("span",{children:O})]},O)})})})]}):e.jsxs("div",{className:"flex gap-1",children:[B&&e.jsxs("select",{value:K,onChange:O=>ae(O.target.value),className:"h-7 text-xs rounded-md border border-input bg-transparent px-1","aria-label":"Include match mode","data-testid":`select-include-mode-${c}`,children:[e.jsx("option",{value:"contains",children:"contains"}),e.jsx("option",{value:"starts",children:"starts with"}),e.jsx("option",{value:"ends",children:"ends with"})]}),e.jsx(Ee,{placeholder:`Add ${r.toLowerCase()}...`,value:T,onChange:O=>{J(O.target.value),k("")},onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),pe(T))},className:"h-7 text-xs flex-1"}),e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>pe(T),children:e.jsx(ns,{className:"h-3 w-3"})})]}),E.include.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:E.include.map(O=>{const I=`${fa(O)}|${dn(O)}`;return e.jsxs(ie,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-blue-100 text-blue-800 hover:bg-blue-200 cursor-pointer",onClick:()=>Ze(O),title:je(O),children:[B?lr(O):fa(O)," ",e.jsx(Ut,{className:"h-2.5 w-2.5 ml-0.5"})]},I)})}),y&&e.jsx("p",{className:"text-[10px] text-red-500",children:y})]}),e.jsxs("div",{className:"border-t pt-2 space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-semibold text-red-700 flex items-center gap-1",children:[e.jsx(wn,{className:"h-3 w-3"})," Exclude ",r]}),R?e.jsxs(Ns,{children:[e.jsx(Es,{asChild:!0,children:e.jsxs("button",{type:"button",className:"h-7 w-full text-xs flex items-center justify-between rounded-md border border-input bg-transparent px-2 hover:bg-accent hover:text-accent-foreground",children:[e.jsx("span",{className:E.exclude.length===0?"text-muted-foreground":"",children:"Add state to exclude..."}),e.jsx(sr,{className:"h-3 w-3 opacity-50"})]})}),e.jsx(ys,{className:"w-56 p-0",align:"start",children:e.jsx("div",{className:"max-h-60 overflow-y-auto py-1",children:dl.map(O=>{const I=E.exclude.includes(O);return e.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1.5 text-xs text-left hover:bg-accent hover:text-accent-foreground",onClick:()=>{A(I?re=>
120({...re,exclude:re.exclude.filter(Pe=>Pe!==O)}):re=>({...re,exclude:[...re.exclude,O]}))},children:[e.jsx(sa,{className:`h-3 w-3 ${I?"opacity-100":"opacity-0"}`}),e.jsx("span",{children:O})]},O)})})})]}):e.jsxs("div",{className:"flex gap-1",children:[B&&e.jsxs("select",{value:Y,onChange:O=>fe(O.target.value),className:"h-7 text-xs rounded-md border border-input bg-transparent px-1","aria-label":"Exclude match mode","data-testid":`select-exclude-mode-${c}`,children:[e.jsx("option",{value:"contains",children:"contains"}),e.jsx("option",{value:"starts",children:"starts with"}),e.jsx("option",{value:"ends",children:"ends with"})]}),e.jsx(Ee,{placeholder:`Add ${r.toLowerCase()} to exclude...`,value:p,onChange:O=>{v(O.target.value),q("")},onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),Se(p))},className:"h-7 text-xs flex-1"}),e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>Se(p),children:e.jsx(ns,{className:"h-3 w-3"})})]}),E.exclude.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:E.exclude.map(O=>{const I=`${fa(O)}|${dn(O)}`;return e.jsxs(ie,{variant:"destructive",className:"text-[10px] px-1.5 py-0 cursor-pointer",onClick:()=>Me(O),title:je(O),children:[B?lr(O):fa(O)," ",e.jsx(Ut,{className:"h-2.5 w-2.5 ml-0.5"})]},I)})}),a&&e.jsx("p",{className:"text-[10px] text-red-500",children:a})]}),C&&e.jsx(Cn,{value:w,onChange:j,label:`${r} empty values`}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t",children:[e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 text-xs text-gray-500",onClick:ee,children:"Clear"}),e.jsx(N,{size:"sm",className:"h-7 text-xs bg-blue-600 hover:bg-blue-700 text-white",onClick:He,children:"Apply"})]})]})})]})}function vp({filters:t,onApply:r}){const[s,i]=o.useState(!1),l=t.redirectFilter!=="";return e.jsxs(Ns,{open:s,onOpenChange:i,children:[e.jsx(Es,{asChild:!0,children:e.jsx("button",{className:`ml-1 p-0.5 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors ${l?"text-blue-600":"text-gray-400 opacity-50"}`,children:e.jsx(Ls,{className:"h-3 w-3"})})}),e.jsx(ys,{className:"w-44 p-3",align:"start",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-semibold",children:"Filter by Redirect"}),e.jsx("div",{className:"flex flex-col gap-1",children:[{value:"",label:"All"},{value:"yes",label:"Yes"},{value:"no",label:"No"}].map(c=>e.jsx("button",{className:`text-left text-xs px-2 py-1.5 rounded transition-colors ${t.redirectFilter===c.value?"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200 font-medium":"hover:bg-gray-100 dark:hover:bg-gray-800"}`,onClick:()=>{r({redirectFilter:c.value}),i(!1)},children:c.label},c.value))})]})})]})}function hr({column:t,label:r,filters:s,keywordLists:i,onApply:l,orColumns:c,columnKey:d}){const[u,g]=o.useState(!1),f=o.useMemo(()=>i.filter(R=>R.type==="positive"),[i]),C=o.useMemo(()=>i.filter(R=>R.type==="negative"),[i]),F=o.useCallback(()=>{let R=[],pe=[],Se=[];switch(t){case"wCompanyName":R=[...s.nameIncludeTerms],pe=[...s.nameExcludeTerms],Se=[...s.nameKeywordListIds];break;case"wOgrequestedUrl":R=[...s.urlIncludeTerms],pe=[...s.urlExcludeTerms],Se=[...s.urlKeywordListIds];break;case"wSimpleCrawledUrl":R=[...s.crawledUrlIncludeTerms],pe=[...s.crawledUrlExcludeTerms],Se=[...s.crawledUrlKeywordListIds];break;case"wProfileDescriptionShort":R=[...s.descriptionIncludeTerms],pe=[...s.descriptionExcludeTerms],Se=[...s.descriptionKeywordListIds];break;case"aiCategoryEstimation":R=[...s.categoryIncludeTerms],pe=[...s.categoryExcludeTerms],Se=[...s.categoryKeywordListIds];break}return{activeListIds:Se,includeTerms:R,excludeTerms:pe}},[t,s]),w=Oo[t],j=w?s[w]:"any",[E,A]=o.useState(j),[T,J]=o.useState(F),[p,v]=o.useState(""),[y,k]=o.useState(""),[a,q]=o.useState(""),[$,X]=o.useState(""),[B,K]=o.useState(c.includes(d)),ae=R=>R.replace(/\*/g,"").length;o.useEffect(()=>{u&&(J(F()),v(""),k(""),q(""),X(""),K(c.includes(d)),w&&A(s[w]))},[u,F]);const Y=w?s[w]!=="any":!1,fe=(()=>{const R=xp(s,t);switch(t){case"wCompanyName":return R.length>0||s.nameIncludeTerms.length>0||s.nameExcludeTerms.length>0;case"wOgrequestedUrl":return R.length>0||s.urlIncludeTerms.length>0||s.urlExcludeTerms.length>0;case"wSimpleCrawledUrl":return R.length>0||s.crawledUrlIncludeTerms.length>0||s.crawledUrlExcludeTerms.length>0;case"wProfileDescriptionShort":return R.length>0||s.descriptionIncludeTerms.length>0||s.descriptionExcludeTerms.length>0||Y;case"aiCategoryEstimation":return R.length>0||s.categoryIncludeTerms.length>0||s.categoryExcludeTerms.length>0;default:return!1}})(),U=R=>{J(pe=>{const Se=pe.activeListIds.includes(R);return{...pe,activeListIds:Se?pe.activeListIds.filter(Ze=>Ze!==R):[...pe.activeListIds,R]}})},te=R=>{const pe=R.trim();if(!pe){v("");return}if(ae(pe)<3){q("Include terms must be at least 3 characters (excluding *)");return}q(""),T.includeTerms.includes(pe)||J(Se=>({...Se,includeTerms:[...Se.includeTerms,pe]})),v("")},ne=R=>{const pe=R.trim();if(!pe){k("");return}if(ae(pe)<2){X("Exclude terms must be at least 2 characters (excluding *)");return}X(""),T.excludeTerms.includes(pe)||J(Se=>({...Se,excludeTerms:[...Se.excludeTerms,pe]})),k("")},Q=()=>{let R=[...T.includeTerms],pe=[...T.excludeTerms];const Se=p.trim();if(Se){if(ae(Se)<3){q("Include terms must be at least 3 characters (excluding *)");return}R.includes(Se)||R.push(Se)}const Ze=y.trim();if(Ze){if(ae(Ze)<2){X("Exclude terms must be at least 2 characters (excluding *)");return}pe.includes(Ze)||pe.push(Ze)}const Me={};switch(t){case"wCompanyName":Me.nameKeywordListIds=T.activeListIds,Me.nameIncludeTerms=R,Me.nameExcludeTerms=pe;break;case"wOgrequestedUrl":Me.urlKeywordListIds=T.activeListIds,Me.urlIncludeTerms=R,Me.urlExcludeTerms=pe;break;case"wSimpleCrawledUrl":Me.crawledUrlKeywordListIds=T.activeListIds,Me.crawledUrlIncludeTerms=R,Me.crawledUrlExcludeTerms=pe;break;case"wProfileDescriptionShort":Me.descriptionKeywordListIds=T.activeListIds,Me.descriptionIncludeTerms=R,Me.descriptionExcludeTerms=pe;break;case"aiCategoryEstimation":Me.categoryKeywordListIds=T.activeListIds,Me.categoryIncludeTerms=R,Me.categoryExcludeTerms=pe;break}w&&(Me[w]=E),B&&!c.includes(d)?Me.orColumns=[...c,d]:!B&&c.includes(d)&&(Me.orColumns=c.filter(He=>He!==d)),l(Me),g(!1)},V=()=>{J({activeListIds:[],includeTerms:[],excludeTerms:[]}),K(!1),A("any")};return e.jsxs(Ns,{open:u,onOpenChange:g,children:[e.jsx(Es,{asChild:!0,children:e.jsx("button",{className:`ml-1 p-0.5 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors ${fe?"text-blue-600":"text-gray-400 opacity-50"}`,children:e.jsx(Ls,{className:"h-3 w-3"})})}),e.jsx(ys,{className:"w-80 p-0",align:"start",children:e.jsxs("div",{className:"space-y-3 max-h-[60vh] overflow-y-auto p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx("input",{type:"checkbox",id:`or-group-${d}`,checked:B,onChange:R=>K(R.target.checked),className:"rounded border-gray-300"}),e.jsx("label",{htmlFor:`or-group-${d}`,className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:"Include in OR group search"})]}),f.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-semibold text-blue-700 flex items-center gap-1",children:[e.jsx(Kt,{className:"h-3 w-3"})," Positive Keyword Lists"]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:f.map(R=>e.jsxs(ie,{variant:T.activeListIds.includes(R.id)?"default":"outline",className:`curs
120or-pointer text-[10px] px-1.5 py-0.5 ${T.activeListIds.includes(R.id)?"bg-blue-600 hover:bg-blue-700":""}`,onClick:()=>U(R.id),children:["+ ",R.name,R.isDefault&&e.jsx("span",{className:"ml-0.5 opacity-60",children:"(default)"})]},R.id))})]}),C.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-semibold text-red-700 flex items-center gap-1",children:[e.jsx(Kt,{className:"h-3 w-3"})," Negative Keyword Lists"]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:C.map(R=>e.jsxs(ie,{variant:T.activeListIds.includes(R.id)?"destructive":"outline",className:"cursor-pointer text-[10px] px-1.5 py-0.5",onClick:()=>U(R.id),children:["- ",R.name,R.isDefault&&e.jsx("span",{className:"ml-0.5 opacity-60",children:"(default)"})]},R.id))})]}),e.jsxs("div",{className:"border-t pt-2 space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-semibold text-blue-700 flex items-center gap-1",children:[e.jsx(ns,{className:"h-3 w-3"})," Include Search Terms"]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(Ee,{placeholder:`Add term to include in ${r}...`,value:p,onChange:R=>{v(R.target.value),q("")},onKeyDown:R=>{R.key==="Enter"&&(R.preventDefault(),te(p))},className:"h-7 text-xs flex-1"}),e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>te(p),children:e.jsx(ns,{className:"h-3 w-3"})})]}),T.includeTerms.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:T.includeTerms.map(R=>e.jsxs(ie,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-blue-100 text-blue-800 hover:bg-blue-200 cursor-pointer",onClick:()=>J(pe=>({...pe,includeTerms:pe.includeTerms.filter(Se=>Se!==R)})),children:[R," ",e.jsx(Ut,{className:"h-2.5 w-2.5 ml-0.5"})]},R))}),a&&e.jsx("p",{className:"text-[10px] text-red-500",children:a})]}),e.jsxs("div",{className:"border-t pt-2 space-y-1.5",children:[e.jsxs("label",{className:"text-xs font-semibold text-red-700 flex items-center gap-1",children:[e.jsx(wn,{className:"h-3 w-3"})," Exclude Search Terms"]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(Ee,{placeholder:`Add term to exclude from ${r}...`,value:y,onChange:R=>{k(R.target.value),X("")},onKeyDown:R=>{R.key==="Enter"&&(R.preventDefault(),ne(y))},className:"h-7 text-xs flex-1"}),e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>ne(y),children:e.jsx(ns,{className:"h-3 w-3"})})]}),T.excludeTerms.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:T.excludeTerms.map(R=>e.jsxs(ie,{variant:"destructive",className:"text-[10px] px-1.5 py-0 cursor-pointer",onClick:()=>J(pe=>({...pe,excludeTerms:pe.excludeTerms.filter(Se=>Se!==R)})),children:[R," ",e.jsx(Ut,{className:"h-2.5 w-2.5 ml-0.5"})]},R))}),$&&e.jsx("p",{className:"text-[10px] text-red-500",children:$})]}),w&&e.jsx(Cn,{value:E,onChange:A,label:`${r} empty values`}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t",children:[e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 text-xs text-gray-500",onClick:V,children:"Clear All"}),e.jsx(N,{size:"sm",className:"h-7 text-xs bg-blue-600 hover:bg-blue-700 text-white",onClick:Q,children:"Apply"})]})]})})]})}function $n({column:t,label:r,filters:s,onApply:i}){const[l,c]=o.useState(!1),d=o.useCallback(()=>{switch(t){case"wTimeScraped":return{from:s.timeScrapedFrom,to:s.timeScrapedTo};case"wProfileDate":return{from:s.registrationDateFrom,to:s.registrationDateTo};case"lastUpdated":return{from:s.lastUpdatedFrom,to:s.lastUpdatedTo};default:return{from:"",to:""}}},[t,s]),u=y=>{const k=y.match(/^rel:(\d+)([hdwmy])$/);return k?{amount:k[1],unit:k[2]}:{amount:"7",unit:"d"}},g=d(),f=g.from.startsWith("rel:"),[C,F]=o.useState(f?"relative":"range"),[w,j]=o.useState(g),[E,A]=o.useState(u(f?g.from:"rel:7d"));o.useEffect(()=>{if(l){const y=d(),k=y.from.startsWith("rel:");F(k?"relative":"range"),j(y),A(u(k?y.from:"rel:7d"))}},[l,d]);const T=(()=>{switch(t){case"wTimeScraped":return!!s.timeScrapedFrom||!!s.timeScrapedTo;case"wProfileDate":return!!s.registrationDateFrom||!!s.registrationDateTo;case"lastUpdated":return!!s.lastUpdatedFrom||!!s.lastUpdatedTo;default:return!1}})(),J=()=>{const y={};if(C==="relative"){const k=`rel:${E.amount}${E.unit}`;switch(t){case"wTimeScraped":y.timeScrapedFrom=k,y.timeScrapedTo="";break;case"wProfileDate":y.registrationDateFrom=k,y.registrationDateTo="";break;case"lastUpdated":y.lastUpdatedFrom=k,y.lastUpdatedTo="";break}}else switch(t){case"wTimeScraped":y.timeScrapedFrom=w.from,y.timeScrapedTo=w.to;break;case"wProfileDate":y.registrationDateFrom=w.from,y.registrationDateTo=w.to;break;case"lastUpdated":y.lastUpdatedFrom=w.from,y.lastUpdatedTo=w.to;break}i(y),c(!1)},p=()=>{j({from:"",to:""}),A({amount:"7",unit:"d"})},v=t==="lastUpdated"?[{value:"h",label:"Hours"},{value:"d",label:"Days"},{value:"w",label:"Weeks"},{value:"m",label:"Months"},{value:"y",label:"Years"}]:[{value:"d",label:"Days"},{value:"w",label:"Weeks"},{value:"m",label:"Months"},{value:"y",label:"Years"}];return e.jsxs(Ns,{open:l,onOpenChange:c,children:[e.jsx(Es,{asChild:!0,children:e.jsx("button",{className:`ml-1 p-0.5 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors ${T?"text-blue-600":"text-gray-400 opacity-50"}`,children:e.jsx(La,{className:"h-3 w-3"})})}),e.jsx(ys,{className:"w-72 p-3",align:"start",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"text-xs font-semibold",children:[r," Filter"]}),e.jsxs("div",{className:"flex gap-1 border rounded p-0.5",children:[e.jsx("button",{className:`flex-1 text-xs py-1 rounded transition-colors ${C==="range"?"bg-blue-100 dar
120k:bg-blue-900 text-blue-700 dark:text-blue-300 font-medium":"text-gray-500 hover:text-gray-700"}`,onClick:()=>F("range"),children:"Date Range"}),e.jsx("button",{className:`flex-1 text-xs py-1 rounded transition-colors ${C==="relative"?"bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 font-medium":"text-gray-500 hover:text-gray-700"}`,onClick:()=>F("relative"),children:"Relative"})]}),C==="range"?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-gray-500",children:"From"}),e.jsx(Ee,{type:"date",value:w.from.startsWith("rel:")?"":w.from,onChange:y=>j(k=>({...k,from:y.target.value})),className:"h-7 text-xs"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-gray-500",children:"To"}),e.jsx(Ee,{type:"date",value:w.to,onChange:y=>j(k=>({...k,to:y.target.value})),className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-gray-500",children:"Last"}),e.jsx("input",{type:"number",min:"1",max:"999",value:E.amount,onChange:y=>A(k=>({...k,amount:y.target.value})),className:"h-8 text-xs border rounded px-2 w-16 bg-white dark:bg-gray-800 dark:border-gray-600"}),e.jsx("select",{value:E.unit,onChange:y=>A(k=>({...k,unit:y.target.value})),className:"h-8 text-xs border rounded px-2 flex-1 bg-white dark:bg-gray-800 dark:border-gray-600",children:v.map(y=>e.jsx("option",{value:y.value,children:y.label},y.value))})]}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t",children:[e.jsx(N,{size:"sm",variant:"ghost",className:"h-7 text-xs text-gray-500",onClick:p,children:"Clear All"}),e.jsx(N,{size:"sm",className:"h-7 text-xs bg-blue-600 hover:bg-blue-700 text-white",onClick:J,children:"Apply"})]})]})})]})}const Kn=250;function jp(){const t=o.useMemo(()=>({waveDuration:3+Math.random()*2,initialDelay:Math.random()*5}),[]),r=t.waveDuration/Kn;return e.jsx("div",{className:"or-col-overlay",children:Array.from({length:Kn},(s,i)=>e.jsx("div",{className:"or-col-bar",style:{animationName:"or-col-bar",animationDuration:`${t.waveDuration}s`,animationTimingFunction:"ease-in-out",animationIterationCount:"infinite",animationDelay:`-${t.initialDelay+(Kn-1-i)*r}s`}},i))})}function Cs({columnKey:t,isActive:r,className:s,children:i}){return e.jsxs(Ke,{className:`${s||""} relative select-none transition-colors ${r?"bg-gradient-to-b from-blue-50/80 to-purple-50/60 dark:from-blue-950/40 dark:to-purple-950/30":""}`,style:r?{borderLeft:"1px solid rgba(96,165,250,0.35)",borderRight:"1px solid rgba(167,139,250,0.35)"}:void 0,children:[r&&e.jsx(jp,{}),e.jsx("div",{className:"relative z-[2] whitespace-nowrap",children:r?e.jsx("div",{className:"bg-white/90 dark:bg-gray-950/90 rounded-sm px-1 py-0.5 inline-block",children:i}):i})]})}function pl({isSubscribed:t,subscriptionPlan:r,userId:s,freeLeadsUsed:i=0,monthlyCredits:l=0,monthlyCreditsUsed:c=0,permanentCredits:d=0,isVisible:u=!0,onOpenGenerateDialog:g,keywordGenerationJobs:f,onboardingCategoryFilter:C,onSwitchDatabase:F}){var hs,us,Ms;const w=["pro"].includes(r||""),j=["starter","growth","scale","platinum","enterprise"].includes(r||""),E=!w,{toast:A}=Ss(),{user:T}=Pr(),J=ja();Xn();const[p,v]=o.useState(1),[y,k]=o.useState(1e3),[a,q]=o.useState({...Gr}),[$,X]=o.useState(new Set),[B,K]=o.useState(!1),[ae,Y]=o.useState(!1),fe=o.useRef(!1),U=o.useRef(""),te=o.useRef(new Set),[ne,Q]=o.useState(""),[V,R]=o.useState(null),[pe,Se]=o.useState(!1),[Ze,Me]=o.useState(""),[He,ee]=o.useState(!1),[O,I]=o.useState(!1),[re,Pe]=o.useState(void 0),[tt,$e]=o.useState(void 0),[W,Le]=o.useState(null),[ve,Oe]=o.useState(""),[vt,Rt]=o.useState(!1),At=o.useRef(null),at=o.useRef(null),{data:Je}=Qe({queryKey:["/api/leads/export-freshness"],refetchInterval:3e4,enabled:E&&!!s,queryFn:async()=>{const n=await fetch("/api/leads/export-freshness",{credentials:"include"});if(!n.ok)throw new Error("Failed");return n.json()}});o.useEffect(()=>{if(!Je)return;const n=Je.lastExportTs;if(at.current===null){at.current=n;return}n!==at.current&&(at.current=n,z.invalidateQueries({queryKey:["/api/leads"]}))},[Je]);const{data:Te=[],isFetched:Ct}=Qe({queryKey:["/api/keyword-lists"]}),{data:lt=[]}
120=Qe({queryKey:["/api/filter-presets"]}),kt=lt.filter(n=>n.databaseType==="other"),ft=Ne({mutationFn:async n=>(await ue("POST","/api/filter-presets",n)).json(),onSuccess:()=>{z.invalidateQueries({queryKey:["/api/filter-presets"]}),Se(!1),Me(""),A({title:"Filter preset saved"})},onError:n=>{ce("OtherLeadsTable","Failed to save preset",n),A({title:"Failed to save preset",variant:"destructive"})}}),qt=Ne({mutationFn:async n=>{await ue("DELETE",`/api/filter-presets/${n}`)},onSuccess:()=>{z.invalidateQueries({queryKey:["/api/filter-presets"]}),A({title:"Preset deleted"})},onError:n=>{ce("OtherLeadsTable","Failed to delete preset",n),A({title:"Failed to delete preset",variant:"destructive"})}}),et=o.useMemo(()=>Te.filter(n=>n.type==="positive"),[Te]),Ot=o.useMemo(()=>Te.filter(n=>n.type==="negative"),[Te]);o.useEffect(()=>{if(ae||!Ct)return;const n=window.location.hash;if(n&&n.length>1){const L=gp(n,Te);L.length>0&&A({title:"Some keyword lists not found",description:`${L.length} keyword list${L.length>1?"s":""} referenced in the URL ${L.length>1?"no longer exist":"no longer exists"} and ${L.length>1?"were":"was"} removed from the filters.`,variant:"destructive"})}const b=n&&n.length>1?Dn(n,Te):{},h=lp({hash:n,keywordLists:Te,parsed:b,onboardingCategoryFilter:C});h.kind==="fromHash"?(q(h.nextFilters),Q(h.searchDraft),fe.current=!1):(q(L=>({...L,...h.partial})),fe.current=!0,U.current=Wn(Te),te.current=new Set(Te.filter(L=>L.isDefault).map(L=>L.id))),Y(!0)},[Te,Ct,ae,C,A]),o.useEffect(()=>{if(!ae||!fe.current||Te.length===0)return;const n=op({keywordLists:Te,prevFingerprint:U.current,prevDefaultIds:te.current});n&&(U.current=n.newFingerprint,te.current=n.newDefaultIds,n.patch&&(q(b=>({...b,...n.patch})),v(1)))},[Te,ae]);const Xe=o.useRef("");o.useEffect(()=>{if(!ae)return;const n=C?JSON.stringify(C.slice().sort()):"";n&&n!==Xe.current&&(Xe.current=n,!(et.some(h=>h.isDefault)||Ot.some(h=>h.isDefault))&&C&&(q(h=>({...h,categoryIncludeTerms:C})),v(1)))},[ae,C,et,Ot]),o.useEffect(()=>{if(!ae||!Ct)return;const n=new Set(Te.map(L=>L.id)),b=["nameKeywordListIds","urlKeywordListIds","crawledUrlKeywordListIds","descriptionKeywordListIds","categoryKeywordListIds"];let h=!1;for(const L of b)if(a[L].some(_=>!n.has(_))){h=!0;break}h&&q(L=>{const _={...L};for(const G of b)_[G]=L[G].filter(We=>n.has(We));return _})},[Te,Ct,ae]),o.useEffect(()=>{if(!ae||!u)return;const n=Wr(a),b=window.location.hash;if(n!==b){const h=window.location.pathname+window.location.search+n;window.history.replaceState(null,"",h)}},[a,ae,u]);const mt=a.nameIncludeTerms.length>0||a.urlIncludeTerms.length>0||a.crawledUrlIncludeTerms.length>0||a.descriptionIncludeTerms.length>0||a.categoryIncludeTerms.length>0||Array.from(new Set(a.nameKeywordListIds.concat(a.urlKeywordListIds,a.crawledUrlKeywordListIds,a.descriptionKeywordListIds,a.categoryKeywordListIds))).some(n=>{const b=Te.find(h=>h.id===n);return(b==null?void 0:b.type)==="positive"&&Array.isArray(b.keywords)&&b.keywords.length>0}),ut=o.useRef(Te),ot=o.useMemo(()=>new Set([...a.nameKeywordListIds,...a.urlKeywordListIds,...a.crawledUrlKeywordListIds,...a.descriptionKeywordListIds,...a.categoryKeywordListIds]),[a.nameKeywordListIds,a.urlKeywordListIds,a.crawledUrlKeywordListIds,a.descriptionKeywordListIds,a.categoryKeywordListIds]),St=o.useMemo(()=>Te.some(n=>ot.has(n.id)&&n.refinementStatus==="running"),[Te,ot]),Pt=o.useMemo(()=>((!St||ut.current.length===0)&&(ut.current=Te),ut.current),[Te,St]),it=o.useMemo(()=>mt?hp(a,p,y,Pt):null,[a,p,y,mt,Pt]),ze=o.useRef(void 0),_t=o.useRef(!1);o.useEffect(()=>{ze.current===void 0?it!==null&&(ze.current=it):it!==null&&it!==ze.current&&(_t.current=!0)},[it]);const{data:de,isLoading:gt,isFetching:It,isError:Ge,refetch:Ce}=Qe({queryKey:["/api/leads",it],queryFn:async({signal:n})=>{if(!it)return{leads:[],pagination:{page:1,limit:100,total:0,pages:0},requiresKeywords:!0};const b=_t.current?"&refresh=true":"",h=await fetch(`/api/leads?${it}${b}`,{credentials:"include",signal:n});if(!h.ok)throw new Error("Failed to fetch leads");return h.json()},enabled:ae&&mt,retry:1,retryDelay:2e3}),P=((hs=de==null?void 0:de.pagination)==null?void 0:hs.total)!=null?{total:de.pagination.total}:void 0,le=It,De=Ne({mutationFn:async n=>{const b=n==null?void 0:n.selectedIds,h=n==null?void 0:n.maxLeads,L={eventId:`export-${Date.now()}`};if(b&&b.length>0)L.selectedIds=b;else{const G=Do(a,Te),We=Array.from(new Set(a.nameKeywordListIds.concat(a.urlKeywordListIds,a.crawledUrlKeywordListIds,a.descriptionKeywordListIds,a.categoryKeywordListIds)));L.filters={keywordListIds:We.length>0?We.join(","):void 0,positiveKeywords:G.positiveKeywords.length>0?G.positiveKeywords:void 0,negativeKeywords:G.negativeKeywords.length>0?G.negativeKeywords:void 0,nameIncludeTerms:G.nameInclude.length>0?G.nameInclude:void 0,nameExcludeTerms:G.nameExclude.length>0?G.nameExclude:void 0,urlIncludeTerms:G.urlInclude.length>0?G.urlInclude:void 0,urlExcludeTerms:G.urlExclude.length>0?G.urlExclude:void 0,crawledUrlIncludeTerms:G.crawledUrlInclude.length>0?G.crawledUrlInclude:void 0,crawledUrlExcludeTerms:G.crawledUrlExclude.length>0?G.crawledUrlExclude:void 0,descriptionIncludeTerms:G.descInclude.length>0?G.descInclude:void 0,descriptionExcludeTerms:G.descExclude.length>0?G.descExclude:void 0,categoryIncludeTerms:G.catInclude.length>0?G.catInclude:void 0,categoryExcludeTerms:G.catExclude.length>0?G.catExclude:void 0,stateInclude:a.stateInclude.length>0?a.stateInclude.join(","):void 0,stateExclude:a.stateExclude.length>0?a.stateExclude.join(","):void 0,cityInclude:a.cityInclude.length>0?a.cityInclude:void 0,cityExclude:a.cityExclude.length>0?a.cityExclude:void 0,zipInclude:a.zipInclude.length>0?a.zipInclude:void 0,zipExclude:a.zipExclude.length>0?a.zipExclude:void 0,streetInclude:a.streetInclude.length>0?a.streetInclude:void 0,streetExclude:a.streetExclude.length>0?a.streetExclude:void 0,emailPrimaryInclude:a.emailPrimaryInclude.length>0?a.emailPrimaryInclude:void 0,emailPrimaryExclude:a.emailPrimaryExclude.length>0?a.emailPrimaryExclude:void 0,emailTier1Include:a.emailTier1Include.length>0?a.emailTier1Include:void 0,emailTier1Exclude:a.emailTier1Exclude.length>0?a.emailTier1Exclude:void 0,emailTier2Include:a.emailTier2Include.length>0?a.emailTier2Include:void 0,emailTier2Exclude:a.emailTier2Exclude.length>0?a.emailTier2Exclude:void 0,emailTier3Include:a.emailTier3Include.length>0?a.emailTier3Include:void 0,emailTier3Exclude:a.emailTier3Exclude.length>0?a.emailTier3Exclude:void 0,emailTier4Include:a.emailTier4Include.length>0?a.emailTier4Include:void 0,emailTier4Exclude:a.emailTier4Exclude.length>0?a.emailTier4Exclude:void 0,emailTier5Include:a.emailTier5Include.length>0?a.emailTier5Include:void 0,emailTier5Exclude:a.emailTier5Exclude.length>0?a.emailTier5Exclude:void 0,emailTier6Include:a.emailTier6Include.length>0?a.emailTier6Include:void 0,emailTier6Exclude:a.emailTier6Exclude.length>0?a.emailTier6Exclude:void 0,phonePrimaryInclude:a.phonePrimaryInclude.length>0?a.phonePrimaryInclude:void 0,phonePrimaryExclude:a.phonePrimaryExclude.length>0?a.phonePrimaryExclude:void 0,phoneTotalInclude:a.phoneTotalInclude.length>0?a.phoneTotalInclude:void 0,phoneTotalExclude:a.phoneTotalExclude.length>0?a.phoneTotalExclude:void 0,streetEmptyFilter:a.streetEmptyFilter!=="any"?a.streetEmptyFilter:void 0,cityEmptyFilter:a.cityEmptyFilter!=="any"?a.cityEmptyFilter:void 0,stateEmptyFilter:a.stateEmptyFilter!=="any"?a.stateEmptyFilter:void 0,zipEmptyFilter:a.zipEmptyFilter!=="any"?a.zipEmptyFilter:void 0,phonePrimaryEmptyFilter:a.phonePrimaryEmptyFilter!=="any"?a.phonePrimaryEmptyFilter:void 0,phoneTotalEmptyFilter:a.phoneTotalEmptyFilter!=="any"?a.phoneTotalEmptyFilter:void 0,emailPrimaryEmptyFilter:a.emailPrimaryEmptyFilter!=="any"?a.emailPrimaryEmptyFilter:void 0,emailTier1EmptyFilter:a.emailTier1EmptyFilter!=="any"?a.emailTier1EmptyFilter:void 0,emailTier2EmptyFilter:a.emailTier2EmptyFilter!=="any"?a.emailTier2EmptyFilter:void 0,emailTier3EmptyFilter:a.emailTier3EmptyFilter!=="any"?a.emailTier3EmptyFilter:void 0,emailTier4EmptyFilter:a.emailTier4EmptyFilter!=="any"?a.emailTier4EmptyFilter:void 0,emailTier5EmptyFilter:a.emailTier5EmptyFilter!=="any"?a.emailTier5EmptyFilter:void 0,emailTier6EmptyFilter:a.emailTier6EmptyFilter!=="any"?a.emailTier6EmptyFilter:void 0,descriptionEmptyFilter:a.descriptionEmptyFilter!=="any"?a.descriptionEmptyFilter:void 0,employeeCountInclude:a.employeeCountInclude.length>0?a.employeeCountInclude:void 0,employeeCountExclude:a.employeeCountExclude.length>0?a.employeeCountExclude:void 0,foundingDateInclude:a.foundingDateInclude.length>0?a.foundingDateInclude:void 0,foundingDateExclude:a.foundingDateExclude.length>0?a.foundingDateExclude:void 0,isChainInclude:a.isChainInclude.length>0?a.isChainInclude:void 0,isChainExclude:a.isChainExclude.length>0?a.isChainExclude:void 0,priceRangeInclude:a.priceRangeInclude.length>0?a.priceRangeInclude:void 0,priceRangeExclude:a.priceRangeExclude.length>0?a.priceRangeExclude:void 0,legalNameInclude:a.legalNameInclude.length>0?a.legalNameInclude:void 0,legalNameExclude:a.legalNameExclude.length>0?a.legalNameExclude:void 0,industryNaicsInclude:a.industryNaicsInclude.length>0?a.industryNaicsInclude:void 0,industryNaicsExclude:a.industryNaicsExclude.length>
1200?a.industryNaicsExclude:void 0,dunsInclude:a.dunsInclude.length>0?a.dunsInclude:void 0,dunsExclude:a.dunsExclude.length>0?a.dunsExclude:void 0,sloganInclude:a.sloganInclude.length>0?a.sloganInclude:void 0,sloganExclude:a.sloganExclude.length>0?a.sloganExclude:void 0,logoUrlInclude:a.logoUrlInclude.length>0?a.logoUrlInclude:void 0,logoUrlExclude:a.logoUrlExclude.length>0?a.logoUrlExclude:void 0,founderInclude:a.founderInclude.length>0?a.founderInclude:void 0,founderExclude:a.founderExclude.length>0?a.founderExclude:void 0,founderEmailInclude:a.founderEmailInclude.length>0?a.founderEmailInclude:void 0,founderEmailExclude:a.founderEmailExclude.length>0?a.founderEmailExclude:void 0,founderPhoneInclude:a.founderPhoneInclude.length>0?a.founderPhoneInclude:void 0,founderPhoneExclude:a.founderPhoneExclude.length>0?a.founderPhoneExclude:void 0,openingHoursInclude:a.openingHoursInclude.length>0?a.openingHoursInclude:void 0,openingHoursExclude:a.openingHoursExclude.length>0?a.openingHoursExclude:void 0,areaServedInclude:a.areaServedInclude.length>0?a.areaServedInclude:void 0,areaServedExclude:a.areaServedExclude.length>0?a.areaServedExclude:void 0,offersInclude:a.offersInclude.length>0?a.offersInclude:void 0,offersExclude:a.offersExclude.length>0?a.offersExclude:void 0,brandInclude:a.brandInclude.length>0?a.brandInclude:void 0,brandExclude:a.brandExclude.length>0?a.brandExclude:void 0,socialProfilesInclude:a.socialProfilesInclude.length>0?a.socialProfilesInclude:void 0,socialProfilesExclude:a.socialProfilesExclude.length>0?a.socialProfilesExclude:void 0,platformInclude:a.platformInclude.length>0?a.platformInclude:void 0,platformExclude:a.platformExclude.length>0?a.platformExclude:void 0,bookingOpsCrmSoftwareInclude:a.bookingOpsCrmSoftwareInclude.length>0?a.bookingOpsCrmSoftwareInclude:void 0,bookingOpsCrmSoftwareExclude:a.bookingOpsCrmSoftwareExclude.length>0?a.bookingOpsCrmSoftwareExclude:void 0,reputationChatSoftwareInclude:a.reputationChatSoftwareInclude.length>0?a.reputationChatSoftwareInclude:void 0,reputationChatSoftwareExclude:a.reputationChatSoftwareExclude.length>0?a.reputationChatSoftwareExclude:void 0,marketingEmailSoftwareInclude:a.marketingEmailSoftwareInclude.length>0?a.marketingEmailSoftwareInclude:void 0,marketingEmailSoftwareExclude:a.marketingEmailSoftwareExclude.length>0?a.marketingEmailSoftwareExclude:void 0,adPixelsInclude:a.adPixelsInclude.length>0?a.adPixelsInclude:void 0,adPixelsExclude:a.adPixelsExclude.length>0?a.adPixelsExclude:void 0,paymentFinancingSoftwareInclude:a.paymentFinancingSoftwareInclude.length>0?a.paymentFinancingSoftwareInclude:void 0,paymentFinancingSoftwareExclude:a.paymentFinancingSoftwareExclude.length>0?a.paymentFinancingSoftwareExclude:void 0,employeeCountEmptyFilter:a.employeeCountEmptyFilter!=="any"?a.employeeCountEmptyFilter:void 0,foundingDateEmptyFilter:a.foundingDateEmptyFilter!=="any"?a.foundingDateEmptyFilter:void 0,isChainEmptyFilter:a.isChainEmptyFilter!=="any"?a.isChainEmptyFilter:void 0,priceRangeEmptyFilter:a.priceRangeEmptyFilter!=="any"?a.priceRangeEmptyFilter:void 0,legalNameEmptyFilter:a.legalNameEmptyFilter!=="any"?a.legalNameEmptyFilter:void 0,industryNaicsEmptyFilter:a.industryNaicsEmptyFilter!=="any"?a.industryNaicsEmptyFilter:void 0,dunsEmptyFilter:a.dunsEmptyFilter!=="any"?a.dunsEmptyFilter:void 0,sloganEmptyFilter:a.sloganEmptyFilter!=="any"?a.sloganEmptyFilter:void 0,logoUrlEmptyFilter:a.logoUrlEmptyFilter!=="any"?a.logoUrlEmptyFilter:void 0,founderEmptyFilter:a.founderEmptyFilter!=="any"?a.founderEmptyFilter:void 0,founderEmailEmptyFilter:a.founderEmailEmptyFilter!=="any"?a.founderEmailEmptyFilter:void 0,founderPhoneEmptyFilter:a.founderPhoneEmptyFilter!=="any"?a.founderPhoneEmptyFilter:void 0,openingHoursEmptyFilter:a.openingHoursEmptyFilter!=="any"?a.openingHoursEmptyFilter:void 0,areaServedEmptyFilter:a.areaServedEmptyFilter!=="any"?a.areaServedEmptyFilter:void 0,offersEmptyFilter:a.offersEmptyFilter!=="any"?a.offersEmptyFilter:void 0,brandEmptyFilter:a.brandEmptyFilter!=="any"?a.brandEmptyFilter:void 0,socialProfilesEmptyFilter:a.socialProfilesEmptyFilter!=="any"?a.socialProfilesEmptyFilter:void 0,platformEmptyFilter:a.platformEmptyFilter!=="any"?a.platformEmptyFilter:void 0,bookingOpsCrmSoftw
120areEmptyFilter:a.bookingOpsCrmSoftwareEmptyFilter!=="any"?a.bookingOpsCrmSoftwareEmptyFilter:void 0,reputationChatSoftwareEmptyFilter:a.reputationChatSoftwareEmptyFilter!=="any"?a.reputationChatSoftwareEmptyFilter:void 0,marketingEmailSoftwareEmptyFilter:a.marketingEmailSoftwareEmptyFilter!=="any"?a.marketingEmailSoftwareEmptyFilter:void 0,adPixelsEmptyFilter:a.adPixelsEmptyFilter!=="any"?a.adPixelsEmptyFilter:void 0,paymentFinancingSoftwareEmptyFilter:a.paymentFinancingSoftwareEmptyFilter!=="any"?a.paymentFinancingSoftwareEmptyFilter:void 0,emailPrimaryMxValues:a.emailPrimaryMxValues.length>0?a.emailPrimaryMxValues:void 0,emailDomainMxValues:a.emailDomainMxValues.length>0?a.emailDomainMxValues:void 0,emailSecurityValues:a.emailSecurityValues.length>0?a.emailSecurityValues:void 0,addressSourceValues:a.addressSourceValues.length>0?a.addressSourceValues:void 0,emailPrimaryMxEmptyFilter:a.emailPrimaryMxEmptyFilter!=="any"?a.emailPrimaryMxEmptyFilter:void 0,emailDomainMxEmptyFilter:a.emailDomainMxEmptyFilter!=="any"?a.emailDomainMxEmptyFilter:void 0,emailSecurityEmptyFilter:a.emailSecurityEmptyFilter!=="any"?a.emailSecurityEmptyFilter:void 0,addressSourceEmptyFilter:a.addressSourceEmptyFilter!=="any"?a.addressSourceEmptyFilter:void 0,minNumLocations:a.minNumLocations||void 0,maxNumLocations:a.maxNumLocations||void 0,minOpenPositions:a.minOpenPositions||void 0,maxOpenPositions:a.maxOpenPositions||void 0,openPositionsEmptyFilter:a.openPositionsEmptyFilter!=="any"?a.openPositionsEmptyFilter:void 0,minRatingValue:a.minRatingValue||void 0,maxRatingValue:a.maxRatingValue||void 0,minReviewCount:a.minReviewCount||void 0,maxReviewCount:a.maxReviewCount||void 0,redirectFilter:a.redirectFilter||void 0,updateReasonFilter:a.updateReasonFilter.length>0?a.updateReasonFilter:void 0,websiteSchemaFilter:a.websiteSchemaFilter.length>0?a.websiteSchemaFilter:void 0,sortBy:a.sortBy,sortOrder:a.sortOrder,timeScrapedFrom:a.timeScrapedFrom||void 0,timeScrapedTo:a.timeScrapedTo||void 0,registrationDateFrom:a.registrationDateFrom||void 0,registrationDateTo:a.registrationDateTo||void 0,lastUpdatedFrom:a.lastUpdatedFrom||void 0,lastUpdatedTo:a.lastUpdatedTo||void 0},h&&h>0&&(L.maxLeads=h)}return(await ue("POST","/api/leads/export",L)).json()},onSuccess:n=>{if(n.leads&&n.leads.length>0){const b=st(n.leads),h=new Blob([b],{type:"text/csv"}),L=URL.createObjectURL(h),_=document.createElement("a");_.href=L;const G=n.fileSlug||J.fileSlug;_.download=`leads-${G}-${new Date().toISOString().split("T")[0]}.csv`,_.click(),URL.revokeObjectURL(L);const We=!w&&n.remaining!==void 0&&n.remaining>=0?` (${n.remaining} exports remaining)`:"";A({title:"Export Complete",description:`Exported ${n.leads.length} leads.${We}`}),Ul(n,T,"other"),z.invalidateQueries({queryKey:["/api/leads"]}),z.invalidateQueries({queryKey:["/api/auth/user"]}),z.invalidateQueries({queryKey:["/api/me/temporary-credits"]}),X(new Set),Le(null),Oe("")}else ce("OtherLeadsTable","No leads to export"),A({title:"No Leads",description:"No leads to export.",variant:"destructive"})},onError:n=>{ce("OtherLeadsTable","Export failed",n),A({title:"Export Failed",description:"Could not export leads.",variant:"destructive"})}}),st=n=>fo(n,dp,{alwaysQuoteColumns:["aiCategoryEstimation"],logoUrlColumn:vu}),Ft=o.useCallback(n=>{q(b=>({...b,sortBy:n,sortOrder:b.sortBy===n&&b.sortOrder==="desc"?"asc":"desc"})),K(!1),X(new Set),v(1)},[]),oe=o.useCallback(n=>{fe.current=!1,q(b=>({...b,...n})),K(!1),X(new Set),v(1)},[]),Ye=o.useCallback(()=>{q(n=>({...n,search:ne})),K(!1),X(new Set),v(1)}
120,[ne]),pt=j?Math.max(0,l-c)+Math.max(0,d):0,jt=j?pt:((us=de==null?void 0:de.exportLimits)==null?void 0:us.remaining)??(t?-1:Math.max(0,20-i)),ye=w?1/0:Math.max(0,jt);o.useEffect(()=>{($.size>0||B)&&W!==null&&Le(null)},[$,B,W]),o.useEffect(()=>{Le(null),Oe("")},[a]);const Xt=o.useCallback(()=>{if(!(de!=null&&de.leads))return;if(B){K(!1),X(new Set);return}const n=de.leads.map(h=>h.id);if(n.every(h=>$.has(h))||$.size>0&&!w)K(!1),X(new Set);else if(w)K(!0),X(new Set(n));else{const h=Math.min(n.length,ye);X(new Set(n.slice(0,h)))}},[de,$,w,ye,B]),rt=o.useRef(null),fs=o.useCallback((n,b)=>{B&&K(!1);const h=(de==null?void 0:de.leads)||[],L=$.has(n);if(b&&rt.current&&h.length>0){const _=h.findIndex(We=>We.id===rt.current.id),G=h.findIndex(We=>We.id===n);if(_!==-1&&G!==-1){const We=Math.min(_,G),gs=Math.max(_,G),ts=h.slice(We,gs+1).map(nt=>nt.id),Zt=!L;X(nt=>{const ss=new Set(nt);for(const x of ts)if(Zt){if(!w&&ss.size>=ye)break;ss.add(x)}else ss.delete(x);return ss}),rt.current={id:n,wasSelected:Zt};return}}X(_=>{const G=new Set(_);if(G.has(n))G.delete(n);else{if(!w&&G.size>=ye)return _;G.add(n)}return G}),rt.current={id:n,wasSelected:!L}},[w,ye,B,de,$]),Tt=j?"Export to reveal contact details (1 credit per lead)":"Export to get contact details â contact details are not hidden for paid users",yt=(de==null?void 0:de.leads)||[],is=(P==null?void 0:P.total)??((Ms=de==null?void 0:de.pagination)==null?void 0:Ms.total)??null,Dt=is!==null,Ae=de!=null&&de.pagination?{...de.pagination,total:Dt?is:0,pages:Dt?Math.ceil(is/de.pagination.limit):yt.length>=de.pagination.limit?p+1:p}:void 0,bt=B||yt.length>0&&yt.every(n=>$.has(n.id)),Nt=!B&&$.size===0&&!!W&&W>0,ls=o.useCallback(()=>{const n=parseInt(ve,10);if(!Number.isFinite(n)||n<=0){Le(null);return}let b=n;if(!w&&ye!==1/0&&b>ye&&(b=ye,Oe(String(b)),A({title:"Adjusted to your remaining allowance",description:`You can export up to ${ye.toLocaleString()} leads right now.`})),b<=0){Le(null),A({title:"No exports remaining",description:"You have no export allowance left.",variant:"destructive"});return}X(new Set),K(!1),Le(b)},[ve,w,ye,A]),es=o.useCallback(()=>{Rt(!0),At.current&&clearTimeout(At.current),At.current=setTimeout(()=>Rt(!1),700)},[]);o.useEffect(()=>()=>{At.current&&clearTimeout(At.current)},[]);const Rs=o.useCallback(()=>{const n=parseInt(ve,10);!w&&ye!==1/0&&Number.isFinite(n)&&n>ye&&(es(),ls())},[ve,w,ye,es,ls]),bs=o.useCallback(()=>{const n=B||Nt?void 0:Array.from($),b=Nt?W:void 0;if(!w&&jt>=0){const h=B?(Ae==null?void 0:Ae.total)??0:Nt?W:$.size,L=jt-h;if(L<=20&&L>=0){Pe(n),$e(b),I(!0);return}}De.mutate({selectedIds:n,maxLeads:b})},[B,Nt,W,$,w,jt,Ae,De]),Ps={name:"Company Name",url:"URL",crawledUrl:"Crawled URL",description:"Description",category:"Categories"},ms=o.useMemo(()=>{var h,L,_;const n=[];a.stateInclude.length>0&&n.push({label:`State: ${a.stateInclude.join(", ")}`,filterKey:"stateInclude",resetValue:[]}),a.stateExclude.length>0&&n.push({label:`Not State: ${a.stateExclude.join(", ")}`,filterKey:"stateExclude",resetValue:[]}),a.cityInclude.length>0&&n.push({label:`City: ${a.cityInclude.join(", ")}`,filterKey:"cityInclude",resetValue:[]}),a.cityExclude.length>0&&n.push({label:`Not City: ${a.cityExclude.join(", ")}`,filterKey:"cityExclude",resetValue:[]}),a.zipInclude.length>0&&n.push({label:`Zip: ${a.zipInclude.join(", ")}`,filterKey:"zipInclude",resetValue:[]}),a.zipExclude.length>0&&n.push({label:`Not Zip: ${a.zipExclude.join(", ")}`,filterKey:"zipExclude",resetValue:[]}),a.redirectFilter==="yes"&&n.push({label:"Redirect: Yes",filterKey:"redirectFilter",resetValue:""}),a.redirectFilter==="no"&&n.push({label:"Redirect: No",filterKey:"redirectFilter",resetValue:""}),a.search&&n.push({label:`Search: "${a.search}"`,filterKey:"search",resetValue:""}),a.nameIncludeTerms.length>0&&n.push({label:`Name includes: ${a.nameIncludeTerms.join(", ")}`,filterKey:"nameIncludeTerms",resetValue:[]}),a.nameExcludeTerms.length>0&&n.push({label:`Name excludes: ${a.nameExcludeTerms.join(", ")}`,filterKey:"nameExcludeTerms",resetValue:[]}),a.urlIncludeTerms.length>0&&n.push({label:`URL includes: ${a.urlIncludeTerms.join(", ")}`,filterKey:"urlIncludeTerms",resetValue:[]}),a.urlExcludeTerms.length>
1200&&n.push({label:`URL excludes: ${a.urlExcludeTerms.join(", ")}`,filterKey:"urlExcludeTerms",resetValue:[]}),a.crawledUrlIncludeTerms.length>0&&n.push({label:`Crawled URL includes: ${a.crawledUrlIncludeTerms.join(", ")}`,filterKey:"crawledUrlIncludeTerms",resetValue:[]}),a.crawledUrlExcludeTerms.length>0&&n.push({label:`Crawled URL excludes: ${a.crawledUrlExcludeTerms.join(", ")}`,filterKey:"crawledUrlExcludeTerms",resetValue:[]}),a.descriptionIncludeTerms.length>0&&n.push({label:`Description includes: ${a.descriptionIncludeTerms.join(", ")}`,filterKey:"descriptionIncludeTerms",resetValue:[]}),a.descriptionExcludeTerms.length>0&&n.push({label:`Description excludes: ${a.descriptionExcludeTerms.join(", ")}`,filterKey:"descriptionExcludeTerms",resetValue:[]}),a.categoryIncludeTerms.length>0&&n.push({label:`Categories includes: ${a.categoryIncludeTerms.map(G=>`*${G.trim().replace(/\s+/g,"*")}*`).join(", ")}`,filterKey:"categoryIncludeTerms",resetValue:[]}),a.categoryExcludeTerms.length>0&&n.push({label:`Categories excludes: ${a.categoryExcludeTerms.join(", ")}`,filterKey:"categoryExcludeTerms",resetValue:[]}),a.streetInclude.length>0&&n.push({label:`Street: ${a.streetInclude.join(", ")}`,filterKey:"streetInclude",resetValue:[]}),a.streetExclude.length>0&&n.push({label:`Not Street: ${a.streetExclude.join(", ")}`,filterKey:"streetExclude",resetValue:[]});const b=G=>G==="only_empty"?"only empty":"non-empty";return a.streetEmptyFilter!=="any"&&n.push({label:`Street: ${b(a.streetEmptyFilter)}`,filterKey:"streetEmptyFilter",resetValue:"any"}),a.cityEmptyFilter!=="any"&&n.push({label:`City: ${b(a.cityEmptyFilter)}`,filterKey:"cityEmptyFilter",resetValue:"any"}),a.stateEmptyFilter!=="any"&&n.push({label:`State: ${b(a.stateEmptyFilter)}`,filterKey:"stateEmptyFilter",resetValue:"any"}),a.zipEmptyFilter!=="any"&&n.push({label:`Zip: ${b(a.zipEmptyFilter)}`,filterKey:"zipEmptyFilter",resetValue:"any"}),a.phonePrimaryEmptyFilter!=="any"&&n.push({label:`Phone Primary: ${b(a.phonePrimaryEmptyFilter)}`,filterKey:"phonePrimaryEmptyFilter",resetValue:"any"}),a.phoneTotalEmptyFilter!=="any"&&n.push({label:`Total Phones: ${b(a.phoneTotalEmptyFilter)}`,filterKey:"phoneTotalEmptyFilter",resetValue:"any"}),a.emailPrimaryEmptyFilter!=="any"&&n.push({label:`Email Primary: ${b(a.emailPrimaryEmptyFilter)}`,filterKey:"emailPrimaryEmptyFilter",resetValue:"any"}),a.emailTier1EmptyFilter!=="any"&&n.push({label:`Tier 1 Emails: ${b(a.emailTier1EmptyFilter)}`,filterKey:"emailTier1EmptyFilter",resetValue:"any"}),a.emailTier2EmptyFilter!=="any"&&n.push({label:`Tier 2 Emails: ${b(a.emailTier2EmptyFilter)}`,filterKey:"emailTier2EmptyFilter",resetValue:"any"}),a.emailTier3EmptyFilter!=="any"&&n.push({label:`Tier 3 Emails: ${b(a.emailTier3EmptyFilter)}`,filterKey:"emailTier3EmptyFilter",resetValue:"any"}),a.emailTier4EmptyFilter!=="any"&&n.push({label:`Tier 4 Emails: ${b(a.emailTier4EmptyFilter)}`,filterKey:"emailTier4EmptyFilter",resetValue:"any"}),a.emailTier5EmptyFilter!=="any"&&n.push({label:`Tier 5 Emails: ${b(a.emailTier5EmptyFilter)}`,filterKey:"emailTier5EmptyFilter",resetValue:"any"}),a.emailTier6EmptyFilter!=="any"&&n.push({label:`Tier 6 Emails: ${b(a.emailTier6EmptyFilter)}`,filterKey:"emailTier6EmptyFilter",resetValue:"any"}),a.descriptionEmptyFilter!=="any"&&n.push({label:`Description: ${b(a.descriptionEmptyFilter)}`,filterKey:"descriptionEmptyFilter",resetValue:"any"}),a.emailPrimaryInclude.length>0&&n.push({label:`Email Primary: ${a.emailPrimaryInclude.map(je).join(", ")}`,filterKey:"emailPrimaryInclude",resetValue:[]}),a.emailPrimaryExclude.length>0&&n.push({label:`Not Email Primary: ${a.emailPrimaryExclude.map(je).join(", ")}`,filterKey:"emailPrimaryExclude",resetValue:[]}),a.emailTier1Include.length>0&&n.push({label:`Tier 1 Emails: ${a.emailTier1Include.map(je).join(", ")}`,filterKey:"emailTier1Include",resetValue:[]}),a.emailTier1Exclude.length>0&&n.push({label:`Not Tier 1 Emails: ${a.emailTier1Exclude.map(je).join(", ")}`,filterKey:"emailTier1Exclude",resetValue:[]}),a.emailTier2Include.length>0&&n.push({label:`Tier 2 Emails: ${a.emailTier2Include.map(je).join(", ")}`,filterKey:"emailTier2Include",resetValue:[]}),a.emailTier2Exclude.length>0&&n.push({label:`Not Tier 2 Emails: ${a.emailTier2Exclude.map(je).join(", ")}`,filterKey:"emailTier2Exclude",resetValue:[]}),a.emailTier3Include.length>0&&n.push({label:`Tier 3 Emails: ${a.emailTier3Include.map(je).join(", ")}`,filterKey:"emailTier3Include",resetValue:[]}),a.emailTier3Exclude.length>0&&n.push({label:`Not Tier 3 Emails: ${a.emailTier3Exclude.map(je).join(", ")}`,filterKey:"emailTier3Exclude",resetValue:[]}),a.emailTier4Include.length>0&&n.push({label:`Tier 4 Emails: ${a.emailTier4Include.map(je).join(", ")}`,filterKey:"emailTier4Include",resetValue:[]}),a.emailTier4Exclude.length>0&&n.push({label:`Not Tier 4 Emails: ${a.emailTier4Exclude.map(je).join(", ")}`,filterKey:"emailTier4Exclude",resetValue:[]}),a.emailTier5Include.length>0&&n.push({label:`Tier 5 Emails: ${a.emailTier5Include.map(je).join(", ")}`,filterKey:"emailTier5Include",resetValue:[]}),a.emailTier5Exclude.length>0&&n.push({label:`Not Tier 5 Emails: ${a.emailTier5Exclude.map(je).join(", ")}`,filterKey:"emailTier5Exclude",resetValue:[]}),a.emailTier6Include.length>0&&n.push({label:`Tier 6 Emails: ${a.emailTier6Include.map(je).join(", ")}`,filterKey:"emailTier6Include",resetValue:[]}),a.emailTier6Exclude.length>0&&n.push({label:`Not Tier 6 Emails: ${a.emailTier6Exclude.map(je).join(", ")}`,filterKey:"emailTier6Exclude",resetValue:[]}),a.phonePrimaryInclude.length>0&&n.push({label:`Phone Primary: ${a.phonePrimaryInclude.map(je).join(", ")}`,filterKey:"phonePrimaryInclude",resetValue:[]}),a.phonePrimaryExclude.length>0&&n.push({label:`Not Phone Primary: ${a.phonePrimaryExclude.map(je).join(", ")}`,filterKey:"phonePrimaryExclude",resetValue:[]}),a.phoneTotalInclude.length>0&&n.push({label:`Total Phones: ${a.phoneTotalInclude.map(je).join(", ")}`,filterKey:"phoneTotalInclude",resetValue:[]}),a.phoneTotalExclude.length>0&&n.push({label:`Not Total Phones: ${a.phoneTotalExclude.map(je).join(", ")}`,filterKey:"phoneTotalExclude",resetValue:[]}),a.employeeCountInclude.length>0&&n.push({label:`Employees: ${a.employeeCountInclude.map(je).join(", ")}`,filterKey:"employeeCountInclude",resetValue:[]}),a.employeeCountExclude.length>0&&n.push({label:`Not Employees: ${a.employeeCountExclude.map(je).join(", ")}`,filterKey:"employeeCountExclude",resetValue:[]}),a.foundingDateInclude.length>0&&n.push({label:`Founding Date: ${a.foundingDateInclude.map(je).join(", ")}`,filterKey:"foundingDateInclude",resetValue:[]}),a.foundingDateExclude.length>0&&n.push({label:`Not Founding Date: ${a.foundingDateExclude.map(je).join(", ")}`,filterKey:"foundingDateExclude",resetValue:[]}),a.isChainInclude.length>0&&n.push({label:`Is Chain?: ${a.isChainInclude.map(je).join(", ")}`,filterKey:"isChainInclude",resetValue:[]}),a.isChainExclude.length>0&&n.push({label:`Not Is Chain?: ${a.isChainExclude.map(je).join(", ")}`,filterKey:"isChainExclude",resetValue:[]}),a.priceRangeInclude.length>0&&n.push({label:`Price Range: ${a.priceRangeInclude.map(je).join(", ")}`,filterKey:"priceRangeInclude",resetValue:[]}),a.priceRangeExclude.length>0&&n.push({label:`Not Price Range: ${a.priceRangeExclude.map(je).join(", ")}`,filterKey:"priceRangeExclude",resetValue:[]}),a.legalNameInclude.length>0&&n.push({label:`Legal Name: ${a.legalNameInclude.map(je).join(", ")}`,filterKey:"legalNameInclude",resetValue:[]}),a.legalNameExclude.length>0&&n.push({label:`Not Legal Name: ${a.legalNameExclude.map(je).join(", ")}`,filterKey:"legalNameExclude",resetValue:[]}),a.industryNaicsInclude.length>0&&n.push({label:`NAICS Code: ${a.industryNaicsInclude.map(je).join(", ")}`,filterKey:"industryNaicsInclude",resetValue:[]}),a.industryNaicsExclude.length>0&&n.push({label:`Not NAICS Code: ${a.industryNaicsExclude.map(je).join(", ")}`,filterKey:"industryNaicsExclude",resetValue:[]}),a.dunsInclude.length>0&&n.push({label:`DUNS Number: ${a.dunsInclude.map(je).join(", ")}`,filterKey:"dunsInclude",resetValue:[]}),a.dunsExclude.length>0&&n.push({label:`Not DUNS Number: ${a.dunsExclude.map(je).join(", ")}`,filterKey:"dunsExclude",resetValue:[]}),a.sloganInclude.length>0&&n.push({label:`Slogan: ${a.sloganInclude.map(je).join(", ")}`,filterKey:"sloganInclude",resetValue:[]}),a.sloganExclude.length>0&&n.push({label:`Not Slogan: ${a.sloganExclude.map(je).join(", ")}`,filterKey:"sloganExclude",resetValue:[]}),a.logoUrlInclude.length>0&&n.push({label:`Logo URL: ${a.logoUrlInclude.map(je).join(", ")}`,filterKey:"logoUrlInclude",resetValue:[]}
120),a.logoUrlExclude.length>0&&n.push({label:`Not Logo URL: ${a.logoUrlExclude.map(je).join(", ")}`,filterKey:"logoUrlExclude",resetValue:[]}),a.founderInclude.length>0&&n.push({label:`Founder Name(s): ${a.founderInclude.map(je).join(", ")}`,filterKey:"founderInclude",resetValue:[]}),a.founderExclude.length>0&&n.push({label:`Not Founder Name(s): ${a.founderExclude.map(je).join(", ")}`,filterKey:"founderExclude",resetValue:[]}),a.founderEmailInclude.length>0&&n.push({label:`Founder Email(s): ${a.founderEmailInclude.map(je).join(", ")}`,filterKey:"founderEmailInclude",resetValue:[]}),a.founderEmailExclude.length>0&&n.push({label:`Not Founder Email(s): ${a.founderEmailExclude.map(je).join(", ")}`,filterKey:"founderEmailExclude",resetValue:[]}),a.founderPhoneInclude.length>0&&n.push({label:`Founder Phone(s): ${a.founderPhoneInclude.map(je).join(", ")}`,filterKey:"founderPhoneInclude",resetValue:[]}),a.founderPhoneExclude.length>0&&n.push({label:`Not Founder Phone(s): ${a.founderPhoneExclude.map(je).join(", ")}`,filterKey:"founderPhoneExclude",resetValue:[]}),a.openingHoursInclude.length>0&&n.push({label:`Opening Hours: ${a.openingHoursInclude.map(je).join(", ")}`,filterKey:"openingHoursInclude",resetValue:[]}),a.openingHoursExclude.length>0&&n.push({label:`Not Opening Hours: ${a.openingHoursExclude.map(je).join(", ")}`,filterKey:"openingHoursExclude",resetValue:[]}),a.areaServedInclude.length>0&&n.push({label:`Area Served: ${a.areaServedInclude.map(je).join(", ")}`,filterKey:"areaServedInclude",resetValue:[]}),a.areaServedExclude.length>0&&n.push({label:`Not Area Served: ${a.areaServedExclude.map(je).join(", ")}`,filterKey:"areaServedExclude",resetValue:[]}),a.offersInclude.length>0&&n.push({label:`Offers: ${a.offersInclude.map(je).join(", ")}`,filterKey:"offersInclude",resetValue:[]}),a.offersExclude.length>0&&n.push({label:`Not Offers: ${a.offersExclude.map(je).join(", ")}`,filterKey:"offersExclude",resetValue:[]}),a.brandInclude.length>0&&n.push({label:`Brand: ${a.brandInclude.map(je).join(", ")}`,filterKey:"brandInclude",resetValue:[]}),a.brandExclude.length>0&&n.push({label:`Not Brand: ${a.brandExclude.map(je).join(", ")}`,filterKey:"brandExclude",resetValue:[]}),a.socialProfilesInclude.length>0&&n.push({label:`Social Profiles: ${a.socialProfilesInclude.map(je).join(", ")}`,filterKey:"socialProfilesInclude",resetValue:[]}),a.socialProfilesExclude.length>0&&n.push({label:`Not Social Profiles: ${a.socialProfilesExclude.map(je).join(", ")}`,filterKey:"socialProfilesExclude",resetValue:[]}),a.platformInclude.length>0&&n.push({label:`Platform: ${a.platformInclude.map(je).join(", ")}`,filterKey:"platformInclude",resetValue:[]}),a.platformExclude.length>0&&n.push({label:`Not Platform: ${a.platformExclude.map(je).join(", ")}`,filterKey:"platformExclude",resetValue:[]}),a.bookingOpsCrmSoftwareInclude.length>0&&n.push({label:`Booking/Ops/CRM Software: ${a.bookingOpsCrmSoftwareInclude.map(je).join(", ")}`,filterKey:"bookingOpsCrmSoftwareInclude",resetValue:[]}),a.bookingOpsCrmSoftwareExclude.length>0&&n.push({label:`Not Booking/Ops/CRM Software: ${a.bookingOpsCrmSoftwareExclude.map(je).join(", ")}`,filterKey:"bookingOpsCrmSoftwareExclude",resetValue:[]}),a.reputationChatSoftwareInclude.length>0&&n.push({label:`Reputation/Chat Software: ${a.reputationChatSoftwareInclude.map(je).join(", ")}`,filterKey:"reputationChatSoftwareInclude",resetValue:[]}),a.reputationChatSoftwareExclude.length>0&&n.push({label:`Not Reputation/Chat Software: ${a.reputationChatSoftwareExclude.map(je).join(", ")}`,filterKey:"reputationChatSoftwareExclude",resetValue:[]}),a.marketingEmailSoftwareInclude.length>0&&n.push({label:`Marketing/Email Software: ${a.marketingEmailSoftwareInclude.map(je).join(", ")}`,filterKey:"marketingEmailSoftwareInclude",resetValue:[]}),a.marketingEmailSoftwareExclude.length>0&&n.push({label:`Not Marketing/Email Software: ${a.marketingEmailSoftwareExclude.map(je).join(", ")}`,filterKey:"marketingEmailSoftwareExclude",resetValue:[]}),a.adPixelsInclude.length>0&&n.push({label:`Ad Pixels: ${a.adPixelsInclude.map(je).join(", ")}`,filterKey:"adPixelsInclude",resetValue:[]}),a.adPixelsExclude.length>0&&n.push({label:`Not Ad Pixels: ${a.adPixelsExclude.map(je).join(", ")}`,filterKey:"adPixelsExclude",resetValue:[]}
120),a.paymentFinancingSoftwareInclude.length>0&&n.push({label:`Payment/Financing Software: ${a.paymentFinancingSoftwareInclude.map(je).join(", ")}`,filterKey:"paymentFinancingSoftwareInclude",resetValue:[]}),a.paymentFinancingSoftwareExclude.length>0&&n.push({label:`Not Payment/Financing Software: ${a.paymentFinancingSoftwareExclude.map(je).join(", ")}`,filterKey:"paymentFinancingSoftwareExclude",resetValue:[]}),a.employeeCountEmptyFilter!=="any"&&n.push({label:`Employees: ${b(a.employeeCountEmptyFilter)}`,filterKey:"employeeCountEmptyFilter",resetValue:"any"}),a.foundingDateEmptyFilter!=="any"&&n.push({label:`Founding Date: ${b(a.foundingDateEmptyFilter)}`,filterKey:"foundingDateEmptyFilter",resetValue:"any"}),a.isChainEmptyFilter!=="any"&&n.push({label:`Is Chain?: ${b(a.isChainEmptyFilter)}`,filterKey:"isChainEmptyFilter",resetValue:"any"}),a.priceRangeEmptyFilter!=="any"&&n.push({label:`Price Range: ${b(a.priceRangeEmptyFilter)}`,filterKey:"priceRangeEmptyFilter",resetValue:"any"}),a.legalNameEmptyFilter!=="any"&&n.push({label:`Legal Name: ${b(a.legalNameEmptyFilter)}`,filterKey:"legalNameEmptyFilter",resetValue:"any"}),a.industryNaicsEmptyFilter!=="any"&&n.push({label:`NAICS Code: ${b(a.industryNaicsEmptyFilter)}`,filterKey:"industryNaicsEmptyFilter",resetValue:"any"}),a.dunsEmptyFilter!=="any"&&n.push({label:`DUNS Number: ${b(a.dunsEmptyFilter)}`,filterKey:"dunsEmptyFilter",resetValue:"any"}),a.sloganEmptyFilter!=="any"&&n.push({label:`Slogan: ${b(a.sloganEmptyFilter)}`,filterKey:"sloganEmptyFilter",resetValue:"any"}),a.logoUrlEmptyFilter!=="any"&&n.push({label:`Logo URL: ${b(a.logoUrlEmptyFilter)}`,filterKey:"logoUrlEmptyFilter",resetValue:"any"}),a.founderEmptyFilter!=="any"&&n.push({label:`Founder Name(s): ${b(a.founderEmptyFilter)}`,filterKey:"founderEmptyFilter",resetValue:"any"}),a.founderEmailEmptyFilter!=="any"&&n.push({label:`Founder Email(s): ${b(a.founderEmailEmptyFilter)}`,filterKey:"founderEmailEmptyFilter",resetValue:"any"}),a.founderPhoneEmptyFilter!=="any"&&n.push({label:`Founder Phone(s): ${b(a.founderPhoneEmptyFilter)}`,filterKey:"founderPhoneEmptyFilter",resetValue:"any"}),a.openingHoursEmptyFilter!=="any"&&n.push({label:`Opening Hours: ${b(a.openingHoursEmptyFilter)}`,filterKey:"openingHoursEmptyFilter",resetValue:"any"}),a.areaServedEmptyFilter!=="any"&&n.push({label:`Area Served: ${b(a.areaServedEmptyFilter)}`,filterKey:"areaServedEmptyFilter",resetValue:"any"}),a.offersEmptyFilter!=="any"&&n.push({label:`Offers: ${b(a.offersEmptyFilter)}`,filterKey:"offersEmptyFilter",resetValue:"any"}),a.brandEmptyFilter!=="any"&&n.push({label:`Brand: ${b(a.brandEmptyFilter)}`,filterKey:"brandEmptyFilter",resetValue:"any"}),a.socialProfilesEmptyFilter!=="any"&&n.push({label:`Social Profiles: ${b(a.socialProfilesEmptyFilter)}`,filterKey:"socialProfilesEmptyFilter",resetValue:"any"}),a.platformEmptyFilter!=="any"&&n.push({label:`Platform: ${b(a.platformEmptyFilter)}`,filterKey:"platformEmptyFilter",resetValue:"any"}),a.bookingOpsCrmSoftwareEmptyFilter!=="any"&&n.push({label:`Booking/Ops/CRM Software: ${b(a.bookingOpsCrmSoftwareEmptyFilter)}`,filterKey:"bookingOpsCrmSoftwareEmptyFilter",resetValue:"any"}),a.reputationChatSoftwareEmptyFilter!=="any"&&n.push({label:`Reputation/Chat Software: ${b(a.reputationChatSoftwareEmptyFilter)}`,filterKey:"reputationChatSoftwareEmptyFilter",resetValue:"any"}),a.marketingEmailSoftwareEmptyFilter!=="any"&&n.push({label:`Marketing/Email Software: ${b(a.marketingEmailSoftwareEmptyFilter)}`,filterKey:"marketingEmailSoftwareEmptyFilter",resetValue:"any"}),a.adPixelsEmptyFilter!=="any"&&n.push({label:`Ad Pixels: ${b(a.adPixelsEmptyFilter)}`,filterKey:"adPixelsEmptyFilter",resetValue:"any"}),a.paymentFinancingSoftwareEmptyFilter!=="any"&&n.push({label:`Payment/Financing Software: ${b(a.paymentFinancingSoftwareEmptyFilter)}`,filterKey:"paymentFinancingSoftwareEmptyFilter",resetValue:"any"}),(a.minNumLocations||a.maxNumLocations)&&n.push({label:`Number of Locations: ${a.minNumLocations||"0"}-${a.maxNumLocations||"â"}`,filterKey:"minNumLocations",resetValue:"__nl__"}),(a.minOpenPositions||a.maxOpenPositions)&&n.push({label:`Number of Job Postings: ${a.minOpenPositions||"0"}-${a.maxOpenPositions||"â"}`,filterKey:"minOpenPositions",resetValue:"__op__"}),a.openPositionsEmptyFilter!=="any"&&n.push({label:`Number of Job Postings: ${b(a.openPositionsEmptyFilter)}`,filterKey:"openPositionsEmptyFilter",resetValue:"any"}),(a.minRatingValue||a.maxRatingValue)&&n.push({label:`Rating Value: ${a.minRatingValue||"0"}-${a.maxRatingValue||"5"}`,filterKey:"minRatingValue",resetValue:"__rv__"}),(a.minReviewCount||a.maxReviewCount)&&n.push({label:`Review Count: ${a.minReviewCount||"0"}-${a.maxReviewCount||"â"}`,filterKey:"minReviewCount",resetValue:"__rc__"}),(a.timeScrapedFrom||a.timeScrapedTo)&&((h=a.timeScrapedFrom)!=null&&h.startsWith("rel:")?n.push({label:`Scraped: ${Mn(a.timeScrapedFrom)}`,filterKey:"timeScrapedFrom",resetValue:""}):(a.timeScrapedFrom&&n.push({label:`Scraped from: ${a.timeScrapedFrom}`,filterKey:"timeScrapedFrom",resetValue:""}),a.timeScrapedTo&&n.push({label:`Scraped to: ${a.timeScrapedTo}`,filterKey:"timeScrapedTo",resetValue:""}))),(a.registrationDateFrom||a.registrationDateTo)&&((L=a.registrationDateFrom)!=null&&L.startsWith("rel:")?n.push({label:`Registered: ${Mn(a.registrationDateFrom)}`,filterKey:"registrationDateFrom",resetValue:""}):(a.registrationDateFrom&&n.push({label:`Registered from: ${a.registrationDateFrom}`,filterKey:"registrationDateFrom",resetValue:""}),a.registrationDateTo&&n.push({label:`Registered to: ${a.registrationDateTo}`,filterKey:"registrationDateTo",resetValue:""}))),(a.lastUpdatedFrom||a.lastUpdatedTo)&&((_=a.lastUpdatedFrom)!=null&&_.startsWith("rel:")?n.push({label:`${ca}: ${Mn(a.lastUpdatedFrom)}`,filterKey:"lastUpdatedFrom",resetValue:""}):(a.lastUpdatedFrom&&n.push({label:`${ca} from: ${a.lastUpdatedFrom}`,filterKey:"lastUpdatedFrom",resetValue:""}),a.lastUpdatedTo&&n.push({label:`${ca} to: ${a.lastUpdatedTo}`,filterKey:"lastUpdatedTo",resetValue:""}))),a.updateReasonFilter.length>0&&n.push({label:`${Xa}: ${a.updateReasonFilter.join(", ")}`,filterKey:"updateReasonFilter",resetValue:[]}),a.websiteSchemaFilter.length>0&&n.push({label:`Website Schema: ${a.websiteSchemaFilter.join(", ")}`,filterKey:"websiteSchemaFilter",resetValue:[]}),a.emailPrimaryMxValues.length>0&&n.push({label:`Email Primary Provider: ${a.emailPrimaryMxValues.join(", ")}`,filterKey:"emailPrimaryMxValues",resetValue:[]}),a.emailPrimaryMxEmptyFilter!=="any"&&n.push({label:`Email Primary Provider: ${b(a.emailPrimaryMxEmptyFilter)}`,filterKey:"emailPrimaryMxEmptyFilter",resetValue:"any"}),a.emailDomainMxValues.length>0&&n.push({label:`Website Email Provider: ${a.emailDomainMxValues.join(", ")}`,filterKey:"emailDomainMxValues",resetValue:[]}),a.emailDomainMxEmptyFilter!=="any"&&n.push({label:`Website Email Provider: ${b(a.emailDomainMxEmptyFilter)}`,filterKey:"emailDomainMxEmptyFilter",resetValue:"any"}),a.emailSecurityValues.length>0&&n.push({label:`Website Email Security: ${a.emailSecurityValues.join(", ")}`,filterKey:"emailSecurityValues",resetValue:[]}),a.emailSecurityEmptyFilter!=="any"&&n.push({label:`Website Email Security: ${b(a.emailSecurityEmptyFilter)}`,filterKey:"emailSecurityEmptyFilter",resetValue:"any"}),a.addressSourceValues.length>0&&n.push({label:`Address Source: ${a.addressSourceValues.join(", ")}`,filterKey:"addressSourceValues",resetValue:[]}),a.addressSourceEmptyFilter!=="any"&&n.push({label:`Address Source: ${b(a.addressSourceEmptyFilter)}`,filterKey:"addressSourceEmptyFilter",resetValue:"any"}),n},[a]),Bt=o.useMemo(()=>{const n=[],b=Array.from(new Set(a.nameKeywordListIds.concat(a.urlKeywordListIds,a.crawledUrlKeywordListIds,a.descriptionKeywordListIds,a.categoryKeywordListIds)));for(const h of Te.filter(L=>
120b.includes(L.id)))a.nameKeywordListIds.includes(h.id)&&n.push({id:h.id,name:h.name,type:h.type,isDefault:h.isDefault,scope:"name"}),a.urlKeywordListIds.includes(h.id)&&n.push({id:h.id,name:h.name,type:h.type,isDefault:h.isDefault,scope:"url"}),a.crawledUrlKeywordListIds.includes(h.id)&&n.push({id:h.id,name:h.name,type:h.type,isDefault:h.isDefault,scope:"crawledUrl"}),a.descriptionKeywordListIds.includes(h.id)&&n.push({id:h.id,name:h.name,type:h.type,isDefault:h.isDefault,scope:"description"}),a.categoryKeywordListIds.includes(h.id)&&n.push({id:h.id,name:h.name,type:h.type,isDefault:h.isDefault,scope:"category"});return n},[Te,a.nameKeywordListIds,a.urlKeywordListIds,a.crawledUrlKeywordListIds,a.descriptionKeywordListIds,a.categoryKeywordListIds]),he=({column:n,children:b})=>{if(!mp.includes(n))return e.jsx("span",{children:b});const h=a.sortBy===n;return e.jsxs("button",{onClick:()=>Ft(n),className:"flex items-center gap-1 hover:text-gray-900 dark:hover:text-white transition-colors font-medium",children:[b,h?a.sortOrder==="asc"?e.jsx(si,{className:"h-3.5 w-3.5"}):e.jsx(ai,{className:"h-3.5 w-3.5"}):e.jsx(li,{className:"h-3.5 w-3.5 opacity-40"})]})},_s=(n,b)=>{const h={...a};switch(b){case"name":h.nameKeywordListIds=h.nameKeywordListIds.filter(L=>L!==n);break;case"url":h.urlKeywordListIds=h.urlKeywordListIds.filter(L=>L!==n);break;case"crawledUrl":h.crawledUrlKeywordListIds=h.crawledUrlKeywordListIds.filter(L=>L!==n);break;case"description":h.descriptionKeywordListIds=h.descriptionKeywordListIds.filter(L=>L!==n);break;case"category":h.categoryKeywordListIds=h.categoryKeywordListIds.filter(L=>L!==n);break}q(h),K(!1),X(new Set),v(1),z.removeQueries({queryKey:["/api/leads"]})};return ae?e.jsxs("div",{className:"space-y-4",children:[St&&mt&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 rounded-lg bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-800 text-sm text-blue-700 dark:text-blue-300",children:[e.jsx(Kt,{className:"h-4 w-4 flex-shrink-0 animate-pulse"}),e.jsx("span",{children:"Our AI auto refiner is optimizing your keywords right now - expect even more relevant results in a few minutes!"})]}),e.jsxs(Ue,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs(Vt,{className:"text-lg flex items-center gap-2",children:["Lead Results",e.jsx(ie,{variant:"secondary",className:"text-xs font-normal","data-testid":"badge-active-database",children:J.badgeName}),mt&&e.jsx("span",{className:"text-sm font-normal text-gray-500",children:le&&!P?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," ",e.jsx("span",{className:"text-sm text-muted-foreground",children:"Calculating total results"})]}):P?e.jsxs(e.Fragment,{children:["(",(is??0).toLocaleString()," total)"]}):null}),It&&!gt&&e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," ",e.jsx("span",{className:"text-sm text-muted-foreground",children:"Refreshing results"})]})]}),ar()]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("div",{className:"relative flex items-center gap-1",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_l,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-gray-400"}),e.jsx(Ee,{placeholder:"Search all fields...",value:ne,onChange:n=>Q(n.target.value),onKeyDown:n=>{n.key==="Enter"&&Ye()},className:"pl-7 h-8 text-xs w-40 sm:w-52"}),ne&&e.jsx("button",{onClick:()=>{Q(""),q(n=>({...n,search:""})),K(!1),X(new Set),v(1)},className:"absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:e.jsx(Ut,{className:"h-3 w-3"})})]}),e.jsx(N,{size:"sm",className:"h-8 text-xs px-3 bg-blue-600 hover:bg-blue-700 text-white",onClick:Ye,children:"Apply"})]}),e.jsx(To,{selectedIds:Array.from($),disabled:De.isPending,onSuccess:()=>X(new Set)}),e.jsx(N,{size:"sm",onClick:bs,disabled:De.isPending||!B&&$.size===0&&!Nt,className:"text-xs bg-gradient-to-r from-blue-600 via-purple-600 to-pink-600 hover:from-blue-700 hover:via-purple-700 hover:to-pink-700 border-0",children:De.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Qs,{className:"h-3.5 w-3.5 mr-1"}
120),"Export",B&&Ae?` (${Ae.total.toLocaleString()})`:$.size>0?` (${$.size.toLocaleString()})`:Nt?` (${W.toLocaleString()})`:""]})})]})]})}),e.jsxs(_e,{className:"space-y-3 pt-0",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[e.jsxs(Ns,{open:He,onOpenChange:ee,children:[e.jsx(Es,{asChild:!0,children:e.jsxs(N,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1",children:[e.jsx(eo,{className:"h-3 w-3"}),"Saved Filters",kt.length>0&&e.jsx("span",{className:"ml-0.5 bg-blue-100 text-blue-700 rounded-full px-1.5 text-[10px] font-medium",children:kt.length})]})}),e.jsx(ys,{align:"start",className:"w-72 p-2",children:kt.length===0?e.jsx("p",{className:"text-xs text-gray-500 text-center py-3",children:"No saved filters yet"}):e.jsx("div",{className:"space-y-1 max-h-60 overflow-y-auto",children:kt.map(n=>{var ts;const b=typeof n.filters=="string"?n.filters:((ts=n.filters)==null?void 0:ts.hash)||"",h=b?Dn(b,Te):{},L=[];let _=!1,G=!1;h.streetInclude&&h.streetInclude.length>0&&(_=!0,L.push(`Street: ${h.streetInclude.join(", ")}`)),h.streetExclude&&h.streetExclude.length>0&&(_=!0,L.push(`Not Street: ${h.streetExclude.join(", ")}`));const We=[{key:"streetEmptyFilter",label:"Street"},{key:"cityEmptyFilter",label:"City"},{key:"stateEmptyFilter",label:"State"},{key:"zipEmptyFilter",label:"Zip"},{key:"phonePrimaryEmptyFilter",label:"Phone (primary)"},{key:"phoneTotalEmptyFilter",label:"Total Phones"},{key:"emailPrimaryEmptyFilter",label:"Email (primary)"},{key:"emailTier1EmptyFilter",label:"Tier 1 Emails"},{key:"emailTier2EmptyFilter",label:"Tier 2 Emails"},{key:"emailTier3EmptyFilter",label:"Tier 3 Emails"},{key:"emailTier4EmptyFilter",label:"Tier 4 Emails"},{key:"emailTier5EmptyFilter",label:"Tier 5 Emails"},{key:"emailTier6EmptyFilter",label:"Tier 6 Emails"},{key:"descriptionEmptyFilter",label:"Description"}];for(const Zt of We){const nt=h[Zt.key];nt&&nt!=="any"&&(G=!0,L.push(`${Zt.label}: ${nt==="only_empty"?"only empty":"non-empty"}`))}const gs=L.length>0?`${n.name} 121${L.join(` 122`)}`:n.name;return e.jsxs("div",{className:"flex items-center gap-1 group",children:[e.jsxs("button",{className:"flex-1 text-left text-xs px-2 py-1.5 rounded hover:bg-gray-100 dark:hover:bg-gray-800 truncate flex items-center gap-1 min-w-0",title:gs,onClick:()=>{if(b){const Zt=Dn(b,Te),nt={...Gr,...Zt};q(nt),Q(nt.search||""),K(!1),X(new Set),v(1),z.removeQueries({queryKey:["/api/leads"]});const ss=window.location.pathname+window.location.search+b;window.history.replaceState(null,"",ss)}ee(!1)},children:[e.jsx("span",{className:"truncate flex-1 min-w-0",children:n.name}),_&&e.jsx("span",{className:"shrink-0 bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300 rounded px-1 text-[9px] font-medium uppercase tracking-wide",children:"Street"}),G&&e.jsx("span",{className:"shrink-0 bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-300 rounded px-1 text-[9px] font-medium uppercase tracking-wide",children:"Empty"})]}),e.jsx("button",{className:"opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-red-50 hover:text-red-600 transition-opacity",onClick:Zt=>{Zt.stopPropagation(),qt.mutate(n.id)},children:e.jsx(Hs,{className:"h-3 w-3"})})]},n.id)})})})]}),e.jsxs(N,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1",onClick:()=>{if(!Wr(a)){A({title:"No active filters to save"});return}Me(""),Se(!0)},children:[e.jsx(nr,{className:"h-3 w-3"}),"Save Filters"]}),e.jsxs(N,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1",onClick:()=>{const n=et.filter(L=>L.isDefault),b=Ot.filter(L=>L.isDefault),h=[...n,...b].map(L=>L.id);q({...Gr,orColumns:[...hi],nameKeywordListIds:h,urlKeywordListIds:h,crawledUrlKeywordListIds:h,categoryKeywordListIds:h,redirectFilter:"no"}),Q(""),v(1),X(new Set),K(!1),fe.current=!0,U.current=Wn(Te),_t.current=!0,z.removeQueries({queryKey:["/api/leads"]}),window.history.replaceState(null,"",window.location.pathname),A({title:"Filters reset to defaults"})},children:[e.jsx(to,{className:"h-3 w-3"}),"Reset Filters"]}),e.jsxs(N,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1",onClick:()=>{_t.current=!0,z.removeQueries({queryKey:["/api/leads"]}),A({title:"Refreshing results..."})},disabled:It||le,children:[e.jsx(Ks,{className:`h-3 w-3 ${It||le?"animate-spin":""}`}),"Refresh Results"]}),e.jsxs("div",{className:"flex items-center gap-1",title:"Select the first N leads by the current sort (default newest first)",children:[e.jsx("span",{className:"text-xs text-gray-500",children:"Select first"}),e.jsx(Ee,{type:"number",min:1,placeholder:"N",value:ve,onChange:n=>Oe(n.target.value),onKeyDown:n=>{n.key==="Enter"&&ls()},onBlur:Rs,disabled:!mt,className:`h-7 w-16 text-xs ${vt?"animate-border-flash":""}`}),e.jsxs(N,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1",onClick:ls,disabled:!mt||!ve.trim(),children:[e.jsx(sa,{className:"h-3 w-3"}),"Apply"]}),Nt&&e.jsxs(ie,{variant:"secondary",className:"text-[10px] px-1.5 py-0.5 flex items-center gap-0.5",children:["First ",W.toLocaleStr
122ing(),e.jsx("button",{onClick:()=>{Le(null),Oe("")},className:"ml-0.5 hover:opacity-70",children:e.jsx(Ut,{className:"h-2.5 w-2.5"})})]})]}),(Bt.length>0||ms.length>0)&&e.jsx("span",{className:"w-px h-5 bg-gray-200 dark:bg-gray-700 mx-0.5"}),Bt.map((n,b)=>e.jsxs(ie,{variant:n.type==="positive"?"default":"destructive",className:`text-[10px] px-1.5 py-0.5 flex items-center gap-0.5 ${n.type==="positive"?"bg-blue-600 hover:bg-blue-700":""}`,children:[e.jsx(Kt,{className:"h-2.5 w-2.5 mr-0.5"}),n.type==="positive"?"+":"-"," ",n.name,e.jsxs("span",{className:"ml-0.5 opacity-60",children:["(",Ps[n.scope],")"]}),n.isDefault&&e.jsx("span",{className:"opacity-60",children:"(default)"}),e.jsx("button",{onClick:()=>_s(n.id,n.scope),className:"ml-0.5 hover:opacity-70",children:e.jsx(Ut,{className:"h-2.5 w-2.5"})})]},`kl-${n.id}-${n.scope}`)),ms.map((n,b)=>e.jsxs(ie,{variant:"secondary",className:"text-[10px] px-1.5 py-0.5 flex items-center gap-0.5",children:[n.label,e.jsx("button",{onClick:()=>{const h={...a};n.resetValue==="__nl__"?(h.minNumLocations="",h.maxNumLocations=""):n.resetValue==="__op__"?(h.minOpenPositions="",h.maxOpenPositions=""):n.resetValue==="__rv__"?(h.minRatingValue="",h.maxRatingValue=""):n.resetValue==="__rc__"?(h.minReviewCount="",h.maxReviewCount=""):h[n.filterKey]=n.resetValue,n.filterKey==="search"&&Q(""),q(h),K(!1),X(new Set),v(1),z.removeQueries({queryKey:["/api/leads"]})},className:"ml-0.5 hover:opacity-70",children:e.jsx(Ut,{className:"h-2.5 w-2.5"})})]},`f-${b}`))]}),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border rounded-lg overflow-auto max-h-[70vh]",children:e.jsxs(Nn,{children:[e.jsx(En,{className:"sticky top-0 z-20 bg-white dark:bg-gray-950 leads-table-headers shadow-[inset_0_-2px_0_0_rgba(229,231,235,1)] dark:shadow-[inset_0_-2px_0_0_rgba(55,65,81,1)]",children:e.jsxs(za,{children:[e.jsx(Ke,{className:"w-20 sticky left-0 z-30 bg-white dark:bg-gray-950 text-center shadow-[inset_-2px_0_0_0_rgba(229,231,235,1)] dark:shadow-[inset_-2px_0_0_0_rgba(55,65,81,1)]",children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx(Ws,{checked:bt,onCheckedChange:Xt,disabled:!mt||yt.length===0||gt})})}),e.jsx(Ke,{className:"min-w-[200px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"lastUpdated",children:ca}),e.jsx($n,{column:"lastUpdated",label:ca,filters:a,onApply:oe})]})}),e.jsx(Ke,{className:"min-w-[200px]",children:e.jsxs("div",{className:"flex items-center gap-1",children:[Xa,e.jsx(bp,{options:Nd,selected:a.updateReasonFilter,onApply:n=>oe({updateReasonFilter:n})})]})}),e.jsx(Cs,{columnKey:"wOgrequestedUrl",isActive:a.orColumns.includes("wOgrequestedUrl"),className:"min-w-[280px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wOgrequestedUrl",children:"Registered URL"}),e.jsx(hr,{column:"wOgrequestedUrl",label:"Registered URL",filters:a,keywordLists:Te,onApply:oe,orColumns:a.orColumns,columnKey:"wOgrequestedUrl"})]})}),e.jsx(Ke,{className:"min-w-[120px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wProfileDate",children:"Registration Date"}),e.jsx($n,{column:"wProfileDate",label:"Registration Date",filters:a,onApply:oe})]})}),e.jsx(Ke,{className:"min-w-[70px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wRedirectYn",children:"Redirect"}),e.jsx(vp,{filters:a,onApply:oe})]})}),e.jsx(Cs,{columnKey:"wSimpleCrawledUrl",isActive:a.orColumns.includes("wSimpleCrawledUrl"),className:"min-w-[280px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wSimpleCrawledUrl",children:"Crawled URL"}),e.jsx(hr,{column:"wSimpleCrawledUrl",label:"Crawled URL",filters:a,keywordLists:Te,onApply:oe,orColumns:a.orColumns,columnKey:"wSimpleCrawledUrl"})]})}),e.jsx(Cs,{columnKey:"wCompanyName",isActive:a.orColumns.includes("wCompanyName"),className:"min-w-[280px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wCompanyName",children:"Company Name"}),e.jsx(hr,{column:"wCompanyName",label:"Company Name",filters:a,keywordLists:Te,onApply:oe,orColumns:a.orColumns,columnKey:"wCompanyName"})]})}),e.jsx(Cs,{columnKey:"aiCategoryEstimation",isActive:a.orColumns.includes("aiCategoryEstimation"),className:"min-w-[200px]",children:e.jsxs("div",{className:"flex items-center",children:["Categories (AI Enrichment)",e.jsx(hr,{column:"aiCategoryEstimation",label:"Categories (AI Enrichment)",filters:a,keywordLists:Te,onApply:oe,orColumns:a.orColumns,columnKey:"aiCategoryEstimation"})]})}),e.jsx(Cs,{columnKey:"wPhonePrimary",isActive:a.orColumns.includes("wPhonePrimary"),className:"min-w-[120px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wPhonePrimary",children:"Phone Primary"}),e.jsx(wt,{column:"wPhonePrimary",label:"Phone Primary",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wPhonePrimary"})]})}),e.jsx(Cs,{columnKey:"wPhoneTotal",isActive:a.orColumns.includes("wPhoneTotal"),className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:["Total Phones",e.jsx(wt,{column:"wPhoneTotal",label:"Total Phones",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wPhoneTotal"})]})}),e.jsx(Cs,{columnKey:"wEmailPrimary",isActive:a.orColumns.includes("wEmailPrimary"),className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wEmailPrimary",children:"Email Primary"}),e.jsx(wt,{column:"wEmailPrimary",label:"Email Primary",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wEmailPrimary"})]})}),e.jsx(Ke,{className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wEmailPrimaryMx",children:"Email Primary Provider"}),e.jsx(Br,{field:"emailPrimaryMx",label:"Email Primary Provider",valuesKey:"emailPrimaryMxValues",emptyKey:"emailPrimaryMxEmptyFilter",filters:a,onApply:oe})]})}),e.jsx(Cs,{columnKey:"wEmailTier1",isActive:a.orColumns.includes("wEmailTier1"),className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:["Tier 1 Emails",e.jsx(wt,{column:"wEmailTier1",label:"Tier 1 Emails",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wEmailTier1"})]})}),e.jsx(Cs,{columnKey:"wEmailTier2",isActive:a.orColumns.includes("wEmailTier2"),className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:["Tier 2 Emails",e.jsx(wt,{column:"wEmailTier2",label:"Tier 2 Emails",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wEmailTier2"})]})}),e.jsx(Cs,{columnKey:"wEmailTier3",isActive:a.orColumns.includes("wEmailTier3"),className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:["Tier 3 Emails",e.jsx(wt,{column:"wEmailTier3",label:"Tier 3 Emails",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wEmailTier3"})]})}),e.jsx(Cs,{columnKey:"wEmailTier4",isActive:a.orColumns.includes("wEmailTier4"),className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:["Tier 4 Emails",e.jsx(wt,{column:"wEmailTier4",label:"Tier 4 Emails",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wEmailTier4"})]})}),e.jsx(Cs,{columnKey:"wEmailTier5",isActive:a.orColumns.includes("wEmailTier5"),className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:["Tier 5 Emails",e.jsx(wt,{column:"wEmailTier5",label:"Tier 5 Emails",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wEmailTier5"})]})}),e.jsx(Cs,{columnKey:"wEmailTier6",isActive:a.orColumns.includes("wEmailTier6"),className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:["Tier 6 Emails",e.jsx(wt,{column:"wEmailTier6",label:"Tier 6 Emails",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wEmailTier6"})]})}),e.jsx(Ke,{className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wEmailDomainMx",children:"Website Email Provider"}),e.jsx(Br,{field:"emailDomainMx",label:"Website Email Provider",valuesKey:"emailDomainMxValues",emptyKey:"emailDomainMxEmptyFilter",filters:a,onApply:oe})]})}),e.jsx(Ke,{className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wEmailSecurity",children:"Website Email Security"}),e.jsx(Br,{field:"emailSecurity",label:"Website Email Security",valuesKey:"emailSecurityValues",emptyKey:"emailSecurityEmptyFilter",filters:a,onApply:oe})]})}),e.jsx(Ke,{className:"min-w-[140px]",children:e.jsxs("div",{className:"flex items-center gap-1",children:["Website Schema",e.jsx(wp,{selected:a.websiteSchemaFilter,onApply:n=>oe({websiteSchemaFilter:n})})]})}),e.jsx(Cs,{columnKey:"wProfileDescriptionShort",isActive:a.orColumns.includes("wProfileDescriptionShort"),className:"min-w-[200px]",children:e.jsxs("div",{className:"flex items-center",children:["Description Short",e.jsx(hr,{column:"wProfileDescriptionShort",label:"Description Short",filters:a,keywordLists:Te,onApply:oe,orColumns:a.orColumns,columnKey:"wProfileDescriptionShort"})]})}),e.jsx(Ke,{className:"min-w-[200px]",children:"Description Long"}),e.jsx(Ke,{className:"min-w-[150px]",children:"Address Full"}),e.jsx(Cs,{columnKey:"wAddressStreet",isActive:a.orColumns.includes("wAddressStreet"),className:"min-w-[130px]",children:e.jsxs("div",{className:"flex items-center",children:["Street",e.jsx(wt,{column:"wAddressStreet",label:"Street",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wAddressStreet"})]})}),e.jsx(Cs,{columnKey:"wAddressCity",isActive:a.orColumns.includes("wAddressCity"),className:"min-w-[120px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wAddressCity",children:"City"}),e.jsx(wt,{column:"wAddressCity",label:"City",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wAddressCity"})]})}),e.jsx(Cs,{columnKey:"wAddressState",isActive:a.orColumns.includes("wAddressState"),className:"min-w-[60px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wAddressState",children:"State"}
122),e.jsx(wt,{column:"wAddressState",label:"State",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wAddressState"})]})}),e.jsx(Cs,{columnKey:"wAddressZip",isActive:a.orColumns.includes("wAddressZip"),className:"min-w-[70px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wAddressZip",children:"Zip"}),e.jsx(wt,{column:"wAddressZip",label:"Zip",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wAddressZip"})]})}),e.jsx(Ke,{className:"min-w-[140px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wAddressSource",children:"Address Source"}),e.jsx(Br,{field:"addressSource",label:"Address Source",valuesKey:"addressSourceValues",emptyKey:"addressSourceEmptyFilter",filters:a,onApply:oe})]})}),e.jsx(Ke,{className:"min-w-[140px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wPlatform",children:"Platform"}),e.jsx(wt,{column:"wPlatform",label:"Platform",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wPlatform",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[200px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wBookingOpsCrmSoftware",children:"Booking/Ops/CRM Software"}),e.jsx(wt,{column:"wBookingOpsCrmSoftware",label:"Booking/Ops/CRM Software",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wBookingOpsCrmSoftware",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[200px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wReputationChatSoftware",children:"Reputation/Chat Software"}),e.jsx(wt,{column:"wReputationChatSoftware",label:"Reputation/Chat Software",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wReputationChatSoftware",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[200px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wMarketingEmailSoftware",children:"Marketing/Email Software"}),e.jsx(wt,{column:"wMarketingEmailSoftware",label:"Marketing/Email Software",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wMarketingEmailSoftware",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[140px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wAdPixels",children:"Ad Pixels"}),e.jsx(wt,{column:"wAdPixels",label:"Ad Pixels",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wAdPixels",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[200px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wPaymentFinancingSoftware",children:"Payment/Financing Software"}),e.jsx(wt,{column:"wPaymentFinancingSoftware",label:"Payment/Financing Software",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wPaymentFinancingSoftware",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[120px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wEmployeeCount",children:"Employees"}),e.jsx(wt,{column:"wEmployeeCount",label:"Employees",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wEmployeeCount",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[150px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wOpenPositions",children:"Number of Job Postings"}),e.jsx(Jr,{column:"wOpenPositions",label:"Number of Job Postings",filters:a,onApply:oe})]})}),e.jsx(Ke,{className:"min-w-[120px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wFoundingDate",children:"Founding Date"}),e.jsx(wt,{column:"wFoundingDate",label:"Founding Date",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wFoundingDate",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[140px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wNumLocations",children:"Number of Locations"}),e.jsx(Jr,{column:"wNumLocations",label:"Number of Locations",filters:a,onApply:oe})]})}),e.jsx(Ke,{className:"min-w-[90px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wIsChain",children:"Is Chain?"}),e.jsx(wt,{column:"wIsChain",label:"Is Chain?",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wIsChain",supp
122ortsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[120px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wRatingValue",children:"Rating Value"}),e.jsx(Jr,{column:"wRatingValue",label:"Rating Value",filters:a,onApply:oe})]})}),e.jsx(Ke,{className:"min-w-[120px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wReviewCount",children:"Review Count"}),e.jsx(Jr,{column:"wReviewCount",label:"Review Count",filters:a,onApply:oe})]})}),e.jsx(Ke,{className:"min-w-[110px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wPriceRange",children:"Price Range"}),e.jsx(wt,{column:"wPriceRange",label:"Price Range",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wPriceRange",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wLegalName",children:"Legal Name"}),e.jsx(wt,{column:"wLegalName",label:"Legal Name",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wLegalName",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[110px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wIndustryNaics",children:"NAICS Code"}),e.jsx(wt,{column:"wIndustryNaics",label:"NAICS Code",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wIndustryNaics",supp
122ortsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[120px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wDuns",children:"DUNS Number"}),e.jsx(wt,{column:"wDuns",label:"DUNS Number",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wDuns",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wFounder",children:"Founder Name(s)"}),e.jsx(wt,{column:"wFounder",label:"Founder Name(s)",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wFounder",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[180px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wFounderEmail",children:"Founder Email(s)"}),e.jsx(wt,{column:"wFounderEmail",label:"Founder Email(s)",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wFounderEmail",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wFounderPhone",children:"Founder Phone(s)"}),e.jsx(wt,{column:"wFounderPhone",label:"Founder Phone(s)",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wFounderPhone",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[100px]",children:e.jsx("div",{className:"flex items-center",children:e.jsx(he,{column:"wGeoLat",children:"Latitude"})})}),e.jsx(Ke,{className:"min-w-[100px]",children:e.jsx("div",{className:"flex items-center",children:e.jsx(he,{column:"wGeoLong",children:"Longitude"})})}),e.jsx(Ke,{className:"min-w-[180px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wOpeningHours",children:"Opening Hours"}),e.jsx(wt,{column:"wOpeningHours",label:"Opening Hours",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wOpeningHours",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wAreaServed",children:"Area Served"}),e.jsx(wt,{column:"wAreaServed",label:"Area Served",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wAreaServed",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wOffers",children:"Offers"}),e.jsx(wt,{column:"wOffers",label:"Offers",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wOffers",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[140px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wBrand",children:"Brand"}),e.jsx(wt,{column:"wBrand",label:"Brand",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wBrand",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wSlogan",children:"Slogan"}),e.jsx(wt,{column:"wSlogan",label:"Slogan",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wSlogan",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[140px]",children:"Logo URL"}),e.jsx(Ke,{className:"min-w-[180px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wSocialProfiles",children:"Social Profiles"}),e.jsx(wt,{column:"wSocialProfiles",label:"Social Profiles",filters:a,onApply:oe,orColumns:a.orColumns,columnKey:"wSocialProfiles",supportsOrGroup:!1})]})}),e.jsx(Ke,{className:"min-w-[130px]",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(he,{column:"wTimeScraped",children:"Time Scraped"}),e.jsx($n,{column:"wTimeScraped",label:"Time Scraped",filters:a,onApply:oe})]})})]})}),e.jsx(Sn,{children:mt&&!gt&&yt.length>0?yt.map((n,b)=>{const h=(p-1)*y+b,L=$.has(n.id)||Nt&&h<W;return e.jsxs(za,{className:L?"bg-blue-50 dark:bg-blue-950":"",children:[e.jsx(Fe,{className:`p-2 sticky left-0 z-10 text-center shadow-[inset_-2px_0_0_0_rgba(229,231,235,1)] dark:shadow-[inset_-2px_0_0_0_rgba(55,65,81,1)] ${L?"bg-blue-50 dark:bg-blue-950":"bg-white dark:bg-gray-950"}`,children:e.jsx(Ws,{checked:L,onClick:_=>{_.stopPropagation(),fs(n.id,_.shiftKey)},onCheckedChange:()=>{},disabled:!w&&!$.has(n.id)&&$.size>=ye})}),e.jsx(Fe,{className:"text-xs text-gray-500 whitespace-nowrap cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:ca,value:n.lastUpdated?ul(n.lastUpdated):" - "}),children:n.lastUpdated?ul(n.lastUpdated):" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:Xa,value:Array.isArray(n.lastUpdatedReason)?n.lastUpdatedReason.join(", "):n.lastUpdatedReason||" - "}),children:e.jsx("div",{className:"flex flex-col gap-0.5",children:Array.isArray(n.lastUpdatedReason)&&n.lastUpdatedReason.length>0?n.lastUpdatedReason.map((_,G)=>{const We=yp[_]??fp;return e.jsx(ie,{className:`text-[10px] px-1.5 py-0.5 leading-none font-normal w-fit whitespace-nowrap border-0 ${We}`,children:_},G)}):e.jsx("span",{className:"text-xs text-gray-400",children:" - "})})}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Registered URL",value:n.wOgrequestedUrl||" - "}),children:n.wOgrequestedUrl?e.jsxs("a",{href:n.wOgrequestedUrl.startsWith("http")?n.wOgrequestedUrl:`https://${n.wOgrequestedUrl}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-blue-600 hover:text-blue-800 text-xs",onClick:_=>_.stopPropagation(),children:[e.jsx(aa,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate max-w-[140px]",children:n.wOgrequestedUrl.replace(/^https?:\/\//,"")})]}):" - "}),e.jsx(Fe,{className:"text-xs text-gray-500 whitespace-nowrap cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Registration Date",value:n.wProfileDate||" - "}),children:n.wProfileDate||" - "}),e.jsx(Fe,{className:"text-xs text-gray-500 cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Redirect",value:n.wRedirectYn||" - "}),children:n.wRedirectYn||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Crawled URL",value:n.wSimpleCrawledUrl||" - "}),children:n.wSimpleCrawledUrl?e.jsxs("a",{href:n.wSimpleCrawledUrl.startsWith("http")?n.wSimpleCrawledUrl:`https://${n.wSimpleCrawledUrl}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-blue-600 hover:text-blue-800 text-xs",onClick:_=>_.stopPropagation(),children:[e.jsx(aa,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate max-w-[140px]",children:n.wSimpleCrawledUrl.replace(/^https?:\/\//,"")})]}):" - "}),e.jsx(Fe,{className:"font-medium cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Company Name",value:n.wCompanyName||" - "}),children:e.jsx("span",{className:"block truncate max-w-[220px]",children:n.wCompanyName||" - "})}),e.jsx(Fe,{children:(()=>{const _=n.aiCategoryEstimation;if(!_)return e.jsx("span",{className:"text-xs text-gray-400",children:" - "});const G=_.replace(/^\[|\]$/g,"").split(/'\s*,\s*'/).map(We=>
122We.replace(/^'|'$/g,"").trim()).filter(Boolean);return G.length===0?e.jsx("span",{className:"text-xs text-gray-400",children:" - "}):e.jsx("div",{className:"flex flex-wrap gap-1",children:G.map((We,gs)=>e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",children:We},gs))})})()}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Phone Primary",value:n.wPhonePrimary||" - ",contactExported:n.contactExported}),children:n.wPhonePrimary?E&&!n.contactExported?e.jsxs("span",{title:Tt,className:"flex items-center gap-1 text-gray-500 cursor-default text-sm",children:[e.jsx(ya,{className:"h-3 w-3"}),n.wPhonePrimary]}):e.jsxs("span",{className:"flex items-center gap-1 text-blue-600 text-sm",children:[e.jsx(ei,{className:"h-3 w-3"}),n.wPhonePrimary]}):" - "}),e.jsx(la,{title:"Total Phones",value:n.wPhoneTotal,kind:"phone",shouldMaskContacts:E,contactExported:n.contactExported,maskedTooltipText:Tt,onOpen:()=>R({title:"Total Phones",value:n.wPhoneTotal||" - ",contactExported:n.contactExported})}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Email Primary",value:n.wEmailPrimary||" - ",contactExported:n.contactExported}),children:n.wEmailPrimary?E&&!n.contactExported?e.jsxs("span",{title:Tt,className:"flex items-center gap-1 text-gray-500 cursor-default text-xs",children:[e.jsx(ya,{className:"h-3 w-3"}),n.wEmailPrimary]}):e.jsxs("a",{href:`mailto:${n.wEmailPrimary}`,className:"flex items-center gap-1 text-blue-600 hover:text-blue-800 text-xs",onClick:_=>_.stopPropagation(),children:[e.jsx(_a,{className:"h-3 w-3"}),n.wEmailPrimary]}):" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Email Primary Provider",value:n.wEmailPrimaryMx||" - "}),children:n.wEmailPrimaryMx||" - "}),e.jsx(la,{title:"Tier 1 Emails",value:n.wEmailTier1,kind:"email",shouldMaskContacts:E,contactExported:n.contactExported,maskedTooltipText:Tt,onOpen:()=>R({title:"Tier 1 Emails",value:n.wEmailTier1||" - ",contactExported:n.contactExported})}),e.jsx(la,{title:"Tier 2 Emails",value:n.wEmailTier2,kind:"email",shouldMaskContacts:E,contactExported:n.contactExported,maskedTooltipText:Tt,onOpen:()=>R({title:"Tier 2 Emails",value:n.wEmailTier2||" - ",contactExported:n.contactExported})}),e.jsx(la,{title:"Tier 3 Emails",value:n.wEmailTier3,kind:"email",shouldMaskContacts:E,contactExported:n.contactExported,maskedTooltipText:Tt,onOpen:()=>R({title:"Tier 3 Emails",value:n.wEmailTier3||" - ",contactExported:n.contactExported})}),e.jsx(la,{title:"Tier 4 Emails",value:n.wEmailTier4,kind:"email",shouldMaskContacts:E,contactExported:n.contactExported,maskedTooltipText:Tt,onOpen:()=>R({title:"Tier 4 Emails",value:n.wEmailTier4||" - ",contactExported:n.contactExported})}),e.jsx(la,{title:"Tier 5 Emails",value:n.wEmailTier5,kind:"email",shouldMaskContacts:E,contactExported:n.contactExported,maskedTooltipText:Tt,onOpen:()=>R({title:"Tier 5 Emails",value:n.wEmailTier5||" - ",contactExported:n.contactExported})}),e.jsx(la,{title:"Tier 6 Emails",value:n.wEmailTier6,kind:"email",shouldMaskContacts:E,contactExported:n.contactExported,maskedTooltipText:Tt,onOpen:()=>R({title:"Tier 6 Emails",value:n.wEmailTier6||" - ",contactExported:n.contactExported})}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Website Email Provider",value:n.wEmailDomainMx||" - "}),children:n.wEmailDomainMx||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Website Email Security",value:n.wEmailSecurity||" - "}),children:n.wEmailSecurity||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Website Schema",value:n.wProfileCategory||" - "}),children:n.wProfileCategory?(()=>{const _=ml(n.wProfileCategory),G=_.slice(0,3),We=_.length-3;return e.jsxs("div",{className:"flex flex-col gap-1",children:[G.map((gs,ts)=>e.jsx(ie,{variant:"outline",className:"text-[10px] px-1.5 py-0.5 leading-none font-normal w-fit whitespace-nowrap",children:gs},ts)),We>0&&e.jsxs("span",{className:"text-[10px] text-gray-400",children:["+",We," more"]})]})})():" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Description Short",value:n.wProfileDescriptionShort||" - "}),children:e.jsx("span",{className:"text-xs text-gray-500 line-clamp-2",children:n.wProfileDescriptionShort||" - "})}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Description Long",value:n.wProfileDescriptionLong||" - "}),children:e.jsx("span",{className:"text-xs text-gray-500 line-clamp-2",children:n.wProfileDescriptionLong||" - "})}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Address Full",value:n.wAddressFull||" - "}),children:e.jsx("span",{className:"text-xs text-gray-500 line-clamp-1",children:n.wAddressFull||" - "})}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Street",value:n.wAddressStreet||" - "}),children:e.jsx("span",{className:"text-xs text-gray-500",children:n.wAddressStreet||" - "})}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"City",value:n.wAddressCity||" - "}),children:n.wAddressCity||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"State",value:n.wAddressState||" - "}),children:n.wAddressState||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Zip",value:n.wAddressZip||" - "}),children:n.wAddressZip||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Address Source",value:n.wAddressSource||" - "}),children:n.wAddressSource||" - "}),e.jsx(Js,{value:n.wPlatform,onOpen:()=>R({title:"Platform",value:n.wPlatform||" - "})}
122),e.jsx(Js,{value:n.wBookingOpsCrmSoftware,onOpen:()=>R({title:"Booking/Ops/CRM Software",value:n.wBookingOpsCrmSoftware||" - "})}),e.jsx(Js,{value:n.wReputationChatSoftware,onOpen:()=>R({title:"Reputation/Chat Software",value:n.wReputationChatSoftware||" - "})}),e.jsx(Js,{value:n.wMarketingEmailSoftware,onOpen:()=>R({title:"Marketing/Email Software",value:n.wMarketingEmailSoftware||" - "})}),e.jsx(Js,{value:n.wAdPixels,onOpen:()=>R({title:"Ad Pixels",value:n.wAdPixels||" - "})}),e.jsx(Js,{value:n.wPaymentFinancingSoftware,onOpen:()=>R({title:"Payment/Financing Software",value:n.wPaymentFinancingSoftware||" - "})}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Employees",value:n.wEmployeeCount||" - "}),children:n.wEmployeeCount||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Number of Job Postings",value:n.wOpenPositions??" - "}),children:n.wOpenPositions??" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Founding Date",value:n.wFoundingDate||" - "}),children:n.wFoundingDate||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>{const _=n.wNumLocations?(()=>{const G=parseFloat(n.wNumLocations);return isNaN(G)?n.wNumLocations:String(Math.round(G))})():null;R({title:"Number of Locations",value:_||" - "})},children:n.wNumLocations?(()=>{const _=parseFloat(n.wNumLocations);return isNaN(_)?n.wNumLocations:String(Math.round(_))})():" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Is Chain?",value:n.wIsChain||" - "}),children:n.wIsChain||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Rating Value",value:n.wRatingValue||" - "}),children:n.wRatingValue||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Review Count",value:n.wReviewCount||" - "}),children:n.wReviewCount||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Price Range",value:n.wPriceRange||" - "}),children:n.wPriceRange||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Legal Name",value:n.wLegalName||" - "}),children:e.jsx("span",{className:"block truncate max-w-[160px]",children:n.wLegalName||" - "})}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"NAICS Code",value:n.wIndustryNaics||" - "}),children:n.wIndustryNaics||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"DUNS Number",value:n.wDuns||" - "}),children:n.wDuns||" - "}),e.jsx(Js,{value:n.wFounder,onOpen:()=>R({title:"Founder Name(s)",value:n.wFounder||" - "})}),e.jsx(la,{title:"Founder Email(s)",value:n.wFounderEmail,kind:"email",shouldMaskContacts:E,contactExported:n.contactExported,maskedTooltipText:Tt,onOpen:()=>R({title:"Founder Email(s)",value:n.wFounderEmail||" - ",contactExported:n.contactExported})}),e.jsx(la,{title:"Founder Phone(s)",value:n.wFounderPhone,kind:"phone",shouldMaskContacts:E,contactExported:n.contactExported,maskedTooltipText:Tt,onOpen:()=>R({title:"Founder Phone(s)",value:n.wFounderPhone||" - ",contactExported:n.contactExported})}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Latitude",value:n.wGeoLat||" - "}),children:n.wGeoLat||" - "}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Longitude",value:n.wGeoLong||" - "}),children:n.wGeoLong||" - "}),e.jsx(Js,{value:n.wOpeningHours,onOpen:()=>R({title:"Opening Hours",value:n.wOpeningHours||" - "})}),e.jsx(Js,{value:n.wAreaServed,onOpen:()=>R({title:"Area Served",value:n.wAreaServed||" - "})}),e.jsx(Js,{value:n.wOffers,onOpen:()=>R({title:"Offers",value:n.wOffers||" - "})}),e.jsx(Js,{value:n.wBrand,onOpen:()=>R({title:"Brand",value:n.wBrand||" - "})}),e.jsx(Fe,{className:"cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Slogan",value:n.wSlogan||" - "}),children:e.jsx("span",{className:"block truncate max-w-[200px]",children:n.wSlogan||" - "})}),e.jsx(up,{value:n.wLogoUrl,onOpen:()=>R({title:"Logo URL",value:n.wLogoUrl||" - "})}),e.jsx(pp,{value:n.wSocialProfiles,onOpen:()=>R({title:"Social Profiles",value:n.wSocialProfiles||" - "})}),e.jsx(Fe,{className:"text-xs text-gray-500 whitespace-nowrap cursor-pointer hover:bg-white dark:hover:bg-gray-900",onClick:()=>R({title:"Time Scraped",value:n.wTimeScraped||" - "}),children:n.wTimeScraped||" - "})]},n.id)}):null})]})}),mt?gt?e.jsx("div",{className:"py-12 flex items-center justify-center",children:e.jsx(ea,{size:"lg",text:"Loading leads..."})}):Ge?e.jsxs("div",{className:"py-12 flex flex-col items-center justify-center",children:[e.jsx(tr,{className:"h-10 w-10 text-red-600 mb-3"}),e.jsx("p",{className:"text-gray-700 text-lg",children:"Leads failed to load"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"The search took too long or the server had a hiccup. Your filters are unchanged."}),e.jsx(N,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>Ce(),"data-testid":"other-leads-error-retry",children:"Retry search"})]}):yt.length===0?e.jsxs("div",{className:"py-12 flex flex-col items-center justify-center",children:[e.jsx(tr,{className:"h-10 w-10 text-gray-400 mb-3"}),e.jsx("p",{className:"text-gray-700 text-lg",children:"No leads found"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"Try adjusting your keywords or filters"})]}):null:e.jsx("div",{className:"py-12 flex items-center justify-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(Kt,{className:"h-8 w-8 text-blue-400"}),e.jsxs("p",{className:"text-gray-700",children:["Apply positive keyword filters or include terms to the ",e.jsx("span",{className:"font-semibold",children:"Registered URL"}),", ",e.jsx("span",{className:"font-semibold",children:"Crawled URL"}),", ",e.jsx("span",{className:"font-semibold",children:"Company Name"}),", or ",e.jsx("span",{className:"font-semibold",children:"Description Short"})," columns to see results."]}),e.jsx("p",{className:"text-sm text-gray-400",children:"Click the filter icon on any of those columns to get started."})]})}),mt&&Ae&&(Ae.pages>1||yt.length>0&&!Dt)&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3 pt-2",children:[e.jsxs("div",{className:"flex items-center gap-3 text-xs text-gray-500",children:[e.jsx("span",{children:Dt?e.jsxs(e.Fragment,{children:["Showing ",Math.min((Ae.page-1)*Ae.limit+1,Ae.total)," to"," ",Math.min(Ae.page*Ae.limit,Ae.total)," of"," ",Ae.total.toLocaleStr
122ing()," leads"]}):e.jsxs(e.Fragment,{children:["Page ",p," · ",yt.length," leads loaded · ",e.jsx(Lt,{size:12})," calculating total..."]})}),e.jsxs("select",{value:y,onChange:n=>{k(Number(n.target.value)),v(1)},className:"h-7 rounded border border-gray-300 bg-white px-1.5 text-xs dark:border-gray-600 dark:bg-gray-800",children:[e.jsx("option",{value:100,children:"100 / page"}),e.jsx("option",{value:500,children:"500 / page"}),e.jsx("option",{value:1e3,children:"1000 / page"})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(N,{variant:"outline",size:"sm",disabled:p<=1,onClick:()=>v(n=>n-1),className:"h-7 text-xs",children:e.jsx(ci,{className:"h-3.5 w-3.5"})}),Array.from({length:Math.min(7,Ae.pages)},(n,b)=>{let h;return Ae.pages<=7||p<=4?h=b+1:p>=Ae.pages-3?h=Ae.pages-6+b:h=p-3+b,e.jsx(N,{variant:h===p?"default":"outline",size:"sm",onClick:()=>v(h),className:"h-7 w-7 text-xs p-0",children:h},h)}),e.jsx(N,{variant:"outline",size:"sm",disabled:p>=Ae.pages,onClick:()=>v(n=>n+1),className:"h-7 text-xs",children:e.jsx(ti,{className:"h-3.5 w-3.5"})})]})]})]})]})]}),e.jsx(os,{open:!!V,onOpenChange:n=>{n||R(null)},children:e.jsxs(cs,{className:"max-w-md",children:[e.jsx(as,{children:e.jsx(rs,{children:V==null?void 0:V.title})}),e.jsx("div",{className:"text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap break-words max-h-[60vh] overflow-auto",children:(V==null?void 0:V.title)==="Website Schema"&&(V!=null&&V.value)&&V.value!==" - "?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:ml(V.value).map((n,b)=>e.jsx(ie,{variant:"outline",className:"text-xs px-2 py-0.5 leading-none font-normal",children:n},b))}):((V==null?void 0:V.title)==="Phone Primary"||(V==null?void 0:V.title)==="Total Phones"||(V==null?void 0:V.title)==="Founder Phone(s)")&&E&&!(V!=null&&V.contactExported)&&(V!=null&&V.value)&&V.value!==" - "?e.jsxs("span",{className:"flex items-center gap-1 text-gray-500",children:[e.jsx(ya,{className:"h-3.5 w-3.5"}),V.value]}):((V==null?void 0:V.title)==="Email Primary"||(V==null?void 0:V.title)==="Tier 1 Emails"||(V==null?void 0:V.title)==="Tier 2 Emails"||(V==null?void 0:V.title)==="Tier 3 Emails"||(V==null?void 0:V.title)==="Tier 4 Emails"||(V==null?void 0:V.title)==="Tier 5 Emails"||(V==null?void 0:V.title)==="Tier 6 Emails"||(V==null?void 0:V.title)==="Founder Email(s)")&&E&&!(V!=null&&V.contactExported)&&(V!=null&&V.value)&&V.value!==" - "?e.jsxs("span",{className:"flex items-center gap-1 text-gray-500",children:[e.jsx(ya,{className:"h-3.5 w-3.5"}),V.value]}):(V==null?void 0:V.title)==="Social Profiles"&&(V!=null&&V.value)&&V.value!==" - "?e.jsx("div",{className:"flex flex-col gap-1.5",children:Ro(V.value).map((n,b)=>e.jsx("a",{href:n.startsWith("http")?n:`https://${n}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 break-all text-xs",onClick:h=>h.stopPropagation(),children:n},b))}):V==null?void 0:V.value})]})}),e.jsx(os,{open:pe,onOpenChange:Se,children:e.jsxs(cs,{className:"max-w-sm",children:[e.jsx(as,{children:e.jsx(rs,{children:"Save Current Filters"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ee,{placeholder:"Preset name",value:Ze,onChange:n=>Me(n.target.value),onKeyDown:n=>{if(n.key==="Enter"&&Ze.trim()){const b=Wr(a);ft.mutate({name:Ze.trim(),filters:{hash:b},databaseType:"other"})}},autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(N,{variant:"outline",size:"sm",onClick:()=>Se(!1),children:"Cancel"}),e.jsx(N,{size:"sm",disabled:!Ze.trim()||ft.isPending,onClick:()=>{const n=Wr(a);ft.mutate({name:Ze.trim(),filters:{hash:n},databaseType:"other"})},children:ft.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(nr,{className:"h-3 w-3 mr-1"}),"Save"]})})]})]})]})}),e.jsx(Io,{open:O,remainingAfterExport:jt-(B?(Ae==null?void 0:Ae.total)??0:$.size>0?$.size:W??0),onConfirm:()=>{I(!1),De.mutate({selectedIds:re,maxLeads:tt}),Pe(void 0),$e(void 0)},onCancel:()=>{I(!1),Pe(void 0),$e(void 0)}})]}):e.jsx(Ue,{children:e.jsx(_e,{className:"p-8 flex items-center justify-center",children:e.jsx(ea,{size:"lg",text:"Loading keywords..."})})})}var gi="Progress",yi=100,[Np]=kr(gi),[Ep,Sp]=Np(gi),Mo=o.forwardRef((t,r)=>{const{__scopeProgress:s,value:i=null,max:l,getValueLabel:c=Cp,...d}=t;(l||l===0)&&!xl(l)&&console.error(kp(`${l}`,"Progress"));const u=xl(l)?l:yi;i!==null&&!hl(i,u)&&console.error(Fp(`${i}`,"Progress"));const g=hl(i,u)?i:null,f=mn(g)?c(g,u):void 0;return e.jsx(Ep,{scope:s,value:g,max:u,children:e.jsx(va.div,{"aria-valuemax":u,"aria-valuemin":0,"aria-valuenow":mn(g)?g:void 0,"aria-valuetext":f,role:"progressbar","data-state":Uo(g,u),"data-value":g??void 0,"data-max":u,...d,ref:r})})});Mo.displayName=gi;var $o="ProgressIndicator",Ko=o.forwardRef((t,r)=>{const{__scopeProgress:s,...i}=t,l=Sp($o,s);return e.jsx(va.div,{"data-state":Uo(l.value,l.max),"data-value":l.value??void 0,"data-max":l.max,...i,ref:r})});Ko.displayName=$o;function Cp(t,r){return`${Math.round(t/r*100)}%`}function Uo(t,r){return t==null?"indeterminate":t===r?"complete":"loading"}function mn(t){return typeof t=="number"}function xl(t){return mn(t)&&!isNaN(t)&&t>0}function hl(t,r){return mn(t)&&!isNaN(t)&&t<=r&&t>=0}function kp(t,r){return`Invalid prop \`max\` of value \`${t}\` supplied to \`${r}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${yi}\`.`}function Fp(t,r){return`Invalid prop \`value\` of value \`${t}\` supplied to \`${r}\`. The \`value\` prop must be: 123 - a positive number 124 - less than the value passed to \`max\` (or ${yi} if no \`max\` prop is set) 125 - \`null\` or \`undefined\` if the progress is indeterminate. 126 127Defaulting to \`null\`.`}var _o=Mo,Pp=Ko;const zo=o.forwardRef(({className:t,value:r,...s},i)=>e.jsx(_o,{ref:i,className:Fs("relative h-4 w-full overflow-hidden rounded-full bg-secondary",t),...s,children:e.jsx(Pp,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(r||0)}%)`}})}));zo.displayName=_o.displayName;var fi="Radio",[Ip,Vo]=kr(fi),[Tp,Ap]=Ip(fi),qo=o.forwardRef((t,r)=>{const{__scopeRadio:s,name:i,checked:l=!1,required:c,disabled:d,value:u="on",onCheck:g,form:f,...C}=t,[F,w]=o.useState(null),j=Fr(r,T=>w(T)),E=o.useRef(!1),A=F?f||!!F.closest("form"):!0;return e.jsxs(Tp,{scope:s,checked:l,disabled:d,children:[e.jsx(va.button,{type:"button",role:"radio","aria-checked":l,"data-state":Bo(l),"data-disabled":d?"":void 0,disabled:d,value:u,...C,ref:j,onClick:As(t.onClick,T=>{l||g==null||g(),A&&(E.current=T.isPropagationStopped(),E.current||T.stopPropagation())})}),A&&e.jsx(Lp,{control:F,bubbles:!E.current,name:i,value:u,checked:l,required:c,disabled:d,form:f,style:{transform:"translateX(-100%)"}})]})});qo.displayName=fi;var Ho="RadioIndicator",Wo=o.forwardRef((t,r)=>{const{__scopeRadio:s,forceMount:i,...l}
127=t,c=Ap(Ho,s);return e.jsx(Cr,{present:i||c.checked,children:e.jsx(va.span,{"data-state":Bo(c.checked),"data-disabled":c.disabled?"":void 0,...l,ref:r})})});Wo.displayName=Ho;var Lp=t=>{const{control:r,checked:s,bubbles:i=!0,...l}=t,c=o.useRef(null),d=Id(s),u=_c(r);return o.useEffect(()=>{const g=c.current,f=window.HTMLInputElement.prototype,F=Object.getOwnPropertyDescriptor(f,"checked").set;if(d!==s&&F){const w=new Event("click",{bubbles:i});F.call(g,s),g.dispatchEvent(w)}},[d,s,i]),e.jsx("input",{type:"radio","aria-hidden":!0,defaultChecked:s,...l,tabIndex:-1,ref:c,style:{...t.style,...u,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})};function Bo(t){return t?"checked":"unchecked"}var Rp=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],bi="RadioGroup",[Op]=kr(bi,[zl,Vo]),Jo=zl(),Yo=Vo(),[Dp,Mp]=Op(bi),Qo=o.forwardRef((t,r)=>{const{__scopeRadioGroup:s,name:i,defaultValue:l,value:c,required:d=!1,disabled:u=!1,orientation:g,dir:f,loop:C=!0,onValueChange:F,...w}=t,j=Jo(s),E=$c(f),[A,T]=Gn({prop:c,defaultProp:l,onChange:F});return e.jsx(Dp,{scope:s,name:i,required:d,disabled:u,value:A,onValueChange:T,children:e.jsx(Kc,{asChild:!0,...j,orientation:g,dir:E,loop:C,children:e.jsx(va.div,{role:"radiogroup","aria-required":d,"aria-orientation":g,"data-disabled":u?"":void 0,dir:E,...w,ref:r})})})});Qo.displayName=bi;var Go="RadioGroupItem",Zo=o.forwardRef((t,r)=>{const{__scopeRadioGroup:s,disabled:i,...l}=t,c=Mp(Go,s),d=c.disabled||i,u=Jo(s),g=Yo(s),f=o.useRef(null),C=Fr(r,f),F=c.value===l.value,w=o.useRef(!1);return o.useEffect(()=>{const j=A=>{Rp.includes(A.key)&&(w.current=!0)},E=()=>w.current=!1;return document.addEventListener("keydown",j),document.addEventListener("keyup",E),()=>{document.removeEventListener("keydown",j),document.removeEventListener("keyup",E)}},[]),e.jsx(Uc,{asChild:!0,...u,focusable:!d,active:F,children:e.jsx(qo,{disabled:d,required:c.required,checked:F,...g,...l,name:c.name,ref:C,onCheck:()=>c.onValueChange(l.value),onKeyDown:As(j=>{j.key==="Enter"&&j.preventDefault()}),onFocus:As(l.onFocus,()=>{var j;w.current&&((j=f.current)==null||j.click())})})})});Zo.displayName=Go;var $p="RadioGroupIndicator",Xo=o.forwardRef((t,r)=>{const{__scopeRadioGroup:s,...i}=t,l=Yo(s);return e.jsx(Wo,{...l,...i,ref:r})});Xo.displayName=$p;var ec=Qo,tc=Zo,Kp=Xo;const sc=o.forwardRef(({className:t,...r},s)=>e.jsx(ec,{className:Fs("grid gap-2",t),...r,ref:s}));sc.displayName=ec.displayName;const Zr=o.forwardRef(({className:t,...r},s)=>e.jsx(tc,{ref:s,className:Fs("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),...r,children:e.jsx(Kp,{className:"flex items-center justify-center",children:e.jsx(zc,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Zr.displayName=tc.displayName;function Up({onApplyFilters:t,keywordGenerationJobs:r,showGenerateDialog:s,setShowGenerateDialog:i,showCreateDialog:l,setShowCreateDialog:c,forceBothKeywordType:d=!1}){const{toast:u}=Ss(),g=ja(),[f,C]=o.useState([]),[F,w]=o.useState(null),[j,E]=o.useState(null),[A,T]=o.useState(!1),[J,p]=o.useState("created_desc"),[v,y]=o.useState(null),[k,a]=o.use
127State(""),[q,$]=o.useState(""),[X,B]=o.useState("positive"),[K,ae]=o.useState([]),[Y,fe]=o.useState(""),U=o.useRef(null),[te,ne]=o.useState(!1),Q=o.useRef(null),[V,R]=o.useState("both");o.useEffect(()=>{d&&s&&R("both")},[d,s]);const[pe,Se]=o.useState(""),[Ze,Me]=o.useState(""),[He,ee]=o.useState([]),[O,I]=o.useState(""),[re,Pe]=o.useState([]),[tt,$e]=o.useState(""),[W,Le]=o.useState(""),[ve,Oe]=o.useState({}),[vt,Rt]=o.useState({}),[At,at]=o.useState(null),[Je,Te]=o.useState(""),[Ct,lt]=o.useState([]),[kt,ft]=o.useState(!1),[qt,et]=o.useState(null),[Ot,Xe]=o.useState(""),[mt,ut]=o.useState([]),ot=3,[St,Pt]=o.useState({}),it=o.useRef({}),{data:ze,isLoading:_t,refetch:de}=Qe({queryKey:["/api/keyword-lists"],staleTime:300*1e3,refetchInterval:m=>{const D=m.state.data;return D!=null&&D.some(H=>H.refinementStatus==="running")?15e3:!1}}),gt=o.useRef([]),It=o.useRef(null);o.useEffect(()=>{if(ze&&ze.length>0){const m=ze.filter(D=>!D.viewedAt).map(D=>D.id);if(gt.current=m,m.length>0){It.current===null&&(It.current=Date.now());const D=setTimeout(async()=>{try{await ue("POST","/api/keyword-lists/mark-viewed",{listIds:m}),z.invalidateQueries({queryKey:["/api/keyword-lists"]}),It.current=null}catch(H){ce("[FiltersSection:162]","Failed to mark keywords as viewed after 5 minutes",H)}},300*1e3);return()=>clearTimeout(D)}else It.current=null}},[ze]),o.useEffect(()=>()=>{gt.current.length>0&&It.current!==null&&ue("POST","/api/keyword-lists/mark-viewed",{listIds:gt.current}).then(()=>{z.invalidateQueries({queryKey:["/api/keyword-lists"]})}).catch(m=>{ce("[FiltersSection:192]","Failed to mark keywords as viewed on cleanup",m)})},[]),o.useEffect(()=>{ze&&Oe(m=>{const D={...m};for(const H of ze)(H.autoRefineEnabled||H.refinementStatus==="running")&&!vt[H.id]&&(D[H.id]=!0);return D})},[ze,vt]),o.useEffect(()=>{l||(Ms(),w(null))},[l]),o.useEffect(()=>{const m=setTimeout(()=>{const D=Q.current;if(D){const H=D.scrollHeight>D.clientHeight;ne(H)}},10);return()=>clearTimeout(m)},[K,l]);const Ge=r||[],{data:Ce}=Qe({queryKey:["/api/auth/user"],staleTime:30*1e3}),[P,le]=o.useState(!1),De=async()=>{const m=Ce==null?void 0:Ce.companyWebsite;if(!(!(m!=null&&m.trim())||!Xs(m))){le(!0);try{const D=await ue("POST","/api/rescan-website",{websiteUrl:m,updateProfile:!1});if(z.invalidateQueries({queryKey:["/api/auth/user"]}),D.ok){let H={};try{H=await D.json()}catch{}const Z=H.analysisSucceeded!==!1;u(Z?{title:"Website Analyzed Successfully",description:"Your website has been analyzed. AI keyword generation will now use updated information."}:{title:"Analysis Issue",description:H.message||"We couldn't fully analyze your website. Please verify the URL is correct.",variant:"destructive"})}else{let H={};try{H=await D.json()}catch{}u({title:"Scan Failed",description:H.message||"Failed to scan website",variant:"destructive"})}}catch(D){ce("[FiltersSection:handleRescanWebsite]","Error scanning website",D),z.invalidateQueries({queryKey:["/api/auth/user"]}),u({title:"Error",description:"Failed to scan website. Please try again.",variant:"destructive"})}finally{le(!1)}}};o.useEffect(()=>{s&&Ce&&(Se(Ce.companyDescription||""),Me(Ce.productService||""),ee([]),ut(Ce.targetCategories||[]),Pe(Ce.businessesToAvoid||[]),Le(Ce.additionalContext||""))},[s,Ce]);const st=(ze==null?void 0:ze.filter(m=>m.type==="positive"))||[],Ft=(ze==null?void 0:ze.filter(m=>m.type==="negative"))||[],Ye=[...(()=>{const m=new Set,D=[];for(const H of st)if(H.pairedListId&&!m.has(H.id)){const Z=Ft.find(we=>we.id===H.pairedListId);D.push({positive:H,negative:Z||null,sortDate:new Date(H.createdAt||0)}),m.add(H.id),Z&&m.add(Z.id)}for(const H of Ft)if(H.pairedListId&&!m.has(H.id)){const Z=st.find(we=>we.id===H.pairedListId);Z&&!m.has(Z.id)&&(D.push({positive:Z,negative:H,sortDate:new Date(Z.createdAt||0)}),m.add(Z.id),m.add(H.id))}for(const H of st)m.has(H.id)||(D.push({positive:H,negative:null,sortDate:new Date(H.createdAt||0)}),m.add(H.id));for(const H of Ft)m.has(H.id)||(D.push({positive:null,negative:H,sortDate:new Date(H.createdAt||0)}),m.add(H.id));return D})()].sort((m,D)=>{const H=Be=>Be.positive||Be.negative,Z=H(m),we=H(D);
127switch(J){case"name_asc":return(Z.name||"").localeCompare(we.name||"");case"name_desc":return(we.name||"").localeCompare(Z.name||"");case"created_asc":return new Date(Z.createdAt||0).getTime()-new Date(we.createdAt||0).getTime();case"created_desc":return new Date(we.createdAt||0).getTime()-new Date(Z.createdAt||0).getTime();case"modified_asc":return new Date(Z.updatedAt||Z.createdAt||0).getTime()-new Date(we.updatedAt||we.createdAt||0).getTime();case"modified_desc":return new Date(we.updatedAt||we.createdAt||0).getTime()-new Date(Z.updatedAt||Z.createdAt||0).getTime();default:return 0}}),pt=st,jt=Ft,ye=(Ge==null?void 0:Ge.filter(m=>m.status==="pending"))||[],Xt=(Ce==null?void 0:Ce.onboardingCompleted)&&pt.length===0&&jt.length===0||ye.length>0,rt=o.useRef(null),fs=o.useRef(null),[Tt,yt]=o.useState(!1),[is,Dt]=o.useState(!1),Ae=o.useRef(!1),bt=o.useRef(!1);o.useEffect(()=>{!Ae.current&&Ge&&Ge.length>0&&(Ae.current=!0,Ge.some(D=>D.status==="pending")&&Dt(!0))},[Ge]),o.useEffect(()=>{Tt&&ye.length===0&&yt(!1)},[Tt,ye.length]),o.useEffect(()=>(is&&!Tt?(ye.length>0&&(bt.current=!0),rt.current||(fs.current||(fs.current=Date.now(),yt(!1)),rt.current=setInterval(()=>{const m=Date.now()-(fs.current||0),D=3600*1e3;if(m>=D){rt.current&&(clearInterval(rt.current),rt.current=null),fs.current=null,bt.current=!1,yt(!0),Dt(!1),de(),z.invalidateQueries({queryKey:["/api/keyword-generation-jobs"]});return}de(),z.invalidateQueries({queryKey:["/api/keyword-generation-jobs"]})},5e3)),rt.current&&bt.current&&ye.length===0&&(clearInterval(rt.current),rt.current=null,fs.current=null,bt.current=!1,yt(!1),Dt(!1))):!is&&rt.current&&(clearInterval(rt.current),rt.current=null,bt.current=!1),()=>{rt.current&&(clearInterval(rt.current),rt.current=null)}),[is,ye.length,Tt,de]);const Nt=Ne({mutationFn:async m=>(await ue("POST","/api/keyword-lists",m)).json(),onSuccess:()=>{z.invalidateQueries({queryKey:["/api/keyword-lists"]}),c(!1),u({title:"Success",description:"Keyword list created successfully"})},onError:m=>{ce("[FiltersSection:379]","Failed to create keyword list:",m),u({title:"Error",description:"Failed to create keyword list",variant:"destructive"})}}),ls=Ne({mutationFn:async({id:m,...D})=>(await ue("PUT",`/api/keyword-lists/${m}`,D)).json(),onSuccess:()=>{z.invalidateQueries({queryKey:["/api/keyword-lists"]}),c(!1),u({title:"Success",description:"Keyword list updated successfully"})},onError:m=>{ce("[FiltersSection:419]","Failed to update keyword list:",m),u({title:"Error",description:"Failed to update keyword list",variant:"destructive"})}}),es=Ne({mutationFn:async({positiveId:m,negativeId:D,newBaseName:H})=>{var we,Be;const Z=[];if(m){const ge=ze==null?void 0:ze.find(dt=>dt.id===m);if(ge){const vs=((we=(ge.name||"").match(/ - \d{4}-\d{2}-\d{2}$/))==null?void 0:we[0])||"";Z.push(ue("PUT",`/api/keyword-lists/${m}`,{name:`${H} (Positive)${vs}`}))}}if(D){const ge=ze==null?void 0:ze.find(dt=>dt.id===D);if(ge){const vs=((Be=(ge.name||"").match(/ - \d{4}-\d{2}-\d{2}$/))==null?void 0:Be[0])||"";Z.push(ue("PUT",`/api/keyword-lists/${D}`,{name:`${H} (Negative)${vs}`}))}}await Promise.all(Z)},onSuccess:()=>{z.invalidateQueries({queryKey:["/api/keyword-lists"]}),y(null),u({title:"Renamed",description:"Keyword list renamed successfully"})},onError:m=>{ce("[FiltersSection:renameRow]","Failed to rename keyword list:",m),u({title:"Error",description:"Failed to rename keyword list",variant:"destructive"})}}),Rs=Ne({mutationFn:async m=>{await ue("DELETE",`/api/keyword-lists/${m}`)},onSuccess:()=>{z.invalidateQueries({queryKey:["/api/keyword-lists"]}),u({title:"Success",description:"Keyword list deleted successfully"})},onError:m=>{ce("[FiltersSection:445]","Failed to delete keyword list:",m),u({title:"Error",description:"Failed to delete keyword list",variant:"destructive"})}}),bs=o.useRef({}),Ps=o.useRef({}),ms=o.useRef({});o.useEffect(()=>()=>{Object.values(bs.current).forEach(clearTimeout)},[]);const Bt=o.useCallback((m,D)=>{var H;if(!(m in ms.current)){const Z=z.getQueryData(["/api/keyword-lists"]),we=((H=Z==null?void 0:Z.find(Be=>Be.id===m))==null?void 0:H.isDefault)||!1;ms.current[m]=we}z.cancelQueries({queryKey:["/api/keyword-lists"]}),z.setQueryData(["/api/keyword-lists"],Z=>Z==null?void 0:Z.map(we=>we.id===m?{...we,isDefault:D}:we)),Ps.current[m]=D,bs.current[m]&&clearTimeout(bs.current[m]),bs.current[m]=setTimeout(()=>{const Z=Ps.current[m],we=ms.current[m];delete Ps.current[m],delete bs.current[m],delete ms.current[m],ue("PUT",`/api/keyword-lists/${m}`,{isDefault:Z}).then(()=>{z.invalidateQueries({queryKey:["/api/keyword-lists"]})}).catch(Be=>{z.setQueryData(["/api/keyword-lists"],ge=>ge==null?void 0:ge.map(dt=>dt.id===m?{...dt,isDefault:we}:dt)),ce("[FiltersSection:toggleDefault]","Failed to toggle default status:",Be),u({title:"Error",description:"Failed to update default status",variant:"destructive"})})},1e3)},[u]),he=Ne({mutationFn:async({listId:m,sourceCategories:D})=>(await ue("PUT",`/api/keyword-lists/${m}`,{sourceCategories:D})).json(),onSuccess:()=>{z.invalidateQueries({queryKey:["/api/keyword-lists"]}),at(null),u({title:"Categories updated",description:"Source categories saved for this keyword list"})},onError:m=>{u({title:"Failed to update categories",description:m.message,variant:"destructive"}),ce("FiltersSection","Failed to update source categories",m)}});Ne({mutationFn:async({listId:m,enabled:D})=>(await ue("POST",`/api/keyword-lists/${m}/refine/toggle`,{enabled:D})).json(),onSuccess:()=>{z.invalidateQueries({queryKey:["/api/keyword-lists"]})},onError:m=>{u({title:"Failed to toggle auto refine",description:m.message,variant:"destructive"}),ce("FiltersSection","Failed to toggle auto refine",m)}});const _s=o.useCallback((m,D)=>{var we,Be;const H=z.getQueryData(["/api/keyword-lists"]);(we=H==null?void 0:H.find(ge=>ge.id===m))!=null&&we.autoRefineEnabled,z.cancelQueries({queryKey:["/api/keyword-lists"]});const Z=(Be=H==null?void 0:H.find(ge=>ge.id===m))==null?void 0:Be.pairedListId;z.setQueryData(["/api/keyword-lists"],ge=>ge==null?void 0:ge.map(dt=>dt.id===m||Z&&dt.id===Z?{...dt,autoRefineEnabled:D,refinementStatus:D?dt.refinementStatus:null}:dt)),ue("POST",`/api/keyword-lists/${m}/refine/toggle`,{enabled:D}).then(()=>{z.invalidateQueries({queryKey:["/api/keyword-lists"]})}).catch(ge=>{z.invalidateQueries({queryKey:["/api/keyword-lists"]}),u({title:"Failed to toggle auto refine",description:ge.message,variant:"destructive"}),ce("FiltersSection","Failed to toggle auto refine",ge)})},[u]),hs=Ne({mutationFn:async m=>(await ue("PATCH","/api/onboarding-settings",m)).json(),onSuccess:()=>{z.invalidateQueries({queryKey:["/api/auth/user"]}),u({title:"Settings Saved",description:"Your business settings have been updated successfully."})},onError:m=>{ce("[FiltersSection:482]","Failed to save settings",m),u({title:"Error",description:"Failed to save settings",variant:"destructive"})}}),us=Ne({mutationFn:async m=>(await ue("POST","/api/generate-keyword-filters",m)).json(),onSuccess:()=>{n(),i(!1),z.invalidateQueries({queryKey:["/api/keyword-lists"]}),z.invalidateQueries({queryKey:["/api/keyword-generation-jobs"]}
127),Dt(!0),yt(!1),u({title:"Generating Keywords",description:"Your AI-generated keyword lists are being created. This may take a moment."})},onError:m=>{ce("[FiltersSection:527]","Failed to generate keyword lists:",m),u({title:"Error",description:"Failed to generate keyword lists",variant:"destructive"})}});o.useEffect(()=>{if(!ye||ye.length===0){Object.keys(it.current).forEach(D=>{clearInterval(it.current[D]),delete it.current[D]}),Pt({});return}const m=[{duration:3e4,message:Ce!=null&&Ce.websiteOptOut?"Analyzing your company description & product/service to fine tune keywords...":`Analyzing ${(Ce==null?void 0:Ce.companyWebsite)||"your website"} to fine tune keywords...`},{duration:3e4,message:"Personalizing keywords for your target market..."},{duration:3e4,message:"Optimizing keyword strategy and targeting..."},{duration:3e4,message:"Finalizing keyword lists and filtering duplicates..."}];Object.keys(it.current).forEach(D=>{ye.find(H=>H.id===D)||(clearInterval(it.current[D]),delete it.current[D],Pt(H=>{const Z={...H};return delete Z[D],Z}))}),ye.forEach(D=>{if(!it.current[D.id]){if(!D.startedAt){Pt(Is=>({...Is,[D.id]:{progress:5,stage:0,message:m[0].message}}));return}const H=new Date(D.startedAt).getTime(),Z=120*1e3,we=Math.max(0,Date.now()-H),Be=Math.min(we/Z*99,99);let ge=Be,dt=-1,vs=!1,Gs=0,ia=0,xa=0;for(let Is=0;Is<m.length;Is++){if(we>=ia&&we<ia+m[Is].duration){xa=Is;break}ia+=m[Is].duration,Is===m.length-1&&(xa=Is)}Pt(Is=>({...Is,[D.id]:{progress:Math.floor(Be),stage:xa,message:m[xa].message}}));const or=()=>{const Is=Math.max(0,Math.min(Date.now()-H,Z)),qa=Math.min(Is/Z*99,99);let cr=0,ha=0;for(let Ts=0;Ts<m.length;Ts++){if(Is>=cr&&Is<cr+m[Ts].duration){ha=Ts;break}cr+=m[Ts].duration,Ts===m.length-1&&(ha=Ts)}if(!vs&&Math.random()<.1&&(vs=!0,Gs=Date.now()+Math.random()*3e3+1e3),vs)Date.now()>=Gs&&(vs=!1);else{const Ts=qa-ge;if(Ts>0){let Wa=0;Ts>5?Wa=Math.random()*2+1:Ts>1?Wa=Math.random()*.5+.1:Wa=Math.random()*.2+.05,ge=Math.min(ge+Wa,qa,99)}}const Ha=Math.floor(ge);(ha!==xa||Ha!==dt)&&(xa=ha,dt=Ha,Pt(Ts=>({...Ts,[D.id]:{progress:Ha,stage:ha,message:m[ha].message}})))};it.current[D.id]=setInterval(or,100)}})},[ye,Ce==null?void 0:Ce.companyWebsite]),o.useEffect(()=>()=>{Object.keys(it.current).forEach(m=>{clearInterval(it.current[m])})},[]);const Ms=()=>{$(""),B("positive"),ae([]),fe("")},n=()=>{R("both"),Se(""),Me(""),ee([]),I(""),Pe([]),$e(""),Le("")},b=()=>{if(!O.trim())return;const D=O.split(",").map(H=>H.trim()).filter(H=>H.length>0).filter(H=>!He.some(Z=>Z.toLowerCase()===H.toLowerCase()));if(D.length>0){const H=ot-He.length;if(H<=0)return;ee([...He,...D.slice(0,H)])}I("")},h=m=>{ee(He.filter(D=>D!==m))},L=async()=>{ft(!0),et(null);try{const D=await(await ue("GET","/api/auth/user")).json(),H=D.companyName,Z=pe||D.companyDescription,we=Ze||D.productService,Be=D.companyWebsite;if(Xe(Be||""),!H||!Z||!we){et("Please complete your company information in Account Settings before using AI suggestions"),ft(!1);return}const ge={companyName:H,companyDescription:Z,productService:we,websiteUrl:Be||void 0,smbType:vr(D.smbType),excludeCategories:D.targetCategories||[]},dt=await ue("POST","/api/suggest-categories",ge);if(!dt.ok){const Gs=await dt.text();throw new Error(`API error: ${dt.status} - ${Gs}`)}const vs=await dt.json();lt(vs.categories||[])}catch{et("Failed to load suggestions")}finally{ft(!1)}},_=m=>{He.includes(m)?h(m):He.length<ot&&ee([...He,m])},G=m=>{He.includes(m)?h(m):He.length<ot&&ee([...He,m])},We=()=>{if(!tt.trim())return;const D=tt.split(",").map(H=>H.trim()).filter(H=>H.length>0).filter(H=>!re.some(Z=>Z.toLowerCase()===H.toLowerCase()));D.length>0&&Pe([...re,...D]),$e("")},gs=m=>{Pe(re.filter(D=>D!==m))},ts=()=>{Y.trim()&&!K.includes(Y.trim())&&(ae([...K,Y.trim()]),fe(""))},Zt=m=>{ae(K.filter(D=>D!==m))},nt=()=>{if(!q.trim()||K.length===0){ce("[FiltersSection:877]","Missing list name or keywords"),u({title:"Error",description:"Please provide a name and at least one keyword",variant:"destructive"});return}const m={name:q,type:X,keywords:K};F?ls.mutate({id:F.id,...m}):Nt.mutate(m)},ss=30,x=m=>{if(m.refinementStatus!=="running")return!1;if(!m.lastRefinedAt)return!0;const D=new Date(m.lastRefinedAt).getTime();return Date.now()-D>ss*60*1e3},M=m=>m.autoRefineEnabled||m.refinementStatus==="running",me=m=>{if(M(m)){u({title:"Editing not allowed",description:"You cannot edit this keyword list while Auto Refine is turned on. Please toggle Auto Refine off first.",variant:"destructive"});return}$(m.name),B(m.type),ae(Array.isArray(m.keywords)?m.keywords:[]),w(m),c(!0)},Ve=m=>{const D=`${m.name} (Copy)`,H=Array.isArray(m.keywords)?m.keywords:[];Nt.mutate({name:D,type:m.type,keywords:H})},xt=m=>
127{if(M(m)){u({title:"Deletion not allowed",description:"You cannot delete this keyword list while Auto Refine is turned on. Please toggle Auto Refine off first.",variant:"destructive"});return}E(m),T(!0)},Ht=()=>{j&&(Rs.mutate(j.id),T(!1),E(null))},be=m=>{var Z;const D=(Z=m.target.files)==null?void 0:Z[0];if(!D)return;if(!D.name.endsWith(".txt")){ce("FiltersSection","Invalid file type for keyword upload",void 0,{fileName:D.name}),u({title:"Invalid file type",description:"Please upload a .txt file",variant:"destructive"});return}const H=new FileReader;H.onload=we=>{var vs;const ge=((vs=we.target)==null?void 0:vs.result).split(/\r?\n/).map(Gs=>Gs.trim()).filter(Gs=>Gs.length>0),dt=Array.from(new Set([...K,...ge]));ae(dt),u({title:"Keywords imported",description:`Added ${ge.length} keywords from file`}),U.current&&(U.current.value="")},H.onerror=()=>{ce("[FiltersSection:974]","Failed to read uploaded file"),u({title:"Error",description:"Failed to read file",variant:"destructive"})},H.readAsText(D)},ra=()=>{if(K.length===0){ce("FiltersSection","No keywords to export"),u({title:"No keywords to export",description:"Add keywords before exporting",variant:"destructive"});return}const m=K.join(` 128`),D=new Blob([m],{type:"text/plain"}),H=URL.createObjectURL(D),Z=document.createElement("a");Z.href=H,Z.download=`${q||"keywords"}.txt`,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(H),u({title:"Keywords exported",description:`Exported ${K.length} keywords to ${q||"keywords"}.txt`})},na=()=>{let m=[...He],D=[...re];if(O.trim()){const Be=O.split(",").map(ge=>ge.trim()).filter(ge=>ge.length>0).filter(ge=>!m.some(dt=>dt.toLowerCase()===ge.toLowerCase()));m=[...m,...Be],ee(m),I("")}if(tt.trim()){const Be=tt.split(",").map(ge=>ge.trim()).filter(ge=>ge.length>0).filter(ge=>!D.some(dt=>dt.toLowerCase()===ge.toLowerCase()));D=[...D,...Be],Pe(D),$e("")}const H=[];if(pe.trim()||H.push("Company Description"),Ze.trim()||H.push("Product/Service"),m.length===0&&H.push("Target SMB Types"),H.length>0){ce("FiltersSection","Validation: missing business info for AI suggestions"),u({title:"Missing required fields",description:`Please fill in: ${H.join(", ")}`,variant:"destructive"});return}const Z=Array.from(new Set([...(Ce==null?void 0:Ce.targetCategories)||[],...m]));hs.mutate({companyDescription:pe.trim(),productService:Ze.trim(),targetCategories:Z,businessesToAvoid:D,additionalContext:W.trim()})},pa=()=>{let m=[...He],D=[...re];if(O.trim()){const we=O.split(",").map(Be=>Be.trim()).filter(Be=>Be.length>0).filter(Be=>!m.some(ge=>ge.toLowerCase()===Be.toLowerCase()));m=[...m,...we],ee(m),I("")}if(tt.trim()){const we=tt.split(",").map(Be=>Be.trim()).filter(Be=>Be.length>0).filter(Be=>!D.some(ge=>ge.toLowerCase()===Be.toLowerCase()));D=[...D,...we],Pe(D),$e("")}const H=[];if(pe.trim()||H.push("Company Description"),Ze.trim()||H.push("Product/Service"),m.length===0&&H.push("Target SMB Types"),H.length>0){ce("[FiltersSection:handleGenerateSubmit]","Missing required fields for keyword generation"),u({title:"Missing required fields",description:`Please fill in: ${H.join(", ")}`,variant:"destructive"});return}us.mutate({keywordType:V,businessDescription:pe,targetSMBTypes:m,productService:Ze,companiesToAvoid:D,additionalContext:W})},Va=async()=>{let m=[...He],D=[...re];if(O.trim()){const Be=O.split(",").map(ge=>ge.trim()).filter(ge=>ge.length>0).filter(ge=>!m.some(dt=>dt.toLowerCase()===ge.toLowerCase()));m=[...m,...Be],ee(m),I("")}if(tt.trim()){const Be=tt.split(",").map(ge=>ge.trim()).filter(ge=>ge.length>0).filter(ge=>!D.some(dt=>dt.toLowerCase()===ge.toLowerCase()));D=[...D,...Be],Pe(D),$e("")}const H=[];if(pe.trim()||H.push("Company Description"),Ze.trim()||H.push("Product/Service"),m.length===0&&H.push("Target SMB Types"),H.length>0){ce("[FiltersSection:handleGenerateAndSave]","Missing required fields for keyword generation"),u({title:"Missing required fields",description:`Please fill in: ${H.join(", ")}`,variant:"destructive"});return}const Z=Array.from(new Set([...(Ce==null?void 0:Ce.targetCategories)||[],...m]));try{await hs.mutateAsync({companyDescription:pe.trim(),productService:Ze.trim(),targetCategories:Z,businessesToAvoid:D,additionalContext:W.trim()})}catch(we){ce("[FiltersSection:1209]","Failed to save settings in handleGenerateAndSave",we),u({title:"Error",description:"Failed to save settings",variant:"destructive"});return}us.mutate({keywordType:V,businessDescription:pe,targetSMBTypes:He,productService:Ze,companiesToAvoid:re,additionalContext:W})},ct=()=>{if(f.length===0){ce("[FiltersSection:1235]","No keyword lists selected"),u({title:"Error",description:"Please select at least one keyword list",variant:"destructive"});return}const m=(ze==null?void 0:ze.filter(Z=>f.includes(Z.id)))||[],D=m.filter(Z=>Z.type==="positive").flatMap(Z=>Array.isArray(Z.keywords)?Z.keywords:[]),H=m.filter(Z=>Z.type==="negative").flatMap(Z=>Array.isArray(Z.keywords)?Z.keywords:[]);
128t==null||t({positiveKeywords:D,negativeKeywords:H}),u({title:"Filters Applied",description:`Applied ${D.length} positive and ${H.length} negative keywords`})},qe=m=>{const D=Array.isArray(m.sourceCategories)?m.sourceCategories:[];return At===m.id?e.jsxs("div",{className:"mt-2 pt-2 border-t border-gray-200",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1",children:[e.jsx(Bi,{className:"w-3 h-3 text-gray-500"}),e.jsx("span",{className:"text-xs font-medium text-gray-700",children:"Refinement Categories"})]}),e.jsx("textarea",{className:"w-full text-xs border rounded p-2 min-h-[60px] bg-white",value:Je,onChange:Z=>Te(Z.target.value),placeholder:"Enter categories, one per line"}),e.jsxs("div",{className:"flex gap-1 mt-1",children:[e.jsx(N,{size:"sm",variant:"outline",className:"h-6 text-xs px-2",onClick:()=>{const Z=Je.split(` 129`).map(we=>we.trim()).filter(we=>we.length>0);he.mutate({listId:m.id,sourceCategories:Z})},disabled:he.isPending,children:he.isPending?"Saving...":"Save"}),e.jsx(N,{size:"sm",variant:"ghost",className:"h-6 text-xs px-2",onClick:()=>at(null),children:"Cancel"})]})]}):e.jsxs("div",{className:"mt-2 pt-2 border-t border-gray-200",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Bi,{className:"w-3 h-3 text-gray-500"}),e.jsx("span",{className:"text-xs font-medium text-gray-700",children:"Refinement Categories"}),e.jsx("button",{className:"ml-auto text-xs text-blue-600 hover:text-blue-800",onClick:()=>{if(M(m)){u({title:"Editing not allowed",description:"You cannot edit categories while Auto Refine is turned on. Please toggle Auto Refine off first.",variant:"destructive"});return}at(m.id),Te(D.join(` 130`))},children:D.length>0?"Edit":"Set"})]}),D.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:D.map((Z,we)=>e.jsx(ie,{variant:"outline",className:"text-xs bg-purple-50 border-purple-200 text-purple-700",children:Z},we))}):e.jsx("p",{className:"text-xs text-gray-400 mt-0.5",children:"No categories set - Auto Refine will use your account categories"})]})},ht=o.useRef({});o.useEffect(()=>{if(ze)for(const m of ze){const D=ht.current[m.id];D&&ve[m.id]&&(D.scrollTop=D.scrollHeight)}},[ze,ve]);const Os=m=>{const D=Array.isArray(m.refinementLogs)?m.refinementLogs:[];if(D.length===0&&m.refinementStatus!=="running")return null;const H=ve[m.id]||!1,Z=()=>{const Be=!H;Oe(ge=>({...ge,[m.id]:Be})),Rt(Be?ge=>({...ge,[m.id]:!1}):ge=>({...ge,[m.id]:!0}))},we={info:"text-gray-400",score:"text-yellow-400",adjust:"text-cyan-400",error:"text-red-400",complete:"text-green-400"};return e.jsxs("div",{className:"mt-2",children:[e.jsxs("button",{onClick:Z,className:"flex items-center gap-1 text-xs text-gray-500 hover:text-gray-700 transition-colors w-full",children:[e.jsx(Vc,{className:"w-3 h-3"}),e.jsxs("span",{children:["Refinement Log (",D.length,")"]}),H?e.jsx(Vn,{className:"w-3 h-3 ml-auto"}):e.jsx(sr,{className:"w-3 h-3 ml-auto"})]}),H&&e.jsx("div",{ref:Be=>{ht.current[m.id]=Be},className:"mt-1 bg-gray-900 rounded-md p-2 max-h-40 overflow-y-auto font-mono text-xs",children:D.length===0?e.jsx("div",{className:"text-gray-500 animate-pulse",children:"Waiting for logs..."}):D.map((Be,ge)=>e.jsxs("div",{className:"flex gap-2 leading-relaxed",children:[e.jsx("span",{className:"text-gray-700 flex-shrink-0",children:new Date(Be.timestamp).toLocaleTimeString()}),e.jsx("span",{className:we[Be.type]||"text-gray-400",children:Be.message})]},ge))})]})},ws=m=>{const D=m.type==="positive"?"card-positive-list":"card-negative-list";return e.jsxs("div",{className:`border rounded-lg p-4 ${m.autoRefineEnabled?"bg-white animate-golden-glimmer":m.viewedAt?"bg-gray-50 border-gray-300":"bg-gray-50 border-blue-500 border-2"}`,"data-testid":`${D}-${m.id}`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-2 gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-medium mb-1","data-testid":`text-list-name-${m.id}`,children:m.name}),e.jsxs("div",{className:"text-xs text-gray-500 space-y-0.5",children:[e.jsxs("div",{children:["Created: ",m.createdAt?new Date(m.createdAt).toLocaleDateString():"N/A"]}),e.jsxs("div",{children:["Modified: ",m.updatedAt?new Date(m.updatedAt).toLocaleDateString():"N/A"]})]})]}),e.jsxs("div",{className:"flex flex-col items-end gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"flex",children:[e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>me(m),"data-testid":`button-edit-list-${m.id}`,children:e.jsx(_d,{className:"w-5 h-5"})}),e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>Ve(m),"data-testid":`button-duplicate-list-${m.id}`,children:e.jsx(jr,{className:"w-5 h-5"})}),e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>xt(m),"data-testid":`button-delete-list-${m.id}`,children:e.jsx(Hs,{className:"w-5 h-5"})})]}),e.jsx("div",{className:"flex gap-2",children:!m.viewedAt&&e.jsx(ie,{className:"bg-blue-600 text-white text-xs",children:"New"})})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-2",children:[Array.isArray(m.keywords)&&m.keywords.slice(0,5).map((H,Z)=>e.jsx(ie,{variant:"outline",className:"text-xs","data-testid":`badge-keyword-${m.id}-${Z}`,children:H},Z)),Array.isArray(m.keywords)&&m.keywords.length>5&&e.jsxs(ie,{variant:"outline",className:"text-xs",children:["+",m.keywords.length-5," more"]})]}),e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:m.isDefault||!1,onChange:()=>{Bt(m.id,!m.isDefault)},"data-testid":`checkbox-select-list-${m.id}`}),e.jsx("span",{className:"text-sm",children:"Include in search by default"})]}),qe(m),e.jsxs("div",{className:"flex items-center justify-between mt-2 pt-2 border-t border-gray-200",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kt,{className:`w-4 h-4 ${m.autoRefineEnabled?"text-blue-700":"text-gray-400"}`}),e.jsx("span",{className:`text-sm font-medium ${m.autoRefineEnabled?"text-blue-700":""}`,children:"Auto Refine"}),m.refinementStatus==="running"&&!x(m)&&e.jsx(ie,{className:"badge-shimmer text-white text-xs border-0",children:"Running"}),m.refinementStatus==="running"&&x(m)&&e.jsx(ie,{variant:"outline",className:"text-xs text-amber-600 border-amber-300",children:"Resuming..."}),m.refinementStatus==="completed"&&e.jsx(ie,{className:"bg-gradient-to-r from-purple-600 to-pink-600 text-white text-xs border-0",children:"Optimized"}),m.refinementStatus==="paused"&&e.jsx(ie,{variant:"outline",className:"text-xs",children:"Paused"}),m.refinementStatus==="failed"&&e.jsx(ie,{variant:"outline",className:"text-xs text-red-600 border-red-300",children:"Failed"})]}),e.jsx(xs,{checked:m.autoRefineEnabled||!1,onCheckedChange:H=>_s(m.id,H),className:"data-[state=checked]:bg-blue-700","data-testid":`toggle-auto-refine-${m.id}`})]}),(()=>{const H=Array.isArray(m.scoresPerRound)?m.scoresPerRound:[];if(H.length===0)return null;const Z=H[H.length-1];return e.jsx("div",{className:"mt-2 flex gap-1 flex-wrap",children:e.jsx(Qa,{children:e.jsxs(Ra,{children:[e.jsx(Oa,{children:e.jsxs("div",{className:`px-2 py-0.5 rounded text-xs font-medium border ${Z.score>=8?"bg-purple-100 border-purple-200 text-purple-700":Z.score>=5?"bg-blue-100 border-blue-200 text-blue-700":"bg-gray-100 border-gray-200 text-gray-600"}`,children:["Score: ",Z.score,"/10"]})}),e.jsx(Da,{side:"bottom",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:Z.reasoning})})]})})})})(),Os(m)]},m.id)};return e.jsxs("div",{className:"space-y-6","data-testid":"filters-section",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:justify-between sm:items-center gap-3",children:[e.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2","data-testid":"text-filters-title",children:["Keyword Filters",e.jsx(ie,{variant:"secondary",className:"text-xs font-normal","data-testid":"badge-active-database",children:vr(Ce==null?void 0:Ce.smbType)==="home_improvement"?"Home Improvement/Contractor":g.badgeName})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Jt,{value:J,onValueChange:m=>p(m),children:[e.jsxs(Yt,{className:"w-auto min-w-fit bg-white","data-testid":"sort-keyword-lists",children:[e.jsx(li,{className:"w-4 h-4 mr-2"}),e.jsx(Qt,{placeholder:"Sort by..."})]}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"name_asc",children:"Name (A-Z)"}),e.jsx(Ie,{value:"name_desc",children:"Name (Z-A)"}),e.jsx(Ie,{value:"created_asc",children:"Created (Oldest)"}),e.jsx(Ie,{value:"created_desc",children:"Created (Newest)"}),e.jsx(Ie,{value:"modified_asc",children:"Modified (Oldest)"}),e.jsx(Ie,{value:"modified_desc",children:"Modified (Newest)"})]})]}),e.jsxs(os,{open:s,onOpenChange:i,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(N,{className:"bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white order-3","data-testid":"button-generate-ai",children:[e.jsx(Kt,{className:"w-4 h-4 mr-2"}),"Generate with AI"]})}),e.jsxs(cs,{className:"max-w-2xl max-h-[92vh] overflow-hidden flex flex-col","data-testid":"dialog-generate-ai",onOpenAutoFocus:m=>m.preventDefault(),children:[e.jsxs(as,{className:"border-b border-gray-200 pb-4",children:[e.jsx(rs,{children:"Generate Keyword Filters with AI"}
130),(Ce==null?void 0:Ce.companyWebsite)&&!(Ce!=null&&Ce.websiteOptOut)&&e.jsxs("div",{className:"flex items-center justify-between gap-2 mt-2 p-2.5 bg-blue-50 border border-blue-200 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-blue-700 min-w-0",children:[e.jsx(ri,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:Ce.companyWebsite}),Ce.websiteAnalysisStatus==="success"&&e.jsx("span",{className:"text-green-600 flex-shrink-0",children:"(analyzed)"}),Ce.websiteAnalysisStatus==="failed"&&e.jsx("span",{className:"text-red-600 flex-shrink-0",children:"(failed)"})]}),e.jsxs(N,{type:"button",variant:"outline",size:"sm",onClick:De,disabled:P,className:"whitespace-nowrap text-xs h-7 px-2.5 bg-white border-blue-300 hover:bg-blue-100 text-blue-700","data-testid":"button-rescan-website-keywords",children:[P?e.jsx(Ks,{className:"h-3.5 w-3.5 animate-spin mr-1"}):e.jsx(Ks,{className:"h-3.5 w-3.5 mr-1"}),P?"Scanning...":"Scan My Website"]})]})]}),e.jsxs("div",{className:"overflow-y-auto flex-1 pr-2 pl-1 dialog-scrollbar",children:[e.jsxs("div",{className:"bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-md p-3 flex items-start gap-2 mb-4","data-testid":"info-settings-loaded",children:[e.jsx(br,{className:"h-4 w-4 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0"}),e.jsxs("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:["Pre-loaded from your account settings. Choose:"," ",e.jsx("strong",{children:"Save"})," (update account settings only),"," ",e.jsx("strong",{children:"Generate + Save"})," (update settings & create keywords), or ",e.jsx("strong",{children:"Generate"})," (create keywords without saving changes)."]})]}),e.jsxs("div",{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(xe,{children:"Keyword Type *"}),e.jsxs(sc,{value:V,onValueChange:m=>{d||R(m)},children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Zr,{value:"both",id:"type-both","data-testid":"radio-type-both"}),e.jsx(xe,{htmlFor:"type-both",className:"font-normal cursor-pointer",children:"Both (Positive & Negative)"})]}),e.jsxs("div",{className:`flex items-center space-x-2 ${d?"opacity-40 pointer-events-none":""}`,children:[e.jsx(Zr,{value:"positive",id:"type-positive","data-testid":"radio-type-positive",disabled:d}),e.jsx(xe,{htmlFor:"type-positive",className:`font-normal ${d?"cursor-not-allowed":"cursor-pointer"}`,children:"Positive Only"})]}),e.jsxs("div",{className:`flex items-center space-x-2 ${d?"opacity-40 pointer-events-none":""}`,children:[e.jsx(Zr,{value:"negative",id:"type-negative","data-testid":"radio-type-negative",disabled:d}),e.jsx(xe,{htmlFor:"type-negative",className:`font-normal ${d?"cursor-not-allowed":"cursor-pointer"}`,children:"Negative Only"})]})]})]}),e.jsxs("div",{children:[e.jsx(xe,{htmlFor:"business-description",children:"Company Description (the more info the better our sales targeting will be!) *"}),e.jsx(Ma,{id:"business-description","data-testid":"input-business-description",placeholder:"Describe your business and what you do...",value:pe,onChange:m=>Se(m.target.value)})]}),e.jsxs("div",{children:[e.jsx(xe,{htmlFor:"product-service",children:"Product/Service *"}),e.jsx(Ee,{id:"product-service","data-testid":"input-product-service",placeholder:"What product or service do you offer?",value:Ze,onChange:m=>Me(m.target.value)})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between gap-1",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(xe,{htmlFor:"target-smb-types",children:"Target SMB Types *"}),e.jsx(Qa,{delayDuration:200,children:e.jsxs(Ra,{children:[e.jsx(Oa,{asChild:!0,children:e.jsx(br,{className:"h-4 w-4 text-muted-foreground cursor-help","data-testid":"info-target-smb-types"})}),e.jsx(Da,{className:"max-w-xs",children:e.jsx("p",{className:"text-sm",children:"Examples: Restaurants, Retail Stores, Law Firms, Medical Practices, Construction Companies, Accounting Firms"})})]})})]}),e.jsxs("span",{className:`text-xs font-medium ${He.length>=ot?"text-blue-700":"text-gray-500"}`,children:[He.length," / ",ot," selected"]})]}),e.jsx("p",{className:"text-xs text-blue-600 mt-1 mb-2 font-medium",children:"Select up to 3 categories for keyword lists. Need more? Create another keyword list for those additional categories."}),mt.length>0&&e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1.5 font-medium",children:"Your account categories - click to add:"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:mt.map(m=>{const D=He.includes(m),Z=He.length>=ot&&!D;return e.jsx(ie,{variant:D?"default":"outline",className:`transition-colors text-xs py-1 px-2 ${D?"cursor-pointer bg-blue-600 text-white hover:bg-blue-700 border-blue-600":Z?"cursor-not-allowed opacity-40 border-gray-300 text-gray-500":"cursor-pointer border-blue-300 text-blue-700 hover:bg-blue-50 hover:border-blue-400"}`,onClick:()=>!Z&&G(m),"data-testid":`badge-account-category-${m.toLowerCase().replace(/\s+/g,"-")}`,children:D?`${m} â`:m},m)})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Or type your own and separate multiple types with commas"}),e.jsxs("div",{className:"space-y-2 mt-2",children:[e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(Ee,{id:"target-smb-types","data-testid":"input-target-smb-types",placeholder:"e.g., Restaurants, Retail Stores",value:O,onChange:m=>I(m.target.value),onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),b())},className:"flex-1"}),e.jsx(N,{type:"button",onClick:b,className:"px-4 bg-blue-600 hover:bg-blue-700","data-testid":"button-add-smb-type",disabled:He.length>=ot,children:"Add"})]}),e.jsxs(N,{type:"button",onClick:L,disabled:kt,className:"w-full bg-gradient-to-r from-yellow-500 to-amber-500 hover:from-yellow-600 hover:to-amber-600 text-white font-semibold","data-testid":"button-suggest-categories-ai-generate",children:[e.jsx("span",{className:"mr-2",children:"â¨"}),"Suggest with AI"]}),(kt||Ct.length>0)&&e.jsxs("div",{className:"bg-gradient-to-r from-yellow-50 to-amber-50 border-2 border-yellow-400 rounded-lg p-4",children:[e.jsx("div",{className:"flex items-center mb-2",children:e.jsxs("h3",{className:"text-sm font-semibold text-yellow-800 flex items-center",children:[e.jsx("span",{className:"mr-2",children:"â¨"}),"Suggested Categories"]})}),kt&&e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(Lt,{size:20}),e.jsx("p",{className:"text-sm text-yellow-700",children:Ot&&!["n/a","na","none","not available","not applicable"].includes(Ot.trim().toLowerCase())&&!(Ce!=null&&
130Ce.websiteOptOut)?`Visiting ${Ot} to make category suggestions (this can take 2-3 minutes)...`:"Making category suggestions based on your company description & product/service (this can take 2-3 minutes)..."})]}),!kt&&Ct.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-yellow-700 mb-3",children:"Based on your business information, we recommend these categories:"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Ct.map(m=>{const D=He.includes(m),Z=He.length>=ot&&!D;return e.jsx(ie,{variant:D?"default":"outline",className:`p-2 text-center transition-colors ${D?"cursor-pointer bg-yellow-600 text-white hover:bg-yellow-700 border-yellow-600":Z?"cursor-not-allowed opacity-40 bg-white border-yellow-400 text-yellow-800":"cursor-pointer bg-white border-yellow-400 text-yellow-800 hover:bg-yellow-100 hover:border-yellow-500"}`,onClick:()=>!Z&&_(m),"data-testid":`badge-suggested-generate-${m.toLowerCase().replace(/\s+/g,"-")}`,children:m},m)})})]}),qt&&e.jsx("p",{className:"text-sm text-yellow-700",children:"Unable to load suggestions. Please add your own categories."})]}),He.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:He.map(m=>e.jsxs(ie,{variant:"secondary",className:"gap-1 bg-blue-800 hover:bg-blue-600 text-white","data-testid":`badge-smb-type-${m}`,children:[m,e.jsx(Ut,{className:"h-3 w-3 cursor-pointer",onClick:()=>h(m)})]},m))})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(xe,{htmlFor:"companies-to-avoid",children:"Company Types to Avoid (Optional)"}),e.jsx(Qa,{delayDuration:200,children:e.jsxs(Ra,{children:[e.jsx(Oa,{asChild:!0,children:e.jsx(br,{className:"h-4 w-4 text-muted-foreground cursor-help","data-testid":"info-company-types-avoid"})}),e.jsx(Da,{className:"max-w-xs",children:e.jsx("p",{className:"text-sm",children:"Examples: Art Galleries, Non-Profits, Government Agencies, Educational Institutions, Franchises"})})]})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Separate multiple types with commas"}),e.jsxs("div",{className:"space-y-2 mt-2",children:[e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(Ee,{id:"companies-to-avoid","data-testid":"input-companies-to-avoid",placeholder:"e.g., Art Galleries, Non-Profits",value:tt,onChange:m=>$e(m.target.value),onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),We())},className:"flex-1"}),e.jsx(N,{type:"button",onClick:We,className:"px-4 bg-red-600 hover:bg-red-700","data-testid":"button-add-company-to-avoid",children:"Add"})]}),re.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:re.map(m=>e.jsxs(ie,{variant:"secondary",className:"gap-1 bg-red-800 hover:bg-red-600 text-white","data-testid":`badge-company-avoid-${m}`,children:[m,e.jsx(Ut,{className:"h-3 w-3 cursor-pointer",onClick:()=>gs(m)})]},m))})]})]}),e.jsxs("div",{children:[e.jsx(xe,{htmlFor:"additional-context",children:"Additional Context (Optional)"}),e.jsx(Ma,{id:"additional-context","data-testid":"input-additional-context",placeholder:"Any additional information that would help generate better keywords...",value:W,onChange:m=>Le(m.target.value)})]})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-4 px-6 pb-4 border-t border-gray-200",children:[e.jsx(N,{variant:"outline",onClick:()=>i(!1),"data-testid":"button-cancel-generate",children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(N,{variant:"outline",onClick:na,disabled:hs.isPending||us.isPending,"data-testid":"button-save-settings",children:hs.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(nr,{className:"w-4 h-4 mr-2"}),"Save"]})}),e.jsx(N,{onClick:Va,disabled:hs.isPending||us.isPending,className:"bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white","data-testid":"button-generate-and-save",children:hs.isPending||us.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," ",hs.isPending?"Saving...":"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Kt,{className:"w-4 h-4 mr-2"}),"Generate + Save"]})}),e.jsx(N,{onClick:pa,disabled:hs.isPending||us.isPending,className:"bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white","data-testid":"button-submit-generate",children:us.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Kt,{className:"w-4 h-4 mr-2"}),"Generate"]})})]})]})]})]}),e.jsxs(os,{open:l,onOpenChange:c,children:[e.jsx(Di,{asChild:!0,children:e.jsxs(N,{variant:"outline",className:"order-2","data-testid":"button-create-list",children:[e.jsx(ns,{className:"w-4 h-4 mr-2"}),"Create List"]})}),e.jsxs(cs,{"data-testid":"dialog-create-list",className:"max-h-[90vh] flex flex-col",onOpenAutoFocus:m=>m.preventDefault(),children:[e.jsx(as,{children:e.jsxs(rs,{children:[F?"Edit":"Create"," Keyword List"]})}),!F&&e.jsxs("div",{className:"flex items-start gap-2 bg-purple-50 border border-purple-200 rounded-lg p-3 text-sm text-purple-800",children:[e.jsx(Kt,{className:"w-4 h-4 mt-0.5 flex-shrink-0 text-purple-600"}),e.jsxs("span",{children:["We highly recommend using ",e.jsx("strong",{children:"Generate with AI"})," to automatically create optimized keyword lists tailored to your business."]})]}),e.jsxs("div",{className:"space-y-4 overflow-y-auto flex-1 pr-2 pl-1",children:[e.jsxs("div",{children:[e.jsx(xe,{htmlFor:"list-name",children:"List Name *"}),e.jsx(Ee,{id:"list-name","data-testid":"input-list-name",placeholder:"Enter list name",value:q,onChange:m=>$(m.target.value)})]}),e.jsxs("div",{children:[e.jsx(xe,{htmlFor:"list-type",children:"List Type *"}),e.jsxs(Jt,{value:X,onValueChange:m=>B(m),children:[e.jsx(Yt,{"data-testid":"select-list-type",children:e.jsx(Qt,{})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"positive","data-testid":"option-
130positive",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(Vi,{className:"w-4 h-4 mr-2 text-blue-600"}),"Positive Keywords (Include)"]})}),e.jsx(Ie,{value:"negative","data-testid":"option-negative",children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(qi,{className:"w-4 h-4 mr-2 text-red-600"}),"Negative Keywords (Exclude)"]})})]})]})]}),e.jsxs("div",{children:[e.jsx(xe,{className:"mb-2 block",children:"Keywords"}),e.jsxs("div",{className:"mb-2",children:[e.jsx("input",{ref:U,type:"file",accept:".txt",onChange:be,className:"hidden","data-testid":"input-file-upload"}),e.jsx(N,{variant:"outline",size:"sm",onClick:()=>{var m;return(m=U.current)==null?void 0:m.click()},"data-testid":"button-upload-file",className:"w-full",children:"Upload .txt file"})]}),e.jsx("div",{className:"text-center text-sm text-gray-500 mb-2",children:"and/or"}),e.jsxs("div",{className:"flex gap-2 mb-2",children:[e.jsx(Ee,{"data-testid":"input-new-keyword",placeholder:"Enter keyword (use * for wildcards)",value:Y,onChange:m=>fe(m.target.value),onKeyPress:m=>m.key==="Enter"&&ts()}),e.jsx(N,{onClick:ts,"data-testid":"button-add-keyword",children:e.jsx(ns,{className:"w-4 h-4"})})]}),e.jsx("div",{className:te?"scrollable-with-gradient":"",children:e.jsx("div",{ref:Q,className:"flex flex-wrap gap-2 max-h-48 overflow-y-auto p-1 visible-scrollbar",children:K.map((m,D)=>e.jsxs(ie,{variant:"outline",className:"flex items-center gap-1 bg-white","data-testid":`badge-keyword-${D}`,children:[m,e.jsx(Ut,{className:"w-3 h-3 cursor-pointer",onClick:()=>Zt(m),"data-testid":`button-remove-keyword-${D}`})]},D))})})]})]}),e.jsxs("div",{className:"flex justify-between items-center gap-2 pt-4 border-t",children:[e.jsx("div",{children:F&&K.length>0&&e.jsx(N,{variant:"outline",onClick:ra,"data-testid":"button-export-keywords",children:"Export .txt"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(N,{variant:"outline",onClick:()=>{c(!1),w(null),Ms()},"data-testid":"button-cancel-create",children:"Cancel"}),e.jsxs(N,{onClick:nt,disabled:Nt.isPending||ls.isPending,"data-testid":"button-submit-create",children:[e.jsx(nr,{className:"w-4 h-4 mr-2"}),F?"Update":"Create"]})]})]})]})]}),e.jsx(os,{open:A,onOpenChange:T,children:e.jsxs(cs,{"data-testid":"dialog-delete-confirmation",onOpenAutoFocus:m=>m.preventDefault(),children:[e.jsx(as,{children:e.jsxs(rs,{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"h-5 w-5 text-red-500"}),"Delete Keyword List"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-gray-700",children:["Are you sure you want to delete"," ",e.jsxs("span",{className:"font-semibold",children:['"',j==null?void 0:j.name,'"']}),"?"]}),(j==null?void 0:j.isDefault)&&e.jsxs("div",{className:"bg-amber-50 border border-amber-300 rounded-lg p-3 flex items-start gap-2",children:[e.jsx(ps,{className:"h-4 w-4 text-amber-600 mt-0.5 flex-shrink-0"}),e.jsxs("p",{className:"text-sm text-amber-800",children:["This list is set to ",e.jsx("span",{className:"font-semibold",children:"include in search by default"}),". Deleting it will remove it from your default search filters."]})]}),j&&e.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm font-medium text-gray-700 mb-2",children:"Preview of keywords:"}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[Array.isArray(j.keywords)&&j.keywords.slice(0,10).map((m,D)=>e.jsx(ie,{variant:"outline",className:"text-xs bg-white",children:m},D)),Array.isArray(j.keywords)&&j.keywords.length>10&&e.jsxs(ie,{variant:"outline",className:"text-xs bg-white",children:["+",j.keywords.length-10," more"]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(N,{variant:"outline",onClick:()=>{T(!1),E(null)},"data-testid":"button-cancel-delete",children:"Cancel"}),e.jsxs(N,{variant:"destructive",onClick:Ht,disabled:Rs.isPending,"data-testid":"button-confirm-delete",children:[e.jsx(Hs,{className:"w-4 h-4 mr-2"}),"Delete"]})]})]})]})})]})]}),e.jsx("div",{"data-testid":"card-keyword-lists",children:_t?e.jsx("p",{children:"Loading keyword lists..."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3 mb-4",children:[ye.map(m=>e.jsxs("div",{className:"flex items-center gap-3 p-4 bg-blue-50 border border-blue-200 rounded-lg","data-testid":`pending-job-${m.id}`,children:[e.jsx(Lt,{size:18}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-blue-900 font-medium",children:"AI keyword generation pending"}),e.jsx("p",{className:"text-blue-700 text-sm",children:"We're analyzing your business and generating smart targeting keywords. This usually takes 1-2 minutes."}),St[m.id]&&e.jsxs("div",{className:"mt-3 space-y-2","data-testid":`progress-keyword-generation-${m.id}`,children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("p",{className:"text-sm font-medium text-blue-800",children:St[m.id].message}),e.jsxs("span",{className:"text-sm font-semibold text-blue-900",children:[St[m.id].progress,"%"]})]}
130),e.jsx(zo,{value:St[m.id].progress,className:"h-2"})]})]})]},m.id)),Tt&&e.jsxs("div",{className:"flex items-center gap-3 p-4 bg-yellow-50 border border-yellow-200 rounded-lg",children:[e.jsx("div",{className:"w-4 h-4 bg-yellow-600 rounded-full"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-yellow-900 font-medium",children:"Keyword generation is taking longer than expected"}),e.jsx("p",{className:"text-yellow-700 text-sm",children:"You can create keyword lists manually or try refreshing the page to check if they're ready."})]})]})]}),Ye.length===0&&!Xt?e.jsx("p",{className:"text-gray-500",children:"No keyword lists yet. Create one to get started!"}):e.jsxs("div",{className:"space-y-0",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 pl-5",children:[e.jsx(Vi,{className:"w-5 h-5 text-blue-600"}),e.jsx("h3",{className:"font-semibold text-gray-700",children:"Positive Keywords (Include)"})]}),e.jsxs("div",{className:"flex items-center gap-2 pl-5",children:[e.jsx(qi,{className:"w-5 h-5 text-red-600"}),e.jsx("h3",{className:"font-semibold text-gray-700",children:"Negative Keywords (Exclude)"})]})]}),e.jsx("div",{className:"space-y-4",children:Ye.map((m,D)=>{var we,Be;const H=((Be=(we=m.positive||m.negative)==null?void 0:we.name)==null?void 0:Be.replace(/ \((Positive|Negative)\).*$/,""))||"",Z=v===D;return e.jsxs("div",{className:"bg-white border border-gray-300 rounded-xl shadow-sm p-5",children:[e.jsx("div",{className:"flex items-center gap-2 mb-4 pb-3 border-b border-gray-200",children:Z?e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx("input",{type:"text",value:k,onChange:ge=>a(ge.target.value),onKeyDown:ge=>{var dt,vs;ge.key==="Enter"&&k.trim()&&es.mutate({positiveId:(dt=m.positive)==null?void 0:dt.id,negativeId:(vs=m.negative)==null?void 0:vs.id,newBaseName:k.trim()}),ge.key==="Escape"&&y(null)},autoFocus:!0,className:"text-base font-semibold text-gray-800 border border-gray-300 rounded px-2 py-1 flex-1 max-w-xs focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),e.jsx(N,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!k.trim()||es.isPending,onClick:()=>{var ge,dt;k.trim()&&es.mutate({positiveId:(ge=m.positive)==null?void 0:ge.id,negativeId:(dt=m.negative)==null?void 0:dt.id,newBaseName:k.trim()})},children:e.jsx(sa,{className:"w-4 h-4 text-green-600"})}),e.jsx(N,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>y(null),children:e.jsx(Ut,{className:"w-4 h-4 text-gray-400"})})]}):e.jsxs("div",{className:"flex items-center gap-1.5 group",children:[e.jsx("span",{className:"text-base font-semibold text-gray-800",children:H}),e.jsx("button",{onClick:()=>{y(D),a(H)},className:"opacity-0 group-hover:opacity-100 transition-opacity p-0.5 rounded hover:bg-gray-100",title:"Rename list",children:e.jsx(Kd,{className:"w-3.5 h-3.5 text-gray-400"})})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx("div",{children:m.positive?ws(m.positive):e.jsx("div",{className:"border border-dashed border-gray-300 rounded-lg p-4 flex items-center justify-center min-h-[120px]",children:e.jsx("p",{className:"text-gray-400 text-sm text-center",children:"No positive list"})})}),e.jsx("div",{children:m.negative?ws(m.negative):e.jsx("div",{className:"border border-dashed border-gray-300 rounded-lg p-4 flex items-center justify-center min-h-[120px]",children:e.jsx("p",{className:"text-gray-400 text-sm text-center",children:"No negative list"})})})]})]},`row-${D}`)})})]})]})}),f.length>0&&e.jsx(Ue,{"data-testid":"card-apply-filters",children:e.jsx(_e,{className:"pt-6",children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("span",{"data-testid":"text-selected-lists",children:[f.length," list",f.length!==1?"s":""," selected"]}),e.jsxs(N,{onClick:ct,"data-testid":"button-apply-filters",children:[e.jsx(Ls,{className:"w-4 h-4 mr-2"}),"Apply Filters"]})]})})})]})}const Un=90;function _p(t){if(!t)return null;const r=t instanceof Date?t:new Date(t);return Number.isNaN(r.getTime())?null:r}function zp(t){const r=_p(t);return r?r.toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric",timeZone:"UTC"}):""}const Xr=["lastUpdated","ylprProfileUrl","ylprProfileName","ylprStars","ylprReviewCount","ylprCategories","ylprAddressFull","ylprAddressStreet","ylprAddressCity","ylprAddressState","ylprAddressZip","ylprPhone","ylprDescription","ylprFeaturedReview","ylprTimeScraped"],en=["lastUpdated","lastUpdatedReason","wOgrequestedUrl","wProfileDate","
130wRedirectYn","wSimpleCrawledUrl","wCompanyName","aiCategoryEstimation","wPhonePrimary","wPhoneTotal","wEmailPrimary","wEmailPrimaryMx","wEmailTier1","wEmailTier2","wEmailTier3","wEmailTier4","wEmailTier5","wEmailTier6","wEmailDomainMx","wEmailSecurity","wProfileCategory","wProfileDescriptionShort","wProfileDescriptionLong","wAddressFull","wAddressStreet","wAddressCity","wAddressState","wAddressZip","wAddressSource","wPlatform","wBookingOpsCrmSoftware","wReputationChatSoftware","wMarketingEmailSoftware","wAdPixels","wPaymentFinancingSoftware","wEmployeeCount","wOpenPositions","wFoundingDate","wNumLocations","wIsChain","wRatingValue","wReviewCount","wPriceRange","wLegalName","wIndustryNaics","wDuns","wFounder","wFounderEmail","wFounderPhone","wGeoLat","wGeoLong","wOpeningHours","wAreaServed","wOffers","wBrand","wSlogan","wLogoUrl","wSocialProfiles","wTimeScraped"],Vp={lastUpdated:ca,lastUpdatedReason:Xa,ylprProfileUrl:"Profile URL",ylprProfileName:"Company Name",ylprStars:"Stars",ylprReviewCount:"Review Count",ylprCategories:"Categories",ylprAddressFull:"Address Full",ylprAddressStreet:"Street",ylprAddressCity:"City",ylprAddressState:"State",ylprAddressZip:"Zip",ylprPhone:"Phone",ylprDescription:"Description",ylprFeaturedReview:"Review Snippet",ylprTimeScraped:"Time Scraped",wOgrequestedUrl:"Registered URL",wProfileDate:"Registration Date",wRedirectYn:"Redirect",wSimpleCrawledUrl:"Crawled URL",wCompanyName:"Company Name",aiCategoryEstimation:"Categories (AI Enrichment)",wAddressFull:"Address Full",wAddressStreet:"Street",wAddressCity:"City",wAddressState:"State",wAddressZip:"Zip",wAddressSource:"Address Source",wPhonePrimary:"Phone Primary",wPhoneTotal:"Total Phones",wEmailPrimary:"Email Primary",wEmailPrimaryMx:"Email Primary Provider",wEmailTier1:"Tier 1 Emails",wEmailTier2:"Tier 2 Emails",wEmailTier3:"Tier 3 Emails",wEmailTier4:"Tier 4 Emails",wEmailTier5:"Tier 5 Emails",wEmailTier6:"Tier 6 Emails",wEmailDomainMx:"Website Email Provider",wEmailSecurity:"Website Email Security",wProfileCategory:"Website Schema",wProfileDescriptionShort:"Description Short",wProfileDescriptionLong:"Description Long",wPlatform:"Platform",wBookingOpsCrmSoftware:"Booking/Ops/CRM Software",wReputationChatSoftware:"Reputation/Chat Software",wMarketingEmailSoftware:"Marketing/Email Software",wAdPixels:"Ad Pixels",wPaymentFinancingSoftware:"Payment/Financing Software",wEmployeeCount:"Employees",wOpenPositions:"Number of Job Postings",wFoundingDate:"Founding Date",wNumLocations:"Number of Locations",wIsChain:"Is Chain?",wRatingValue:"Rating Value",wReviewCount:"Review Count",wPriceRange:"Price Range",wLegalName:"Legal Name",wIndustryNaics:"NAICS Code",wDuns:"DUNS Number",wFounder:"Founder Name(s)",wFounderEmail:"Founder Email(s)",wFounderPhone:"Founder Phone(s)",wGeoLat:"Latitude",wGeoLong:"Longitude",wOpeningHours:"Opening Hours",wAreaServed:"Area Served",wOffers:"Offers",wBrand:"Brand",wSlogan:"Slogan",wLogoUrl:"Logo URL",wSocialProfiles:"Social Profiles",wTimeScraped:"Time Scraped"},qp={lastUpdated:Ed};function gr(t,r){return r==="home_improvement"&&qp[t]||Vp[t]||t}function gl(t){switch(t){case"csv":return e.jsx($a,{className:"h-3.5 w-3.5"});case"json":return e.jsx(Od,{className:"h-3.5 w-3.5"});case"xlsx":return e.jsx(Dd,{className:"h-3.5 w-3.5"});default:return e.jsx($a,{className:"h-3.5 w-3.5"})}}function yl(t){switch(t){case"csv":return"bg-green-100 text-green-700";case"json":return"bg-blue-100 text-blue-700";case"xlsx":return"bg-purple-100 text-purple-700";default:return"bg-gray-100 text-gray-700"}}function Hp(t,r,s){let i;if(r==="xlsx"){const d=atob(s),u=new Uint8Array(d.length);for(let g=0;g<d.length;g++)u[g]=d.charCodeAt(g);i=new Blob([u],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})}else i=new Blob([s],{type:r==="json"?"application/json":"text/csv;charset=utf-8"});const l=URL.createObjectURL(i),c=document.createElement("a");c.href=l,c.download=t,document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(l)}function Wp(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}const fl=t=>({name:"",fileType:"csv",startRow:1,fieldMappings:(t==="home_improvement"?Xr:en).map(s=>({sourceField:s,exportName:gr(s,t),type:"field"})),splitFiles:!1,splitMode:"max_rows",maxRowsPerFile:null,numberOfParts:null,includeTotal:!1,includeHeaders:!0,combinedAssigneeColumnName:"Assigned To",combinedFileNameColumnName:"File Part"}),Bp={ylprProfileName:"company",wCompanyName:"company",ylprPhone:"phone",wPhonePrimary:"phone",wPhoneTotal:"phone",wEmailPrimary:"email",wEmailTier1:"email",wEmailTier2:"email",wEmailTier3:"email",wEmailTier4:"email",wEmailTier5:"email",wEmailTier6:"email",ylprAddressCity:"city",wAddressCity:"city",ylprAddressState:"state",wAddressState:"state"};function bl(t,r,s){if(!t)return" - ";const i=t[r];return r==="lastUpdated"?i?Ka(new Date(i),"MMM d, yyyy"):" - ":r==="lastUpdatedReason"?!i||i.length===0?" - ":Array.isArray(i)?i.join(", "):String(i):r==="ylprProfileUrl"?i?e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline",children:i}):" - ":r==="ylprPhone"?s!=null&&s.maskFn?s.maskFn(i):i||" - ":r==="ylprTimeScraped"?i?Ka(new Date(i),"MMM d, yyyy"):" - ":i??" - "}function wl(t,r,s){if(!t)return" - ";const i=t[r];
130if(r==="lastUpdated")return i?Ka(new Date(i),"MMM d, yyyy"):" - ";if(r==="lastUpdatedReason")return!i||i.length===0?" - ":Array.isArray(i)?i.join(", "):String(i);if(r==="wOgrequestedUrl"||r==="wSimpleCrawledUrl")return i?e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline",children:i}):" - ";if(r==="wTimeScraped"||r==="wProfileDate")return i?Ka(new Date(i),"MMM d, yyyy"):" - ";const l=new Set(["wPhonePrimary","wPhoneTotal","wEmailPrimary","wEmailTier1","wEmailTier2","wEmailTier3","wEmailTier4","wEmailTier5","wEmailTier6","wFounderEmail","wFounderPhone"]);return s!=null&&s.maskFn&&l.has(r)?s.maskFn(i):i??" - "}function vl(t,r){const s=t instanceof Error?t.message:String(t??""),i=s.slice(s.indexOf(":")+1).trim();try{const l=JSON.parse(i);if(l&&typeof l.message=="string"&&l.message)return l.message}catch{}return r}function Jp({userId:t,smbType:r,subscriptionPlan:s,isSubscribed:i=!1,freeLeadsUsed:l=0,monthlyCredits:c=0,monthlyCreditsUsed:d=0,permanentCredits:u=0}){var ss;const{toast:g}=Ss(),{user:f}=Pr(),C=!!(f!=null&&f.isAdmin),F=ja(),w=vr(),j=ar(),E=w==="home_improvement"?Xr:en,A=w==="home_improvement"?"yelp_profile":"domain",[T,J]=o.useState(!1),[p,v]=o.useState(null),[y,k]=o.useState(fl(w)),[a,q]=o.useState(!1),[$,X]=o.useState(A),[B,K]=o.useState(""),[ae,Y]=o.useState(!1),[fe,U]=o.useState(""),[te,ne]=o.useState(!1),[Q,V]=o.useState(!1),[R,pe]=o.useState(""),{data:Se=[],isLoading:Ze}=Qe({queryKey:["/api/export-formats"]}),Me=Se.filter(x=>x.databaseType===w),{data:He=[],isLoading:ee}=Qe({queryKey:["/api/export-blacklist"]}),{data:O}=Qe({queryKey:["/api/export-blacklist/google-doc"]}),I=C?500:50,{data:re,isLoading:Pe,isFetchingNextPage:tt,hasNextPage:$e,fetchNextPage:W}=Rd({queryKey:["/api/export-history",I],initialPageParam:0,queryFn:async({pageParam:x})=>{const M=new URLSearchParams({limit:String(I),offset:String(x??0)}),me=await fetch(`/api/export-history?${M}`);if(!me.ok)throw new Error("Failed to fetch export history");return me.json()},getNextPageParam:(x,M)=>{const me=M.reduce((Ve,xt)=>Ve+xt.entries.length,0);if(!(me>=x.totalCount))return me}}),Le=(re==null?void 0:re.pages.flatMap(x=>x.entries))??[],ve=((ss=re==null?void 0:re.pages[0])==null?void 0:ss.totalCount)??0,[Oe,vt]=o.useState(0),[Rt,At]=o.useState(""),[at,Je]=o.useState(""),[Te,Ct]=o.useState(""),[lt,kt]=o.useState(""),[ft,qt]=o.useState(()=>{const x=localStorage.getItem("leadHistoryPageSize"),M=x?parseInt(x):25;return[25,50,100,200,500,1e3].includes(M)?M:25}),{data:et,isLoading:Ot}=Qe({queryKey:["/api/lead-export-history",Oe,ft,Rt,at,Te,lt],queryFn:async()=>{const x=new URLSearchParams({limit:String(ft),offset:String(Oe*ft)});Rt&&x.set("databaseType",Rt),at&&x.set("exportMethod",at),Te&&x.set("dateFrom",Te),lt&&x.set("dateTo",lt);const M=await fetch(`/api/lead-export-history?${x}`);if(!M.ok)throw new Error("Failed to fetch lead export history");return M.json()}}),{data:Xe,isLoading:mt}=Qe({queryKey:["/api/lead-reservoir"],queryFn:async()=>{const x=await fetch("/api/lead-reservoir");if(!x.ok)throw new Error("Failed to fetch reservoir");return x.json()}}),[ut,ot]=o.useState(new Set),St=["pro"].includes(s||""),Pt=["starter","growth","scale","platinum","enterprise"].includes(s||""),it=Pt?Math.max(0,c-d)+Math.max(0,u):0,ze=Pt?it:i?1/0:Math.max(0,20-l),_t=St?1/0:Math.max(0,ze),de=w==="home_improvement"?"home_improvement":"other",gt=((Xe==null?void 0:Xe.allLeadIds)||[]).filter(x=>x.databaseType===de).map(x=>x.leadId),It=Xe!=null&&Xe.allLeadIds?new Set(Xe.allLeadIds.map(x=>x.databaseType)).size>1:!1,Ge=x=>{ot(M=>{const me=new Set(M);if(me.has(x))me.delete(x);else{if(!St&&me.size>=_t)return M;me.add(x)}return me})},Ce=()=>{if(ut.size>0)ot(new Set);else{const x=Math.min(gt.length,St?1/0:_t);ot(new Set(gt.slice(0,x)))}},P=Ne({mutationFn:async()=>(await ue("DELETE","/api/lead-reservoir")).json(),onSuccess:()=>{z.invalidateQueries({queryKey:["/api/lead-reservoir"]}),ot(new Set),g({title:"Reservoir cleared"})},onError:x=>{ce("ExportsTab","Failed to clear reservoir",x),g({title:"Error",description:"Failed to clear reservoir",variant:"destructive"})}}),le=Ne({mutationFn:async x=>(await ue("POST","/api/lead-reservoir/export",{selectedLeadIds:x,databaseType:de})).json(),onSuccess:x=>{z.invalidateQueries({queryKey:["/api/lead-reservoir"]}),z.invalidateQueries({queryKey:["/api/export-history"]}),z.invalidateQueries({queryKey:["/api/lead-export-history"]}),z.invalidateQueries({queryKey:["/api/user"]}),ot(new Set);const M=(x.files||[]).filter(me=>
130me.downloadAvailable===!1&&typeof me.data=="string");for(const me of M)Hp(me.fileName,me.fileType,me.data);g({title:`Exported ${x.leadCount} reservoir leads`,description:M.length>0?"Your file was downloaded now because it could not be saved to Export History.":"Download the file from Export History above."})},onError:x=>{ce("ExportsTab","Failed to export reservoir leads",x),g({title:"Error",description:(x==null?void 0:x.message)||"Failed to export reservoir leads",variant:"destructive"})}}),[De,st]=o.useState(new Set),[Ft,oe]=o.useState(""),Ye=x=>{st(M=>{const me=new Set(M);return me.has(x)?me.delete(x):me.add(x),me})},pt=x=>x.filter(M=>M.databaseType===w).map(M=>M.id),jt=()=>{if(!et)return;const x=pt(et.entries),M=x.every(me=>De.has(me));st(M?new Set:new Set(x))},ye=Ne({mutationFn:async()=>{const x={trackingIds:Array.from(De)};return Ft&&(x.formatId=parseInt(Ft)),await ue("POST","/api/lead-export-history/re-export",x)},onSuccess:async x=>{const M=x.headers.get("content-disposition"),me=M==null?void 0:M.match(/filename="(.+)"/),Ve=me?me[1]:"re-export.csv",xt=await x.blob(),Ht=URL.createObjectURL(xt),be=document.createElement("a");be.href=Ht,be.download=Ve,document.body.appendChild(be),be.click(),document.body.removeChild(be),URL.revokeObjectURL(Ht),g({title:"Re-export complete",description:`Downloaded ${Ve}`}),st(new Set)},onError:x=>{ce("ExportsTab","Failed to re-export leads",x),g({title:"Error",description:vl(x,"Failed to re-export leads"),variant:"destructive"})}}),Xt=Ne({mutationFn:async()=>{const x=new URLSearchParams,M=w;M&&x.set("databaseType",M),at&&x.set("exportMethod",at),Te&&x.set("dateFrom",Te),lt&&x.set("dateTo",lt);const me=await fetch(`/api/lead-export-history/ids?${x}`);if(!me.ok)throw new Error("Failed to fetch all IDs");return(await me.json()).ids},onSuccess:x=>{st(new Set(x))},onError:()=>{g({title:"Error",description:"Failed to select all results",variant:"destructive"})}}),rt=Ne({mutationFn:async()=>{const x={trackingIds:Array.from(De)};return(await ue("POST","/api/lead-export-history/refresh",x)).json()},onSuccess:x=>{z.invalidateQueries({queryKey:["/api/lead-export-history"]});const M=x.results||[],me=M.filter(be=>be.refreshed).length,Ve=M.filter(be=>be.changed).length,xt=me-Ve,Ht=me===0?"No entries could be refreshed.":Ve>0?`${Ve} lead${Ve===1?"":"s"} had new data, ${xt} unchanged.`:`${me} lead${me===1?"":"s"} refreshed (no changes).`;g({title:"Refresh complete",description:Ht})},onError:x=>{ce("ExportsTab","Failed to refresh lead export history",x),g({title:"Error",description:"Failed to refresh lead data",variant:"destructive"})}}),fs=Ne({mutationFn:async x=>(await ue("POST","/api/lead-export-history/acknowledge-changes",{trackingIds:x})).json(),onSuccess:()=>{z.invalidateQueries({queryKey:["/api/lead-export-history"]})},onError:x=>{ce("ExportsTab","Failed to acknowledge lead export changes",x),g({title:"Error",description:"Failed to clear change indicators",variant:"destructive"})}}),Tt=Ne({mutationFn:async()=>{const x={trackingIds:Array.from(De)};return Ft&&(x.formatId=parseInt(Ft)),await ue("POST","/api/lead-export-history/refresh-and-export",x)},onSuccess:async x=>{const M=x.headers.get("content-disposition"),me=M==null?void 0:M.match(/filename="(.+)"/),Ve=me?me[1]:"refreshed-export.csv",xt=await x.blob(),Ht=URL.createObjectURL(xt),be=document.createElement("a");be.href=Ht,be.download=Ve,document.body.appendChild(be),be.click(),document.body.removeChild(be),URL.revokeObjectURL(Ht),z.invalidateQueries({queryKey:["/api/lead-export-history"]}),g({title:"Refresh and export complete",description:`Downloaded ${Ve} with latest lead data.`}),st(new Set)},onError:x=>{ce("ExportsTab","Failed to refresh and export leads",x),g({title:"Error",description:vl(x,"Failed to refresh and export leads"),variant:"destructive"})}}),yt=Ne({mutationFn:async x=>(await ue("POST","/api/export-formats",{...x,userId:t,databaseType:w})).json(),onSuccess:()=>{z.invalidateQueries({queryKey:["/api/export-formats"]}),J(!1),Bt(),g({title:"Format Created",description:"Export format has been created."})},onError:x=>{ce("ExportsTab","Failed to create export format",x),g({title:"Error",description:"Failed to create export format.",variant:"destructive"})}}),is=Ne({mutationFn:async({id:x,data:M})=>(await ue("PATCH",`/api/export-formats/${x}`,M)).json(),onSuccess:()=>{z.invalidateQueries({queryKey:["/api/export-formats"]}),J(!1),v(null),Bt(),g({title:"Format Updated",description:"Export format has been updated."})},onError:x=>{ce("ExportsTab","Failed to update export format",x),g({title:"Error",description:"Failed to update export format.",variant:"destructive"})}}),Dt=Ne({mutationFn:async x=>{await ue("DELETE",`/api/export-formats/${x}`)},onSuccess:()=>{z.invalidateQueries({queryKey:["/api/export-formats"]}),g({title:"Format Deleted",description:"Export format has been deleted."})},onError:x=>{ce("ExportsTab","Failed to delete export format",x),g({title:"Error",description:"Failed to delete export format.",variant:"destructive"})}}),Ae=Ne({mutationFn:async x=>{await ue("POST",`/api/export-formats/${x}/set-default`)},onSuccess:()=>{z.invalidateQueries({queryKey:["/api/export-formats"]}),g({title:"Default Updated",description:"Default export format has been updated."})},onError:x=>{ce("ExportsTab","Failed to set default format",x),g({title:"Error",description:"Failed to set default format.",variant:"destructive"})}}),bt=Ne({mutationFn:async()=>{await ue("POST","/api/export-formats/clear-default")},onSuccess:()=>{z.invalidateQueries({queryKey:["/api/export-formats"]}),g({title:"Default Updated",description:"System default format is now active."})},onError:x=>{ce("ExportsTab","Failed to clear default format",x),g({title:"Error",description:"Failed to update default format.",variant:"destructive"})}}),Nt=Ne({mutationFn:async x=>(await ue("POST","/api/export-blacklist",{...x,userId:t})).json(),onSuccess:()=>{z.invalidateQueries({queryKey:["/api/export-blacklist"]}
130),q(!1),K(""),g({title:"Entry Added",description:"Blacklist entry has been added."})},onError:x=>{ce("ExportsTab","Failed to add blacklist entry",x),g({title:"Error",description:"Failed to add blacklist entry.",variant:"destructive"})}}),ls=Ne({mutationFn:async x=>(await ue("POST","/api/export-blacklist",{entries:x})).json(),onSuccess:()=>{z.invalidateQueries({queryKey:["/api/export-blacklist"]}),Y(!1),U(""),g({title:"Import Complete",description:"Blacklist entries have been imported."})},onError:x=>{ce("ExportsTab","Failed to import blacklist entries",x),g({title:"Error",description:"Failed to import blacklist entries.",variant:"destructive"})}}),es=Ne({mutationFn:async x=>{await ue("DELETE",`/api/export-blacklist/${x}`)},onSuccess:()=>{z.invalidateQueries({queryKey:["/api/export-blacklist"]}),g({title:"Entry Removed",description:"Blacklist entry has been removed."})},onError:x=>{ce("ExportsTab","Failed to remove blacklist entry",x),g({title:"Error",description:"Failed to remove blacklist entry.",variant:"destructive"})}}),Rs=Ne({mutationFn:async()=>{await ue("DELETE","/api/export-blacklist")},onSuccess:()=>{z.invalidateQueries({queryKey:["/api/export-blacklist"]}),ne(!1),g({title:"Blacklist Cleared",description:"All blacklist entries have been removed."})},onError:x=>{ce("ExportsTab","Failed to clear blacklist",x),g({title:"Error",description:"Failed to clear blacklist.",variant:"destructive"})}}),bs=Ne({mutationFn:async x=>(await ue("POST","/api/export-blacklist/google-doc",{googleDocUrl:x})).json(),onSuccess:()=>{z.invalidateQueries({queryKey:["/api/export-blacklist/google-doc"]}),V(!1),pe(""),g({title:"Google Doc Connected",description:"Google Doc has been linked to your blackl
130ist."})},onError:x=>{ce("ExportsTab","Failed to connect Google Doc",x),g({title:"Error",description:"Failed to connect Google Doc.",variant:"destructive"})}}),Ps=Ne({mutationFn:async()=>{await ue("DELETE","/api/export-blacklist/google-doc")},onSuccess:()=>{z.invalidateQueries({queryKey:["/api/export-blacklist/google-doc"]}),g({title:"Google Doc Removed",description:"Google Doc has been unlinked."})},onError:x=>{ce("ExportsTab","Failed to remove Google Doc",x),g({title:"Error",description:"Failed to remove Google Doc.",variant:"destructive"})}}),ms=Ne({mutationFn:async()=>{await ue("POST","/api/export-blacklist/google-doc/refresh")},onSuccess:()=>{z.invalidateQueries({queryKey:["/api/export-blacklist"]}),z.invalidateQueries({queryKey:["/api/export-blacklist/google-doc"]}),g({title:"Refreshed",description:"Google Doc blacklist has been refreshed."})},onError:x=>{ce("ExportsTab","Failed to refresh Google Doc",x),g({title:"Error",description:"Failed to refresh Google Doc.",variant:"destructive"})}});function Bt(){k(fl(w)),v(null)}function he(){Bt(),J(!0)}function _s(){const x=w==="home_improvement"?Xr:en;v(null),k({name:"My Export Format",fileType:"csv",startRow:1,fieldMappings:x.map(M=>({sourceField:M,exportName:gr(M,w),type:"field"})),splitFiles:!1,splitMode:"max_rows",maxRowsPerFile:null,numberOfParts:null,includeTotal:!1,includeHeaders:!0,combinedAssigneeColumnName:"Assigned To",combinedFileNameColumnName:"File Part"}),J(!0)}function hs(x){v(null),k({name:`${x.name} (Copy)`,fileType:x.fileType,startRow:x.startRow??1,fieldMappings:x.fieldMappings||[],splitFiles:x.splitFiles??!1,splitMode:x.splitMode??"max_rows",maxRowsPerFile:x.maxRowsPerFile??null,numberOfParts:x.numberOfParts??null,includeTotal:x.includeTotal??!1,includeHeaders:x.includeHeaders??!0,combinedAssigneeColumnName:x.combinedAssigneeColumnName||"Assigned To",combinedFileNameColumnName:x.combinedFileNameColumnName||"File Part"}),J(!0)}function us(x){v(x.id),k({name:x.name,fileType:x.fileType,startRow:x.startRow??1,fieldMappings:x.fieldMappings||[],splitFiles:x.splitFiles??!1,splitMode:x.splitMode??"max_rows",maxRowsPerFile:x.maxRowsPerFile??null,numberOfParts:x.numberOfParts??null,includeTotal:x.includeTotal??!1,includeHeaders:x.includeHeaders??!0,combinedAssigneeColumnName:x.combinedAssigneeColumnName||"Assigned To",combinedFileNameColumnName:x.combinedFileNameColumnName||"File Part"}),J(!0)}function Ms(){k(x=>({...x,fieldMappings:[...x.fieldMappings,{sourceField:E[0],exportName:gr(E[0],w),type:"field"}]}))}function n(){k(x=>({...x,fieldMappings:[...x.fieldMappings,{sourceField:"",exportName:"",type:"spacer"}]}))}function b(x,M){k(me=>({...me,fieldMappings:me.fieldMappings.map((Ve,xt)=>xt===x?{...Ve,...M}:Ve)}))}function h(x){k(M=>({...M,fieldMappings:M.fieldMappings.filter((me,Ve)=>Ve!==x)}))}function L(x,M){k(me=>{const Ve=[...me.fieldMappings],xt=M==="up"?x-1:x+1;return xt<0||xt>=Ve.length?me:([Ve[x],Ve[xt]]=[Ve[xt],Ve[x]],{...me,fieldMappings:Ve})})}function _(){if(!y.name.trim()){ce("ExportsTab","Validation: format name required"),g({title:"Validation Error",description:"Format name is required.",variant:"destructive"});return}if(y.fieldMappings.length===0){ce("ExportsTab","Validation: no field mappings"),g({title:"Validation Error",description:"At least one field mapping is required.",variant:"destructive"});return}p?is.mutate({id:p,data:y}):yt.mutate(y)}function G(){const x=fe.split(` 131`).map(me=>me.trim()).filter(me=>me.length>0);if(x.length===0){ce("ExportsTab","Validation: no blacklist entries"),g({title:"No Entries",description:"Please enter at least one entry.",variant:"destructive"});return}const M=x.map(me=>({entryType:A,value:me,userId:t}));ls.mutate(M)}const[We,gs]=o.useState(null),ts=o.useRef(Promise.resolve());async function Zt(x){if(We!==x.id){gs(x.id);try{const M=await fetch(`/api/export-history/${x.id}/download-url`),me=await M.json().catch(()=>({}));if(!M.ok||typeof me.url!="string"){g({title:"Download unavailable",description:me.message||"This export file could not be downloaded.",variant:"destructive"}),M.status===410&&z.invalidateQueries({queryKey:["/api/export-history"]});return}const Ve=me.url,xt=ts.current.then(()=>new Promise(Ht=>{window.location.assign(Ve),setTimeout(Ht,1500)}));ts.current=xt.catch(()=>{}),await xt}
131catch(M){ce("ExportsTab","Failed to download export file",M,{exportId:x.id}),g({title:"Error",description:"Failed to download export file.",variant:"destructive"})}finally{gs(null)}}}const nt=yt.isPending||is.isPending;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Ue,{className:"bg-white border-gray-200",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Ga,{className:"h-5 w-5 text-blue-600"}),"Export Settings"]})}),e.jsxs(_e,{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:"font-semibold text-gray-800 flex items-center gap-2",children:[e.jsx($a,{className:"h-4 w-4 text-gray-500"}),"Format Presets"]}),e.jsxs(N,{size:"sm",onClick:he,children:[e.jsx(ns,{className:"h-4 w-4 mr-1"}),"Create Format"]})]}),Ze?e.jsx(ea,{size:"sm",text:"Loading formats...",className:"py-0"}):e.jsxs("div",{className:"space-y-2",children:[(()=>{const M=!Me.some(Ve=>Ve.isDefault),me=w==="home_improvement"?Xr.length:en.length;return e.jsxs("div",{className:`flex items-center justify-between p-3 border rounded-lg transition-colors ${M?"border-blue-200 bg-blue-50/30":"border-gray-200 bg-gray-50/50 opacity-70"}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{type:"button",role:"checkbox","aria-checked":M,disabled:M||bt.isPending||Ae.isPending,onClick:()=>{M||bt.mutate()},className:`h-4 w-4 shrink-0 rounded-sm border flex items-center justify-center transition-colors disabled:opacity-50 ${M?"border-blue-600 bg-blue-600 text-white":"border-gray-300 hover:border-gray-400"}`,children:M&&e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"h-3 w-3",children:e.jsx("polyline",{points:"20 6 9 17 4 12"})})}),e.jsx("span",{className:"font-medium text-gray-500",children:"System Default"}),M&&e.jsx("span",{className:"text-xs text-blue-600",children:"(Active)"}),e.jsxs(ie,{className:"text-xs bg-green-100 text-green-700",children:[e.jsx($a,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"ml-1",children:"CSV"})]}),e.jsxs("span",{className:"text-xs text-gray-400",children:[me," fields, headers included"]})]}),e.jsx(N,{variant:"ghost",size:"sm",onClick:_s,title:"Copy as new format",children:e.jsx(jr,{className:"h-3.5 w-3.5 text-gray-400"})})]})})(),Me.length===0&&e.jsx("p",{className:"text-xs text-gray-400 px-1",children:"Create a custom format to control which fields are exported and in what order."}),Me.map(x=>e.jsxs("div",{className:`flex items-center justify-between p-3 border rounded-lg hover:bg-gray-50 transition-colors ${x.isDefault?"border-blue-200 bg-blue-50/30":"border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{type:"button",role:"checkbox","aria-checked":!!x.isDefault,disabled:bt.isPending||Ae.isPending,onClick:()=>{x.isDefault?bt.mutate():Ae.mutate(x.id)},className:`h-4 w-4 shrink-0 rounded-sm border flex items-center justify-center transition-colors disabled:opacity-50 ${x.isDefault?"border-blue-600 bg-blue-600 text-white":"border-gray-300 hover:border-gray-400"}`,children:x.isDefault&&e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"h-3 w-3",children:e.jsx("polyline",{points:"20 6 9 17 4 12"})})}),e.jsx("span",{className:"font-medium text-gray-800",children:x.name}),x.isDefault&&e.jsx("span",{className:"text-xs text-blue-600",children:"(Active)"}),e.jsxs(ie,{className:`text-xs ${yl(x.fileType)}`,children:[gl(x.fileType),e.jsx("span",{className:"ml-1",children:x.fileType.toUpperCase()})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>hs(x),title:"Duplicate",children:e.jsx(jr,{className:"h-3.5 w-3.5 text-gray-400"})}),e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>us(x),title:"Edit",children:e.jsx(Ga,{className:"h-3.5 w-3.5 text-gray-500"})}),e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>Dt.mutate(x.id),disabled:Dt.isPending,title:"Delete",children:e.jsx(Hs,{className:"h-3.5 w-3.5 text-red-400"})})]})]},x.id))]})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:"font-semibold text-gray-800 flex items-center gap-2",children:[e.jsx(Za,{className:"h-4 w-4 text-gray-500"}),"Export Blacklist"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(N,{variant:"outline",size:"sm",onClick:()=>q(!0),children:[e.jsx(ns,{className:"h-4 w-4 mr-1"}),"Add Entry"]}),e.jsxs(N,{variant:"outline",size:"sm",onClick:()=>Y(!0),children:[e.jsx($a,{className:"h-4 w-4 mr-1"}),"Import Multiple"]}),He.length>0&&e.jsxs(N,{variant:"outline",size:"sm",onClick:()=>ne(!0),className:"text-red-600 hover:text-red-700",children:[e.jsx(Hs,{className:"h-4 w-4 mr-1"}),"Clear All"]})]})]}),ee?e.jsx(ea,{size:"sm",text:"Loading blacklist...",className:"py-0"}):He.length===0?e.jsx("div",{className:"text-center py-6 text-gray-500 text-sm border border-dashed border-gray-200 rounded-lg",children:"No blacklist entr
131ies. Add entries to exclude them from exports."}):e.jsx("div",{className:"space-y-1 max-h-60 overflow-y-auto",children:He.map(x=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border border-gray-100 rounded hover:bg-gray-50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ie,{variant:"outline",className:`text-xs ${x.entryType==="domain"?"bg-blue-50 text-blue-600 border-blue-200":"bg-orange-50 text-orange-600 border-orange-200"}`,children:x.entryType==="domain"?"Domain":"Yelp Profile"}),e.jsx("span",{className:"text-sm text-gray-700 truncate max-w-xs",children:x.value})]}),e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>es.mutate(x.id),disabled:es.isPending,className:"h-6 w-6 p-0",children:e.jsx(Ut,{className:"h-3.5 w-3.5 text-gray-400 hover:text-red-500"})})]},x.id))}),e.jsxs("div",{className:"mt-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Wi,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"font-medium text-sm text-gray-700",children:"Google Docs Integration"})]}),e.jsx("p",{className:"text-xs text-gray-500 mb-3",children:"Link a Google Doc with a list of entries (one per line) to automatically sync your blackl
131ist."}),O!=null&&O.googleDocUrl?e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm text-blue-600 truncate max-w-sm",children:O.googleDocUrl}),e.jsx(N,{variant:"outline",size:"sm",onClick:()=>ms.mutate(),disabled:ms.isPending,children:ms.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," Refreshing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ks,{className:"h-3.5 w-3.5 mr-1"}),"Refresh"]})}),e.jsxs(N,{variant:"outline",size:"sm",onClick:()=>Ps.mutate(),disabled:Ps.isPending,className:"text-red-600",children:[e.jsx(Hs,{className:"h-3.5 w-3.5 mr-1"}),"Remove"]})]}):e.jsxs(N,{variant:"outline",size:"sm",onClick:()=>V(!0),children:[e.jsx(Wi,{className:"h-3.5 w-3.5 mr-1"}),"Connect Google Doc"]})]})]})]})]}),e.jsxs(Ue,{className:"bg-white border-gray-200",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Qs,{className:"h-5 w-5 text-green-600"}),"Export History",e.jsx(ie,{variant:"secondary",className:"text-xs font-normal","data-testid":"badge-active-database",children:w==="home_improvement"?"Home Improvement/Contractor":F.badgeName}),!Pe&&ve>0&&e.jsxs("span",{className:"text-gray-500 font-normal",children:["(",ve.toLocaleString(),")"]})]})}),e.jsx(_e,{children:Pe?e.jsx(ea,{size:"md",text:"Loading export history..."}):Le.length===0?e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"No exports yet. Your export history will appear here."}):e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("p",{className:"mb-3 text-xs text-gray-500","data-testid":"text-export-retention",children:["Export files can be downloaded for ",Un," days after the export. After that, re-export the leads from Lead Export History below at no credit cost."]}),C&&(()=>{const x=Le.length,M=ve||x,me=!!$e,Ve=Le.map(be=>be.createdAt?new Date(be.createdAt).getTime():null).filter(be=>be!==null),xt=Ve.length?new Date(Math.min(...Ve)):null,Ht=Ve.length?new Date(Math.max(...Ve)):null;return e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900","data-testid":"admin-export-history-banner",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"Admin view:"})," ",me?`Showing first ${x.toLocaleString()} of ${M.toLocaleString()} exports`:`Showing all ${x.toLocaleString()} exports`,xt&&Ht&&e.jsxs(e.Fragment,{children:[" ","from ",Ka(xt,"MMM d, yyyy")," to ",Ka(Ht,"MMM d, yyyy")]})]}),me&&e.jsx(N,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>W(),disabled:tt,"data-testid":"button-load-more-exports",children:tt?"Loading...":"Load 500 more"})]})})(),e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-200 text-left",children:[e.jsx("th",{className:"pb-2 font-medium text-gray-700",children:"File Name"}),e.jsx("th",{className:"pb-2 font-medium text-gray-700",children:"Format"}),e.jsx("th",{className:"pb-2 font-medium text-gray-700",children:"File Type"}),e.jsx("th",{className:"pb-2 font-medium text-gray-700",children:"Lead Count"}),e.jsx("th",{className:"pb-2 font-medium text-gray-700",children:"File Size"}),e.jsx("th",{className:"pb-2 font-medium text-gray-700",children:"Date"}),e.jsx("th",{className:"pb-2 font-medium text-gray-700"})]})}),e.jsx("tbody",{children:Le.map(x=>e.jsxs("tr",{className:"border-b border-gray-100 hover:bg-gray-50",children:[e.jsx("td",{className:"py-2.5 text-gray-800 truncate max-w-[200px]",children:x.fileName}),e.jsx("td",{className:"py-2.5 text-gray-700",children:x.formatName||" - "}),e.jsx("td",{className:"py-2.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(ie,{className:`text-xs ${yl(x.fileType)}`,children:[gl(x.fileType),e.jsx("span",{className:"ml-1",children:x.fileType.toUpperCase()})]}),!x.downloadAvailable&&e.jsx(ie,{variant:"outline",className:"text-xs text-gray-500 border-gray-300","data-testid":`badge-export-unavailable-${x.id}`,children:x.unavailableReason==="expired"?"Expired":"Not available"})]})}),e.jsx("td",{className:"py-2.5 text-gray-700",children:x.leadCount.toLocaleStr
131ing()}),e.jsx("td",{className:"py-2.5 text-gray-700",children:Wp(x.fileSize)}),e.jsxs("td",{className:"py-2.5 text-gray-500",children:[x.createdAt?nn(new Date(x.createdAt),{addSuffix:!0}):" - ",x.downloadAvailable&&x.expiresAt&&e.jsxs("div",{className:"text-xs text-gray-400","data-testid":`text-export-expires-${x.id}`,children:["Available until ",zp(x.expiresAt)]}),!x.downloadAvailable&&e.jsx("div",{className:"text-xs text-gray-400","data-testid":`text-export-unavailable-${x.id}`,children:x.unavailableReason==="expired"?`Expired after ${Un} days. Re-export from Lead Export History (no credit cost).`:"File not available. Re-export from Lead Export History (no credit cost)."})]}),e.jsx("td",{className:"py-2.5",children:e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>Zt(x),disabled:We===x.id||!x.downloadAvailable,title:x.downloadAvailable?"Download":x.unavailableReason==="expired"?`Export files can be downloaded for ${Un} days. Re-export these leads from Lead Export History (no credit cost).`:"This file is not available. Re-export these leads from Lead Export History (no credit cost).","data-testid":`button-download-export-${x.id}`,children:We===x.id?e.jsx(Ks,{className:"h-4 w-4 text-blue-400 animate-spin"}):e.jsx(Qs,{className:`h-4 w-4 ${x.downloadAvailable?"text-blue-600":"text-gray-300"}`})})})]},x.id))})]}),$e&&e.jsx("div",{className:"flex justify-center mt-4",children:e.jsx(N,{variant:"outline",size:"sm",onClick:()=>W(),disabled:tt,children:tt?e.jsxs(e.Fragment,{children:[e.jsx(Ks,{className:"h-3.5 w-3.5 mr-1 animate-spin"}),"Loading..."]}):e.jsx(e.Fragment,{children:"Load more"})})})]})})]}),e.jsxs(Ue,{className:"bg-white border-gray-200",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(qc,{className:"h-5 w-5 text-blue-600"}),"Lead Export History"]})}),e.jsxs(_e,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3 flex-wrap",children:[j,e.jsxs(Jt,{value:at,onValueChange:x=>{Je(x==="all"?"":x),vt(0)},children:[e.jsx(Yt,{className:"w-44",children:e.jsx(Qt,{placeholder:"All methods"})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"all",children:"All Methods"}),e.jsx(Ie,{value:"dashboard",children:"Dashboard"}),e.jsx(Ie,{value:"api",children:"API"}),e.jsx(Ie,{value:"email_schedule",children:"Email Schedule"}),e.jsx(Ie,{value:"crm_push",children:"CRM Push"})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-gray-500",children:"From:"}),e.jsx("input",{type:"date",value:Te,onChange:x=>{Ct(x.target.value),vt(0)},className:"border rounded px-2 py-1 text-xs text-gray-700"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-gray-500",children:"To:"}),e.jsx("input",{type:"date",value:lt,onChange:x=>{kt(x.target.value),vt(0)},className:"border rounded px-2 py-1 text-xs text-gray-700"})]}),(Te||lt)&&e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>{Ct(""),kt(""),vt(0)},className:"text-xs",children:"Clear dates"})]}),De.size>0&&e.jsxs("div",{className:"flex items-center gap-2 mb-3 p-2 bg-blue-50 rounded border border-blue-200 flex-wrap",children:[e.jsxs("span",{className:"text-sm text-blue-700 font-medium",children:[De.size," of ",(et==null?void 0:et.totalCount)||De.size," selected"]}),e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>st(new Set),className:"h-7 text-xs text-blue-600 px-2",children:"Clear"}),e.jsxs(Jt,{value:Ft,onValueChange:oe,children:[e.jsx(Yt,{className:"w-44 h-8 text-xs",children:e.jsx(Qt,{placeholder:"Default format (CSV)"})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"default",children:"Default (CSV)"}),(Me||[]).map(x=>e.jsx(Ie,{value:String(x.id),children:x.name},x.id))]})]}),e.jsx(N,{size:"sm",onClick:()=>ye.mutate(),disabled:ye.isPending||rt.isPending||Tt.isPending,className:"h-8 text-xs",children:ye.isPending?"Exporting...":"Re-export"}),e.jsxs(N,{size:"sm",variant:"outline",onClick:()=>rt.mutate(),disabled:rt.isPending||ye.isPending||Tt.isPending,className:"h-8 text-xs gap-1",children:[e.jsx(Ks,{className:`h-3 w-3 ${rt.isPending?"animate-spin":""}`}),rt.isPending?"Refreshing...":"Refresh Data"]}),e.jsxs(N,{size:"sm",variant:"outline",onClick:()=>Tt.mutate(),disabled:Tt.isPending||ye.isPending||rt.isPending,className:"h-8 text-xs gap-1",children:[e.jsx(Ks,{className:`h-3 w-3 ${Tt.isPending?"animate-spin":""}`}),Tt.isPending?"Working...":"Refresh and Export"]}),e.jsx("span",{className:"text-[10px] text-blue-500",children:"No credits charged"})]}),Ot?e.jsx(ea,{size:"md",text:"Loading lead export history..."}):!et||et.entries.length===0?e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"No lead export history yet. Leads you export will appear here with full contact details."}):e.jsxs(e.Fragment,{children:[(()=>{const x=et.entries,M=x.some(qe=>qe.databaseType==="home_improvement"),me=x.some(qe=>qe.databaseType==="other"),Ve=M&&me,xt=pt(x),Ht=xt.length>0&&xt.every(qe=>De.has(qe)),be=(et.totalCount||0)>ft,ra=Ht&&be&&De.size<(et.totalCount||0),na=Ca.map(qe=>qe.label),pa=ka.map(qe=>qe.label),Va=tl.map(qe=>qe.label),ct=Ve?Va:M?na:pa;return e.jsxs("div",{className:"overflow-x-auto",children:[ra&&e.jsxs("div",{className:"mb-2 p-2 bg-blue-50 border border-blue-200 rounded text-xs text-center text-blue-700",children:["All ",xt.length," items on this page are selected."," ",e.jsx("button",{className:"underline font-medium",onClick:()=>Xt.mutate(),disabled:Xt.isPending,children:Xt.isPending?"Loading...":`Select all ${et.totalCount} results`})]}),e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-200 text-left",children:[e.jsx("th",{className:"pb-2 pr-2 w-8",children:e.jsx(Ws,{checked:Ht,onCheckedChange:jt})}),e.jsx("th",{className:"pb-2 font-medium text-gray-700 whitespace-nowrap",children:"Export Time"}),e.jsx("th",{className:"pb-2 font-medium text-gray-700 whitespace-nowrap",children:"Export Method"}),Ve&&j,Ve&&!j&&e.jsx("th",{className:"pb-2 font-medium text-gray-700",children:"Source"}),ct.map(qe=>e.jsx("th",{className:"pb-2 font-medium text-gray-700 whitespace-nowrap",children:qe},qe))]})}),e.jsx("tbody",{children:x.map(qe=>
131{const ht=qe.lead,Os=qe.databaseType==="home_improvement",ws=Array.isArray(qe.lastChangedFields)?qe.lastChangedFields:[],m=new Set(ws),D=new Set(ws.map(we=>Bp[we]).filter(Boolean)),H=ws.length>0,Z=(we,Be)=>(Be?D.has(we):m.has(we))?"bg-amber-50 border-l-2 border-amber-400":"";return e.jsxs("tr",{className:`border-b border-gray-100 hover:bg-gray-50 ${H?"bg-amber-50/30":""}`,children:[e.jsx("td",{className:"py-2 pr-2",children:e.jsx(Ws,{checked:De.has(qe.id),onCheckedChange:()=>Ye(qe.id)})}),e.jsx("td",{className:"py-2 text-gray-700 text-xs whitespace-nowrap",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[qe.exportedAt?Ka(new Date(qe.exportedAt),"MMM d, yyyy HH:mm"):" - ",H&&e.jsxs("button",{type:"button",title:`Updated fields since last export: ${ws.join(", ")}. Click to dismiss.`,onClick:()=>fs.mutate([qe.id]),disabled:fs.isPending,className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium bg-amber-100 text-amber-800 hover:bg-amber-200 disabled:opacity-50","data-testid":`button-acknowledge-changes-${qe.id}`,children:[e.jsx(Kt,{className:"h-2.5 w-2.5"}),ws.length," new",e.jsx(Ut,{className:"h-2.5 w-2.5 ml-0.5"})]})]})}),e.jsx("td",{className:"py-2",children:e.jsx(ie,{variant:"outline",className:"text-[10px]",children:qe.exportMethod==="email_schedule"?"Email":qe.exportMethod==="api"?"API":qe.exportMethod==="dashboard"?"Dashboard":qe.exportMethod==="crm_push"?"CRM Push":" - "})}),Ve&&j,Ve&&!j&&e.jsx("td",{className:"py-2",children:e.jsx(ie,{className:`text-[10px] ${Os?"bg-gray-100 text-gray-600":"bg-blue-100 text-blue-700"}`,title:Os?"From an earlier lead source that is no longer offered. Re-export these separately from your other leads.":void 0,children:Os?"Legacy":F.abbrev})}),!Ve&&M&&(ht?Ca.map(we=>e.jsx("td",{className:`py-2 text-xs text-gray-700 max-w-[180px] truncate ${Z(we.key,!1)}`,children:bl(ht,we.key)},we.key)):e.jsx("td",{colSpan:Ca.length,className:"py-2 text-xs text-gray-400 italic",children:"Lead data unavailable"})),!Ve&&me&&(ht?ka.map(we=>e.jsx("td",{className:`py-2 text-xs text-gray-700 max-w-[180px] truncate ${Z(we.key,!1)}`,children:wl(ht,we.key)},we.key)):e.jsx("td",{colSpan:ka.length,className:"py-2 text-xs text-gray-400 italic",children:"Lead data unavailable"})),Ve&&e.jsxs(e.Fragment,{children:[e.jsx("td",{className:`py-2 text-xs text-gray-800 max-w-[150px] truncate ${Z("company",!0)}`,children:ht?(Os?ht.ylprProfileName:ht.wCompanyName)||" - ":"(deleted)"}),e.jsx("td",{className:`py-2 text-xs text-gray-700 ${Z("phone",!0)}`,children:ht&&(Os?ht.ylprPhone:ht.wPhonePrimary)||" - "}),e.jsx("td",{className:`py-2 text-xs text-gray-700 ${Z("email",!0)}`,children:ht&&!Os&&ht.wEmailPrimary||" - "}),e.jsx("td",{className:`py-2 text-xs text-gray-700 ${Z("city",!0)}`,children:ht&&(Os?ht.ylprAddressCity:ht.wAddressCity)||" - "}),e.jsx("td",{className:`py-2 text-xs text-gray-700 ${Z("state",!0)}`,children:ht&&(Os?ht.ylprAddressState:ht.wAddressState)||" - "})]})]},qe.id)})})]})]})})(),e.jsxs("div",{className:"flex items-center justify-between mt-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-xs text-gray-500",children:[et.totalCount.toLocaleString()," total entries"]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-gray-400",children:"Per page:"}),e.jsxs(Jt,{value:String(ft),onValueChange:x=>{const M=parseInt(x);qt(M),vt(0),localStorage.setItem("leadHistoryPageSize",String(M))},children:[e.jsx(Yt,{className:"h-7 w-20 text-xs",children:e.jsx(Qt,{})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"25",children:"25"}),e.jsx(Ie,{value:"50",children:"50"}),e.jsx(Ie,{value:"100",children:"100"}),e.jsx(Ie,{value:"200",children:"200"}),e.jsx(Ie,{value:"500",children:"500"}),e.jsx(Ie,{value:"1000",children:"1000"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(N,{variant:"ghost",size:"sm",disabled:Oe===0,onClick:()=>vt(x=>x-1),children:e.jsx(ci,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-gray-600",children:["Page ",Oe+1," of ",Math.max(1,Math.ceil((et.totalCount||0)/ft))]}),e.jsx(N,{variant:"ghost",size:"sm",disabled:(Oe+1)*ft>=(et.totalCount||0),onClick:()=>vt(x=>x+1),children:e.jsx(ti,{className:"h-4 w-4"})})]})]})]})]})]}),e.jsxs(Ue,{className:"bg-white border-gray-200",children:[e.jsx(zt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Vt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Vl,{className:"h-5 w-5 text-amber-600"}),"Lead Reservoir"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ut.size>0&&e.jsx(N,{variant:"default",size:"sm",onClick:()=>le.mutate(Array.from(ut)),disabled:le.isPending,className:"bg-amber-600 hover:bg-amber-700 text-white",children:le.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:14})," Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Qs,{className:"h-3.5 w-3.5 mr-1"}
131)," Export ",ut.size.toLocaleString()," Selected"]})}),Xe&&Xe.totalCount>0&&e.jsx(N,{variant:"outline",size:"sm",onClick:()=>P.mutate(),disabled:P.isPending,className:"text-red-600 border-red-200 hover:bg-red-50",children:P.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:14})," Clearing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Hs,{className:"h-3.5 w-3.5 mr-1"})," Clear All"]})})]})]})}),e.jsx(_e,{children:mt?e.jsx(ea,{size:"md",text:"Loading reservoir..."}):!Xe||Xe.entries.length===0?e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"No leads in reservoir. When your email schedule has a max leads limit, overflow leads are stored here for the next run."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mb-3 flex items-center justify-between",children:e.jsxs("p",{className:"text-sm text-gray-600",children:[e.jsx("span",{className:"font-medium text-amber-700",children:Xe.totalCount.toLocaleString()})," leads waiting in reservoir. These will be merged with fresh leads on the next email schedule run or API export and prioritized by ",ca,". Reservoir capacity is capped at your plan's credit limit."]})}),_t>0&>.length>0&&e.jsxs("div",{className:"mb-3 flex items-center gap-3 text-xs text-gray-500",children:[e.jsxs("span",{children:[ut.size>0?`${ut.size.toLocaleString()} selected`:"None selected",!St&&ze!==1/0&&e.jsxs(e.Fragment,{children:[" - ",ze.toLocaleString()," credit",ze!==1?"s":""," remaining"]})]}),It&&e.jsx("span",{className:"text-amber-600",children:"Some older reservoir leads can't be selected for export"})]}),(()=>{const x=Xe.entries,M=x.some(ct=>ct.databaseType==="home_improvement"),me=x.some(ct=>ct.databaseType==="other"),Ve=M&&me,xt=Ca.map(ct=>ct.label),Ht=ka.map(ct=>ct.label),be=tl.map(ct=>ct.label),ra=Ve?be:M?xt:Ht,na=ct=>ct?ct.length<=4?"****":ct.substring(0,2)+"****"+ct.substring(ct.length-2):" - ",pa=x.filter(ct=>ct.databaseType===de),Va=pa.length>0&&pa.every(ct=>ut.has(ct.leadId));return e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-200 text-left",children:[e.jsx("th",{className:"pb-2 w-8",children:e.jsx("input",{type:"checkbox",checked:Va&&ut.size>0,onChange:Ce,className:"rounded border-gray-300"})}),Ve&&j,ra.map(ct=>e.jsx("th",{className:"pb-2 font-medium text-gray-700 whitespace-nowrap",children:ct},ct)),e.jsx("th",{className:"pb-2 font-medium text-gray-700",children:"Source"}),e.jsx("th",{className:"pb-2 font-medium text-gray-700",children:"Added"})]})}),e.jsx("tbody",{children:x.map(ct=>{const qe=ct.lead,ht=ct.databaseType==="home_improvement",Os=ct.databaseType===de,ws=ut.has(ct.leadId);return e.jsxs("tr",{className:`border-b border-gray-100 hover:bg-gray-50 ${ws?"bg-amber-50":""}`,children:[e.jsx("td",{className:"py-2",children:Os?e.jsx("input",{type:"checkbox",checked:ws,onChange:()=>Ge(ct.leadId),disabled:!ws&&!St&&ut.size>=_t,className:"rounded border-gray-300"}):e.jsx("span",{className:"text-gray-300",children:" - "})}),Ve&&j,!Ve&&M&&(qe?Ca.map(m=>e.jsx("td",{className:"py-2 text-xs text-gray-700 max-w-[180px] truncate",children:bl(qe,m.key,{maskFn:na})},m.key)):e.jsx("td",{colSpan:Ca.length,className:"py-2 text-xs text-gray-400 italic",children:"Lead data unavailable"})),!Ve&&me&&(qe?ka.map(m=>e.jsx("td",{className:"py-2 text-xs text-gray-700 max-w-[180px] truncate",children:wl(qe,m.key,{maskFn:na})},m.key)):e.jsx("td",{colSpan:ka.length,className:"py-2 text-xs text-gray-400 italic",children:"Lead data unavailable"})),Ve&&e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"py-2 text-xs text-gray-800 max-w-[150px] truncate",children:qe?(ht?qe.ylprProfileName:qe.wCompanyName)||" - ":`#${ct.leadId}`}),e.jsx("td",{className:"py-2 text-xs text-gray-700",children:qe?na(ht?qe.ylprPhone:qe.wPhonePrimary):" - "}),e.jsx("td",{className:"py-2 text-xs text-gray-700",children:qe&&!ht?na(qe.wEmailPrimary):" - "}),e.jsx("td",{className:"py-2 text-xs text-gray-700",children:qe&&(ht?qe.ylprAddressCity:qe.wAddressCity)||" - "}),e.jsx("td",{className:"py-2 text-xs text-gray-700",children:qe&&(ht?qe.ylprAddressState:qe.wAddressState)||" - "})]}),e.jsx("td",{className:"py-2 text-gray-500 text-xs max-w-[120px] truncate",children:ct.scheduleName||(ct.scheduleId?`Schedule #${ct.scheduleId}`:"API export")}),e.jsx("td",{className:"py-2 text-gray-500 text-xs whitespace-nowrap",children:ct.addedAt?nn(new Date(ct.addedAt),{addSuffix:!0}):" - "})]},ct.id)})})]})})})(),Xe.totalCount>100&&e.jsxs("p",{className:"text-xs text-gray-400 mt-2",children:["Showing first 100 of ",Xe.totalCount.toLocaleStr
131ing()," reservoir entries."]})]})})]}),e.jsx(os,{open:T,onOpenChange:x=>{J(x),x||Bt()},children:e.jsxs(cs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(as,{children:[e.jsx(rs,{children:p?"Edit Export Format":"Create Export Format"}),e.jsx($s,{children:"Configure how your export files are structured."})]}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(xe,{children:"Name"}),e.jsx(Ee,{value:y.name,onChange:x=>k(M=>({...M,name:x.target.value})),placeholder:"My Export Format"})]}),e.jsxs("div",{children:[e.jsx(xe,{children:"File Type"}),e.jsxs(Jt,{value:y.fileType,onValueChange:x=>k(M=>({...M,fileType:x})),children:[e.jsx(Yt,{children:e.jsx(Qt,{})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"csv",children:"CSV"}),e.jsx(Ie,{value:"json",children:"JSON"}),e.jsx(Ie,{value:"xlsx",children:"XLSX"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(xe,{children:"Start Row"}),e.jsx(Ee,{type:"number",min:1,max:100,value:y.startRow,onChange:x=>k(M=>({...M,startRow:Math.max(1,Math.min(100,parseInt(x.target.value)||1))}))})]}),y.fileType!=="json"&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xs,{checked:y.includeHeaders,onCheckedChange:x=>k(M=>({...M,includeHeaders:x}))}),e.jsx("span",{className:"text-sm text-gray-700",children:"Include column headers"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(xe,{className:"text-sm font-medium",children:"Field Mappings"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(N,{variant:"outline",size:"sm",onClick:Ms,children:[e.jsx(ns,{className:"h-3.5 w-3.5 mr-1"}),"Add Field"]}),e.jsxs(N,{variant:"outline",size:"sm",onClick:n,children:[e.jsx($d,{className:"h-3.5 w-3.5 mr-1"}),"Add Spacer"]})]})]}),y.fieldMappings.length===0?e.jsx("div",{className:"text-center py-4 text-gray-400 text-sm border border-dashed border-gray-200 rounded",children:"No field mappings. Add fields to define your export columns."}):e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:y.fieldMappings.map((x,M)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-gray-50 rounded border border-gray-200",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx(N,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0",onClick:()=>L(M,"up"),disabled:M===0,children:e.jsx(si,{className:"h-3 w-3"})}),e.jsx(N,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0",onClick:()=>L(M,"down"),disabled:M===y.fieldMappings.length-1,children:e.jsx(ai,{className:"h-3 w-3"})})]}),x.type==="spacer"?e.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[e.jsx(ie,{variant:"outline",className:"text-xs bg-gray-100",children:"Spacer"}),e.jsx("span",{className:"text-xs text-gray-400",children:"Empty column in export"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex-1",children:e.jsxs(Jt,{value:x.sourceField,onValueChange:me=>b(M,{sourceField:me,exportName:gr(me,w)}),children:[e.jsx(Yt,{className:"h-8 text-xs",children:e.jsx(Qt,{placeholder:"Source field"})}),e.jsx(Gt,{children:E.map(me=>e.jsx(Ie,{value:me,children:gr(me,w)},me))})]})}),e.jsx("div",{className:"flex-1",children:e.jsx(Ee,{className:"h-8 text-xs",value:x.exportName,onChange:me=>b(M,{exportName:me.target.value}),placeholder:"Export column name"})})]}),e.jsx(N,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>h(M),children:e.jsx(Ut,{className:"h-3.5 w-3.5 text-red-400"})})]},M))})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-4",children:[e.jsx(xe,{className:"text-sm font-medium",children:"File Splitting"}),e.jsxs("div",{className:"mt-2 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xs,{checked:y.splitFiles,onCheckedChange:x=>k(M=>({...M,splitFiles:x,splitMode:x&&M.splitMode||"max_rows",maxRowsPerFile:x&&(M.splitMode==="max_rows"||M.splitMode==="parts_max_rows")?M.maxRowsPerFile||1e3:M.maxRowsPerFile,numberOfParts:x&&(M.splitMode==="equal_parts"||M.splitMode==="parts_max_rows")?M.numberOfParts||2:M.numberOfParts}))}),e.jsx("span",{className:"text-sm text-gray-700",children:"Split files"})]}),y.splitFiles&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(xe,{className:"text-xs",children:"Split mode"}),e.jsxs(Jt,{value:y.splitMode,onValueChange:x=>k(M=>({...M,splitMode:x,maxRowsPerFile:x==="max_rows"||x==="parts_max_rows"?M.maxRowsPerFile||1e3:M.maxRowsPerFile,numberOfParts:x==="equal_parts"||x==="parts_max_rows"?M.numberOfParts||2:M.numberOfParts})),children:[e.jsx(Yt,{className:"mt-1",children:e.jsx(Qt,{})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"max_rows",children:"Max rows per file"}),e.jsx(Ie,{value:"equal_parts",children:"Split into equal parts"}),e.jsx(Ie,{value:"parts_max_rows",children:"Number of parts with max rows"})]})]})]}),(y.splitMode==="max_rows"||y.splitMode==="parts_max_rows")&&e.jsxs("div",{children:[e.jsx(xe,{className:"text-xs",children:"Max rows per file"}),e.jsx(Ee,{type:"number",min:10,max:1e5,value:y.maxRowsPerFile??1e3,onChange:x=>k(M=>({...M,maxRowsPerFile:Math.max(10,parseInt(x.target.value)||10)})),className:"mt-1"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Minimum: 10 rows"})]}),(y.splitMode==="equal_parts"||y.splitMode==="parts_max_rows")&&e.jsxs("div",{children:[e.jsx(xe,{className:"text-xs",children:"Number of parts"}),e.jsx(Ee,{type:"number",min:2,max:100,value:y.numberOfParts??2,onCh
131ange:x=>k(M=>({...M,numberOfParts:Math.max(2,parseInt(x.target.value)||2)})),className:"mt-1"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xs,{checked:y.includeTotal,onCheckedChange:x=>k(M=>({...M,includeTotal:x}))}),e.jsx("span",{className:"text-sm text-gray-700",children:"Include total file"})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t border-gray-200",children:[e.jsx("p",{className:"text-xs font-medium text-gray-700",children:"Combined File Column Names"}),e.jsx("p",{className:"text-xs text-gray-400",children:"Default column names for when a combined file is generated in email schedules."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(xe,{className:"text-xs",children:"Assignee Column"}),e.jsx(Ee,{value:y.combinedAssigneeColumnName,onChange:x=>k(M=>({...M,combinedAssigneeColumnName:x.target.value})),placeholder:"Assigned To",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-xs",children:"File Name Column"}),e.jsx(Ee,{value:y.combinedFileNameColumnName,onChange:x=>k(M=>({...M,combinedFileNameColumnName:x.target.value})),placeholder:"File Part",className:"mt-1"})]})]})]})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(N,{variant:"outline",onClick:()=>{J(!1),Bt()},children:"Cancel"}),e.jsx(N,{onClick:_,disabled:nt,children:nt?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," Saving..."]}):p?"Update":"Save"})]})]})]})}),e.jsx(os,{open:a,onOpenChange:q,children:e.jsxs(cs,{children:[e.jsxs(as,{children:[e.jsx(rs,{children:"Add Blacklist Entry"}),e.jsx($s,{children:"Add a single entry to your export blacklist."})]}),e.jsxs("div",{className:"space-y-4 mt-2",children:[j,e.jsxs("div",{children:[e.jsx(xe,{children:"Domain"}),e.jsx(Ee,{value:B,onChange:x=>K(x.target.value),placeholder:$==="domain"?"example.com":"yelp-profile-url"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(N,{variant:"outline",onClick:()=>q(!1),children:"Cancel"}),e.jsx(N,{onClick:()=>Nt.mutate({entryType:$,value:B}),disabled:!B.trim()||Nt.isPending,children:Nt.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," Adding..."]}):"Add Entry"})]})]})]})}),e.jsx(os,{open:ae,onOpenChange:Y,children:e.jsxs(cs,{children:[e.jsxs(as,{children:[e.jsx(rs,{children:"Import Multiple Entries"}),e.jsxs($s,{children:['Enter one entry per line. All entries will be added as "',A==="domain"?"Domain":"Yelp Profile",'" type.']})]}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsx(Ma,{value:fe,onChange:x=>U(x.target.value),placeholder:`Enter entries, one per line... 132${A==="domain"?`example.com 133another.com`:`yelp-url-1 134yelp-url-2`}`,rows:8}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(N,{variant:"outline",onClick:()=>Y(!1),children:"Cancel"}),e.jsx(N,{onClick:G,disabled:!fe.trim()||ls.isPending,children:ls.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," Importing..."]}):"Import"})]})]})]})}),e.jsx(os,{open:te,onOpenChange:ne,children:e.jsxs(cs,{children:[e.jsxs(as,{children:[e.jsxs(rs,{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"h-5 w-5 text-red-500"}),"Clear All Blacklist Entries"]}),e.jsxs($s,{children:["This will remove all ",He.length," blacklist entries. This action cannot be undone."]})]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(N,{variant:"outline",onClick:()=>ne(!1),children:"Cancel"}),e.jsx(N,{variant:"destructive",onClick:()=>Rs.mutate(),disabled:Rs.isPending,children:Rs.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," Clearing..."]}):"Clear All"})]})]})}),e.jsx(os,{open:Q,onOpenChange:V,children:e.jsxs(cs,{children:[e.jsxs(as,{children:[e.jsx(rs,{children:"Connect Google Doc"}),e.jsx($s,{children:"Enter the URL of a Google Doc containing blacklist entries (one per line)."})]}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{children:[e.jsx(xe,{children:"Google Doc URL"}),e.jsx(Ee,{value:R,onChange:x=>pe(x.target.value),placeholder:"https://docs.google.com/document/d/..."})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(N,{variant:"outline",onClick:()=>V(!1),children:"Cancel"}),e.jsx(N,{onClick:()=>bs.mutate(R),disabled:!R.trim()||bs.isPending,children:bs.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," Connecting..."]}):"Connect"})]})]})]})})]})}function ac(t){return(t==null?void 0:t.splitFiles)!==!0?0:(t.splitMode==="equal_parts"||t.splitMode==="parts_max_rows")&&t.numberOfParts&&t.numberOfParts>=2?t.numberOfParts:2}function jl({recipients:t,onChange:r,exportFormat:s}){const[i,l]=o.useState(""),c=(s==null?void 0:s.splitFiles)===!0,d=ac(s)||1;function u(){const C=i.trim().toLowerCase();!C||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(C)||t.some(w=>w.email===C)||t.length>=50||(r([...t,{email:C,splitParts:[]}]),l(""))}function g(C){r(t.filter(F=>F.email!==C))}function f(C,F){r(t.map(w=>{if(w.email!==C)return w;const j=w.splitParts||[],E=j.includes(F);return{...w,splitParts:E?j.filter(A=>A!==F):[...j,F].sort((A,T)=>A-T)}}))}return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ee,{type:"email",placeholder:"Add recipient email",value:i,onChange:C=>l(C.target.value),onKeyDown:C=>{C.key==="Enter"&&(C.preventDefault(),u())},className:"flex-1"}),e.jsx(N,{type:"button",size:"sm",variant:"outline",onClick:u,disabled:t.length>=50,children:e.jsx(ns,{className:"h-3.5 w-3.5"})})]}),t.length>0&&e.jsx("div",{className:"space-y-1.5 max-h-40 overflow-y-auto",children:t.map(C=>e.jsxs("div",{className:"flex items-center gap-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded px-2.5 py-1.5 text-sm",children:[e.jsx(_a,{className:"h-3.5 w-3.5 text-gray-400 flex-shrink-0"}),e.jsx("span",{className:"flex-1 truncate text-gray-700 dark:text-gray-300",children:C.email}),c&&d>1&&e.jsx("div",{className:"flex gap-1 flex-shrink-0",children:Array.from({length:d},(F,w)=>w+1).map(F=>e.jsx("button",{type:"button",onClick:()=>f(C.email,F),className:`w-5 h-5 rounded text-[10px] font-medium border transition-colors ${(C.splitParts||[]).includes(F)?"bg-blue-500 text-white border-blue-500":"bg-gray-100 dark:bg-gray-700 text-gray-500 border-gray-300 dark:border-gray-600"}`,title:`Part ${F}${(C.splitParts||[]).includes(F)?" (assigned)":""}`,children:F},F))}),e.jsx("button",{type:"button",onClick:()=>g(C.email),className:"text-red-400 hover:text-red-600 flex-shrink-0",children:e.jsx(Ut,{className:"h-3.5 w-3.5"})})]},C.email))}),e.jsxs("p",{className:"text-xs text-gray-400",children:[t.length,"/50 recipients."," ",c&&d>1?"Click numbered buttons to assign specific file parts. No selection = all parts.":"All recipients receive the full export."]}
134)]})}function Yp({schedule:t,onSave:r,onCancel:s,isPending:i}){const[l,c]=o.useState(t.combinedFileEnabled??!1),[d,u]=o.useState(Array.isArray(t.combinedRecipients)?t.combinedRecipients:[]),[g,f]=o.useState(t.combinedIncludeAssignee??!0),[C,F]=o.useState(t.combinedIncludeFileName??!0),[w,j]=o.useState(t.combinedColumnPosition||"end"),[E,A]=o.useState(t.combinedAssigneeColumnName||"Assigned To"),[T,J]=o.useState(t.combinedFileNameColumnName||"File Part");function p(){r({combinedFileEnabled:l,combinedRecipients:d,combinedIncludeAssignee:g,combinedIncludeFileName:C,combinedColumnPosition:w,combinedAssigneeColumnName:E.trim()||"Assigned To",combinedFileNameColumnName:T.trim()||"File Part"})}return e.jsxs("div",{className:"border-t border-blue-200 px-4 py-3 bg-blue-50/50 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xs,{checked:l,onCheckedChange:c}),e.jsxs(xe,{className:"flex items-center gap-1.5 text-sm font-medium",children:[e.jsx(qn,{className:"h-3.5 w-3.5"}),"Send combined file"]})]}),e.jsx("p",{className:"text-xs text-gray-400",children:"Merge all split parts into one file with attribution columns and send to separate recipients."}),l&&e.jsxs("div",{className:"space-y-3 pl-4 border-l-2 border-blue-200",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{className:"text-xs",children:"Combined File Recipients"}),e.jsx(Bn,{emails:d,onChange:u,max:50})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xs,{checked:g,onCheckedChange:f}),e.jsx("span",{className:"text-xs text-gray-700",children:"Assignee column"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xs,{checked:C,onCheckedChange:F}),e.jsx("span",{className:"text-xs text-gray-700",children:"File name column"})]})]}),(g||C)&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx(xe,{className:"text-xs",children:"Column position"}),e.jsxs(Jt,{value:w,onValueChange:j,children:[e.jsx(Yt,{className:"mt-1",children:e.jsx(Qt,{})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"beginning",children:"Beginning of row"}),e.jsx(Ie,{value:"end",children:"End of row"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[g&&e.jsxs("div",{children:[e.jsx(xe,{className:"text-xs",children:"Assignee column name"}),e.jsx(Ee,{value:E,onChange:v=>A(v.target.value),className:"mt-1",placeholder:"Assigned To"})]}),C&&e.jsxs("div",{children:[e.jsx(xe,{className:"text-xs",children:"File name column name"}),e.jsx(Ee,{value:T,onChange:v=>J(v.target.value),className:"mt-1",placeholder:"File Part"})]})]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(N,{size:"sm",onClick:p,disabled:i,children:i?"Saving...":"Save Combined Settings"}),e.jsx(N,{size:"sm",variant:"ghost",onClick:s,children:"Cancel"})]})]})}function Bn({emails:t,onChange:r,max:s=50}){const[i,l]=o.useState("");function c(){const d=i.trim().toLowerCase();!d||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d)||t.includes(d)||t.length>=s||(r([...t,d]),l(""))}return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ee,{type:"email",placeholder:"Add email",value:i,onChange:d=>l(d.target.value),onKeyDown:d=>{d.key==="Enter"&&(d.preventDefault(),c())},className:"flex-1"}),e.jsx(N,{type:"button",size:"sm",variant:"outline",onClick:c,disabled:t.length>=s,children:e.jsx(ns,{className:"h-3.5 w-3.5"})})]}),t.length>0&&e.jsx("div",{className:"space-y-1 max-h-28 overflow-y-auto",children:t.map(d=>e.jsxs("div",{className:"flex items-center gap-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded px-2.5 py-1 text-sm",children:[e.jsx(_a,{className:"h-3 w-3 text-gray-400 flex-shrink-0"}),e.jsx("span",{className:"flex-1 truncate text-gray-700 dark:text-gray-300",children:d}),e.jsx("button",{type:"button",onClick:()=>r(t.filter(u=>u!==d)),className:"text-red-400 hover:text-red-600 flex-shrink-0",children:e.jsx(Ut,{className:"h-3 w-3"})})]},d))}),e.jsxs("p",{className:"text-xs text-gray-400",children:[t.length,"/",s," recipients"]})]})}function Qp({userId:t,userEmail:r,isSubscribed:s,smbType:i,onDatabaseSwitch:l}){const{toast:c}=Ss(),d=ja(),u=vr(),g=ar(),[f,C]=o.useState(!1),[F,w]=o.useState(""),[j,E]=o.useState(""),[A,T]=o.useState(""),[J,p]=o.use
134State("24"),[v,y]=o.useState("hours"),[k,a]=o.useState([]),[q,$]=o.useState("full_copy"),[X,B]=o.useState([]),[K,ae]=o.useState(!1),[Y,fe]=o.useState([]),[U,te]=o.useState(!0),[ne,Q]=o.useState(!0),[V,R]=o.useState("end"),[pe,Se]=o.useState("Assigned To"),[Ze,Me]=o.useState("File Part"),[He,ee]=o.useState(""),[O,I]=o.useState(null),[re,Pe]=o.useState({}),[tt,$e]=o.useState(null),[W,Le]=o.useState(null),[ve,Oe]=o.useState(""),{data:vt=[],isLoading:Rt}=Qe({queryKey:["/api/email-schedules"],enabled:s,refetchInterval:P=>{const le=P.state.data;return(le==null?void 0:le.some(st=>st.isActive||st.pauseReason==="insufficient_credits"))?6e4:!1}}),At=o.useRef(null);o.useEffect(()=>{const P=vt.reduce((le,De)=>le+(De.totalSentCount||0),0);At.current!==null&&P>At.current&&(z.invalidateQueries({queryKey:["/api/auth/user"]}),z.invalidateQueries({queryKey:["/api/me/temporary-credits"]})),At.current=P},[vt]);const{data:at=[]}=Qe({queryKey:["/api/filter-presets"],enabled:s}),Je=at.filter(P=>P.databaseType===u),{data:Te=[]}=Qe({queryKey:["/api/export-formats"],enabled:s}),Ct=Te.filter(P=>P.databaseType===u);o.useEffect(()=>{if(f&&!A){const P=Ct.find(le=>le.isDefault);P&&T(String(P.id))}},[Ct,f]),o.useEffect(()=>{f&&r&&k.length===0&&a([{email:r.toLowerCase(),splitParts:[]}])},[f,r]);const lt=Ne({mutationFn:async P=>(await ue("POST","/api/email-schedules",P)).json(),onSuccess:()=>{z.invalidateQueries({queryKey:["/api/email-schedules"]}),C(!1),Xe(),c({title:"Schedule Created",description:"Your email schedule has been created."})},onError:P=>{ce("EmailSchedulesTab","Failed to create schedule",P),c({title:"Error",description:P.message||"Failed to create schedule",variant:"destructive"})}}),kt=o.useCallback((P,le)=>{if(le&&!s){c({title:"Subscription required",description:"You need an active subscription to resume email schedules.",variant:"destructive"});return}const De=z.getQueryData(["/api/email-schedules"]),st=De==null?void 0:De.find(Ye=>Ye.id===P),Ft=(st==null?void 0:st.isActive)??!1,oe=(st==null?void 0:st.pauseReason)??null;z.cancelQueries({queryKey:["/api/email-schedules"]}),z.setQueryData(["/api/email-schedules"],Ye=>Ye==null?void 0:Ye.map(pt=>pt.id===P?{...pt,isActive:le,pauseReason:le?null:"user"}:pt)),ue("PATCH",`/api/email-schedules/${P}`,{isActive:le}).then(async Ye=>{const pt=await Ye.json(),jt=pt.schedule||pt;jt.pauseReason==="insufficient_credits"?(z.setQueryData(["/api/email-schedules"],ye=>ye==null?void 0:ye.map(Xt=>Xt.id===P?{...Xt,...jt}:Xt)),c({title:"Schedule will auto-resume",description:"This schedule will automatically resume when credits are replenished."})):(z.invalidateQueries({queryKey:["/api/email-schedules"]}),c({title:le?"Schedule resumed":"Schedule paused",description:le?"This schedule will send emails on its next interval.":"This schedule will not send emails until resumed."}))}).catch(Ye=>{z.setQueryData(["/api/email-schedules"],jt=>jt==null?void 0:jt.map(ye=>ye.id===P?{...ye,isActive:Ft,pauseReason:oe}:ye));let pt="Failed to toggle schedule";try{const jt=(Ye==null?void 0:Ye.message)||"",ye=jt.indexOf("{");ye!==-1&&(pt=JSON.parse(jt.substring(ye)).message||pt)}catch{}c({title:"Error",description:pt,variant:"destructive"})})},[c,s]),ft=Ne({mutationFn:async P=>{await ue("DELETE",`/api/email-schedules/${P}`)},onSuccess:()=>{z.invalidateQueries({queryKey:["/api/email-schedules"]}),c({title:"Schedule Deleted"})}}),qt=Ne({mutationFn:async({id:P,recipients:le})=>(await ue("PATCH",`/api/email-schedules/${P}`,{recipients:le})).json(),onSuccess:(P,le)=>{z.invalidateQueries({queryKey:["/api/email-schedules"]}),I(null),Pe(De=>{const st={...De};return delete st[le.id],st}),c({title:"Recipients Updated"})},onError:P=>{c({title:"Error",description:P.message||"Failed to update recipients",variant:"destructive"})}}),et=Ne({mutationFn:async({id:P,data:le})=>(await ue("PATCH",`/api/email-schedules/${P}`,le)).json(),onSuccess:(P,le)=>{z.invalidateQueries({queryKey:["/api/email-schedules"]}),$e(null),c({title:"Combined File Settings Updated"})},onError:P=>{c({title:"Error",description:P.message||"Failed to update combined file settings",variant:"destructive"})}}),Ot=Ne({mutationFn:async({id:P,maxLeadsPerEmail:le})=>(await ue("PATCH",`/api/email-schedules/${P}`,{maxLeadsPerEmail:le})).json(),onSuccess:()=>{z.invalidateQueries({queryKey:["/api/email-schedules"]}),Le(null),c({title:"Max leads per email updated"})},onError:P=>{c({title:"Error",description:P.message||"Failed to update max leads",variant:"destructive"})}});function Xe(){w(""),E("");const P=Ct.find(le=>le.isDefault);T(P?String(P.id):""),p("24"),y("hours"),a(r?[{email:r.toLowerCase(),splitParts:[]}]:[]),$("full_copy"),B([]),ae(!1),fe([]),te(!0),Q(!0),R("end"),Se("Assigned To"),Me("File Part"),ee("")}function mt(){const P=parseInt(J,10);if(!F.trim()){ce("EmailSchedulesTab","Validation: name required"),
134c({title:"Name required",variant:"destructive"});return}if(!j){ce("EmailSchedulesTab","Validation: filter preset not selected"),c({title:"Select a filter preset",variant:"destructive"});return}if(isNaN(P)||P<1){ce("EmailSchedulesTab","Validation: invalid interval"),c({title:"Invalid interval",variant:"destructive"});return}if(k.length===0){ce("EmailSchedulesTab","Validation: at least 1 recipient required"),c({title:"At least one recipient is required",variant:"destructive"});return}const le=He.trim()?parseInt(He,10):null;if(le!==null&&(isNaN(le)||le<1)){c({title:"Max leads per email must be at least 1",variant:"destructive"});return}lt.mutate({name:F.trim(),filterPresetId:parseInt(j,10),exportFormatId:A&&A!=="default"?parseInt(A,10):null,intervalValue:P,intervalUnit:v,recipients:k,distributionMode:q,fullCopyRecipients:q==="split_evenly"?X:[],combinedFileEnabled:K,combinedRecipients:Y,combinedIncludeAssignee:U,combinedIncludeFileName:ne,combinedColumnPosition:V,combinedAssigneeColumnName:pe,combinedFileNameColumnName:Ze,maxLeadsPerEmail:le})}function ut(P,le){return le==="days"?P===1?"Every day":`Every ${P} days`:P===1?"Every hour":`Every ${P} hours`}function ot(P){const le=at.find(De=>De.id===P);return(le==null?void 0:le.name)||`Preset #${P}`}function St(P){return!1}function Pt(P){if(!P)return"Default";const le=Te.find(De=>De.id===P);return(le==null?void 0:le.name)||"Custom"}function it(P){return P.exportFormatId?Te.find(le=>le.id===P.exportFormatId)||null:Ct.find(le=>le.isDefault)||null}function ze(P){const le=P.recipients;return Array.isArray(le)?le.length:0}function _t(P){if(O===P)I(null),Pe(le=>{const De={...le};return delete De[P],De});else{const le=vt.find(st=>st.id===P),De=Array.isArray(le==null?void 0:le.recipients)?le.recipients:[];Pe(st=>({...st,[P]:[...De]})),I(P)}}function de(){return!A||A==="default"?null:Ct.find(P=>P.id===parseInt(A,10))||null}function gt(P){return(P==null?void 0:P.splitFiles)===!0}function It(P){const le=it(P);return ac(le)}if(!s)return e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"blur-[3px] pointer-events-none select-none","aria-hidden":"true",children:e.jsx("div",{className:"space-y-6",children:e.jsxs(Ue,{className:"bg-white dark:bg-gray-900 border-gray-200 dark:border-gray-700",children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Vt,{className:"flex items-center space-x-2",children:[e.jsx(La,{className:"h-5 w-5 text-green-500"}),e.jsx("span",{children:"Email Schedules"})]}),e.jsxs(N,{size:"sm",disabled:!0,children:[e.jsx(ns,{className:"h-4 w-4 mr-1"}),"New Schedule"]})]}),e.jsx(_e,{children:e.jsx("div",{className:"space-y-3",children:(u==="other"?[{name:"Daily TX Restaurants",preset:"TX Restaurants",interval:"Every 24 hours",active:!0},{name:"Weekly FL Auto Shops",preset:"FL Auto Shops",interval:"Every 7 days",active:!0},{name:"Bi-Daily CA Dentists",preset:"CA Dentists",interval:"Every 48 hours",active:!1}]:[{name:"Daily Ohio Plumbers",preset:"Ohio Plumbers",interval:"Every 24 hours",active:!0},{name:"Weekly NY Electricians",preset:"NY Electricians",interval:"Every 7 days",active:!0},{name:"Bi-Daily CA Roofers",preset:"CA Roofers",interval:"Every 48 hours",active:!1}]).map((P,le)=>e.jsx("div",{className:`border rounded-lg p-4 ${P.active?"border-green-200 bg-green-50/30 dark:border-green-800 dark:bg-green-950/30":"border-gray-200 bg-gray-50/50 dark:border-gray-700 dark:bg-gray-800/50"}`,children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h4",{className:"font-medium text-gray-900 dark:text-gray-100",children:P.name}),e.jsx(ie,{variant:P.active?"default":"secondary",className:"text-xs",children:P.active?"Active":"Paused"})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-sm text-gray-700 dark:text-gray-400",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ls,{className:"h-3.5 w-3.5"}),P.preset]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ua,{className:"h-3.5 w-3.5"}),P.interval]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx($a,{className:"h-3.5 w-3.5"}),"Default"]})]}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"Last sent 3 hours ago"})]}),e.jsxs("div",{className:"flex items-center gap-3 ml-4 flex-shrink-0",children:[e.jsx(xs,{checked:P.active,disabled:!0}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-8 w-8 text-red-500",disabled:!0,children:e.jsx(Hs,{className:"h-4 w-4"})})]})]})},le))})})]})})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:e.jsxs("div",{className:"bg-white/95 dar
134k:bg-gray-900/95 border border-gray-200 dark:border-gray-700 rounded-xl shadow-lg px-8 py-6 max-w-md text-center",children:[e.jsx(_a,{className:"h-10 w-10 mx-auto mb-3 text-green-500"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2",children:"Automated Email Schedules"}),e.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-400 mb-4",children:"Automatically receive new leads delivered straight to your inbox on a schedule you choose. Available on Pro, Platinum, Enterprise, and Agency plans."}),e.jsx(Hc,{href:"/#pricing",children:e.jsx(N,{className:"bg-green-600 hover:bg-green-700 text-white",children:"Upgrade to Unlock"})})]})})]});const Ge=u==="home_improvement"?"other":"home_improvement";return(Ge==="home_improvement"?"Home Improvement/Contractor":d.badgeName).replace(/\s+Database$/i,""),vt.filter(P=>{if(!P.isActive)return!1;const le=at.find(De=>De.id===P.filterPresetId);return le&&le.databaseType===Ge}).length,e.jsx("div",{className:"space-y-6",children:e.jsxs(Ue,{className:"bg-white border-gray-200",children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between flex-wrap gap-2",children:[e.jsxs(Vt,{className:"flex items-center space-x-2",children:[e.jsx(La,{className:"h-5 w-5 text-green-500"}),e.jsx("span",{children:"Email Schedules"}),e.jsx(ie,{variant:"secondary",className:"text-xs font-normal","data-testid":"badge-active-database",children:u==="home_improvement"?"Home Improvement/Contractor":d.badgeName})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g,e.jsxs(N,{size:"sm",onClick:()=>{f||Xe(),C(!f)},disabled:Je.length===0,children:[e.jsx(ns,{className:"h-4 w-4 mr-1"}),"New Schedule"]})]})]}),e.jsxs(_e,{children:[Je.length===0&&e.jsx("div",{className:"text-center py-4 mb-4 bg-amber-50 border border-amber-200 rounded-lg",children:e.jsx("p",{className:"text-amber-700 text-sm",children:"Save a filter preset on the Leads tab first, then you can create an email schedule based on it."})}),f&&e.jsxs("div",{className:"border border-blue-200 bg-blue-50/50 rounded-lg p-4 mb-6 space-y-4",children:[e.jsx("h3",{className:"font-medium text-gray-800",children:"Create Email Schedule"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(xe,{htmlFor:"schedule-name",children:"Schedule Name"}),e.jsx(Ee,{id:"schedule-name",placeholder:"e.g. Daily Ohio Plumbers",value:F,onChange:P=>w(P.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(xe,{children:"Filter Preset"}),e.jsxs(Jt,{value:j,onValueChange:E,children:[e.jsx(Yt,{children:e.jsx(Qt,{placeholder:"Select a saved filter preset"})}),e.jsx(Gt,{children:Je.map(P=>e.jsx(Ie,{value:String(P.id),children:P.name},P.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(xe,{children:"Send Interval"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ee,{type:"number",min:"1",max:"168",value:J,onChange:P=>p(P.target.value),className:"w-20"}),e.jsxs(Jt,{value:v,onValueChange:y,children:[e.jsx(Yt,{className:"w-28",children:e.jsx(Qt,{})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"hours",children:"Hours"}),e.jsx(Ie,{value:"days",children:"Days"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(xe,{children:"Export Format"}),e.jsxs(Jt,{value:A,onValueChange:T,children:[e.jsx(Yt,{children:e.jsx(Qt,{placeholder:"Default format"})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"default",children:"Default Format"}),Ct.map(P=>e.jsx(Ie,{value:String(P.id),children:P.name},P.id))]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(xe,{children:"Max Leads Per Email (optional)"}),e.jsx(Ee,{type:"number",min:"1",placeholder:"No limit",value:He,onChange:P=>ee(P.target.value),className:"w-40"}),e.jsx("p",{className:"text-xs text-gray-400",children:"Limit how many leads are sent per email. Overflow leads are saved to your reservoir for the next run."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(xe,{className:"flex items-center gap-1.5",children:[e.jsx(yr,{className:"h-3.5 w-3.5"}),"Recipients"]}),e.jsx(jl,{recipients:k,onChange:a,exportFormat:de()})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{className:"text-sm",children:"Distribution Mode"}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"radio",name:"distributionMode",value:"full_copy",checked:q==="full_copy",onChange:()=>$("full_copy"),className:"accent-blue-600"}),e.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300",children:"Send full copy to all recipients"})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"radio",name:"distributionMode",value:"split_evenly",checked:q==="split_evenly",onChange:()=>$("split_evenly"),className:"accent-blue-600"}),e.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300",children:"Split evenly among recipients"})]})]}),e.jsx("p",{className:"text-xs text-gray-400",children:q==="full_copy"?"Every recipient receives all leads in the export.":"Leads are divided evenly among recipients so each person gets a unique portion."}),q==="split_evenly"&&e.jsxs("div",{className:"space-y-1.5 pl-4 border-l-2 border-blue-200",children:[e.jsx(xe,{className:"text-xs text-gray-600 dark:text-gray-400",children:"Send full copy to these recipients (optional)"}),e.jsx("p",{className:"text-xs text-gray-400",children:"These recipients will receive the complete lead list even though leads are split among the main recipients. Useful for managers."}),e.jsx(Bn,{emails:X,onChange:B,max:50})]})]}),gt(de())&&e.jsxs("div",{className:"space-y-3 border-t border-blue-200 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xs,{checked:K,onCheckedChange:ae}),e.jsxs(xe,{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(qn,{
134className:"h-3.5 w-3.5"}),"Send combined file"]})]}),e.jsx("p",{className:"text-xs text-gray-400",children:"Merge all split parts into one file with attribution columns and send to separate recipients."}),K&&e.jsxs("div",{className:"space-y-3 pl-4 border-l-2 border-blue-200",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{className:"text-xs",children:"Combined File Recipients"}),e.jsx(Bn,{emails:Y,onChange:fe,max:50})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xs,{checked:U,onCheckedChange:te}),e.jsx("span",{className:"text-xs text-gray-700",children:"Assignee column"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xs,{checked:ne,onCheckedChange:Q}),e.jsx("span",{className:"text-xs text-gray-700",children:"File name column"})]})]}),(U||ne)&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx(xe,{className:"text-xs",children:"Column position"}),e.jsxs(Jt,{value:V,onValueChange:R,children:[e.jsx(Yt,{className:"mt-1",children:e.jsx(Qt,{})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"beginning",children:"Beginning of row"}),e.jsx(Ie,{value:"end",children:"End of row"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[U&&e.jsxs("div",{children:[e.jsx(xe,{className:"text-xs",children:"Assignee column name"}),e.jsx(Ee,{value:pe,onChange:P=>Se(P.target.value),className:"mt-1",placeholder:"Assigned To"})]}),ne&&e.jsxs("div",{children:[e.jsx(xe,{className:"text-xs",children:"File name column name"}),e.jsx(Ee,{value:Ze,onChange:P=>Me(P.target.value),className:"mt-1",placeholder:"File Part"})]})]})]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(N,{onClick:mt,disabled:lt.isPending,children:lt.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:16})," Creating..."]}):"Create Schedule"}),e.jsx(N,{variant:"ghost",onClick:()=>{C(!1),Xe()},children:"Cancel"})]})]}),Rt?e.jsx(ea,{size:"md"}):vt.length===0?e.jsxs("div",{className:"text-center py-8 text-gray-500",children:[e.jsx(_a,{className:"h-10 w-10 mx-auto mb-3 text-gray-300"}),e.jsx("p",{children:"No email schedules yet."}),e.jsx("p",{className:"text-sm mt-1",children:"Create a schedule to automatically receive new leads by email."})]}):e.jsx("div",{className:"space-y-3",children:vt.map(P=>{const le=ze(P),De=O===P.id,st=re[P.id],Ft=!P.isActive&&P.pauseReason==="insufficient_credits",oe=P.isActive||Ft;return e.jsxs("div",{className:`border rounded-lg transition-colors ${Ft?"border-amber-200 bg-amber-50/30":P.isActive?"border-green-200 bg-green-50/30":"border-gray-200 bg-gray-50/50"}`,children:[e.jsx("div",{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h4",{className:"font-medium text-gray-900 truncate",children:P.name}),Ft?e.jsx(ie,{variant:"outline",className:"text-xs border-amber-400 text-amber-600",children:"Credit Paused"}):e.jsx(ie,{variant:P.isActive?"default":"secondary",className:"text-xs",children:P.isActive?"Active":"Paused"})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-sm text-gray-700",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ls,{className:"h-3.5 w-3.5"}),ot(P.filterPresetId),St(P.filterPresetId)&&e.jsx(ie,{variant:"outline",className:"text-[10px] px-1 py-0 border-amber-400 text-amber-600 ml-1",children:"Wrong DB"})]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ua,{className:"h-3.5 w-3.5"}),ut(P.intervalValue,P.intervalUnit)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx($a,{className:"h-3.5 w-3.5"}),Pt(P.exportFormatId)]}),W===P.id?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("input",{type:"number",min:"1",value:ve,onChange:Ye=>Oe(Ye.target.value),className:"w-20 border rounded px-1.5 py-0.5 text-xs",placeholder:"No limit",onKeyDown:Ye=>{if(Ye.key==="Enter"){const pt=ve.trim()?parseInt(ve,10):null;if(pt!==null&&(isNaN(pt)||pt<1))return;Ot.mutate({id:P.id,maxLeadsPerEmail:pt})}Ye.key==="Escape"&&Le(null)}}),e.jsx("button",{type:"button",className:"text-green-600 hover:text-green-800 text-xs",onClick:()=>{const Ye=ve.trim()?parseInt(ve,10):null;Ye!==null&&(isNaN(Ye)||Ye<1)||Ot.mutate({id:P.id,maxLeadsPerEmail:Ye})},children:"Save"}),e.jsx("button",{type:"button",className:"text-gray-400 hover:text-gray-600 text-xs",onClick:()=>Le(null),children:"Cancel"})]}):e.jsx("button",{type:"button",className:"flex items-center gap-1 text-amber-600 hover:text-amber-800 transition-colors",onClick:()=>{Le(P.id),Oe(P.maxLeadsPerEmail?String(P.maxLeadsPerEmail):"")},children:P.maxLeadsPerEmail?`Max ${P.maxLeadsPerEmail.toLocaleStr
134ing()} leads`:"Set max leads"}),e.jsxs("button",{type:"button",onClick:()=>_t(P.id),className:"flex items-center gap-1 hover:text-blue-600 transition-colors",children:[e.jsx(yr,{className:"h-3.5 w-3.5"}),le," recipient",le!==1?"s":"",De?e.jsx(Vn,{className:"h-3 w-3"}):e.jsx(sr,{className:"h-3 w-3"})]}),It(P)>0&&e.jsxs("button",{type:"button",onClick:()=>$e(tt===P.id?null:P.id),className:`flex items-center gap-1 transition-colors ${P.combinedFileEnabled?"text-blue-600 hover:text-blue-700":"hover:text-blue-600"}`,children:[e.jsx(qn,{className:"h-3.5 w-3.5"}),"Combined",P.combinedFileEnabled?" ON":"",tt===P.id?e.jsx(Vn,{className:"h-3 w-3"}):e.jsx(Ud,{className:"h-3 w-3"})]})]}),P.lastSent&&e.jsxs("p",{className:"text-xs text-gray-400 mt-1",children:["Last sent ",nn(new Date(P.lastSent),{addSuffix:!0})]})]}),e.jsxs("div",{className:"flex items-center gap-3 ml-4 flex-shrink-0",children:[Ft?e.jsx(Qa,{children:e.jsxs(Ra,{children:[e.jsx(Oa,{asChild:!0,children:e.jsx("div",{className:"opacity-50",children:e.jsx(xs,{checked:oe,onCheckedChange:Ye=>kt(P.id,Ye)})})}),e.jsx(Da,{side:"top",className:"max-w-[250px] text-center",children:e.jsx("p",{className:"text-xs",children:"Purchase additional credits or wait until your subscription renews for this schedule to resume."})})]})}):e.jsx(xs,{checked:P.isActive??!1,disabled:!s&&!P.isActive,onCheckedChange:Ye=>kt(P.id,Ye)}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-8 w-8 text-red-500 hover:text-red-700 hover:bg-red-50",onClick:()=>ft.mutate(P.id),children:e.jsx(Hs,{className:"h-4 w-4"})})]})]})}),De&&st!==void 0&&e.jsxs("div",{className:"border-t border-gray-200 px-4 py-3 bg-gray-50/80 space-y-3",children:[e.jsx(jl,{recipients:st,onChange:Ye=>Pe(pt=>({...pt,[P.id]:Ye})),exportFormat:it(P)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(N,{size:"sm",onClick:()=>qt.mutate({id:P.id,recipients:st}),disabled:qt.isPending,children:qt.isPending?"Saving...":"Save Recipients"}),e.jsx(N,{size:"sm",variant:"ghost",onClick:()=>_t(P.id),children:"Cancel"})]})]}),tt===P.id&&e.jsx(Yp,{schedule:P,onSave:Ye=>et.mutate({id:P.id,data:Ye}),onCancel:()=>$e(null),isPending:et.isPending})]},P.id)})})]})]})})}const Gp=["pro","platinum","enterprise","agency","starter","growth","scale"],Zp=2e4;async function Xp({signal:t}){const r=new AbortController,s=()=>r.abort();t&&(t.aborted?r.abort():t.addEventListener("abort",s,{once:!0}));const i=setTimeout(()=>r.abort(),Zp);try{const l=await fetch("/api/api-keys",{credentials:"include",signal:r.signal});if(Wc(l),!l.ok){const c=await l.text()||l.statusText;throw new Error(`${l.status}: ${c}`)}return await l.json()}catch(l){throw(l==null?void 0:l.name)==="AbortError"&&!(t!=null&&t.aborted)?new Error("Timed out loading API keys. Check your connection and try again."):l}finally{clearTimeout(i),t==null||t.removeEventListener("abort",s)}}function Ea({code:t,language:r}){const[s,i]=o.useState(!1),l=async()=>{await navigator.clipboard.writeText(t),i(!0),setTimeout(()=>i(!1),2e3)};return e.jsxs("div",{className:"relative",children:[e.jsx("pre",{className:"bg-gray-900 text-gray-100 p-4 rounded-lg text-sm overflow-x-auto",children:e.jsx("code",{children:t})}),e.jsx(N,{variant:"ghost",size:"sm",className:"absolute top-2 right-2 text-gray-400 hover:text-white hover:bg-gray-700",onClick:l,children:s?e.jsx(sa,{className:"h-4 w-4"}):e.jsx(jr,{className:"h-4 w-4"})})]})}function Nl(t){if(t<1024)return`${t} B`;const r=["KB","MB","GB","TB"];let s=t/1024,i=0;for(;s>=1024&&i<r.length-1;)s/=1024,i++;return`${s.toFixed(s>=100?0:1)} ${r[i]}`}function El(t){const r=Math.floor(t/1e3),s=Math.floor(r/60),i=r%60;return`${s}:${String(i).padStart(2,"0")}`}function ex({baseUrl:t}){Ss();const[r,s]=o.useState(""),[i,l]=o.useState(!1),c=ja(),[d,u]=o.useState("home_improvement"),[g,f]=o.useState("idle"),[C,F]=o.useState(0),[w,j]=o.useState(0),[E,A]=o.useState(null),[T,J]=o.useState(null),p=o.useRef(0),v=o.useRef(null);o.useEffect(()=>()=>{v.current&&clearInterval(v.current)},[]);const y=async()=>{const a=r.trim();f("downloading"),F(0),j(0),A(null),J(null),p.current=Date.now(),v.current&&clearInterval(v.current),v.current=setInterval(()=>{j(Date.now()-p.current)},1e3);try{const q={};a&&(q.Authorization=`Bearer ${a}`);const $=await fetch(`${t}/admin/database-export?database=${d}`,{headers:q,credentials:"same-origin"});if(!$.ok||!$.body){let V=`Export failed (HTTP ${$.status})`;try{const R=await $.json();R!=null&&R.message&&(V=R.message)}catch{}throw new Error(V)}const X=$.headers.get("X-Export-Part-Count"),B=$.body.getReader(),K=[];let ae=0;for(;;){const{done:V,value:R}=await B.read();if(V)break;R&&(K.push(R),ae+=R.length,F(ae))}const Y=new Blob(K,{type:"application/zip"}),U=($.headers.get("Content-Disposition")||"").match(/filename="?([^"]+)"?/),te=(U==null?void 0:U[1])||`${d}-export.zip`,ne=URL.createObjectURL(Y),Q=document.createElement("a");Q.href=ne,Q.download=te,document.body.appendChild(Q),Q.click(),Q.remove(),URL.revokeObjectURL(ne),F(ae),j(Date.now()-p.current),A(X?parseInt(X,10):null),f("done")}catch(q){J((q==null?void 0:q.message)||"Export failed"),f("error")}finally{v.current&&(clearInterval(v.current),v.current=null)}},k=g==="downloading";return e.jsxs("div",{className:"space-y-3 rounded-lg border border-amber-200 bg-amber-50/60 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-amber-900",children:[e.jsx(Qs,{className:"h-4 w-4"}),"Download in this browser"]}),e.jsx("p",{className:"text-xs text-gray-600",children:"Runs the export here with a live progress indicator, signed in with your current admin session â no API key needed. For the very largest tables, the cURL command above is still the most reliable option."}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-[1fr_auto]",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx(xe,{className:"text-xs text-gray-700",children:"Database"}),e.jsxs(Jt,{value:d,onValueChange:a=>u(a),disabled:k,children:[e.jsx(Yt,{className:"sm:w-48",children:e.jsx(Qt,{})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"home_improvement",children:"Home Improvement"}),e.jsx(Ie,{value:"other",children:c.abbrev})]})]})]})}),e.jsx("div",{className:"space-y-1",children:i?e.jsxs(e.Fragment,{children:[e.jsx(xe,{htmlFor:"admin-export-key",className:"text-xs text-gray-700",children:"Admin API key (optional)"}),e.jsx(Ee,{id:"admin-export-key",type:"password",placeholder:"Bearer key (e.g. sk_live_...)",value:r,onChange:a=>s(a.target.value),disabled:k,autoComplete:"off"}),e.jsx("p",{className:"text-[11px] text-gray-500",children:"Leave blank to use your admin session."})]}):e.jsx(N,{type:"button",variant:"link",size:"sm",className:"h-auto p-0 text-xs text-amber-700",onClick:()=>l(!0),disabled:k,children:"Use an API key instead (optional)"})}),e.jsx(N,{onClick:y,disabled:k,className:"bg-amber-600 hover:bg-amber-700 text-white",children:k?e.jsxs(e.Fragment,{children:[e.jsx(Ua,{className:"h-4 w-4 mr-2 animate-spin"}),"Download in progressâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(Qs,{className:"h-4 w-4 mr-2"}
134),"Download export"]})}),k&&e.jsxs("div",{className:"space-y-2","aria-live":"polite",children:[e.jsx("div",{className:"h-1.5 w-full overflow-hidden rounded-full bg-amber-200",children:e.jsx("div",{className:"h-full w-1/3 animate-pulse rounded-full bg-amber-500"})}),e.jsxs("p",{className:"text-sm text-amber-900",children:["Downloading⦠",Nl(C)," received · ",El(w)," elapsed"]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Large tables can take up to 30 minutes. Keep this tab open until it finishes."})]}),g==="done"&&e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-green-200 bg-green-50 p-3 text-sm text-green-800","aria-live":"polite",children:[e.jsx(da,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Export complete"}),e.jsxs("p",{className:"text-xs text-green-700",children:[Nl(C)," downloaded in ",El(w),E!==null&&e.jsxs(e.Fragment,{children:[" · ZIP contains ",E," CSV part",E===1?"":"s"]}),". Check your browser downloads for the ZIP file."]})]})]}),g==="error"&&e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-800","aria-live":"polite",children:[e.jsx(rr,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Export failed"}),e.jsx("p",{className:"text-xs text-red-700",children:T})]})]})]})}function tx(){const{user:t}=Pr(),{toast:r}=Ss(),[s,i]=o.useState(""),[l,c]=o.useState(null),[d,u]=o.useState(!1),g=(t==null?void 0:t.isSubscribed)&&Gp.includes((t==null?void 0:t.subscriptionPlan)||""),{data:f,isLoading:C,isError:F,error:w,isFetching:j,isPaused:E,refetch:A}=Qe({queryKey:["/api/api-keys"],enabled:!!g,queryFn:Xp,retry:1,retryDelay:1e3,refetchInterval:K=>{var fe;const ae=K.state.data;return((fe=ae==null?void 0:ae.keys)==null?void 0:fe.some(U=>!U.revokedAt))?6e4:!1}}),T=o.useRef(null);o.useEffect(()=>{const K=f==null?void 0:f.keys;if(!K)return;const ae=K.reduce((Y,fe)=>Y+(fe.totalCreditsUsed||0),0);T.current!==null&&ae>T.current&&(z.invalidateQueries({queryKey:["/api/auth/user"]}),z.invalidateQueries({queryKey:["/api/me/temporary-credits"]})),T.current=ae},[f]);const J=Ne({mutationFn:async K=>await(await ue("POST","/api/api-keys",{name:K})).json(),onSuccess:K=>{c(K.rawKey),i(""),z.invalidateQueries({queryKey:["/api/api-keys"]}),r({title:"API Key Created",description:"Save your key now - it won't be shown again."})},onError:K=>{r({title:"Error",description:K.message,variant:"destructive"})}}),p=Ne({mutationFn:async K=>{await ue("POST",`/api/api-keys/${K}/revoke`)},onSuccess:()=>{z.invalidateQueries({queryKey:["/api/api-keys"]}),r({title:"API Key Revoked",description:"The API key has been revoked and can no longer be used."})},onError:K=>{r({title:"Error",description:K.message,variant:"destructive"})}}),v=async()=>{l&&(await navigator.clipboard.writeText(l),u(!0),setTimeout(()=>u(!1),2e3))},y=()=>{if(!s.trim()){r({title:"Name Required",description:"Please enter a name for your API key.",variant:"destructive"});return}J.mutate(s.trim())};if(!g)return e.jsxs("div",{className:"space-y-6 relative",children:[e.jsx("div",{className:"absolute inset-0 z-20 flex items-start justify-center pt-24",children:e.jsx(Ue,{className:"bg-white border-2 border-blue-200 shadow-xl max-w-md mx-4",children:e.jsxs(_e,{className:"flex flex-col items-center justify-center py-8 px-6 text-center",children:[e.jsx("div",{className:"w-14 h-14 bg-blue-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(ya,{className:"h-7 w-7 text-blue-600"})}),e.jsx("h3",{className:"text-xl font-semibold mb-2",children:"API Access - Paid Plans Only"}),e.jsxs("p",{className:"text-gray-700 mb-6 text-sm leading-relaxed",children:["The REST API is available exclusively for users on a ",e.jsx("strong",{children:"Starter"}),", ",e.jsx("strong",{children:"Growth"}),", ",e.jsx("strong",{children:"Scale"}),", ",e.jsx("strong",{children:"Pro"}),", ",e.jsx("strong",{children:"Platinum"}),", ",e.jsx("strong",{children:"Enterprise"}),", or ",e.jsx("strong",{children:"Agency"})," plan. Upgrade your plan to create API keys and integrate SMB Sales Boost with your existing tools and workflows."]}),e.jsx(N,{className:"bg-blue-600 hover:bg-blue-700 text-white",onClick:()=>window.location.href="/#pricing",children:"Upgrade to Unlock API Access"})]})})}),e.jsxs("div",{className:"filter blur-[3px] pointer-events-none select-none","aria-hidden":"true",children:[e.jsxs(Ue,{className:"bg-white",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-5 w-5"}),"API Keys",e.jsx(ie,{variant:"secondary",className:"ml-2",children:"0 / 10 active"})]})}),e.jsxs(_e,{children:[e.jsxs("div",{className:"flex gap-2 mb-6",children:[e.jsx(Ee,{placeholder:"Key name (e.g., Production, Staging)",disabled:!0,className:"max-w-sm"}),e.jsxs(N,{disabled:!0,className:"bg-blue-600 text-white",children:[e.jsx(ns,{className:"h-4 w-4 mr-1"}),"Create Key"]})]}),e.jsxs("div",{className:"text-center py-8 text-gray-500",children:[e.jsx(Ta,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No API keys yet. Create one to get started."})]})]})]}),e.jsxs(Ue,{className:"bg-white",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center gap-2",children:[e.jsx(Hi,{className:"h-5 w-5"}),"Quick Start"]})}),e.jsx(_e,{children:e.jsx("div",{className:"bg-gray-900 text-gray-100 p-4 rounded-lg text-sm overflow-x-auto",children:e.jsx("code",{children:`curl -H "Authorization: Bearer YOUR_API_KEY" \\ 135 https://example.com/api/v1/me`})})})]}),e.jsxs(Ue,{className:"bg-white",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center gap-2",children:[e.jsx(Za,{className:"h-5 w-5"}),"Rate Limits"]})}),e.jsx(_e,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-gray-50 rounded-lg",children:[e.jsx(ua,{className:"h-5 w-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"General Requests"}),e.jsx("p",{className:"text-sm text-gray-500",children:"600 requests per minute"})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-gray-50 rounded-lg",children:[e.jsx(Ya,{className:"h-5 w-5 text-amber-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Exports"}),e.jsx("p",{className:"text-sm text-gray-500",children:"5 exports per minute"})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-gray-50 rounded-lg",children:[e.jsx(Ya,{className:"h-5 w-5 text-purple-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"AI Endpoints"}),e.jsx("p",{className:"text-sm text-gray-500",children:"5 requests per minute"})]})]})]})})]})]})]});const k=(f==null?void 0:f.keys)||[],a=k.filter(K=>!K.revokedAt),q=`${window.location.origin}/api/v1`,$=`# Get your account info 136curl -H "Authorization: Bearer YOUR_API_KEY" \\ 137 "${q}/me" 138 139# List leads 140curl -H "Authorization: Bearer YOUR_API_KEY" \\ 141 "${q}/leads?page=1&limit=25" 142 143# Export leads as CSV 144curl -X POST -H "Authorization: Bearer YOUR_API_KEY" \\ 145 -H "Content-Type: application/json" \\ 146 -d '{"format":"csv"}' \\ 147 "${q}/leads/export"`,X=`const API_KEY = "YOUR_API_KEY"; 148const BASE_URL = "${q}"; 149 150// Get your account info 151const me = await fetch(\`\${BASE_URL}/me\`, { 152 headers: { "Authorization": \`Bearer \${API_KEY}\` } 153}).then(r => r.json()); 154 155// List leads 156const leads = await fetch(\`\${BASE_URL}/leads?page=1&limit=25\`, { 157 headers: { "Authorization": \`Bearer \${API_KEY}\` } 158}).then(r => r.json()); 159 160// Export leads as CSV 161const exported = await fetch(\`\${BASE_URL}/leads/export\`, { 162 method: "POST", 163 headers: { 164 "Authorization": \`Bearer \${API_KEY}\`, 165 "Content-Type": "application/json" 166 }, 167 body: JSON.stringify({ format: "csv" }) 168}).then(r => r.json());`,B=`import requests 169 170API_KEY = "YOUR_API_KEY" 171BASE_URL = "${q}" 172headers = {"Authorization": f"Bearer {API_KEY}"} 173 174# Get your account info 175me = requests.get(f"{BASE_URL}/me", headers=headers).json() 176 177# List leads 178leads = requests.get( 179 f"{BASE_URL}/leads", 180 headers=headers, 181 params={"page": 1, "limit": 25} 182).json() 183 184# Export leads as CSV 185exported = requests.post( 186 f"{BASE_URL}/leads/export", 187 headers=headers, 188 json={"format": "csv"} 189).json()`;return e.jsxs("div",{className:"space-y-6",children:[l&&e.jsx(Ue,{className:"bg-green-50 border-green-200",children:e.jsx(_e,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ps,{className:"h-5 w-5 text-amber-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"font-semibold text-green-800 mb-1",children:"API Key Created - Save It Now"}),e.jsx("p",{className:"text-sm text-green-700 mb-3",children:"This is the only time your full API key will be shown. Copy it and store it securely."}),e.jsxs("div",{className:"flex items-center gap-2 bg-white border border-green-300 rounded-lg p-3",children:[e.jsx("code",{className:"ph-no-capture flex-1 text-sm font-mono break-all text-gray-800",children:l}),e.jsxs(N,{variant:"outline",size:"sm",onClick:v,className:"flex-shrink-0",children:[d?e.jsx(sa,{className:"h-4 w-4 text-green-600"}):e.jsx(jr,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-1",children:d?"Copied":"Copy"})]})]}),e.jsx(N,{variant:"ghost",size:"sm",className:"mt-2 text-green-700",onClick:()=>c(null),children:"I've saved my key - dismiss"})]})]})})}),e.jsxs(Ue,{className:"bg-white",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-5 w-5"}),"API Keys",e.jsxs(ie,{variant:"secondary",className:"ml-2",children:[a.length," / 10 active"]})]})}),e.jsxs(_e,{children:[e.jsxs("div",{className:"flex gap-2 mb-6",children:[e.jsx(Ee,{placeholder:"Key name (e.g., Production, Staging)",value:s,onChange:K=>i(K.target.value),onKeyDown:K=>K.key==="Enter"&&y(),maxLength:100,className:"max-w-sm"}),e.jsxs(N,{onClick:y,disabled:J.isPending||a.length>=10,className:"bg-blue-600 hover:bg-blue-700 text-white",children:[e.jsx(ns,{className:"h-4 w-4 mr-1"}),J.isPending?"Creating...":"Create Key"]})]}),C?e.jsxs("div",{className:"flex items-center justify-center gap-2 py-8 text-gray-500",children:[e.jsx(Ua,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:"Loading API keys..."})]}):E?e.jsxs("div",{className:"text-center py-8 text-gray-500",children:[e.jsx(rr,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"You appear to be offline. Your API keys will load once the connection is back."})]}):F?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(rr,{className:"h-8 w-8 mx-auto mb-2 text-red-500"}),e.jsx("p",{className:"text-sm text-gray-700 mb-1",children:"Could not load your API keys."}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:(w==null?void 0:w.message)||"Unknown error"}),e.jsx(N,{variant:"outline",size:"sm",onClick:()=>A(),disabled:j,children:j?"Retrying...":"Try again"})]}):k.length===0?e.jsxs("div",{className:"text-center py-8 text-gray-500",children:[e.jsx(Ta,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No API keys yet. Create one to get started."})]}):e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-gray-50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left p-3 font-medium text-gray-700",children:"Name"}),e.jsx("th",{className:"text-left p-3 font-medium text-gray-700",children:"Key"}),e.jsx("th",{className:"text-left p-3 font-medium text-gray-700",children:"Created"}),e.jsx("th",{className:"text-left p-3 font-medium text-gray-700",children:"Last Used"}),e.jsx("th",{className:"text-right p-3 font-medium text-gray-700",children:"Cycle Credits"}),e.jsx("th",{className:"text-right p-3 font-medium text-gray-700",children:"Total Credits"}),e.jsx("th",{className:"text-left p-3 font-medium text-gray-700",children:"Status"}),e.jsx("th",{className:"text-right p-3 font-medium text-gray-700",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y",children:k.map(K=>e.jsxs("tr",{className:K.revokedAt?"opacity-60":"",children:[e.jsx("td",{className:"p-3 font-medium",children:K.name}),e.jsx("td",{className:"p-3 font-mono text-gray-500",children:K.keyPrefix}),e.jsx("td",{className:"p-3 text-gray-500",children:new Date(K.createdAt).toLocaleDateString()}),e.jsx("td",{className:"p-3 text-gray-500",children:K.lastUsedAt?new Date(K.lastUsedAt).toLocaleDateString():"Never"}),e.jsx("td",{className:"p-3 text-right text-gray-700 font-mono text-xs",children:K.currentCycleCreditsUsed.toLocaleStr
189ing()}),e.jsx("td",{className:"p-3 text-right text-gray-700 font-mono text-xs",children:K.totalCreditsUsed.toLocaleString()}),e.jsx("td",{className:"p-3",children:K.revokedAt?e.jsx(ie,{variant:"destructive",className:"text-xs",children:"Revoked"}):e.jsx(ie,{className:"bg-green-100 text-green-700 text-xs",children:"Active"})}),e.jsx("td",{className:"p-3 text-right",children:!K.revokedAt&&e.jsxs(N,{variant:"ghost",size:"sm",className:"text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>p.mutate(K.id),disabled:p.isPending,children:[e.jsx(Hs,{className:"h-4 w-4 mr-1"}),"Revoke"]})})]},K.id))})]})})]})]}),e.jsxs(Ue,{className:"bg-white",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center gap-2",children:[e.jsx(Hi,{className:"h-5 w-5"}),"Quick Start"]})}),e.jsx(_e,{children:e.jsxs(_n,{defaultValue:"curl",className:"w-full",children:[e.jsxs(zn,{children:[e.jsx(Vs,{value:"curl",children:"cURL"}),e.jsx(Vs,{value:"javascript",children:"JavaScript"}),e.jsx(Vs,{value:"python",children:"Python"})]}),e.jsx(Us,{value:"curl",className:"mt-4",children:e.jsx(Ea,{code:$,language:"bash"})}),e.jsx(Us,{value:"javascript",className:"mt-4",children:e.jsx(Ea,{code:X,language:"javascript"})}),e.jsx(Us,{value:"python",className:"mt-4",children:e.jsx(Ea,{code:B,language:"python"})})]})})]}),e.jsxs(Ue,{className:"bg-white",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center gap-2",children:[e.jsx(Za,{className:"h-5 w-5"}),"Rate Limits"]})}),e.jsx(_e,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-gray-50 rounded-lg",children:[e.jsx(ua,{className:"h-5 w-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"General Requests"}),e.jsx("p",{className:"text-sm text-gray-500",children:"600 requests per minute"})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-gray-50 rounded-lg",children:[e.jsx(Ya,{className:"h-5 w-5 text-amber-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Exports"}),e.jsx("p",{className:"text-sm text-gray-500",children:"5 exports per minute"})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-gray-50 rounded-lg",children:[e.jsx(Ya,{className:"h-5 w-5 text-purple-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"AI Endpoints"}),e.jsx("p",{className:"text-sm text-gray-500",children:"5 requests per minute"})]})]})]})})]}),e.jsx(Ue,{className:"bg-white",children:e.jsxs(_e,{className:"flex items-center justify-between py-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(aa,{className:"h-4 w-4 text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-700",children:"Need more details? Check out the full API documentation."})]}),e.jsxs(N,{variant:"outline",size:"sm",onClick:()=>window.open("/docs/api","_blank"),children:["View API Docs",e.jsx(aa,{className:"h-3 w-3 ml-1"})]})]})}),(t==null?void 0:t.isAdmin)===!0&&e.jsxs(Ue,{className:"bg-white border-2 border-amber-300",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center gap-2 text-amber-800",children:[e.jsx(Vl,{className:"h-5 w-5"}),"Admin: Full Database Export",e.jsx(ie,{className:"bg-amber-100 text-amber-800 ml-2 text-xs",children:"Admin Only"})]})}),e.jsxs(_e,{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-gray-700",children:["Stream the entire ",e.jsx("strong",{children:"home_improvement"})," or ",e.jsx("strong",{children:"other"})," lead database as a ZIP archive containing one or more CSV files. Tables with more than 900,000 rows are automatically split into equal-sized chunks (⤠900,000 data rows each) so every file opens cleanly in Excel. As a logged-in admin you can download directly in this browser â no API key needed (an API key is optional, only if you'd rather authenticate that way). Large exports may take up to 30 minutes â use ",e.jsx("code",{className:"bg-gray-100 px-1 rounded text-xs",children:"--max-time 1800"})," with cURL to avoid client-side timeouts. No credits are deducted."]}),e.jsx("p",{className:"text-sm text-amber-700 font-medium",children:"This endpoint is hidden from all public docs, the OpenAPI spec, and the MCP server â visible here only."}),e.jsxs(_n,{defaultValue:"curl-hi",className:"w-full",children:[e.jsxs(zn,{children:[e.jsx(Vs,{value:"curl-hi",children:"cURL (Home Improvement)"}),e.jsx(Vs,{value:"curl-other",children:"cURL (Other)"}),e.jsx(Vs,{value:"js-hi",children:"JavaScript"}),e.jsx(Vs,{value:"py-hi",children:"Python"})]}),e.jsx(Us,{value:"curl-hi",className:"mt-4",children:e.jsx(Ea,{language:"bash",code:`curl --max-time 1800 \\ 190 -H "Authorization: Bearer YOUR_ADMIN_API_KEY" \\ 191 "${q}/admin/database-export?database=home_improvement" \\ 192 -o home_improvement-$(date +%F).zip`})}),e.jsx(Us,{value:"curl-other",className:"mt-4",children:e.jsx(Ea,{language:"bash",code:`curl --max-time 1800 \\ 193 -H "Authorization: Bearer YOUR_ADMIN_API_KEY" \\ 194 "${q}/admin/database-export?database=other" \\ 195 -o other-$(date +%F).zip`})}),e.jsx(Us,{value:"js-hi",className:"mt-4",children:e.jsx(Ea,{language:"javascript",code:`const fs = require("fs"); 196const https = require("https"); 197 198const API_KEY = "YOUR_ADMIN_API_KEY"; 199const database = "home_improvement"; // or "other" 200const url = \`${q}/admin/database-export?database=\${database}\`; 201 202// Response is a ZIP archive containing one or more CSV chunks 203const file = fs.createWriteStream(\`\${database}-export.zip\`); 204https.get(url, { headers: { Authorization: \`Bearer \${API_KEY}\` } }, (res) => { 205 res.pipe(file); 206 file.on("finish", () => { file.close(); console.log("Done â unzip to access CSV chunks"); }); 207});`})}),e.jsx(Us,{value:"py-hi",className:"mt-4",children:e.jsx(Ea,{language:"python",code:`import requests 208 209API_KEY = "YOUR_ADMIN_API_KEY" 210database = "home_improvement" # or "other" 211url = f"${q}/admin/database-export?database={"{database}"}" 212 213# Response is a ZIP archive containing one or more CSV chunks 214with requests.get( 215 url, 216 headers={"Authorization": f"Bearer {"{API_KEY}"}"}, 217 stream=True, 218 timeout=1800, 219) as r: 220 r.raise_for_status() 221 with open(f"{"{database}"}-export.zip", "wb") as f: 222 for chunk in r.iter_content(chunk_size=8192): 223 f.write(chunk) 224print("Export complete â unzip to access CSV chunks")`})})]}),e.jsx(ex,{baseUrl:q})]})]})]})}const Sl=Bc,sx=Jc,rc=o.forwardRef(({className:t,...r},s)=>e.jsx(Bl,{className:Fs("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...r,ref:s}));rc.displayName=Bl.displayName;const ax=Qc("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),Jn=o.forwardRef(({side:t="right",className:r,children:s,...i},l)=>e.jsxs(sx,{children:[e.jsx(rc,{}),e.jsxs(ql,{ref:l,className:Fs(ax({side:t}),r),...i,children:[s,e.jsxs(Yc,{className:"absolute right-4 top-4 roun
224ded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[e.jsx(Ut,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Jn.displayName=ql.displayName;const Yn=({className:t,...r})=>e.jsx("div",{className:Fs("flex flex-col space-y-2 text-center sm:text-left",t),...r});Yn.displayName="SheetHeader";const Qn=o.forwardRef(({className:t,...r},s)=>e.jsx(Hl,{ref:s,className:Fs("text-lg font-semibold text-foreground",t),...r}));Qn.displayName=Hl.displayName;const nc=o.forwardRef(({className:t,...r},s)=>e.jsx(Wl,{ref:s,className:Fs("text-sm text-muted-foreground",t),...r}));nc.displayName=Wl.displayName;const rx=["pro","platinum","enterprise","agency","starter","growth","scale"],nx={zapier:{steps:["In Zapier, create a new Zap and pick the 'Webhooks by Zapier' trigger.","Choose 'Catch Hook', copy the unique webhook URL Zapier gives you, and paste it into the field below.","Send a test event from this page to populate sample data, then map the fields to your downstream Zap action."],snippet:`Trigger: Webhooks by Zapier -> Catch Hook 225Method: POST (signed with HMAC-SHA256 in X-SMB-Signature) 226Sample headers: X-SMB-Event, X-SMB-Timestamp, X-SMB-Signature 227Body: { id, type, occurredAt, userId, integrationId, provider, data }`},n8n:{steps:["In n8n, create a Workflow and add a 'Webhook' trigger node.","Set HTTP Method to POST and copy the test/production webhook URL into the field below.","Optionally verify our HMAC signature using the Crypto node and the signing secret shown after creation."],snippet:`Node: Webhook (POST) 228Response Mode: On Received 229Validate signature (Function node): 230 const ts = $headers['x-smb-timestamp']; 231 const sig = ($headers['x-smb-signature']||'').split('v1=')[1]; 232 const expected = require('crypto').createHmac('sha256', SIGNING_SECRET).update(ts+'.'+JSON.stringify($json)).digest('hex'); 233 if (sig !== expected) throw new Error('bad signature');`},make:{steps:["In Make (Integromat), create a Scenario and add the 'Custom webhook' trigger.","Click 'Add', name the hook, copy the address, and paste it below.","Run 'Send test event' here to teach Make the payload structure, then map fields downstream."],snippet:`Module: Webhooks > Custom webhook 234Method: POST 235Data type: JSON pass-through 236Downstream module: HTTP, Google Sheets, HubSpot, Pipedrive, etc.`},pipedream:{steps:["In Pipedream, create a New Workflow and use the 'HTTP / Webhook' trigger.","Copy the unique URL and paste it below.","Add a downstream step (Slack, Notion, Postgres, etc.) and map fields from steps.trigger.event.body.data."],snippet:`Trigger: HTTP / Webhook 237Reference body: steps.trigger.event.body.data 238Verify HMAC using $.steps.trigger.event.headers['x-smb-signature'] 239Body fields: id, type, occurredAt, userId, integrationId, provider, data`}},wi=["lead.created","lead.updated","export.completed","email_schedule.sent","credit.low_balance"];function ix(t){if(!t)return{};try{const r=JSON.parse(t);if(r&&typeof r=="object"){const s=typeof r.personId=="number"?r.personId:void 0,i=typeof r.dealId=="number"?r.dealId:void 0;return{personId:s,dealId:i}}}catch{}return{}}function lx(t){if(!t||typeof t!="object")return null;const r=t.apiDomain;if(r&&/^https?:\/\//i.test(r))return r.replace(/\/$/,"");const s=t.companyDomain;return s?`https://${s}.pipedrive.com`:null}const ic={"lead.created":"New lead exported","lead.updated":"Lead updated","export.completed":"Export completed","email_schedule.sent":"Scheduled email sent","credit.low_balance":"Credit balance low"},ox=Zl({displayName:fr().min(1,"Required").max(100).optional().or(zi("")),targetUrl:fr().url("Must be a valid URL").max(2048),events:Xl(Gl(wi)).min(1,"Pick at least one event"),apiKey:fr().max(500).optional().or(zi(""))});function lc({status:t}){return t==="connected"?e.jsxs(ie,{className:"bg-green-100 text-green-800 hover:bg-green-100",children:[e.jsx(da,{className:"h-3 w-3 mr-1"}),"Connected"]}):t==="needs_attention"?e.jsxs(ie,{className:"bg-orange-100 text-orange-800 hover:bg-orange-100",children:[e.jsx(ps,{className:"h-3 w-3 mr-1"}),"Action needed"]}):e.jsxs(ie,{variant:"outline",children:[e.jsx(rr,{className:"h-3 w-3 mr-1"}),"Disabled"]})}function cx({provider:t,connected:r,onConnect:s}){return e.jsx(Ue,{className:`relative transition-shadow ${t.available?"hover:shadow-md":"opacity-60"}`,"data-testid":`provider-card-${t.id}`,children:e.jsxs(_e,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg flex items-center justify-center text-white font-bold text-sm",style:{backgroundColor:t.brandColor},children:t.name.slice(0,2).toUpperCase()}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-gray-900",children:t.name}),e.jsx("p",{className:"text-xs text-gray-500",children:t.tagline})]})]}),r>0&&e.jsxs(ie,{variant:"outline",className:"text-xs",children:[r," connected"]})]}),e.jsx("p",{className:"text-sm text-gray-600 mb-4 leading-relaxed",children:t.description}),t.available?e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(N,{size:"sm",onClick:()=>s(t),"data-testid":`connect-${t.id}`,children:[e.jsx(ns,{className:"h-4 w-4 mr-1"}),t.authMethod==="oauth2"?"Connect":"Add webhook"]}),t.setupHelpUrl&&e.jsxs("a",{href:t.setupHelpUrl,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-blue-600 hover:underline flex items-center",children:["Setup guide ",e.jsx(aa,{className:"h-3 w-3 ml-1"})]})]}):e.jsx("div",{children:e.jsx(ie,{variant:"outline",className:"text-gray-500",children:"Coming soon"})})]})})}function dx({provider:t,onCreated:r,onCancel:s}){const{toast:i}=Ss(),l=kd({resolver:Pd(ox),defaultValues:{displayName:t.name,targetUrl:"",events:t.defaultEvents,apiKey:""}}),c=Ne({mutationFn:async g=>await(await ue("POST","/api/integrations/webhook",{provider:t.id,displayName:g.displayName||t.name,targetUrl:g.targetUrl,events:g.events,apiKey:g.apiKey||void 0})).json(),onSuccess:g=>{i({title:"Integration created",description:"We will sign every event with HMAC-SHA256."}),z.invalidateQueries({queryKey:["/api/integrations"]}),r((g==null?void 0:g.signingSecret)||"")},onError:g=>{i({title:"Could not create integration",description:(g==null?void 0:g.message)||"Please try again",variant:"destructive"})}}),d=g=>c.mutate(g),u=nx[t.id];return e.jsx(Fd,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(d),className:"space-y-4",children:[u&&e.jsxs("div",{className:"rounded-md border bg-blue-50 dark:bg-blue-950 p-3 text-xs space-y-2",children:[e.jsxs("div",{className:"font-semibold flex items-center gap-1",children:[e.jsx(Ya,{className:"h-3 w-3"})," Quick recipe for ",t.name]}),e.jsx("ol",{className:"list-decimal pl-4 space-y-1 text-gray-700 dark:text-gray-300",children:u.steps.map((g,f)=>e.jsx("li",{children:g},f))}),e.jsx("pre",{className:"bg-white dark:bg-gray-900 border rounded p-2 overflow-x-auto whitespace-pre text-[11px]",children:u.snippet}),e.jsx(N,{type:"button",size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>{navigator.clipboard.writeText(u.snippet).catch(()=>{}),i({title:"Copied recipe to clipboard"})},"data-testid":"copy-recipe",children:"Copy snippet"})]}),e.jsx($r,{control:l.control,name:"displayName",render:({field:g})=>e.jsxs(Kr,{children:[e.jsx(Ur,{children:"Display name"}),e.jsx(In,{children:e.jsx(Ee,{...g,placeholder:t.name,"data-testid":"input-display-name"})}),e.jsx(_r,{})]})}),e.jsx($r,{control:l.control,name:"targetUrl",render:({field:g})=>e.jsxs(Kr,{children:[e.jsx(Ur,{children:"Webhook URL"}),e.jsx(In,{children:e.jsx(Ee,{...g,placeholder:"https://hooks.example.com/abc123","data-testid":"input-target-url"})}),e.jsx(_r,{})]})}),e.jsx($r,{control:l.control,name:"apiKey",render:({field:g})=>e.jsxs(Kr,{children:[e.jsx(Ur,{children:"Header API key (optional)"}),e.jsx(In,{children:e.jsx(Ee,{...g,type:"password",placeholder:"Optional shared-secret header","data-testid":"input-api-key"})}),e.jsx(_r,{})]})}),e.jsx($r,{control:l.control,name:"events",render:({field:g})=>e.jsxs(Kr,{children:[e.jsx(Ur,{children:"Events to forward"}),e.jsx("div",{className:"space-y-2 border rounded-md p-3",children:wi.map(f=>{var F;const C=(F=g.value)==null?void 0:F.includes(f);return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(xe,{className:"text-sm",htmlFor:`evt-${f}`,children:[e.jsx("span",{className:"font-mono text-xs text-gray-500 mr-2",children:f}),ic[f]]}
239),e.jsx(xs,{id:`evt-${f}`,checked:!!C,onCheckedChange:w=>{const j=g.value||[];g.onChange(w?Array.from(new Set([...j,f])):j.filter(E=>E!==f))},"data-testid":`event-toggle-${f}`})]},f)})}),e.jsx(_r,{})]})}),e.jsx("p",{className:"text-xs text-gray-500",children:t.helpText}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(N,{type:"button",variant:"outline",onClick:s,"data-testid":"button-cancel-webhook",children:"Cancel"}),e.jsx(N,{type:"submit",disabled:c.isPending,"data-testid":"button-create-webhook",children:c.isPending?"Creating...":"Create integration"})]})]})})}const ma="__unmapped__";function oc({integrationId:t,config:r,initialMapping:s,refreshing:i,onRefresh:l}){const{toast:c}=Ss(),[d,u]=o.useState(()=>{const T={};for(const J of r.scopes)T[J.id]={...s[J.id]||{}};return T}),[g,f]=o.useState(!1);o.useEffect(()=>{u(()=>{const T={};for(const J of r.scopes)T[J.id]={...s[J.id]||{}};return T})},[s,r.scopes]);const C=Ne({mutationFn:async()=>await(await ue("PATCH",`/api/integrations/${t}/${r.apiSegment}/mapping`,d)).json(),onSuccess:()=>{c({title:"Mapping saved",description:`Future ${r.providerLabel} pushes will use these fields.`}),z.invalidateQueries({queryKey:["/api/integrations",t,r.apiSegment,"fields"]}),z.invalidateQueries({queryKey:["/api/integrations"]})},onError:T=>{c({title:"Save failed",description:T==null?void 0:T.message,variant:"destructive"})}}),[F,w]=o.useState(null),j=Ne({mutationFn:async()=>await(await ue("POST",`/api/integrations/${t}/${r.apiSegment}/mapping/test`,{mapping:d})).json(),onSuccess:T=>{w(T);const J=T.scopes.reduce((v,y)=>v+y.issues.filter(k=>k.severity==="error").length,0),p=T.scopes.reduce((v,y)=>v+y.issues.filter(k=>k.severity==="warning").length,0);T.ok&&p===0?c({title:"Mapping looks good",description:`All ${r.providerLabel} fields validated.`}):c({title:T.ok?"Mapping has warnings":"Mapping has errors",description:`${J} error${J===1?"":"s"}, ${p} warning${p===1?"":"s"}. Save still allowed.`,variant:T.ok?"default":"destructive"})},onError:T=>{c({title:"Test failed",description:T==null?void 0:T.message,variant:"destructive"})}}),E=Ne({mutationFn:async()=>await(await ue("DELETE",`/api/integrations/${t}/${r.apiSegment}/mapping`)).json(),onSuccess:()=>{c({title:"Reset to defaults",description:r.resetDescription}),w(null);const T={};for(const J of r.scopes)T[J.id]={};u(T),z.invalidateQueries({queryKey:["/api/integrations",t,r.apiSegment,"fields"]}),z.invalidateQueries({queryKey:["/api/integrations"]})},onError:T=>{c({title:"Reset failed",description:T==null?void 0:T.message,variant:"destructive"})}}),A=T=>{const J=r.smbFields.filter($=>$.scope===T.id),p=T.fields.filter($=>$.editable).slice();p.sort(($,X)=>$.isCustom!==X.isCustom?$.isCustom?-1:1:$.name.localeCompare(X.name));const v=d[T.id]||{},y=F==null?void 0:F.scopes.find($=>$.scope===T.id),k=(y==null?void 0:y.issues.filter($=>$.severity==="error").length)||0,a=(y==null?void 0:y.issues.filter($=>$.severity==="warning").length)||0,q=new Map;if(y)for(const $ of y.issues){if(!$.smbFieldId)continue;const X=q.get($.smbFieldId)||[];X.push($),q.set($.smbFieldId,X)}return e.jsxs("div",{className:"space-y-2","data-testid":`mapping-scope-${T.id}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-semibold capitalize",children:T.label}),y&&k>0&&e.jsxs(ie,{className:"bg-red-100 text-red-800 hover:bg-red-100","data-testid":`${r.testIdPrefix}-scope-badge-${T.id}-error`,children:[e.jsx(rr,{className:"h-3 w-3 mr-1"}),k," error",k===1?"":"s"]}),y&&a>0&&e.jsxs(ie,{className:"bg-orange-100 text-orange-800 hover:bg-orange-100","data-testid":`${r.testIdPrefix}-scope-badge-${T.id}-warn`,children:[e.jsx(ps,{className:"h-3 w-3 mr-1"}),a," warning",a===1?"":"s"]}),y&&k===0&&a===0&&e.jsxs(ie,{className:"bg-green-100 text-green-800 hover:bg-green-100","data-testid":`${r.testIdPrefix}-scope-badge-${T.id}-ok`,children:[e.jsx(da,{className:"h-3 w-3 mr-1"}),"OK"]})]}),e.jsx("div",{className:"space-y-2",children:J.map($=>{const X=v[$.id]||ma,B=q.get($.id)||[],K=B.some(Y=>Y.severity==="error"),ae=B.some(Y=>Y.severity==="warning");return e.jsxs("div",{className:`grid grid-cols-1 md:grid-cols-2 gap-2 items-start border rounded-md p-3 ${K?"border-red-300 bg-red-50":ae?"border-orange-300 bg-orange-50":""}`,"data-testid":`${r.testIdPrefix}-mapping-row-${$.id}`,children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:$.label}),e.jsx("div",{className:"text-xs text-gray-500 leading-snug",children:$.description}),B.map((Y,fe)=>e.jsxs("div",{className:`text-xs mt-1 ${Y.severity==="error"?"text-red-700":"text-orange-700"}`,"data-testid":`${r.testIdPrefix}-mapping-issue-${$.id}-${fe}`,children:[Y.severity==="error"?"Error: ":"Warning: ",Y.message]},fe))]}),e.jsx("div",{children:e.jsxs(Jt,{value:X,onValueChange:Y=>{w(null),u(fe=>{const U={...fe,[T.id]:{...fe[T.id]||{}}};return Y===ma?delete U[T.id][$.id]:U[T.id][$.id]=Y,U})},children:[e.jsx(Yt,{"data-testid":`${r.testIdPrefix}-mapping-select-${$.id}`,children:e.jsx(Qt,{placeholder:r.defaultBehaviorText})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:ma,children:r.defaultBehaviorText}),p.map(Y=>e.jsxs(Ie,{value:Y.key,children:[Y.name,Y.isCustom?" (custom)":""]},Y.key))]})]})})]},$.id)})})]})};return e.jsxs("div",{className:"space-y-5","data-testid":`${r.testIdPrefix}-field-mapping`,children:[e.jsx(Ue,{className:"bg-blue-50 border-blue-200",children:e.jsxs(_e,{className:"pt-3 pb-3 text-xs text-blue-900 leading-relaxed",children:["Pick which ",r.providerLabel," field should receive each SMB Sales Boost lead value. Anything left as ",e.jsxs("span",{className:"font-medium",children:['"',r.defaultBehaviorText,'"']})," still uses the standard SMB Sales Boost behavior. Field list cached at ",new Date(r.cachedAt).toLocaleStr
239ing(),"."]})}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(N,{size:"sm",variant:"outline",onClick:l,disabled:i,"data-testid":`${r.testIdPrefix}-fields-refresh`,children:[e.jsx(ba,{className:"h-4 w-4 mr-1"})," ",i?"Refreshing...":`Refresh fields from ${r.providerLabel}`]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(N,{size:"sm",variant:"outline",onClick:()=>f(!0),disabled:E.isPending,"data-testid":`${r.testIdPrefix}-mapping-reset`,children:"Reset to defaults"}),e.jsx(N,{size:"sm",variant:"outline",onClick:()=>j.mutate(),disabled:j.isPending,"data-testid":`${r.testIdPrefix}-mapping-test`,children:j.isPending?"Testing...":"Test mapping"}),e.jsx(N,{size:"sm",onClick:()=>C.mutate(),disabled:C.isPending,"data-testid":`${r.testIdPrefix}-mapping-save`,children:C.isPending?"Saving...":"Save mapping"})]})]}),F&&e.jsx(Ue,{className:F.ok?"border-green-200 bg-green-50":"border-red-200 bg-red-50","data-testid":`${r.testIdPrefix}-mapping-test-result`,children:e.jsxs(_e,{className:"pt-3 pb-3 text-xs space-y-2",children:[e.jsx("div",{className:"font-medium",children:F.ok?"Synthetic lead validated against your mapping.":"Mapping has errors. Save still allowed, but pushes may fail."}),F.scopes.map(T=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium",children:[T.label,":"]})," ",T.issues.length===0?"No issues.":`${T.issues.length} issue${T.issues.length===1?"":"s"}`,T.issues.filter(J=>!J.smbFieldId).map((J,p)=>e.jsxs("div",{className:J.severity==="error"?"text-red-700 ml-3":"text-orange-700 ml-3",children:[J.severity==="error"?"Error: ":"Warning: ",J.message]},p))]},T.scope))]})}),r.scopes.map(T=>e.jsx(o.Fragment,{children:A(T)},T.id)),e.jsx(pn,{open:g,onOpenChange:f,children:e.jsxs(xn,{children:[e.jsxs(hn,{children:[e.jsx(gn,{children:"Reset field mapping?"}),e.jsxs(yn,{children:["We'll clear your custom field mappings. ",r.resetDescription]})]}),e.jsxs(fn,{children:[e.jsx(oi,{children:"Cancel"}),e.jsx(bn,{onClick:()=>E.mutate(),children:"Reset"})]})]})})]})}function cc(t,r,s){const{toast:i}=Ss(),[l,c]=o.useState(!1),d=Ne({mutationFn:async()=>{c(!0);const u=await fetch(`/api/integrations/${t}/${r}/fields?refresh=1`,{credentials:"include"});if(!u.ok){const g=await u.json().catch(()=>({}));throw new Error((g==null?void 0:g.message)||"Failed to refresh fields")}return await u.json()},onSuccess:u=>{z.setQueryData(["/api/integrations",t,r,"fields"],u),i({title:`Fields refreshed from ${s}`})},onError:u=>{i({title:"Refresh failed",description:u==null?void 0:u.message,variant:"destructive"})},onSettled:()=>c(!1)});return{refreshing:l,refresh:()=>d.mutate()}}function mx({integrationId:t}){var J;const{toast:r}=Ss(),[s,i]=o.useState(!1),[l,c]=o.useState(null),[d,u]=o.useState(!1),g=Qe({queryKey:["/api/integrations",t,"pipedrive","fields"]});o.useEffect(()=>{var p,v;g.data&&l===null&&c({person:{...((p=g.data.mapping)==null?void 0:p.person)||{}},organization:{...((v=g.data.mapping)==null?void 0:v.organization)||{}}})},[g.data,l]);const f=Ne({mutationFn:async()=>{i(!0);const p=await fetch(`/api/integrations/${t}/pipedrive/fields?refresh=1`,{credentials:"include"});if(!p.ok){const v=await p.json().catch(()=>({}));throw new Error((v==null?void 0:v.message)||"Failed to refresh fields")}return await p.json()},onSuccess:p=>{var v,y;z.setQueryData(["/api/integrations",t,"pipedrive","fields"],p),w(null),c({person:{...((v=p.mapping)==null?void 0:v.person)||{}},organization:{...((y=p.mapping)==null?void 0:y.organization)||{}}}),r({title:"Fields refreshed from Pipedrive"})},onError:p=>{r({title:"Refresh failed",description:p==null?void 0:p.message,variant:"destructive"})},onSettled:()=>i(!1)}),C=Ne({mutationFn:async()=>{if(!l)throw new Error("No mapping to save");return await(await ue("PATCH",`/api/integrations/${t}/pipedrive/mapping`,l)).json()},onSuccess:()=>{r({title:"Mapping saved",description:"Future Pipedrive pushes will use these fields."}),z.invalidateQueries({queryKey:["/api/integrations",t,"pipedrive","fields"]}),z.invalidateQueries({queryKey:["/api/integrations"]})},onError:p=>{r({title:"Save failed",description:p==null?void 0:p.message,variant:"destructive"})}}),[F,w]=o.useState(null),j=Ne({mutationFn:async()=>
239{if(!l)throw new Error("No mapping to test");return await(await ue("POST",`/api/integrations/${t}/pipedrive/mapping/test`,{mapping:l})).json()},onSuccess:p=>{w(p);const v=p.scopes.reduce((k,a)=>k+a.issues.filter(q=>q.severity==="error").length,0),y=p.scopes.reduce((k,a)=>k+a.issues.filter(q=>q.severity==="warning").length,0);p.ok&&y===0?r({title:"Mapping looks good",description:"All Pipedrive fields validated."}):r({title:p.ok?"Mapping has warnings":"Mapping has errors",description:`${v} error${v===1?"":"s"}, ${y} warning${y===1?"":"s"}. Save still allowed.`,variant:p.ok?"default":"destructive"})},onError:p=>{r({title:"Test failed",description:p==null?void 0:p.message,variant:"destructive"})}}),E=Ne({mutationFn:async()=>await(await ue("DELETE",`/api/integrations/${t}/pipedrive/mapping`)).json(),onSuccess:()=>{r({title:"Reset to defaults",description:"Pipedrive pushes will fall back to the SMB Sales Boost note."}),w(null),c({person:{},organization:{}}),z.invalidateQueries({queryKey:["/api/integrations",t,"pipedrive","fields"]}),z.invalidateQueries({queryKey:["/api/integrations"]})},onError:p=>{r({title:"Reset failed",description:p==null?void 0:p.message,variant:"destructive"})}});if(g.isError)return e.jsx(Ue,{className:"border-red-200 bg-red-50",children:e.jsxs(_e,{className:"pt-4 pb-4 text-sm text-red-800",children:[e.jsx("p",{className:"font-medium",children:"Could not load Pipedrive fields."}),e.jsx("p",{className:"mt-1",children:((J=g.error)==null?void 0:J.message)||"Try again in a moment."}),e.jsxs(N,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>f.mutate(),disabled:s,"data-testid":"pipedrive-fields-retry",children:[e.jsx(ba,{className:"h-4 w-4 mr-1"})," Retry"]})]})});if(g.isLoading||!l)return e.jsx("p",{className:"text-sm text-gray-500",children:"Loading Pipedrive fields..."});const A=g.data,T=p=>{const v=A.smbFields.filter(B=>B.scope===p),y=(p==="person"?A.personFields:A.organizationFields).filter(B=>B.editable);y.sort((B,K)=>B.isCustom!==K.isCustom?B.isCustom?-1:1:B.name.localeCompare(K.name));const k=l[p],a=F==null?void 0:F.scopes.find(B=>B.scope===p),q=(a==null?void 0:a.issues.filter(B=>B.severity==="error").length)||0,$=(a==null?void 0:a.issues.filter(B=>B.severity==="warning").length)||0,X=new Map;if(a)for(const B of a.issues){if(!B.smbFieldId)continue;const K=X.get(B.smbFieldId)||[];K.push(B),X.set(B.smbFieldId,K)}return e.jsxs("div",{className:"space-y-2","data-testid":`mapping-scope-${p}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-semibold capitalize",children:p==="person"?"Person fields":"Organization fields"}),a&&q>0&&e.jsxs(ie,{className:"bg-red-100 text-red-800 hover:bg-red-100","data-testid":`pipedrive-scope-badge-${p}-error`,children:[e.jsx(rr,{className:"h-3 w-3 mr-1"}),q," error",q===1?"":"s"]}),a&&$>0&&e.jsxs(ie,{className:"bg-orange-100 text-orange-800 hover:bg-orange-100","data-testid":`pipedrive-scope-badge-${p}-warn`,children:[e.jsx(ps,{className:"h-3 w-3 mr-1"}),$," warning",$===1?"":"s"]}),a&&q===0&&$===0&&e.jsxs(ie,{className:"bg-green-100 text-green-800 hover:bg-green-100","data-testid":`pipedrive-scope-badge-${p}-ok`,children:[e.jsx(da,{className:"h-3 w-3 mr-1"}),"OK"]})]}),e.jsx("div",{className:"space-y-2",children:v.map(B=>{const K=k[B.id]||ma,ae=X.get(B.id)||[],Y=ae.some(U=>U.severity==="error"),fe=ae.some(U=>U.severity==="warning");return e.jsxs("div",{className:`grid grid-cols-1 md:grid-cols-2 gap-2 items-start border rounded-md p-3 ${Y?"border-red-300 bg-red-50":fe?"border-orange-300 bg-orange-50":""}`,"data-testid":`mapping-row-${B.id}`,children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:B.label}),e.jsx("div",{className:"text-xs text-gray-500 leading-snug",children:B.description}),ae.map((U,te)=>e.jsxs("div",{className:`text-xs mt-1 ${U.severity==="error"?"text-red-700":"text-orange-700"}`,"data-testid":`pipedrive-mapping-issue-${B.id}-${te}`,children:[U.severity==="error"?"Error: ":"Warning: ",U.message]},te))]}),e.jsx("div",{children:e.jsxs(Jt,{value:K,onValueChange:U=>{w(null),c(te=>{if(!te)return te;const ne={...te,[p]:{...te[p]}};return U===ma?delete ne[p][B.id]:ne[p][B.id]=U,ne})},children:[e.jsx(Yt,{"data-testid":`mapping-select-${B.id}`,children:e.jsx(Qt,{placeholder:"Send to SMB note (default)"})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:ma,children:"Send to SMB note (default)"}),y.map(U=>e.jsxs(Ie,{value:U.key,children:[U.name,U.isCustom?" (custom)":""]},U.key))]})]})})]},B.id)})})]})};
239return e.jsxs("div",{className:"space-y-5","data-testid":"pipedrive-field-mapping",children:[e.jsx(Ue,{className:"bg-blue-50 border-blue-200",children:e.jsxs(_e,{className:"pt-3 pb-3 text-xs text-blue-900 leading-relaxed",children:["Pick which Pipedrive Person or Organization custom field should receive each SMB Sales Boost lead value. Anything left as ",e.jsx("span",{className:"font-medium",children:'"Send to SMB note (default)"'})," still lands on the auto-created note. Field list cached at ",new Date(A.cachedAt).toLocaleString(),"."]})}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(N,{size:"sm",variant:"outline",onClick:()=>f.mutate(),disabled:s,"data-testid":"pipedrive-fields-refresh",children:[e.jsx(ba,{className:"h-4 w-4 mr-1"})," ",s?"Refreshing...":"Refresh fields from Pipedrive"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(N,{size:"sm",variant:"outline",onClick:()=>u(!0),disabled:E.isPending,"data-testid":"pipedrive-mapping-reset",children:"Reset to defaults"}),e.jsx(N,{size:"sm",variant:"outline",onClick:()=>j.mutate(),disabled:j.isPending,"data-testid":"pipedrive-mapping-test",children:j.isPending?"Testing...":"Test mapping"}),e.jsx(N,{size:"sm",onClick:()=>C.mutate(),disabled:C.isPending,"data-testid":"pipedrive-mapping-save",children:C.isPending?"Saving...":"Save mapping"})]})]}),F&&e.jsx(Ue,{className:F.ok?"border-green-200 bg-green-50":"border-red-200 bg-red-50","data-testid":"pipedrive-mapping-test-result",children:e.jsxs(_e,{className:"pt-3 pb-3 text-xs space-y-2",children:[e.jsx("div",{className:"font-medium",children:F.ok?"Synthetic lead validated against your mapping.":"Mapping has errors. Save still allowed, but pushes may fail."}),F.scopes.map(p=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium",children:[p.label,":"]})," ",p.issues.length===0?"No issues.":`${p.issues.length} issue${p.issues.length===1?"":"s"}`,p.issues.filter(v=>!v.smbFieldId).map((v,y)=>e.jsxs("div",{className:v.severity==="error"?"text-red-700 ml-3":"text-orange-700 ml-3",children:[v.severity==="error"?"Error: ":"Warning: ",v.message]},y))]},p.scope))]})}),T("person"),T("organization"),e.jsx(pn,{open:d,onOpenChange:u,children:e.jsxs(xn,{children:[e.jsxs(hn,{children:[e.jsx(gn,{children:"Reset field mapping?"}),e.jsx(yn,{children:"We'll clear your custom field mappings. Future Pipedrive pushes will fall back to the original SMB Sales Boost note behavior."})]}),e.jsxs(fn,{children:[e.jsx(oi,{children:"Cancel"}),e.jsx(bn,{onClick:()=>E.mutate(),children:"Reset"})]})]})})]})}function ux({integration:t}){var K,ae;const{toast:r}=Ss(),i=(t.metadata||{}).pipedriveDeals||{},[l,c]=o.useState(!!i.enabled),[d,u]=o.useState(typeof i.pipelineId=="number"?i.pipelineId:void 0),[g,f]=o.useState(typeof i.stageId=="number"?i.stageId:void 0),[C,F]=o.useState(i.defaultValue!=null?String(i.defaultValue):""),[w,j]=o.useState(typeof i.defaultCurrency=="string"?i.defaultCurrency:"USD"),[E,A]=o.useState(i.expectedCloseDays!=null?String(i.expectedCloseDays):""),[T,J]=o.useState(null),[p,v]=o.useState(!1),y=Qe({queryKey:["/api/integrations",t.id,"pipedrive/pipelines"]}),k=Qe({queryKey:["/api/integrations",t.id,"pipedrive","deal-fields"]});o.useEffect(()=>{k.data&&T===null&&J({...k.data.fieldMap||{}})},[k.data,T]);const a=Ne({mutationFn:async()=>{v(!0);const Y=await fetch(`/api/integrations/${t.id}/pipedrive/deal-fields?refresh=1`,{credentials:"include"});if(!Y.ok){const fe=await Y.json().catch(()=>({}));throw new Error((fe==null?void 0:fe.message)||"Failed to refresh deal fields")}return await Y.json()},onSuccess:Y=>{z.setQueryData(["/api/integrations",t.id,"pipedrive","deal-fields"],Y),J({...Y.fieldMap||{}}),r({title:"Deal fields refreshed from Pipedrive"})},onError:Y=>{r({title:"Refresh failed",description:Y==null?void 0:Y.message,variant:"destructive"})},onSettled:()=>v(!1)}),q=((K=y.data)==null?void 0:K.pipelines)||[],$=q.find(Y=>Y.id===d),X=($==null?void 0:$.stages)||[],B=Ne({mutationFn:async()=>{const Y={enabled:l,pipelineId:d,stageId:g,defaultValue:C?Number(C):0,defaultCurrency:w||"USD",expectedCloseDays:E?Number(E):0};return T!==null&&(Y.fieldMap=T),await(await ue("PATCH",`/api/integrations/${t.id}`,{pipedriveDeals:Y})).json()},onSuccess:()=>{r({title:"Pipedrive Deal settings saved"}),z.invalidateQueries({queryKey:["/api/integrations"]}),z.invalidateQueries({queryKey:["/api/integrations",t.id,"pipedrive","deal-fields"]})},onError:Y=>{r({title:"Save failed",description:Y==null?void 0:Y.message,variant:"destructive"})}});return e.jsx(Ue,{children:e.jsxs(_e,{className:"pt-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Create a Deal for every pushed lead"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"When enabled, after the Person and Organization are upserted we also create (or update) a Deal in your Pipedrive pipeline so the lead lands ready to work. Re-pushing the same SMB lead never creates duplicate Deals."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(xe,{className:"text-sm",htmlFor:"deals-enabled",children:"Enable Deal creation"}),e.jsx(xs,{id:"deals-enabled",checked:l,onCheckedChange:c,"data-testid":"toggle-deals-enabled"})]}),y.isLoading?e.jsx("p",{className:"text-sm text-gray-500",children:"Loading pipelines from Pipedrive..."}):y.isError?e.jsx("p",{className:"text-sm text-red-600",children:"Could not load pipelines from Pipedrive. Reconnect the integration if your token expired."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(xe,{className:"text-xs",children:"Pipeline"}),e.jsxs(Jt,{value:d?String(d):"",onValueChange:Y=>{const fe=Number(Y);u(fe),f(void 0)},children:[e.jsx(Yt,{"data-testid":"select-pipeline",children:e.jsx(Qt,{placeholder:"Pick a pipeline"})}),e.jsx(Gt,{children:q.map(Y=>e.jsxs(Ie,{value:String(Y.id),"data-testid":`pipeline-option-${Y.id}`,children:[Y.name,Y.active?"":" (inactive)"]},Y.id))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(xe,{className:"text-xs",children:"Stage"}),e.jsxs(Jt,{value:g?String(g):"",onValueChange:Y=>f(Number(Y)),disabled:!$,children:[e.jsx(Yt,{"data-testid":"select-stage",children:e.jsx(Qt,{placeholder:$?"Pick a stage":"Pick a pipeline first"})}),e.jsx(Gt,{children:X.map(Y=>e.jsx(Ie,{value:String(Y.id),"data-testid":`stage-option-${Y.id}`,children:Y.name},Y.id))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(xe,{className:"text-xs",children:"Default value (optional)"}),e.jsx(Ee,{type:"number",min:"0",value:C,onChange:Y=>F(Y.target.value),placeholder:"0","data-testid":"input-default-value"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(xe,{className:"text-xs",children:"Currency"}),e.jsx(Ee,{value:w,onChange:Y=>j(Y.target.value.toUpperCase().slice(0,8)),placeholder:"USD","data-testid":"input-default-currency"})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(xe,{className:"text-xs",children:"Expected close in N days (optional)"}),e.jsx(Ee,{type:"number",min:"0",value:E,onChange:Y=>A(Y.target.value),placeholder:"e.g. 30","data-testid":"input-expected-close-days"})]})]}),e.jsxs("div",{className:"border-t pt-4 space-y-3","data-testid":"deal-field-mapping",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Map SMB lead fields to Deal custom fields"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Wire any SMB lead attribute into one of your own Deal custom fields. Unmapped attributes are ignored."})]}),e.jsxs(N,{size:"sm",variant:"outline",onClick:()=>a.mutate(),disabled:p,"data-testid":"deal-fields-refresh",children:[e.jsx(ba,{className:"h-4 w-4 mr-1"}),p?"Refreshing...":"Refresh"]})]}),k.isError?e.jsxs("p",{className:"text-sm text-red-600",children:["Could not load Deal fields from Pipedrive: ",((ae=k.error)==null?void 0:ae.message)||"try again","."]}):k.isLoading||!T||!k.data?e.jsx("p",{className:"text-sm text-gray-500",children:"Loading Deal fields..."}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["Field list cached at ",new Date(k.data.cachedAt).toLocaleStr
239ing(),"."]}),e.jsx("div",{className:"space-y-2",children:k.data.smbFields.map(Y=>{const fe=k.data.dealFields.filter(te=>te.editable).slice().sort((te,ne)=>te.isCustom!==ne.isCustom?te.isCustom?-1:1:te.name.localeCompare(ne.name)),U=T[Y.id]||ma;return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2 items-start border rounded-md p-3","data-testid":`deal-mapping-row-${Y.id}`,children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:Y.label}),e.jsx("div",{className:"text-xs text-gray-500 leading-snug",children:Y.description})]}),e.jsx("div",{children:e.jsxs(Jt,{value:U,onValueChange:te=>{J(ne=>{const Q={...ne||{}};return te===ma?delete Q[Y.id]:Q[Y.id]=te,Q})},children:[e.jsx(Yt,{"data-testid":`deal-mapping-select-${Y.id}`,children:e.jsx(Qt,{placeholder:"Not mapped"})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:ma,children:"Not mapped"}),fe.map(te=>e.jsxs(Ie,{value:te.key,children:[te.name,te.isCustom?" (custom)":""]},te.key))]})]})})]},Y.id)})})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(N,{onClick:()=>B.mutate(),disabled:B.isPending||l&&(!d||!g),"data-testid":"button-save-deals",children:B.isPending?"Saving...":"Save Deal settings"})})]})})}function px({integrationId:t}){var d,u,g;const r=Qe({queryKey:["/api/integrations",t,"hubspot","fields"]}),{refreshing:s,refresh:i}=cc(t,"hubspot","HubSpot");if(r.isError)return e.jsx(Ue,{className:"border-red-200 bg-red-50",children:e.jsxs(_e,{className:"pt-4 pb-4 text-sm text-red-800",children:[e.jsx("p",{className:"font-medium",children:"Could not load HubSpot fields."}),e.jsx("p",{className:"mt-1",children:((d=r.error)==null?void 0:d.message)||"Try again in a moment."}),e.jsxs(N,{size:"sm",variant:"outline",className:"mt-3",onClick:i,disabled:s,"data-testid":"hubspot-fields-retry",children:[e.jsx(ba,{className:"h-4 w-4 mr-1"})," Retry"]})]})});if(r.isLoading||!r.data)return e.jsx("p",{className:"text-sm text-gray-500",children:"Loading HubSpot fields..."});const l=r.data,c={providerLabel:"HubSpot",apiSegment:"hubspot",testIdPrefix:"hubspot",smbFields:l.smbFields,cachedAt:l.cac
239hedAt,defaultBehaviorText:"Use HubSpot default property",resetDescription:"Future HubSpot pushes will fall back to the standard contact and company properties.",scopes:[{id:"contact",label:"Contact properties",fields:l.contactFields},{id:"company",label:"Company properties",fields:l.companyFields}]};return e.jsx(oc,{integrationId:t,config:c,initialMapping:{contact:((u=l.mapping)==null?void 0:u.contact)||{},company:((g=l.mapping)==null?void 0:g.company)||{}},refreshing:s,onRefresh:i})}function xx({integrationId:t}){var d,u;const r=Qe({queryKey:["/api/integrations",t,"salesforce","fields"]}),{refreshing:s,refresh:i}=cc(t,"salesforce","Salesforce");if(r.isError)return e.jsx(Ue,{className:"border-red-200 bg-red-50",children:e.jsxs(_e,{className:"pt-4 pb-4 text-sm text-red-800",children:[e.jsx("p",{className:"font-medium",children:"Could not load Salesforce fields."}),e.jsx("p",{className:"mt-1",children:((d=r.error)==null?void 0:d.message)||"Try again in a moment."}),e.jsxs(N,{size:"sm",variant:"outline",className:"mt-3",onClick:i,disabled:s,"data-testid":"salesforce-fields-retry",children:[e.jsx(ba,{className:"h-4 w-4 mr-1"})," Retry"]})]})});if(r.isLoading||!r.data)return e.jsx("p",{className:"text-sm text-gray-500",children:"Loading Salesforce fields..."});const l=r.data,c={providerLabel:"Salesforce",apiSegment:"salesforce",testIdPrefix:"salesforce",smbFields:l.smbFields,cachedAt:l.cac
239hedAt,defaultBehaviorText:"Use Salesforce Lead default field",resetDescription:"Future Salesforce pushes will fall back to the standard Lead fields.",scopes:[{id:"lead",label:"Lead fields",fields:l.leadFields}]};return e.jsx(oc,{integrationId:t,config:c,initialMapping:{lead:((u=l.mapping)==null?void 0:u.lead)||{}},refreshing:s,onRefresh:i})}function hx({integration:t,onClose:r}){var T,J;const{toast:s}=Ss(),[i,l]=o.useState(!1),[c,d]=o.useState(t.subscriptions||[]),[u,g]=o.useState(null),f=Qe({queryKey:["/api/integrations",t.id,"deliveries"]}),C=Ne({mutationFn:async()=>await(await ue("PATCH",`/api/integrations/${t.id}`,{subscriptions:c.map(v=>({eventType:v.eventType,targetUrl:v.targetUrl,isActive:v.isActive,config:v.config}))})).json(),onSuccess:()=>{s({title:"Saved"}),z.invalidateQueries({queryKey:["/api/integrations"]}),z.invalidateQueries({queryKey:["/api/integrations",t.id,"deliveries"]})},onError:p=>{s({title:"Save failed",description:p==null?void 0:p.message,variant:"destructive"})}}),F=Ne({mutationFn:async()=>await(await ue("POST",`/api/integrations/${t.id}/test`,{})).json(),onSuccess:p=>{s({title:(p==null?void 0:p.status)==="success"?"Test event delivered":"Test event failed",description:(p==null?void 0:p.error)||`Status ${(p==null?void 0:p.statusCode)??"?"} in ${(p==null?void 0:p.latencyMs)??"?"} ms`,variant:(p==null?void 0:p.status)==="success"?"default":"destructive"}),z.invalidateQueries({queryKey:["/api/integrations",t.id,"deliveries"]}),z.invalidateQueries({queryKey:["/api/integrations"]})}}),w=Ne({mutationFn:async p=>await(await ue("POST",`/api/integrations/${t.id}/deliveries/${p}/retry`,{})).json(),onSuccess:p=>{s({title:(p==null?void 0:p.status)==="success"?"Retry delivered":"Retry failed",description:(p==null?void 0:p.error)||`Status ${(p==null?void 0:p.statusCode)??"?"}`,variant:(p==null?void 0:p.status)==="success"?"default":"destructive"}),z.invalidateQueries({queryKey:["/api/integrations",t.id,"deliveries"]}),z.invalidateQueries({queryKey:["/api/integrations"]})},onError:p=>{s({title:"Retry failed",description:p==null?void 0:p.message,variant:"destructive"})}}),j=Ne({mutationFn:async()=>await(await ue("PATCH",`/api/integrations/${t.id}`,{status:"connected"})).json(),onSuccess:()=>{s({title:"Re-enabled"}),z.invalidateQueries({queryKey:["/api/integrations"]})}}),E=Ne({mutationFn:async()=>await(await ue("DELETE",`/api/integrations/${t.id}`)).json(),onSuccess:()=>{s({title:"Integration removed"}),z.invalidateQueries({queryKey:["/api/integrations"]}),r()}}),A=(p,v)=>{d(y=>{var a;const k=y.findIndex(q=>q.eventType===p);if(k>=0){const q=[...y];return q[k]={...q[k],...v},q}return[...y,{id:0,eventType:p,targetUrl:((a=t.subscriptions[0])==null?void 0:a.targetUrl)||null,isActive:!0,...v}]})};return e.jsxs("div",{className:"space-y-6","data-testid":"integration-detail",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold",children:t.displayName||t.providerName}),e.jsx(lc,{status:t.status})]}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:[t.providerName," ⢠",t.authMethod==="oauth2"?"OAuth":"Webhook"]})]}),e.jsxs("div",{className:"flex gap-2",children:[t.status==="needs_attention"&&e.jsxs(N,{variant:"outline",size:"sm",onClick:()=>j.mutate(),disabled:j.isPending,"data-testid":"button-reenable",children:[e.jsx(ba,{className:"h-4 w-4 mr-1"})," Re-enable"]}),e.jsxs(N,{variant:"outline",size:"sm",onClick:()=>F.mutate(),disabled:F.isPending,"data-testid":"button-test-fire",children:[e.jsx(Ya,{className:"h-4 w-4 mr-1"})," Send test event"]}),e.jsxs(N,{variant:"destructive",size:"sm",onClick:()=>l(!0),"data-testid":"button-delete-integration",children:[e.jsx(Hs,{className:"h-4 w-4 mr-1"})," Remove"]})]})]}),e.jsxs(_n,{defaultValue:"events",children:[e.jsxs(zn,{children:[e.jsx(Vs,{value:"events","data-testid":"tab-events",children:"Events"}),e.jsx(Vs,{value:"deliveries","data-testid":"tab-deliveries",children:"Deliveries"}),t.provider==="pipedrive"&&e.jsxs(e.Fragment,{children:[e.jsx(Vs,{value:"deals","data-testid":"tab-deals",children:"Deals"}),e.jsx(Vs,{value:"mapping","data-testid":"tab-mapping",children:"Field mapping"})]}),(t.provider==="hubspot"||t.provider==="salesforce")&&e.jsx(Vs,{value:"mapping","data-testid":"tab-mapping",children:"Field mapping"}),e.jsx(Vs,{value:"info","data-testid":"tab-info",children:"Details"})]}),t.provider==="pipedrive"&&e.jsx(Us,{value:"deals",children:e.jsx(ux,{integration:t})}),e.jsxs(Us,{value:"events",className:"space-y-3",children:[wi.map(p=>{const v=c.find(y=>y.eventType===p);return e.jsx(Ue,{children:e.jsxs(_e,{className:"pt-4 pb-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:ic[p]}),e.jsx("p",{className:"text-xs text-gray-500 font-mono",children:p})]}),e.jsx(xs,{checked:!!(v!=null&&v.isActive),onCheckedChange:y=>A(p,{isActive:y}),"data-testid":`sub-toggle-${p}`})]}),t.authMethod!=="oauth2"&&(v==null?void 0:v.isActive)&&e.jsxs("div",{className:"mt-3",children:[e.jsx(xe,{className:"text-xs",children:"Target URL override (optional)"}),e.jsx(Ee,{value:v.targetUrl||"",onChange:y=>A(p,{targetUrl:y.target.value}),placeholder:"Inherit from default",className:"mt-1","data-testid":`sub-url-${p}`})]})]})},p)}),e.jsx("div",{className:"flex justify-end",children:e.jsx(N,{onClick:()=>C.mutate(),disabled:C.isPending,"data-testid":"button-save-events",children:C.isPending?"Saving...":"Save changes"})})]}),e.jsx(Us,{value:"deliveries",children:e.jsx(Ue,{children:e.jsx(_e,{className:"pt-4",children:f.isLoading?e.jsx("p",{className:"text-sm text-gray-500",children:"Loading deliveries..."}):(((T=f.data)==null?void 0:T.deliveries)||[]).length===0?e.jsx("p",{className:"text-sm text-gray-500",children:'No deliveries yet. Use "Send test event" above to verify the connection.'}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left border-b",children:[e.jsx("th",{className:"py-2 pr-4",children:"When"}),e.jsx("th",{className:"py-2 pr-4",children:"Event"}),e.jsx("th",{className:"py-2 pr-4",children:"Target"}),e.jsx("th",{className:"py-2 pr-4",children:"Status"}),e.jsx("th",{className:"py-2 pr-4",children:"HTTP"}),e.jsx("th",{className:"py-2 pr-4",children:"Attempts"}),e.jsx("th",{className:"py-2 pr-4",children:"Latency"}),e.jsx("th",{className:"py-2 pr-4 text-right",children:"Action"})]})}),e.jsx("tbody",{children:(((J=f.data)==null?void 0:J.deliveries)||[]).map(p=>{const v=u===p.id,y=p.targetUrl||"-",k=(p.provider||t.provider)==="pipedrive",a=p.mappingSummary,q=a?(a.personFieldsApplied||0)+(a.organizationFieldsApplied||0):0;let $=null,X="";k&&(a?q===0?($="defaults / note only",X=a.noteCreated?"No mapped custom fields applied. Lead details landed on the auto-created SMB note.":"No mapped custom fields applied and no note attached."):($=`mapped ${a.personFieldsApplied}p + ${a.organizationFieldsApplied}o`,X=`Applied ${a.personFieldsApplied} of ${a.personFieldsConfigured} mapped Person field(s) and ${a.organizationFieldsApplied} of ${a.organizationFieldsConfigured}
239 mapped Organization field(s).`+(a.noteCreated?" SMB note also attached.":"")):($="defaults / note only",X="No custom field mapping metadata recorded for this delivery."));const B=k&&p.status==="success",{personId:K,dealId:ae}=B?ix(p.responseBody):{},Y=B?lx(t.metadata):null;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"border-b last:border-0 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-900",onClick:()=>g(v?null:p.id),"data-testid":`delivery-row-${p.id}`,children:[e.jsx("td",{className:"py-2 pr-4 whitespace-nowrap",children:new Date(p.createdAt).toLocaleString()}),e.jsxs("td",{className:"py-2 pr-4 font-mono text-xs",children:[e.jsx("div",{children:p.eventType}),$&&e.jsx(ie,{variant:"outline",className:"mt-1 font-normal text-[10px] px-1.5 py-0 leading-tight",title:X,"data-testid":`delivery-mapping-${p.id}`,children:$})]}),e.jsx("td",{className:"py-2 pr-4 font-mono text-xs max-w-[220px]",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"ph-no-capture truncate",title:y,children:y}),Y&&K&&e.jsxs("a",{href:`${Y}/person/${K}`,target:"_blank",rel:"noopener noreferrer",onClick:fe=>fe.stopPropagation(),className:"inline-flex items-center text-blue-600 hover:text-blue-800 dark:text-blue-400 whitespace-nowrap",title:"Open Person in Pipedrive","data-testid":`pipedrive-person-link-${p.id}`,children:[e.jsx(aa,{className:"h-3 w-3 mr-0.5"}),"Person"]}),Y&&ae&&e.jsxs("a",{href:`${Y}/deal/${ae}`,target:"_blank",rel:"noopener noreferrer",onClick:fe=>fe.stopPropagation(),className:"inline-flex items-center text-blue-600 hover:text-blue-800 dark:text-blue-400 whitespace-nowrap",title:"Open Deal in Pipedrive","data-testid":`pipedrive-deal-link-${p.id}`,children:[e.jsx(aa,{className:"h-3 w-3 mr-0.5"}),"Deal"]})]})}),e.jsx("td",{className:"py-2 pr-4",children:p.status==="success"?e.jsx(ie,{className:"bg-green-100 text-green-800",children:"success"}):e.jsx(ie,{variant:"destructive",children:p.status})}),e.jsx("td",{className:"py-2 pr-4",children:p.statusCode??"-"}),e.jsx("td",{className:"py-2 pr-4",children:p.attemptCount}),e.jsxs("td",{className:"py-2 pr-4",children:[p.latencyMs??"-"," ms"]}),e.jsx("td",{className:"py-2 pr-4 text-right",children:e.jsxs(N,{size:"sm",variant:"outline",className:"h-7 px-2 text-xs",disabled:w.isPending,onClick:fe=>{fe.stopPropagation(),w.mutate(p.id)},"data-testid":`retry-delivery-${p.id}`,children:[e.jsx(ba,{className:"h-3 w-3 mr-1"}),"Retry"]})})]}),v&&e.jsx("tr",{className:"border-b last:border-0 bg-gray-50 dark:bg-gray-900",children:e.jsx("td",{colSpan:8,className:"py-2 px-4 text-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Target URL:"})," ",e.jsx("span",{className:"ph-no-capture font-mono break-all",children:y})]}),p.errorMessage&&e.jsxs("div",{className:"text-red-600 dark:text-red-400",children:[e.jsx("span",{className:"text-gray-500",children:"Error:"})," ",p.errorMessage]}),e.jsx("div",{className:"text-gray-500",children:"Response body:"}),e.jsx("pre",{className:"bg-white dark:bg-gray-950 border rounded p-2 max-h-48 overflow-auto whitespace-pre-wrap break-all text-[11px]",children:typeof p.responseBody=="string"&&p.responseBody.length>0?p.responseBody:"(empty)"})]})})})]},p.id)})})]})})})})}),t.provider==="pipedrive"&&e.jsx(Us,{value:"mapping",children:e.jsx(mx,{integrationId:t.id})}),t.provider==="hubspot"&&e.jsx(Us,{value:"mapping",children:e.jsx(px,{integrationId:t.id})}),t.provider==="salesforce"&&e.jsx(Us,{value:"mapping",children:e.jsx(xx,{integrationId:t.id})}),e.jsx(Us,{value:"info",children:e.jsx(Ue,{children:e.jsxs(_e,{className:"pt-4 space-y-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Provider: "}),t.providerName]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Auth: "}),t.authMethod]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"External account: "}),t.externalAccountId||"-"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Last success: "}
239),t.lastSuccessAt?new Date(t.lastSuccessAt).toLocaleString():"never"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Last failure: "}),t.lastFailureAt?new Date(t.lastFailureAt).toLocaleString():"never"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Consecutive failures: "}),t.consecutiveFailures]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Token expires: "}),t.tokenExpiresAt?new Date(t.tokenExpiresAt).toLocaleString():"n/a"]})]})})})]}),e.jsx(pn,{open:i,onOpenChange:l,children:e.jsxs(xn,{children:[e.jsxs(hn,{children:[e.jsx(gn,{children:"Remove this integration?"}),e.jsx(yn,{children:"We will stop forwarding events to this destination. You can reconnect at any time."})]}),e.jsxs(fn,{children:[e.jsx(oi,{children:"Cancel"}),e.jsx(bn,{onClick:()=>E.mutate(),className:"bg-red-600 hover:bg-red-700",children:"Remove"})]})]})})]})}function gx(){var j,E,A,T,J;const{toast:t}=Ss(),{data:r}=Qe({queryKey:["/api/auth/user"]}),s=!!(r!=null&&r.isAdmin||r!=null&&r.isSubscribed&&rx.includes((r==null?void 0:r.subscriptionPlan)||""));o.useEffect(()=>{if(typeof window>"u")return;const p=new URLSearchParams(window.location.search),v=["hubspot","salesforce","pipedrive"];let y=!1;for(const k of v){p.get(`${k}_connected`)==="1"&&(t({title:`${k[0].toUpperCase()}${k.slice(1)} connected`,description:"Auto-push of new and updated leads is now active."}),p.delete(`${k}_connected`),y=!0,z.invalidateQueries({queryKey:["/api/integrations"]}));const a=p.get(`${k}_error`);a&&(t({title:`${k[0].toUpperCase()}${k.slice(1)} connection failed`,description:a,variant:"destructive"}),p.delete(`${k}_error`),y=!0)}if(y){const k=p.toString(),a=window.location.pathname+(k?`?${k}`:"")+window.location.hash;window.history.replaceState({},"",a)}},[t]);const i=Qe({queryKey:["/api/integrations/providers"],enabled:s}),l=Qe({queryKey:["/api/integrations"],enabled:s}),[c,d]=o.useState(null),[u,g]=o.useState(null),[f,C]=o.useState(null);if(!s)return e.jsx(Ue,{children:e.jsxs(_e,{className:"py-12 text-center space-y-3",children:[e.jsx(wr,{className:"h-10 w-10 mx-auto text-gray-400"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Integrations are a paid feature"}),e.jsx("p",{className:"text-sm text-gray-600 max-w-md mx-auto",children:"Upgrade to any paid plan to connect HubSpot, Salesforce, Pipedrive, Zapier, n8n, Make, Pipedream, Clay, and any custom webhook to your SMB Sales Boost workflows."})]})});const F=async p=>{if(p.authMethod==="oauth2"){try{const v=await fetch(`/api/integrations/${p.id}/start`,{credentials:"include"});if(!v.ok){const k=await v.json().catch(()=>({}));alert((k==null?void 0:k.message)||`Cannot start ${p.name} OAuth`);return}const y=await v.json();y!=null&&y.url&&(window.open(y.url,"_blank","noopener")||(window.location.href=y.url))}catch(v){alert(`Cannot start ${p.name} OAuth: ${v==null?void 0:v.message}`)}return}d(p)},w=(((j=l.data)==null?void 0:j.integrations)||[]).reduce((p,v)=>{var y;return(p[y=v.provider]||(p[y]=[])).push(v),p},{});return e.jsxs("div",{className:"space-y-8","data-testid":"integrations-tab",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(wr,{className:"h-6 w-6"})," Integrations"]}),e.jsx("p",{className:"text-sm text-gray-600 mt-1 max-w-3xl",children:'Stream events from SMB Sales Boost into your CRM, automation tools, and custom endpoints. Webhooks are signed with HMAC-SHA256 (X-SMB-Signature header) and retried with exponential backoff up to 5 times before flipping to "Action needed".'})]}),(((E=l.data)==null?void 0:E.integrations)||[]).filter(p=>p.status==="needs_attention").length>0&&e.jsx(Ue,{className:"border-orange-300 bg-orange-50",children:e.jsxs(_e,{className:"pt-4 pb-4 flex items-start gap-3",children:[e.jsx(ps,{className:"h-5 w-5 text-orange-600 mt-0.5"}),e.jsxs("div",{className:"text-sm text-orange-900",children:[e.jsx("p",{className:"font-medium",children:"One or more integrations need attention."}),e.jsx("p",{children:'We paused delivery after repeated failures. Open the integration below, fix the destination, then click "Re-enable".'})]})]})}),(((A=l.data)==null?void 0:A.integrations)||[]).length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-3",children:"Connected"}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:(((T=l.data)==null?void 0:T.integrations)||[]).map(p=>e.jsx(Ue,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>C(p),"data-testid":`integration-row-${p.id}`,children:e.jsxs(_e,{className:"pt-4 pb-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(zd,{className:"h-5 w-5 text-gray-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:p.displayName||p.providerName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[p.providerName," ⢠",p.subscriptions.filter(v=>v.isActive).length," active events"]})]})]}),e.jsx(lc,{status:p.status})]})},p.id))})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-3",children:"Available providers"}),i.isLoading?e.jsx("p",{className:"text-sm text-gray-500",children:"Loading providers..."}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:(((J=i.data)==null?void 0:J.providers)||[]).map(p=>e.jsx(cx,{provider:p,connected:(w[p.id]||[]).length,onConnect:F}
239,p.id))})]}),e.jsx(Ue,{className:"bg-gray-50",children:e.jsxs(_e,{className:"pt-4 pb-4 text-xs text-gray-600 leading-relaxed",children:[e.jsx("p",{className:"font-medium text-gray-800 mb-1",children:"Verifying webhook signatures"}),e.jsxs("p",{children:["Each request includes ",e.jsx("code",{className:"px-1 py-0.5 bg-white rounded",children:"X-SMB-Signature: t=<timestamp>,v1=<hex>"}),". Compute ",e.jsx("code",{className:"px-1 py-0.5 bg-white rounded",children:'HMAC-SHA256(secret, <timestamp> + "." + rawBody)'})," and compare to ",e.jsx("code",{children:"v1"}),". We display the secret once, when you create the integration."]})]})}),e.jsx(Sl,{open:!!c,onOpenChange:p=>!p&&d(null),children:e.jsxs(Jn,{className:"sm:max-w-lg overflow-y-auto",children:[e.jsxs(Yn,{children:[e.jsxs(Qn,{children:["Connect ",c==null?void 0:c.name]}),e.jsx(nc,{children:c==null?void 0:c.helpText})]}),c&&e.jsx("div",{className:"mt-6",children:e.jsx(dx,{provider:c,onCancel:()=>d(null),onCreated:p=>{d(null),p&&g(p)}})})]})}),e.jsx(pn,{open:!!u,onOpenChange:p=>!p&&g(null),children:e.jsxs(xn,{children:[e.jsxs(hn,{children:[e.jsx(gn,{children:"Save your signing secret"}),e.jsx(yn,{children:"Use this to verify the X-SMB-Signature header on every event. We will not show it again."})]}),e.jsx("pre",{className:"ph-no-capture bg-gray-900 text-gray-100 p-3 rounded text-xs overflow-x-auto","data-testid":"signing-secret",children:u}),e.jsx(fn,{children:e.jsx(bn,{onClick:()=>g(null),children:"I have saved it"})})]})}),e.jsx(Sl,{open:!!f,onOpenChange:p=>!p&&C(null),children:e.jsxs(Jn,{className:"sm:max-w-2xl overflow-y-auto",children:[e.jsx(Yn,{children:e.jsx(Qn,{children:"Manage integration"})}),f&&e.jsx("div",{className:"mt-6",children:e.jsx(hx,{integration:f,onClose:()=>C(null)})})]})})]})}function dc(t){const r=[];let s=[],i="",l=!1;for(let c=0;c<t.length;c++){const d=t[c];if(l){d==='"'?t[c+1]==='"'?(i+='"',c++):l=!1:i+=d;continue}if(d==='"'&&i.length===0){l=!0;continue}if(d===","){s.push(i),i="";continue}if(d!=="\r"){if(d===` 240`){s.push(i),r.push(s),s=[],i="";continue}i+=d}}for((i.length>0||s.length>0)&&(s.push(i),r.push(s));r.length>0&&r[r.length-1].every(c=>c.trim()==="");)r.pop();return r}function yx(t,r=3){const s=dc(t);if(s.length===0)return{headers:[],sampleRows:[],rowCount:0};const[i,...l]=s;return{headers:i.map((c,d)=>c.trim()||`Column ${d+1}`),sampleRows:l.slice(0,r),rowCount:l.length}}function fx(t,r){const s=dc(t);return s.length<=1?[]:s.slice(1).map(i=>(i[r]??"").trim()).filter(i=>i.length>0)}function bx(t){const r=t.headers.findIndex(l=>/\b(url|website|site|domain|link|web)\b/i.test(l));if(r!==-1)return r;let s=0,i=0;for(let l=0;l<t.headers.length;l++){const d=t.sampleRows.map(u=>u[l]??"").filter(u=>/^(https?:\/\/)?[a-z0-9.-]+\.[a-z]{2,}/i.test(u.trim())).length;d>i&&(i=d,s=l)}return s}const Cl={queued:{label:"In Progress",tone:"bg-gray-100 text-gray-700",hint:"Waiting to start."},matching:{label:"In Progress",tone:"bg-blue-100 text-blue-700",hint:"Checking your URLs against our database."},scraping:{label:"In Progress",tone:"bg-blue-100 text-blue-700",hint:"Fetching the URLs we did not already have. This can take a few hours for a large list."},merging:{label:"In Progress",tone:"bg-blue-100 text-blue-700",hint:"Building your file."},delivering:{label:"In Progress",tone:"bg-blue-100 text-blue-700",hint:"Building your file."},completed:{label:"Finished",tone:"bg-green-100 text-green-700",hint:"Your file is ready. URLs we could not get data for are listed in it and cost nothing."},partial:{label:"Finished",tone:"bg-amber-100 text-amber-800",hint:"Your file is ready, but your credit limit stopped this run before the end of your list. You were only charged for what you received."},failed:{label:"Failed",tone:"bg-red-100 text-red-700",hint:"Something went wrong."}
240,cancelled:{label:"Cancelled",tone:"bg-gray-100 text-gray-700",hint:"This run was cancelled."}};function wx(t){return(t.creditsCharged||0)+(t.scrapeTenthsCharged||0)/10}function vx(){const{toast:t}=Ss(),r=ni(),s=o.useRef(null),[i,l]=o.useState("paste"),[c,d]=o.useState(""),[u,g]=o.useState(""),[f,C]=o.useState(""),[F,w]=o.useState(null),[j,E]=o.useState(0),[A,T]=o.useState(""),[J,p]=o.useState(100),[v,y]=o.useState("either"),[k,a]=o.useState(null),[q,$]=o.useState(!1),[X,B]=o.useState(!1),{data:K}=Qe({queryKey:["/api/enrichments/preferences"]}),{data:ae,isLoading:Y}=Qe({queryKey:["/api/enrichments/runs"],refetchInterval:15e3}),fe=(ae==null?void 0:ae.runs)??[],U=o.useMemo(()=>i==="paste"?c.split(/[\s,;]+/).map(I=>I.trim()).filter(Boolean):u?fx(u,j):[],[i,c,u,j]),ne=o.useMemo(()=>{const I=new Set;for(const re of U){const Pe=re.toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").split(/[/?#]/)[0];Pe&&I.add(Pe)}return[...I]},[U]).length,Q=k??(K==null?void 0:K.emailResults)??!0,V=(K==null?void 0:K.pricingWarningThreshold)??1e3,R=(K==null?void 0:K.maxUrls)??1e5,pe=ne>R,Se=48*1024*1024,Ze=I=>{if(!/\.csv$/i.test(I.name)){t({title:"Not a CSV",description:"Please upload a .csv file.",variant:"destructive"});return}if(I.size>Se){t({title:"File too large",description:`That file is ${(I.size/1024/1024).toFixed(0)} MB. Please split it, or paste the URL column directly.`,variant:"destructive"});return}const re=new FileReader;re.onload=()=>{const Pe=String(re.result??""),tt=yx(Pe);if(tt.headers.length===0){t({title:"Empty file",description:"That CSV has no rows.",variant:"destructive"});return}g(Pe),C(I.name),w(tt),E(bx(tt))},re.readAsText(I)},Me=Ne({mutationFn:async()=>{const I={databaseMatchPercent:J,contactTypes:v,emailResults:Q},re=Number(A);return A.trim()!==""&&Number.isFinite(re)&&re>0&&(I.maxCredits=Math.floor(re)),(await ue("POST","/api/enrichments/runs",{urls:U,options:I})).json()},onSuccess:I=>{t({title:"Enrichment started",description:`${I.urlCount} URL${I.urlCount===1?"":"s"} queued`+(I.duplicatesRemoved?` (${I.duplicatesRemoved} duplicate${I.duplicatesRemoved===1?"":"s"} removed)`:"")+". You can leave this page; we will have your file ready here when it is done."}),d(""),g(""),C(""),w(null),p(100),s.current&&(s.current.value=""),r.invalidateQueries({queryKey:["/api/enrichments/runs"]})},onError:I=>{t({title:"Could not start enrichment",description:I.message,variant:"destructive"})}}),He=Ne({mutationFn:async()=>(await ue("PATCH","/api/enrichments/preferences",{pricingAcknowledged:!0})).json(),onSuccess:()=>r.invalidateQueries({queryKey:["/api/enrichments/preferences"]})}),ee=()=>{if(!(U.length===0||pe)){if(ne>V&&!(K!=null&&K.pricingAcknowledged)){$(!0);return}Me.mutate()}},O=()=>{X&&He.mutate(),$(!1),Me.mutate()};return e.jsxs("div",{className:"space-y-6","data-testid":"enrichments-tab",children:[e.jsxs(Ue,{children:[e.jsxs(zt,{children:[e.jsx(Vt,{children:"Enrich a list of URLs"}),e.jsx(Mi,{children:"Paste your URLs or upload a CSV. We check each one against our database first, then fetch anything we do not already have. You pay 1 credit for a new database match, 0.1 credit for a live result, and nothing for a URL we have already sold you or got no data for. We never add the URLs you submit, or the results we find for them, to our lead database, which we keep curated so it stays clean and focused on high-quality leads."})]}),e.jsxs(_e,{className:"space-y-5",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(N,{type:"button",variant:i==="paste"?"default":"outline",onClick:()=>l("paste"),"data-testid":"button-mode-paste",children:[e.jsx(di,{className:"mr-2 h-4 w-4"})," Paste URLs"]}),e.jsxs(N,{type:"button",variant:i==="upload"?"default":"outline",onClick:()=>l("upload"),"data-testid":"button-mode-upload",children:[e.jsx(Ji,{className:"mr-2 h-4 w-4"})," Upload CSV"]})]}),i==="paste"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{htmlFor:"enrichment-urls",children:"URLs"}),e.jsx(Ma,{id:"enrichment-urls",rows:8,placeholder:`example.com 241https://another-example.com/about 242...`,value:c,onChange:I=>d(I.target.value),"data-testid":"textarea-urls"}),e.jsx("p",{className:"text-sm text-gray-500",children:"One per line, or separated by commas or spaces."})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("input",{ref:s,t
242ype:"file",accept:".csv",className:"hidden",onChange:I=>{var Pe;const re=(Pe=I.target.files)==null?void 0:Pe[0];re&&Ze(re)},"data-testid":"input-csv-file"}),e.jsxs(N,{type:"button",variant:"outline",onClick:()=>{var I;return(I=s.current)==null?void 0:I.click()},"data-testid":"button-choose-csv",children:[e.jsx(Ji,{className:"mr-2 h-4 w-4"}),f?`Replace ${f}`:"Choose a CSV file"]}),F&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{htmlFor:"enrichment-column",children:"Which column holds the URLs?"}),e.jsxs(Jt,{value:String(j),onValueChange:I=>E(Number(I)),children:[e.jsx(Yt,{id:"enrichment-column","data-testid":"select-url-column",children:e.jsx(Qt,{})}),e.jsx(Gt,{children:F.headers.map((I,re)=>{var Pe;return e.jsxs(Ie,{value:String(re),children:[I,(Pe=F.sampleRows[0])!=null&&Pe[re]?` - e.g. ${F.sampleRows[0][re].slice(0,40)}`:""]},re)})})]}),e.jsxs("p",{className:"text-sm text-gray-500",children:[F.rowCount," row",F.rowCount===1?"":"s"," in the file."]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{htmlFor:"enrichment-max-credits",children:"Maximum credits for this run"}),e.jsx(Ee,{id:"enrichment-max-credits",type:"number",min:1,placeholder:"All available credits",value:A,onChange:I=>T(I.target.value),"data-testid":"input-max-credits"}),e.jsx("p",{className:"text-xs text-gray-500",children:"Leave blank to use whatever you have."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{htmlFor:"enrichment-db-share",children:"Maximum share spent on database matches"}),e.jsxs(Jt,{value:String(J),onValueChange:I=>p(Number(I)),children:[e.jsx(Yt,{id:"enrichment-db-share","data-testid":"select-db-share",children:e.jsx(Qt,{})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"100",children:"100% (recommended)"}),e.jsx(Ie,{value:"75",children:"75%"}),e.jsx(Ie,{value:"50",children:"50%"}),e.jsx(Ie,{value:"25",children:"25%"}),e.jsx(Ie,{value:"0",children:"0%"})]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Anything left over is spent on live results. Matches you have already bought are always returned free, whatever this is set to."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{htmlFor:"enrichment-contact",children:"Minimum contact details"}),e.jsxs(Jt,{value:v,onValueChange:I=>y(I),children:[e.jsx(Yt,{id:"enrichment-contact","data-testid":"select-contact-types",children:e.jsx(Qt,{})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"either",children:"A phone number or an email (recommended)"}),e.jsx(Ie,{value:"phone",children:"At least a phone number"}),e.jsx(Ie,{value:"email",children:"At least an email"})]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Each result must have at least this. A business with both a phone number and an email always qualifies. You are only charged for results that qualify."})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx(xe,{htmlFor:"enrichment-email",className:"font-medium",children:"Email me the file when it is ready"}),e.jsx("p",{className:"text-xs text-gray-500",children:"It will always be downloadable here regardless."})]}),e.jsx(xs,{id:"enrichment-email",checked:Q,onCheckedChange:a,"data-testid":"switch-email-results"})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[e.jsx("div",{className:"text-sm text-gray-600","data-testid":"text-url-count",children:U.length===0?"No URLs yet.":e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium text-gray-900",children:ne.toLocaleString()})," unique URL",ne===1?"":"s",U.length!==ne&&` (${(U.length-ne).toLocaleString()} duplicate${U.length-ne===1?"":"s"} will be removed)`,pe&&e.jsxs("span",{className:"ml-2 text-red-600",children:["over the ",R.toLocaleString()," limit for one run"]})]})}),e.jsxs(N,{onClick:ee,disabled:U.length===0||pe||Me.isPending,"data-testid":"button-start-enrichment",children:[Me.isPending&&e.jsx(Ua,{className:"mr-2 h-4 w-4 animate-spin"}),"Start enrichment"]})]})]})]}),e.jsxs(Ue,{children:[e.jsxs(zt,{children:[e.jsx(Vt,{children:"Your enrichments"}
242),e.jsx(Mi,{children:"Runs keep going if you close this page. Come back any time to download a finished file."})]}),e.jsx(_e,{children:Y?e.jsxs("div",{className:"flex items-center gap-2 text-gray-500",children:[e.jsx(Ua,{className:"h-4 w-4 animate-spin"})," Loading..."]}):fe.length===0?e.jsx("p",{className:"text-sm text-gray-500","data-testid":"text-no-runs",children:"Nothing yet. Your first enrichment will appear here."}):e.jsxs(Nn,{children:[e.jsx(En,{children:e.jsxs(za,{children:[e.jsx(Ke,{children:"Started"}),e.jsx(Ke,{children:"URLs"}),e.jsx(Ke,{children:"Status"}),e.jsx(Ke,{children:"Results"}),e.jsx(Ke,{children:"Credits"}),e.jsx(Ke,{className:"text-right",children:"File"})]})}),e.jsx(Sn,{children:fe.map(I=>{const re=Cl[I.status]??Cl.queued;return e.jsxs(za,{"data-testid":`row-run-${I.id}`,children:[e.jsx(Fe,{className:"whitespace-nowrap",children:new Date(I.createdAt).toLocaleString()}),e.jsx(Fe,{children:I.inputUrlCount.toLocaleString()}),e.jsxs(Fe,{children:[e.jsx(ie,{className:re.tone,variant:"secondary",children:re.label}),e.jsx("p",{className:"mt-1 max-w-xs text-xs text-gray-500",children:re.hint}),I.errorMessage&&e.jsxs("p",{className:"mt-1 flex items-start gap-1 text-xs text-red-600",children:[e.jsx(tr,{className:"mt-0.5 h-3 w-3 shrink-0"}),I.errorMessage]})]}),e.jsxs(Fe,{className:"text-sm",children:[e.jsxs("div",{children:[I.deliveredMatchCount.toLocaleString()," from our database"]}),e.jsxs("div",{children:[I.deliveredScrapeCount.toLocaleString()," fetched live"]}),(I.skippedOverDbBudget>0||I.skippedOverScrapeBudget>0)&&e.jsxs("div",{className:"text-amber-700",children:[(I.skippedOverDbBudget+I.skippedOverScrapeBudget).toLocaleString()," left out by your credit limit"]}),(I.matchedNoContactCount??0)+(I.scrapedNoContactCount??0)>0&&e.jsxs("div",{className:"text-gray-500",children:[((I.matchedNoContactCount??0)+(I.scrapedNoContactCount??0)).toLocaleString()," without the contact details you asked for"]})]}),e.jsxs(Fe,{className:"whitespace-nowrap text-sm",children:[wx(I).toLocaleString(void 0,{maximumFractionDigits:1}),!I.deliveredAt&&e.jsx("span",{className:"text-gray-500",children:" so far"})]}),e.jsx(Fe,{className:"text-right",children:I.downloadReady?e.jsx(N,{asChild:!0,size:"sm",variant:"outline","data-testid":`button-download-${I.id}`,children:e.jsxs("a",{href:`/api/enrichments/runs/${I.id}/download`,children:[e.jsx(Qs,{className:"mr-2 h-4 w-4"})," Download"]})}):I.status==="completed"||I.status==="partial"?e.jsxs("span",{className:"text-xs text-gray-500",children:[e.jsx(da,{className:"mr-1 inline h-3 w-3"}),"Done"]}):e.jsx("span",{className:"text-xs text-gray-400",children:"Not ready"})})]},I.id)})})]})})]}),e.jsx(os,{open:q,onOpenChange:$,children:e.jsxs(cs,{"data-testid":"dialog-pricing",children:[e.jsxs(as,{children:[e.jsx(rs,{children:"How this run will be charged"}),e.jsx($s,{asChild:!0,children:e.jsxs("div",{className:"space-y-3 pt-2 text-sm text-gray-700",children:[e.jsxs("p",{children:["You are about to enrich ",ne.toLocaleString()," URLs. Here is what each one can cost:"]}),e.jsxs("ul",{className:"list-disc space-y-1 pl-5",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"1 credit"})," for a URL we already have and you have not bought before, including its buying signals and category enrichments."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"0.1 credit"})," for a URL we do not have and fetch live for you."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Nothing"})," for a URL you have already exported, one we got no data for, or one without the contact details you asked for."]})]}),e.jsx("p",{children:"We never spend more than your credit limit for this run, or more than you have. Anything we cannot pay for is listed in your file with a reason instead of being charged."})]})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ws,{id:"enrichment-dont-show",checked:X,onCheckedChange:I=>B(I===!0),"data-testid":"checkbox-dont-show-again"}),e.jsx(xe,{htmlFor:"enrichment-dont-show",className:"text-sm font-normal",children:"Do not show this again"})]}),e.jsxs(er,{children:[e.jsx(N,{variant:"outline",onClick:()=>$(!1),"data-testid":"button-pricing-cancel",children:"Cancel"}),e.jsx(N,{onClick:O,"data-testid":"button-pricing-confirm",children:"Start enrichment"})]})]})})]})}function kl({provider:t}){return t==="google"?e.jsxs("svg",{className:"h-5 w-5",viewBox:"0 0 24 24","aria-hidden":"true",children:[e.jsx("path",{d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z",fill:"#4285F4"}),e.jsx("path",{d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z",fill:"#34A853"}),e.jsx("path",{d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z",fill:"#FBBC05"}),e.jsx("path",{d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z",fill:"#EA4335"})]}
242):t==="facebook"?e.jsx(Gc,{className:"h-5 w-5 text-[#1877F2]"}):t==="linkedin_oidc"?e.jsx(Zc,{className:"h-5 w-5 text-[#0A66C2]"}):e.jsx(di,{className:"h-5 w-5 text-gray-400"})}function jx(){const{toast:t}=Ss(),[r,s]=o.useState(null),{data:i,isLoading:l,isError:c}=Qe({queryKey:["/api/auth/identities"],staleTime:300*1e3}),d=Ne({mutationFn:async f=>(s(f),sessionStorage.setItem("oauth_link_return","/dashboard?tab=settings"),sessionStorage.setItem("oauth_link_provider",f),sessionStorage.removeItem("oauth_intent"),(await ue("POST","/api/auth/link-oauth",{provider:f})).json()),onSuccess:f=>{if(f!=null&&f.url){window.location.href=f.url;return}s(null),t({title:"Could not connect",description:"Please try again in a moment.",variant:"destructive"})},onError:f=>{s(null),sessionStorage.removeItem("oauth_link_return"),sessionStorage.removeItem("oauth_link_provider");const C=String((f==null?void 0:f.message)||"");let F="Please try again, or contact [email protected]";const w=C.indexOf("{");if(w!==-1)try{const j=JSON.parse(C.slice(w));typeof(j==null?void 0:j.error)=="string"&&(F=j.error)}catch{}t({title:"Could not connect",description:F,variant:"destructive"}),ce("[SignInMethodsCard]","OAuth link failed",f)}}),u=(i==null?void 0:i.identities)||[],g=(i==null?void 0:i.connectable)||[];return e.jsxs(Ue,{className:"bg-white border-gray-200",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center space-x-2",children:[e.jsx(di,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{children:"Sign-in methods"})]})}),e.jsxs(_e,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Connect another way to sign in. The account stays the same, so a connected provider can use a different email address than your account email."}),l&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(Ua,{className:"h-4 w-4 animate-spin"}),"Loading your sign-in methods..."]}),c&&e.jsx("p",{className:"text-sm text-gray-500",children:"We could not load your sign-in methods right now. Please refresh the page."}),!l&&!c&&u.length>0&&e.jsx("div",{className:"space-y-2",children:u.map(f=>e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-gray-200 px-3 py-2","data-testid":`identity-${f.provider}`,children:[e.jsx(kl,{provider:f.provider}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:$i(f.provider)}),f.email&&e.jsx("p",{className:"truncate text-xs text-gray-500",children:f.email})]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs font-medium text-green-600",children:[e.jsx(sa,{className:"h-4 w-4"}),"Connected"]})]},`${f.provider}-${f.email||""}`))}),!l&&!c&&g.length>0&&e.jsx("div",{className:"space-y-2",children:g.map(f=>e.jsxs(N,{type:"button",variant:"outline",className:"w-full h-11 justify-start gap-3 border-2 border-gray-300 hover:bg-gray-50",disabled:d.isPending,onClick:()=>d.mutate(f),"data-testid":`button-connect-${f}`,children:[r===f&&d.isPending?e.jsx(Ua,{className:"h-5 w-5 animate-spin"}):e.jsx(kl,{provider:f}),e.jsxs("span",{className:"flex-1 text-center",children:["Connect ",$i(f)]})]},f))}),!l&&!c&&g.length===0&&u.length>0&&e.jsx("p",{className:"text-sm text-gray-500",children:"Every available sign-in method is already connected to this account."})]})]})}function Nx(t,r){const s=String((t==null?void 0:t.message)??"");if(!s)return r;const i=s.replace(/^\d{3}:\s*/,""),l=i.indexOf("{");if(l!==-1)try{const c=JSON.parse(i.slice(l));if(c&&typeof c.error=="string"&&c.error){const d=typeof c.detail=="string"?c.detail.trim():"";return d?`${c.error}: ${d}`:c.error}if(c&&typeof c.message=="string"&&c.message)return c.message}catch{}return i||r}const mc="/api/email-preferences",vi="One of our emails to this address was marked as spam, so product updates and offers cannot be turned back on here. Please contact [email protected] and we will help.",Ex="We could not turn these emails back on right now. Nothing was changed. Please try again later.",Sx="Too many changes to your email preferences. Please wait a few minutes and try again.",ks={cardTitle:"Email preferences",switchLabel:"Product updates and offers",switchHelp:"Turning this off never stops account and billing emails.",deliveryIssue:"Our recent emails to your address could not be delivered, so these emails are paused. If your address is correct, please contact [email protected].",loading:"Loading your email preferences",loadFailed:"We could not load your email preferences right now. Please refresh the page.",saveFailedTitle:"Could not save",saveFailed:"We could not save your email preference. Please try again in a moment.",turnedOffTitle:"Emails off",turnedOff:"You will no longer get product updates and offers. Account and billing emails are not affected.",turnedOnTitle:"Emails on",turnedOn:"You will get product updates and offers again.",savedTitle:"Preference saved"},Aa=[mc],Fl="email-pref-marketing",Pl="email-pref-marketing-help",Il="email-pref-spam",Tl="email-pref-delivery",Cx=new Set(["provider_unavailable","provider_failed"]),Al=new WeakMap;function kx(t){let r=Al.get(t);return r||(r={inFlight:!1,desired:null,confirmed:null},Al.set(t,r)),r}function Fx(t){const r=String((t==null?void 0:t.message)??""),s=/^(\d{3}):\s*([\s\S]*)$/.exec(r);if(!s)return{status:null,body:null};let i=null;try{const l=JSON.parse(s[2]);l&&typeof l=="object"&&(i=l)}catch{}return{status:Number(s[1]),body:i}}function Px(t,r,s){s.marketingEmails?s.deliveryIssue?t({title:ks.savedTitle,de
242scription:ks.deliveryIssue}):t({title:ks.turnedOnTitle,description:ks.turnedOn}):r&&s.resubscribeBlocked!==null?t({title:ks.saveFailedTitle,description:vi,variant:"destructive"}):t({title:ks.turnedOffTitle,description:ks.turnedOff})}function Ix(t,r){const{status:s,body:i}=Fx(r),l=typeof(i==null?void 0:i.error)=="string"&&i.error?i.error:null;if(s===409){t({title:ks.saveFailedTitle,description:Nx(r,vi),variant:"destructive"});return}if(s===429){t({title:ks.saveFailedTitle,description:Sx,variant:"destructive"});return}if((s===502||s===503)&&typeof(i==null?void 0:i.code)=="string"&&Cx.has(i.code)){t({title:ks.saveFailedTitle,description:l??Ex,variant:"destructive"});return}t({title:ks.saveFailedTitle,description:ks.saveFailed,variant:"destructive"}),ce("EmailPreferencesCard","Failed to update email preferences",r)}async function Tx(t,r,s){r.inFlight=!0;try{for(;r.desired!==null;){const i=r.desired;r.desired=null;try{const c=await(await ue("PUT",mc,{marketingEmails:i})).json(),d={marketingEmails:c.marketingEmails,resubscribeBlocked:c.resubscribeBlocked,deliveryIssue:c.deliveryIssue};r.confirmed=d,r.desired===null&&(t.setQueryData(Aa,d),Px(s,i,d))}catch(l){r.desired=null;const c=r.confirmed;c&&t.setQueryData(Aa,c),Ix(s,l);break}}}finally{r.inFlight=!1,t.invalidateQueries({queryKey:Aa})}}function Ax(){const t=ni(),{toast:r}=Ss(),{data:s,isPending:i}=Qe({queryKey:Aa});function l(u){const g=kx(t);g.inFlight||(g.confirmed=t.getQueryData(Aa)??null),t.cancelQueries({queryKey:Aa}),t.setQueryData(Aa,f=>f&&{...f,marketingEmails:u}),g.desired=u,g.inFlight||Tx(t,g,r)}const c=(s==null?void 0:s.resubscribeBlocked)==="spam_complaint",d=[Pl,c?Il:null,s!=null&&s.deliveryIssue?Tl:null].filter(Boolean).join(" ");return e.jsxs(Ue,{className:"bg-white border-gray-200","data-testid":"card-email-preferences",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center space-x-2",children:[e.jsx(_a,{className:"h-5 w-5"}),e.jsx("span",{children:ks.cardTitle})]})}),e.jsx(_e,{className:"space-y-3",children:s?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(xe,{htmlFor:Fl,className:"font-medium",children:ks.switchLabel}),e.jsx("p",{id:Pl,className:"text-sm text-gray-500","data-testid":"text-email-pref-help",children:ks.switchHelp})]}),e.jsx(xs,{id:Fl,className:"shrink-0",checked:s.marketingEmails,onCheckedChange:l,disabled:s.resubscribeBlocked!==null&&!s.marketingEmails,"aria-describedby":d,"data-testid":"switch-email-marketing"})]}),c&&e.jsx("p",{id:Il,className:"text-sm text-amber-700","data-testid":"text-email-pref-spam-complaint",children:vi}),s.deliveryIssue&&e.jsx("p",{id:Tl,className:"text-sm text-amber-700","data-testid":"text-email-pref-delivery-issue",children:ks.deliveryIssue})]}):i?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",role:"status","data-testid":"status-email-pref-loading",children:[e.jsx(Lt,{size:16}),e.jsx("span",{children:ks.loading})]}):e.jsx("p",{className:"text-sm text-gray-500","data-testid":"text-email-pref-load-error",children:ks.loadFailed})})]})}function Ia(t,r){const s=i=>r?`${r}/month`:i;switch(t){case"starter":return{name:"Starter Plan",price:s("$49/month")};case"growth":return{name:"Growth Plan",price:s("$149/month")};case"scale":return{name:"Scale Plan",price:s("$499/month")};case"pro":return{name:"Pro Plan (Legacy)",price:s("$299/month")};case"platinum":return{name:"Platinum Plan",price:s("$1,999/month")};case"enterprise":return{name:"Enterprise Plan",price:s("$4,999/month")};case"agency":return{name:"Agency Plan",price:s("$99/mo per client")};default:return{name:"No Active Plan",price:""}}}function Ll(t){switch(t){case"platinum":return{className:"bg-gradient-to-r from-purple-500 via-purple-600 to-purple-700 text-white text-xs hidden sm:flex shadow-lg shadow-purple-500/50 border-0",dotClass:"w-2 h-2 bg-purple-200 rounded-full animate-pulse mr-2"};case"enterprise":return{className:"bg-gradient-to-r from-blue-400 via-blue-500 to-cyan-500 text-white text-xs hidden sm:flex shadow-lg shadow-blue-400/50 border-0",dotClass:"w-2 h-2 bg-blue-100 rounded-full animate-pulse mr-2"};case"agency":return{className:"bg-gradient-to-r from-amber-500 via-amber-600 to-orange-600 text-white text-xs hidden sm:flex shadow-lg shadow-amber-500/50 border-0",dotClass:"w-2 h-2 bg-amber-200 rounded-full animate-pulse mr-2"};case"scale":return{className:"bg-gradient-to-r from-indigo-500 via-indigo-600 to-indigo-700 text-white text-xs hidden sm:flex shadow-lg shadow-indigo-500/50 border-0",dotClass:"w-2 h-2 bg-indigo-200 rounded-full animate-pulse mr-2"};case"growth":return{className:"bg-gradient-to-r from-teal-500 via-teal-600 to-teal-700 text-white text-xs hidden sm:flex shadow-lg shadow-teal-500/50 border-0",dotClass:"w-2 h-2 bg-teal-200 rounded-full animate-pulse mr-2"};case"starter":return{className:"bg-green-100 text-green-700 text-xs hidden sm:flex",dotClass:"w-2 h-2 bg-green-500 rounded-full animate-pulse mr-2"};case"pro":default:return{className:"bg-green-100 text-green-700 text-xs hidden sm:flex",dotClass:"w-2 h-2 bg-green-500 rounded-full animate-pulse mr-2"}}}function Fa(t){if(!t||t.websiteOptOut)return!1;if(t.websiteAnalysisStatus==="failed")return!0;
242if(t.websiteAnalysisStatus==="pending"&&t.websiteAnalysisStartedAt){const r=new Date(t.websiteAnalysisStartedAt).getTime(),s=Date.now(),i=300*1e3;return s-r>i}return!1}function uc(t){var r,s;if(!t||!t.type)return"Not set";switch(t.type){case"continental_usa":return"Mainland USA (48 states)";case"all_usa":return"All USA (50 states + territories)";case"specific_states":return`${((r=t.data)==null?void 0:r.length)||0} specific states`;case"specific_cities":return`${((s=t.data)==null?void 0:s.length)||0} specific cities`;default:return"Not set"}}const zs={starter:{name:"Starter",credits:500,price:49,overageRate:"$0.10"},growth:{name:"Growth",credits:2e3,price:149,overageRate:"$0.075"},scale:{name:"Scale",credits:1e4,price:499,overageRate:"$0.05"}},tn=["starter","growth","scale"];function Rl(t){if(!t)return null;const r=tn.indexOf(t);return r===-1||r>=tn.length-1?null:tn[r+1]}function Lx({user:t,accountStats:r,databaseSwitchStatus:s,upcomingBilling:i,isRescanningWebsite:l,websitePopupDismissed:c,websiteRescanTriggered:d,setWebsiteRescanTriggered:u,setPopupWebsiteInput:g,setPopupSelectedOption:f,setShowWebsiteAnalysisPopup:C,handleManageBilling:F,handleManageBillingPortal:w,handleOpenProfileDialog:j,handleOpenOnboardingSettings:E,handleDatabaseSwitch:A,handleRescanWebsite:T}){var es,Rs,bs,Ps,ms,Bt,he,_s,hs,us,Ms;const{toast:J}=Ss();ja();const p=ni(),{data:v}=Qe({queryKey:["/api/enrichments/preferences"]}),y=Ne({mutationFn:async n=>(await ue("PATCH","/api/enrichments/preferences",{emailResults:n})).json(),onSuccess:(n,b)=>{p.invalidateQueries({queryKey:["/api/enrichments/preferences"]}),J({title:b?"Emails on":"Emails off",description:b?"We will email your enrichment files when they are ready.":"Your files will still be downloadable from the Enrichments tab."})},onError:n=>{J({title:"Could not save",description:n.message,variant:"destructive"})}}),{data:k}=Qe({queryKey:["/api/me/temporary-credits"],enabled:!!t&&Ys(t==null?void 0:t.subscriptionPlan),staleTime:3e4}),[a,q]=o.useState(()=>Date.now());o.useEffect(()=>{const n=setInterval(()=>q(Date.now()),1e3);return()=>clearInterval(n)},[]);const $=yo(k==null?void 0:k.grants,a),X=o.useRef(null);o.useEffect(()=>{const n=X.current;n!==null&&$.length<n&&z.invalidateQueries({queryKey:["/api/me/temporary-credits"]}),X.current=$.length},[$.length]);const[B,K]=o.useState(!1),[ae,Y]=o.useState(500),[fe,U]=o.useState("500"),[te,ne]=o.useState(!1),[Q,V]=o.useState("credits"),[R,pe]=o.useState("200"),[Se,Ze]=o.useState("credits"),[Me,He]=o.useState("500"),[ee,O]=o.useState(!1),[I,re]=o.useState("dollars"),[Pe,tt]=o.useState("100"),[$e,W]=o.useState(!1),Le=Jl(t),ve=Le.isTrialing,Oe=oa(Le.trialEndsAt),vt=(i==null?void 0:i.formatted)||Yl(t==null?void 0:t.subscriptionPlan),[Rt,At]=o.useState(!1),[at,Je]=o.useState(null),[Te,Ct]=o.useState(!1),[lt,kt]=o.useState(null),[ft,qt]=o.useState(null),[et,Ot]=o.useState(null),Xe=(t==null?void 0:t.subscriptionPlan)||"",mt=Ba.includes(Xe),ut=mt&&Xc({subscriptionPlan:Xe,pendingDowngradeToPlan:t==null?void 0:t.pendingDowngradeToPlan,pendingDowngradeFromPlan:t==null?void 0:t.pendingDowngradeFromPlan})||Xe,ot=!ve&&mt&&ut!==Xe,St=((es=zs[(t==null?void 0:t.pendingDowngradeToPlan)||Xe])==null?void 0:es.name)||(t==null?void 0:t.pendingDowngradeToPlan)||Xe,Pt=((Rs=zs[ut])==null?void 0:Rs.name)||ut,it=(n,b=!ve)=>mt&&Ba.includes(n)?td({currentPlan:Xe,targetPlan:n,pendingDowngradeToPlan:b?t==null?void 0:t.pendingDowngradeToPlan:null,pendingDowngradeFromPlan:b?t==null?void 0:t.pendingDowngradeFromPlan:null}).kind:n===Xe?"same":Ba.indexOf(n)>Ba.indexOf(Xe)?"upgrade":"downgrade",{data:ze}=Qe({queryKey:["/api/subscription/status"],enabled:ot,retry:!1}),_t=typeof(ze==null?void 0:ze.currentPeriodEnd)=="number"?oa(ze.currentPeriodEnd*1e3):"",de=Math.max(0,(t==null?void 0:t.monthlyCreditsUsed)||0),gt=(n,b,h)=>{const L=Ki(n),_=Ui(n,t==null?void 0:t.monthlyCreditsUsed);return de>0?`${_.toLocaleString()} of ${L.toLocaleString()} trial credits left, then ${b.toLocaleString()}${h}`:`${L.toLocaleString()} trial credits, then ${b.toLocaleString()}${h}`},It=(()=>{if(!zs[Xe])return null;if(ve){const n=Rl(Xe);return n?{planId:n,kind:"upgrade"}:null}for(const n of Ba.slice(Ba.indexOf(Xe)+1)){const b=it(n);if(b==="upgrade"||b==="cancel_downgrade")return{planId:n,kind:b}}return null})(),Ge=(n,b)=>{Je(n),kt(ve?b:null),qt(null),Ot(null),Ct(!0)},Ce=()=>{Ct(!1),Je(null),kt(null),qt(null),Ot(null)},P=at?it(at,!lt):null,le=at&&((bs=zs[at])==null?void 0:bs.name)||"",De=!!lt&&!ve,st=De||!!et&&!et.retryable,Ft=()=>window.location.reload(),oe=Ne({mutationFn:async n=>{const b={targetPlan:n.targetPlan};return n.mode&&(b.mode=n.mode),(await ue("POST","/api/subscription/change-plan",b)).json()},onSuccess:n=>{const b={upgrade:"Plan Upgraded!",downgrade:"Plan Changed",trial_switch:"Trial Plan Switched",trial_activated:"Your Plan Is Active"};J(n!=null&&n.alreadyProcessed?{title:"Your Plan Is Active",description:"Your plan is already active."}:{title:b[n==null?void 0:n.changeType]||"Plan Changed",description:n==null?void 0:n.message}),qt(null),Ot(null),Ct(!1),At(!1),Je(null),kt(null),z.invalidateQueries({queryKey:["/api/auth/user"]}),z.invalidateQueries({queryKey:["/api/subscription/status"]}),z.invalidateQueries({queryKey:["/api/subscription/next-billing-amount"]})},onError:(n,b)=>{const h=_i(n);if(h.status===402&&h.error==="payment_declined"){qt(h.message||"Your payment method was declined, so your plan has not started. Your free trial is still active.");return}const L=sd(h,{trialMove:!!(b!=null&&b.mode)});if(L){Ot(L),z.invalidateQueries({queryKey:["/api/auth/user"]}),z.invalidateQueries({queryKey:["/api/subscription/status"]});return}J({title:"Error",description:h.message||(n==null?void 0:n.message)||"Failed to change plan. Please try again.",variant:"destructive"})}}),Ye=Ne({mutationFn:async n=>{const b=ad(),h={creditCount:n};return Object.keys(b).length>0&&(h.clickIds=b),(await ue("POST","/api/purchase-credits",h)).json()},onSuccess:n=>{J({title:"Credits Purchased!",description:n.message||`Successfully purchased ${n.creditsAdded} credits.`}),K(!1),z.invalidateQueries({queryKey:["/api/auth/user"]})},onError:n=>{const b=_i(n);J({title:"Purchase Failed",description:b.message||"Failed to purchase credits. Please try again.",variant:"destructive"})}}),pt=Qe({queryKey:["/api/auto-top-up"],enabled:!!t&&Ys(t==null?void 0:t.subscriptionPlan)});o.useEffect(()=>{if(pt.data){const n=pt.data;ne(n.enabled??!1),V(n.triggerType||"credits"),pe(String(n.triggerAmount||"200")),Ze(n.purchaseType||"credits"),He(String(n.purchaseAmount||"500")),O(!!(n.capType&&n.capAmount)),re(n.capType||"dollars"),tt(String(n.capAmount||"100")),W(!1)}},[pt.data]);const jt=Ne({mutationFn:async n=>(await ue("PATCH","/api/auto-top-up",n)).json(),onSuccess:()=>{J({title:"Auto Top-Up Updated",description:"Your auto top-up settings have been saved."}),W(!1),z.invalidateQueries({queryKey:["/api/auto-top-up"]}),z.invalidateQueries({queryKey:["/api/auth/user"]})},onError:n=>{J({title:"Error",description:(n==null?void 0:n.message)||"Failed to update auto top-up settings.",variant:"destructive"})}}),ye=()=>{const n={enabled:te};te&&(n.triggerType=Q,n.triggerAmount=parseFloat(R),n.purchaseType=Se,n.purchaseAmount=parseFloat(Me),ee?(n.capType=I,n.capAmount=parseFloat(Pe)):(n.capType=null,n.capAmount=null)),jt.mutate(n)},[Xt,rt]=o.useState(!1),[fs,Tt]=o.useState("dollars"),[yt,is]=o.use
242State("100"),[Dt,Ae]=o.useState(!1),bt=Qe({queryKey:["/api/overage-budget"],enabled:!!t&&Ys(t==null?void 0:t.subscriptionPlan)});o.useEffect(()=>{if(bt.data){const n=bt.data;rt(n.enabled??!1),Tt(n.budgetType||"dollars"),is(String(n.budgetAmount||"100")),Ae(!1)}},[bt.data]);const Nt=Ne({mutationFn:async n=>(await ue("PATCH","/api/overage-budget",n)).json(),onSuccess:()=>{J({title:"Overage Budget Updated",description:"Your overage budget settings have been saved."}),Ae(!1),z.invalidateQueries({queryKey:["/api/overage-budget"]}),z.invalidateQueries({queryKey:["/api/auth/user"]})},onError:n=>{J({title:"Error",description:(n==null?void 0:n.message)||"Failed to update overage budget settings.",variant:"destructive"})}}),ls=()=>{const n={enabled:Xt};Xt&&(n.budgetType=fs,n.budgetAmount=parseFloat(yt)),Nt.mutate(n)};return e.jsxs("div",{className:"space-y-6",children:[Fa(t)&&c&&!d&&e.jsx("div",{className:"p-4 rounded-lg border-2 border-orange-400 bg-orange-50",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ps,{className:"h-5 w-5 text-orange-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium text-orange-800",children:"Website Analysis Issue"}),e.jsxs("p",{className:"text-sm text-orange-700 mt-1",children:["We couldn't analyze your website (",(t==null?void 0:t.companyWebsite)||"not set","). Please choose one of the options below:"]}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-3",children:[e.jsxs(N,{size:"sm",variant:"outline",className:"border-orange-400 text-orange-700 hover:bg-orange-100",onClick:async()=>{u(!0),await T((t==null?void 0:t.companyWebsite)||"")},disabled:l,children:[l?e.jsx(Ks,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx(Ks,{className:"h-4 w-4 mr-1.5"}),"Retry Scan"]}),e.jsxs(N,{size:"sm",variant:"outline",className:"border-orange-400 text-orange-700 hover:bg-orange-100",onClick:()=>{g((t==null?void 0:t.companyWebsite)||""),f(2),C(!0)},children:[e.jsx(ri,{className:"h-4 w-4 mr-1.5"}),"Enter Correct Website"]}),e.jsx(N,{size:"sm",variant:"ghost",className:"text-orange-600 hover:bg-orange-100",onClick:async()=>{try{(await fetch("/api/website-opt-out",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({optOut:!0})})).ok&&(z.invalidateQueries({queryKey:["/api/auth/user"]}),J({title:"Preference Saved",description:"We'll skip website analysis for keyword generation."}))}catch(n){ce("dashboard","Failed to save no-website preference",n),J({title:"Error",description:"Failed to save preference. Please try again.",variant:"destructive"})}},children:"I don't have a website"})]})]})]})}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs(Ue,{className:"bg-white border-gray-200",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center space-x-2",children:[e.jsx(sn,{className:"h-5 w-5"}),e.jsx("span",{children:"Subscription"})]})}),e.jsxs(_e,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Current Plan"}),t!=null&&t.isSubscribed?e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{className:"font-semibold",children:[Ia(ot?ut:t==null?void 0:t.subscriptionPlan,i==null?void 0:i.formatted).name,!ve&&!ot&&(i==null?void 0:i.hasDiscount)&&(i==null?void 0:i.baseFormatted)&&e.jsxs("span",{className:"ml-2",children:[e.jsx("span",{className:"line-through text-gray-400 text-sm",children:i.baseFormatted}),e.jsx("span",{className:"ml-2 text-green-600",children:i.formatted}),e.jsx("span",{className:"text-sm",children:"/month"})]}),!ve&&!ot&&!(i!=null&&i.hasDiscount)&&(i==null?void 0:i.formatted)&&e.jsxs("span",{className:"ml-2 text-gray-900",children:[i.formatted,"/month"]})]}),ot&&e.jsxs("div",{className:"space-y-0.5","data-testid":"text-pending-downgrade-line",children:[e.jsxs("p",{className:"text-sm font-medium text-amber-700",children:["You are on ",Pt," until ",_t||"your next renewal",", then ",St,i!=null&&i.formatted?` at ${i.formatted}/month`:"","."]}),e.jsx("p",{className:"text-xs text-gray-600",children:"Your remaining credits expire when the change takes effect."})]}),ve&&e.jsx("p",{className:"text-sm font-medium text-blue-700","data-testid":"text-trial-plan-line",children:Oe?`Free trial until ${Oe}, then ${vt}/month`:`Free trial, then ${vt}/month`}),ve&&zs[(t==null?void 0:t.subscriptionPlan)||""]&&e.jsx(N,{size:"sm",variant:"outline",className:"mt-2",onClick:()=>Ge((t==null?void 0:t.subscriptionPlan)||"","activate_now"),"data-testid":"button-activate-now-current",children:"Start my plan now"}),(i==null?void 0:i.hasDiscount)&&((Ps=i==null?void 0:i.discount)==null?void 0:Ps.cyclesRemaining)!==null&&((ms=i==null?void 0:i.discount)==null?void 0:ms.cyclesRemaining)!==void 0&&e.jsxs("div",{className:"mt-2 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-gradient-to-r from-amber-100 to-yellow-100 border-2 border-amber-400",children:[e.jsx(Kt,{className:"h-3.5 w-3.5 text-amber-600"}),e.jsxs("span",{className:"text-xs font-medium text-amber-800",children:["Special discount ⢠",i.discount.cyclesRemaining," ",i.discount.cyclesRemaining===1?"month":"months"," remaining"]})]}),(i==null?void 0:i.hasDiscount)&&((Bt=i==null?void 0:i.discount)==null?void 0:Bt.type)==="forever"&&e.jsxs("div",{className:"mt-2 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-gradient-to-r from-amber-100 to-yellow-100 border-2 border-amber-400",children:[e.jsx(Kt,{className:"h-3.5 w-3.5 text-amber-600"}),e.jsx("span",{className:"text-xs font-medium text-amber-800",children:"Special discount ⢠Lifetime discount"})]}),(i==null?void 0:i.hasDiscount)&&((he=i==null?void 0:i.discount)==null?void 0:he.type)==="once"&&e.jsxs("div",{className:"mt-2 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-gradient-to-r from-amber-100 to-yellow-100 border-2 border-amber-400","data-testid":"badge-one-time-discount",children:[e.jsx(Kt,{className:"h-3.5 w-3.5 text-amber-600"}),e.jsx("span",{className:"text-xs font-medium text-amber-800",children:i.amount===0?"Your next charge is covered, then billing resumes as normal":"Special discount ⢠Applies to your next charge only"})]})]}):e.jsx("p",{className:"font-semibold",children:"No Active Plan"})]}),(t==null?void 0:t.isSubscribed)&&It&&e.jsxs("div",{className:"flex-1 border-l pl-4",children:[e.jsx("p",{className:"text-sm text-gray-500",children:It.kind==="cancel_downgrade"?"Keep Your Plan":"Next Plan"}),(()=>{const n=It.planId,b=zs[n],h=It.kind==="cancel_downgrade";return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{className:"font-semibold text-green-700",children:[b.name," Plan"]}),e.jsxs("p",{className:"text-sm text-gray-600",children:["$",b.price,"/month"]}),e.jsx("p",{className:"text-xs text-gray-500",children:ve?gt(n,b.credits," credits/mo"):`${b.credits.toLocaleStr
242ing()} credits/mo`}),e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:ve?"Switching costs nothing and your trial end date stays the same":h?"Cancels your scheduled downgrade and keeps your credits":ot?"Cancels your scheduled downgrade. Your unused credits carry over":"Your unused credits carry over when you upgrade"}),ve?e.jsx("div",{className:"flex flex-wrap gap-2 mt-1",children:e.jsx(N,{size:"sm",onClick:()=>At(!0),"data-testid":"button-view-all-plans-next",children:"View All Plans"})}):e.jsxs(N,{size:"sm",className:"mt-1",onClick:()=>Ge(n,null),"data-testid":h?"button-keep-plan-next":"button-upgrade-next",children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1"}),h?`Keep ${b.name}`:"Upgrade"]})]})})()]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Status"}),e.jsx(ie,{className:ve?"bg-blue-100 text-blue-700":t!=null&&t.isSubscribed?"bg-green-100 text-green-700":"bg-gray-100 text-gray-700","data-testid":"badge-subscription-status",children:ve?Oe?`Free trial - ends ${Oe}`:"Free trial":t!=null&&t.isSubscribed?"Active":"Free"})]}),(t==null?void 0:t.isSubscribed)&&zs[(t==null?void 0:t.subscriptionPlan)||""]&&!(ve&&Rl(t==null?void 0:t.subscriptionPlan))&&e.jsx(N,{variant:"ghost",size:"sm",className:"text-blue-600 hover:text-blue-700",onClick:()=>At(!0),children:"View All Plans"})]}),e.jsx(N,{variant:"outline",className:"w-full",onClick:F,"data-testid":"button-manage-billing",children:"Manage Billing"}),e.jsx("p",{className:"text-xs text-gray-500 text-center mt-2",children:"All billing information and processing is handled securely by Stripe. We do not collect, store, or have access to any billing information."})]})]}),e.jsxs(Ue,{className:"bg-white border-gray-200",children:[e.jsx(zt,{children:e.jsx(Vt,{children:"Profile"})}),e.jsxs(_e,{className:"space-y-4",children:[e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Email"}),e.jsx("p",{className:"font-semibold","data-testid":"text-user-email",children:t==null?void 0:t.email})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Name"}),e.jsx("p",{className:"font-semibold",children:t!=null&&t.firstName&&(t!=null&&t.lastName)?`${t.firstName} ${t.lastName}`:"Not set"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Password"}),e.jsx("p",{className:"font-semibold",children:"â¢â¢â¢â¢â¢â¢â¢â¢"})]})]}),e.jsx(N,{variant:"outline",className:"w-full",onClick:j,"data-testid":"button-update-profile",children:"Update Profile"})]})]}),e.jsx(jx,{}),e.jsx(Ax,{})]}),Ys(t==null?void 0:t.subscriptionPlan)&&e.jsxs(Ue,{className:"bg-white border-gray-200",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center space-x-2",children:[e.jsx("img",{src:ii,alt:"",className:"h-5 w-5"}),e.jsx("span",{children:"Credits"})]})}),e.jsxs(_e,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-500",children:"Credits"}),e.jsxs("span",{className:"font-medium","data-testid":"text-combined-credits",children:[Math.max(0,((t==null?void 0:t.monthlyCredits)||0)-((t==null?void 0:t.monthlyCreditsUsed)||0))+((t==null?void 0:t.permanentCredits)||0)," available"]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Unused credits roll over each billing cycle and never expire while your subscription is active. If you cancel or downgrade your plan, your remaining balance expires at the end of the billing period."}),$.length>0&&e.jsx("div",{className:"space-y-1.5","data-testid":"list-bonus-credits-expiry",children:$.map(n=>{const b=Er(n.expiresAt,a);return e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm","data-testid":`row-bonus-credits-expiry-${n.id}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5 font-medium text-amber-700",children:[e.jsx(Kt,{className:"h-4 w-4"}),n.amountRemaining," temporary bonus credit",n.amountRemaining===1?"":"s",e.jsx("span",{className:"text-xs font-normal text-amber-500",children:Hn(n.source)})]}),e.jsxs("span",{className:"flex items-center gap-1 text-amber-600",title:`${n.amountRemaining} temporary bonus credit${n.amountRemaining===1?"":"s"} (${Hn(n.source)}) expire in ${cn(b)}`,children:[e.jsx(ua,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"expiring in"}),e.jsx("span",{className:"font-mono font-medium","data-testid":`text-bonus-credits-countdown-${n.id}`,children:cn(b)})]})]},n.id)})}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-500",children:"Additional Credits (roll over while your subscription is active)"}),e.jsxs("span",{className:"font-medium",children:[Or(t==null?void 0:t.subscriptionPlan)," per credit"]})]}),e.jsx(N,{className:"w-full",onClick:()=>{Y(500),U("500"),K(!0)},children:"Buy More Credits"})]})]}),Ys(t==null?void 0:t.subscriptionPlan)&&e.jsxs(Ue,{className:"bg-white border-gray-200",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ks,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{children:"Auto Top-Up"})]}),e.jsx(xs,{checked:te,disabled:ve,onCheckedChange:n=>{ne(n),W(!0)},"data-testid":"switch-auto-top-up"})]})}),e.jsx(_e,{className:"space-y-4",children:te&&!ve?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(xe,{className:"text-sm text-gray-600 mb-1 block",children:"When your credit balance falls below"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Jt,{value:Q,onValueChange:n=>{V(n),W(!0)},children:[e.jsx(Yt,{className:"w-[110px]",children:e.jsx(Qt,{})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"credits",children:"Credits"}),e.jsx(Ie,{value:"dollars",children:"Dollars"})]})]}),e.jsxs("div",{className:"flex-1 relative",children:[Q==="dollars"&&e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400",children:"$"}),e.jsx(Ee,{type:"number",min:1,value:R,onChange:n=>{pe(n.target.value),W(!0)},className:Q==="dollars"?"pl-7":""})]})]})]}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-sm text-gray-600 mb-1 block",children:"Automatically purchase"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Jt,{value:Se,onValueChange:n=>{Ze(n),W(!0)},children:[e.jsx(Yt,{className:"w-[110px]",children:e.jsx(Qt,{})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"credits",children:"Credits"}),e.jsx(Ie,{value:"dollars",children:"Dollars"})]})]}),(()=>{const n={starter:500,growth:2e3,scale:1e4,platinum:1e5,enterprise:25e4},b={starter:10,growth:7.5,scale:5,platinum:3,enterprise:2},h=(n[(t==null?void 0:t.subscriptionPlan)||"starter"]||500)*5,L=b[(t==null?void 0:t.subscriptionPlan)||"starter"]||10,_=Se==="credits"?h:
242h*L/100;return e.jsxs("div",{className:"flex-1 relative",children:[Se==="dollars"&&e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400",children:"$"}),e.jsx(Ee,{type:"number",min:Se==="credits"?100:1,max:_,value:Me,onChange:G=>{He(G.target.value),W(!0)},className:Se==="dollars"?"pl-7":""})]})})()]}),(()=>{const n={starter:500,growth:2e3,scale:1e4,platinum:1e5,enterprise:25e4},b={starter:10,growth:7.5,scale:5,platinum:3,enterprise:2},h=(n[(t==null?void 0:t.subscriptionPlan)||"starter"]||500)*5,L=b[(t==null?void 0:t.subscriptionPlan)||"starter"]||10,_=Se==="credits"?h:h*L/100;return e.jsxs("p",{className:"text-xs text-gray-400 mt-1",children:[Se==="credits"?`Min 100, max ${h.toLocaleString()} credits`:`Min $1, max $${_.toLocaleString()}`," at ",Or(t==null?void 0:t.subscriptionPlan),"/credit"]})})()]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(xe,{className:"text-sm text-gray-600",children:"Monthly spending cap"}),e.jsx(xs,{checked:ee,onCheckedChange:n=>{O(n),W(!0)}})]}),ee&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Jt,{value:I,onValueChange:n=>{re(n),W(!0)},children:[e.jsx(Yt,{className:"w-[110px]",children:e.jsx(Qt,{})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"credits",children:"Credits"}),e.jsx(Ie,{value:"dollars",children:"Dollars"})]})]}),e.jsxs("div",{className:"flex-1 relative",children:[I==="dollars"&&e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400",children:"$"}),e.jsx(Ee,{type:"number",min:1,value:Pe,onChange:n=>{tt(n.target.value),W(!0)},className:I==="dollars"?"pl-7":""})]})]})]})]}),pt.data&&(pt.data.capUsedCredits>0||pt.data.capUsedCents>0)&&e.jsxs("div",{className:"rounded-lg bg-blue-50 p-3 text-sm",children:[e.jsx("p",{className:"font-medium text-blue-800 mb-1",children:"This month's auto top-ups"}),e.jsxs("div",{className:"flex justify-between text-blue-700",children:[e.jsxs("span",{children:[pt.data.capUsedCredits.toLocaleString()," credits purchased"]}),e.jsxs("span",{children:["$",(pt.data.capUsedCents/100).toFixed(2)," charged"]})]})]}),e.jsx(N,{className:"w-full",onClick:ye,disabled:!$e||jt.isPending,children:jt.isPending?"Saving...":"Save Auto Top-Up Settings"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Automatically purchase credits when your credit balance gets low. Never run out of credits mid-export."}),ve&&e.jsx("p",{className:"text-sm font-medium text-blue-700","data-testid":"text-auto-top-up-trial-note",children:"Available once your free trial converts to a paid plan."}),!ve&&$e&&e.jsx(N,{className:"w-full",variant:"outline",onClick:ye,disabled:jt.isPending,children:jt.isPending?"Saving...":"Save (Disable Auto Top-Up)"})]})})]}),Ys(t==null?void 0:t.subscriptionPlan)&&e.jsxs(Ue,{className:"bg-white border-gray-200",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Md,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{children:"Overage Budget"})]}),e.jsx(xs,{checked:Xt,disabled:ve,onCheckedChange:n=>{rt(n),Ae(!0)},"data-testid":"switch-overage-budget"})]})}),e.jsxs(_e,{className:"space-y-4",children:[Xt&&!ve?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-sm text-gray-500",children:["Keep going when your credits run out: extra usage is billed at ",((_s=bt.data)==null?void 0:_s.pricePerCredit)||Or(t==null?void 0:t.subscriptionPlan),"/credit to your card on file once per day, up to this budget each billing cycle."]}),e.jsxs("div",{children:[e.jsx(xe,{className:"text-sm text-gray-600 mb-1 block",children:"Allow up to"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Jt,{value:fs,onValueChange:n=>{Tt(n),Ae(!0)},children:[e.jsx(Yt,{className:"w-[110px]","data-testid":"select-overage-budget-type",children:e.jsx(Qt,{})}),e.jsxs(Gt,{children:[e.jsx(Ie,{value:"dollars",children:"Dollars"}),e.jsx(Ie,{value:"credits",children:"Credits"})]})]}),e.jsxs("div",{className:"flex-1 relative",children:[fs==="dollars"&&e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400",children:"$"}),e.jsx(Ee,{type:"number",min:1,value:yt,onChange:n=>{is(n.target.value),Ae(!0)},className:fs==="dollars"?"pl-7":"","data-testid":"input-overage-budget-amount"})]})]}),e.jsxs("p",{className:"text-xs text-gray-400 mt-1",children:[fs==="dollars"?"Maximum extra dollars per billing cycle":"Maximum extra credits per billing cycle",". Resets at renewal."]})]}),e.jsx(N,{className:"w-full",onClick:ls,disabled:!Dt||Nt.isPending,"data-testid":"button-save-overage-budget",children:Nt.isPending?"Saving...":"Save Overage Budget"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Set a budget to keep exporting after your credits run out. Extra usage is billed to your card once per day at your plan's overage rate - you only pay for what you use, up to the budget you set."}),ve&&e.jsx("p",{className:"text-sm font-medium text-blue-700","data-testid":"text-overage-trial-note",children:"Available once your free trial converts to a paid plan."}),!ve&&Dt&&e.jsx(N,{className:"w-full",variant:"outline",onClick:ls,disabled:Nt.isPending,"data-testid":"button-save-overage-budget",children:Nt.isPending?"Saving...":"Save (Disable Overage Budget)"})]}),bt.data&&(bt.data.usedCredits>0||bt.data.pendingCents>0)&&e.jsxs("div",{className:"rounded-lg bg-blue-50 p-3 text-sm","data-testid":"text-overage-usage",children:[e.jsx("p",{className:"font-medium text-blue-800 mb-1",children:"This cycle's overage"}),e.jsxs("div",{className:"flex justify-between text-blue-700",children:[e.jsxs("span",{children:[bt.data.usedCredits.toLocaleStr
242ing()," credits used"]}),e.jsxs("span",{children:["$",(bt.data.usedCents/100).toFixed(2)]})]}),bt.data.pendingCents>0&&e.jsx("p",{className:"text-blue-700 mt-1",children:bt.data.pendingCents>=50?`$${(bt.data.pendingCents/100).toFixed(2)} will be charged at the next daily billing run.`:Xt?`$${(bt.data.pendingCents/100).toFixed(2)} unbilled - amounts under $0.50 roll into the next charge.`:`$${(bt.data.pendingCents/100).toFixed(2)} unbilled - amounts under $0.50 are waived while the budget stays disabled.`})]}),((hs=bt.data)==null?void 0:hs.billingFailedAt)&&e.jsxs("div",{className:"rounded-lg bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-start gap-2","data-testid":"text-overage-billing-suspended",children:[e.jsx(ps,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsx("span",{children:"A daily overage charge could not be processed, so overage usage is paused. Please update your payment method - we retry once per day."})]})]})]}),e.jsx(os,{open:B,onOpenChange:K,children:e.jsxs(cs,{children:[e.jsxs(as,{children:[e.jsx(rs,{children:"Purchase Credits"}),e.jsxs($s,{children:["Buy additional credits using your card on file. To update your payment method, go to"," ",e.jsx("button",{type:"button",className:"text-blue-600 hover:underline font-medium",onClick:()=>{K(!1),w()},children:"Manage Billing Details"}),"."]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{htmlFor:"creditCount",children:"Number of Credits"}),(()=>{const b=({starter:500,growth:2e3,scale:1e4,platinum:1e5,enterprise:25e4}[(t==null?void 0:t.subscriptionPlan)||"starter"]||500)*5;return e.jsxs(e.Fragment,{children:[e.jsx(Ee,{id:"creditCount",type:"number",min:100,max:b,value:fe,onChange:h=>{U(h.target.value);const L=parseInt(h.target.value);!isNaN(L)&&L>0&&Y(Math.min(L,b))},onBlur:()=>{const h=parseInt(fe);if(isNaN(h)||h<100)Y(100),U("100");else{const L=Math.min(h,b);Y(L),U(String(L))}}}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Min 100, max ",b.toLocaleString()," credits per purchase"]})]})})()]}),e.jsxs("div",{className:"rounded-lg bg-gray-50 p-3 space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:[ae.toLocaleString()," credits"]}),e.jsxs("span",{children:["Ã ",Or(t==null?void 0:t.subscriptionPlan)]})]}),e.jsxs("div",{className:"flex justify-between font-semibold border-t pt-1",children:[e.jsx("span",{children:"Total"}),e.jsxs("span",{children:["$",(ae*((t==null?void 0:t.creditOverageRate)||10)/100).toFixed(2)]})]})]})]}),e.jsxs(er,{children:[e.jsx(N,{variant:"outline",onClick:()=>K(!1),children:"Cancel"}),e.jsx(N,{disabled:ae<100||Ye.isPending,onClick:async()=>{const n=Math.max(100,ae);Ye.mutate(n)},children:Ye.isPending?"Processing...":"Purchase Credits"})]})]})}),e.jsx(os,{open:Rt,onOpenChange:At,children:e.jsxs(cs,{className:"sm:max-w-lg",children:[e.jsxs(as,{children:[e.jsx(rs,{children:ve?"Change Your Trial Plan":"Change Plan"}),e.jsxs($s,{children:[ve?`Switch your trial to any plan for free: you are not charged and your trial still ends${Oe?` on ${Oe}`:" on its original date"}. Or start a plan right now, which ends the trial, charges your card on file today, and adds that plan's trial credits, minus what you have already used, to your balance. If you bought credits during the trial, you cannot move to a plan with a higher per-credit price while any of them remain.`:"Choose the plan that best fits your needs. Upgrades take effect immediately and downgrades take effect at your next billing cycle. When you upgrade, your unused credits carry over to your new plan. When you downgrade, any unused, rolled-over, and purchased credits expire at the end of your current billing period.",ot&&e.jsxs("span",{className:"block mt-2","data-testid":"text-pending-downgrade-dialog-note",children:["You have a downgrade from ",Pt," to ",St," scheduled for your next renewal. Choosing ",Pt," or a higher plan cancels it and keeps your credits. Choosing another plan below ",Pt," changes the scheduled downgrade, and your remaining credits still expire at renewal."]})]})]}),e.jsx("div",{className:"space-y-3 py-4",children:tn.map(n=>{const b=zs[n],h=(ve?Xe:ut)===n,L=ot&&n===Xe,_=it(n);return e.jsx("div",{className:`rounded-lg border-2 p-4 ${h?"border-green-500 bg-green-50":"border-gray-200 hover:border-gray-300"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-semibold text-lg",children:b.name}),h&&e.jsx(ie,{className:"bg-green-100 text-green-700 text-xs",children:"Current Plan"}),L&&e.jsx(ie,{className:"bg-amber-100 text-amber-700 text-xs","data-testid":`badge-scheduled-plan-${n}`,children:"Starts at renewal"})]}),e.jsxs("p",{className:"text-gray-600 text-sm mt-1",children:["$",b.price,"/month"]}),e.jsxs("div",{className:"flex gap-4 mt-1",children:[e.jsx("span",{className:"text-xs text-gray-500",children:ve?gt(n,b.credits,"/mo"):`${b.credits.toLocaleStr
242ing()} credits/mo`}),e.jsxs("span",{className:"text-xs text-gray-500",children:["Additional: ",b.overageRate,"/credit"]})]})]}),ve?e.jsxs("div",{className:"flex flex-col gap-2 shrink-0",children:[!h&&e.jsx(N,{size:"sm",onClick:()=>Ge(n,"switch_trial"),"data-testid":`button-switch-trial-${n}`,children:"Switch trial plan"}),e.jsx(N,{size:"sm",variant:"outline",onClick:()=>Ge(n,"activate_now"),"data-testid":`button-activate-now-${n}`,children:"Start my plan now"})]}):_!=="same"&&e.jsx(N,{size:"sm",variant:_==="downgrade"?"outline":"default",onClick:()=>Ge(n,null),"data-testid":`button-change-plan-${n}`,children:_==="cancel_downgrade"?e.jsxs(e.Fragment,{children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1"}),"Keep ",b.name]}):_==="upgrade"?e.jsxs(e.Fragment,{children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1"}),"Upgrade"]}):e.jsxs(e.Fragment,{children:[e.jsx(Yr,{className:"h-3.5 w-3.5 mr-1"}),"Downgrade"]})})]})},n)})})]})}),e.jsx(os,{open:Te,onOpenChange:n=>{n||Ce()},children:e.jsxs(cs,{children:[e.jsx(as,{children:e.jsx(rs,{children:lt==="switch_trial"?"Switch trial plan":lt==="activate_now"?"Start my plan now":P==="cancel_downgrade"?`Keep your ${le} plan`:P==="upgrade"?"Confirm Upgrade":"Confirm Downgrade"})}),at&&zs[at]&<&&(()=>{var G;const n=zs[at],b=Ki(at),h=Ui(at,t==null?void 0:t.monthlyCreditsUsed),L=lt==="switch_trial",_=at===Xe;return e.jsxs("div",{className:"space-y-4 py-2","data-testid":"text-trial-change-plan-copy",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-gray-500",children:"Current Plan"}),e.jsxs("span",{className:"font-medium",children:[((G=zs[Xe])==null?void 0:G.name)||(t==null?void 0:t.subscriptionPlan)," (free trial)"]})]}),!_&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center justify-center",children:P==="downgrade"?e.jsx(Yr,{className:"h-5 w-5 text-orange-500","data-testid":"icon-trial-move-down"}):e.jsx(Pa,{className:"h-5 w-5 text-green-600","data-testid":"icon-trial-move-up"})}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-gray-500",children:"New Plan"}),e.jsxs("span",{className:"font-medium",children:[n.name," - $",n.price,"/mo"]})]})]}),e.jsx("div",{className:"rounded-lg bg-gray-50 p-3 space-y-2 text-sm",children:L?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-green-700 font-medium",children:"You will not be charged today."}),e.jsxs("p",{children:["Your free trial continues on the ",n.name," plan and still ends",Oe?` on ${Oe}`:" on its original date",". On that date your card on file is charged $",n.price," and the plan starts, unless you cancel first."]}),e.jsxs("p",{"data-testid":"text-trial-switch-balance",children:["Your trial balance becomes ",h.toLocaleString()," credit",h===1?"":"s"," for the rest of the trial.",de>0?` The ${n.name} trial includes ${b.toLocaleString()} credits, minus the ${de.toLocaleString()} you have already used.`:""," ","Credits already used during the trial stay used."]}),de>0&&h===0&&e.jsxs("p",{className:"text-orange-700 font-medium","data-testid":"text-trial-switch-zero",children:["You have already used more than the ",n.name," tri
242al includes, so no trial credits are left on it."]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"font-medium",children:["Your free trial ends now and your ",n.name," plan starts today."]}),e.jsxs("p",{children:["Your card on file is charged $",n.price," right away, and then every month. All charges are final."]}),h>0?e.jsxs("p",{className:"text-green-700 font-medium","data-testid":"text-trial-activate-carry",children:["Your ",h.toLocaleString()," unused trial credit",h===1?" is":"s are"," added to your balance on top of the"," ",n.credits.toLocaleString()," credits of your new plan, and roll over every month."]}):de>0?e.jsxs("p",{"data-testid":"text-trial-activate-carry",children:["You have already used the ",b.toLocaleString()," trial credits the ",n.name," ","plan includes, so no trial credits carry over."]}):null,!_&&e.jsx("p",{className:"text-xs text-gray-600","data-testid":"text-trial-activate-carry-reason",children:de>0?`Unused trial credits are counted on the ${n.name} plan: its ${b.toLocaleString()} trial credits minus the ${de.toLocaleString()} you have already used.`:`Unused trial credits are counted on the ${n.name} plan, which includes ${b.toLocaleString()} trial credits.`})]})}),ft&&e.jsxs("div",{className:"rounded-lg border border-red-200 bg-red-50 p-3 space-y-2","data-testid":"box-payment-declined",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ps,{className:"h-4 w-4 text-red-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-red-700",children:[e.jsx("p",{className:"font-semibold",children:"Your payment was declined"}),e.jsx("p",{children:ft})]})]}),e.jsxs(N,{variant:"outline",className:"w-full border-red-300 text-red-700 hover:bg-red-100",onClick:()=>{Ce(),w()},"data-testid":"button-update-payment-method",children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"}),"Update payment method"]})]})]})})(),at&&zs[at]&&!lt&&(()=>{const n=zs[at],b=P==="upgrade"||P==="cancel_downgrade",h=Math.max(0,((t==null?void 0:t.monthlyCredits)||0)-((t==null?void 0:t.monthlyCreditsUsed)||0)),L=h+Math.max(0,(t==null?void 0:t.permanentCredits)||0);return e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-gray-500",children:"Current Plan"}),e.jsxs("span",{className:"font-medium",children:[Pt||(t==null?void 0:t.subscriptionPlan),ot?` (${St} from your next renewal)`:""]})]}),e.jsx("div",{className:"flex items-center justify-center",children:b?e.jsx(Pa,{className:"h-5 w-5 text-green-600"}):e.jsx(Yr,{className:"h-5 w-5 text-orange-500"})}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-gray-500",children:"New Plan"}),e.jsxs("span",{className:"font-medium",children:[n.name," - $",n.price,"/mo"]})]}),e.jsx("div",{className:"rounded-lg bg-gray-50 p-3 space-y-2 text-sm",children:P==="cancel_downgrade"?e.jsxs(e.Fragment,{children:[e.jsxs("p",{"data-testid":"text-cancel-downgrade-copy",children:["This cancels your scheduled downgrade to ",St," and keeps you on the ",n.name," plan. You'll be charged the ",n.name," plan's full price ($",n.price,") now, your billing cycle will restart today, and your new credits will be available right away."]}),e.jsx("p",{className:"text-green-700 font-medium",children:h>0?`Your credits are kept: your ${h.toLocaleString()} unused credits carry over and keep rolling over.`:"Your credits are kept and keep rolling over."})]}):b?e.jsxs(e.Fragment,{children:[e.jsx("p",{children:"Your plan will be upgraded immediately. You'll be charged the new plan's full price now, your billing cycle will restart today, and your new credits will be available right away."}),ot&&e.jsxs("p",{children:["This also cancels your scheduled downgrade to ",St,"."]}),h>0&&e.jsxs("p",{className:"text-green-700 font-medium",children:["Your ",h.toLocaleString()," unused credits will carry over to your new plan and keep rolling over."]})]}):e.jsxs(e.Fragment,{children:[ot?e.jsxs("p",{"data-testid":"text-retarget-downgrade-copy",children:["This replaces your scheduled downgrade to ",St,". You stay on ",Pt," until"," ",_t||"your next renewal",", then your billing changes to $",n.price,"/mo. No additional charges will be made."]}):e.jsxs("p",{children:["Your billing will change to $",n.price,"/mo at your next renewal. No additional charges will be made."]}),e.jsx("p",{children:"You can keep using your current credits until your renewal date."}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-red-200 bg-red-50 p-2",children:[e.jsx(ps,{className:"h-4 w-4 text-red-600 flex-shrink-0 mt-0.5"}),e.jsxs("p",{className:"text-red-600 font-medium","data-testid":"text-downgrade-credit-warning",children:["When the downgrade takes effect at renewal, your remaining balance of ",L.toLocaleStr
242ing()," credit",L===1?"":"s"," (including unused, rolled-over, and purchased credits) will expire. Your new plan will then start with ",n.credits.toLocaleString()," fresh credits."]})]}),ot&&e.jsxs("p",{className:"text-xs text-gray-600",children:["To keep your credits, choose ",Pt," or a higher plan instead."]})]})})]})})(),De?e.jsx("div",{className:"rounded-lg border border-amber-200 bg-amber-50 p-3","data-testid":"box-plan-change-notice",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ps,{className:"h-4 w-4 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-sm text-amber-800",children:"Your free trial has already ended, so this change is no longer available. Close this window to see your current plan."})]})}):et?e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 p-3 space-y-2","data-testid":"box-plan-change-notice",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ps,{className:"h-4 w-4 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-sm text-amber-800",children:et.message})]}),et.refreshSuggested&&e.jsx(N,{variant:"outline",size:"sm",className:"w-full border-amber-300 text-amber-800 hover:bg-amber-100",onClick:Ft,"data-testid":"button-plan-change-refresh",children:"Refresh page"})]}):null,e.jsxs(er,{children:[e.jsx(N,{variant:"outline",onClick:Ce,disabled:oe.isPending,"data-testid":"button-cancel-plan-change",children:st?"Close":lt?"Keep my trial as it is":"Cancel"}),e.jsx(N,{onClick:()=>{at&&!st&&(Ot(null),oe.mutate({targetPlan:at,mode:lt}))},disabled:oe.isPending||st,"data-testid":"button-confirm-plan-change",children:oe.isPending?"Processing...":lt==="switch_trial"?"Switch trial plan":lt==="activate_now"?ft?"Try again":"Start my plan now":P==="cancel_downgrade"?`Keep ${le}`:P==="upgrade"?"Confirm Upgrade":"Confirm Downgrade"})]})]})}),e.jsxs(Ue,{className:"bg-white border-gray-200",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center space-x-2",children:[e.jsx(Kt,{className:"h-5 w-5"}),e.jsx("span",{children:"Enrichments"})]})}),e.jsx(_e,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"pr-4",children:[e.jsx(xe,{htmlFor:"enrichment-email-results",className:"font-medium",children:"Email me my enrichment files"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Finished files are always available to download from the Enrichments tab. Turn this off if you would rather not also receive them by email."})]}),e.jsx(xs,{id:"enrichment-email-results",checked:(v==null?void 0:v.emailResults)??!0,onCheckedChange:n=>y.mutate(n),disabled:y.isPending,"data-testid":"switch-enrichment-email-results"})]})})]}),e.jsxs(Ue,{className:"bg-white border-gray-200",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center space-x-2",children:[e.jsx(Ga,{className:"h-5 w-5"}),e.jsx("span",{children:"Account Settings"})]})}),e.jsxs(_e,{className:"space-y-4",children:[e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Company Name"}),e.jsx("p",{className:"font-semibold",children:(t==null?void 0:t.companyName)||"Not set"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Company Website"}),e.jsx("p",{className:"font-semibold text-sm",children:t!=null&&t.websiteOptOut?"No website currently set!":(t==null?void 0:t.companyWebsite)||"Not set"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Job Title"}),e.jsx("p",{className:"font-semibold",children:(t==null?void 0:t.jobTitle)||"Not set"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Target Categories"}),e.jsxs("p",{className:"text-sm",children:[((us=t==null?void 0:t.targetCategories)==null?void 0:us.length)||0," ","categories"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Target Locations"}),e.jsx("p",{className:"text-sm",children:uc(t==null?void 0:t.targetLocations)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Businesses to Avoid"}),e.jsxs("p",{className:"text-sm",children:[((Ms=t==null?void 0:t.businessesToAvoid)==null?void 0:Ms.length)||0," types"]})]})]}),e.jsx(N,{variant:"outline",className:"w-full",onClick:E,"data-testid":"button-update-account-settings",children:"Update Account Settings"})]})]}),r&&e.jsxs(Ue,{className:"bg-white dark:bg-gray-900 border-gray-200 dark:border-gray-800",children:[e.jsx(zt,{children:e.jsxs(Vt,{className:"flex items-center space-x-2",children:[e.jsx(ed,{className:"h-5 w-5"}),e.jsx("span",{children:"Account Info"})]})}),e.jsx(_e,{className:"space-y-4",children:e.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold text-gray-400 uppercase tracking-wide",children:"Membership"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"h-4 w-4 text-gray-400"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium",children:["Member for ",r.daysAsMember," days"]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Since ",r.memberSince?new Date(r.memberSince).toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric"}):" - "]})]})]}),Ys(t==null?void 0:t.subscriptionPlan)?e.jsxs("p",{className:"text-xs text-gray-500",children:[Math.max(0,((t==null?void 0:t.monthlyCredits)||0)-((t==null?void 0:t.monthlyCreditsUsed)||0))+((t==null?void 0:t.permanentCredits)||0)," credits remaining"]}):r.freeLeadsRemaining>=0&&!(t!=null&&t.isSubscribed)?e.jsxs("p",{className:"text-xs text-gray-500",children:[r.freeLeadsRemaining," credits remaining"]}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold text-gray-400 uppercase tracking-wide",children:"Exports"}),e.jsxs("p",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:r.totalExportsLifetime})," total exports"]}),e.jsxs("p",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:r.totalRowsExportedLifetime.toLocaleStr
242ing()})," rows exported (all time)"]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Last 30 days: ",r.totalRowsExportedLastMonth.toLocaleString()," rows"]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Last 7 days: ",r.totalRowsExportedLastWeek.toLocaleString()," rows"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold text-gray-400 uppercase tracking-wide",children:"Resources"}),e.jsxs("p",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:r.keywordListCount})," keyword lists"]}),e.jsxs("p",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:r.emailScheduleCount})," email schedules",r.activeEmailScheduleCount>0&&e.jsxs("span",{className:"text-green-600 ml-1",children:["(",r.activeEmailScheduleCount," active)"]})]}),r.totalScheduledEmailsSent>0&&e.jsxs("p",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:r.totalScheduledEmailsSent})," scheduled emails sent"]}),r.lastManualExportAt&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Last export: ",new Date(r.lastManualExportAt).toLocaleDateString("en-US",{month:"short",day:"numeric"})]}),r.lastEmailExportAt&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Last scheduled: ",new Date(r.lastEmailExportAt).toLocaleDateString("en-US",{month:"short",day:"numeric"})]})]})]})})]}),ar()]})}function pc(t){const r=t/100,s=Math.round(r*100)%100!==0;return`$${r.toLocaleString("en-US",{minimumFractionDigits:s?2:0,maximumFractionDigits:2})}`}function Rx({trialEndsAt:t,plan:r,firstChargeAmountCents:s,chargeLabel:i,cancelAtPeriodEnd:l,onCancelTrial:c,onReactivate:d,isReactivating:u}){const g=oa(t),f=g?`on ${g}`:"when your trial ends",C=Ia(r).name,F=i||(typeof s=="number"&&s>0?pc(s):Yl(r));return l?e.jsx(Ue,{className:"border-2 border-amber-300 bg-amber-50 mb-4 sm:mb-6","data-testid":"banner-free-trial-cancelled",children:e.jsx(_e,{className:"p-4 sm:p-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3 flex-1 min-w-0",children:[e.jsx(ps,{className:"h-5 w-5 text-amber-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm text-gray-800 min-w-0",children:[e.jsxs("p",{className:"font-semibold",children:["Your free trial is set to end ",f,". You will not be charged."]}),e.jsxs("p",{className:"text-gray-700",children:["Your access and any remaining trial credits end ",f,". Reactivate to keep your ",C,": your first charge of"," ",e.jsx("span",{className:"font-semibold",children:F})," would then happen ",f,"."]})]})]}),e.jsx(N,{onClick:d,disabled:u,className:"bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 shrink-0","data-testid":"button-reactivate-trial-banner",children:u?"Reactivating...":"Keep My Plan"})]})})}):e.jsx(Ue,{className:"border-2 border-blue-300 bg-blue-50 mb-4 sm:mb-6","data-testid":"banner-free-trial",children:e.jsx(_e,{className:"p-4 sm:p-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3 flex-1 min-w-0",children:[e.jsx(Kt,{className:"h-5 w-5 text-blue-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm text-gray-800 min-w-0",children:[e.jsxs("p",{className:"font-semibold flex flex-wrap items-center gap-2",children:[e.jsx("span",{children:"You are on a free trial"}),e.jsx(ie,{className:"bg-blue-600 text-white text-xs","data-testid":"badge-trial-days-left",children:Ql(t)})]}),e.jsxs("p",{className:"text-gray-700","data-testid":"text-trial-first-charge",children:["Your ",C," starts ",f,", when your card on file is charged ",e.jsx("span",{className:"font-semibold",children:F})," ","and then every month. Cancel before ",g||"then"," and you will not be charged."]})]})]}),e.jsx(N,{variant:"outline",onClick:c,className:"border-blue-400 text-blue-700 hover:bg-blue-100 shrink-0","data-testid":"button-cancel-trial-banner",children:"Cancel Free Trial"})]})})})}const Ox=o.lazy(()=>wd(()=>import("./AdminTab-B7PuUhR0.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24])).catch(t=>{var i;const r=((i=t==null?void 0:t.message)==null?void 0:i.toLowerCase())||"";if(r.includes("dynamically imported module")||r.includes("failed to fetch")||r.includes("loading chunk")||r.includes("loading css chunk")){const l="chunk_reload_ts",c=sessionStorage.getItem(l),d=Date.now();if(!c||d-Number(c)>1e4)return sessionStorage.setItem(l,String(d)),window.location.reload(),new Promise(()=>{})}throw t}));function Dx(){var ki,Fi,Pi,Ii,Ti,Ai,Li;const{user:t,isLoading:r,isAuthenticated:s}=Pr(),{toast:i}=Ss();o.useEffect(()=>{window.__removeGlobalLoader&&window.__removeGlobalLoader()},[]),rd({title:"Dashboard",description:"Access your B2B lead database. Search, filter, and export leads for your sales outreach campaigns."}),o.useEffect(()=>
242{if(new URLSearchParams(window.location.search).get("refreshAuth")==="1"){console.log("[Dashboard] Invalidating user cache due to refreshAuth parameter"),z.invalidateQueries({queryKey:["/api/auth/user"]});const se=window.location.pathname;window.history.replaceState({},"",se)}},[]);const l=o.useRef(!1);o.useEffect(()=>{if(!t||l.current)return;const S=t.targetCategories,se=t.onboardingCategoryFilter,Re=S&&S.length>0,Mt=se&&se.length>0;if(!Re||Mt)return;l.current=!0;let Et=0;const qs=setInterval(()=>{Et++,z.invalidateQueries({queryKey:["/api/auth/user"]}),Et>=15&&clearInterval(qs)},3e3);return()=>clearInterval(qs)},[t,z]);const c=nd();c==null||c.scenario;const d=(c==null?void 0:c.metadata)??null,u=(c==null?void 0:c.onboardingTimerActive)??!1,g=(c==null?void 0:c.adminDiscountCodeState)??{status:"none"},f=(c==null?void 0:c.shouldShowExpiredBanner)??!1,C=(c==null?void 0:c.expiredBannerHeight)??200,F=(c==null?void 0:c.discountCodeBannerHeight)??90,w=(c==null?void 0:c.onboardingBannerHeight)??90,E=(()=>{const S=g.status!=="none",se=f;let Re=0;return S&&(Re+=F),se&&(Re+=C),u&&(Re+=w),Re})(),[A,T]=Xn(),J=id(),[p,v]=o.useState({}),[y,k]=o.useState("leads"),[a,q]=o.useState(!1),[$,X]=o.useState(!1),[B,K]=o.useState(!1),[ae,Y]=o.useState(!1),[fe,U]=o.useState(!1),[te,ne]=o.useState(""),[Q,V]=o.useState(""),[R,pe]=o.useState(""),[Se,Ze]=o.useState(!1),[Me,He]=o.useState(""),[ee,O]=o.useState(""),[I,re]=o.useState(""),[Pe,tt]=o.useState(""),[$e,W]=o.useState(""),[Le,ve]=o.useState([]),[Oe,vt]=o.useState(null),[Rt,At]=o.useState([]),[at,Je]=o.useState(""),[Te,Ct]=o.useState(""),[lt,kt]=o.useState(""),[ft,qt]=o.useState([]),[et,Ot]=o.useState(!1),[Xe,mt]=o.useState(null),[ut,ot]=o.useState(!1),[St,Pt]=o.useState(null),[it,ze]=o.useState(!1),[_t,de]=o.useState(!1),[gt,It]=o.useState(""),[Ge,Ce]=o.useState(null),[P,le]=o.useState(!1);o.useEffect(()=>{y!=="settings"&&de(!1)},[y]),o.useEffect(()=>{!P||ut||((t==null?void 0:t.websiteAnalysisStatus)==="completed"||(t==null?void 0:t.websiteAnalysisStatus)==="success"||(t==null?void 0:t.websiteAnalysisStatus)==="failed")&&le(!1)},[t==null?void 0:t.websiteAnalysisStatus,P,ut]);const[De,st]=o.useState(!1),[Ft,oe]=o.useState(""),[Ye,pt]=o.useState([]),[jt,ye]=o.useState(!1),[Xt,rt]=o.useState(-1),fs=o.useRef(null),Tt=o.useRef(null),[yt,is]=o.useState(!1),[Dt,Ae]=o.useState(5),[bt,Nt]=o.useState(5),ls=o.useRef(!1),[es,Rs]=o.useState(1),{data:bs}=Qe({queryKey:["/api/me/temporary-credits"],enabled:!!t&&Ys(t.subscriptionPlan),staleTime:3e4}),Ps=!!t&&Ys(t.subscriptionPlan);o.useEffect(()=>{if(!Ps)return;const S=()=>{z.invalidateQueries({queryKey:["/api/auth/user"]}),z.invalidateQueries({queryKey:["/api/me/temporary-credits"]})},se=setInterval(()=>{document.visibilityState==="visible"&&S()},6e4);return window.addEventListener("focus",S),()=>{clearInterval(se),window.removeEventListener("focus",S)}},[Ps]);const ms=(ki=bs==null?void 0:bs.grants)==null?void 0:ki.find(S=>S.source==="onboarding_bonus"),Bt=!!ms,[he,_s]=o.useState(null);o.useEffect(()=>{if(!ms)return;const S=()=>{const Re=new Date(ms.expiresAt).getTime()-Date.now();_s(Math.max(0,Math.floor(Re/1e3)))};S();const se=setInterval(S,1e3);return()=>clearInterval(se)},[ms]),o.useEffect(()=>{t!=null&&t.shouldShowOptimizationPopup&&!ls.current&&(is(!0),Ae(5),Nt(5),Rs(1))},[t==null?void 0:t.shouldShowOptimizationPopup]),o.useEffect(()=>{if(!yt||!Bt||es!==1||bt<=0)return;const S=setTimeout(()=>Nt(se=>se-1),1e3);return()=>clearTimeout(S)},[yt,bt,Bt,es]),o.useEffect(()=>{if(!yt||Dt<=0||Bt&&es===1)return;const S=setTimeout(()=>Ae(se=>se-1),1e3);return()=>clearTimeout(S)},[yt,Dt,Bt,es]);
242const[hs,us]=o.useState(!1),[Ms,n]=o.useState(!1),[b,h]=o.useState(!1),L=S=>{q(S),S?(window.history.replaceState(null,"",window.location.pathname+window.location.search+"#managebilling"),nt.current="managebilling"):(window.location.hash==="#managebilling"||window.location.hash==="#billing")&&(window.history.replaceState(null,"",window.location.pathname+window.location.search),nt.current="")},_=S=>{X(S),window.location.hash==="#downgrade"&&(window.history.replaceState(null,"",window.location.pathname+window.location.search),nt.current="")},G=S=>{U(S),S?(window.history.replaceState(null,"",window.location.pathname+window.location.search+"#profile"),nt.current="profile"):window.location.hash==="#profile"&&(window.history.replaceState(null,"",window.location.pathname+window.location.search),nt.current="")},We=S=>{Ze(S),S?(window.history.replaceState(null,"",window.location.pathname+window.location.search+"#accountsettings"),nt.current="accountsettings"):(window.location.hash==="#accountsettings"||window.location.hash==="#settings")&&(window.history.replaceState(null,"",window.location.pathname+window.location.search),nt.current="")},gs=S=>{us(S),S?(window.history.replaceState(null,"",window.location.pathname+window.location.search+"#generateai"),nt.current="generateai"):window.location.hash==="#generateai"&&(window.history.replaceState(null,"",window.location.pathname+window.location.search),nt.current="",h(!1))},ts=()=>{h(!0),k("filters"),setTimeout(()=>{gs(!0)},100)},Zt=S=>{n(S),S?(window.history.replaceState(null,"",window.location.pathname+window.location.search+"#createlist"),nt.current="createlist"):window.location.hash==="#createlist"&&(window.history.replaceState(null,"",window.location.pathname+window.location.search),nt.current="")};o.useEffect(()=>{if(!r&&!s){ce("[Dashboard:493]","User not authenticated"),i({title:"Unauthorized",description:"You are logged out. Logging in again...",variant:"destructive"}),setTimeout(()=>{window.location.href="/api/login"},500);return}},[s,r,i]),o.useEffect(()=>{if(t&&!r&&!t.onboardingCompleted){const S=t.isSubscribed&&(t.onboardingStep??0)<6;(!t.isSubscribed||S)&&T("/onboarding")}},[t,r,T]),o.useEffect(()=>{t!=null&&t.isSubscribed&&ld(t==null?void 0:t.subscriptionStatus)&&od()},[t==null?void 0:t.isSubscribed,t==null?void 0:t.subscriptionStatus]),o.useEffect(()=>{t&&!r&&s&&window.innerWidth<768&&Y(!0)},[t,r,s]);const nt=o.useRef("");o.useEffect(()=>{const S=()=>{const Re=new URLSearchParams(window.location.search).get("tab"),Mt=window.location.hash.substring(1),Et={leads:"leads",enrichments:"enrichments",keywords:"filters",filters:"filters",exports:"exports",schedules:"schedules",settings:"settings",referrals:"referrals",admin:"admin",api:"api",integrations:"integrations"};Re&&Et[Re]?Et[Re]==="admin"&&!(t!=null&&t.isAdmin)?k("leads"):k(Et[Re]):k("leads");const qs={managebilling:{open:()=>q(!0),close:()=>q(!1)},billing:{open:()=>q(!0),close:()=>q(!1)},downgrade:{open:()=>X(!0),close:()=>X(!1)},profile:{open:()=>U(!0),close:()=>U(!1)},accountsettings:{open:()=>Ze(!0),close:()=>Ze(!1)},settings:{open:()=>Ze(!0),close:()=>Ze(!1)},generateai:{open:()=>us(!0),close:()=>us(!1)},createlist:{open:()=>n(!0),close:()=>n(!1)}};nt.current&&nt.current!==Mt&&qs[nt.current]&&qs[nt.current].close(),Mt&&qs[Mt]&&qs[Mt].open(),nt.current=Mt};return S(),window.addEventListener("hashchange",S),window.addEventListener("popstate",S),()=>{window.removeEventListener("hashchange",S),window.removeEventListener("popstate",S)}},[A]),o.useEffect(()=>{const se={leads:"leads",enrichments:"enrichments",filters:"keywords",exports:"exports",schedules:"schedules",settings:"settings",referrals:"referrals",admin:"admin",api:"api",integrations:"integrations"}[y],Re=new URLSearchParams(window.location.search);if(Re.get("tab")!==se){Re.set("tab",se);const Et=`${window.location.pathname}?${Re.toString()}${window.location.hash}`;window.history.replaceState(null,"",Et)}},[y]);const ss=vr(t==null?void 0:t.smbType),{data:x}=Qe({queryKey:["/api/filter-presets"],enabled:s,retry:!1}),{data:M,refetch:me}=Qe({queryKey:["/api/subscription/status"],enabled:s&&!!(t!=null&&t.isSubscribed),retry:!1}),Ve=Jl(t),xt=(M==null?void 0:M.isTrialing)===!0||Ve.isTrialing,Ht=(M==null?void 0:M.trialEnd)??Ve.trialEndsAt,{data:be}=Qe({queryKey:["/api/subscription/next-billing-amount"],enabled:s&&!!(t!=null&&t.isSubscribed)&&!!(t!=null&&t.stripeSubscriptionId),retry:!1,staleTime:300*1e3}),ra=(be==null?void 0:be.formatted)||(typeof(M==null?void 0:M.firstChargeAmountCents)=="number"&&M.firstChargeAmountCents>0?pc(M.firstChargeAmountCents):""),{data:na}=Qe({queryKey:["/api/email-schedules"],enabled:s,retry:!1}),{data:pa,refetch:Va}=Qe({queryKey:["/api/database-switch-status"],enabled:s&&ar(),retry:!1});ja();const{data:ct}=Qe({queryKey:["/api/user/account-stats"],enabled:s,retry:!1}),{data:qe}=Qe({queryKey:["/api/keyword-lists"],enabled:s,retry:!1}),{data:ht}=Qe({queryKey:["/api/keyword-generation-jobs"],enabled:s,retry:!1,refetchInterval:S=>{const se=S.state.data;return se&&se.some(Mt=>Mt.status==="pending")?5e3:!1}}),Os=qe&&qe.length>0&&qe.some(S=>!S.viewedAt),ws=ht&&ht.some(S=>S.status==="pending"),m=o.useRef(void 0);o.useEffect(()=>{if(ht&&m.current){const S=m.current.some(Re=>Re.status==="pending"),se=ht.some(Re=>Re.status==="pending");S&&!se&&z.invalidateQueries({queryKey:["/api/keyword-lists"]})}m.current=ht},[ht]);const D=o.useRef(y);o.useEffect(()=>{D.current==="filters"&&y!=="filters"&&z.invalidateQueries({queryKey:["/api/keyword-generation-jobs"]}),D.current=y},[y]);
242const[H,Z]=o.useState(!1),[we,Be]=o.useState(null),ge=()=>{fd(),Mr(),window.location.href="/api/logout"},dt=()=>{T("/")},vs=()=>{k("referrals")},Gs=S=>{},ia=void 0,xa=()=>{ne((t==null?void 0:t.firstName)||""),V((t==null?void 0:t.lastName)||""),pe((t==null?void 0:t.profileImageUrl)||"gradient-1"),G(!0)},or=Ne({mutationFn:async S=>(await ue("PATCH","/api/profile",S)).json(),onSuccess:()=>{i({title:"Profile Updated",description:"Your profile has been successfully updated."}),G(!1),z.invalidateQueries({queryKey:["/api/auth/user"]})},onError:S=>{ce("[Dashboard:1099]","Failed to update profile",S),i({title:"Error",description:"Failed to update profile. Please try again.",variant:"destructive"})}}),Is=()=>{or.mutate({firstName:te,lastName:Q,profileImageUrl:R})},qa=Ne({mutationFn:async()=>(await ue("POST","/api/reset-password",{})).json(),onSuccess:()=>{i({title:"Password Reset Email Sent",description:"Check your email for password reset instructions. You will be logged out shortly."}),G(!1),setTimeout(()=>{Mr(),window.location.href="/api/logout"},2e3)},onError:S=>{ce("[Dashboard:1133]","Failed to send password reset email",S),i({title:"Error",description:"Failed to send password reset email. Please try again.",variant:"destructive"})}}),cr=()=>{qa.mutate()},ha=()=>{He((t==null?void 0:t.companyName)||""),O((t==null?void 0:t.companyWebsite)||""),re((t==null?void 0:t.companyDescription)||""),tt((t==null?void 0:t.productService)||""),W((t==null?void 0:t.jobTitle)||""),ve((t==null?void 0:t.targetCategories)||[]),vt((t==null?void 0:t.targetLocations)||{type:""}),At((t==null?void 0:t.businessesToAvoid)||[]),Je((t==null?void 0:t.additionalContext)||""),Ct(""),kt(""),st(!1),t!=null&&t.companyWebsite&&xc(t.companyWebsite),We(!0)};o.useEffect(()=>{Se||(st(!1),oe(""),pt([]),ye(!1),rt(-1))},[Se]);const Ha=()=>{if(!Te.trim())return;const se=Te.split(",").map(Re=>Re.trim()).filter(Re=>Re.length>0).filter(Re=>!Le.some(Mt=>Mt.toLowerCase()===Re.toLowerCase()));se.length>0&&ve([...Le,...se]),Ct("")},Ts=S=>{ve(Le.filter(se=>se!==S))},Wa=async()=>{Ot(!0),mt(null);try{const se=await(await ue("POST","/api/suggest-categories",{companyName:Me,companyDescription:I,productService:Pe,websiteUrl:ee||void 0,smbType:ss,excludeCategories:Le})).json();qt(se.categories||[])}catch(S){ce("[Dashboard:1224]","Error fetching category suggestions",S),mt("Failed to load suggestions")}finally{Ot(!1)}},dr=async(S,se=!1)=>{const Re=S||ee;if(Re.trim()){if(!Xs(Re)){i({title:"Invalid Website",description:"Please enter a valid website URL (e.g., example.com or https://example.com).",variant:"destructive"});return}ot(!0);try{const Mt=await ue("POST","/api/rescan-website",{websiteUrl:Re,updateProfile:se});if(z.invalidateQueries({queryKey:["/api/auth/user"]}),Mt.ok){let Et={};try{Et=await Mt.json()}catch{}Pt(new Date().toISOString()),Et.analysisSucceeded!==!1?i({title:"Website Analyzed Successfully",description:"Your website has been analyzed. AI suggestions will now use updated information."}):(ce("dashboard","Website analysis issue",void 0,{message:Et.message}),i({title:"Analysis Issue",description:Et.message||"We couldn't fully analyze your website. Please verify the URL is correct.",variant:"destructive"}))}else{let Et={};try{Et=await Mt.json()}catch{}ce("dashboard","Re-scan failed",void 0,{message:Et.message}),i({title:"Re-scan Failed",description:Et.message||"Failed to re-scan website",variant:"destructive"})}}catch(Mt){ce("[Dashboard:handleRescanWebsite]","Error re-scanning website",Mt),z.invalidateQueries({queryKey:["/api/auth/user"]}),i({title:"Error",description:"Failed to re-scan website. Please try again.",variant:"destructive"})}finally{ot(!1)}}},xc=async S=>{if(!S.trim()){Pt(null);return}try{const se=await ue("GET",`/api/website-analysis-status?url=${encodeURIComponent(S)}`);if(se.ok){const Re=await se.json();Pt(Re.lastAnalyzed||null)}}catch{}},kn=()=>{k("settings"),Fa(t)&&!_t&&!P&&(It((t==null?void 0:t.companyWebsite)||""),Ce(null),ze(!0))},hc=async()=>{if(Ge===1)ze(!1),le(!0),await dr((t==null?void 0:t.companyWebsite)||"",!1);else if(Ge===2){if(!gt.trim()){ce("dashboard","Validation: website required"),i({title:"Website Required",description:"Please enter your website URL.",variant:"destructive"});return}
242if(!Xs(gt)){ce("dashboard","Validation: invalid website URL",void 0,{url:gt}),i({title:"Invalid Website",description:"Please enter a valid website URL (e.g., example.com or https://example.com).",variant:"destructive"});return}ze(!1),le(!0),await dr(gt,!0)}else if(Ge===3){ze(!1);try{(await fetch("/api/website-opt-out",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({optOut:!0})})).ok&&(z.invalidateQueries({queryKey:["/api/auth/user"]}),i({title:"Preference Saved",description:"We'll skip website analysis for keyword generation."}))}catch(S){ce("dashboard","Failed to save opt-out preference",S),i({title:"Error",description:"Failed to save preference. Please try again.",variant:"destructive"})}}},ji=S=>{S||(ze(!1),de(!0))},gc=S=>{Le.includes(S)?Ts(S):ve([...Le,S])},Ni=()=>{if(!lt.trim())return;const se=lt.split(",").map(Re=>Re.trim()).filter(Re=>Re.length>0).filter(Re=>!Rt.some(Mt=>Mt.toLowerCase()===Re.toLowerCase()));se.length>0&&At([...Rt,...se]),kt("")},yc=S=>{At(Rt.filter(se=>se!==S))},Ar=S=>{vt({type:S,data:[]})},fc=S=>{vt(se=>{var Re;return{...se,data:(Re=se.data)!=null&&Re.includes(S)?se.data.filter(Mt=>Mt!==S):[...se.data||[],S]}})},Lr=S=>{if(!S.trim())return;const se=S.trim();if((Oe.data||[]).some(Et=>Et.toLowerCase()===se.toLowerCase())){ce("dashboard","Duplicate city",void 0,{city:se}),i({title:"City already added",description:`"${se}" is already in your list.`,variant:"destructive"});return}vt(Et=>({...Et,data:[...Et.data||[],se]}))},bc=S=>{vt(se=>{var Re;return{...se,data:((Re=se.data)==null?void 0:Re.filter(Mt=>Mt!==S))||[]}})},wc=S=>{if(oe(S),rt(-1),S.trim().length>0){const se=wu.filter(Re=>Re.toLowerCase().includes(S.toLowerCase())).slice(0,10);pt(se),ye(se.length>0)}else pt([]),ye(!1)},Ei=S=>{Lr(S),oe(""),pt([]),ye(!1),rt(-1)},vc=S=>{if(!jt||Ye.length===0){S.key==="Enter"?(S.preventDefault(),Ft.trim()&&(Lr(Ft),oe(""),ye(!1))):S.key==="Escape"&&(ye(!1),rt(-1));return}switch(S.key){case"ArrowDown":S.preventDefault(),rt(se=>se<Ye.length-1?se+1:0);break;case"ArrowUp":S.preventDefault(),rt(se=>se>0?se-1:Ye.length-1);break;case"Enter":S.preventDefault(),Xt>=0?Ei(Ye[Xt]):Ft.trim()&&(Lr(Ft),oe(""),ye(!1));break;case"Escape":ye(!1),rt(-1);break;case"Tab":ye(!1),rt(-1);break}},Fn=Ne({mutationFn:async S=>(await ue("PATCH","/api/onboarding-settings",S)).json(),onSuccess:()=>{i({title:"Settings Updated",description:"Your business settings have been successfully updated."}),We(!1),z.invalidateQueries({queryKey:["/api/auth/user"]})},onError:S=>{ce("[Dashboard:1430]","Failed to update onboarding settings",S),i({title:"Error",description:"Failed to update settings. Please try again.",variant:"destructive"})}}),jc=()=>{let S=[...Le],se=[...Rt];if(Te.trim()){const Mt=Te.split(",").map(Et=>Et.trim()).filter(Et=>Et.length>0).filter(Et=>!S.some(qs=>qs.toLowerCase()===Et.toLowerCase()));S=[...S,...Mt],ve(S),Ct("")}if(lt.trim()){const Mt=lt.split(",").map(Et=>Et.trim()).filter(Et=>Et.length>0).filter(Et=>!se.some(qs=>qs.toLowerCase()===Et.toLowerCase()));se=[...se,...Mt],At(se),kt("")}if(!Me.trim()){ce("dashboard","Validation: company name required"),i({title:"Validation Error",description:"Company Name is required",variant:"destructive"});return}if(!ee.trim()){ce("dashboard","Validation: company website required"),i({title:"Validation Error",description:"Company Website is required",variant:"destructive"});return}if(!Xs(ee)){ce("dashboard","Validation: invalid website URL"),i({title:"Validation Error",description:"Please enter a valid website URL (e.g., example.com or https://example.com)",variant:"destructive"});return}if(!I.trim()){ce("dashboard","Validation: company description required"),i({title:"Validation Error",description:"Company Description is required",variant:"destructive"});return}if(!Pe.trim()){ce("dashboard","Validation: product/service required"),i({title:"Validation Error",description:"Product/Service is required",variant:"destructive"});return}if(S.length===0){ce("dashboard","Validation: no target categories"),i({title:"Validation Error",description:"At least one Target SMB Type is required",variant:"destructive"});return}Fn.mutate({companyName:Me,companyWebsite:ee,companyDescription:I,productService:Pe,
242jobTitle:$e,targetCategories:S,targetLocations:Oe,businessesToAvoid:se,additionalContext:at})},Nc=()=>{L(!0)},Ec=()=>{q(!1),setTimeout(()=>{T("/exclusive-pricing")},0)},Sc=async()=>{if(!(t!=null&&t.isSubscribed)||!(t!=null&&t.stripeSubscriptionId)){ce("dashboard","No active subscription for downgrade"),i({title:"Error",description:"No active subscription found",variant:"destructive"});return}try{const se=await(await ue("POST","/api/subscription/cancel",{})).json();if(se!=null&&se.isTrial){const Re=oa(se.trialEndsAt)||oa(Ht);i({title:"Free Trial Cancelled",description:Re?`You will not be charged. Your access and any remaining trial credits end on ${Re}.`:"You will not be charged. Your access and any remaining trial credits end when your trial ends."})}else i({title:"Subscription Cancelled",description:`Your ${Ia(t==null?void 0:t.subscriptionPlan).name} will remain active until ${new Date(se.currentPeriodEnd*1e3).toLocaleDateString()}, then your account will no longer have an active paid plan.`});_(!1),q(!1),z.invalidateQueries({queryKey:["/api/auth/user"]}),Mr(),await me()}catch(S){ce("[Dashboard:1574]","Failed to cancel subscription:",S),i({title:"Error",description:S.message||"Failed to cancel subscription. Please try again.",variant:"destructive"})}},Rr=Math.max(0,((t==null?void 0:t.monthlyCredits)||0)-((t==null?void 0:t.monthlyCreditsUsed)||0))+((t==null?void 0:t.permanentCredits)||0),Si=async()=>{if(!B){K(!0);try{await ue("POST","/api/subscription/reactivate",{}),i({title:"Subscription Reactivated",description:"Auto-renew is back on. Your plan continues as normal and your credits are safe."}),z.invalidateQueries({queryKey:["/api/auth/user"]}),Mr(),await me()}catch(S){ce("dashboard","Failed to reactivate subscription:",S),i({title:"Error",description:S.message||"Failed to reactivate subscription. Please try again.",variant:"destructive"})}finally{K(!1)}}},Ci=async()=>{try{const se=await(await ue("POST","/api/create-billing-portal-session",{})).json();se.url&&(window.location.href=se.url)}catch(S){ce("[Dashboard:1597]","Failed to open billing portal:",S),i({title:"Error",description:"Failed to open billing portal. Please try again.",variant:"destructive"})}};if(r||!s)return null;const Cc=()=>{switch(y){case"leads":return t!=null&&t.onboardingCompleted?null:ss==="home_improvement"?e.jsx(cl,{isSubscribed:!!(t!=null&&t.isSubscribed),subscriptionPlan:t==null?void 0:t.subscriptionPlan,userId:t==null?void 0:t.id,freeLeadsUsed:(t==null?void 0:t.freeLeadsUsed)||0,monthlyCredits:(t==null?void 0:t.monthlyCredits)||0,monthlyCreditsUsed:(t==null?void 0:t.monthlyCreditsUsed)||0,permanentCredits:(t==null?void 0:t.permanentCredits)||0,isVisible:!0,onOpenGenerateDialog:ts,keywordGenerationJobs:ht,onboardingCategoryFilter:(t==null?void 0:t.onboardingCategoryFilter)||void 0,onSwitchDatabase:ia}):e.jsx(pl,{isSubscribed:!!(t!=null&&t.isSubscribed),subscriptionPlan:t==null?void 0:t.subscriptionPlan,userId:t==null?void 0:t.id,freeLeadsUsed:(t==null?void 0:t.freeLeadsUsed)||0,monthlyCredits:(t==null?void 0:t.monthlyCredits)||0,monthlyCreditsUsed:(t==null?void 0:t.monthlyCreditsUsed)||0,permanentCredits:(t==null?void 0:t.permanentCredits)||0,isVisible:!0,onOpenGenerateDialog:ts,keywordGenerationJobs:ht,onboardingCategoryFilter:(t==null?void 0:t.onboardingCategoryFilter)||void 0,onSwitchDatabase:ia});case"enrichments":return e.jsx(vx,{});case"filters":return e.jsx(Up,{onApplyFilters:v,keywordGenerationJobs:ht,showGenerateDialog:hs,setShowGenerateDialog:gs,showCreateDialog:Ms,setShowCreateDialog:Zt,forceBothKeywordType:b});case"exports":return e.jsx(Jp,{userId:(t==null?void 0:t.id)||"",smbType:ss,subscriptionPlan:(t==null?void 0:t.subscriptionPlan)??void 0,isSubscribed:(t==null?void 0:t.isSubscribed)||!1,freeLeadsUsed:(t==null?void 0:t.freeLeadsUsed)||0,monthlyCredits:(t==null?void 0:t.monthlyCredits)||0,monthlyCreditsUsed:(t==null?void 0:t.monthlyCreditsUsed)||0,permanentCredits:(t==null?void 0:t.permanentCredits)||0});case"schedules":return e.jsx(Qp,{userId:(t==null?void 0:t.id)||"",userEmail:(t==null?void 0:t.email)||"",isSubscribed:(t==null?void 0:t.isSubscribed)||!1,smbType:ss,onDatabaseSwitch:ia});case"api":return e.jsx(tx,{});case"integrations":return e.jsx(gx,{});case"settings":return e.jsx(Lx,{user:t,accountStats:ct,databaseSwitchStatus:pa,upcomingBilling:be,isRescanningWebsite:ut,websitePopupDismissed:_t,websiteRescanTriggered:P,setWebsiteRescanTriggered:le,setPopupWebsiteInput:It,setPopupSelectedOption:Ce,setShowWebsiteAnalysisPopup:ze,handleManageBilling:Nc,handleManageBillingPortal:Ci,handleOpenProfileDialog:xa,handleOpenOnboardingSettings:ha,handleDatabaseSwitch:Gs,handleRescanWebsite:dr});case"referrals":return e.jsx(Sd,{});case"admin":return t!=null&&t.isAdmin?e.jsx(o.Suspense,{fallback:e.jsx(bd,{text:"Loading Admin..."}),children:e.jsx(Ox,{isVisible:y==="admin"})}):e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(Ue,{className:"max-w-md",children:e.jsxs(_e,{className:"p-6 text-center",children:[e.jsx("p",{className:"text-lg font-semibold text-gray-900",children:"Access Denied"}),e.jsx("p",{className:"text-gray-700 mt-2",children:"You do not have permission to access this page."})]})})})}};return e.jsxs("div",{className:"min-h-screen bg-gray-50 text-gray-900 overflow-x-hidden",style:E>0?{paddingBottom:`${E}px`}:void 0,children:[e.jsx("header",{className:"border-b border-gray-200 bg-white shadow-sm",children:e.jsx("div",{className:"max-w-7xl mx-auto px-3 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"flex justify-between items-center py-3 sm:py-4",children:[e.jsx("div",{className:"flex items-center space-x-2 sm:space-x-4",children:e.jsxs("button",{onClick:dt,className:"text-base sm:text-2xl font-bold flex items-center gap-1 sm:gap-2 hover:opacity-80 transition-opacity cursor-pointer","data-testid":"button-logo-home",children:[e.jsx("img",{src:cd,alt:"SMB Sales Boost logo",className:"w-6 h-6 sm:w-8 sm:h-8 flex-shrink-0",loading:"eager"}),e.jsx("span",{className:"text-gray-900 whitespace-nowrap",children:"SMB Sales Boost"})]})}),e.jsx("div",{className:"flex items-center space-x-2 sm:space-x-4",children:e.jsxs(dd,{children:[e.jsx(md,{asChild:!0,children:e.jsxs("button",{className:"flex items-center space-x-2 hover:opacity-80 transition-opacity cursor-pointer","data-testid":"button-profile-menu",children:[t&&(t.isSubscribed?e.jsxs(e.Fragment,{children:[e.jsxs(ie,{className:Ll(t.subscriptionPlan).className,children:[e.jsx("div",{className:Ll(t.subscriptionPlan).dotClass}),Ia(t.subscriptionPlan).name]}),xt&&e.jsxs(ie,{className:"bg-blue-100 text-blue-700 text-xs hidden sm:flex","data-testid":"badge-header-trial",children:["Free trial: ",Ql(Ht)]}),e.jsx(fu,{user:t})]}):e.jsxs(ie,{className:"bg-amber-50 text-amber-700 border border-amber-200 text-xs flex items-center gap-1",children:[Math.max(0,20-(t.freeLeadsUsed||0))," credits",e.jsx("img",{src:ii,alt:"",className:"h-3.5 w-3.5"})]})),e.jsx("span",{className:"text-sm text-gray-700 hidden sm:inline",children:(t==null?void 0:t.firstName)||(t==null?void 0:t.email)}),e.jsx(ud,{avatarId:(t==null?void 0:t.profileImageUrl)||void 0,initials:t!=null&&t.firstName&&(t!=null&&t.lastName)?`${t.firstName[0]}${t.lastName[0]}`:((Fi=t==null?void 0:t.email)==null?void 0:Fi[0])||"U",size:"sm"})]})}),e.jsxs(pd,{align:"end",className:"w-48",children:[e.jsxs(Bs,{onClick:()=>k("leads"),className:"cursor-pointer","data-testid":"menu-item-leads",children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Leads"})]}),e.jsxs(Bs,{onClick:()=>k("enrichments"),className:"cursor-pointer","data-testid":"menu-item-enrichments",children:[e.jsx(Kt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Enrichments"})]}),e.jsxs(Bs,{onClick:()=>k("filters"),className:"cursor-pointer","data-testid":"menu-item-filters",children:[e.jsx(Ls,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"flex-1",children:"Keywords"}),(ws||Os)&&e.jsx("div",{className:"flex-shrink-0 ml-2",children:ws?e.jsx(Lt,{size:14}):e.jsx(da,{className:"h-4 w-4 text-green-600"})})]}),e.jsxs(Bs,{onClick:()=>k("exports"),className:"cursor-pointer","data-testid":"menu-item-exports",children:[e.jsx(Qs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Exports"})]}),e.jsxs(Bs,{onClick:()=>k("schedules"),className:"cursor-pointer","data-testid":"menu-item-schedules",children:[e.jsx(La,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Schedules"})]}),e.jsxs(Bs,{onClick:kn,className:"cursor-pointer","data-testid":"menu-item-settings",children:[e.jsx(Ga,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"flex-1",children:"Settings"}),Fa(t)&&!P&&e.jsx("div",{className:"flex-shrink-0 ml-2",children:e.jsx(Tn,{className:"h-4 w-4 text-orange-500 fill-orange-500"})})]}),e.jsxs(Bs,{onClick:vs,className:"cursor-pointer","data-testid":"menu-item-referrals",children:[e.jsx(Dr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Referrals"})]}),e.jsxs(Bs,{onClick:()=>k("api"),className:"cursor-pointer","data-testid":"menu-item-api",children:[e.jsx(Ta,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"API"})]}),e.jsxs(Bs,{onClick:()=>k("integrations"),className:"cursor-pointer","data-testid":"menu-item-integrations",children:[e.jsx(wr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Integrations"})]}),(t==null?void 0:t.isAdmin)&&e.jsxs(Bs,{onClick:()=>k("admin"),className:"cursor-pointer","data-testid":"menu-item-admin",children:[e.jsx(Za,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Admin"})]}),e.jsx(xd,{}),e.jsxs(Bs,{onClick:ge,className:"cursor-pointer text-red-600","data-testid":"menu-item-logout",children:[e.jsx(hd,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Log Out"})]})]})]})})]})})}),e.jsxs("div",{className:"flex w-full",children:[e.jsx("div",{className:"hidden md:block md:w-64 bg-white border-r border-gray-200 min-h-screen flex-shrink-0",children:e.jsx("div",{className:"p-4",children:e.jsxs("nav",{className:"space-y-2",children:[e.jsxs("button",{onClick:()=>k("leads"),className:`w-full flex items-center space-x-3 px-3 py-2 rounded-lg text-left transition-colors ${y==="leads"?"bg-blue-100 text-blue-700 font-medium":"text-gray-700 hover:bg-gray-100"}`,"data-testid":"nav-leads",children:[e.jsx(yr,{className:"h-5 w-5"}),e.jsx("span",{children:"Leads"})]}),e.jsxs("button",{onClick:()=>k("enrichments"),className:`w-full flex items-center space-x-3 px-3 py-2 rounded-lg text-left transition-colors ${y==="enrichments"?"bg-blue-100 text-blue-700 font-medium":"text-gray-700 hover:bg-gray-100"}`,"data-testid":"nav-enrichments",children:[e.jsx(Kt,{className:"h-5 w-5"}),e.jsx("span",{children:"Enrichments"})]}),e.jsxs("button",{onClick:()=>k("filters"),className:`w-full flex items-center space-x-3 px-3 py-2 rounded-lg text-left transition-colors ${y==="filters"?"bg-blue-100 text-blue-700 font-medium":"text-gray-700 hover:bg-gray-100"}`,"data-testid":"nav-filters",children:[e.jsx(Ls,{className:"h-5 w-5"}),e.jsx("span",{className:"flex-1",children:"Keywords"}),(ws||Os)&&e.jsxs(Ra,{children:[e.jsx(Oa,{asChild:!0,children:e.jsx("div",{"data-testid":"keyword-status-indicator",children:ws?e.jsx(Lt,{size:14}):e.jsx(da,{className:"h-6 w-6 text-green-600"})})}),e.jsx(Da,{children:ws?"You have keywords currently generating":"Your keywords are ready!"})]})]}),e.jsxs("button",{onClick:()=>k("exports"),className:`w-full flex items-center space-x-3 px-3 py-2 rounded-lg text-left transition-colors ${y==="exports"?"bg-blue-100 text-blue-700 font-medium":"text-gray-700 hover:bg-gray-100"}`,"data-testid":"nav-exports",children:[e.jsx(Qs,{className:"h-5 w-5"}),e.jsx("span",{children:"Exports"})]}),e.jsxs("button",{onClick:()=>k("schedules"),className:`w-full flex items-center space-x-3 px-3 py-2 rounded-lg text-left transition-colors ${y==="schedules"?"bg-blue-100 text-blue-700 font-medium":"text-gray-700 hover:bg-gray-100"}`,"data-testid":"nav-schedules",children:[e.jsx(La,{className:"h-5 w-5"}),e.jsx("span",{children:"Email Schedules"})]}),e.jsxs("button",{onClick:kn,className:`w-full flex items-center space-x-3 px-3 py-2 rounded-lg text-left transition-colors ${y==="settings"?"bg-blue-100 text-blue-700 font-medium":"text-gray-700 hover:bg-gray-100"}`,"data-testid":"nav-settings",children:[e.jsx(Ga,{className:"h-5 w-5"}),e.jsx("span",{className:"flex-1",children:"Settings"}),Fa(t)&&!P&&e.jsx("div",{className:"flex-shrink-0 ml-2",children:e.jsx(Tn,{className:"h-5 w-5 text-orange-500 fill-orange-500"})})]}),e.jsxs("button",{onClick:vs,className:`w-full flex items-center space-x-3 px-3 py-2 rounded-lg text-left transition-colors ${y==="referrals"?"bg-blue-100 text-blue-700 font-medium":"text-gray-700 hover:bg-gray-100"}`,"data-testid":"nav-referrals",children:[e.jsx(Dr,{className:"h-5 w-5"}),e.jsx("span",{children:"Referrals"})]}),e.jsxs("button",{onClick:()=>k("api"),className:`w-full flex items-center space-x-3 px-3 py-2 rounded-lg text-left transition-colors ${y==="api"?"bg-blue-100 text-blue-700 font-medium":"text-gray-700 hover:bg-gray-100"}`,"data-testid":"nav-api",children:[e.jsx(Ta,{className:"h-5 w-5"}),e.jsx("span",{children:"API"})]}),e.jsxs("button",{onClick:()=>k("integrations"),className:`w-full flex items-center space-x-3 px-3 py-2 rounded-lg text-left transition-colors ${y==="integrations"?"bg-blue-100 text-blue-700 font-medium":"text-gray-700 hover:bg-gray-100"}`,"data-testid":"nav-integrations",children:[e.jsx(wr,{className:"h-5 w-5"}),e.jsx("span",{children:"Integrations"})]}),(t==null?void 0:t.isAdmin)&&e.jsxs("button",{onClick:()=>k("admin"),className:`w-full flex items-center space-x-3 px-3 py-2 rounded-lg text-left transition-colors ${y==="admin"?"bg-blue-100 text-blue-700 font-medium":"text-gray-700 hover:bg-gray-100"}`,"data-testid":"nav-admin",children:[e.jsx(Za,{className:"h-5 w-5"}),e.jsx("span",{children:"Admin"})]})]})})}),e.jsxs("div",{className:"flex-1 p-3 sm:p-6 w-full max-w-full min-w-0",style:E>0?{paddingBottom:`${E}px`}:void 0,children:[e.jsx("div",{className:"md:hidden mb-4 overflow-x-auto",children:e.jsxs("div",{className:"flex space-x-2 pb-2",children:[e.jsxs("button",{onClick:()=>k("leads"),className:`flex items-center space-x-2 px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap ${y==="leads"?"bg-blue-100 text-blue-700":"text-gray-700 bg-white border border-gray-200"}`,"data-testid":"mobile-nav-leads",children:[e.jsx(yr,{className:"h-4 w-4"}),e.jsx("span",{children:"Leads"})]}),e.jsxs("button",{onClick:()=>k("enrichments"),className:`flex items-center space-x-2 px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap ${y==="enrichments"?"bg-blue-100 text-blue-700":"text-gray-700 bg-white border border-gray-200"}`,"data-testid":"mobile-nav-enrichments",children:[e.jsx(Kt,{className:"h-4 w-4"}),e.jsx("span",{children:"Enrichments"})]}),e.jsxs("button",{onClick:()=>k("filters"),className:`flex items-center space-x-2 px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap relative ${y==="filters"?"bg-blue-100 text-blue-700":"text-gray-700 bg-white border border-gray-200"}`,"data-testid":"mobile-nav-filters",children:[e.jsx(Ls,{className:"h-4 w-4"}),e.jsx("span",{children:"Keywords"}),(ws||Os)&&e.jsx("div",{"data-testid":"mobile-keyword-status-indicator",className:"flex-shrink-0",children:ws?e.jsx(Lt,{size:14}):e.jsx(da,{className:"h-6 w-6 text-green-600"})})]}),e.jsxs("button",{onClick:()=>k("exports"),className:`flex items-center space-x-2 px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap ${y==="exports"?"bg-blue-100 text-blue-700":"text-gray-700 bg-white border border-gray-200"}`,"data-testid":"mobile-nav-exports",children:[e.jsx(Qs,{className:"h-4 w-4"}),e.jsx("span",{children:"Exports"})]}),e.jsxs("button",{onClick:()=>k("schedules"),className:`flex items-center space-x-2 px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap ${y==="schedules"?"bg-blue-100 text-blue-700":"text-gray-700 bg-white border border-gray-200"}`,"data-testid":"mobile-nav-schedules",children:[e.jsx(La,{className:"h-4 w-4"}),e.jsx("span",{children:"Schedules"})]}),e.jsxs("button",{onClick:kn,className:`flex items-center space-x-2 px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap relative ${y==="settings"?"bg-blue-100 text-blue-700":"text-gray-700 bg-white border border-gray-200"}`,"data-testid":"mobile-nav-settings",children:[e.jsx(Ga,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"}),Fa(t)&&!P&&e.jsx("div",{className:"flex-
242shrink-0 ml-1",children:e.jsx(Tn,{className:"h-4 w-4 text-orange-500 fill-orange-500"})})]}),e.jsxs("button",{onClick:vs,className:`flex items-center space-x-2 px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap ${y==="referrals"?"bg-blue-100 text-blue-700":"text-gray-700 bg-white border border-gray-200"}`,"data-testid":"mobile-nav-referrals",children:[e.jsx(Dr,{className:"h-4 w-4"}),e.jsx("span",{children:"Referrals"})]}),e.jsxs("button",{onClick:()=>k("api"),className:`flex items-center space-x-2 px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap ${y==="api"?"bg-blue-100 text-blue-700":"text-gray-700 bg-white border border-gray-200"}`,"data-testid":"mobile-nav-api",children:[e.jsx(Ta,{className:"h-4 w-4"}),e.jsx("span",{children:"API"})]}),e.jsxs("button",{onClick:()=>k("integrations"),className:`flex items-center space-x-2 px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap ${y==="integrations"?"bg-blue-100 text-blue-700":"text-gray-700 bg-white border border-gray-200"}`,"data-testid":"mobile-nav-integrations",children:[e.jsx(wr,{className:"h-4 w-4"}),e.jsx("span",{children:"Integrations"})]}),(t==null?void 0:t.isAdmin)&&e.jsxs("button",{onClick:()=>k("admin"),className:`flex items-center space-x-2 px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap ${y==="admin"?"bg-blue-100 text-blue-700":"text-gray-700 bg-white border border-gray-200"}`,"data-testid":"mobile-nav-admin",children:[e.jsx(Za,{className:"h-4 w-4"}),e.jsx("span",{children:"Admin"})]})]})}),(t==null?void 0:t.isSubscribed)&&xt&&((t==null?void 0:t.cancelAtPeriodEnd)||(M==null?void 0:M.cancelAtPeriodEnd))&&e.jsx(Rx,{trialEndsAt:Ht,plan:t==null?void 0:t.subscriptionPlan,firstChargeAmountCents:M==null?void 0:M.firstChargeAmountCents,chargeLabel:ra,cancelAtPeriodEnd:(t==null?void 0:t.cancelAtPeriodEnd)||(M==null?void 0:M.cancelAtPeriodEnd),onCancelTrial:()=>X(!0),onReactivate:Si,isReactivating:B}),(t==null?void 0:t.isSubscribed)&&(t==null?void 0:t.cancelAtPeriodEnd)&&!xt&&e.jsx(Ue,{className:"border-2 border-amber-300 bg-amber-50 mb-4 sm:mb-6","data-testid":"banner-pending-cancellation",children:e.jsx(_e,{className:"p-4 sm:p-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3 flex-1 min-w-0",children:[e.jsx(ps,{className:"h-5 w-5 text-amber-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm text-gray-800 min-w-0",children:[e.jsxs("p",{className:"font-semibold",children:["Your subscription is set to cancel",t!=null&&t.nextBillDate?` on ${new Date(t.nextBillDate).toLocaleDateString()}`:" at the end of your billing period","."]}),e.jsxs("p",{className:"text-gray-700",children:["When it ends, your remaining balance of"," ",e.jsxs("span",{className:"font-semibold",children:[Rr.toLocaleString()," credit",Rr===1?"":"s"]})," ","will be lost. Reactivate to keep everything, and your next charge stays on your normal billing date."]})]})]}),e.jsx(N,{onClick:Si,disabled:B,className:"bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 shrink-0","data-testid":"button-reactivate-banner",children:B?"Reactivating...":"Reactivate Subscription"})]})})}),!(t!=null&&t.isSubscribed)&&y!=="admin"&&e.jsx(Ue,{className:"bg-gradient-to-r from-blue-50 to-purple-50 border-blue-200 mb-4 sm:mb-6 overflow-hidden",children:e.jsxs(_e,{className:"p-4 sm:p-6 text-center",children:[e.jsx("h2",{className:"text-xl sm:text-2xl font-bold mb-2 break-words",children:"Welcome to SMB Sales Boost! ð"}),e.jsxs("p",{className:"text-sm sm:text-base text-gray-700 mb-4 break-words",children:["You have"," ",20-((t==null?void 0:t.freeLeadsUsed)||0)," starter credits remaining. Upgrade to a paid plan for more credits, full contact details on the dashboard, and automated email delivery of new leads."]}),e.jsxs("div",{className:"space-y-3",children:[d&&e.jsx(ie,{className:"bg-orange-500 text-white font-bold animate-pulse mx-auto block w-fit text-xs sm:text-sm",children:d.mainCopy}),e.jsx("a",{href:"/#pricing",children:e.jsx(N,{className:"bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 border-4 animate-border-glow hover:scale-[1.075] transition-transform duration-200 relative overflow-hidden py-4 sm:py-6 text-sm sm:text-xl font-semibold mx-auto w-fit sm:max-w-md","data-testid":"button-upgrade-main",children:e.jsx("span",{className:"break-words",children:"ð Get Started - Plans from $49/mo"})})})]})]})}),gd({paused:J,activeSection:y})?e.jsx(Ue,{className:"border-2 border-amber-300 bg-amber-50","data-testid":"card-subscription-paused",children:e.jsxs(_e,{className:"p-6 sm:p-10 text-center",children:[e.jsx("div",{className:"mx-auto w-12 h-12 rounded-full bg-amber-100 flex items-center justify-center mb-4",children:e.jsx(ps,{className:"h-6 w-6 text-amber-600"})}),e.jsx("h2",{className:"text-xl sm:text-2xl font-bold text-gray-900 mb-2",children:"Your subscription is paused"}),e.jsx("p",{className:"text-sm sm:text-base text-gray-700 max-w-md mx-auto mb-6",children:"We can't load this view because your subscription is no longer active. Reactivate to continue finding leads and using your saved filters, schedules, and exports."}),e.jsxs(N,{onClick:()=>T("/#pricing"),className:"bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700","data-testid":"button-reactivate-subscription",children:[e.jsx(Pa,{className:"mr-2 h-5 w-5"}),"Reactivate to continue"]})]})}):e.jsxs(e.Fragment,{children:[Cc(),(t==null?void 0:t.onboardingCompleted)&&e.jsx("div",{style:y!=="leads"?{display:"none"}:void 0,children:ss==="home_improvement"?e.jsx(cl,{isSubscribed:!!(t!=null&&t.isSubscribed),subscriptionPlan:t==null?void 0:t.subscriptionPlan,userId:t==null?void 0:t.id,freeLeadsUsed:(t==null?void 0:t.freeLeadsUsed)||0,monthlyCredits:(t==null?void 0:t.monthlyCredits)||0,monthlyCreditsUsed:(t==null?void 0:t.monthlyCreditsUsed)||0,permanentCredits:(t==null?void 0:t.permanentCredits)||0,isVisible:y==="leads",onOpenGenerateDialog:ts,keywordGenerationJobs:ht,onboardingCategoryFilter:(t==null?void 0:t.onboardingCategoryFilter)||void 0,onSwitchDatabase:ia}):e.jsx(pl,{isSubscribed:!!(t!=null&&t.isSubscribed),subscriptionPlan:t==null?void 0:t.subscriptionPlan,userId:t==null?void 0:t.id,freeLeadsUsed:(t==null?void 0:t.freeLeadsUsed)||0,monthlyCredits:(t==null?void 0:t.monthlyCredits)||0,monthlyCreditsUsed:(t==null?void 0:t.monthlyCreditsUsed)||0,permanentCredits:(t==null?void 0:t.permanentCredits)||0,isVisible:y==="leads",onOpenGenerateDialog:ts,keywordGenerationJobs:ht,onboardingCategoryFilter:(t==null?void 0:t.onboardingCategoryFilter)||void 0,onSwitchDatabase:ia})})]})]})]}),e.jsx(os,{open:a,onOpenChange:L,children:e.jsxs(cs,{className:"max-w-lg","data-testid":"dialog-manage-billing",children:[e.jsx(as,{children:e.jsxs(rs,{className:"flex items-center space-x-2",children:[e.jsx(sn,{className:"h-5 w-5"}),e.jsx("span",{children:"Manage Billing"})]})}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[e.jsx("p",{className:"text-sm text-gray-700",children:"Current Plan"}),t!=null&&t.isSubscribed?e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{className:"font-semibold text-lg",children:[Ia(t==null?void 0:t.subscriptionPlan,be==null?void 0:be.formatted).name,(be==null?void 0:be.hasDiscount)&&(be==null?void 0:be.baseFormatted)&&e.jsxs("span",{className:"ml-2",children:[e.jsx("span",{className:"line-through text-gray-400 text-base",children:be.baseFormatted}),e.jsx("span",{className:"ml-2 text-green-600 text-lg",children:be.formatted}),e.jsx("span",{className:"text-base",children:"/month"})]}),!(be!=null&&be.hasDiscount)&&(be==null?void 0:be.formatted)&&e.jsxs("span",{className:"ml-2 text-gray-900",children:[be.formatted,"/month"]})]}),xt&&oa(Ht)&&e.jsxs("p",{className:"text-sm font-medium text-blue-700","data-testid":"text-billing-trial-line",children:["Free trial until ",oa(Ht),ra?`, then ${ra}/month`:""]}),(be==null?void 0:be.hasDiscount)&&((Pi=be==null?void 0:be.discount)==null?void 0:Pi.cyclesRemaining)!==null&&((Ii=be==null?void 0:be.discount)==null?void 0:Ii.cyclesRemaining)!==void 0&&e.jsxs("div",{className:"mt-2 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-gradient-to-r from-amber-100 to-yellow-100 border-2 border-amber-400 animate-[glow-pulse_2s_ease-in-out_infinite]",children:[e.jsx(Kt,{className:"h-3.5 w-3.5 text-amber-600"}),e.jsxs("span",{className:"text-xs font-medium text-amber-800",children:["Special discount ⢠",be.discount.cyclesRemaining," ",be.discount.cyclesRemaining===1?"month":"months"," remaining"]})]}),(be==null?void 0:be.hasDiscount)&&((Ti=be==null?void 0:be.discount)==null?void 0:Ti.type)==="forever"&&e.jsxs("div",{className:"mt-2 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-gradient-to-r from-amber-100 to-yellow-100 border-2 border-amber-400 animate-[glow-pulse_2s_ease-in-out_infinite]",children:[e.jsx(Kt,{className:"h-3.5 w-3.5 text-amber-600"}),e.jsx("span",{className:"text-xs font-medium text-amber-800",children:"Special discount ⢠Lifetime discount"})]}),(be==null?void 0:be.hasDiscount)&&((Ai=be==null?void 0:be.discount)==null?void 0:Ai.type)==="once"&&e.jsxs("div",{className:"mt-2 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-gradient-to-r from-amber-100 to-yellow-100 border-2 border-amber-400 animate-[glow-pulse_2s_ease-in-out_infinite]","data-testid":"badge-one-time-discount",children:[e.jsx(Kt,{className:"h-3.5 w-3.5 text-amber-600"}),e.jsx("span",{className:"text-xs font-medium text-amber-800",children:be.amount===0?"Your next charge is covered, then billing resumes as normal":"Special discount ⢠Applies to your next charge only"})]})]}):e.jsx("p",{className:"font-semibold text-lg",children:"No Active Plan"})]}),!(t!=null&&t.isSubscribed)&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold text-gray-900",children:"Upgrade Your Plan"}),e.jsx("a",{href:"/#pricing",children:e.jsxs(N,{className:"w-full h-12 text-base bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 border-4 animate-border-glow hover:scale-[1.075] transition-transform duration-200","data-testid":"button-upgrade-pro",children:[e.jsx(Pa,{className:"mr-2 flex-shrink-0",size:24,style:{minWidth:"24px",minHeight:"24px"}}),"Get Started - Plans from $49/mo"]})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold text-gray-900",children:"Exclusive Access"}),e.jsx("p",{className:"text-sm text-gray-700",children:"Block other employees at your company from accessing the database with our Platinum or Enterprise plans."}),e.jsxs(N,{onClick:Ec,variant:"outline",className:"w-full border-2 border-blue-500 hover:bg-blue-50","data-testid":"button-exclusive-pricing",children:[e.jsx(Td,{className:"mr-2 h-4 w-4"}),"View Exclusive Pricing",e.jsx(aa,{className:"ml-2 h-3 w-3"})]})]}),(t==null?void 0:t.isSubscribed)&&e.jsxs("div",{className:"space-y-3 pt-4 border-t border-gray-200",children:[e.jsx("h3",{className:"font-semibold text-gray-900",children:"Manage Subscription"}),e.jsx("p",{className:"text-sm text-gray-700",children:xt?"Update your payment method, view invoices, or cancel your free trial before it converts.":"Update payment methods, view invoices, or cancel your subscription."}),e.jsxs(N,{onClick:Ci,variant:"outline",className:"w-full border-blue-500 text-blue-600 hover:bg-blue-50","data-testid":"button-manage-billing",children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Manage Billing Details"]}
242),e.jsxs(N,{onClick:()=>{q(!1),X(!0)},variant:"outline",className:"w-full text-orange-600 hover:text-orange-700 hover:bg-orange-50","data-testid":"button-cancel-subscription",children:[e.jsx(Yr,{className:"mr-2 h-4 w-4"}),xt?"Cancel Free Trial":"Cancel Subscription"]})]}),e.jsx("div",{className:"pt-4 border-t border-gray-200",children:e.jsx("p",{className:"text-xs text-gray-500 text-center",children:"All billing information and processing is handled securely by Stripe. We do not collect, store, or have access to any billing information."})})]})]})}),$&&e.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-[100]",onClick:()=>X(!1),children:e.jsxs(Ue,{className:"w-full max-w-md mx-4 bg-white",onClick:S=>S.stopPropagation(),children:[e.jsxs(zt,{className:"relative",children:[e.jsxs(Vt,{className:"flex items-center space-x-2 pr-8",children:[e.jsx(ps,{className:"h-5 w-5 text-orange-500"}),e.jsx("span",{children:xt?"Cancel your free trial":"Cancel Subscription"})]}),e.jsx("button",{onClick:()=>X(!1),className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 transition-colors","data-testid":"button-close-cancel-dialog",children:e.jsx(Ut,{className:"h-5 w-5"})})]}),e.jsxs(_e,{className:"space-y-4",children:[xt?e.jsxs("div",{className:"text-sm text-gray-700 space-y-2","data-testid":"text-cancel-trial-copy",children:[e.jsx("p",{children:"Are you sure you want to cancel your free trial?"}),e.jsxs("p",{className:"text-green-700 font-medium",children:["You will not be charged. Cancelling now means the"," ",Ia(t==null?void 0:t.subscriptionPlan).name," never starts and your card on file is never billed."]}),e.jsxs("p",{className:"text-gray-700",children:["Your access and any remaining trial credits end"," ",oa(Ht)?`on ${oa(Ht)}`:"when your trial ends",". You can keep using everything until then, and you can turn your plan back on any time before that date."]})]}):e.jsxs("div",{className:"text-sm text-gray-700 space-y-2",children:[e.jsx("p",{children:"Are you sure you want to cancel your subscription?"}),e.jsxs("p",{className:"text-orange-600 font-medium",children:["â ï¸ Your ",Ia(t==null?void 0:t.subscriptionPlan).name," will remain active until your next billing date, then your account will no longer have an active paid plan."]}),e.jsxs("p",{className:"text-red-600 font-medium","data-testid":"text-cancel-credit-warning",children:["Your remaining balance of"," ",Rr.toLocaleString()," credit",Rr===1?"":"s"," will be lost when your subscription ends. Credits are only kept while your subscription is active."]})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(N,{variant:"outline",onClick:()=>{X(!1),xt||q(!0)},className:"flex-1","data-testid":"button-cancel-dialog",children:xt?"Keep My Trial":"Keep Subscription"}),e.jsx(N,{onClick:Sc,className:"flex-1 bg-orange-600 hover:bg-orange-700","data-testid":"button-confirm-cancel",children:xt?"Cancel Free Trial":"Cancel Subscription"})]})]})]})}),e.jsx(os,{open:fe,onOpenChange:G,children:e.jsxs(cs,{"data-testid":"dialog-update-profile",onOpenAutoFocus:S=>S.preventDefault(),children:[e.jsxs(as,{children:[e.jsx(rs,{children:"Update Profile"}),e.jsx($s,{children:"Update your name, profile picture, or reset your password"})]}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{htmlFor:"firstName",children:"First Name"}),e.jsx(Ee,{id:"firstName",value:te,onChange:S=>ne(S.target.value),placeholder:"Enter your first name","data-testid":"input-first-name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{htmlFor:"lastName",children:"Last Name"}),e.jsx(Ee,{id:"lastName",value:Q,onChange:S=>V(S.target.value),placeholder:"Enter your last name","data-testid":"input-last-name"})]}),e.jsx(yd,{selectedAvatar:R,onSelectAvatar:pe,userInitials:te&&Q?`${te[0]}${Q[0]}`:t!=null&&t.firstName&&(t!=null&&t.lastName)?`${t.firstName[0]}${t.lastName[0]}`:"?"}),e.jsxs("div",{className:"border-t border-gray-200 pt-4",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Password"}),e.jsx("p",{className:"text-xs text-gray-500",children:"Reset your account password"})]})}),e.jsx(N,{variant:"outline",onClick:cr,disabled:qa.isPending,className:"w-full","data-testid":"button-reset-password",children:qa.isPending?"Sending...":"Reset Password"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t border-gray-200",children:[e.jsx(N,{variant:"outline",onClick:()=>G(!1),"data-testid":"button-cancel-profile",children:"Cancel"}),e.jsx(N,{onClick:Is,disabled:or.isPending,"data-testid":"button-save-profile",children:or.isPending?"Saving...":"Save Changes"})]})]})]})}),e.jsx(os,{open:it,onOpenChange:ji,children:e.jsxs(cs,{className:"max-w-md","data-testid":"dialog-website-analysis-issue",children:[e.jsxs(as,{children:[e.jsxs(rs,{className:"flex items-center gap-2 text-orange-600",children:[e.jsx(ps,{className:"h-5 w-5"}),"Website Analysis Issue"]}),e.jsx($s,{children:"We couldn't analyze your website. Please choose one of the options below to continue."})]}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:`p-3 rounded-lg border-2 cursor-pointer transition-all ${Ge===1?"border-orange-500 bg-orange-50":"border-gray-200 hover:border-gray-300"}`,onClick:()=>Ce(1),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`w-5 h-5 rounded-full border-2 flex-shrink-0 mt-0.5 flex items-center justify-center ${Ge===1?"border-orange-500 bg-orange-500":"border-gray-300"}`,children:Ge===1&&e.jsx("div",{className:"w-2 h-2 bg-white rounded-full"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:"Yes, my website is correct"}),e.jsxs("p",{className:"text-sm text-gray-700",children:["Current: ",(t==null?void 0:t.companyWebsite)||"Not set"]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"We'll try scanning it again."})]})]})}),e.jsx("div",{className:`p-3 rounded-lg border-2 cursor-pointer transition-all ${Ge===2?"border-orange-500 bg-orange-50":"border-gray-200 hover:border-gray-300"}`,onClick:()=>Ce(2),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`w-5 h-5 rounded-full border-2 flex-shrink-0 mt-0.5 flex items-center justify-center ${Ge===2?"border-orange-500 bg-orange-500":"border-gray-300"}`,children:Ge===2&&e.jsx("div",{className:"w-2 h-2 bg-white rounded-full"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium text-gray-900",children:"No, let me enter the correct website"}),Ge===2&&e.jsxs(e.Fragment,{children:[e.jsx(Ee,{className:`mt-2 ${gt.trim()&&!Xs(gt)?"border-red-500 focus:ring-red-500":""}
242`,placeholder:"https://yourcompany.com",value:gt,onChange:S=>It(S.target.value),onClick:S=>S.stopPropagation(),autoFocus:!0}),gt.trim()&&!Xs(gt)&&e.jsx("p",{className:"text-red-600 text-sm mt-1",children:"Please enter a valid website (e.g., example.com)"})]})]})]})}),e.jsx("div",{className:`p-3 rounded-lg border-2 cursor-pointer transition-all ${Ge===3?"border-orange-500 bg-orange-50":"border-gray-200 hover:border-gray-300"}`,onClick:()=>Ce(3),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`w-5 h-5 rounded-full border-2 flex-shrink-0 mt-0.5 flex items-center justify-center ${Ge===3?"border-orange-500 bg-orange-500":"border-gray-300"}`,children:Ge===3&&e.jsx("div",{className:"w-2 h-2 bg-white rounded-full"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:"I don't have a website"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Skip website analysis for keyword generation."})]})]})})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-gray-200",children:[e.jsx(N,{variant:"outline",onClick:()=>ji(!1),children:"Dismiss"}),e.jsx(N,{onClick:hc,disabled:!Ge||Ge===2&&(!gt.trim()||!Xs(gt)),className:"bg-orange-500 hover:bg-orange-600",children:"Continue"})]})]})]})}),e.jsx(os,{open:Se,onOpenChange:We,children:e.jsxs(cs,{className:`${De?"max-w-4xl":"max-w-3xl"} gap-4 max-h-[92vh] overflow-hidden flex flex-col transition-all duration-300`,"data-testid":"dialog-account-settings",onOpenAutoFocus:S=>S.preventDefault(),children:[e.jsxs(as,{className:"border-b border-gray-200 pb-4",children:[e.jsx(rs,{children:"Update Account Settings"}),e.jsx($s,{children:"Update your business information and targeting preferences"})]}),e.jsx("div",{className:"overflow-y-auto flex-1 pr-2 pl-1 dialog-scrollbar",children:e.jsxs("div",{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{htmlFor:"settings-company-name",children:"Company Name *"}),e.jsx(Ee,{id:"settings-company-name",value:Me,onChange:S=>He(S.target.value),placeholder:"Enter your company name","data-testid":"input-sett
242ings-company-name"})]}),e.jsxs("div",{className:`p-4 rounded-lg border-2 space-y-3 ${Fa(t)&&!P?"border-amber-400 bg-amber-50":"border-blue-200 bg-blue-50/50"}`,children:[Fa(t)&&!P&&e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-amber-100 rounded-md border border-amber-300",children:[e.jsx(ps,{className:"h-5 w-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"space-y-4 flex-1",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-amber-800",children:"Unable to analyze your website"}),e.jsx("p",{className:"text-xs text-amber-700 mt-1",children:"We couldn't access or analyze your website. Please choose one of the options below:"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-amber-800",children:"Option 1: The website above is correct"}),e.jsxs(N,{type:"button",variant:"outline",size:"sm",onClick:()=>{le(!0),dr()},disabled:ut||!ee.trim(),className:"bg-white border-amber-400 hover:bg-amber-50 text-amber-700",children:[ut?e.jsx(Ks,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx(da,{className:"h-4 w-4 mr-1.5"}),"Yes, try scanning again"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-amber-800",children:"Option 2: Enter the correct website"}),e.jsx("p",{className:"text-xs text-amber-700",children:'Update the website URL in the field below and click "Re-scan".'})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t border-amber-200",children:[e.jsx("p",{className:"text-xs font-medium text-amber-800",children:"Option 3: I don't have a website"}),e.jsx(N,{type:"button",variant:"ghost",size:"sm",onClick:async()=>{try{(await fetch("/api/website-opt-out",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({optOut:!0})})).ok?(z.invalidateQueries({queryKey:["/api/auth/user"]}),i({title:"Preference saved",description:"We'll skip website analysis for keyword generation."})):(ce("dashboard","Failed to save skip-analysis preference (non-OK response)"),i({title:"Error",description:"Failed to save preference. Please try again.",variant:"destructive"}))}catch(S){ce("dashboard","Failed to save skip-analysis preference",S),i({title:"Error",description:"Failed to save preference. Please try again.",variant:"destructive"})}},className:"text-amber-700 hover:bg-amber-200/50",children:"Skip website analysis"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(xe,{htmlFor:"settings-company-website",className:"flex items-center gap-2",children:[e.jsx(ri,{className:"h-4 w-4 text-blue-600"}),"Company Website *"]}),e.jsx("p",{className:"text-xs text-gray-700",children:"We scan your website to better understand your business and provide more accurate category and keyword recommendations for targeting."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ee,{id:"settings-company-website",value:ee,onChange:S=>O(S.target.value),placeholder:"https://yourcompany.com","data-testid":"input-sett
242ings-company-website",className:`flex-1 bg-white ${ee.trim()&&!Xs(ee)?"border-red-500 focus:ring-red-500":""}`}),e.jsxs(N,{type:"button",variant:"outline",size:"sm",onClick:()=>dr(),disabled:ut||!ee.trim()||!Xs(ee),className:"whitespace-nowrap","data-testid":"button-rescan-website",children:[ut?e.jsx(Ks,{className:"h-4 w-4 animate-spin"}):e.jsx(Ks,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-1.5",children:"Re-scan"})]})]}),ee.trim()&&!Xs(ee)&&e.jsx("p",{className:"text-red-600 text-sm",children:"Please enter a valid website (e.g., example.com)"}),St&&(t==null?void 0:t.websiteAnalysisStatus)!=="failed"&&!(t!=null&&t.websiteOptOut)&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Last analyzed: ",nn(new Date(St),{addSuffix:!0})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx("input",{type:"checkbox",id:"website-opt-out",checked:(t==null?void 0:t.websiteOptOut)||!1,onChange:async S=>{const se=S.target.checked;try{(await fetch("/api/website-opt-out",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({optOut:se})})).ok?(z.invalidateQueries({queryKey:["/api/auth/user"]}),i({title:se?"Website analysis disabled":"Website analysis enabled",description:se?"Keyword generation will not use website analysis.":"You can now enter your website for better recommendations."})):(ce("dashboard","Failed to save website opt-out toggle (non-OK response)"),i({title:"Error",description:"Failed to save preference. Please try again.",variant:"destructive"}),z.invalidateQueries({queryKey:["/api/auth/user"]}))}catch(Re){ce("dashboard","Failed to save website opt-out toggle",Re),i({title:"Error",description:"Failed to save preference. Please try again.",variant:"destructive"}),z.invalidateQueries({queryKey:["/api/auth/user"]})}},className:"h-4 w-4 rounded border-gray-300"}),e.jsx("label",{htmlFor:"website-opt-out",className:"text-xs text-gray-700 cursor-pointer",children:"I don't have a website"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{htmlFor:"settings-company-description",children:"Company Description (the more info the better our sales targeting will be!) *"}),e.jsx(Ma,{id:"settings-company-description",value:I,onChange:S=>re(S.target.value),placeholder:"Describe what your company does...",rows:3,"data-testid":"input-sett
242ings-company-description"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{htmlFor:"settings-product-service",children:"Product/Service *"}),e.jsx(Ma,{id:"settings-product-service",value:Pe,onChange:S=>tt(S.target.value),placeholder:"What products or services do you offer?",rows:3,"data-testid":"input-settings-product-service"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(xe,{htmlFor:"settings-target-categories",children:"Target SMB Types *"}),e.jsx(Qa,{delayDuration:200,children:e.jsxs(Ra,{children:[e.jsx(Oa,{asChild:!0,children:e.jsx(br,{className:"h-4 w-4 text-muted-foreground cursor-help","data-testid":"info-settings-target-categories"})}),e.jsx(Da,{className:"max-w-xs",children:e.jsx("p",{className:"text-sm",children:"Examples: Restaurants, Retail Stores, Law Firms, Medical Practices, Construction Companies, Accounting Firms"})})]})})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Separate multiple types with commas"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(Ee,{id:"settings-target-categories",value:Te,onChange:S=>Ct(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.preventDefault(),Ha())},placeholder:"e.g., Restaurants, Retail Stores",className:"flex-1","data-testid":"input-sett
242ings-target-categories"}),e.jsx(N,{type:"button",onClick:Ha,className:"px-4 bg-blue-600 hover:bg-blue-700","data-testid":"button-add-target-category",children:"Add"})]}),e.jsxs(N,{type:"button",onClick:Wa,disabled:et||!Me||!I||!Pe,className:"w-full bg-gradient-to-r from-yellow-500 to-amber-500 hover:from-yellow-600 hover:to-amber-600 text-white font-semibold","data-testid":"button-suggest-categories-ai",children:[e.jsx("span",{className:"mr-2",children:"â¨"}),"Suggest with AI"]}),(et||ft.length>0)&&e.jsxs("div",{className:"bg-gradient-to-r from-yellow-50 to-amber-50 border-2 border-yellow-400 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-yellow-800 flex items-center",children:[e.jsx("span",{className:"mr-2",children:"â¨"}),"Suggested Categories"]}),!et&&ft.length>0&&e.jsx(N,{type:"button",variant:"outline",size:"sm",onClick:()=>{if(ft.every(se=>Le.includes(se)))ft.forEach(se=>{Le.includes(se)&&Ts(se)});else{const se=ft.filter(Re=>!Le.includes(Re));ve([...Le,...se])}},className:"text-xs border-yellow-600 text-yellow-800 hover:bg-yellow-100","data-testid":"button-toggle-all-suggested",children:ft.every(S=>Le.includes(S))?"Remove All Suggested":"Add All Suggested"})]}),et&&e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(Lt,{size:16}),e.jsx("p",{className:"text-sm text-yellow-700",children:ee&&!["n/a","na","none","not available","not applicable"].includes(ee.trim().toLowerCase())&&!(t!=null&&t.websiteOptOut)?`Visiting ${ee} to make category suggestions (this can take 2-3 minutes)...`:"Making category suggestions based on your company description & product/service (this can take 2-3 minutes)..."})]}),!et&&ft.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-yellow-700 mb-3",children:"Based on your business information, we recommend these categories:"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:ft.map(S=>{const se=Le.includes(S);return e.jsx(ie,{variant:se?"default":"outline",className:`cursor-pointer p-2 text-center transition-colors ${se?"bg-yellow-600 text-white hover:bg-yellow-700 border-yellow-600":"bg-white border-yellow-400 text-yellow-800 hover:bg-yellow-100 hover:border-yellow-500"}`,onClick:()=>gc(S),"data-testid":`badge-suggested-${S.toLowerCase().replace(/\s+/g,"-")}`,children:S},S)})})]}),Xe&&e.jsx("p",{className:"text-sm text-yellow-700",children:"Unable to load suggestions. Please select from categories below or add your own."})]}),Le.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:Le.map(S=>e.jsxs(ie,{variant:"secondary",className:"gap-1 bg-blue-800 hover:bg-blue-600 text-white","data-testid":`badge-settings-category-${S}`,children:[S,e.jsx(Ut,{className:"h-3 w-3 cursor-pointer",onClick:()=>Ts(S)})]},S))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(xe,{htmlFor:"settings-businesses-to-avoid",children:"Company Types to Avoid (Optional)"}),e.jsx(Qa,{delayDuration:200,children:e.jsxs(Ra,{children:[e.jsx(Oa,{asChild:!0,children:e.jsx(br,{className:"h-4 w-4 text-muted-foreground cursor-help","data-testid":"info-settings-businesses-to-avoid"})}),e.jsx(Da,{className:"max-w-xs",children:e.jsx("p",{className:"text-sm",children:"Examples: Art Galleries, Non-Profits, Government Agencies, Educational Institutions, Franchises"})})]})})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Separate multiple types with commas"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(Ee,{id:"settings-businesses-to-avoid",value:lt,onChange:S=>kt(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.preventDefault(),Ni())},placeholder:"e.g., Art Galleries, Non-Profits",className:"flex-1","data-testid":"input-sett
242ings-businesses-to-avoid"}),e.jsx(N,{type:"button",onClick:Ni,className:"px-4 bg-red-600 hover:bg-red-700","data-testid":"button-add-business-to-avoid",children:"Add"})]}),Rt.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:Rt.map(S=>e.jsxs(ie,{variant:"secondary",className:"gap-1 bg-red-800 hover:bg-red-600 text-white","data-testid":`badge-settings-business-avoid-${S}`,children:[S,e.jsx(Ut,{className:"h-3 w-3 cursor-pointer",onClick:()=>yc(S)})]},S))})]})]}),!De&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{children:"Target Locations"}),e.jsxs(N,{type:"button",variant:"outline",onClick:()=>st(!0),className:"w-full justify-between h-auto py-3","data-testid":"button-manage-locations",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pn,{className:"h-4 w-4"}),e.jsx("span",{children:uc(Oe)})]}),e.jsx("span",{className:"text-blue-600",children:"Change"})]})]}),De&&e.jsxs("div",{className:"space-y-4 border-2 border-blue-200 rounded-lg p-4 bg-blue-50/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2 text-blue-600",children:[e.jsx(Pn,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:"Target Locations"})]}),e.jsx(N,{type:"button",variant:"ghost",size:"sm",onClick:()=>st(!1),"data-testid":"button-close-location-editor",children:"Done"})]}),e.jsx("p",{className:"text-sm text-gray-700",children:"Choose how you want to target locations for your SMB leads."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx("div",{className:"relative",children:e.jsxs("div",{className:`border-4 rounded-lg p-4 cursor-pointer transition-all hover:shadow-md ${(Oe==null?void 0:Oe.type)==="continental_usa"?"border-orange-500 bg-orange-50":"border-gray-300 hover:border-orange-300"}`,onClick:()=>
242Ar("continental_usa"),"data-testid":"option-continental-usa",children:[e.jsx("div",{className:"absolute -top-2 left-4 bg-white px-2 py-1 text-sm font-bold text-orange-600",style:{fontFamily:"'Marker Felt', 'Comic Sans MS', 'Chalkboard SE', 'Trebuchet MS', sans-serif"},children:"Most Popular"}),e.jsxs("div",{className:"text-center",children:[e.jsx("img",{src:vd,alt:"Mainland USA Map",className:"w-full h-24 object-contain mx-auto mb-2"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Mainland USA"}),e.jsx("p",{className:"text-sm text-gray-700",children:"48 contiguous states"})]})]})}),e.jsx("div",{className:`border-2 rounded-lg p-4 cursor-pointer transition-all hover:shadow-md ${(Oe==null?void 0:Oe.type)==="all_usa"?"border-blue-600 bg-blue-50":"border-gray-300 hover:border-blue-300"}`,onClick:()=>Ar("all_usa"),"data-testid":"option-all-usa",children:e.jsxs("div",{className:"text-center",children:[e.jsx("img",{src:jd,alt:"All USA Map",className:"w-full h-24 object-contain mx-auto mb-2"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"All USA"}),e.jsx("p",{className:"text-sm text-gray-700",children:"All 50 states + territories"})]})}),e.jsx("div",{className:`border-2 rounded-lg p-4 cursor-pointer transition-all hover:shadow-md ${(Oe==null?void 0:Oe.type)==="specific_states"?"border-green-600 bg-green-50":"border-gray-300 hover:border-green-300"}`,onClick:()=>Ar("specific_states"),"data-testid":"option-specific-states",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-full h-24 flex items-center justify-center mb-2 bg-gray-100 rounded",children:e.jsx(Pn,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Specific States"}),e.jsx("p",{className:"text-sm text-gray-700",children:"Choose individual states"})]})}),e.jsx("div",{className:`border-2 rounded-lg p-4 cursor-pointer transition-all hover:shadow-md ${(Oe==null?void 0:Oe.type)==="specific_cities"?"border-purple-600 bg-purple-50":"border-gray-300 hover:border-purple-300"}`,onClick:()=>Ar("specific_cities"),"data-testid":"option-specific-cities",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-full h-24 flex items-center justify-center mb-2 bg-gray-100 rounded",children:e.jsx(Ad,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Specific Cities"}),e.jsx("p",{className:"text-sm text-gray-700",children:"Choose individual cities"})]})})]}),(Oe==null?void 0:Oe.type)==="specific_states"&&e.jsxs("div",{className:"space-y-4 mt-6 p-4 bg-gray-50 rounded-lg",children:[e.jsx("h4",{className:"font-medium text-gray-900",children:"Select States"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 max-h-64 overflow-y-auto",children:bu.map(S=>{var se,Re;return e.jsx(ie,{variant:(se=Oe.data)!=null&&se.includes(S)?"default":"outline",className:`cursor-pointer p-2 text-center hover:bg-green-50 ${(Re=Oe.data)!=null&&Re.includes(S)?"bg-green-600 text-white hover:bg-green-700":"hover:border-green-300"}`,onClick:()=>fc(S),"data-testid":`badge-state-${S.toLowerCase().replace(/\s+/g,"-")}`,children:S},S)})}),e.jsxs("p",{className:"text-sm text-gray-500",children:["Selected: ",((Li=Oe.data)==null?void 0:Li.length)||0," ","states"]})]}),(Oe==null?void 0:Oe.type)==="specific_cities"&&e.jsxs("div",{className:"space-y-4 mt-6 p-4 bg-gray-50 rounded-lg",children:[e.jsx("h4",{className:"font-medium text-gray-900",children:"Add Cities"}),e.jsxs("div",{className:"flex space-x-2 relative",children:[e.jsxs("div",{className:"flex-1 relative",children:[e.jsx(Ee,{ref:fs,placeholder:"Enter city, state (e.g., New York, NY or Los Angeles, CA)",value:Ft,onChange:S=>wc(S.target.value),onKeyDown:vc,onBlur:()=>{setTimeout(()=>{ye(!1),rt(-1)},200)},onFocus:()=>{Ft.trim().length>0&&Ye.length>0&&ye(!0)},autoComplete:"off","data-testid":"input-city"}),jt&&Ye.length>0&&e.jsx("div",{ref:Tt,className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg max-h-48 overflow-y-auto","data-testid":"suggestions-dropdown",children:Ye.map((S,se)=>e.jsx("div",{className:`px-4 py-2 cursor-pointer border-b border-gray-100 last:border-b-0 ${se===Xt?"bg-purple-100 text-purple-900":"hover:bg-purple-50 text-gray-900"}`,onClick:()=>Ei(S),onMouseEnter:()=>rt(se),"data-testid":`suggestion-${S.toLowerCase().replace(/[^a-z0-9]/g,"-")}`,children:e.jsx("span",{children:S})},se))})]}),e.jsx(N,{type:"button",onClick:()=>{Ft.trim()&&(Lr(Ft),oe(""),ye(!1))},className:"px-4 bg-purple-600 hover:bg-purple-700","data-testid":"button-add-city",children:"Add"})]}),Oe.data&&Oe.data.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-gray-700",children:"Selected Cities:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Oe.data.map(S=>e.jsxs(ie,{variant:"secondary",className:"bg-purple-100 text-purple-800 cursor-pointer hover:bg-purple-200 pl-3 pr-2 py-1",onClick:()=>bc(S),"data-testid":`badge-city-${S.toLowerCase().replace(/\s+/g,"-")}`,children:[S," ",e.jsx("span",{className:"ml-1 text-purple-600",children:"Ã"})]},S))}),e.jsxs("p",{className:"text-sm text-gray-500",children:["Selected: ",Oe.data.length," ","cities"]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{htmlFor:"settings-job-title",children:"Job Title (Optional)"}),e.jsx(Ee,{id:"settings-job-title",value:$e,onChange:S=>W(S.target.value),placeholder:"e.g., Sales Director, Business Development Manager","data-testid":"input-sett
242ings-job-title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{htmlFor:"settings-additional-context",children:"Additional Context (Optional)"}),e.jsx(Ma,{id:"settings-additional-context",value:at,onChange:S=>Je(S.target.value),placeholder:"Any additional information that might help with targeting...",rows:3,"data-testid":"input-settings-additional-context"})]})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 px-6 pb-4 border-t border-gray-200",children:[e.jsx(N,{variant:"outline",onClick:()=>We(!1),"data-testid":"button-cancel-business-settings",children:"Cancel"}),e.jsx(N,{onClick:jc,disabled:Fn.isPending,"data-testid":"button-save-business-settings",children:Fn.isPending?"Saving...":"Save Changes"})]})]})}),ar(),e.jsx(os,{open:yt,onOpenChange:S=>{if(!S){if(Bt&&es===1||Dt>0)return;ls.current=!0,is(!1),ue("POST","/api/dismiss-optimization-popup").catch(()=>{}),z.invalidateQueries({queryKey:["/api/auth/user"]}),z.invalidateQueries({queryKey:["/api/me/temporary-credits"]})}},children:e.jsx(cs,{className:"sm:max-w-md",onPointerDownOutside:S=>{(Bt&&es===1||Dt>0)&&S.preventDefault()},onEscapeKeyDown:S=>{(Bt&&es===1||Dt>0)&&S.preventDefault()},children:Bt&&es===1?e.jsxs(e.Fragment,{children:[e.jsxs(as,{children:[e.jsxs(rs,{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-5 w-5 text-amber-500"}),"Temporary Bonus Credits Added to Your Account"]}),e.jsxs($s,{className:"text-base pt-2 space-y-3",children:[e.jsxs("span",{className:"block",children:["As a welcome bonus, we've added"," ",e.jsxs("span",{className:"font-semibold text-amber-600",children:[ms.amountGranted," temporary bonus credits"]})," ","to your account. These credits are ready to use right now."]}),he!==null&&he>0&&e.jsxs("span",{className:"block text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ua,{className:"h-4 w-4 inline"})," ","Expires in:"," ",e.jsx("span",{className:"font-mono font-medium text-amber-600",children:he>=3600?`${Math.floor(he/3600)}h ${Math.floor(he%3600/60)}m`:he>=60?`${Math.floor(he/60)}m ${he%60}s`:`${he}s`})]}),he===0&&e.jsx("span",{className:"block text-sm text-red-500",children:"These temporary bonus credits have expired."})]})]}),e.jsx(er,{children:e.jsx(N,{onClick:()=>Rs(2),disabled:bt>0,className:"w-full sm:w-auto",children:bt>0?`Next (${bt}s)`:"Next (1/2)"})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(as,{children:[e.jsxs(rs,{className:"flex items-center gap-2",children:[e.jsx(Lt,{size:16}),"Optimizing Your Results"]}),e.jsxs($s,{className:"text-base pt-2 space-y-2",children:[e.jsx("span",{className:"block",children:"Our AI is analyzing your business to find the most relevant leads for you. This typically takes about 15 minutes."}),e.jsx("span",{className:"block",children:"The initial results we've loaded for you are ready to use right now, so dive in and get started. Once the optimization finishes, feel free to tweak the results as you see fit. Adjust your filters and keywords until they match exactly what you're looking for."})]})]}),e.jsx(er,{children:e.jsx(N,{onClick:()=>{ls.current=!0,is(!1),ue("POST","/api/dismiss-optimization-popup").catch(()=>{}),z.invalidateQueries({queryKey:["/api/auth/user"]}),z.invalidateQueries({queryKey:["/api/me/temporary-credits"]})},disabled:Dt>0,className:"w-full sm:w-auto",children:Dt>0?`Finish (${Dt}s)`:Bt?"Finish (2/2)":"Finish"})})]})})}),e.jsx(os,{open:ae,onOpenChange:Y,children:e.jsxs(cs,{"data-testid":"dialog-mobile-warning",children:[e.jsxs(as,{children:[e.jsxs(rs,{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"h-5 w-5 text-amber-500"}),"Desktop Recommended"]}),e.jsx($s,{className:"pt-2",children:"The dashboard is best viewed on a desktop or laptop screen for an optimal experience. Some features and layouts may be limited on mobile devices."})]}),e.jsx(N,{onClick:()=>Y(!1),className:"w-full","data-testid":"button-close-mobile-warning",children:"Got it"})]})})]})}const Xx=Object.freeze(Object.defineProperty({__proto__:null,default:Dx},Symbol.toStringTag,{value:"Module"}));export{ci as C,Md as G,Wi as L,wn as M,zo as P,sc as R,Bi as T,Ji as U,zd as W,Nn as a,En as b,za as c,Ke as d,Sn as e,Fe as f,di as g,ns as h,Zr as i,Kd as j,to as k,rr as l,Xx as m,Nx as
242s};
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.