PageSourceSearch

https://myreviewreport.com/assets/SuperAdmin-DgTDybzq.js

js myreviewreport.com collected 2026-10-06 22:18:01 UTC 177,592 bytes, 284 lines download raw bytes

1import{c as os,r as i,s as R,j as e,d as Qe,a as ne,b as Ge,D as ft,C as ze,P as Oe,F as Ze,E as we,A as Ne,ab as jt,o as Is,u as bt,a1 as vt,g as js,h as bs,e as Nt}from"./index-IZnvRumJ.js";import{C as j,a as W,b as V,d as O,c as _e}from"./card-BWWzAZHh.js";import{I as Ue}from"./input-OGCcGVWJ.js";import{B as Y}from"./button-DcP8iMA9.js";import{B as H}from"./badge-CDTGuZL7.js";import{S as He,A as Te,b as Le,c as yt}from"./AppLayout-cVkycFLS.js";import{S as wt,a as St,d as _t,e as Ct,f as Rt,b as kt}from"./sheet-zYE83Wug.js";import{S as rs}from"./skeleton-D7D6JDZR.js";import{B as Ee}from"./building-2-TavQYcI3.js";import{M as ie}from"./mail-Rp6evAGI.js";import{G as vs}from"./globe-CwLKkDOx.js";import{C as zs}from"./credit-card-Dge_IzRx.js";import{P as At}from"./palette-D2KBmLK0.js";import{U as Re}from"./users-HfDtNntb.js";import{P as Tt}from"./phone-C0glLY_m.js";import{M as Lt}from"./map-pin-DnrJ1CPl.js";import{S as ge,a as fe,b as je,c as be,d as B,e as Et}from"./select-Ds0eJjSi.js";import{S as Ms}from"./shield-ebKOM8r4.js";import{T as oe,a as ce,b as Q,c as L,d as de,e as A}from"./table-CfZyhGAm.js";import{P as Dt}from"./play-DiwQ0sVt.js";import{R as ee}from"./refresh-cw-Cj27TXI0.js";import{C as pe}from"./clock-CgINlRZu.js";import{C as $e}from"./circle-check-big-GuFer4Dh.js";import{C as Se}from"./circle-x-Bkg0PfRg.js";import{T as De}from"./triangle-alert-B8sOFBAg.js";import{F as ye}from"./file-text-CZEMuyyH.js";import{T as ve}from"./trending-up-DZRNf4zr.js";import{C as Be}from"./circle-alert-BmsUTnOk.js";import{D as Fs}from"./download-DgJMEZ5u.js";import{S as Pe}from"./search-9X0la83E.js";import{F as Ns}from"./filter-CFmG5AmF.js";import{P as ys}from"./plus-GBlIdfW8.js";import{T as as}from"./trash-2-CV7TdwLB.js";import{S as ws}from"./square-pen-Ck3gfBhr.js";import{U as $s}from"./user-bRQK6Won.js";import{R as Pt}from"./rotate-ccw-mA8efRwN.js";import{f as Bs}from"./formatDistanceToNow-C5NMARHg.js";import{B as is}from"./brain-CLuMtRvy.js";import{C as le}from"./circle-check-CJPteXk5.js";import{T as We,a as Ve,b as J,c as X}from"./tabs-ilaa6CMj.js";import{u as Os}from"./useQuery-DHnKGTyB.js";import{I as cs}from"./info-C1XR6DJR.js";import{Z as Ss}from"./zap-BJhwTE2I.js";import{C as It}from"./crown-CGzwbtTd.js";import{U as Us}from"./user-check-eex0edCl.js";import{D as Ws,a as zt,b as Vs,c as qs,d as Hs}from"./dialog-RI8CE1mU.js";import{E as Ce}from"./eye-BaRUKt7b.js";import{A as Mt,a as Ft,b as $t,c as Bt,d as Ot,e as Ut,f as Wt,g as Vt}from"./alert-dialog-BrhGOoeP.js";import{S as ns}from"./send-MRCX-zBf.js";import{f as Ys}from"./format-Cn6ElKJ8.js";import{U as qt}from"./user-plus-BzHr9rY5.js";import{T as Je}from"./target-tsid7M2N.js";import{A as Ht}from"./activity-BV4WcV5Y.js";import{A as Yt}from"./arrow-right-C8S3duny.js";import{f as Qt}from"./phone-Dp8aihJC.js";import{E as Gt}from"./external-link-1LE5Lgze.js";import{u as Jt}from"./index-BmRzOyoq.js";import{M as _s}from"./message-square-DqeRE4Ju.js";import{B as Cs}from"./bot-BQdRaamy.js";import{L as Xt}from"./link-2-B0o0W-h3.js";import{M as Kt}from"./mouse-pointer-click-C4y_R1iU.js";import{D as Zt,a as er,b as sr,g as tr,h as Rs,f as ks}from"./dropdown-menu-DqOrHu2j.js";import{D as rr}from"./dollar-sign-CpgVierP.js";import{E as ar}from"./ellipsis-vertical-DFopFIrX.js";import"./mysteryShopperBrand-BYkn7pdw.js";import"./mysterycallai-logo-dark-BFNFGS3B.js";import"./useTier-BULoQlR6.js";import"./chevron-down-1nMbKwc_.js";import"./chart-column-CsqJFWcn.js";import"./swords-CyoFjmFq.js";import"./file-pen-line-DkW7k01H.js";import"./calculator-Pwff5vj0.js";import"./phone-call-Dm3n_iYk.js";import"./lpInvoke-Ds_Z-Vno.js";import"./circle-plus-HJRNrV0j.js";import"./lightbulb-uxg2Rvra.js";import"./graduation-cap-25AkShwK.js";import"./layout-dashboard-D4Xc7vFm.js";import"./book-open-C7ggllaI.js";import"./circle-help-LlvxE_IR.js";import"./label-CoGXWevP.js";import"./types-C-jxggw2.js";import"./publicUrl-bjBORCqm.js";import"./index-MH1WVYsB.js";import"./index-DyIwh2Qx.js";import"./chevron-up-CcQezlK8.js";import"./check-C2pnSUS4.js";import"./en-US-CXXYYhpC.js";import"./index-BlZBv0Jc.js";import"./chevron-right-QiugxkLR.js";/**
2 * @license lucide-react v0.462.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const ir=os("ArrowDownLeft",[["path",{d:"M17 7 7 17",key:"15tmo1"}],["path",{d:"M17 17H7V7",key:"1org7z"}]]);/**
7 * @license lucide-react v0.462.0 - ISC
8 *
9 * This source code is licensed under the ISC license.
10 * See the LICENSE file in the root directory of this source tree.
11 */const nr=os("MousePointer",[["path",{d:"M12.586 12.586 19 19",key:"ea5xo7"}],["path",{d:"M3.688 3.037a.497.497 0 0 0-.651.651l6.5 15.999a.501.501 0 0 0 .947-.062l1.569-6.083a2 2 0 0 1 1.448-1.479l6.124-1.5
1179a.5.5 0 0 0 .063-.947z",key:"277e5u"}]]);/**
12 * @license lucide-react v0.462.0 - ISC
13 *
14 * This source code is licensed under the ISC license.
15 * See the LICENSE file in the root directory of this source tree.
16 */const lr=os("UserCog",[["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m21.7 16.4-.9-.3",key:"12j9ji"}],["path",{d:"m15.2 13.9-.9-.3",key:"1fdjdi"}],["path",{d:"m16.6 18.7.3-.9",key:"heedtr"}],["path",{d:"m19.1 12.2.3-.9",key:"1af3ki"}],["path",{d:"m19.6 18.7-.4-1",key:"1x9vze"}],["path",{d:"m16.8 12.3-.4-1",key:"vqeiwj"}],["path",{d:"m14.3 16.6 1-.4",key:"1qlj63"}],["path",{d:"m20.7 13.8 1-.4",key:"1v5t8k"}]]);function or({agencyId:s,onClose:c}){var w,S,u;const[r,t]=i.useState(!0),[n,l]=i.useState(null),[o,m]=i.useState(null),[d,g]=i.useState(null),[f,b]=i.useState(null);i.useEffect(()=>{s&&N()},[s]);const N=async()=>{try{t(!0);const{data:x,error:_}=await R.from("agencies").select("*").eq("id",s).single();if(_)throw _;l(x);const{data:p}=await R.from("agency_users").select("user_id").eq("agency_id",s).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(p!=null&&p.user_id){const{data:y}=await R.from("profiles").select("email").eq("id",p.user_id).maybeSingle(),a=y==null?void 0:y.email;console.log("[AgencyDetails] Registration email loaded:",a),b(a||null)}else console.log("[AgencyDetails] No agency user found");const{data:v}=await R.from("report_settings").select("*").eq("agency_id",s).single();m(v);const{data:h}=await R.from("subscriptions").select(`
17          *,
18          plans (name, price, billing_interval)
19        `).eq("agency_id",s).single();g(h)}catch(x){console.error("Error loading agency details:",x)}finally{t(!1)}};return e.jsx(wt,{open:!!s,onOpenChange:()=>c(),children:e.jsxs(St,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsxs(_t,{children:[e.jsx(Ct,{children:"Agency Details"}),e.jsx(Rt,{children:"Complete information about this agency"})]}),r?e.jsxs("div",{className:"space-y-4 mt-6",children:[e.jsx(rs,{className:"h-24 w-full"}),e.jsx(rs,{className:"h-32 w-full"}),e.jsx(rs,{className:"h-32 w-full"})]}):n?e.jsxs("div",{className:"space-y-6 mt-6",children:[e.jsx(j,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[n.logo_url?e.jsx("img",{src:n.logo_url,alt:n.name,className:"h-16 w-16 rounded-lg object-cover"}):e.jsx("div",{className:"h-16 w-16 bg-primary/10 rounded-lg flex items-center justify-center",children:e.jsx(Ee,{className:"h-8 w-8 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-xl font-bold",children:n.name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["/",n.slug]}),f&&e.jsxs("div",{className:"mt-2 flex items-center gap-2 px-3 py-2 bg-muted/50 rounded-md",children:[e.jsx(ie,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Registration Email"}),e.jsx("p",{className:"text-sm font-medium",children:f})]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[n.subdomain&&e.jsxs(H,{variant:"outline",children:[e.jsx(vs,{className:"h-3 w-3 mr-1"}),n.subdomain]}),n.custom_domain&&e.jsxs(H,{variant:"outline",children:[e.jsx(vs,{className:"h-3 w-3 mr-1"}),n.custom_domain]})]})]})]})}),e.jsxs("div",{children:[e.jsxs("h4",{className:"text-sm font-semibold mb-3 flex items-center gap-2",children:[e.jsx(zs,{className:"h-4 w-4"}),"Subscription"]}),e.jsx(j,{className:"p-4",children:d?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Plan"}),e.jsx("span",{className:"font-semibold",children:((w=d.plans)==null?void 0:w.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Price"}),e.jsxs("span",{className:"font-semibold",children:["$",(S=d.plans)==null?void 0:S.price,"/",(u=d.plans)==null?void 0:u.billing_interval]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Status"}),e.jsx(H,{variant:d.status==="active"?"default":"secondary",children:d.status})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Reports Used"}),e.jsx("span",{className:"font-semibold",children:d.reports_used})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No active subscription"})})]}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsxs("h4",{className:"text-sm font-semibold mb-3 flex items-center gap-2",children:[e.jsx(At,{className:"h-4 w-4"}),"Branding"]}),e.jsxs(j,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brand Name"}),e.jsx("span",{className:"font-semibold",children:o.brand_name||"—"})]}),e.jsx(He,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Demo Button Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-6 w-6 rounded border",style:{backgroundColor:o.demo_button_bg_color}}),e.jsx("span",{className:"text-sm",children:o.demo_button_bg_color})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"CTA Button Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-6 w-6 rounded border",style:{backgroundColor:o.cta_button_bg_color}}),e.jsx("span",{className:"text-sm",children:o.cta_button_bg_color})]})]})]})]}),e.jsxs("div",{children:[e.jsxs("h4",{className:"text-sm font-semibold mb-3 flex items-center gap-2",children:[e.jsx(ie,{className:"h-4 w-4"}),"Contact Information"]}),e.jsxs(j,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ie,{className:"h-4 w-4 mt-0.5 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"From Email"}),e.jsx("p",{className:"text-sm font-medium",children:o.from_email||"—"})]})]}),e.jsx(He,{}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Re,{className:"h-4 w-4 mt-0.5 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"From Name"}),e.jsx("p",{className:"text-sm font-medium",children:o.from_name||"—"})]})]}),e.jsx(He,{}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Tt,{className:"h-4 w-4 mt-0.5 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Business Phone"}),e.jsx("p",{className:"text-sm font-medium",children:o.business_phone||"—"})]})]}),e.jsx(He,{}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Lt,{className:"h-4 w-4 mt-0.5 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Business Address"}),e.jsx("p",{className:"text-sm font-medium",children:o.business_address_line1?e.jsxs(e.Fragment,{children:[o.business_address_line1,o.business_address_line2&&e.jsxs(e.Fragment,{children:[", ",o.business_address_line2]}),e.jsx("br",{}),o.business_city,", ",o.business_state," ",o.business_zip]}):"—"})]})]})]})]})]})]}):e.jsx("p",{className:"text-muted-foreground mt-6",children:"Agency not found"})]})})}
19function cr({agencyId:s,currentTier:c,onTierUpdated:r}){const[t,n]=i.useState(c),[l,o]=i.useState(!1),m=async()=>{if(t===c){Qe.info("No changes to apply");return}o(!0);try{const{error:d}=await R.from("subscriptions").update({manual_tier_override:!0,override_tier:t}).eq("agency_id",s).eq("status","active");if(d)throw d;Qe.success(`Manual tier override set to ${t}`),r()}catch(d){console.error("Error updating tier:",d),Qe.error(d.message||"Failed to update agency tier")}finally{o(!1)}};return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ms,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(ge,{value:t,onValueChange:n,children:[e.jsx(fe,{className:"w-[140px]",children:e.jsx(je,{})}),e.jsxs(be,{children:[e.jsx(B,{value:"basic",children:"Basic Tier"}),e.jsx(B,{value:"premium",children:"Premium Tier"})]})]}),e.jsx(Y,{onClick:m,disabled:l||t===c,size:"sm",variant:"outline",children:l?"Updating...":"Override"})]})}const dr=()=>{const[s,c]=i.useState({pending:0,processing:0,completed:0,failed:0}),[r,t]=i.useState([]),[n,l]=i.useState([]),[o,m]=i.useState(!1),[d,g]=i.useState(!1),[f,b]=i.useState(new Date),{toast:N}=ne(),w=async()=>{m(!0);try{const{data:h,error:y}=await R.from("report_jobs").select("status");if(y)throw y;const a={pending:0,processing:0,completed:0,failed:0};h==null||h.forEach(I=>{a[I.status]++}),c(a);const{data:k,error:D}=await R.from("report_jobs").select("id, job_type, error_message, retry_count, created_at, report_id").eq("status","failed").order("created_at",{ascending:!1}).limit(10);if(D)throw D;t(k||[]);const E=new Date(Date.now()-10*60*1e3).toISOString(),{data:$,error:T}=await R.from("rm_reports").select("id, business_name, agency_id, created_at, updated_at, error_message").eq("status","processing").lte("updated_at",E).order("created_at",{ascending:!1}).limit(20);if(T)throw T;l($||[]),b(new Date)}catch(h){console.error("Error fetching job metrics:",h)}finally{m(!1)}};i.useEffect(()=>{w();const h=setInterval(w,5e3);return()=>clearInterval(h)},[]);const S=async h=>{try{const{error:y}=await R.from("report_jobs").update({status:"pending",retry_count:0,scheduled_for:new Date().toISOString(),error_message:null}).eq("id",h);if(y)throw y;w()}catch(y){console.error("Error retrying job:",y)}},u=async()=>{g(!0);try{const{data:h,error:y}=await R.functions.invoke("schedule-job-processing");if(y)throw y;N({title:"Jobs Triggered",description:h!=null&&h.triggered?`Processing ${h.pendingJobs} pending job(s)`:"No pending jobs to process"}),setTimeout(w,1e3)}catch(h){console.error("Error processing jobs:",h),N({title:"Error",description:h.message||"Failed to trigger job processing",variant:"destructive"})}finally{g(!1)}},x=async h=>{try{const y={processing_state:{version:1,started_at:new Date().toISOString(),jobs:{}}};await R.from("rm_reports").update({status:"processing",error_message:null,report_data:y,updated_at:new Date().toISOString()}).eq("id",h);const{error:a}=await R.functions.invoke("rm-process-report",{body:{report_id:h}});if(a)throw a;N({title:"Restarted",description:`Report ${h.slice(0,8)} re-queued`}),w()}catch(y){N({title:"Restart failed",description:y.message||"Unknown error",variant:"destructive"})}},_=async h=>{try{const{error:y}=await R.from("rm_reports").update({status:"failed",error_message:"Manually marked failed by admin.",updated_at:new Date().toISOString()}).eq("id",h);if(y)throw y;N({title:"Marked failed",description:`Report ${h.slice(0,8)} flagged for refund/retry`}),w()}catch(y){N({title:"Action failed",description:y.message||"Unknown error",variant:"destructive"})}},p=s.pending+s.processing+s.completed+s.failed,v=p>0?(s.completed/p*100).toFixed(1):0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Job Queue Monitor"}),e.jsx("p",{className:"text-muted-foreground",children:"Real-time tracking of report generation jobs"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Last updated: ",f.toLocaleTimeString()]}),e.jsxs(Y,{onClick:u,size:"sm",disabled:d||s.pending===0,children:[e.jsx(Dt,{className:`h-4 w-4 mr-2 ${d?"animate-pulse":""}`}),"Process Jobs ",s.pending>0&&`(${s.pending})`]}),e.jsxs(Y,{onClick:w,size:"sm",variant:"outline",disabled:o,children:[e.jsx(ee,{className:`h-4 w-4 mr-2 ${o?"animate-spin":""}`}),"Refresh"]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(j,{children:[e.jsxs(W,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(V,{className:"text-sm font-medium",children:"Pending"}),e.jsx(pe,{className:"h-4 w-4 text-yellow-500"})]}),e.jsxs(O,{children:[e.jsx("div",{className:"text-2xl font-bold",children:s.pending}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Waiting in queue"})]})]}),e.jsxs(j,{children:[e.jsxs(W,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(V,{className:"text-sm font-medium",children:"Processing"}),e.jsx(ee,{className:"h-4 w-4 text-blue-500 animate-spin"})]}),e.jsxs(O,{children:[e.jsx("div",{className:"text-2xl font-bold",children:s.processing}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Currently running"})]})]}),e.jsxs(j,{children:[e.jsxs(W,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(V,{className:"text-sm font-medium",children:"Completed"}),e.jsx($e,{className:"h-4 w-4 text-green-500"})]}),e.jsxs(O,{children:[e.jsx("div",{className:"text-2xl font-bold",children:s.completed}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v,"% success rate"]})]})]}),e.jsxs(j,{children:[e.jsxs(W,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(V,{className:"text-sm font-medium",children:"Failed"}),e.jsx(Se,{className:"h-4 w-4 text-red-500"})]}),e.jsxs(O,{children:[e.jsx("div",{className:"text-2xl font-bold",children:s.failed}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Require attention"})]})]})]}),e.jsxs(Te,{children:[e.jsx(De,{className:"h-4 w-4"}),e.jsxs(Le,{children:[e.jsx("strong",{children:"Queue Configuration:"})," Processing up to 50 jobs concurrently every 30 seconds.",s.pending>0&&e.jsxs("span",{children:[" Estimated time for pending jobs: ~",Math.ceil(s.pending/50)*30,"s"]})]})]}),r.length>0&&e.jsxs(j,{children:[e.jsxs(W,{children:[e.jsx(V,{children:"Recent Failed Jobs"}),e.jsx(_e,{children:"Jobs that failed after maximum retries"})]}),e.jsx(O,{children:e.jsxs(oe,{children:[e.jsx(ce,{children:e.jsxs(Q,{children:[e.jsx(L,{children:"Job Type"}),e.jsx(L,{children:"Report ID"}),e.jsx(L,{children:"Error"}),e.jsx(L,{children:"Retries"}),e.jsx(L,{children:"Failed At"}),e.jsx(L,{children:"Action"})]})}),e.jsx(de,{children:r.map(h=>e.jsxs(Q,{children:[e.jsx(A,{children:e.jsx(H,{variant:"outline",children:h.job_type})}),e.jsxs(A,{className:"font-mono text-xs",children:[h.report_id.slice(0,8),"..."]}),e.jsx(A,{className:"max-w-md truncate",title:h.error_message,children:h.error_message||"Unknown error"}),e.jsx(A,{children:h.retry_count}
19),e.jsx(A,{children:new Date(h.created_at).toLocaleString()}),e.jsx(A,{children:e.jsxs(Y,{size:"sm",variant:"ghost",onClick:()=>S(h.id),children:[e.jsx(ee,{className:"h-3 w-3 mr-1"}),"Retry"]})})]},h.id))})]})})]}),n.length>0&&e.jsxs(j,{className:"border-yellow-500/50",children:[e.jsxs(W,{children:[e.jsxs(V,{className:"flex items-center gap-2",children:[e.jsx(De,{className:"h-5 w-5 text-yellow-500"}),"Stuck Review Matchup Reports (",n.length,")"]}),e.jsx(_e,{children:'Reports in "processing" for >10 min. The cron sweeper auto-retries every 30s; use these buttons to force action.'})]}),e.jsx(O,{children:e.jsxs(oe,{children:[e.jsx(ce,{children:e.jsxs(Q,{children:[e.jsx(L,{children:"Business"}),e.jsx(L,{children:"Report ID"}),e.jsx(L,{children:"Stuck For"}),e.jsx(L,{children:"Last Update"}),e.jsx(L,{className:"text-right",children:"Actions"})]})}),e.jsx(de,{children:n.map(h=>{const y=Math.round((Date.now()-new Date(h.created_at).getTime())/6e4);return e.jsxs(Q,{children:[e.jsx(A,{className:"font-medium",children:h.business_name}),e.jsxs(A,{className:"font-mono text-xs",children:[h.id.slice(0,8),"..."]}),e.jsx(A,{children:e.jsxs(H,{variant:y>45?"destructive":"outline",children:[y,"m"]})}),e.jsx(A,{className:"text-xs",children:new Date(h.updated_at).toLocaleTimeString()}),e.jsxs(A,{className:"text-right space-x-2",children:[e.jsxs(Y,{size:"sm",variant:"outline",onClick:()=>x(h.id),children:[e.jsx(ee,{className:"h-3 w-3 mr-1"}),"Restart"]}),e.jsxs(Y,{size:"sm",variant:"destructive",onClick:()=>_(h.id),children:[e.jsx(Se,{className:"h-3 w-3 mr-1"}),"Mark Failed"]})]})]},h.id)})})]})})]}),r.length===0&&s.failed===0&&e.jsxs(Te,{children:[e.jsx($e,{className:"h-4 w-4 text-green-500"}),e.jsx(Le,{children:"No failed jobs! The queue is running smoothly. 🎉"})]})]})};function mr(){const[s,c]=i.useState([]),[r,t]=i.useState([]),[n,l]=i.useState(!0);i.useEffect(()=>{o()},[]);const o=async()=>{try{l(!0);const{data:d,error:g}=await R.from("tier_analytics").select("*").order("tier",{ascending:!1});if(g)throw g;const{data:f,error:b}=await R.from("tier_job_performance").select("*").order("tier",{ascending:!1}).order("job_type");if(b)throw b;c(d||[]),t(f||[])}catch(d){console.error("Error loading analytics:",d),Qe.error("Failed to load tier analytics")}finally{l(!1)}},m=d=>d==="premium"?e.jsx(H,{className:"bg-gradient-to-r from-yellow-500 to-orange-500",children:"⭐ Premium"}):e.jsx(H,{variant:"secondary",children:"📦 Basic"});return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ge,{className:"h-8 w-8 animate-spin"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Tier Analytics"}),e.jsx("p",{className:"text-muted-foreground",children:"Monitor subscription tiers, usage, and performance metrics"})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:s.map(d=>{var g;return e.jsxs(j,{children:[e.jsxs(W,{children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs(V,{className:"flex items-center gap-2",children:[m(d.tier),"Tier Overview"]})}),e.jsx(_e,{children:"Last 30 days performance"})]}),e.jsxs(O,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Re,{className:"h-4 w-4"}),"Agencies"]}),e.jsx("div",{className:"text-2xl font-bold",children:d.agency_count})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ye,{className:"h-4 w-4"}),"Total Reports"]}),e.jsx("div",{className:"text-2xl font-bold",children:d.total_reports})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ve,{className:"h-4 w-4"}),"Last 7 Days"]}),e.jsx("div",{className:"text-2xl font-bold",children:d.reports_last_7_days})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ve,{className:"h-4 w-4"}),"Last 30 Days"]}),e.jsx("div",{className:"text-2xl font-bold",children:d.reports_last_30_days})]})]}),e.jsxs("div",{className:"pt-4 border-t space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Unlocked Reports"}),e.jsx("span",{className:"font-medium",children:d.unlocked_reports})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg Customer Value"}),e.jsxs("span",{className:"font-medium",children:["$",((g=d.avg_customer_value)==null?void 0:g.toFixed(2))||"0.00"]})]})]})]})]},d.tier)})}),e.jsxs(j,{children:[e.jsxs(W,{children:[e.jsx(V,{children:"Job Performance by Tier"}),e.jsx(_e,{children:"Processing statistics for the last 30 days"})]}),e.jsx(O,{children:e.jsx("div",{className:"space-y-4",children:["premium","basic"].map(d=>{const g=r.filter(f=>f.tier===d);return g.length===0?null:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center gap-2 pb-2 border-b",children:m(d)}),e.jsx("div",{className:"grid gap-3",children:g.map(f=>{var b,N;return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium capitalize",children:f.job_type.replace(/_/g," ")}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pe,{className:"h-3 w-3"}),((b=f.avg_duration_seconds)==null?void 0:b.toFixed(1))||"0.0","s avg"]}),e.jsxs("span",{children:["Retries: ",((N=f.avg_retries)==null?void 0:N.toFixed(2))||"0.00"]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1 text-green-600",children:[e.jsx($e,{className:"h-4 w-4"}),f.completed_jobs]}),e.jsxs("div",{className:"flex items-center gap-1 text-yellow-600",children:[e.jsx(Be,{className:"h-4 w-4"}),f.pending_jobs]}),e.jsxs("div",{className:"flex items-center gap-1 text-red-600",children:[e.jsx(Se,{className:"h-4 w-4"}),f.failed_jobs]})]})]},`${f.tier}-${f.job_type}`)})})]},d)})})})]})]})}const xr=()=>{const{toast:s}=ne(),[c,r]=i.useState([]),[t,n]=i.useState(!0),[l,o]=i.useState(""),[m,d]=i.useState("all"),[g,f]=i.useState("all"),[b,N]=i.useState([]),[w,S]=i.useState("all");i.useEffect(()=>{u(),x()},[]),i.useEffect(()=>{x()},[m,g,w]);const u=async()=>{try{const{data:a,error:k}=await R.from("agencies").select("id, name").order("name");if(k)throw k;N(a||[])}catch(a){console.error("Error loading agencies:",a)}},x=async()=>{try{let a=R.from("audit_logs").select(`
20          *,
21          agencies (
22            id,
23            name
24          ),
25          profiles:user_id (
26            full_name,
27            email
28          )
29        `).order("created_at",{ascending:!1}).limit(100);m!=="all"&&(a=a.eq("action",m)),g!=="all"&&(a=a.eq("resource_type",g)),w!=="all"&&(a=a.eq("agency_id",w));const{data:k,error:D}=await a;if(D)throw D;r(k||[])}catch(a){s({title:"Error loading audit logs",description:a.message,variant:"destructive"})}finally{n(!1)}},_=a=>{switch(a){case"create":return e.jsx(ys,{className:"h-4 w-4"});case"update":return e.jsx(ws,{className:"h-4 w-4"});case"soft_delete":return e.jsx(as,{className:"h-4 w-4"});case"hard_delete":return e.jsx(as,{className:"h-4 w-4 text-destructive"});case"restore":return e.jsx(Pt,{className:"h-4 w-4"});default:return e.jsx(ye,{className:"h-4 w-4"})}},p=a=>{const k={create:"bg-green-500/10 text-green-500 border-green-500/20",update:"bg-blue-500/10 text-blue-500 border-blue-500/20",soft_delete:"bg-orange-500/10 text-orange-500 border-orange-500/20",hard_delete:"bg-red-500/10 text-red-500 border-red-500/20",restore:"bg-purple-500/10 text-purple-500 border-purple-500/20"};return e.jsx(H,{variant:"outline",className:k[a]||"",children:e.jsxs("span",{className:"flex items-center gap-1",children:[_(a),a.replace("_"," ")]})})},v=a=>{switch(a){case"reports":return e.jsx(ye,{className:"h-4 w-4"});case"leads":return e.jsx(ie,{className:"h-4 w-4"});case"report_settings":return e.jsx(kt,{className:"h-4 w-4"});default:return e.jsx(ye,{className:"h-4 w-4"})}},h=()=>{const a=[["Timestamp","Agency","User","Action","Resource","Resource ID"].join(","),...c.map($=>{var T,I;return[new Date($.created_at).toISOString(),((T=$.agencies)==null?void 0:T.name)||"N/A",((I=$.profiles)==null?void 0:I.email)||"System",$.action,$.resource_type,$.resource_id].join(",")})].join(`
30`),k=new Blob([a],{type:"text/csv"}),D=window.URL.createObjectURL(k),E=document.createElement("a");E.href=D,E.download=`audit-logs-${new Date().toISOString()}.csv`,E.click(),window.URL.revokeObjectURL(D),s({title:"Export complete",description:"Audit logs exported successfully"})},y=c.filter(a=>{var D,E,$;const k=l.toLowerCase();return((D=a.agencies)==null?void 0:D.name.toLowerCase().includes(k))||
30((E=a.profiles)==null?void 0:E.email.toLowerCase().includes(k))||a.action.toLowerCase().includes(k)||a.resource_type.toLowerCase().includes(k)||(($=a.resource_id)==null?void 0:$.toLowerCase().includes(k))});return t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 border-4 border-primary/30 border-t-primary rounded-full animate-spin"})}):e.jsx(j,{className:"p-6 bg-gradient-card shadow-card",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Audit Logs"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Complete activity trail for all agencies"})]}),e.jsxs(Y,{onClick:h,variant:"outline",size:"sm",children:[e.jsx(Fs,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Pe,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ue,{placeholder:"Search logs...",value:l,onChange:a=>o(a.target.value),className:"pl-10"})]}),e.jsxs(ge,{value:w,onValueChange:S,children:[e.jsxs(fe,{children:[e.jsx(Ee,{className:"h-4 w-4 mr-2"}),e.jsx(je,{placeholder:"All Agencies"})]}),e.jsxs(be,{children:[e.jsx(B,{value:"all",children:"All Agencies"}),b.map(a=>e.jsx(B,{value:a.id,children:a.name},a.id))]})]}),e.jsxs(ge,{value:m,onValueChange:d,children:[e.jsxs(fe,{children:[e.jsx(Ns,{className:"h-4 w-4 mr-2"}),e.jsx(je,{placeholder:"All Actions"})]}),e.jsxs(be,{children:[e.jsx(B,{value:"all",children:"All Actions"}),e.jsx(B,{value:"create",children:"Create"}),e.jsx(B,{value:"update",children:"Update"}),e.jsx(B,{value:"soft_delete",children:"Soft Delete"}),e.jsx(B,{value:"hard_delete",children:"Hard Delete"}),e.jsx(B,{value:"restore",children:"Restore"})]})]}),e.jsxs(ge,{value:g,onValueChange:f,children:[e.jsxs(fe,{children:[e.jsx(Ns,{className:"h-4 w-4 mr-2"}),e.jsx(je,{placeholder:"All Resources"})]}),e.jsxs(be,{children:[e.jsx(B,{value:"all",children:"All Resources"}),e.jsx(B,{value:"reports",children:"Reports"}),e.jsx(B,{value:"leads",children:"Leads"}),e.jsx(B,{value:"report_settings",children:"Settings"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs(j,{className:"p-4 bg-background",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(pe,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Actions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:y.length})]}),e.jsxs(j,{className:"p-4 bg-background",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ys,{className:"h-4 w-4 text-green-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Creates"})]}),e.jsx("p",{className:"text-2xl font-bold",children:y.filter(a=>a.action==="create").length})]}),e.jsxs(j,{className:"p-4 bg-background",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(as,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Deletes"})]}),e.jsx("p",{className:"text-2xl font-bold",children:y.filter(a=>a.action==="soft_delete"||a.action==="hard_delete").length})]}),e.jsxs(j,{className:"p-4 bg-background",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ws,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Updates"})]}),e.jsx("p",{className:"text-2xl font-bold",children:y.filter(a=>a.action==="update").length})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(oe,{children:[e.jsx(ce,{children:e.jsxs(Q,{children:[e.jsx(L,{children:"Timestamp"}),e.jsx(L,{children:"Agency"}),e.jsx(L,{children:"User"}),e.jsx(L,{children:"Action"}),e.jsx(L,{children:"Resource"}),e.jsx(L,{children:"Resource ID"})]})}),e.jsx(de,{children:y.length===0?e.jsx(Q,{children:e.jsxs(A,{colSpan:6,className:"text-center py-12",children:[e.jsx(ye,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4"}),e.jsx("p",{className:"text-lg font-semibold mb-2",children:"No audit logs found"}),e.jsx("p",{className:"text-muted-foreground",children:l||m!=="all"||g!=="all"?"Try adjusting your filters":"Activity will appear here as agencies use the platform"})]})}):y.map(a=>{var k,D,E;return e.jsxs(Q,{children:[e.jsx(A,{children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium",children:Bs(new Date(a.created_at),{addSuffix:!0})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(a.created_at).toLocaleStr
30ing()})]})}),e.jsx(A,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ee,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm",children:((k=a.agencies)==null?void 0:k.name)||"N/A"})]})}),e.jsx(A,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($s,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm",children:((D=a.profiles)==null?void 0:D.email)||"System"})]})}),e.jsx(A,{children:p(a.action)}),e.jsx(A,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[v(a.resource_type),e.jsx("span",{className:"text-sm",children:a.resource_type})]})}),e.jsx(A,{children:e.jsxs("code",{className:"text-xs bg-muted px-2 py-1 rounded",children:[(E=a.resource_id)==null?void 0:E.substring(0,8),"..."]})})]},a.id)})})]})}),y.length>0&&e.jsxs("div",{className:"text-sm text-muted-foreground text-center",children:["Showing ",y.length," of ",c.length," total audit logs (last 100)"]})]})})},ur=()=>{const{toast:s}=ne(),[c,r]=i.useState(!1),[t,n]=i.useState(null),l=async()=>{r(!0),n(null);try{console.log("[SystemTools] Starting AI summary backfill...");const{data:o,error:m}=await R.functions.invoke("backfill-ai-summaries");if(m)throw console.error("[SystemTools] Backfill error:",m),new Error(m.message||"Failed to invoke backfill function");if(!o)throw new Error("No data returned from backfill function");if(console.log("[SystemTools] Backfill response:",o),!o.success)throw new Error(o.error||"Backfill process failed");if(!o.results){s({title:"No Reports to Process",description:o.message||"All reports already have AI summaries"});return}n(o.results),s({title:"Backfill Complete",description:`Successfully generated AI summaries for ${o.results.successful||0} reports`})}catch(o){console.error("[SystemTools] Error:",o),s({title:"Backfill Failed",description:o.message||"An unknown error occurred",variant:"destructive"})}finally{r(!1)}};return e.jsx("div",{className:"space-y-6",children:e.jsx(j,{className:"p-6 bg-gradient-card shadow-card",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"p-3 bg-primary/10 rounded-lg",children:e.jsx(is,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-xl font-bold mb-2",children:"AI Summary Backfill"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Generate and store AI summaries for all reports that are missing them. This process will:"}),e.jsxs("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1 mb-4",children:[e.jsx("li",{children:"Find all reports without strategic insights"}),e.jsx("li",{children:"Generate AI-powered summaries using existing report data"}),e.jsx("li",{children:"Store insights directly in the database"}),e.jsx("li",{children:"Skip reports with incomplete data"})]}),e.jsx(Y,{onClick:l,disabled:c,className:"gap-2",children:c?e.jsxs(e.Fragment,{children:[e.jsx(Ge,{className:"h-4 w-4 animate-spin"}),"Processing Reports..."]}):e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4"}),"Run Backfill"]})})]})]}),t&&e.jsxs(Te,{className:"mt-6",children:[e.jsx(Be,{className:"h-4 w-4"}),e.jsx(Le,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"font-semibold",children:"Backfill Results:"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(le,{className:"h-4 w-4 text-success"}),e.jsxs("span",{children:["Successful: ",t.successful]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{className:"h-4 w-4 text-destructive"}),e.jsxs("span",{children:["Failed: ",t.failed]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"h-4 w-4 text-warning"}),e.jsxs("span",{children:["Skipped: ",t.skipped]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(is,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:["Total: ",t.total]})]})]}),t.errors&&t.errors.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"font-semibold text-destructive mb-2",children:"Errors:"}),e.jsx("div",{className:"space-y-1 text-xs max-h-40 overflow-y-auto",children:t.errors.map((o,m)=>e.jsxs("div",{className:"bg-destructive/10 p-2 rounded",children:[e.jsx("p",{className:"font-medium",children:o.businessName}),e.jsx("p",{className:"text-muted-foreground",children:o.error})]},m))})]})]})})]})]})})})},hr=({tier:s,stage:c})=>{const{data:r}=Os({queryKey:["super-admin-report-settings"],queryFn:async()=>{const{data:p}=await R.from("agencies").select("id").eq("slug","reviewroi").maybeSingle();if(!p)return null;const{data:v}=await R.from("report_settings").select("*").eq("agency_id",p.id).maybeSingle();return v}}),t={businessName:"Bothell Dental Clinic",businessCity:"Bothell",businessState:"WA",businessAddress:"18115 Bothell Way NE, Bothell, WA 98011",businessPhone:"(425) 486-9011",firstName:"John",rating:4.1,reviewCount:8,reviewScore:28,visibilityScore:s==="premium"?82:void 0,reviewVisibilityScore:42,reviewVolumeRank:4,reviewVolumeTotal:10,averageRank:s==="premium"?2.2:void 0,rankingLocations:s==="premium"?5:void 0,totalLocations:s==="premium"?8:void 0},o=`email_prospect_${c==="optin"?"optin":"initial"}_${s==="basic"?"basic":"premium"}`,m=p=>{var v,h,y;return((y=(h=(v=p==null?void 0:p.replace(/\{business_name\}/g,t.businessName))==null?void 0:v.replace(/\{first_name\}/g,t.firstName))==null?void 0:h.replace(/\{business_city\}/g,t.businessCity))==null?void 0:y.replace(/\{business_state\}/g,t.businessState))||""},d=m((r==null?void 0:r[`${o}_subject`])||""),g=m((r==null?void 0:r[`${o}_title`])||""),f=m((r==null?void 0:r[`${o}_greeting`])||""),b=m((r==null?void 0:r[`${o}_intro`])||"");m((r==null?void 0:r[`${o}_why_matters`])||"");const N=m((r==null?void 0:r[`${o}_cta_text`])||""),w=m((r==null?void 0:r[`${o}_closing`])||""),S=m((r==null?void 0:r[`${o}_signature`])||""),u=(r==null?void 0:r.email_button_color)||"#667eea",x=(r==null?void 0:r.cta_button_text_color)||"#FFFFFF",_=()=>s==="basic"?`Your 4.1-star rating with only ${t.reviewCount} reviews is pulling your overall review score down to a critical ${t.reviewScore}%. Addressing this low review count now could significantly boost customer trust and your visibility!`:`Your remarkable ${t.visibilityScore}% visibility score and average rank of ${t.averageRank} against competitors are fantastic, but your 4.1-star rating with only ${t.reviewCount} reviews is pulling your overall review score down to a critical ${t.reviewScore}%. Addressing this low review count now could significantly boost customer trust and propel your visibility even higher!`;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(j,{className:"p-4 bg-blue-50 border-blue-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(cs,{className:"h-5 w-5 text-blue-600 mt-0.5"}),e.jsxs("div",{className:"space-y-2 flex-1",children:[e.jsx("h4",{className:"font-semibold text-blue-900",children:"Template Data Structure"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-blue-800",children:"Template:"})," ",e.jsxs(H,{variant:"outline",className:"ml-1",children:["email_prospect_",c,"_",s,"_*"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-blue-800",children:"AI Insights:"})," ",e.jsx(H,{variant:"outline",className:"ml-1",children:s==="premium"?"Full ranking data":"Review data only"})]})]})]})]})}),e.jsxs(j,{className:"overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-br from-gray-50 to-gray-100 p-4 border-b",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:"Subject Line:"}),e.jsx("p",{className:"font-semibold",children:d||"Loading..."})]}),e.jsxs("div",{className:"p-6 bg-white",style:{maxWidth:"800px",margin:"0 auto"},children:[e.jsx("div",{style:{background:"linear-gradient(135deg, #667eea 0%, #764ba2 100%)",color:"white",padding:"30px",borderRadius:"8px 8px 0 0",textAlign:"center"},children:e.jsxs("h1",{style:{margin:0,fontSize:"24px"},children:["📊 ",g||"Loading..."]})}),e.jsxs("div",{style:{background:"#ffffff",padding:"30px",border:"1px solid #e5e7eb",borderTop:"none"},children:[e.jsx("p",{style:{margin:"0 0 16px 0",lineHeight:"1.6"},children:f}),e.jsx("p",{style:{margin:"0 0 16px 0",lineHeight:"1.6"},children:b}),e.jsxs("div",{style:{background:"#eff6ff",borderLeft:"4px solid #3b82f6",padding:"15px",margin:"20px 0"},children:[e.jsx("p",{style:{margin:"0 0 8px 0",color:"#1e40af",fontWeight:500},children:"📊 Quick Insight"}),e.jsx("p",{style:{margin:0,color:"#1e3a8a",lineHeight:"1.6"},children:_()})]}),e.jsxs("div",{style:{background:"#fef3c7",borderLeft:"4px solid #f59e0b",padding:"15px",margin:"15px 0"},children:[e.jsx("strong",{style:{display:"block",marginBottom:"8px"},children:"Business Analyzed:"}),e.jsxs("span",{style:{display:"block",lineHeight:"1.6"},children:[t.businessName,e.jsx("br",{}),t.businessAddress]})]}
30),e.jsx("div",{style:{display:"flex",gap:"15px",margin:"20px 0"},children:s==="premium"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{flex:1,background:"#f9fafb",borderLeft:"4px solid #667eea",padding:"15px"},children:[e.jsxs("p",{style:{fontSize:"32px",fontWeight:"bold",color:"#667eea",margin:0},children:[t.reviewScore,"/100"]}),e.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"5px 0 0 0"},children:"Review Score"})]}),e.jsxs("div",{style:{flex:1,background:"#f9fafb",borderLeft:"4px solid #10b981",padding:"15px"},children:[e.jsxs("p",{style:{fontSize:"32px",fontWeight:"bold",color:"#10b981",margin:0},children:[t.visibilityScore,"/100"]}),e.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"5px 0 0 0"},children:"Visibility Score"}),e.jsxs("p",{style:{fontSize:"12px",color:"#9ca3af",margin:"5px 0 0 0"},children:[t.rankingLocations," of ",t.totalLocations," locations"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{flex:1,background:"#f9fafb",borderLeft:"4px solid #667eea",padding:"15px"},children:[e.jsxs("p",{style:{fontSize:"32px",fontWeight:"bold",color:"#667eea",margin:0},children:[t.reviewScore,"/100"]}),e.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"5px 0 0 0"},children:"Review Score"})]}),e.jsxs("div",{style:{flex:1,background:"#f9fafb",borderLeft:"4px solid #10b981",padding:"15px"},children:[e.jsxs("p",{style:{fontSize:"32px",fontWeight:"bold",color:"#10b981",margin:0},children:[t.reviewVisibilityScore,"/100"]}),e.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"5px 0 0 0"},children:"Review Visibility"}),e.jsxs("p",{style:{fontSize:"12px",color:"#9ca3af",margin:"5px 0 0 0"},children:["Ranked #",t.reviewVolumeRank," of ",t.reviewVolumeTotal]})]})]})}),s==="premium"&&e.jsxs("div",{style:{margin:"20px 0"},children:[e.jsx("div",{style:{background:"#fef3c7",borderRadius:"10px",padding:"18px 20px",marginBottom:"10px"},children:e.jsxs("div",{style:{display:"flex",justifyContent:"space-between"},children:[e.jsx("span",{style:{color:"#92400e",fontWeight:600},children:"Average Ranking"}),e.jsx("span",{style:{color:"#78350f",fontWeight:"bold",fontSize:"18px"},children:t.averageRank})]})}),e.jsxs("div",{style:{background:"#dbeafe",borderRadius:"10px",padding:"18px 20px"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between"},children:[e.jsx("span",{style:{color:"#1e40af",fontWeight:600},children:"Current Rating"}),e.jsxs("span",{style:{color:"#1e3a8a",fontWeight:"bold",fontSize:"18px"},children:[t.rating," ⭐"]})]}),e.jsxs("div",{style:{textAlign:"right",color:"#60a5fa",fontSize:"14px",marginTop:"4px"},children:[t.reviewCount," total reviews"]})]})]}),e.jsx("div",{style:{textAlign:"center",margin:"30px 0"},children:e.jsx("a",{href:"#",style:{display:"inline-block",background:u,color:x,padding:"14px 32px",textDecoration:"none",borderRadius:"6px",fontWeight:600},children:N})}),e.jsx("p",{style:{margin:"20px 0 0 0",lineHeight:"1.6"},children:w}),e.jsx("p",{style:{margin:"16px 0 0 0",lineHeight:"1.6",whiteSpace:"pre-wrap"},children:S})]}),e.jsx("div",{style:{background:"#f9fafb",padding:"20px",borderRadius:"0 0 8px 8px",textAlign:"center",fontSize:"12px",color:"#6b7280"},children:e.jsx("p",{style:{margin:0},children:"My Review Report"})})]})]})]})},pr=({tier:s,stage:c})=>{const{data:r}=Os({queryKey:["super-admin-report-settings-admin"],queryFn:async()=>{const{data:f}=await R.from("agencies").select("id").eq("slug","reviewroi").maybeSingle();if(!f)return null;const{data:b}=await R.from("report_settings").select("*").eq("agency_id",f.id).maybeSingle();return b}}),t={businessName:"Bothell Dental Clinic",businessCity:"Bothell",businessState:"WA",businessAddress:"18115 Bothell Way NE, Bothell, WA 98011",businessPhone:"(425) 486-9011",leadName:"John Smith",leadEmail:"[email protected]",leadPhone:"(206) 555-1234",hotScore:67,leadQuality:"Hot",leadColor:"#DC2626",rating:4.1,reviewCount:8,reviewScore:28,visibilityScore:s==="premium"?82:void 0,reviewVisibilityScore:42,reviewVolumeRank:4,reviewVolumeTotal:10,averageRank:s==="premium"?2.2:void 0,rankingLocations:s==="premium"?5:void 0,totalLocations:s==="premium"?8:void 0},o=`admin_email_${c==="optin"?"optin":"initial"}_${s==="basic"?"basic":"premium"}`,m=(r==null?void 0:r[`${o}_subject`])||"",d=(r==null?void 0:r[`${o}_header`])||"",g=()=>`${m}: ${t.businessName} - ${t.leadQuality} Lead`;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(j,{className:"p-4 bg-purple-50 border-purple-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(cs,{className:"h-5 w-5 text-purple-600 mt-0.5"}),e.jsxs("div",{className:"space-y-2 flex-1",children:[e.jsx("h4",{className:"font-semibold text-purple-900",children:"Admin Notification Data"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-purple-800",children:"Recipients:"})," ",e.jsx(H,{variant:"outline",className:"ml-1",children:"notification_emails or agency users"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-purple-800",children:"Hot Score:"})," ",e.jsxs(H,{variant:"outline",className:"ml-1",children:[t.hotScore," (",t.leadQuality,")"]})]})]})]})]})}),e.jsxs(j,{className:"overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-br from-gray-50 to-gray-100 p-4 border-b",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:"Subject Line:"}),e.jsx("p",{className:"font-semibold",children:g()})]}),e.jsxs("div",{className:"p-6 bg-white",style:{maxWidth:"800px",margin:"0 auto"},children:[e.jsxs("div",{style:{background:"linear-gradient(135deg, #667eea 0%, #764ba2 100%)",color:"white",padding:"40px 30px",textAlign:"center"},children:[e.jsx("h1",{style:{margin:0,fontSize:"32px",fontWeight:"bold",letterSpacing:"-0.5px"},children:d||"Loading..."}),e.jsx("p",{style:{margin:"10px 0 0",color:"rgba(255, 255, 255, 0.9)",fontSize:"14px"},children:new Date().toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})})]}),e.jsx("div",{style:{padding:"30px 30px 20px",textAlign:"center"},children:e.jsxs("div",{style:{display:"inline-block",backgroundColor:t.leadColor,color:"white",padding:"12px 24px",borderRadius:"25px",fontWeight:"bold",fontSize:"16px",boxShadow:`0 4px 12px ${t.leadColor}40`},children:[t.leadQuality," Lead · Score: ",t.hotScore]})}),e.jsx("div",{style:{padding:"0 30px 25px"},children:e.jsxs("div",{style:{background:"linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%)",borderRadius:"12px",padding:"25px",borderLeft:"5px solid #667eea"},children:[e.jsx("h2",{style:{color:"#1f2937",fontSize:"24px",margin:"0 0 15px",fontWeight:"bold"},children:t.businessName}),e.jsxs("p",{style:{color:"#6b7280",margin:"0 0 8px",fontSize:"14px"},children:[e.jsx("span",{style:{marginRight:"8px"},children:"📍"})," ",t.businessCity,","," ",t.businessState]}),e.jsx("p",{style:{color:"#6b7280",margin:"0 0 8px",fontSize:"14px",lineHeight:"1.5"},children:t.businessAddress}),e.jsxs("p",{style:{color:"#6b7280",margin:0,fontSize:"14px"},children:[e.jsx("span",{style:{marginRight:"8px"},children:"📞"})," ",t.businessPhone]})]})}),e.jsxs("div",{style:{padding:"0 30px 25px"},children:[e.jsx("h3",{style:{color:"#1f2937",fontSize:"18px",margin:"0 0 20px",fontWeight:"bold"},children:"📊 Key Performance Metrics"}),e.jsx("div",{style:{display:"flex",gap:"12px",marginBottom:"12px"},children:s==="premium"?e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{flex:1},children:e.jsxs("div",{style:{background:"linear-gradient(135deg, #10b981 0%, #059669 100%)",borderRadius:"10px",padding:"20px",textAlign:"center"},children:[e.jsx("div",{style:{color:"rgba(255, 255, 255, 0.9)",fontSize:"14px",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.5px",marginBottom:"8px"},children:"Visibility Score"}),e.jsx("div",{style:{color:"#ffffff",fontSize:"36px",fontWeight:"bold",lineHeight:1},children:t.visibilityScore}),e.jsxs("div",{style:{color:"rgba(255, 255, 255, 0.8)",fontSize:"14px",marginTop:"6px"},children:["out of 100 · ",t.rankingLocations," of ",t.totalLocations," ","locations"]})]})}),e.jsx("div",{style:{flex:1},children:e.jsxs("div",{style:{background:"linear-gradient(135deg, #f59e0b 0%, #d97706 100%)",borderRadius:"10px",padding:"20px",textAlign:"center"},children:[e.jsx("div",{style:{color:"rgba(255, 255, 255, 0.9)",fontSize:"14px",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.5px",marginBottom:"8px"},children:"Review Score"}),e.jsx("div",{style:{color:"#ffffff",fontSize:"36px",fontWeight:"bold",lineHeight:1},children:t.reviewScore}),e.jsxs("div",{style:{color:"rgba(255, 255, 255, 0.8)",fontSize:"14px",marginTop:"6px"},children:["out of 100 · ",t.reviewCount," reviews"]})]})})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{flex:1},children:e.jsxs("div",{style:{background:"linear-gradient(135deg, #10b981 0%, #059669 100%)",borderRadius:"10px",padding:"20px",textAlign:"center"},children:[e.jsx("div",{style:{color:"rgba(255, 255, 255, 0.9)",fontSize:"14px",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.5px",marginBottom:"8px"},children:"Review Visibility"}),e.jsx("div",{style:{color:"#ffffff",fontSize:"36px",fontWeight:"bold",lineHeight:1},children:t.reviewVisibilityScore}),e.jsx("div",{style:{color:"rgba(255, 255, 255, 0.8)",fontSize:"14px",marginTop:"6px"},children:"out of 100"}),e.jsxs("div",{style:{color:"rgba(255, 255, 255, 0.9)",fontSize:"14px",fontWeight:600,marginTop:"12px",paddingTop:"12px",borderTop:"1px solid rgba(255, 255, 255, 0.2)"},children:["Ranked #",t.reviewVolumeRank," of ",t.reviewVolumeTotal]}),e.jsx("div",{style:{color:"rgba(255, 255, 255, 0.7)",fontSize:"12px"},children:"based on review volume"})]})}),e.jsx("div",{style:{flex:1},children:e.jsxs("div",{style:{background:"linear-gradient(135deg, #f59e0b 0%, #d97706 100%)",borderRadius:"10px",padding:"20px",textAlign:"center"},children:[e.jsx("div",{style:{color:"rgba(255, 255, 255, 0.9)",fontSize:"14px",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.5px",marginBottom:"8px"},children:"Review Score"}),e.jsx("div",{style:{color:"#ffffff",fontSize:"36px",fontWeight:"bold",lineHeight:1},children:t.reviewScore}),e.jsxs("div",{style:{color:"rgba(255, 255, 255, 0.8)",fontSize:"14px",marginTop:"6px"},children:["out of 100 · ",t.reviewCount," reviews"]})]})})]})}),s==="premium"&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[e.jsx("div",{style:{backgroundColor:"#fef3c7",borderRadius:"10px",padding:"18px 20px"},children:e.jsxs("div",{style:{display:"flex",justifyContent:"space-between"},children:[e.jsx("span",{style:{color:"#92400e",fontWeight:600,fontSize:"14px"},children:"Average Ranking"}),e.jsx("span",{style:{color:"#78350f",fontWeight:"bold",fontSize:"16px"},children:t.averageRank})]})}),e.jsx("div",{style:{backgroundColor:"#dbeafe",borderRadius:"10px",padding:"18px 20px"},children:e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("span",{style:{color:"#1e40af",fontWeight:600,fontSize:"14px"},children:"Current Rating"}),e.jsxs("div",{style:{textAlign:"right"},children:[e.jsxs("span",{style:{color:"#1e3a8a",fontWeight:"bold",fontSize:"16px"},children:[t.rating," ⭐"]}),e.jsxs("div",{style:{color:"#60a5fa",fontSize:"12px",marginTop:"4px"},children:[t.reviewCount," total reviews"]})]})]})})]})]}),c==="optin"&&e.jsx("div",{style:{padding:"0 30px 25px"},children:e.jsxs("div",{style:{backgroundColor:"#f0fdf4",borderLeft:"4px solid #10b981",padding:"20px",borderRadius:"10px"},children:[e.jsx("h3",{style:{margin:"0 0 15px",color:"#1f2937",fontSize:"16px",fontWeight:"bold"},children:"💬 Contact Information"}),e.jsxs("p",{style:{margin:"8px 0",color:"#4b5563",fontSize:"14px"},children:[e.jsx("strong",{style:{color:"#1f2937"},children:"Name:"})," ",t.leadName]}),e.jsxs("p",{style:{margin:"8px 0",color:"#4b5563",fontSize:"14px"},children:[e.jsx("strong",{style:{color:"#1f2937"},children:"Email:"})," ",e.jsx("a",{href:`mailto:${t.leadEmail}`,style:{color:"#667eea",textDecoration:"none"},children:t.leadEmail})]}),e.jsxs("p",{style:{margin:"8px 0",color:"#4b5563",fontSize:"14px"},children:[e.jsx("strong",{style:{color:"#1f2937"},children:"Phone:"})," ",e.jsx("a",{href:`tel:${t.leadPhone}`,style:{color:"#667eea",textDecoration:"none"},children:t.leadPhone})]})]})}),e.jsxs("div",{style:{padding:"0 30px 35px"},children:[e.jsxs("div",{style:{display:"flex",gap:"16px"},children:[e.jsx("div",{style:{flex:1,textAlign:"center"},children:e.jsx("a",{href:"#",title:"Links to: /report/{report.id}",style:{display:"inline-block",background:"linear-gradient(135deg, #10b981 0%, #059669 100%)",color:"white",textDecoration:"none",padding:"16px 24px",borderRadius:"8px",fontWeight:"bold",fontSize:"14px",boxShadow:"0 4px 15px rgba(16, 185, 129, 0.4)",width:"100%"},children:"📊 View Report"})}),e.jsx("div",{style:{flex:1,textAlign:"center"},children:e.jsx("a",{href:"#",title:"Links to: https://reviewroi.ai/auth",style:{display:"inline-block",background:"linear-gradient(135deg, #667eea 0%, #764ba2 100%)",color:"white",textDecoration:"none",padding:"16px 24px",borderRadius:"8px",fontWeight:"bold",fontSize:"14px",boxShadow:"0 4px 15px rgba(102, 126, 234, 0.4)",width:"100%"},children:"👥 Lead Dashboard"})})]}),e.jsx("p",{style:{margin:"12px 0 0",fontSize:"12px",color:"#6b7280",textAlign:"center"},children:"View Report links to specific report • Lead Dashboard links to https://reviewroi.ai/auth"})]}),e.jsxs("div",{style:{backgroundColor:"#f9fafb",padding:"25px 30px",textAlign:"center",borderTop:"1px solid #e5e7eb"},children:[e.jsx("p",{style:{margin:"0 0 8px",color:"#9ca3af",fontSize:"14px"},children:e.jsx("a",{href:"#",style:{color:"#667eea",textDecoration:"none",fontWeight:500},children:"Manage notification preferences"})}),e.jsx("p",{style:{margin:"0 0 8px",color:"#d1d5db",fontSize:"14px"},children:"ReviewROI · Automated Lead Notification"}),e.jsx("p",{style:{margin:0,color:"#9ca3af",fontSize:"12px"},children:e.jsx("a",{href:"#",style:{color:"#9ca3af",textDecoration:"underline"},children:"Unsubscribe"})})]})]})]})]})},gr=()=>{const[s,c]=i.useState("basic"),[r,t]=i.useState("initial");return e.jsxs("div",{className:"space-y-6",children:[e.jsx(j,{className:"p-6 bg-gradient-to-br from-primary/5 via-background to-accent/5",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Email Templates"}),e.jsx("p",{className:"text-muted-foreground",children:"Visual preview of all email templates with real data structure"})]}),e.jsx(ie,{className:"h-12 w-12 text-primary/20"})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(j,{className:"p-4",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Ss,{className:"h-4 w-4"}),"Select Tier"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("button",{onClick:()=>c("basic"),className:`flex-1 p-3 rounded-lg border-2 transition-all ${s==="basic"?"border-primary bg-primary/10":"border-border hover:border-primary/50"}`,children:[e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx(Ss,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Basic"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Review-based metrics"})]}),e.jsxs("button",{onClick:()=>c("premium"),className:`flex-1 p-3 rounded-lg border-2 transition-all ${s==="premium"?"border-primary bg-primary/10":"border-border hover:border-primary/50"}`,children:[e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx(It,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Premium"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Ranking + competitive data"})]})]})]}),e.jsxs(j,{className:"p-4",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Us,{className:"h-4 w-4"}),"Select Stage"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("button",{onClick:()=>t("initial"),className:`flex-1 p-3 rounded-lg border-2 transition-all ${r==="initial"?"border-primary bg-primary/10":"border-border hover:border-primary/50"}`,children:[e.jsxs("div",{className:"flex items
30-center justify-center gap-2",children:[e.jsx("span",{className:"text-xl",children:"🔍"}),e.jsx("span",{className:"font-medium",children:"Initial Search"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"First contact"})]}),e.jsxs("button",{onClick:()=>t("optin"),className:`flex-1 p-3 rounded-lg border-2 transition-all ${r==="optin"?"border-primary bg-primary/10":"border-border hover:border-primary/50"}`,children:[e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx("span",{className:"text-xl",children:"✅"}),e.jsx("span",{className:"font-medium",children:"Opt-In"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"After unlock"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(H,{variant:"outline",className:"text-sm",children:["Viewing: ",r==="initial"?"Initial Search":"Opt-In"]}),e.jsxs(H,{variant:"outline",className:"text-sm",children:["Tier: ",s==="basic"?"Basic":"Premium"]})]}),e.jsxs(We,{defaultValue:"prospect",className:"space-y-6",children:[e.jsxs(Ve,{className:"grid w-full grid-cols-2",children:[e.jsx(J,{value:"prospect",children:"Prospect Email"}),e.jsx(J,{value:"admin",children:"Admin Notification"})]}),e.jsx(X,{value:"prospect",className:"space-y-4",children:e.jsx(hr,{tier:s,stage:r})}),e.jsx(X,{value:"admin",className:"space-y-4",children:e.jsx(pr,{tier:s,stage:r})})]})]})},fr=({planName:s,planPrice:c})=>{const[r,t]=i.useState(!1),n="John Smith",l="#",o=`
31    <div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background: #f6f9fc; padding: 20px;">
32      <div style="background: #ffffff; margin: 0 auto; padding: 40px 30px; border-radius: 10px; max-width: 600px;">
33        <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 30px; border-radius: 10px 10px 0 0; text-align: center; margin-bottom: 30px;">
34          <h1 style="font-size: 32px; font-weight: bold; color: #ffffff; margin: 0;">ReviewROI</h1>
35          <p style="font-size: 14px; color: #ffffff; opacity: 0.9; margin: 5px 0 0 0;">Turn Reviews Into Revenue</p>
36        </div>
37        
38        <p style="font-size: 16px; line-height: 1.6; color: #333333; margin-bottom: 20px;">Hi ${n},</p>
39        
40        <p style="font-size: 16px; line-height: 1.6; color: #333333; margin-bottom: 20px;">
41          I noticed you started signing up for <strong>${s}</strong> (just <strong>$${c}/month</strong>) but didn't complete your purchase. I wanted to reach out personally.
42        </p>
43        
44        <p style="font-size: 16px; line-height: 1.6; color: #333333; margin-bottom: 20px;">
45          Here's the thing – most agencies are sitting on a goldmine and don't even know it. Your clients' reviews aren't just testimonials, they're untapped revenue waiting to happen.
46        </p>
47        
48        <div style="background: #f8f4ff; padding: 25px; border-left: 4px solid #667eea; border-radius: 4px; margin: 25px 0;">
49          <p style="font-size: 16px; font-weight: bold; color: #333333; margin-bottom: 10px;">What You're Missing:</p>
50          <ul style="margin: 10px 0; padding-left: 20px;">
51            <li style="margin-bottom: 8px; font-size: 16px; line-height: 1.6; color: #333333;"><strong>Show clients their hidden revenue</strong> – Generate instant review ROI reports</li>
52            <li style="margin-bottom: 8px; font-size: 16px; line-height: 1.6; color: #333333;"><strong>Close more deals</strong> – Data-driven proof of their review gaps</li>
53            <li style="margin-bottom: 8px; font-size: 16px; line-height: 1.6; color: #333333;"><strong>White-label everything</strong> – Your brand, your credibility</li>
54            <li style="margin-bottom: 8px; font-size: 16px; line-height: 1.6; color: #333333;"><strong>Automate lead capture</strong> – Convert prospects while you sleep</li>
55          </ul>
56        </div>
57        
58        <p style="font-size: 16px; line-height: 1.6; color: #333333; margin-bottom: 20px;">
59          The best part? It takes less than 5 minutes to set up. Your first client report can be ready today.
60        </p>
61        
62        <div style="text-align: center; margin: 35px 0;">
63          <a href="${l}" style="display: inline-block; padding: 16px 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #ffffff; text-decoration: none; border-radius: 8px; font-weight: 600; font-size: 16px;">
64            Complete My Signup Now →
65          </a>
66        </div>
67        
68        <p style="font-size: 14px; color: #666666; margin-top: 30px; padding-top: 20px; border-top: 1px solid #eeeeee;">
69          Have questions? Just hit reply – I'm here to help you turn this into revenue.
70        </p>
71        
72        <p style="font-size: 14px; color: #666666; margin-top: 15px;">
73          To your success,<br />
74          The ReviewROI Team
75        </p>
76        
77        <p style="font-size: 12px; color: #999999; text-align: center; margin-top: 20px;">
78          © 2025 ReviewROI. All rights reserved.
79        </p>
80      </div>
81    </div>
82  `,m=`
83    <div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background: #f6f9fc; padding: 20px;">
84      <div style="background: #ffffff; margin: 0 auto; padding: 40px 30px; border-radius: 10px; max-width: 600px;">
85        <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 30px; border-radius: 10px 10px 0 0; text-align: center; margin-bottom: 30px;">
86          <h1 style="font-size: 32px; font-weight: bold; color: #ffffff; margin: 0;">ReviewROI</h1>
87          <p style="font-size: 14px; color: #ffffff; opacity: 0.9; margin: 5px 0 0 0;">Turn Reviews Into Revenue</p>
88        </div>
89        
90        <p style="font-size: 16px; line-height: 1.6; color: #333333; margin-bottom: 20px;">Hi ${n},</p>
91        
92        <p style="font-size: 16px; line-height: 1.6; color: #333333; margin-bottom: 20px;">
93          Quick question: Do you know how much revenue your clients are losing because of their review gaps?
94        </p>
95        
96        <p style="font-size: 16px; line-height: 1.6; color: #333333; margin-bottom: 20px;">
97          Most agencies pitch "reputation management" as a nice-to-have. That's why they struggle to close deals.
98        </p>
99        
100        <div style="background: #f0fdf4; padding: 25px; border-left: 4px solid #10b981; border-radius: 4px; margin: 25px 0;">
101          <p style="font-size: 18px; font-weight: bold; color: #065f46; margin-bottom: 15px;">Here's What Changes With ReviewROI:</p>
102          
103          <div style="margin-bottom: 20px;">
104            <p style="font-size: 16px; font-weight: bold; color: #333333; margin-bottom: 5px;">💰 Show Real Dollars</p>
105            <p style="font-size: 15px; line-height: 1.5; color: #666666; margin: 0;">
106              "Mr. Client, you're losing $47,000/year in revenue because of your review situation" hits different than "you should get more reviews."
107            </p>
108          </div>
109          
110          <div style="margin-bottom: 20px;">
111            <p style="font-size: 16px; font-weight: bold; color: #333333; margin-bottom: 5px;">🎯 Close Faster</p>
112            <p style="font-size: 15px; line-height: 1.5; color: #666666; margin: 0;">
113              Data-driven reports make prospects say "when can we start?" instead of "let me think about it."
114            </p>
115          </div>
116          
117          <div style="margin-bottom: 20px;">
118            <p style="font-size: 16px; font-weight: bold; color: #333333; margin-bottom: 5px;">⚡ Scale Effortlessly</p>
119            <p style="font-size: 15px; line-height: 1.5; color: #666666; margin: 0;">
120              White-label automation means you generate reports while you sleep. Your brand, our engine.
121            </p>
122          </div>
123        </div>
124        
125        <p style="font-size: 16px; line-height: 1.6; color: #333333; margin-bottom: 20px;">
126          <strong>${s}</strong> is just <strong>$${c}/month</strong>. Most agencies close one client and it pays for itself 10x over.
127        </p>
128        
129        <div style="text-align: center; margin: 35px 0;">
130          <a href="${l}" style="display: inline-block; padding: 16px 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #ffffff; text-decoration: none; border-radius: 8px; font-weight: 600; font-size: 16px;">
131            Activate My Account Now →
132          </a>
133        </div>
134        
135        <p style="font-size: 14px; color: #666666; margin-top: 30px; padding-top: 20px; border-top: 1px solid #eeeeee;">
136          Questions? Hit reply. I'm here to help you turn this into real revenue.
137        </p>
138        
139        <p style="font-size: 14px; color: #666666; margin-top: 15px;">
140          Cheers,<br />
141          The ReviewROI Team
142        </p>
143        
144        <p style="font-size: 12px; color: #999999; text-align: center; margin-top: 20px;">
145          © 2025 ReviewROI. All rights reserved.
146        </p>
147      </div>
148    </div>
149  `,d=`
150    <div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background: #f6f9fc; padding: 20px;">
151      <div style="background: #ffffff; margin: 0 auto; padding: 40px 30px; border-radius: 10px; max-width: 600px;">
152        <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 30px; border-radius: 10px 10px 0 0; text-align: center; margin-bottom: 30px;">
153          <h1 style="font-size: 32px; font-weight: bold; color: #ffffff; margin: 0;">ReviewROI</h1>
154          <p style="font-size: 14px; color: #ffffff; opacity: 0.9; margin: 5px 0 0 0;">Turn Reviews Into Revenue</p>
155        </div>
156        
157        <p style="font-size: 16px; line-height: 1.6; color: #333333; margin-bottom: 20px;">Hi ${n},</p>
158        
159        <p style="font-size: 16px; line-height: 1.6; color: #333333; margin-bottom: 20px;">
160          This is my last email. I wanted to give you one final opportunity before we close your account.
161        </p>
162        
163        <p style="font-size: 16px; line-height: 1.6; color: #333333; margin-bottom: 20px;">
164          I completely understand if now isn't the right time. But I'd feel terrible if you missed out because you thought it was complicated or expensive.
165        </p>
166        
167        <div style="background: #fef3c7; padding: 25px; border-left: 4px solid #f59e0b; border-radius: 4px; margin: 25px 0;">
168          <p style="font-size: 18px; font-weight: bold; color: #92400e; margin-bottom: 15px;">The Truth About ReviewROI:</p>
169          
170          <p style="font-size: 16px; line-height: 1.6; color: #333333; margin-bottom: 20px;">
171            <strong>It's not about reputation management.</strong> It's about showing clients the exact dollar amount they're losing – and positioning yourself as the person who can fix it.
172          </p>
173          
174          <p style="font-size: 16px; line-height: 1.6; color: #333333; margin-bottom: 20px;">
175            <strong>Most agencies struggle to explain value.</strong> ReviewROI gives you a calculator that proves it in black and white. Hard numbers win deals.
176          </p>
177          
178          <p style="font-size: 16px; line-height: 1.6; color: #333333; margin-bottom: 20px;">
179            <strong>Your first client pays for the whole year.</strong> At $${c}/month, you're looking at making your investment back 10-20x with one closed deal.
180          </p>
181        </div>
182        
183        <p style="font-size: 16px; line-height: 1.6; color: #333333; margin-bottom: 20px;">
184          <strong>Still hesitating?</strong> Here's why:
185        </p>
186        
187        <ul style="font-size: 16px; line-height: 1.6; color: #333333; margin-bottom: 20px; padding-left: 20px;">
188          <li style="margin-bottom: 10px;"><strong>Worried it won't work?</strong> We have agencies closing deals with it every single day.</li>
189          <li style="margin-bottom: 10px;"><strong>Think setup is hard?</strong> Literally 5 minutes. Add your logo, connect your domain, done.</li>
190          <li style="margin-bottom: 10px;"><strong>Not sure about ROI?</strong> One client pays for the whole year. Every deal after that is pure profit.</li>
191        </ul>
192        
193        <div style="text-align: center; margin: 35px 0;">
194          <a href="${l}" style="display: inline-block; padding: 16px 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #ffffff; text-decoration: none; border-radius: 8px; font-weight: 600; font-size: 16px;">
195            Activate Now - Last Chance →
196          </a>
197        </div>
198        
199        <div style="padding: 20px; background: #fff8e1; border-left: 4px solid #ffc107; border-radius: 4px; margin-top: 30px;">
200          <p style="margin: 0; font-size: 15px; color: #666666;">
201            <strong>This is my final email.</strong> If I don't hear from you, I'll assume it's not the right fit. No hard feelings – I appreciate you considering ReviewROI.
202          </p>
203        </div>
204        
205        <p style="font-size: 14px; color: #666666; margin-top: 30px; padding-top: 20px; border-top: 1px solid #eeeeee;">
206          Whatever you decide, I wish you massive success closing more deals.
207        </p>
208        
209        <p style="font-size: 14px; color: #666666; margin-top: 15px;">
210          All the best,<br />
211          The ReviewROI Team
212        </p>
213        
214        <p style="font-size: 12px; color: #999999; text-align: center; margin-top: 20px;">
215          P.S. If you have questions, just hit reply. I'm here to help.
216        </p>
217        
218        <p style="font-size: 12px; color: #999999; text-align: center; margin-top: 20px;">
219          © 2025 ReviewROI. All rights reserved.
220        </p>
221      </div>
222    </div>
223  `;return e.jsxs(Ws,{open:r,onOpenChange:t,children:[e.jsx(zt,{asChild:!0,children:e.jsxs(Y,{variant:"outline",size:"sm",children:[e.jsx(Ce,{className:"h-4 w-4 mr-2"}),"Preview Emails"]}
223)}),e.jsxs(Vs,{className:"max-w-4xl max-h-[90vh]",children:[e.jsx(qs,{children:e.jsx(Hs,{children:"Revenue Recovery Email Previews"})}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"These are the 3 emails sent to abandoned signups (10 min, 24h, 48h after)"}),e.jsxs(We,{defaultValue:"email1",className:"w-full",children:[e.jsxs(Ve,{className:"grid w-full grid-cols-3",children:[e.jsx(J,{value:"email1",children:"Email 1 (10 min)"}),e.jsx(J,{value:"email2",children:"Email 2 (+24 hours)"}),e.jsx(J,{value:"email3",children:"Email 3 (+48 hours)"})]}),e.jsxs(X,{value:"email1",className:"mt-4",children:[e.jsx(j,{children:e.jsx(O,{className:"p-0",children:e.jsx("div",{className:"overflow-auto max-h-[600px]",dangerouslySetInnerHTML:{__html:o}})})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 text-center",children:"Subject: Quick question about ReviewROI..."})]}),e.jsxs(X,{value:"email2",className:"mt-4",children:[e.jsx(j,{children:e.jsx(O,{className:"p-0",children:e.jsx("div",{className:"overflow-auto max-h-[600px]",dangerouslySetInnerHTML:{__html:m}})})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 text-center",children:"Subject: The revenue you're leaving on the table..."})]}),e.jsxs(X,{value:"email3",className:"mt-4",children:[e.jsx(j,{children:e.jsx(O,{className:"p-0",children:e.jsx("div",{className:"overflow-auto max-h-[600px]",dangerouslySetInnerHTML:{__html:d}})})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 text-center",children:"Subject: Last call - Don't leave this revenue on the table"})]})]})]})]})},jr=()=>{var T,I,xe,re,ae,ue,U,G,he,ke;const{toast:s}=ne(),[c,r]=i.useState(!0),[t,n]=i.useState([]),[l,o]=i.useState([]),[m,d]=i.useState([]),[g,f]=i.useState(null),[b,N]=i.useState(!1),[w,S]=i.useState(null),[u,x]=i.useState(!1),[_,p]=i.useState(null),[v,h]=i.useState({totalSignups:0,successfulSignups:0,pendingSignups:0,failedSignups:0,totalTierChanges:0,completedUpgrades:0,pendingUpgrades:0,activeCampaigns:0,completedCampaigns:0,totalEmailsSent:0}),y=async()=>{r(!0);try{const C=new Date;C.setDate(C.getDate()-30);const{data:q,error:P}=await R.from("signup_attempts").select("*, plans(name, tier, price, billing_interval, features)").gte("created_at",C.toISOString()).order("created_at",{ascending:!1}).limit(50);if(P)throw P;const{data:M,error:K}=await R.from("subscription_history").select("*").gte("initiated_at",C.toISOString()).order("initiated_at",{ascending:!1}).limit(50);if(K)throw K;const{data:se,error:qe}=await R.from("signup_email_campaigns").select("*").order("created_at",{ascending:!1}).limit(50);if(qe)throw qe;n(q||[]),o(M||[]),d(se||[]);const F={totalSignups:(q==null?void 0:q.length)||0,successfulSignups:(q==null?void 0:q.filter(z=>z.status==="successful").length)||0,pendingSignups:(q==null?void 0:q.filter(z=>z.status==="pending").length)||0,failedSignups:(q==null?void 0:q.filter(z=>["failed","abandoned"].includes(z.status)).length)||0,totalTierChanges:(M==null?void 0:M.length)||0,completedUpgrades:(M==null?void 0:M.filter(z=>z.status==="completed"&&z.change_type==="upgrade").length)||0,pendingUpgrades:(M==null?void 0:M.filter(z=>z.status==="initiated").length)||0,activeCampaigns:(se==null?void 0:se.filter(z=>z.status==="active").length)||0,completedCampaigns:(se==null?void 0:se.filter(z=>z.status==="completed").length)||0,totalEmailsSent:(se==null?void 0:se.reduce((z,Z)=>z+Z.emails_sent,0))||0};h(F)}catch(C){console.error("Error loading tracking data:",C),s({title:"Error",description:"Failed to load tracking data",variant:"destructive"})}finally{r(!1)}};i.useEffect(()=>{y();const C=R.channel("signup-attempts-changes").on("postgres_changes",{event:"*",schema:"public",table:"signup_attempts"},M=>{console.log("[SIGNUP-TRACKING] Real-time update:",M),y()}).subscribe(),q=R.channel("subscription-history-changes").on("postgres_changes",{event:"*",schema:"public",table:"subscription_history"},M=>{console.log("[SIGNUP-TRACKING] Tier change update:",M),y()}).subscribe(),P=R.channel("email-campaigns-changes").on("postgres_changes",{event:"*",schema:"public",table:"signup_email_campaigns"},M=>
223{console.log("[SIGNUP-TRACKING] Campaign update:",M),y()}).subscribe();return()=>{R.removeChannel(C),R.removeChannel(q),R.removeChannel(P)}},[]);const a=async C=>{S(C),N(!0)},k=async()=>{if(w){f(w.id),N(!1);try{const{data:C,error:q}=await R.functions.invoke("send-incomplete-signup-reminder",{body:{attemptId:w.id}});if(q)throw q;s({title:"Reminder email sent successfully!",description:`Sent to ${w.email} (${C.reminderCount} of 3 reminders)`}),await y()}catch(C){console.error("Failed to send reminder:",C),s({title:"Failed to send reminder",description:C.message||"Please try again",variant:"destructive"})}finally{f(null),S(null)}}},D=C=>{if(C.status!=="pending"||(C.reminder_email_count||0)>=3)return!1;if(C.reminder_email_sent_at){const q=new Date(C.reminder_email_sent_at);if((Date.now()-q.getTime())/(1e3*60*60)<24)return!1}return!0},E=C=>{const q=C.reminder_email_count||0;if(q>=3)return"Max reminders sent";if(C.reminder_email_sent_at){const P=new Date(C.reminder_email_sent_at),M=(Date.now()-P.getTime())/(1e3*60*60);if(M<24)return`Wait ${Math.ceil(24-M)}h`}return q>0?`Send Reminder (${q}/3)`:"Send Reminder"},$=C=>{const P={successful:{variant:"default",icon:le},completed:{variant:"default",icon:le},pending:{variant:"secondary",icon:pe},initiated:{variant:"secondary",icon:pe},failed:{variant:"destructive",icon:Se},abandoned:{variant:"destructive",icon:Se}}[C]||{variant:"outline",icon:pe},M=P.icon;return e.jsxs(H,{variant:P.variant,className:"flex items-center gap-1",children:[e.jsx(M,{className:"h-3 w-3"}),C.replace("_"," ")]})};return c?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ee,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs(We,{defaultValue:"signups",className:"w-full",children:[e.jsxs(Ve,{className:"grid w-full grid-cols-3",children:[e.jsx(J,{value:"signups",children:"Recent Signup Attempts"}),e.jsx(J,{value:"campaigns",children:"Email Recovery Campaigns"}),e.jsx(J,{value:"tiers",children:"Tier Changes"})]}),e.jsxs(X,{value:"signups",className:"mt-6 space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs(j,{children:[e.jsxs(W,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(V,{className:"text-sm font-medium",children:"Total Signups"}),e.jsx(ve,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(O,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v.totalSignups}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]}),e.jsxs(j,{children:[e.jsxs(W,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(V,{className:"text-sm font-medium",children:"Successful"}),e.jsx(le,{className:"h-4 w-4 text-green-600"})]}),e.jsxs(O,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v.successfulSignups}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.totalSignups>0?(v.successfulSignups/v.totalSignups*100).toFixed(0):0,"% conversion"]})]})]}),e.jsxs(j,{children:[e.jsxs(W,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(V,{className:"text-sm font-medium",children:"Pending"}),e.jsx(pe,{className:"h-4 w-4 text-yellow-600"})]}),e.jsxs(O,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v.pendingSignups}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"In progress"})]})]}),e.jsxs(j,{children:[e.jsxs(W,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(V,{className:"text-sm font-medium",children:"Failed/Cancelled"}),e.jsx(Se,{className:"h-4 w-4 text-red-600"})]}),e.jsxs(O,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v.failedSignups}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.totalSignups>0?(v.failedSignups/v.totalSignups*100).toFixed(0):0,"% dropout"]})]})]})]}),e.jsxs(j,{children:[e.jsxs(W,{className:"flex flex-row items-center justify-between",children:[e.jsx(V,{children:"Recent Signup Attempts"}),e.jsxs(Y,{variant:"outline",size:"sm",onClick:y,children:[e.jsx(ee,{className:"h-4 w-4 mr-2"}),"Refresh"]})]}),e.jsx(O,{children:e.jsxs(oe,{children:[e.jsx(ce,{children:e.jsxs(Q,{children:[e.jsx(L,{children:"Email"}),e.jsx(L,{children:"Name"}),e.jsx(L,{children:"Plan"}),e.jsx(L,{children:"Status"}),e.jsx(L,{children:"Created"}),e.jsx(L,{children:"Actions"})]})}),e.jsx(de,{children:t.length===0?e.jsx(Q,{children:e.jsx(A,{colSpan:6,className:"text-center text-muted-foreground",children:"No signup attempts found"})}):t.map(C=>e.jsxs(Q,{children:[e.jsx(A,{className:"font-medium",children:C.email}),e.jsx(A,{children:C.full_name}),e.jsx(A,{children:C.plans?e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-medium",children:C.plans.name}),e.jsxs("div",{className:"text-muted-foreground text-xs",children:["$",C.plans.price," • ",C.plans.tier]})]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(A,{children:$(C.status)}),e.jsx(A,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-sm",children:new Date(C.created_at).toLocaleStr
223ing()}),C.reminder_email_sent_at&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Reminder: ",new Date(C.reminder_email_sent_at).toLocaleString()]})]})}),e.jsx(A,{children:C.status==="pending"&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Y,{size:"sm",variant:"outline",onClick:()=>{p(C),x(!0)},children:[e.jsx(Ce,{className:"h-3 w-3 mr-1"}),"Preview"]}),e.jsx(Y,{size:"sm",variant:"outline",disabled:!D(C)||g===C.id,onClick:()=>a(C),children:g===C.id?e.jsxs(e.Fragment,{children:[e.jsx(ee,{className:"h-3 w-3 mr-1 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ns,{className:"h-3 w-3 mr-1"}),E(C)]})})]})})]},C.id))})]})})]})]}),e.jsxs(X,{value:"campaigns",className:"mt-6 space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs(j,{children:[e.jsxs(W,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(V,{className:"text-sm font-medium",children:"Active Campaigns"}),e.jsx(ie,{className:"h-4 w-4 text-purple-600"})]}),e.jsxs(O,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v.activeCampaigns}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Currently running"})]})]}),e.jsxs(j,{children:[e.jsxs(W,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(V,{className:"text-sm font-medium",children:"Total Emails Sent"}),e.jsx(ns,{className:"h-4 w-4 text-blue-600"})]}),e.jsxs(O,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v.totalEmailsSent}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All campaigns"})]})]}),e.jsxs(j,{children:[e.jsxs(W,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(V,{className:"text-sm font-medium",children:"Completed"}),e.jsx(le,{className:"h-4 w-4 text-green-600"})]}),e.jsxs(O,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v.completedCampaigns}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Finished campaigns"})]})]})]}),e.jsxs(j,{children:[e.jsx(W,{children:e.jsx(V,{children:"Email Template Previews"})}),e.jsxs(O,{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Preview the 3 ReviewROI revenue recovery emails sent at: 10 min, 24h, and 48h after signup abandonment"}),e.jsx(fr,{planName:"Premium Plan",planPrice:99})]})]}),e.jsxs(j,{children:[e.jsxs(W,{className:"flex flex-row items-center justify-between",children:[e.jsx(V,{children:"Email Recovery Campaigns"}),e.jsxs(Y,{variant:"outline",size:"sm",onClick:y,children:[e.jsx(ee,{className:"h-4 w-4 mr-2"}),"Refresh"]})]}),e.jsx(O,{children:e.jsxs(oe,{children:[e.jsx(ce,{children:e.jsxs(Q,{children:[e.jsx(L,{children:"Email"}),e.jsx(L,{children:"Plan"}),e.jsx(L,{children:"Emails Sent"}),e.jsx(L,{children:"Last Sent"}),e.jsx(L,{children:"Next Scheduled"}),e.jsx(L,{children:"Status"})]})}),e.jsx(de,{children:m.length===0?e.jsx(Q,{children:e.jsx(A,{colSpan:6,className:"text-center text-muted-foreground",children:"No email campaigns found"})}):m.map(C=>e.jsxs(Q,{children:[e.jsx(A,{className:"font-medium",children:C.email}),e.jsx(A,{children:e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-medium",children:C.plan_name}),e.jsxs("div",{className:"text-muted-foreground",children:["$",C.plan_price]})]})}),e.jsx(A,{children:e.jsxs(H,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[e.jsx(ns,{className:"h-3 w-3"}),C.emails_sent," / 3"]})}),e.jsx(A,{className:"text-sm text-muted-foreground",children:C.last_email_sent_at?new Date(C.last_email_sent_at).toLocaleString():"-"}),e.jsx(A,{className:"text-sm text-muted-foreground",children:C.next_email_scheduled_for?new Date(C.next_email_scheduled_for).toLocaleString():"-"}),e.jsx(A,{children:$(C.status)})]},C.id))})]})})]})]}),e.jsxs(X,{value:"tiers",className:"mt-6 space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs(j,{children:[e.jsxs(W,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(V,{className:"text-sm font-medium",children:"Total Changes"}),e.jsx(ve,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(O,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v.totalTierChanges}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]}),e.jsxs(j,{children:[e.jsxs(W,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(V,{className:"text-sm font-medium",children:"Completed Upgrades"}),e.jsx(le,{className:"h-4 w-4 text-green-600"})]}),e.jsxs(O,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v.completedUpgrades}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Successful changes"})]})]}),e.jsxs(j,{children:[e.jsxs(W,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(V,{className:"text-sm font-medium",children:"Pending"}),e.jsx(pe,{className:"h-4 w-4 text-yellow-600"})]}),e.jsxs(O,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v.pendingUpgrades}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"In progress"})]})]})]}),e.jsxs(j,{children:[e.jsxs(W,{className:"flex flex-row items-center justify-between",children:[e.jsx(V,{children:"Tier Changes"}),e.jsxs(Y,{variant:"outline",size:"sm",onClick:y,children:[e.jsx(ee,{className:"h-4 w-4 mr-2"}),"Refresh"]})]}),e.jsx(O,{children:e.jsxs(oe,{children:[e.jsx(ce,{children:e.jsxs(Q,{children:[e.jsx(L,{children:"Agency ID"}),e.jsx(L,{children:"Change Type"}),e.jsx(L,{children:"Tiers"}),e.jsx(L,{children:"Status"}),e.jsx(L,{children:"Initiated"}),e.jsx(L,{children:"Completed"})]})}),e.jsx(de,{children:l.length===0?e.jsx(Q,{children:e.jsx(A,{colSpan:6,className:"text-center text-muted-foreground",children:"No tier changes found"})}):l.map(C=>e.jsxs(Q,{children:[e.jsxs(A,{className:"font-mono text-xs",children:[C.agency_id.slice(0,8),"..."]}),e.jsx(A,{children:e.jsx(H,{variant:C.change_type==="upgrade"?"default":"secondary",children:C.change_type})}),e.jsx(A,{children:e.jsxs("span",{className:"text-sm",children:[C.old_tier||"none"," → ",C.new_tier]})}),e.jsx(A,{children:$(C.status)}),e.jsx(A,{className:"text-sm text-muted-foreground",children:new Date(C.initiated_at).toLocaleStr
223ing()}),e.jsx(A,{className:"text-sm text-muted-foreground",children:C.completed_at?new Date(C.completed_at).toLocaleString():"-"})]},C.id))})]})})]})]})]}),e.jsx(Mt,{open:b,onOpenChange:N,children:e.jsxs(Ft,{children:[e.jsxs($t,{children:[e.jsx(Bt,{children:"Send Incomplete Signup Reminder?"}),e.jsx(Ot,{children:w&&e.jsxs("div",{className:"space-y-2 mt-2",children:[e.jsxs("p",{children:["This will send a reminder email to ",e.jsx("strong",{children:w.email})," (",w.full_name,") about completing their signup."]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"The email will include a link to the signup page with urgency messaging about the offer expiring in 3 days."}),e.jsxs("p",{className:"text-sm font-medium",children:["Reminder count: ",(w.reminder_email_count||0)+1," of 3"]})]})})]}),e.jsxs(Ut,{children:[e.jsx(Wt,{children:"Cancel"}),e.jsx(Vt,{onClick:k,children:"Send Reminder"})]})]})}),e.jsx(Ws,{open:u,onOpenChange:x,children:e.jsxs(Vs,{className:"max-w-4xl max-h-[80vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx(Hs,{children:"Reminder Email Preview"})}),_&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"To:"})," ",_.email]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Subject:"})," Complete Your ",(T=_.plans)==null?void 0:T.name," Setup - Limited Time Offer"]})]}),e.jsx("iframe",{srcDoc:`
224<!DOCTYPE html>
225<html>
226<head>
227  <meta charset="utf-8">
228  <meta name="viewport" content="width=device-width, initial-scale=1.0">
229</head>
230<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Ubuntu, sans-serif; margin: 0; padding: 20px; background-color: #f6f9fc;">
231  <div style="background-color: #ffffff; border-radius: 8px; padding: 40px; max-width: 600px; margin: 0 auto;">
232    <h1 style="color: #1f2937; font-size: 28px; font-weight: bold; margin: 0 0 30px;">
233      ⏰ Your ${((I=_.plans)==null?void 0:I.name)||"Plan"} is Waiting
234    </h1>
235    <p style="color: #374151; font-size: 16px; line-height: 26px; margin: 16px 0;">
236      Hi ${_.first_name||"there"},
237    </p>
238    <p style="color: #374151; font-size: 16px; line-height: 26px; margin: 16px 0;">
239      You started signing up for <strong>${(xe=_.plans)==null?void 0:xe.name}</strong> at <strong>$${(re=_.plans)==null?void 0:re.price}${((ae=_.plans)==null?void 0:ae.billing_interval)==="monthly"?"/mo":((ue=_.plans)==null?void 0:ue.billing_interval)==="yearly"?"/yr":""}</strong>, 
240      but didn't complete your registration.
241    </p>
242    <div style="background-color: #fef3c7; border: 2px solid #f59e0b; border-radius: 8px; padding: 20px; margin: 30px 0; text-align: center;">
243      <p style="color: #92400e; font-size: 18px; font-weight: bold; margin: 0 0 8px;">
244        ⚠️ <strong>This offer expires in 3 days</strong>
245      </p>
246      <p style="color: #92400e; font-size: 14px; margin: 0;">
247        After that, this pricing won't be available again.
248      </p>
249    </div>
250    <p style="color: #374151; font-size: 16px; line-height: 26px; margin: 16px 0;">
251      ${((U=_.plans)==null?void 0:U.billing_interval)==="lifetime"?"This is a one-time lifetime deal - once it's gone, it's gone forever.":"Lock in this rate now before prices go up."}
252    </p>
253    <div style="margin: 32px 0; text-align: center;">
254      <a href="#" style="background-color: #3b82f6; border-radius: 6px; color: #ffffff; font-size: 16px; font-weight: bold; text-decoration: none; display: inline-block; padding: 14px 32px;">
255        Complete My Signup Now →
256      </a>
257    </div>
258    <p style="color: #1f2937; font-size: 18px; font-weight: bold; margin: 24px 0 12px;">
259      What you get with ${(G=_.plans)==null?void 0:G.name}:
260    </p>
261    <p style="color: #374151; font-size: 15px; line-height: 26px; margin: 0 0 24px;">
262      ${(Array.isArray((he=_.plans)==null?void 0:he.features)?_.plans.features:[]).map(C=>`✓ ${C}`).join(`<br>
263      `)}${((ke=_.plans)==null?void 0:ke.billing_interval)==="lifetime"?`<br>
264✓ Lifetime access - pay once, use forever`:""}
265    </p>
266    <p style="color: #374151; font-size: 16px;
266 line-height: 26px; margin: 16px 0;">
267      Questions? Just reply to this email - we're here to help!
268    </p>
269    <p style="color: #6b7280; font-size: 14px; line-height: 24px; margin-top: 32px;">
270      Best regards,<br>
271      The ReviewROI Team
272    </p>
273    <p style="color: #9ca3af; font-size: 13px; font-style: italic; margin-top: 16px;">
274      P.S. Don't miss out - this offer expires in just 3 days.
275    </p>
276  </div>
277</body>
278</html>
279                `,style:{width:"100%",height:"600px",border:"1px solid #e5e7eb",borderRadius:"8px"},title:"Email Preview"})]})]})})]})},br=()=>{const{toast:s}=ne(),[c,r]=i.useState(!0),[t,n]=i.useState(null),[l,o]=i.useState([]),[m,d]=i.useState([]),[g,f]=i.useState({}),[b,N]=i.useState({}),w=async()=>{r(!0);try{const{data:x,error:_}=await R.from("orphaned_reports_stats").select("*").single();if(_)throw _;n(x);const{data:p,error:v}=await R.from("orphaned_reports_view").select("*");if(v)throw v;o(p||[]);const{data:h,error:y}=await R.from("agencies").select("id, name, slug").order("name");if(y)throw y;d(h||[])}catch(x){console.error("Error loading orphaned reports:",x),s({title:"Error",description:x.message,variant:"destructive"})}finally{r(!1)}};i.useEffect(()=>{w()},[]);const S=async x=>{const _=g[x];if(!_){s({title:"No agency selected",description:"Please select an agency to reassign this report to.",variant:"destructive"});return}N(p=>({...p,[x]:!0}));try{const{data:p,error:v}=await R.rpc("reassign_orphaned_report",{p_report_id:x,p_target_agency_id:_});if(v)throw v;s({title:"Report Reassigned",description:"The orphaned report has been successfully reassigned."}),await w()}catch(p){console.error("Error reassigning report:",p),s({title:"Reassignment Failed",description:p.message,variant:"destructive"})}finally{N(p=>({...p,[x]:!1}))}};if(c)return e.jsx("div",{className:"flex items-center justify-center p-8",children:e.jsx(Ge,{className:"h-8 w-8 animate-spin"})});const u=t&&t.total_orphaned>0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Orphaned Reports"}),e.jsx("p",{className:"text-muted-foreground",children:"Monitor and recover reports without agency association"})]}),e.jsxs(Y,{onClick:w,variant:"outline",size:"sm",children:[e.jsx(ee,{className:"h-4 w-4 mr-2"}),"Refresh"]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(j,{children:[e.jsx(W,{className:"pb-2",children:e.jsx(V,{className:"text-sm font-medium",children:"Total Orphaned"})}),e.jsx(O,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[u?e.jsx(De,{className:"h-4 w-4 text-orange-500"}):e.jsx(le,{className:"h-4 w-4 text-green-500"}),e.jsx("span",{className:"text-2xl font-bold",children:(t==null?void 0:t.total_orphaned)||0})]})})]}),e.jsxs(j,{children:[e.jsx(W,{className:"pb-2",children:e.jsx(V,{className:"text-sm font-medium",children:"Unique Businesses"})}),e.jsx(O,{children:e.jsx("span",{className:"text-2xl font-bold",children:(t==null?void 0:t.unique_businesses)||0})})]}),e.jsxs(j,{children:[e.jsx(W,{className:"pb-2",children:e.jsx(V,{className:"text-sm font-medium",children:"By Tier"})}),e.jsx(O,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Premium:"}),e.jsx("span",{className:"font-medium",children:(t==null?void 0:t.premium_count)||0})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Basic:"}),e.jsx("span",{className:"font-medium",children:(t==null?void 0:t.basic_count)||0})]})]})})]}),e.jsxs(j,{children:[e.jsx(W,{className:"pb-2",children:e.jsx(V,{className:"text-sm font-medium",children:"White Label"})}),e.jsxs(O,{children:[e.jsx("span",{className:"text-2xl font-bold",children:(t==null?void 0:t.white_label_count)||0}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Reports with correlation ID"})]})]})]}),u?e.jsxs(j,{children:[e.jsxs(W,{children:[e.jsx(V,{children:"Orphaned Reports"}),e.jsx(_e,{children:"These reports are missing agency association. Reassign them to the appropriate agency."})]}),e.jsx(O,{children:e.jsxs(oe,{children:[e.jsx(ce,{children:e.jsxs(Q,{children:[e.jsx(L,{children:"Business"}),e.jsx(L,{children:"Location"}),e.jsx(L,{children:"Tier"}),e.jsx(L,{children:"Generated"}),e.jsx(L,{children:"Lead Info"}),e.jsx(L,{children:"Reassign To"}),e.jsx(L,{children:"Action"})]})}),e.jsx(de,{children:l.map(x=>e.jsxs(Q,{children:[e.jsx(A,{className:"font-medium",children:x.business_name}),e.jsxs(A,{children:[x.business_city,", ",x.business_state]}),e.jsx(A,{children:e.jsx(H,{variant:x.processing_tier==="premium"?"default":"secondary",children:x.processing_tier})}),e.jsx(A,{children:Ys(new Date(x.generated_at),"MMM d, yyyy HH:mm")}
279),e.jsx(A,{children:x.lead_email||x.first_name?e.jsxs("div",{className:"text-sm",children:[x.first_name&&e.jsxs("div",{children:[x.first_name," ",x.last_name]}),x.lead_email&&e.jsx("div",{className:"text-muted-foreground",children:x.lead_email})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"No lead info"})}),e.jsx(A,{children:e.jsxs(ge,{value:g[x.id]||"",onValueChange:_=>f(p=>({...p,[x.id]:_})),children:[e.jsx(fe,{className:"w-[200px]",children:e.jsx(je,{placeholder:"Select agency..."})}),e.jsx(be,{children:m.map(_=>e.jsx(B,{value:_.id,children:_.name},_.id))})]})}),e.jsx(A,{children:e.jsx(Y,{onClick:()=>S(x.id),disabled:!g[x.id]||b[x.id],size:"sm",children:b[x.id]?e.jsx(Ge,{className:"h-4 w-4 animate-spin"}):"Reassign"})})]},x.id))})]})})]}):e.jsx(j,{children:e.jsx(O,{className:"pt-6",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(le,{className:"h-12 w-12 text-green-500 mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Orphaned Reports"}),e.jsx("p",{className:"text-muted-foreground max-w-md",children:"All reports are properly associated with agencies. The database constraint is working correctly."})]})})})]})};function vr(){const{toast:s}=ne(),[c,r]=i.useState(!1),[t,n]=i.useState(!1),[l,o]=i.useState(null),[m,d]=i.useState([]),[g,f]=i.useState(null),b=async()=>{r(!0);try{const{data:u,error:x}=await R.functions.invoke("stripe-sync-check");if(x)throw x;o(u.stats),d(u.issues),f(u.timestamp),s({title:"Sync Check Complete",description:`Found ${u.stats.total_issues} issues. Health Score: ${u.stats.health_score}%`})}catch(u){s({title:"Sync Check Failed",description:u.message,variant:"destructive"})}finally{r(!1)}},N=async u=>{n(!0);try{const x=[];if(u.type==="duplicate"){const v=u.subscription_ids.slice(0,-1);for(const h of v)x.push({action:"cancel_subscription",subscription_id:h,reason:"duplicate_subscription_cleanup"})}else if(u.type==="missing_backup"){const v=u.subscription_ids[1];x.push({action:"pause_subscription",subscription_id:v,customer_id:u.customer_id,reason:"upgrade_backup_missing"})}if(x.length===0){s({title:"No Action Required",description:"This issue requires manual intervention"});return}const{data:_,error:p}=await R.functions.invoke("stripe-cleanup-action",{body:{actions:x}});if(p)throw p;s({title:"Cleanup Complete",description:`${_.summary.successful} actions completed successfully`}),await b()}catch(x){s({title:"Cleanup Failed",description:x.message,variant:"destructive"})}finally{n(!1)}},w=u=>{switch(u){case"critical":return"destructive";case"high":return"destructive";case"medium":return"default";case"low":return"secondary";default:return"default"}},S=u=>{switch(u){case"critical":return e.jsx(Be,{className:"h-5 w-5 text-destructive"});case"high":return e.jsx(De,{className:"h-5 w-5 text-destructive"});case"medium":return e.jsx(De,{className:"h-5 w-5 text-warning"});default:return e.jsx(Ms,{className:"h-5 w-5 text-muted-foreground"})}};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(j,{children:e.jsx(W,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(V,{children:"Stripe Synchronization"}),e.jsx(_e,{children:"Monitor and fix discrepancies between Stripe and your database"})]}),e.jsxs(Y,{onClick:b,disabled:c,children:[e.jsx(ee,{className:`mr-2 h-4 w-4 ${c?"animate-spin":""}`}),c?"Checking...":"Run Sync Check"]})]})})}),l&&e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs(j,{children:[e.jsx(W,{className:"pb-2",children:e.jsx(V,{className:"text-sm font-medium",children:"Health Score"})}),e.jsx(O,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:`text-2xl font-bold ${l.health_score>=80?"text-green-600":l.health_score>=50?"text-yellow-600":"text-red-600"}`,children:[l.health_score,"%"]}),l.health_score>=80?e.jsx($e,{className:"h-5 w-5 text-green-600"}):e.jsx(Be,{className:"h-5 w-5 text-red-600"})]})})]}),e.jsxs(j,{children:[e.jsx(W,{className:"pb-2",children:e.jsx(V,{className:"text-sm font-medium",children:"Critical Issues"})}),e.jsxs(O,{children:[e.jsx("div",{className:"text-2xl font-bold text-red-600",children:l.critical_issues}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Requires immediate action"})]})]}),e.jsxs(j,{children:[e.jsx(W,{className:"pb-2",children:e.jsx(V,{className:"text-sm font-medium",children:"High Priority"})}),e.jsxs(O,{children:[e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:l.high_issues}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Should be addressed soon"})]})]}),e.jsxs(j,{children:[e.jsx(W,{className:"pb-2",children:e.jsx(V,{className:"text-sm font-medium",children:"Total Subscriptions"})}),e.jsxs(O,{children:[e.jsx("div",{className:"text-2xl font-bold",children:l.total_stripe_subscriptions}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active in Stripe"})]})]})]}),g&&e.jsx(Te,{children:e.jsxs(Le,{children:["Last checked: ",new Date(g).toLocaleStr
279ing()]})}),m.length>0&&e.jsxs(j,{children:[e.jsxs(W,{children:[e.jsxs(V,{children:["Issues Found (",m.length,")"]}),e.jsx(_e,{children:"Review and fix synchronization issues"})]}),e.jsx(O,{className:"space-y-4",children:m.map((u,x)=>e.jsxs("div",{className:"border rounded-lg p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[S(u.severity),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(H,{variant:w(u.severity),children:u.severity.toUpperCase()}),e.jsx(H,{variant:"outline",children:u.type.replace("_"," ")})]}),e.jsx("p",{className:"font-medium mt-1",children:u.customer_email||u.customer_id})]})]}),(u.type==="duplicate"||u.type==="missing_backup")&&e.jsx(Y,{size:"sm",onClick:()=>N(u),disabled:t,children:t?"Processing...":"Fix Now"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:u.description}),e.jsxs("div",{className:"text-sm",children:[e.jsx("strong",{children:"Subscription IDs:"})," ",u.subscription_ids.join(", ")]}),e.jsx(Te,{children:e.jsxs(Le,{className:"text-sm",children:[e.jsx("strong",{children:"Recommended Action:"})," ",u.recommended_action]})})]},x))})]}),l&&m.length===0&&e.jsxs(Te,{children:[e.jsx($e,{className:"h-4 w-4"}),e.jsx(Le,{children:"No synchronization issues found! Your Stripe and database are perfectly in sync."})]})]})}const Nr=()=>{const{toast:s}=ne(),[c,r]=i.useState(!0),[t,n]=i.useState("30d"),[l,o]=i.useState({uniqueVisitors:0,signupAttempts:0,checkoutStarted:0,paymentCompleted:0,activeTrials:0,activeSubscriptions:0,cancelledSubscriptions:0}),[m,d]=i.useState([]),[g,f]=i.useState([]),[b,N]=i.useState([]),w=p=>{const v=new Date,h=p==="7d"?7:p==="14d"?14:p==="30d"?30:90;return v.setDate(v.getDate()-h),v.toISOString()},S=async()=>{r(!0);try{const p=w(t),[v,h,y,a]=await Promise.all([R.from("page_views").select("session_id, created_at, page_path").gte("created_at",p),R.from("signup_attempts").select("*, plans(name, tier, price, billing_interval)").gte("created_at",p).order("created_at",{ascending:!1}),R.from("subscriptions").select("*, plans(name, tier, price, billing_interval)").order("created_at",{ascending:!1}),R.from("plans").select("id, name, tier, price, billing_interval").eq("is_active",!0)]);if(v.error)throw v.error;if(h.error)throw h.error;if(y.error)throw y.error;const k=v.data||[],D=h.data||[],E=y.data||[],$=a.data||[],I=new Set(k.map(P=>P.session_id).filter(Boolean)).size,xe=D.length,re=D.filter(P=>P.stripe_session_id).length,ae=D.filter(P=>P.status==="successful").length,ue=E.filter(P=>P.status==="trialing").length,U=E.filter(P=>P.status==="active").length,G=E.filter(P=>P.status==="cancelled").length;o({uniqueVisitors:I,signupAttempts:xe,checkoutStarted:re,paymentCompleted:ae,activeTrials:ue,activeSubscriptions:U,cancelledSubscriptions:G});const he=new Map,ke=t==="7d"?7:t==="14d"?14:t==="30d"?30:90;for(let P=0;P<ke;P++){const M=new Date;M.setDate(M.getDate()-P);const K=M.toISOString().split("T")[0];he.set(K,{date:K,visitors:0,signups:0,completed:0})}k.forEach(P=>{const M=P.created_at.split("T")[0],K=he.get(M);K&&K.visitors++}),D.forEach(P=>{const M=P.created_at.split("T")[0],K=he.get(M);K&&(K.signups++,P.status==="successful"&&K.completed++)});const C=Array.from(he.values()).sort((P,M)=>P.date.localeCompare(M.date));d(C),f(D.slice(0,15));const q=new Map;D.forEach(P=>{const M=P.plans;if(!M)return;const K=P.plan_id;q.has(K)||q.set(K,{name:M.name,tier:M.tier,price:M.price,interval:M.billing_interval,count:0,successful:0});const se=q.get(K);se.count++,P.status==="successful"&&se.successful++}),N(Array.from(q.values()).sort((P,M)=>M.count-P.count))}catch(p){console.error("Error loading funnel data:",p),s({title:"Error",description:"Failed to load funnel analytics",variant:"destructive"})}finally{r(!1)}};i.useEffect(()=>{S()},[t]);const u=i.useMemo(()=>{const p=l.uniqueVisitors>0?(l.signupAttempts/l.uniqueVisitors*100).toFixed(1):"0.0",v=l.signupAttempts>0?(l.checkoutStarted/l.signupAttempts*100).toFixed(1):"0.0",h=l.checkoutStarted>0?(l.paymentCompleted/l.checkoutStarted*100).toFixed(1):"0.0",y=l.uniqueVisitors>0?(l.paymentCompleted/l.uniqueVisitors*100).toFixed(1):"0.0";return{visitorToSignup:p,signupToCheckout:v,checkoutToPayment:h,overallConversion:y}},[l]),x=i.useMemo(()=>{const p=m.slice(-7);return{visitors:p.reduce((v,h)=>v+h.visitors,0),signups:p.reduce((v,h)=>v+h.signups,0),completed:p.reduce((v,h)=>v+h.completed,0)}},[m]);if(c)return e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ee,{className:"h-6 w-6 animate-spin text-muted-foreground"})});const _=Math.max(...m.map(p=>p.visitors),1);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Paid Traffic Funnel"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Track visitors → signups → paying customers"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ge,{value:t,onValueChange:p=>n(p),children:[e.jsx(fe,{className:"w-32",children:e.jsx(je,{})}),e.jsxs(be,{children:[e.jsx(B,{value:"7d",children:"Last 7 days"}),e.jsx(B,{value:"14d",children:"Last 14 days"}),e.jsx(B,{value:"30d",children:"Last 30 days"}),e.jsx(B,{value:"90d",children:"Last 90 days"})]})]}),e.jsxs(Y,{variant:"outline",size:"sm",onClick:S,children:[e.jsx(ee,{className:"h-4 w-4 mr-2"}),"Refresh"]})]})]}),e.jsxs(j,{className:"p-6",children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground mb-4 uppercase tracking-wide",children:"Conversion Funnel"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-3",children:[e.jsx(Ye,{icon:Ce,label:"Unique Visitors",value:l.uniqueVisitors,subtext:"Landing page views",color:"blue",showArrow:!0}),e.jsx(Ye,{icon:qt,label:"Signup Started",value:l.signupAttempts,subtext:`${u.visitorToSignup}% of visitors`,color:"indigo",showArrow:!0}),e.jsx(Ye,{icon:zs,label:"Checkout Started",value:l.checkoutStarted,subtext:`${u.signupToCheckout}% of signups`,color:"purple",showArrow:!0}),e.jsx(Ye,{icon:le,label:"Payment Complete",value:l.paymentCompleted,subtext:`${u.checkoutToPayment}% of checkouts`,color:"green"})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Je,{className:"h-4 w-4"}),e.jsx("span",{children:"Overall Visitor → Customer Conversion"})]}),e.jsxs("span",{className:"text-2xl font-bold text-primary",children:[u.overallConversion,"%"]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 ga
279p-4",children:[e.jsx(Fe,{label:"Active Subscriptions",value:l.activeSubscriptions,icon:Re,description:"Paying customers"}),e.jsx(Fe,{label:"Active Trials",value:l.activeTrials,icon:Ht,description:"In trial period"}),e.jsx(Fe,{label:"Cancelled",value:l.cancelledSubscriptions,icon:ve,description:"Total cancelled"}),e.jsx(Fe,{label:"Last 7d Visitors",value:x.visitors,icon:Ce,description:`${x.signups} signups`}),e.jsx(Fe,{label:"Last 7d Conversions",value:x.completed,icon:le,description:x.visitors>0?`${(x.completed/x.visitors*100).toFixed(1)}% CVR`:"0% CVR"})]}),e.jsxs(j,{className:"p-6",children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground mb-4 uppercase tracking-wide",children:"Daily Traffic & Conversions"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"grid grid-cols-12 gap-2 text-xs font-semibold text-muted-foreground px-2 pb-2 border-b",children:[e.jsx("div",{className:"col-span-2",children:"Date"}),e.jsx("div",{className:"col-span-1 text-right",children:"Visitors"}),e.jsx("div",{className:"col-span-1 text-right",children:"Signups"}),e.jsx("div",{className:"col-span-1 text-right",children:"Paid"}),e.jsx("div",{className:"col-span-1 text-right",children:"CVR"}),e.jsx("div",{className:"col-span-6",children:"Traffic"})]}),[...m].reverse().slice(0,t==="7d"?7:t==="14d"?14:30).map(p=>{const v=_>0?p.visitors/_*100:0,h=p.visitors>0?(p.completed/p.visitors*100).toFixed(0):"0",a=new Date(p.date+"T00:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric",weekday:"short"});return e.jsxs("div",{className:"grid grid-cols-12 gap-2 items-center px-2 py-1.5 rounded hover:bg-muted/50 text-sm",children:[e.jsx("div",{className:"col-span-2 text-muted-foreground text-xs",children:a}),e.jsx("div",{className:"col-span-1 text-right font-medium",children:p.visitors}),e.jsx("div",{className:"col-span-1 text-right",children:p.signups||e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx("div",{className:"col-span-1 text-right",children:p.completed||e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsxs("div",{className:"col-span-1 text-right text-xs text-muted-foreground",children:[h,"%"]}),e.jsx("div",{className:"col-span-6",children:e.jsx("div",{className:"h-4 rounded-sm overflow-hidden bg-muted/30",children:e.jsx("div",{className:"h-full bg-primary/60 rounded-sm transition-all",style:{width:`${v}%`}})})})]},p.date)})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(j,{className:"p-6",children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground mb-4 uppercase tracking-wide",children:"Signup by Plan"}),b.length===0?e.jsx("p",{className:"text-muted-foreground text-sm",children:"No signup data yet"}):e.jsx("div",{className:"space-y-3",children:b.map((p,v)=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-background",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:p.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["$",p.price,"/",p.interval," · ",p.tier]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"font-bold",children:[p.count," attempts"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[p.successful," completed (",p.count>0?(p.successful/p.count*100).toFixed(0):0,"%)"]})]})]},v))})]}),e.jsxs(j,{className:"p-6",children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground mb-4 uppercase tracking-wide",children:"Recent Signup Attempts"}),g.length===0?e.jsx("p",{className:"text-muted-foreground text-sm",children:"No signups yet"}):e.jsx("div",{className:"space-y-2 max-h-[400px] overflow-y-auto",children:g.map(p=>{var v;return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-background",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:p.email}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[p.full_name," · ",((v=p.plans)==null?void 0:v.name)||"Unknown plan"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:new Date(p.created_at).toLocaleStr
279ing()})]}),e.jsx(yr,{status:p.status})]},p.id)})})]})]})]})};function Ye({icon:s,label:c,value:r,subtext:t,color:n,showArrow:l}){const o={blue:"bg-blue-50 border-blue-100 text-blue-900",indigo:"bg-indigo-50 border-indigo-100 text-indigo-900",purple:"bg-purple-50 border-purple-100 text-purple-900",green:"bg-green-50 border-green-100 text-green-900"},m={blue:"bg-blue-600",indigo:"bg-indigo-600",purple:"bg-purple-600",green:"bg-green-600"},d={blue:"text-blue-700",indigo:"text-indigo-700",purple:"text-purple-700",green:"text-green-700"};return e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:`flex items-center gap-3 p-4 rounded-lg border ${o[n]}`,children:[e.jsx("div",{className:`${m[n]} p-2.5 rounded-lg`,children:e.jsx(s,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:r.toLocaleString()}),e.jsx("p",{className:"text-xs font-medium",children:c}),e.jsx("p",{className:`text-xs ${d[n]}`,children:t})]})]}),l&&e.jsx("div",{className:"hidden md:flex absolute -right-2 top-1/2 -translate-y-1/2 z-10",children:e.jsx(Yt,{className:"h-4 w-4 text-muted-foreground"})})]})}function Fe({label:s,value:c,icon:r,description:t}){return e.jsxs(j,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-1",children:[e.jsx("div",{className:"p-1.5 bg-muted rounded-md",children:e.jsx(r,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-xs font-semibold text-muted-foreground",children:s})]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t})]})}function yr({status:s}){const r={successful:{variant:"default",label:"Paid"},pending:{variant:"secondary",label:"Pending"},failed:{variant:"destructive",label:"Failed"},abandoned:{variant:"destructive",label:"Abandoned"},cancelled:{variant:"outline",label:"Cancelled"}}[s]||{variant:"outline",label:s};return e.jsx(H,{variant:r.variant,className:"text-xs whitespace-nowrap",children:r.label})}const wr=()=>{const{toast:s}=ne(),[c,r]=i.useState([]),[t,n]=i.useState(!0),[l,o]=i.useState(""),[m,d]=i.useState("all"),[g,f]=i.useState("all"),[b,N]=i.useState({total:0,optedIn:0,fromMeta:0,fromEmail:0,converted:0});i.useEffect(()=>{w()},[]);const w=async()=>{n(!0);try{const{data:x}=await R.from("agencies").select("id").eq("name","ReviewROI").maybeSingle();if(!(x!=null&&x.id)){n(!1);return}const{data:_,error:p}=await R.from("leads").select(`
280          id, email, phone, first_name, last_name, status, 
281          source, utm_source, utm_medium, utm_campaign, landing_url,
282          created_at, report_id
283        `).eq("agency_id",x.id).is("deleted_at",null).order("created_at",{ascending:!1}).limit(500);if(p)throw p;const v=[...new Set((_||[]).map(U=>U.report_id))],{data:h}=v.length>0?await R.from("reports").select("id, business_name").in("id",v):{data:[]},y=new Map((h||[]).map(U=>[U.id,U.business_name])),a=(_||[]).map(U=>U.id),{data:k}=a.length>0?await R.from("lead_pipeline").select("id, lead_id, stage, signup_attempt_id").in("lead_id",a):{data:[]},D=new Map((k||[]).map(U=>[U.lead_id,U])),E=(k||[]).map(U=>U.signup_attempt_id).filter(Boolean),{data:$}=E.length>0?await R.from("signup_attempts").select("id, status").in("id",E):{data:[]},T=new Map(($||[]).map(U=>[U.id,U.status])),I=(_||[]).map(U=>{const G=D.get(U.id);return{...U,business_name:y.get(U.report_id)||"Unknown",pipeline_stage:(G==null?void 0:G.stage)||"new",pipeline_id:(G==null?void 0:G.id)||null,signup_attempt_id:(G==null?void 0:G.signup_attempt_id)||null,signup_status:G!=null&&G.signup_attempt_id&&T.get(G.signup_attempt_id)||null}});r(I);const xe=I.filter(U=>U.status==="opted_in").length,re=I.filter(U=>{var G;return["meta","facebook","fb"].includes(((G=U.utm_source)==null?void 0:G.toLowerCase())||"")}).length,ae=I.filter(U=>{var G;return((G=U.utm_source)==null?void 0:G.toLowerCase())==="email"}).length,ue=I.filter(U=>U.pipeline_stage==="converted").length;N({total:I.length,optedIn:xe,fromMeta:re,fromEmail:ae,converted:ue})}catch(x){s({title:"Error loading demo leads",description:x.message,variant:"destructive"})}finally{n(!1)}},S=async(x,_,p)=>{try{_?await R.from("lead_pipeline").update({stage:p}).eq("id",_):await R.from("lead_pipeline").insert({lead_id:x,stage:p}),r(v=>v.map(h=>
283h.id===x?{...h,pipeline_stage:p}:h)),s({title:"Stage updated",description:`Lead moved to ${p}`})}catch(v){s({title:"Error updating stage",description:v.message,variant:"destructive"})}},u=c.filter(x=>{var h,y,a,k,D,E;const _=!l||((h=x.email)==null?void 0:h.toLowerCase().includes(l.toLowerCase()))||((y=x.first_name)==null?void 0:y.toLowerCase().includes(l.toLowerCase()))||((a=x.last_name)==null?void 0:a.toLowerCase().includes(l.toLowerCase()))||((k=x.business_name)==null?void 0:k.toLowerCase().includes(l.toLowerCase())),p=m==="all"||x.pipeline_stage===m,v=g==="all"||g==="meta"&&["meta","facebook","fb"].includes(((D=x.utm_source)==null?void 0:D.toLowerCase())||"")||g==="email"&&((E=x.utm_source)==null?void 0:E.toLowerCase())==="email"||g==="organic"&&!x.utm_source;return _&&p&&v});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-5 gap-4",children:[e.jsxs(j,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Re,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Demos"})]}),e.jsx("p",{className:"text-2xl font-bold",children:b.total})]}),e.jsxs(j,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ce,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Opted In"})]}),e.jsx("p",{className:"text-2xl font-bold",children:b.optedIn}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.total>0?(b.optedIn/b.total*100).toFixed(1):0,"% rate"]})]}),e.jsxs(j,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Je,{className:"h-4 w-4 text-purple-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"From Meta"})]}),e.jsx("p",{className:"text-2xl font-bold",children:b.fromMeta})]}),e.jsxs(j,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Je,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"From Email"})]}),e.jsx("p",{className:"text-2xl font-bold",children:b.fromEmail})]}),e.jsxs(j,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ve,{className:"h-4 w-4 text-green-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Converted"})]}),e.jsx("p",{className:"text-2xl font-bold",children:b.converted})]})]}),e.jsx(j,{className:"p-4",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Pe,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ue,{placeholder:"Search by name, email, or business...",value:l,onChange:x=>o(x.target.value),className:"pl-10"})]}),e.jsxs(ge,{value:m,onValueChange:d,children:[e.jsx(fe,{className:"w-[160px]",children:e.jsx(je,{placeholder:"Pipeline Stage"})}),e.jsxs(be,{children:[e.jsx(B,{value:"all",children:"All Stages"}),e.jsx(B,{value:"new",children:"New"}),e.jsx(B,{value:"engaged",children:"Engaged"}),e.jsx(B,{value:"nurturing",children:"Nurturing"}),e.jsx(B,{value:"trial_started",children:"Trial Started"}),e.jsx(B,{value:"converted",children:"Converted"}),e.jsx(B,{value:"lost",children:"Lost"})]})]}),e.jsxs(ge,{value:g,onValueChange:f,children:[e.jsx(fe,{className:"w-[140px]",children:e.jsx(je,{placeholder:"Source"})}),e.jsxs(be,{children:[e.jsx(B,{value:"all",children:"All Sources"}),e.jsx(B,{value:"meta",children:"Meta Ads"}),e.jsx(B,{value:"email",children:"Email"}),e.jsx(B,{value:"organic",children:"Organic"})]})]}),e.jsxs(Y,{variant:"outline",size:"sm",onClick:w,disabled:t,children:[e.jsx(ee,{className:`h-4 w-4 mr-2 ${t?"animate-spin":""}`}),"Refresh"]})]})}),e.jsx(j,{children:e.jsxs(oe,{children:[e.jsx(ce,{children:e.jsxs(Q,{children:[e.jsx(L,{children:"Contact"}),e.jsx(L,{children:"Business"}),e.jsx(L,{children:"Source"}),e.jsx(L,{children:"Campaign"}),e.jsx(L,{children:"Status"}),e.jsx(L,{children:"Pipeline"}),e.jsx(L,{children:"Date"}),e.jsx(L,{children:"Report"})]})}),e.jsx(de,{children:u.length===0?e.jsx(Q,{children:e.jsx(A,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:t?"Loading...":"No demo leads found"})}):u.map(x=>e.jsxs(Q,{children:[e.jsx(A,{children:e.jsxs("div",{children:[x.first_name||x.last_name?e.jsxs("p",{className:"font-medium text-sm",children:[x.first_name," ",x.last_name]}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"No name"}),x.email&&e.jsx("p",{className:"text-xs text-muted-foreground",children:x.email}),x.phone&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Qt(x.phone)})]})}),e.jsx(A,{className:"text-sm",children:x.business_name}),e.jsx(A,{children:x.utm_source?e.jsx(H,{variant:"outline",className:"text-xs",children:x.utm_source}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"organic"})}),e.jsx(A,{children:x.utm_campaign?e.jsx("span",{className:"text-xs",children:x.utm_campaign}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}),e.jsx(A,{children:e.jsx(H,{variant:x.status==="opted_in"?"default":"secondary",className:"text-xs",children:x.status==="opted_in"?"Opted In":"Searched"})}),e.jsx(A,{children:e.jsxs(ge,{value:x.pipeline_stage||"new",onValueChange:_=>S(x.id,x.pipeline_id||null,_),children:[e.jsx(fe,{className:"w-[130px] h-7 text-xs",children:e.jsx(je,{})}),e.jsxs(be,{children:[e.jsx(B,{value:"new",children:"New"}),e.jsx(B,{value:"engaged",children:"Engaged"}),e.jsx(B,{value:"nurturing",children:"Nurturing"}),e.jsx(B,{value:"trial_started",children:"Trial Started"}),e.jsx(B,{value:"converted",children:"Converted"}),e.jsx(B,{value:"lost",children:"Lost"})]})]})}),e.jsx(A,{className:"text-xs text-muted-foreground",children:new Date(x.created_at).toLocaleDateString()}),e.jsx(A,{children:e.jsx(Y,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:()=>window.open(`/report/${x.report_id}`,"_blank"),children:e.jsx(Gt,{className:"h-3 w-3"})})})]},x.id))})]})})]})};function Sr(){const{toast:s}=ne(),[c,r]=i.useState([]),[t,n]=i.useState({total_sent:0,total_delivered:0,total_opened:0,total_clicked:0,total_bounced:0,total_complained:0,open_rate:0,click_rate:0}),[l,o]=i.useState(!0),[m,d]=i.useState(!1),[g,f]=i.useState("all");i.useEffect(()=>{b()},[g]);const b=async()=>{o(!0);try{let u=R.from("demo_nurture_campaigns").select("*").order("created_at",{ascending:!1}).limit(100);g!=="all"&&(u=u.eq("status",g));const{data:x,error:_}=await u;if(_)throw _;
283r(x||[]);const{data:p,error:v}=await R.from("email_analytics").select("event_type").eq("email_category","nurture");if(!v&&p){const h={};p.forEach(E=>{h[E.event_type]=(h[E.event_type]||0)+1});const y=h.sent||0,a=h.delivered||0,k=h.opened||0,D=h.clicked||0;n({total_sent:y,total_delivered:a,total_opened:k,total_clicked:D,total_bounced:h.bounced||0,total_complained:h.complained||0,open_rate:a>0?Math.round(k/a*100):0,click_rate:a>0?Math.round(D/a*100):0})}}catch(u){console.error("Error loading nurture data:",u),s({title:"Error",description:u.message,variant:"destructive"})}finally{o(!1)}},N=async()=>{d(!0);try{const{error:u}=await R.functions.invoke("process-nurture-campaigns",{body:{}});if(u)throw u;s({title:"Processing triggered",description:"Nurture campaigns are being processed."}),await b()}catch(u){s({title:"Error",description:u.message,variant:"destructive"})}finally{d(!1)}},w={active:c.filter(u=>u.status==="active").length,converted:c.filter(u=>u.status==="converted").length,completed:c.filter(u=>u.status==="completed").length,unsubscribed:c.filter(u=>u.status==="unsubscribed").length,paused:c.filter(u=>u.status==="paused").length},S=u=>{switch(u){case"active":return"bg-blue-100 text-blue-800";case"converted":return"bg-green-100 text-green-800";case"completed":return"bg-gray-100 text-gray-800";case"unsubscribed":return"bg-orange-100 text-orange-800";case"paused":return"bg-red-100 text-red-800";default:return"bg-gray-100 text-gray-800"}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Nurture Campaigns & Email Analytics"}),e.jsx("p",{className:"text-muted-foreground",children:"Track homepage demo lead nurture sequences and email performance"})]}),e.jsxs(Y,{onClick:N,disabled:m,size:"sm",children:[e.jsx(ee,{className:`h-4 w-4 mr-2 ${m?"animate-spin":""}`}),"Process Now"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:[e.jsxs(j,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ie,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Sent"})]}),e.jsx("p",{className:"text-2xl font-bold",children:t.total_sent})]}),e.jsxs(j,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ve,{className:"h-4 w-4 text-green-500"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Delivered"})]}),e.jsx("p",{className:"text-2xl font-bold",children:t.total_delivered})]}),e.jsxs(j,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ce,{className:"h-4 w-4 text-purple-500"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Opened"})]}),e.jsx("p",{className:"text-2xl font-bold",children:t.total_opened}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.open_rate,"% rate"]})]}),e.jsxs(j,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(nr,{className:"h-4 w-4 text-indigo-500"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Clicked"})]}),e.jsx("p",{className:"text-2xl font-bold",children:t.total_clicked}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.click_rate,"% rate"]})]}),e.jsxs(j,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(De,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Bounced"})]}),e.jsx("p",{className:"text-2xl font-bold",children:t.total_bounced})]}),e.jsxs(j,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Re,{className:"h-4 w-4 text-emerald-500"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Converted"})]}),e.jsx("p",{className:"text-2xl font-bold",children:w.converted})]})]}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:["all","active","converted","completed","unsubscribed","paused"].map(u=>e.jsxs(Y,{variant:g===u?"default":"outline",size:"sm",onClick:()=>f(u),children:[u.charAt(0).toUpperCase()+u.slice(1),u!=="all"&&` (${w[u]||0})`]},u))}),e.jsx(j,{children:e.jsxs(oe,{children:[e.jsx(ce,{children:e.jsxs(Q,{children:[e.jsx(L,{children:"Lead"}),e.jsx(L,{children:"Business"}),e.jsx(L,{children:"Status"}),e.jsx(L,{children:"Emails Sent"}),e.jsx(L,{children:"Last Sent"}),e.jsx(L,{children:"Next Scheduled"}),e.jsx(L,{children:"Source"}),e.jsx(L,{children:"Created"})]})}),e.jsx(de,{children:l?e.jsx(Q,{children:e.jsx(A,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):c.length===0?e.jsx(Q,{children:e.jsx(A,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"No nurture campaigns yet. Leads will appear here when homepage demo visitors opt in."})}):c.map(u=>e.jsxs(Q,{children:[e.jsx(A,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:u.first_name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u.email})]})}),e.jsx(A,{className:"max-w-[200px] truncate",children:u.business_name}),e.jsx(A,{children:e.jsx(H,{className:S(u.status),children:u.status})}),e.jsx(A,{children:e.jsxs("span",{className:"font-mono",children:[u.emails_sent,"/7"]}
vendor: 9,412 bytes, line 283
283)}),e.jsx(A,{className:"text-xs",children:u.last_email_sent_at?new Date(u.last_email_sent_at).toLocaleDateString():"—"}),e.jsx(A,{className:"text-xs",children:u.next_email_scheduled_for?new Date(u.next_email_scheduled_for).toLocaleDateString():"—"}),e.jsx(A,{className:"text-xs",children:u.utm_source||u.utm_campaign||"—"}),e.jsx(A,{className:"text-xs",children:new Date(u.created_at).toLocaleDateString()})]},u.id))})]})})]})}function _r(s,c){return i.useReducer((r,t)=>c[r][t]??r,s)}var ds="ScrollArea",[Qs,Ri]=ft(ds),[Cr,te]=Qs(ds),Gs=i.forwardRef((s,c)=>{const{__scopeScrollArea:r,type:t="hover",dir:n,scrollHideDelay:l=600,...o}=s,[m,d]=i.useState(null),[g,f]=i.useState(null),[b,N]=i.useState(null),[w,S]=i.useState(null),[u,x]=i.useState(null),[_,p]=i.useState(0),[v,h]=i.useState(0),[y,a]=i.useState(!1),[k,D]=i.useState(!1),E=ze(c,T=>d(T)),$=Jt(n);return e.jsx(Cr,{scope:r,type:t,dir:$,scrollHideDelay:l,scrollArea:m,viewport:g,onViewportChange:f,content:b,onContentChange:N,scrollbarX:w,onScrollbarXChange:S,scrollbarXEnabled:y,onScrollbarXEnabledChange:a,scrollbarY:u,onScrollbarYChange:x,scrollbarYEnabled:k,onScrollbarYEnabledChange:D,onCornerWidthChange:p,onCornerHeightChange:h,children:e.jsx(Oe.div,{dir:$,...o,ref:E,style:{position:"relative","--radix-scroll-area-corner-width":_+"px","--radix-scroll-area-corner-height":v+"px",...s.style}})})});Gs.displayName=ds;var Js="ScrollAreaViewport",Xs=i.forwardRef((s,c)=>{const{__scopeScrollArea:r,children:t,nonce:n,...l}=s,o=te(Js,r),m=i.useRef(null),d=ze(c,m,o.onViewportChange);return e.jsxs(e.Fragment,{children:[e.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:n}),e.jsx(Oe.div,{"data-radix-scroll-area-viewport":"",...l,ref:d,style:{overflowX:o.scrollbarXEnabled?"scroll":"hidden",overflowY:o.scrollbarYEnabled?"scroll":"hidden",...s.style},children:e.jsx("div",{ref:o.onContentChange,style:{minWidth:"100%",display:"table"},children:t})})]})});Xs.displayName=Js;var me="ScrollAreaScrollbar",ms=i.forwardRef((s,c)=>{const{forceMount:r,...t}=s,n=te(me,s.__scopeScrollArea),{onScrollbarXEnabledChange:l,onScrollbarYEnabledChange:o}=n,m=s.orientation==="horizontal";return i.useEffect(()=>(m?l(!0):o(!0),()=>{m?l(!1):o(!1)}),[m,l,o]),n.type==="hover"?e.jsx(Rr,{...t,ref:c,forceMount:r}):n.type==="scroll"?e.jsx(kr,{...t,ref:c,forceMount:r}):n.type==="auto"?e.jsx(Ks,{...t,ref:c,forceMount:r}):n.type==="always"?e.jsx(xs,{...t,ref:c}):null});ms.displayName=me;var Rr=i.forwardRef((s,c)=>{const{forceMount:r,...t}=s,n=te(me,s.__scopeScrollArea),[l,o]=i.useState(!1);return i.useEffect(()=>{const m=n.scrollArea;let d=0;if(m){const g=()=>{window.clearTimeout(d),o(!0)},f=()=>{d=window.setTimeout(()=>o(!1),n.scrollHideDelay)};return m.addEventListener("pointerenter",g),m.addEventListener("pointerleave",f),()=>{window.clearTimeout(d),m.removeEventListener("pointerenter",g),m.removeEventListener("pointerleave",f)}}},[n.scrollArea,n.scrollHideDelay]),e.jsx(Ze,{present:r||l,children:e.jsx(Ks,{"data-state":l?"visible":"hidden",...t,ref:c})})}),kr=i.forwardRef((s,c)=>{const{forceMount:r,...t}=s,n=te(me,s.__scopeScrollArea),l=s.orientation==="horizontal",o=ss(()=>d("SCROLL_END"),100),[m,d]=_r("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return i.useEffect(()=>{if(m==="idle"){const g=window.setTimeout(()=>d("HIDE"),n.scrollHideDelay);return()=>window.clearTimeout(g)}},[m,n.scrollHideDelay,d]),i.useEffect(()=>{const g=n.viewport,f=l?"scrollLeft":"scrollTop";if(g){let b=g[f];const N=()=>{const w=g[f];b!==w&&(d("SCROLL"),o()),b=w};return g.addEventListener("scroll",N),()=>g.removeEventListener("scroll",N)}},[n.viewport,l,d,o]),e.jsx(Ze,{present:r||m!=="hidden",children:e.jsx(xs,{"data-state":m==="hidden"?"hidden":"visible",...t,ref:c,onPointerEnter:we(s.onPointerEnter,()=>d("POINTER_ENTER")),onPointerLeave:we(s.onPointerLeave,()=>d("POINTER_LEAVE"))})})}),Ks=i.forwardRef((s,c)=>{const r=te(me,s.__scopeScrollArea),{forceMount:t,...n}=s,[l,o]=i.useState(!1),m=s.orientation==="horizontal",d=ss(()=>{if(r.viewport){const g=r.viewport.offsetWidth<r.viewport.scrollWidth,f=r.viewport.offsetHeight<r.viewport.scrollHeight;o(m?g:f)}},10);return Ie(r.viewport,d),Ie(r.content,d),e.jsx(Ze,{present:t||l,children:e.jsx(xs,{"data-state":l?"visible":"hidden",...n,ref:c})})}),xs=i.forwardRef((s,c)=>{const{orientation:r="vertical",...t}=s,n=te(me,s.__scopeScrollArea),l=i.useRef(null),o=i.useRef(0),[m,d]=i.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),g=rt(m.viewport,m.content),f={...t,sizes:m,onSizesChange:d,hasThumb:g>0&&g<1,onThumbChange:N=>l.current=N,onThumbPointerUp:()=>o.current=0,onThumbPointerDown:N=>o.current=N};function b(N,w){return Pr(N,o.current,m,w)}return r==="horizontal"?e.jsx(Ar,{...f,ref:c,onThumbPositionChange:()=>{if(n.viewport&&l.current){const N=n.viewport.scrollLeft,w=As(N,m,n.dir);l.current.style.transform=`translate3d(${w}px, 0, 0)`}},onWheelScroll:N=>{n.viewport&&(n.viewport.scrollLeft=N)},onDragScroll:N=>{n.viewport&&(n.viewport.scrollLeft=b(N,n.dir))}}):r==="vertical"?e.jsx(Tr,{...f,ref:c,onThumbPositionChange:()=>{if(n.viewport&&l.current){const N=n.viewport.scrollTop,w=As(N,m);l.current.style.transform=`translate3d(0, ${w}px, 0)`}},onWheelScroll:N=>{n.viewport&&(n.viewport.scrollTop=N)},onDragScroll:N=>{n.viewport&&(n.viewport.scrollTop=b(N))}}):null}),Ar=i.forwardRef((s,c)=>{const{sizes:r,onSizesChange:t,...n}=s,l=te(me,s.__scopeScrollArea),[o,m]=i.useState(),d=i.useRef(null),g=ze(c,d,l.onScrollbarXChange);return i.useEffect(()=>{d.current&&m(getComputedStyle(d.current))},[d]),e.jsx(et,{"data-orientation":"horizontal",...n,ref:g,sizes:r,style:{bottom:0,left:l.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:l.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":es(r)+"px",...s.style},onThumbPointerDown:f=>s.onThumbPointerDown(f.x),onDragScroll:f=>s.onDragScroll(f.x),onWheelScroll:(f,b)=>{if(l.viewport){const N=l.viewport.scrollLeft+f.deltaX;s.onWheelScroll(N),it(N,b)&&f.preventDefault()}},onResize:()=>{d.current&&l.viewport&&o&&t({content:l.viewport.scrollWidth,viewport:l.viewport.offsetWidth,scrollbar:{size:d.current.clientWidth,paddingStart:Ke(o.paddingLeft),paddingEnd:Ke(o.paddingRight)}})}})}),Tr=i.forwardRef((s,c)=>{const{sizes:r,onSizesChange:t,...n}=s,l=te(me,s.__scopeScrollArea),[o,m]=i.useState(),d=i.useRef(null),g=ze(c,d,l.onScrollbarYChange);return i.useEffect(()=>{d.current&&m(getComputedStyle(d.current))},[d]),e.jsx(et,{"data-orientation":"vertical",...n,ref:g,sizes:r,style:{top:0,right:l.dir==="ltr"?0:void 0,left:l.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":es(r)+"px",...s.style},onThumbPointerDown:f=>s.onThumbPointerDown(f.y),onDragScroll:f=>s.onDragScroll(f.y),onWheelScroll:(f,b)=>{if(l.viewport){const N=l.viewport.scrollTop+f.deltaY;s.onWheelScroll(N),it(N,b)&&f.preventDefault()}},onResize:()=>{d.current&&l.viewport&&o&&t({content:l.viewport.scrollHeight,viewport:l.viewport.offsetHeight,scrollbar:{size:d.current.clientHeight,paddingStart:Ke(o.paddingTop),paddingEnd:Ke(o.paddingBottom)}})}})}),[Lr,Zs]=Qs(me),et=i.forwardRef((s,c)=>{const{__scopeScrollArea:r,sizes:t,hasThumb:n,onThumbChange:l,onThumbPointerUp:o,onThumbPointerDown:m,onThumbPositionChange:d,onDragScroll:g,onWheelScroll:f,onResize:b,...N}=s,w=te(me,r),[S,u]=i.useState(null),x=ze(c,E=>u(E)),_=i.useRef(null),p=i.useRef(""),v=w.viewport,h=t.content-t.viewport,y=Ne(f),a=Ne(d),k=ss(b,10);function D(E){if(_.current){const $=E.clientX-_.current.left,T=E.clientY-_.current.top;g({x:$,y:T})}}return i.useEffect(()=>{const E=$=>{const T=$.target;(S==null?void 0:S.contains(T))&&y($,h)};return document.addEventListener("wheel",E,{passive:!1}),()=>document.removeEventListener("wheel",E,{passive:!1})},[v,S,h,y]),i.useEffect(a,[t,a]),Ie(S,k),Ie(w.content,k),e.jsx(Lr,{scope:r,scrollbar:S,hasThumb:n,onThumbChange:Ne(l),onThumbPointerUp:Ne(o),onThumbPositionChange:a,onThumbPointerDown:Ne(m),children:e.jsx(Oe.div,{...N,ref:x,style:{position:"absolute",...N.style},onPointerDown:we(s.onPointerDown,E=>{E.button===0&&(E.target.setPointerCapture(E.pointerId),_.current=S.getBoundingClientRect(),p.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",w.viewport&&(w.viewport.style.scrollBehavior="auto"),D(E))}),onPointerMove:we(s.onPointerMove,D),onPointerUp:we(s.onPointerUp,E=>{const $=E.target;$.hasPointerCapture(E.pointerId)&&$.releasePointerCapture(E.pointerId),document.body.style.webkitUserSelect=p.current,w.viewport&&(w.viewport.style.scrollBehavior=""),_.current=null})})})}),Xe="ScrollAreaThumb",st=i.forwardRef((s,c)=>{const{forceMount:r,...t}=s,n=Zs(Xe,s.__scopeScrollArea);return e.jsx(Ze,{present:r||n.hasThumb,children:e.jsx(Er,{ref:c,...t})})}),Er=i.forwardRef((s,c)=>{const{__scopeScrollArea:r,style:t,...n}=s,l=te(Xe,r),o=Zs(Xe,r),{onThumbPositionChange:m}=o,d=ze(c,b=>o.onThumbChange(b)),g=i.useRef(void 0),f=ss(()=>{g.current&&(g.current(),g.current=void 0)},100);return i.useEffect(()=>{const b=l.viewport;if(b){const N=()=>
283{if(f(),!g.current){const w=Ir(b,m);g.current=w,m()}};return m(),b.addEventListener("scroll",N),()=>b.removeEventListener("scroll",N)}},[l.viewport,f,m]),e.jsx(Oe.div,{"data-state":o.hasThumb?"visible":"hidden",...n,ref:d,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...t},onPointerDownCapture:we(s.onPointerDownCapture,b=>{const w=b.target.getBoundingClientRect(),S=b.clientX-w.left,u=b.clientY-w.top;o.onThumbPointerDown({x:S,y:u})}),onPointerUp:we(s.onPointerUp,o.onThumbPointerUp)})});st.displayName=Xe;var us="ScrollAreaCorner",tt=i.forwardRef((s,c)=>{const r=te(us,s.__scopeScrollArea),t=!!(r.scrollbarX&&r.scrollbarY);return r.type!=="scroll"&&t?e.jsx(Dr,{...s,ref:c}):null});tt.displayName=us;var Dr=i.forwardRef((s,c)=>{const{__scopeScrollArea:r,...t}=s,n=te(us,r),[l,o]=i.useState(0),[m,d]=i.useState(0),g=!!(l&&m);return Ie(n.scrollbarX,()=>{var b;const f=((b=n.scrollbarX)==null?void 0:b.offsetHeight)||0;n.onCornerHeightChange(f),d(f)}),Ie(n.scrollbarY,()=>{var b;const f=((b=n.scrollbarY)==null?void 0:b.offsetWidth)||0;n.onCornerWidthChange(f),o(f)}),g?e.jsx(Oe.div,{...t,ref:c,style:{width:l,height:m,position:"absolute",right:n.dir==="ltr"?0:void 0,left:n.dir==="rtl"?0:void 0,bottom:0,...s.style}}):null});function Ke(s){return s?parseInt(s,10):0}function rt(s,c){const r=s/c;return isNaN(r)?0:r}function es(s){const c=rt(s.viewport,s.content),r=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,t=(s.scrollbar.size-r)*c;return Math.max(t,18)}function Pr(s,c,r,t="ltr"){const n=es(r),l=n/2,o=c||l,m=n-o,d=r.scrollbar.paddingStart+o,g=r.scrollbar.size-r.scrollbar.paddingEnd-m,f=r.content-r.viewport,b=t==="ltr"?[0,f]:[f*-1,0];return at([d,g],b)(s)}function As(s,c,r="ltr"){const t=es(c),n=c.scrollbar.paddingStart+c.scrollbar.paddingEnd,l=c.scrollbar.size-n,o=c.content-c.viewport,m=l-t,d=r==="ltr"?[0,o]:[o*-1,0],g=Et(s,d);return at([0,o],[0,m])(g)}function at(s,c){return r=>{if(s[0]===s[1]||c[0]===c[1])return c[0];const t=(c[1]-c[0])/(s[1]-s[0]);return c[0]+t*(r-s[0])}}function it(s,c){return s>0&&s<c}var Ir=(s,c=()=>{})=>{let r={left:s.scrollLeft,top:s.scrollTop},t=0;return function n(){const l={left:s.scrollLeft,top:s.scrollTop},o=r.left!==l.left,m=r.top!==l.top;(o||m)&&c(),r=l,t=window.requestAnimationFrame(n)}(),()=>window.cancelAnimationFrame(t)};function ss(s,c){const r=Ne(s),t=i.useRef(0);return i.useEffect(()=>()=>window.clearTimeout(t.current),[]),i.useCallback(()=>{window.clearTimeout(t.current),t.current=window.setTimeout(r,c)},[r,c])}function Ie(s,c){const r=Ne(c);jt(()=>{let t=0;if(s){const n=new ResizeObserver(()=>{cancelAnimationFrame(t),t=window.requestAnimationFrame(r)});return n.observe(s),()=>{window.cancelAnimationFrame(t),n.unobserve(s)}}},[s,r])}var nt=Gs,zr=Xs,Mr=tt;const ls=i.forwardRef(({className:s,children:c,...r},t)=>e.jsxs(nt,{ref:t,className:Is("relative overflow-hidden",s),...r,children:[e.jsx(zr,{className:"h-full w-full rounded-[inherit]",children:c}),e.jsx(lt,{}),e.jsx(Mr,{})]}));ls.displayName=nt.displayName;const lt=i.forwardRef(({className:s,orientation:c="vertical",...r},t)=>e.jsx(ms,{ref:t,orientation:c,className:Is("flex touch-none select-none transition-colors",c==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",c==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",s),...r,children:e.jsx(st,{className:"relative flex-1 rounded-full bg-border"})}));lt.displayName=ms.displayName;const Fr=()=>{const[s,c]=i.useState([]),[r,t]=i.useState(null),[n,l]=i.useState(""),[o,m]=i.useState(!0),[d,g]=i.useState({totalConversations:0,totalMessages:0,inboundReplies:0,activeThreads:0});i.useEffect(()=>{f()},[]);const f=async()=>{var S;m(!0);try{const{data:u}=await R.from("demo_nurture_campaigns").select("id, email, first_name, business_name, status, emails_sent, created_at, updated_at, metadata").order("updated_at",{ascending:!1}),x=(u||[]).map(a=>a.id),{data:_}=x.length>0?await R.from("email_conversations").select("*").in("campaign_id",x).order("created_at",{ascending:!0}):{data:[]},{data:p}=await R.from("email_conversations").select("*").is("campaign_id",null).order("created_at",{ascending:!1}).limit(50),v=new Map;
283(_||[]).forEach(a=>{const k=v.get(a.campaign_id)||[];k.push(a),v.set(a.campaign_id,k)});const h=(u||[]).filter(a=>{const k=v.get(a.id);return k&&k.length>0}).map(a=>{const k=v.get(a.id)||[],D=k.some($=>$.direction==="inbound"),E=k[k.length-1];return{campaign_id:a.id,email:a.email,business_name:a.business_name,first_name:a.first_name,status:a.status,emails_sent:a.emails_sent,messages:k,last_message_at:(E==null?void 0:E.created_at)||a.updated_at,has_inbound:D}}).sort((a,k)=>a.has_inbound!==k.has_inbound?a.has_inbound?-1:1:new Date(k.last_message_at).getTime()-new Date(a.last_message_at).getTime());p&&p.length>0&&h.push({campaign_id:"__unmatched__",email:"Various",business_name:"Unmatched Inbound",first_name:null,status:"unmatched",emails_sent:0,messages:p,last_message_at:((S=p[0])==null?void 0:S.created_at)||"",has_inbound:!0}),c(h);const y=[..._||[],...p||[]];g({totalConversations:h.length,totalMessages:y.length,inboundReplies:y.filter(a=>a.direction==="inbound").length,activeThreads:h.filter(a=>a.has_inbound&&a.status==="active").length}),h.length>0&&!r&&t(h[0].campaign_id)}catch(u){console.error("Error loading conversations:",u)}finally{m(!1)}},b=s.filter(S=>S.email.toLowerCase().includes(n.toLowerCase())||S.business_name.toLowerCase().includes(n.toLowerCase())||(S.first_name||"").toLowerCase().includes(n.toLowerCase())),N=s.find(S=>S.campaign_id===r),w=S=>{switch(S){case"active":return"bg-green-500/10 text-green-600 border-green-200";case"replying":return"bg-purple-500/10 text-purple-600 border-purple-200";case"converted":return"bg-blue-500/10 text-blue-600 border-blue-200";case"unsubscribed":return"bg-red-500/10 text-red-600 border-red-200";case"paused":return"bg-yellow-500/10 text-yellow-600 border-yellow-200";case"completed":return"bg-gray-500/10 text-gray-600 border-gray-200";default:return"bg-muted text-muted-foreground"}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs(j,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(_s,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Conversations"})]}),e.jsx("p",{className:"text-2xl font-bold",children:d.totalConversations})]}),e.jsxs(j,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ie,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Messages"})]}),e.jsx("p",{className:"text-2xl font-bold",children:d.totalMessages})]}),e.jsxs(j,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ir,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Inbound Replies"})]}),e.jsx("p",{className:"text-2xl font-bold",children:d.inboundReplies})]}),e.jsxs(j,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Cs,{className:"h-4 w-4 text-blue-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Active Threads"})]}),e.jsx("p",{className:"text-2xl font-bold",children:d.activeThreads})]})]}),e.jsx(j,{className:"overflow-hidden",children:e.jsxs("div",{className:"flex h-[600px]",children:[e.jsxs("div",{className:"w-80 border-r flex flex-col",children:[e.jsxs("div",{className:"p-3 border-b flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Pe,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ue,{placeholder:"Search...",value:n,onChange:S=>l(S.target.value),className:"pl-8 h-8 text-sm"})]}),e.jsx(Y,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:f,children:e.jsx(ee,{className:`h-4 w-4 ${o?"animate-spin":""}`})})]}),e.jsx(ls,{className:"flex-1",children:b.length===0?e.jsx("div",{className:"p-6 text-center text-muted-foreground text-sm",children:o?"Loading...":"No conversations yet"}):b.map(S=>e.jsxs("button",{onClick:()=>t(S.campaign_id),className:`w-full text-left p-3 border-b hover:bg-muted/50 transition-colors ${r===S.campaign_id?"bg-muted":""}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"font-medium text-sm truncate max-w-[180px]",children:S.first_name||S.email.split("@")[0]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Bs(new Date(S.last_message_at),{addSuffix:!0})})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:S.business_name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(H,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${w(S.status)}`,children:S.status}),S.has_inbound&&e.jsx(H,{variant:"outline",className:"text-[10px] px-1.5 py-0 bg-green-500/10 text-green-600 border-green-200",children:"replied"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground ml-auto",children:[S.messages.length," msgs"]})]})]},S.campaign_id))})]}),e.jsx("div",{className:"flex-1 flex flex-col",children:N?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"p-4 border-b bg-muted/30",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:N.first_name||N.email}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[N.email," — ",N.business_name]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(H,{variant:"outline",className:w(N.status),children:N.status}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[N.emails_sent," emails sent"]})]})]})}),e.jsx(ls,{className:"flex-1 p-4",children:e.jsx("div",{className:"space-y-4 max-w-2xl mx-auto",children:N.messages.map(S=>{var x,_;const u=S.direction==="inbound";return e.jsx("div",{className:`flex ${u?"justify-start":"justify-end"}`,children:e.jsxs("div",{className:`max-w-[80%] rounded-lg p-3 ${u?"bg-muted border":"bg-primary/10 border border-primary/20"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[u?e.jsx($s,{className:"h-3 w-3 text-green-600"}):e.jsx(Cs,{className:"h-3 w-3 text-primary"}),e.jsx("span",{className:"text-xs font-medium",children:u?S.from_email:"Zach (AI)"}),S.ai_model_used&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["via ",S.ai_model_used.split("/").pop()]})]}),S.subject&&e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:S.subject}),e.jsxs("div",{className:"text-sm whitespace-pre-wrap break-words",children:[(x=S.body_text)==null?void 0:x.slice(0,1e3),(((_=S.body_text)==null?void 0:_.length)||0)>1e3&&e.jsx("span",{className:"text-muted-foreground",children:"... (truncated)"})]}),e.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[e.jsx(pe,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Ys(new Date(S.created_at),"MMM d, yyyy h:mm a")})]})]})},S.id)})})})]}):e.jsx("div",{className:"flex-1 flex items-center justify-center text-muted-foreground",children:e.jsxs("div",{className:"text-center",children:[e.jsx(_s,{className:"h-12 w-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{children:"Select a conversation to view"})]})})})]})})]})},Ts="https://aisearchaudit.co?utm_source=sendgrid&utm_medium=email&utm_campaign=ai-visibility-launch",Ls="sendgrid",Es=300,$r="2026-03-25T23:59:59Z",Br=389,Ds=s=>(s||"").trim().toLowerCase(),Or=()=>{const[s,c]=i.useState([]),[r,t]=i.useState([]),[n,l]=i.useState(0),[o,m]=i.useState(!0),[d,g]=i.useState(!0),[f,b]=i.useState(!1);i.useEffect(()=>{N(),w()},[]);const N=async()=>{m(!0);const{data:T,error:I}=await R.from("webinar_page_analytics").select("*").order("created_at",{ascending:!1}).limit(1e3);!I&&T&&c(T),m(!1)},w=async()=>{g(!0);try{const{data:T,error:I}=await R.functions.invoke("list-webinar-registrants",{body:{}});!I&&(T!=null&&T.registrants)&&(t(T.registrants),l(T.totalRegistrants||T.registrants.length))}catch(T){console.error("Failed to load GoToWebinar registrants:",T)}g(!1)},S=()=>{navigator.clipboard.writeText(Ts),b(!0),setTimeout(()=>b(!1),2e3)},u=s.filter(T=>T.event_type==="registration"),x=s.filter(T=>["page_view","unique_page_view"].includes(T.event_type)),_=x.filter(T=>
283Ds(T.utm_source)===Ls),p=new Set(_.map(T=>T.visitor_id)).size,v=Math.max(0,p-Br),h=Es+v,y=_.length,a=x.length,k=new Map;u.forEach(T=>{T.email&&k.set(T.email.toLowerCase(),{utm_source:T.utm_source||void 0,utm_medium:T.utm_medium||void 0,utm_campaign:T.utm_campaign||void 0,referrer:T.referrer||void 0})});const D=r.map(T=>{const I=k.get(T.email.toLowerCase());return{...T,utm_source:(I==null?void 0:I.utm_source)||null,utm_medium:(I==null?void 0:I.utm_medium)||null,utm_campaign:(I==null?void 0:I.utm_campaign)||null,referrer:(I==null?void 0:I.referrer)||null,hasTracking:!!I}}),E=D.filter(T=>Ds(T.utm_source)===Ls).length,$=h>0?(n/h*100).toFixed(1):"0.0";return o&&d?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 border-4 border-primary/30 border-t-primary rounded-full animate-spin"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(j,{className:"p-4 border-2 border-amber-200 bg-amber-50/50",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"p-2 bg-amber-100 rounded-lg mt-0.5",children:e.jsx(Xt,{className:"h-5 w-5 text-amber-700"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-amber-900",children:"Tracking Link — Use This in All Emails"}),e.jsx("p",{className:"text-xs text-amber-700 mt-1 mb-2",children:"aisearchaudit.co auto-redirects to /aeo-webinar with UTM params. All clicks are tracked."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"text-xs bg-white border border-amber-200 rounded px-2 py-1.5 text-amber-900 truncate flex-1",children:Ts}),e.jsx(Y,{variant:"outline",size:"sm",onClick:S,className:"shrink-0 border-amber-300 hover:bg-amber-100",children:f?"Copied!":"Copy"})]})]})]})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide",children:"Webinar Traffic (Email-Tracked)"}),e.jsxs(Y,{variant:"outline",size:"sm",onClick:()=>{N(),w()},disabled:o||d,children:[e.jsx(ee,{className:`h-4 w-4 mr-1 ${o||d?"animate-spin":""}`}),"Refresh"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:["Baseline: ",Es," SendGrid unique clicks (as of ",new Date($r).toLocaleDateString(),") + new JS-tracked visitors after that date."]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs(j,{className:"p-5 border-2 border-blue-200 bg-blue-50/30",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(Kt,{className:"h-5 w-5 text-blue-600"})}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Email Unique Visitors"})]}),e.jsx("p",{className:"text-3xl font-bold",children:h}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Deduplicated by visitor_id"})]}),e.jsxs(j,{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"p-2 bg-indigo-100 rounded-lg",children:e.jsx(Ce,{className:"h-5 w-5 text-indigo-600"})}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Email Total Visits"})]}),e.jsx("p",{className:"text-3xl font-bold",children:y}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["All-source visits: ",a]})]}),e.jsxs(j,{className:"p-5 border-2 border-primary/20 bg-primary/5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"p-2 bg-green-100 rounded-lg",children:e.jsx(Us,{className:"h-5 w-5 text-green-600"})}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Total Registrations"})]}),e.jsx("p",{className:"text-3xl font-bold",children:d?"...":n}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:d?"Live from GoToWebinar":`${E} tracked from sendgrid source`})]}),e.jsxs(j,{className:"p-5 border-2 border-green-200 bg-green-50/30",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"p-2 bg-green-100 rounded-lg",children:e.jsx(ve,{className:"h-5 w-5 text-green-600"})}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Conversion Rate"})]}),e.jsxs("p",{className:"text-3xl font-bold",children:[d?"...":$,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[d?"...":n," regs / ",h," unique visitors"]})]})]})]}),e.jsxs(j,{className:"p-6",children:[e.jsxs("h3",{className:"text-lg font-semibold mb-4",children:["All Registrations (",d?"...":n,")"]}),d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 border-4 border-primary/30 border-t-primary rounded-full animate-spin"})}):D.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No registrations yet."}):e.jsx("div",{className:"max-h-[600px] overflow-y-auto",children:e.jsxs(oe,{children:[e.jsx(ce,{children:e.jsxs(Q,{children:[e.jsx(L,{children:"#"}),e.jsx(L,{children:"Name"}),e.jsx(L,{children:"Email"}),e.jsx(L,{children:"Source"}),e.jsx(L,{children:"Referrer"}),e.jsx(L,{children:"Registered"})]})}),e.jsx(de,{children:[...D].sort((T,I)=>new Date(I.registrationDate).getTime()-new Date(T.registrationDate).getTime()).map((T,I)=>e.jsxs(Q,{children:[e.jsx(A,{className:"text-muted-foreground",children:I+1}),e.jsxs(A,{className:"font-medium",children:[T.firstName," ",T.lastName]}),e.jsx(A,{children:T.email}),e.jsx(A,{children:T.utm_source?e.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800",children:[T.utm_source,T.utm_campaign?` / ${T.utm_campaign}`:""]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}),e.jsx(A,{className:"max-w-[150px] truncate text-xs text-muted-foreground",children:T.referrer||"—"}),e.jsx(A,{className:"text-xs",children:new Date(T.registrationDate).toLocaleStr
283ing()})]},T.email+T.registrationDate))})]})})]})]})},Ur=s=>new Date(s).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Wr=(s,c)=>{const r=["Full Name","Email","Source","Signed Up"],t=d=>`"${(d??"").replace(/"/g,'""')}"`,n=[r.join(","),...s.map(d=>[d.full_name,d.email,d.source??"",d.created_at].map(t).join(","))].join(`
284`),l=new Blob([n],{type:"text/csv;charset=utf-8;"}),o=URL.createObjectURL(l),m=document.createElement("a");m.href=o,m.download=c,m.click(),URL.revokeObjectURL(o)},Ps=({rows:s,loading:c,filename:r,emptyLabel:t})=>{const[n,l]=i.useState(""),o=s.filter(m=>{const d=n.toLowerCase();return m.full_name.toLowerCase().includes(d)||m.email.toLowerCase().includes(d)||(m.source??"").toLowerCase().includes(d)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"relative w-full max-w-sm",children:[e.jsx(Pe,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ue,{placeholder:"Search name, email, source...",value:n,onChange:m=>l(m.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(H,{variant:"secondary",className:"gap-1",children:[e.jsx(Re,{className:"h-3 w-3"}),s.length," total"]}),e.jsxs(Y,{variant:"outline",size:"sm",onClick:()=>Wr(o,r),disabled:o.length===0,children:[e.jsx(Fs,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]})]}),c?e.jsx("div",{className:"py-12 text-center text-muted-foreground",children:"Loading..."}):o.length===0?e.jsxs("div",{className:"py-12 text-center",children:[e.jsx(ie,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium",children:t})]}):e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"grid grid-cols-12 gap-4 px-4 py-3 text-xs font-semibold uppercase text-muted-foreground border-b bg-muted/30",children:[e.jsx("div",{className:"col-span-3",children:"Name"}),e.jsx("div",{className:"col-span-4",children:"Email"}),e.jsx("div",{className:"col-span-2",children:"Source"}),e.jsx("div",{className:"col-span-3",children:"Signed Up"})]}),e.jsx("div",{className:"divide-y",children:o.map(m=>e.jsxs("div",{className:"grid grid-cols-12 gap-4 px-4 py-3 text-sm items-center hover:bg-muted/20 transition-colors",children:[e.jsx("div",{className:"col-span-3 font-medium",children:m.full_name}),e.jsx("div",{className:"col-span-4 text-muted-foreground truncate",children:m.email}),e.jsx("div",{className:"col-span-2",children:e.jsx(H,{variant:"outline",className:"text-xs",children:m.source??"—"})}),e.jsx("div",{className:"col-span-3 text-muted-foreground",children:Ur(m.created_at)})]},m.id))})]})]})},Vr=()=>{const{toast:s}=ne(),[c,r]=i.useState([]),[t,n]=i.useState([]),[l,o]=i.useState(!0),[m,d]=i.useState(!0);return i.useEffect(()=>{(async()=>{try{const{data:f,error:b}=await R.from("aeo_waitlist").select("id, full_name, email, source, created_at").order("created_at",{ascending:!1});if(b)throw b;r(f??[])}catch(f){s({title:"Failed to load AI Search Audit waitlist",description:f.message,variant:"destructive"})}finally{o(!1)}try{const{data:f,error:b}=await R.from("reviewroi_waitlist").select("id, full_name, email, source, created_at").order("created_at",{ascending:!1});if(b)throw b;n(f??[])}catch(f){s({title:"Failed to load ReviewROI waitlist",description:f.message,variant:"destructive"})}finally{d(!1)}})()},[s]),e.jsxs(j,{className:"p-6 bg-gradient-card shadow-card",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Waitlists"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"People who signed up to be notified when enrollment opens."})]}),e.jsxs(We,{defaultValue:"aeo",className:"space-y-4",children:[e.jsxs(Ve,{children:[e.jsxs(J,{value:"aeo",children:["AI Search Audit (",c.length,")"]}),e.jsxs(J,{value:"review",children:["ReviewROI (",t.length,")"]})]}),e.jsx(X,{value:"aeo",children:e.jsx(Ps,{rows:c,loading:l,filename:`aisearchaudit-waitlist-${new Date().toISOString().split("T")[0]}.csv`,emptyLabel:"No AI Search Audit waitlist signups yet"})}),e.jsx(X,{value:"review",children:e.jsx(Ps,{rows:t,loading:m,filename:`reviewroi-waitlist-${new Date().toISOString().split("T")[0]}.csv`,emptyLabel:"No ReviewROI waitlist signups yet"})})]})]})},ki=()=>{const s=bt(),{toast:c}=ne(),{startImpersonation:r,isImpersonating:t,impersonatedAgency:n}=vt();i.useEffect(()=>{if(!t||!(n!=null&&n.id))return;let a=!1;return(async()=>{let k="/dashboard";try{const{data:D}=await R.from("subscriptions").select("product_type, plans:plan_i
284d(prospector_enabled, aeo_enabled, review_roi_enabled, plan_modules(module_key))").eq("agency_id",n.id).in("status",["active","trialing"]),E=js(D);k=bs(E)}catch(D){console.error("[SuperAdmin] Failed to resolve dashboard target while impersonating",D)}a||s(k,{replace:!0})})(),()=>{a=!0}},[t,n==null?void 0:n.id,s]);const[l,o]=i.useState(!0),[m,d]=i.useState([]),[g,f]=i.useState(""),[b,N]=i.useState(null),[w,S]=i.useState({totalAgencies:0,totalUsers:0,totalReports:0,totalRevenue:0,mrr:0}),[u,x]=i.useState("agencies"),[_,p]=Nt();i.useEffect(()=>{const a=_.get("t");a&&["agencies","emails","queue","analytics","audit","tools","tracking","orphaned","stripe-sync","funnel","demo-leads","nurture","conversations","webinar","waitlist"].includes(a)?x(a):x("agencies")},[_]),i.useEffect(()=>{v()},[]),i.useEffect(()=>{l||h()},[l]),i.useEffect(()=>{if(!l){const a=setInterval(()=>{h()},3e4);return()=>clearInterval(a)}},[l]);const v=async()=>{const{data:{user:a}}=await R.auth.getUser();if(!a){s("/auth");return}const{data:k}=await R.from("user_roles").select("role").eq("user_id",a.id).eq("role","super_admin");if(!k||k.length===0){c({title:"Access Denied",description:"Super admin access required",variant:"destructive"}),s("/unauthorized");return}o(!1)},h=async()=>{try{const{data:a,error:k}=await R.from("agencies").select("*").order("created_at",{ascending:!1});if(k)throw k;const{data:D}=await R.from("agency_users").select("agency_id, user_id, created_at").order("created_at",{ascending:!0}),E=new Map;(D||[]).forEach(F=>{E.has(F.agency_id)||E.set(F.agency_id,F.user_id)});const $=Array.from(E.values()),{data:T}=$.length>0?await R.from("profiles").select("id, email").in("id",$):{data:[]},I=new Map;(T||[]).forEach(F=>{I.set(F.id,F.email)});const xe=new Map;E.forEach((F,z)=>{const Z=I.get(F);Z&&xe.set(z,Z)});const{data:re}=await R.from("reports").select("agency_id, id"),{data:ae}=await R.from("leads").select("agency_id, id, status"),{data:ue}=await R.from("subscriptions").select("agency_id, status, reports_used, plan_id, manual_tier_override, override_tier"),U=Array.from(new Set((ue||[]).map(F=>F.plan_id).filter(Boolean))),{data:G}=U.length>0?await R.from("plans").select("id, name, price, billing_interval, tier").in("id",U):{data:[]},he=new Map((ue||[]).map(F=>[F.agency_id,F])),ke=new Map((G||[]).map(F=>[F.id,F])),{data:C}=await R.from("agency_onboarding_status").select("agency_id, upgrade_flow_completed, branding_setup_completed"),q=new Map((C||[]).map(F=>[F.agency_id,F])),P=(a||[]).map(F=>{const z=he.get(F.id),Z=z?ke.get(z.plan_id):null,ot=(re||[]).filter(Me=>Me.agency_id===F.id),hs=(ae||[]).filter(Me=>Me.agency_id===F.id),ct=hs.filter(Me=>Me.status==="opted_in"),ts=hs.length,ps=ct.length,dt=ts>0?(ps/ts*100).toFixed(1):"0",gs=(Z==null?void 0:Z.billing_interval)==="lifetime",mt=(Z==null?void 0:Z.price)||0,xt=(Z==null?void 0:Z.name)||"No plan",ut=z!=null&&z.manual_tier_override&&(z!=null&&z.override_tier)?z.override_tier:(Z==null?void 0:Z.tier)||"basic",ht=!!z,fs=(z==null?void 0:z.manual_tier_override)||!1,pt=fs?"Manual Override":gs?"Lifetime Active":(z==null?void 0:z.status)||"No subscription",Ae=q.get(F.id),gt=!!(Ae!=null&&Ae.upgrade_flow_completed&&(Ae!=null&&Ae.branding_setup_completed));return{...F,searchesPerformed:ts,totalLeads:ps,conversionRate:dt,totalReports:ot.length,revenue:mt,isLifetime:gs,hasSubscription:ht,displayStatus:pt,subscriptionStatus:(z==null?void 0:z.status)||null,planName:xt,tier:ut,isManualOverride:fs,registrationEmail:xe.get(F.id)||null,onboardingComplete:gt}});d(P);const M=(re==null?void 0:re.length)||0,K=(ae==null?void 0:ae.length)||0,se=P.reduce((F,z)=>F+(z.revenue||0),0);console.log("[SuperAdmin] Total Revenue Calculation:",{agencyCount:P.length,totalRevenue:se,agencies:P.map(F=>({name:F.name,revenue:F.revenue,isLifetime:F.isLifetime}))});const qe=P.filter(F=>!F.isLifetime&&F.subscriptionStatus==="active").reduce((F,z)=>F+(z.revenue||0),0);S({totalAgencies:P.length,totalUsers:K,totalReports:M,totalRevenue:se,mrr:qe})}catch(a){c({title:"Error loading dashboard data",description:a.message,variant:"destructive"})}},y=m.filter(a=>a.name.toLowerCase().includes(g.toLowerCase())||a.slug.toLowerCase().includes(g.toLowerCase())||a.registrationEmail&&a.registrationEmail.toLowerCase().includes(g.toLowerCase()));return l||t?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 border-4 border-primary/30 border-t-primary rounded-full animate-spin"})}):e.jsxs(yt,{userRole:"super_admin",pageTitle:"System Dashboard",pageDescription:"Central hub for platform health and agency management",onAgencyCreated:h,children:[e.jsxs(We,{value:u,onValueChange:a=>{x(a);const k=new URLSearchParams(_);k.set("t",a),p(k,{replace:!0})},className:"space-y-6",children:[e.jsxs(Ve,{children:[e.jsx(J,{value:"agencies",children:"Agencies"}),e.jsx(J,{value:"funnel",children:"📊 Funnel"}),e.jsx(J,{value:"demo-leads",children:"🎯 Demo Leads"}),e.jsx(J,{value:"nurture",children:"🌱 Nurture"}),e.jsx(J,{value:"conversations",children:"💬 Conversations"}),e.jsx(J,{value:"tracking",children:"Signup Tracking"}),e.jsx(J,{value:"emails",children:"Emails"}),e.jsx(J,{value:"queue",children:"Job Queue"}),e.jsx(J,{value:"analytics",children:"Tier Analytics"}),e.jsx(J,{value:"orphaned",children:"Orphaned Reports"}),e.jsx(J,{value:"stripe-sync",children:"Stripe Sync"}),e.jsx(J,{value:"audit",children:"Audit Logs"}),e.jsx(J,{value:"webinar",children:"🎙️ Webinar"}),e.jsx(J,{value:"waitlist",children:"📝 Waitlist"}),e.jsx(J,{value:"tools",children:"System Tools"})]}),e.jsxs(X,{value:"agencies",className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 ga
284p-6",children:[e.jsxs(j,{className:"p-6 bg-gradient-card shadow-card hover:shadow-lg transition-all",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Ee,{className:"h-5 w-5 text-primary"})}),e.jsx("h3",{className:"font-semibold text-sm text-muted-foreground",children:"Agencies"})]}),e.jsx("p",{className:"text-3xl font-bold",children:w.totalAgencies})]}),e.jsxs(j,{className:"p-6 bg-gradient-card shadow-card hover:shadow-lg transition-all",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"p-2 bg-accent/10 rounded-lg",children:e.jsx(Re,{className:"h-5 w-5 text-accent"})}),e.jsx("h3",{className:"font-semibold text-sm text-muted-foreground",children:"Total Leads"})]}),e.jsx("p",{className:"text-3xl font-bold",children:w.totalUsers})]}),e.jsxs(j,{className:"p-6 bg-gradient-card shadow-card hover:shadow-lg transition-all",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"p-2 bg-success/10 rounded-lg",children:e.jsx(ye,{className:"h-5 w-5 text-success"})}),e.jsx("h3",{className:"font-semibold text-sm text-muted-foreground",children:"Reports"})]}),e.jsx("p",{className:"text-3xl font-bold",children:w.totalReports})]}),e.jsxs(j,{className:"p-6 bg-gradient-card shadow-card hover:shadow-lg transition-all",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(rr,{className:"h-5 w-5 text-primary"})}),e.jsx("h3",{className:"font-semibold text-sm text-muted-foreground",children:"MRR"})]}),e.jsxs("p",{className:"text-3xl font-bold",children:["$",w.mrr.toFixed(0)]})]}),e.jsxs(j,{className:"p-6 bg-gradient-premium shadow-card hover:shadow-lg transition-all border border-primary/20",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"p-2 bg-success/10 rounded-lg",children:e.jsx(ve,{className:"h-5 w-5 text-success"})}),e.jsx("h3",{className:"font-semibold text-sm text-muted-foreground",children:"Total Revenue"})]}),e.jsxs("p",{className:"text-3xl font-bold",children:["$",w.totalRevenue.toFixed(0)]})]})]}),e.jsxs(j,{className:"p-6 bg-gradient-card shadow-card",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Agencies Overview"}),e.jsxs("div",{className:"relative w-80",children:[e.jsx(Pe,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ue,{placeholder:"Search agencies...",value:g,onChange:a=>f(a.target.value),className:"pl-10"})]})]}),y.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ee,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4"}),e.jsx("p",{className:"text-lg font-semibold mb-2",children:g?"No agencies found":"No agencies yet"}),e.jsx("p",{className:"text-muted-foreground",children:g?"Try a different search term":"Create your first agency to get started"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-12 gap-4 px-4 py-2 text-sm font-semibold text-muted-foreground border-b",children:[e.jsx("div",{className:"col-span-2",children:"Agency"}),e.jsx("div",{className:"col-span-1 text-center",children:"Searches"}),e.jsx("div",{className:"col-span-1 text-center",children:"Leads"}),e.jsx("div",{className:"col-span-1 text-center",children:"Conv. Rate"}),e.jsx("div",{className:"col-span-1 text-center",children:"Reports"}),e.jsx("div",{className:"col-span-2 text-center",children:"Revenue"}),e.jsx("div",{className:"col-span-1 text-center",children:"Status"}),e.jsx("div",{className:"col-span-2 text-center",children:"Tier"}),e.jsx("div",{className:"col-span-1 text-right",children:"Actions"})]}),y.map(a=>e.jsxs("div",{className:"grid grid-cols-12 gap-4 px-4 py-4 bg-background rounded-lg border hover:border-primary/50 transition-all items-center",children:[e.jsxs("div",{className:"col-span-2 flex items-center gap-3",children:[a.logo_url?e.jsx("img",{src:a.logo_url,alt:a.name,className:"h-10 w-10 rounded-lg object-cover"}):e.jsx("div",{className:"h-10 w-10 bg-primary/10 rounded-lg flex items-center justify-center",children:e.jsx(Ee,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:a.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["/",a.slug]}),a.registrationEmail&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ie,{className:"h-3 w-3"}),a.registrationEmail]}),e.jsx(H,{variant:"outline",className:"mt-1 text-[10px] px-1.5 py-0 "+(a.onboardingComplete?"bg-emerald-500/10 text-emerald-600 border-emerald-500/30":"bg-amber-500/10 text-amber-600 border-amber-500/30"),children:a.onboardingComplete?"Onboarded":"Onboarding incomplete"})]})]}),e.jsx("div",{className:"col-span-1 text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Pe,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"font-semibold",children:a.searchesPerformed})]})}),e.jsx("div",{className:"col-span-1 text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ie,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"font-semibold",children:a.totalLeads})]})}),e.jsx("div",{className:"col-span-1 text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Je,{className:"h-3 w-3 text-muted-foreground"}),e.jsxs("span",{className:"font-semibold",children:[a.conversionRate,"%"]})]})}),e.jsx("div",{className:"col-span-1 text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ye,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"font-semibold",children:a.totalReports})]})}),e.jsx("div",{className:"col-span-2 text-center",children:e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsxs("span",{className:"font-semibold",children:["$",a.revenue,a.isLifetime?" (lifetime)":"/mo"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a.planName})]})}),e.jsx("div",{className:"col-span-1 text-center",children:e.jsx(H,{variant:a.displayStatus==="No subscription"?"secondary":"default",className:a.displayStatus==="Manual Override"?"bg-orange-500/10 text-orange-500 border-orange-500/20":a.displayStatus.includes("Active")?"bg-green-500/10 text-green-500 border-green-500/20":"",children:a.displayStatus})}),e.jsx("div",{className:"col-span-2",children:e.jsx(cr,{agencyId:a.id,currentTier:a.tier,onTierUpd
284ated:h})}),e.jsx("div",{className:"col-span-1 flex items-center justify-end",children:e.jsxs(Zt,{children:[e.jsx(er,{asChild:!0,children:e.jsx(Y,{variant:"outline",size:"sm",children:e.jsx(ar,{className:"h-4 w-4"})})}),e.jsxs(sr,{align:"end",className:"w-48",children:[e.jsx(tr,{children:"Agency Actions"}),e.jsx(Rs,{}),e.jsxs(ks,{onClick:()=>{console.log("[SuperAdmin] View Details clicked for agency:",a.id),N(a.id)},children:[e.jsx(cs,{className:"h-4 w-4 mr-2"}),"View Details"]}),e.jsx(Rs,{}),e.jsxs(ks,{onClick:async()=>{console.log("[SuperAdmin] Impersonate clicked for agency:",{id:a.id,name:a.name,slug:a.slug}),r({id:a.id,name:a.name,slug:a.slug});let k="/dashboard";try{const{data:D}=await R.from("subscriptions").select("product_type, plans:plan_id(prospector_enabled, aeo_enabled, review_roi_enabled, plan_modules(module_key))").eq("agency_id",a.id).in("status",["active","trialing"]),E=js(D);k=bs(E)}catch(D){console.error("[SuperAdmin] Failed to resolve impersonation target",D)}setTimeout(()=>{console.log("[SuperAdmin] Navigating to",k),s(k)},150)},children:[e.jsx(lr,{className:"h-4 w-4 mr-2"}),"Impersonate"]})]})]})})]},a.id))]})]})]}),e.jsx(X,{value:"tracking",children:e.jsx(jr,{})}),e.jsx(X,{value:"emails",children:e.jsx(gr,{})}),e.jsx(X,{value:"queue",children:e.jsx(dr,{})}),e.jsx(X,{value:"analytics",children:e.jsx(mr,{})}),e.jsx(X,{value:"orphaned",children:e.jsx(br,{})}),e.jsx(X,{value:"audit",children:e.jsx(xr,{})}),e.jsx(X,{value:"tools",children:e.jsx(ur,{})}),e.jsx(X,{value:"stripe-sync",children:e.jsx(vr,{})}),e.jsx(X,{value:"funnel",children:e.jsx(Nr,{})}),e.jsx(X,{value:"demo-leads",children:e.jsx(wr,{})}),e.jsx(X,{value:"nurture",children:e.jsx(Sr,{})}),e.jsx(X,{value:"conversations",children:e.jsx(Fr,{})}),e.jsx(X,{value:"webinar",children:e.jsx(Or,{})}),e.jsx(X,{value:"waitlist",children:e.jsx(Vr,{})})]}),e.jsx(or,{agencyId:b,onClose:()=>N(null)})]})};export{ki 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.