1import{j as e,u as b,r as j}from"./index-DKJ0tKwF.js";import{t as K,M as os,k as js,i as ys,U as vs,g as ws,V as bs,G as Ns,J as S,a4 as Cs,m as Be,D as k,f as Q,l as Me,r as ve,d as ze,b as Ye,T as ks,o as Ue,a6 as _s,S as Je}from"./button-DFML8rOM.js";import{T as Ss,aQ as As,aR as Es,aS as Ms,C as Ps,m as Is,e as Ts,O as xe,c as Ls,am as F,al as z,p as Ze}from"./V2Layout-DEbe2yZA.js";import{r as R,cQ as Fs,H as Rs,aE as te,f as W,$ as q,bo as Ds,e8 as Xe,F as qs,aR as Ke,q as D,aI as me,aJ as ue,aK as ge,J as G,b$ as Gs,c0 as Os,c1 as $s,c2 as zs,c3 as Us,c4 as Vs,c5 as Bs,c6 as Ks,ap as we,cZ as Hs,aq as be,ar as Pe,as as Ie,at as Te,bM as He,bN as Qe,bO as de,bP as Ne,g as ee,s as ne,v as ie,w as oe,x as ce,y as se,C as Qs,d as cs,ba as rs,e9 as ls,cw as Ce,dR as Ws,bz as ds,dz as Ys,c7 as Js,ea as Zs,cU as Xs,co as et,aQ as es,aw as st,a7 as tt,a8 as at,z as nt,eb as qe,D as ms,cC as it,bj as ss,bn as Ge,a2 as ot,bg as ct}from"./App-CL-mfmhu.js";import{g as us,l as ke,T as gs,v as rt,E as Le,n as hs,e as lt}from"./v3LegalOverrides-BUgTGJPl.js";import{Z as re,L as M}from"./tracker-DzJH7QDt.js";import{u as dt}from"./useIntegrationConnections-BpAmOXkz.js";import{A as Y,a as J}from"./alert-6VEnsWT3.js";import{u as xs}from"./useMetaIntegration-Zzv9jBXP.js";import{u as mt}from"./useApolloConnection-BnPF4UmA.js";import{C as ps}from"./mouse-pointer-2-CzsmklB8.js";import ut from"./IntegrationsCallback-CAN9rbou.js";import{u as gt}from"./useZoomIntegration-Cep2H_ok.js";import"./index-BNGwt955.js";import"./SEOHead-B5IBZJEm.js";import"./types-DU7944Yl.js";function ht({className:s,size:a="sm",showIcon:t=!0,variant:i="default",tooltip:f="This feature is coming soon. Stay tuned for updates!"}){const x={sm:"text-[10px] px-1.5 py-0.5",md:"text-xs px-2 py-0.5",lg:"text-sm px-2.5 py-1"},u={default:"bg-amber-500/10 text-amber-600 border-amber-500/20 dark:text-amber-400",subtle:"bg-muted text-muted-foreground border-transparent",outline:"bg-transparent text-muted-foreground border-muted-foreground/30"},g={sm:"h-2.5 w-2.5",md:"h-3 w-3",lg:"h-3.5 w-3.5"},y=e.jsxs(R,{variant:"outline",className:K("font-medium gap-1 shrink-0",x[a],u[i],s),children:[t&&e.jsx(us,{className:g[a]}),"Coming Soon"]});return f?e.jsx(Ss,{children:e.jsxs(As,{children:[e.jsx(Es,{asChild:!0,children:y}),e.jsx(Ms,{side:"top",className:"max-w-[200px] text-center",children:e.jsx("p",{className:"text-xs",children:f})})]})}):y}const ye=[{id:"email",name:"Email & Marketing",description:"Connect your email providers and marketing tools",icon:os,integrations:[{id:"gmail",name:"Gmail",description:"Send emails directly from your CRM",icon:"https://www.google.com/gmail/about/static-2.0/images/logo-gmail.png",category:"email",popular:!0},{id:"outlook",name:"Outlook",description:"Microsoft email integration",icon:"https://upload.wikimedia.org/wikipedia/commons/d/df/Microsoft_Office_Outlook_%282018%E2%80%93present%29.svg",category:"email",popular:!0,comingSoon:!0},{id:"mailchimp",name:"Mailchimp",description:"Email marketing automation",icon:"https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/MailChimp.svg/1200px-MailChimp.svg.png",category:"email",comingSoon:!0},{id:"sendgrid",name:"SendGrid",description:"Transactional email delivery",icon:"https://sendgrid.com/wp-content/uploads/2021/06/SG_Twilio_Lockup_RGB.png",category:"email",comingSoon:!0},{id:"klaviyo",name:"Klaviyo",description:"E-commerce email marketing",icon:"https://www.klaviyo.com/wp-content/uploads/2023/03/klaviyo-mark.svg",category:"email",comingSoon:!0},{id:"activecampaign",name:"ActiveCampaign",description:"Marketing automation platform",icon:"https://www.activecampaign.com/wp-content/uploads/2022/11/AC-Icon-Blue-300x300.png",category:"email",comingSoon:!0},{id:"convertkit",name:"ConvertKit",description:"Creator email marketing",icon:"https://convertkit.com/favicon.ico",category:"email",comingSoon:!0}]},{id:"calendar",name:"Calendar & Scheduling",description:"Sync calendars and scheduling tools",icon:Ps,integrations:[{id:"google-calendar",name:"Google Calendar",description:"Sync meetings and events",icon:"https://upload.wikimedia.org/wikipedia/commons/a/a5/Google_Calendar_icon_%282020%29.svg",category:"calendar",popular:!0},{id:"outlook-calendar",name:"Outlook Calendar",description:"Microsoft calendar sync",icon:"https://upload.wikimedia.org/wikipedia/commons/d/df/Microsoft_Office_Outlook_%282018%E2%80%93present%29.svg",category:"calendar",popular:!0,comingSoon:!0},{id:"calendly",name:"Calendly",description:"Auto-create contacts, deals & calendar events from Calendly bookings",icon:"https://assets.calendly.com/assets/logo-square-cd364a3c3a6d926d5e41ba6a5f4be018c08d6477ac5e6556dd9c35f1dfc6ae65.svg",category:"calendar",popular:!0},{id:"cal-com",name:"Cal.com",description:"Open source scheduling",icon:"https://cal.com/android-chrome-512x512.png",category:"calendar",comingSoon:!0},{id:"acuity",name:"Acuity Scheduling",description:"Client scheduling",icon:"https://acuityscheduling.com/favicon.ico",category:"calendar",comingSoon:!0}]},{id:"communication",name:"Communication",description:"Team chat and video conferencing",icon:js,integrations:[{id:"slack",
1name:"Slack",description:"Team messaging and notifications",icon:"https://upload.wikimedia.org/wikipedia/commons/d/d5/Slack_icon_2019.svg",category:"communication",popular:!0,comingSoon:!0},{id:"teams",name:"Microsoft Teams",description:"Microsoft collaboration",icon:"https://upload.wikimedia.org/wikipedia/commons/c/c9/Microsoft_Office_Teams_%282018%E2%80%93present%29.svg",category:"communication",popular:!0,comingSoon:!0},{id:"zoom",name:"Zoom",description:"Video conferencing",icon:"https://st1.zoom.us/zoom.ico",category:"communication",popular:!0},{id:"discord",name:"Discord",description:"Community messaging",icon:"https://assets-global.website-files.com/6257adef93867e50d84d30e2/636e0a69f118df70ad7828d4_icon_clyde_blurple_RGB.svg",category:"communication",comingSoon:!0},{id:"intercom",name:"Intercom",description:"Customer messaging",icon:"https://www.intercom.com/favicon.ico",category:"communication",comingSoon:!0}]},{id:"social",name:"Social Media",description:"Connect social media accounts",icon:Is,integrations:[{id:"facebook",name:"Facebook",description:"Meta Business Suite",icon:"https://upload.wikimedia.org/wikipedia/commons/5/51/Facebook_f_logo_%282019%29.svg",category:"social",popular:!0},{id:"instagram",name:"Instagram",description:"Instagram Business",icon:"https://upload.wikimedia.org/wikipedia/commons/e/e7/Instagram_logo_2016.svg",category:"social",popular:!0},{id:"linkedin",name:"LinkedIn",description:"Professional networking",icon:"https://upload.wikimedia.org/wikipedia/commons/c/ca/LinkedIn_logo_initials.png",category:"social",popular:!0,comingSoon:!0},{id:"twitter",name:"X (Twitter)",description:"Social media platform",icon:"https://abs.twimg.com/responsive-web/client-web/icon-ios.77d25eba.png",category:"social",comingSoon:!0}
1,{id:"tiktok",name:"TikTok",description:"Short-form video platform",icon:"https://www.tiktok.com/favicon.ico",category:"social",comingSoon:!0},{id:"youtube",name:"YouTube",description:"Video platform",icon:"https://www.youtube.com/s/desktop/12d6b690/img/favicon_144x144.png",category:"social",comingSoon:!0},{id:"pinterest",name:"Pinterest",description:"Visual discovery",icon:"https://www.pinterest.com/favicon.ico",category:"social",comingSoon:!0}]},{id:"ads",name:"Advertising",description:"Ad platforms and tracking",icon:ys,integrations:[{id:"google-ads",name:"Google Ads",description:"Search and display advertising",icon:"https://upload.wikimedia.org/wikipedia/commons/c/c7/Google_Ads_logo.svg",category:"ads",popular:!0},{id:"meta-ads",name:"Meta Ads",description:"Facebook & Instagram ads",icon:"https://upload.wikimedia.org/wikipedia/commons/7/7b/Meta_Platforms_Inc._logo.svg",category:"ads",popular:!0},{id:"tiktok-ads",name:"TikTok Ads",description:"TikTok advertising",icon:"https://www.tiktok.com/favicon.ico",category:"ads",popular:!0},{id:"linkedin-ads",name:"LinkedIn Ads",description:"B2B advertising",icon:"https://upload.wikimedia.org/wikipedia/commons/c/ca/LinkedIn_logo_initials.png",category:"ads",comingSoon:!0},{id:"microsoft-ads",name:"Microsoft Ads",description:"Bing advertising",icon:"https://upload.wikimedia.org/wikipedia/commons/4/44/Microsoft_logo.svg",category:"ads",comingSoon:!0}]},{id:"crm",name:"CRM & Sales",description:"Sync with other CRM platforms",icon:vs,integrations:[{id:"salesforce",name:"Salesforce",description:"Enterprise CRM",icon:"https://www.salesforce.com/favicon.ico",category:"crm",popular:!0,comingSoon:!0},{id:"hubspot",name:"HubSpot",description:"Inbound marketing CRM",icon:"https://www.hubspot.com/favicon.ico",category:"crm",popular:!0,comingSoon:!0},{id:"pipedrive",name:"Pipedrive",description:"Sales-focused CRM",icon:"https://www.pipedrive.com/favicon.ico",category:"crm",comingSoon:!0},{id:"zoho",name:"Zoho CRM",description:"Business software suite",icon:"https://www.zoho.com/favicon.ico",category:"crm",comingSoon:!0},{id:"freshsales",name:"Freshsales",description:"AI-powered CRM",icon:"https://www.freshworks.com/favicon.ico",category:"crm",comingSoon:!0},{id:"close",name:"Close",description:"Inside sales CRM",icon:"https://close.com/favicon.ico",category:"crm",comingSoon:!0},{id:"gohighlevel",name:"GoHighLevel",description:"Migrate all your data from GHL â contacts, pipelines, automations, and more",icon:"https://images.leadconnectorhq.com/image/f_webp/q_80/r_1200/u_https://cdn.filesafe.space/46QWLMIJNQYGxf7OlnMB/media/63ff845a5067f14e53e2cc8c.png",category:"crm",popular:!0}]},{id:"ecommerce",name:"E-commerce",description:"Online stores and payments",icon:Fs,integrations:[{id:"shopify",name:"Shopify",description:"E-commerce platform",icon:"https://cdn.shopify.com/shopifycloud/web/assets/v1/favicon-c9a5fcf25dc7a8f2f4c5a2f4fd1d0eab.ico",category:"ecommerce",popular:!0},{id:"woocommerce",name:"WooCommerce",description:"WordPress e-commerce",icon:"https://woocommerce.com/wp-content/uploads/2023/08/woocommerce-favicon.ico",category:"ecommerce",popular:!0,comingSoon:!0},{id:"stripe",name:"Stripe",description:"Payment processing",icon:"https://stripe.com/favicon.ico",category:"ecommerce",popular:!0,connected:!0},{id:"paypal",name:"PayPal",description:"Online payments",icon:"https://www.paypal.com/favicon.ico",category:"ecommerce",comingSoon:!0},{id:"square",name:"Square",description:"Payment and POS",icon:"https://squareup.com/favicon.ico",category:"ecommerce",comingSoon:!0},{id:"bigcommerce",name:"BigCommerce",description:"Enterprise e-commerce",icon:"https://www.bigcommerce.com/favicon.ico",category:"ecommerce",comingSoon:!0}]},{id:"automation",name:"Automation",description:"Workflow automation tools",icon:re,integrations:[{id:"zapier",name:"Zapier",description:"Connect 5,000+ apps",icon:"https://cdn.zapier.com/zapier/images/favicon.ico",category:"automation",popular:!0,comingSoon:!0},{id:"make",name:"Make",description:"Visual automation platform",icon:"https://www.make.com/favicon.ico",category:"automation",popular:!0,comingSoon:!0},{id:"n8n",name:"n8n",description:"Open-source automation",icon:"https://n8n.io/favicon.ico",category:"automation",comingSoon:!0},{id:"pabbly",name:"Pabbly Connect",description:"Affordable automation",icon:"https://www.pabbly.com/favicon.ico",category:"automation",comingSoon:!0},{id:"integrately",name:"Integrately",description:"One-click integrations",icon:"https://integrately.com/favicon.ico",category:"automation",comingSoon:!0}]},{id:"analytics",name:"Analytics",description:"Tracking and analytics tools",icon:Ts,integrations:[{id:"google-analytics",name:"Google Analytics",description:"Website analytics",icon:"https://www.google.com/analytics/static/images/favicon.ico",category:"analytics",popular:!0,comingSoon:!0},{id:"mixpanel",name:"Mixpanel",description:"Product analytics",icon:"https://mixpanel.com/favicon.ico",category:"analytics",comingSoon:!0},{id:"amplitude",name:"Amplitude",description:"Digital analytics",icon:"https://amplitude.com/favicon.ico",category:"analytics",comingSoon:!0},{id:"hotjar",name:"Hotjar",description:"User behavior analytics",icon:"https://www.hotjar.com/favicon.ico",category:"analytics",comingSoon:!0},{id:"segment",name:"Segment",description:"Customer data platform",icon:"https://segment.com/favicon.ico",category:"analytics",comingSoon:!0},{id:"plausible",name:"Plausible",description:"Privacy-first analytics",icon:"https://plausible.io/favicon.ico",category:"analytics",comingSoon:!0}]},{id:"documents",name:"Documents & Storage",description:"File storage and documents",icon:ws,integrations:[{id:"google-drive",name:"Google Drive",description:"Cloud file storage",icon:"https://ssl.gstatic.
1com/docs/doclist/images/drive_2022q3_32dp.png",category:"documents",popular:!0,comingSoon:!0},{id:"dropbox",name:"Dropbox",description:"File hosting",icon:"https://cfl.dropboxstatic.com/static/images/favicon.ico",category:"documents",comingSoon:!0},{id:"onedrive",name:"OneDrive",description:"Microsoft cloud storage",icon:"https://upload.wikimedia.org/wikipedia/commons/3/3c/Microsoft_Office_OneDrive_%282019%E2%80%93present%29.svg",category:"documents",comingSoon:!0},{id:"notion",name:"Notion",description:"All-in-one workspace",icon:"https://www.notion.so/images/favicon.ico",category:"documents",popular:!0,comingSoon:!0},{id:"docusign",name:"DocuSign",description:"Electronic signatures",icon:"https://www.docusign.com/favicon.ico",category:"documents",comingSoon:!0},{id:"pandadoc",name:"PandaDoc",description:"Document automation",icon:"https://www.pandadoc.com/favicon.ico",category:"documents",comingSoon:!0}]},{id:"support",name:"Support & Helpdesk",description:"Customer support tools",icon:Rs,integrations:[{id:"zendesk",name:"Zendesk",description:"Customer service platform",icon:"https://www.zendesk.com/favicon.ico",category:"support",popular:!0,comingSoon:!0},{id:"freshdesk",name:"Freshdesk",description:"Helpdesk software",icon:"https://www.freshworks.com/favicon.ico",category:"support",comingSoon:!0},{id:"helpscout",name:"Help Scout",description:"Customer support",icon:"https://www.helpscout.com/favicon.ico",category:"support",comingSoon:!0},{id:"crisp",name:"Crisp",description:"Customer messaging",icon:"https://crisp.chat/favicon.ico",category:"support",comingSoon:!0},{id:"drift",name:"Drift",description:"Conversational marketing",icon:"https://www.drift.com/favicon.ico",category:"support",comingSoon:!0}]},{id:"webinars",name:"Webinars & Events",description:"Virtual events and webinars",icon:bs,integrations:[{id:"webinarjam",name:"WebinarJam",description:"Live webinar platform",icon:"https://home.webinarjam.com/favicon.ico",category:"webinars",comingSoon:!0},{id:"gotowebinar",name:"GoToWebinar",description:"Webinar software",icon:"https://www.goto.com/favicon.ico",category:"webinars",comingSoon:!0},{id:"demio",name:"Demio",description:"Simple webinars",icon:"https://demio.com/favicon.ico",category:"webinars",comingSoon:!0},{id:"eventbrite",name:"Eventbrite",description:"Event management",icon:"https://www.eventbrite.com/favicon.ico",category:"webinars",popular:!0,comingSoon:!0},{id:"livestorm",name:"Livestorm",description:"Video engagement",icon:"https://livestorm.co/favicon.ico",category:"webinars",comingSoon:!0}]},{id:"website",name:"Website & Forms",description:"Website builders and forms",icon:Ns,integrations:[{id:"wordpress",name:"WordPress",description:"Website platform",icon:"https://wordpress.org/favicon.ico",category:"website",popular:!0,comingSoon:!0},{id:"webflow",name:"Webflow",description:"Visual web builder",icon:"https://webflow.com/favicon.ico",category:"website",comingSoon:!0},{id:"typeform",name:"Typeform",description:"Conversational forms",icon:"https://www.typeform.com/favicon.ico",category:"website",popular:!0,comingSoon:!0},{id:"jotform",name:"JotForm",description:"Online form builder",icon:"https://www.jotform.com/favicon.ico",category:"website",comingSoon:!0},{id:"unbounce",name:"Unbounce",description:"Landing page builder",icon:"https://unbounce.com/favicon.ico",category:"website",comingSoon:!0},{id:"leadpages",name:"Leadpages",description:"Landing pages",icon:"https://www.leadpages.com/favicon.ico",category:"website",comingSoon:!0}]}],xt=()=>ye.flatMap(s=>s.integrations),pt=()=>xt().filter(s=>s.popular);function Se(s){const{workspace:a}=te(),t=xe(),i=a==null?void 0:a.id,f=async(r,o={})=>{const{data:h,error:n}=await S.functions.invoke("ad-attachments",{body:{action:r,workspace_id:i,platform:s,...o}});if(n){if(n instanceof Cs){const l=await n.context.clone().json().catch(()=>null);throw new Error((l==null?void 0:l.error)||n.message)}throw new Error(n.message)}if(h!=null&&h.error)throw new Error(h.error);return h},x=W({queryKey:["ad-attachments",i,s],queryFn:async()=>i?(await f("list_attachments")).attachments??[]:[],enabled:!!i}),u=W({queryKey:["ad-attachments-agency",i,s],queryFn:async()=>i?(await f("list_agency_assets")).credentials??[]:[],enabled:!!i}),g=()=>{t.invalidateQueries({queryKey:["ad-attachments",i,s]})},y=q({mutationFn:r=>f("attach_from_agency",r),onSuccess:()=>{g(),b.success("Ad account attached")},onError:r=>b.error(`Attach failed: ${r.message}`)}),w=q({mutationFn:r=>f("attach_self",r),onSuccess:()=>{g(),b.success("Ad account attached to this workspace")},onError:r=>b.error(`Attach failed: ${r.message}`)}),_=q({mutationFn:r=>f("create_invite",r),onSuccess:()=>b.success("Invite sent"),onError:r=>b.error(`Could not send invite: ${r.message}`)}),d=q({mutationFn:r=>f("detach",{attachment_id:r}),onSuccess:()=>{g(),b.success("Detached")},onError:r=>b.error(`Detach failed: ${r.message}`)});return{attachments:x.data??[],isLoading:x.isLoading,agencyCredentials:u.data??[],isLoadingAgency:u.isLoading,attachFromAgency:y,attachSelf:w,createInvite:_,detach:d,refetch:()=>{x.refetch(),u.refetch()}}}function ft(){const{workspace:s}=te(),{effectiveUser:a}=Ds(),t=xe();j.useEffect(()=>{const n=()=>{t.invalidateQueries({queryKey:["google-ads-connection",s==null?void 0:s.id]}),t.invalidateQueries({queryKey:["google-ads-campaigns",s==null?void 0:s.id]}),b.success("Google Ads connected successfully!")},l=A=>{A.key==="google-ads-oauth-complete"&&n()}
1,N=A=>{const p=A.data;!p||typeof p!="object"||p.type==="oauth-callback"&&p.provider==="google-ads"&&p.success&&n()};return window.addEventListener("storage",l),window.addEventListener("message",N),()=>{window.removeEventListener("storage",l),window.removeEventListener("message",N)}},[t,s==null?void 0:s.id]);const{data:i,isLoading:f}=W({queryKey:["google-ads-connection",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const n="id, workspace_id, customer_id, customer_name, is_active, connected_by, connected_at, last_synced_at, created_at, updated_at",{data:l,error:N}=await S.from("google_ad_connections_safe").select(n).eq("workspace_id",s.id).eq("is_active",!0).order("updated_at",{ascending:!1}).order("connected_at",{ascending:!1}).limit(1).maybeSingle();if(N)throw N;return l},enabled:!!(s!=null&&s.id)}),{data:x=[],isLoading:u,refetch:g}=W({queryKey:["google-ads-campaigns",s==null?void 0:s.id,i==null?void 0:i.id],queryFn:async()=>{if(!(s!=null&&s.id)||!(i!=null&&i.id))return[];const{data:n,error:l}=await S.from("google_ad_campaigns").select("*").eq("workspace_id",s.id).eq("connection_id",i.id).order("last_synced_at",{ascending:!1});if(l)throw l;return n},enabled:!!(s!=null&&s.id)&&!!(i!=null&&i.id)}),y=q({mutationFn:async()=>{if(!(s!=null&&s.id)||!(a!=null&&a.id))throw new Error("Missing workspace or user");const n=600,l=760,N=window.screenX+(window.outerWidth-n)/2,A=window.screenY+(window.outerHeight-l)/2,p=`/settings/integrations/google-ads/start?workspaceId=${encodeURIComponent(s.id)}`,E=window.open(p,"_blank",`popup=yes,width=${n},height=${l},left=${N},top=${A}`);if(!E)throw new Error("Popup blocked. Please allow popups for this site and try again.");return E.focus(),{opened:!0}},onSuccess:()=>{b.success("Google Ads sign-in opened in a new tab. Complete it there, then return here.")},onError:n=>{b.error(`Failed to connect Google Ads: ${n.message}`)}}),w=q({mutationFn:async()=>{if(!(i!=null&&i.id))throw new Error("No connection to disconnect");const{error:n}=await S.from("google_ad_connections").delete().eq("id",i.id);if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["google-ads-connection",s==null?void 0:s.id]}),t.invalidateQueries({queryKey:["google-ads-campaigns",s==null?void 0:s.id]}),b.success("Google Ads disconnected")},onError:n=>{b.error(`Failed to disconnect: ${n.message}`)}}),_=q({mutationFn:async()=>{var l;if(!(i!=null&&i.id)||!(s!=null&&s.id))throw new Error("No connection available");const n=await S.functions.invoke("google-ads-oauth",{body:{action:"sync",connectionId:i.id,workspaceId:s.id}});if(n.error)throw new Error(n.error.message);if((l=n.data)!=null&&l.error)throw new Error(n.data.error);return n.data},onSuccess:()=>{g(),b.success("Campaigns synced successfully")},onError:n=>{b.error(`Failed to sync campaigns: ${n.message}`)}}),d=async()=>{if(!(s!=null&&s.id))throw new Error("Missing workspace");const n=await S.functions.invoke("google-ads-oauth",{body:{action:"list_customers",workspaceId:s.id}}),l=await Xe(n,"Failed to load Google Ads accounts");return(l==null?void 0:l.accounts)??[]},r=q({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Missing workspace");const l=await S.functions.invoke("google-ads-oauth",{body:{action:"set_customer",workspaceId:s.id,customerId:n.customerId,customerName:n.customerName}});return Xe(l,"Failed to attach Google Ads account")},onSuccess:()=>{t.invalidateQueries({queryKey:["google-ads-connection",s==null?void 0:s.id]})}}),o=!!i,h=x.reduce((n,l)=>{const N=l.metrics;return{totalSpend:n.totalSpend+((N==null?void 0:N.spend)||0),totalImpressions:n.totalImpressions+((N==null?void 0:N.impressions)||0),totalClicks:n.totalClicks+((N==null?void 0:N.clicks)||0),totalConversions:n.totalConversions+((N==null?void 0:N.conversions)||0)}},{totalSpend:0,totalImpressions:0,totalClicks:0,totalConversions:0});return{connection:i,campaigns:x,isConnected:o,isLoading:f||u,summary:h,connectGoogleAds:y,disconnectGoogleAds:w,syncCampaigns:_,refetchCampaigns:g,fetchAvailableCustomers:d,setCustomer:r}}const jt={meta:{label:"Meta (Facebook & Instagram)",description:"Attach a single Meta ad account (
1and optional Page) to this workspace.",accent:"text-blue-500",icon:qs},google:{label:"Google Ads",description:"Attach a single Google Ads customer account to this workspace.",accent:"text-emerald-500",icon:ke}};function ts({platform:s}){const a=jt[s],t=a.icon,{attachments:i,isLoading:f,agencyCredentials:x,detach:u}=Se(s),g=Ke(),y=xs(),[w,_]=j.useState(null);return e.jsxs(D,{children:[e.jsx(me,{children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-muted/60",children:e.jsx(t,{className:`h-6 w-6 ${a.accent}`})}),e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[a.label,e.jsxs(R,{variant:"outline",className:"text-[10px]",children:[e.jsx(Be,{className:"h-3 w-3 mr-1"})," Per-client scoped"]})]}),e.jsx(ge,{children:a.description})]})]}),e.jsx(yt,{platform:s,hasAgency:x.length>0})]})}),e.jsx(G,{className:"space-y-3",children:f?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(M,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):i.length===0?e.jsxs("div",{className:"text-sm text-muted-foreground py-4 text-center border border-dashed rounded-md",children:["No ad account attached. Click ",e.jsx("span",{className:"font-medium text-foreground",children:"Attach ad account"})," to get started."]}):i.map(d=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-md border bg-muted/30",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium truncate",children:d.ad_account_name??d.ad_account_id}),e.jsx(R,{variant:"secondary",className:"text-[10px] capitalize",children:d.source.replace("_"," ")}),d.currency&&e.jsx("span",{className:"text-xs text-muted-foreground",children:d.currency})]}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[d.ad_account_id,d.page_name?` ⢠Page: ${d.page_name}`:""]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[s==="meta"&&d.page_id&&e.jsxs(k,{variant:"ghost",size:"sm",disabled:y.isConnecting,onClick:y.startOAuth,title:"Reconnect Meta and update the Pages shared with this workspace",children:[y.isConnecting&&e.jsx(M,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Reconnect Meta"]}),s==="meta"&&d.page_id&&e.jsxs(k,{variant:"ghost",size:"sm",disabled:y.isRepairingPageAccess,onClick:async()=>{try{const r=await y.repairPageAccess();if((r==null?void 0:r.success)===!1||r!=null&&r.error){b.error((r==null?void 0:r.error)||"Meta Page access still needs attention",{duration:12e3});return}b.success(`Page access repaired and ${Number((r==null?void 0:r.synced_count)||0)} form(s) synced`)}catch(r){b.error(r instanceof Error?r.message:"Could not repair Meta Page access")}},title:"Re-check the Page token, lead forms, and webhook subscription",children:[y.isRepairingPageAccess&&e.jsx(M,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Repair Page Access"]}),s==="meta"&&d.page_id&&e.jsx(k,{variant:"ghost",size:"sm",onClick:()=>g("/marketing?tab=ads&adsTab=leads"),title:"Pick which lead forms to import and map fields",children:"Manage lead forms"}),e.jsx(k,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>_(d.id),children:e.jsx(gs,{className:"h-4 w-4"})})]})]},d.id))}),e.jsx(Gs,{open:w!==null,onOpenChange:d=>!d&&_(null),children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Detach ad account?"}),e.jsx(Us,{children:"Detach this ad account from this workspace? You can re-attach it any time."})]}),e.jsxs(Vs,{children:[e.jsx(Bs,{children:"Cancel"}),e.jsx(Ks,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{w&&u.mutate(w),_(null)},children:"Detach"})]})]})})]})}function yt({platform:s,hasAgency:a}){const[t,i]=j.useState(!1),[f,x]=j.useState(!1),[u,g]=j.useState(a?"agency":"invite");return j.useEffect(()=>{t&&x(!1)},[t]),e.jsxs(we,{open:t,onOpenChange:i,children:[e.jsx(Hs,{asChild:!0,children:e.jsxs(k,{size:"sm",children:[e.jsx(rt,{className:"h-4 w-4 mr-1"}),"Attach ad account"]})}),e.jsxs(be,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Pe,{children:[e.jsxs(Ie,{children:["Connect ",s==="meta"?"Meta":"Google Ads"]}),e.jsxs(Te,{children:["One click to log in. We'll pull your ad accounts",s==="meta"?" and Pages":""," so you can pick what to sync."]})]}),f?e.jsxs("div",{className:"mt-2 space-y-3",children:[e.jsx(k,{variant:"link",size:"sm",className:"h-auto p-0 text-xs",onClick:()=>x(!1),children:"â Back to one-click connect"}),e.jsxs(He,{value:u,onValueChange:y=>g(y),children:[e.jsxs(Qe,{className:"grid grid-cols-2 w-full",children:[e.jsxs(de,{value:"agency",disabled:!a,children:[e.jsx(Ls,{className:"h-4 w-4 mr-1.5"}),"From agency"]}),e.jsxs(de,{value:"invite",children:[e.jsx(os,{className:"h-4 w-4 mr-1.5"}),"Invite client"]})]}),e.jsx(Ne,{value:"agency",className:"mt-4",children:e.jsx(vt,{platform:s,onDone:()=>i(!1)})}),e.jsx(Ne,{value:"invite",className:"mt-4",children:e.jsx(wt,{platform:s,onDone:()=>i(!1)})})]})]}):e.jsxs("div",{className:"mt-2 space-y-3",children:[e.jsx(bt,{platform:s,onDone:()=>i(!1)}),e.jsxs("div",{className:"pt-3 border-t flex items-center justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:"Need agency-managed or invite-based access?"}),e.jsx(k,{variant:"link",size:"sm",className:"h-auto p-0 text-xs",onClick:()=>x(!0),children:"More options"})]})]})]})]})}function vt({platform:s,onDone:a}){const{agencyCredentials:t,isLoadingAgency:i,attachFromAgency:f}=Se(s),[x,u]=j.useState(""),[g,y]=j.useState(""),[w,_]=j.useState(""),[d,r]=j.useState(""),[o,h]=j.useState("");return i?e.jsx("div",{className:"py-8 flex justify-center",children:e.jsx(M,{className:"h-5 w-5 animate-spin"})}):t.length===0?e.jsxs(Y,{children:[e.jsx(ee,{className:"h-4 w-4"}),e.jsxs(J,{children:["No agency-level ",s==="meta"?"Meta Business Manager":"Google Ads MCC"," login is configured. An admin can add one under ",e.jsx("span",{className:"font-medium",children:"Settings â Agency â Ad Platforms"}),"."]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Use an account the agency already manages. The agency master login stays on the parent workspace â we only attach this
1single ad account to this workspace."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Agency credential"}),e.jsxs(ne,{value:x,onValueChange:u,children:[e.jsx(ie,{children:e.jsx(oe,{placeholder:"Choose an agency login"})}),e.jsx(ce,{children:t.map(n=>e.jsx(se,{value:n.id,children:n.label||n.external_account_name||n.external_account_id||n.id},n.id))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Ad account ID"}),e.jsx(z,{value:g,onChange:n=>y(n.target.value),placeholder:s==="meta"?"act_123456789":"123-456-7890"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Ad account name"}),e.jsx(z,{value:w,onChange:n=>_(n.target.value),placeholder:"Acme Co Ads"})]})]}),s==="meta"&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(F,{children:["Facebook Page ID ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(z,{value:d,onChange:n=>r(n.target.value),placeholder:"123456789"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Page name"}),e.jsx(z,{value:o,onChange:n=>h(n.target.value)})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(k,{variant:"outline",onClick:a,children:"Cancel"}),e.jsxs(k,{disabled:!x||!g||f.isPending,onClick:async()=>{try{await f.mutateAsync({credential_id:x,ad_account:{id:g,name:w||void 0},page:d?{id:d,name:o||void 0}:void 0}),a()}catch{}},children:[f.isPending&&e.jsx(M,{className:"h-4 w-4 mr-2 animate-spin"}),"Attach"]})]})]})}function wt({platform:s,onDone:a}){const{createInvite:t}=Se(s),[i,f]=j.useState(""),[x,u]=j.useState(""),[g,y]=j.useState(""),[w,_]=j.useState(null),[d,r]=j.useState(!1),o=async()=>{try{const n=await t.mutateAsync({target_email:i,target_name:x||void 0,notes:g||void 0}),l=`${window.location.origin}/invite/ads/${n.invite.invite_token}`;_(l)}catch{}},h=async()=>{w&&(await navigator.clipboard.writeText(w),r(!0),setTimeout(()=>r(!1),1500))};return w?e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Y,{children:[e.jsx(Q,{className:"h-4 w-4"}),e.jsxs(J,{children:["Invite sent to ",e.jsx("span",{className:"font-medium",children:i}),". They'll get a link to pick one ad account",s==="meta"?" and one Page":""," to share."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Or share this link directly"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{readOnly:!0,value:w,className:"font-mono text-xs"}),e.jsx(k,{variant:"outline",size:"icon",onClick:h,children:d?e.jsx(Q,{className:"h-4 w-4"}):e.jsx(Qs,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(k,{onClick:a,children:"Done"})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["We email your client a one-time link. They log into their own ",s==="meta"?"Meta":"Google"," account, pick a single ad account",s==="meta"?" and one Page":"",", and only that asset is shared with this workspace. The agency never sees the rest of their account."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Client email"}),e.jsx(z,{type:"email",value:i,onChange:n=>f(n.target.value),placeholder:"[email protected]"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(F,{children:["Client name ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(z,{value:x,onChange:n=>u(n.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(F,{children:["Note shown to the client ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(z,{value:g,onChange:n=>y(n.target.value)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(k,{variant:"outline",onClick:a,children:"Cancel"}),e.jsxs(k,{disabled:!i||t.isPending,onClick:o,children:[t.isPending&&e.jsx(M,{className:"h-4 w-4 mr-2 animate-spin"}),"Send invite"]})]})]})}function bt({platform:s,onDone:a}){return s==="meta"?e.jsx(Nt,{onDone:a}):e.jsx(Ct,{onDone:a})}function Nt({onDone:s}
1){const a=xs(),{workspace:t}=te(),{attachSelf:i}=Se("meta"),{fetchAvailableAdAccounts:f,fetchAvailablePages:x,isConnected:u,syncLeadForms:g}=a,y=Ke(),[w,_]=j.useState([]),[d,r]=j.useState([]),[o,h]=j.useState(""),[n,l]=j.useState(""),[N,A]=j.useState(!1),[p,E]=j.useState(null),[I,m]=j.useState(null),[v,P]=j.useState(!1),T=j.useCallback(async()=>{if(u){A(!0),E(null),m(null);try{const[L,U]=await Promise.allSettled([f(),x()]),V=L.status==="fulfilled"?L.value:[],c=U.status==="fulfilled"?U.value:[];if(_((V||[]).map(C=>({id:String(C.id),name:C.name,currency:C.currency}))),r((c||[]).map(C=>({id:String(C.id),name:C.name}))),U.status==="rejected"){const C=U.reason;m(C instanceof Error?C.message:"Meta did not return any Facebook Pages for this login.")}else(c||[]).length===0&&m("Meta returned no Facebook Pages for this login.");if(L.status==="rejected")throw L.reason}catch(L){const U=L instanceof Error?L.message:"Failed to load Meta assets";E(U),b.error(U)}finally{A(!1)}}},[f,x,u]);j.useEffect(()=>{u&&T()},[u,T]),j.useEffect(()=>{w.length===1&&!o&&h(w[0].id)},[w,o]),j.useEffect(()=>{d.length===1&&!n&&l(d[0].id)},[d,n]);const O=j.useMemo(()=>w.find(L=>L.id===o),[w,o]),Z=j.useMemo(()=>d.find(L=>L.id===n),[d,n]);return a.isConnected?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-md border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Be,{className:"h-4 w-4 text-green-500"}),e.jsx("span",{className:"text-muted-foreground",children:"Meta connected."}),e.jsx(k,{variant:"link",size:"sm",className:"h-auto p-0 text-xs",onClick:T,disabled:N,children:"Refresh"})]}),e.jsxs(k,{variant:"outline",size:"sm",onClick:a.startOAuth,disabled:a.isConnecting,children:[a.isConnecting?e.jsx(M,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(ke,{className:"h-3.5 w-3.5 mr-1.5"}),"Reconnect Meta"]})]}),N?e.jsx("div",{className:"py-6 flex justify-center",children:e.jsx(M,{className:"h-5 w-5 animate-spin"})}):e.jsxs(e.Fragment,{children:[p&&e.jsxs(Y,{variant:"destructive",children:[e.jsx(ee,{className:"h-4 w-4"}),e.jsxs(J,{className:"text-sm",children:["Meta assets could not load. Click ",e.jsx("strong",{children:"Reconnect Meta"}),", choose ",e.jsx("strong",{children:"Edit previous settings"}),", then select the ad account and Page you want to share."]})]}),!p&&w.length===0&&e.jsxs(Y,{children:[e.jsx(ee,{className:"h-4 w-4"}),e.jsxs(J,{className:"text-sm",children:["No ad accounts were included in this app login. Click ",e.jsx("strong",{children:"Reconnect Meta"}),", choose ",e.jsx("strong",{children:"Edit previous settings"}),", and select the ad account and Page on Meta's screen."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Ad account to share"}),e.jsxs(ne,{value:o,onValueChange:h,children:[e.jsx(ie,{children:e.jsx(oe,{placeholder:"Pick one ad account"})}),e.jsx(ce,{children:w.map(L=>e.jsxs(se,{value:L.id,children:[L.name||L.id," ",L.currency?`(${L.currency})`:""]},L.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(F,{children:["Facebook Page ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsxs(ne,{value:n,onValueChange:l,disabled:d.length===0,children:[e.jsx(ie,{children:e.jsx(oe,{placeholder:d.length===0?"No Pages available":"Pick one Page"})}),e.jsx(ce,{children:d.map(L=>e.jsx(se,{value:L.id,children:L.name||L.id},L.id))})]}),d.length===0&&e.jsxs(Y,{children:[e.jsx(ee,{className:"h-4 w-4"}),e.jsxs(J,{className:"text-sm",children:[I||"No Facebook Pages came back with this login."," Click ",e.jsx("strong",{children:"Reconnect Meta"}),", choose ",e.jsx("strong",{children:"Edit previous settings"}),", and tick the Page you want to share (you need a Page admin/advertise role on it). Then click ",e.jsx("strong",{children:"Refresh"}),"."]})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(k,{variant:"outline",onClick:s,children:"Cancel"}),e.jsxs(k,{disabled:!o||i.isPending||v,onClick:async()=>{if(O)try{if(await i.mutateAsync({ad_account:O,page:Z?{id:Z.id,name:Z.name}:void 0}),Z){P(!0);const L="/marketing?tab=ads&adsTab=leads";let U=!1,V=0;try{const c=await g();if(t!=null&&t.id&&window.sessionStorage.setItem(`meta-lead-forms:last-sync:${t.id}`,JSON.stringify(c)),(c==null?void 0:c.success)===!1||c!=null&&c.error){b.error("Ad account and Page attached, but Meta access needs attention",{description:(c==null?void 0:c.error)||(c==null?void 0:c.details)||"Meta did not return any lead forms",duration:12e3}),c!=null&&c.needs_reconnect&&b.info("Reconnect Meta to share this Page",{description:"Choose Edit previous settings, select this Page, then run Repair Page Access.",duration:12e3});return}V=Number((c==null?void 0:c.synced_count)??(c==null?void 0:c.count)??0),U=!0}catch(c){const C=c instanceof Error?c.message:"Failed to sync lead forms";b.error("Ad account and Page attached, but lead forms could not sync",{description:C,duration:12e3})}finally{P(!1)}if(U){b[V>0?"success":"info"](V>0?`${V} lead form${V===1?"":"s"} synced`:"No Meta lead forms found",{description:V>0?"Opening form mapping now.":"Opening sync details now.",duration:8e3}),s(),y(L);return}}s()}catch{}},children:[(i.isPending||v)&&e.jsx(M,{className:"h-4 w-4 mr-2 animate-spin"}),v?"Syncing formsâ¦":"Attach"]})]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log into Meta in a popup. You'll then pick a single ad account and Page to attach to this workspace."}),e.jsxs(Y,{children:[e.jsx(ee,{className:"h-4 w-4"}),e.jsxs(J,{className:"text-sm",children:["In the Meta dialog, choose ",e.jsx("strong",{children:"Edit previous settings"}),", then select the ad account and Page you want shared. Meta treats this separately from your Business Settings access."]})]}),e.jsxs(k,{onClick:a.startOAuth,disabled:a.isConnecting,children:[a.isConnecting?e.jsx(M,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ke,{className:"h-4 w-4 mr-2"}),"Log into Meta"]})]})}function Ct({onDone:s}
1){const a=ft(),{attachSelf:t}=Se("google"),[i,f]=j.useState([]),[x,u]=j.useState(""),[g,y]=j.useState(!1),[w,_]=j.useState(null),d=j.useCallback(async()=>{if(a.isConnected){y(!0),_(null);try{const o=await a.fetchAvailableCustomers();f(o)}catch(o){const h=o instanceof Error?o.message:"Failed to load Google Ads accounts";_(h),b.error(h)}finally{y(!1)}}},[a]);j.useEffect(()=>{a.isConnected&&d()},[a.isConnected]),j.useEffect(()=>{const o=i.filter(h=>!h.isManager);o.length===1&&!x&&u(o[0].id)},[i,x]);const r=j.useMemo(()=>i.find(o=>o.id===x),[i,x]);return a.isConnected?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-md border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Be,{className:"h-4 w-4 text-green-500"}),e.jsx("span",{className:"text-muted-foreground",children:"Google connected."}),e.jsx(k,{variant:"link",size:"sm",className:"h-auto p-0 text-xs",onClick:d,disabled:g,children:"Refresh"})]}),e.jsxs(k,{variant:"outline",size:"sm",onClick:()=>a.connectGoogleAds.mutate(),disabled:a.connectGoogleAds.isPending,children:[a.connectGoogleAds.isPending?e.jsx(M,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(ke,{className:"h-3.5 w-3.5 mr-1.5"}),"Reconnect Google"]})]}),g?e.jsx("div",{className:"py-6 flex justify-center",children:e.jsx(M,{className:"h-5 w-5 animate-spin"})}):e.jsxs(e.Fragment,{children:[w&&e.jsxs(Y,{variant:"destructive",children:[e.jsx(ee,{className:"h-4 w-4"}),e.jsxs(J,{className:"text-sm",children:["Couldn't load your Google Ads accounts: ",w,". Click ",e.jsx("strong",{children:"Reconnect Google"})," above and approve Google Ads access."]})]}),!w&&i.length===0&&e.jsxs(Y,{children:[e.jsx(ee,{className:"h-4 w-4"}),e.jsxs(J,{className:"text-sm",children:["No Google Ads accounts found for this Google login. If you manage your client via a Manager (MCC) account, make sure that manager has been linked to the client account in Google Ads, then click ",e.jsx("strong",{children:"Refresh"}),"."]})]}),i.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Google Ads account to attach"}),e.jsxs(ne,{value:x,onValueChange:u,children:[e.jsx(ie,{children:e.jsx(oe,{placeholder:"Pick a Google Ads account"})}),e.jsx(ce,{children:i.map(o=>e.jsxs(se,{value:o.id,disabled:o.isManager,children:[o.name,o.currency?` (${o.currency})`:""," â ",o.id,o.isManager?" · Manager":""]},o.id))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Manager (MCC) accounts are listed for context but can't be attached directly â pick the underlying client account instead."})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(k,{variant:"outline",onClick:s,children:"Cancel"}),e.jsxs(k,{disabled:!r||r.isManager||t.isPending||a.setCustomer.isPending,onClick:async()=>{if(r)try{await t.mutateAsync({ad_account:{id:r.id,name:r.name}}),await a.setCustomer.mutateAsync({customerId:r.id,customerName:r.name}),s()}catch{}},children:[(t.isPending||a.setCustomer.isPending)&&e.jsx(M,{className:"h-4 w-4 mr-2 animate-spin"}),"Attach"]})]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log into Google in a popup. We'll pull every Google Ads account you can access (including ones managed via your Manager / MCC) so you can pick which one to attach to this workspace."}),e.jsxs(Y,{children:[e.jsx(ee,{className:"h-4 w-4"}),e.jsx(J,{className:"text-sm",children:"Sign in with the Google account that has access to your client's Google Ads account â either directly, or via your manager (MCC) account."})]}),e.jsxs(k,{onClick:()=>a.connectGoogleAds.mutate(),disabled:a.connectGoogleAds.isPending,children:[a.connectGoogleAds.isPending?e.jsx(M,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ke,{className:"h-4 w-4 mr-2"}),"Log into Google Ads"]})]})}function kt(){const{workspace:s}=te(),{user:a}=cs(),t=xe(),{data:i,isLoading:f}=W({queryKey:["tiktok-ads-connection",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const o="id, workspace_id, advertiser_id, advertiser_name, is_active, connected_by, connected_at, last_synced_at, created_at, updated_at",{data:h,error:n}=await S.from("tiktok_ad_connections_safe").select(o).eq("workspace_id",s.id).maybeSingle();if(n)throw n;return h},enabled:!!(s!=null&&s.id)}),{data:x=[],isLoading:u,refetch:g}=W({queryKey:["tiktok-ads-campaigns",s==null?void 0:s.id,i==null?void 0:i.id],queryFn:async()=>
1{if(!(s!=null&&s.id)||!(i!=null&&i.id))return[];const{data:o,error:h}=await S.from("tiktok_ad_campaigns").select("*").eq("workspace_id",s.id).eq("connection_id",i.id).order("last_synced_at",{ascending:!1});if(h)throw h;return o},enabled:!!(s!=null&&s.id)&&!!(i!=null&&i.id)}),y=q({mutationFn:async()=>{var E;if(!(s!=null&&s.id)||!(a!=null&&a.id))throw new Error("Missing workspace or user");const o=`${window.location.origin}/settings/integrations/tiktok-ads/callback`,h=await S.functions.invoke("tiktok-ads-oauth",{body:{action:"authorize",workspaceId:s.id,redirectUri:o}});if(h.error)throw new Error(h.error.message);if((E=h.data)!=null&&E.error)throw new Error(h.data.error);const n=600,l=700,N=window.screenX+(window.outerWidth-n)/2,A=window.screenY+(window.outerHeight-l)/2,p=window.open(h.data.url,"tiktok-ads-oauth",`width=${n},height=${l},left=${N},top=${A}`);return new Promise((I,m)=>{const v=T=>{var O,Z;if(((O=T.data)==null?void 0:O.type)==="oauth-callback"&&((Z=T.data)==null?void 0:Z.provider)==="tiktok-ads"){if(window.removeEventListener("message",v),p==null||p.close(),T.data.error){m(new Error(T.data.error));return}I(T.data)}};window.addEventListener("message",v);const P=setInterval(()=>{p!=null&&p.closed&&(clearInterval(P),window.removeEventListener("message",v))},1e3)})},onSuccess:()=>{t.invalidateQueries({queryKey:["tiktok-ads-connection",s==null?void 0:s.id]}),b.success("TikTok Ads connected successfully!")},onError:o=>{b.error(`Failed to connect TikTok Ads: ${o.message}`)}}),w=q({mutationFn:async()=>{if(!(i!=null&&i.id))throw new Error("No connection to disconnect");const{error:o}=await S.from("tiktok_ad_connections").delete().eq("id",i.id);if(o)throw o},onSuccess:()=>{t.invalidateQueries({queryKey:["tiktok-ads-connection",s==null?void 0:s.id]}),t.invalidateQueries({queryKey:["tiktok-ads-campaigns",s==null?void 0:s.id]}),b.success("TikTok Ads disconnected")},onError:o=>{b.error(`Failed to disconnect: ${o.message}`)}}),_=q({mutationFn:async()=>{var h;if(!(i!=null&&i.id)||!(s!=null&&s.id))throw new Error("No connection available");const o=await S.functions.invoke("tiktok-ads-oauth",{body:{action:"sync",connectionId:i.id,workspaceId:s.id}});if(o.error)throw new Error(o.error.message);if((h=o.data)!=null&&h.error)throw new Error(o.data.error);return o.data},onSuccess:()=>{g(),b.success("Campaigns synced successfully")},onError:o=>{b.error(`Failed to sync campaigns: ${o.message}`)}}),d=!!i,r=x.reduce((o,h)=>{const n=h.metrics;return{totalSpend:o.totalSpend+((n==null?void 0:n.spend)||0),totalImpressions:o.totalImpressions+((n==null?void 0:n.impressions)||0),totalClicks:o.totalClicks+((n==null?void 0:n.clicks)||0),totalConversions:o.totalConversions+((n==null?void 0:n.conversions)||0)}},{totalSpend:0,totalImpressions:0,totalClicks:0,totalConversions:0});return{connection:i,campaigns:x,isConnected:d,isLoading:f||u,summary:r,connectTikTokAds:y,disconnectTikTokAds:w,syncCampaigns:_,refetchCampaigns:g}}function _t(){const{connection:s,isConnected:a,isLoading:t,connectTikTokAds:i,disconnectTikTokAds:f,syncCampaigns:x}=kt();return t?e.jsx(D,{children:e.jsx(G,{className:"flex items-center justify-center py-8",children:e.jsx(M,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):a&&s?e.jsxs(D,{className:"border-green-500/30 bg-green-500/5",children:[e.jsx(me,{className:"pb-3",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-black flex items-center justify-center",children:e.jsx("span",{className:"text-white font-bold text-sm",children:"T"})}),e.jsxs("div",{children:[e.jsxs(ue,{className:"text-lg flex items-center gap-2",children:["TikTok Ads",e.jsxs(R,{variant:"outline",className:"border-green-500/50 text-green-600",children:[e.jsx(Q,{className:"w-3 h-3 mr-1"}),"Connected"]})]}),e.jsx(ge,{children:s.advertiser_name||s.advertiser_id||"Connected Account"})]})]})})}),e.jsxs(G,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 text-sm text-muted-foreground",children:[e.jsxs("span",{children:["Advertiser ID: ",s.advertiser_id||"N/A"]}),s.connected_at&&e.jsxs("span",{children:["⢠Connected ",rs(s.connected_at,"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(k,{variant:"outline",size:"sm",onClick:()=>x.mutate(),disabled:x.isPending,children:[x.isPending?e.jsx(M,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Me,{className:"w-4 h-4 mr-2"}),"Sync Campaigns"]}),e.jsxs(k,{variant:"ghost",size:"sm",className:"text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>f.mutate(),disabled:f.isPending,children:[f.isPending?e.jsx(M,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(ls,{className:"w-4 h-4 mr-2"}),"Disconnect"]})]})]})]}):e.jsxs(D,{className:"hover:border-primary/30 transition-colors",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-black flex items-center justify-center",children:e.jsx("span",{className:"text-white font-bold text-sm",children:"T"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg",children:"TikTok Ads"}),e.jsx(ge,{children:"Connect your TikTok Business account to manage ads"})]})]})}),e.jsx(G,{children:e.jsxs(k,{className:"w-full",onClick:()=>i.mutate(),disabled:i.isPending,children:[i.isPending?e.jsx(M,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Le,{className:"w-4 h-4 mr-2"}),"Connect TikTok Ads"]})})]})}function St(){const{workspace:s}=te(),a=xe();j.useEffect(()=>{const u=()=>{a.invalidateQueries({queryKey:["monday-connection",s==null?void 0:s.id]})},g=w=>{w.key==="monday-oauth-complete"&&u()},y=w=>{const _=w.data;!_||typeof _!="object"||_.type==="oauth-callback"&&_.provider==="monday"&&_.success&&(u(),b.success("Monday.com connected!"))};return window.addEventListener("storage",g),window.addEventListener("message",y),()=>{window.removeEventListener("storage",g),window.removeEventListener("message",y)}},[a,s==null?void 0:s.id]);const{data:t,isLoading:i}=W({queryKey:["monday-connection",s==null?void 0:s.id],queryFn:async()=>
1{if(!(s!=null&&s.id))return null;const{data:u,error:g}=await S.rpc("get_monday_connections_safe",{_workspace_id:s.id});if(g)throw g;return(u??[]).find(y=>y.status==="active")??null},enabled:!!(s!=null&&s.id)}),f=q({mutationFn:async()=>{if(!(s!=null&&s.id))throw new Error("No workspace selected");const{data:u,error:g}=await S.functions.invoke("monday-oauth-init",{body:{workspaceId:s.id}});if(g)throw new Error(g.message);if(!(u!=null&&u.authUrl))throw new Error("No authorization URL returned");const y=600,w=760,_=window.screenX+(window.outerWidth-y)/2,d=window.screenY+(window.outerHeight-w)/2,r=window.open(u.authUrl,"_blank",`popup=yes,width=${y},height=${w},left=${_},top=${d}`);if(!r)throw new Error("Popup blocked. Please allow popups and try again.");return r.focus(),{opened:!0}},onError:u=>b.error(`Failed to connect Monday: ${u.message}`)}),x=q({mutationFn:async()=>{if(!(s!=null&&s.id))throw new Error("No workspace selected");const{data:u,error:g}=await S.functions.invoke("monday-disconnect",{body:{workspaceId:s.id}});if(g)throw new Error(g.message);if(u!=null&&u.error)throw new Error(u.error)},onSuccess:()=>{a.invalidateQueries({queryKey:["monday-connection",s==null?void 0:s.id]}),b.success("Monday.com disconnected")},onError:u=>b.error(`Failed to disconnect: ${u.message}`)});return{connection:t,isConnected:!!t,isLoading:i,connectMonday:f,disconnectMonday:x}}const At={contacts:[{key:"first_name",label:"First name"},{key:"last_name",label:"Last name"},{key:"email",label:"Email"},{key:"phone",label:"Phone"},{key:"mobile",label:"Mobile"},{key:"job_title",label:"Job title"},{key:"lifecycle_stage",label:"Lifecycle stage"},{key:"source",label:"Source"}],deals:[{key:"name",label:"Name"},{key:"value",label:"Value"},{key:"currency",label:"Currency"},{key:"expected_close_date",label:"Expected close date"},{key:"probability",label:"Probability"},{key:"description",label:"Description"},{key:"priority",label:"Priority"}],tasks:[{key:"title",label:"Title"},{key:"description",label:"Description"},{key:"due_date",label:"Due date"},{key:"priority",label:"Priority"},{key:"outcome",label:"Outcome"}]},Oe={contacts:{entity_type:"contacts",enabled:!1,board_id:null,board_name:null,column_mapping:{},two_way_enabled:!0},deals:{entity_type:"deals",enabled:!1,board_id:null,board_name:null,column_mapping:{},two_way_enabled:!0},tasks:{entity_type:"tasks",enabled:!1,board_id:null,board_name:null,column_mapping:{},two_way_enabled:!0}};function Et({open:s,onOpenChange:a}){const{workspace:t}=te(),i=xe(),[f,x]=j.useState("contacts"),[u,g]=j.useState(Oe),{data:y,isFetching:w,refetch:_}=W({queryKey:["monday-boards",t==null?void 0:t.id],enabled:s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:m,error:v}=await S.functions.invoke("monday-boards",{body:{workspaceId:t.id}});if(v)throw new Error(v.message);if(m!=null&&m.error)throw new Error(m.error);return(m==null?void 0:m.boards)??[]}}),{data:d}=W({queryKey:["monday-sync-settings",t==null?void 0:t.id],enabled:s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:m,error:v}=await S.from("monday_sync_settings").select("id, entity_type, enabled, board_id, board_name, column_mapping, two_way_enabled").eq("workspace_id",t.id);if(v)throw v;return m??[]}});j.useEffect(()=>{if(!d)return;const m={...Oe};for(const v of d)m[v.entity_type]={...Oe[v.entity_type],...v};g(m)},[d]);const r=u[f],{data:o,isFetching:h}=W({queryKey:["monday-board-columns",r.board_id],enabled:s&&!!r.board_id,queryFn:async()=>{var P;const{data:m,error:v}=await S.functions.invoke("monday-boards",{body:{workspaceId:t.id,boardId:r.board_id}});if(v)throw new Error(v.message);return((P=m==null?void 0:m.board)==null?void 0:P.columns)??[]}}),n=m=>g(v=>({...v,[f]:{...v[f],...m}})),l=m=>{const v=y==null?void 0:y.find(P=>P.id===m);n({board_id:m,board_name:(v==null?void 0:v.name)??null,column_mapping:{}})},N=(m,v,P)=>{const T={...r.column_mapping};!P||P==="__none__"?delete T[m]:T[m]={crmField:P,type:v},n({column_mapping:T})},A=q({mutationFn:async()=>{if(!(t!=null&&t.id))throw new Error("No workspace");for(const m of Object.values(u)){const v={workspace_id:t.id,entity_type:m.entity_type,enabled:m.enabled,board_id:m.board_
1id,board_name:m.board_name,column_mapping:m.column_mapping,two_way_enabled:m.two_way_enabled},{error:P}=await S.from("monday_sync_settings").upsert(v,{onConflict:"workspace_id,entity_type"});if(P)throw P}},onSuccess:()=>{i.invalidateQueries({queryKey:["monday-sync-settings",t==null?void 0:t.id]}),b.success("Sync settings saved")},onError:m=>b.error(m.message)}),p=q({mutationFn:async()=>{const{data:m,error:v}=await S.functions.invoke("monday-sync",{body:{workspaceId:t.id}});if(v)throw new Error(v.message);if(m!=null&&m.error)throw new Error(m.error);return m},onSuccess:m=>{const v=Object.entries((m==null?void 0:m.results)??{}).map(([P,T])=>`${P}: +${T.pushed} new, ${T.updated} updated`).join(" · ")||"Nothing to sync";b.success(`Sync complete â ${v}`)},onError:m=>b.error(m.message)}),{data:E}=W({queryKey:["monday-webhook-secret",t==null?void 0:t.id],enabled:!!(t!=null&&t.id)&&s,queryFn:async()=>{const{data:m,error:v}=await S.rpc("get_monday_webhook_secret",{_workspace_id:t.id});if(v)throw new Error(v.message);return m??null}}),I=t!=null&&t.id&&E?`https://fujtwtslpgahaburozky.supabase.co/functions/v1/monday-webhook?workspace_id=${t.id}&entity=${f}&secret=${E}`:"";return e.jsx(we,{open:s,onOpenChange:a,children:e.jsxs(be,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Pe,{children:[e.jsx(Ie,{children:"Monday.com Sync Settings"}),e.jsx(Te,{children:"Select a board and map fields for each entity. Two-way sync uses a webhook installed in Monday."})]}),e.jsxs(He,{value:f,onValueChange:m=>x(m),className:"mt-2",children:[e.jsxs(Qe,{className:"grid w-full grid-cols-3",children:[e.jsx(de,{value:"contacts",children:"Contacts"}),e.jsx(de,{value:"deals",children:"Deals"}),e.jsx(de,{value:"tasks",children:"Tasks"})]}),["contacts","deals","tasks"].map(m=>e.jsxs(Ne,{value:m,className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(F,{className:"text-base",children:["Enable ",m," sync"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Push ",m," into Monday and (optionally) pull updates back."]})]}),e.jsx(Ce,{checked:u[m].enabled,onCheckedChange:v=>g(P=>({...P,[m]:{...P[m],enabled:v}}))})]}),u[m].enabled&&e.jsxs(D,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(F,{children:"Monday board"}),e.jsxs(ne,{value:u[m].board_id??"",onValueChange:v=>{x(m),l(v)},children:[e.jsx(ie,{children:e.jsx(oe,{placeholder:"Select a board"})}),e.jsx(ce,{children:(y??[]).map(v=>e.jsx(se,{value:v.id,children:v.name},v.id))})]})]}),e.jsx(k,{variant:"outline",size:"icon",onClick:()=>_(),disabled:w,children:e.jsx(Me,{className:`h-4 w-4 ${w?"animate-spin":""}`})})]}),f===m&&u[m].board_id&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(F,{children:"Two-way (Monday â CRM)"}),e.jsx(Ce,{checked:u[m].two_way_enabled,onCheckedChange:v=>g(P=>({...P,[m]:{...P[m],two_way_enabled:v}}))})]}),e.jsxs("div",{children:[e.jsx(F,{className:"mb-2 block",children:"Field mapping"}),h?e.jsx("div",{className:"flex justify-center py-4",children:e.jsx(M,{className:"h-5 w-5 animate-spin"})}):e.jsx("div",{className:"space-y-2",children:(o??[]).map(v=>{var P,T;return e.jsxs("div",{className:"grid grid-cols-[1fr_auto_1fr] items-center gap-2",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-medium",children:v.title}),e.jsx("div",{className:"text-xs text-muted-foreground",children:v.type})]}),e.jsx("span",{className:"text-muted-foreground",children:"â"}),e.jsxs(ne,{value:((T=(P=u[m].column_mapping)==null?void 0:P[v.id])==null?void 0:T.crmField)??"__none__",onValueChange:O=>N(v.id,v.type,O),children:[e.jsx(ie,{children:e.jsx(oe,{placeholder:"â"})}),e.jsxs(ce,{children:[e.jsx(se,{value:"__none__",children:"â Not mapped â"}),At[m].map(O=>e.jsx(se,{value:O.key,children:O.label},O.key))]})]})]},v.id)})})]}),u[m].two_way_enabled&&e.jsx(D,{className:"p-3 bg-muted/30",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ws,{className:"h-4 w-4 mt-0.5 text-muted-foreground"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium mb-1",children:"Webhook URL for this board"}),e.jsx("code",{className:"text-xs break-all block bg-background rounded px-2 py-1.5",children:I||"Connect Monday.com to generate a signed webhook URL."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Keep this URL private â it c
1ontains a secret that authenticates Monday to your workspace."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:'In Monday: Board â Integrations â Webhooks â Create webhook â paste this URL â event "Create an Item" and "Column value changed".'})]})]})})]})]})]},m))]}),e.jsxs(ds,{className:"gap-2",children:[e.jsxs(k,{variant:"outline",onClick:()=>p.mutate(),disabled:p.isPending,children:[p.isPending?e.jsx(M,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Me,{className:"h-4 w-4 mr-2"}),"Sync now"]}),e.jsxs(k,{onClick:()=>A.mutate(),disabled:A.isPending,children:[A.isPending?e.jsx(M,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Save settings"]})]})]})})}function Mt(){const[s,a]=j.useState(!1),{connection:t,isConnected:i,isLoading:f,connectMonday:x,disconnectMonday:u}=St();return f?e.jsx(D,{children:e.jsx(G,{className:"flex items-center justify-center py-8",children:e.jsx(M,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):i&&t?e.jsxs(e.Fragment,{children:[e.jsxs(D,{className:"border-green-500/30 bg-green-500/5",children:[e.jsx(me,{className:"pb-3",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-gradient-to-br from-[#ff3d57] to-[#fdab3d] flex items-center justify-center",children:e.jsx("span",{className:"text-white font-bold text-sm",children:"M"})}),e.jsxs("div",{children:[e.jsxs(ue,{className:"text-lg flex items-center gap-2",children:["Monday.com",e.jsxs(R,{variant:"outline",className:"border-green-500/50 text-green-600",children:[e.jsx(Q,{className:"w-3 h-3 mr-1"}),"Connected"]})]}),e.jsx(ge,{children:t.monday_account_name||t.monday_user_name||"Connected"})]})]})})}),e.jsxs(G,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 text-sm text-muted-foreground",children:[t.monday_user_email&&e.jsx("span",{children:t.monday_user_email}),t.created_at&&e.jsxs("span",{children:["⢠Connected ",rs(t.created_at,"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(k,{variant:"outline",size:"sm",onClick:()=>a(!0),children:[e.jsx(Js,{className:"w-4 h-4 mr-2"}),"Configure Sync"]}),e.jsxs(k,{variant:"ghost",size:"sm",className:"text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>u.mutate(),disabled:u.isPending,children:[u.isPending?e.jsx(M,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(ls,{className:"w-4 h-4 mr-2"}),"Disconnect"]})]})]})]}),e.jsx(Et,{open:s,onOpenChange:a})]}):e.jsxs(D,{className:"hover:border-primary/30 transition-colors",children:[e.jsx(me,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-gradient-to-br from-[#ff3d57] to-[#fdab3d] flex items-center justify-center",children:e.jsx("span",{className:"text-white font-bold text-sm",children:"M"})}),e.jsxs("div",{children:[e.jsx(ue,{className:"text-lg",children:"Monday.com"}),e.jsx(ge,{children:"Two-way sync for contacts, deals and tasks"})]})]})}),e.jsx(G,{children:e.jsxs(k,{className:"w-full",onClick:()=>x.mutate(),disabled:x.isPending,children:[x.isPending?e.jsx(M,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Le,{className:"w-4 h-4 mr-2"}),"Connect Monday.com"]})})]})}const as={people_search:"People search",company_search:"Company search",people_match:"Contact enrichment",sequences:"Sequences"};function Pt(){const{status:s,connected:a,loading:t,busy:i,connect:f,verify:x,disconnect:u,setCreditCap:g}=mt(),y=Ke(),[w,_]=j.useState(""),[d,r]=j.useState(""),o=async()=>{try{await f(w.trim()),_(""),b.success("Apollo connected")}catch(p){b.error(p instanceof Error?p.message:"Could not connect Apollo")}},h=async()=>{try{await x(),b.success("Apollo key re-verified")}catch(p){b.error(p instanceof Error?p.message:"Verification failed")}},n=async()=>{try{await u(),b.success("Apollo disconnected")}catch(p){b.error(p instanceof Error?p.message:"Could not disconnect")}},l=async()=>{const p=d.trim()===""?null:Number(d);if(p!==null&&(!Number.isFinite(p)||p<0)){b.error("Enter a positive number, or leave blank for no cap");return}try{await g(p),b.success(p===null?"Credit cap removed":`Credit cap set to ${p}/month`)}catch(E){b.error(E instanceof Error?E.message:"Could not update the cap")}},N=(s==null?void 0:s.endpoint_access)??{},A=Object.entries(N).filter(([,p])=>p===!1);return e.jsxs(D,{className:"border-border/60",children:[e.jsx(me,{className:"pb-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"p-2.5 rounded-xl bg-primary/10",children:e.jsx(Zs,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsxs(ue,{className:"text-base flex items-center gap-2",children:["Apollo.io",a?e.jsx(R,{className:"bg-emerald-500/15 text-emerald-600 border-emerald-500/30",children:"Connected"}):e.jsx(R,{variant:"secondary",children:"Not connected"})]}),e.jsx(ge,{children:"Prospect, enrich and push contacts to sequences using this workspace's own Apollo account."})]})]}),a&&e.jsx(k,{size:"sm",variant:"outline",onClick:()=>y("/apollo"),children:"Open prospecting"})]})}),e.jsx(G,{className:"space-y-5",children:t?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(M,{className:"h-4 w-4 animate-spin"})," Checking connectionâ¦"]}):a?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsx(Ee,{label:"Account",value:(s==null?void 0:s.account_name)??(s==null?void 0:s.account_email)??"â"}),e.jsx(Ee,{label:"Plan",value:(s==null?void 0:s.plan)??"â"}),e.jsx(Ee,{label:"Credits left",value:(s==null?void 0:s.credits_remaining)!=null?String(s.credits_remaining):"â"}),e.jsx(Ee,{label:"Used this month",value:`${(s==null?void 0:s.credits_used_this_period)??0}${s!=null&&s.monthly_credit_cap?` / ${s.monthly_credit_cap}`:""}`})]}),(s==null?void 0:s.last_error)&&e.jsxs(Y,{variant:"destructive",children:[e.jsx(ve,{className:"h-4 w-4"}),e.jsx(J,{children:s.last_error})]}),A.length>0&&e.jsxs(Y,{children:[e.jsx(ve,{className:"h-4 w-4"}),e.jsxs(J,{className:"text-sm",children:["Your Apollo key can't reach: ",A.map(([p])=>as[p]??p).join(", "),". Enable those endpoints in Apollo (Settings â Integrations â API), or use a master key, then re-verify."]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 text-xs",children:Object.entries(N).map(([p,E])=>e.jsxs(R,{variant:E?"secondary":"outline",className:"gap-1",children:[E?e.jsx(ps,{className:"h-3 w-3 text-emerald-500"}):e.jsx(ve,{className:"h-3 w-3 text-amber-500"}),as[p]??p]},p))}),e.jsx(Xs,{}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end gap-3",children:[e.jsxs("div",{className:"space-y-2 flex-1",children:[e.jsx(F,{htmlFor:"apollo-cap",children:"Monthly credit cap"}),e.jsx(z,{id:"apollo-cap",inputMode:"numeric",placeholder:s!=null&&s.monthly_credit_cap?String(s.monthly_credit_cap):"No cap",value:d,onChange:p=>r(p.target.value)})]}),e.jsx(k,{variant:"outline",onClick:l,disabled:i,children:"Save cap"}),e.jsxs(k,{variant:"outline",onClick:h,disabled:i,children:[e.jsx(Me,{className:"h-4 w-4 mr-2"})," Re-verify"]}),e.jsxs(k,{variant:"ghost",className:"text-destructive",onClick:n,disabled:i,children:[e.jsx(gs,{className:"h-4 w-4 mr-2"})," Disconnect"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{htmlFor:"apollo-key",children:"Apollo API key"}),e.jsx(z,{id:"apollo-key",type:"password",autoComplete:"off",placeholder:"Paste your Apollo API key",value:w,onChange:p=>_(p.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Apollo â Settings â Integrations â API. Create a ",e.jsx("strong",{children:"master key"})," so people search and enrichment endpoints are enabled. The key is stored encrypted and is never sent to the browser."]}
1)]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(k,{onClick:o,disabled:i||w.trim().length<10,children:[i&&e.jsx(M,{className:"h-4 w-4 mr-2 animate-spin"}),"Connect Apollo"]}),e.jsx(k,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"https://app.apollo.io/#/settings/integrations/api",target:"_blank",rel:"noreferrer noopener",children:["Get a key ",e.jsx(Le,{className:"h-3.5 w-3.5 ml-1"})]})})]})]})})]})}function Ee({label:s,value:a}){return e.jsxs("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:s}),e.jsx("p",{className:"text-sm font-semibold truncate",title:a,children:a})]})}const le=["customFields","customValues","tags","pipelines","contacts","notes","opportunities","forms","surveys","calendars","bookings","conversations","products","funnels","mediaLibrary","users","automations"],Ve=["automations"],_e={tags:"Tags",customFields:"Custom Fields",customValues:"Custom Values / Snippets",pipelines:"Pipelines & Stages",contacts:"Contacts",notes:"Notes",opportunities:"Opportunities / Deals",forms:"Forms & Quizzes",surveys:"Surveys",calendars:"Calendars & Events",bookings:"Bookings / Appointments",conversations:"Conversations (SMS/Email/WhatsApp)",automations:"Automations / Workflows",users:"Staff / Users",funnels:"Landing Pages / Funnels",products:"Products",mediaLibrary:"Media Library (URL references)"},fs={tags:"All tags and contact-tag associations",customFields:"Custom field definitions and values",customValues:"Custom values, snippets, and text shortcuts",pipelines:"Pipelines, stages, and their order",contacts:"All contacts with fields, tags, and data",notes:"Contact notes attached to each record",opportunities:"Deals/opportunities mapped to pipelines",forms:"Forms and quizzes with fields",surveys:"Surveys with questions and responses",calendars:"Calendar events and availability",bookings:"Booked appointments with contact, date/time, calendar, and status",conversations:"SMS, email, and WhatsApp message history",automations:"Workflows imported as PAUSED for safety review",users:"Staff members invited to workspace",funnels:"Landing pages and funnel pages",products:"Products and pricing",mediaLibrary:"Media file URL references (files not transferred)"};function It(){const{workspace:s}=te(),{isSystemAdmin:a}=et(),[t,i]=j.useState({step:"connect",ghlToken:"",locationId:"",locationName:"",selectedEntities:[...le],entityCounts:{},progress:{},migrationId:null,isValidating:!1,isFetchingCounts:!1,isMigrating:!1,autoTag:!0}),f=j.useCallback(d=>{i(r=>({...r,...d}))},[]),x=j.useCallback(async d=>{if(a)return!0;const{data:{user:r}}=await S.auth.getUser();if(!r)return!1;const{data:o}=await S.from("workspace_members").select("role").eq("user_id",r.id).eq("workspace_id",d).maybeSingle();if((o==null?void 0:o.role)==="owner"||(o==null?void 0:o.role)==="admin")return!0;const{data:h}=await S.from("workspaces").select("parent_workspace_id").eq("id",d).single();if(h!=null&&h.parent_workspace_id){const{data:n}=await S.from("workspace_members").select("role").eq("user_id",r.id).eq("workspace_id",h.parent_workspace_id).maybeSingle();if((n==null?void 0:n.role)==="owner"||(n==null?void 0:n.role)==="admin")return!0}return!1},[a]),u=j.useCallback(async(d,r)=>{const{data:o,error:h}=await S.functions.invoke("ghl-migration",{body:{action:d,ghlToken:t.ghlToken,locationId:t.locationId,workspaceId:s==null?void 0:s.id,migrationId:t.migrationId,...r}});if(h)throw new Error(h.message);if(o!=null&&o.error)throw new Error(o.error);return o},[t.ghlToken,t.locationId,t.migrationId,s==null?void 0:s.id]),g=j.useCallback(async()=>{var r,o;if(!t.ghlToken||!t.locationId){b.error("Please enter both API token and Location ID");return}if(!(s!=null&&s.id)){b.error("No workspace selected");return}if(!await x(s.id)){b.error("You do not have permission to run migrations for this workspace. Owners and admins only.");return}f({isValidating:!0});try{const h=await u("validate");if(h.valid){f({locationName:((r=h.location)==null?void 0:r.name)||"Unknown Location",isValidating:!1}),b.success(`Connected to ${((o=h.location)==null?void 0:o.name)||"GHL"}`),f({isFetchingCounts:!0});const n=await u("fetch-counts");f({entityCounts:n.counts||{},isFetchingCounts:!1,step:"select"})}else throw new Error(h.error||"Invalid credentials")}catch(h){b.error(`Connection failed: ${h.message}`),f({isValidating:!1,isFetchingCounts:!1})}},[t.ghlToken,t.locationId,s==null?void 0:s.id,u,f,x]),y=j.useCallback(d=>{i(r=>({...r,selectedEntities:r.selectedEntities.includes(d)?r.selectedEntities.filter(o=>o!==d):[...r.selectedEntities,d]}))},[]),w=j.useCallback(async()=>
1{if(!(s!=null&&s.id))return;f({isMigrating:!0,step:"migrating"});const{data:d,error:r}=await S.from("ghl_migrations").insert({workspace_id:s.id,ghl_location_id:t.locationId,status:"in_progress",selected_entities:t.selectedEntities,entity_counts:t.entityCounts,started_at:new Date().toISOString()}).select("id").single();if(r||!d){b.error("Failed to create migration record"),f({isMigrating:!1,step:"review"});return}const o=d.id;f({migrationId:o});const h={};t.selectedEntities.forEach(l=>{h[l]={total:0,migrated:0,status:"pending"}}),f({progress:h});const n=le.filter(l=>t.selectedEntities.includes(l));for(const l of n){i(A=>({...A,progress:{...A.progress,[l]:{total:0,migrated:0,status:"in_progress"}}}));const N={tags:"migrate-tags",customFields:"migrate-custom-fields",customValues:"migrate-custom-values",pipelines:"migrate-pipelines",contacts:"migrate-contacts",notes:"migrate-notes",opportunities:"migrate-opportunities",forms:"migrate-forms",surveys:"migrate-surveys",calendars:"migrate-calendars",bookings:"migrate-bookings",conversations:"migrate-conversations",automations:"migrate-automations",users:"migrate-users",funnels:"migrate-funnels",products:"migrate-products",mediaLibrary:"migrate-media-library"};try{const p=(await S.functions.invoke("ghl-migration",{body:{action:N[l],ghlToken:t.ghlToken,locationId:t.locationId,workspaceId:s.id,migrationId:o,autoTag:t.autoTag,forcePaused:Ve.includes(l)}})).data;i(E=>({...E,progress:{...E.progress,[l]:{total:(p==null?void 0:p.total)||0,migrated:(p==null?void 0:p.migrated)||0,status:"completed"}}}))}catch(A){i(p=>({...p,progress:{...p.progress,[l]:{total:0,migrated:0,status:"failed",error:A.message}}}))}}try{await S.functions.invoke("ghl-migration",{body:{action:"complete-migration",ghlToken:t.ghlToken,locationId:t.locationId,workspaceId:s.id,migrationId:o}})}catch{}f({isMigrating:!1,step:"complete"}),b.success("Migration completed!")},[s==null?void 0:s.id,t.selectedEntities,t.locationId,t.ghlToken,t.entityCounts,t.autoTag,f]);j.useEffect(()=>{if(!t.migrationId)return;const d=S.channel(`ghl-migration-${t.migrationId}`).on("postgres_changes",{event:"UPDATE",schema:"public",table:"ghl_migrations",filter:`id=eq.${t.migrationId}`},r=>{const o=r.new.progress;o&&i(h=>({...h,progress:{...h.progress,...o}}))}).subscribe();return()=>{S.removeChannel(d)}},[t.migrationId]);const _=j.useCallback(()=>{const d=[];d.push("Entity,Status,Total,Migrated,Error");for(const l of t.selectedEntities){const N=t.progress[l];N&&d.push([_e[l],N.status,N.total.toString(),N.migrated.toString(),N.error?`"${N.error.replace(/"/g,'""')}"`:""].join(","))}const r=d.join(` 2`),o=new Blob([r],{type:"text/csv;charset=utf-8;"}),h=URL.createObjectURL(o),n=document.createElement("a");n.href=h,n.download=`ghl-migration-report_${new Date().toISOString().split("T")[0]}.csv`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(h)},[t.selectedEntities,t.progress]);return{state:t,updateState:f,validateConnection:g,toggleEntity:y,startMigration:w,generateCSVReport:_,ENTITY_LABELS:_e,ENTITY_DESCRIPTIONS:fs,MIGRATION_ORDER:le}}function ns({progress:s,selectedEntities:a}){const t=g=>{switch(g){case"completed":return e.jsx(Q,{className:"w-4 h-4 text-green-500"});case"in_progress":return e.jsx(M,{className:"w-4 h-4 text-primary animate-spin"});case"failed":return e.jsx(ee,{className:"w-4 h-4 text-destructive"});default:return e.jsx(us,{className:"w-4 h-4 text-muted-foreground"})}},i=g=>g.status==="completed"?100:g.status==="pending"?0:g.total===0?g.status==="in_progress"?50:0:Math.round(g.migrated/g.total*100),f=Object.values(s).reduce((g,y)=>g+y.migrated,0);Object.values(s).reduce((g,y)=>g+y.total,0);const x=Object.values(s).filter(g=>g.status==="completed").length,u=a.length>0?Math.round(x/a.length*100):0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"p-4 rounded-lg bg-muted/50 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Overall Progress"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[u,"%"]})]}),e.jsx(es,{value:u,className:"h-3"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[x," of ",a.length," entities complete ⢠",f.toLocaleStr
2ing()," items migrated"]})]}),e.jsx("div",{className:"space-y-3",children:a.map(g=>{const y=s[g]||{total:0,migrated:0,status:"pending"},w=i(y);return e.jsxs("div",{className:K("flex items-center gap-3 p-3 rounded-lg border transition-colors",y.status==="in_progress"&&"border-primary/30 bg-primary/5",y.status==="completed"&&"border-green-500/30 bg-green-500/5",y.status==="failed"&&"border-destructive/30 bg-destructive/5"),children:[t(y.status),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-sm font-medium",children:_e[g]}),e.jsxs("div",{className:"flex items-center gap-2",children:[y.total>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[y.migrated,"/",y.total]}),e.jsx(R,{variant:"outline",className:K("text-xs",y.status==="completed"&&"border-green-500/30 text-green-600",y.status==="failed"&&"border-destructive/30 text-destructive"),children:y.status==="in_progress"?"Migrating...":y.status})]})]}),y.status!=="pending"&&e.jsx(es,{value:w,className:"h-1.5"}),y.error&&e.jsx("p",{className:"text-xs text-destructive mt-1",children:y.error})]})]},g)})})]})}function Tt({onClose:s}){const{state:a,updateState:t,validateConnection:i,toggleEntity:f,startMigration:x,generateCSVReport:u}=It(),[g,y]=j.useState(!1),w=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"p-4 rounded-lg bg-blue-500/10 border border-blue-500/20",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(st,{className:"w-5 h-5 text-blue-500 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-blue-500",children:"Secure Connection"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Your API token is used only during the migration and is never stored in our database. All data transfers happen through encrypted connections."})]})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{htmlFor:"ghl-token",children:"GHL Private Integration Token"}),e.jsxs("div",{className:"relative",children:[e.jsx(z,{id:"ghl-token",type:g?"text":"password",placeholder:"pit-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",value:a.ghlToken,onChange:l=>t({ghlToken:l.target.value}),className:"pr-10"}),e.jsx("button",{type:"button",onClick:()=>y(!g),className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:g?e.jsx(tt,{className:"w-4 h-4"}):e.jsx(at,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Find this in GHL â Settings â Business Profile â Private Integrations"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{htmlFor:"location-id",children:"Location ID"}),e.jsx(z,{id:"location-id",placeholder:"xxxxxxxxxxxxxxxxxxxxxxxxxx",value:a.locationId,onChange:l=>t({locationId:l.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Find this in GHL â Settings â Business Profile â scroll to Location ID"})]})]}),e.jsx(k,{onClick:i,disabled:a.isValidating||!a.ghlToken||!a.locationId,className:"w-full",children:a.isValidating?e.jsxs(e.Fragment,{children:[e.jsx(M,{className:"w-4 h-4 mr-2 animate-spin"}),"Validating Connection..."]}):e.jsxs(e.Fragment,{children:["Connect & Verify",e.jsx(ze,{className:"w-4 h-4 ml-2"})]})})]}),_=()=>e.jsxs("div",{className:"space-y-6",children:[a.locationName&&e.jsxs("div",{className:"p-3 rounded-lg bg-green-500/10 border border-green-500/20 flex items-center gap-2",children:[e.jsx(Q,{className:"w-4 h-4 text-green-500"}),e.jsxs("span",{className:"text-sm",children:["Connected to ",e.jsx("strong",{children:a.locationName})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("p",{className:"text-sm font-medium",children:"Select data to migrate"}),e.jsx(k,{variant:"ghost",size:"sm",onClick:()=>{const l=a.selectedEntities.length===le.length;t({selectedEntities:l?[]:[...le]})},children:a.selectedEntities.length===le.length?"Deselect All":"Select All"})]}),e.jsx("div",{className:"space-y-2 max-h-[400px] overflow-y-auto pr-1",children:le.map(l=>{const N=a.entityCounts[l]||0,A=a.selectedEntities.includes(l),p=Ve.includes(l);return e.jsxs("div",{className:K("flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors",A?"border-primary/30 bg-primary/5":"border-border hover:border-primary/20"),onClick:()=>f(l),children:[e.jsx(nt,{checked:A}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium flex items-center gap-2",children:[_e[l],p&&e.jsxs(R,{variant:"outline",className:"text-xs border-amber-500/30 text-amber-600 gap-1",children:[e.jsx(qe,{className:"w-3 h-3"}),"Imported Paused"]})]}),N>0&&e.jsxs(R,{variant:"secondary",className:"text-xs",children:[N.toLocaleStr
2ing()," found"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:fs[l]})]})]},l)})})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(k,{variant:"outline",onClick:()=>t({step:"connect"}),children:[e.jsx(Ye,{className:"w-4 h-4 mr-2"}),"Back"]}),e.jsxs(k,{className:"flex-1",onClick:()=>t({step:"review"}),disabled:a.selectedEntities.length===0,children:["Review Migration",e.jsx(ze,{className:"w-4 h-4 ml-2"})]})]})]}),d=()=>{const l=a.selectedEntities.includes("automations");return e.jsxs("div",{className:"space-y-6",children:[l&&e.jsx("div",{className:"p-4 rounded-lg bg-amber-500/10 border border-amber-500/20",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(hs,{className:"w-5 h-5 text-amber-500 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium text-amber-500 flex items-center gap-2",children:["Automations Will Be Imported as Paused",e.jsx(R,{variant:"outline",className:"text-xs border-amber-500/30 text-amber-600",children:"Cannot be changed"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["For safety, all imported automations/workflows will be set to ",e.jsx("strong",{children:"paused"})," status. You must manually review and activate each one after import to prevent unintended triggers."]})]})]})}),e.jsx("div",{className:"p-4 rounded-lg bg-blue-500/10 border border-blue-500/20",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ve,{className:"w-5 h-5 text-blue-500 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-blue-500",children:"Ready to Migrate"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"This will import data from GoHighLevel into your workspace. Existing data will not be overwritten. This process may take several minutes depending on data volume."})]})]})}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border border-border",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ks,{className:"w-4 h-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Auto-tag imported records"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["All imported contacts, deals, and companies will be tagged with ",e.jsx("code",{className:"px-1 py-0.5 bg-muted rounded text-xs",children:"ghl-import"})]})]})]}),e.jsx(Ce,{checked:a.autoTag,onCheckedChange:N=>t({autoTag:N})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Migration Summary"}),e.jsx("div",{className:"space-y-1.5",children:a.selectedEntities.map(N=>e.jsxs("div",{className:"flex items-center justify-between py-1.5 text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(lt,{className:"w-3 h-3 text-muted-foreground"}),_e[N],Ve.includes(N)&&e.jsx(qe,{className:"w-3 h-3 text-amber-500"})]}),e.jsxs("span",{className:"text-muted-foreground",children:[(a.entityCounts[N]||0).toLocaleString()," items"]})]},N))})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(k,{variant:"outline",onClick:()=>t({step:"select"}),children:[e.jsx(Ye,{className:"w-4 h-4 mr-2"}),"Back"]}),e.jsx(k,{className:"flex-1",onClick:x,disabled:a.isMigrating,children:a.isMigrating?e.jsxs(e.Fragment,{children:[e.jsx(M,{className:"w-4 h-4 mr-2 animate-spin"}),"Starting Migration..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ms,{className:"w-4 h-4 mr-2"}),"Start Migration"]})})]})]})},r=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center py-2",children:[e.jsx(M,{className:"w-8 h-8 text-primary animate-spin mx-auto mb-3"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Migration in Progress"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please keep this page open. Do not close or refresh."})]}),e.jsx(ns,{progress:a.progress,selectedEntities:a.selectedEntities})]}),o=()=>{const l=Object.values(a.progress).filter(p=>p.status==="completed").length,N=Object.values(a.progress).filter(p=>p.status==="failed").length,A=Object.values(a.progress).reduce((p,E)=>p+E.migrated,0);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center py-4",children:[N===0?e.jsx(ps,{className:"w-12 h-12 text-green-500 mx-auto mb-3"}):e.jsx(ve,{className:"w-12 h-12 text-amber-500 mx-auto mb-3"}),e.jsx("h3",{className:"text-xl font-semibold",children:"Migration Complete"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[A.toLocaleStr
2ing()," items migrated successfully"]}),a.autoTag&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["All records tagged with ",e.jsx("code",{className:"px-1 py-0.5 bg-muted rounded text-xs",children:"ghl-import"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"p-3 rounded-lg bg-green-500/10 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-green-500",children:l}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Completed"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-destructive/10 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-destructive",children:N}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Failed"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-primary/10 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-primary",children:A.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Items"})]})]}),a.selectedEntities.includes("automations")&&e.jsxs("div",{className:"p-3 rounded-lg bg-amber-500/10 border border-amber-500/20 flex items-start gap-2",children:[e.jsx(qe,{className:"w-4 h-4 text-amber-500 mt-0.5 shrink-0"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{className:"text-amber-500",children:"Reminder:"})," Imported automations are paused. Review and activate them manually in the Automations section."]})]}),e.jsx(ns,{progress:a.progress,selectedEntities:a.selectedEntities}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(k,{variant:"outline",onClick:u,className:"flex-1",children:[e.jsx(it,{className:"w-4 h-4 mr-2"}),"Download CSV Report"]}),e.jsxs(k,{className:"flex-1",onClick:s,children:[e.jsx(Ue,{className:"w-4 h-4 mr-2"}),"Done"]})]})]})},h=[{key:"connect",label:"Connect"},{key:"select",label:"Select Data"},{key:"review",label:"Review"},{key:"migrating",label:"Migrating"},{key:"complete",label:"Complete"}],n=h.findIndex(l=>l.key===a.step);return e.jsx("div",{className:"max-w-2xl mx-auto",children:e.jsxs(D,{children:[e.jsxs(me,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(ue,{className:"flex items-center gap-2",children:[e.jsx("img",{src:"https://images.leadconnectorhq.com/image/f_webp/q_80/r_1200/u_https://cdn.filesafe.space/46QWLMIJNQYGxf7OlnMB/media/63ff845a5067f14e53e2cc8c.png",alt:"GoHighLevel",className:"w-6 h-6 rounded",onError:l=>{l.currentTarget.src="https://ui-avatars.com/api/?name=GHL&background=0B7DDA&color=fff"}}),"GoHighLevel Migration"]}),e.jsx(ge,{children:"Migrate all your data from GHL to your workspace"})]}),a.step!=="migrating"&&e.jsx(k,{variant:"ghost",size:"sm",onClick:s,children:"Close"})]}),e.jsx("div",{className:"flex items-center gap-1 mt-4",children:h.map((l,N)=>e.jsx("div",{className:"flex items-center flex-1",children:e.jsx("div",{className:K("h-1.5 rounded-full flex-1 transition-colors",N<=n?"bg-primary":"bg-muted")})},l.key))}),e.jsx("div",{className:"flex justify-between mt-1",children:h.map((l,N)=>e.jsx("span",{className:K("text-xs",N<=n?"text-primary font-medium":"text-muted-foreground"),children:l.label},l.key))})]}),e.jsxs(G,{children:[a.step==="connect"&&w(),a.step==="select"&&_(),a.step==="review"&&d(),a.step==="migrating"&&r(),a.step==="complete"&&o()]})]})})}function Lt({open:s,onOpenChange:a}){const{workspace:t}=te(),[i,f]=j.useState(!0),[x,u]=j.useState(!1),[g,y]=j.useState([]),[w,_]=j.useState([]),[d,r]=j.useState(""),[o,h]=j.useState(""),[n,l]=j.useState(!0),[N,A]=j.useState(!0);j.useEffect(()=>{!s||!(t!=null&&t.id)||(async()=>{var I,m;f(!0);try{const[{data:v},{data:P},{data:T}]=await Promise.all([S.from("pipelines").select("id,name").eq("workspace_id",t.id).order("created_at"),S.from("pipeline_stages").select("id,name,pipeline_id").eq("workspace_id",t.id).order("position"),S.from("calendly_settings").select("*").eq("workspace_id",t.id).maybeSingle()]);y(v||[]),_(P||[]),T?(r(T.pipeline_id||((I=v==null?void 0:v[0])==null?void 0:I.id)||""),h(T.stage_id||""),l(T.auto_create_contacts),A(T.auto_create_deals)):(r(((m=v==null?void 0:v[0])==null?void 0:m.id)||""),h(""))}catch(v){b.error(v.message)}finally{f(!1)}})()},[s,t==null?void 0:t.id]);const p=w.filter(I=>I.pipeline_id===d),E=async()=>
2{if(t!=null&&t.id){u(!0);try{const{error:I}=await S.from("calendly_settings").upsert({workspace_id:t.id,pipeline_id:d||null,stage_id:o||null,auto_create_contacts:n,auto_create_deals:N},{onConflict:"workspace_id"});if(I)throw I;b.success("Calendly settings saved"),a(!1)}catch(I){b.error(I.message)}finally{u(!1)}}};return e.jsx(we,{open:s,onOpenChange:a,children:e.jsxs(be,{className:"sm:max-w-md",children:[e.jsxs(Pe,{children:[e.jsx(Ie,{children:"Calendly Settings"}),e.jsx(Te,{children:"Configure how Calendly bookings flow into your CRM."})]}),i?e.jsx("div",{className:"py-8 flex justify-center",children:e.jsx(M,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(F,{children:"Auto-create contacts"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add the invitee to your CRM contacts."})]}),e.jsx(Ce,{checked:n,onCheckedChange:l})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(F,{children:"Auto-create deals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Create a deal in your pipeline on every booking."})]}),e.jsx(Ce,{checked:N,onCheckedChange:A})]}),e.jsxs("div",{className:N?"space-y-3":"space-y-3 opacity-50 pointer-events-none",children:[e.jsxs("div",{children:[e.jsx(F,{children:"Pipeline"}),e.jsxs(ne,{value:d,onValueChange:I=>{r(I),h("")},children:[e.jsx(ie,{children:e.jsx(oe,{placeholder:"Select pipeline"})}),e.jsx(ce,{children:g.map(I=>e.jsx(se,{value:I.id,children:I.name},I.id))})]})]}),e.jsxs("div",{children:[e.jsx(F,{children:"Stage"}),e.jsxs(ne,{value:o,onValueChange:h,disabled:!d,children:[e.jsx(ie,{children:e.jsx(oe,{placeholder:"First stage (default)"})}),e.jsx(ce,{children:p.map(I=>e.jsx(se,{value:I.id,children:I.name},I.id))})]})]})]})]}),e.jsxs(ds,{children:[e.jsx(k,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(k,{onClick:E,disabled:x||i,children:[x&&e.jsx(M,{className:"w-4 h-4 mr-1.5 animate-spin"}),"Save"]})]})]})})}const $e=["google","google-calendar","gmail"],fe=["facebook","instagram","meta-ads"],je=["google-ads","tiktok-ads"],is="gohighlevel";function Jt(){const[s]=_s(),{workspace:a,loading:t}=te(),{user:i}=cs(),f=xe(),[x,u]=j.useState(""),[g,y]=j.useState("all"),[w,_]=j.useState(null),[d,r]=j.useState(!1),[o,h]=j.useState(!1),{connections:n,connectGoogle:l,disconnectIntegration:N,isConnected:A,getConnection:p}=dt(),E=gt(),I=j.useMemo(()=>{const c=new Set;return n.forEach(C=>{c.add(C.provider)}),c},[n]),m=pt(),v=ye.map(c=>({...c,integrations:c.integrations.filter(C=>C.name.toLowerCase().includes(x.toLowerCase())||C.description.toLowerCase().includes(x.toLowerCase()))})).filter(c=>c.integrations.length>0),P=v.flatMap(c=>c.integrations),T=n.length;if(s.get("meta_callback")==="true"||s.get("provider")==="meta")return e.jsx(ut,{});const O=c=>$e.includes(c)?A("google"):c==="zoom"?E.isConnected:fe.includes(c)||je.includes(c)?!1:I.has(c),Z=async()=>{if(!(a!=null&&a.id))return;if(I.has("calendly")){try{const{error:C}=await S.functions.invoke("calendly-oauth",{body:{workspace_id:a.id},method:"POST"});if(C){const $="https://fujtwtslpgahaburozky.supabase.co/functions/v1/calendly-oauth?action=disconnect",{data:{session:H}}=await S.auth.getSession();await fetch($,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${H==null?void 0:H.access_token}`},body:JSON.stringify({workspace_id:a.id})})}f.invalidateQueries({queryKey:["integration-connections"]}),b.success("Calendly disconnected")}catch(C){b.error(`Disconnect failed: ${C.message}`)}return}try{const{data:{session:C}}=await S.auth.getSession(),H=`https://fujtwtslpgahaburozky.supabase.co/functions/v1/calendly-oauth?action=authorize&workspace_id=${a.id}&redirect_uri=${encodeURIComponent("https://ineedleads.co.uk/settings/integrations/callback")}`,Ae=await fetch(H,{headers:{Authorization:`Bearer ${C==null?void 0:C.access_token}`}}),he=await Ae.json();if(!Ae.ok||!he.url)throw new Error(he.error||"Failed to start Calendly OAuth");const ae=window.open(he.url,"calendly-oauth","width=600,height=720"),B=async pe=>{if(![window.location.origin,"https://ineedleads.co.uk"].includes(pe.origin))return;const X=pe.data;if(!(!X||X.type!=="oauth-callback"||X.provider!=="calendly")){if(window.removeEventListener("message",B),X.error){b.error(`Calendly: ${X.error}`);return}try{const Re=`https://fujtwtslpgahaburozky.supabase.co/functions/v1/calendly-oauth?action=callback&code=${encodeURIComponent(X.co
2de)}&state=${encodeURIComponent(X.state)}`,We=await fetch(Re),De=await We.json();if(!We.ok)throw new Error(De.error||"Callback failed");b.success(`Calendly connected${De.email?` as ${De.email}`:""}`),f.invalidateQueries({queryKey:["integration-connections"]})}catch(Re){b.error(`Calendly: ${Re.message}`)}try{ae==null||ae.close()}catch{}}};window.addEventListener("message",B)}catch(C){b.error(C.message)}},L=async c=>{const C=c.id;if(C===is){r(!0);return}if(C==="calendly"){await Z();return}if(C==="zoom"){E.isConnected?await E.disconnect.mutateAsync():await E.connect.mutateAsync();return}if(!fe.includes(C)&&!je.includes(C)){if($e.includes(C)){A("google")?N.mutate("google"):l.mutate();return}I.has(C)?(n.find(H=>H.provider===C)&&N.mutate(C),b.success(`${c.name} disconnected`)):_(c)}},U=async()=>{if(w&&(a!=null&&a.id)&&(i!=null&&i.id)){try{const{error:c}=await S.from("integration_connections").insert({workspace_id:a.id,user_id:i.id,provider:w.id,metadata:{name:w.name}});if(c)throw c;f.invalidateQueries({queryKey:["integration-connections"]}),b.success(`${w.name} connected successfully!`)}catch(c){b.error(`Failed to connect: ${c.message}`)}_(null)}},V=({integration:c,compact:C=!1})=>{var pe,Fe;const $=O(c.id),H=$e.includes(c.id),Ae=c.id==="zoom",he=H&&(l.isPending||N.isPending)||Ae&&(E.connect.isPending||E.disconnect.isPending||E.isConnecting),ae=p("google"),B=c.comingSoon;return e.jsxs(D,{className:K("group relative overflow-hidden transition-all duration-300",!B&&"hover:shadow-lg hover:shadow-primary/5 hover:border-primary/30",$&&"border-green-500/30 bg-green-500/5",B&&"opacity-75"),children:[e.jsxs("div",{className:"absolute top-2 right-2 flex items-center gap-1.5",children:[B&&e.jsx(ht,{size:"sm",tooltip:"This integration is in development and will be available soon."}),c.popular&&!C&&!B&&e.jsxs(R,{variant:"secondary",className:"bg-amber-500/10 text-amber-500 border-amber-500/20 text-xs",children:[e.jsx(Ze,{className:"w-3 h-3 mr-1 fill-amber-500"}),"Popular"]})]}),e.jsxs(G,{className:K("p-4",C&&"p-3"),children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:K("relative shrink-0 rounded-xl bg-muted/50 p-2 overflow-hidden",C?"w-10 h-10":"w-12 h-12",B&&"grayscale opacity-60"),children:[e.jsx("img",{src:c.icon,alt:c.name,className:"w-full h-full object-contain",onError:X=>{X.currentTarget.src=`https://ui-avatars.com/api/?name=${c.name}&background=random`}}),$&&!B&&e.jsx("div",{className:"absolute -bottom-1 -right-1 w-5 h-5 rounded-full bg-green-500 flex items-center justify-center",children:e.jsx(Q,{className:"w-3 h-3 text-white"})})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:K("font-semibold truncate",C?"text-sm":"text-base",B&&"text-muted-foreground"),children:c.name}),H&&!B&&e.jsx(R,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:"OAuth"})]}),!C&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mt-0.5",children:c.description}),$&&H&&((pe=ae==null?void 0:ae.metadata)==null?void 0:pe.email)&&e.jsx("p",{className:"text-xs text-green-600 mt-1 truncate",children:ae.metadata.email}),$&&c.id==="zoom"&&((Fe=E.connection)==null?void 0:Fe.email)&&e.jsx("p",{className:"text-xs text-green-600 mt-1 truncate",children:E.connection.email})]})]}),e.jsx("div",{className:K("flex items-center gap-2",C?"mt-3":"mt-4"),children:B?e.jsxs(k,{variant:"outline",size:"sm",className:"flex-1 cursor-not-allowed opacity-60",disabled:!0,children:[e.jsx(hs,{className:"w-4 h-4 mr-1.5"}),"Coming Soon"]}):e.jsxs(e.Fragment,{children:[e.jsx(k,{variant:$?"outline":"default",size:"sm",className:K("flex-1 group/btn",$&&"border-green-500/30 text-green-500 hover:text-red-500 hover:border-red-500/30"),onClick:()=>L(c),disabled:he,children:he?e.jsxs(e.Fragment,{children:[e.jsx(M,{className:"w-4 h-4 mr-1.5 animate-spin"}),$?"Disconnecting...":"Connecting..."]}):$?e.jsxs(e.Fragment,{children:[e.jsx(Q,{className:"w-4 h-4 mr-1.5 group-hover/btn:hidden"}),e.jsx("span",{className:"group-hover/btn:hidden",children:"Connected"}),e.jsx("span",{className:"hidden group-hover/btn:inline",children:"Disconnect"})]}):c.id===is?e.jsxs(e.Fragment,{children:[e.jsx(ms,{className:"w-4 h-4 mr-1.5"}),"Migrate"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ge,{className:"w-4 h-4 mr-1.5"}),"Connect"]})}),$&&e.jsx(k,{variant:"ghost",size:"sm",className:"px-2",onClick:()=>{c.id==="calendly"&&h(!0)},children:e.jsx(ct,{className:"w-4 h-4"})})]})})]})]})};return t||!a?e.jsx(ss,{children:e.jsx("main",{className:"flex-1 overflow-auto",children:e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(M,{className:"h-8 w-8 animate-spin text-primary"})})})}):e.jsxs(ss,{children:[e.jsx("main",{className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"p-8",children:[e.jsx("div",{className:"mb-8",children:e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"p-2.5 rounded-xl bg-primary/10",children:e.jsx(Ge,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold",children:"Integrations"}),e.jsx("p",{className:"text-muted-foreground",children:"Connect your favorite tools and supercharge your CRM"})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-8",children:[e.jsx(D,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:e.jsxs(G,{className:"p-4 flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-xl bg-primary/10",children:e.jsx(re,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:T}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connected"})]})]})}),e.jsx(D,{children:e.jsxs(G,{className:"p-4 flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-xl bg-muted",children:e.jsx(Ge,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:P.length}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Available"})]})]})}),e.jsx(D,{children:e.jsxs(G,{className:"p-4 flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-xl bg-muted",children:e.jsx(Ue,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:ye.length}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Categories"})]})]})})]}),e.jsxs("div",{className:"relative mb-6",children:[e.jsx(Je,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(z,{type:"search",name:"integrations-search",id:"integrations-search",autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,"data-form-type":"other","data-lpignore":"true","data-1p-ignore":"true",placeholder:"Search integrations...",value:x,onChange:c=>u(c.target.value),className:"pl-10 h-11 bg-muted/50"})]}),!x&&e.jsxs("div",{className:"mb-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(re,{className:"h-5 w-5 text-blue-500"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Meta Integration"}),e.jsx(R,{variant:"secondary",className:"text-xs",children:"Per-client scoped ⢠Lead Forms ⢠Ads ⢠CAPI"})]}),e.jsx(ts,{platform:"meta"})]}),!x&&e.jsxs("div",{className:"mb-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(re,{className:"h-5 w-5 text-green-500"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Google Ads Integration"}),e.jsx(R,{variant:"secondary",className:"text-xs",children:"Per-client scoped ⢠Search ⢠Display ⢠YouTube"})]}),e.jsx(ts,{platform:"google"})]}),!x&&e.jsxs("div",{className:"mb-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(re,{className:"h-5 w-5 text-pink-500"}),e.jsx("h2",{className:"text-lg font-semibold",children:"TikTok Ads Integration"}),e.jsx(R,{variant:"secondary",className:"text-xs",children:"In-Feed ⢠TopView ⢠Spark Ads"})]}),e.jsx(_t,{})]}
2),(!x||"monday.com crm sync two-way contacts deals tasks".includes(x.toLowerCase()))&&e.jsxs("div",{className:"mb-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(re,{className:"h-5 w-5 text-[#ff3d57]"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Monday.com CRM Sync"}),e.jsx(R,{variant:"secondary",className:"text-xs",children:"Two-way ⢠Contacts ⢠Deals ⢠Tasks"})]}),e.jsx(Mt,{})]}),(!x||"apollo prospecting b2b data enrichment sequences".includes(x.toLowerCase()))&&e.jsxs("div",{className:"mb-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(re,{className:"h-5 w-5 text-indigo-500"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Apollo.io"}),e.jsx(R,{variant:"secondary",className:"text-xs",children:"Prospecting ⢠Enrichment ⢠Sequences"})]}),e.jsx(Pt,{})]}),e.jsx(we,{open:d,onOpenChange:r,children:e.jsx(be,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto p-0",children:e.jsx(Tt,{onClose:()=>r(!1)})})}),e.jsx(Lt,{open:o,onOpenChange:h}),!x&&e.jsxs("div",{className:"mb-8",children:[e.jsx("div",{className:"flex items-center justify-between mb-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"h-5 w-5 text-amber-500 fill-amber-500"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Popular Integrations"})]})}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:m.filter(c=>!fe.includes(c.id)&&!je.includes(c.id)).slice(0,8).map(c=>e.jsx(V,{integration:c,compact:!0},c.id))})]}),e.jsxs(He,{value:g,onValueChange:y,children:[e.jsx(ot,{className:"w-full",children:e.jsxs(Qe,{className:"inline-flex h-auto p-1 bg-muted/50 mb-6",children:[e.jsx(de,{value:"all",className:"px-4 py-2",children:"All"}),ye.map(c=>e.jsxs(de,{value:c.id,className:"px-4 py-2 gap-2",children:[e.jsx(c.icon,{className:"w-4 h-4"}),c.name]},c.id))]})}),e.jsx(Ne,{value:"all",className:"mt-0",children:e.jsx("div",{className:"space-y-8",children:v.map(c=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"p-2 rounded-lg bg-muted",children:e.jsx(c.icon,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:c.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c.description})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:c.integrations.filter(C=>!fe.includes(C.id)&&!je.includes(C.id)).map(C=>e.jsx(V,{integration:C},C.id))})]},c.id))})}),ye.map(c=>e.jsxs(Ne,{value:c.id,className:"mt-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("div",{className:"p-3 rounded-xl bg-muted",children:e.jsx(c.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold",children:c.name}),e.jsx("p",{className:"text-muted-foreground",children:c.description})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:c.integrations.filter(C=>!fe.includes(C.id)&&!je.includes(C.id)&&(C.name.toLowerCase().includes(x.toLowerCase())||C.description.toLowerCase().includes(x.toLowerCase()))).map(C=>e.jsx(V,{integration:C},C.id))})]},c.id))]}),x&&P.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"p-4 rounded-full bg-muted/50 w-fit mx-auto mb-4",children:e.jsx(Je,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No integrations found"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Try searching with different keywords"}),e.jsx(k,{variant:"outline",onClick:()=>u(""),children:"Clear search"})]}),e.jsx(D,{className:"mt-12 border-dashed",children:e.jsxs(G,{className:"py-8 text-center",children:[e.jsx("div",{className:"p-4 rounded-full bg-muted/50 w-fit mx-auto mb-4",children:e.jsx(Ue,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Can't find what you're looking for?"}),e.jsx("p",{className:"text-muted-foreground mb-4 max-w-md mx-auto",children:"We're always adding new integrations. Let us know what you need!"}),e.jsxs(k,{variant:"outline",children:["Request Integration",e.jsx(ze,{className:"w-4 h-4 ml-2"})]})]})})]})}),e.jsx(we,{open:!!w,onOpenChange:()=>_(null),children:e.jsxs(be,{className:"sm:max-w-md",children:[e.jsxs(Pe,{children:[e.jsx(Ie,{className:"flex items-center gap-3",children:w&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-muted p-2",children:e.jsx("img",{src:w.icon,alt:w.name,className:"w-full h-full object-contain",onError:c=>
2{c.currentTarget.src=`https://ui-avatars.com/api/?name=${w.name}&background=random`}})}),"Connect ",w.name]})}),e.jsx(Te,{children:w==null?void 0:w.description})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Clicking connect will redirect you to ",w==null?void 0:w.name," to authorize the connection. Your data will be securely synced with NextGen CRM."]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"This integration will:"}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-1",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(Q,{className:"w-4 h-4 text-green-500"}),"Sync contacts and data automatically"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(Q,{className:"w-4 h-4 text-green-500"}),"Enable two-way communication"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(Q,{className:"w-4 h-4 text-green-500"}),"Keep your data secure and encrypted"]})]})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(k,{variant:"outline",className:"flex-1",onClick:()=>_(null),children:"Cancel"}),e.jsxs(k,{className:"flex-1",onClick:U,children:[e.jsx(Le,{className:"w-4 h-4 mr-2"}),"Connect"]})]})]})})]})}export{Jt as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.