1import{j as e,u as V}from"./data-DN-eP4ae.js";import{r as f,L as ae,e as I,N as Us}from"./react-BUOzgyp0.js";import{t as Ys,w as ws,B as x,W as Ns,L as Z,C as se,c as T,u as De,g as Be,r as Ke,T as Qs,a as Zs,b as Js,I as Xs,d as et,P as st,e as tt,f as at,S as nt,n as z,h as it,s as _,i as H,j as ke,A as J,M as ks,k as ye,Z as ge,U as ne,F as Ue,l as _e,m as de,o as Ae,p as _s,D as Cs,q as is,v as ot,x as rt,y as ve,z as lt,E as ct,G as dt,H as ut,J as Oe,K as ie,N as Ss,O as mt,Q as Ce,R as Se,V as $e,X as Ye,Y as pt,_ as xt,$ as We,a0 as le,a1 as Qe,a2 as ht,a3 as ze,a4 as ft,a5 as gt,a6 as yt,a7 as vt,a8 as bt,a9 as jt,aa as wt,ab as Nt,ac as kt,ad as _t,ae as Ls,af as Me,ag as Ze,ah as Ct,ai as St,aj as He,ak as Lt,al as Tt,am as Ts,an as Dt,ao as At,ap as Ds,aq as As,ar as Os,as as Ot,at as Je,au as $t,av as Wt,aw as Mt,ax as Xe,ay as Pt,az as Rt,aA as $s,aB as Ws,aC as Ms,aD as Ps,aE as It,aF as Et,aG as qt,aH as Ft,aI as zt,aJ as Ht,aK as Vt,aL as Gt,aM as Rs,aN as Ie,aO as os,aP as Bt,aQ as Le,aR as Kt,aS as Ut,aT as Is,aU as Yt,aV as Qt,aW as Zt,aX as Jt,aY as Xt,aZ as ea,a_ as sa,a$ as ta,b0 as aa,b1 as na,b2 as ia,b3 as oa,b4 as ra,b5 as la,b6 as ca,b7 as da,b8 as ua,b9 as ma,ba as pa,bb as xa,bc as ha,bd as fa,be as rs,bf as ga,bg as ya,bh as va,bi as ba,bj as ja,bk as wa,bl as Na,bm as ka,bn as ls,bo as _a}from"./index-6GUxm5Tl.js";import{E as Ca}from"./EmptyState-ChyoO585.js";import{u as Sa}from"./useProductiveLoading-BO0IaMGS.js";import{M as La,A as Ta}from"./maximize-2-B3P4cQNS.js";import{R as Da,S as Aa,A as Oa,a as $a,M as Wa,N as Ma}from"./square-D7bNRzj-.js";import{A as Pa}from"./arrow-up-uYleynt9.js";import{A as Ra}from"./arrow-down-BMPlnjnx.js";import{E as Ia}from"./eye-off-DP6aatND.js";import{G as Ea}from"./grip-vertical-CiuWx_Va.js";import{E as qa}from"./ellipsis-vertical-CEb_a4k-.js";import{r as Fa,s as za}from"./recognised-revenue-CWypD7KS.js";import{s as Ha}from"./startOfMonth-kO_ql4le.js";import{o as be}from"./contact-nav-B0Ta2B34.js";import{f as Es}from"./format-BOCe1Q81.js";import{i as cs}from"./isToday-CDVfXo1I.js";import{u as Va}from"./useContactGroups-CZ4ICVoa.js";import{f as qs,C as es}from"./RelationshipContactPicker-BgrKoois.js";import{C as Ga}from"./ContactStatusBadge-DR9Rg8ll.js";import{P as Ba}from"./party-popper-CCyO5Xb5.js";import{c as Ka}from"./useNpsSurveys-BbtidKWE.js";import{C as Ua}from"./calendar-heart-Bpd6k3fS.js";import{u as Ya}from"./useCommissions-D4DjCA3_.js";import{W as Qa}from"./wallet-hX8y-nkf.js";import{C as Za}from"./circle-check-big-CqaXP6K1.js";import{u as Ja,a as Xa}from"./useSettingsReturn-3V0Z2K8A.js";import{u as en,a as sn,b as tn,c as an}from"./useOrgReferrals-CzLWDJFW.js";import{u as nn,a as on,b as rn,c as ln,E as cn,v as dn}from"./useVisitorSessions-D_RcL8eD.js";import{V as un}from"./VisitorSummary-BL_OmptZ.js";import{M as mn}from"./map-pin-D8yKoJwU.js";import{u as je,a as Fs}from"./useFollowups-YB0qEXzK.js";import{T as pn}from"./timer-PGzFq-_7.js";import{A as xn}from"./arrow-up-right-DbUg8U10.js";import{u as Y}from"./useDashboardFeatureMetrics-DDUJBq5T.js";import{u as zs}from"./useInvoices-Bf7ro_Wr.js";import{u as hn}from"./useCustomerCare-Cgubd3Qs.js";import{u as ss}from"./useDismissable-BvpILM0V.js";import{S as fn}from"./save-Bg7aMJuF.js";import{P as gn}from"./module-intro-N0cKHpsA.js";import{u as yn}from"./useBusinessIdentity-CmNQT2Nl.js";import{A as vn}from"./AttentionStrip-DreKh8i4.js";import{u as bn}from"./useVisibility-40vaeyEh.js";import{u as jn}from"./useIntelligencePlacement-CbLnAc_a.js";import{O as wn}from"./OutcomeChooser-DBg_DoAG.js";import{C as Nn}from"./card-Bpoa90g8.js";import{u as kn}from"./useDomainReadiness-Ca2aDeb7.js";import{G as _n}from"./globe-C22yugrV.js";import{u as Cn,a as Sn}from"./useTasks-xNZM6HdJ.js";import{u as Ln}from"./useNotes-qt8p4RYX.js";import{u as Tn}from"./useConnectedChannels-h55XEIpK.js";import{C as Dn}from"./ComposeNewConversationDialog-De0kJHEJ.js";import{S as An}from"./sticky-note-BKRB5oMJ.js";import{M as On}from"./ActionChoiceSheet-Bej1gA4Q.js";import"./documents-Bju1cS7G.js";import"./charts-BjVT6r80.js";
1import"./app-primitives-C7oGnmBt.js";import"./isSameDay-BZkPoTMS.js";import"./formatDistanceStrict-C9HAzcFi.js";import"./chevron-left-BO8s0r98.js";import"./useCustomerLifecycle-C5vbSUQ7.js";import"./useOrgSettings-Bek7ES8S.js";import"./useLeads-DsKSjHTD.js";import"./settings-return-GcuqJJ7v.js";import"./url-BxF7c6Us.js";import"./onboarding-business-types-InVCPvhM.js";import"./business-taxonomy-DjKP5GVb.js";import"./useDisclosurePreference-CSD3NNSj.js";import"./useSmartGuide-DB5xQ_Gx.js";import"./repeat-DtLx7W2-.js";import"./message-circle-BaAVvJru.js";import"./badge-dollar-sign-DDsaUsAf.js";import"./useCustomDomains-DP7xNCnz.js";import"./intents-B7QdDHP4.js";import"./page-language-DGjnPgNe.js";import"./actions-BENKwVac.js";import"./actions-yEkN2hqn.js";import"./state-r26xUHiu.js";import"./registry-IoY3InxL.js";import"./state-DQ0n84Dr.js";import"./select-C1j_15i9.js";import"./useSendEmail-i2nBz5Xn.js";import"./RichTextEditor-ChuVxgR7.js";import"./underline-mwsmAvFy.js";import"./sanitize-sfKXnpsX.js";import"./ellipsis-CAutlZKC.js";import"./undo-2-BA1ZMI54.js";import"./list-DGGkzBbs.js";import"./list-ordered-D8gwkM9h.js";import"./minus-DzNOUrXP.js";import"./image-CyeYP78T.js";import"./channel-experience-BEOSuJ2Q.js";import"./useBroadcast-BXeJvBXh.js";import"./useBusinessProfile-CMeAwowy.js";import"./HelpTip-Dhp2bChC.js";import"./eye-BMa0xke4.js";import"./paperclip-D1wmnOro.js";import"./instagram-B8Ezlogz.js";function $n(t){return+Ys(t)<Date.now()}const Wn={icon:Z,compact:Aa,standard:Da,expanded:La};function Ee({children:t}){return e.jsx("p",{className:"px-2 pb-1 pt-1.5 text-[10px] font-bold uppercase tracking-wider text-muted-foreground",children:t})}function Mn({widgetId:t,size:s,atTop:a,atBottom:n,onSize:i,onMove:l,onHide:r}){const o=ws(t);return e.jsxs("div",{className:"space-y-0.5",children:[o.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(Ee,{children:"Display"}),o.map(c=>{const d=Wn[c],p=c===s;return e.jsxs(x,{variant:"ghost",size:"sm",className:T("w-full justify-start gap-2 text-xs",p&&"font-semibold text-primary"),onClick:()=>i(c),children:[e.jsx(d,{className:"h-3.5 w-3.5"})," ",Ns[c],p&&e.jsx(se,{className:"ml-auto h-3.5 w-3.5"})]},c)}),e.jsx("div",{className:"my-1 border-t"})]}),e.jsx(Ee,{children:"Position"}),e.jsxs(x,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-xs",disabled:a,onClick:()=>l("up"),children:[e.jsx(Pa,{className:"h-3.5 w-3.5"})," Move up"]}),e.jsxs(x,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-xs",disabled:n,onClick:()=>l("down"),children:[e.jsx(Ra,{className:"h-3.5 w-3.5"})," Move down"]}),e.jsxs(x,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-xs",disabled:a,onClick:()=>l("top"),children:[e.jsx(Oa,{className:"h-3.5 w-3.5"})," Move to top"]}),e.jsxs(x,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-xs",disabled:n,onClick:()=>l("bottom"),children:[e.jsx($a,{className:"h-3.5 w-3.5"})," Move to bottom"]}),e.jsx("div",{className:"my-1 border-t"}),e.jsx(Ee,{children:"Visibility"}),e.jsxs(x,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-xs text-destructive",onClick:r,children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Hide widget"]})]})}function Pn({widgetId:t,children:s,className:a,isDragging:n,isDragOver:i,onDragStart:l,onDragEnd:r,onDragOver:o,onDragEnter:c,onDragLeave:d,onDrop:p}){const{widgetSizes:m,setWidgetSize:b,toggleWidget:g,moveWidget:k,enabledWidgets:N,widgetOrder:y}=De(),j=Be(t),S=Ke(t,m[t]),[C,$]=f.useState(!1),W=y.filter(G=>N.includes(G)),P=N.filter(G=>!W.includes(G)),q=[...W,...P],u=q.indexOf(t),v=u<=0,D=u===-1||u===q.length-1,K=()=>{$(!1),g(t),z.info(`"${(j==null?void 0:j.name)??t}" removed`,{action:{label:"Undo",onClick:()=>g(t)}})},R=G=>{$(!1),k(t,G)},U=G=>{$(!1),b(t,G)};return e.jsx(Qs,{delayDuration:300,children:e.jsxs("div",{draggable:!0,onDragStart:l,onDragEnd:r,onDragOver:o,onDragEnter:c,onDragLeave:d,onDrop:p,className:T("relative rounded-lg border bg-card transition-all duration-200 ease-out overflow-hidden hover:shadow-md ring-1 ring-border/50 group",nt[S],n&&"opacity-40 scale-95 ring-primary/50",i&&"ring-2 ring-primary shadow-lg shadow-primary/10",a),children:[e.jsx("div",{className:"absolute top-1.5 left-2 z-10 h-6 w-6 flex items-center justify-center rounded-md cursor-grab active:cursor-grabbing opacity-0 group-hover:opacity-100 transition-opacity hover:bg-muted",children:e.jsx(Ea,{className:"h-3.5 w-3.5 text-muted-foreground"})}),(j==null?void 0:j.description)&&S!=="icon"&&e.jsxs(Zs,{children:[e.jsx(Js,{asChild:!0,children:e.jsx("button",{className:"absolute top-1.5 right-14 z-10 h-6 w-6 flex items-center justify-center rounded-md hover:bg-muted transition-colors",children:e.jsx(Xs,{className:"h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(et,{side:"bottom",className:"max-w-[200px] text-center",children:j.description})]}),e.jsxs(st,{open:C,onOpenChange:$,children:[e.jsx(tt,{asChild:!0,children:e.jsx("button",{"aria-label":`${(j==null?void 0:j.name)??"Widget"} options`,className:T("absolute top-1.5 right-2 z-10 h-6 w-6 flex items-center justify-center rounded-md hover:bg-muted transition-colors",S==="icon"&&"opacity-0 group-hover:opacity-100 focus-visible:opacity-100"),children:e.jsx(qa,{className:"h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(at,{align:"end",className:"w-48 p-1",children:e.jsx(Mn,{widgetId:t,size:S,atTop:v,atBottom:D,onSize:U,onMove:R,onHide:K})})]}),s(S)]})})}const Rn={default:"bg-primary text-primary-foreground",warning:"bg-warning text-warning-foreground",destructive:"bg-destructive text-destructive-foreground"};function In({icon:t,label:s,route:a,badge:n,badgeTone:i="default",ariaLabel:l}){const r=n!=null&&n!==""&&n!==0;return e.jsxs(ae,{to:a,"aria-label":l??`${s} - open`,className:"flex h-full min-h-[44px] flex-col items-center justify-center gap-1.5 p-2 text-center transition-colors hover:bg-muted/50",children:[e.jsxs("span",{className:"relative flex h-11 w-11 items-center justify-center rounded-lg bg-primary/10",children:[e.jsx(t,{className:"h-5 w-5 text-primary"}),r&&e.jsx("span",{className:T("absolute -right-1 -top-1 min-w-[18px] rounded-full px-1 text-[10px] font-bold leading-[18px]",Rn[i]),children:n})]}),e.jsx("span",{className:"w-full truncate text-[11px] font-medium text-muted-foreground",children:s})]})}const ue=1e3*60*5,me=1e3*60*30;function oe(){const t=V({queryKey:["dashboard-stats"],queryFn:async()=>{var P,q;const s=Ha(new Date).toISOString(),[a,n,i,l,r,o,c]=await Promise.all([_.from("contacts").select("id",{count:"exact",head:!0}),_.from("deals").select("id, stage, value, updated_at, actual_close_date, currency, is_archived"),_.from("calls").select("id, status, created_at").gte("created_at",s),_.from("tasks").select("id, status, completed_at").eq("status","done").gte("completed_at",s),_.from("form_submissions").select("id",{count:"exact",head:!0}).gte("submitted_at",s),_.from("automation_log").select("id",{count:"exact",head:!0}).gte("created_at",s),_.from("pipeline_stages").select("key, is_won, is_lost")]),d=a.count??0,p=n.data??[],m=Fa(c.data),b=new Set(m),g=new Set((c.data??[]).filter(u=>u.is_lost).map(u=>u.key));g.size===0&&g.add("closed_lost");const k=p.filter(u=>!u.is_archived&&!b.has(u.stage)&&!g.has(u.stage)),N=za(p,{wonStageKeys:m,fromISO:s,toISO:new Date().toISOString()}),y=N.total,j=k.reduce((u,v)=>u+(Number(v.value)||0),0),S=((P=i.data)==null?void 0:P.length)??0,C=((q=l.data)==null?void 0:q.length)??0,$=r.count??0,W=o.count??0;return{totalContacts:d,openDeals:k.length,revenue:y,pipelineValue:j,callsThisMonth:S,tasksCompleted:C,formSubmissions:$,automationsFired:W,dealsWon:N.deals}},staleTime:ue,gcTime:me,placeholderData:s=>s});return it("dashboard.stats",t),t}function En(){return V({queryKey:["dashboard-tag-leaderboard"],queryFn:async()=>{const{data:t}=await _.from("contact_tags").select("tag_id, tags(id, name, color, type)");if(!t)return[];const s=new Map;for(const a of t){const n=a.tags;if(!n)continue;const i=s.get(n.id);i?i.count++:s.set(n.id,{id:n.id,name:n.name,color:n.color,type:n.type,count:1})}return Array.from(s.values()).sort((a,n)=>n.count-a.count).slice(0,10)},staleTime:ue,gcTime:me,placeholderData:t=>t})}function qn(){const t=typeof window<"u"?localStorage.getItem("preferred_pipeline"):null;return V({queryKey:["dashboard-pipeline",t],queryFn:async()=>{let s=null;if(t){const{data:r}=await _.from("pipelines").select("id").eq("id",t).maybeSingle();r&&(s=t)}if(!s){const{data:r}=await _.from("pipelines").select("id").eq("is_default",!0).maybeSingle();r&&(s=r.id)}let a={},n=[];if(s){const{data:r}=await _.from("pipeline_stages").select("key, name, position").eq("pipeline_id",s).order("position",{ascending:!0});if(r&&r.length>0){n=r.filter(o=>o.key!=="closed_won"&&o.key!=="closed_lost").map(o=>o.key);for(const o of r)a[o.key]=o.name}}n.length===0&&(n=["prospect","qualified","proposal","negotiation"],a={prospect:"Prospect",qualified:"Qualified",proposal:"Proposal",negotiation:"Negotiation"});let i=_.from("deals").select("stage, value, pipeline_id").not("stage","in","(closed_won,closed_lost)");
1s&&(i=i.eq("pipeline_id",s));const{data:l}=await i;return n.map(r=>({stage:r,label:a[r]||r,count:(l??[]).filter(o=>o.stage===r).length,value:(l??[]).filter(o=>o.stage===r).reduce((o,c)=>o+(Number(c.value)||0),0)}))},staleTime:ue,gcTime:me,placeholderData:s=>s})}function Hs(){return V({queryKey:["dashboard-activity"],queryFn:async()=>{const{data:t}=await _.from("activity_log").select("id, activity_type, description, created_at, contact_id, deal_id, user_id, metadata").order("created_at",{ascending:!1}).limit(20);return t??[]},staleTime:ue,gcTime:me,placeholderData:t=>t})}function Fn(){return V({queryKey:["dashboard-recent-contacts"],queryFn:async()=>{const{data:t}=await _.from("contacts").select("id, full_name, status, created_at, phone, email").order("created_at",{ascending:!1}).limit(5);return t??[]},staleTime:ue,gcTime:me,placeholderData:t=>t})}function zn(){return V({queryKey:["dashboard-upcoming-tasks"],queryFn:async()=>{const{data:t}=await _.from("tasks").select("id, title, due_date, priority, status, contact_id").neq("status","done").order("due_date",{ascending:!0}).limit(5);return t??[]},staleTime:ue,gcTime:me,placeholderData:t=>t})}const Hn={call_logged:Ae,deal_created:Z,deal_stage_updated:Z,task_created:de,tag_applied:_e,form_submitted:Ue,contact_created:ne,automation_notification:ge,message_sent:ye,email_sent:ks},qe=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;function Vn(t,s){const a=t.activity_type||"",n=t.metadata&&typeof t.metadata=="object"?t.metadata:{};if(a.startsWith("deal_")){const i=t.deal_id||n.deal_id;if(i&&qe.test(i))return()=>s(`/deals/${i}`)}return a.startsWith("task_")?()=>s("/tasks"):t.contact_id&&qe.test(t.contact_id)?()=>be(s,t.contact_id):t.deal_id&&qe.test(t.deal_id)?()=>s(`/deals/${t.deal_id}`):null}function Gn({size:t}){const s=I(),{data:a=[],isLoading:n}=Hs(),i=t==="compact"?3:t==="expanded"?10:5;return n?e.jsx("div",{className:"p-5 space-y-3",children:Array.from({length:4}).map((l,r)=>e.jsx(H,{className:"h-10 rounded-lg"},r))}):e.jsxs("div",{className:"p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 pr-24",children:[e.jsxs("h3",{className:"text-base font-semibold flex items-center gap-2",children:[e.jsx(ke,{className:"h-4 w-4 text-primary"})," Recent Activity"]}),e.jsxs(x,{variant:"ghost",size:"sm",onClick:()=>s("/reports"),children:["View All ",e.jsx(J,{className:"h-3 w-3 ml-1"})]})]}),a.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-muted mb-2",children:e.jsx(ke,{className:"h-5 w-5 text-muted-foreground"})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recent activity"}),e.jsx("p",{className:"text-xs text-muted-foreground/60 mt-0.5",children:"Activities will show up here as you use DuceCRM"})]}):e.jsx("div",{className:"space-y-1.5",children:a.slice(0,i).map(l=>{const r=Hn[l.activity_type]||ke,o=Vn(l,s),c=e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary/10",children:e.jsx(r,{className:"h-4 w-4 text-primary"})}),e.jsx("span",{className:"flex-1 text-sm truncate text-left",children:l.description||l.activity_type}),e.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:Es(new Date(l.created_at),"MMM d, HH:mm")})]});return o?e.jsx("button",{type:"button",onClick:o,className:"w-full flex items-center gap-3 rounded-lg p-2 hover:bg-muted/50 transition-colors cursor-pointer focus:outline-none focus:ring-2 focus:ring-ring text-left",children:c},l.id):e.jsx("div",{className:"flex items-center gap-3 rounded-lg p-2",children:c},l.id)})})]})}function Bn({size:t}){const s=I(),{data:a=[],isLoading:n}=En(),i=f.useMemo(()=>Math.max(...a.map(r=>r.count),1),[a]),l=t==="compact"?3:t==="expanded"?10:5;return n?e.jsx("div",{className:"p-5 space-y-3",children:Array.from({length:4}).map((r,o)=>e.jsx(H,{className:"h-8 rounded-lg"},o))}):t==="compact"?e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3",children:[e.jsx(_e,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Top Tags:"}),a.slice(0,3).map(r=>e.jsxs("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium",style:{backgroundColor:`${r.color}20`,color:r.color},children:[r.name," (",r.count,")"]},r.id))]}):e.jsxs("div",{className:"p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 pr-24",children:[e.jsxs("h3",{className:"text-base font-semibold flex items-center gap-2",children:[e.jsx(_e,{className:"h-4 w-4 text-primary"})," Top Tags"]}),e.jsxs(x,{variant:"ghost",size:"sm",onClick:()=>s("/reports?tab=tags"),children:[e.jsx(_s,{className:"h-3 w-3 mr-1"})," Analytics"]})]}),a.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-muted mb-2",children:e.jsx(_e,{className:"h-5 w-5 text-muted-foreground"})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No tags yet"}
1),e.jsx("p",{className:"text-xs text-muted-foreground/60 mt-0.5",children:"Tag contacts to see your most-used tags here"})]}):e.jsx("div",{className:"space-y-2",children:a.slice(0,l).map(r=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium shrink-0",style:{backgroundColor:`${r.color}20`,color:r.color,border:`1px solid ${r.color}40`},children:r.name}),e.jsx("div",{className:"flex-1 h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${r.count/i*100}%`,backgroundColor:r.color}})}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground w-6 text-right",children:r.count})]},r.id))})]})}function Kn(t){return t>=1e6?`â¦${(t/1e6).toFixed(1)}M`:t>=1e3?`â¦${(t/1e3).toFixed(0)}K`:`â¦${t.toLocaleString()}`}function Un({size:t}){const s=I(),{data:a=[],isLoading:n}=qn();return n?e.jsx("div",{className:"p-5 space-y-3",children:Array.from({length:4}).map((i,l)=>e.jsx(H,{className:"h-12 rounded-lg"},l))}):t==="compact"?e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3",children:[e.jsx(Z,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Pipeline:"}),a.map(i=>e.jsxs("span",{className:"text-xs",children:[i.label," ",e.jsx("strong",{className:"font-display",children:i.count})]},i.stage))]}):e.jsxs("div",{className:"p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 pr-24",children:[e.jsxs("h3",{className:"text-base font-semibold flex items-center gap-2",children:[e.jsx(Z,{className:"h-4 w-4 text-primary"})," Pipeline Snapshot"]}),e.jsxs(x,{variant:"ghost",size:"sm",onClick:()=>s("/pipeline"),children:["View Board ",e.jsx(J,{className:"h-3 w-3 ml-1"})]})]}),e.jsx("div",{className:"space-y-2",children:a.map(i=>
1e.jsxs("div",{className:"flex items-center gap-4 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:i.label}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[i.count," deal",i.count!==1?"s":""]})]}),e.jsx("span",{className:"text-sm font-bold font-display text-primary",children:Kn(i.value)})]},i.stage))})]})}function Yn({size:t}){const s=I(),{data:a=[],isLoading:n}=zn();return n?e.jsx("div",{className:"p-5 space-y-3",children:Array.from({length:3}).map((i,l)=>e.jsx(H,{className:"h-14 rounded-lg"},l))}):t==="compact"?e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3",children:[e.jsx(de,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Tasks:"}),e.jsxs("span",{className:"text-sm font-bold font-display",children:[a.length," pending"]})]}):e.jsxs("div",{className:"p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 pr-24",children:[e.jsxs("h3",{className:"text-base font-semibold flex items-center gap-2",children:[e.jsx(de,{className:"h-4 w-4 text-primary"})," Upcoming Tasks"]}),e.jsxs(x,{variant:"ghost",size:"sm",onClick:()=>s("/tasks"),children:["View All ",e.jsx(J,{className:"h-3 w-3 ml-1"})]})]}),a.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-muted mb-2",children:e.jsx(de,{className:"h-5 w-5 text-muted-foreground"})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No pending tasks"}),e.jsx("p",{className:"text-xs text-muted-foreground/60 mt-0.5",children:"Tasks you create will appear here"})]}):e.jsx("div",{className:"space-y-2",children:a.map(i=>{const l=i.due_date&&$n(new Date(i.due_date))&&!cs(new Date(i.due_date)),r=i.due_date&&cs(new Date(i.due_date));return e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border p-3",children:[e.jsx("div",{className:T("mt-1 h-2 w-2 rounded-full shrink-0",i.priority==="high"?"bg-destructive":i.priority==="medium"?"bg-warning":"bg-muted-foreground")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:i.title}),e.jsx("p",{className:T("text-xs text-muted-foreground",l&&"text-destructive font-medium",r&&"text-warning font-medium"),children:i.due_date?l?"Overdue":r?"Due today":Es(new Date(i.due_date),"MMM d, h:mm a"):"No due date"})]})]},i.id)})})]})}const ds=[{label:"Add Contact",icon:ne,bgClass:"bg-pink-500/10",iconClass:"text-pink-500",pillClass:"border-pink-500/30 bg-pink-500/5 hover:bg-pink-500/10",path:"/contacts"},{label:"Send Email",icon:ks,bgClass:"bg-primary/10",iconClass:"text-primary",pillClass:"border-primary/30 bg-primary/5 hover:bg-primary/10",path:"/campaigns"},{label:"Create Task",icon:de,bgClass:"bg-blue-500/10",iconClass:"text-blue-500",pillClass:"border-blue-500/30 bg-blue-500/5 hover:bg-blue-500/10",path:"/tasks"},{label:"Make Call",icon:Ae,bgClass:"bg-green-500/10",iconClass:"text-green-500",pillClass:"border-green-500/30 bg-green-500/5 hover:bg-green-500/10",path:"/calls"},{label:"Add deal",icon:Z,bgClass:"bg-purple-500/10",iconClass:"text-purple-500",pillClass:"border-purple-500/30 bg-purple-500/5 hover:bg-purple-500/10",path:"/pipeline"},{label:"Create Form",icon:Ue,bgClass:"bg-orange-500/10",iconClass:"text-orange-500",pillClass:"border-orange-500/30 bg-
1orange-500/5 hover:bg-orange-500/10",path:"/forms"}];function Qn({size:t}){const s=I();return t==="compact"?e.jsx("div",{className:"flex items-center gap-2 px-4 py-3 overflow-x-auto",children:ds.map(a=>e.jsxs("button",{onClick:()=>s(a.path),className:`flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors shrink-0 ${a.pillClass}`,children:[e.jsx(a.icon,{className:`h-3.5 w-3.5 ${a.iconClass}`}),a.label]},a.label))}):e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"text-base font-semibold mb-3",children:"Quick Actions"}),e.jsx("div",{className:"flex gap-3 overflow-x-auto pb-1",children:ds.map(a=>e.jsxs("button",{onClick:()=>s(a.path),className:"flex flex-col items-center gap-2 rounded-lg border p-4 hover:bg-muted/50 transition-colors min-w-[90px] shrink-0",children:[e.jsx("div",{className:`flex h-10 w-10 items-center justify-center rounded-full ${a.bgClass}`,children:e.jsx(a.icon,{className:`h-5 w-5 ${a.iconClass}`})}),e.jsx("span",{className:"text-xs font-medium",children:a.label})]},a.label))})]})}const us={default:"text-foreground",warning:"text-warning",destructive:"text-destructive",success:"text-success"};function E({icon:t,name:s,size:a,isLoading:n,value:i,valueLabel:l,valueHref:r,valueTone:o="default",children:c,extra:d,viewHref:p,viewLabel:m="View",className:b}){const g=a==="standard"||a==="expanded",k=a==="expanded",N=i!==void 0&&e.jsxs("div",{children:[n?e.jsx(H,{className:"h-7 w-20"}):r?e.jsx(ae,{to:r,className:"hover:underline underline-offset-2",children:e.jsx("span",{className:T("font-display text-2xl font-semibold leading-none tabular-nums",us[o]),children:i})}):e.jsx("span",{className:T("font-display text-2xl font-semibold leading-none tabular-nums",us[o]),children:i}),l&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:l})]});return e.jsxs("div",{className:T("flex h-full flex-col gap-2.5 p-4",b),children:[e.jsxs("div",{className:"flex items-center gap-2 pr-16",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(t,{className:"h-4 w-4 text-primary"})}),e.jsx("p",{className:"min-w-0 truncate text-[11px] font-bold uppercase tracking-wider text-muted-foreground",children:s})]}),N,g&&c,k&&d,p&&g&&e.jsx("div",{className:"mt-auto flex items-center pt-1",children:e.jsxs(ae,{to:p,className:"ml-auto inline-flex items-center gap-1 text-xs font-semibold text-primary hover:underline underline-offset-2",children:[m," ",e.jsx(J,{className:"h-3 w-3"})]})})]})}function Zn(t){return t>=1e6?`â¦${(t/1e6).toFixed(1)}M`:t>=1e3?`â¦${(t/1e3).toFixed(0)}K`:`â¦${t.toLocaleString()}`}function Jn({size:t}){const{data:s,isLoading:a}=oe();return e.jsx(E,{icon:Cs,name:"Revenue",size:t,isLoading:a,value:Zn((s==null?void 0:s.revenue)??0),valueLabel:"Won this month",valueTone:"success",viewHref:"/reports",viewLabel:"View reports",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"Value of deals won since the 1st."})})}function Xn({size:t}){const{data:s,isLoading:a}=oe();return e.jsx(E,{icon:Z,name:"Open deals",size:t,isLoading:a,value:String((s==null?void 0:s.openDeals)??0),valueLabel:"Still in play",valueHref:"/pipeline",viewHref:"/pipeline",viewLabel:"View pipeline",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"Deals that have not been won or lost yet."})})}function ei({size:t}){const{data:s,isLoading:a}=oe();return e.jsx(E,{icon:ne,name:"Customers",size:t,isLoading:a,value:((s==null?void 0:s.totalContacts)??0).toLocaleString(),valueLabel:"People in your address book",valueHref:"/contacts",viewHref:"/contacts",viewLabel:"View customers",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"Everyone you can call, message or invoice."})})}function Fe(t){return t>=1e6?`â¦${(t/1e6).toFixed(1)}M`:t>=1e3?`â¦${(t/1e3).toFixed(0)}K`:`â¦${t.toLocaleString()}`}function si({icon:t,label:s,value:a,iconClass:n}){return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(t,{className:`h-4 w-4 ${n??"text-primary"}`})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:s}),e.jsx("p",{className:"text-sm font-bold font-display",children:a})]})]})}function ti({size:t}){const{data:s,isLoading:a}=oe(),n=(s==null?void 0:s.dealsWon)??0;return e.jsx(E,{icon:rt,name:"Deals won",size:t,isLoading:a,value:String(n),valueLabel:"closed this month",valueTone:n>
10?"success":"default",valueHref:"/pipeline?status=won",viewHref:"/pipeline?status=won",viewLabel:"View won deals",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:n>0?"Well done - keep the momentum going.":"Nothing closed yet this month."})})}function ai({size:t}){const{data:s,isLoading:a}=oe(),n=(s==null?void 0:s.callsThisMonth)??0;return e.jsx(E,{icon:Ae,name:"Calls",size:t,isLoading:a,value:String(n),valueLabel:"logged this month",viewHref:"/inbox?channel=calls",viewLabel:n>0?"View calls":"Log a call",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:n>0?"Every call logged against a customer this month.":"No calls logged yet - log one from any customer record."})})}function ni({size:t}){const{data:s,isLoading:a}=oe(),n=(s==null?void 0:s.automationsFired)??0;return e.jsx(E,{icon:ge,name:"Automation",size:t,isLoading:a,value:String(n),valueLabel:"automatic actions this month",viewHref:"/automation",viewLabel:n>0?"View automation":"Set up automation",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:n>0?"Work DuceCRM did for you without anyone clicking.":"Nothing running yet - let DuceCRM handle the repeat work."})})}function ii({size:t}){const{data:s=[],isLoading:a}=Hs(),n=t==="expanded"?8:5;return e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2 mb-2",children:[e.jsx(ot,{className:"h-4 w-4 text-primary"})," Team Activity"]}),a?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(i=>e.jsx(H,{className:"h-6 rounded-md"},i))}):s.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No recent activity"}):e.jsx("div",{className:"space-y-1",children:s.slice(0,n).map(i=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-md px-2 py-1.5 hover:bg-muted/50 transition-colors",children:[e.jsx("span",{className:"text-xs truncate flex-1",children:i.description||i.activity_type.replace(/_/g," ")}),e.jsx("span",{className:"text-[10px] text-muted-foreground shrink-0",children:i.created_at?qs(i.created_at):""})]},i.id))})]})}function oi({size:t}){const{data:s,isLoading:a}=oe();return e.jsx(E,{icon:_s,name:"Revenue trend",size:t,isLoading:a,value:Fe((s==null?void 0:s.revenue)??0),valueLabel:"won this month",valueTone:"success",viewHref:"/reports",viewLabel:"View reports",extra:e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Pipeline still open: ",e.jsx("strong",{className:"font-display",children:Fe((s==null?void 0:s.pipelineValue)??0)})]}),children:e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Still in the pipeline: ",e.jsx("strong",{className:"font-display text-foreground",children:Fe((s==null?void 0:s.pipelineValue)??0)})]})})}function ri({size:t}){const{data:s,isLoading:a}=Fn(),n=I();return e.jsxs("div",{className:"p-5",children:[e.jsxs("h3",{className:"text-base font-semibold mb-3 flex items-center gap-2",children:[e.jsx(ne,{className:"h-4 w-4 text-primary"})," Recent Contacts"]}),a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(i=>e.jsxs("div",{className:"flex items-center gap-3 animate-pulse",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted"}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("div",{className:"h-3 w-24 rounded bg-muted"}),e.jsx("div",{className:"h-2.5 w-16 rounded bg-muted"})]})]},i))}):s!=null&&s.length?e.jsx("div",{className:"space-y-2.5",children:s.slice(0,t==="expanded"?8:5).map(i=>e.jsxs("button",{type:"button",onClick:()=>be(n,i.id),className:"w-full flex items-center gap-3 rounded-md px-2 py-1.5 -mx-2 text-left hover:bg-muted/50 transition-colors cursor-pointer focus:outline-none focus:ring-2 focus:ring-ring",children:[e.jsx(es,{name:i.full_name,size:"sm"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:i.full_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:qs(i.created_at)})]}),e.jsx(Ga,{status:i.status})]},i.id))}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No contacts yet - add your first one"})]})}function li({size:t}){const{data:s,isLoading:a}=Va(),n=I();return t==="compact"?e.jsx(si,{icon:is,label:"Contact Groups",value:a?"-":(s==null?void 0:s.length)??0}):e.jsxs("div",{className:"p-5",children:[e.jsxs("h3",{className:"text-base font-semibold mb-3 flex items-center gap-2",children:[e.jsx(is,{className:"h-4 w-4 text-primary"})," Contact Groups"]}),a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(i=>e.jsxs("div",{className:"flex items-center gap-3 animate-pulse",children:[e.jsx("div",{className:"h-3 w-3 rounded-full bg-muted"}),e.jsx("div",{className:"h-3 w-24 rounded bg-muted"})]},i))}):s!=null&&s.length?e.jsxs("div",{className:"space-y-2",children:[s.slice(0,t==="expanded"?8:5).map(i=>e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"h-3 w-3 rounded-full shrink-0",style:{backgroundColor:i.color}}),e.jsx("span",{className:"text-sm font-medium truncate flex-1",children:i.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:i.member_count??0})]},i.id)),e.jsx("button",{onClick:()=>n("/contacts"),className:"text-xs text-primary hover:underline mt-1",children:"View all"})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No groups yet"})]})}function ci({size:t}){var r;const{profile:s}=ve(),a=s==null?void 0:s.org_id,{data:n=[],isLoading:i}=V({queryKey:["team-leaderboard-widget",a],queryFn:async()=>
1{if(!a)return[];const{data:o}=await _.from("loyalty_summary").select("*").eq("org_id",a).order("monthly_points",{ascending:!1}).limit(5);if(!o||o.length===0)return[];const c=o.map(m=>m.user_id),{data:d}=await _.from("users").select("auth_id, full_name, avatar_url").in("auth_id",c),p=new Map((d||[]).map(m=>[m.auth_id,m]));return o.filter(m=>m.monthly_points>0).map((m,b)=>{const g=p.get(m.user_id);return{id:m.user_id,name:(g==null?void 0:g.full_name)||"Unknown",avatar:(g==null?void 0:g.avatar_url)||null,monthlyPoints:Number(m.monthly_points),tier:m.tier||"bronze",rank:m.rank||b+1}})},enabled:!!a,staleTime:3e4,placeholderData:o=>o});if(i)return e.jsx("div",{className:"space-y-3 p-1",children:[1,2,3].map(o=>e.jsx(H,{className:"h-10 w-full rounded"},o))});if(n.length===0)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-6 text-muted-foreground",children:[e.jsx(lt,{className:"h-8 w-8 mb-2 opacity-40"}),e.jsx("p",{className:"text-sm",children:"No activity this month yet"})]});const l=((r=n[0])==null?void 0:r.monthlyPoints)||1;return e.jsx("div",{className:"space-y-2.5",children:n.map((o,c)=>{const d=Math.round(o.monthlyPoints/l*100),p=o.tier==="gold"?"[&>div]:bg-amber-500":o.tier==="silver"?"[&>div]:bg-slate-400":"[&>div]:bg-orange-400";return e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"w-5 shrink-0 text-center",children:c===0?e.jsx(Wa,{className:"h-4 w-4 text-amber-500 mx-auto"}):e.jsx("span",{className:"text-xs font-bold text-muted-foreground",children:o.rank})}),e.jsxs(ct,{className:"h-7 w-7 shrink-0",children:[e.jsx(dt,{src:o.avatar||""}),e.jsx(ut,{className:"text-[10px] bg-muted",children:o.name.split(" ").map(m=>m[0]).join("").toUpperCase().slice(0,2)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-1",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:o.name}),e.jsxs("span",{className:"text-xs font-semibold text-foreground shrink-0",children:[o.monthlyPoints," pts"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[e.jsx(Oe,{value:d,className:`h-1.5 flex-1 ${p}`}),e.jsx("span",{className:"text-[10px] text-muted-foreground capitalize w-10 text-right",children:o.tier})]})]})]},o.id)})})}function di({size:t}){const s=ie(),a=I(),n=t==="expanded"?8:4,{data:i=[],isLoading:l}=V({queryKey:["retention-alerts",s,n],queryFn:async()=>{if(!s)return[];const o=new Date(Date.now()-14*864e5).toISOString(),{data:c,error:d}=await _.from("contacts").select("id, full_name, email, phone, last_interaction_at, avatar_url").eq("org_id",s).eq("status","customer").or(`last_interaction_at.is.null,last_interaction_at.lt.${o}`).order("last_interaction_at",{ascending:!0,nullsFirst:!0}).limit(n);if(d)throw d;return c||[]},enabled:!!s}),r=o=>o?`${Math.floor((Date.now()-new Date(o).getTime())/864e5)} days ago`:"Never contacted";return e.jsx(E,{icon:Ss,name:"Going cold",size:t,isLoading:l,value:String(i.length),valueLabel:"customers with no contact in 14 days",valueTone:i.length>0?"warning":"success",viewHref:"/customer-care",viewLabel:"Open Customer Care",children:l?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(o=>e.jsx(H,{className:"h-10 rounded-lg"},o))}):i.length===0?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Ba,{className:"h-4 w-4","aria-hidden":"true"}),"Everyone has been spoken to recently."]}):e.jsx("div",{className:"space-y-2",children:i.map(o=>e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border px-3 py-2 hover:bg-muted/50 transition-colors cursor-pointer",onClick:()=>be(a,o.id),children:[e.jsx(es,{name:o.full_name,avatarUrl:o.avatar_url,size:"sm"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:o.full_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r(o.last_interaction_at)})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(x,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:c=>{c.stopPropagation(),be(a,o.id)},title:"Send a message",children:e.jsx(ye,{className:"h-3.5 w-3.5"})}),e.jsx(x,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:c=>{c.stopPropagation(),a(`/tasks?action=create&contact=${o.id}`)},title:"Create a follow-up task",children:e.jsx(mt,{className:"h-3.5 w-3.5"})})]})]},o.id))})})}function ui({size:t}){const{data:s,isLoading:a}=V({queryKey:["customer-success-stats"],queryFn:async()=>{const[l,r,o]=await Promise.all([_.from("support_tickets").select("id, status",{count:"exact"}).in("status",["open","in_progress"]),_.from("nps_surveys").select("score"),_.from("contacts").select("id, last_interaction_at, status").eq("status","customer")]),c=l.count??0,d=r.data??[],p=Ka(d.map(g=>({...g,id:"",org_id:"",contact_id:"",survey_type:"nps",feedback:null,sent_at:"",responded_at:null,sent_by:null,created_at:""}))),m=new Date,b=(o.data??[]).filter(g=>g.last_interaction_at?m.getTime()-new Date(g.last_interaction_at).getTime()>14*24*60*60*1e3:!0).length;return{openTickets:c,nps:p,atRisk:b,totalSurveys:d.length}},staleTime:3e4}),n=s??{openTickets:0,nps:0,atRisk:0,totalSurveys:0},i=[{icon:Ce,label:"Satisfaction score",value:String(n.nps),tone:"bg-primary/10 text-primary"},{icon:Se,label:"Open complaints",value:String(n.openTickets),tone:"bg-warning/10 text-warning"},{icon:$e,label:"At risk",value:String(n.atRisk),tone:"bg-destructive/10 text-destructive"},{icon:Ye,label:"Surveys sent",value:String(n.totalSurveys),tone:"bg-success/10 text-success"}];return e.jsx(E,{icon:Se,name:"Customer care",size:t,isLoading:a,value:String(n.openTickets),valueLabel:n.openTickets===1?"customer waiting on you":"customers waiting on you",valueTone:n.openTickets>0?"warning":"success",valueHref:"/customer-care",viewHref:"/customer-care",viewLabel:"Open Customer Care",children:e.jsx("div",{className:"grid grid-cols-2 gap-2",children:i.slice(0,4).map(l=>e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border p-2",children:[e.jsx("span",{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-full ${l.tone}`,children:e.jsx(l.icon,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-display text-sm font-bold tabular-nums",children:l.value}),e.jsx("p",{className:"truncate text-[10px] text-muted-foreground",children:l.label})]})]},l.label))})})}const mi={upsell_opportunity:{label:"Upsell",icon:Ce,variant:"success"},cross_sell:{label:"Cross-Sell",icon:pt,variant:"info"},renewal_risk:{label:"Risk",icon:$e,variant:"danger"}
1,after_sale:{label:"Follow-Up",icon:Ye,variant:"warning"},sales_opportunity:{label:"Sales Opp",icon:Cs,variant:"success"},customer_event:{label:"Event",icon:Ua,variant:"info"},news_mention:{label:"News",icon:Ma,variant:"warning"}};function pi({size:t}){const s=ie(),a=I(),{data:n=[]}=V({queryKey:["duce-signals-widget",s],queryFn:async()=>{if(!s)return[];const{data:i,error:l}=await _.from("intel_signals").select("id, title, description, signal_type, severity, created_at, contact_id, contacts!inner(id, full_name, avatar_url)").eq("org_id",s).or("signal_type.in.(upsell_opportunity,cross_sell,renewal_risk,after_sale,sales_opportunity,customer_event,news_mention),severity.in.(opportunity,risk)").order("created_at",{ascending:!1}).limit(5);if(l)throw l;return i||[]},enabled:!!s,staleTime:3e4});return t==="compact"?e.jsxs("div",{className:"flex items-center justify-center h-full gap-2",children:[e.jsx(ge,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"text-2xl font-bold",children:n.length}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"signals"})]}):n.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center p-4",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center mb-2",children:e.jsx(ge,{className:"h-5 w-5 text-primary"})}),e.jsx("p",{className:"text-sm font-medium",children:"No high-priority signals yet"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Signals will appear here as DuceIntel discovers them"})]}):e.jsx("div",{className:"space-y-2",children:n.map(i=>{const l=mi[i.signal_type]??{label:i.signal_type,icon:ge,variant:"info"},r=l.icon,o=i.contacts;return e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border px-3 py-2 hover:bg-muted/50 transition-colors cursor-pointer",onClick:()=>be(a,i.contact_id,{tab:"intelligence"}),children:[e.jsx(es,{name:(o==null?void 0:o.full_name)??"Unknown",avatarUrl:o==null?void 0:o.avatar_url,size:"sm"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:i.title}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[(o==null?void 0:o.full_name)??"Unknown"," · ",xt(new Date(i.created_at),{addSuffix:!0})]})]}),e.jsxs(We,{variant:l.variant,className:"shrink-0 text-[10px]",children:[e.jsx(r,{className:"h-3 w-3 mr-1"}),l.label]})]},i.id)})})}function xi({size:t}){const s=ie(),a=I(),{data:n=[]}=Ya(s||void 0),i=n.reduce((d,p)=>d+Number(p.commission_amount),0),l=n.filter(d=>d.status==="pending").reduce((d,p)=>d+Number(p.commission_amount),0),r=n.filter(d=>d.status==="approved").reduce((d,p)=>d+Number(p.commission_amount),0),o=n.filter(d=>d.status==="paid").reduce((d,p)=>d+Number(p.commission_amount),0),c=r>=5e4;return t==="compact"?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground flex items-center gap-1",children:[e.jsx(Ce,{className:"h-3 w-3"})," Total Earned"]}),e.jsx("p",{className:"text-2xl font-bold text-primary leading-tight",children:le(i)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-success/30 bg-success/10 px-2 py-1.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-success font-semibold",children:"Ready to Pay Out"}),e.jsx("p",{className:"text-sm font-bold text-success truncate",children:le(r)})]}),c&&e.jsx(J,{className:"h-3.5 w-3.5 text-success shrink-0 cursor-pointer",onClick:()=>a("/commissions")})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-lg border border-primary/20 bg-primary/5 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[e.jsx(Ce,{className:"h-3.5 w-3.5 text-primary"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-medium",children:"Total Earned"})]}),e.jsx("p",{className:"text-xl font-bold text-primary leading-tight",children:le(i)})]}),e.jsxs("div",{className:"rounded-lg border border-success/30 bg-success/10 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[e.jsx(Qa,{className:"h-3.5 w-3.5 text-success"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-success font-semibold",children:"Ready to Pay Out"})]}),e.jsx("p",{className:"text-xl font-bold text-success leading-tight",children:le(r)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-lg border bg-card/60 p-2.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[e.jsx(Qe,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Pending"})]}),e.jsx("p",{className:"text-sm font-semibold",children:le(l)})]}),e.jsxs("div",{className:"rounded-lg border bg-card/60 p-2.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[e.jsx(Za,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Paid"})]}),e.jsx("p",{className:"text-sm font-semibold",children:le(o)})]})]}),e.jsxs(x,{variant:"ghost",size:"sm",className:"w-full h-7 text-xs gap-1 text-primary hover:text-primary",onClick:()=>a("/commissions"),children:["View My Commissions ",e.jsx(J,{className:"h-3 w-3"})]})]})}function hi({size:t}){I();const s=Ja(),{data:a}=en(),{data:n=[]}=sn(),{balance:i}=tn(),l=n.filter(d=>d.status==="qualified").length,r=l%5/5*100,o=5-l%5,c=()=>{a&&(navigator.clipboard.writeText(an(a.code)),z.success("Referral link copied!"))};return e.jsx("div",{className:"h-full",children:e.jsxs("div",{className:"pt-4 pb-3 px-4 h-full flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ye,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-semibold",children:"Refer & Earn"})]}),i>0&&e.jsxs("span",{className:"text-xs font-medium text-success",children:["â¦",i.toLocaleStr
1ing()," credit"]})]}),e.jsxs("div",{className:"space-y-2 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[l%5,"/5 to next â¦9,000 reward"]}),e.jsxs("span",{children:[o," more"]})]}),e.jsx(Oe,{value:r,className:"h-2"})]}),t!=="compact"&&e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(x,{variant:"outline",size:"sm",className:"flex-1 text-xs",onClick:c,children:[e.jsx(ht,{className:"h-3 w-3 mr-1"})," Copy Link"]}),e.jsx(x,{variant:"ghost",size:"sm",className:"text-xs",onClick:()=>s({section:"referrals"}),children:e.jsx(J,{className:"h-3 w-3"})})]})]})})}function ms({active:t}){return t?e.jsxs("span",{className:"relative flex h-2 w-2","aria-label":"Live",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full rounded-full bg-emerald-500 opacity-60 animate-ping"}),e.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-emerald-500"})]}):e.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/40","aria-hidden":!0})}function fi({size:t}){const s=I();nn();const{data:a,isLoading:n}=on(),i=a??cn,{data:l=[],isLoading:r}=rn({status:"all"}),o=ln(),c=i.now.active,d=i.now.online>0,p=dn(i),m=()=>s("/inbox?channel=livechat&view=visitors"),b=async y=>{try{await o.mutateAsync(y)?s(`/inbox?channel=livechat&view=visitors&visitor=${y}`):z.error("Already claimed by another rep")}catch{z.error("Couldn't engage visitor")}};if(t==="compact")return e.jsxs("button",{type:"button",onClick:m,className:"flex items-center gap-3 px-4 py-3 w-full text-left hover:bg-muted/50 transition-colors rounded-lg","aria-label":"View live visitors",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(ne,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Live Visitors"}),e.jsx(ms,{active:c>0})]}),e.jsxs("p",{className:"text-sm font-bold font-display tabular-nums",children:[n?"â":`${i.now.online} online`,e.jsx("span",{className:"ml-1.5 text-xs font-normal text-muted-foreground",children:n?"":`· ${i.today.visits} ${i.today.visits===1?"visit":"visits"} today`})]})]})]});const g=e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2 min-w-0",children:[e.jsx(ne,{className:"h-4 w-4 text-primary shrink-0"}),e.jsx("span",{className:"truncate",children:"Live Visitors"}),e.jsx(ms,{active:c>0})]}),e.jsxs(x,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs shrink-0",onClick:m,children:["View all",e.jsx(ze,{className:"h-3 w-3 ml-1"})]})]}),k=n?e.jsx(H,{className:"h-20 w-full"}):e.jsx(un,{analytics:i});if(t==="standard")return e.jsxs("div",{className:"p-4",children:[g,k]});const N=l.filter(y=>y.status==="active"||y.status==="idle").slice(0,3);return e.jsxs("div",{className:"p-4 flex flex-col h-full",children:[g,k,e.jsxs("div",{className:"mt-3 pt-3 border-t flex-1 min-h-0 flex flex-col",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1.5",children:"Hottest right now"}),r?e.jsx("div",{className:"space-y-1.5",children:[0,1,2].map(y=>e.jsx(H,{className:"h-9 w-full"},y))}):d?e.jsx("div",{className:"space-y-1 overflow-y-auto",children:N.map(y=>{const j=[y.city,y.country].filter(Boolean).join(", ")||"Unknown",S=y.current_page_title||y.current_page||"â",C=Math.max(1,Math.round((y.total_time_seconds||0)/60));return e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium",children:[e.jsx(mn,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsx("span",{className:"truncate",children:j})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground truncate",title:S,children:[S," · ",C,"m · ",y.page_count,"p"]})]}),e.jsx(x,{size:"sm",variant:"outline",className:"h-7 px-2 text-[11px] shrink-0",onClick:()=>b(y.id),disabled:o.isPending,"aria-label":`Engage visitor in ${j}`,children:"Engage"})]},y.id)})}):e.jsxs("div",{className:"flex flex-col items-center justify-center flex-1 text-center py-3",children:[e.jsx("p",{className:"text-xs font-medium",children:p.title}),p.detail&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:p.detail}),p.showInstallCheck?e.jsx("button",{type:"button",onClick:()=>s("/settings/livechat"),className:"text-[11px] text-primary hover:underline mt-0.5",children:"Check installation"}):e.jsx("button",{type:"button",onClick:m,className:"text-[11px] text-primary hover:underline mt-0.5",children:"See recent visitors"})]})]})]})}const Te="/customer-care?tab=attention&view=reminders",Pe="/customer-care?tab=attention&view=reminders&ftab=insights";function gi({size:t}){var i;const{data:s,isLoading:a}=Fs({scope:"all",state:"open",page:0}),n=((i=s==null?void 0:s.counts)==null?void 0:i.due_today)??0;return e.jsx(E,{icon:Qe,name:"Due today",size:t,isLoading:a,value:String(n),valueLabel:n===1?"customer to contact today":"customers to contact today",valueTone:n>0?"warning":"default",valueHref:Te,viewHref:Te,viewLabel:"Open queue",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:n>0?"Reach these people before the day ends.":"Nothing due today - you are up to date."})})}function yi({size:t}){var i;const{data:s,isLoading:a}=Fs({scope:"all",state:"open",page:0}),n=((i=s==null?void 0:s.counts)==null?void 0:i.overdue)??0;return e.jsx(E,{icon:$e,name:"Overdue",size:t,isLoading:a,value:String(n),valueLabel:n===1?"follow-up has slipped":"follow-ups have slipped",valueTone:n>0?"destructive":"success",valueHref:Te,viewHref:Te,viewLabel:"Open queue",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:n>0?"These customers are waiting longer than you promised.":"Nothing overdue."})})}function vi({size:t}){const{data:s,isLoading:a}=je(30),n=(s==null?void 0:s.customer_health_pct)??100;return e.jsx(E,{icon:Ss,name:"Customer health",size:t,isLoading:a,value:`${n}%`,valueLabel:"contacted inside their expected window",valueTone:n>=80?"success":n>=50?"warning":"destructive",viewHref:Pe,viewLabel:"See care insights",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days across every customer you look after."})})}function bi({size:t}){const{data:s,isLoading:a}=je(30),n=(s==null?void 0:s.completion_rate_pct)??(s==null?void 0:s.compliance_pct)??0;return e.jsx(E,{icon:ft,name:"Follow-ups cleared",size:t,isLoading:a,value:`${n}%`,valueLabel:"of the follow-up queue completed",valueTone:n>=70?"success":"warning",viewHref:Pe,viewLabel:"See care insights",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days."})})}function ji({size:t}){const{data:s,isLoading:a}=je(30),n=(s==null?void 0:s.avg_first_response_hours)??(s==null?void 0:s.avg_response_hours)??0;return e.jsx(E,{icon:pn,name:"Response time",size:t,isLoading:a,value:`${n}h`,valueLabel:"average first reply",valueTone:n<=4?"success":n<=24?"warning":"destructive",viewHref:Pe,viewLabel:"See care insights",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"How long a customer waits for your first answer."})})}function wi({size:t}){const{data:s,isLoading:a}=je(30),n=(s==null?void 0:s.recovery_rate_pct)??0;return e.jsx(E,{icon:Se,name:"Customers recovered",size:t,isLoading:a,value:`${n}%`,valueLabel:"of at-risk customers brought back",valueTone:n>=50?"success":"warning",viewHref:Pe,viewLabel:"See care insights",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days."})})}function Ni({values:t,className:s,height:a=40}){const n=f.useId();if(t.length<2)return null;const i=100,l=Math.max(...t),r=Math.min(...t),o=l-r||1,c=i/(t.length-1),d=t.map((p,m)=>{const b=m*c,g=a-(p-r)/o*(a-6)-3;return`${b.toFixed(2)},${g.toFixed(2)}`});return e.jsxs("svg",{viewBox:`0 0 ${i} ${a}`,preserveAspectRatio:"none",className:s,"aria-hidden":"true",focusable:"false",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:n,x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:"0.25"}),e.jsx("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:"0"})]})}),e.jsx("polygon",{points:`0,${a} ${d.join(" ")} ${i},${a}`,fill:`url(#${n})`}),e.jsx("polyline",{points:d.join(" "),fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:"non-scaling-stroke"}),e.jsx("circle",{cx:i,cy:d[d.length-1].split(",")[1],r:"2",fill:"
1currentColor"})]})}const ki={default:"text-foreground",warning:"text-warning",destructive:"text-destructive",success:"text-success"};function ps({metric:t,className:s}){const a=e.jsx("span",{className:T("font-semibold tabular-nums",ki[t.tone??"default"],s),children:t.value});return t.href?e.jsx(ae,{to:t.href,className:"hover:underline underline-offset-2",children:a}):a}function Q({icon:t,name:s,primary:a,supporting:n=[],alert:i,quickLinks:l=[],viewHref:r,viewLabel:o="View",size:c="standard",isLoading:d,trend:p=[],changePercent:m=null,changeLabel:b="vs last 7 days"}){const g=c==="standard"||c==="expanded",k=c==="expanded",N=n.slice(0,k?3:2),y=(m??0)>=0,j=y?xn:Ta,S=c!=="icon"&&p.length>1;return e.jsxs("div",{className:"flex h-full flex-col gap-2.5 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2.5 pr-16",children:[e.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-primary/10 ring-1 ring-inset ring-primary/20",children:e.jsx(t,{className:"h-4 w-4 text-primary"})}),e.jsx("p",{className:"min-w-0 truncate text-sm font-semibold text-foreground",children:s})]}),d?e.jsx(H,{className:"h-10 w-28"}):e.jsxs("div",{className:"flex items-end justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(ps,{metric:a,className:"text-3xl leading-none font-display tracking-tight"}),e.jsx("p",{className:"mt-1.5 truncate text-xs text-muted-foreground",children:a.label}),m!==null&&e.jsxs("p",{className:"mt-1.5 flex items-center gap-1 text-xs",children:[e.jsxs("span",{className:T("inline-flex items-center gap-0.5 font-semibold",y?"text-success":"text-destructive"),children:[e.jsx(j,{className:"h-3.5 w-3.5"}),Math.abs(m),"%"]}),e.jsx("span",{className:"truncate text-muted-foreground",children:b})]})]}),S&&e.jsx(Ni,{values:p,height:40,className:T("h-10 w-24 shrink-0 self-end",m!==null&&!y?"text-destructive":"text-primary")})]}),g&&N.length>0&&e.jsx("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground",children:d?e.jsx(H,{className:"h-4 w-40"}):N.map(C=>e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ps,{metric:C,className:"text-sm"}),e.jsx("span",{children:C.label})]},C.label))}),k&&i&&e.jsxs(ae,{to:i.href??r,className:"inline-flex items-center gap-1.5 rounded-md bg-warning/10 px-2 py-1.5 text-xs font-medium text-warning hover:bg-warning/15 transition-colors",children:[e.jsx($e,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate",children:i.label})]}),g&&e.jsxs("div",{className:"mt-auto flex flex-wrap items-center gap-x-3 gap-y-1 pt-1",children:[k&&l.map(C=>e.jsx(ae,{to:C.href,className:"text-xs font-medium text-muted-foreground hover:text-foreground transition-colors",children:C.label},C.href+C.label)),e.jsxs(ae,{to:r,className:"ml-auto inline-flex items-center gap-1 text-xs font-semibold text-primary hover:underline underline-offset-2",children:[o," ",e.jsx(J,{className:"h-3 w-3"})]})]})]})}const Ve=864e5,ce=7;function Ne(t){const s=new Date;s.setHours(0,0,0,0);const a=s.getTime()-(ce*2-1)*Ve,n=new Array(ce*2).fill(0);for(const o of t){if(!o.at)continue;const c=new Date(o.at).getTime();if(Number.isNaN(c)||c<a)continue;const d=Math.floor((c-a)/Ve);d<0||d>=n.length||(n[d]+=o.amount??1)}const i=n.slice(0,ce).reduce((o,c)=>o+c,0),l=n.slice(ce).reduce((o,c)=>o+c,0),r=i>0?Math.round((l-i)/i*100):null;return{series:n.slice(ce),changePercent:r}}function Re(){const t=ie();return V({queryKey:["dashboard-widget-trends",t],staleTime:5*6e4,gcTime:10*6e4,placeholderData:s=>s,queryFn:async()=>{const s=_,a=new Date(Date.now()-ce*2*Ve).toISOString(),n=async c=>{try{const d=await c();return(d==null?void 0:d.data)??[]}catch{return[]}},[i,l,r,o]=await Promise.all([n(()=>s.from("contacts").select("created_at").eq("is_archived",!1).gte("created_at",a).limit(2e3)),n(()=>s.from("deals").select("created_at").gte("created_at",a).limit(2e3)),n(()=>s.from("invoice_payments").select("paid_at, amount").gte("paid_at",a).limit(2e3)),n(()=>s.from("bookings").select("start_time").neq("status","cancelled").gte("start_time",a).limit(2e3))]);return{contacts:Ne(i.map(c=>
1({at:c.created_at}))),deals:Ne(l.map(c=>({at:c.created_at}))),invoices:Ne(r.map(c=>({at:c.paid_at,amount:Number(c.amount)||0}))),bookings:Ne(o.map(c=>({at:c.start_time})))}}})}const Ge=t=>t>=1e6?`â¦${(t/1e6).toFixed(1)}M`:t>=1e3?`â¦${(t/1e3).toFixed(0)}K`:`â¦${Math.round(t).toLocaleString()}`,A=t=>(t??0).toLocaleString();function _i({size:t}){const{data:s,isLoading:a}=Y(),{data:n}=Re();return e.jsx(Q,{size:t,isLoading:a,icon:ne,name:"Customers",primary:{label:"Contacts",value:A(s==null?void 0:s.contactsTotal),href:"/contacts"},supporting:[{label:"new this week",value:A(s==null?void 0:s.contactsNew7d),href:"/contacts?view=recent"},{label:"new leads",value:A(s==null?void 0:s.leadsNew),href:"/leads?status=new"},{label:"qualified",value:A(s==null?void 0:s.leadsQualified),href:"/leads?status=qualified"}],quickLinks:[{label:"Add contact",href:"/contacts?new=1"}],viewHref:"/contacts",trend:n==null?void 0:n.contacts.series,changePercent:(n==null?void 0:n.contacts.changePercent)??null,viewLabel:"View customers"})}function Ci({size:t}){const{data:s,isLoading:a}=Y(),n=(s==null?void 0:s.dealsStale)??0,{data:i}=Re();return e.jsx(Q,{size:t,isLoading:a,icon:wt,name:"Deals",primary:{label:"Open pipeline value",value:Ge((s==null?void 0:s.dealsPipelineValue)??0),href:"/pipeline"},supporting:[{label:"open deals",value:A(s==null?void 0:s.dealsOpen),href:"/pipeline"},{label:"need attention",value:A(n),href:"/pipeline?view=attention",tone:n>0?"warning":"default"}],alert:n>0?{label:`${n} deal${n===1?"":"s"} untouched for 14+ days`,href:"/pipeline?view=attention"}:null,quickLinks:[{label:"Add deal",href:"/pipeline?new=1"}],viewHref:"/pipeline",trend:i==null?void 0:i.deals.series,changePercent:(i==null?void 0:i.deals.changePercent)??null,viewLabel:"View pipeline"})}function Si({size:t}){const{data:s,isLoading:a}=Y(),n=(s==null?void 0:s.bookingsPending)??0,{data:i}=Re();return e.jsx(Q,{size:t,isLoading:a,icon:jt,name:"Bookings",primary:{label:"Appointments today",value:A(s==null?void 0:s.bookingsToday),href:"/bookings?tab=appointments"},supporting:[{label:"upcoming",value:A(s==null?void 0:s.bookingsUpcoming),href:"/bookings?tab=appointments&status=upcoming"},{label:"awaiting approval",value:A(n),tone:n>0?"warning":"default",href:"/bookings?tab=appointments&status=pending"}],alert:n>0?{label:`${n} booking${n===1?"":"s"} waiting for approval`,href:"/bookings?tab=appointments&status=pending"}:null,quickLinks:[{label:"Share booking link",href:"/bookings?tab=booking-page"}],viewHref:"/bookings",trend:i==null?void 0:i.bookings.series,changePercent:(i==null?void 0:i.bookings.changePercent)??null,viewLabel:"View bookings"})}function Li({size:t}){const{data:s,isLoading:a}=zs(),n=(s==null?void 0:s.overdue)??0,{data:i}=Re();return e.jsx(Q,{size:t,isLoading:a,icon:bt,name:"Invoices",primary:{label:"Outstanding",value:Ge((s==null?void 0:s.outstanding)??0),href:"/invoices?status=sent"},supporting:[{label:"collected",value:Ge((s==null?void 0:s.revenue_collected)??0),tone:"success",href:"/invoices?status=paid"},{label:"overdue",value:A(n),tone:n>0?"destructive":"default",href:"/invoices?status=overdue"},{label:"drafts",value:A(s==null?void 0:s.draft),href:"/invoices?status=draft"}],alert:n>0?{label:`${n} invoice${n===1?"":"s"} past due - chase payment`,href:"/invoices?status=overdue"}:null,quickLinks:[{label:"New invoice",href:"/invoices?new=1"}],viewHref:"/invoices",trend:i==null?void 0:i.invoices.series,changePercent:(i==null?void 0:i.invoices.changePercent)??null,viewLabel:"View invoices"})}function Ti({size:t}){const{data:s,isLoading:a}=Y(),n=Xa();return e.jsx(Q,{size:t,isLoading:a,icon:ye,name:"Inbox",primary:{label:"Open conversations",value:A(s==null?void 0:s.conversationsOpen),href:"/inbox"},supporting:[{label:"active campaigns",value:A(s==null?void 0:s.campaignsActive),href:"/campaigns"}],quickLinks:[{label:"Connect a channel",href:n({section:"channels"})}],viewHref:"/inbox",viewLabel:"Open inbox"})}function Di({size:t}){const{data:s,isLoading:a}=Y(),n=(s==null?void 0:s.tasksOverdue)??0;return e.jsx(Q,{size:t,isLoading:a,icon:de,name:"Tasks",primary:{label:"Due today",value:A(s==null?void 0:s.tasksDueToday),href:"/tasks"},supporting:[{label:"overdue",value:A(n),tone:n>0?"destructive":"default",href:"/tasks?view=overdue"}],alert:n>0?{label:`${n} task${n===1?"":"s"} already late`,href:"/tasks?view=overdue"}:null,quickLinks:[{label:"Add task",href:"/tasks?new=1"}],viewHref:"/tasks",viewLabel:"View tasks"})}function Ai({size:t}){const{data:s,isLoading:a}=Y();return e.jsx(Q,{size:t,isLoading:a,icon:Ue,name:"Forms",primary:{label:"Responses this week",value:A(s==null?void 0:s.formSubmissions7d),href:"/forms"},supporting:[{label:"live forms",value:A(s==null?void 0:s.formsActive),href:"/forms"}],quickLinks:[{label:"New form",href:"/forms?new=1"}],viewHref:"/forms",viewLabel:"View forms"})}function Oi({size:t}){const{data:s,isLoading:a}=Y();return e.jsx(Q,{size:t,isLoading:a,icon:vt,name:"Products & services",primary:{label:"Items customers can buy",value:A(s==null?void 0:s.offersActive),href:"/catalog"},quickLinks:[{label:"Add item",href:"/catalog?new=1"}],viewHref:"/catalog",viewLabel:"View catalog"})}function $i({size:t}){const{data:s,isLoading:a}=Y(),{data:n,isLoading:i}=hn(),l=(s==null?void 0:s.ticketsOpen)??0,r=(n==null?void 0:n.overdue)??0,o=(n==null?void 0:n.quiet)??0,c=r+o+l;return e.jsx(Q,{size:t,isLoading:a||i,icon:Se,name:"Customers needing attention",primary:{label:"Need attention",value:A(c),href:"/customer-care?tab=attention"},supporting:[{label:"No contact in 30 days",value:A(o),href:"/customer-care?tab=attention&filter=quiet"},{label:"Overdue follow-ups",value:A(r),href:"/customer-care?tab=attention&filter=overdue"},{label:"Unresolved complaints",value:A(l),href:"/customer-care?tab=complaints"}],alert:c>0?{label:`${c} customer${c===1?"":"s"} waiting on you`,href:"/customer-care?tab=attention"}:null,quickLinks:[{label:"New complaint",href:"/customer-care?tab=complaints&new=1"}],viewHref:"/customer-care",viewLabel:"View customers"})}function Wi({size:t}){const{data:s,isLoading:a}=Y();return e.jsx(Q,{size:t,isLoading:a,icon:yt,name:"Commissions",primary:{label:"Pending payouts",value:A(s==null?void 0:s.commissionsPending),href:"/commissions"},viewHref:"/commissions",viewLabel:"View commissions"})}function Mi({size:t}){const{data:s,isLoading:a}=Y();return e.jsx(Q,{size:t,isLoading:a,icon:gt,name:"Campaigns",primary:{label:"Active campaigns",value:A(s==null?void 0:s.campaignsActive),href:"/campaigns"},quickLinks:[{label:"New campaign",href:"/campaigns?new=1"}],viewHref:"/campaigns",viewLabel:"View campaigns"})}const Vs={kpi_revenue:Jn,kpi_open_deals:Xn,kpi_contacts:ei,recent_activity:Gn,recent_contacts:ri,tag_leaderboard:Bn,pi
1peline_snapshot:Un,upcoming_tasks:Yn,quick_actions:Qn,deals_won:ti,call_stats:ai,automation_stats:ni,team_activity:ii,revenue_chart:oi,contact_groups:li,team_leaderboard:ci,retention_alerts:di,customer_success:ui,duce_signals:pi,commission_summary:xi,referral_progress:hi,live_visitors:fi,followups_due_today:gi,followups_overdue:yi,customer_health:vi,followup_completion_rate:bi,avg_response_time:ji,customer_recovery_rate:wi,contacts_feature:_i,deals_feature:Ci,tasks_feature:Di,bookings_feature:Si,invoices_feature:Li,inbox_feature:Ti,forms_feature:Ai,catalog_feature:Oi,support_feature:$i,commissions_feature:Wi,campaigns_feature:Mi};function xs(t){return!!Vs[t]}function Gs({widgetId:t,size:s}){const a=Be(t);if(s==="icon"&&a)return e.jsx(In,{icon:a.icon,label:kt(t),route:Nt(t),ariaLabel:`${a.name} - open`});const n=Vs[t];return n?e.jsx(n,{size:s}):null}const Pi={available:!0};function hs(t,s){const a=typeof t=="string"?Be(t):t;return a?a.hiddenFromLibrary&&s.forLibrary?{available:!1,reason:"not_ready",message:"Not ready yet - it will appear here once it can answer the question properly."}:a.adminOnly&&!s.isAdmin?{available:!1,reason:"admin_only",message:"Only workspace admins can see this."}:a.moduleKey&&!s.moduleEnabled(a.moduleKey)?{available:!1,reason:"module_off",message:"This feature is switched off for your workspace."}:a.requiredPermission&&!Ct(s.permissions,[a.requiredPermission])?{available:!1,reason:"no_permission",message:"You do not have access to this information."}:a.planRequirement&&!St(s.planTier,a.planRequirement)?{available:!1,reason:"plan",message:"Available on a higher plan."}:Pi:{available:!1,reason:"unknown_widget",message:"This widget is no longer part of DuceCRM."}}function Bs(t=!1){const{state:s}=_t(),{permissions:a}=Ls(),{isAdmin:n}=Me(),{planTier:i}=Ze(),l={moduleEnabled:r=>s[r]!==!1,permissions:a,isAdmin:n,planTier:i,forLibrary:t};return{context:l,availability:r=>hs(r,l),isAvailable:r=>hs(r,l).available}}const Ri=[{key:"recommended",label:"Recommended"},...Ts.map(t=>({key:t.key,label:t.label}))];function Ii({open:t,onOpenChange:s}){var u;const[a,n]=f.useState(""),[i,l]=f.useState("recommended"),[r,o]=f.useState(null),[c,d]=f.useState(He),{enabledWidgets:p,widgetSizes:m,toggleWidget:b,setWidgetSize:g,setMaxWidgets:k}=De(),{limits:N,isFreePlan:y}=Ze();Me();const{isAvailable:j}=Bs(!0),S=ss("dashboard.what-is-a-widget");f.useEffect(()=>{k(N.max_widgets)},[N.max_widgets,k]),f.useEffect(()=>{t||o(null)},[t]);const C=y&&p.length>=N.max_widgets,$=f.useMemo(()=>Lt.filter(v=>{if(!j(v))return!1;if(a){const D=a.toLowerCase();return v.name.toLowerCase().includes(D)||v.description.toLowerCase().includes(D)}return i==="recommended"?Tt.includes(v.id):v.group===i}),[a,i,j]),W=(u=Ts.find(v=>v.key===i))==null?void 0:u.blurb,P=v=>{const K=p.includes(v.id)?m[v.id]:He;d(Ke(v.id,K)),o(v)},q=()=>{if(!r)return;p.includes(r.id)||b(r.id),g(r.id,c),o(null),s(!1),z.success(`${r.name} added`,{description:"You can resize or move it anytime.",action:{label:"View dashboard",onClick:()=>{window.location.href="/dashboard"}}})};return e.jsx(Dt,{open:t,onOpenChange:s,children:e.jsx(At,{side:"bottom",className:"h-[85vh] rounded-t-lg px-4 pb-4 flex flex-col",children:r?e.jsx(Ei,{widget:r,size:c,onSize:d,onBack:()=>o(null),onConfirm:q,alreadyOn:p.includes(r.id)}):e.jsxs(e.Fragment,{children:[e.jsxs(Ds,{className:"pb-2 text-left",children:[e.jsxs(As,{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Z,{className:"h-5 w-5 text-primary"})," Add to your dashboard"]}),y&&e.jsxs(We,{variant:"secondary",className:"text-xs font-medium shrink-0",children:[p.length," / ",N.max_widgets," used"]})]}),e.jsx(Os,{className:"text-xs",children:"Choose the business information you want to see whenever you open DuceCRM."})]}),!S.dismissed&&e.jsxs("div",{className:"mb-3 flex items-start gap-2 rounded-lg border bg-muted/40 p-2.5",children:[e.jsx(Ot,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("p",{className:"flex-1 text-[11px] leading-relaxed text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"What is a widget?"}
1)," A small view of something important in your business, such as customers, sales, bookings or money."]}),e.jsx("button",{"aria-label":"Dismiss hint",className:"text-muted-foreground hover:text-foreground",onClick:S.dismiss,children:e.jsx(Je,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"relative mb-3",children:[e.jsx($t,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Wt,{placeholder:"Search what you want to see",className:"pl-9",value:a,onChange:v=>n(v.target.value)})]}),e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:Ri.map(v=>e.jsx("button",{onClick:()=>l(v.key),className:T("shrink-0 rounded-full px-3 py-1.5 text-xs font-medium transition-colors",v.key===i?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-muted/80"),children:v.label},v.key))}),!a&&W&&e.jsx("p",{className:"mb-3 text-[11px] text-muted-foreground",children:W}),!a&&i==="recommended"&&e.jsx("p",{className:"mb-3 text-[11px] text-muted-foreground",children:"A good starting set. Switch on more when you need them."}),C&&e.jsxs("div",{className:"mb-3 rounded-lg border border-primary/20 bg-primary/5 p-3 flex items-center gap-2",children:[e.jsx(Mt,{className:"h-4 w-4 text-primary shrink-0"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["You've reached your Starter plan limit."," ",e.jsx("a",{href:"/settings?section=billing",className:"text-primary font-medium underline",children:"Upgrade to Pro"})," ","for unlimited widgets."]})]}),e.jsxs("div",{className:"flex-1 space-y-2.5 overflow-y-auto pr-1",children:[$.length===0&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"Nothing here yet. Try another group or a different search."}),$.map(v=>{const D=p.includes(v.id),K=!D&&C,R=v.icon;return e.jsxs("div",{className:T("rounded-lg border bg-card p-3 transition-colors",D&&"border-primary/40 ring-1 ring-primary/20",K&&"opacity-60"),children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:T("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",D?"bg-primary/10":"bg-muted"),children:e.jsx(R,{className:T("h-4 w-4",D?"text-primary":"text-muted-foreground")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold",children:v.name}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:v.description})]}),D?e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 text-[11px] font-medium text-primary",children:[e.jsx(se,{className:"h-3 w-3"})," Added"]}):e.jsxs(x,{size:"sm",variant:"outline",className:"h-8 shrink-0 gap-1 text-xs",disabled:K,onClick:()=>P(v),children:[e.jsx(Xe,{className:"h-3.5 w-3.5"})," Add"]})]}),D&&e.jsxs("div",{className:"mt-2 flex items-center gap-3",children:[e.jsx("button",{className:"text-[11px] font-medium text-primary hover:underline",onClick:()=>P(v),children:"Adjust how much it shows"}),e.jsx("button",{className:"text-[11px] text-muted-foreground transition-colors hover:text-destructive",onClick:()=>b(v.id),children:"Remove from dashboard"})]})]},v.id)})]})]})})})}function Ei({widget:t,size:s,onSize:a,onBack:n,onConfirm:i,alreadyOn:l}){const r=ws(t.id),o=t.icon;return e.jsxs(e.Fragment,{children:[e.jsxs(Ds,{className:"pb-2 text-left",children:[e.jsxs(As,{className:"flex items-center gap-2",children:[e.jsx("button",{"aria-label":"Back",onClick:n,className:"text-muted-foreground hover:text-foreground",children:e.jsx(Pt,{className:"h-4 w-4"})}),e.jsx(o,{className:"h-5 w-5 text-primary"})," ",t.name]}),e.jsx(Os,{className:"text-xs",children:"How much would you like to see?"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto pr-1",children:[e.jsxs("div",{className:"mb-4 rounded-lg border bg-muted/30 p-3",children:[e.jsx("p",{className:"mb-2 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"Preview"}),e.jsx("div",{className:T("rounded-lg",s==="icon"&&"w-24"),children:e.jsx(Gs,{widgetId:t.id,size:s})})]}),e.jsx("div",{className:"space-y-2",children:r.map(c=>{const d=c===s;return e.jsxs("button",{onClick:()=>a(c),"aria-pressed":d,className:T("w-full rounded-lg border p-3 text-left transition-colors",d?"border-primary bg-primary/5 ring-1 ring-primary/20":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold",children:Ns[c]}),c===He&&e.jsx(We,{variant:"secondary",className:"text-[10px]",children:"Recommended"}),d&&e.jsx(se,{className:"ml-auto h-4 w-4 text-primary"})]}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:Rt[c]})]},c)})})]}),e.jsx("div",{className:"pt-3",children:e.jsx(x,{className:"w-full",onClick:i,children:l?"Save":"Add to dashboard"})})]})}function qi({open:t,onOpenChange:s}){const{profile:a}=ve(),{isAdmin:n}=Me(),i=(a==null?void 0:a.org_id)??"",{resetToDefaults:l,resetToCompanyDefault:r,saveAsCompanyDefault:o}=De(),[c,d]=f.useState(null),[p,m]=f.useState("suggested"),[b,g]=f.useState(!1),[k,N]=f.useState(!1),[y,j]=f.useState(!1);f.useEffect(()=>{if(!t||!i)return;let $=!1;return(async()=>{const{data:W}=await _.from("dashboard_company_defaults").select("id").eq("org_id",i).maybeSingle();if($)return;const P=!!W;d(P),m(P?"company":"suggested")})(),()=>{$=!0}},[t,i]);const S=async()=>{g(!0);try{if(p==="company"){if(!await r(i))return}else l();j(!1),s(!1)}finally{g(!1)}},C=async()=>{N(!0);try{await o(i)&&d(!0)}finally{N(!1)}};return e.jsxs($s,{open:t,onOpenChange:s,children:[e.jsxs(Ws,{size:"md",className:"",children:[e.jsxs(Ms,{children:[e.jsx(Ps,{children:"Reset your dashboard"}),e.jsx(It,{children:"Pick an arrangement to restore. Your current customisations will be replaced."})]}),e.jsxs("div",{className:"space-y-2.5",children:[e.jsx(fs,{icon:e.jsx(Et,{className:"h-4 w-4"}),title:"Company default",description:c===!1?"Your admin hasn't saved a company default yet.":"The layout your admin saved for the team.",disabled:c===!1,selected:p==="company",onSelect:()=>m("company")}),e.jsx(fs,{icon:e.jsx(ke,{className:"h-4 w-4"}),title:"Suggested layout",description:"The built-in starter layout for new accounts.",selected:p==="suggested",onSelect:()=>m("suggested")})]}),n&&e.jsxs("div",{className:"mt-2 rounded-lg border border-dashed border-border p-3 flex items-start gap-3",children:[e.jsx(Z,{className:"h-4 w-4 mt-0.5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:"Save current as company default"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 leading-snug",children:"Make your current arrangement the starting point for everyone on the team."})]}),e.jsxs(x,{size:"sm",variant:"outline",className:"gap-1 shrink-0",onClick:C,disabled:k,children:[e.jsx(fn,{className:"h-3.5 w-3.5"}),k?"Saving...":"Save"]})]}),e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsx(x,{className:"w-full",onClick:()=>j(!0),disabled:b||p==="company"&&c===!1,children:b?"Resetting...":"Reset dashboard"}),e.jsx(x,{variant:"ghost",className:"w-full",onClick:()=>s(!1),disabled:b,children:"Cancel"})]})]}),e.jsx(qt,{open:y,onOpenChange:j,title:"Reset dashboard?",message:p==="company"?"This will replace your current widget arrangement with the company default. Your personal customisations will be lost.":"This will replace your current widget arrangement with the suggested starter layout. Your personal customisations will be lost.",confirmLabel:"Reset dashboard",confirmVariant:"destructive",onConfirm:S,loading:b})]})}function fs({icon:t,title:s,description:a,selected:n,disabled:i,onSelect:l}){return e.jsxs("button",{type:"button",onClick:i?void 0:l,disabled:i,className:T("w-full text-left rounded-lg border p-3 flex items-start gap-3 transition-colors",n?"border-primary ring-1 ring-primary/40 bg-primary/5":"border-border hover:bg-muted/50",i&&"opacity-60 cursor-not-allowed hover:bg-transparent"),children:[e.jsx("span",{className:T("h-8 w-8 rounded-md flex items-center justify-center shrink-0",n?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:t}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:s}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 leading-snug",children:a})]}
1),e.jsx("span",{className:T("h-4 w-4 rounded-full border flex items-center justify-center shrink-0 mt-0.5",n?"border-primary bg-primary text-primary-foreground":"border-muted-foreground/40"),children:n&&e.jsx(se,{className:"h-3 w-3"})})]})}const Fi={invoicesOverdue:0,invoicesOutstanding:0,tasksOverdue:0,tasksDueToday:0,followupsOverdue:0,followupsDueToday:0,dealsNeedingAttention:0,dealsStuck:0,dealsCloseDatePassed:0,contactsGoingCold:0,bookingsPending:0,bookingsToday:0,ticketsOpen:0},O=(t,s,a)=>t===1?s:a;function gs(t){return t>=1e6?`â¦${(t/1e6).toFixed(1).replace(/\.0$/,"")}M`:t>=1e3?`â¦${Math.round(t/1e3)}K`:`â¦${Math.round(t)}`}function zi(t){const s={...Fi,...t},a=[];s.invoicesOverdue>0&&a.push({id:"invoices_overdue",headline:`Collect ${s.invoicesOverdue} overdue ${O(s.invoicesOverdue,"invoice","invoices")}`,reason:s.invoicesOutstanding>0?`${gs(s.invoicesOutstanding)} still unpaid`:"Past the due date",count:s.invoicesOverdue,tone:"urgent",actionLabel:"View invoices",href:"/invoices?status=overdue",rank:10,observed:[`${s.invoicesOverdue} ${O(s.invoicesOverdue,"invoice is","invoices are")} past the due date.`,...s.invoicesOutstanding>0?[`${gs(s.invoicesOutstanding)} is outstanding across open invoices.`]:[]],prediction:"Older invoices tend to get harder to collect the longer they sit.",recommended:"Send a payment reminder today, oldest first."}),s.tasksOverdue>0&&a.push({id:"tasks_overdue",headline:`Clear ${s.tasksOverdue} overdue ${O(s.tasksOverdue,"task","tasks")}`,reason:"Clear the oldest first",count:s.tasksOverdue,tone:"urgent",actionLabel:"View tasks",href:"/tasks?due=overdue&status=open",rank:20,observed:[`${s.tasksOverdue} ${O(s.tasksOverdue,"task","tasks")} passed the due date and ${O(s.tasksOverdue,"is","are")} still open.`,...s.tasksDueToday>0?[`${s.tasksDueToday} more ${O(s.tasksDueToday,"task is","tasks are")} due today.`]:[]],prediction:"Work left open past its date usually slips again.",recommended:"Work through the oldest overdue tasks first."});const n=s.followupsOverdue+s.followupsDueToday;if(n>0){const i=[];s.followupsOverdue>0&&i.push(`${s.followupsOverdue} overdue`),s.followupsDueToday>0&&i.push(`${s.followupsDueToday} due today`),a.push({id:"followups_due",headline:`Complete ${n} waiting ${O(n,"follow-up","follow-ups")}`,reason:i.join(", "),count:n,tone:s.followupsOverdue>0?"urgent":"warning",actionLabel:"Follow up",href:"/customer-care?tab=attention",rank:30,observed:[...s.followupsOverdue>0?[`${s.followupsOverdue} ${O(s.followupsOverdue,"follow-up is","follow-ups are")} overdue.`]:[],...s.followupsDueToday>0?[`${s.followupsDueToday} ${O(s.followupsDueToday,"follow-up is","follow-ups are")} due today.`]:[]],prediction:"Customers waiting on a reply may go elsewhere.",recommended:"Reply to the overdue ones first, then today's list."})}if(s.dealsNeedingAttention>0){const i=[];s.dealsStuck>0&&i.push(`${s.dealsStuck} stuck`),s.dealsCloseDatePassed>0&&i.push(`${s.dealsCloseDatePassed} past close date`),a.push({id:"deals_attention",headline:`Follow up on ${s.dealsNeedingAttention} ${O(s.dealsNeedingAttention,"deal","deals")} that need attention`,reason:i.length>0?i.join(", "):"No activity for a while",count:s.dealsNeedingAttention,tone:"warning",actionLabel:"View deals",href:"/pipeline?view=attention",rank:40,observed:[`${s.dealsNeedingAttention} open ${O(s.dealsNeedingAttention,"deal has","deals have")} had no recorded activity recently.`,...s.dealsCloseDatePassed>0?[`${s.dealsCloseDatePassed} ${O(s.dealsCloseDatePassed,"deal is","deals are")} past the expected close date.`]:[]],prediction:"Some of these may be losing momentum.",recommended:"Follow up today and agree a next step."})}return s.contactsGoingCold>0&&a.push({id:"contacts_cold",headline:`Follow up with ${s.contactsGoingCold} quiet ${O(s.contactsGoingCold,"customer","customers")}`,reason:"No contact in 14 days",count:s.contactsGoingCold,tone:"warning",actionLabel:"Follow up",href:"/contacts?filter=cold",rank:50,observed:[`${s.contactsGoingCold} ${O(s.contactsGoingCold,"customer has","customers have")} had no contact for more than 14 days.`],prediction:"Quiet customers are more likely to drift away.",recommended:"Send a short check-in message."}),s.ticketsOpen>0&&a.push({id:"tickets_open",headline:`Resolve ${s.ticketsOpen} open ${O(s.ticketsOpen,"customer issue","customer issues")}`,reason:"Waiting on your team",count:s.ticketsOpen,tone:"warning",actionLabel:"View issues",href:"/support",rank:60,observed:[`${s.ticketsOpen} support ${O(s.ticketsOpen,"ticket is","tickets are")} still unresolved.`],recommended:"Resolve or reply to the oldest issue first."}),s.bookingsPending>0&&a.push({id:"bookings_pending",headline:`Approve ${s.bookingsPending}
1 pending ${O(s.bookingsPending,"booking","bookings")}`,reason:"Waiting for your confirmation",count:s.bookingsPending,tone:"warning",actionLabel:"Review bookings",href:"/bookings?tab=appointments&status=pending",rank:70,observed:[`${s.bookingsPending} ${O(s.bookingsPending,"booking request is","booking requests are")} waiting for approval.`],recommended:"Approve or decline them so customers know where they stand."}),s.bookingsToday>0&&a.push({id:"bookings_today",headline:`Prepare for ${s.bookingsToday} ${O(s.bookingsToday,"appointment","appointments")} today`,reason:"Be ready before they start",count:s.bookingsToday,tone:"default",actionLabel:"View schedule",href:"/bookings?tab=appointments",rank:80,observed:[`${s.bookingsToday} ${O(s.bookingsToday,"appointment is","appointments are")} scheduled for today.`],recommended:"Check the times and prepare."}),a.sort((i,l)=>i.rank-l.rank)}function Hi(t){if(t.length===0)return"Nothing is overdue or waiting on you today.";const s=Math.min(t.length,3);return`Here is what needs your attention today - ${s} ${O(s,"priority","priorities")} to clear.`}function Vi(t){if(t.length===0)return"See how your business is doing.";const s=Math.min(t.length,3);return`Clear ${s} ${O(s,"priority","priorities")} today.`}const Gi=864e5;function Bi(){const t=ie();return V({queryKey:["dashboard-extra-signals",t],enabled:!!t,staleTime:6e4,queryFn:async()=>{const s=_,a=new Date(Date.now()-14*Gi).toISOString(),n=new Date().toISOString().slice(0,10),i={count:"exact",head:!0},[l,r]=await Promise.all([s.from("contacts").select("id",i).eq("org_id",t).eq("is_archived",!1).neq("status","churned").lt("last_interaction_at",a),s.from("deals").select("id",i).eq("org_id",t).eq("is_archived",!1).not("stage","in",'("closed_won","closed_lost")').lt("expected_close_date",n)]);return{contactsGoingCold:(l==null?void 0:l.count)??0,dealsCloseDatePassed:(r==null?void 0:r.count)??0}}})}function Ks(){const{data:t,isLoading:s}=Y(),{data:a,isLoading:n}=zs(),{data:i,isLoading:l}=je(30),{data:r,isLoading:o}=Bi();return f.useMemo(()=>{const c=(t==null?void 0:t.dealsStale)??0,d=(r==null?void 0:r.dealsCloseDatePassed)??0,p={invoicesOverdue:(a==null?void 0:a.overdue)??0,invoicesOutstanding:(a==null?void 0:a.outstanding)??0,tasksOverdue:(t==null?void 0:t.tasksOverdue)??0,tasksDueToday:(t==null?void 0:t.tasksDueToday)??0,followupsOverdue:(i==null?void 0:i.open_overdue)??0,followupsDueToday:(i==null?void 0:i.due_today)??0,dealsNeedingAttention:Math.max(c,d),dealsStuck:c,dealsCloseDatePassed:d,contactsGoingCold:(r==null?void 0:r.contactsGoingCold)??0,bookingsPending:(t==null?void 0:t.bookingsPending)??0,bookingsToday:(t==null?void 0:t.bookingsToday)??0,ticketsOpen:(t==null?void 0:t.ticketsOpen)??0},m=zi(p);return{priorities:m,top:m.slice(0,3),hiddenCount:Math.max(0,m.length-3),summary:Hi(m),actionLine:Vi(m),isLoading:s||n||l||o}},[t,a,i,r,s,n,l,o])}function Ki(){const t=new Date().getHours();return t<12?"Good morning":t<17?"Good afternoon":"Good evening"}const Ui="ducecrm_dashboard_welcomed:";function Yi(t){const[s,a]=f.useState(!1);return f.useEffect(()=>{if(t)try{const n=`${Ui}${t}`;if(window.localStorage.getItem(n))return;window.localStorage.setItem(n,String(Date.now())),a(!0),Ft("first_dashboard_reached")}catch{}},[t]),s}function Qi({onStartDay:t}){var d,p,m,b;const{profile:s,session:a}=ve(),{actionLine:n,isLoading:i}=Ks(),{identity:l}=yn(),r=Yi((s==null?void 0:s.id)||(a==null?void 0:a.user.id)),o=((d=s==null?void 0:s.first_name)==null?void 0:d.trim())||((p=s==null?void 0:s.full_name)==null?void 0:p.trim().split(" ")[0])||(((m=a==null?void 0:a.user.user_metadata)==null?void 0:m.full_name)||((b=a==null?void 0:a.user.user_metadata)==null?void 0:b.name)||"").trim().split(" ")[0]||"",c=r&&!!(l!=null&&l.businessType);return e.jsxs("section",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"font-display text-xl sm:text-2xl font-bold tracking-tight",children:c?`Welcome to DuceCRM${o?`, ${o}`:""}`:`${Ki()}${o?`, ${o}`:""}`}),c?e.jsxs("p",{className:"mt-1 text-sm text-muted-foreground",children:["Your workspace is ready for your ",l.businessType," business."]}):i?e.jsx(H,{className:"mt-2 h-4 w-64"}):e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:n})]}),e.jsx(gn,{label:"Start my day",icon:e.jsx(J,{className:"h-4 w-4"}),onClick:t,className:"w-full sm:w-auto"})]})}function Zi(){const{top:t,hiddenCount:s,isLoading:a}=Ks(),n=I(),{setCurrentLabel:i}=zt(),l=bn("home");if(a)return e.jsx("div",{className:"space-y-2",children:Array.from({length:2}).map((d,p)=>
1e.jsx(H,{className:"h-14 rounded-lg"},p))});const r=d=>{i("Needs your attention"),n(d)},o=l.finding?[{id:l.finding.id,title:l.finding.title,reason:l.finding.why,actionLabel:l.finding.ctaLabel,onAction:()=>r(l.finding.href),onOpen:()=>r(l.finding.href),tone:l.finding.tone==="warning"?"warning":"neutral"}]:[],c=t.map(d=>({id:d.id,title:d.headline,reason:d.reason,meta:d.recommended,actionLabel:d.actionLabel,onAction:()=>r(d.href),onOpen:()=>r(d.href),tone:d.tone==="urgent"?"urgent":d.tone==="warning"?"warning":"neutral"}));return e.jsx(vn,{items:[...c,...o],limit:3,collapsibleKey:"dashboard.attention",dismissKey:"dashboard.attention",onViewAll:s>0?()=>n("/customer-care?tab=attention"):void 0})}function Ji(t){const{enabled:s,isAdmin:a,setEnabled:n,saving:i}=jn(),{isHidden:l,dismiss:r}=Ht(),o=`invite:${t}`,c=f.useCallback(async()=>{await n(!0)},[n]),d=f.useCallback(()=>{r(o,t)},[r,o,t]);return{available:!s&&a&&!l(o),turnOn:c,notNow:d,saving:i}}function Xi({className:t}){const{available:s,turnOn:a,notNow:n,saving:i}=Ji("setup");return s?e.jsxs("div",{className:T("space-y-2 rounded-lg border p-4",t),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-medium",children:"Would you like DuceCRM to point out what needs attention?"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Gt}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.jsx(x,{size:"sm",disabled:i,onClick:()=>void a(),children:"Yes, switch Smart Guide on"}),e.jsx(x,{size:"sm",variant:"ghost",onClick:n,children:"No thanks"})]})]}):null}function eo({eyebrow:t,title:s,what:a,why:n,cta:i,onAction:l,stepNumber:r,totalSteps:o,doneCount:c,onSkip:d,onLater:p,onReview:m,skipLabel:b="Skip this",laterLabel:g="I'll do this later",className:k}){const N=typeof o=="number"&&o>0,y=c??0;return e.jsxs("section",{className:T("rounded-lg border bg-card p-4 sm:p-5",k),children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:t??"Next step"}),N&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y," of ",o," done"]})]}),N&&e.jsx(Oe,{value:y/o*100,className:"mt-2 h-1.5"}),e.jsxs("div",{className:"mt-3 flex items-start gap-3",children:[e.jsx("span",{className:"mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-primary/10 text-xs font-semibold text-primary",children:r??e.jsx(se,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-base font-semibold leading-tight",children:s}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:a}),e.jsxs("p",{className:"mt-1 text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Why: "}),n]})]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:[e.jsxs(x,{size:"sm",onClick:l,children:[i," ",e.jsx(J,{className:"ml-1.5 h-4 w-4"})]}),d&&e.jsx(x,{size:"sm",variant:"ghost",onClick:d,children:b}),p&&e.jsx(x,{size:"sm",variant:"ghost",className:"text-muted-foreground",onClick:p,children:g}),m&&e.jsx(x,{size:"sm",variant:"ghost",className:"text-muted-foreground",onClick:m,children:"View the full path"})]})]})}function so(){const t=I(),{isLoading:s,needsOutcome:a,dismissed:n,path:i,skipStep:l,dismiss:r,chooseOutcome:o}=Rs();if(s)return null;if(a)return e.jsx(wn,{eyebrow:"Let's set you up",onChoose:async d=>{await o(d)},onLater:()=>void r(!0)});if(n)return e.jsx("div",{className:"flex justify-start",children:e.jsxs(x,{variant:"outline",onClick:Ie,children:[e.jsx(os,{className:"mr-2 h-4 w-4"})," Your path to success"]})});if(i.complete||!i.nextStep)return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Xi,{}),e.jsxs(x,{variant:"outline",onClick:Ie,children:[e.jsx(os,{className:"mr-2 h-4 w-4"})," Review your path to success"]})]});const c=i.nextStep;return e.jsx(eo,{eyebrow:"Your path to success",title:c.title,what:c.what,why:c.why,cta:c.cta,stepNumber:c.number,totalSteps:i.total,doneCount:i.doneCount,onAction:()=>t(c.route),onSkip:()=>void l(c.key),onLater:()=>void r(!0),onReview:Ie})}function to(){const t=I(),s=kn(),{dismissed:a,dismiss:n}=ss("dashboard.domain-cta",["domain-cta"]);return s.isLoading||!s.canManage||s.key==="live"||s.key==="paused"||s.key==="off"||!s.action||a&&s.key!=="needs_attention"?null:e.jsxs(Nn,{className:"flex flex-col gap-3 p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary",children:e.jsx(_n,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:s.headline}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s.key==="not_started"?"Buy a domain or c
1onnect one you already own, then use it for your booking page, forms and emails.":"We will keep checking - you only need to come back if something needs you."})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:shrink-0",children:[e.jsx(x,{size:"sm",onClick:()=>t(s.href),children:s.action.label}),s.key!=="needs_attention"&&e.jsx(x,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground","aria-label":"Hide for now",onClick:n,children:e.jsx(Je,{className:"h-4 w-4"})})]})]})}function ao(){const{path:t,celebrated:s,markCelebrated:a,isLoading:n}=Rs(),i=f.useRef(new Set);return f.useEffect(()=>{if(n)return;const l=t.steps.filter(r=>r.done).map(r=>r.completedWhen);for(const r of l){const o=Bt[r];if(o&&!s.includes(r)&&!i.current.has(r)){i.current.add(r),z.success(o.title,{description:o.line}),a(r);break}}},[n,t,s,a]),null}function no(t){const s=t.trim();if(!s)return"there";const a=s.split(/\s+/),n=new Set(["mr","mrs","ms","miss","dr","chief","engr","prof","alhaji","pastor"]);return a.length>1&&n.has(a[0].toLowerCase().replace(/\./g,""))?`${a[0]} ${a[1]}`:a[0]}function io(t){return t.stale==="reactivate"||t.stale==="review_first"?"It has been a while since we spoke, so I wanted to check in properly.":t.stale==="re_engage"?"I know it has been a little while since we last spoke.":null}const oo={task_overdue:t=>{var a;return`I am following up on our last conversation${(a=t.task)!=null&&a.title?` about ${t.task.title.toLowerCase()}`:""}. Are you still interested in moving ahead? I am happy to answer any questions.`},invoice_overdue:t=>{var n;const s=t.money?` for ${Le(t.money)}`:"";return`I am checking in on${(n=t.money)!=null&&n.label?` ${t.money.label}`:""}${s}, which is now past its due date. Could you let me know when payment will be made so I can update our records?`},deal_idle:t=>{var a;return`I wanted to check where things stand${(a=t.deal)!=null&&a.title?` about ${t.deal.title}`:""}. Is there anything you need from me to help you decide?`},customer_quiet:()=>"I wanted to check in and see how things are going. Is there anything you need from us at the moment?",appointment_today:t=>{var a;return`Just confirming our${(a=t.booking)!=null&&a.purpose?` ${t.booking.purpose.toLowerCase()}`:" appointment"} today. Let me know if the time still works for you.`},customer_waiting:t=>{var a;const s=(a=t.conversation)==null?void 0:a.lastMessage;return s?`Thank you for your message, and apologies for the delay. On your question - "${s}" - here is where we stand:`:"Thank you for your message, and apologies for the delay in coming back to you."},lead_untouched:()=>"Thank you for getting in touch. I wanted to introduce myself properly - could you tell me a little about what you are looking for?",offer_awaiting_decision:t=>{var a;return`I wanted to check where things stand with${(a=t.money)!=null&&a.label?` ${t.money.label}`:" the offer"}. Do you have any questions, or is there anything you would like changed before you decide?`},payment_unverified:t=>`Thank you for letting us know about your payment${t.money?` of ${Le(t.money)}`:""}. We are confirming it now and I will come back to you as soon as it shows on our side.`,service_risk:()=>"",deadline_approaching:()=>"",approval_waiting:()=>"",work_blocked:()=>""};function ro(t){const s=`Hi ${no(t.who.name)},`,a=io(t),n=oo[t.reason](t);return[s,a,n].filter(Boolean).join(" ")}function ys(t){return t.stale==="act_now"?"Written from this customer's records.":`Written from this customer's records, allowing for the ${t.daysWaiting}-day gap.`}function vs({label:t,children:s}){return e.jsxs("div",{className:"sm:flex sm:gap-3",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground sm:w-24 sm:shrink-0 sm:pt-0.5",children:t}),e.jsx("div",{className:"text-sm leading-snug",children:s})]})}function ee({title:t,children:s}){return e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:t}),e.jsx("div",{className:"mt-0.5 text-sm leading-snug",children:s})]})}function fe(t){if(!t)return null;const s=new Date(t);if(Number.isNaN(s.getTime()))return null;const a=Math.floor((Date.now()-s.getTime())/864e5),n=s.toLocaleTimeString("en-NG",{hour:"numeric",minute:"2-digit"});return a<=0?`Today ${n}`:a===1?`Yesterday ${n}`:a<30?`${a} days ago`:s.toLocaleDateString("en-NG",{day:"numeric",month:"long"})}function bs(t){const s=t.replace(/\s+/g," ").trim();return s.length>120?`${s.slice(0,117)}...`:s}
1function lo({item:t,position:s,draft:a,onDraftChange:n}){var d,p;const[i,l]=f.useState(!1),[r,o]=f.useState(!1),c=bs(a)!==a.replace(/\s+/g," ").trim();return e.jsxs("div",{className:"space-y-3 rounded-lg border bg-card p-3 sm:p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("h3",{className:"mt-0.5 truncate font-display text-base font-semibold leading-snug",children:t.who.name}),t.who.statusLine&&e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.who.statusLine})]}),e.jsx(We,{className:Ut[t.priority],variant:"secondary",children:Kt[t.priority]})]}),e.jsx("p",{className:"text-sm font-semibold leading-snug",children:t.summaryLine}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(vs,{label:"What to do",children:t.whatToDo}),e.jsx(vs,{label:"Goal",children:e.jsx("span",{className:"text-muted-foreground",children:t.goal})})]}),r?e.jsxs("div",{className:"space-y-1",children:[e.jsx(Is,{value:a,onChange:m=>n(m.target.value),rows:4,className:"text-sm"}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[ys(t),e.jsx(x,{size:"sm",variant:"link",className:"h-auto p-0 text-xs",onClick:()=>o(!1),children:"Done editing"})]})]}):e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("p",{className:"min-w-0 flex-1 rounded-md bg-muted/50 p-2 text-sm italic",children:['"',bs(a),'"']}),e.jsx(x,{size:"sm",variant:"link",className:"h-auto shrink-0 p-0 text-xs",onClick:()=>o(!0),children:"Edit"})]}),(d=t.conversation)!=null&&d.lastMessage?e.jsxs("p",{className:"hidden text-xs text-muted-foreground sm:block",children:['They said: "',t.conversation.lastMessage,'"']}):t.lastActivity&&fe(t.lastActivity.at)&&e.jsxs("p",{className:"hidden text-xs text-muted-foreground sm:block",children:[t.lastActivity.label,": ",fe(t.lastActivity.at)]}),e.jsxs("div",{children:[e.jsxs(x,{size:"sm",variant:"ghost",className:"h-7 gap-1 px-0 text-xs",onClick:()=>l(m=>!m),children:[i?e.jsx(Yt,{className:"h-3.5 w-3.5"}):e.jsx(Qt,{className:"h-3.5 w-3.5"}),"More context"]}),i&&e.jsxs("div",{className:"mt-2 space-y-3 border-t pt-3",children:[e.jsxs(ee,{title:"Why this needs you",children:[e.jsx("ul",{className:"space-y-0.5",children:t.why.map((m,b)=>e.jsx("li",{children:m},b))}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:Zt[t.reason]}),t.staleNote&&e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[Jt[t.stale].label,". ",t.staleNote]})]}),((p=t.conversation)==null?void 0:p.lastMessage)&&e.jsxs(ee,{title:"Last message",children:[e.jsxs("p",{className:"rounded-md bg-muted/50 p-2 italic",children:['"',t.conversation.lastMessage,'"']}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:[t.conversation.channelLabel,fe(t.conversation.lastMessageAt)].filter(Boolean).join(" · ")})]}),t.booking&&e.jsx(ee,{title:"Appointment",children:e.jsxs("p",{children:[t.booking.startsAt?new Date(t.booking.startsAt).toLocaleString("en-NG",{weekday:"long",hour:"numeric",minute:"2-digit"}):"Time not recorded",e.jsxs("span",{className:"text-muted-foreground",children:[" ","· ",t.booking.confirmed?"Confirmed":"Not confirmed yet"]})]})}),t.money&&e.jsxs(ee,{title:"Money",children:[e.jsxs("p",{children:[Le(t.money)," outstanding",t.money.dueAt&&e.jsxs("span",{className:"text-muted-foreground",children:[" ","· was due"," ",new Date(t.money.dueAt).toLocaleDateString("en-NG",{day:"numeric",month:"long"})]})]}),t.money.label&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.money.label})]}),t.lastActivity&&fe(t.lastActivity.at)&&e.jsx(ee,{title:"Last activity",children:e.jsxs("p",{children:[fe(t.lastActivity.at),e.jsxs("span",{className:"text-muted-foreground",children:[" · ",t.lastActivity.label]})]})}),t.deal&&e.jsx(ee,{title:"Sale",children:e.jsxs("p",{children:[t.deal.title,t.deal.value?` · ${Le({amount:t.deal.value,currency:t.deal.currency})}`:"",t.deal.stage?` · ${t.deal.stage}`:""]})}),t.task&&e.jsxs(ee,{title:"Task",children:[e.jsx("p",{children:t.task.title}),t.task.createdAt&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Created"," ",new Date(t.task.createdAt).toLocaleDateString("en-NG",{day:"numeric",month:"long"})]})]}),c&&e.jsxs(ee,{title:"Suggested message",children:[e.jsxs("p",{className:"rounded-md bg-muted/50 p-2 italic",children:['"',a,'"']}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:ys(t)})]})]})]})]})}function co({open:t,onOpenChange:s,items:a,lenses:n=["mine"],lens:i="mine",onLensChange:l}){const r=ie(),o=I(),c=Cn(),d=Sn(),p=Ln(),{channels:m}=Tn(),[b,g]=f.useState(0),[k,N]=f.useState({}),[y,j]=f.useState({}),[S,C]=f.useState(!1),[$,W]=f.useState(""),[P,q]=f.useState(!1);f.useEffect(()=>{t&&(g(0),N({}),j({}),C(!1),W(""))},[t]),f.useEffect(()=>{g(0)},[i]);const u=a[b],v=t&&a.length>0&&b>=a.length,D=u?y[u.id]??ro(u):"",{data:K}=V({queryKey:["start-my-day-contact",u==null?void 0:u.who.contactId],enabled:!!(u!=null&&u.who.contactId)&&P,queryFn:async()=>{const{data:h}=await _.from("contacts").select("id, full_name, email, phone, whatsapp_handle, instagram_username, company, avatar_url").eq("id",u.who.contactId).maybeSingle();return h??null}}),R=h=>{u&&(N(M=>({...M,[u.id]:h})),g(M=>M+1),C(!1),W(""))},U=f.useMemo(()=>{const h=Object.values(k);return{handled:h.filter(M=>M==="handled").length,later:h.filter(M=>M==="later").length,skipped:h.filter(M=>M==="skipped").length}},[k]),G=async()=>
1{if(u!=null&&u.task)try{await c.mutateAsync({id:u.task.id,orgId:r}),z.success("Task completed."),R("handled")}catch{z.error("That task could not be completed. Nothing was changed.")}},we=async()=>{if(u!=null&&u.task){const h=new Date(Date.now()+2592e5).toISOString().slice(0,10);try{await d.mutateAsync({id:u.task.id,due_date:h}),z.success("Moved to three days from now.")}catch{z.error("That date could not be changed. Nothing was saved.");return}}R("later")},re=async()=>{var h;if(!(!(u!=null&&u.who.contactId)||!$.trim()))try{await p.mutateAsync({content:$.trim(),contact_id:u.who.contactId,org_id:r,category:"general",task_id:((h=u.task)==null?void 0:h.id)??null}),z.success("Note saved to this customer."),R("handled")}catch{z.error("That note could not be saved.")}},ts=()=>{u!=null&&u.conversation&&(sessionStorage.setItem("inbox:draft",D),s(!1),o(u.links.record||"/inbox"))},pe=async()=>{if(u!=null&&u.booking)try{const{error:h}=await _.from("bookings").update({status:"confirmed"}).eq("id",u.booking.id).eq("org_id",r);if(h)throw h;z.success("Appointment confirmed."),R("handled")}catch{z.error("That appointment could not be confirmed. Nothing was changed.")}},xe=(h,M)=>{if(!u)return null;const F=M==="primary"?void 0:"outline";switch(h){case"reply":return e.jsxs(x,{size:"sm",variant:F,className:"gap-1.5",onClick:ts,children:[e.jsx(ye,{className:"h-4 w-4"}),"Reply"]},h);case"message":return u.who.contactId?e.jsxs(x,{size:"sm",variant:F,className:"gap-1.5",onClick:()=>q(!0),children:[e.jsx(ye,{className:"h-4 w-4"}),"Message"]},h):null;case"call":return e.jsxs(x,{size:"sm",variant:F,className:"gap-1.5",onClick:()=>R("handled"),children:[e.jsx(Ae,{className:"h-4 w-4"}),"Call"]},h);case"confirm_appointment":return e.jsxs(x,{size:"sm",variant:F,className:"gap-1.5",onClick:pe,children:[e.jsx(aa,{className:"h-4 w-4"}),"Confirm"]},h);case"complete_task":return e.jsxs(x,{size:"sm",variant:F,className:"gap-1.5",onClick:G,children:[e.jsx(se,{className:"h-4 w-4"}),"Do task"]},h);case"reschedule_task":return e.jsxs(x,{size:"sm",variant:F,className:"gap-1.5",onClick:we,children:[e.jsx(Qe,{className:"h-4 w-4"}),"Reschedule"]},h);case"record_note":return u.who.contactId?e.jsxs(x,{size:"sm",variant:F,className:"gap-1.5",onClick:()=>C(!0),children:[e.jsx(An,{className:"h-4 w-4"}),"Add a note"]},h):null;case"ask_for_decision":case"verify_payment":case"assign_owner":{const w=u.links.record||u.links.customer;if(!w)return null;const X=h==="ask_for_decision"?"Ask for a decision":h==="verify_payment"?"Verify payment":"Assign it";return e.jsxs(x,{size:"sm",variant:F,className:"gap-1.5",onClick:()=>{s(!1),o(w)},children:[e.jsx(ze,{className:"h-4 w-4"}),X]},h)}case"open_conversation":case"open_booking":case"open_record":case"open_customer":{const w=u.links.record||u.links.customer;return w?e.jsxs(x,{size:"sm",variant:F,className:"gap-1.5",onClick:()=>{s(!1),o(w)},children:[e.jsx(ze,{className:"h-4 w-4"}),u.conversation?"Open conversation":u.booking?"Open booking":"Open record"]},h):null}default:return null}},te=((u==null?void 0:u.secondaryActions)??[]).filter((h,M,F)=>!h.startsWith("open_")||F.findIndex(w=>w.startsWith("open_"))===M);return e.jsxs(e.Fragment,{children:[e.jsx($s,{open:t,onOpenChange:s,children:e.jsxs(Ws,{className:"flex max-h-[92vh] max-w-lg flex-col gap-0 overflow-hidden p-0",children:[e.jsxs(Ms,{className:"space-y-1 border-b px-4 py-3 text-left",children:[e.jsx(Ps,{className:"font-display text-base",children:"Start my day"}),n.length>1&&l&&e.jsx("div",{className:"flex gap-1 pt-1",children:n.map(h=>e.jsx(x,{size:"sm",variant:h===i?"secondary":"ghost",className:"h-7 px-2 text-xs",title:ea[h],onClick:()=>l(h),children:Xt[h]},h))}),u&&!v&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b+1," of ",a.length,U.handled>0?` · ${U.handled} done`:"",U.skipped>0?` · ${U.skipped} skipped`:""]})]}),a.length===0&&e.jsxs("div",{className:"px-4 py-6 text-center",children:[e.jsx("p",{className:"text-sm",children:sa(i)}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Anything overdue, unpaid or gone quiet will appear here."})]}),v&&e.jsxs("div",{className:"space-y-3 px-4 py-6 text-center",children:[e.jsx("div",{className:"mx-auto flex h-10 w-10 items-center justify-center rounded-full bg-primary/10",children:e.jsx(se,{className:"h-5 w-5 text-primary"})}),e.jsx("p",{className:"text-sm font-medium",children:"That is your day handled."}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[U.handled," acted on · ",U.later," moved to later · ",U.skipped," skipped"]}),e.jsx(x,{className:"w-full",onClick:()=>s(!1),children:"Close"})]}),u&&!v&&e.jsxs(e.Fragment,{children:[e.jsx(Oe,{value:(b+1)/a.length*100,className:"h-1 rounded-none"}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-3 sm:p-4",children:[e.jsx(lo,{item:u,position:`Person ${b+1} of ${a.length}`,draft:D,onDraftChange:h=>j(M=>({...M,[u.id]:h}))}),S&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Is,{value:$,onChange:h=>W(h.target.value),rows:3,placeholder:"What happened?"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(x,{size:"sm",onClick:re,disabled:!$.trim()||p.isPending,children:"Save note"}),e.jsx(x,{size:"sm",variant:"ghost",onClick:()=>C(!1),children:"Cancel"})]})]}),!S&&te.length>0&&e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:te.map(h=>xe(h,"quiet"))})]}),e.jsxs("div",{className:"shrink-0 space-y-2 border-t bg-background px-3 py-3 sm:px-4",children:[e.jsxs("div",{className:"flex gap-2",children:[u.primaryActions.map(h=>xe(h,"primary")),e.jsxs(x,{size:"sm",variant:"outline",className:"ml-auto gap-1.5",onClick:()=>R("handled"),children:[e.jsx(se,{className:"h-4 w-4"}),"Done"]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(x,{size:"sm",variant:"ghost",className:"text-xs",onClick:we,children:u.task?"Remind me in 3 days":"Later"}),e.jsxs(x,{size:"sm",variant:"ghost",className:"gap-1 text-xs",onClick:()=>R("skipped"),children:["Next",e.jsx(ta,{className:"h-4 w-4"})]})]})]})]})]})}),P&&e.jsx(Dn,{open:P,onOpenChange:h=>{q(h),h||R("handled")},contacts:K?[K]:[],presetContactId:(u==null?void 0:u.who.contactId)??null,presetMessage:D,onConversationCreated:()=>q(!1),connectedChannels:m})]})}const uo=10;function mo(t=!0){const s=ie(),{data:a}=na(),{scope:n}=ia("contacts"),{context:i}=oa(),l=(a==null?void 0:a.id)??null,r=(a==null?void 0:a.auth_id)??null,o=!n.scopeKind||ra.has(n.scopeKind),c=f.useMemo(()=>la({role:(i==null?void 0:i.role)??null,scopeKind:n.scopeKind??null}),[i,n.scopeKind]),[d,p]=f.useState(null),m=d&&c.includes(d)?d:ca(c),b=
1o||m==="mine",{data:g,isLoading:k}=V({queryKey:["start-my-day",s,l,b],enabled:t&&!!s,...da("frequent"),queryFn:async()=>{const y=await ma(_,{orgId:s,myId:l,myAuthId:r,ownWorkOnly:b});return pa(y.map(xa))}}),N=f.useMemo(()=>ua(g??[],m).slice(0,uo),[g,m]);return f.useMemo(()=>({items:N,isLoading:k,restrictedToOwnWork:o,lenses:c,lens:m,setLens:y=>p(y)}),[N,k,o,c,m])}function po({onAdd:t,onReset:s,onCustomize:a}){const n=ss("dashboard.widget-sizes-hint",["widget-sizes"]),i=[];return a&&i.push({label:"Customize widgets",icon:e.jsx(ha,{className:"h-4 w-4"}),onClick:a}),s&&i.push({label:"Reset dashboard",icon:e.jsx(fa,{className:"h-4 w-4"}),onClick:s}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("h2",{className:"text-sm font-semibold tracking-tight text-foreground",children:"Your business"}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsxs(x,{variant:"secondary",className:"gap-2",onClick:t,children:[e.jsx(Xe,{className:"h-4 w-4"})," Add widget"]}),e.jsx(On,{items:i,size:"compact",label:"Dashboard options"})]})]}),!n.dismissed&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-border/60 bg-muted/40 px-2.5 py-1.5",children:[e.jsx("p",{className:"text-[11px] leading-snug text-muted-foreground",children:"Choose how much each widget shows: Icon, Compact, Standard or Expanded."}),e.jsx(x,{variant:"ghost",size:"icon-sm",className:"ml-auto h-6 w-6 shrink-0","aria-label":"Dismiss hint",onClick:n.dismiss,children:e.jsx(Je,{className:"h-3.5 w-3.5"})})]})]})}const js={icon:"col-span-3 md:col-span-2 lg:col-span-3",compact:"col-span-6 md:col-span-4 lg:col-span-6",standard:"col-span-12 md:col-span-6 lg:col-span-8",expanded:"col-span-12 md:col-span-12 lg:col-span-16"};function xo(t){return js[t]??js.standard}function ho({children:t,className:s}){return e.jsx("div",{className:T("grid grid-cols-12 gap-3 md:grid-cols-12 lg:grid-cols-24",s),children:t})}const ol=()=>{var h,M,F;const{profile:t,session:s}=ve(),{isAdmin:a}=Me(),{permissions:n,isLoading:i}=Ls(),l=Sa("home",{accessResolved:!i,capabilityAvailable:!i&&(a||rs(n))}),{workType:r}=ga(),{config:o}=ya(),c=!a&&!i&&!rs(n),d=va(n);(h=t==null?void 0:t.full_name)!=null&&h.trim().split(" ")[0],(((M=s==null?void 0:s.user.user_metadata)==null?void 0:M.full_name)||((F=s==null?void 0:s.user.user_metadata)==null?void 0:F.name)||"").trim().split(" ")[0];const[p,m]=f.useState(!1),[b,g]=f.useState(!1),[k,N]=f.useState(!1),y=mo(k),{user:j}=ve(),{enabledWidgets:S,widgetOrder:C,widgetSizes:$,loaded:W,isNewUser:P,loadPreferences:q,reorderWidgets:u,setMaxWidgets:v}=De(),{limits:D,isFreePlan:K}=Ze(),R=(t==null?void 0:t.org_id)||"";ba(R);const[U,G]=f.useState(null),[we,re]=f.useState(null),[ts,pe]=f.useState(1);f.useEffect(()=>{if(!W)return;const w=o.dashboardLayers;if(w<=1)return;const X=setTimeout(()=>pe(B=>Math.max(B,2)),100),L=w>=3?setTimeout(()=>pe(3),300):void 0;return()=>{clearTimeout(X),L&&clearTimeout(L)}},[W,o.dashboardLayers]),f.useCallback(()=>{o.dashboardLayers<=1&&pe(w=>Math.min(w+1,3))},[o.dashboardLayers]),f.useEffect(()=>{v(D.max_widgets)},[D.max_widgets,v]),f.useEffect(()=>{v(D.max_widgets),q(j==null?void 0:j.id,R||void 0)},[q,j==null?void 0:j.id,R,D.max_widgets,v]),f.useEffect(()=>{const w="dashboard_widget_picker_shown";W&&P&&S.length===0&&!sessionStorage.getItem(w)&&(sessionStorage.setItem(w,"1"),m(!0))},[W,P,S.length]);const{isAvailable:xe}=Bs(),te=f.useMemo(()=>{const w=C.filter(B=>S.includes(B)),X=S.filter(B=>!w.includes(B));let L=[...w,...X];return L=L.filter(B=>xe(B)&&xs(B)),w.length===0&&X.length>0&&(L=ja(L,r)),K&&D.max_widgets!==1/0?L.slice(0,D.max_widgets):L},[S,C,K,D.max_widgets,xe,r]);return c&&d!=="/dashboard"?e.jsx(Us,{to:d,replace:!0}):W?e.jsxs("div",{className:T(ls("section"),_a("bottom-nav-safe")),children:[e.jsx(Qi,{onStartDay:()=>N(!0)}),e.jsx(so,{}),e.jsx(to,{}),e.jsx(ao,{}),e.jsx(Zi,{}),te.length>0&&e.jsx(po,{onAdd:()=>m(!0),onReset:()=>g(!0)}),te.length===0?e.jsx(Ca,{icon:Z,title:"Your dashboard is empty",description:"A widget is a live view of one part of your business.",whyItMatters:"This is the screen you open first - it should show what needs you today.",whatAp
1pears:"Revenue, deals to move, people to reply to and today's bookings.",actionLabel:"Add widget",actionIcon:e.jsx(Xe,{className:"h-4 w-4"}),onAction:()=>m(!0)}):e.jsx(ho,{children:te.map(w=>{if(!xs(w))return null;const X=Ke(w,$[w]);return e.jsx("div",{className:xo(X),children:e.jsx(Pn,{widgetId:w,isDragging:U===w,isDragOver:we===w,onDragStart:L=>{G(w),L.dataTransfer.effectAllowed="move",L.dataTransfer.setData("text/plain",w)},onDragEnd:()=>{G(null),re(null)},onDragOver:L=>{L.preventDefault(),L.dataTransfer.dropEffect="move"},onDragEnter:L=>{L.preventDefault(),w!==U&&re(w)},onDragLeave:()=>{re(L=>L===w?null:L)},onDrop:L=>{L.preventDefault();const B=L.dataTransfer.getData("text/plain");if(B&&B!==w){const he=[...te],as=he.indexOf(B),ns=he.indexOf(w);as!==-1&&ns!==-1&&(he.splice(as,1),he.splice(ns,0,B),u(he))}G(null),re(null)},children:L=>e.jsx(Gs,{widgetId:w,size:L})})},w)})}),e.jsx(Ii,{open:p,onOpenChange:m}),e.jsx(qi,{open:b,onOpenChange:g}),e.jsx(co,{open:k,onOpenChange:N,items:y.items,lenses:y.lenses,lens:y.lens,onLensChange:y.setLens})]}):e.jsxs("div",{className:ls("section"),children:[e.jsx(wa,{}),e.jsx(Na,{rows:6,shape:"cards"}),e.jsx(ka,{...l})]})};export{ol 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.