1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/company-cards-DqVAco0I.js","assets/index-BA-hDO3C.js","assets/index-MNiv30KO.css","assets/badge-BmS2sdGI.js","assets/checkbox-ZpY8b9Nw.js","assets/mail-ZTV35zlk.js","assets/contact-row-DhEji99D.js","assets/ban-Z2WHw_L5.js","assets/linkedin-UAFeFJyr.js","assets/phone-CNUoMUC0.js","assets/message-square-CUDKYNfg.js","assets/star-CLniQGze.js","assets/thumbs-down-R5QH_mmm.js","assets/chevron-left-CJuQnFIJ.js","assets/building-2-B59OQuVd.js","assets/globe-B4oBl9ot.js","assets/map-pin-CADt7NYp.js","assets/external-link-BC7xl8Dm.js","assets/index-Ce07gEuN.js","assets/seo-head-Chmo95B1.js","assets/confetti-ujQDGIfe.js","assets/building-BgjY0t8u.js","assets/pen-D2DENtO3.js","assets/user-search-DD3oUyUp.js","assets/form-BlxB3cD1.js","assets/settings-B8h2hIg2.js","assets/square-anTqQ9Ws.js","assets/search-BKbM58WA.js","assets/scroll-area-rnGeKXLQ.js","assets/switch-JUsuRP0a.js","assets/popover-BZcGkHPI.js","assets/format-CW0G_LzU.js","assets/email-link-generator-l1i5n3fe.js","assets/separator-BBS0OGtK.js","assets/refresh-cw-Bjqttn03.js","assets/index-C_RXtAVN.js","assets/EmailSendButton-BTPzeS1w.js","assets/copy-xRPq65Vh.js","assets/calendar-DSpXbRC4.js","assets/autopilot-modal-DK4L1XNr.js","assets/user-check-DaHvBzHb.js","assets/link-7NHK12HN.js","assets/file-text-BX3u1_rs.js","assets/trash-2-C0n4-7p4.js","assets/square-pen-UkCAhx-Y.js","assets/rocket-Cq1-ZY_U.js","assets/index-B7oylYAA.js","assets/circle-play-D7XJuzr-.js","assets/clock-D2r8GWus.js","assets/pause-Bcc2NwYQ.js","assets/play-BjufNzl7.js","assets/index-BCiyo5pc.js","assets/trending-up-BgCxkwuB.js","assets/index-COrCWlF3.js","assets/sender-profile-form-BAEXHHsS.js","assets/radio-group-CD5Rry9i.js","assets/arrow-right-BcF0pNNj.js","assets/package-DeJG0lAj.js","assets/briefcase-CeOyilvV.js","assets/index-ICiZL7jf.js","assets/index-ByInqQi6.js","assets/circle-user-Dc-V5xWc.js","assets/SelectionToolbar-EvSsmc4K.js","assets/index-sWwZ3lr_.js","assets/circle-stop-xP4ZLX4K.js","assets/filter-DAdcOGqF.js","assets/index-BKj4yEPd.js"])))=>i.map(i=>d[i]); 2import{j as e,a7 as hs,r as s,O as he,a8 as ps,T as Pe,x as Fe,y as Le,g as tt,a9 as Wt,z as Ae,U as ut,aa as Pt,a5 as st,I as Me,ab as Ft,X as Lt,ac as zt,ad as Ct,ae as wt,af as vt,ag as jt,S as dt,B as at,w as ht,ah as Et,a as Ht,f as Kt,ai as Ue,N as fs,H as gs,J as Ut,aj as lt,ak as Ss,al as xs,u as ys,am as bs,an as Cs,ao as ws,Y as At,$ as _t,_ as ke}from"./index-BA-hDO3C.js";import{S as vs}from"./seo-head-Chmo95B1.js";import{u as js}from"./confetti-ujQDGIfe.js";import{B as Gt}from"./building-BgjY0t8u.js";import{P as qt}from"./pen-D2DENtO3.js";import{B as xt}from"./building-2-B59OQuVd.js";import{M as Es}from"./mail-ZTV35zlk.js";import{U as Yt}from"./user-search-DD3oUyUp.js";import{o as ks,s as Ve,l as Ns,u as Ts,t as Is,F as Rs,a as Je,b as We,c as ze,d as He,e as Ke}from"./form-BlxB3cD1.js";import{S as Os}from"./settings-B8h2hIg2.js";import{S as $s}from"./square-anTqQ9Ws.js";import{S as Xt}from"./search-BKbM58WA.js";import"./checkbox-ZpY8b9Nw.js";import"./scroll-area-rnGeKXLQ.js";import"./switch-JUsuRP0a.js";import"./popover-BZcGkHPI.js";import"./email-link-generator-l1i5n3fe.js";import"./separator-BBS0OGtK.js";import{B as Ds}from"./badge-BmS2sdGI.js";import{R as Ms}from"./refresh-cw-Bjqttn03.js";function Bt({phase:o,completed:a,total:r,isVisible:c}){if(!c)return null;const l=r>0?Math.round(a/r*100):0,n=l<100&&l>0;return e.jsxs("div",{className:"mt-3 mb-1 w-full",children:[e.jsxs("div",{className:"flex justify-between items-center mb-1",children:[e.jsx("span",{className:"text-xs font-medium",children:o}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[l,"%"]})]}),e.jsx(hs,{value:l,className:"h-1.5",showShimmer:n})]})}function Qt(){return e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs("div",{className:"h-12 bg-slate-100 dark:bg-slate-800 rounded-t-lg flex items-center px-4",children:[e.jsx("div",{className:"h-4 bg-slate-300 dark:bg-slate-600 rounded w-20 animate-pulse"}),e.jsx("div",{className:"h-4 bg-slate-300 dark:bg-slate-600 rounded w-32 ml-8 animate-pulse"}),e.jsx("div",{className:"h-4 bg-slate-300 dark:bg-slate-600 rounded w-24 ml-8 animate-pulse"}),e.jsx("div",{className:"h-4 bg-slate-300 dark:bg-slate-600 rounded w-16 ml-auto animate-pulse"})]}),Array.from({length:5}).map((o,a)=>e.jsxs("div",{className:"h-16 border-t flex items-center px-4 space-x-8",children:[e.jsx("div",{className:"h-4 bg-slate-200 dark:bg-slate-700 rounded w-24 animate-pulse"}),e.jsx("div",{className:"h-4 bg-slate-200 dark:bg-slate-700 rounded w-48 animate-pulse"}),e.jsx("div",{className:"h-4 bg-slate-200 dark:bg-slate-700 rounded w-32 animate-pulse"}),e.jsx("div",{className:"h-8 bg-slate-200 dark:bg-slate-700 rounded w-20 ml-auto animate-pulse"})]},a))]})})}const Vt={status:"idle",plan:null,results:[],progressMessages:[],error:null,completionStats:null,isExpanding:!1};function Ps(){const[o,a]=s.useState(Vt),r=s.useRef(null),c=s.useCallback(()=>{r.current&&(r.current.abort(),r.current=null),a(Vt)},[]),l=s.useCallback(async(g,y,b)=>{var v;c(),a(w=>({...w,status:"connecting"}));
2try{r.current=new AbortController;const w=await fetch("/api/super-search/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:g,listId:y,variantId:b}),signal:r.current.signal});if(!w.ok){const M=await w.json();throw new Error(M.error||"Failed to start search")}a(M=>({...M,status:"streaming"}));const T=(v=w.body)==null?void 0:v.getReader();if(!T)throw new Error("No response body");const z=new TextDecoder;let D="",p="";for(;;){const{done:M,value:N}=await T.read();if(M)break;D+=z.decode(N,{stream:!0});const F=D.split(` 3`);D=F.pop()||"";for(const Q of F){if(Q.startsWith("event: ")){p=Q.slice(7).trim();continue}if(Q.startsWith("data: ")){const A=Q.slice(6);if(p==="error"){let I=A;try{const x=JSON.parse(A);I=x.error||x.message||A}catch{}a(x=>({...x,status:"error",error:I})),p="";continue}if(p==="complete"){try{const I=JSON.parse(A);a(x=>({...x,status:"complete",completionStats:I}))}catch{a(x=>({...x,status:"complete"}))}p="";continue}try{const I=JSON.parse(A);if(p==="plan"||"queryType"in I&&"displayMode"in I)a(x=>({...x,plan:I}));else if(p==="progress"||typeof I=="string"){const x=typeof I=="string"?I:String(I);a($=>({...$,progressMessages:[...$.progressMessages,x]}))}else p==="result"||"type"in I&&(I.type==="company"||I.type==="contact")?a(x=>({...x,results:[...x.results,I]})):"totalResults"in I&&a(x=>({...x,status:"complete",completionStats:I}))}catch{A.trim()&&p==="progress"&&a(x=>({...x,progressMessages:[...x.progressMessages,A.trim()]}))}p=""}}}a(M=>M.status!=="error"?{...M,status:"complete"}:M)}catch(w){if(w.name==="AbortError")return;a(T=>({...T,status:"error",error:w instanceof Error?w.message:"Search failed"}))}},[c]),n=s.useCallback(()=>{r.current&&r.current.abort(),c()},[c]),S=s.useCallback((g,y)=>{a({status:"complete",plan:g,results:y,progressMessages:[],error:null,completionStats:{totalResults:y.length,companiesSaved:y.filter(b=>b.type==="company").length,contactsSaved:y.filter(b=>b.type==="contact").length},isExpanding:!1})},[]),d=s.useCallback(g=>{const y=g.name.toLowerCase().trim(),b=g.type==="company"?(g.website||"").toLowerCase().trim():(g.companyWebsite||"").toLowerCase().trim();return`${y}|${b}`},[]),j=s.useCallback(async(g,y=5)=>{var v;if(!o.plan||o.results.length===0){console.error("Cannot expand without existing plan and results");return}const b=new Set(o.results.map(d));a(w=>({...w,isExpanding:!0,error:null}));try{r.current=new AbortController;const w=o.results.map(N=>({name:N.name,website:N.type==="company"?N.website:N.companyWebsite})),T=await fetch("/api/super-search/expand",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({originalQuery:g,existingResults:w,additionalCount:y,plan:{queryType:o.plan.queryType,standardFields:o.plan.standardFields,customFields:o.plan.customFields}}),signal:r.current.signal});if(!T.ok){const N=await T.json();throw new Error(N.error||"Failed to expand search")}const z=(v=T.body)==null?void 0:v.getReader();if(!z)throw new Error("No response body");const D=new TextDecoder;let p="",M="";for(;;){const{done:N,value:F}=await z.read();if(N)break;p+=D.decode(F,{stream:!0});const Q=p.split(` 4`);p=Q.pop()||"";for(const A of Q){if(A.startsWith("event: ")){M=A.slice(7).trim();continue}if(A.startsWith("data: ")){const I=A.slice(6);if(M==="error"){let x=I;try{const $=JSON.parse(I);x=$.error||$.message||I}catch{}a($=>({...$,isExpanding:!1,error:x})),M="";continue}if(M==="complete"){a(x=>({...x,isExpanding:!1,completionStats:x.completionStats?{...x.completionStats,totalResults:x.results.length}:null})),M="";continue}try{const x=JSON.parse(I);if(M==="result"||"type"in x&&(x.type==="company"||x.type==="contact")){const $=x,oe=d($);b.has(oe)?console.log("[SuperSearch] Skipping duplicate result:",$.name):(b.add(oe),a(h=>({...h,results:[...h.results,$]})))}}catch{}M=""}}}a(N=>({...N,isExpanding:!1}))}catch(w){if(w.name==="AbortError"){a(T=>({...T,isExpanding:!1}));return}a(T=>({...T,isExpanding:!1,error:w instanceof Error?w.message:"Expand failed"}))}},[o.plan,o.results,d]);
4return{...o,startSearch:l,cancel:n,reset:c,loadFromSaved:S,expandResults:j,isLoading:o.status==="connecting"||o.status==="streaming"}}const mt=class mt{static createSession(a,r,c){const l=`search_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,n={id:l,query:a,status:"pending",startTime:Date.now(),lastChecked:Date.now(),strategyId:r,contactSearchConfig:c};return this.saveSession(n),console.log("Created search session:",l,"for query:",a),this.cleanupActiveSessions().catch(S=>console.warn("[Session Cleanup] Background cleanup failed:",S)),n}static updateSessionWithJob(a,r){const c=this.getSession(a);c&&(c.jobId=r,c.lastChecked=Date.now(),this.saveSession(c),console.log("Updated session with job ID:",a,r))}static updateWithQuickResults(a,r){const c=this.getSession(a);c&&(c.status="companies_found",c.quickResults=r,c.lastChecked=Date.now(),this.saveSession(c),console.log("Updated session with quick results:",a,r.length,"companies"))}static updateWithFullResults(a,r){const c=this.getSession(a);c&&(c.status="contacts_complete",c.fullResults=r,c.lastChecked=Date.now(),this.saveSession(c),console.log("Updated session with full results:",a,r.length,"companies with contacts"))}static markSessionFailed(a){const r=this.getSession(a);r&&(r.status="failed",r.lastChecked=Date.now(),this.saveSession(r),console.log("Marked session as failed:",a))}static markEmailSearchStarted(a){const r=this.getSession(a);r&&(r.emailSearchStatus="running",r.lastChecked=Date.now(),this.saveSession(r),console.log("Marked email search as started for session:",a))}static markEmailSearchCompleted(a){const r=this.getSession(a);r&&(r.emailSearchStatus="completed",r.emailSearchCompleted=Date.now(),r.lastChecked=Date.now(),this.saveSession(r),console.log("Marked email search as completed for session:",a))}static markQuickResultsComplete(a){const r=this.getSession(a);r&&r.quickResults&&(r.status="companies_complete",r.lastChecked=Date.now(),this.saveSession(r),console.log(`Marked quick results as complete for session: ${a}`))}static getActiveSessions(){return this.getAllSessions().filter(r=>r.status==="pending"||r.status==="companies_found")}static getMostRecentCompleteSession(){return this.getAllSessions().filter(c=>c.status==="contacts_complete"||c.status==="companies_complete").sort((c,l)=>l.startTime-c.startTime)[0]||null}static getSession(a){try{const r=localStorage.getItem(`${this.SESSION_PREFIX}${a}`);if(r)return JSON.parse(r)}catch(r){console.error("Error loading search session:",r)}return null}static saveSession(a){try{localStorage.setItem(`${this.SESSION_PREFIX}${a.id}`,JSON.stringify(a))}catch(r){console.error("Error saving search session:",r)}}static getAllSessions(){const a=[];for(let r=0;r<localStorage.length;r++){const c=localStorage.key(r);if(c&&c.startsWith(this.SESSION_PREFIX))try{const l=localStorage.getItem(c);if(l){const n=JSON.parse(l);Date.now()-n.startTime<this.MAX_SESSION_AGE?a.push(n):localStorage.removeItem(c)}}catch(l){console.error("Error parsing session:",l),localStorage.removeItem(c)}}return a.sort((r,c)=>c.startTime-r.startTime)}static cleanupOldSessions(){const a=Date.now()-864e5;for(let r=0;r<localStorage.length;r++){const c=localStorage.key(r);if(c&&c.startsWith(this.SESSION_PREFIX))try{const l=localStorage.getItem(c);if(l){const n=JSON.parse(l);n.startTime<a&&(n.status==="contacts_complete"||n.status==="failed")&&(localStorage.removeItem(c),console.log("Cleaned up old session:",n.id))}}catch{localStorage.removeItem(c)}}}static cleanupSession(a){try{localStorage.removeItem(`${this.SESSION_PREFIX}${a}`),console.log("Cleaned up session:",a)}catch(r){console.error("Error cleaning up session:",r)}}static clearAllSessions(){const a=[];for(let r=0;r<localStorage.length;r++){const c=localStorage.key(r);c&&c.startsWith(this.SESSION_PREFIX)&&a.push(c)}a.forEach(r=>localStorage.removeItem(r)),console.log("Cleared all search sessions")}static async cleanupActiveSessions(){try{const a=this.getActiveSessions();if(a.length>0){console.log(`[Session Cleanup] Found ${a.length} active sessions, terminating...`);for(const r of a){try{(await fetch(`/api/search-sessions/${r.id}`,{method:"DELETE"})).ok&&console.log(`[Session Cleanup] Backend session terminated: ${r.id}`)}catch(c){console.warn(`[Session Cleanup] Failed to terminate backend session ${r.id}:`,c)}this.cleanupSession(r.id)}console.log(`[Session Cleanup] Completed cleanup of ${a.length} sessions`)}}catch(a){console.error("[Session Cleanup] Error during active session cleanup:",a)}}static async terminateSession(a){try{(await fetch(`/api/search-sessions/${a}`,{method:"DELETE"})).ok&&console.log(`[Session Cleanup] Backend session terminated: ${a}`),this.cleanupSession(a)}catch(r){console.error(`[Session Cleanup] Error terminating session ${a}:`,r),this.cleanupSession(a)}}static async bulkCleanupCompletedSessions(){try{const a=await fetch("/api/search-sessions",{method:"DELETE"});if(a.ok){const r=await a.json();console.log(`[Bulk Cleanup] ${r.message}`);const c=this.getAllSessions();let l=0;for(const n of c){const S=Date.now()-n.startTime>36e5,d=n.emailSearchStatus==="completed";(S||d)&&(this.cleanupSession(n.id),l++)}console.log(`[Bulk Cleanup] Cleaned ${l} local sessions`)}}catch(a){console.error("[Bulk Cleanup] Error during bulk cleanup:",a)}}};mt.SESSION_PREFIX="searchSession_",mt.MAX_SESSION_AGE=30*60*1e3;let ue=mt;const yt="searchState",je={load:()=>{try{const o=sessionStorage.getItem(yt);if(o){const a=JSON.parse(o);if(a.currentQuery||a.currentResults&&a.currentResults.length>0)return a}}catch(o){console.error("Error loading search session state:",o)}return null},save:o=>{try{if(!o.currentQuery&&(!o.currentResults||o.currentResults.length===0))return;sessionStorage.setItem(yt,JSON.stringify(o))}catch(a){console.error("Error saving search session state:",a)}},clear:()=>{sessionStorage.removeItem(yt)}};function Fs(o){const a=s.useRef(!0),r=s.useRef(!1),c=s.useRef(!1),l=s.useRef(0),n=s.useCallback(()=>je.load(),[]),S=s.useCallback((y,b)=>{const v=b.lastExecutedQuery||b.currentQuery,w={currentQuery:v,currentResults:y.currentResults,currentListId:b.currentListId,lastExecutedQuery:b.lastExecutedQuery||v,...y.emailSearchCompleted!==void 0&&{emailSearchCompleted:y.emailSearchCompleted},...y.emailSearchTimestamp!==void 0&&{emailSearchTimestamp:y.emailSearchTimestamp??void 0},...y.navigationRefreshTimestamp!==void 0&&{navigationRefreshTimestamp:y.navigationRefreshTimestamp}};je.save(w),console.log("Persisted search state to session storage:",{companyCount:y.currentResults.length,emailCount:y.currentResults.reduce((T,z)=>{var D;return T+(((D=z.contacts)==null?void 0:D.filter(p=>p.email&&p.email.length>0).length)||0)},0),hasListId:!!b.currentListId})},[]),d=s.useCallback(async(y,b)=>{try{console.log("Refreshing contact data from database...");const v=await Promise.all(y.map(async w=>{try{const z=await(await he("GET",`/api/companies/${w.id}/contacts`)).json();return{...w,contacts:z}}catch(T){return console.error(`Failed to refresh contacts for company ${w.id}:`,T),w}}));return console.log("Contact data refresh completed from database"),v}catch(v){return console.error("Database refresh failed:",v),y}},[]),j=y=>[...y].sort((b,v)=>{var z,D;const w=((z=b.contacts)==null?void 0:z.length)||0;return(((D=v.contacts)==null?void 0:D.length)||0)-w}),g=s.useCallback(async(y,b,v={})=>{try{const w=++l.current,T=await d(y,{forceFresh:v.forceFresh});if(w!==l.current)return console.log("Skipping stale refresh result from version",w),y;const z=j(T);return v.forceUiReset?(o([]),setTimeout(()=>{w===l.current&&o(z)},100)):o(z),S({currentResults:z,...v.additionalStateFields},b),v.clearEmailSearchTimestamp&&(sessionStorage.removeItem("lastEmailSearchTimestamp"),console.log("Cleared lastEmailSearchTimestamp")),console.log("Refreshed and updated results:",{companyCount:z.length,companiesWithContacts:z.filter(D=>D.contacts&&D.contacts.length>0).length}),z}catch(w){return console.error("Failed to refresh and update results:",w),y}}
4,[d,S,o]);return{loadSearchState:n,persistSearchState:S,refreshContactDataFromDatabase:d,refreshAndUpdateResults:g,isMountedRef:a,isInitializedRef:r,hasSessionRestoredDataRef:c,refreshVersionRef:l}}function Ls({config:o,onConfigChange:a,disabled:r=!1,isSearching:c=!1,hasSearchResults:l=!1,inputHasChanged:n=!1}){const[S,d]=s.useState(!1),[j,g]=s.useState(!1),[y,b]=s.useState(""),[v,w]=s.useState("");s.useState("");const[T,z]=s.useState(!1),D=s.useRef(null),[p,M]=s.useState(()=>{if(o)return o;const h=localStorage.getItem("contactSearchConfig");if(h)try{return{enableCoreLeadership:!0,enableDepartmentHeads:!1,enableMiddleManagement:!1,enableCustomSearch:!1,customSearchTarget:"",enableCustomSearch2:!1,customSearchTarget2:"",...JSON.parse(h)}}catch(G){console.error("Error loading saved contact search config:",G)}return{enableCoreLeadership:!0,enableDepartmentHeads:!1,enableMiddleManagement:!1,enableCustomSearch:!1,customSearchTarget:"",enableCustomSearch2:!1,customSearchTarget2:""}});s.useEffect(()=>{o&&(M(o),b(o.customSearchTarget||""),w(o.customSearchTarget2||""))},[o]),s.useEffect(()=>{localStorage.setItem("contactSearchConfig",JSON.stringify(p))},[p]),s.useEffect(()=>()=>{D.current&&clearTimeout(D.current)},[]);const N=h=>{M(G=>{const xe={...G,...h};return a(xe),xe})},F=h=>{if(!(window.innerWidth<768)){h();return}T?h():(z(!0),D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{z(!1)},5e3))},Q=()=>{const h=y.trim();N({customSearchTarget:h,enableCustomSearch:h?p.enableCustomSearch:!1}),d(!1),h||b("")},A=()=>{d(!0),b(p.customSearchTarget)},I=()=>{p.customSearchTarget.trim()?p.enableCustomSearch?N({enableCustomSearch:!1}):N({enableCoreLeadership:!1,enableDepartmentHeads:!1,enableMiddleManagement:!1,enableCustomSearch:!0,enableCustomSearch2:!1}):d(!0)},x=()=>{const h=v.trim();N({customSearchTarget2:h,enableCustomSearch2:h?p.enableCustomSearch2:!1}),g(!1),h||w("")},$=()=>{S&&Q(),g(!0),w(p.customSearchTarget2)},oe=()=>{p.customSearchTarget2.trim()?p.enableCustomSearch2?N({enableCustomSearch2:!1}):N({enableCoreLeadership:!1,enableDepartmentHeads:!1,enableMiddleManagement:!1,enableCustomSearch:!1,enableCustomSearch2:!0}):g(!0)};return e.jsxs("div",{className:"flex flex-wrap gap-2 mt-3",children:[e.jsx(Pe,{children:e.jsxs(Fe,{children:[e.jsx(Le,{asChild:!0,children:e.jsxs("button",{onClick:()=>F(()=>N({enableCoreLeadership:!p.enableCoreLeadership,enableDepartmentHeads:!1,enableMiddleManagement:!1,enableCustomSearch:!1,enableCustomSearch2:!1})),disabled:r,className:` 5 flex items-center gap-2 px-3 py-2 rounded-lg transition-all duration-200 6 md:gap-2 gap-1 md:px-3 px-2 7 ${T?"":`max-md:justify-center ${p.enableCoreLeadership?"max-md:min-w-16 max-md:px-2":"max-md:w-10 max-md:h-10 max-md:px-0"}`} 8 ${p.enableCoreLeadership?"bg-secondary text-secondary-foreground hover:bg-secondary-hover":"bg-muted text-muted-foreground hover:bg-muted-hover"} 9 ${r?"opacity-50 cursor-not-allowed":"cursor-pointer"} 10 `,children:[p.enableCoreLeadership&&e.jsx(tt,{className:"h-3 w-3"}),e.jsx(Wt,{className:"h-3 w-3"}),e.jsx("span",{className:`text-sm font-medium ${T?"":"max-md:hidden"}`,children:"Leadership"})]})}),e.jsx(Ae,{children:e.jsx("p",{children:"CEO, CTO, Founders, C-level executives"})})]})}),e.jsx(Pe,{children:e.jsxs(Fe,{children:[e.jsx(Le,{asChild:!0,children:e.jsxs("button",{onClick:()=>F(()=>N({enableCoreLeadership:!1,enableDepartmentHeads:!p.enableDepartmentHeads,enableMiddleManagement:!1,enableCustomSearch:!1,enableCustomSearch2:!1})),disabled:r,className:` 11 flex items-center gap-2 px-3 py-2 rounded-lg transition-all duration-200 12 md:gap-2 gap-1 md:px-3 px-2 13 ${T?"":`max-md:justify-center ${p.enableDepartmentHeads?"max-md:min-w-16 max-md:px-2":"max-md:w-10 max-md:h-10 max-md:px-0"}`} 14 ${p.enableDepartmentHeads?"bg-secondary text-secondary-foreground hover:bg-secondary-hover":"bg-muted text-muted-foreground hover:bg-muted-hover"} 15 ${r?"opacity-50 cursor-not-allowed":"cursor-pointer"} 16 `,children:[p.enableDepartmentHeads&&e.jsx(tt,{className:"h-3 w-3"}),e.jsx(Gt,{className:"h-3 w-3"}),e.jsx("span",{className:`text-sm font-medium ${T?"":"max-md:hidden"}`,children:"Marketing"})]})}),e.jsx(Ae,{children:e.jsx("p",{children:"CMO, VP Marketing, Marketing Directors, Growth Leaders"})})]})}),e.jsx(Pe,{children:e.jsxs(Fe,{children:[e.jsx(Le,{asChild:!0,children:e.jsxs("button",{onClick:()=>F(()=>N({enableCoreLeadership:!1,enableDepartmentHeads:!1,enableMiddleManagement:!p.enableMiddleManagement,enableCustomSearch:!1,enableCustomSearch2:!1})),disabled:r,className:` 17 flex items-center gap-2 px-3 py-2 rounded-lg transition-all duration-200 18 md:gap-2 gap-1 md:px-3 px-2 19 ${T?"":`max-md:justify-center ${p.enableMiddleManagement?"max-md:min-w-16 max-md:px-2":"max-md:w-10 max-md:h-10 max-md:px-0"}`} 20 ${p.enableMiddleManagement?"bg-secondary text-secondary-foreground hover:bg-secondary-hover":"bg-muted text-muted-foreground hover:bg-muted-hover"} 21 ${r?"opacity-50 cursor-not-allowed":"cursor-pointer"} 22 `,children:[p.enableMiddleManagement&&e.jsx(tt,{className:"h-3 w-3"}),e.jsx(ut,{className:"h-3 w-3"}),e.jsx("span",{className:`text-sm font-medium ${T?"":"max-md:hidden"}`,children:"CTO"})]})}),e.jsx(Ae,{children:e.jsx("p",{children:"Chief Technology Officer, VP Engineering, Technical Leaders"})})]})}),!S&&!p.customSearchTarget.trim()&&e.jsx("button",{onClick:()=>F(A),disabled:r,className:` 23 flex items-center justify-center px-3 py-2 rounded-lg border border-dashed border-border 24 text-muted-foreground hover:bg-muted-hover transition-all duration-200 min-w-[40px] 25 max-md:w-10 max-md:h-10 max-md:px-0 26 ${r?"opacity-50 cursor-not-allowed":"cursor-pointer"} 27 `,children:e.jsx(Pt,{className:"h-4 w-4"})}),S&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg border border-border bg-secondary",children:[e.jsx(st,{className:"h-3 w-3 text-secondary-foreground"}),e.jsx(Me,{value:y,onChange:h=>b(h.target.value.slice(0,22)),placeholder:"e.g., Marketing Manager",disabled:r,maxLength:22,className:"h-6 text-sm border-none bg-transparent p-0 focus:ring-0 focus:outline-none min-w-[200px]",onKeyDown:h=>{h.key==="Enter"&&Q(),h.key==="Escape"&&(d(!1),b(p.customSearchTarget))},onBlur:()=>{y.trim()||(d(!1),b(p.customSearchTarget))},autoFocus:!0}),e.jsx("button",{onClick:Q,disabled:r,className:"text-secondary-foreground hover:text-foreground",children:e.jsx(Ft,{className:"h-3 w-3"})}),e.jsx("button",{onClick:()=>{N({customSearchTarget:"",enableCustomSearch:!1}),d(!1),b("")},disabled:r,className:"text-destructive hover:text-destructive/80",children:e.jsx(Lt,{className:"h-3 w-3"})})]}),p.customSearchTarget.trim()&&!S&&e.jsx(Pe,{children:e.jsxs(Fe,{children:[e.jsx(Le,{asChild:!0,children:e.jsxs("button",{onClick:()=>F(I),disabled:r,className:` 28 flex items-center gap-2 px-3 py-2 rounded-lg transition-all duration-200 29 md:gap-2 gap-1 md:px-3 px-2 30 ${T?"":`max-md:justify-center ${p.customSearchTarget.trim()?"max-md:min-w-16 max-md:px-2":"max-md:w-10 max-md:h-10 max-md:px-0"}`} 31 ${p.enableCustomSearch?"bg-secondary text-secondary-foreground hover:bg-secondary-hover":"bg-muted text-muted-foreground hover:bg-muted-hover"} 32 ${r?"opacity-50 cursor-not-allowed":"cursor-pointer"} 33 `,children:[p.enableCustomSearch&&e.jsx(tt,{className:"h-3 w-3"}),e.jsx(st,{className:"h-3 w-3"}),e.jsx("span",{className:`text-sm font-medium ${T?"":"max-md:hidden"}`,children:p.customSearchTarget}),e.jsx("span",{onClick:h=>{h.stopPropagation(),A()}
33,className:"ml-1 text-muted-foreground/60 hover:text-muted-foreground cursor-pointer",role:"button",tabIndex:0,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),h.stopPropagation(),A())},children:e.jsx(qt,{className:"h-3 w-3"})})]})}),e.jsx(Ae,{children:e.jsxs("p",{children:["Boost scores for ",p.customSearchTarget," roles"]})})]})}),!j&&!p.customSearchTarget2.trim()&&p.customSearchTarget.trim()&&e.jsx("button",{onClick:()=>F($),disabled:r,className:` 34 flex items-center justify-center px-3 py-2 rounded-lg border border-dashed border-border 35 text-muted-foreground hover:bg-muted-hover transition-all duration-200 min-w-[40px] 36 max-md:w-10 max-md:h-10 max-md:px-0 37 ${r?"opacity-50 cursor-not-allowed":"cursor-pointer"} 38 `,children:e.jsx(Pt,{className:"h-4 w-4"})}),j&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg border border-border bg-secondary",children:[e.jsx("input",{type:"text",value:v,onChange:h=>w(h.target.value.slice(0,22)),placeholder:"e.g., Sales Director",disabled:r,maxLength:22,className:"h-6 text-sm border-none bg-transparent p-0 focus:ring-0 focus:outline-none min-w-[200px]",onKeyDown:h=>{h.key==="Enter"&&x(),h.key==="Escape"&&(g(!1),w(p.customSearchTarget2))},onBlur:()=>{v.trim()||(g(!1),w(p.customSearchTarget2))},autoFocus:!0}),e.jsx("button",{onClick:x,disabled:r,className:"text-secondary-foreground hover:text-foreground",children:e.jsx(Ft,{className:"h-3 w-3"})}),e.jsx("button",{onClick:()=>{N({customSearchTarget2:"",enableCustomSearch2:!1}),g(!1),w("")},disabled:r,className:"text-destructive hover:text-destructive/80",children:e.jsx(Lt,{className:"h-3 w-3"})})]}),p.customSearchTarget2.trim()&&!j&&e.jsx(Pe,{children:e.jsxs(Fe,{children:[e.jsx(Le,{asChild:!0,children:e.jsxs("button",{onClick:()=>F(oe),disabled:r,className:` 39 flex items-center gap-2 px-3 py-2 rounded-lg transition-all duration-200 40 md:gap-2 gap-1 md:px-3 px-2 41 ${T?"":`max-md:justify-center ${p.customSearchTarget2.trim()?"max-md:min-w-16 max-md:px-2":"max-md:w-10 max-md:h-10 max-md:px-0"}`} 42 ${p.enableCustomSearch2?"bg-secondary text-secondary-foreground hover:bg-secondary-hover":"bg-muted text-muted-foreground hover:bg-muted-hover"} 43 ${r?"opacity-50 cursor-not-allowed":"cursor-pointer"} 44 `,children:[p.enableCustomSearch2&&e.jsx(tt,{className:"h-3 w-3"}),e.jsx(st,{className:"h-3 w-3"}),e.jsx("span",{className:`text-sm font-medium ${T?"":"max-md:hidden"}`,children:p.customSearchTarget2}),e.jsx("span",{onClick:h=>{h.stopPropagation(),$()},className:"ml-1 text-muted-foreground/60 hover:text-muted-foreground cursor-pointer",role:"button",tabIndex:0,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),h.stopPropagation(),$())},children:e.jsx(qt,{className:"h-3 w-3"})})]})}),e.jsx(Ae,{children:e.jsxs("p",{children:["Boost scores for ",p.customSearchTarget2," roles"]})})]})})]})}const Jt=ps.memo(Ls),bt=[{type:"companies",label:"Only Companies",icons:[e.jsx(xt,{className:"h-3 w-3 md:h-[14px] md:w-[14px] lg:h-[18px] lg:w-[18px]"},"company")],estimatedTime:"7 seconds",creditCost:10},{type:"contacts",label:"+ Contacts",icons:[e.jsx(xt,{className:"h-3 w-3 md:h-[14px] md:w-[14px] lg:h-[18px] lg:w-[18px]"},"company"),e.jsx(ut,{className:"h-3 w-3 md:h-[14px] md:w-[14px] lg:h-[18px] lg:w-[18px]"},"contacts")],estimatedTime:"12 seconds",creditCost:70},{type:"emails",label:"+ Emails",icons:[e.jsx(xt,{className:"h-3 w-3 md:h-[14px] md:w-[14px] lg:h-[18px] lg:w-[18px]"},"company"),e.jsx(ut,{className:"h-3 w-3 md:h-[14px] md:w-[14px] lg:h-[18px] lg:w-[18px]"},"contacts"),e.jsx(Es,{className:"h-3 w-3 md:h-[14px] md:w-[14px] lg:h-[18px] lg:w-[18px]"},"emails")],estimatedTime:"22 seconds",creditCost:160},{type:"individual_search",label:"Find Individual",icons:[e.jsx(Yt,{className:"h-3 w-3 md:h-[14px] md:w-[14px] lg:h-[18px] lg:w-[18px]"},"individual-search")],estimatedTime:"18 seconds",creditCost:100},{type:"super_search_fast",label:"Super Search (Fast)",icons:[e.jsx(dt,{className:"h-3 w-3 md:h-[14px] md:w-[14px] lg:h-[18px] lg:w-[18px]"}
44,"super-search-fast")],estimatedTime:"30 seconds",creditCost:250},{type:"super_search_deep",label:"Super Search (Deep)",icons:[e.jsx(dt,{className:"h-3 w-3 md:h-[14px] md:w-[14px] lg:h-[18px] lg:w-[18px]"},"super-search-deep")],estimatedTime:"90 seconds",creditCost:250},{type:"super_search_query_first",label:"Super Search (Query-First)",icons:[e.jsx(dt,{className:"h-3 w-3 md:h-[14px] md:w-[14px] lg:h-[18px] lg:w-[18px]"},"super-search-query-first")],estimatedTime:"60 seconds",creditCost:250}];function As({selectedType:o,onTypeChange:a,disabled:r=!1}){const[c,l]=s.useState(!1),n=bt.find(d=>d.type===o)||bt[2],S=d=>{a(d),l(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{"data-testid":"search-options-button",className:`flex items-center gap-1 px-2 py-1 cursor-pointer hover:bg-muted-hover rounded transition-colors ${r?"opacity-50 cursor-not-allowed":""}`,onClick:()=>!r&&l(!0),children:[n.icons.map((d,j)=>e.jsx("div",{className:"text-muted-foreground",children:d},j)),e.jsx(zt,{className:"h-3 w-3 md:h-[14px] md:w-[14px] lg:h-[18px] lg:w-[18px] text-muted-foreground"})]}),e.jsx(Ct,{open:c,onOpenChange:l,children:e.jsxs(wt,{className:"sm:max-w-md rounded-2xl",children:[e.jsx(vt,{children:e.jsx(jt,{children:"Select Your Search Type"})}),e.jsx("div",{className:"space-y-3",children:bt.map(d=>e.jsxs("div",{"data-testid":`search-type-option-${d.type}`,className:`flex items-center justify-between py-2 px-3 rounded-lg border cursor-pointer transition-all ${o===d.type?"border-accent/30 bg-accent-hover hover:bg-accent-active":"border-border bg-muted hover:bg-muted-hover"}`,onClick:()=>S(d.type),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex items-center gap-1",children:d.icons.map((j,g)=>e.jsx("div",{className:`${o===d.type?"text-accent":"text-muted-foreground"}`,children:j},g))}),e.jsx("span",{className:`text-base font-medium ${o===d.type?"text-accent":"text-foreground"}`,children:d.label})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:["~",d.estimatedTime]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground/70",children:[d.creditCost," credits"]})]})]},d.type))})]})})]})}const _s=ks({fullName:Ve().min(2,"Full name is required (at least 2 characters)"),location:Ve().optional(),role:Ve().optional(),company:Ve().optional(),otherContext:Ve().optional(),knownEmail:Ve().email("Please enter a valid email").optional().or(Ns(""))});function qs({isOpen:o,onClose:a,onSearch:r,isSearching:c=!1}){const l=Ts({resolver:Is(_s),defaultValues:{fullName:"",location:"",role:"",company:"",otherContext:"",knownEmail:""}}),n=d=>{r(d)},S=()=>{c||(l.reset(),a())};return e.jsx(Ct,{open:o,onOpenChange:S,children:e.jsxs(wt,{className:"sm:max-w-lg",children:[e.jsx(vt,{children:e.jsxs(jt,{className:"flex items-center gap-2",children:[e.jsx(Yt,{className:"h-5 w-5 text-blue-600"}),"Find Individual"]})}),e.jsx(Rs,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(n),className:"space-y-4",children:[e.jsx(Je,{control:l.control,name:"fullName",render:({field:d})=>e.jsxs(We,{children:[e.jsxs(ze,{className:"flex items-center gap-1",children:["Full Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(He,{children:e.jsx(Me,{placeholder:"Jonathan Novotny","data-testid":"input-full-name",...d})}),e.jsx(Ke,{})]})}),e.jsx(Je,{control:l.control,name:"location",render:({field:d})=>e.jsxs(We,{children:[e.jsx(ze,{className:"text-gray-600",children:"Location (city, state, or country)"}),e.jsx(He,{children:e.jsx(Me,{placeholder:"New York, USA","data-testid":"input-location",...d})}),e.jsx(Ke,{})]})}),e.jsx(Je,{control:l.control,name:"role",render:({field:d})=>e.jsxs(We,{children:[e.jsx(ze,{className:"text-gray-600",children:"Role or Title"}),e.jsx(He,{children:e.jsx(Me,{placeholder:"VP of Engineering","data-testid":"input-role",...d})}),e.jsx(Ke,{})]})}),e.jsx(Je,{control:l.control,name:"company",render:({field:d})=>e.jsxs(We,{children:[e.jsx(ze,{className:"text-gray-600",children:"Company"}),e.jsx(He,{children:e.jsx(Me,{placeholder:"Acme Corp","data-testid":"input-company",...d})}),e.jsx(Ke,{})]})}),e.jsx(Je,{control:l.control,name:"otherContext",render:({field:d})=>e.jsxs(We,{children:[e.jsx(ze,{className:"text-gray-600",children:"Other Context"}),e.jsx(He,{children:e.jsx(Me,{placeholder:"Previously worked at Google","data-testid":"input-other
44-context",...d})}),e.jsx(Ke,{})]})}),e.jsx(Je,{control:l.control,name:"knownEmail",render:({field:d})=>e.jsxs(We,{children:[e.jsx(ze,{className:"text-gray-600",children:"Known Email (helps verify identity)"}),e.jsx(He,{children:e.jsx(Me,{type:"email",placeholder:"[email protected]","data-testid":"input-known-email",...d})}),e.jsx(Ke,{})]})}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[e.jsx(at,{type:"button",variant:"outline",onClick:S,disabled:c,"data-testid":"button-cancel",children:"Cancel"}),e.jsx(at,{type:"submit",disabled:c,className:"bg-gradient-to-r from-cyan-500 to-blue-500 hover:from-cyan-600 hover:to-blue-600","data-testid":"button-search",children:c?"Searching...":"Search"})]})]})})]})})}function Bs({onAnalyze:o,onComplete:a,onSearchResults:r,onCompaniesReceived:c,isAnalyzing:l,value:n,onChange:S,isFromLandingPage:d=!1,onDismissLandingHint:j,lastExecutedQuery:g=null,onSearchSuccess:y,hasSearchResults:b=!1,onSessionIdChange:v,hideRoleButtons:w=!1,onSearchMetricsUpdate:T,onOpenSearchDrawer:z,onProgressUpdate:D,onCacheHit:p,superSearch:M,onSuperSearchActive:N}){const{toast:F}=ht(),Q=Et(),{fireCelebrateConfetti:A}=js(),[I,x]=s.useState({phase:"",completed:0,total:5});s.useState(!1);const[$,oe]=s.useState({query:"",totalCompanies:0,totalContacts:0,totalEmails:0,searchDuration:0,startTime:0,companies:[]}),{user:h}=Ht(),{openForProtectedRoute:G}=Kt(),[xe,ie]=s.useState(!1),[te,O]=s.useState(()=>{const u=localStorage.getItem("contactSearchConfig");if(u)try{return JSON.parse(u)}catch(k){console.error("Error loading saved contact search config:",k)}return{enableCoreLeadership:!0,enableDepartmentHeads:!1,enableMiddleManagement:!1,enableCustomSearch:!1,customSearchTarget:"",enableCustomSearch2:!1,customSearchTarget2:""}}),[le,Y]=s.useState(!1),H=s.useRef(null),[R,Ee]=s.useState(()=>localStorage.getItem("searchType")||"contacts"),[Ge,se]=s.useState(!1),[ne,pe]=s.useState(!1);(M==null?void 0:M.status)==="streaming"||(M==null?void 0:M.status)==="connecting"||(M==null||M.status);const fe=u=>{u==="individual_search"&&se(!0),Ee(u)};s.useEffect(()=>{const u=localStorage.getItem("searchType"),k=!localStorage.getItem("hasEverBeenRegistered");h&&k?(localStorage.setItem("hasEverBeenRegistered","true"),Ee("emails")):u||Ee(h?"emails":"contacts")},[h]),s.useEffect(()=>{localStorage.setItem("searchType",R)},[R]);const[X,ce]=s.useState(null),[ye,ae]=s.useState(!1),[Ie,Ne]=s.useState(!1),ge=s.useRef(null),K=s.useRef(!1),qe=s.useRef(null),V=s.useRef(null),Se=s.useRef(!1),Oe=s.useRef(r),Re=s.useRef(c),de=s.useRef(y),Te=s.useRef(F);s.useEffect(()=>{Oe.current=r,Re.current=c,de.current=y,Te.current=F});const Be=async u=>{try{const k=je.load();if(!k)return;const _=k.currentResults;if(!_||_.length===0)return;console.log("[Email Refresh] Starting database sync for",_.length,"companies"),console.log("[Email Refresh] Invalidating React Query cache..."),_.forEach(U=>{Q.invalidateQueries({queryKey:[`/api/companies/${U.id}/contacts`]})}),await new Promise(U=>setTimeout(U,50)),console.log("[Email Refresh] Fetching fresh contact data from database...");const L=await Promise.all(_.map(async U=>{try{const J=await fetch(`/api/companies/${U.id}/contacts`);if(J.ok){const ee=await J.json();return{...U,contacts:ee}}else return console.error(`Failed to refresh contacts for company ${U.id}:`,J.status),U}catch(J){return console.error(`Failed to refresh contacts for company ${U.id}:`,J),U}}));je.save({currentQuery:u.query,currentResults:L,currentListId:null,lastExecutedQuery:u.query}),Oe.current(u.query,L),console.log("[Email Refresh] Database sync completed - all emails reflected"),Te.current({title:"Email Search Complete",description:"Contact data updated with fresh email discoveries"})}catch(k){console.error("[Email Refresh] Database sync failed:",k)}};s.useEffect(()=>{if(!X||!ye||K.current)return;K.current=!0;const u=async()=>{var k;if(K.current)try{const _=await fetch(`/api/search-sessions/${X}/status`);if(_.ok){const L=_.headers.get("content-type");if(!L||!L.includes("application/json")){console.warn("Session polling response is not JSON, skipping...");return}const U=await _.json();if(!U.success||!U.session){console.warn("Invalid session response structure:",U);return}const J=U.session;if(J.emailSearchStatus==="completed"&&J.emailSearchCompleted){console.log("Email search completed, refreshing contact data");const ee=localStorage.getItem("lastCacheUpdate")?parseInt(localStorage.getItem("lastCacheUpdate")||"0"):0;J.emailSearchCompleted>ee&&(console.log("Email search newer than cache, refreshing data"),Be(J),localStorage.setItem("lastCacheUpdate",J.emailSearchCompleted.toString()))}J.status==="contacts_complete"&&J.fullResults?(console.log("Session completed, restoring results:",J),K.current=!1,ae(!1),ge.current&&(clearInterval(ge.current),ge.current=null),ue.cleanupSession(J.id),Oe.current(J.query,J.fullResults),(k=de.current)==null||k.call(de),Te.current({title:"Search completed!",description:`Found results for "${J.query}"`})):J.status==="failed"&&(console.log("Session failed:",J),K.current=!1,ae(!1),ge.current&&(clearInterval(ge.current),ge.current=null),ue.cleanupSession(J.id),Te.current({title:"Search failed",description:J.error||"An error occurred during search",variant:"destructive"}))}}catch(_){console.error("Error polling session:",_),K.current&&(K.current=!1,ae(!1),ge.current&&(clearInterval(ge.current),ge.current=null))}};return ge.current=setInterval(u,3e3),()=>{K.current=!1,ge.current&&(clearInterval(ge.current),ge.current=null)}},[X,ye]),s.useEffect(()=>()=>{ge.current&&clearInterval(ge.current),qe.current&&clearTimeout(qe.current),H.current&&clearTimeout(H.current),K.current=!1},[]);const pt=u=>!u.fullResults||!Array.isArray(u.fullResults)?!1:u.fullResults.some(k=>k.contacts&&Array.isArray(k.contacts)&&k.contacts.length>0);s.useEffect(()=>
44{if(console.log("[SESSION-RESTORE] Effect triggered",{hasRestoredSession:Ie,currentSessionId:X,isPolling:ye}),Ie){console.log("[SESSION-RESTORE] Skipping - already restored");return}(async()=>{console.log("[SESSION-RESTORE] handleSessionRestore starting");const k=ue.getActiveSessions(),_=ue.getMostRecentCompleteSession();if(k.length>0){if(k.length>1){console.log(`[Session Conflict] Found ${k.length} active sessions, cleaning up older ones...`);const U=k[0],J=k.slice(1);for(const ee of J)await ue.terminateSession(ee.id);console.log(`[Session Conflict] Terminated ${J.length} older sessions, keeping ${U.id}`)}const L=k[0];console.log("Resuming active session:",L),console.log("[SESSION-RESTORE] Resuming session, setting isPolling=true"),ce(L.id),ae(!0),Ne(!0),v==null||v(L.id),L.quickResults&&L.quickResults.length>0&&(Re.current(L.query,L.quickResults),S(L.query)),Te.current({title:"Search in progress",description:`Continuing search for "${L.query}"`})}else if(_){const L=pt(_);console.log("Restoring recent complete session:",_),console.log("Session has complete contact data:",L),S(_.query),_.fullResults&&L?(console.log("Using complete session data with contacts"),Oe.current(_.query,_.fullResults),Ne(!0)):console.log("Session has incomplete data - allowing localStorage fallback")}})()},[Ie]);const $e=s.useCallback(()=>{const u=!le;Y(u),H.current&&(clearTimeout(H.current),H.current=null),u&&(H.current=setTimeout(()=>{Y(!1),H.current=null},6e3))},[le]),rt=s.useCallback(u=>{console.log("PromptEditor received config update:",u),O(u),H.current&&(clearTimeout(H.current),H.current=null),H.current=setTimeout(()=>{Y(!1),H.current=null},600)},[]);s.useEffect(()=>{g!==null&&n!==g&&ie(!0)},[n,g]);const[ft,ot]=s.useState(!1);s.useEffect(()=>{if(d){ot(!0);const u=setTimeout(()=>{ot(!1)},3e3);return()=>clearTimeout(u)}},[d]);const be=Ue({mutationFn:async u=>{console.log("Initiating company search process..."),console.log("Sending request to company discovery API..."),console.log("[Session Management] Cleaning up active sessions before starting new search..."),await ue.cleanupActiveSessions();const k=ue.createSession(u,void 0,te).id;return ce(k),Ne(!0),console.log(`Created session ${k} for query: ${u}`),console.log("Quick search initiated"),(await he("POST","/api/companies/quick-search",{query:u,strategyId:void 0,contactSearchConfig:te,sessionId:k,searchType:R}
44)).json()},onSuccess:u=>{if(console.log(`Job created with ID: ${u.jobId}`),V.current=u.jobId,Se.current){console.log("Cache hit already occurred, terminating new job"),he("POST",`/api/search-jobs/${u.jobId}/terminate`).catch(()=>{}),K.current=!1,ae(!1);return}ie(!1),X&&(ue.updateSessionWithJob(X,u.jobId),ae(!0),console.log(`Started polling for job ${u.jobId} completion`));const k=async()=>{var _,L,U,J,ee;if(K.current)try{const P=await he("GET",`/api/search-jobs/${u.jobId}`);if(P.ok){const q=await P.json();if((q.status==="processing"||q.status==="completed")&&q.results){const W=((_=q.results)==null?void 0:_.companies)||[],re=W.reduce((Z,me)=>{var we;return Z+(((we=me.contacts)==null?void 0:we.length)||0)},0);W.length>0&&(X&&(R==="companies"?(ue.updateWithQuickResults(X,W),c(n,W)):(ue.updateWithFullResults(X,W),r(n,W))),console.log(`Progressive update: ${W.length} companies, ${re} contacts`))}if(q.status==="completed"){console.log(`Job ${u.jobId} completed`),console.log("[POLLING] Job completed - setting isPolling=false, isPollingRef=false"),K.current=!1,ae(!1);const W=((L=q.results)==null?void 0:L.companies)||[],re=W.reduce((Z,me)=>{var we;return Z+(((we=me.contacts)==null?void 0:we.length)||0)},0);if(console.log(`Final results: ${W.length} companies with ${re} contacts`),X&&R==="companies"&&ue.markQuickResultsComplete(X),R==="companies")F({title:"Search Complete",description:`Found ${W.length} companies.`}),x(Z=>({...Z,phase:"Search Complete",completed:5,total:5}));else{const Z=Math.round((Date.now()-$.startTime)/1e3),me=W.reduce((Ze,ct)=>ct.contacts?Ze+ct.contacts.filter(ve=>ve.email&&ve.email.length>5).length:Ze,0),we={...$,totalCompanies:W.length,totalContacts:re,totalEmails:me,searchDuration:Z,companies:W,searchType:R,sourceBreakdown:(U=q.results)==null?void 0:U.sourceBreakdown};oe(we),T&&setTimeout(()=>{T(we,!0),setTimeout(()=>{T(we,!1)},15e3)},1e3),A()}h&&Q.invalidateQueries({queryKey:["/api/credits"]}),console.log("[SESSION] Clearing currentSessionId on job completion"),ce(null),a()}else if(q.status==="failed"){console.error(`Job ${u.jobId} failed:`,q.error),K.current=!1,ae(!1),x(Z=>({...Z,phase:"",completed:0,total:5}));const W=q.error||"An error occurred during search";if(W.toLowerCase().includes("insufficient credits"))lt();else try{F({title:"Search Failed",description:W,variant:"destructive"})}catch(Z){console.error("Failed to show toast:",Z)}h&&Q.invalidateQueries({queryKey:["/api/credits"]}),ce(null),a()}else{const W=((J=q.progress)==null?void 0:J.phase)||"",re=W.toLowerCase().includes("error")||W.toLowerCase().includes("insufficient"),Z=((ee=q.progress)==null?void 0:ee.message)||q.error||"";re?(console.error(`Job ${u.jobId} has error phase:`,W,Z),K.current=!1,ae(!1),x(we=>({...we,phase:"",completed:0,total:5})),W.toLowerCase().includes("insufficient")||Z.toLowerCase().includes("insufficient credits")?lt():F({title:"Search Failed",description:Z||"An error occurred during search",variant:"destructive"}),h&&Q.invalidateQueries({queryKey:["/api/credits"]}),ce(null),a()):(q.progress&&x(me=>({...me,phase:W||"Processing",completed:q.progress.completed||0,total:q.progress.total||5})),setTimeout(k,500))}}}catch(P){console.error("Polling error:",P),K.current&&setTimeout(k,1e3)}};K.current=!0,ae(!0),k()},onError:u=>{x(L=>({...L,phase:"",completed:0,total:5}));const k=u.message||"Search failed";if(k.includes("402:")||k.toLowerCase().includes("insufficient credits"))lt();else try{F({title:"Search Failed",description:k,variant:"destructive"})}catch(L){console.error("Failed to show toast:",L)}h&&Q.invalidateQueries({queryKey:["/api/credits"]}),a()}}),Qe=Ue({mutationFn:async u=>{console.log("Initiating structured individual search..."),await ue.cleanupActiveSessions();const k=[u.fullName,u.role,u.company?`at ${u.company}`:null,u.location?`in ${u.location}`:null].filter(Boolean).join(" "),_=ue.createSession(k).id;return ce(_),(await he("POST","/api/companies/quick-search",{query:k,searchType:"individual_search",sessionId:_,structuredSearch:{fullName:u.fullName,location:u.location||void 0,role:u.role||void 0,company:u.company||void 0,otherContext:u.otherContext||void 0,knownEmail:u.knownEmail||void 0}})).json()},onSuccess:u=>{console.log(`Individual search job created with ID: ${u.jobId}`),se(!1),ie(!1),X&&(ue.updateSessionWithJob(X,u.jobId),ae(!0));const k=async()=>{var _,L,U,J;if(K.current)try{const ee=await he("GET",`/api/search-jobs/${u.jobId}`);if(ee.ok){const P=await ee.json();if((P.status==="processing"||P.status==="completed")&&P.results){const q=((_=P.results)==null?void 0:_.companies)||[],W=q.reduce((re,Z)=>{var me;return re+(((me=Z.contacts)==null?void 0:me.length)||0)},0);q.length>0&&(X&&(ue.updateWithFullResults(X,q),r(n,q)),console.log(`Individual search update: ${q.length} companies, ${W} contacts`))}if(P.status==="completed"){console.log(`Individual search job ${u.jobId} completed`),K.current=!1,ae(!1),pe(!1),ce(null);const W=(((L=P.results)==null?void 0:L.companies)||[]).reduce((re,Z)=>{var me;return re+(((me=Z.contacts)==null?void 0:me.length)||0)},0);a(),y==null||y(),Q.invalidateQueries({queryKey:["/api/credits"]}),F({title:"Individual Search Complete",description:`Found ${W} candidate(s)`})}else if(P.status==="failed"){K.current=!1,ae(!1),pe(!1),ce(null),x(re=>({...re,phase:"",completed:0,total:5}));const q=P.error||"Individual search failed",W=q.toLowerCase().includes("insufficient credits");try{F({title:W?"Insufficient Credits":"Search Failed",description:q,variant:"destructive"})}catch(re){console.error("Failed to show toast:",re)}Q.invalidateQueries({queryKey:["/api/credits"]}),a()}else{const q=((U=P.progress)==null?void 0:U.phase)||"",W=q.toLowerCase().includes("error")||q.toLowerCase().includes("insufficient"),re=((J=P.progress)==null?void 0:J.message)||P.error||"";if(W){console.error(`Individual search job ${u.jobId} has error phase:`,q,re),K.current=!1,ae(!1),pe(!1),ce(null),x(me=>({...me,phase:"",completed:0,total:5}));const Z=q.toLowerCase().includes("insufficient")||re.toLowerCase().includes("insufficient credits");F({title:Z?"Insufficient Credits":"Search Failed",description:Z?"You don't have enough credits for this search. Please add more credits to continue."
44:re||"An error occurred during search",variant:"destructive"}),Q.invalidateQueries({queryKey:["/api/credits"]}),a()}else setTimeout(k,500)}}}catch(ee){console.error("Individual search polling error:",ee),K.current&&setTimeout(k,1e3)}};K.current=!0,ae(!0),k()},onError:u=>{pe(!1),x(L=>({...L,phase:"",completed:0,total:5}));const k=u.message||"Search failed";if(k.includes("402:")||k.toLowerCase().includes("insufficient credits"))lt();else try{F({title:"Search Failed",description:k,variant:"destructive"})}catch(L){console.error("Failed to show toast:",L)}Q.invalidateQueries({queryKey:["/api/credits"]}),a()}});s.useEffect(()=>{if(D){const u=be.isPending||ye||Qe.isPending;D({phase:I.phase,completed:I.completed,total:I.total,isVisible:u})}},[I.phase,I.completed,I.total,be.isPending,ye,Qe.isPending,D]);const nt=u=>{pe(!0),o();const k=[u.fullName,u.role,u.company?`at ${u.company}`:null,u.location?`in ${u.location}`:null].filter(Boolean).join(" ");S(k),x({phase:"Starting search",completed:0,total:5}),oe({query:k,totalCompanies:0,totalContacts:0,totalEmails:0,searchDuration:0,startTime:Date.now(),companies:[]}),Qe.mutate(u)},Ye=async()=>{var U,J;if(!n.trim()){F({title:"Empty Query",description:"Please enter a search query.",variant:"destructive"});return}const u=n.trim().toLowerCase();if(u==="5ducks"||u==="free palestine"||u==="he is risen")try{const P=await(await he("POST","/api/credits/easter-egg",{query:n.trim()})).json();F({title:`${P.easterEgg.emoji} Easter Egg Found!`,description:`${P.easterEgg.description} - +${P.easterEgg.reward} credits added!`}),Q.invalidateQueries({queryKey:["/api/credits"]}),a();return}catch(ee){const P=await((U=ee.response)==null?void 0:U.json());F({title:"Easter Egg",description:(P==null?void 0:P.message)||"Already claimed!",variant:"destructive"}),a();return}d&&j&&j(),x({phase:"Starting search",completed:0,total:5}),oe({query:n,totalCompanies:0,totalContacts:0,totalEmails:0,searchDuration:0,startTime:Date.now(),companies:[]}),(J=window.dataLayer)==null||J.push({event:"search_performed"}),Ut("search_performed").catch(()=>{}),console.log("Analyzing search query...");const k=R==="super_search_fast"||R==="super_search_deep"||R==="super_search_query_first";if(console.log(`Preparing to search for ${R==="companies"?"companies only":R==="contacts"?"companies and contacts":R==="individual_search"?"specific individual":k?"AI-powered super search":"companies, contacts, and emails"}...`),o(),k){const ee=R==="super_search_fast"?"v1_perplexity_one-shot":R==="super_search_deep"?"v2_anthropic_multi-step":"v3_anthropic_query-first";M&&N&&(N(!0),M.startSearch(n,void 0,ee));return}else be.mutate(n);h||setTimeout(()=>{G()},35e3),Se.current=!1;const _=sessionStorage.getItem("forceBypassCache")==="true";_&&(sessionStorage.removeItem("forceBypassCache"),console.log("ð Bypass cache flag detected - skipping cache check for fresh results")),(async()=>{if(_){console.log("ð Cache bypass active - fetching fresh results");return}try{const P=await(await fetch(`/api/lists/by-prompt?prompt=${encodeURIComponent(n)}`)).json();if(P&&P.listId&&!Se.current){if(console.log(`ð¯ Cache hit! Found cached search (listId: ${P.listId})`),Se.current=!0,V.current)try{await he("POST",`/api/search-jobs/${V.current}/terminate`),console.log(`Terminated job ${V.current} due to cache hit`)}catch{console.log("Job termination skipped (may have already completed)")}K.current=!1,ae(!1),ce(null),p&&p(P),F({title:"Loaded cached results",description:`Found ${P.resultCount} companies from a previous search.`})}}catch{console.log("Cache check failed, continuing with fresh search")}})()},Xe=s.useRef(()=>{});s.useEffect(()=>{Xe.current=Ye}),s.useEffect(()=>{const u=()=>{console.log("ð Fresh search triggered via event"),Xe.current()};return window.addEventListener("triggerFreshSearch",u),()=>{window.removeEventListener("triggerFreshSearch",u)}},[]);const gt=async()=>{if(console.log("User requested search stop"),K.current=!1,ae(!1),V.current)try{await he("POST",`/api/search-jobs/${V.current}/terminate`),console.log(`Terminated job ${V.current}
44`),F({title:"Search stopped",description:"The search has been cancelled."})}catch{console.log("Job termination failed")}V.current=null,ce(null),a()};return e.jsxs("div",{className:"pl-0 pr-1 pt-1 pb-1 shadow-none",children:[" ",e.jsxs("div",{className:"flex flex-col gap-0 md:gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(fs,{value:n,onChange:u=>{S(u.target.value)},onKeyDown:u=>{u.key==="Enter"&&!u.shiftKey&&!(l||be.isPending)&&(u.preventDefault(),Ye())},placeholder:"Recently exited startups in Miami ",rows:2,className:`md:rounded-md rounded-md resize-none pb-12 text-base md:text-lg text-foreground placeholder:text-muted-foreground/50 hover:border-border md:focus-visible:border-border ${d?"racing-light-effect":""} ${ft?"gradient-text-input":""}`,"data-testid":"search-input"}),e.jsxs("div",{className:"absolute bottom-2 left-2 right-2 flex items-end justify-between pointer-events-none",children:[e.jsxs("div",{className:"pointer-events-auto flex items-center gap-2",children:[e.jsx(As,{selectedType:R,onTypeChange:fe,disabled:l||be.isPending||Qe.isPending}),te.enableCoreLeadership?e.jsxs("button",{onClick:$e,className:"flex items-center gap-1 px-2 py-1 rounded text-muted-foreground text-sm hover:bg-muted-hover transition-colors cursor-pointer",children:[e.jsx(Wt,{className:"h-3 w-3 md:h-[14px] md:w-[14px] lg:h-[18px] lg:w-[18px]"}),e.jsx("span",{className:"font-medium",children:"Leadership"})]}):te.enableDepartmentHeads?e.jsxs("button",{onClick:$e,className:"flex items-center gap-1 px-2 py-1 rounded text-muted-foreground text-sm hover:bg-muted-hover transition-colors cursor-pointer",children:[e.jsx(Gt,{className:"h-3 w-3 md:h-[14px] md:w-[14px] lg:h-[18px] lg:w-[18px]"}),e.jsx("span",{className:"font-medium",children:"Marketing"})]}):te.enableMiddleManagement?e.jsxs("button",{onClick:$e,className:"flex items-center gap-1 px-2 py-1 rounded text-muted-foreground text-sm hover:bg-muted-hover transition-colors cursor-pointer",children:[e.jsx(ut,{className:"h-3 w-3 md:h-[14px] md:w-[14px] lg:h-[18px] lg:w-[18px]"}),e.jsx("span",{className:"font-medium",children:"CTO"})]}):te.enableCustomSearch&&te.customSearchTarget?e.jsxs("button",{onClick:$e,className:"flex items-center gap-1 px-2 py-1 rounded text-muted-foreground text-sm hover:bg-muted-hover transition-colors cursor-pointer",children:[e.jsx(st,{className:"h-3 w-3 md:h-[14px] md:w-[14px] lg:h-[18px] lg:w-[18px]"}),e.jsx("span",{className:"font-medium",children:te.customSearchTarget})]}):te.enableCustomSearch2&&te.customSearchTarget2?e.jsxs("button",{onClick:$e,className:"flex items-center gap-1 px-2 py-1 rounded text-muted-foreground text-sm hover:bg-muted-hover transition-colors cursor-pointer",children:[e.jsx(st,{className:"h-3 w-3 md:h-[14px] md:w-[14px] lg:h-[18px] lg:w-[18px]"}),e.jsx("span",{className:"font-medium",children:te.customSearchTarget2})]}):null,(h==null?void 0:h.isAdmin)&&e.jsx(Pe,{children:e.jsxs(Fe,{children:[e.jsx(Le,{asChild:!0,children:e.jsx("button",{onClick:z,className:"flex items-center justify-center p-2 rounded-full text-muted-foreground hover:bg-muted-hover hover:text-foreground transition-colors cursor-pointer","aria-label":"Search Management","data-testid":"button-search-management",children:e.jsx(Os,{className:"h-4 w-4"})})}),e.jsx(Ae,{children:e.jsx("p",{children:"Manage Search Queue"})})]})})]}),e.jsx("div",{className:"pointer-events-auto",children:(()=>{const u=l||be.isPending||ye;return console.log("[STATE] isSearchActive:",{isAnalyzing:l,isPending:be.isPending,isPolling:ye,result:u}),e.jsx(at,{type:u?"button":"submit",onClick:u?gt:Ye,disabled:!u&&(l||be.isPending),className:` 45 rounded-md group 46 transition-all duration-300 flex items-center gap-2 47 ${!(n!=null&&n.trim())||g&&!xe&&!u?"bg-secondary hover:bg-secondary-hover shadow-md hover:shadow-lg text-muted-foreground":"bg-gradient-to-r from-accent-light to-accent hover:from-accent hover:to-accent-dark text-white shadow-md hover:shadow-lg"} 48 `,"aria-label":u?"Stop Search":"Search","data-testid":u?"stop-search-button":"search-button",children:u?e.jsxs(e.Fragment,{children:[e.jsx(gs,{className:"h-4 w-4 animate-spin hidden md:block md:group-hover:hidden"}),e.jsx("span",{className:"hidden md:block md:group-hover:hidden",children:"Searching"}),e.jsx($s,{className:"h-4 w-4 block md:hidden md:group-hover:block"}),e.jsx("span",{className:"block md:hidden md:group-hover:block",children:"Stop"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Xt,{className:"h-4 w-4"}),e.jsx("span",{children:"Search"})]})})})()})]})]}),!w&&le&&e.jsx("div",{className:"md:hidden",children:e.jsx(Jt,{config:te,onConfigChange:rt,disabled:l||be.isPending,isSearching:be.isPending,hasSearchResults:b,inputHasChanged:b&&n!==g})}),!w&&le&&e.jsx("div",{className:"hidden md:block",children:e.jsx(Jt,{config:te,onConfigChange:rt,disabled:l||be.isPending,isSearching:be.isPending,hasSearchResults:b,inputHasChanged:b&&n!==g})})]}),e.jsx(qs,{isOpen:Ge,onClose:()=>se(!1),onSearch:nt,isSearching:ne})]})}const _e="emailComposerState",Qs=500;function Ba(o,a=!0){const r=s.useRef(),c=s.useRef(!1),l=s.useRef(!1),n=s.useRef("");return s.useEffect(()=>{if(!a||c.current||!l.current)return;const j=JSON.stringify(o);if(j!==n.current)return r.current&&clearTimeout(r.current),r.current=setTimeout(()=>{try{const g=Object.entries(o).reduce((y,[b,v])=>(v!==void 0&&typeof v!="function"&&(y[b]=v),y),{});g.isOpen&&(localStorage.setItem(_e,JSON.stringify(g)),n.current=j,console.log("Saved email composer state:",g))}catch(g){console.error("Failed to save email composer state:",g)}},Qs),()=>{r.current&&clearTimeout(r.current)}},[o,a]),{restoreState:()=>{try{c.current=!0;const j=localStorage.getItem(_e);if(j){const g=JSON.parse(j);return console.log("Restored email composer state:",g),setTimeout(()=>{c.current=!1,l.current=!0},200),g}}catch(j){console.error("Failed to restore email composer state:",j)}return c.current=!1,setTimeout(()=>{l.current=!0},100),null},clearState:()=>{try{localStorage.removeItem(_e),n.current="",console.log("Cleared email composer state")}catch(j){console.error("Failed to clear email composer state:",j)}}}}function Vs(){try{const o=localStorage.getItem(_e);if(o){const a=JSON.parse(o);return{isOpen:a.isOpen||!1,drawerMode:a.drawerMode,emailSubject:a.emailSubject||a.templateSubject||a.aiSubject}}}catch(o){console.error("Failed to get drawer state:",o)}return{isOpen:!1}}function Js(o){try{const a=localStorage.getItem(_e);if(a){const r=JSON.parse(a);r.isOpen=o,localStorage.setItem(_e,JSON.stringify(r))}}catch(a){console.error("Failed to update drawer state:",a)}}function Ws(){try{const o=localStorage.getItem(_e);if(o){const a=JSON.parse(o);return a.emailSubject||a.templateSubject||a.aiSubject}}catch(o){console.error("Failed to get email subject:",o)}}function zs(o={}){const a=Vs(),[r,c]=s.useState(a.isOpen||!1),[l,n]=s.useState(a.drawerMode||"compose"),[
48S,d]=s.useState("normal"),[j,g]=s.useState(null),[y,b]=s.useState(null),[v,w]=s.useState([]),[T,z]=s.useState(480),[D,p]=s.useState(!1);s.useEffect(()=>{const $=h=>{if(!D)return;const G=window.innerWidth-h.clientX,xe=Math.max(320,Math.min(720,G));z(xe)},oe=()=>{p(!1)};return D&&(document.addEventListener("mousemove",$),document.addEventListener("mouseup",oe),document.body.style.userSelect="none",document.body.style.cursor="col-resize"),()=>{document.removeEventListener("mousemove",$),document.removeEventListener("mouseup",oe),document.body.style.userSelect="",document.body.style.cursor=""}},[D]);const M=s.useCallback(($,oe,h)=>{var G;g($),b(oe),w(h),c(!0),d("normal"),(G=o.onOpen)==null||G.call(o,$,oe)},[o]),N=s.useCallback(()=>{var $;c(!1),Js(!1),n("compose"),d("normal"),g(null),b(null),w([]),($=o.onClose)==null||$.call(o)},[o]),F=s.useCallback(()=>{n("compose"),g(null),b(null),w([]),c(!0),d("normal")},[]),Q=s.useCallback($=>{$.preventDefault(),p(!0)},[]),A=s.useCallback(()=>{d("minimized")},[]),I=s.useCallback(()=>{d("expanded")},[]),x=s.useCallback(()=>{d("normal")},[]);return{isOpen:r,mode:l,viewState:S,selectedContact:j,selectedCompany:y,selectedCompanyContacts:v,drawerWidth:T,isResizing:D,openDrawer:M,openCompose:F,closeDrawer:N,setMode:n,setSelectedContact:g,setIsResizing:p,handleMouseDown:Q,minimize:A,expand:I,restore:x}}function Hs(o={}){const[a,r]=s.useState(!1),[c,l]=s.useState(480),[n,S]=s.useState(!1);s.useEffect(()=>{const y=v=>{if(!n)return;const w=window.innerWidth-v.clientX,T=Math.max(400,Math.min(720,w));l(T)},b=()=>{S(!1)};return n&&(document.addEventListener("mousemove",y),document.addEventListener("mouseup",b),document.body.style.userSelect="none",document.body.style.cursor="col-resize"),()=>{document.removeEventListener("mousemove",y),document.removeEventListener("mouseup",b),document.body.style.userSelect="",document.body.style.cursor=""}},[n]);const d=s.useCallback(()=>{var y;r(!0),(y=o.onOpen)==null||y.call(o)},[o]),j=s.useCallback(()=>{var y;r(!1),(y=o.onClose)==null||y.call(o)},[o]),g=s.useCallback(y=>{y.preventDefault(),S(!0)},[]);return{isOpen:a,drawerWidth:c,isResizing:n,openDrawer:d,closeDrawer:j,setIsResizing:S,handleMouseDown:g}}const Ks=[{id:0,type:"welcome",trigger:"registration_complete",title:"Congrats Hatchling Level Unlocked!",description:`You have unlocked **Email Search**. 49 50Run a NEW search now to see complete results including emails of ~2 Key Contacts per company.`,badge:"Hatchling",emoji:"ð¦",buttonText:"Chirp"}];function Us(o){return Ks.find(a=>a.trigger===o)}const Zt="5ducks_shown_badges";function es(){try{const o=localStorage.getItem(Zt);return o?JSON.parse(o):[]}catch{return[]}}function Gs(o){try{const a=es();a.includes(o)||(a.push(o),localStorage.setItem(Zt,JSON.stringify(a)))}catch(a){console.error("Failed to save badge state:",a)}}function Ys(o){return es().includes(o)}function Xs(){const[o,a]=s.useState({isOpen:!1,badge:null}),r=s.useCallback(l=>{if(Ys(l))return console.log("Badge already shown for trigger:",l),!1;const n=Us(l);return n?(a({isOpen:!0,badge:n}),!0):(console.log("No badge found for trigger:",l),!1)},[]),c=s.useCallback(()=>{o.badge&&Gs(o.badge.trigger),a({isOpen:!1,badge:null})},[o.badge]);return{notificationState:o,triggerNotification:r,closeNotification:c}}function Zs({notificationState:o,onClose:a}){if(!o||!o.isOpen||!o.notification&&!o.badge)return null;const r=o.badge||o.notification,c=l=>l.split(` 51`).map((n,S)=>e.jsxs("span",{children:[n.split("**").map((d,j)=>j%2===1?e.jsx("strong",{children:d},j):d),S<l.split(` 52`).length-1&&e.jsx("br",{})]},S));return e.jsx(Ct,{open:o.isOpen,onOpenChange:a,children:e.jsxs(wt,{className:"sm:max-w-md rounded-lg border-2 shadow-xl border-blue-200 bg-white",children:[e.jsxs(vt,{className:"text-center space-y-4",children:[r.badge&&e.jsx("div",{className:"flex justify-center",children:e.jsxs(Ds,{variant:"outline",className:"rounded-full px-4 py-2 text-sm font-medium border-2 bg-blue-100 text-blue-800 border-blue-200",children:[r.emoji&&e.jsx("span",{className:"mr-2",children:r.emoji}),r.badge]})}),e.jsx(jt,{className:"text-xl font-bold text-gray-900 leading-tight",children:r.title}),e.jsx(Ss,{className:"text-gray-700 leading-relaxed text-base",children:c(r.description)})]}),e.jsx(xs,{className:"mt-6",children:e.jsx(at,{onClick:a,className:"w-full rounded-md bg-gray-900 text-white hover:bg-gray-800 transition-colors font-medium",children:r.buttonText||"OK"})})]})})}
52const ea={dancing1:"animate-disco-bounce",dancing2:"animate-salsa-spin",dancing3:"animate-breakdance"},ta=5e3,sa=18e4;function aa(){const[o,a]=s.useState("egg"),[r,c]=s.useState(1);s.useEffect(()=>{const n=setTimeout(()=>{a("hatching")},7e3),S=setTimeout(()=>{a("chick")},1e4),d=setTimeout(()=>{a("settled")},15e3);return()=>{clearTimeout(n),clearTimeout(S),clearTimeout(d)}},[]),s.useEffect(()=>{if(o==="settled"){const n=setInterval(()=>{a(`dancing${r}`),setTimeout(()=>{a("settled"),c(S=>S%3+1)},ta)},sa);return()=>clearInterval(n)}},[o,r]);const l=o==="egg"?"animate-egg-shake":o==="hatching"?"animate-hatching-wobble":o==="chick"?"animate-chick-bounce":o.startsWith("dancing")?ea[o]:"";return e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:`text-4xl transform transition-transform duration-300 ${l}`,children:o==="egg"?"ð¥":o==="hatching"?"ð£":"ð¥"})})}function ra(o,a={maxPerCompany:3,minProbability:50}){const c=[...o.filter(d=>d.name&&d.probability&&d.probability>=(a.minProbability??50))].sort((d,j)=>(j.probability||0)-(d.probability||0)),l=[],n=new Set,S={};for(const d of c)d.email&&n.has(d.email.toLowerCase())||d.companyId&&(S[d.companyId]=S[d.companyId]||0,S[d.companyId]>=(a.maxPerCompany??3))||(l.push(d),d.email&&n.add(d.email.toLowerCase()),d.companyId&&S[d.companyId]++);return l}async function oa(o,a){return await(await he("POST",`/api/contacts/${o}/consolidated-email-search`,{searchContext:a})).json()}function na(o={}){const[a,r]=s.useState(new Set),{toast:c}=ht(),{onContactUpdate:l,onSearchComplete:n}=o;return{handleComprehensiveEmailSearch:s.useCallback(async(d,j,g)=>{var y,b;if(!a.has(d)){if(j.email){c({title:"Email Already Found",description:`${j.name} already has email: ${j.email}`,variant:"default"});return}(y=j.completedSearches)!=null&&y.includes("comprehensive_search")&&console.log("[search-email] Comprehensive search already attempted, allowing retry"),r(v=>new Set(v).add(d));try{const v=await oa(d,g);v.emailFound&&v.contact?(c({title:"Email Found!",description:`Found email for ${j.name} via ${v.source}`,variant:"default"}),l==null||l(v.contact),n==null||n(d,!0)):(c({title:"Search Complete",description:`No email found for ${j.name}. All search methods exhausted.`,variant:"default"}),v.contact&&(l==null||l(v.contact)),n==null||n(d,!1))}catch(v){console.error("[search-email] Comprehensive search error:",v),(b=v==null?void 0:v.message)!=null&&b.includes("402")||(v==null?void 0:v.status)===402?c({title:"Insufficient Credits",description:"Please add more credits to continue searching for emails.",variant:"destructive"}):c({title:"Search Error",description:"Failed to complete email search. Please try again.",variant:"destructive"}),n==null||n(d,!1)}finally{r(v=>{const w=new Set(v);return w.delete(d),w})}}},[a,c,l,n]),pendingSearchIds:a,isPending:d=>a.has(d)}}function ca({currentResults:o,currentQuery:a,currentListId:r,lastExecutedQuery:c,currentSessionId:l,setCurrentResults:n,refreshContactDataIfNeeded:S,refreshAndUpdateResults:d,updateListMutation:j,isAutomatedSearchRef:g}){const{toast:y}=ht(),b=Et(),[v,w]=s.useState(!1),[T,z]=s.useState({phase:"",completed:0,total:0,isVisible:!1}),[D,p]=s.useState(!1),[M,N]=s.useState(0),[F,Q]=s.useState(void 0),A=s.useCallback((h,G)=>!h.contacts||h.contacts.length===0?[]:[...h.contacts].sort((ie,te)=>(te.probability||0)-(ie.probability||0)).slice(0,G),[]),I=s.useCallback(()=>(o==null?void 0:o.filter(h=>!A(h,3).some(G=>G.email&&G.email.length>5)))||[],[o,A]),x=s.useCallback(async()=>{if(!(!o||o.length===0)){w(!0),g.current=!0,p(!1),z({phase:"Starting email search",completed:0,total:5,isVisible:!0});try{const G=(await S(o)).filter(se=>!A(se,3).some(ne=>ne.email&&ne.email.length>5));if(G.length===0){console.log("No companies need email searches - all companies have sufficient emails"),w(!1),p(!0);return}const xe=G.map(se=>se.id);console.log(`Starting backend email orchestration for ${xe.length} companies`),l&&ue.markEmailSearchStarted(l);const ie=await he("POST","/api/search-jobs",{query:"email-search-bulk",searchType:"emails",metadata:{companyIds:xe,sessionId:l,isBulkEmailSearch:!0},priority:0});if(!ie.ok)throw new Error(`Job creation failed: ${ie.status}`);const{jobId:te}=await ie.json();let O=!1,le=0;const Y=60;let H={summary:{emailsFound:0,contactsProcessed:0,companiesProcessed:xe.length}};for(;!O&&le<Y;){await new Promise(pe=>setTimeout(pe,2e3));const ne=await(await he("GET",`/api/search-jobs/${te}`)).json();if(ne.progress&&z({phase:ne.progress.phase||"Processing",completed:ne.progress.completed||0,total:ne.progress.total||5,isVisible:!0}),ne.status==="completed")O=!0,H=ne.results||H,console.log("Backend orchestration completed:",H);else if(ne.status==="failed")throw new Error(`Email search job failed: ${ne.error}`);le++}if(!O)throw new Error("Email search job timed out");const R=H.metadata||H.summary||{emailsFound:0,contactsEnriched:0,companiesSearched:0};console.log("Backend orchestration completed with metadata:",R),l&&ue.markEmailSearchCompleted(l),N(R.emailsFound||0),Q(R.sourceBreakdown||{});const Ee=R.contactsEnriched||R.contactsProcessed||0,Ge=R.companiesSearched||R.companiesProcessed||0;if(y({title:"Email Search Complete",description:`Found ${R.emailsFound||0} emails for ${Ee} contacts across ${Ge} companies`}),await b.invalidateQueries({queryKey:["/api/credits"]}),console.log("EMAIL SEARCH COMPLETE: Updating results with email data"),H.
52companies&&Array.isArray(H.companies)){console.log(`Merging emails from ${H.companies.length} companies into current results`);const se=new Map;H.companies.forEach(fe=>{fe.contacts&&Array.isArray(fe.contacts)&&se.set(fe.id,fe.contacts)});const ne=o.map(fe=>{var ce;const X=se.get(fe.id);if(X){const ye=((ce=fe.contacts)==null?void 0:ce.map(ae=>{const Ie=X.find(Ne=>Ne.id===ae.id);return Ie?{...ae,...Ie}:ae}))||X;return{...fe,contacts:ye}}return fe});n(ne),je.save({currentQuery:a,currentResults:ne,currentListId:r,lastExecutedQuery:c,emailSearchCompleted:!0});const pe=ne.reduce((fe,X)=>{var ce;return fe+(((ce=X.contacts)==null?void 0:ce.filter(ye=>ye.email&&ye.email.length>0).length)||0)},0);console.log(`Email merge completed with ${pe} emails found`)}else{console.log("EMAIL SEARCH COMPLETE: Falling back to database reload"),await new Promise(pe=>setTimeout(pe,1e3));const ne=(await d(o,{currentQuery:a,currentListId:r,lastExecutedQuery:c},{forceFresh:!0,additionalStateFields:{emailSearchCompleted:!0,emailSearchTimestamp:Date.now()}})).reduce((pe,fe)=>{var X;return pe+(((X=fe.contacts)==null?void 0:X.filter(ce=>ce.email&&ce.email.length>0).length)||0)},0);console.log(`Database reload completed with ${ne} emails found`)}r&&a&&o&&(console.log("Updating existing list after email search completion:",r),j.mutate({query:a,companies:o,listId:r})),w(!1),g.current=!1,p(!0),z(se=>({...se,isVisible:!1}))}catch(h){console.error("Backend email orchestration error:",h),y({title:"Search Failed",description:h instanceof Error?h.message:"Failed to complete email search",variant:"destructive"}),w(!1),g.current=!1,z(G=>({...G,isVisible:!1}))}}},[o,a,r,c,l,n,S,d,j,g,y,b,A]),$=s.useCallback((h,G)=>{N(h),G&&Q(G),p(!0)},[]),oe=s.useCallback(()=>{p(!1)},[]);return{isSearching:v,searchProgress:T,summaryVisible:D,lastEmailSearchCount:M,lastSourceBreakdown:F,runEmailSearch:x,getCurrentCompaniesWithoutEmails:I,getTopContacts:A,updateEmailSearchMetrics:$,closeSummary:oe}}function ia(o={}){const[a,r]=s.useState([]),[c,l]=s.useState(!1),[n,S]=s.useState(!1),[d,j]=s.useState(null),[g,y]=s.useState(null),b=s.useRef(null),v=s.useCallback(async N=>{var Q;if(!N.trim())return;const F={id:`user-${Date.now()}`,role:"user",content:N,createdAt:new Date};r(A=>[...A,F]),l(!0),j(null),b.current=new AbortController;try{const A=await fetch("/api/assistant-chat/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:[...a,F].map(h=>({role:h.role,content:h.content})),searchContext:g}),signal:b.current.signal});if(!A.ok)throw new Error("Failed to send message");const I=(Q=A.body)==null?void 0:Q.getReader();if(!I)throw new Error("No response body");const x={id:`assistant-${Date.now()}`,role:"assistant",content:"",toolCalls:[],createdAt:new Date};r(h=>[...h,x]);const $=new TextDecoder;let oe="";for(;;){const{done:h,value:G}=await I.read();if(h)break;oe+=$.decode(G,{stream:!0});const xe=oe.split(` 53`);oe=xe.pop()||"";for(const ie of xe)if(ie.startsWith("data: ")){const te=ie.slice(6);if(te==="[DONE]")continue;try{const O=JSON.parse(te);O.type==="text"?r(le=>{const Y=[...le],H=Y[Y.length-1];return H.role==="assistant"&&(H.content+=O.content),Y}):O.type==="tool_calls"&&r(le=>{const Y=[...le],H=Y[Y.length-1];return H.role==="assistant"&&(H.toolCalls=O.calls),Y})}catch(O){console.error("Failed to parse SSE data:",O)}}}}catch(A){A.name!=="AbortError"&&(console.error("Chat error:",A),j(A.message))}finally{l(!1),b.current=null}},[a,g,o]),w=s.useCallback(()=>{var N;(N=b.current)==null||N.abort(),l(!1)},[]),T=s.useCallback(()=>S(!0),[]),z=s.useCallback(()=>S(!1),[]),D=s.useCallback(()=>S(N=>!N),[]),p=s.useCallback(()=>{r([]),j(null)},[]),M=s.useCallback(N=>{if(y(N),N&&a.length===0){const F={id:`assistant-welcome-${Date.now()}`,role:"assistant",content:la(N),createdAt:new Date};r([F])}},[a.length]);return{messages:a,isLoading:c,isOpen:n,error:d,searchContext:g,sendMessage:v,stopGeneration:w,openPanel:T,closePanel:z,togglePanel:D,clearMessages:p,updateSearchContext:M}}function la(o){const{query:a,resultCount:r,emailCount:c,companies:l}=o,n=r>0?Math.round(c/r*100):0;
53let S=`I found **${r} contacts** across **${l.length} companies** for "${a}".`;return n<50?S+=` Only ${n}% have emails - would you like me to find more?`:n>=80&&(S+=` Great news - ${n}% already have emails!`),S+=` 54 55Here are some things I can help with:`,S}const da=s.lazy(()=>ke(()=>import("./company-cards-DqVAco0I.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]))),ua=s.lazy(()=>ke(()=>import("./index-Ce07gEuN.js"),__vite__mapDeps([18,1,2,17,8,19,20,21,22,14,5,23,24,25,26,27,4,28,29,30,31,13,32,33,3,34])).then(o=>({default:o.SuperSearchResults}))),ma=s.lazy(()=>ke(()=>import("./index-C_RXtAVN.js"),__vite__mapDeps([35,1,2,36,32,5,37,4,28,27,29,30,31,13,38,39,15,40,41,42,11,22,43,44,45,19,20,21,14,23,24,25,26,33,3,34])).then(o=>({default:o.EmailDrawer}))),ha=s.lazy(()=>ke(()=>import("./index-B7oylYAA.js"),__vite__mapDeps([46,1,2,3,47,48,49,50,43,33,29,27,25,19,20,21,22,14,5,23,24,26,4,28,30,31,13,32,34])).then(o=>({default:o.SearchManagementDrawer}))),pa=s.lazy(()=>ke(()=>import("./index-BCiyo5pc.js"),__vite__mapDeps([51,1,2,14,5,52,48,34])).then(o=>({default:o.SearchReportModal}))),fa=s.lazy(()=>ke(()=>import("./index-COrCWlF3.js"),__vite__mapDeps([53,1,2,28,44,14,12,54,55,56,45,57,58,3,52,20])).then(o=>({default:o.OnboardingFlowOrchestrator}))),ga=s.lazy(()=>ke(()=>import("./index-ICiZL7jf.js"),__vite__mapDeps([59,1,2,11,12])).then(o=>({default:o.FeedbackModal}))),Sa=s.lazy(()=>ke(()=>import("./index-ByInqQi6.js"),__vite__mapDeps([60,1,2,6,3,4,5,7,8,9,10,11,12,61])).then(o=>({default:o.TopProspectsCard}))),xa=s.lazy(()=>ke(()=>import("./SelectionToolbar-EvSsmc4K.js"),__vite__mapDeps([62,1,2])).then(o=>({default:o.SelectionToolbar}))),ya=s.lazy(()=>ke(()=>import("./index-sWwZ3lr_.js"),__vite__mapDeps([63,1,2,28,64,27,16,5,65,66,19,20,21,22,14,23,24,25,26,4,29,30,31,13,32,33,3,34])).then(o=>({default:o.AssistantChatPanel})));function ba({isNewSearch:o=!1}){const[a,r]=s.useState(!1),[c,l]=s.useState(""),[n,S]=s.useState(null),[d,j]=s.useState(!1),[g,y]=s.useState(null),b=t=>{var i;console.log("ð¢ LIST ID CHANGED:",{from:g,to:t,timestamp:new Date().toISOString(),stackTrace:(i=new Error().stack)==null?void 0:i.split(` 56`).slice(2,5).join(` 57`)}),y(t)},[v,w]=s.useState("scroll"),[T,z]=s.useState(new Set),[D,p]=s.useState(new Set),[M,N]=s.useState(!1),[F,Q]=s.useState(!1),[A,I]=s.useState(!1),[x,$]=s.useState(null),[oe,h]=s.useState(!1),[G,xe]=s.useState(null),[ie,te]=s.useState({isCached:!1,cachedDate:null,query:null}),O=zs({onClose:()=>{R(!1)}}),le=Hs(),Y=ia({onAction:t=>be(t)}),[H,R]=s.useState(()=>{if(typeof window>"u"||localStorage.getItem("pendingSearchQuery"))return!1;if(window.location.pathname.match(/^\/search\/[^/]+\/\d+/))return!0;const t=je.load();return!!(t!=null&&t.currentResults&&t.currentResults.length>0)}),[Ee,Ge]=s.useState({phase:"",completed:0,total:5,isVisible:!1}),se=Ps(),[ne,pe]=s.useState(!1),[fe,X]=s.useState(!1);s.useEffect(()=>{sessionStorage.getItem("hasTrackedAppPageView")||(Ut("app_page_view").catch(()=>{}),sessionStorage.setItem("hasTrackedAppPageView","true"))},[]);const[ce,ye]=s.useState(!1),[ae,Ie]=s.useState(""),[Ne,ge]=s.useState([]),[K,qe]=s.useState({isOpen:!1,contactId:null,contactName:"",feedbackType:"excellent"}),{toast:V}=ht(),Se=Et(),[,Oe]=ys(),[Re,de]=bs("/search/:slug/:listId"),Te=Kt(),Be=Ht(),{notificationState:pt,triggerNotification:$e,closeNotification:rt}=Xs(),ft=(t,i)=>{var f,C;const m=((f=n==null?void 0:n.find(E=>E.id===i.id))==null?void 0:f.contacts)||[];if(O.openDrawer(t,i,m),!t.email){const E=(C=t.completedSearches)==null?void 0:C.includes("comprehensive_search");V(E?{title:"No email available",description:`All search methods have been exhausted for ${t.name}. Consider selecting another contact.`,variant:"default"}:{title:"No email found",description:'Click the "Find email" button to search for it.',variant:"default"})}R(!0)},ot=t=>{O.setSelectedContact(t)}
57;s.useEffect(()=>{O.isOpen&&n&&n.length>0||n&&n.length>0?R(!0):window.location.pathname.match(/^\/search\/[^/]+\/\d+/)||R(!1)},[O.isOpen,n]),s.useEffect(()=>{if(n&&n.length>0&&c){const t=n.reduce((f,C)=>{var E,B;return f+(((B=(E=C.contacts)==null?void 0:E.filter(Ce=>Ce.email))==null?void 0:B.length)||0)},0),i=n.reduce((f,C)=>{var E;return f+(((E=C.contacts)==null?void 0:E.length)||0)},0),m={query:c,resultCount:i,emailCount:t,companies:n.map(f=>{var C;return{id:f.id,name:f.name,contactCount:((C=f.contacts)==null?void 0:C.length)||0}})};Y.updateSearchContext(m),Y.isOpen||Y.openPanel()}},[n,c]);const be=t=>{var i;switch(console.log("Executing assistant action:",t),t.type){case"expandSearch":t.modifiedQuery?(l(t.modifiedQuery),h(!0),R(!1),V({title:"Query updated",description:"Click Search to find more results"})):(R(!1),V({title:"Expand your search",description:`Strategy: ${(i=t.strategy)==null?void 0:i.replace(/_/g," ")}`}));break;case"narrowSearch":R(!1),V({title:"Narrow your search",description:`Apply filter: ${t.filterType}${t.filterValue?` = ${t.filterValue}`:""}`});break;case"findEmails":ve.runEmailSearch(),V({title:"Finding emails",description:`Searching for emails (${t.scope})...`});break;case"modifyQuery":t.newQuery&&(l(t.newQuery),h(!0),R(!1),V({title:"New search query",description:t.reason||"Click Search to execute"}));break;case"filterByRole":if(t.roles&&t.roles.length>0){const m=t.roles.join(", "),f=c?`${c} ${m}`:m;l(f),h(!0),R(!1),V({title:"Role filter applied",description:`Filtering by: ${m}`})}break;case"analyzeResults":V({title:"Analysis",description:`Performing ${t.analysisType} analysis...`});break;default:V({title:"Action noted",description:"Processing your request..."})}},{handleComprehensiveEmailSearch:Qe,pendingSearchIds:nt}=na({onContactUpdate:t=>{S(i=>{if(!i)return null;const m=i.map(C=>{var E;return{...C,contacts:(E=C.contacts)==null?void 0:E.map(B=>B.id===t.id?{...t,companyName:C.name,companyId:C.id}:B)}}),f=x||c;return je.save({currentQuery:f,currentResults:m,currentListId:g,lastExecutedQuery:x}),m})}}),Ye=Fs(S),{loadSearchState:Xe,persistSearchState:gt,refreshContactDataFromDatabase:u,refreshAndUpdateResults:k,isMountedRef:_,isInitializedRef:L,hasSessionRestoredDataRef:U,refreshVersionRef:J}=Ye,ee=s.useRef(null),P=s.useRef(!1),q=s.useRef(null),W=s.useRef(!1),re=s.useRef(!1),Z=s.useRef(null),me=async t=>{try{const i=sessionStorage.getItem("lastEmailSearchTimestamp");if(i&&Date.now()-parseInt(i)<12e4){console.log("Recent email search detected, refreshing contact data...");const f=await k(t,{currentQuery:c,currentListId:g,lastExecutedQuery:x},{clearEmailSearchTimestamp:!0});return console.log("Contact data refresh completed"),f}}catch(i){console.error("Auto-refresh failed:",i)}return t};s.useEffect(()=>{var m;console.log("ð£ COMPONENT MOUNT - Home page mounting");const t=localStorage.getItem("pendingSearchQuery");if(t)console.log("Found pending search query:",t),l(t),I(!0),localStorage.removeItem("pendingSearchQuery"),je.clear(),b(null),j(!1);else if(!Re&&!o){const f=Xe();if(f&&f.currentResults&&!U.current){U.current=!0,console.log("Restoring from session storage:",{query:f.currentQuery,resultsCount:(m=f.currentResults)==null?void 0:m.length,listId:f.currentListId});const C=f.currentQuery||"",E=f.currentListId;l(C),b(E),S(f.currentResults),$(f.lastExecutedQuery||f.currentQuery),h(!1),E&&j(!0)}else console.log("No saved search state found or session data already restored")}const i=async()=>{if(!W.current){W.current=!0,console.log("Registration success detected, triggering welcome notification");try{const f=Xe(),C={originalQuery:(f==null?void 0:f.currentQuery)||null};console.log("Extracted guest data:",C),je.clear(),localStorage.removeItem("contactSearchConfig"),sessionStorage.removeItem("lastEmailSearchTimestamp"),localStorage.removeItem("pendingSearchQuery"),localStorage.removeItem("fluffy-guidance-progress"),Object.keys(localStorage).forEach(E=>{E.startsWith("fluffy-quest-triggered-")&&localStorage.removeItem(E)}),S(null),b(null),j(!1),Q(!1),$(null),h(!1),Se.invalidateQueries({queryKey:["/api/lists"]}),console.log("Guest data cleared successfully"),C.originalQuery&&(l(C.originalQuery),console.log("Restored guest query to input:",C.originalQuery)),$e("registration_complete")}catch(f){console.error("Failed to handle registration success:",f)}}};return L.current||Te.setRegistrationSuccessCallback(i),L.current=!0,()=>{Te.setRegistrationSuccessCallback(()=>{}),_.current=!1}},[]),s.useEffect(()=>{const t=f=>{St(f.detail)},i=()=>{It()},m=()=>{O.openCompose()};return window.addEventListener("loadSavedSearch",t),window.addEventListener("startNewSearch",i),window.addEventListener("openEmailCompose",m),()=>{window.removeEventListener("loadSavedSearch",t),window.removeEventListener("startNewSearch",i),window.removeEventListener("openEmailCompose",m)}},[O.openCompose]),s.useEffect(()=>(ee.current&&clearTimeout(ee.current),ee.current=setTimeout(()=>{if(!(!_.current||!L.current)&&(c||n&&n.length>0)){const i={currentQuery:x||c,currentResults:n,currentListId:g,lastExecutedQuery:x};je.save(i)}},1e3),()=>{ee.current&&clearTimeout(ee.current)}),[c,n,g,x]);const we=Ue({mutationFn:async({query:t,companies:i})=>{if(console.log("ð´ LIST CREATION - Starting auto-create mutation:",{query:t,companiesCount:i==null?void 0:i.length,timestamp:new Date().toISOString()}),!t||!i)return;const m=localStorage.getItem("contactSearchConfig");let f=null;if(m)try{f=JSON.parse(m)}catch(B){console.error("Error parsing contact search config:",B)}const E=await(await he("POST","/api/lists",{companies:i,prompt:t,contactSearchConfig:f})).json();return console.log("ð´ [AUTO-CREATE LIST] Backend response from POST /api/lists:",E),console.log("ð´ [AUTO-CREATE LIST] Response fields:",Object.keys(E)),E},onSuccess:t=>{console.log("Backend returned data from list creation:",t),Se.invalidateQueries({queryKey:["/api/lists"]});const i=t.listId;if(b(i),j(!0),P.current=!1,console.log("List created successfully with listId:",i),gt({currentResults:n||[]},{currentQuery:c,currentListId:i,lastExecutedQuery:x}),console.log("Persisted new listId to localStorage:",i),Z.current&&i){const m=Z.current;he("PATCH",`/api/lists/${i}/metrics`,m).then(()=>
57{console.log(`Persisted pending search metrics to newly created list ${i}`),Z.current=null}).catch(f=>{console.error("Failed to persist pending search metrics:",f)})}},onError:t=>{console.error("Auto list creation failed:",t),P.current=!1}}),Ze=Ue({mutationFn:async({query:t,companies:i,listId:m})=>{if(console.log("ð¡ LIST UPDATE - Starting update mutation:",{listId:m,query:t,companiesCount:i==null?void 0:i.length,timestamp:new Date().toISOString()}),!t||!i||!m)throw console.error("Update list validation failed:",{hasQuery:!!t,hasResults:!!i,hasListId:!!m,listId:m}),new Error("Missing required data for list update");console.log("Starting list update:",{listId:m,query:t,companyCount:i.length,companyIds:i.map(B=>B.id)});const f=localStorage.getItem("contactSearchConfig");let C=null;if(f)try{C=JSON.parse(f)}catch(B){console.error("Error parsing contact search config:",B)}return(await he("PUT",`/api/lists/${m}`,{companies:i,prompt:t,contactSearchConfig:C})).json()},onSuccess:t=>{console.log("List update successful:",t),Se.invalidateQueries({queryKey:["/api/lists"]}),P.current=!1},onError:t=>{console.error("List update failed:",t),P.current=!1}}),ct=s.useRef(!1),ve=ca({currentResults:n,currentQuery:c,currentListId:g,lastExecutedQuery:x,currentSessionId:G,setCurrentResults:S,refreshContactDataIfNeeded:me,refreshAndUpdateResults:k,updateListMutation:Ze,isAutomatedSearchRef:ct});Ue({mutationFn:async()=>{if(!c||!n)return null;const t=localStorage.getItem("contactSearchConfig");let i=null;if(t)try{i=JSON.parse(t)}catch(f){console.error("Error parsing contact search config:",f)}return(await he("POST","/api/lists",{companies:n,prompt:c,contactSearchConfig:i})).json()},onSuccess:t=>{Se.invalidateQueries({queryKey:["/api/lists"]}),V({title:"List Saved",description:"Your search results have been saved. Click on any contact to compose an email."}),j(!0),t&&t.listId&&b(t.listId)},onError:t=>{V({title:"Save Failed",description:t.message,variant:"destructive"})}});const ts=()=>{r(!1)},kt=t=>[...t].sort((i,m)=>{var E,B;const f=((E=i.contacts)==null?void 0:E.length)||0;return(((B=m.contacts)==null?void 0:B.length)||0)-f}),ss=(t,i)=>{console.log("Companies received:",i.length),U.current=!0,l(t);const m=i.map(C=>({...C,contacts:[]})),f=kt(m);S(f),j(!1),N(!0),Q(!1)},Nt=(t,i)=>{console.log("=== PARENT COMPONENT: handleSearchResults called ==="),console.log("Received query:",t),console.log("Received results count:",i.length),console.log("Current component state - query:",c),console.log("Current component state - results count:",(n==null?void 0:n.length)||0),console.log("Complete results received with contacts:",i.length);const m=c!==t;i.length>0&&(Ie(t),ge(i)),m&&(console.log("New search detected - clearing stale session data and list ID"),je.clear(),b(null),j(!1)),U.current=!0;const f=kt(i);console.log("Companies reordered by contact count:",f.map(E=>{var B;return{name:E.name,contacts:((B=E.contacts)==null?void 0:B.length)||0}})),l(t),S(f),j(!1),N(!1),console.log("=== PARENT COMPONENT: State updated ==="),console.log("New state - query:",t),console.log("New state - results count:",f.length),console.log("handleSearchResults completed"),Q(!0),$(t),h(!1);const C=i.filter(E=>E.contacts&&E.contacts.length>0).length;if(console.log("Companies with contacts:",C,"of",i.length),q.current&&clearTimeout(q.current),f.length>0){const E=t,B=f,Ce=m?null:g;q.current=setTimeout(()=>{if(console.log("ðµ LIST DECISION - Timer fired after 1.5s:",{listIdAtTimeOfResults:Ce,queryAtTimeOfResults:E,resultsCount:B.length,mutationInProgress:P.current,timestamp:new Date().toISOString()}),P.current){console.log("ðµ LIST DECISION - List mutation already in progress, skipping duplicate call");return}Ce?(console.log("ðµ LIST DECISION - Updating existing list:",Ce),P.current=!0,Ze.mutate({query:E,companies:B,listId:Ce})):(console.log("ðµ LIST DECISION - Creating new list for search results (new search or no existing list)"),P.current=!0,we.mutate({query:E,companies:B}))},1500)}},as=s.useMemo(()=>{if(!n)return[];const t=[];return n.forEach(i=>{i.contacts&&t.push(...i.contacts)}),ra(t,{maxPerCompany:3,minProbability:50})},[n]),rs=t=>{const i=t.slug||t.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").substring(0,50);Oe(`/p/${i}/${t.id}`)},os=t=>{const i=t.slug||t.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").substring(0,50);Oe(`/company/${i}/${t.id}`)},Tt=Ue({mutationFn:async({contactId:t,feedbackType:i,ispContext:m})=>(await he("POST",`/api/contacts/${t}/feedback`,{feedbackType:i,ispContext:m})).json(),onSuccess:t=>{S(i=>i?i.map(m=>{var f;return{...m,contacts:(f=m.contacts)==null?void 0:f.map(C=>C.id===t.contactId?{...C,feedbackType:t.feedbackType,ispContext:t.ispContext,feedbackAt:t.feedbackAt}:C)}}
57):null),V({title:"Feedback Recorded",description:"Thank you for helping us find your ideal customer!"}),qe(i=>({...i,isOpen:!1}))},onError:t=>{V({title:"Feedback Failed",description:t instanceof Error?t.message:"Failed to record feedback",variant:"destructive"})}}),ns=(t,i)=>{var f;const m=(f=n==null?void 0:n.flatMap(C=>C.contacts||[]))==null?void 0:f.find(C=>C.id===t);if(!m){V({title:"Error",description:"Contact not found",variant:"destructive"});return}if(m.feedbackType){V({title:"Feedback Already Given",description:"You have already provided feedback for this contact."});return}qe({isOpen:!0,contactId:t,contactName:m.name,feedbackType:i})},cs=(t,i)=>{K.contactId&&Tt.mutate({contactId:K.contactId,feedbackType:t,ispContext:i})},is=()=>{qe(t=>({...t,isOpen:!1}))},St=async t=>{if(console.log("Loading saved search:",{searchName:t.prompt,listId:t.listId,resultCount:t.resultCount,searchType:t.searchType}),t.searchType==="super"&&t.superSearchData){const i=t.superSearchData;se.loadFromSaved(i.plan,i.results),l(t.prompt),$(t.prompt),pe(!0),X(!0),S(null),console.log("Super Search loaded:",{query:t.prompt,resultCount:i.results.length});return}try{await Se.refetchQueries({queryKey:[`/api/lists/${t.listId}/companies`],type:"all",exact:!0});const i=await Se.fetchQuery({queryKey:[`/api/lists/${t.listId}/companies`]});console.log("Fetched companies from database:",{listId:t.listId,count:i.length,expectedCount:t.resultCount});const m=await Promise.all(i.map(async C=>{try{await Se.refetchQueries({queryKey:[`/api/companies/${C.id}/contacts`],type:"all",exact:!0});const B=(await Se.fetchQuery({queryKey:[`/api/companies/${C.id}/contacts`]})).map(Ce=>({...Ce,companyName:C.name,companyId:C.id}));return{...C,contacts:B}}catch(E){return console.error(`Failed to load contacts for company ${C.id}:`,E),{...C,contacts:[]}}}));l(t.prompt),$(t.prompt),S(m),b(t.listId),j(!0),console.log("Saved search loaded successfully:",{query:t.prompt,listId:t.listId,companiesLoaded:m.length,totalContacts:m.reduce((C,E)=>{var B;return C+(((B=E.contacts)==null?void 0:B.length)||0)},0)}),setTimeout(()=>{h(!1)},0);const f=m.reduce((C,E)=>{var B;return C+(((B=E.contacts)==null?void 0:B.length)||0)},0);(t.totalContacts!==null||t.totalEmails!==null||t.searchDurationSeconds!==null)&&(Ot({query:t.prompt,totalCompanies:m.length,totalContacts:t.totalContacts??0,totalEmails:t.totalEmails??0,searchDuration:t.searchDurationSeconds?t.searchDurationSeconds*1e3:0,companies:m,sourceBreakdown:t.sourceBreakdown??{Perplexity:0,Apollo:0,Hunter:0}}),console.log("Loaded persisted search metrics:",{totalContacts:t.totalContacts,totalEmails:t.totalEmails,searchDurationSeconds:t.searchDurationSeconds,sourceBreakdown:t.sourceBreakdown}))}catch{V({title:"Failed to load search",description:"Could not load the selected search.",variant:"destructive"})}},It=()=>{O.closeDrawer(),l(""),S(null),b(null),$(null),j(!1),h(!1),p(new Set),Q(!1),R(!1),je.clear(),localStorage.removeItem("emailComposerState")};s.useEffect(()=>{o&&setTimeout(()=>It(),0)},[o]),s.useEffect(()=>{if(!re.current&&Re&&de!=null&&de.listId){const t=parseInt(de.listId,10);if(isNaN(t))return;if(g===t){console.log("Search already loaded, skipping fetch:",{listId:t}),re.current=!0;return}if(!Be.authReady){console.log("Waiting for auth to be ready before loading search:",{listId:t});return}re.current=!0,console.log("Loading search from URL (one-time):",{listId:t,slug:de.slug}),(async()=>{try{const m=await Se.fetchQuery({queryKey:["/api/lists",t]});m?St(m):(console.warn("Search not found for listId:",t),V({title:"Search not found",description:"The search you're looking for could not be found.",variant:"destructive"}))}catch(m){console.error("Failed to load search by listId:",m),V({title:"Search not found",description:"The search you're looking for could not be found.",variant:"destructive"})}})()}},[Re,de==null?void 0:de.listId,g,Be.authReady,Be.user]);const[Rt,it]=s.useState(!1),[De,Ot]=s.useState({query:"",totalCompanies:0,totalContacts:0,totalEmails:0,searchDuration:0,companies:[],sourceBreakdown:void 0}),$t=async t=>{const i=n==null?void 0:n.flatMap(f=>f.contacts||[]).find(f=>f.id===t);if(!i)return;const m=n==null?void 0:n.find(f=>{var C;return(C=f.contacts)==null?void 0:C.some(E=>E.id===t)});await Qe(t,i,{companyName:m==null?void 0:m.name,companyWebsite:(m==null?void 0:m.website)||void 0,companyDescription:(m==null?void 0:m.description)||void 0})},[ls,Dt]=s.useState(new Set),ds=async t=>{Dt(i=>new Set(i).add(t));try{const i=await fetch(`/api/contacts/${t}/find-mobile-phone`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include"}),m=await i.json();if(!i.ok){V({title:"Phone lookup failed",description:m.error||"Could not initiate phone lookup",variant:"destructive"});return}V({title:"Phone lookup started",description:m.message||"Results will arrive in 5-15 minutes"}),g&&Se.invalidateQueries({queryKey:[`/api/lists/${g}/companies`]}),Se.invalidateQueries({queryKey:["/api/lists"]})}
57catch(i){console.error("Error finding mobile phone:",i),V({title:"Error",description:"Failed to initiate phone lookup",variant:"destructive"})}finally{Dt(i=>{const m=new Set(i);return m.delete(t),m})}},us=t=>{p(i=>{const m=new Set(i);return m.has(t)?m.delete(t):m.add(t),m})},Mt=t=>{var f;const i=((f=t.contacts)==null?void 0:f.filter(C=>C.email))||[];if(i.length===0)return"unchecked";const m=i.filter(C=>D.has(C.id)).length;return m===0?"unchecked":m===i.length?"checked":"indeterminate"},ms=t=>{var f;const i=((f=t.contacts)==null?void 0:f.filter(C=>C.email))||[];if(i.length===0)return;const m=Mt(t);p(C=>{const E=new Set(C);return m==="checked"||m==="indeterminate"?i.forEach(B=>{E.delete(B.id)}):i.forEach(B=>{E.add(B.id)}),E})},et=s.useMemo(()=>{if(!Re||!c||!g)return null;const t=(de==null?void 0:de.slug)||Cs(c),i=(n==null?void 0:n.length)??0,m=`https://5ducks.ai/search/${t}/${g}`;return{title:`${c} | 5Ducks`,description:`${i} companies found for "${c}". Discover verified contacts and leads for your B2B outreach.`,canonicalUrl:m,jsonLd:{"@context":"https://schema.org","@type":"CollectionPage",name:c,description:`${i} companies matching: ${c}`,url:m,numberOfItems:i,provider:{"@type":"Organization",name:"5Ducks",url:"https://5ducks.ai"}}}},[Re,c,g,n==null?void 0:n.length,de==null?void 0:de.slug]);return e.jsxs(e.Fragment,{children:[et&&e.jsx(vs,{title:et.title,description:et.description,canonicalUrl:et.canonicalUrl,jsonLd:et.jsonLd}),Rt&&e.jsx(s.Suspense,{fallback:null,children:e.jsx(pa,{metrics:{query:De.query,totalCompanies:De.totalCompanies,totalContacts:De.totalContacts,totalEmails:De.totalEmails,searchDuration:De.searchDuration,companies:De.companies,sourceBreakdown:De.sourceBreakdown},isVisible:Rt,onClose:()=>it(!1),cachedInfo:ie,onRefresh:()=>{const t=ie.query||x||c;t!=null&&t.trim()&&(sessionStorage.setItem("forceBypassCache","true"),l(t),R(!1),V({title:"Refreshing search",description:"Getting fresh results..."}),requestAnimationFrame(()=>{setTimeout(()=>{window.dispatchEvent(new CustomEvent("triggerFreshSearch",{detail:{query:t}}))},50)}))}})}),e.jsxs("div",{className:"flex h-[calc(100vh-3.5rem)] overflow-hidden relative",children:[Y.isOpen&&e.jsx(s.Suspense,{fallback:null,children:e.jsx(ya,{open:Y.isOpen,messages:Y.messages,isLoading:Y.isLoading,searchContext:Y.searchContext,onClose:Y.closePanel,onSendMessage:Y.sendMessage,onStopGeneration:Y.stopGeneration,onActionExecute:be})}),O.isOpen&&e.jsx("div",{className:"fixed inset-0 bg-black/50 z-40 md:hidden",onClick:()=>{O.closeDrawer()}}),!Y.isOpen&&n&&n.length>0&&e.jsx("button",{onClick:Y.openPanel,className:"fixed left-4 top-1/2 -translate-y-1/2 z-30 p-3 rounded-full bg-amber-500 hover:bg-amber-600 text-white shadow-lg hover:shadow-xl transition-all duration-200 hover:scale-105",title:"Open search assistant","data-testid":"button-open-assistant",children:e.jsx(dt,{className:"h-5 w-5"})}),e.jsxs("div",{className:`flex-1 overflow-y-auto main-content-compressed ${O.isOpen&&n&&n.length>0?"compressed-view":""} ${Y.isOpen?"ml-80":""}`,children:[e.jsx("div",{className:"container mx-auto py-6 px-0 md:px-6 max-w-4xl",children:e.jsx("div",{className:"grid grid-cols-12 gap-3 md:gap-6",children:e.jsxs("div",{className:"col-span-12 space-y-2 md:space-y-4 mt-[-10px]",children:[Ee.isVisible&&e.jsx("div",{className:"px-3 md:px-6",children:e.jsx(Bt,{phase:Ee.phase,completed:Ee.completed,total:Ee.total,isVisible:Ee.isVisible})}),e.jsxs("div",{className:"relative transition-all duration-300 ease-in-out",children:[H&&e.jsxs("div",{className:"w-full px-3 md:px-6 py-2 bg-background border rounded-lg flex items-center justify-between mb-2",children:[e.jsxs("button",{onClick:()=>R(!1),className:"flex-1 flex items-center gap-2 hover:bg-gray-50 dark:hover:bg-gray-900 transition-colors rounded-l-lg group","data-testid":"button-expand-search",children:[e.jsx(Xt,{className:"h-4 w-4 text-muted-foreground"}),c&&e.jsx("span",{className:"text-sm text-muted-foreground truncate max-w-[200px] md:max-w-[400px]",children:c})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ie.isCached&&e.jsx(Pe,{children:e.jsxs(Fe,{children:[e.jsx(Le,{asChild:!0,children:e.jsxs("button",{onClick:t=>{t.stopPropagation();const i=ie.query||x||c;if(!(i!=null&&i.trim())){V({title:"Unable to refresh",description:"No search query available",variant:"destructive"});return}sessionStorage.setItem("forceBypassCache","true"),l(i),R(!1),V({title:"Refreshing search",description:"Getting fresh results..."}),requestAnimationFrame(()=>{setTimeout(()=>{window.dispatchEvent(new CustomEvent("triggerFreshSearch",{detail:{query:i}}))},50)})},className:"flex items-center gap-1.5 px-2 py-1 rounded text-xs text-muted-foreground hover:text-foreground hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors","data-testid":"button-refresh-search",children:[e.jsxs("span",{className:"hidden md:inline text-[10px] opacity-70",children:["Search results from ",ie.cachedDate&&new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}).format(ie.cachedDate)]}),e.jsx(Ms,{className:"h-3.5 w-3.5"})]})}),e.jsx(Ae,{side:"bottom",children:e.jsxs("p",{children:["Results from ",ie.cachedDate?new Intl.DateTimeFormat("en-US",{month:"long",day:"numeric",year:"numeric"}).format(ie.cachedDate):"cache",". Click to search fresh."]})})]})}),e.jsx("button",{onClick:()=>R(!1),className:"p-1 hover:bg-gray-100 dark:hover:bg-gray-800 rounded transition-colors group",children:e.jsx(zt,{className:"h-4 w-4 text-muted-foreground group-hover:text-foreground transition-colors"})})]})]}),e.jsx("div",{className:`transition-all duration-300 ease-in-out overflow-hidden ${H?"max-h-0 opacity-0 pointer-events-none":"max-h-[500px] opacity-100"}`,children:e.jsxs("div",{className:"px-3 md:px-6 py-1",children:[" ",!H&&n&&n.length>0&&e.jsx("button",{onClick:()=>R(!0),className:"absolute right-3 md:right-6 top-2 z-10 p-1.5 rounded-md hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors group","data-testid":"button-collapse-search",title:"Minimize search",children:e.jsx(ws,{className:"h-4 w-4 text-muted-foreground group-hover:text-foreground"})}),!n&&!a&&e.jsx("div",{className:"flex flex-col-reverse md:flex-row items-center gap-4 mb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(aa,{}),e.jsxs("h2",{className:"text-2xl sm:text-3xl md:text-4xl mt-2 md:mt-0 font-serif text-accent dark:text-accent",children:["Find your ideal ",e.jsx("em",{children:"business"})," customers"]})]})}),e.jsx(Bs,{onAnalyze:()=>{r(!0),te({isCached:!1,cachedDate:null,query:null}),c&&c!==x&&(console.log("Starting new search - clearing list ID and results for query:",c),b(null),j(!1),S(null),p(new Set))},onComplete:ts,onSearchResults:Nt,onCompaniesReceived:ss,isAnalyzing:a,value:c||"",onChange:t=>{l(t),h(t!==x)},isFromLandingPage:A,onDismissLandingHint:()=>I(!1),lastExecutedQuery:x,onSearchSuccess:()=>{(localStorage.getItem("searchType")||"contacts")==="emails"&&setTimeout(()=>ve.runEmailSearch(),500)},hasSearchResults:n?n.length>0:!1,onSessionIdChange:xe,hideRoleButtons:!!(H&&n&&n.length>0&&!oe),onSearchMetricsUpdate:async(t,i)=>{var C;Ot({...t,sourceBreakdown:t.sourceBreakdown}),it(i);const m=((C=t.companies)==null?void 0:C.map(E=>{var B;return{id:E.id,name:E.name,contacts:(B=E.contacts)==null?void 0:B.map(Ce=>({id:Ce.id,name:Ce.name,role:Ce.role,email:Ce.email,probability:Ce.probability}))}}))??null,f={totalContacts:t.totalContacts??null,totalEmails:t.totalEmails??null,searchDurationSeconds:t.searchDuration??null,sourceBreakdown:t.sourceBreakdown??null,reportCompanies:m};if(g&&t)try{await he("PATCH",`/api/lists/${g}/metrics`,f),console.log(`Persisted search metrics to list ${g}`)}catch(E){console.error("Failed to persist search metrics:",E)}else t&&(Z.current=f,console.log("Stored pending metrics for later persistence"))},onOpenSearchDrawer:()=>le.openDrawer(),onProgressUpdate:Ge,superSearch:{startSearch:se.startSearch,reset:se.reset,status:se.status},onSuperSearchActive:t=>{pe(t),t&&X(!1)},onCacheHit:async t=>{console.log(`ð¯ Cache hit detected, loading list ${t.listId}`),r(!1),te({isCached:!0,cachedDate:t.createdAt?new Date(t.createdAt):null,query:t.prompt||c});try{const i=await Se.fetchQuery({queryKey:[`/api/lists/${t.listId}`]});i&&(await St(i),it(!0))}catch(i){console.error("Failed to load cached list:",i)}}}),!n&&!a&&e.jsxs("div",{className:"mt-4 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Or select one of the suggestions below:"}),e.jsx("div",{className:"flex flex-wrap justify-center gap-2",children:["Recently exited startups in Miami","Real-estate lawyers in Salt Lake City","Stationary suppliers in Scranton","Health-tech SaaS in Brooklyn"].map(t=>e.jsx("button",{onClick:()=>{l(t),h(!0)},className:"px-3 py-1.5 text-sm bg-transparent border border-secondary-foreground
57/60 hover:border-secondary-foreground text-secondary-foreground/60 hover:text-secondary-foreground rounded-lg transition-colors","data-testid":`button-suggestion-${t.toLowerCase().replace(/\s+/g,"-").slice(0,30)}`,children:t},t))})]}),!n&&a&&!ne&&e.jsx("div",{className:"mt-8 text-center",children:e.jsx("p",{className:"text-lg text-muted-foreground",children:"â³ Your amazing list of companies will show up here."})})]})})]}),n&&n.length>0?e.jsxs(At,{className:`w-full rounded-none md:rounded-lg border-0 transition-all duration-300 bg-background ${O.isOpen?"shadow-none":""}`,"data-testid":"search-results-card",children:[ve.isSearching&&e.jsx("div",{className:"px-0 md:px-4 pt-0 pb-3",children:e.jsx(Bt,{phase:ve.searchProgress.phase,completed:ve.searchProgress.completed,total:ve.searchProgress.total,isVisible:ve.isSearching})}),e.jsx(_t,{className:"p-0",children:e.jsx("div",{className:"px-0 md:px-4 pb-4",children:e.jsx(s.Suspense,{fallback:e.jsx(Qt,{}),children:e.jsx(da,{companies:n||[],handleCompanyView:os,handleComprehe
57nsiveEmailSearch:$t,handleFindMobilePhone:ds,pendingContactIds:T,pendingComprehensiveSearchIds:nt,pendingPhoneRevealIds:ls,onContactClick:ft,onViewModeChange:w,selectedEmailContact:O.selectedContact,selectedContacts:D,onContactSelectionChange:us,getCompanySelectionState:Mt,onCompanySelectionChange:ms,topActionsTrailing:D.size>0?e.jsx(s.Suspense,{fallback:null,children:e.jsx(xa,{selectedCount:D.size,onClear:()=>p(new Set),selectedContactIds:Array.from(D)})}):void 0,onShowReport:()=>it(!0),onFindKeyEmails:ve.runEmailSearch,isFindingEmails:ve.isSearching,query:c,onExtendSearch:Nt,isAuthenticated:!!Be.user,onLoginRequired:()=>Te.openModal()})})})})]}):null,n&&n.length>0&&v!=="slides"&&e.jsx(s.Suspense,{fallback:null,children:e.jsx(Sa,{prospects:as,pendingComprehensiveSearchIds:nt,isVisible:!0,onContactView:rs,onContactFeedback:ns,handleComprehensiveEmailSearch:$t})})]})})}),ne&&e.jsx("div",{className:"container mx-auto py-4 px-0 md:px-6 max-w-7xl",children:e.jsx(At,{className:"w-full rounded-none md:rounded-lg border-0 bg-background",children:e.jsxs(_t,{className:"p-4 md:p-6",children:[e.jsx(s.Suspense,{fallback:e.jsx(Qt,{}),children:e.jsx(ua,{state:se,query:c||void 0,alreadySaved:fe,onSaved:t=>{console.log(`Super Search saved with list ID: ${t}`),X(!0)},onExpandResults:t=>{c&&se.expandResults(c,t)}})}),se.status==="complete"&&e.jsx("div",{className:"mt-4 flex justify-end",children:e.jsx(at,{variant:"outline",onClick:()=>{pe(!1),se.reset(),r(!1)},children:"Close Results"})})]})})})]}),O.isOpen&&e.jsx(s.Suspense,{fallback:null,children:e.jsx(ma,{open:O.isOpen,mode:O.mode,viewState:O.viewState,selectedContact:O.selectedContact,selectedCompany:O.selectedCompany,selectedCompanyContacts:O.selectedCompanyContacts,width:O.drawerWidth,isResizing:O.isResizing,currentListId:g,currentQuery:c,emailSubject:O.viewState==="minimized"?Ws():void 0,onClose:O.closeDrawer,onModeChange:O.setMode,onContactChange:ot,onResizeStart:O.handleMouseDown,onMinimize:O.minimize,onExpand:O.expand,onRestore:O.restore})}),le.isOpen&&e.jsx(s.Suspense,{fallback:null,children:e.jsx(ha,{open:le.isOpen,width:le.drawerWidth,isResizing:le.isResizing,onClose:le.closeDrawer,onResizeStart:le.handleMouseDown,onTrainAI:()=>ye(!0),hasSearchResults:Ne&&Ne.length>0})}),e.jsx(Zs,{notificationState:pt,onClose:rt}),ce&&e.jsx(s.Suspense,{fallback:null,children:e.jsx(fa,{searchQuery:ae,searchResults:Ne,onComplete:()=>{ye(!1),localStorage.setItem("hasCompletedOnboarding","true"),V({title:"Setup complete!",description:"Your campaign is now active and ready to start generating leads."})},onClose:()=>{ye(!1)}})}),K.isOpen&&e.jsx(s.Suspense,{fallback:null,children:e.jsx(ga,{isOpen:K.isOpen,onClose:is,onSubmit:cs,feedbackType:K.feedbackType,contactName:K.contactName,isPending:Tt.isPending})})]})]})}const Qa=Object.freeze(Object.defineProperty({__proto__:null,default:ba},Symbol.toStringTag,{value:"Module"}));export{Ba as a,zs as b,Hs as c,ia as d,Qa as h,Ps as u};
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.