PageSourceSearch

https://novo.gruposvip.com/assets/CRM-Dwv5jRZ9.js

js gruposvip.com collected 2026-09-26 08:44:23 UTC 209,900 bytes, 98 lines download raw bytes

1import{j as e,b as Q,u as we,c as X}from"./query-Q_ThwKGI.js";import{r as E,R as ke,k as Cs,i as Ts}from"./react-vendor-wefok28f.js";import{T as ts,a as ss,b as xe,c as he}from"./tabs-CMLwnORc.js";import{s as k}from"./client-DjLwxtrO.js";import{S as re,a as ne,b as le,c as de,d as F}from"./select-DECm7gW5.js";import{S as H}from"./skeleton-B8BTwlen.js";import{D as _e}from"./DashboardStatCard-Du7a8-ug.js";import{u as ce}from"./useCurrencyFormat-BvjeeDQW.js";import{ae as Ie,t as De,Y as nt,a1 as Se,au as Re,r as pt,g as Ms,b5 as as,aX as rt,O as qs,n as je,C as rs,b6 as ns,aE as Mt,ac as lt,a7 as ft,aa as Le,M as dt,B as Ue,z as it,U as qt,aR as ls,b7 as Fs,b8 as Vt,b9 as Ft,y as Pt,a6 as ct,a0 as ds,a2 as Ot,F as Ps,aw as Os,J as ot,ba as gt,Q as yt,G as Lt,bb as Ls,a9 as ht,E as is,aA as Et,aW as _t,al as cs,q as Es,l as As,aH as Rs,w as Is,m as Us,bc as Ks,bd as $s,aY as zs,a3 as Ys,j as Ws}from"./icons-By8asZST.js";import{C as $,b as se,c as ae,d as ye,a as ee}from"./card-DYyqUxY6.js";import{R as Ce,z as bt,B as Te,X as Me,Y as qe,E as Fe,I as Ke,F as fe,o as os,H as Oe,r as Bs}from"./LineChart-CjBOByky.js";import{B as At,e as Vs}from"./BarChart-tyxo_96n.js";import{T as $e,a as ze,b as ie,c as B,d as Ye,e as z}from"./table-D25X3X5Y.js";import{S as ms}from"./scroll-area-D3rGvhtF.js";import{B as U,D as Rt,a as It,b as Ut,c as Kt,e as $t}from"./badge-u_30_p7s.js";import{d as Nt,T as be,a as Ne,b as ve,u as mt,J,c as Qs}from"./index-C4Kq7kkR.js";import{t as at,i as Qt,f as R,s as wt,o as us,e as xs}from"./format-NnwPU_mP.js";import{e as st}from"./currencyUtils-D4WwR8db.js";import{I as Z}from"./input-Cu6Tiemi.js";import{B as Y}from"./button-DrepnwkX.js";import{S as kt,b as Dt,c as St,d as hs}from"./sheet-BNa5OgBl.js";import{u as We}from"./useTranslation-DNoH3foE.js";import{g as jt,W as Hs,n as Gs}from"./WhatsAppTimelineComposer-wTlFnG2J.js";import{u as zt}from"./index.esm-CGhUaq_S.js";import{L as T}from"./label-Ch0F7L4t.js";import{T as Yt}from"./textarea-DJfrjX2A.js";import{A as Be,a as Ve,b as Qe,c as He,d as Ge,e as Je,f as Xe,g as Ze,h as ps}from"./alert-dialog-BzFKdENb.js";import{S as gs}from"./switch-CnLyyNmH.js";import{f as js,e as Pe,a as fs}from"./formatDistanceToNow-g8DDsg0V.js";import{C as ys,a as bs,b as Ns}from"./collapsible-l8V3raC7.js";import{b as vs,i as Ct,a as Js}from"./isYesterday-CGiRJIKk.js";import{S as Ae}from"./separator-BOvWbUMa.js";import{u as ge}from"./AuthProvider-BSQZ2YtM.js";import{i as Xs}from"./isPast-HAFfZZEv.js";import{p as me}from"./parseISO-DQNCGdKl.js";import{A as Zs,a as ea}from"./AreaChart-B73AzQi3.js";import{p as _s}from"./pt-BR-9-TZCPQM.js";import{u as ta,a as sa}from"./useSubscription-svlizlcK.js";import{P as aa}from"./ProFeatureGate-CXf1Td84.js";import"./index-lwN0GFAE.js";import"./index-CryppvJw.js";import"./supabase-COHOFxoQ.js";import"./index-DviHZN-M.js";import"./index-CSO0Tzy2.js";import"./UserPreferencesContext-CmtdahHI.js";import"./tiny-invariant-BaFNuDhB.js";import"./index-DC33WZD-.js";import"./useWhatsAppConnection-BkLcuBJO.js";import"./index-Bdz2fkUq.js";import"./subDays-rNULONAo.js";import"./PlanFeatureChecklist-BdN1LsxW.js";function ra(t,n){const s=at(t);if(isNaN(n))return Qt(t,NaN);if(!n)return s;const r=s.getDate(),c=Qt(t,s.getTime());c.setMonth(s.getMonth()+n+1,0);const m=c.getDate();return r>=m?c:(s.setFullYear(c.getFullYear(),c.getMonth(),r),s)}function ws(t,n){const s=at(t.start),r=at(t.end);let c=+s>+r;const m=c?+s:+r,g=c?r:s;g.setHours(0,0,0,0),g.setDate(1);let i=1;const o=[];for(;+g<=m;)o.push(at(g)),g.setMonth(g.getMonth()+i);return c?o.reverse():o}function pe(t){const n=at(t);return n.setDate(1),n.setHours(0,0,0,0),n}function Tt(t,n){return ra(t,-n)}const na=({stats:t,isLoading:n,onCardClick:s})=>{const{formatValue:r}=ce();return n?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[...Array(4)].map((c,m)=>e.jsx(H,{className:"h-32"},m))}):e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx("div",{className:s?"cursor-pointer transition-transform hover:scale-[1.02]":"",onClick:()=>s==null?void 0:s("cart"),children:e.jsx(_e,{label:"Cart Abandoned",value:((t==null?void 0:t.cartAbandonedCount)??0).toString(),subtext:"Incomplete checkouts",icon:Ie,color:"text-amber-600"})}),e.jsx("div",{className:s?"cursor-pointer transition-transform hover:scale-[1.02]":"",onClick:()=>s==null?void 0:s("pending"),children:e.jsx(_e,{label:"Pending",value:((t==null?void 0:t.pendingCount)??0).toString(),subtext:r((t==null?void 0:t.pendingRevenue)||0),icon:De,color:"text-blue-600"})}),e.jsx("div",{className:s?"cursor-pointer transition-transform hover:scale-[1.02]":"",onClick:()=>s==null?void 0:s("won"),children:e.jsx(_e,{label:"Won",value:((t==null?void 0:t.wonCount)??0).toString(),subtext:r((t==null?void 0:t.wonRevenue)||0),icon:nt,color:"text-emerald-600"})}),e.jsx("div",{className:s?"cursor-pointer transition-transform hover:scale-[1.02]":"",onClick:()=>s==null?void 0:s("lost"),children:e.jsx(_e,{label:"Lost",value:((t==null?void 0:t.lostCount)??0).toString(),subtext:r((t==null?void 0:t.lostRevenue)||0),icon:Se,color:"text-rose-600"})})]})},Ht=t=>{const[n,s,r]=t.split("-").map(Number);return new Date(n,s-1,r)},la=({data:t,isLoading:n,showComparison:s=!1,comparisonLabel:r="Previous Per
1iod"})=>{const{formatValue:c,language:m}=ce(),g=o=>Math.round(o).toLocaleString(m);if(n)return e.jsxs($,{className:"p-6",children:[e.jsx(H,{className:"h-8 w-64 mb-4"}),e.jsx(H,{className:"h-[320px]"})]});const i=s&&(t==null?void 0:t.some(o=>o.previousRevenue!==void 0&&o.previousRevenue>0));return e.jsxs($,{className:"p-6 border-border/40 shadow-sm hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Revenue Over Time"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Approved sales daily revenue",i&&e.jsxs("span",{className:"text-muted-foreground/70",children:[" • Dashed line shows ",r.toLowerCase()]})]})]}),e.jsx(Ce,{width:"100%",height:320,children:e.jsxs(bt,{data:t,margin:{top:20,right:10,bottom:10,left:60},children:[e.jsx(Te,{strokeDasharray:"3 3",className:"stroke-muted/30"}),e.jsx(Me,{dataKey:"date",tickFormatter:o=>{const p=Ht(o);return`${String(p.getDate()).padStart(2,"0")}/${String(p.getMonth()+1).padStart(2,"0")}`},className:"text-xs text-muted-foreground",tick:{fill:"hsl(var(--muted-foreground))"}}),e.jsx(qe,{width:70,tickFormatter:o=>c(o,null,{compact:!0}),className:"text-xs text-muted-foreground",tick:{fill:"hsl(var(--muted-foreground))"}}),e.jsx(Fe,{labelFormatter:o=>Ht(o).toLocaleDateString(m,{day:"2-digit",month:"short",year:"numeric"}),formatter:(o,p)=>[c(o),p==="previousRevenue"?r:"Current Period"],contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}}),e.jsx(Ke,{wrapperStyle:{paddingTop:"20px"},formatter:o=>o==="previousRevenue"?r:"Current Period"}),i&&e.jsx(fe,{type:"monotone",dataKey:"previousRevenue",stroke:"hsl(var(--muted-foreground))",name:"previousRevenue",strokeWidth:1.5,strokeDasharray:"5 5",strokeOpacity:.5,dot:!1,activeDot:{r:4,fill:"hsl(var(--muted-foreground))",opacity:.6}}),e.jsx(fe,{type:"monotone",dataKey:"revenue",stroke:"hsl(var(--primary))",name:"revenue",strokeWidth:2.5,dot:{r:3,fill:"hsl(var(--primary))"},activeDot:{r:5,fill:"hsl(var(--primary))"},children:e.jsx(os,{dataKey:"revenue",position:"top",formatter:g,style:{fontSize:"10px",fill:"hsl(var(--muted-foreground))",fontWeight:500},offset:8})})]})})]})},Gt=t=>{const[n,s,r]=t.split("-").map(Number);return new Date(n,s-1,r)},da=({data:t,isLoading:n,showComparison:s=!1,comparisonLabel:r="Previous Period"})=>{if(n)return e.jsxs($,{className:"p-6",children:[e.jsx(H,{className:"h-8 w-64 mb-4"}),e.jsx(H,{className:"h-[280px]"})]});const c=s&&(t==null?void 0:t.some(m=>m.previousCount!==void 0&&m.previousCount>0));return e.jsxs($,{className:"p-6 border-border/40 shadow-sm hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Sales Count Over Time"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Number of approved transactions per day",c&&e.jsxs("span",{className:"text-muted-foreground/70",children:[" • Ghost bars show ",r.toLowerCase()]})]})]}),e.jsx(Ce,{width:"100%",height:280,children:e.jsxs(At,{data:t,margin:{top:20,right:10,bottom:10,left:20},children:[e.jsx(Te,{strokeDasharray:"3 3",className:"stroke-muted/30"}),e.jsx(Me,{dataKey:"date",tickFormatter:m=>{const g=Gt(m);return`${String(g.getDate()).padStart(2,"0")}/${String(g.getMonth()+1).padStart(2,"0")}`},className:"text-xs text-muted-foreground",tick:{fill:"hsl(var(--muted-foreground))"}}),e.jsx(qe,{width:40,className:"text-xs text-muted-foreground",tick:{fill:"hsl(var(--muted-foreground))"},allowDecimals:!1}),e.jsx(Fe,{labelFormatter:m=>Gt(m).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"}),formatter:(m,g)=>[m,g==="previousCount"?r:"Current Period"],contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}}),e.jsx(Ke,{wrapperStyle:{paddingTop:"20px"},formatter:m=>m==="previousCount"?r:"Current Period"}),c&&e.jsx(Oe,{dataKey:"previousCount",fill:"hsl(var(--muted-foreground))",name:"previousCount",radius:[4,4,0,0],fillOpacity:.25}),e.jsx(Oe,{dataKey:"count",fill:"hsl(var(--primary))",name:"count",radius:[4,4,0,0],children:e.jsx(os,{dataKey:"count",position:"top",style:{fontSize:"10px",fill:"hsl(var(--muted-foreground))",fontWeight:500},offset:4})})]})})]})},Jt=t=>{const[n,s,r]=t.split("-").map(Number);return new Date(n,s-1,r)},ia=({data:t,isLoading:n})=>n?e.jsxs($,{className:"p-6",children:[e.jsx(H,{className:"h-8 w-64 mb-4"}),e.jsx(H,{className:"h-[360px]"})]}):e.jsxs($,{className:"p-6 border-border/40 shadow-sm hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Opportunities Over Time"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Daily opportunity activity by stage"})]}),e.jsx(Ce,{width:"100%",height:360,children:e.jsxs(bt,{data:t,margin:{top:10,right:10,bottom:10,left:10},children:[e.jsx(Te,{strokeDasharray:"3 3",className:"stroke-muted/30"}),e.jsx(Me,{dataKey:"date",tickFormatter:s=>{const r=Jt(s);return`${String(r.getDate()).padStart(2,"0")}/${String(r.getMonth()+1).padStart(2,"0")}`},className:"text-xs text-muted-foreground",tick:{fill:"hsl(var(--muted-foreground))"}}),e.jsx(qe,{width:40,className:"text-xs text-muted-foreground",tick:{fill:"hsl(var(--muted-foreground))"}}),e.jsx(Fe,{labelFormatter:s=>Jt(s).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"}),contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}}),e.jsx(Ke,{wrapperStyle:{paddingTop:"20px"}}),e.jsx(fe,{type:"monotone",dataKey:"won",stroke:"hsl(142 76% 36%)",name:"Won",strokeWidth:2.5,dot:!1}),e.jsx(fe,{type:"monotone",dataKey:"pending",stroke:"hsl(217 91% 60%)",name:"Pending",strokeWidth:2.5,dot:!1}),e.jsx(fe,{type:"monotone",dataKey:"cart",stroke:"hsl(38 92% 50%)",name:"Cart",strokeWidth:2.5,dot:!1}),e.jsx(fe,{type:"monotone",dataKey:"lost",stroke:"hsl(0 84% 60%)",name:"Lost",strokeWidth:2.5,dot:!1})]})})]}),Xt=t=>{const[n,s,r]=t.split("-").map(Number);return new Date(n,s-1,r)},ca=({data:t,isLoading:n})=>n?e.jsxs($,{className:"p-6",children:[e.jsx(H,{className:"h-8 w-64 mb-4"}),e.jsx(H,{className:"h-[320px]"})]}):e.jsxs($,{className:"p-6 border-border/40 shadow-sm hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Win Rate Performance"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Closed opportunities by outcome"})]}),e.jsx(Ce,{width:"100%",height:320,children:e.jsxs(bt,{data:t,margin:{top:10,right:10,bottom:10,left:10},children:[e.jsx(Te,{strokeDasharray:"3 3",className:"stroke-muted/30"}),e.jsx(Me,{dataKey:"date",tickFormatter:s=>{const r=Xt(s);return`${String(r.getDate()).padStart(2,"0")}/${String(r.getMonth()+1).padStart(2,"0")}`},className:"text-xs text-muted-foreground",tick:{fill:"hsl(var(--muted-foreground))"}}),e.jsx(qe,{width:40,className:"text-xs text-muted-foreground",tick:{fill:"hsl(var(--muted-foreground))"}}),e.jsx(Fe,{labelFormatter:s=>Xt(s).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"}),contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}}),e.jsx(Ke,{wrapperStyle:{paddingTop:"20px"}}),e.jsx(fe,{type:"monotone",dataKey:"won",stroke:"hsl(142 76% 36%)",name:"Won",strokeWidth:2.5,dot:{r:3,fill:"hsl(142 76% 36%)"},activeDot:{r:5}}),e.jsx(fe,{type:"monotone",dataKey:"lost",stroke:"hsl(0 84% 60%)",name:"Lost",strokeWidth:2.5,dot:{r:3,fill:"hsl(0 84% 60%)"},activeDot:{r:5}})]})})]}),oa=t=>{const[n,s,r]=t.split("-").map(Number);return new Date(n,s-1,r)},ma=({dateRange:t,getDateRange:n,earliestDate:s})=>{const{formatValue:r,convertValue:c}=ce(),{data:m,isLoading:g}=Q({queryKey:["crm-product-sales-table",t,R(new Date,"yyyy-MM-dd"),s==null?void 0:s.toISOString()],queryFn:async()=>{const{data:{user:o}}=await k.auth.getUser();if(!o)return[];const{startDate:p,endDate:x}=n(t),{data:a,error:_}=await k.from("sales").select("product_name, net_value, approved_date, currency").eq("user_id",o.id
1).eq("status","approved").not("approved_date","is",null).not("product_name","is",null).gte("approved_date",p.toISOString()).lte("approved_date",x.toISOString()).order("approved_date",{ascending:!1});if(_)throw _;const j={};return a&&a.length>0&&a.forEach(y=>{const d=new Date(y.approved_date),f=new Date(d.getFullYear(),d.getMonth(),d.getDate()),q=R(f,"yyyy-MM-dd"),L=y.product_name||"Unknown Product",l=`${q}|${L}`;j[l]||(j[l]={date:q,product_name:L,quantity:0,revenue:0}),j[l].quantity+=1;const w=c(Number(y.net_value??0),y.currency);j[l].revenue+=isNaN(w)?0:w}),Object.values(j).sort((y,d)=>{const f=d.date.localeCompare(y.date);return f!==0?f:d.quantity-y.quantity})},enabled:t!=="all"||s!==void 0}),i=(o,p=40)=>o.length<=p?o:o.substring(0,p)+"...";return g?e.jsxs($,{children:[e.jsxs(se,{children:[e.jsxs(ae,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"h-5 w-5"}),"Product Sales by Day"]}),e.jsx(ye,{children:"Breakdown of products sold each day"})]}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((o,p)=>e.jsx(H,{className:"h-12 w-full"},p))})})]}):!m||m.length===0?e.jsxs($,{children:[e.jsxs(se,{children:[e.jsxs(ae,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"h-5 w-5"}),"Product Sales by Day"]}),e.jsx(ye,{children:"Breakdown of products sold each day"})]}),e.jsx(ee,{children:e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No product sales found for the selected period"})})]}):e.jsxs($,{children:[e.jsxs(se,{children:[e.jsxs(ae,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"h-5 w-5"}),"Product Sales by Day"]}),e.jsx(ye,{children:"Breakdown of products sold each day"})]}),e.jsx(ee,{children:e.jsx(ms,{className:"h-[400px]",children:e.jsxs($e,{children:[e.jsx(ze,{children:e.jsxs(ie,{children:[e.jsx(B,{className:"w-[100px]",children:"Date"}),e.jsx(B,{children:"Product"}),e.jsx(B,{className:"text-center w-[80px]",children:"Qty"}),e.jsx(B,{className:"text-right w-[120px]",children:"Revenue"})]})}),e.jsx(Ye,{children:e.jsx(Nt,{children:m.map((o,p)=>{const x=oa(o.date),a=R(x,"dd/MM/yyyy"),_=o.product_name.length>40;return e.jsxs(ie,{children:[e.jsx(z,{className:"font-medium text-muted-foreground",children:a}),e.jsx(z,{children:_?e.jsxs(be,{children:[e.jsx(Ne,{asChild:!0,children:e.jsx("span",{className:"cursor-help",children:i(o.product_name)})}),e.jsx(ve,{side:"top",className:"max-w-[300px]",children:e.jsx("p",{children:o.product_name})})]}):o.product_name}),e.jsx(z,{className:"text-center",children:e.jsx(U,{variant:"secondary",className:"font-semibold",children:o.quantity})}),e.jsx(z,{className:"text-right font-medium text-emerald-600",children:r(o.revenue)})]},`${o.date}-${o.product_name}-${p}`)})})})]})})})]})},ua=({onNavigateToTransactions:t})=>{const[n,s]=E.useState("this_month"),{data:r}=Q({queryKey:["crm-earliest-date"],queryFn:async()=>{const{data:{user:h}}=await k.auth.getUser();if(!h)return null;const{data:u}=await k.from("sales").select("approved_date").eq("user_id",h.id).not("approved_date","is",null).order("approved_date",{ascending:!0}).limit(1).single();return u!=null&&u.approved_date?new Date(u.approved_date):null}}),c=h=>{const u=new Date,P=new Date(u.getFullYear(),u.getMonth(),u.getDate(),0,0,0,0),A=new Date(u.getFullYear(),u.getMonth(),u.getDate(),23,59,59,999);let D,N=A;if(h==="30"){const I=new Date(P);I.setDate(I.getDate()-29),D=I}else if(h==="this_month")D=new Date(u.getFullYear(),u.getMonth(),1,0,0,0,0);else if(h==="last_month"){const I=new Date(u.getFullYear(),u.getMonth()-1,1);D=new Date(I.getFullYear(),I.getMonth(),1,0,0,0,0);const S=new Date(u.getFullYear(),u.getMonth(),0);N=new Date(S.getFullYear(),S.getMonth(),S.getDate(),23,59,59,999)}else h==="this_year"?D=new Date(u.getFullYear(),0,1,0,0,0,0):D=r||new Date(0);return{startDate:D,endDate:N}},m=h=>{const{startDate:u,endDate:P}=c(h),A=P.getTime()-u.getTime(),D=Math.ceil(A/(1e3*60*60*24)),N=new Date(u);N.setDate(N.getDate()-1),N.setHours(23,59,59,999);const I=new Date(N);return I.setDate(I.getDate()-D+1),I.setHours(0,0,0,0),{startDate:I,endDate:N}},g=h=>{switch(h){case"30":return"Previous 30 days";case"this_month":return"Last Month";case"last_month":return"Month Before";case"this_year":return"Last Year";
1default:return"Previous Period"}},{data:i,isLoading:o}=Q({queryKey:["crm-dashboard-stats",n,R(new Date,"yyyy-MM-dd"),r==null?void 0:r.toISOString()],queryFn:async()=>{const{data:{user:h}}=await k.auth.getUser();if(!h)return null;const{startDate:u,endDate:P}=c(n),A=[],D=1e3;let N=0;for(;;){const{data:b,error:C}=await k.from("crm_opportunities").select("stage, value, currency, current_status, created_at, last_activity_date, closed_date, is_won, is_lost").eq("user_id",h.id).order("created_at",{ascending:!1}).range(N,N+D-1);if(C)throw C;if(!b||b.length===0||(A.push(...b),b.length<D))break;N+=D}const I=A.filter(b=>{if(n==="all")return!0;const C=(b.is_won||b.is_lost)&&b.closed_date?new Date(b.closed_date):new Date(b.last_activity_date);return C>=u&&C<=P}),S=I.filter(b=>b.stage==="cart"),v=I.filter(b=>b.stage==="pending"),O=I.filter(b=>b.stage==="won"),K=I.filter(b=>b.stage==="lost");return{cartAbandonedCount:S.length,pendingCount:v.length,wonCount:O.length,lostCount:K.length,wonRevenue:O.reduce((b,C)=>b+st(C.value||0,C.currency),0),pendingRevenue:v.reduce((b,C)=>b+st(C.value||0,C.currency),0),lostRevenue:K.reduce((b,C)=>b+st(C.value||0,C.currency),0)}},enabled:n!=="all"||r!==void 0}),{data:p,isLoading:x}=Q({queryKey:["crm-revenue-chart",n,R(new Date,"yyyy-MM-dd"),r==null?void 0:r.toISOString()],queryFn:async()=>{const{data:{user:h}}=await k.auth.getUser();if(!h)return[];const{startDate:u,endDate:P}=c(n),{data:A,error:D}=await k.from("sales").select("net_value, approved_date, currency").eq("user_id",h.id).eq("status","approved").not("approved_date","is",null).gte("approved_date",u.toISOString()).lte("approved_date",P.toISOString()).order("approved_date",{ascending:!0});if(D)throw D;const N={};A&&A.length>0&&A.forEach(v=>{const O=new Date(v.approved_date),K=new Date(O.getFullYear(),O.getMonth(),O.getDate()),b=R(K,"yyyy-MM-dd");N[b]||(N[b]={date:b,revenue:0});const C=st(Number(v.net_value??0),v.currency);N[b].revenue+=isNaN(C)?0:C});const I=[],S=new Date(u);for(;S<=P;){const v=R(S,"yyyy-MM-dd");I.push(N[v]||{date:v,revenue:0}),S.setDate(S.getDate()+1)}return I},enabled:n!=="all"||r!==void 0}),{data:a}=Q({queryKey:["crm-revenue-chart-prev",n,R(new Date,"yyyy-MM-dd"),r==null?void 0:r.toISOString()],queryFn:async()=>{const{data:{user:h}}=await k.auth.getUser();if(!h||n==="all")return[];const{startDate:u,endDate:P}=m(n),{data:A,error:D}=await k.from("sales").select("net_value, approved_date, currency").eq("user_id",h.id).eq("status","approved").not("approved_date","is",null).gte("approved_date",u.toISOString()).lte("approved_date",P.toISOString()).order("approved_date",{ascending:!0});if(D)throw D;const N={};A&&A.length>0&&A.forEach(v=>{const O=new Date(v.approved_date),K=new Date(O.getFullYear(),O.getMonth(),O.getDate()),b=R(K,"yyyy-MM-dd"),C=st(Number(v.net_value??0),v.currency);N[b]=(N[b]||0)+(isNaN(C)?0:C)});const I=[],S=new Date(u);for(;S<=P;){const v=R(S,"yyyy-MM-dd");I.push(N[v]||0),S.setDate(S.getDate()+1)}return I},enabled:n!=="all"}),_=p==null?void 0:p.map((h,u)=>({...h,previousRevenue:(a==null?void 0:a[u])??void 0})),{data:j,isLoading:y}=Q({queryKey:["crm-sales-count-chart",n,R(new Date,"yyyy-MM-dd"),r==null?void 0:r.toISOString()],queryFn:async()=>{const{data:{user:h}}=await k.auth.getUser();if(!h)return[];const{startDate:u,endDate:P}=c(n),{data:A,error:D}=await k.from("sales").select("approved_date").eq("user_id",h.id).eq("status","approved").not("approved_date","is",null).gte("approved_date",u.toISOString()).lte("approved_date",P.toISOString()).order("approved_date",{ascending:!0});if(D)throw D;const N={};A&&A.length>0&&A.forEach(v=>{const O=new Date(v.approved_date),K=new Date(O.getFullYear(),O.getMonth(),O.getDate()),b=R(K,"yyyy-MM-dd");N[b]||(N[b]={date:b,count:0}),N[b].count+=1});const I=[],S=new Date(u);for(;S<=P;){const v=R(S,"yyyy-MM-dd");I.push(N[v]||{date:v,count:0}),S.setDate(S.getDate()+1)}return I},enabled:n!=="all"||r!==void 0}),{data:d}=Q({queryKey:["crm-sales-count-chart-prev",n,R(new Date,"yyyy-MM-dd"),r==null?void 0:r.toISOString()],queryFn:async()=>{const{data:{user:h}}=await k.auth.getUser();if(!h||n==="all")return[];const{startDate:u,endDate:P}=m(n),{data:A,error:D}=await k.from("sales").select("approved_date").eq("user_id",h.id).eq("status","approved").not("approved_date","is",null).gte("approved_date",u.toISOString()).lte("approved_date",P.toISOString()).order("approved_date",{ascending:!0});if(D)throw D;const N={};A&&A.length>0&&A.forEach(v=>{const O=new Date(v.approved_date),K=new Date(O.getFullYear(),O.getMonth(),O.getDate()),b=R(K,"yyyy-MM-dd");N[b]=(N[b]||0)+1});const I=[],S=new Date(u);for(;S<=P;){const v=R(S,"yyyy-MM-dd");I.push(N[v]||0),S.setDate(S.getDate()+1)}return I},enabled:n!=="all"}),f=j==null?void 0:j.map((h,u)=>({...h,previousCount:(d==null?void 0:d[u])??void 0})),{data:q,isLoading:L}=Q({queryKey:["crm-opportunities-chart",n,R(new Date,"yyyy-MM-dd"),r==null?void 0:r.toISOString()],queryFn:async()=>{const{data:{user:h}}=await k.auth.getUser();if(!h)return[];const{startDate:u,endDate:P}=c(n),{data:A,error:D}=await k.from("crm_opportunities").select("stage, last_activity_date").eq("user_id",h.id).gte("last_activity_date",u.toISOString()).lte("last_activity_date",P.toISOString()).order("last_activity_date",{ascending:!0});if(D)throw D;const N={};A&&A.length>0&&A.forEach(v=>{const O=new Date(v.last_activity_date),K=new Date(O.getFullYear(),O.getMonth(),O.getDate()),b=R(K,"yyyy-MM-dd");N[b]||(N[b]={date:b,cart:0,pending:0,won:0,lost:0}),N[b][v.stage]=(N[b][v.stage]||0)+1});const I=[],S=new Date(u);for(;S<=P;){const v=R(S,"yyyy-MM-dd");I.push(N[v]||{date:v,cart:0,pending:0,won:0,lost:0}),S.setDate(S.getDate()+1)}return I},enabled:n!=="all"||r!==void 0}),{data:l,isLoading:w}=Q({queryKey:["crm-performance-chart",n,R(new Date,"yyyy-MM-dd"),r==null?void 0:r.toISOString()],queryFn:async()=>{const{data:{user:h}}=await k.auth.getUser();if(!h)return[];const{startDate:u,endDate:P}=c(n),{data:A,error:D}
1=await k.from("crm_opportunities").select("closed_date, is_won, is_lost").eq("user_id",h.id).not("closed_date","is",null).gte("closed_date",u.toISOString()).lte("closed_date",P.toISOString()).order("closed_date",{ascending:!0});if(D)throw D;const N={};A&&A.length>0&&A.forEach(v=>{const O=new Date(v.closed_date),K=new Date(O.getFullYear(),O.getMonth(),O.getDate()),b=R(K,"yyyy-MM-dd");N[b]||(N[b]={date:b,won:0,lost:0}),v.is_won&&(N[b].won+=1),v.is_lost&&(N[b].lost+=1)});const I=[],S=new Date(u);for(;S<=P;){const v=R(S,"yyyy-MM-dd");I.push(N[v]||{date:v,won:0,lost:0}),S.setDate(S.getDate()+1)}return I},enabled:n!=="all"||r!==void 0}),M=h=>{t&&t({cart:"checkout_abandoned",pending:"pending",won:"approved",lost:"canceled"}[h]||"all")};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-semibold tracking-tight",children:"Dashboard & Analytics"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Track your CRM performance and revenue"})]}),e.jsxs(re,{value:n,onValueChange:s,children:[e.jsx(ne,{className:"w-[180px]",children:e.jsx(le,{placeholder:"Select period"})}),e.jsxs(de,{children:[e.jsx(F,{value:"30",children:"Last 30 days"}),e.jsx(F,{value:"this_month",children:"This Month"}),e.jsx(F,{value:"last_month",children:"Last Month"}),e.jsx(F,{value:"this_year",children:"This Year"}),e.jsx(F,{value:"all",children:"All time"})]})]})]}),e.jsx(na,{stats:i||void 0,isLoading:o,onCardClick:t?M:void 0}),e.jsx(la,{data:_,isLoading:x,showComparison:n!=="all",comparisonLabel:g(n)}),e.jsx(da,{data:f,isLoading:y,showComparison:n!=="all",comparisonLabel:g(n)}),e.jsx(ma,{dateRange:n,getDateRange:c,earliestDate:r}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsx(ca,{data:l,isLoading:w}),e.jsx(ia,{data:q,isLoading:L})]})]})},xa={cart:{divider:"bg-amber-100 text-amber-800 border-amber-200",chip:"bg-amber-50 text-amber-700 border-amber-200"},pending:{divider:"bg-blue-100 text-blue-800 border-blue-200",chip:"bg-blue-50 text-blue-700 border-blue-200"},won:{divider:"bg-emerald-100 text-emerald-800 border-emerald-200",chip:"bg-emerald-50 text-emerald-700 border-emerald-200"},lost:{divider:"bg-rose-100 text-rose-800 border-rose-200",chip:"bg-rose-50 text-rose-700 border-rose-200"}},ha=({sales:t,leadRegistrationDate:n,leadFormName:s,whatsappActivities:r=[],leadEvents:c=[],stageHistory:m=[],currentStage:g="cart",cancellationType:i,opportunityCreatedAt:o,opportunityAutoCreated:p,opportunityTransactionId:x,leadScore:a,leadTemperature:_,composer:j})=>{const{t:y}=We(["crm"]),{formatValue:d,language:f}=ce(),q=(S,v)=>{switch(S){case"checkout_abandoned":return e.jsx(Ie,{className:"h-5 w-5 text-muted-foreground"});case"billet_printed":case"pending":return e.jsx(De,{className:"h-5 w-5 text-yellow-500"});case"approved":case"complete":return e.jsx(nt,{className:"h-5 w-5 text-green-500"});case"canceled":case"expired":return v==="payment_failed"?e.jsx(rt,{className:"h-5 w-5 text-amber-500"}):e.jsx(Se,{className:"h-5 w-5 text-red-500"});case"refunded":case"chargeback":return e.jsx(qs,{className:"h-5 w-5 text-orange-500"});case"delayed":return e.jsx(De,{className:"h-5 w-5 text-amber-500"});default:return e.jsx(rt,{className:"h-5 w-5 text-muted-foreground"})}},L=S=>{switch(S){case"joined_group":return e.jsx(pt,{className:"h-5 w-5 text-green-500"});case"left_group":return e.jsx(Mt,{className:"h-5 w-5 text-red-500"});case"message_sent":return e.jsx(je,{className:"h-5 w-5 text-green-500"});case"reaction":return e.jsx(ns,{className:"h-5 w-5 text-pink-500"});case"poll_answered":return e.jsx(rs,{className:"h-5 w-5 text-blue-500"});default:return e.jsx(je,{className:"h-5 w-5 text-green-500"})}},l=S=>({joined_group:"Joined Group",left_group:"Left Group",message_sent:"Message Sent",reaction:"Reaction",poll_answered:"Poll Answered"})[S]||S,w=(S,v)=>
1{if(S==="canceled"&&v){if(v==="payment_failed")return"Payment Failed";if(v==="user_canceled")return"User Canceled"}return{checkout_abandoned:"Cart Abandoned",billet_printed:"Billet Printed",pending:"Pending",approved:"Approved",complete:"Complete",canceled:"Canceled",expired:"Expired",refunded:"Refunded",chargeback:"Chargeback",delayed:"Payment Delayed"}[S]||S},M=(S,v)=>{switch(S){case"approved":case"complete":return"default";case"checkout_abandoned":return"secondary";case"canceled":case"expired":return v==="payment_failed"?"outline":"destructive";case"refunded":case"chargeback":return"destructive";case"delayed":return"outline";default:return"outline"}},h=S=>S?R(new Date(S),f==="pt-BR"?"dd/MM/yyyy 'às' HH:mm":"MM/dd/yyyy 'at' HH:mm"):"N/A",u=[];if(n&&u.push({kind:"lead",date:n}),o){const S=p===!0||typeof x=="string"&&x.startsWith("LS-");u.push({kind:"opp_created",date:o,isLeadScore:S})}t.forEach(S=>{u.push({kind:"sale",sale:S,date:S.purchase_date||S.created_at||""})}),r.forEach(S=>{u.push({kind:"whatsapp",activity:S,date:S.created_at||""})}),c.forEach(S=>{u.push({kind:"private_msg",event:S,date:S.timestamp})}),u.sort((S,v)=>new Date(S.date).getTime()-new Date(v.date).getTime());const P=[...m].sort((S,v)=>new Date(S.changed_at).getTime()-new Date(v.changed_at).getTime()),A=S=>{if(!S)return g;const v=new Date(S).getTime();let O=P.length>0?"cart":g;for(const K of P)if(new Date(K.changed_at).getTime()<=v)O=K.to_stage;else break;return O},D=S=>S==="lost"&&i==="payment_failed"?f==="pt-BR"?"Pagamento Falhou":"Payment Failed":y(`crm:timeline.phaseLabels.${S}`),N=S=>{const v=S.metadata||{};return v.body||v.text||v.message||v.message_preview||v.caption||S.description||""};let I=null;return e.jsx(Nt,{delayDuration:200,children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute left-[11px] top-0 bottom-0 w-0.5 bg-border"}),e.jsxs("div",{className:"space-y-6",children:[u.map(S=>{var G,te,ue,xt;const v=A(S.date),O=v!==I;I=v;const K=xa[v],b=e.jsx(U,{variant:"outline",className:`text-[10px] px-1.5 py-0 h-4 font-normal ${K.chip}`,children:D(v)}),C=O?e.jsxs("div",{className:"relative flex items-center gap-3 -mb-2",children:[e.jsx("div",{className:"relative z-10 flex-shrink-0 w-6 flex justify-center",children:e.jsx("div",{className:`h-2.5 w-2.5 rounded-full border ${K.divider}`})}),e.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[e.jsx(U,{className:`text-xs ${K.divider}`,children:D(v)}),e.jsx("div",{className:"flex-1 h-px bg-border"})]})]},`div-${S.date}-${v}`):null;let W=null;if(S.kind==="lead")W=e.jsxs("div",{className:"relative flex gap-4",children:[e.jsx("div",{className:"relative z-10 flex-shrink-0",children:e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border-2 border-background bg-card",children:e.jsx(pt,{className:"h-5 w-5 text-blue-500"})})}),e.jsx("div",{className:"flex-1 pb-6",children:e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx(U,{variant:"outline",className:"bg-blue-500/10 text-blue-500 border-blue-500/20",children:"Lead Subscription"}),b]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:h(n)}),s&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Form: ",e.jsx("span",{className:"font-medium",children:s})]})]})})})]},"lead-registration");else if(S.kind==="opp_created"){const V=S.isLeadScore,oe=_?_.replace(/_/g," "):null;W=e.jsxs("div",{className:"relative flex gap-4",children:[e.jsx("div",{className:"relative z-10 flex-shrink-0",children:e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border-2 border-background bg-card",children:V?e.jsx(Ms,{className:"h-5 w-5 text-purple-500"}):e.jsx(as,{className:"h-5 w-5 text-indigo-500"})})}),e.jsx("div",{className:"flex-1 pb-6",children:e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx(U,{variant:"outline",className:V?"bg-purple-500/10 text-purple-600 border-purple-500/20":"bg-indigo-500/10 text-indigo-600 border-indigo-500/20",children:V?"Opportunity Auto-Created (Lead Score)":"Opportunity Created"}),b]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:h(S.date)}),V&&(a!=null||oe)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[a!=null&&e.jsxs(e.Fragment,{children:["Score: ",e.jsx("span",{className:"font-medium",children:a})]}),a!=null&&oe&&" · ",oe&&e.jsx("span",{className:"capitalize font-medium",children:oe})]})]})})})]},"opp-created")}else if(S.kind==="whatsapp"){const V=S.activity,oe=V.activity_data||{},Ee=oe.group_name||oe.groupName||"",tt=oe.body||oe.message_preview||oe.poll_option||"";W=e.jsxs("div",{className:"relative flex gap-4",children:[e.jsx("div",{className:"relative z-10 flex-shrink-0",children:e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border-2 border-background bg-card",children:L(V.activity_type)})}),e.jsx("div",{className:"flex-1 pb-6",children:e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx(U,{variant:"outline",className:"bg-green-500/10 text-green-600 border-green-500/20",children:l(V.activity_type)}),b]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:h(V.created_at)}),Ee&&e.jsx("p",{className:"text-sm text-muted-foreground",children:Ee}),tt&&e.jsxs(be,{children:[e.jsx(Ne,{asChild:!0,children:e.jsx("p",{className:"text-xs text-muted-foreground
1/70 mt-1 line-clamp-2 cursor-help",children:tt})}),e.jsx(ve,{side:"top",align:"start",className:"max-w-sm whitespace-pre-wrap break-words",children:tt})]})]})})})]},`wa-${V.id}`)}else if(S.kind==="private_msg"){const V=S.event,oe=V.event_type==="whatsapp_manual_sent",Ee=V.event_type==="whatsapp_manual_failed",tt=Ss=>{switch(Ss){case"whatsapp_manual_sent":return e.jsx(je,{className:"h-5 w-5 text-green-600"});case"whatsapp_manual_failed":return e.jsx(Se,{className:"h-5 w-5 text-red-500"});case"message_received":return e.jsx(je,{className:"h-5 w-5 text-teal-500"});case"message_sent":return e.jsx(je,{className:"h-5 w-5 text-slate-500"});case"document_received":return e.jsx(je,{className:"h-5 w-5 text-cyan-500"});case"audio_received":return e.jsx(je,{className:"h-5 w-5 text-rose-500"});case"image_received":return e.jsx(je,{className:"h-5 w-5 text-fuchsia-500"});default:return e.jsx(je,{className:"h-5 w-5 text-teal-500"})}},vt=N(V),Bt=(G=V.metadata)==null?void 0:G.error,Ds=oe?"bg-green-500/10 text-green-600 border-green-500/20":Ee?"bg-red-500/10 text-red-600 border-red-500/20":"bg-teal-500/10 text-teal-600 border-teal-500/20";W=e.jsxs("div",{className:"relative flex gap-4",children:[e.jsx("div",{className:"relative z-10 flex-shrink-0",children:e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border-2 border-background bg-card",children:tt(V.event_type)})}),e.jsx("div",{className:"flex-1 pb-6",children:e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx(U,{variant:"outline",className:Ds,children:oe?"WhatsApp Sent (manual)":Ee?"WhatsApp Failed":V.title}),b]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:h(V.timestamp)}),vt&&e.jsxs(be,{children:[e.jsx(Ne,{asChild:!0,children:e.jsx("p",{className:"text-sm text-foreground/80 mt-1 line-clamp-2 whitespace-pre-wrap cursor-help",children:vt})}),e.jsx(ve,{side:"top",align:"start",className:"max-w-sm whitespace-pre-wrap break-words",children:vt})]}),Ee&&Bt&&e.jsxs("p",{className:"text-xs text-red-500 mt-1",children:["Error: ",Bt]})]})})})]},`le-${V.id}`)}else{const V=S.sale;W=e.jsxs("div",{className:"relative flex gap-4",children:[e.jsx("div",{className:"relative z-10 flex-shrink-0",children:e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border-2 border-background bg-card",children:q(V.status,V.cancellation_type)})}),e.jsx("div",{className:"flex-1 pb-6",children:e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx(U,{variant:M(V.status,V.cancellation_type),children:w(V.status,V.cancellation_type)}),V.is_subscription&&V.subscription_plan_name&&e.jsx(U,{variant:"outline",className:"text-xs bg-blue-500/10 text-blue-600 border-blue-500/20",children:V.subscription_plan_name}),b]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:h(V.purchase_date||V.created_at)}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Value:"}),e.jsx("span",{className:"font-medium",children:d(V.net_value,V.currency)})]}),V.payment_method&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Payment:"}),e.jsx("span",{className:"font-medium capitalize",children:V.payment_method.replace(/_/g," ")})]}),V.approved_date&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Approved:"}),e.jsx("span",{className:"font-medium",children:h(V.approved_date)})]})]})]})})})]},V.id)}return e.jsxs(ke.Fragment,{children:[C,W]},`row-${S.kind}-${S.date}-${((te=S.sale)==null?void 0:te.id)||((ue=S.activity)==null?void 0:ue.id)||((xt=S.event)==null?void 0:xt.id)||"lead"}`)}),j]})]})})},ks=({isOpen:t,onClose:n,onSave:s,initialData:r,isLoading:c})=>{const{register:m,handleSubmit:g,setValue:i,watch:o,reset:p}=zt({defaultValues:r||{title:"",description:"",due_date:"",priority:"medium",status:"pending",task_type:"follow_up",assignee:""}});ke.useEffect(()=>{p(r||{title:"",description:"",due_date:"",priority:"medium",status:"pending",task_type:"follow_up",assignee:""})},[r,p]);const x=a=>{s(a)};return e.jsx(Rt,{open:t,onOpenChange:n,children:e.jsxs(It,{className:"sm:max-w-md",children:[e.jsx(Ut,{children:e.jsx(Kt,{children:r?"Edit Task":"Add Task"})}),e.jsxs("form",{onSubmit:g(x),className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"title",children:"Title *"}),e.jsx(Z,{id:"title",placeholder:"Follow up call...",...m("title",{required:!0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"description",children:"Description"}),e.jsx(Yt,{id:"description",placeholder:"Task details...",...m("description"),rows:3})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"due_date",children:"Due Date"}),e.jsx(Z,{id:"due_date",type:"datetime-local",...m("due_date")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"assignee",children:"Assignee"}),e.jsx(Z,{id:"assignee",placeholder:"Name...",...m("assignee")})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Task Type"}),e.jsxs(re,{value:o("task_type"),onValueChange:a=>i("task_type",a),children:[e.jsx(ne,{children:e.jsx(le,{})}),e.jsxs(de,{children:[e.jsx(F,{value:"call",children:"📞 Call"}),e.jsx(F,{value:"email",children:"📧 Email"}),e.jsx(F,{value:"meeting",children:"📅 Meeting"}),e.jsx(F,{value:"follow_up",children:"🔄 Follow-up"}),e.jsx(F,{value:"whatsapp",children:"💬 WhatsApp"}),e.jsx(F,{value:"proposal",children:"📄 Proposal"}),e.jsx(F,{value:"other",children:"⚡ Other"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Priority"}),e.jsxs(re,{value:o("priority"),onValueChange:a=>i("priority",a),children:[e.jsx(ne,{children:e.jsx(le,{})}),e.jsxs(de,{children:[e.jsx(F,{value:"low",children:"🟢 Low"}),e.jsx(F,{value:"medium",children:"🟡 Medium"}),e.jsx(F,{value:"high",children:"🟠 High"}),e.jsx(F,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Status"}),e.jsxs(re,{value:o("status"),onValueChange:a=>i("status",a),children:[e.jsx(ne,{children:e.jsx(le,{})}),e.jsxs(de,{children:[e.jsx(F,{value:"pending",children:"⏳ Pending"}),e.jsx(F,{value:"in_progress",children:"🔄 In Progress"}),e.jsx(F,{value:"completed",children:"✅ Completed"}),e.jsx(F,{value:"cancelled",children:"❌ Cancelled"})]})]})]})]}),e.jsxs($t,{children:[e.jsx(Y,{type:"button",variant:"outline",onClick:n,children:"Cancel"}
1),e.jsx(Y,{type:"submit",disabled:c,children:c?"Saving...":"Save Task"})]})]})]})})},pa=({opportunityId:t})=>{const{toast:n}=mt(),s=we(),[r,c]=E.useState(!1),[m,g]=E.useState(null),[i,o]=E.useState(null),{data:p,isLoading:x}=Q({queryKey:["opportunity-tasks",t],queryFn:async()=>{const{data:h,error:u}=await k.from("opportunity_tasks").select("*").eq("opportunity_id",t).order("due_date",{ascending:!0,nullsFirst:!1});if(u)throw u;return h}}),a=X({mutationFn:async h=>{const{data:{user:u}}=await k.auth.getUser();if(!u)throw new Error("Not authenticated");const{error:P}=await k.from("opportunity_tasks").insert({opportunity_id:t,user_id:u.id,title:h.title,description:h.description||null,due_date:h.due_date||null,priority:h.priority,status:h.status,task_type:h.task_type,assignee:h.assignee||null});if(P)throw P},onSuccess:()=>{s.invalidateQueries({queryKey:["opportunity-tasks",t]}),n({title:"Task created successfully"}),c(!1)},onError:h=>{n({title:"Error creating task",description:h.message,variant:"destructive"})}}),_=X({mutationFn:async({id:h,data:u})=>{const{error:P}=await k.from("opportunity_tasks").update({title:u.title,description:u.description||null,due_date:u.due_date||null,priority:u.priority,status:u.status,task_type:u.task_type,assignee:u.assignee||null,completed_at:u.status==="completed"?new Date().toISOString():null}).eq("id",h);if(P)throw P},onSuccess:()=>{s.invalidateQueries({queryKey:["opportunity-tasks",t]}),n({title:"Task updated successfully"}),g(null),c(!1)},onError:h=>{n({title:"Error updating task",description:h.message,variant:"destructive"})}}),j=X({mutationFn:async h=>{const{error:u}=await k.from("opportunity_tasks").delete().eq("id",h);if(u)throw u},onSuccess:()=>{s.invalidateQueries({queryKey:["opportunity-tasks",t]}),n({title:"Task deleted successfully"}),o(null)},onError:h=>{n({title:"Error deleting task",description:h.message,variant:"destructive"})}}),y=X({mutationFn:async h=>{const{error:u}=await k.from("opportunity_tasks").update({status:"completed",completed_at:new Date().toISOString()}).eq("id",h);if(u)throw u},onSuccess:()=>{s.invalidateQueries({queryKey:["opportunity-tasks",t]}),n({title:"Task marked as complete"})}}),d=h=>{m?_.mutate({id:m.id,data:h}):a.mutate(h)},f=h=>{g(h),c(!0)},q=h=>{const u={low:{label:"🟢 Low",variant:"outline"},medium:{label:"🟡 Medium",variant:"secondary"},high:{label:"🟠 High",variant:"default"},urgent:{label:"🔴 Urgent",variant:"destructive"}},{label:P,variant:A}=u[h]||u.medium;return e.jsx(U,{variant:A,className:"text-xs",children:P})},L=h=>{const u={pending:{label:"⏳ Pending",variant:"outline"},in_progress:{label:"🔄 In Progress",variant:"secondary"},completed:{label:"✅ Completed",variant:"default"},cancelled:{label:"❌ Cancelled",variant:"destructive"}},{label:P,variant:A}=u[h]||u.pending;return e.jsx(U,{variant:A,className:"text-xs",children:P})},l=h=>h?R(new Date(h),"dd/MM/yyyy HH:mm"):"No date",w=h=>!h.due_date||h.status==="completed"||h.status==="cancelled"?!1:new Date(h.due_date)<new Date,M=h=>{const u={call:{label:"📞 Call",className:"bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400"},email:{label:"📧 Email",className:"bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400"},meeting:{label:"📅 Meeting",className:"bg-indigo-100 text-indigo-800 dark:bg-indigo-900/30 dark:text-indigo-400"},follow_up:{label:"🔄 Follow-up",className:"bg-cyan-100 text-cyan-800 dark:bg-cyan-900/30 dark:text-cyan-400"},whatsapp:{label:"💬 WhatsApp",className:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400"},proposal:{label:"📄 Proposal",className:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400"},other:{label:"⚡ Other",className:"bg-slate-100 text-slate-800 dark:bg-slate-900/30 dark:text-slate-400"}},{label:P,className:A}=u[h||"follow_up"]||u.follow_up;return e.jsx(U,{className:A,children:P})};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-sm font-medium text-muted-foreground uppercase tracking-wide",children:["Tasks (",(p==null?void 0:p.length)||0,")"]}),e.jsxs(Y,{size:"sm",variant:"outline",onClick:()=>{g(null),c(!0)},children:[e.jsx(lt,{className:"w-4 h-4 mr-1"}),"Add Task"]})]}),x?e.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center",children:"Loading tasks..."}):!p||p.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-6 text-center border border-dashed rounded-lg",children:"No tasks yet. Add your first follow-up task."}):e.jsx("div",{className:"space-y-2",children:p.map(h=>e.jsx("div",{className:`p-3 rounded-lg border bg-card ${w(h)?"border-destructive/50 bg-destructive/5":""}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:`font-medium text-sm ${h.status==="completed"?"line-through text-muted-foreground":""}`,children:h.title}),w(h)&&e.jsx(U,{variant:"destructive",className:"text-xs",children:"Overdue"})]}),h.description&&e.jsx("p",{className:"text-sm text-muted-foreground mb-2 line-clamp-2",children:h.description}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:l(h.due_date)}),h.assignee&&e.jsxs("span",{children:["• ",h.assignee]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[M(h.task_type),q(h.priority),L(h.status)]})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[h.status!=="completed"&&e.jsx(Y,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>y.mutate(h.id),children:e.jsx(nt,{className:"w-4 h-4 text-emerald-600"})}),e.jsx(Y,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>f(h),children:e.jsx(ft,{className:"w-4 h-4"})}),e.jsx(Y,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>o(h.id),children:e.jsx(Le,{className:"w-4 h-4 text-destructive"})})]})]})},h.id))}),e.jsx(ks,{isOpen:r,onClose:()=>{c(!1),g(null)}
1,onSave:d,initialData:m?{title:m.title,description:m.description||"",due_date:m.due_date?m.due_date.slice(0,16):"",priority:m.priority,status:m.status,task_type:m.task_type||"follow_up",assignee:m.assignee||""}:void 0,isLoading:a.isPending||_.isPending}),e.jsx(Be,{open:!!i,onOpenChange:()=>o(null),children:e.jsxs(Ve,{children:[e.jsxs(Qe,{children:[e.jsx(He,{children:"Delete Task"}),e.jsx(Ge,{children:"Are you sure you want to delete this task? This action cannot be undone."})]}),e.jsxs(Je,{children:[e.jsx(Xe,{children:"Cancel"}),e.jsx(Ze,{onClick:()=>i&&j.mutate(i),children:"Delete"})]})]})})]})},ga=[{value:"note",label:"Note",icon:dt},{value:"call",label:"Call",icon:Ue},{value:"email",label:"Email",icon:it},{value:"meeting",label:"Meeting",icon:qt},{value:"other",label:"Other",icon:ls}],ja=({isOpen:t,onClose:n,onSave:s,initialData:r,isLoading:c=!1})=>{const{register:m,handleSubmit:g,setValue:i,watch:o,reset:p,formState:{errors:x}}=zt({defaultValues:r||{content:"",note_type:"note",is_pinned:!1}}),a=o("note_type"),_=o("is_pinned");ke.useEffect(()=>{t&&p(r||{content:"",note_type:"note",is_pinned:!1})},[t,r,p]);const j=y=>{s(y)};return e.jsx(Rt,{open:t,onOpenChange:n,children:e.jsxs(It,{className:"sm:max-w-md",children:[e.jsx(Ut,{children:e.jsx(Kt,{children:r?"Edit Note":"Add Note"})}),e.jsxs("form",{onSubmit:g(j),className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"note_type",children:"Type"}),e.jsxs(re,{value:a,onValueChange:y=>i("note_type",y),children:[e.jsx(ne,{children:e.jsx(le,{placeholder:"Select type"})}),e.jsx(de,{children:ga.map(y=>e.jsx(F,{value:y.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(y.icon,{className:"w-4 h-4"}),e.jsx("span",{children:y.label})]})},y.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"content",children:"Content"}),e.jsx(Yt,{id:"content",placeholder:"Write your note here...",className:"min-h-[120px] resize-none",...m("content",{required:"Content is required"})}),x.content&&e.jsx("p",{className:"text-xs text-destructive",children:x.content.message})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(T,{htmlFor:"is_pinned",className:"text-sm",children:"Pin this note"}),e.jsx(gs,{id:"is_pinned",checked:_,onCheckedChange:y=>i("is_pinned",y)})]}),e.jsxs($t,{className:"gap-2 sm:gap-0",children:[e.jsx(Y,{type:"button",variant:"outline",onClick:n,children:"Cancel"}),e.jsx(Y,{type:"submit",disabled:c,children:c?"Saving...":"Save"})]})]})]})})},Zt={note:{label:"Note",icon:dt,className:"bg-slate-100 text-slate-700"},call:{label:"Call",icon:Ue,className:"bg-blue-100 text-blue-700"},email:{label:"Email",icon:it,className:"bg-purple-100 text-purple-700"},meeting:{label:"Meeting",icon:qt,className:"bg-emerald-100 text-emerald-700"},other:{label:"Other",icon:ls,className:"bg-gray-100 text-gray-700"}},fa=({note:t,onEdit:n,onDelete:s})=>{const r=Zt[t.note_type]||Zt.note,c=r.icon;return e.jsxs("div",{className:"group relative p-3 rounded-lg border bg-card hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${r.className}`,children:e.jsx(c,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(U,{variant:"secondary",className:"text-xs",children:r.label}),t.is_pinned&&e.jsxs(U,{variant:"outline",className:"text-xs bg-amber-50 text-amber-700 border-amber-200",children:[e.jsx(Fs,{className:"w-3 h-3 mr-1"}),"Pinned"]}),e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:js(new Date(t.created_at),{addSuffix:!0})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap break-words",children:t.content})]})]}),e.jsxs("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity flex items-center gap-1",children:[e.jsx(Y,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>n(t),children:e.jsx(ft,{className:"w-3.5 h-3.5"})}),e.jsx(Y,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:()=>s(t.id),children:e.jsx(Le,{className:"w-3.5 h-3.5"})})]})]})},ya=({opportunityId:t})=>{const n=we(),[s,r]=E.useState(!1),[c,m]=E.useState(null),[g,i]=E.useState(null),{data:o,isLoading:p}=Q({queryKey:["opportunity-notes",t],queryFn:async()=>{const{data:f,error:q}=await k.from("opportunity_notes").select("*").eq("opportunity_id",t).order("is_pinned",{ascending:!1}).order("created_at",{ascending:!1});if(q)throw q;return f}}),x=X({mutationFn:async f=>{const{data:q}=await k.auth.getUser();if(!q.user)throw new Error("Not authenticated");const{data:L,error:l}=await k.from("opportunity_notes").insert({opportunity_id:t,user_id:q.user.id,...f}).select().single();if(l)throw l;return L},onSuccess:()=>{n.invalidateQueries({queryKey:["opportunity-notes",t]}),r(!1),J.success("Note added successfully")},onError:()=>{J.error("Failed to add note")}}),a=X({mutationFn:async({id:f,data:q})=>{const{error:L}=await k.from("opportunity_notes").update(q).eq("id",f);if(L)throw L},onSuccess:()=>{n.invalidateQueries({queryKey:["opportunity-notes",t]}),r(!1),m(null),J.success("Note updated successfully")},onError:()=>{J.error("Failed to update note")}}),_=X({mutationFn:async f=>{const{error:q}=await k.from("opportunity_notes").delete().eq("id",f);if(q)throw q},onSuccess:()=>{n.invalidateQueries({queryKey:["opportunity-notes",t]}),i(null),J.success("Note deleted successfully")},onError:()=>{J.error("Failed to delete note")}}),j=f=>{c?a.mutate({id:c.id,data:f}):x.mutate(f)},y=f=>{m(f),r(!0)},d=()=>{r(!1),m(null)};return p?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(H,{className:"h-5 w-24"}),e.jsx(H,{className:"h-8 w-24"})]}),e.jsx(H,{className:"h-20 w-full"}),e.jsx(H,{className:"h-20 w-full"})]}):e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-muted-foreground uppercase tracking-wide flex items-center gap-2",children:[e.jsx(Vt,{className:"w-4 h-4"}),"Notes & History"]}),e.jsxs(Y,{variant:"outline",size:"sm",onClick:()=>r(!0),className:"h-7 text-xs",children:[e.jsx(lt,{className:"w-3.5 h-3.5 mr-1"}),"Add Note"]})]}),o&&o.length>0?e.jsx("div",{className:"space-y-2 max-h-[300px] overflow-y-auto pr-1",children:o.map(f=>e.jsx(fa,{note:f,onEdit:y,onDelete:i},f.id))}):e.jsxs("div",{className:"text-center py-6 text-muted-foreground",children:[e.jsx(Vt,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No notes yet"}),e.jsx("p",{className:"text-xs",children:"Add notes to track communications and important details"})]}),e.jsx(ja,{isOpen:s,onClose:d,onSave:j,initialData:c?{content:c.content,note_type:c.note_type,is_pinned:c.is_pinned}:void 0,isLoading:x.isPending||a.isPending}),e.jsx(Be,{open:!!g,onOpenChange:()=>i(null),children:e.jsxs(Ve,{children:[e.jsxs(Qe,{children:[e.jsx(He,{children:"Delete Note"}),e.jsx(Ge,{children:"Are you sure you want to delete this note? This action cannot be undone."})]}),e.jsxs(Je,{children:[e.jsx(Xe,{children:"Cancel"}),e.jsx(Ze,{onClick:()=>g&&_.mutate(g),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})},ba=({leadId:t,customerEmail:n,currentOpportunityId:s,onSelectOpportunity:r})=>{const[c,m]=ke.useState(!1),{formatValue:g,language:i}=ce(),{data:o,isLoading:p}=Q({queryKey:["related-opportunities",t,n,s],queryFn:async()=>{let j=k.from("crm_opportunities").select("id, product_name, value, currency, stage, last_activity_date, current_status").neq("id",s).order("last_activity_date",{ascending:!1});if(t)j=j.eq("lead_id",t);else if(n)j=j.eq("customer_email",n);else return[];const{data:y,error:d}=await j;if(d)throw d;return y},enabled:!!(t||n)}),x=(j,y)=>j?g(j,y):g(0),a=j=>j?new Date(j).toLocaleDateString(i,{day:"2-digit",month:"2-digit",year:"numeric"}):"N/A",_=j=>{const y={cart:{label:"Cart",className:"bg-amber-100 text-amber-800 border-amber-200"},pending:{label:"Pending",className:"bg-blue-100 text-blue-800 border-blue-200"},won:{label:"Won",className:"bg-emerald-100 text-emerald-800 border-emerald-200"},lost:{label:"Lost",className:"bg-rose-100 text-rose-800 border-rose-200"}},{label:d,className:f}
1=y[j]||y.pending;return e.jsx(U,{className:`text-xs ${f}`,children:d})};return p?e.jsxs("div",{className:"rounded-lg border bg-card p-4",children:[e.jsx(H,{className:"h-5 w-48 mb-2"}),e.jsx(H,{className:"h-16 w-full"})]}):!o||o.length===0?null:e.jsx(ys,{open:c,onOpenChange:m,children:e.jsxs("div",{className:"rounded-lg border bg-card",children:[e.jsxs(bs,{className:"w-full p-4 flex items-center justify-between hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ft,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:"Related Opportunities"}),e.jsx(U,{variant:"secondary",className:"text-xs",children:o.length})]}),e.jsx(Pt,{className:`w-4 h-4 text-muted-foreground transition-transform ${c?"rotate-180":""}`})]}),e.jsx(Ns,{children:e.jsx("div",{className:"px-4 pb-4 pt-0 border-t",children:e.jsx("div",{className:"space-y-2 pt-3 max-h-[280px] overflow-y-auto",children:o.map(j=>e.jsx("button",{onClick:()=>r(j.id),className:"w-full text-left rounded-lg border bg-muted/30 p-3 hover:bg-muted/60 transition-colors group",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex items-start gap-2 min-w-0 flex-1",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(Re,{className:"w-4 h-4 text-primary"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:j.product_name}),_(j.stage)]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-foreground",children:x(j.value,j.currency)}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ct,{className:"w-3 h-3"}),a(j.last_activity_date)]})]})]})]}),e.jsx(ds,{className:"w-4 h-4 text-muted-foreground group-hover:text-foreground transition-colors flex-shrink-0 mt-2"})]})},j.id))})})})]})})},Na=({isOpen:t,onClose:n,onSave:s,initialData:r,isLoading:c})=>{const{register:m,handleSubmit:g,reset:i,formState:{errors:o}}=zt({defaultValues:{customer_name:r.customer_name||"",customer_email:r.customer_email,customer_phone:r.customer_phone||"",customer_document:r.customer_document||""}});ke.useEffect(()=>{i({customer_name:r.customer_name||"",customer_email:r.customer_email,customer_phone:r.customer_phone||"",customer_document:r.customer_document||""})},[r,i]);const p=x=>{s(x)};return e.jsx(Rt,{open:t,onOpenChange:n,children:e.jsxs(It,{className:"sm:max-w-md",children:[e.jsx(Ut,{children:e.jsx(Kt,{children:"Edit Customer Data"})}),e.jsxs("form",{onSubmit:g(p),className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"customer_name",children:"Name"}),e.jsx(Z,{id:"customer_name",placeholder:"Customer name...",...m("customer_name")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"customer_email",children:"Email *"}),e.jsx(Z,{id:"customer_email",type:"email",placeholder:"[email protected]",...m("customer_email",{required:"Email is required",pattern:{value:/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,message:"Invalid email address"}})}),o.customer_email&&e.jsx("p",{className:"text-xs text-destructive",children:o.customer_email.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"customer_phone",children:"Phone"}),e.jsx(Z,{id:"customer_phone",placeholder:"+55 (11) 99999-9999",...m("customer_phone")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"customer_document",children:"Document (CPF/CNPJ)"}),e.jsx(Z,{id:"customer_document",placeholder:"000.000.000-00",...m("customer_document")})]}),e.jsxs($t,{children:[e.jsx(Y,{type:"button",variant:"outline",onClick:n,children:"Cancel"}),e.jsx(Y,{type:"submit",disabled:c,children:c?"Saving...":"Save Changes"})]})]})]})})},Wt=({opportunityId:t,isOpen:n,onClose:s,onOpportunityChange:r})=>{var h,u,P,A,D,N,I,S;const c=we(),{formatValue:m,language:g}=ce(),[i,o]=E.useState(!1),[p,x]=E.useState(!1),{data:a,isLoading:_}=Q({queryKey:["opportunity",t],queryFn:async()=>{var K;const{data:v,error:O}=await k.from("crm_opportunities").select(`
2          *,
3          leads!crm_opportunities_lead_id_fkey (
4            id,
5            name,
6            email,
7            phone,
8            whatsapp_phone,
9            form_id,
10            created_at,
11            registered_at,
12            tags,
13            utm_data,
14            lead_score,
15            lead_temperature
16          )
17        `).eq("id",t).single();if(O)throw O;if((K=v==null?void 0:v.leads)!=null&&K.form_id){const{data:b}=await k.from("forms").select("name").eq("id",v.leads.form_id).single();b&&(v.leads.form_name=b.name)}return v},enabled:n}),{data:j,isLoading:y}=Q({queryKey:["opportunity-sales",t],queryFn:async()=>{const{data:v,error:O}=await k.from("sales").select("*").eq("opportunity_id",t).order("created_at",{ascending:!0});if(O)throw O;return v},enabled:n}),{data:d}=Q({queryKey:["opportunity-whatsapp-activities",t],queryFn:async()=>
17{if(!a)return[];const v=[];if(a.lead_id&&v.push(`lead_id.eq.${a.lead_id}`),a.customer_phone){const b=jt(a.customer_phone);b.length>0&&v.push(`phone.in.(${b.join(",")})`)}if(v.length===0)return[];const{data:O,error:K}=await k.from("lead_group_activities").select("*").or(v.join(",")).order("created_at",{ascending:!0}).limit(100);if(K)throw K;return O||[]},enabled:n&&!!a}),{data:f}=Q({queryKey:["opportunity-stage-history",t],queryFn:async()=>{const{data:v,error:O}=await k.from("opportunity_stage_history").select("changed_at, to_stage").eq("opportunity_id",t).order("changed_at",{ascending:!0});if(O)throw O;return v||[]},enabled:n}),{data:q}=Q({queryKey:["opportunity-lead-events",t,a==null?void 0:a.lead_id,a==null?void 0:a.customer_phone,a==null?void 0:a.customer_email],queryFn:async()=>{if(!a)return[];const v=new Set;a.lead_id&&v.add(a.lead_id);const O=a.customer_phone?jt(a.customer_phone):[];if(O.length>0||a.customer_email){let W=k.from("leads").select("id").limit(50);const G=[];if(O.length>0&&(G.push(`phone.in.(${O.join(",")})`),G.push(`whatsapp_phone.in.(${O.join(",")})`)),a.customer_email&&G.push(`email.eq.${a.customer_email}`),G.length>0){W=W.or(G.join(","));const{data:te,error:ue}=await W;if(ue)throw ue;te==null||te.forEach(xt=>v.add(xt.id))}}const K=Array.from(v);if(K.length===0)return[];const{data:b,error:C}=await k.from("lead_events").select("*").in("lead_id",K).in("event_type",["message_received","message_sent","document_received","audio_received","image_received","whatsapp_manual_sent","whatsapp_manual_failed"]).order("timestamp",{ascending:!0}).limit(200);if(C)throw C;return b||[]},enabled:n&&!!a}),L=X({mutationFn:async v=>{const{error:O}=await k.from("crm_opportunities").update({customer_name:v.customer_name||null,customer_email:v.customer_email,customer_phone:v.customer_phone||null,customer_document:v.customer_document||null}).eq("id",t);if(O)throw O},onSuccess:()=>{c.invalidateQueries({queryKey:["opportunity",t]}),J.success("Customer data updated"),x(!1)},onError:()=>{J.error("Failed to update customer data")}}),l=X({mutationFn:async()=>{await k.from("opportunity_tasks").delete().eq("opportunity_id",t),await k.from("opportunity_notes").delete().eq("opportunity_id",t);const{error:v}=await k.from("crm_opportunities").delete().eq("id",t);if(v)throw v},onSuccess:()=>{c.invalidateQueries({queryKey:["crm-opportunities"]}),c.invalidateQueries({queryKey:["opportunities-kanban"]}),J.success("Opportunity deleted successfully"),s()},onError:()=>{J.error("Failed to delete opportunity")}}),w=v=>v?R(new Date(v),g==="pt-BR"?"dd/MM/yyyy":"MM/dd/yyyy"):"N/A",M=(v,O)=>{if(v==="lost"&&O){if(O==="payment_failed")return e.jsxs(U,{className:"bg-amber-100 text-amber-800 border-amber-200 flex items-center gap-1",children:[e.jsx(rt,{className:"w-3 h-3"}),"Payment Failed"]});if(O==="user_canceled"||O==="admin_canceled")return e.jsx(U,{className:"bg-rose-100 text-rose-800 border-rose-200",children:"Subscription Canceled"})}const K={cart:{label:"Cart Abandoned",variant:"secondary",className:"bg-amber-100 text-amber-800 border-amber-200"},pending:{label:"Pending Payment",variant:"outline",className:"bg-blue-100 text-blue-800 border-blue-200"},won:{label:"Won",variant:"default",className:"bg-emerald-100 text-emerald-800 border-emerald-200"},lost:{label:"Lost",variant:"destructive",className:"bg-rose-100 text-rose-800 border-rose-200"}},{label:b,className:C}=K[v]||K.pending;return e.jsx(U,{className:C,children:b})};return _?e.jsx(kt,{open:n,onOpenChange:s,children:e.jsxs(Dt,{className:"w-full sm:max-w-lg overflow-y-auto",children:[e.jsx(St,{children:e.jsx(H,{className:"h-8 w-48"})}),e.jsxs("div",{className:"space-y-4 mt-6",children:[e.jsx(H,{className:"h-24 w-full"}),e.jsx(H,{className:"h-32 w-full"}),e.jsx(H,{className:"h-48 w-full"})]})]})}):a?e.jsx(kt,{open:n,onOpenChange:s,children:e.jsxs(Dt,{className:"w-full sm:max-w-lg overflow-y-auto",children:[e.jsxs(St,{className:"pb-4 border-b",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[M(a.stage,a.cancellation_type),e.jsx(hs,{className:"text-lg",children:"Opportunity Details"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Created ",w(a.created_at)]})]}),e.jsxs("div",{className:"space-y-6 mt-6",children:[e.jsx("div",{className:"rounded-lg border bg-card p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(Ot,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"font-semibold text-base truncate",children:a.customer_name||"Unknown Customer"}),e.jsx(Y,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>x(!0),children:e.jsx(ft,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground mt-0.5",children:[e.jsx(it,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"truncate",children:a.customer_email})]}),a.customer_phone&&e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground mt-0.5",children:[e.jsx(Ue,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:a.customer_phone})]}),a.customer_document&&e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground mt-0.5",children:[e.jsx(Ps,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:a.customer_document})]})]})]})}),e.jsx("div",{className:"rounded-lg border bg-card p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-emerald-500/10 flex items-center justify-center flex-shrink-0",children:e.jsx(Re,{className:"w-5 h-5 text-emerald-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("h3",{className:"font-medium text-sm break-words",children:a.product_name}),e.jsx("span",{className:"text-lg font-bold text-emerald-600",children:m(a.value,a.currency)})]}),e.jsxs("div",{className:"mt-3 grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Status"}),e.jsx("p",{className:"font-medium capitalize",children:a.current_status.replace(/_/g," ")})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"First Contact"}),e.jsx("p",{className:"font-medium",children:w(a.first_contact_date)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Last Activity"}),e.jsx("p",{className:"font-medium",children:w(a.last_activity_date)})]}),a.closed_date&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Closed Date"}),e.jsx("p",{className:"font-medium",children:w(a.closed_date)})]})]})]})]})}),e.jsx(ba,{leadId:a.lead_id,customerEmail:a.customer_email,currentOpportunityId:t,onSelectOpportunity:v=>{r&&r(v)}}),e.jsx("div",{className:"rounded-lg border bg-card p-4",children:e.jsx(pa,{opportunityId:t})}),a.leads&&e.jsx(ys,{open:i,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border bg-card",children:[e.jsxs(bs,{className:"w-full p-4 flex items-center justify-between hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ct,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:"Lead Source"}),e.jsx(U,{variant:"outline",className:"text-xs",children:((h=a.leads)==null?void 0:h.form_name)||"Direct"})]}),e.jsx(Pt,{className:`w-4 h-4 text-muted-foreground transition-transform ${i?"rotate-180":""}`})]}),e.jsx(Ns,{children:e.jsxs("div",{className:"px-4 pb-4 pt-0 space-y-3 border-t",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm pt-3",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Lead Registration"}),e.jsx("p",{className:"font-medium",children:a.leads.registered_at?w(a.leads.registered_at):"N/A"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Days to Purchase"}),e.jsxs("p",{className:"font-medium",children:[a.leads.registered_at?Math.floor((new Date(a.first_contact_date).getTime()-new Date(a.leads.registered_at).getTime())/(1e3*60*60*24)):"N/A"," ","days"]})]})]}),a.leads.tags&&a.leads.tags.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs block mb-1",children:"Tags"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:a.leads.tags.map((v,O)=>e.jsxs(U,{variant:"secondary",className:"text-xs",children:[e.jsx(Os,{className:"w-3 h-3 mr-1"}),v]},O))})]}),a.leads.utm_data&&Object.keys(a.leads.utm_data).length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs block mb-1",children:"UTM Parameters"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:Object.entries(a.leads.utm_data).map(([v,O])=>O&&e.jsxs(U,{variant:"outline",className:"text-xs",children:[v,": ",O]},v))})]})]})})]})}),e.jsxs("div",{className:"rounded-lg border bg-card p-4",children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsx("h4",{className:"text-sm font-medium text-muted-foreground uppercase tracking-wide",children:"Timeline"})}),y?e.jsx(H,{className:"h-32 w-full"}):e.jsx(ha,{sales:j||[],leadRegistrationDate:((u=a==null?void 0:a.leads)==null?void 0:u.registered_at)||((P=a==null?void 0:a.leads)==null?void 0:P.created_at),leadFormName:(A=a==null?void 0:a.leads)==null?void 0:A.form_name,whatsappActivities:d||[],leadEvents:q||[],stageHistory:f||[],currentStage:a.stage,cancellationType:a.cancellation_type,opportunityCreatedAt:a.created_at,opportunityAutoCreated:a.auto_created,opportunityTransactionId:a.transaction_id,leadScore:((D=a==null?void 0:a.leads)==null?void 0:D.lead_score)??null,leadTemperature:((N=a==null?void 0:a.leads)==null?void 0:N.lead_temperature)??null,composer:e.jsx(Hs,{leadId:a.lead_id,phone:a.customer_phone||((I=a.leads)==null?void 0:I.phone)||((S=a.leads)==null?void 0:S.whatsapp_phone)||null,opportunityId:t,context:"opportunity"})})]}),e.jsx("div",{className:"rounded-lg border bg-card p-4",children:e.jsx(ya,{opportunityId:t})}),e.jsx("div",{className:"rounded-lg border border-destructive/30 bg-destructive/5 p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-destructive",children:"Danger Zone"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Permanently delete this opportunity and all associated data"})]}),e.jsxs(Be,{children:[e.jsx(ps,{asChild:!0,children:e.jsxs(Y,{variant:"destructive",size:"sm",children:[e.jsx(Le,{className:"w-4 h-4 mr-2"}),"Delete"]})}),e.jsxs(Ve,{children:[e.jsxs(Qe,{children:[e.jsx(He,{children:"Delete Opportunity"}),e.jsx(Ge,{children:"Are you sure you want to delete this opportunity? This will also delete all associated tasks and notes. This action cannot be undone."})]}),e.jsxs(Je,{children:[e.jsx(Xe,{children:"Cancel"}),e.jsx(Ze,{onClick:()=>l.mutate(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})]})]})})]}),e.jsx(Na,{isOpen:p,onClose:()=>x(!1),onSave:v=>L.mutate(v),initialData:{customer_name:a.customer_name,customer_email:a.customer_email,customer_phone:a.customer_phone,customer_document:a.customer_document},isLoading:L.isPending})]})}):null},ut=(t,n,s)=>{const r=new Date;switch(t){case"today":return{startDate:wt(r),endDate:Pe(r)};case"this_month":return{startDate:pe(r),endDate:Pe(r)};case"last_month":const c=Tt(r,1);return{startDate:pe(c),endDate:fs(c)};case"this_year":return{startDate:us(r),endDate:Pe(r)};case"all_time":return{startDate:new Date(2020,0,1),endDate:Pe(r)};
17case"custom":return{startDate:n?wt(new Date(n)):wt(r),endDate:s?Pe(new Date(s)):Pe(r)};default:return{startDate:pe(r),endDate:Pe(r)}}},et=({dateRange:t,onDateRangeChange:n,customDateFrom:s,customDateTo:r,onCustomDateFromChange:c,onCustomDateToChange:m,className:g=""})=>e.jsxs("div",{className:`space-y-3 ${g}`,children:[e.jsxs(re,{value:t,onValueChange:i=>n(i),children:[e.jsx(ne,{className:"w-full md:w-48",children:e.jsx(le,{placeholder:"Date range"})}),e.jsxs(de,{children:[e.jsx(F,{value:"today",children:"Today"}),e.jsx(F,{value:"this_month",children:"This Month"}),e.jsx(F,{value:"last_month",children:"Last Month"}),e.jsx(F,{value:"this_year",children:"This Year"}),e.jsx(F,{value:"all_time",children:"All Time"}),e.jsx(F,{value:"custom",children:"Custom Range"})]})]}),t==="custom"&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(T,{htmlFor:"dateFrom",className:"text-sm",children:"From"}),e.jsx(Z,{id:"dateFrom",type:"date",value:s||R(new Date,"yyyy-MM-dd"),onChange:i=>c==null?void 0:c(i.target.value)})]}),e.jsxs("div",{children:[e.jsx(T,{htmlFor:"dateTo",className:"text-sm",children:"To"}),e.jsx(Z,{id:"dateTo",type:"date",value:r||R(new Date,"yyyy-MM-dd"),onChange:i=>m==null?void 0:m(i.target.value)})]})]})]}),va=()=>{const[t]=Cs(),[n,s]=E.useState(""),[r,c]=E.useState("all"),[m,g]=E.useState("this_month"),[i,o]=E.useState(R(new Date,"yyyy-MM-dd")),[p,x]=E.useState(R(new Date,"yyyy-MM-dd")),[a,_]=E.useState(null),[j,y]=E.useState(!1),{formatValue:d}=ce(),f=ke.useRef(!1);E.useEffect(()=>{const D=t.get("search"),N=t.get("autoOpen");D&&(s(D),g("all_time"),N==="1"&&(f.current=!1))},[t]);const{startDate:q,endDate:L}=ut(m,i,p),{data:l,isLoading:w}=Q({queryKey:["crm-opportunities",r,m,i,p],queryFn:async()=>{const{data:{user:D}}=await k.auth.getUser();if(!D)throw new Error("Not authenticated");let N=k.from("crm_opportunities").select("*").eq("user_id",D.id).order("created_at",{ascending:!1});r!=="all"&&(N=N.eq("stage",r)),N=N.gte("created_at",q.toISOString()).lte("created_at",L.toISOString());const{data:I,error:S}=await N;if(S)throw S;return await Promise.all((I||[]).map(async O=>{var G,te;const[K,b,C,W]=await Promise.all([k.from("sales").select("is_order_bump, is_funnel").eq("opportunity_id",O.id),k.from("opportunity_tasks").select("id",{count:"exact",head:!0}).eq("opportunity_id",O.id),k.from("opportunity_notes").select("id",{count:"exact",head:!0}).eq("opportunity_id",O.id),O.lead_id?k.from("crm_opportunities").select("id",{count:"exact",head:!0}).eq("lead_id",O.lead_id).neq("id",O.id):k.from("crm_opportunities").select("id",{count:"exact",head:!0}).eq("customer_email",O.customer_email).neq("id",O.id)]);return{...O,has_order_bump:((G=K.data)==null?void 0:G.some(ue=>ue.is_order_bump))||!1,has_upsell:((te=K.data)==null?void 0:te.some(ue=>ue.is_funnel))||!1,tasks_count:b.count||0,notes_count:C.count||0,related_count:W.count||0}}))}}),M=l==null?void 0:l.filter(D=>{var N;return D.customer_email.toLowerCase().includes(n.toLowerCase())||((N=D.customer_name)==null?void 0:N.toLowerCase().includes(n.toLowerCase()))||D.product_name.toLowerCase().includes(n.toLowerCase())});E.useEffect(()=>{const D=t.get("autoOpen"),N=t.get("oppId");if(D==="1"&&l&&!f.current&&!w){if(N){const I=l.find(S=>S.id===N);if(I){f.current=!0,_(I),y(!0);return}}M&&M.length===1?(f.current=!0,_(M[0]),y(!0)):M&&M.length>1&&(f.current=!0,console.log(`Found ${M.length} opportunities for this customer`))}},[l,M,t,w]);const h=(D,N)=>D?d(D,N):d(0),u=D=>{switch(D){case"cart":return e.jsx(Ie,{className:"h-4 w-4"});case"pending":return e.jsx(De,{className:"h-4 w-4"});case"won":return e.jsx(nt,{className:"h-4 w-4"});case"lost":return e.jsx(Se,{className:"h-4 w-4"});default:return e.jsx(De,{className:"h-4 w-4"})}},P=D=>{const N={cart:"secondary",pending:"outline",won:"default",lost:"destructive"},I={cart:"Cart",pending:"Pending",won:"Won",lost:"Lost"};return e.jsxs(U,{variant:N[D]||"outline",className:"gap-1",children:[u(D),I[D]||D]})},A=D=>{const N=new Date(D);return isNaN(N.getTime())?"-":vs(N,new Date)?"Today":R(N,"dd MMM yyyy")};return w?e.jsx($,{className:"p-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(H,{className:"h-10 w-full"}),e.jsx(H,{className:"h-64 w-full"})]})}):e.jsxs(e.Fragment,{children:[e.jsx($,{className:"p-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col md:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ot,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Z,{placeholder:"Search by customer or product...",value:n,onChange:D=>s(D.target.value),className:"pl-10"})]}),e.jsxs(re,{value:r,onValueChange:c,children:[e.jsx(ne,{className:"w-full md:w-48",children:e.jsx(le,{placeholder:"Filter by stage"})}),e.jsxs(de,{children:[e.jsx(F,{value:"all",children:"All Stages"}),e.jsx(F,{value:"cart",children:"Cart"}),e.jsx(F,{value:"pending",children:"Pending"}),e.jsx(F,{value:"won",children:"Won"}),e.jsx(F,{value:"lost",children:"Lost"})]})]}),e.jsx(et,{dateRange:m,onDateRangeChange:g,customDateFrom:i,customDateTo:p,onCustomDateFromChange:o,onCustomDateToChange:x})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[(M==null?void 0:M.length)||0," ",((M==null?void 0:M.length)||0)===1?"opportunity":"opportunities"," found"]}
17),e.jsx("div",{className:"rounded-md border",children:e.jsxs($e,{children:[e.jsx(ze,{children:e.jsxs(ie,{children:[e.jsx(B,{children:"Customer"}),e.jsx(B,{children:"Product"}),e.jsx(B,{children:"Value"}),e.jsx(B,{children:"Stage"}),e.jsx(B,{children:"Activity"}),e.jsx(B,{className:"text-right",children:"Actions"})]})}),e.jsx(Ye,{children:(M==null?void 0:M.length)===0?e.jsx(ie,{children:e.jsx(z,{colSpan:6,className:"text-center text-muted-foreground",children:"No opportunities found"})}):M==null?void 0:M.map(D=>e.jsxs(ie,{children:[e.jsx(z,{children:e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"font-medium",children:D.customer_name||"N/A"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:D.customer_email}),D.customer_phone&&e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Ue,{className:"h-3 w-3"}),e.jsx("span",{children:D.customer_phone})]})]})}),e.jsx(z,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{children:D.product_name}),e.jsxs("div",{className:"flex gap-1",children:[D.has_order_bump&&e.jsx(U,{variant:"outline",className:"text-xs",children:"Order Bump"}),D.has_upsell&&e.jsx(U,{variant:"outline",className:"text-xs",children:"Upsell"})]})]})}),e.jsx(z,{className:"font-medium",children:h(D.value,D.currency)}),e.jsx(z,{children:P(D.stage)}),e.jsx(z,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:A(D.last_activity_date)}),e.jsx(Nt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(D.tasks_count||0)>0&&e.jsxs(be,{children:[e.jsx(Ne,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 text-xs text-blue-600 bg-blue-50 px-1.5 py-0.5 rounded-md",children:[e.jsx(gt,{className:"h-3 w-3"}),e.jsx("span",{children:D.tasks_count})]})}),e.jsx(ve,{children:e.jsxs("p",{children:[D.tasks_count," task",D.tasks_count!==1?"s":""]})})]}),(D.notes_count||0)>0&&e.jsxs(be,{children:[e.jsx(Ne,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 text-xs text-amber-600 bg-amber-50 px-1.5 py-0.5 rounded-md",children:[e.jsx(dt,{className:"h-3 w-3"}),e.jsx("span",{children:D.notes_count})]})}),e.jsx(ve,{children:e.jsxs("p",{children:[D.notes_count," note",D.notes_count!==1?"s":""]})})]}),(D.related_count||0)>0&&e.jsxs(be,{children:[e.jsx(Ne,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 text-xs text-purple-600 bg-purple-50 px-1.5 py-0.5 rounded-md",children:[e.jsx(Ft,{className:"h-3 w-3"}),e.jsx("span",{children:D.related_count})]})}),e.jsx(ve,{children:e.jsxs("p",{children:[D.related_count," related opportunit",D.related_count!==1?"ies":"y"]})})]})]})})]})}),e.jsx(z,{className:"text-right",children:e.jsxs(Y,{variant:"ghost",size:"sm",onClick:()=>{_(D),y(!0)},children:[e.jsx(yt,{className:"h-4 w-4 mr-2"}),"View"]})})]},D.id))})]})})]})}),a&&e.jsx(Wt,{opportunityId:a.id,isOpen:j,onClose:()=>{y(!1),_(null)},onOpportunityChange:D=>{_({...a,id:D})}})]})},_a=({sale:t,isOpen:n,isEditing:s,onClose:r,onSave:c})=>{const{toast:m}=mt(),g=we(),{formatValue:i,language:o}=ce(),[p,x]=E.useState({});ke.useEffect(()=>{t&&x(t)},[t]);const a=(y,d)=>{x(f=>({...f,[y]:d}))},_=async()=>{try{const{error:y}=await k.from("sales").update({status:p.status,notes:p.notes,tags:p.tags}).eq("id",p.id);if(y)throw y;await g.invalidateQueries({queryKey:["sales"]}),await g.invalidateQueries({queryKey:["crm-stats"]}),m({title:"Success",description:"Sale updated successfully"}),c()}catch(y){m({title:"Error",description:y.message,variant:"destructive"})}},j=y=>y?new Date(y).toLocaleDateString(o):"-";return t?e.jsx(kt,{open:n,onOpenChange:r,children:e.jsxs(Dt,{className:"overflow-y-auto w-full sm:max-w-2xl",children:[e.jsx(St,{children:e.jsx(hs,{children:"Sale Details"})}),e.jsxs("div",{className:"space-y-6 py-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Customer Information"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Name"}),e.jsx("p",{className:"font-medium",children:t.customer_name||"-"})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Email"}),e.jsx("p",{className:"font-medium text-sm",children:t.customer_email||"-"})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Phone"}),e.jsx("p",{className:"font-medium",children:t.customer_phone||"-"})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Document"}),e.jsx("p",{className:"font-medium",children:t.customer_document||"-"})]})]})]}),e.jsx(Ae,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Product Information"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Product"}),e.jsx("p",{className:"font-medium",children:t.product_name||"-"})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Product ID"}),e.jsx("p",{className:"font-medium",children:t.product_id||"-"})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Product UCode"}),e.jsx("p",{className:"font-medium text-sm",children:t.product_ucode||"-"})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Offer Code"}),e.jsx("p",{className:"font-medium",children:t.offer_code||"-"})]})]})]}),e.jsx(Ae,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Transaction Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Status"}),s?e.jsxs(re,{value:p.status,onValueChange:y=>a("status",y),children:[e.jsx(ne,{children:e.jsx(le,{})}),e.jsxs(de,{children:[e.jsx(F,{value:"approved",children:"Approved"}),e.jsx(F,{value:"pending",children:"Pending"}),e.jsx(F,{value:"refunded",children:"Refunded"}),e.jsx(F,{value:"cancelled",children:"Cancelled"}),e.jsx(F,{value:"chargeback",children:"Chargeback"})]})]}):e.jsx(U,{variant:t.status==="approved"?"default":t.status==="refunded"?"destructive":"secondary",children:t.status})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Transaction ID"}),e.jsx("p",{className:"font-medium text-sm",children:t.transaction_id||"-"})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Payment Method"}),e.jsx("p",{className:"font-medium",children:t.payment_method||"-"})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Installments"}),e.jsxs("p",{className:"font-medium",children:[t.installments||1,"x"]})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Platform"}),e.jsx(U,{variant:"outline",className:"capitalize",children:t.platform})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Currency"}),e.jsx("p",{className:"font-medium",children:t.currency||"BRL"})]})]})]}),e.jsx(Ae,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Financial Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Gross Value"}),e.jsx("p",{className:"font-semibold text-green-600",children:i(t.gross_value,t.currency)})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Net Value"}),e.jsx("p",{className:"font-semibold text-blue-600",children:i(t.net_value,t.currency)})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Commission"}),e.jsx("p",{className:"font-medium",children:i(t.commission_value,t.currency)})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Fee"}),e.jsx("p",{className:"font-medium",children:i(t.fee_value,t.currency)})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Marketplace Commission"}),e.jsx("p",{className:"font-medium",children:i(t.marketplace_commission,t.currency)})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Producer Commission"}),e.jsx("p",{className:"font-medium",children:i(t.producer_commission,t.currency)})]})]})]}),e.jsx(Ae,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Important Dates"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Order Date"}),e.jsx("p",{className:"font-medium",children:j(t.order_date)})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Purchase Date"}),e.jsx("p",{className:"font-medium",children:j(t.purchase_date)})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Approved Date"}),e.jsx("p",{className:"font-medium",children:j(t.approved_date)})]}),t.refund_date&&e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Refund Date"}),e.jsx("p",{className:"font-medium text-red-600",children:j(t.refund_date)})]})]})]}),t.producer_name&&e.jsxs(e.Fragment,{children:[e.jsx(Ae,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Producer Information"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Producer"}),e.jsx("p",{className:"font-medium",children:t.producer_name})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Document"}),e.jsx("p",{className:"font-medium",children:t.producer_document||"-"})]}),t.has_co_production&&e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Co-Production"}),e.jsx(U,{children:"Yes"})]})]})]})]}),e.jsx(Ae,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Additional Information"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(T,{children:"Notes"}),s?e.jsx(Yt,{value:p.notes||"",onChange:y=>a("notes",y.target.value),rows:3}):e.jsx("p",{className:"text-sm text-muted-foreground",children:t.notes||"No notes"})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Tags"}),s?e.jsx(Z,{value:(p.tags||[]).join(", "),onChange:y=>a("tags",y.target.value.split(",").map(d=>d.trim())),placeholder:"tag1, tag2, tag3"}):e.jsx("div",{className:"flex gap-2 flex-wrap",children:t.tags&&t.tags.length>0?t.tags.map((y,d)=>e.jsx(U,{variant:"secondary",children:y},d)):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No tags"})})]})]})]})]}),s&&e.jsxs("div",{className:"flex gap-2 pt-4 border-t",children:[e.jsx(Y,{onClick:_,className:"flex-1",children:"Save Changes"}),e.jsx(Y,{onClick:r,variant:"outline",className:"flex-1",children:"Cancel"})]})]})}):null},wa=({initialStatusFilter:t="all"})=>{const{toast:n}=mt(),s=we(),[r,c]=E.useState(""),[m,g]=E.useState(t),[i,o]=E.useState("this_month"),[p,x]=E.useState(R(new Date,"yyyy-MM-dd")),[a,_]=E.useState(R(new Date,"yyyy-MM-dd")),[j,y]=E.useState(null),[d,f]=E.useState(!1),[q,L]=E.useState(!1),[l,w]=E.useState(null),{formatValue:
17M,language:h}=ce(),{startDate:u,endDate:P}=ut(i,p,a);E.useEffect(()=>{t!=="all"&&g(t)},[t]);const{data:A,isLoading:D}=Q({queryKey:["sales",m,i,p,a],queryFn:async()=>{const{data:{user:b}}=await k.auth.getUser();let C=k.from("sales").select("*").eq("user_id",b==null?void 0:b.id).gte("created_at",u.toISOString()).lte("created_at",P.toISOString()).order("purchase_date",{ascending:!1});m!=="all"&&(C=C.eq("status",m));const{data:W,error:G}=await C;if(G)throw G;return W}}),N=A==null?void 0:A.filter(b=>{var W,G,te,ue;const C=r.toLowerCase();return((W=b.customer_name)==null?void 0:W.toLowerCase().includes(C))||((G=b.customer_email)==null?void 0:G.toLowerCase().includes(C))||((te=b.product_name)==null?void 0:te.toLowerCase().includes(C))||((ue=b.transaction_id)==null?void 0:ue.toLowerCase().includes(C))}),I=b=>{const C={approved:"default",billet_printed:"secondary",pending:"secondary",canceled:"outline",expired:"destructive",refunded:"destructive",chargeback:"destructive",checkout_abandoned:"outline"},W={approved:"✓ Approved",billet_printed:"⏳ Awaiting Payment",pending:"⏳ Pending",canceled:"✗ Payment Failed",expired:"⌛ Expired",refunded:"↩ Refunded",chargeback:"⚠ Chargeback",checkout_abandoned:"🛒 Cart Abandoned"};return e.jsx(U,{variant:C[b]||"secondary",children:W[b]||b})},S=(b,C)=>b?M(b,C):"-",v=b=>b?new Date(b).toLocaleDateString(h):"-",O=b=>{w(b),L(!0)},K=async()=>{if(l)try{const{error:b}=await k.from("sales").delete().eq("id",l);if(b)throw b;await s.invalidateQueries({queryKey:["sales"]}),await s.invalidateQueries({queryKey:["crm-stats"]}),n({title:"Success",description:"Sale deleted successfully"})}catch(b){n({title:"Error",description:b.message,variant:"destructive"})}finally{L(!1),w(null)}};return D?e.jsx("div",{className:"text-center py-8",children:"Loading sales..."}):e.jsxs("div",{className:"space-y-4",children:[e.jsx($,{className:"p-4",children:e.jsx("div",{className:"flex flex-col gap-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ot,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(Z,{placeholder:"Name, email, product...",value:r,onChange:b=>c(b.target.value),className:"pl-10"})]}),e.jsx("div",{children:e.jsxs(re,{value:m,onValueChange:g,children:[e.jsx(ne,{className:"w-full md:w-48",children:e.jsx(le,{placeholder:"Filter by status"})}),e.jsxs(de,{children:[e.jsx(F,{value:"all",children:"All Status"}),e.jsx(F,{value:"approved",children:"✓ Approved"}),e.jsx(F,{value:"billet_printed",children:"⏳ Awaiting Payment"}),e.jsx(F,{value:"pending",children:"⏳ Pending"}),e.jsx(F,{value:"canceled",children:"✗ Payment Failed"}),e.jsx(F,{value:"expired",children:"⌛ Expired"}),e.jsx(F,{value:"refunded",children:"↩ Refunded"}),e.jsx(F,{value:"chargeback",children:"⚠ Chargeback"}),e.jsx(F,{value:"checkout_abandoned",children:"🛒 Cart Abandoned"})]})]})}),e.jsx(et,{dateRange:i,onDateRangeChange:o,customDateFrom:p,customDateTo:a,onCustomDateFromChange:x,onCustomDateToChange:_})]})})}),!N||N.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx("p",{children:"No sales found"}),e.jsx("p",{className:"text-sm mt-2",children:"Configure your webhook to start receiving sales data"})]}):e.jsx("div",{className:"border rounded-lg",children:e.jsxs($e,{children:[e.jsx(ze,{children:e.jsxs(ie,{children:[e.jsx(B,{children:"Date"}),e.jsx(B,{children:"Customer"}),e.jsx(B,{children:"Product"}),e.jsx(B,{children:"Payment"}),e.jsx(B,{children:"Status"}),e.jsx(B,{children:"Amount"}),e.jsx(B,{children:"Platform"}),e.jsx(B,{children:"Actions"})]})}),e.jsx(Ye,{children:N.map(b=>e.jsxs(ie,{children:[e.jsx(z,{className:"text-sm",children:v(b.purchase_date)}),e.jsx(z,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:b.customer_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b.customer_email})]})}),e.jsx(z,{className:"text-sm max-w-[200px]",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:b.product_name}),b.is_order_bump&&e.jsxs(U,{variant:"secondary",className:"text-xs flex items-center gap-1 flex-shrink-0",children:[e.jsx(Ie,{className:"w-3 h-3"}),"Bump"]})]})}),e.jsx(z,{children:e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-medium",children:b.payment_method||"-"}),b.installments&&b.installments>1&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.installments,"x"]})]})}),e.jsx(z,{children:I(b.status)}),e.jsx(z,{className:"font-medium",children:S(b.gross_value,b.currency)}),e.jsx(z,{children:e.jsx(U,{variant:"outline",className:"capitalize",children:b.platform})}),e.jsx(z,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{variant:"ghost",size:"icon",onClick:()=>{y(b),f(!1)},children:e.jsx(yt,{className:"w-4 h-4"})}),e.jsx(Y,{variant:"ghost",size:"icon",onClick:()=>{y(b),f(!0)},children:e.jsx(ft,{className:"w-4 h-4"})}),e.jsx(Y,{variant:"ghost",size:"icon",onClick:()=>O(b.id),children:e.jsx(Le,{className:"w-4 h-4 text-destructive"})})]})})]},b.id))})]})}),e.jsx(_a,{sale:j,isOpen:!!j,isEditing:d,onClose:()=>{y(null),f(!1)},onSave:()=>{y(null),f(!1),s.invalidateQueries({queryKey:["sales"]}),s.invalidateQueries({queryKey:["crm-stats"]})}}),e.jsx(Be,{open:q,onOpenChange:L,children:e.jsxs(Ve,{children:[e.jsxs(Qe,{children:[e.jsx(He,{children:"Are you sure?"}),e.jsx(Ge,{children:"This action cannot be undone. This will permanently delete the sale record."})]}),e.jsxs(Je,{children:[e.jsx(Xe,{children:"Cancel"}),e.jsx(Ze,{onClick:K,children:"Delete"})]})]})})]})},ka=()=>{const[t,n]=E.useState(""),[s,r]=E.useState("this_month"),[c,m]=E.useState(R(new Date,"yyyy-MM-dd")),[g,i]=E.useState(R(new Date,"yyyy-MM-dd")),[o,p]=E.useState(null),[x,a]=E.useState(!1),{formatValue:_,convertValue:j,language:y}=ce(),{startDate:d,endDate:f}=ut(s,c,g),{data:q,isLoading:L}=Q({queryKey:["opportunities-kanban",s,c,g],queryFn:async()=>{const{data:{user:u}}=await k.auth.getUser(),{data:P,error:A}=await k.from("crm_opportunities").select("*").eq("user_id",u==null?void 0:u.id).gte("created_at",d.toISOString()).lte("created_at",f.toISOString()).order("created_at",{ascending:!1});if(A)throw A;return await Promise.all((P||[]).map(async N=>{var K,b;const[I,S,v,O]=await Promise.all([k.from("sales").select("is_order_bump, is_funnel").eq("opportunity_id",N.id),k.from("opportunity_tasks").select("id",{count:"exact",head:!0}).eq("opportunity_id",N.id),k.from("opportunity_notes").select("id",{count:"exact",head:!0}).eq("opportunity_id",N.id),N.lead_id?k.from("crm_opportunities").select("id",{count:"exact",head:!0}).eq("lead_id",N.lead_id).neq("id",N.id):k.from("crm_opportunities").select("id",{count:"exact",head:!0}).eq("customer_email",N.customer_email).neq("id",N.id)]);return{...N,has_order_bump:((K=I.data)==null?void 0:K.some(C=>
17C.is_order_bump))||!1,has_upsell:((b=I.data)==null?void 0:b.some(C=>C.is_funnel))||!1,tasks_count:S.count||0,notes_count:v.count||0,related_count:O.count||0}}))}}),l=[{key:"cart",label:"Cart Abandoned",color:"bg-yellow-50 border-yellow-200",icon:Ie},{key:"pending",label:"Pending",color:"bg-blue-50 border-blue-200",icon:De},{key:"won",label:"Won",color:"bg-green-50 border-green-200",icon:nt},{key:"lost",label:"Lost",color:"bg-red-50 border-red-200",icon:Se}],w=(u,P)=>u?_(u,P):_(0),M=u=>{const P=(q==null?void 0:q.filter(A=>A.stage===u))||[];return t?P.filter(A=>{var D;return A.customer_email.toLowerCase().includes(t.toLowerCase())||((D=A.customer_name)==null?void 0:D.toLowerCase().includes(t.toLowerCase()))||A.product_name.toLowerCase().includes(t.toLowerCase())}):P},h=u=>u.reduce((P,A)=>P+j(A.value,A.currency),0);return L?e.jsxs("div",{className:"space-y-4",children:[e.jsx(H,{className:"h-20"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-4",children:[...Array(4)].map((u,P)=>e.jsx(H,{className:"h-[500px]"},P))})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx($,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ot,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Z,{placeholder:"Search by customer or product...",value:t,onChange:u=>n(u.target.value),className:"pl-10"})]}),e.jsx(et,{dateRange:s,onDateRangeChange:r,customDateFrom:c,customDateTo:g,onCustomDateFromChange:m,onCustomDateToChange:i})]})}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:l.map(u=>{const P=M(u.key),A=h(P),D=u.icon;return e.jsxs($,{className:`p-4 ${u.color}`,children:[e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(D,{className:"h-5 w-5"}),e.jsx("h3",{className:"font-semibold text-lg",children:u.label})]}),e.jsxs("div",{className:"flex justify-between items-center text-sm text-muted-foreground",children:[e.jsxs("span",{children:[P.length," opportunities"]}),e.jsx("span",{className:"font-medium text-foreground",children:w(A)})]})]}),e.jsx("div",{className:"space-y-3 max-h-[600px] overflow-y-auto",children:P.map(N=>e.jsx($,{className:"p-3 bg-background hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{p(N),a(!0)},children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ot,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("p",{className:"font-medium text-sm truncate",children:N.customer_name||"N/A"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(it,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:N.customer_email})]}),N.customer_phone&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ue,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:N.customer_phone})]})]}),e.jsx(Nt,{children:e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[(N.tasks_count||0)>0&&e.jsxs(be,{children:[e.jsx(Ne,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-0.5 text-xs text-blue-600 bg-blue-100 px-1.5 py-0.5 rounded-full",children:[e.jsx(gt,{className:"h-3 w-3"}),e.jsx("span",{className:"font-medium",children:N.tasks_count})]})}),e.jsx(ve,{children:e.jsxs("p",{children:[N.tasks_count," task",N.tasks_count!==1?"s":""]})})]}),(N.notes_count||0)>0&&e.jsxs(be,{children:[e.jsx(Ne,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-0.5 text-xs text-amber-600 bg-amber-100 px-1.5 py-0.5 rounded-full",children:[e.jsx(dt,{className:"h-3 w-3"}),e.jsx("span",{className:"font-medium",children:N.notes_count})]})}),e.jsx(ve,{children:e.jsxs("p",{children:[N.notes_count," note",N.notes_count!==1?"s":""]})})]}),(N.related_count||0)>0&&e.jsxs(be,{children:[e.jsx(Ne,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-0.5 text-xs text-purple-600 bg-purple-100 px-1.5 py-0.5 rounded-full",children:[e.jsx(Ft,{className:"h-3 w-3"}),e.jsx("span",{className:"font-medium",children:N.related_count})]})}),e.jsx(ve,{children:e.jsxs("p",{children:[N.related_count," related opportunit",N.related_count!==1?"ies":"y"]})})]})]})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("p",{className:"text-sm truncate",children:N.product_name})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-2 border-t",children:[e.jsx("span",{className:"text-sm font-semibold",children:w(N.value,N.currency)}),e.jsxs("div",{className:"flex gap-1",children:[N.has_order_bump&&e.jsx(U,{variant:"outline",className:"text-xs",children:"Order Bump"}),N.has_upsell&&e.jsx(U,{variant:"outline",className:"text-xs",children:"Upsell"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(ct,{className:"h-3 w-3 flex-shrink-0"}
17),e.jsx("span",{children:new Date(N.created_at).toLocaleString(y,{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})})]})]})},N.id))})]},u.label)})}),e.jsx(Wt,{opportunityId:(o==null?void 0:o.id)||"",isOpen:x,onClose:()=>{a(!1),p(null)},onOpportunityChange:u=>{o&&p({...o,id:u})}})]})},Da=()=>{const{user:t}=ge(),n=we(),[s,r]=E.useState("this_month"),[c,m]=E.useState(""),[g,i]=E.useState(""),[o,p]=E.useState("all"),[x,a]=E.useState("all"),[_,j]=E.useState("all"),[y,d]=E.useState(!1),[f,q]=E.useState(null),[L,l]=E.useState(null),{startDate:w,endDate:M}=ut(s,c,g),{data:h,isLoading:u}=Q({queryKey:["crm-all-tasks",t==null?void 0:t.id,s,c,g,o,x,_],queryFn:async()=>{if(!(t!=null&&t.id))return[];let C=k.from("opportunity_tasks").select(`
18          id,
19          title,
20          description,
21          due_date,
22          priority,
23          status,
24          task_type,
25          assignee,
26          created_at,
27          opportunity_id,
28          crm_opportunities!inner (
29            customer_name,
30            customer_email,
31            product_name
32          )
33        `).eq("user_id",t.id).order("due_date",{ascending:!0,nullsFirst:!1});w&&(C=C.gte("created_at",w.toISOString())),M&&(C=C.lte("created_at",M.toISOString())),o!=="all"&&(C=C.eq("status",o)),x!=="all"&&(C=C.eq("priority",x)),_!=="all"&&(C=C.eq("task_type",_));const{data:W,error:G}=await C;if(G)throw G;return(W||[]).map(te=>({...te,opportunity:te.crm_opportunities}))},enabled:!!(t!=null&&t.id)}),P=X({mutationFn:async({id:C,data:W})=>{const{error:G}=await k.from("opportunity_tasks").update(W).eq("id",C);if(G)throw G},onSuccess:()=>{n.invalidateQueries({queryKey:["crm-all-tasks"]}),J.success("Task updated"),d(!1),q(null)},onError:()=>J.error("Failed to update task")}),A=X({mutationFn:async C=>{const{error:W}=await k.from("opportunity_tasks").delete().eq("id",C);if(W)throw W},onSuccess:()=>{n.invalidateQueries({queryKey:["crm-all-tasks"]}),J.success("Task deleted"),l(null)},onError:()=>J.error("Failed to delete task")}),D=X({mutationFn:async C=>{const{error:W}=await k.from("opportunity_tasks").update({status:"completed",completed_at:new Date().toISOString()}).eq("id",C);if(W)throw W},onSuccess:()=>{n.invalidateQueries({queryKey:["crm-all-tasks"]}),J.success("Task completed")},onError:()=>J.error("Failed to complete task")}),N=C=>{q(C),d(!0)},I=C=>{f&&P.mutate({id:f.id,data:C})},S=C=>{const G={low:{label:"🟢 Low",className:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400"},medium:{label:"🟡 Medium",className:"bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400"},high:{label:"🟠 High",className:"bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-400"},urgent:{label:"🔴 Urgent",className:"bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400"}}[C||"medium"];return e.jsx(U,{className:G.className,children:G.label})},v=C=>{const G={pending:{label:"⏳ Pending",className:"bg-slate-100 text-slate-800 dark:bg-slate-900/30 dark:text-slate-400"},in_progress:{label:"🔄 In Progress",className:"bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400"},completed:{label:"✅ Completed",className:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400"},cancelled:{label:"❌ Cancelled",className:"bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400"}}[C||"pending"];return e.jsx(U,{className:G.className,children:G.label})},O=C=>{const W={call:{label:"📞 Call",className:"bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400"},email:{label:"📧 Email",className:"bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400"},meeting:{label:"📅 Meeting",className:"bg-indigo-100 text-indigo-800 dark:bg-indigo-900/30 dark:text-indigo-400"},follow_up:{label:"🔄 Follow-up",className:"bg-cyan-100 text-cyan-800 dark:bg-cyan-900/30 dark:text-cyan-400"},whatsapp:{label:"💬 WhatsApp",className:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400"},proposal:{label:"📄 Proposal",className:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400"},other:{label:"⚡ Other",className:"bg-slate-100 text-slate-800 dark:bg-slate-900/30 dark:text-slate-400"}},{label:G,className:te}=W[C||"follow_up"]||W.follow_up;return e.jsx(U,{className:te,children:G})},K=C=>!C.due_date||C.status==="completed"||C.status==="cancelled"?!1:Xs(me(C.due_date))&&!Ct(me(C.due_date)),b=C=>{if(!C)return"-";const W=me(C);return Ct(W)?"Today":R(W,"dd/MM/yyyy HH:mm")};return u?e.jsxs("div",{className:"space-y-4",children:[e.jsx(H,{className:"h-10 w-full"}),e.jsx(H,{className:"h-64 w-full"})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx(et,{dateRange:s,onDateRangeChange:r,customDateFrom:c,customDateTo:g,onCustomDateFromChange:m,onCustomDateToChange:i}),e.jsxs(re,{value:o,onValueChange:p,children:[e.jsx(ne,{className:"w-[150px]",children:e.jsx(le,{placeholder:"Status"})}),e.jsxs(de,{children:[e.jsx(F,{value:"all",children:"All Status"}),e.jsx(F,{value:"pending",children:"Pending"}),e.jsx(F,{value:"in_progress",children:"In Progress"}),e.jsx(F,{value:"completed",children:"Completed"}),e.jsx(F,{value:"cancelled",children:"Cancelled"})]})]}),e.jsxs(re,{value:x,onValueChange:a,children:[e.jsx(ne,{className:"w-[150px]",children:e.jsx(le,{placeholder:"Priority"})}),e.jsxs(de,{children:[e.jsx(F,{value:"all",children:"All Priority"}),e.jsx(F,{value:"urgent",children:"Urgent"}),e.jsx(F,{value:"high",children:"High"}),e.jsx(F,{value:"medium",children:"Medium"}),e.jsx(F,{value:"low",children:"Low"})]})]}),e.jsxs(re,{value:_,onValueChange:j,children:[e.jsx(ne,{className:"w-[150px]",children:e.jsx(le,{placeholder:"Type"})}),e.jsxs(de,{children:[e.jsx(F,{value:"all",children:"All Types"}),e.jsx(F,{value:"call",children:"📞 Call"}),e.jsx(F,{value:"email",children:"📧 Email"}),e.jsx(F,{value:"meeting",children:"📅 Meeting"}),e.jsx(F,{value:"follow_up",children:"🔄 Follow-up"}),e.jsx(F,{value:"whatsapp",children:"💬 WhatsApp"}),e.jsx(F,{value:"proposal",children:"📄 Proposal"}),e.jsx(F,{value:"other",children:"⚡ Other"})]})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(gt,{className:"h-4 w-4"}),(h==null?void 0:h.length)||0," tasks"]})]}),h&&h.length>0?e.jsx("div",{className:"rounded-md border",children:e.jsxs($e,{children:[e.jsx(ze,{children:e.jsxs(ie,{children:[e.jsx(B,{children:"Task"}),e.jsx(B,{children:"Type"}),e.jsx(B,{children:"Opportunity"}),e.jsx(B,{children:"Due Date"}),e.jsx(B,{children:"Priority"}),e.jsx(B,{children:"Status"}),e.jsx(B,{children:"Assignee"}),e.jsx(B,{className:"text-right",children:"Actions"})]})}),e.jsx(Ye,{children:h.map(C=>{var W,G,te;return e.jsxs(ie,{className:K(C)?"bg-red-50/50 dark:bg-red-900/10":"",children:[e.jsx(z,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-medium",children:C.title}),C.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:C.description})]})}),e.jsx(z,{children:O(C.task_type)}),e.jsx(z,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:((W=C.opportunity)==null?void 0:W.customer_name)||((G=C.opportunity)==null?void 0:G.customer_email)}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:(te=C.opportunity)==null?void 0:te.product_name})]})}),e.jsx(z,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ct,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:K(C)?"text-red-600 font-medium":"",children:b(C.due_date)})]})}),e.jsx(z,{children:S(C.priority)}),e.jsx(z,{children:v(C.status)}),e.jsx(z,{children:C.assignee?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ot,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm",children:C.assignee})]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(z,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[C.status!=="completed"&&C.status!=="c
33ancelled"&&e.jsx(Y,{variant:"ghost",size:"icon",onClick:()=>D.mutate(C.id),className:"h-8 w-8 text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(Lt,{className:"h-4 w-4"})}),e.jsx(Y,{variant:"ghost",size:"icon",onClick:()=>N(C),className:"h-8 w-8",children:e.jsx(Ls,{className:"h-4 w-4"})}),e.jsx(Y,{variant:"ghost",size:"icon",onClick:()=>l(C.id),className:"h-8 w-8 text-destructive hover:text-destructive",children:e.jsx(Le,{className:"h-4 w-4"})})]})})]},C.id)})})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center border rounded-lg",children:[e.jsx(gt,{className:"h-12 w-12 text-muted-foreground/50 mb-4"}),e.jsx("h3",{className:"font-semibold text-lg",children:"No tasks found"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Tasks will appear here when you create them in opportunity details"})]}),e.jsx(ks,{isOpen:y,onClose:()=>{d(!1),q(null)},onSave:I,initialData:f?{title:f.title,description:f.description||"",due_date:f.due_date||"",priority:f.priority||"medium",status:f.status||"pending",task_type:f.task_type||"follow_up",assignee:f.assignee||""}:void 0,isLoading:P.isPending}),e.jsx(Be,{open:!!L,onOpenChange:()=>l(null),children:e.jsxs(Ve,{children:[e.jsxs(Qe,{children:[e.jsx(He,{children:"Delete Task"}),e.jsx(Ge,{children:"Are you sure you want to delete this task? This action cannot be undone."})]}),e.jsxs(Je,{children:[e.jsx(Xe,{children:"Cancel"}),e.jsx(Ze,{onClick:()=>L&&A.mutate(L),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})},Sa=()=>{const{toast:t}=mt(),n=we(),[s,r]=E.useState(!1),[c,m]=E.useState("hotmart"),{data:g,isLoading:i}=Q({queryKey:["webhook-endpoint"],queryFn:async()=>{const{data:{user:a}}=await k.auth.getUser(),{data:_,error:j}=await k.from("webhook_endpoints").select("*").eq("user_id",a==null?void 0:a.id).maybeSingle();if(j&&j.code!=="PGRST116")throw j;return _}}),o=X({mutationFn:async a=>{const{data:{user:_}}=await k.auth.getUser(),j=crypto.randomUUID().replace(/-/g,""),y=`https://roksdtmnlqynbzukdqzm.supabase.co/functions/v1/receive-webhook?token=${j}`,{data:d,error:f}=await k.from("webhook_endpoints").insert({user_id:_==null?void 0:_.id,webhook_token:j,webhook_url:y,platform:a,is_active:!0}).select().single();if(f)throw f;return d},onSuccess:()=>{t({title:"Webhook created successfully"}),n.invalidateQueries({queryKey:["webhook-endpoint"]})},onError:a=>{t({title:"Error creating webhook",description:a.message,variant:"destructive"})}}),p=X({mutationFn:async()=>{const a=crypto.randomUUID().replace(/-/g,""),_=`https://roksdtmnlqynbzukdqzm.supabase.co/functions/v1/receive-webhook?token=${a}`,{error:j}=await k.from("webhook_endpoints").update({webhook_token:a,webhook_url:_}).eq("id",g==null?void 0:g.id);if(j)throw j},onSuccess:()=>{t({title:"Token regenerated successfully"}),n.invalidateQueries({queryKey:["webhook-endpoint"]})},onError:a=>{t({title:"Error regenerating token",description:a.message,variant:"destructive"})}}),x=()=>{navigator.clipboard.writeText((g==null?void 0:g.webhook_url)||""),t({title:"Webhook URL copied to clipboard"})};return i?e.jsx("div",{className:"text-center py-8",children:"Loading..."}):g?e.jsxs("div",{className:"space-y-6",children:[e.jsx($,{className:"p-4 bg-muted/50",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(T,{className:"text-sm font-medium",children:"Platform"}),e.jsx("p",{className:"text-sm mt-1 capitalize font-medium",children:g.platform})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-sm font-medium",children:"Webhook URL"}),e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(Z,{value:g.webhook_url,readOnly:!0,className:"font-mono text-xs"}),e.jsx(Y,{onClick:x,variant:"outline",size:"icon",children:e.jsx(ht,{className:"w-4 h-4"})})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Use this URL in your ",g.platform," webhook configuration"]})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-sm font-medium",children:"Webhook Token"}),e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(Z,{value:s?g.webhook_token:"•".repeat(32),readOnly:!0,className:"font-mono text-xs"}),e.jsx(Y,{onClick:()=>r(!s),variant:"outline",size:"icon",children:s?e.jsx(is,{className:"w-4 h-4"}):e.jsx(yt,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsxs("p",{children:["Total Requests: ",g.total_requests]}),g.last_request_at&&e.jsxs("p",{className:"text-xs mt-1",children:["Last request: ",new Date(g.last_request_at).toLocaleStr
33ing()]})]}),e.jsxs(Y,{onClick:()=>p.mutate(),variant:"outline",size:"sm",disabled:p.isPending,children:[e.jsx(Et,{className:"w-4 h-4 mr-2"}),p.isPending?"Regenerating...":"Regenerate Token"]})]})]})}),e.jsxs($,{className:"p-4 bg-blue-50 dark:bg-blue-950/30 border-blue-200 dark:border-blue-900",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:["📋 Configuration Instructions for ",g.platform]}),e.jsxs("ol",{className:"text-sm space-y-2 list-decimal list-inside text-muted-foreground",children:[e.jsx("li",{children:"Copy the Webhook URL above"}),e.jsxs("li",{children:["Go to your ",g.platform," dashboard"]}),e.jsx("li",{children:"Navigate to Integrations → Webhooks or Tools → Postback"}),e.jsx("li",{children:"Paste the URL and save"}),e.jsx("li",{children:"Test the webhook to ensure it's working"})]})]})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Create Your Webhook"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure your webhook to receive sales data from platforms like Hotmart, Eduzz, and Monetizze."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Select Platform"}),e.jsxs(re,{value:c,onValueChange:m,children:[e.jsx(ne,{children:e.jsx(le,{placeholder:"Select a platform"})}),e.jsxs(de,{children:[e.jsx(F,{value:"hotmart",children:"Hotmart"}),e.jsx(F,{value:"eduzz",children:"Eduzz"}),e.jsx(F,{value:"monetizze",children:"Monetizze"})]})]})]}),e.jsxs(Y,{onClick:()=>o.mutate(c),disabled:o.isPending,children:[e.jsx(lt,{className:"w-4 h-4 mr-2"}),o.isPending?"Creating...":"Create Webhook"]})]})]})},Ca=()=>{const[t,n]=E.useState(new Set),{data:s,isLoading:r}=Q({queryKey:["webhook-logs"],queryFn:async()=>{const{data:{user:i}}=await k.auth.getUser(),{data:o,error:p}=await k.from("webhook_logs").select("*").eq("user_id",i==null?void 0:i.id).order("created_at",{ascending:!1}).limit(50);if(p)throw p;return o}}),c=i=>new Date(i).toLocaleString("pt-BR"),m=i=>{n(o=>{const p=new Set(o);return p.has(i)?p.delete(i):p.add(i),p})},g=i=>{var o,p;try{const x=i.request_body;return(p=(o=x==null?void 0:x.data)==null?void 0:o.purchase)!=null&&p.status?x.data.purchase.status:x!=null&&x.status?x.status:x!=null&&x.event?x.event.toLowerCase().replace("purchase_",""):"unknown"}catch{return"unknown"}};return r?e.jsx("div",{className:"text-center py-8",children:"Loading logs..."}):!s||s.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx("p",{children:"No webhook logs found"}),e.jsx("p",{className:"text-sm mt-2",children:"Logs will appear here when webhooks are received"})]}):e.jsx("div",{className:"border rounded-lg",children:e.jsxs($e,{children:[e.jsx(ze,{children:e.jsxs(ie,{children:[e.jsx(B,{className:"w-12"}),e.jsx(B,{children:"Date"}),e.jsx(B,{children:"Method"}),e.jsx(B,{children:"Transaction Status"}),e.jsx(B,{children:"Response Status"}),e.jsx(B,{children:"Processed"})]})}),e.jsx(Ye,{children:s.map(i=>e.jsxs(ke.Fragment,{children:[e.jsxs(ie,{children:[e.jsx(z,{children:e.jsx(Y,{variant:"ghost",size:"sm",onClick:()=>m(i.id),className:"p-0 h-auto",children:t.has(i.id)?e.jsx(Pt,{className:"w-4 h-4"}):e.jsx(ds,{className:"w-4 h-4"})})}),e.jsx(z,{className:"text-sm",children:c(i.created_at)}),e.jsx(z,{children:e.jsx(U,{variant:"outline",children:i.request_method})}),e.jsx(z,{children:e.jsx(U,{variant:"secondary",children:g(i)})}),e.jsx(z,{children:e.jsx(U,{variant:i.response_status===200?"default":"destructive",children:i.response_status})}),e.jsx(z,{children:i.was_processed?e.jsx(Lt,{className:"w-5 h-5 text-green-600"}):e.jsx(Se,{className:"w-5 h-5 text-red-600"})})]}),t.has(i.id)&&e.jsx(ie,{children:e.jsx(z,{colSpan:6,className:"bg-muted/50",children:e.jsxs("div",{className:"p-4",children:[e.jsx("h4",{className:"font-semibold mb-2",children:"Request Body:"}),e.jsx("pre",{className:"bg-background p-4 rounded-lg overflow-auto max-h-96 text-xs",children:JSON.stringify(i.request_body,null,2)}),i.processing_error&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"font-semibold mb-2 mt-4",children:"Processing Error:"}),e.jsx("pre",{className:"bg-destructive/10 p-4 rounded-lg text-xs text-destructive",children:i.processing_error})]})]})})})]},i.id))})]})})},Ta=()=>{const t=we(),[n,s]=E.useState("CRM API Token"),[r,c]=E.useState({}),[m,g]=E.useState(null),{data:i,isLoading:o}=Q({queryKey:["api-tokens"],queryFn:async()=>{const{data:{user:d}}=await k.auth.getUser();if(!d)throw new Error("Not authenticated");const{data:f,error:q}=await k.from("api_tokens").select("*").eq("user_id",d.id).order("created_at",{ascending:!1});if(q)throw q;return f}}),p=X({mutationFn:async d=>{const{data:{user:f}}=await k.auth.getUser();if(!f)throw new Error("Not authenticated");const{data:q,error:L}=await k.rpc("generate_api_token");if(L)throw L;const{data:l,error:w}=await k.from("api_tokens").insert({user_id:f.id,token:q,name:d}).select().single();if(w)throw w;return l},onSuccess:d=>{t.invalidateQueries({queryKey:["api-tokens"]}),g(d.token),J.success("API token created successfully!"),s("CRM API Token")},onError:d=>{J.error(`Failed to create token: ${d.message}`)}}),x=X({mutationFn:async d=>{const{error:f}=await k.from("api_tokens").delete().eq("id",d);if(f)throw f},onSuccess:()=>{t.invalidateQueries({queryKey:["api-tokens"]}),J.success("API token deleted")},onError:d=>{J.error(`Failed to delete token: ${d.message}`)}}),a=X({mutationFn:async({tokenId:d,isActive:f})=>{const{error:q}=await k.from("api_tokens").update({is_active:f}).eq("id",d);if(q)throw q},onSuccess:()=>{t.invalidateQueries({queryKey:["api-tokens"]}),J.success("Token status updated")},onError:d=>{J.error(`Failed to update token: ${d.message}`)}}),_=d=>{navigator.clipboard.writeText(d),J.success("Copied to clipboard!")},j=d=>`${d.substring(0,8)}...${d.substring(d.length-8)}
33`,y="https://roksdtmnlqynbzukdqzm.supabase.co/functions/v1/crm-api";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs($,{children:[e.jsxs(se,{children:[e.jsxs(ae,{className:"flex items-center gap-2",children:[e.jsx(_t,{className:"h-5 w-5"}),"API Tokens"]}),e.jsx(ye,{children:"Create API tokens to access your CRM data (tasks & notes) from external applications like Make.com, Zapier, or custom integrations."})]}),e.jsxs(ee,{className:"space-y-6",children:[e.jsxs("div",{className:"flex gap-4 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(T,{htmlFor:"tokenName",children:"Token Name"}),e.jsx(Z,{id:"tokenName",value:n,onChange:d=>s(d.target.value),placeholder:"My Integration Token"})]}),e.jsxs(Y,{onClick:()=>p.mutate(n),disabled:p.isPending||!n.trim(),children:[e.jsx(lt,{className:"h-4 w-4 mr-2"}),"Create Token"]})]}),m&&e.jsx($,{className:"border-green-500 bg-green-50 dark:bg-green-950",children:e.jsxs(ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(_t,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"font-medium text-green-700 dark:text-green-300",children:"New Token Created"})]}),e.jsx("p",{className:"text-sm text-green-600 dark:text-green-400 mb-3",children:"Copy this token now. You won't be able to see it again!"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 p-2 bg-white dark:bg-gray-900 rounded text-sm font-mono break-all",children:m}),e.jsx(Y,{variant:"outline",size:"icon",onClick:()=>_(m),children:e.jsx(ht,{className:"h-4 w-4"})})]}),e.jsx(Y,{variant:"ghost",size:"sm",className:"mt-2",onClick:()=>g(null),children:"Dismiss"})]})}),o?e.jsx("div",{className:"text-center py-4 text-muted-foreground",children:"Loading tokens..."}):i&&i.length>0?e.jsx("div",{className:"space-y-3",children:i.map(d=>e.jsx($,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium truncate",children:d.name}),e.jsx(U,{variant:d.is_active?"default":"secondary",children:d.is_active?"Active":"Inactive"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"text-sm text-muted-foreground font-mono",children:r[d.id]?d.token:j(d.token)}),e.jsx(Y,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>c(f=>({...f,[d.id]:!f[d.id]})),children:r[d.id]?e.jsx(is,{className:"h-3 w-3"}):e.jsx(yt,{className:"h-3 w-3"})}),e.jsx(Y,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>_(d.token),children:e.jsx(ht,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Created: ",R(new Date(d.created_at),"dd/MM/yyyy HH:mm"),d.last_used_at&&e.jsxs(e.Fragment,{children:[" • Last used: ",R(new Date(d.last_used_at),"dd/MM/yyyy HH:mm")]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Y,{variant:"outline",size:"sm",onClick:()=>a.mutate({tokenId:d.id,isActive:!d.is_active}),children:[e.jsx(Et,{className:"h-3 w-3 mr-1"}),d.is_active?"Deactivate":"Activate"]}),e.jsxs(Be,{children:[e.jsx(ps,{asChild:!0,children:e.jsx(Y,{variant:"destructive",size:"sm",children:e.jsx(Le,{className:"h-3 w-3"})})}),e.jsxs(Ve,{children:[e.jsxs(Qe,{children:[e.jsx(He,{children:"Delete API Token"}),e.jsx(Ge,{children:"Are you sure you want to delete this token? Any integrations using this token will stop working."})]}),e.jsxs(Je,{children:[e.jsx(Xe,{children:"Cancel"}),e.jsx(Ze,{onClick:()=>x.mutate(d.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})]})]})]})},d.id))}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(_t,{className:"h-12 w-12 mx-auto mb-3 opacity-50"}),e.jsx("p",{children:"No API tokens created yet"}),e.jsx("p",{className:"text-sm",children:"Create a token to start using the CRM API"})]})]})]}),e.jsxs($,{children:[e.jsxs(se,{children:[e.jsxs(ae,{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"h-5 w-5"}),"API Documentation"]}),e.jsx(ye,{children:"Complete reference for the CRM API"})]}),e.jsxs(ee,{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx(T,{className:"text-sm font-medium",children:"Base URL"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("code",{className:"flex-1 p-2 bg-muted rounded text-sm font-mono break-all",children:y}),e.jsx(Y,{variant:"outline",size:"icon",onClick:()=>_(y),children:e.jsx(ht,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"border rounded-lg p-4 bg-blue-50 dark:bg-blue-950/30",children:[e.jsx("h4",{className:"font-semibold mb-3",children:"🔐 Authentication"}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["All requests must include your API token in the ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"X-API-Token"})," header."]}),e.jsx(T,{className:"text-xs font-medium",children:"Required Header:"}),e.jsx("div",{className:"mt-2 bg-muted rounded p-3 text-xs space-y-2",children:e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"X-API-Token"}),": Your API token"]})}
33),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Example cURL:"}),e.jsxs("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono break-all",children:['curl -H "X-API-Token: YOUR_TOKEN" "',y,'?action=list-tasks"']}),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Example JavaScript (fetch):"}),e.jsx("pre",{className:"mt-1 p-2 bg-muted rounded text-xs font-mono overflow-x-auto",children:`fetch("${y}?action=list-tasks", {
34  headers: {
35    "X-API-Token": "YOUR_TOKEN",
36    "Content-Type": "application/json"
37  }
38})`})]}),e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold mb-3",children:"🔍 search-opportunities"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Search and filter opportunities by multiple criteria"}),e.jsx(T,{className:"text-xs font-medium",children:"Query Parameters:"}),e.jsxs("div",{className:"mt-2 bg-muted rounded p-3 text-xs space-y-2",children:[e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"email"})," - Filter by customer email (partial match)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"name"})," - Filter by customer name (partial match)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"product"})," - Filter by product name (partial match)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"phone"})," - Filter by phone (partial match)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"status"})," - Filter by current_status: ",e.jsx("code",{children:"checkout_abandoned"}),", ",e.jsx("code",{children:"billet_printed"}),", ",e.jsx("code",{children:"pending"}),", ",e.jsx("code",{children:"approved"}),", ",e.jsx("code",{children:"complete"}),", ",e.jsx("code",{children:"canceled"}),", ",e.jsx("code",{children:"expired"}),", ",e.jsx("code",{children:"refunded"}),", ",e.jsx("code",{children:"chargeback"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"stage"})," - Filter by stage: ",e.jsx("code",{children:"cart"}),", ",e.jsx("code",{children:"pending"}),", ",e.jsx("code",{children:"won"}),", ",e.jsx("code",{children:"lost"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"date_from"})," - Start date (YYYY-MM-DD)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"date_to"})," - End date (YYYY-MM-DD)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"date_field"})," - Which date to filter: ",e.jsx("code",{children:"last_activity_date"})," (default), ",e.jsx("code",{children:"created_at"}),", ",e.jsx("code",{children:"first_contact_date"}),", ",e.jsx("code",{children:"closed_date"})]})]}),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Examples:"}),e.jsxs("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono break-all",children:['curl -H "X-API-Token: YOUR_TOKEN" "',y,'?action=search-opportunities&status=approved"']}),e.jsxs("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono break-all",children:['curl -H "X-API-Token: YOUR_TOKEN" "',y,'?action=search-opportunities&stage=won&date_from=2024-01-01"']})]}),e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold mb-3",children:"📋 get-opportunity"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Get opportunity details by ID"}),e.jsx(T,{className:"text-xs font-medium",children:"Query Parameters:"}),e.jsxs("div",{className:"mt-2 bg-muted rounded p-3 text-xs space-y-2",children:[e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"id"})," - Opportunity ID (required)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"include_tasks"})," - Set to ",e.jsx("code",{children:"true"})," to include tasks"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"include_notes"})," - Set to ",e.jsx("code",{children:"true"})," to include notes"]})]}
38),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Example:"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono break-all",children:"?action=get-opportunity&id=UUID&include_tasks=true&include_notes=true"})]}),e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold mb-3",children:"📦 get-opportunity-full"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Get complete opportunity with all related data"}),e.jsx(T,{className:"text-xs font-medium",children:"Query Parameters:"}),e.jsx("div",{className:"mt-2 bg-muted rounded p-3 text-xs space-y-2",children:e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"id"})," - Opportunity ID (required)"]})}),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Returns:"}),e.jsx("div",{className:"mt-1 bg-muted rounded p-3 text-xs",children:"opportunity, tasks[], notes[], sales[], summary (counts)"})]}),e.jsxs("div",{className:"border rounded-lg p-4 bg-green-50 dark:bg-green-950/30",children:[e.jsxs("h4",{className:"font-semibold mb-3",children:["✅ check-opportunity-status ",e.jsx(U,{variant:"secondary",className:"ml-2",children:"Make.com Friendly"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Get boolean flags for easy automation filtering. Returns true/false values instead of arrays."}),e.jsx(T,{className:"text-xs font-medium",children:"Query Parameters:"}),e.jsx("div",{className:"mt-2 bg-muted rounded p-3 text-xs space-y-2",children:e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"id"})," - Opportunity ID (required)"]})}),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Returns:"}),e.jsxs("div",{className:"mt-1 bg-muted rounded p-3 text-xs space-y-1",children:[e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"has_tasks"})," - true/false if opportunity has any tasks"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"has_pending_tasks"})," - true/false if has pending/in_progress tasks"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"has_overdue_tasks"})," - true/false if has overdue tasks"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"has_notes"})," - true/false if has any notes"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"has_sales"})," - true/false if has any sales"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"counts"})," - object with total_tasks, pending_tasks, completed_tasks, overdue_tasks, total_notes, total_sales"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"customer_email, customer_name, customer_phone"})," - contact info for messaging"]})]}),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Example:"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono break-all",children:"?action=check-opportunity-status&id=OPPORTUNITY_UUID"}),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Example Response:"}),e.jsx("pre",{className:"mt-1 p-2 bg-muted rounded text-xs font-mono overflow-x-auto",children:`{
39  "success": true,
40  "data": {
41    "opportunity_id": "uuid",
42    "customer_email": "[email protected]",
43    "customer_name": "John Doe",
44    "customer_phone": "+5511999999999",
45    "has_tasks": true,
46    "has_pending_tasks": false,
47    "has_overdue_tasks": false,
48    "has_notes": true,
49    "has_sales": false,
50    "counts": { "total_tasks": 2, ... }
51  }
52}`})]}),e.jsxs("div",{className:"border rounded-lg p-4 bg-green-50 dark:bg-green-950/30",children:[e.jsxs("h4",{className:"font-semibold mb-3",children:["📊 list-opportunities-status ",e.jsx(U,{variant:"secondary",className:"ml-2",children:"Make.com Friendly"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"List opportunities with boolean status flags. Filter by has_tasks or has_pending_tasks for automation."}),e.jsx(T,{className:"text-xs font-medium",children:"Query Parameters:"}),e.jsxs("div",{className:"mt-2 bg-muted rounded p-3 text-xs space-y-2",children:[e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"stage"})," - Filter by stage: cart, pending, won, lost. Use comma for multiple: ",e.jsx("code",{children:"stage=pending,cart"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"has_tasks"})," - Filter: ",e.jsx("code",{children:"true"})," = only with tasks, ",e.jsx("code",{children:"false"})," = only without tasks"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"has_pending_tasks"})," - Filter: ",e.jsx("code",{children:"true"})," = only with pending tasks, ",e.jsx("code",{children:"false"})," = only without"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"limit"})," - Max results (default: 100)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"date_from"})," - Start date (YYYY-MM-DD)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"date_to"})," - End date (YYYY-MM-DD)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"date_field"})," - Which date to filter: ",e.jsx("code",{children:"last_activity_date"})," (default), ",e.jsx("code",{children:"created_at"}),", ",e.jsx("code",{children:"first_contact_date"}),", ",e.jsx("code",{children:"closed_date"})]})]}
52),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Examples:"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono break-all",children:"?action=list-opportunities-status&has_tasks=false"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"↑ Get all opportunities WITHOUT tasks (for automation to create tasks)"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono break-all",children:"?action=list-opportunities-status&stage=pending&has_pending_tasks=true"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"↑ Get pending opportunities with pending tasks (for follow-up automation)"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono break-all",children:"?action=list-opportunities-status&stage=pending,cart"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"↑ Get opportunities in multiple stages at once"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono break-all",children:"?action=list-opportunities-status&date_from=2025-01-01&date_to=2025-01-31&date_field=last_activity_date"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"↑ Filter by date range using last activity date"}),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Returns for each opportunity:"}),e.jsxs("div",{className:"mt-1 bg-muted rounded p-3 text-xs space-y-1",children:[e.jsx("div",{children:e.jsx("code",{className:"font-semibold",children:"opportunity_id, customer_email, customer_name, customer_phone"})}),e.jsx("div",{children:e.jsx("code",{className:"font-semibold",children:"stage, current_status, product_name"})}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"has_tasks, has_pending_tasks, has_overdue_tasks"})," - boolean flags"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"task_count, pending_task_count, overdue_task_count"})," - numeric counts"]})]})]}),e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold mb-3",children:"📝 list-tasks"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"List all tasks with optional filters"}),e.jsx(T,{className:"text-xs font-medium",children:"Query Parameters:"}),e.jsxs("div",{className:"mt-2 bg-muted rounded p-3 text-xs space-y-2",children:[e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"opportunity_id"})," - Filter by opportunity UUID (optional)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"status"})," - Filter by status: ",e.jsx("code",{children:"pending"}),", ",e.jsx("code",{children:"in_progress"}),", ",e.jsx("code",{children:"completed"}),", ",e.jsx("code",{children:"cancelled"}),". Use comma for multiple: ",e.jsx("code",{children:"status=pending,in_progress"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"priority"})," - Filter by priority: ",e.jsx("code",{children:"low"}),", ",e.jsx("code",{children:"medium"}),", ",e.jsx("code",{children:"high"}),", ",e.jsx("code",{children:"urgent"}),". Use comma for multiple: ",e.jsx("code",{children:"priority=high,urgent"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"task_type"})," - Filter by task type. Use comma for multiple: ",e.jsx("code",{children:"task_type=call,email"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"search"})," - Search in task title (partial match)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"date_from"})," - Start date filter (YYYY-MM-DD)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"date_to"})," - End date filter (YYYY-MM-DD)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"date_field"})," - Which date to filter: ",e.jsx("code",{children:"due_date"})," (default), ",e.jsx("code",{children:"created_at"})]})]}),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Examples:"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono break-all",children:"?action=list-tasks&status=pending,in_progress&priority=high,urgent"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono break-all",children:"?action=list-tasks&task_type=call,email&date_from=2024-12-01"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono break-all",children:"?action=list-tasks&opportunity_id=UUID&search=follow"})]}),e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold mb-3",children:"📋 get-task"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Get a single task by ID"}),e.jsx(T,{className:"text-xs font-medium",children:"Query Parameters:"}),e.jsx("div",{className:"mt-2 bg-muted rounded p-3 text-xs",children:e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"id"})," - Task ID (required)"]})}
52),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Example:"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono",children:"?action=get-task&id=TASK_UUID"})]}),e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold mb-3",children:"➕ create-task (POST)"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Create a new task for an opportunity"}),e.jsx(T,{className:"text-xs font-medium",children:"Body Parameters (JSON):"}),e.jsxs("div",{className:"mt-2 bg-muted rounded p-3 text-xs space-y-2",children:[e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold text-red-600",children:"opportunity_id"})," - Opportunity UUID (required)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold text-red-600",children:"title"})," - Task title (required)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"description"})," - Task description (optional)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"due_date"})," - Due date in ISO format, e.g. ",e.jsx("code",{children:"2024-12-20T10:00:00Z"})," (optional)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"priority"})," - ",e.jsx("code",{children:"low"}),", ",e.jsx("code",{children:"medium"})," (default), ",e.jsx("code",{children:"high"}),", ",e.jsx("code",{children:"urgent"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"status"})," - ",e.jsx("code",{children:"pending"})," (default), ",e.jsx("code",{children:"in_progress"}),", ",e.jsx("code",{children:"completed"}),", ",e.jsx("code",{children:"cancelled"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"task_type"})," - Task type, e.g. ",e.jsx("code",{children:"call"}),", ",e.jsx("code",{children:"email"}),", ",e.jsx("code",{children:"meeting"}),", etc. (optional)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"assignee"})," - Assignee name (optional)"]})]}),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Example:"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono whitespace-pre",children:`POST ?action=create-task
53{
54  "opportunity_id": "uuid-here",
55  "title": "Follow up call",
56  "description": "Call customer about order",
57  "due_date": "2024-12-20T10:00:00Z",
58  "priority": "high",
59  "status": "pending",
60  "task_type": "call",
61  "assignee": "John"
62}`})]}),e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold mb-3",children:"✏️ update-task (POST/PUT)"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Update an existing task"}),e.jsx(T,{className:"text-xs font-medium",children:"Parameters:"}),e.jsxs("div",{className:"mt-2 bg-muted rounded p-3 text-xs space-y-2",children:[e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold text-red-600",children:"id"})," - Task ID (query param or body, required)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"title"})," - New title (optional)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"description"})," - New description (optional)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"due_date"})," - New due date in ISO format (optional)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"priority"})," - ",e.jsx("code",{children:"low"}),", ",e.jsx("code",{children:"medium"}),", ",e.jsx("code",{children:"high"}),", ",e.jsx("code",{children:"urgent"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"status"})," - ",e.jsx("code",{children:"pending"}),", ",e.jsx("code",{children:"in_progress"}),", ",e.jsx("code",{children:"completed"}),", ",e.jsx("code",{children:"cancelled"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"task_type"})," - Task type, e.g. ",e.jsx("code",{children:"call"}),", ",e.jsx("code",{children:"email"}),", ",e.jsx("code",{children:"meeting"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"assignee"})," - Assignee name (optional)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"completed_at"})," - Completion timestamp in ISO format (optional)"]})]}
62),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Examples:"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono whitespace-pre",children:`POST ?action=update-task&id=TASK_UUID
63{
64  "status": "completed",
65  "completed_at": "2024-12-18T15:30:00Z"
66}`}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono whitespace-pre",children:`POST ?action=update-task
67{
68  "id": "TASK_UUID",
69  "priority": "urgent",
70  "task_type": "call",
71  "due_date": "2024-12-19T09:00:00Z"
72}`})]}),e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold mb-3",children:"🗑️ delete-task"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Delete a task"}),e.jsx(T,{className:"text-xs font-medium",children:"Parameters:"}),e.jsx("div",{className:"mt-2 bg-muted rounded p-3 text-xs",children:e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold text-red-600",children:"id"})," - Task ID (query param or body, required)"]})}),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Examples:"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono",children:"GET/DELETE ?action=delete-task&id=TASK_UUID"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono whitespace-pre",children:`POST ?action=delete-task
73{ "id": "TASK_UUID" }`})]}),e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold mb-3",children:"💬 list-notes"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"List all notes with optional filters"}),e.jsx(T,{className:"text-xs font-medium",children:"Query Parameters:"}),e.jsxs("div",{className:"mt-2 bg-muted rounded p-3 text-xs space-y-2",children:[e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"opportunity_id"})," - Filter by opportunity UUID (optional)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"note_type"})," - Filter by type: ",e.jsx("code",{children:"note"}),", ",e.jsx("code",{children:"call"}),", ",e.jsx("code",{children:"email"}),", ",e.jsx("code",{children:"meeting"}),", ",e.jsx("code",{children:"other"}),". Use comma for multiple: ",e.jsx("code",{children:"note_type=call,email"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"is_pinned"})," - Filter pinned notes: ",e.jsx("code",{children:"true"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"search"})," - Search in note content (partial match)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"date_from"})," - Start date filter (YYYY-MM-DD)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"date_to"})," - End date filter (YYYY-MM-DD)"]})]}),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Examples:"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono break-all",children:"?action=list-notes&note_type=call,email&is_pinned=true"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono break-all",children:"?action=list-notes&opportunity_id=UUID&date_from=2024-12-01"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono break-all",children:"?action=list-notes&search=premium"})]}),e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold mb-3",children:"📄 get-note"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Get a single note by ID"}),e.jsx(T,{className:"text-xs font-medium",children:"Query Parameters:"}),e.jsx("div",{className:"mt-2 bg-muted rounded p-3 text-xs",children:e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"id"})," - Note ID (required)"]})}),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Example:"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono",children:"?action=get-note&id=NOTE_UUID"})]}),e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold mb-3",children:"➕ create-note (POST)"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Create a new note for an opportunity"}),e.jsx(T,{className:"text-xs font-medium",children:"Body Parameters (JSON):"}),e.jsxs("div",{className:"mt-2 bg-muted rounded p-3 text-xs space-y-2",children:[e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold text-red-600",children:"opportunity_id"})," - Opportunity UUID (required)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold text-red-600",children:"content"})," - Note content/text (required)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"note_type"})," - ",e.jsx("code",{children:"note"})," (default), ",e.jsx("code",{children:"call"}),", ",e.jsx("code",{children:"email"}),", ",e.jsx("code",{children:"meeting"}),", ",e.jsx("code",{children:"other"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"is_pinned"})," - Pin the note: ",e.jsx("code",{children:"true"})," or ",e.jsx("code",{children:"false"})," (default)"]})]}
73),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Example:"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono whitespace-pre",children:`POST ?action=create-note
74{
75  "opportunity_id": "uuid-here",
76  "content": "Customer interested in premium plan. Schedule demo for next week.",
77  "note_type": "call",
78  "is_pinned": true
79}`})]}),e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold mb-3",children:"✏️ update-note (POST/PUT)"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Update an existing note"}),e.jsx(T,{className:"text-xs font-medium",children:"Parameters:"}),e.jsxs("div",{className:"mt-2 bg-muted rounded p-3 text-xs space-y-2",children:[e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold text-red-600",children:"id"})," - Note ID (query param or body, required)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"content"})," - New content/text (optional)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"note_type"})," - ",e.jsx("code",{children:"note"}),", ",e.jsx("code",{children:"call"}),", ",e.jsx("code",{children:"email"}),", ",e.jsx("code",{children:"meeting"}),", ",e.jsx("code",{children:"other"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"is_pinned"})," - Pin/unpin: ",e.jsx("code",{children:"true"})," or ",e.jsx("code",{children:"false"})]})]}),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Examples:"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono whitespace-pre",children:`POST ?action=update-note&id=NOTE_UUID
80{
81  "is_pinned": false,
82  "note_type": "meeting"
83}`}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono whitespace-pre",children:`POST ?action=update-note
84{
85  "id": "NOTE_UUID",
86  "content": "Updated note content with new info"
87}`})]}),e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold mb-3",children:"🗑️ delete-note"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Delete a note"}),e.jsx(T,{className:"text-xs font-medium",children:"Parameters:"}),e.jsx("div",{className:"mt-2 bg-muted rounded p-3 text-xs",children:e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold text-red-600",children:"id"})," - Note ID (query param or body, required)"]})}),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Examples:"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono",children:"GET/DELETE ?action=delete-note&id=NOTE_UUID"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono whitespace-pre",children:`POST ?action=delete-note
88{ "id": "NOTE_UUID" }`})]}),e.jsx("div",{className:"pt-4 border-t",children:e.jsx("h3",{className:"text-lg font-bold mb-3",children:"👤 Leads Endpoints"})}),e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold mb-3",children:"📋 list-leads"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"List leads owned by the user (via forms or lead events)."}),e.jsx(T,{className:"text-xs font-medium",children:"Optional Filters:"}),e.jsxs("div",{className:"mt-2 bg-muted rounded p-3 text-xs space-y-2",children:[e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"search"})," - Search in email, name, or phone"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"email"})," / ",e.jsx("code",{className:"font-semibold",children:"phone"})," - Partial match"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"lead_temperature"})," - ",e.jsx("code",{children:"cold"}),", ",e.jsx("code",{children:"warm"}),", ",e.jsx("code",{children:"hot"}),", ",e.jsx("code",{children:"super_hot"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"lead_source"})," - e.g. ",e.jsx("code",{children:"form"}),", ",e.jsx("code",{children:"api"}),", ",e.jsx("code",{children:"whatsapp_private"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"lead_journey_type"})," - ",e.jsx("code",{children:"group_funnel"})," or ",e.jsx("code",{children:"private_conversation"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"form_id"})," / ",e.jsx("code",{className:"font-semibold",children:"campaign_id"})," - Filter by source"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"date_from"})," / ",e.jsx("code",{className:"font-semibold",children:"date_to"})," - YYYY-MM-DD (created_at)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"limit"})," - Default: 100"]})]}
88),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Example:"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono break-all",children:"GET ?action=list-leads&lead_temperature=hot&limit=50"})]}),e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold mb-3",children:"🔍 get-lead"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Get a single lead by ID."}),e.jsx(T,{className:"text-xs font-medium",children:"Parameters:"}),e.jsx("div",{className:"mt-2 bg-muted rounded p-3 text-xs",children:e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold text-red-600",children:"id"})," - Lead UUID (required)"]})}),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Example:"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono break-all",children:"GET ?action=get-lead&id=LEAD_UUID"})]}),e.jsxs("div",{className:"border rounded-lg p-4 bg-blue-50 dark:bg-blue-950/30",children:[e.jsxs("h4",{className:"font-semibold mb-3",children:["➕ create-lead (POST) ",e.jsx(U,{variant:"secondary",className:"ml-2",children:"New"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["Create a new lead in the Leads table. A ",e.jsx("code",{children:"lead_created"})," event is automatically logged for ownership."]}),e.jsx(T,{className:"text-xs font-medium",children:"Body Parameters:"}),e.jsxs("div",{className:"mt-2 bg-muted rounded p-3 text-xs space-y-2",children:[e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold text-red-600",children:"email"})," - Lead email (required, unless phone is provided — auto-generated then)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"name"})," - Full name"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"phone"})," / ",e.jsx("code",{className:"font-semibold",children:"whatsapp_phone"})," - Phone numbers"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"lead_source"})," - Default: ",e.jsx("code",{children:"api"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"lead_journey_type"})," - ",e.jsx("code",{children:"group_funnel"})," or ",e.jsx("code",{children:"private_conversation"})," (default)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"lead_temperature"})," - ",e.jsx("code",{children:"cold"})," (default), ",e.jsx("code",{children:"warm"}),", ",e.jsx("code",{children:"hot"}),", ",e.jsx("code",{children:"super_hot"})]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"lead_score"})," - Initial score (number, default 0)"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"form_id"})," - Optional, must belong to the user"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"campaign_id"})," - Optional, must belong to the user"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"tags"})," - Array of strings"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"additional_data"})," - JSON object with custom fields"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"utm_data"})," - JSON object with UTM parameters"]}),e.jsxs("div",{children:[e.jsx("code",{className:"font-semibold",children:"is_registered"})," - Boolean (default ",e.jsx("code",{children:"true"}),")"]})]}),e.jsx(T,{className:"text-xs font-medium mt-3 block",children:"Example:"}),e.jsx("code",{className:"block mt-1 p-2 bg-muted rounded text-xs font-mono whitespace-pre",children:`POST ?action=create-lead
89{
90  "email": "[email protected]",
91  "name": "John Doe",
92  "phone": "5511999999999",
93  "lead_source": "api",
94  "lead_temperature": "warm",
95  "tags": ["imported", "vip"],
96  "additional_data": { "company": "Acme Inc" },
97  "utm_data": { "utm_source": "zapier" }
98}`})]})]})]})]})},Ma=()=>{const{toast:t}=mt(),n=we(),[s,r]=E.useState(""),[c,m]=E.useState(""),[g,i]=E.useState(""),{data:o=[],isLoading:p}=Q({queryKey:["outbound-webhook-endpoints"],queryFn:async()=>{const{data:d,error:f}=await k.from("outbound_webhook_endpoints").select("*").order("created_at",{ascending:!1});if(f)throw f;return d||[]}}),{data:x=[]}=Q({queryKey:["outbound-webhook-deliveries"],queryFn:async()=>{const{data:d,error:f}=await k.from("outbound_webhook_deliveries").select("*").order("attempted_at",{ascending:!1}).limit(20);if(f)throw f;return d||[]}}),a=X({mutationFn:async()=>{const{data:{user:d}}=await k.auth.getUser();if(!d)throw new Error("Not authenticated");if(!c.trim()||!s.trim())throw new Error("Name and URL required");const{error:f}=await k.from("outbound_webhook_endpoints").insert({user_id:d.id,name:s.trim(),target_url:c.trim(),secret:g.trim()||null,events:["lead_score.opportunity_created"],is_active:!0});if(f)throw f},onSuccess:()=>{r(""),m(""),i(""),n.invalidateQueries({queryKey:["outbound-webhook-endpoints"]}),t({title:"Webhook created"})},onError:d=>t({title:"Error",description:d.message,variant:"destructive"})}),_=X({mutationFn:async({id:d,is_active:f})=>{const{error:q}=await k.from("outbound_webhook_endpoints").update({is_active:f}).eq("id",d);if(q)throw q},onSuccess:()=>n.invalidateQueries({queryKey:["outbound-webhook-endpoints"]})}),j=X({mutationFn:async d=>{const{error:f}=await k.from("outbound_webhook_endpoints").delete().eq("id",d);if(f)throw f},onSuccess:()=>{n.invalidateQueries({queryKey:["outbound-webhook-endpoints"]}),t({title:"Webhook removed"})}}),y=X({mutationFn:async d=>{const{error:f}=await k.functions.invoke("dispatch-lead-opportunity-webhook",{body:{endpoint_id:d.id,user_id:d.user_id,event:"lead_score.opportunity_created",test:!0}});if(f)throw f},onSuccess:()=>{n.invalidateQueries({queryKey:["outbound-webhook-deliveries"]}),n.invalidateQueries({queryKey:["outbound-webhook-endpoints"]}),t({title:"Test payload sent"})},onError:d=>t({title:"Error",description:d.message,variant:"destructive"})});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs($,{className:"p-6 rounded-2xl border border-border/50 shadow-sm",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"Outbound Webhooks"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Send lead data, timeline and lead-score details to an external CRM whenever a lead becomes an opportunity via lead score."}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx(T,{children:"Name"}),e.jsx(Z,{value:s,onChange:d=>r(d.target.value),placeholder:"My CRM"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(T,{children:"Target URL"}),e.jsx(Z,{value:c,onChange:d=>m(d.target.value),placeholder:"https://..."})]}),e.jsxs("div",{className:"md:col-span-3",children:[e.jsx(T,{children:"Secret (optional, used for HMAC SHA-256 signature)"}),e.jsx(Z,{value:g,onChange:d=>i(d.target.value),placeholder:"shared secret"})]})]}),e.jsxs(Y,{className:"mt-4",onClick:()=>a.mutate(),disabled:a.isPending,children:[e.jsx(lt,{className:"h-4 w-4 mr-2"})," Add webhook"]})]}),e.jsxs($,{className:"p-6 rounded-2xl border border-border/50 shadow-sm",children:[e.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Configured endpoints"}),p?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):o.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No endpoints yet."}):e.jsx("div",{className:"space-y-3",children:o.map(d=>e.jsxs("div",{className:"flex items-center gap-3 p-3 border border-border/50 rounded-xl",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:d.name}),d.last_delivery_status&&e.jsx(U,{variant:d.last_delivery_status<300?"default":"destructive",children:d.last_delivery_status})]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:d.target_url}),d.last_delivery_at&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Last: ",new Date(d.last_delivery_at).toLocaleStr
98ing()]})]}),e.jsx(gs,{checked:d.is_active,onCheckedChange:f=>_.mutate({id:d.id,is_active:f})}),e.jsxs(Y,{size:"sm",variant:"outline",onClick:()=>y.mutate(d),disabled:y.isPending,children:[e.jsx(Es,{className:"h-4 w-4 mr-1"})," Test"]}),e.jsx(Y,{size:"sm",variant:"ghost",onClick:()=>j.mutate(d.id),children:e.jsx(Le,{className:"h-4 w-4"})})]},d.id))})]}),e.jsxs($,{className:"p-6 rounded-2xl border border-border/50 shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Recent deliveries"}),e.jsx(Y,{size:"sm",variant:"ghost",onClick:()=>n.invalidateQueries({queryKey:["outbound-webhook-deliveries"]}),children:e.jsx(Et,{className:"h-4 w-4"})})]}),x.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No deliveries yet."}):e.jsx("div",{className:"space-y-2",children:x.map(d=>e.jsxs("div",{className:"flex items-center gap-3 p-2 text-sm border border-border/50 rounded-lg",children:[e.jsx(U,{variant:d.response_status&&d.response_status<300?"default":"destructive",children:d.response_status??"ERR"}),e.jsx("span",{className:"text-muted-foreground",children:d.event_type}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:new Date(d.attempted_at).toLocaleString()}),d.error&&e.jsx("span",{className:"text-xs text-destructive truncate max-w-[200px]",children:d.error})]},d.id))})]})]})},qa=()=>{const[t,n]=E.useState("webhooks");return e.jsx($,{className:"p-6",children:e.jsxs(ts,{value:t,onValueChange:n,children:[e.jsxs(ss,{className:"grid w-full grid-cols-4 max-w-2xl",children:[e.jsx(xe,{value:"webhooks",children:"Webhooks"}),e.jsx(xe,{value:"logs",children:"Logs"}),e.jsx(xe,{value:"api",children:"API Tokens"}),e.jsx(xe,{value:"outbound",children:"Outbound"})]}),e.jsx(he,{value:"webhooks",className:"mt-6",children:e.jsx(Sa,{})}),e.jsx(he,{value:"logs",className:"mt-6",children:e.jsx(Ca,{})}),e.jsx(he,{value:"api",className:"mt-6",children:e.jsx(Ta,{})}),e.jsx(he,{value:"outbound",className:"mt-6",children:e.jsx(Ma,{})})]})})};function Fa({dateRange:t,getDateRange:n}){var o;const{user:s}=ge(),{formatValue:r}=ce(),{startDate:c,endDate:m}=n(t),{data:g,isLoading:i}=Q({queryKey:["subscription-stats",s==null?void 0:s.id,t,R(new Date,"yyyy-MM-dd")],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{count:p}=await k.from("subscriptions").select("*",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","active"),{count:x}=await k.from("subscriptions").select("*",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","delayed"),{data:a}=await k.from("subscriptions").select("mrr").eq("user_id",s.id).eq("status","active"),_=(a==null?void 0:a.reduce((w,M)=>w+(Number(M.mrr)||0),0))||0,{count:j}=await k.from("subscriptions").select("*",{count:"exact",head:!0}).eq("user_id",s.id).gte("started_at",c).lte("started_at",m),{count:y}=await k.from("subscriptions").select("*",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","canceled").eq("cancellation_type","payment_failed").gte("canceled_at",c).lte("canceled_at",m),{count:d}=await k.from("subscriptions").select("*",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","canceled").eq("cancellation_type","user_canceled").gte("canceled_at",c).lte("canceled_at",m),{count:f}=await k.from("subscriptions").select("*",{count:"exact",head:!0}).eq("user_id",s.id).not("canceled_at","is",null).gte("canceled_at",c).lte("canceled_at",m),q=new Date(c),{count:L}=await k.from("subscriptions").select("*",{count:"exact",head:!0}).eq("user_id",s.id).lte("started_at",q.toISOString()).or(`canceled_at.is.null,canceled_at.gt.${q.toISOString()}`),l=L&&L>0?(d||0)/L*100:0;return{activeCount:p||0,delayedCount:x||0,totalMRR:_,newCount:j||0,paymentFailedCount:y||0,userCanceledCount:d||0,totalCanceledCount:f||0,churnRate:l}},enabled:!!(s!=null&&s.id),staleTime:3e4});return i?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-5",children:[1,2,3,4,5].map(p=>e.jsx(H,{className:"h-[120px]"},p))}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-5",children:[e.jsx(_e,{label:"Active Subscribers",value:String((g==null?void 0:g.activeCount)||0),subtext:`+${(g==null?void 0:g.newCount)||0} new in period`,icon:qt,color:"text-green-500"}),e.jsx(_e,{label:"Current MRR",value:r((g==null?void 0:g.totalMRR)||0),subtext:"Monthly recurring revenue",icon:As,color:"text-blue-500"}),e.jsx(_e,{label:"Delayed",value:String((g==null?void 0:g.delayedCount)||0),subtext:"Pending payments",icon:De,color:"text-amber-500"}),e.jsx(_e,{label:"Payment Failed",value:String((g==null?void 0:g.paymentFailedCount)||0),subtext:"Recoverable (card declined)",icon:rt,color:"text-orange-500"}),e.jsx(_e,{label:"Churn Rate",value:`${((o=g==null?void 0:g.churnRate)==null?void 0:o.toFixed(1))||0}%`,subtext:`${(g==null?void 0:g.userCanceledCount)||0} user cancellations`,icon:Mt,color:"text-red-500"})]})}function es(t){const[n,s,r]=t.split("-").map(Number);return new Date(n,s-1,r)}function Pa({dateRange:t,getDateRange:n}){const{user:s}=ge(),{startDate:r,endDate:c}=n(t),{data:m,isLoading:g}=Q({queryKey:["subscribers-chart",s==null?void 0:s.id,t,R(new Date,"yyyy-MM-dd")],queryFn:async()=>
98{if(!(s!=null&&s.id))return[];const{data:i}=await k.from("subscriptions").select("started_at").eq("user_id",s.id).gte("started_at",r).lte("started_at",c),{data:o}=await k.from("subscriptions").select("canceled_at, cancellation_type").eq("user_id",s.id).eq("status","canceled").not("canceled_at","is",null).gte("canceled_at",r).lte("canceled_at",c),p=new Date(r),x=new Date(c),_=Math.ceil((x.getTime()-p.getTime())/(1e3*60*60*24))>90,j=_?ws({start:p,end:x}):Vs({start:p,end:x}),y=new Map;return j.forEach(d=>{const f=_?R(d,"yyyy-MM"):R(d,"yyyy-MM-dd");y.set(f,{new:0,paymentFailed:0,churned:0})}),i==null||i.forEach(d=>{const f=new Date(d.started_at),q=_?R(f,"yyyy-MM"):R(f,"yyyy-MM-dd"),L=y.get(q);L&&L.new++}),o==null||o.forEach(d=>{if(d.canceled_at){const f=new Date(d.canceled_at),q=_?R(f,"yyyy-MM"):R(f,"yyyy-MM-dd"),L=y.get(q);L&&(d.cancellation_type==="payment_failed"?L.paymentFailed++:L.churned++)}}),Array.from(y.entries()).map(([d,f])=>({date:d,new:f.new,paymentFailed:f.paymentFailed,churned:f.churned}))},enabled:!!(s!=null&&s.id),staleTime:3e4});return g?e.jsxs($,{children:[e.jsx(se,{children:e.jsx(ae,{children:"Subscriber Movement"})}),e.jsx(ee,{children:e.jsx(H,{className:"h-[300px]"})})]}):e.jsxs($,{children:[e.jsxs(se,{children:[e.jsx(ae,{children:"Subscriber Movement"}),e.jsx(ye,{children:"New, Payment Failed (recoverable), and Churned (user canceled)"})]}),e.jsx(ee,{children:e.jsx(Ce,{width:"100%",height:300,children:e.jsxs(bt,{data:m,children:[e.jsx(Te,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Me,{dataKey:"date",tick:{fontSize:12},tickFormatter:i=>{const o=es(i.length>7?i:`${i}-01`);return R(o,i.length>7?"dd/MM":"MMM")}}),e.jsx(qe,{tick:{fontSize:12}}),e.jsx(Fe,{labelFormatter:i=>{const o=es(String(i).length>7?String(i):`${i}-01`);return R(o,String(i).length>7?"dd/MM/yyyy":"MMMM yyyy")}}),e.jsx(Ke,{}),e.jsx(fe,{type:"monotone",dataKey:"new",name:"New",stroke:"hsl(142 76% 36%)",strokeWidth:2,dot:!1}),e.jsx(fe,{type:"monotone",dataKey:"paymentFailed",name:"Payment Failed",stroke:"hsl(45 93% 47%)",strokeWidth:2,dot:!1}),e.jsx(fe,{type:"monotone",dataKey:"churned",name:"Churned",stroke:"hsl(var(--destructive))",strokeWidth:2,dot:!1})]})})})]})}function Oa({dateRange:t,getDateRange:n}){const{user:s}=ge(),{formatValue:r,convertValue:c}=ce(),{startDate:m,endDate:g}=n(t),{data:i,isLoading:o}=Q({queryKey:["mrr-chart",s==null?void 0:s.id,t,R(new Date,"yyyy-MM-dd")],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:p}=await k.from("sales").select("approved_date, net_value, subscriber_code, currency").eq("user_id",s.id).eq("is_subscription",!0).eq("status","approved").gte("approved_date",m).lte("approved_date",g).order("approved_date",{ascending:!0});if(!p||p.length===0)return[];const x=new Date(m),a=new Date(g),_=ws({start:x,end:a}),j=new Map;return _.forEach(y=>{const d=R(y,"yyyy-MM");j.set(d,{mrr:0,subscribers:new Set})}),p.forEach(y=>{if(y.approved_date){const d=new Date(y.approved_date),f=R(d,"yyyy-MM"),q=j.get(f);q&&(q.mrr+=c(Number(y.net_value)||0,y.currency),y.subscriber_code&&q.subscribers.add(y.subscriber_code))}}),Array.from(j.entries()).map(([y,d])=>({date:y,mrr:d.mrr,subscribers:d.subscribers.size}))},enabled:!!(s!=null&&s.id),staleTime:3e4});return o?e.jsxs($,{children:[e.jsx(se,{children:e.jsx(ae,{children:"MRR Over Time"})}),e.jsx(ee,{children:e.jsx(H,{className:"h-[300px]"})})]}):!i||i.length===0?e.jsxs($,{children:[e.jsxs(se,{children:[e.jsx(ae,{children:"MRR Over Time"}),e.jsx(ye,{children:"Monthly recurring revenue"})]}),e.jsx(ee,{children:e.jsx("div",{className:"h-[300px] flex items-center justify-center text-muted-foreground",children:"No subscription data found for selected period"})})]}):e.jsxs($,{children:[e.jsxs(se,{children:[e.jsx(ae,{children:"MRR Over Time"}),e.jsx(ye,{children:"Monthly recurring revenue"})]}),e.jsx(ee,{children:e.jsx(Ce,{width:"100%",height:300,children:e.jsxs(Zs,{data:i,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorMrr",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"hsl(142 76% 36%)",stopOpacity:.8}),e.jsx("stop",{offset:"95%",stopColor:"hsl(142 76% 36%)",stopOpacity:0})]})}),e.jsx(Te,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Me,{dataKey:"date",tick:{fontSize:12},tickFormatter:p=>{const[x,a]=p.split("-");return R(new Date(Number(x),Number(a)-1,1),"MMM")}}),e.jsx(qe,{tick:{fontSize:12},tickFormatter:p=>r(p,null,{compact:!0})}),e.jsx(Fe,{labelFormatter:p=>{const[x,a]=String(p).split("-");return R(new Date(Number(x),Number(a)-1,1),"MMMM yyyy")},formatter:(p,x)=>[x==="mrr"?r(p):p,x==="mrr"?"MRR":"Subscribers"]}
98),e.jsx(ea,{type:"monotone",dataKey:"mrr",stroke:"hsl(142 76% 36%)",fillOpacity:1,fill:"url(#colorMrr)"})]})})})]})}function La({dateRange:t,getDateRange:n}){const{user:s}=ge(),r=Ts(),{formatValue:c}=ce(),[m,g]=E.useState("all"),[i,o]=E.useState(""),{data:p,isLoading:x}=Q({queryKey:["subscribers-table",s==null?void 0:s.id,m,R(new Date,"yyyy-MM-dd")],queryFn:async()=>{if(!(s!=null&&s.id))return[];let j=k.from("subscriptions").select("*").eq("user_id",s.id).order("updated_at",{ascending:!1}).limit(200);m!=="all"&&(m==="payment_failed"||m==="user_canceled"||m==="admin_canceled"?j=j.eq("status","canceled").eq("cancellation_type",m):m==="canceled"?j=j.eq("status","canceled"):j=j.eq("status",m));const{data:y}=await j;if(!y)return[];const d=new Map,f={active:3,delayed:2,canceled:1};return[...y].sort((L,l)=>{const w=f[L.status]||0,M=f[l.status]||0;return w!==M?M-w:new Date(l.updated_at||0).getTime()-new Date(L.updated_at||0).getTime()}).forEach(L=>{const l=`${L.customer_email}-${L.product_id}`;d.has(l)||d.set(l,L)}),Array.from(d.values()).slice(0,50)},enabled:!!(s!=null&&s.id),staleTime:3e4}),a=(j,y)=>{switch(j){case"active":return e.jsx(U,{className:"bg-green-500/20 text-green-700 border-green-500/30",children:"Active"});case"delayed":return e.jsx(U,{className:"bg-amber-500/20 text-amber-700 border-amber-500/30",children:"Delayed"});case"canceled":return y==="payment_failed"?e.jsx(U,{className:"bg-amber-500/20 text-amber-700 border-amber-500/30",children:"Payment Failed"}):y==="user_canceled"||y==="admin_canceled"?e.jsx(U,{className:"bg-red-500/20 text-red-700 border-red-500/30",children:"Canceled"}):e.jsx(U,{className:"bg-gray-500/20 text-gray-700 border-gray-500/30",children:"Canceled"});case"churned":return e.jsx(U,{className:"bg-gray-500/20 text-gray-700 border-gray-500/30",children:"Churned"});default:return e.jsx(U,{variant:"secondary",children:j})}};if(x)return e.jsxs($,{children:[e.jsx(se,{children:e.jsx(ae,{children:"Subscribers"})}),e.jsx(ee,{children:e.jsx(H,{className:"h-[400px]"})})]});const _=p==null?void 0:p.filter(j=>{var d,f,q;if(!i)return!0;const y=i.toLowerCase();return((d=j.customer_name)==null?void 0:d.toLowerCase().includes(y))||((f=j.customer_email)==null?void 0:f.toLowerCase().includes(y))||((q=j.product_name)==null?void 0:q.toLowerCase().includes(y))});return e.jsxs($,{children:[e.jsxs(se,{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ae,{children:"Subscribers"}),e.jsx(ye,{children:"Detailed subscriber list"})]}),e.jsxs(re,{value:m,onValueChange:g,children:[e.jsx(ne,{className:"w-[180px]",children:e.jsx(le,{placeholder:"Filter status"})}),e.jsxs(de,{children:[e.jsx(F,{value:"all",children:"All"}),e.jsx(F,{value:"active",children:"Active"}),e.jsx(F,{value:"delayed",children:"Delayed"}),e.jsx(F,{value:"canceled",children:"All Canceled"}),e.jsx(F,{value:"payment_failed",children:"Payment Failed"}),e.jsx(F,{value:"user_canceled",children:"User Canceled"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ot,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Z,{placeholder:"Search by name, email or product...",value:i,onChange:j=>o(j.target.value),className:"pl-9"})]}),(i||m!=="all")&&e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[(_==null?void 0:_.length)||0," record",(_==null?void 0:_.length)!==1?"s":""," found"]})]})]}),e.jsx(ee,{children:e.jsx(ms,{className:"h-[400px]",children:e.jsxs($e,{children:[e.jsx(ze,{children:e.jsxs(ie,{children:[e.jsx(B,{children:"Customer"}),e.jsx(B,{children:"Product / Plan"}),e.jsx(B,{children:"Status"}),e.jsx(B,{className:"text-center",children:"Tenure"}),e.jsx(B,{children:"Last Payment"}),e.jsx(B,{className:"text-right",children:"Payments"}),e.jsx(B,{className:"text-right",children:"Total Revenue"})]})}),e.jsx(Ye,{children:_&&_.length>0?_.map(j=>e.jsxs(ie,{children:[e.jsx(z,{children:e.jsxs("div",{className:"cursor-pointer hover:text-primary group",onClick:()=>{r(`/crm?tab=oportunidades&search=${encodeURIComponent(j.customer_email)}&autoOpen=1`)},children:[e.jsxs("p",{className:"font-medium flex items-center gap-1",children:[j.customer_name||"N/A",e.jsx(cs,{className:"h-3 w-3 opacity-0 group-hover:opacity-100 transition-opacity"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:j.customer_email})]})}),e.jsx(z,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:j.product_name}),j.plan_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:j.plan_name})]})}),e.jsx(z,{children:a(j.status,j.cancellation_type)}),e.jsx(z,{className:"text-center",children:e.jsxs(U,{variant:"outline",children:[j.recurrence_number||1," mo"]})}),e.jsx(z,{children:j.last_payment_at?R(new Date(j.last_payment_at),"dd/MM/yyyy"):"N/A"}),e.jsx(z,{className:"text-right",children:e.jsx(U,{variant:"outline",children:j.total_payments||0})}),e.jsx(z,{className:"text-right font-medium",children:c(j.total_revenue)})]},j.id)):e.jsx(ie,{children:e.jsx(z,{colSpan:7,className:"text-center text-muted-foreground py-8",children:"No subscribers found"})})})]})})})]})}function Ea({dateRange:t,getDateRange:n}){const{user:s}=ge(),{startDate:r,endDate:c}=n(t),{data:m,isLoading:g}=Q({queryKey:["saas-growth-chart",s==null?void 0:s.id,r,c],queryFn:async()=>
98{if(!(s!=null&&s.id))return[];const{data:i}=await k.from("subscriptions").select("started_at, canceled_at, status, cancellation_type").eq("user_id",s.id);if(!i||i.length===0)return[];const o=me(r),p=me(c),x={};let a=pe(o);for(;a<=p;){const _=R(a,"yyyy-MM");x[_]={active:0,delayed:0,paymentFailed:0,churned:0},a=new Date(a.getFullYear(),a.getMonth()+1,1)}return i.forEach(_=>{const j=_.started_at?pe(me(_.started_at)):null,y=_.canceled_at?pe(me(_.canceled_at)):null;Object.keys(x).forEach(d=>{const f=me(d+"-01");if(!(!j||f<j))if(y&&f>=y)_.cancellation_type==="payment_failed"?x[d].paymentFailed++:x[d].churned++;else if(_.status==="delayed"){const q=pe(new Date);R(f,"yyyy-MM")===R(q,"yyyy-MM")?x[d].delayed++:x[d].active++}else{if(_.status==="canceled")return;x[d].active++}})}),Object.entries(x).map(([_,j])=>({month:R(me(_+"-01"),"MMM/yy"),...j})).sort((_,j)=>_.month.localeCompare(j.month))},enabled:!!(s!=null&&s.id)});return g?e.jsx(H,{className:"h-[350px] w-full"}):!m||m.length===0?e.jsxs($,{children:[e.jsx(se,{children:e.jsx(ae,{className:"text-lg",children:"SaaS Growth Report"})}),e.jsx(ee,{children:e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No subscription data found for selected period"})})]}):e.jsxs($,{children:[e.jsx(se,{children:e.jsx(ae,{className:"text-lg",children:"SaaS Growth Report"})}),e.jsx(ee,{children:e.jsx(Ce,{width:"100%",height:300,children:e.jsxs(At,{data:m,margin:{top:10,right:30,left:0,bottom:0},children:[e.jsx(Te,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Me,{dataKey:"month",tick:{fontSize:12},className:"text-muted-foreground"}),e.jsx(qe,{tick:{fontSize:12},className:"text-muted-foreground"}),e.jsx(Fe,{contentStyle:{backgroundColor:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}}),e.jsx(Ke,{}),e.jsx(Oe,{dataKey:"active",name:"Active",stackId:"a",fill:"hsl(var(--primary))"}),e.jsx(Oe,{dataKey:"delayed",name:"Delayed",stackId:"a",fill:"hsl(45 93% 47%)"}),e.jsx(Oe,{dataKey:"paymentFailed",name:"Payment Failed",stackId:"a",fill:"hsl(45 93% 47%)"}),e.jsx(Oe,{dataKey:"churned",name:"Churned",stackId:"a",fill:"hsl(0 84% 60%)"})]})})})]})}function Aa({dateRange:t,getDateRange:n}){const{user:s}=ge(),{startDate:r,endDate:c}=n(t),{data:m,isLoading:g}=Q({queryKey:["subscription-cohort",s==null?void 0:s.id,r,c],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:x}=await k.from("subscriptions").select("started_at, canceled_at, status, cancellation_type, customer_email, product_id").eq("user_id",s.id).gte("started_at",r).lte("started_at",c);if(!x||x.length===0)return null;const a={},_=new Date,j=12,y=new Map;x.forEach(q=>{if(!q.started_at)return;const L=`${q.customer_email}-${q.product_id}`,l=y.get(L);(!l||new Date(q.started_at)<new Date(l.started_at))&&y.set(L,q)}),Array.from(y.values()).forEach(q=>{if(!q.started_at)return;const L=R(pe(me(q.started_at)),"yyyy-MM");a[L]||(a[L]={total:0,retention:Array(j).fill(0)}),a[L].total++;const l=q.canceled_at?me(q.canceled_at):null,w=me(q.started_at);for(let M=0;M<j;
98M++){const h=new Date(w.getFullYear(),w.getMonth()+M,1);if(h>_)break;(!l||h<l)&&a[L].retention[M]++}});const d=Object.entries(a).map(([q,L])=>({month:q,label:R(me(q+"-01"),"MMM/yy"),...L})).sort((q,L)=>q.month.localeCompare(L.month)),f=Array(j).fill(0);return d.forEach(q=>{q.retention.forEach((L,l)=>{f[l]+=L})}),{cohorts:d,periodTotals:f,maxPeriods:j}},enabled:!!(s!=null&&s.id)});if(g)return e.jsx(H,{className:"h-[400px] w-full"});if(!m||m.cohorts.length===0)return e.jsxs($,{children:[e.jsx(se,{children:e.jsx(ae,{className:"text-lg",children:"Retention Cohort"})}),e.jsx(ee,{children:e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No cohort data found for selected period"})})]});const i=m.periodTotals.reduce((x,a,_)=>a>0?_+1:x,0),o=Math.min(Math.max(i,6),m.maxPeriods),p=(x,a)=>{if(a===0)return"bg-muted";const _=x/a;return _>=.9?"bg-green-500/80 text-white":_>=.7?"bg-green-400/70 text-white":_>=.5?"bg-yellow-400/70":_>=.3?"bg-orange-400/70":_>0?"bg-red-400/70 text-white":"bg-muted"};return e.jsxs($,{children:[e.jsx(se,{children:e.jsx(ae,{className:"text-lg",children:"Retention Cohort"})}),e.jsx(ee,{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left p-2 font-medium text-muted-foreground",children:"Cohort"}),e.jsx("th",{className:"text-center p-2 font-medium text-muted-foreground",children:"Total"}),Array.from({length:o},(x,a)=>e.jsxs("th",{className:"text-center p-2 font-medium text-muted-foreground min-w-[50px]",children:["#",a+1]},a))]})}),e.jsx("tbody",{children:m.cohorts.map(x=>e.jsxs("tr",{className:"border-b border-border/50",children:[e.jsx("td",{className:"p-2 font-medium",children:x.label}),e.jsx("td",{className:"p-2 text-center font-semibold",children:x.total}),x.retention.slice(0,o).map((a,_)=>{const j=x.total>0?(a/x.total*100).toFixed(0):"0";return e.jsxs("td",{className:Qs("p-2 text-center text-xs font-medium",p(a,x.total)),children:[a>0?a:"-",a>0&&x.total>0&&e.jsxs("span",{className:"block text-[10px] opacity-75",children:[j,"%"]})]},_)})]},x.month))}),e.jsx("tfoot",{children:e.jsxs("tr",{className:"bg-muted/50",children:[e.jsx("td",{className:"p-2 font-semibold",children:"Total"}),e.jsx("td",{className:"p-2 text-center font-semibold",children:m.cohorts.reduce((x,a)=>x+a.total,0)}),m.periodTotals.slice(0,o).map((x,a)=>e.jsx("td",{className:"p-2 text-center font-semibold",children:x>0?x:"-"},a))]})})]})})]})}function Ra({dateRange:t,getDateRange:n}){const{user:s}=ge(),{data:r,isLoading:c}=Q({queryKey:["recurrence-distribution",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:i}=await k.from("subscriptions").select("recurrence_number, status").eq("user_id",s.id).eq("status","active");return!i||i.length===0?[]:[{label:"1-3",min:1,max:3},{label:"4-6",min:4,max:6},{label:"7-12",min:7,max:12},{label:"13-24",min:13,max:24},{label:"25-36",min:25,max:36},{label:"37+",min:37,max:1/0}].map(x=>{const a=i.filter(_=>{const j=_.recurrence_number||1;return j>=x.min&&j<=x.max}).length;return{range:x.label,count:a,months:x.label==="37+"?"37+ months":`${x.min}-${x.max} months`}})},enabled:!!(s!=null&&s.id)}),{data:m}=Q({queryKey:["avg-recurrence",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return 0;const{data:i}=await k.from("subscriptions").select("recurrence_number").eq("user_id",s.id).eq("status","active");if(!i||i.length===0)return 0;const o=i.reduce((p,x)=>p+(x.recurrence_number||1),0);return Math.round(o/i.length*10)/10},enabled:!!(s!=null&&s.id)});if(c)return e.jsx(H,{className:"h-[350px] w-full"});if(!r||r.length===0)return e.jsxs($,{children:[e.jsx(se,{children:e.jsx(ae,{className:"text-lg",children:"Subscriber Tenure Distribution"})}),e.jsx(ee,{children:e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No subscription data found"})})]});const g=["hsl(var(--primary) / 0.5)","hsl(var(--primary) / 0.6)","hsl(var(--primary) / 0.7)","hsl(var(--primary) / 0.8)","hsl(var(--primary) / 0.9)","hsl(var(--primary))"];return e.jsxs($,{children:[e.jsxs(se,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(ae,{className:"text-lg",children:"Subscriber Tenure Distribution"}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Avg. tenure: ",e.jsxs("span",{className:"font-semibold text-foreground",children:[m," months"]})]})]}),e.jsx(ee,{children:e.jsx(Ce,{width:"100%",height:300,children:e.jsxs(At,{data:r,margin:{top:10,right:30,left:0,bottom:0},children:[e.jsx(Te,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Me,{dataKey:"range",tick:{fontSize:12},className:"text-muted-foreground",label:{value:"Months",position:"insideBottom",offset:-5}}),e.jsx(qe,{tick:{fontSize:12},className:"text-muted-foreground",label:{value:"Subscribers",angle:-90,position:"insideLeft"}}),e.jsx(Fe,{contentStyle:{backgroundColor:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:"8px"},formatter:(i,o)=>[i,"Subscribers"],labelFormatter:i=>`Tenure: ${i} months`}),e.jsx(Oe,{dataKey:"count",name:"Subscribers",radius:[4,4,0,0],children:r.map((i,o)=>e.jsx(Bs,{fill:g[o%g.length]},`cell-${o}`))})]})})})]})}function Ia(){const{user:t}=ge(),[n,s]=E.useState("this_year"),[r,c]=E.useState(""),[m,g]=E.useState(""),{data:i}=Q({queryKey:["earliest-subscription",t==null?void 0:t.id],queryFn:async()=>
98{if(!(t!=null&&t.id))return null;const{data:p}=await k.from("subscriptions").select("started_at").eq("user_id",t.id).order("started_at",{ascending:!0}).limit(1).maybeSingle();return(p==null?void 0:p.started_at)||null},enabled:!!(t!=null&&t.id)}),o=p=>{const x=new Date,a=new Date(x.getFullYear(),x.getMonth(),x.getDate(),0,0,0),_=new Date(x.getFullYear(),x.getMonth(),x.getDate(),23,59,59);switch(p){case"today":return{startDate:a.toISOString(),endDate:_.toISOString()};case"this_month":return{startDate:pe(x).toISOString(),endDate:_.toISOString()};case"last_month":const j=Tt(x,1);return{startDate:pe(j).toISOString(),endDate:fs(j).toISOString()};case"this_year":return{startDate:us(x).toISOString(),endDate:_.toISOString()};case"all_time":return{startDate:i||Tt(x,12).toISOString(),endDate:_.toISOString()};case"custom":return{startDate:r?new Date(r).toISOString():pe(x).toISOString(),endDate:m?new Date(m).toISOString():_.toISOString()};default:return{startDate:pe(x).toISOString(),endDate:_.toISOString()}}};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:"Subscriptions"}),e.jsx("p",{className:"text-muted-foreground",children:"Track your subscribers and recurring revenue"})]}),e.jsx(et,{dateRange:n,onDateRangeChange:s,customDateFrom:r,customDateTo:m,onCustomDateFromChange:c,onCustomDateToChange:g})]}),e.jsx(Fa,{dateRange:n,getDateRange:o}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-2",children:[e.jsx(Oa,{dateRange:n,getDateRange:o}),e.jsx(Pa,{dateRange:n,getDateRange:o})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-2",children:[e.jsx(Ea,{dateRange:n,getDateRange:o}),e.jsx(Ra,{dateRange:n,getDateRange:o})]}),e.jsx(Aa,{dateRange:n,getDateRange:o}),e.jsx(La,{dateRange:n,getDateRange:o})]})}function Ua(t){const{user:n}=ge();return Q({queryKey:["opportunity-timeline",n==null?void 0:n.id,t],queryFn:async()=>{if(!(n!=null&&n.id))return[];const s=[];let r=k.from("crm_opportunities").select("*").eq("user_id",n.id).order("created_at",{ascending:!1});t.opportunityId&&(r=r.eq("id",t.opportunityId)),t.productName&&(r=r.eq("product_name",t.productName)),t.stage&&(r=r.eq("stage",t.stage)),t.dateRange&&(r=r.gte("created_at",t.dateRange.startDate.toISOString()).lte("created_at",t.dateRange.endDate.toISOString()));const{data:c,error:m}=await r;if(m)throw m;const g=(c==null?void 0:c.map(l=>l.id))||[];if(g.length===0)return[];const i=(c==null?void 0:c.map(l=>l.lead_id).filter(Boolean))||[],o=(c==null?void 0:c.map(l=>l.customer_phone).filter(Boolean))||[],p=[...new Set(o.flatMap(l=>jt(l)))],[{data:x},{data:a},{data:_},{data:j},{data:y},{data:d}]=await Promise.all([k.from("opportunity_stage_history").select("*").in("opportunity_id",g).order("changed_at",{ascending:!1}),k.from("opportunity_tasks").select("*").in("opportunity_id",g).order("created_at",{ascending:!1}),k.from("opportunity_notes").select("*").in("opportunity_id",g).order("created_at",{ascending:!1}),k.from("sales").select("*").in("opportunity_id",g).order("created_at",{ascending:!1}),k.from("leads").select("*").in("id",i.length>0?i:["__none__"]),(async()=>{if(i.length===0&&p.length===0)return{data:[],error:null};const l=[];return i.length>0&&l.push(`lead_id.in.(${i.join(",")})`),p.length>0&&l.push(`phone.in.(${p.join(",")})`),k.from("lead_group_activities").select("*").or(l.join(",")).order("created_at",{ascending:!1}).limit(500)})()]),f=new Map(c==null?void 0:c.map(l=>[l.id,l])),q=new Map(y==null?void 0:y.map(l=>[l.id,l]));if(c==null||c.forEach(l=>{const w=l.auto_created===!0||typeof l.transaction_id=="string"&&l.transaction_id.startsWith("LS-"),M=l.lead_id?q.get(l.lead_id):null;s.push({id:`opp-created-${l.id}`,type:"opportunity_created",timestamp:l.created_at,opportunityId:l.id,customerName:l.customer_name,customerEmail:l.customer_email,productName:l.product_name,title:w?"Opportunity Auto-Created (Lead Score)":"Opportunity Created",description:w?`Generated from lead scoring${(M==null?void 0:M.lead_score)!=null?` · score ${M.lead_score}`:""}${M!=null&&M.lead_temperature?` · ${M.lead_temperature}`:""}`:null,value:l.value,currency:l.currency,metadata:{stage:l.stage,status:l.current_status,autoCreated:!!l.auto_created,source:w?"lead_score":"manual",leadScore:(M==null?void 0:M.lead_score)??null,leadTemperature:(M==null?void 0:M.lead_temperature)??null}}),l.lead_id&&M&&s.push({id:`lead-${M.id}`,type:"lead_registered",timestamp:M.created_at,opportunityId:l.id,customerName:M.name,customerEmail:M.email,productName:l.product_name,title:"Lead Registered",description:M.form_id?"Via form submission":null,value:null,currency:null,metadata:{formId:M.form_id,utmData:M.utm_data}})}),x==null||x.forEach(l=>{const w=f.get(l.opportunity_id),M=l.to_stage==="won",h=l.to_stage==="lost";let u="stage_changed";M&&(u="opportunity_won"),h&&(u="opportunity_lost"),s.push({id:`stage-${l.id}`,type:u,timestamp:l.changed_at,opportunityId:l.opportunity_id,customerName:(w==null?void 0:w.customer_name)||null,customerEmail:(w==null?void 0:w.customer_email)||null,productName:(w==null?void 0:w.product_name)||null,title:M?"Opportunity Won!":h?"Opportunity Lost":"Stage Changed",description:`${l.from_stage||"new"} → ${l.to_stage}`,value:(w==null?void 0:w.value)||null,currency:(w==null?void 0:w.currency)||null,metadata:{fromStage:l.from_stage,toStage:l.to_stage,fromStatus:l.from_status,toStatus:l.to_status,triggerSource:l.trigger_source}})}),a==null||a.forEach(l=>{const w=f.get(l.opportunity_id);s.push({id:`task-created-${l.id}`,type:"task_created",timestamp:l.created_at,opportunityId:l.opportunity_id,customerName:(w==null?void 0:w.customer_name)||null,customerEmail:(w==null?void 0:w.customer_email)||null,productName:(w==null?void 0:w.product_name)||null,title:`Task Created: ${l.title}`,description:l.description,value:null,currency:null,metadata:{taskId:l.id,priority:l.priority,taskType:l.task_type,dueDate:l.due_date}}),l.status==="completed"&&l.completed_at&&s.push({id:`task-completed-${l.id}`,type:"task_completed",timestamp:l.completed_at,opportunityId:l.opportunity_id,customerName:(w==null?void 0:w.customer_name)||null,customerEmail:(w==null?void 0:w.customer_email)||null,productName:(w==null?void 0:w.product_name)||null,title:`Task Completed: ${l.title}`,description:l.description,value:null,currency:null,metadata:{taskId:l.id,priority:l.priority,taskType:l.task_type},contributedToConversion:l.contributed_to_conversion||!1})}),_==null||_.forEach(l=>{const w=f.get(l.opportunity_id);let M="note_added",h="Note Added";l.note_type==="call"?(M="call_logged",h="Call Logged"):l.note_type==="email"?(M="email_sent",h="Email Sent"):l.note_type==="meeting"?(M="meeting_logged",h="Meeting Logged"):l.note_type==="whatsapp"&&(M="whatsapp_sent",h="WhatsApp Sent"),s.push({id:`note-${l.id}`,type:M,timestamp:l.created_at,opportunityId:l.opportunity_id,customerName:(w==null?void 0:w.customer_name)||null,customerEmail:(w==null?void 0:w.customer_email)||null,productName:(w==null?void 0:w.product_name)||null,title:h,description:l.content,value:null,currency:null,metadata:{noteType:l.note_type}})}
98),j==null||j.forEach(l=>{const w=f.get(l.opportunity_id);let M="sale_created",h="Sale Created";l.status==="approved"||l.status==="complete"?(M="sale_approved",h="Payment Approved"):l.status==="canceled"||l.status==="expired"?(M="sale_canceled",h="Sale Canceled"):l.status==="refunded"&&(M="sale_refunded",h="Sale Refunded"),s.push({id:`sale-${l.id}`,type:M,timestamp:l.created_at||l.purchase_date||new Date().toISOString(),opportunityId:l.opportunity_id,customerName:l.customer_name||(w==null?void 0:w.customer_name)||null,customerEmail:l.customer_email||(w==null?void 0:w.customer_email)||null,productName:l.product_name||(w==null?void 0:w.product_name)||null,title:h,description:l.payment_method?`Via ${l.payment_method}`:null,value:l.gross_value,currency:l.currency,metadata:{saleId:l.id,status:l.status,paymentMethod:l.payment_method,transactionId:l.transaction_id}})}),d&&d.length>0){const l=new Map,w=new Map;c==null||c.forEach(u=>{u.lead_id&&l.set(u.lead_id,u),u.customer_phone&&jt(u.customer_phone).forEach(P=>{w.set(P,u)})});const M={joined_group:"whatsapp_joined_group",left_group:"whatsapp_left_group",message_sent:"whatsapp_message_sent",reaction:"whatsapp_reaction",poll_answered:"whatsapp_poll_answered"},h={joined_group:"Joined WhatsApp Group",left_group:"Left WhatsApp Group",message_sent:"Message in WhatsApp Group",reaction:"Reaction in WhatsApp Group",poll_answered:"Poll Answered in Group"};d.forEach(u=>{let P=u.lead_id?l.get(u.lead_id):void 0;if(!P&&u.phone&&(P=w.get(Gs(u.phone))),!P)return;const A=M[u.activity_type]||"whatsapp_message_sent",D=u.activity_data||{},N=D.group_name||D.groupName||null,I=D.message_preview||D.messagePreview||D.poll_option||null;s.push({id:`wa-activity-${u.id}`,type:A,timestamp:u.created_at,opportunityId:P.id,customerName:P.customer_name,customerEmail:P.customer_email,productName:P.product_name,title:h[u.activity_type]||"WhatsApp Activity",description:N?I?`${N}: ${I}`:N:I,value:null,currency:null,metadata:{activityType:u.activity_type,phone:u.phone,groupId:u.group_id,provider:u.provider,matchedLead:u.matched_lead,...D}})})}let L=s;if(t.eventTypes&&t.eventTypes.length>0&&(L=s.filter(l=>t.eventTypes.includes(l.type))),t.search){const l=t.search.toLowerCase();L=L.filter(w=>{var M,h,u,P;return w.title.toLowerCase().includes(l)||((M=w.customerName)==null?void 0:M.toLowerCase().includes(l))||((h=w.customerEmail)==null?void 0:h.toLowerCase().includes(l))||((u=w.productName)==null?void 0:u.toLowerCase().includes(l))||((P=w.description)==null?void 0:P.toLowerCase().includes(l))})}return L.sort((l,w)=>new Date(w.timestamp).getTime()-new Date(l.timestamp).getTime()),L},enabled:!!(n!=null&&n.id)})}function Ka(){const{user:t}=ge();return Q({queryKey:["timeline-products",t==null?void 0:t.id],queryFn:async()=>{if(!(t!=null&&t.id))return[];const{data:n,error:s}=await k.from("crm_opportunities").select("product_name").eq("user_id",t.id).not("product_name","
98is",null);if(s)throw s;return[...new Set(n==null?void 0:n.map(c=>c.product_name).filter(Boolean))]},enabled:!!(t!=null&&t.id)})}function $a(){const{user:t}=ge();return Q({queryKey:["timeline-opportunities",t==null?void 0:t.id],queryFn:async()=>{if(!(t!=null&&t.id))return[];const{data:n,error:s}=await k.from("crm_opportunities").select("id, customer_name, customer_email, product_name").eq("user_id",t.id).order("created_at",{ascending:!1}).limit(100);if(s)throw s;return n||[]},enabled:!!(t!=null&&t.id)})}const za=[{value:"all",labelKey:"timeline.filters.all"},{value:"tasks",labelKey:"details.tasks"},{value:"notes",labelKey:"details.notes"},{value:"sales",labelKey:"tabs.sales"},{value:"stageChanges",labelKey:"timeline.filters.stageChanges"},{value:"whatsapp",labelKey:"timeline.filters.whatsappActivities"}],Ya=[{value:"all",labelKey:"timeline.filters.all"},{value:"cart",labelKey:"stages.cart"},{value:"pending",labelKey:"stages.pending"},{value:"won",labelKey:"stages.won"},{value:"lost",labelKey:"stages.lost"}];function Wa({dateRange:t,customFrom:n,customTo:s,eventType:r,opportunityId:c,productName:m,stage:g,search:i,onDateRangeChange:o,onCustomFromChange:p,onCustomToChange:x,onEventTypeChange:a,onOpportunityIdChange:_,onProductNameChange:j,onStageChange:y,onSearchChange:d}){const{t:f}=We(["crm","common"]),{data:q=[]}=Ka(),{data:L=[]}=$a();return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsx("div",{className:"flex-1",children:e.jsx(et,{dateRange:t,onDateRangeChange:o,customDateFrom:n,customDateTo:s,onCustomDateFromChange:p,onCustomDateToChange:x})}),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ot,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Z,{placeholder:f("crm:timeline.filters.search"),value:i,onChange:l=>d(l.target.value),className:"pl-10"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(re,{value:r,onValueChange:a,children:[e.jsxs(ne,{className:"w-[160px]",children:[e.jsx(Rs,{className:"h-4 w-4 mr-2"}),e.jsx(le,{placeholder:f("crm:timeline.filters.eventType")})]}),e.jsx(de,{children:za.map(l=>e.jsx(F,{value:l.value,children:f(`crm:${l.labelKey}`)},l.value))})]}),e.jsxs(re,{value:m,onValueChange:j,children:[e.jsx(ne,{className:"w-[180px]",children:e.jsx(le,{placeholder:f("crm:filters.product")})}),e.jsxs(de,{children:[e.jsx(F,{value:"all",children:f("crm:timeline.filters.all")}),q.map(l=>e.jsx(F,{value:l,children:l},l))]})]}),e.jsxs(re,{value:g,onValueChange:y,children:[e.jsx(ne,{className:"w-[140px]",children:e.jsx(le,{placeholder:f("crm:filters.stage")})}),e.jsx(de,{children:Ya.map(l=>e.jsx(F,{value:l.value,children:f(`crm:${l.labelKey}`)},l.value))})]}),e.jsxs(re,{value:c,onValueChange:_,children:[e.jsx(ne,{className:"w-[220px]",children:e.jsx(le,{placeholder:f("crm:timeline.filters.opportunity")})}),e.jsxs(de,{children:[e.jsx(F,{value:"all",children:f("crm:timeline.filters.all")}),L.map(l=>e.jsxs(F,{value:l.id,children:[l.customer_name||l.customer_email," - ",l.product_name]},l.id))]})]})]})]})}function Ba(t){switch(t){case"tasks":return["task_created","task_completed"];case"notes":return["note_added","call_logged","email_sent","meeting_logged","whatsapp_sent"];case"sales":return["sale_created","sale_approved","sale_canceled","sale_refunded"];case"stageChanges":return["stage_changed","opportunity_won","opportunity_lost"];case"whatsapp":return["whatsapp_joined_group","whatsapp_left_group","whatsapp_message_sent","whatsapp_reaction","whatsapp_poll_answered"];default:return null}}const Va={lead_registered:{icon:pt,colorClass:"text-blue-600 dark:text-blue-400",bgClass:"bg-blue-100 dark:bg-blue-900/30"},opportunity_created:{icon:as,colorClass:"text-purple-600 dark:text-purple-400",bgClass:"bg-purple-100 dark:bg-purple-900/30"},stage_changed:{icon:Us,colorClass:"text-gray-600 dark:text-gray-400",bgClass:"bg-gray-100 dark:bg-gray-800"},task_created:{icon:Ks,colorClass:"text-slate-600 dark:text-slate-400",bgClass:"bg-slate-100 dark:bg-slate-800"},task_completed:{icon:Lt,colorClass:"text-green-600 dark:text-green-400",bgClass:"bg-green-100 dark:bg-green-900/30"}
98,note_added:{icon:dt,colorClass:"text-amber-600 dark:text-amber-400",bgClass:"bg-amber-100 dark:bg-amber-900/30"},call_logged:{icon:Ue,colorClass:"text-purple-600 dark:text-purple-400",bgClass:"bg-purple-100 dark:bg-purple-900/30"},email_sent:{icon:it,colorClass:"text-indigo-600 dark:text-indigo-400",bgClass:"bg-indigo-100 dark:bg-indigo-900/30"},meeting_logged:{icon:ct,colorClass:"text-blue-600 dark:text-blue-400",bgClass:"bg-blue-100 dark:bg-blue-900/30"},whatsapp_sent:{icon:je,colorClass:"text-emerald-600 dark:text-emerald-400",bgClass:"bg-emerald-100 dark:bg-emerald-900/30"},sale_created:{icon:Ie,colorClass:"text-orange-600 dark:text-orange-400",bgClass:"bg-orange-100 dark:bg-orange-900/30"},sale_approved:{icon:rt,colorClass:"text-green-600 dark:text-green-400",bgClass:"bg-green-100 dark:bg-green-900/30"},sale_canceled:{icon:Se,colorClass:"text-red-600 dark:text-red-400",bgClass:"bg-red-100 dark:bg-red-900/30"},sale_refunded:{icon:$s,colorClass:"text-orange-600 dark:text-orange-400",bgClass:"bg-orange-100 dark:bg-orange-900/30"},opportunity_won:{icon:zs,colorClass:"text-yellow-600 dark:text-yellow-400",bgClass:"bg-yellow-100 dark:bg-yellow-900/30"},opportunity_lost:{icon:Se,colorClass:"text-red-600 dark:text-red-400",bgClass:"bg-red-100 dark:bg-red-900/30"},whatsapp_joined_group:{icon:pt,colorClass:"text-green-600 dark:text-green-400",bgClass:"bg-green-100 dark:bg-green-900/30"},whatsapp_left_group:{icon:Mt,colorClass:"text-red-600 dark:text-red-400",bgClass:"bg-red-100 dark:bg-red-900/30"},whatsapp_message_sent:{icon:je,colorClass:"text-green-600 dark:text-green-400",bgClass:"bg-green-100 dark:bg-green-900/30"},whatsapp_reaction:{icon:ns,colorClass:"text-pink-600 dark:text-pink-400",bgClass:"bg-pink-100 dark:bg-pink-900/30"},whatsapp_poll_answered:{icon:rs,colorClass:"text-blue-600 dark:text-blue-400",bgClass:"bg-blue-100 dark:bg-blue-900/30"}};function Qa({event:t,onClick:n}){const{i18n:s,t:r}=We(["crm"]),{formatValue:c}=ce(),m=s.language==="pt-BR"?_s:xs,g=Va[t.type],i=g.icon,o=js(new Date(t.timestamp),{addSuffix:!0,locale:m}),p=R(new Date(t.timestamp),"PPpp",{locale:m}),x=t.type==="opportunity_won",a=t.type==="opportunity_lost";return e.jsx($,{className:`p-4 cursor-pointer transition-all hover:shadow-md ${x?"border-yellow-400 bg-yellow-50/50 dark:bg-yellow-900/10":""} ${a?"border-red-300 bg-red-50/50 dark:bg-red-900/10":""}`,onClick:n,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`p-2 rounded-full ${g.bgClass} shrink-0`,children:e.jsx(i,{className:`h-5 w-5 ${g.colorClass}`})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h4",{className:"font-medium text-foreground truncate",children:[t.title,x&&e.jsx("span",{className:"ml-1",children:"🏆"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground truncate",children:[t.customerName||t.customerEmail,t.productName&&e.jsxs("span",{className:"text-muted-foreground/70",children:[" • ",t.productName]})]}),t.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:t.description}),t.contributedToConversion&&e.jsxs(U,{variant:"secondary",className:"mt-2 bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400",children:[e.jsx(Is,{className:"h-3 w-3 mr-1 fill-current"}),r("crm:timeline.attribution.contributedToWin")]})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsxs(be,{children:[e.jsx(Ne,{asChild:!0,children:e.jsx("span",{className:"text-xs text-muted-foreground",children:o})}),e.jsx(ve,{children:e.jsx("p",{children:p})})]}),t.value&&t.value>0&&e.jsx("p",{className:`text-sm font-medium mt-1 ${t.type==="sale_approved"||t.type==="opportunity_won"?"text-green-600 dark:text-green-400":"text-foreground"}`,children:c(t.value,t.currency||"BRL")})]})]})})]})})}function Ha({events:t,isLoading:n,onEventClick:s}){const{t:r,i18n:c}=We(["crm","common"]),m=c.language==="pt-BR"?_s:xs,g=ke.useMemo(()=>{const i=[];return t.forEach(o=>{const p=new Date(o.timestamp),x=i.find(a=>vs(a.date,p));if(x)x.events.push(o);else{let a;Ct(p)?a=r("common:today"):Js(p)?a=r("common:yesterday"):a=R(p,"PPP",{locale:m}),i.push({date:p,label:a,events:[o]})}}),i.sort((o,p)=>p.date.getTime()-o.date.getTime()),i},[t,m,r]);return n?e.jsx("div",{className:"space-y-6",children:[1,2,3].map(i=>e.jsxs("div",{className:"space-y-3",children:[e.jsx(H,{className:"h-5 w-24"}),e.jsx(H,{className:"h-24 w-full"}),e.jsx(H,{className:"h-24 w-full"})]},i))}):t.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"rounded-full bg-muted p-4 mb-4",children:e.jsx(Ys,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"text-lg font-medium text-foreground mb-1",children:r("crm:timeline.empty.title")}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-sm",children:r("crm:timeline.empty.description")})]}):e.jsx("div",{className:"space-y-8",children:g.map(i=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(De,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide",children:i.label}),e.jsx("div",{className:"flex-1 h-px bg-border"})]}),e.jsx("div",{className:"space-y-3 ml-6 relative before:absolute before:left-[-18px] before:top-0 before:bottom-0 before:w-[2px] before:bg-border",children:i.events.map(o=>e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute left-[-22px] top-6 w-2.5 h-2.5 rounded-full bg-border ring-4 ring-background"}),e.jsx(Qa,{event:o,onClick:()=>s==null?void 0:s(o)})]},o.id))})]},i.label))})}function Ga(){const{t}=We(["crm","common"]),[n,s]=E.useState("this_month"),[r,c]=E.useState(""),[m,g]=E.useState(""),[i,o]=E.useState("all"),[p,x]=E.useState("all"),[a,_]=E.useState("all"),[j,y]=E.useState("all"),[d,f]=E.useState(""),[q,L]=E.useState(null),[l,w]=E.useState(!1),M=ut(n,r,m),h={dateRange:M.startDate&&M.endDate?{startDate:M.startDate,endD
98ate:M.endDate}:null,eventTypes:Ba(i),opportunityId:p!=="all"?p:null,productName:a!=="all"?a:null,stage:j!=="all"?j:null,search:d},{data:u=[],isLoading:P}=Ua(h),A=N=>{L(N.opportunityId),w(!0)},D=()=>{w(!1),L(null)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs($,{children:[e.jsx(se,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-primary/10",children:e.jsx(Ws,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(ae,{children:t("crm:timeline.title")}),e.jsx(ye,{children:t("crm:timeline.subtitle")})]})]})}),e.jsx(ee,{children:e.jsx(Wa,{dateRange:n,customFrom:r,customTo:m,eventType:i,opportunityId:p,productName:a,stage:j,search:d,onDateRangeChange:s,onCustomFromChange:c,onCustomToChange:g,onEventTypeChange:o,onOpportunityIdChange:x,onProductNameChange:_,onStageChange:y,onSearchChange:f})})]}),e.jsx($,{children:e.jsx(ee,{className:"pt-6",children:e.jsx(Ha,{events:u,isLoading:P,onEventClick:A})})}),q&&e.jsx(Wt,{opportunityId:q,isOpen:l,onClose:D})]})}const Qr=()=>{const[t,n]=E.useState("dashboard"),{data:s,isLoading:r}=ta(),{t:c}=We(["crm","common"]);sa();const m=(s==null?void 0:s.canUseProFeature)??!1;return!r&&!m?e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold",children:c("crm:title")}),e.jsx("p",{className:"text-muted-foreground mt-1",children:c("crm:subtitle")})]}),e.jsx(aa,{title:"CRM completo é um recurso PRO",description:"Seu test drive acabou. Ative a assinatura para reabrir o CRM, pipeline e oportunidades."})]}):e.jsx(e.Fragment,{children:e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold",children:c("crm:title")}),e.jsx("p",{className:"text-muted-foreground mt-1",children:c("crm:subtitle")})]}),e.jsxs(ts,{value:t,onValueChange:n,children:[e.jsxs(ss,{className:"grid w-full grid-cols-8",children:[e.jsx(xe,{value:"dashboard",children:c("crm:tabs.dashboard")}),e.jsx(xe,{value:"opportunities",children:c("crm:tabs.opportunities")}),e.jsx(xe,{value:"kanban",children:c("crm:tabs.kanban")}),e.jsx(xe,{value:"subscriptions",children:c("crm:tabs.subscriptions")}),e.jsx(xe,{value:"tasks",children:c("crm:tabs.tasks")}),e.jsx(xe,{value:"timeline",children:c("crm:tabs.timeline")}),e.jsx(xe,{value:"list",children:c("crm:tabs.transactions")}),e.jsx(xe,{value:"setup",children:c("crm:tabs.setup")})]}),e.jsx(he,{value:"dashboard",className:"mt-6",children:e.jsx(ua,{})}),e.jsx(he,{value:"opportunities",className:"mt-6",children:e.jsx(va,{})}),e.jsx(he,{value:"kanban",className:"mt-6",children:e.jsx(ka,{})}),e.jsx(he,{value:"subscriptions",className:"mt-6",children:e.jsx(Ia,{})}),e.jsx(he,{value:"tasks",className:"mt-6",children:e.jsx(Da,{})}),e.jsx(he,{value:"timeline",className:"mt-6",children:e.jsx(Ga,{})}),e.jsx(he,{value:"list",className:"mt-6",children:e.jsx(wa,{})}),e.jsx(he,{value:"setup",className:"mt-6",children:e.jsx(qa,{})})]})]})})};export{Qr 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.