PageSourceSearch

https://allocationchat-production.up.railway.app/assets/AdminDashboard-CmtMD3df.js

js allocationchat-production.up.railway.app collected 2026-10-03 12:11:14 UTC 55,872 bytes, 1 lines download raw bytes

1import{o as Le,U as Me,a6 as He,h as Ae,aJ as Je,aK as Ye,aL as Xe,aM as Ee,j as e,C as H,a as ee,b as se,e as J,r as n,aN as De,s as h,F as T,aO as Ze,B as O,g as ae,Z as ve,d as ne,a7 as Re,aP as $e,aQ as qe,f as we,m as ke,aR as Qe,aS as ze,aT as es,I as Be,aU as ss,u as z,L as ie,R as ts,ay as as,ae as ns,T as We,q as Ge,t as Z,M as rs,ag as ls,x as Q,G as is,aV as os,K as cs,af as Ue}from"./index-DBnK5Ebt.js";import{T as Ne,a as be,b as te,c as v,d as ye,e as j}from"./table-DUNx-voj.js";import{C as ds,S as B,a as W,b as G,c as K,d as g}from"./select-DHqBjKMR.js";import{C as us,a as ms,b as xs}from"./collapsible-D-LsY3uj.js";import{S as he}from"./switch-Bmav1MoG.js";import{T as hs,R as ps,A as js,C as fs,X as _s,Y as gs,a as vs,L as Ns,b as Se}from"./AreaChart-qRsAFMM6.js";import{C as bs,E as ys,S as Cs,B as ws,N as Ss}from"./NotificationLog-BK5mTE0U.js";import{L as Ve,U as ks}from"./unlink-CwUJOd6N.js";import{S as Ls}from"./save-qnTkXPh-.js";import"./index-vEARVTCU.js";import"./circle-check-xGskycB-.js";import"./file-text-D-xf-QYX.js";import"./image-DePik4tO.js";function As({stats:r}){const s=[{title:"Total Clients",value:r.totalClients,sub:"Website owners",icon:Le},{title:"Total Agents",value:r.totalAgents,sub:"Chat representatives",icon:Me},{title:"Properties",value:r.totalProperties,sub:"Websites with widget",icon:He},{title:"Conversations",value:r.totalConversations,sub:"All time",icon:Ae},{title:"Active Chats",value:r.activeConversations,sub:"Active & pending",icon:Je,highlight:!0},{title:"Phones Captured",value:r.totalPhones,sub:"Visitors with phone",icon:Ye},{title:"Total Leads",value:r.totalLeads,sub:"Name, email, or phone",icon:Xe},{title:"Open Complaints",value:r.openComplaints,sub:"Needs attention",icon:Ee,warn:r.openComplaints>0}];return e.jsx("div",{className:"grid gap-4 md:grid-cols-4 mb-8",children:s.map(d=>e.jsxs(H,{children:[e.jsxs(ee,{className:"flex flex-row items-center justify-between pb-2",children:[e.jsx(se,{className:"text-sm font-medium",children:d.title}),e.jsx(d.icon,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(J,{children:[e.jsx("div",{className:`text-2xl font-bold ${d.highlight?"text-green-600":""} ${d.warn?"text-destructive":""}`,children:d.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.sub})]})]},d.title))})}const Es={active:"default",comped:"default",trialing:"secondary",past_due:"destructive",incomplete:"destructive",canceled:"outline",trial_expired:"outline",no_subscription:"outline"},Ds=new Set(["past_due","incomplete","canceled","trial_expired","no_subscription"]);function Ts({userId:r}){const[s,d]=n.useState(null),[L,y]=n.useState(!0),[A,f]=n.useState(!1),[m,x]=n.useState(!1),{toast:u}=De();n.useEffect(()=>{h.from("subscriptions").select("*").eq("user_id",r).maybeSingle().then(({data:F})=>{d(F),y(!1)})},[r]);const o=async F=>{f(!0);const c=F?{is_comped:!0,status:"comped"}:{is_comped:!1,status:"trialing"},{error:M}=await h.from("subscriptions").update(c).eq("user_id",r);M?u({title:"Error",description:"Failed to update comp status",variant:"destructive"}):(d(V=>V&&{...V,...c}),u({title:"Success",description:F?"Account comped":"Comp removed"})),f(!1)},p=async()=>{x(!0);const{error:F}=await h.functions.invoke("send-payment-reminders",{body:{userId:r}});F?u({title:"Failed to send reminder",description:F.message,variant:"destructive"}):(d(c=>c&&{...c,last_payment_reminder_at:new Date().toISOString()}),u({title:"Reminder sent",description:"Payment reminder email sent."})),x(!1)};if(L)return e.jsx("span",{className:"text-xs text-muted-foreground",children:"..."});if(!s)return e.jsx("span",{className:"text-xs text-muted-foreground",children:"No sub"});const C=s.is_comped?"comped":s.status,b=Es[C]??"outline",N=!s.is_comped&&Ds.has(s.status),I=s.trial_ends_at&&new Date(s.trial_ends_at)<new Date,U=s.current_period_end?`Renews ${new Date(s.current_period_end).toLocaleDateString()}`:s.trial_ends_at?I?`Trial ended ${new Date(s.trial_ends_at).toLocaleDateString()}`:`Trial ends ${new Date(s.trial_ends_at).toLocaleDateString()}`:null;return e.jsxs("div",{className:"flex flex-col gap-1.5 min-w-[160px]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(T,{variant:b,className:"text-xs capitalize",children:C.replace("_"," ")}),s.plan_id&&!s.is_comped&&e.jsx("span",{className:"text-xs text-muted-foreground capitalize",children:s.plan_id})]}),U&&e.jsx("span",{className:"text-[11px] text-muted-foreground",children:U}),s.last_payment_reminder_at&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["Reminded ",Ze(new Date(s.last_payment_reminder_at),{addSuffix:!0})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",title:"Comp account (free access)",children:[e.jsx(he,{checked:s.is_comped,onCheckedChange:o,disabled:A,className:"scale-75"}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Comp"})]}),N&&e.jsx(O,{variant:"outline",size:"sm",className:"h-6 px-2 text-[11px]",onClick:p,disabled:m,title:"Send payment reminder email",children:m?e.jsx(ae,{className:"h-3 w-3 animate-spin"}):e.jsx(ve,{className:"h-3 w-3"})})]})]})}function Is({clients:r,loading:s}){const[d,L]=n.useState(null),[y,A]=n.useState({}),[f,m]=n.useState(null),x=async u=>
1{if(d===u){L(null);return}if(L(u),y[u])return;m(u);const{data:o,error:p}=await h.rpc("admin_client_details",{client_user_id:u});if(!p&&o){const C=typeof o=="string"?JSON.parse(o):o;A(b=>({...b,[u]:C}))}m(null)};return e.jsxs(H,{children:[e.jsxs(ee,{children:[e.jsx(se,{children:"Client Overview"}),e.jsx(ne,{children:"View performance metrics for all clients — click a row to expand details"})]}),e.jsx(J,{children:s?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading clients..."}):r.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No clients yet"}):e.jsxs(Ne,{children:[e.jsx(be,{children:e.jsxs(te,{children:[e.jsx(v,{}),e.jsx(v,{children:"Client"}),e.jsx(v,{children:"Company"}),e.jsx(v,{className:"text-center",children:"Properties"}),e.jsx(v,{className:"text-center",children:"Agents"}),e.jsx(v,{className:"text-center",children:"Chats"}),e.jsx(v,{className:"text-center",children:"Phones"}),e.jsx(v,{className:"text-center",children:"Leads"}),e.jsx(v,{className:"text-center",children:"Complaints"}),e.jsx(v,{children:"Subscription"}),e.jsx(v,{children:"Joined"})]})}),e.jsx(ye,{children:r.map(u=>{const o=d===u.user_id,p=y[u.user_id],C=f===u.user_id;return e.jsx(us,{open:o,onOpenChange:()=>x(u.user_id),asChild:!0,children:e.jsxs(e.Fragment,{children:[e.jsx(ms,{asChild:!0,children:e.jsxs(te,{className:"cursor-pointer hover:bg-muted/50",children:[e.jsx(j,{children:e.jsx(O,{variant:"ghost",size:"icon",className:"h-6 w-6",children:o?e.jsx(ds,{className:"h-4 w-4"}):e.jsx(Re,{className:"h-4 w-4"})})}),e.jsxs(j,{children:[e.jsx("p",{className:"font-medium",children:u.full_name||"N/A"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u.email})]}),e.jsx(j,{children:u.company_name||"N/A"}),e.jsx(j,{className:"text-center",children:e.jsx(T,{variant:"secondary",children:u.properties_count})}),e.jsx(j,{className:"text-center",children:e.jsx(T,{variant:"outline",children:u.agents_count})}),e.jsx(j,{className:"text-center",children:e.jsx(T,{variant:"default",children:u.conversations_count})}),e.jsx(j,{className:"text-center",children:e.jsx(T,{variant:"secondary",children:u.phones_count})}),e.jsx(j,{className:"text-center",children:e.jsx(T,{variant:"secondary",children:u.leads_count})}),e.jsx(j,{className:"text-center",children:e.jsx(T,{variant:u.complaints_count>0?"destructive":"outline",children:u.complaints_count})}),e.jsx(j,{children:e.jsx(Ts,{userId:u.user_id})}),e.jsx(j,{children:new Date(u.created_at).toLocaleDateString()})]})}),e.jsx(xs,{asChild:!0,children:e.jsx(te,{children:e.jsx(j,{colSpan:11,className:"bg-muted/30 p-4",children:C?e.jsxs("div",{className:"flex items-center justify-center py-4 gap-2 text-muted-foreground",children:[e.jsx(ae,{className:"h-4 w-4 animate-spin"}),"Loading details..."]}):e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold mb-2 text-sm",children:"Properties"}),!(p!=null&&p.properties)||p.properties.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No properties"}):e.jsx("ul",{className:"space-y-1",children:p.properties.map(b=>e.jsxs("li",{className:"text-sm flex justify-between",children:[e.jsxs("span",{children:[b.name," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",b.domain,")"]})]}),e.jsxs(T,{variant:"outline",className:"text-xs",children:[b.conversations_count," chats"]})]},b.id))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold mb-2 text-sm",children:"Agents"}),!(p!=null&&p.agents)||p.agents.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No agents"}):e.jsx("ul",{className:"space-y-1",children:p.agents.map((b,N)=>e.jsxs("li",{className:"text-sm flex justify-between",children:[e.jsxs("span",{children:[b.name," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",b.email,")"]})]}),e.jsx(T,{variant:b.status==="online"?"default":"outline",className:"text-xs",children:b.status})]},N))})]})]})})})})]})},u.user_id)})})]})})]})}function Fs({complaints:r,loading:s,onRefresh:d}){const{toast:L}=De(),[y,A]=n.useState("all"),[f,m]=n.useState(null),x=y==="all"?r:r.filter(o=>o.status===y),u=async(o,p)=>{const{error:C}
1=await h.from("agent_complaints").update({status:p}).eq("id",o);if(C){L({title:"Error",description:"Failed to update complaint status",variant:"destructive"});return}L({title:"Updated",description:`Complaint marked as ${p}`}),d()};return e.jsxs(H,{children:[e.jsx(ee,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Agent Complaints"}),e.jsx(ne,{children:"Review and manage complaints from agents"})]}),e.jsxs(B,{value:y,onValueChange:A,children:[e.jsx(W,{className:"w-32",children:e.jsx(G,{})}),e.jsxs(K,{children:[e.jsx(g,{value:"all",children:"All"}),e.jsx(g,{value:"open",children:"Open"}),e.jsx(g,{value:"resolved",children:"Resolved"})]})]})]})}),e.jsx(J,{children:s?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading complaints..."}):x.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No complaints found"}):e.jsxs(Ne,{children:[e.jsx(be,{children:e.jsxs(te,{children:[e.jsx(v,{children:"Agent"}),e.jsx(v,{children:"Property"}),e.jsx(v,{children:"Category"}),e.jsx(v,{children:"Subject"}),e.jsx(v,{children:"Status"}),e.jsx(v,{children:"Date"}),e.jsx(v,{children:"Actions"})]})}),e.jsx(ye,{children:x.map(o=>e.jsxs(e.Fragment,{children:[e.jsxs(te,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>m(f===o.id?null:o.id),children:[e.jsx(j,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[f===o.id?e.jsx(Re,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}):e.jsx($e,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:o.agent_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.agent_email})]})]})}),e.jsx(j,{children:o.property_name||"N/A"}),e.jsx(j,{children:e.jsx(T,{variant:"outline",children:o.category})}),e.jsx(j,{className:"max-w-[200px] truncate",children:o.subject}),e.jsx(j,{children:e.jsx(T,{variant:o.status==="open"?"destructive":"secondary",children:o.status})}),e.jsx(j,{children:new Date(o.created_at).toLocaleDateString()}),e.jsx(j,{onClick:p=>p.stopPropagation(),children:e.jsxs(B,{value:o.status,onValueChange:p=>u(o.id,p),children:[e.jsx(W,{className:"w-28",children:e.jsx(G,{})}),e.jsxs(K,{children:[e.jsx(g,{value:"open",children:"Open"}),e.jsx(g,{value:"resolved",children:"Resolved"})]})]})})]},o.id),f===o.id&&e.jsx(te,{className:"bg-muted/30",children:e.jsxs(j,{colSpan:7,className:"py-4 px-6",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground mb-1",children:"Message"}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:o.message})]})},`${o.id}-detail`)]}))})]})})]})}function Ps(){const[r,s]=n.useState([]),[d,L]=n.useState(!0);n.useEffect(()=>{(async()=>{const{data:x,error:u}=await h.rpc("admin_daily_stats",{p_days:30});!u&&x&&s(x.map(o=>({day:new Date(o.day).toLocaleDateString("en-US",{month:"short",day:"numeric"}),new_conversations:Number(o.new_conversations),leads_captured:Number(o.leads_captured),phones_captured:Number(o.phones_captured)}))),L(!1)})()},[]);const y=r.reduce((m,x)=>m+x.new_conversations,0),A=r.reduce((m,x)=>m+x.leads_captured,0),f=r.reduce((m,x)=>m+x.phones_captured,0);return e.jsxs(H,{className:"col-span-full",children:[e.jsx(ee,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(se,{className:"text-lg flex items-center gap-2",children:[e.jsx(hs,{className:"h-5 w-5 text-primary"}),"Platform Activity — Last 30 Days"]}),e.jsx(ne,{children:"Daily conversations, leads, and phone captures across all clients"})]}),e.jsxs("div",{className:"flex gap-6 text-sm",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-foreground",children:y}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Conversations"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-foreground",children:A}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leads"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-foreground",children:f}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Phones"})]})]})]})}),e.jsx(J,{children:d?e.jsxs("div",{className:"flex items-center justify-center py-16 text-muted-foreground",children:[e.jsx(ae,{className:"h-5 w-5 animate-spin mr-2"}),"Loading chart..."]}):e.jsx(ps,{width:"100%",height:280,children:e.jsxs(js,{data:r,margin:{top:5,right:10,left:-20,bottom:0},children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"colorConvos",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",
1stopColor:"hsl(var(--primary))",stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:"hsl(var(--primary))",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"colorLeads",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"#22c55e",stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:"#22c55e",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"colorPhones",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"#8b5cf6",stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:"#8b5cf6",stopOpacity:0})]})]}),e.jsx(fs,{strokeDasharray:"3 3",className:"stroke-border/30"}),e.jsx(_s,{dataKey:"day",tick:{fontSize:11},className:"text-muted-foreground",interval:"preserveStartEnd"}),e.jsx(gs,{tick:{fontSize:11},className:"text-muted-foreground",allowDecimals:!1}),e.jsx(vs,{contentStyle:{backgroundColor:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:"8px",fontSize:"13px"}}),e.jsx(Ns,{wrapperStyle:{fontSize:"12px"}}),e.jsx(Se,{type:"monotone",dataKey:"new_conversations",name:"Conversations",stroke:"hsl(var(--primary))",fillOpacity:1,fill:"url(#colorConvos)",strokeWidth:2}),e.jsx(Se,{type:"monotone",dataKey:"leads_captured",name:"Leads",stroke:"#22c55e",fillOpacity:1,fill:"url(#colorLeads)",strokeWidth:2}),e.jsx(Se,{type:"monotone",dataKey:"phones_captured",name:"Phones",stroke:"#8b5cf6",fillOpacity:1,fill:"url(#colorPhones)",strokeWidth:2})]})})})]})}function Os({conversation:r,onBack:s}){const[d,L]=n.useState([]),[y,A]=n.useState(!0);n.useEffect(()=>{(async()=>{A(!0);const{data:x}=await h.rpc("admin_conversation_messages",{p_conversation_id:r.conversation_id});x&&L(x),A(!1)})()},[r.conversation_id]);const f=m=>new Date(m).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(O,{variant:"ghost",size:"sm",onClick:s,children:[e.jsx(qe,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:r.visitor_name||"Anonymous Visitor"}),e.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[e.jsx("span",{children:r.property_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:r.client_email}),r.visitor_phone&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"text-primary font-medium",children:r.visitor_phone})]})]})]}),e.jsx(T,{className:we(r.status==="active"&&"bg-green-100 text-green-700 border-green-200",r.status==="pending"&&"bg-amber-100 text-amber-700 border-amber-200",r.status==="closed"&&"text-muted-foreground"),variant:r.status==="closed"?"outline":"default",children:r.status}),r.ai_enabled&&e.jsxs(T,{variant:"secondary",className:"gap-1",children:[e.jsx(ke,{className:"h-3 w-3"})," AI"]})]}),y?e.jsxs("div",{className:"flex items-center justify-center py-16 text-muted-foreground",children:[e.jsx(ae,{className:"h-5 w-5 animate-spin mr-2"})," Loading messages..."]}):d.length===0?e.jsx("div",{className:"text-center py-16 text-muted-foreground",children:"No messages in this conversation"}):e.jsx(Qe,{className:"h-[600px] border rounded-lg bg-muted/30 p-4",children:e.jsxs("div",{className:"space-y-3 max-w-3xl mx-auto",children:[e.jsxs("p",{className:"text-xs text-center text-muted-foreground mb-4",children:[f(r.created_at)," — Conversation started"]}),d.map(m=>{const x=m.sender_type==="visitor";return e.jsx("div",{className:we("flex",x?"justify-start":"justify-end"),children:e.jsxs("div",{className:we("max-w-[75%] rounded-2xl px-4 py-2.5 text-sm shadow-sm",x?"bg-card border text-card-foreground rounded-bl-md":"bg-primary text-primary-foreground rounded-br-md"),children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[x?e.jsx(ze,{className:"h-3 w-3 opacity-60"}):e.jsx(ke,{className:"h-3 w-3 opacity-60"}),e.jsx("span",{className:"text-[10px] font-medium opacity-60 uppercase",children:m.sender_type==="visitor"?"Visitor":m.sender_type==="agent"?"Agent":"AI"}),e.jsx("span",{className:"text-[10px] opacity-40 ml-auto",children:f(m.created_at)})]}),e.jsx("p",{className:"whitespace-pre-wrap break-words leading-relaxed",children:m.content})]})},m.message_id)}),e.jsxs("p",{className:"text-xs text-center text-muted-foreground mt-4",children:[d.length," message",d.length!==1?"s":""," total"]})]})})]})}const pe=25;function Us(){const[r,s]=n.useState([]),[d,L]=n.useState(!0),[y,A]=n.useState(""),[f,m]=n.useState("all"),[x,u]=n.useState(0),[o,p]=n.useState(!0),[C,b]=n.useState(null),N=n.useCallback(async()=>{L(!0);try{const c={p_limit:pe,p_offset:x*pe};f!=="all"&&(c.p_status=f),y.trim()&&(c.p_search=y.trim());const{data:M,error:V}=await h.rpc("admin_conversations_browse",c);if(V){console.error("AdminConversationsTab fetch error:",V),L(!1);return}const R=(M||[]).map(S=>({conversation_id:S.conversation_id,status:S.status,created_at:S.created_at,updated_at:S.updated_at,property_name:S.property_name||"",property_domain:S.property_domain||"",client_email:S.client_email||"",client_name:S.client_name||null,visitor_name:S.visitor_name||null,visitor_email:S.visitor_email||null,visitor_phone:S.visitor_phone||null,message_count:Number(S.message_count)||0,ai_enabled:S.ai_enabled}));p(R.length===pe),s(R)}catch(c){console.error("AdminConversationsTab error:",c)}L(!1)},[x,f,y]);n.useEffect(()=>{N()},[N]);const I=()=>{u(0),N()},U=c=>{switch(c){case"active":return e.jsx(T,{className:"bg-green-100 text-green-700 border-green-200",children:"Active"});
1case"pending":return e.jsx(T,{className:"bg-amber-100 text-amber-700 border-amber-200",children:"Pending"});case"closed":return e.jsx(T,{variant:"outline",className:"text-muted-foreground",children:"Closed"});default:return e.jsx(T,{variant:"outline",children:c})}},F=c=>{const M=Date.now()-new Date(c).getTime(),V=Math.floor(M/6e4);if(V<60)return`${V}m ago`;const R=Math.floor(V/60);if(R<24)return`${R}h ago`;const S=Math.floor(R/24);return S<30?`${S}d ago`:new Date(c).toLocaleDateString()};return C?e.jsx(H,{children:e.jsx(J,{className:"pt-6",children:e.jsx(Os,{conversation:C,onBack:()=>b(null)})})}):e.jsxs(H,{children:[e.jsxs(ee,{children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(Ae,{className:"h-5 w-5 text-primary"}),"All Conversations"]}),e.jsx(ne,{children:"Click any conversation to view the full message thread"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(es,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Be,{placeholder:"Search visitor, property, or client...",value:y,onChange:c=>A(c.target.value),onKeyDown:c=>c.key==="Enter"&&I(),className:"pl-9"})]}),e.jsxs(B,{value:f,onValueChange:c=>{m(c),u(0)},children:[e.jsx(W,{className:"w-36",children:e.jsx(G,{})}),e.jsxs(K,{children:[e.jsx(g,{value:"all",children:"All Statuses"}),e.jsx(g,{value:"active",children:"Active"}),e.jsx(g,{value:"pending",children:"Pending"}),e.jsx(g,{value:"closed",children:"Closed"})]})]}),e.jsx(O,{variant:"outline",size:"sm",onClick:I,children:"Search"})]}),d?e.jsxs("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:[e.jsx(ae,{className:"h-5 w-5 animate-spin mr-2"}),"Loading conversations..."]}):r.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"No conversations found"}):e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{children:[e.jsx(be,{children:e.jsxs(te,{children:[e.jsx(v,{children:"Status"}),e.jsx(v,{children:"Visitor"}),e.jsx(v,{children:"Property"}),e.jsx(v,{children:"Client"}),e.jsx(v,{className:"text-center",children:"Messages"}),e.jsx(v,{className:"text-center",children:"AI"}),e.jsx(v,{children:"Started"}),e.jsx(v,{children:"Last Activity"})]})}),e.jsx(ye,{children:r.map(c=>e.jsxs(te,{className:"cursor-pointer hover:bg-muted/60 transition-colors",onClick:()=>b(c),children:[e.jsx(j,{children:U(c.status)}),e.jsx(j,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:c.visitor_name||"Anonymous"}),c.visitor_email&&e.jsx("p",{className:"text-xs text-muted-foreground",children:c.visitor_email}),c.visitor_phone&&e.jsx("p",{className:"text-xs text-primary font-medium",children:c.visitor_phone})]})}),e.jsx(j,{children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:c.property_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:c.property_domain})]})}),e.jsx(j,{children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:c.client_name||"N/A"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:c.client_email})]})}),e.jsx(j,{className:"text-center",children:e.jsx(T,{variant:"secondary",children:c.message_count})}),e.jsx(j,{className:"text-center",children:c.ai_enabled?e.jsx(ke,{className:"h-4 w-4 text-primary mx-auto"}):e.jsx(ze,{className:"h-4 w-4 text-muted-foreground mx-auto"})}),e.jsx(j,{className:"text-sm text-muted-foreground",children:F(c.created_at)}),e.jsx(j,{className:"text-sm text-muted-foreground",children:F(c.updated_at)})]},c.conversation_id))})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing ",x*pe+1,"–",x*pe+r.length]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(O,{variant:"outline",size:"sm",disabled:x===0,onClick:()=>u(c=>c-1),children:[e.jsx(ss,{className:"h-4 w-4 mr-1"})," Previous"]}),e.jsxs(O,{variant:"outline",size:"sm",disabled:!o,onClick:()=>u(c=>c+1),children:["Next ",e.jsx($e,{className:"h-4 w-4 ml-1"})]})]})]})]})]})]})}const Vs="/assets/salesforce-BxaqqpZa.svg",Ms=[{value:"first_name",label:"First Name"},{value:"last_name",label:"Last Name"},{value:"name",label:"Full Name"},{value:"email",label:"Email"},{value:"phone",label:"Phone"},{value:"age",label:"Age"},{value:"occupation",label:"Occupation"},{value:"location",label:"Location"},{value:"current_page",label:"Current Page"},{value:"browser_info",label:"Browser Info"},{value:"gclid",label:"Google Click ID (GCLID)"},{value:"drug_of_choice",label:"Drug of Choice"},{value:"addiction_history",label:"Addiction History"},{value:"treatment_interest",label:"Treatment Interest"},{value:"insurance_company",label:"Insurance Company"},{value:"member_id",label:"Member ID"},{value:"insurance_info",label:"Insurance Info (Legacy)"},{value:"insurance_card_url",label:"Insurance Card Photo URL"},{value:"urgency_level",label:"Urgency Level"},{value:"date_of_birth",label:"Date of Birth"},{value:"conversation_transcript",label:"Conversation Transcript (Full)"},{value:"conversation_summary",label:"Conversation Summary (AI)"}],Rs=({propertyId:r})=>{const[s,d]=n.useState(null),[L,y]=n.useState(!0),[A,f]=n.useState(!1),[m,x]=n.useState([]),[u,o]=n.useState(!1),[p,C]=n.useState(""),[b,N]=n.useState(""),[I,U]=n.useState(""),[F,c]=n.useState([]),[M,V]=n.useState([]),[R,S]=n.useState(!1),[re,oe]=n.useState(!1);n.useEffect(()=>{de()},[r]),n.useEffect(()=>{(s!=null&&s.salesforce_org_id||s!=null&&s.instance_url)&&ce()},[s==null?void 0:s.salesforce_org_id,s==null?void 0:s.instance_url]);const ce=async()=>{var l;S(!0),oe(!1);try{const{data:a,error:t}=await h.functions.invoke("salesforce-describe-lead",{body:{propertyId:r}});if(t){console.error("Error fetching Salesforce fields:",t);let E="";try{if((l=t.context)!=null&&l.body)E=typeof t.context.body=="str
1ing"?t.context.body:JSON.stringify(t.context.body);else if(typeof t.json=="function"){const X=await t.json();E=(X==null?void 0:X.error)||""}}catch{}const $=`${typeof t=="object"&&t.message?t.message:String(t)} ${E} ${(a==null?void 0:a.error)||""}`;$.includes("Session expired")||$.includes("INVALID_SESSION_ID")||$.includes("non-2xx")?oe(!0):z.error("Failed to fetch Salesforce Lead fields")}else a!=null&&a.error?a.error.includes("Session expired")||a.error.includes("INVALID_SESSION_ID")?oe(!0):z.error(a.error):a!=null&&a.fields&&(c(a.fields),a.statusValues&&V(a.statusValues),oe(!1))}catch(a){console.error("Error:",a)}S(!1)},de=async()=>{y(!0);const{data:l,error:a}=await h.from("salesforce_settings").select("*").eq("property_id",r).maybeSingle(),t=l;if(a){console.error("Error fetching Salesforce settings:",a),z.error("Failed to load Salesforce settings"),y(!1);return}if(t){let E=null;if(t.salesforce_org_id){const{data:$}=await h.from("salesforce_orgs").select("id, instance_url").eq("id",t.salesforce_org_id).maybeSingle();E=$}d({id:t.id,enabled:t.enabled,salesforce_org_id:t.salesforce_org_id||null,instance_url:(E==null?void 0:E.instance_url)||t.instance_url,auto_export_on_escalation:t.auto_export_on_escalation,auto_export_on_conversation_end:t.auto_export_on_conversation_end,auto_export_on_insurance_detected:t.auto_export_on_insurance_detected??!1,auto_export_on_phone_detected:t.auto_export_on_phone_detected??!1,include_insurance_card_attachment:t.include_insurance_card_attachment??!1,insurance_card_lead_status:t.insurance_card_lead_status||"",no_insurance_card_lead_status:t.no_insurance_card_lead_status||"",field_mappings:t.field_mappings,client_id:t.client_id||"",client_secret:t.client_secret||"",login_url:t.login_url||""}),C(t.login_url||""),N(t.client_id||""),U(t.client_secret||"");const D=Object.entries(t.field_mappings).map(([$,X])=>({salesforceField:$,visitorField:X}));x(D)}else d(null),x([]);y(!1)},je=async()=>{f(!0);const l=m.reduce((E,D)=>(D.salesforceField&&D.visitorField&&(E[D.salesforceField]=D.visitorField),E),{}),a={property_id:r,enabled:(s==null?void 0:s.enabled)??!1,auto_export_on_escalation:(s==null?void 0:s.auto_export_on_escalation)??!1,auto_export_on_conversation_end:(s==null?void 0:s.auto_export_on_conversation_end)??!1,auto_export_on_insurance_detected:(s==null?void 0:s.auto_export_on_insurance_detected)??!1,auto_export_on_phone_detected:(s==null?void 0:s.auto_export_on_phone_detected)??!1,include_insurance_card_attachment:(s==null?void 0:s.include_insurance_card_attachment)??!1,insurance_card_lead_status:(s==null?void 0:s.insurance_card_lead_status)||null,no_insurance_card_lead_status:(s==null?void 0:s.no_insurance_card_lead_status)||null,field_mappings:l,client_id:(s==null?void 0:s.client_id)||null,client_secret:(s==null?void 0:s.client_secret)||null,login_url:(s==null?void 0:s.login_url)||null};let t;if(s!=null&&s.id?t=await h.from("salesforce_settings").update(a).eq("id",s.id):t=await h.from("salesforce_settings").insert(a).select().single(),f(!1),t.error){console.error("Error saving Salesforce settings:",t.error),z.error("Failed to save Salesforce settings");return}!(s!=null&&s.id)&&t.data&&d({...a,id:t.data.id,instance_url:null}),z.success("Salesforce settings saved")},fe=async()=>{var $,X;o(!0);const l=600,a=700,t=window.screenX+(window.outerWidth-l)/2,E=window.screenY+(window.outerHeight-a)/2,D=window.open("about:blank","salesforce-oauth",`width=${l},height=${a},left=${t},top=${E},popup=1`);try{const{data:q,error:i}=await h.functions.invoke("salesforce-oauth-start",{body:{propertyId:r,clientId:b.trim()||void 0,clientSecret:I.trim()||void 0,loginUrl:p.trim()||void 0}});if(i||!(q!=null&&q.url)){D==null||D.close(),console.error("Error initiating OAuth:",i,q);let P=q==null?void 0:q.error;if(!P&&i)try{P=((X=($=i.context)==null?void 0:$.body)==null?void 0:X.error)||i.message}catch{}z.error(P||"Failed to start Salesforce connection"),o(!1);return}if(!D||D.closed){z.error("Popup was blocked. Please allow popups for this site and try again."),o(!1);return}D.location.href=q.url;const _=P=>{var le,me;((le=P.data)==null?void 0:le.type)==="salesforce-oauth-success"?(z.success("Successfully connected to Salesforce!"),o(!1),d(xe=>({...xe??{id:"",enabled:!0,auto_export_on_escalation:!1,auto_export_on_conversation_end:!1,auto_export_on_insurance_detected:!1,auto_export_on_phone_detected:!1,include_insurance_card_attachment:!1,insurance_card_lead_status:"",no_insurance_card_lead_status:"",field_mappings:{},client_id:b,client_secret:I,login_url:p},salesforce_org_id:"connected",instance_url:p||"connected"})),de(),window.removeEventListener("message",_)):((me=P.data)==null?void 0:me.type)==="salesforce-oauth-error"&&(z.error(`Salesforce connection failed: ${P.data.error||"Unknown error"}`),o(!1),window.removeEventListener("message",_))};window.addEventListener("message",_);const w=setInterval(()=>{(!D||D.closed)&&(clearInterval(w),setTimeout(()=>{window.removeEventListener("message",_),o(!1),de()},500))},500)}catch(q){D==null||D.close(),console.error("Error initiating OAuth:",q),z.error("Failed to start OAuth flow"),o(!1)}},ue=async()=>
1{if(!(s!=null&&s.id))return;const{error:l}=await h.from("salesforce_settings").update({salesforce_org_id:null,access_token:null,refresh_token:null,instance_url:null,token_expires_at:null,enabled:!1}).eq("id",s.id);if(l){z.error("Failed to disconnect Salesforce");return}z.success("Salesforce disconnected"),de()},Y=()=>{const l=new Set(m.map(t=>t.salesforceField)),a=F.find(t=>!l.has(t.name));x(a?[...m,{salesforceField:a.name,visitorField:""}]:[...m,{salesforceField:"",visitorField:""}])},Ce=l=>{x(m.filter((a,t)=>t!==l))},_e=(l,a,t)=>{const E=[...m];E[l]={...E[l],[a]:t},x(E)};return L?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ae,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs(H,{"data-tour":"salesforce-connection",children:[e.jsx(ee,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Salesforce Connection"}),e.jsx(ne,{children:"Connect your Salesforce account to export leads"})]}),e.jsx(T,{variant:s!=null&&s.salesforce_org_id||s!=null&&s.instance_url?re?"destructive":"default":"secondary",children:s!=null&&s.salesforce_org_id||s!=null&&s.instance_url?re?"Token Expired":"Connected":"Not Connected"})]})}),e.jsx(J,{children:s!=null&&s.salesforce_org_id||s!=null&&s.instance_url?e.jsxs("div",{className:"space-y-3",children:[re&&e.jsxs("div",{className:"flex flex-col gap-3 p-4 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ee,{className:"h-5 w-5 text-amber-500 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Salesforce session expired"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Your Salesforce OAuth session has expired or been revoked. Please reconnect to continue exporting leads."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"url",className:"flex-1 h-8 rounded-md border border-input bg-background px-3 text-xs focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"https://login.salesforce.com",value:p,onChange:l=>C(l.target.value)}),e.jsxs(O,{size:"sm",onClick:fe,disabled:u,children:[u?e.jsx(ae,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(Ve,{className:"mr-2 h-3 w-3"}),"Reconnect"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Connected to Salesforce"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s.instance_url})]}),e.jsxs(O,{variant:"outline",size:"sm",className:"text-destructive",onClick:ue,children:[e.jsx(ks,{className:"mr-2 h-4 w-4"}),"Disconnect"]})]})]}):e.jsxs("div",{className:"space-y-4 border rounded-lg bg-muted/50 p-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:Vs,alt:"Salesforce",className:"h-8 w-8"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Connect your Salesforce org"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Enter your Connected App credentials from Salesforce Setup"})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-xs font-medium",children:["Consumer Key (Client ID) ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx("input",{type:"text",className:"w-full h-9 rounded-md border border-input bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"3MVG9...",value:b,onChange:l=>N(l.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-xs font-medium",children:["Consumer Secret ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx("input",{type:"password",className:"w-full h-9 rounded-md border border-input bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"••••••••••••••••",value:I,onChange:l=>U(l.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs font-medium",children:"Login URL"}),e.jsx("input",{type:"url",className:"w-full h-9 rounded-md border border-input bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"https://login.salesforce.com",value:p,onChange:l=>C(l.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Leave blank for production. Use ",e.jsx("code",{children:"https://test.salesforce.com"})," for sandboxes, or your MyDomain URL."]})]})]}),e.jsxs(O,{disabled:u||!b.trim()||!I.trim(),onClick:fe,children:[u?e.jsx(ae,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ve,{className:"mr-2 h-4 w-4"}),u?"Connecting...":"Connect to Salesforce"]})]})})]}),e.jsxs(H,{"data-tour":"salesforce-auto-export",children:[e.jsxs(ee,{children:[e.jsx(se,{children:"Auto Export"}),e.jsx(ne,{children:"Automatically export leads to Salesforce when certain events occur"})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ie,{children:"Export on Escalation"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically create a lead when a conversation is escalated to a human"})]}),e.jsx(he,{checked:(s==null?void 0:s.auto_export_on_escalation)??!1,onCheckedChange:l=>d(a=>a?{...a,auto_export_on_escalation:l}:null)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ie,{children:"Export on Conversation End"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically create a lead when a conversation is closed"})]}),e.jsx(he,{checked:(s==null?void 0:s.auto_export_on_conversation_end)??!1,onCheckedChange:l=>d(a=>a?{...a,auto_export_on_conversation_end:l}:null)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ie,{children:"Export on Insurance Detected"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically create a lead when insurance details are extracted from the conversation"})]}),e.jsx(he,{checked:(s==null?void 0:s.auto_export_on_insurance_detected)??!1,onCheckedChange:l=>d(a=>a?{...a,auto_export_on_insurance_detected:l}:null)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ie,{children:"Export on Phone Number Detected"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically create a lead when a phone number is captured from the conversation"})]}),e.jsx(he,{checked:(s==null?void 0:s.auto_export_on_phone_detected)??!1,onCheckedChange:l=>d(a=>a?{...a,auto_export_on_phone_detected:l}:null)})]}),e.jsxs("div",{className:"border-t pt-6 space-y-6",children:[e.jsxs("div",{children:[e.jsx(ie,{className:"text-base font-medium",children:"Insurance Card Options"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:"Configure how insurance card uploads are handled when exp
1orting leads"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ie,{children:"Include Insurance Card URL with Lead"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Attach the insurance card photo URL to the lead when the visitor has uploaded one"})]}),e.jsx(he,{checked:(s==null?void 0:s.include_insurance_card_attachment)??!1,onCheckedChange:l=>d(a=>a?{...a,include_insurance_card_attachment:l}:null)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ie,{children:"Lead Status When Insurance Card Present"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set a specific lead status when the visitor has submitted an insurance card"}),e.jsxs(B,{value:(s==null?void 0:s.insurance_card_lead_status)||"_none",onValueChange:l=>d(a=>a?{...a,insurance_card_lead_status:l==="_none"?"":l}:null),children:[e.jsx(W,{className:"w-64",children:e.jsx(G,{placeholder:"No status override"})}),e.jsxs(K,{children:[e.jsx(g,{value:"_none",children:"No status override"}),M.length>0?M.map(l=>e.jsxs(g,{value:l.value,children:[l.label,l.isDefault?" (default)":""]},l.value)):e.jsxs(e.Fragment,{children:[e.jsx(g,{value:"New",children:"New"}),e.jsx(g,{value:"Open - Not Contacted",children:"Open - Not Contacted"}),e.jsx(g,{value:"Working - Contacted",children:"Working - Contacted"}),e.jsx(g,{value:"Closed - Converted",children:"Closed - Converted"}),e.jsx(g,{value:"Closed - Not Converted",children:"Closed - Not Converted"})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ie,{children:"Lead Status When Insurance Card Not Submitted"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set a specific lead status when the visitor has not submitted an insurance card"}),e.jsxs(B,{value:(s==null?void 0:s.no_insurance_card_lead_status)||"_none",onValueChange:l=>d(a=>a?{...a,no_insurance_card_lead_status:l==="_none"?"":l}:null),children:[e.jsx(W,{className:"w-64",children:e.jsx(G,{placeholder:"No status override"})}),e.jsxs(K,{children:[e.jsx(g,{value:"_none",children:"No status override"}),M.length>0?M.map(l=>e.jsxs(g,{value:l.value,children:[l.label,l.isDefault?" (default)":""]},l.value)):e.jsxs(e.Fragment,{children:[e.jsx(g,{value:"New",children:"New"}),e.jsx(g,{value:"Open - Not Contacted",children:"Open - Not Contacted"}),e.jsx(g,{value:"Working - Contacted",children:"Working - Contacted"}),e.jsx(g,{value:"Closed - Converted",children:"Closed - Converted"}),e.jsx(g,{value:"Closed - Not Converted",children:"Closed - Not Converted"})]})]})]})]})]})]})]}),e.jsxs(H,{"data-tour":"salesforce-field-mappings",children:[e.jsx(ee,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Field Mappings"}),e.jsx(ne,{children:"Map visitor data to Salesforce Lead fields"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[((s==null?void 0:s.salesforce_org_id)||(s==null?void 0:s.instance_url))&&e.jsx(O,{variant:"ghost",size:"sm",onClick:ce,disabled:R,children:e.jsx(ts,{className:`h-4 w-4 ${R?"animate-spin":""}`})}),e.jsxs(O,{variant:"outline",size:"sm",onClick:Y,disabled:!(s!=null&&s.salesforce_org_id||s!=null&&s.instance_url)&&F.length===0,children:[e.jsx(as,{className:"mr-2 h-4 w-4"}),"Add Field"]})]})]})}),e.jsx(J,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-[1fr,auto,1fr,auto] gap-4 items-center font-medium text-sm text-muted-foreground",children:[e.jsx("span",{children:"Salesforce Field"}),e.jsx("span",{}),e.jsx("span",{children:"Visitor Data"}),e.jsx("span",{})]}),!(s!=null&&s.salesforce_org_id)||(s==null?void 0:s.instance_url)&&m.length===0&&e.jsx("div",{className:"col-span-4 text-center py-8 text-muted-foreground",children:"Connect to Salesforce to load Lead fields and configure mappings"}),m.map((l,a)=>e.jsxs("div",{className:"grid grid-cols-[1fr,auto,1fr,auto] gap-4 items-center",children:[e.jsxs(B,{value:l.salesforceField,onValueChange:t=>_e(a,"salesforceField",t),children:[e.jsx(W,{children:e.jsx(G,{placeholder:"Select Salesforce field"})}),e.jsx(K,{children:F.length>0?F.map(t=>e.jsxs(g,{value:t.name,children:[t.label," ",t.required&&e.jsx("span",{className:"text-destructive",children:"*"})]},t.name)):e.jsx(g,{value:l.salesforceField||"loading",disabled:!0,children:R?"Loading fields...":"Connect to load fields"})})]}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs(B,{value:l.visitorField,onValueChange:t=>_e(a,"visitorField",t),children:[e.jsx(W,{children:e.jsx(G,{placeholder:"Select data"})}),e.jsx(K,{children:Ms.map(t=>e.jsx(g,{value:t.value,children:t.label},t.value))})]}),e.jsx(O,{variant:"ghost",size:"icon",onClick:()=>Ce(a),className:"text-muted-foreground hover:text-destructive",children:e.jsx(ns,{className:"h-4 w-4"})})]},a)),m.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:'No field mappings configured. Click "Add Field" to create one.'})]})})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(O,{onClick:je,disabled:A,children:[A?e.jsx(ae,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ls,{className:"mr-2 h-4 w-4"}),"Save Salesforce Settings"]})})]})};function $s(){const[r,s]=n.useState([]),[d,L]=n.useState(""),[y,A]=n.useState([]),[f,m]=n.useState(""),[x,u]=n.useState(!0),[o,p]=n.useState(!1);n.useEffect(()=>{(async()=>{const{data:I}=await h.from("user_roles").select("user_id").eq("role","client"),U=(I||[]).map(c=>
1c.user_id);if(U.length===0){s([]),u(!1);return}const{data:F}=await h.from("profiles").select("user_id, email, full_name, company_name").in("user_id",U).order("email");s(F||[]),u(!1)})()},[]),n.useEffect(()=>{if(!d){A([]),m("");return}p(!0),(async()=>{var U;const{data:I}=await h.from("properties").select("id, name, domain").eq("user_id",d).order("created_at");A(I||[]),m(((U=I==null?void 0:I[0])==null?void 0:U.id)||""),p(!1)})()},[d]);const C=r.find(N=>N.user_id===d),b=y.find(N=>N.id===f);return e.jsxs(H,{children:[e.jsxs(ee,{children:[e.jsx(se,{children:"Client Settings"}),e.jsx(ne,{children:"Select a client and property to view and edit their settings"})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsxs("div",{className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex flex-col gap-1.5 min-w-64",children:[e.jsx("label",{className:"text-sm font-medium",children:"Client"}),e.jsxs(B,{value:d,onValueChange:L,disabled:x,children:[e.jsx(W,{children:e.jsx(G,{placeholder:x?"Loading...":"Select a client"})}),e.jsx(K,{children:r.map(N=>e.jsxs(g,{value:N.user_id,children:[N.company_name||N.full_name||N.email,e.jsx("span",{className:"text-muted-foreground text-xs ml-2",children:N.email})]},N.user_id))})]})]}),d&&e.jsxs("div",{className:"flex flex-col gap-1.5 min-w-64",children:[e.jsx("label",{className:"text-sm font-medium",children:"Property"}),e.jsxs(B,{value:f,onValueChange:m,disabled:o,children:[e.jsx(W,{children:e.jsx(G,{placeholder:o?"Loading...":"Select a property"})}),e.jsx(K,{children:y.map(N=>e.jsx(g,{value:N.id,children:N.name||N.domain||N.id},N.id))})]})]})]}),f&&e.jsxs("div",{className:"border rounded-lg p-4 bg-muted/20",children:[e.jsxs("p",{className:"text-sm text-muted-foreground mb-4",children:["Editing: ",e.jsx("span",{className:"font-medium text-foreground",children:(C==null?void 0:C.company_name)||(C==null?void 0:C.email)})," · ",e.jsx("span",{className:"font-medium text-foreground",children:(b==null?void 0:b.name)||(b==null?void 0:b.domain)})]}),e.jsxs(We,{defaultValue:"email",children:[e.jsxs(Ge,{className:"mb-4 flex-wrap h-auto gap-1",children:[e.jsxs(Z,{value:"email",children:[e.jsx(ve,{className:"mr-1.5 h-3.5 w-3.5"}),"Email"]}),e.jsxs(Z,{value:"slack",children:[e.jsx(rs,{className:"mr-1.5 h-3.5 w-3.5"}),"Slack"]}),e.jsxs(Z,{value:"salesforce",children:[e.jsx(ls,{className:"mr-1.5 h-3.5 w-3.5"}),"Salesforce"]}),e.jsxs(Z,{value:"business",children:[e.jsx(Le,{className:"mr-1.5 h-3.5 w-3.5"}),"Business Info"]}),e.jsxs(Z,{value:"logs",children:[e.jsx(bs,{className:"mr-1.5 h-3.5 w-3.5"}),"Notification Log"]})]}),e.jsx(Q,{value:"email",children:e.jsx(ys,{propertyId:f})}),e.jsx(Q,{value:"slack",children:e.jsx(Cs,{propertyId:f})}),e.jsx(Q,{value:"salesforce",children:e.jsx(Rs,{propertyId:f})}),e.jsx(Q,{value:"business",children:e.jsx(ws,{propertyId:f})}),e.jsx(Q,{value:"logs",children:e.jsx(Ss,{propertyId:f})})]})]}),d&&!o&&y.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"This client has no properties."})]})]})}function st(){const{user:r,isAdmin:s,loading:d,signOut:L}=is(),{startImpersonation:y}=os(),[A,f]=n.useState([]),[m,x]=n.useState(!1),[u,o]=n.useState([]),[p,C]=n.useState([]),[b,N]=n.useState([]),[I,U]=n.useState({totalClients:0,totalAgents:0,totalConversations:0,totalProperties:0,activeConversations:0,totalPhones:0,totalLeads:0,openComplaints:0}),[F,c]=n.useState(!0),[M,V]=n.useState(!0),[R,S]=n.useState(!0),[re,oe]=n.useState(!1),[ce,de]=n.useState(!1),[je,fe]=n.useState(""),ue=cs(),{toast:Y}=De();n.useEffect(()=>{!d&&!r?ue("/auth"):!d&&!s&&ue("/dashboard")},[r,s,d,ue]),n.useEffect(()=>{s&&(l(),t(),E(),a(),Ce())},[s]);const Ce=async()=>{const{data:i}=await h.from("user_roles").select("user_id").eq("role","client"),_=(i||[]).map(P=>P.user_id);if(!_.length)return;const{data:w}=await h.from("profiles").select("user_id, email, full_name, company_name").in("user_id",_).order("email");f(w||[])},_e=async i=>{x(!0),await y(i,ue),x(!1)},l=async()=>{const[{data:i},{data:_}]=await Promise.all([h.from("profiles").select("*"),h.from("user_roles").select("*")]);if(!i||!_){Y({title:"Error",description:"Failed to load users",variant:"destructive"});return}o(i.map(w=>{const P=_.find(le=>
1le.user_id===w.user_id);return{...w,role:(P==null?void 0:P.role)||"client"}})),c(!1)},a=async()=>{const{data:i}=await h.from("agent_complaints").select("*");if(!i){S(!1);return}const _=[...new Set(i.map(k=>k.agent_id))],w=[...new Set(i.filter(k=>k.property_id).map(k=>k.property_id))],[{data:P},{data:le},{data:me}]=await Promise.all([h.from("agents").select("id, name, email").in("id",_.length?_:["_"]),h.from("properties").select("id, name").in("id",w.length?w:["_"]),h.from("profiles").select("user_id, full_name, email").in("user_id",_.length?_:["_"])]),xe=Object.fromEntries((P||[]).map(k=>[k.id,k])),ge=Object.fromEntries((me||[]).map(k=>[k.user_id,k])),Ke=Object.fromEntries((le||[]).map(k=>[k.id,k]));N(i.map(k=>{var Te,Ie,Fe,Pe,Oe;return{...k,agent_name:((Te=xe[k.agent_id])==null?void 0:Te.name)||((Ie=ge[k.agent_id])==null?void 0:Ie.full_name)||"Unknown",agent_email:((Fe=xe[k.agent_id])==null?void 0:Fe.email)||((Pe=ge[k.agent_id])==null?void 0:Pe.email)||"",property_name:k.property_id&&((Oe=Ke[k.property_id])==null?void 0:Oe.name)||null}})),S(!1)},t=async()=>{const{data:i,error:_}=await h.rpc("admin_client_overview");if(_||!i){console.error("Error fetching client overview:",_),C([]),V(!1);return}C(i.map(w=>({user_id:w.user_id,email:w.email,full_name:w.full_name,company_name:w.company_name,created_at:w.created_at,properties_count:Number(w.properties_count),conversations_count:Number(w.conversations_count),agents_count:Number(w.agents_count),phones_count:Number(w.phones_count),leads_count:Number(w.leads_count),complaints_count:Number(w.complaints_count),properties:[],agents:[]}))),V(!1)},E=async()=>{const[{count:i},{count:_},{count:w},{count:P},{count:le},{count:me},{count:xe},{count:ge}]=await Promise.all([h.from("user_roles").select("*",{count:"exact",head:!0}).eq("role","client"),h.from("user_roles").select("*",{count:"exact",head:!0}).eq("role","agent"),h.from("conversations").select("*",{count:"exact",head:!0}),h.from("conversations").select("*",{count:"exact",head:!0}).in("status",["active","pending"]),h.from("properties").select("*",{count:"exact",head:!0}),h.from("visitors").select("*",{count:"exact",head:!0}).not("phone","is",null),h.from("visitors").select("*",{count:"exact",head:!0}).or("name.not.is.null,email.not.is.null,phone.not.is.null"),h.from("agent_complaints").select("*",{count:"exact",head:!0}).eq("status","open")]);U({totalClients:i||0,totalAgents:_||0,totalConversations:w||0,totalProperties:le||0,activeConversations:P||0,totalPhones:me||0,totalLeads:xe||0,openComplaints:ge||0})},D=async(i,_)=>{const{error:w}=await h.from("user_roles").update({role:_}).eq("user_id",i);if(w){Y({title:"Error",description:"Failed to update user role",variant:"destructive"});return}Y({title:"Success",description:"User role updated successfully"}),l(),t(),E()},$=async()=>{const i=je.trim();if(!i){Y({title:"Enter a test email address first",variant:"destructive"});return}oe(!0);try{const{error:_}=await h.functions.invoke("send-bulk-upgrade-email",{body:{testEmail:i}});if(_)throw _;Y({title:"Test email sent",description:`Delivered to ${i}`})}catch(_){Y({title:"Error",description:_.message,variant:"destructive"})}finally{oe(!1)}},X=async()=>{if(window.confirm("This will send the upgrade announcement email to ALL users. Are you sure?")){de(!0);try{const{data:i,error:_}=await h.functions.invoke("send-bulk-upgrade-email",{body:{}});if(_)throw _;Y({title:"Upgrade emails sent",description:`Sent: ${i.sent} · Errors: ${i.errors}`})}catch(i){Y({title:"Error",description:i.message,variant:"destructive"})}finally{de(!1)}}},q=i=>{switch(i){case"admin":return"default";case"client":return"secondary";case"agent":return"outline";default:return"secondary"}};return d||!s?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("div",{className:"animate-pulse text-muted-foreground",children:"Loading..."})}):e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b border-border bg-card",children:e.jsxs("div",{className:"container mx-auto px-4 py-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(O,{variant:"ghost",onClick:()=>
1ue("/dashboard"),className:"gap-2",children:[e.jsx(qe,{className:"h-4 w-4"}),"Dashboard"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ue,{className:"h-6 w-6 text-primary"}),e.jsx("h1",{className:"text-xl font-bold",children:"Admin Dashboard"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[A.length>0&&e.jsxs(B,{onValueChange:_e,disabled:m,children:[e.jsx(W,{className:"w-52 h-9 text-sm",children:e.jsx(G,{placeholder:m?"Loading...":"View portal as..."})}),e.jsx(K,{children:A.map(i=>e.jsx(g,{value:i.user_id,children:i.company_name||i.full_name||i.email},i.user_id))})]}),e.jsx(O,{variant:"outline",onClick:L,children:"Sign Out"})]})]})}),e.jsxs("main",{className:"container mx-auto px-4 py-8",children:[e.jsx(As,{stats:I}),e.jsx(Ps,{}),e.jsxs(We,{defaultValue:"clients",className:"space-y-6 mt-8",children:[e.jsxs(Ge,{children:[e.jsxs(Z,{value:"clients",children:[e.jsx(Le,{className:"mr-2 h-4 w-4"}),"Client Overview"]}),e.jsxs(Z,{value:"conversations",children:[e.jsx(Ae,{className:"mr-2 h-4 w-4"}),"All Conversations"]}),e.jsxs(Z,{value:"complaints",children:[e.jsx(Ee,{className:"mr-2 h-4 w-4"}),"Complaints",I.openComplaints>0&&e.jsx(T,{variant:"destructive",className:"ml-2 h-5 px-1.5 text-xs",children:I.openComplaints})]}),e.jsxs(Z,{value:"users",children:[e.jsx(Me,{className:"mr-2 h-4 w-4"}),"User Management"]}),e.jsxs(Z,{value:"client-settings",children:[e.jsx(Ue,{className:"mr-2 h-4 w-4"}),"Client Settings"]})]}),e.jsx(Q,{value:"clients",children:e.jsx(Is,{clients:p,loading:M})}),e.jsx(Q,{value:"conversations",children:e.jsx(Us,{})}),e.jsx(Q,{value:"complaints",children:e.jsx(Fs,{complaints:b,loading:R,onRefresh:()=>{a(),E()}})}),e.jsx(Q,{value:"users",children:e.jsxs(H,{children:[e.jsx(ee,{children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"User Management"}),e.jsx(ne,{children:"Manage user accounts and roles"})]}),e.jsxs("div",{className:"flex gap-2 shrink-0 items-center",children:[e.jsx(Be,{type:"email",placeholder:"Test email address",value:je,onChange:i=>fe(i.target.value),className:"w-52 h-9 text-sm",disabled:re||ce}),e.jsxs(O,{variant:"outline",size:"sm",className:"gap-2",disabled:re||ce,onClick:$,children:[e.jsx(ve,{className:"h-4 w-4"}),re?"Sending…":"Send Test Email"]}),e.jsxs(O,{size:"sm",className:"gap-2",disabled:ce||re,onClick:X,children:[e.jsx(ve,{className:"h-4 w-4"}),ce?"Sending…":"Send to All Users"]})]})]})}),e.jsx(J,{children:F?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading users..."}):e.jsxs(Ne,{children:[e.jsx(be,{children:e.jsxs(te,{children:[e.jsx(v,{children:"Name"}),e.jsx(v,{children:"Email"}),e.jsx(v,{children:"Company"}),e.jsx(v,{children:"Role"}),e.jsx(v,{children:"Joined"}),e.jsx(v,{children:"Actions"})]})}),e.jsx(ye,{children:u.map(i=>e.jsxs(te,{children:[e.jsx(j,{className:"font-medium",children:i.full_name||"N/A"}),e.jsx(j,{children:i.email}),e.jsx(j,{children:i.company_name||"N/A"}),e.jsx(j,{children:e.jsx(T,{variant:q(i.role),children:i.role})}),e.jsx(j,{children:new Date(i.created_at).toLocaleDateString()}),e.jsx(j,{children:e.jsxs(B,{value:i.role,onValueChange:_=>D(i.user_id,_),disabled:i.user_id===(r==null?void 0:r.id),children:[e.jsx(W,{className:"w-28",children:e.jsx(G,{})}),e.jsxs(K,{children:[e.jsx(g,{value:"client",children:"Client"}),e.jsx(g,{value:"agent",children:"Agent"}),e.jsx(g,{value:"admin",children:"Admin"})]})]})})]},i.id))})]})})]})}),e.jsx(Q,{value:"client-settings",children:e.jsx($s,{})})]})]})]})}export{st 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.