PageSourceSearch

https://crmduce.lovable.app/assets/Inbox-DlFB3SLA.js

js crmduce.lovable.app collected 2026-10-03 03:21:22 UTC 243,502 bytes, 34 lines download raw bytes

1var Ji=Object.defineProperty;var Zi=(t,s,n)=>s in t?Ji(t,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[s]=n;var pn=(t,s,n)=>Zi(t,typeof s!="symbol"?s+"":s,n);import{u as ce,j as e,d as zt,e as Ln}from"./data-DN-eP4ae.js";import{dF as Tr,b7 as el,s as H,K as Fe,dG as tl,b1 as ba,bU as ys,dH as ue,dI as ms,M as ot,R as wa,B as E,dJ as Ar,dK as sl,dL as Er,dM as nl,bF as Rr,c as B,_ as Dn,dN as _a,V as Cn,$ as ie,dO as al,dP as rl,dQ as il,c8 as Lr,n as P,bw as we,aG as Je,dR as Dr,cE as De,dS as ta,aT as Bs,bV as On,dT as ll,aA as Hs,aB as Vs,aC as zs,aD as Ks,aE as ja,j as Ps,av as kt,bA as Is,bD as Mn,ct as Or,ay as sa,bG as Na,cs as Sn,an as At,bE as ol,ao as Et,ap as Rt,aq as Lt,P as $s,e as qs,f as Fs,aU as Mr,aV as bs,at as Dt,C as Us,dU as cl,bu as rt,bJ as ws,cd as na,c2 as Pr,c3 as Ir,c4 as $r,c5 as pe,a3 as hs,bx as qr,cr as cs,cR as dl,dV as ul,cp as qa,co as ml,cu as Fr,cv as Ur,v as Tt,cw as Br,a2 as Fa,o as Ht,dW as hl,dX as pl,dY as fl,bd as Hr,dZ as xl,y as Ot,d_ as Vr,d$ as gl,e0 as va,e1 as yl,e2 as bl,e3 as zr,e4 as wl,e5 as Ua,e6 as _l,e7 as jl,e8 as Nl,e9 as Ba,ea as Ha,eb as vl,Y as aa,ec as Cl,a1 as Pn,ed as Sl,aw as Va,ee as za,ef as Kr,eg as Ka,eh as fn,ei as kl,ej as Tl,ek as Wa,el as kn,T as Al,a as Ca,b as Sa,bz as Wr,d as ka,ar as Yr,i as ra,dt as us,U as Qr,a4 as Ta,cy as El,cz as Rl,cA as Ll,F as ia,cQ as la,by as Gr,aF as Dl,a$ as Xr,ax as Jr,af as Zr,cP as is,Q as Ol,dg as Ml,au as Pl,em as ei,en as ti,cV as Il,eo as $l,ep as ql,eq as Fl,er as Ul,es as Bl,h as Hl,et as Vl,bi as zl,eu as Kl,ev as Wl,ew as Yl,ex as Ql,ey as Gl,ez as Xl,ce as Jl,eA as Zl,eB as eo,eC as Ya,eD as Qa,bK as to,bW as so,bq as no,k as ao}from"./index-6GUxm5Tl.js";import{r as d,e as Oe,R as ro,h as io}from"./react-BUOzgyp0.js";import{u as lo}from"./useProductiveLoading-BO0IaMGS.js";import{b as si,u as oo}from"./useSettingsReturn-3V0Z2K8A.js";import{B as co}from"./BroadcastDialog-bNGBazRf.js";import{P as ni}from"./PageHeader-CsFfXur0.js";import{P as uo}from"./PageShell-D0GBfSfY.js";import{M as mo}from"./ModuleControlBar-Un2wShWM.js";import{M as ho}from"./ModeTabs-BYRAhe3-.js";import{C as po}from"./CampaignCreateWizard-vkleQl5x.js";import{u as Aa}from"./useContactLookup-DFTyl5zf.js";import{u as fo,v as xo,T as go,a as yo,b as bo,c as wo,d as _o,e as jo,f as No,g as vo,l as Kn,h as Co,i as So}from"./visitor-help-BtzZ2mC7.js";import{o as it}from"./contact-nav-B0Ta2B34.js";import{u as ko}from"./useDuceBot-BeI3AwB-.js";import{u as To}from"./useSelectionMode-Czy7BffF.js";import{d as Ao,t as Eo,e as ai}from"./language-BHifK4iQ.js";import{a as Ro,u as ri,C as Lo,W as Do}from"./useCallIntent-iIgGqIvV.js";import{c as Oo,m as Mo,P as oa,l as ii,u as Po,a as Io}from"./TeamAvatar-CX7lCsWL.js";import{C as li}from"./CustomerAvatar-DXYuNyPX.js";import{T as oi}from"./TeamAvatarGroup-DoJMQDUT.js";import{R as In}from"./radio-BSNd35KV.js";import{I as Ea}from"./instagram-B8Ezlogz.js";import{S as Ra}from"./smartphone-Bv32NG3H.js";import{M as _s}from"./message-circle-BaAVvJru.js";import{T as $o}from"./TemplatePicker-Bgg_UobW.js";import{m as qo,b as Fo,p as Uo,A as Bo,i as Ho}from"./RichTextEditor-ChuVxgR7.js";import{r as Vo,u as zo,b as Ga,a as Ls,C as Ko,E as Wo,s as Yo,D as Qo}from"./channel-experience-BEOSuJ2Q.js";import{s as Go}from"./sanitize-sfKXnpsX.js";import{r as ci,a as ca,C as Xo}from"./ComposeNewConversationDialog-De0kJHEJ.js";import{u as Jo,V as Zo,s as ec,r as da,O as tc,C as sc}from"./OfferHelpSheet-pKHv3CbI.js";import{r as Xa,f as nc,a as ac,u as rc,g as ic}from"./delivery-path-9gWdKkT2.js";import{C as di,h as ui,f as lc,g as oc,n as Tn,d as cc,c as dc,m as ua,A as mi,r as ls}from"./ActivityActorAvatar-7Q4yxKhm.js";import{I as uc,P as mc,W as Ja}from"./wifi-DFC_pcmF.js";import{n as La,a as hc,b as pc,M as fc}from"./contact-channels-C6DXZ5Q6.js";import{U as xc}from"./undo-2-BA1ZMI54.js";import{E as An}from"./eye-BMa0xke4.js";import{d as gc,e as yc,h as bc,i as wc,T as Za,j as _c,k as jc,l as Nc,g as wn,f as ds,D as vc,c as _n,m as ma,n as Cc,o as Sc,p as kc,q as Tc,r as Ac,C as Ec,b as Rc}from"./useLeads-DsKSjHTD.js";import{u as Lc}from"./useStartBusiness-BtMj-xLP.js";import{C as Dc}from"./calendar-plus-Y9ZLRDRx.js";import{U as hi}from"./user-DBlTe-K_.js";import{S as er}from"./SimpleDisclosure-VZmRaKZG.js";import{E as Oc}from"./EvidenceBlock-D_VAY3Vh.js";import{f as ye}from"./format-BOCe1Q81.js";import{A as Mc}from"./ActivityTrace-DdHQewDY.js";import{u as pi,a as fi,R as Pc}from"./useRecordViewers-t_BHJEGV.js";import{u as Ic}from"./useSendEmail-i2nBz5Xn.js";import{E as $c}from"./ellipsis-CAutlZKC.js";import{u as qc,a as Fc}
1from"./useIndustryLibrary-Dw3G6LuY.js";import{A as Uc}from"./arrow-down-BMPlnjnx.js";import{P as Bc}from"./paperclip-D1wmnOro.js";import{S as Hc}from"./sticky-note-BKRB5oMJ.js";import{S as ps,a as fs,b as xs,c as gs,d as Xe}from"./select-C1j_15i9.js";import{e as Vc}from"./useContacts-8U0XHgTs.js";import{e as xi,u as zc,b as ha}from"./useVisitorSessions-D_RcL8eD.js";import{S as gi}from"./share-2-CZ4zcaRo.js";import{A as Da}from"./arrow-right-left-D96rAsAg.js";import{S as Kc}from"./SimpleModal-BlVviwDy.js";import{F as Wn}from"./FieldLabel-TuIMjPm6.js";import{R as Wc}from"./floating-CZkJj3av.js";import{E as Yc}from"./eye-off-DP6aatND.js";import{C as Ct,b as jn,c as Nn,a as St}from"./card-Bpoa90g8.js";import{I as Qc}from"./image-CyeYP78T.js";import{S as pa}from"./star-BwrGBDd5.js";import{G as Gc}from"./globe-C22yugrV.js";import{u as yi}from"./ModuleIntelligence-CujC5CDF.js";import{D as Xc}from"./DataTable-CaqTwISZ.js";import{M as Jc}from"./MetricRows-ZpQc_A0y.js";import{a as Zc,L as ed,P as td}from"./PostCallActionDialog-CIp_fgbI.js";import{P as bi}from"./pencil-DC8kxVxB.js";import{P as fa,a as xa}from"./phone-outgoing-C15DWOUB.js";import{P as sd}from"./play-I9FKzQDa.js";import{u as nd,P as ad}from"./usePagination-ClGMIx77.js";import{T as rd}from"./PageSkeleton-BvzQGQKW.js";import{e as id}from"./report-utils-Chblg2Ji.js";import{p as wi}from"./page-language-DGjnPgNe.js";import{R as ld,a as od}from"./RecordCard-ks9S4c22.js";import{D as cd}from"./download-D8rVLK2a.js";import{C as dd}from"./ConnectChannelDialog-CryM10as.js";import{r as _i}from"./useTeamContribution-D3gt-sDB.js";import"./intents-B7QdDHP4.js";import{r as ud}from"./actions-BENKwVac.js";import{u as md}from"./useCapabilitySettings-DCVFhIXJ.js";import{u as hd}from"./useEmailEngine-Dzggai4m.js";import{u as pd,a as fd,r as tr,S as sr}from"./state-DQ0n84Dr.js";import{I as xd,a as gd,p as yd,b as bd,c as wd,d as _d,f as jd}from"./inbox-channel-model-w2rjWwUG.js";import{I as Nd}from"./inbox-IpoGX3gq.js";import{U as vd}from"./unplug-BQP60_uU.js";import{i as Cd}from"./isYesterday-BpvvF7Ab.js";import{i as Sd}from"./isToday-CDVfXo1I.js";import{a as kd}from"./module-insights-DIdF2rv9.js";import{A as nr}from"./AdvancedModulePanel-CQIOs9aA.js";import{S as ar}from"./square-pen-Cu7eZch0.js";import{L as Td}from"./layers-3zKAEbPs.js";import"./documents-Bju1cS7G.js";import"./charts-BjVT6r80.js";import"./settings-return-GcuqJJ7v.js";import"./useCommunicationKnowledge-BmNiCY9I.js";import"./TagChip-CQuPvvLR.js";import"./flag-MJRNLl_Q.js";import"./crown-hws5r3dX.js";import"./useReviewContext-Z5ny8VkI.js";import"./useTags-B_wGh09g.js";import"./useBroadcast-BXeJvBXh.js";import"./useBusinessProfile-CMeAwowy.js";import"./useContactGroups-CZ4ICVoa.js";import"./useBroadcastSettings-DvQUMhk3.js";import"./useSensitiveAccess-CZL_8yzA.js";import"./broadcast-model-BkpOe8no.js";import"./useConnectedChannels-h55XEIpK.js";import"./chevron-left-BO8s0r98.js";import"./variable-CNxCo4jt.js";import"./minus-DzNOUrXP.js";import"./circle-play-DeNcn8Lt.js";import"./module-intro-N0cKHpsA.js";import"./ActionChoiceSheet-Bej1gA4Q.js";import"./SearchBar-B8oDBZzP.js";import"./square-check-big-CBgkfjtW.js";import"./DirectionalScrollControls-jxYH8aR3.js";import"./radio-group-CORZjgwn.js";import"./useCampaigns-B6sFd4X0.js";import"./bookmark-plus-_Gy-vFYb.js";import"./map-pin-D8yKoJwU.js";import"./twitter-DqZOoxBv.js";import"./linkedin-BKsvXJLa.js";import"./facebook-BOZYrg5x.js";import"./useTasks-xNZM6HdJ.js";import"./useCommercialAuthority-C5K2HVSZ.js";import"./learning-lcSHoIUq.js";import"./AiAssistNote-BJD9P-1q.js";import"./events-C6DDl7qZ.js";import"./wand-sparkles-5e-vVx-4.js";import"./phone-utils-CwgknJ0K.js";import"./TeamMemberPopover-DimUaiSB.js";import"./tabs-C7nTENN3.js";import"./starter-library-BRYVBLwm.js";import"./proposal-design-DMlifeYf.js";import"./document-presentation-D5EgLi-9.js";import"./underline-mwsmAvFy.js";import"./list-DGGkzBbs.js";import"./list-ordered-D8gwkM9h.js";import"./HelpTip-Dhp2bChC.js";import"./RelationshipContactPicker-BgrKoois.js";import"./formatDistanceStrict-C9HAzcFi.js";import"./key-Be7ol9Ms.js";import"./youtube-DVQWXfeh.js";import"./calendar-clock-BrAgRcD7.js";import"./book-open-C5m3GX53.js";import"./workflow-BQhqW2ze.js";import"./settings-2-1mx35hli.js";import"./useCommercialFlow-LoFMQ_mE.js";import"./CommercialItemPicker-oz4cDl24.js";import"./useBusinessOffers-Dm4HmmtL.js";import"./useBusinessProfileData-CXmZ_ZR5.js";import"./money-BFQpx7jB.js";import"./item-language-En5V_pxE.js";import"./pen-line-9jiWvZNl.js";import"./boxes-CdymS7UW.js";import"./DealCreateModal-BCZ6UaHE.js";import"./work-context-DvBILIz9.js";import"./zod-DvQn8pkg.js";import"./export-contacts-BeyUeCA4.js";import"./index-CGSmUr7J.js";import"./spreadsheets-CKN5doRT.js";import"./AdvancedSection-CBPqO4JF.js";import"./CreateSuccessScreen-CcMPpsnv.js";import"./slider-CM1c_-pG.js";import"./calendar-4kXG8opa.js";import"./addMonths-CBp3ZtZ_.js";import"./isSameDay-BZkPoTMS.js";import"./addDays-FNsJkNgj.js";import"./startOfMonth-kO_ql4le.js";import"./subDays-BHo4iHhB.js";import"./DealTypeIcon-CdVDQ4Ux.js";import"./rotate-cw-BBLCLn01.js";import"./calendar-range-DYekGqLn.js";import"./usePipelines-BaZwYfpx.js";import"./DealContextRow-CTMaC2bx.js";
1import"./trash-2-DEbXoeSC.js";import"./useCreateOffer-x_rsTIEw.js";import"./document-format-4_kSOu4T.js";import"./ContactCreateModal-X0Osxvu6.js";import"./useFields-Igu6f0H0.js";import"./CreateTagDialog-Dp_3gY5l.js";import"./AppDialog-CEzz_wN2.js";import"./database-dY3RtVXf.js";import"./file-spreadsheet-C0YUyC8u.js";import"./upload-ByQVSpnZ.js";import"./table-CeZUCHxF.js";import"./plan-change-C_gheXyi.js";import"./useQuotes-CR6ziI7s.js";import"./url-BxF7c6Us.js";import"./useProposalTemplates-ishV6vS1.js";import"./SendInvoiceDialog-9mVKgKa1.js";import"./AmountInput-CL4QbohD.js";import"./receipt-pdf-Br3WkjKi.js";import"./useInvoices-Bf7ro_Wr.js";import"./printer-BesHXDy7.js";import"./wallet-hX8y-nkf.js";import"./invoice-pdf-C0L4ABdb.js";import"./index-CF40F76-.js";import"./useInvoiceBranding-WhXX4vrG.js";import"./usePaymentAccounts-DNvizVXu.js";import"./useCustomerDocuments-ByjXrD6a.js";import"./image-off-m_279FpP.js";import"./useDismissable-BvpILM0V.js";import"./useDisclosurePreference-CSD3NNSj.js";import"./useTraceability-DcJoQK3N.js";import"./script-starter-DOIlmTqI.js";import"./index-DuA5XNr_.js";import"./useBusinessIndustry-DWMnq4V5.js";import"./AttentionStrip-DreKh8i4.js";import"./useSmartGuide-DB5xQ_Gx.js";import"./useIntelligencePlacement-CbLnAc_a.js";import"./ContextualInsights-Gpukgl55.js";import"./thumbs-up-C_QXljbQ.js";import"./arrow-up-down-DYIY2caZ.js";import"./StatCard-BFLxrhDG.js";import"./phone-input-N3YvTTa3.js";import"./accounts-Csq2Nlwf.js";import"./actions-yEkN2hqn.js";const Ad="Ready to use.";function rr(t){return t.map(s=>s.label).join(", ")}function Ed(t){const s=t.steps??[],n=s.filter(c=>c.required!==!1),a=s.filter(c=>c.required===!1),r=n.filter(c=>!c.done),l=a.filter(c=>!c.done),i=t.deliverySteps??[],o=i.filter(c=>!c.done),u=i.length?{ready:o.length===0,missing:o,summary:o.length?`Cannot send yet: ${rr(o)}.`:"Ready to send."}:void 0,h={steps:s,missing:r,optionalMissing:l,...u?{delivery:u}:{}};return Tr(t.capability),t.entitled===!1?{...h,state:"unavailable",ready:!1,summary:"Not included in this plan."}:t.moduleOn===!1?{...h,state:"off",ready:!1,summary:"Switched off for this business."}:n.length>0&&r.length===n.length?{...h,state:"not-started",ready:!1,summary:`${n.length} step${n.length===1?"":"s"} to set this up.`}:r.length>0?{...h,state:"setup-required",ready:!1,summary:`${r.length} step${r.length===1?"":"s"} remaining: ${rr(r)}.`}:t.degraded?{...h,state:"needs-attention",ready:!0,summary:t.degradedReason??"Working, but something needs attention."}:u&&!u.ready?{...h,state:"needs-attention",ready:!0,summary:u.summary}:l.length>0?{...h,state:"partial",ready:!0,summary:`Ready. ${l.length} optional step${l.length===1?"":"s"} left.`}:{...h,state:"ready",ready:!0,summary:s.length?"Set up and ready.":Ad}}function Rd(t){return[{key:"channel",label:"Connect a way to message people",done:t.hasOperationalChannel}]}const Ld={inbox:"Connect another channel",broadcasts:"Connect another channel",bookings:"Add another booking page",domains:"Connect another domain"};function Dd(t,s,n){if(!s.ready)return n;const a=Tr(t);return(a&&Ld[a])??null}const Od=260;function Md({top:t,viewportHeight:s,viewportOffsetTop:n=0,reserveBottom:a,minHeight:r=Od}){const l=Math.max(0,a),o=Math.max(0,n)+s-Math.max(0,t)-l,u=Math.max(0,Math.min(r,s-l));return Math.max(u,Math.round(o))}function Pd({reserveBottom:t=0,enabled:s=!0}={}){const n=d.useRef(null),[a,r]=d.useState(null),l=d.useCallback(()=>{var u,h;if(!s||typeof window>"u"){r(null);return}const i=n.current;if(!i)return;const o=((u=window.visualViewport)==null?void 0:u.height)??window.innerHeight;r(Md({top:i.getBoundingClientRect().top,viewportHeight:o,viewportOffsetTop:((h=window.visualViewport)==null?void 0:h.offsetTop)??0,reserveBottom:t}))},[s,t]);return d.useEffect(()=>{var u,h,c;if(!s||typeof window>"u"){r(null);return}l();const i=()=>l();window.addEventListener("resize",i),window.addEventListener("orientationchange",i),(u=window.visualViewport)==null||u.addEventListener("resize",i),(h=window.visualViewport)==null||h.addEventListener("scroll",i);let o;return typeof ResizeObserver<"u"&&((c=n.current)!=null&&c.parentElement)&&(o=new ResizeObserver(i),o.observe(n.current.parentElement)),()=>{var f,x;window.removeEventListener("resize",i),window.removeEventListener("orientationchange",i
1),(f=window.visualViewport)==null||f.removeEventListener("resize",i),(x=window.visualViewport)==null||x.removeEventListener("scroll",i),o==null||o.disconnect()}},[s,l]),{ref:n,height:a,remeasure:l}}function Id(t){const s=ce({queryKey:["inbox-conversation-identity",t??null],...el("realtime"),enabled:!!t,queryFn:async()=>{const{data:a,error:r}=await H.rpc("inbox_conversation_identity",{_org_id:t});if(r)throw r;return a??[]}}),n=d.useMemo(()=>{const a=new Map;for(const r of s.data??[])a.set(r.conversation_id,r);return a},[s.data]);return{...s,byConversation:n}}const Yn={state:"MATCHED",needsMatch:!1,contactId:null,candidateIds:[],badge:null,reason:null,action:"none"};function $d(t){const s=(t==null?void 0:t.candidate_contact_ids)??(t==null?void 0:t.conflicting_contact_ids)??null;return Array.isArray(s)?s.filter(n=>typeof n=="string"&&n.length>0):[]}function qd(t,s){if((t==null?void 0:t.status)==="IDENTITY_CONFLICT"){const n=$d(t);return{state:"AMBIGUOUS",needsMatch:!0,contactId:null,candidateIds:n,badge:"Which customer?",reason:n.length>1?`This could be ${n.length} different customers. Choose the right one.`:"This could be more than one customer. Choose the right one.",action:"match_customer"}}return(t==null?void 0:t.status)==="RESOLVED"&&t.canonical_contact_id?{...Yn,contactId:t.canonical_contact_id}:!t&&s?{...Yn,contactId:s}:t!=null&&t.canonical_contact_id?{...Yn,contactId:t.canonical_contact_id}:{state:"UNMATCHED",needsMatch:!0,contactId:s??null,candidateIds:[],badge:"Not matched",reason:"Nobody in your customers matches this yet.",action:"match_customer"}}function Fd(t){return!t||t.status!=="RESOLVED"?null:String(t.display_name??"").trim()||null}const Ud={whatsapp:_s,instagram:Ea,sms:Ra,email:ot,livechat:In,support:wa},Bd=new Set(["instagram","messenger","linkedin","telegram"]);function ji(t){return!!t&&Bd.has(t.toLowerCase())}function ir(t){const s=t.instagram_handle||t.instagram_username||t.provider_handle||null,n=Dr({contactName:t.contact_name,providerName:t.provider_name,handle:s,phone:t.contact_phone,unknownLabel:`Unknown ${De(t.channel)} contact`});return ji(t.channel)&&ta({channelLabel:De(t.channel),handle:s,name:n})?`${n}, ${ta({channelLabel:De(t.channel),handle:s,name:n})}`:n}function Os(t){return ms(t)}const Hd={whatsapp:{icon:_s,typeLabel:"WhatsApp",settingsPath:"/settings/c
1hannels",setupLabel:"Connect WhatsApp",settingsLabel:"View channel settings"},sms:{icon:Ra,typeLabel:"SMS",settingsPath:"/settings/channels",setupLabel:"Connect SMS",settingsLabel:"View channel settings"},instagram:{icon:Ea,typeLabel:"Instagram",settingsPath:"/settings/channels",setupLabel:"Connect Instagram",settingsLabel:"View channel settings"},email:{icon:ot,typeLabel:"Email",settingsPath:"/settings?section=email",setupLabel:"Set up Email",settingsLabel:"View email settings"},livechat:{icon:In,typeLabel:"Live Chat",settingsPath:"/settings?section=livechat",setupLabel:"Set up Live Chat",settingsLabel:"View Live Chat settings"},support:{icon:wa,typeLabel:"Support",settingsPath:"/customer-care?tab=complaints",setupLabel:"Go to Support",settingsLabel:"Go to Support"}};function Vd({parentChannel:t,channelFilter:s,navigate:n,isSmtpConfigured:a,activeChannelName:r,activeChannelConnected:l}){const i=si(),o=t||(s!=="all"&&s!=="unread"&&s!=="mine"?s:null),u=o?Hd[o]:null;if(!u)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6 text-center gap-3",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-muted flex items-center justify-center",children:e.jsx(ot,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx("p",{className:"text-sm font-medium",children:"No conversations yet"}),e.jsx("p",{className:"text-xs text-muted-foreground max-w-[240px]",children:"New messages from your connected channels will appear here."})]});const h=u.icon,c=l??(o==="email"?!!a:void 0)??!1,f=(r==null?void 0:r.trim())||u.typeLabel;return e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6 text-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(h,{className:"h-6 w-6 text-primary"})}),c?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"No conversations yet"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 max-w-[260px]",children:[f," is connected and ready. New ",u.typeLabel.toLowerCase()," conversations will appear here."]})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>n(i(u.settingsPath)),children:u.settingsLabel})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium",children:[u.typeLabel," isn't connected yet"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 max-w-[260px]",children:"Connect it to start receiving conversations in this inbox."})]}),e.jsx(E,{size:"sm",onClick:()=>n(i(u.settingsPath)),children:u.setupLabel})]})]})}function zd({convo:t,selected:s,selectionMode:n,selectedIds:a,onSelect:r,onToggleSelect:l,onEnterSelectionMode:i,onArchived:o,conversationState:u="active",sourceLabels:h,intelligence:c,presence:f,presenceLoading:x}){var K,te;const C=Ar(t.channel),j=sl(t),S=Ud[t.channel]||ot,D=Os(t),g=f??null,A=ii(g),$=t._livechat_site_id||t.connected_account_id||null,b=$?(h==null?void 0:h[$])??null:null,_=b?`${b}${C!=null&&C.label?` · ${C.label}`:""}`:null,M=!!s&&ms(s)===ms(t),O=n&&(a==null?void 0:a.has(D)),U=t.unread_count>0,I=c?Ao(c.purchaseCount+c.pastPurchaseCount)??((K=Eo(c))==null?void 0:K.text)??null:null,[R,W]=d.useState(!1),J=Er(),X=nl(),Y=Oe(),w=u==="archived",L=To({onLongPress:()=>i==null?void 0:i(D),disabled:n||!i}),z=()=>{n?l==null||l(D):r(t)},N=ae=>{if(ae.stopPropagation(),n){l==null||l(D);return}if(t.contact_id){it(Y,t.contact_id);return}r(t)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{onClick:z,...L,className:B("group relative flex items-start gap-3 px-3 py-3 cursor-pointer border-b hover:bg-muted/50 transition-colors",M&&!n&&"bg-muted/70",O&&"bg-primary/10",U&&"border-l-2 border-l-warning"),children:[e.jsx("div",{className:"shrink-0",onClick:N,children:n?e.jsx("div",{className:B("flex items-center justify-center h-9 w-9 rounded-full relative",C.bg),children:e.jsx(Rr,{checked:!!O,className:"h-5 w-5",onClick:ae=>ae.stopPropagation(),onCheckedChange:()=>l==null?void 0:l(D)})}):e.jsx(li,{name:ir(t),channelIcon:S,size:"md"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:B("text-sm truncate",U&&"font-semibold"),children:ir(t)}),e.jsx("span",{className:"text-[10px] text-muted-foreground shrink-0 ml-2",children:Dn(new Date(t.last_message_at),{addSuffix:!1})})]}),t.contact_company&&!ji(t.channel)&&e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:t.contact_company}),((te=t._identity)==null?void 0:te.needsMatch)&&e.jsx("p",{className:"text-[10px] font-medium text-amber-600 dar
1k:text-amber-400 truncate mt-0.5",children:t._identity.badge}),e.jsx("p",{className:B("text-xs truncate mt-0.5",U?"text-foreground":"text-muted-foreground"),children:j.primary}),j.secondary&&e.jsx("p",{className:"text-[11px] text-muted-foreground/80 truncate",children:j.secondary}),_&&e.jsx("p",{className:"text-[10px] text-muted-foreground/70 truncate mt-0.5",children:_}),(()=>{const ae=_a({lastDirection:t.last_direction??null,lastMessageAt:t.last_message_at,unansweredSince:t.unanswered_since??null});return ae.side!=="business"?null:e.jsx("p",{className:B("text-[10px] font-medium truncate mt-0.5",ae.overdue?"text-amber-600 dark:text-amber-400":"text-muted-foreground"),children:ae.label})})(),I&&e.jsx("p",{className:"text-[10px] font-medium text-muted-foreground truncate mt-0.5",children:I}),t.channel==="ducebot"&&t.unread_count>0&&e.jsxs("div",{className:"flex items-center gap-1 mt-0.5",children:[e.jsx(Cn,{className:"h-3 w-3 text-destructive"}),e.jsx("span",{className:"text-[10px] text-destructive font-medium",children:"Escalated"})]}),t.channel==="livechat"&&(()=>{const ae=t._livechat_status,Ce=!!t._ducebot_session_id,_e=!!t.assigned_rep_id;let G,Z;return ae==="waiting"?(G="Waiting",Z="text-emerald-600"):Ce&&_e?(G="Bot → Agent",Z="text-primary"):_e?(G="Agent",Z="text-emerald-600"):Ce?(G="Bot handling",Z="text-primary"):(G="Live chat",Z="text-muted-foreground"),e.jsxs("div",{className:"flex items-center gap-1 mt-0.5",children:[e.jsx(In,{className:B("h-3 w-3",Z,ae==="waiting"&&"animate-pulse")}),e.jsx("span",{className:B("text-[10px] font-medium",Z),children:G})]})})()]}),!n&&e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",onClick:ae=>ae.stopPropagation(),children:[U&&e.jsx(ie,{"aria-label":rl(t.unread_count),className:"h-5 min-w-5 rounded-full px-1.5 flex items-center justify-center text-[10px] font-semibold tabular-nums bg-warning text-warning-foreground",children:al(t.unread_count)}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[!(g!=null&&g.owner)&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Unassigned"}),e.jsx(oi,{presence:g,noun:"conversation",unit:"reply",size:"xs",max:3,loading:x,emptyState:null})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground whitespace-nowrap",children:A})]}),!n&&e.jsx("div",{className:"shrink-0 self-center",onClick:ae=>ae.stopPropagation(),children:e.jsx("button",{type:"button","aria-label":w?ue.restoreAction:ue.action,title:w?ue.restoreAction:ue.action,disabled:X.isPending,onClick:async()=>{if(w){try{await X.mutateAsync(t),P.success(ue.restored,{description:ue.restoredDetail}),o==null||o(t)}catch(ae){P.error("Could not restore this conversation",{description:we(ae)})}return}W(!0)},className:"h-11 w-11 rounded-md flex items-center justify-center text-muted-foreground hover:bg-muted hover:text-foreground transition-colors md:opacity-0 md:group-hover:opacity-100 md:focus-visible:opacity-100",children:w?e.jsx(il,{className:"h-4 w-4"}):e.jsx(Lr,{className:"h-4 w-4"})})})]}),e.jsx(Je,{open:R,onOpenChange:W,title:ue.confirmTitle,message:ue.confirmMessage,confirmLabel:ue.action,loading:J.isPending,onConfirm:async()=>{try{await J.mutateAsync(t),P.success(ue.archived,{description:ue.archivedDetail}),W(!1),o==null||o(t)}catch(ae){P.error("Could not archive this conversation",{description:we(ae)})}}})]})}function Kd({conversations:t,selected:s,onSelect:n,parentChannel:a,onOpenWizard:r,selectionMode:l,selectedIds:i,onToggleSelect:o,onEnterSelectionMode:u,onConversationArchived:h,conversationState:c="active",sourceLabels:f,activeChannelName:x,activeChannelConnected:C,search:j="",statusFilter:S="all",peopleFilter:D="all"}){const g=Oe();si();const A=Fe(),{data:$}=ce({queryKey:["org-smtp-check",A],queryFn:async()=>{if(!A)return null;const{data:Y}=await H.from("organisations").select("settings").eq("id",A).single();return Y},enabled:!!A}),{data:b}=ce({queryKey:["org-smtp-status",A],enabled:!!A,queryFn:async()=>{const{data:Y,error:w}=await H.rpc("org_smtp_status");return w?!1:!!Y}}),{data:_}=ko(A),M=!!_,{byContact:O}=Ro(),U=t.filter(Y=>{var w;return S==="unread"&&Y.unread_count===0||S==="read"&&Y.unread_count>0?!1:j?(w=Y.contact_phone)!=null&&w.toLowerCase().includes(j.toLowerCase())?!0:tl({channel:Y.channel,subject:Y.subject,last_subject:Y.last_subject,last_message:Y.last_message,contact_name:Y.contact_name},j).matched:!0}),I=d.useMemo(()=>U.map(Y=>({key:Os(Y),conversationId:Y.conversation_id??null,contactId:Y.contact_id??null,channel:Y.channel??null,ownerId:Y.assigned_rep_id??null})),[U.map(Y=>Os(Y)).join("|")]),{presence:R,isLoading:W}=Oo(I),{data:J}=ba(),X=U.filter(Y=>Mo(R[Os(Y)],D,{meIds:[J==null?void 0:J.id,J==null?void 0:J.auth_id]}));return e.jsx("div",{className:"flex min-h-0 flex-col h-full border-r",children:e.jsx(ys,{className:"min-h-0 flex-1",children:X.length===0?c==="archived"?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx("p",{className:"text-sm font-medium",children:ue.emptyArchived}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:ue.emptyArchivedDetail})]}):D!=="all"&&U.length>0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsxs("p",{className:"text-sm font-medium",children:['No conversations match "',oa[D],'"']}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Choose Everyone to see all ",U.length," conversations again."]})]}):e.jsx(Vd,{parentChannel:a,channelFilter:S,navigate:g,isSmtpConfigured:b,isDuceBotConfigured:M,activeChannelName:x,activeChannelConnected:C}):X.map((Y,w)=>e.jsx(zd,{convo:Y,selected:s,selectionMode:l,selectedIds:i,onSelect:n,onToggleSelect:o,onEnterSelectionMode:u,onArchived:h,conversationState:c,sourceLabels:f,intelligence:Y.contact_id?O[Y.contact_id]:void 0,presence:R[Os(Y)],presenceLoa
1ding:W},`${ms(Y)}-${w}`))})})}function Wd(t,s,n){return ce({queryKey:["unified-chat-thread",t,s,n],enabled:!!t,queryFn:async()=>{var h;if(!t)return[];const{data:a,error:r}=await H.from("messages").select("*").eq("contact_id",t).in("channel",["livechat","ducebot"]).order("created_at",{ascending:!0}).limit(500);if(r)throw r;const l=(a||[]).map(c=>{let f;return c.direction==="inbound"?f="visitor":c.is_automated?f="bot":f="agent",{id:c.id,source:f,content:c.content||"",created_at:c.created_at,origin:"messages",raw:c}});let i=[];if(s){const{data:c}=await H.from("ducebot_sessions").select("id, messages, started_at").eq("id",s).maybeSingle(),f=c;if((h=f==null?void 0:f.messages)!=null&&h.length){const x=f.started_at?new Date(f.started_at).getTime():Date.now();i=f.messages.map((C,j)=>{const S=C.ts?new Date(C.ts).toISOString():new Date(x+j*1e3).toISOString(),D=C.role==="user"?"visitor":C.role==="system"?"system":"bot";return{id:`bot:${f.id}:${j}`,source:D,content:C.content||"",created_at:S,origin:"ducebot_session"}})}}const o=[...l,...i].sort((c,f)=>new Date(c.created_at).getTime()-new Date(f.created_at).getTime()),u=[];for(const c of o){const f=u[u.length-1];if(f&&f.source===c.source&&f.content.trim()===c.content.trim()&&Math.abs(new Date(c.created_at).getTime()-new Date(f.created_at).getTime())<5e3){f.origin==="ducebot_session"&&c.origin==="messages"&&(u[u.length-1]=c);continue}u.push(c)}return u},refetchInterval:5e3})}const Yd=d.forwardRef(function({value:s,onChange:n,onKeyDown:a,onSend:r,sendDisabled:l,placeholder:i,ariaLabel:o,internal:u,tools:h},c){const f=d.useRef(null);return d.useLayoutEffect(()=>{const x=f.current;x&&(x.style.height="auto",x.style.height=`${Math.min(Math.max(x.scrollHeight,64),192)}px`)},[s]),e.jsxs("div",{"data-composer":"chat",className:"shrink-0",children:[e.jsxs("div",{className:"flex items-end gap-2 min-w-0",children:[e.jsx(Bs,{ref:x=>{f.current=x,typeof c=="function"?c(x):c&&(c.current=x)},placeholder:i,value:s,onChange:x=>n(x.target.value),onKeyDown:a,rows:1,"aria-label":o,className:B("flex-1 min-w-0 resize-none min-h-16 max-h-48 overflow-y-auto rounded-2xl text-base md:text-sm max-md:min-h-[72px]",u&&"border-amber-400 focus-visible:ring-amber-400")}),e.jsx(E,{size:"icon",variant:u?"secondary":"default",onClick:r,disabled:l,"aria-label":"Send message",title:"Send message",className:B("h-11 w-11 shrink-0 rounded-full",u&&"bg-warning text-warning-foreground hover:bg-warning/90"),children:e.jsx(On,{className:"h-4 w-4"})})]}),h&&e.jsx("div",{className:"mt-1.5 flex flex-wrap items-center gap-1",children:h})]})}),Qd=["ACCOUNT_DISCONNECTED","ACCOUNT_UNHEALTHY","THREAD_NOT_FOUND","RECIPIENT_NOT_REACHABLE","PROVIDER_REJECTED","RATE_LIMITED","AUTH_EXPIRED","NETWORK_TIMEOUT","UNSUPPORTED_ACTION","UNKNOWN"],Gd=["THREAD_NOT_FOUND","PROVIDER_REJECTED","RATE_LIMITED","NETWORK_TIMEOUT","UNKNOWN"];function Xd(t){return Gd.includes(t)}function Jd(t,s="this channel"){switch(t){case"ACCOUNT_DISCONNECTED":return`Your ${s} account is not connected. Connect it, then send again.`;case"ACCOUNT_UNHEALTHY":return`Your ${s} connection needs attention. Reconnect it, then send again.`;case"THREAD_NOT_FOUND":return"This chat is still syncing. Press Sync, then try again.";case"RECIPIENT_NOT_REACHABLE":return`This customer has no ${s} address we can reach.`;case"PROVIDER_REJECTED":return`${s} did not accept the message. Nothing was sent.`;case"RATE_LIMITED":return`${s} is limiting messages right now. Try again shortly.`;case"AUTH_EXPIRED":return`Your ${s} sign-in expired. Reconnect the account, then send again.`;case"NETWORK_TIMEOUT":return"The connection timed out before the message left. Try again.";case"UNSUPPORTED_ACTION":return`${s} does not support sending this message.`;default:return"The message did not leave DuceCRM. Try again."}}class Qe extends Error{constructor(n,a,r){super(a);pn(this,"code");pn(this,"retryable");pn(this,"raw");this.name="MessageSendError",this.code=n,this.retryable=Xd(n),this.raw=r}}const Zd={PROVIDER_UNAVAILABLE:"PROVIDER_REJECTED",PROVIDER_NOT_ACCEPTED:"PROVIDER_REJECTED",PROVIDER_RATE_LIMITED:"RATE_LIMITED",ACCOUNT_NEEDS_ATTENTION:"ACCOUNT_UNHEALTHY",ACCOUNT_NOT_CONNECTED:"ACCOUNT_DISCONNECTED",MISSING_CONTACT_FIELD:"RECIPIENT_NOT_REACHABLE",CHAT_NOT_FOUND:"THREAD_NOT_FOUND"};function eu(t){const s=String(t??"").toUpperCase();return Qd.includes(s)?s:Zd[s]??"UNKNOWN"}function lt(t,s="this channel"){if(t instanceof Qe)return t;const n=t??{},a=typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:t instanceof Error?t.message:String(t??"");let r=eu(n.code);r==="UNKNOWN"&&(r=su(a));const l=a&&tu(a)?a:Jd(r,s);return new Qe(r,l,a||void 0)}function tu(t){return t.length>220?!1:!/[{}<>]|Error:|non-2xx|FunctionsHttpError/i.test(t)}function su(t){const s=t.toLowerCase();return s?s.includes("timed out")||s.includes("timeout")||s.includes("network")?"NETWORK_TIMEOUT":s.includes("rate limit")?"RATE_LIMITED":s.includes("reconnect")||s.includes("needs attention")?"ACCOUNT_UNHEALTHY":s.includes("not connected")||s.includes("connect your")?"ACCOUNT_DISCONNECTED":s.includes("syncing")||s.includes("chat yet")||s.includes("not synced")?"THREAD_NOT_FOUND":s.includes("no email")||s.includes("missing")||s.includes("no address")?"RECIPIENT_NOT_REACHABLE":s.includes("expired")||s.includes("unauthorized")?"AUTH_EXPIRED":"UNKNOWN":"UNKNOWN"}const Qn="Message not sent. Your message is saved.";function nu(){return`snd_${typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`}`}async function Ni(t,s){const{data:n}=await H.from("messages").select("id, unipile_message_id, delivery_status").eq("org_id",t).eq("client_send_key",s).maybeSingle();return n&&(!!n.unipile_message_id||["sent","provider_accepted","delivered"].includes(String(n.delivery_status??"")))?{id:n.id,unipile_message_id:n.unipile_message_id??null}:null}function lr(t,s,n){const a=s?n==null?void 0:n.find(i=>i.id===s):null,r=ci({accounts:n,channel:t,presetAccount:a&&ca(a)?a:null}),l=De(t);if(!r.best||!ca(r.best)){const i=r.block==="not_connected"?"ACCOUNT_DISCONNECTED":"ACCOUNT_UNHEALTHY",o=r.reason&&r.reason.includes(l)?r.reason:null;throw new Qe(i,o||(i==="ACCOUNT_DISCONNECTED"?`Connect your ${l} account to chat, then try again.`:`Your ${l} connection needs attention. Reconnect it, then send again.`))}return r.best}async function or(t){const{orgId:s,conversation:n,accountId:a}=t;if(n.conversation_id){const{data:i,error:o}=await H.from("conversations").select("id, unipile_chat_id").eq("id",n.conversation_id).maybeSingle();if(o)throw lt(o,De(n.channel));if(i!=null&&i.id)return{id:i.id,unipile_chat_id:i.unipile_chat_id??null}}if(!n.contact_id)return null;const{data:r,error:l}=await H.from("conversations").select("id, unipile_chat_id").eq("org_id",s).eq("connected_account_id",a).eq("contact_id",n.contact_id).order("last_message_at",{ascending:!1}).limit(1).maybeSingle();if(l)throw lt(l,De(n.channel));return r!=null&&r.id?{id:r.id,unipile_chat_id:r.unipile_chat_id??null}:null}async function Gn(t,s,n){var l,i;const{data:a,error:r}=await H.functions.invoke(t,{body:s});if(r){let o=null;try{o=await((i=(l=r.context)==null?void 0:l.json)==null?void 0:i.call(l))}catch{}throw lt(o??r,n)}if(a&&a.error)throw lt(a,n)}async function au(t){var f,x,C;const{orgId:s,conversation:n,connectedAccounts:a,content:r,clientSendKey:l}=t,i=De(n.channel),o=ll(n.channel);if(await Ni(s,l))return{delivered:!0,alreadyDelivered:!0};if(t.asInternal){if(!n.contact_id)throw new Qe("UNSUPPORTED_ACTION","Link this chat to a customer before adding an internal note.");return await t.saveLocalMessage({org_id:s,contact_id:n.contact_id,channel:n.channel,direction:"outbound",content:r,is_automated:!1,is_internal:!0,client_send_key:l}),{delivered:!0,alreadyDelivered:!1}}const h=o&&!!n.conversation_id;if(!n.contact_id&&!h)throw new Qe("RECIPIENT_NOT_REACHABLE","This conversation has no customer yet.");if(o){const j=lr(n.channel,n.connected_account_id,a);
1if(n.connected_account_id&&n.connected_account_id!==j.id){let g=H.from("conversations").update({connected_account_id:j.id});g=n.conversation_id?g.eq("id",n.conversation_id):g.eq("org_id",s).eq("contact_id",n.contact_id).eq("channel",n.channel),await g}const S=await or({orgId:s,conversation:n,accountId:j.id});if(S!=null&&S.id)return await Gn("unipile-send-message",{conversation_id:S.id,text:r,client_send_key:l,...await Xa(t.templateId,"inbox",{variant:t.templateVariant})},i),{delivered:!0,alreadyDelivered:!1};if(!n.contact_id)throw new Qe("THREAD_NOT_FOUND","This chat is still syncing - press Sync, then reply again.");return await Gn("unipile-start-conversation",{connected_account_id:j.id,contact_id:n.contact_id,text:r,client_send_key:l},i),{delivered:!0,alreadyDelivered:!1}}if(n.channel==="email"){let j=null;try{j=lr(n.channel,n.connected_account_id,a)}catch{j=null}if(j&&n.connected_account_id){const g=await or({orgId:s,conversation:n,accountId:n.connected_account_id});if(!(g!=null&&g.id))throw new Qe("THREAD_NOT_FOUND","This conversation is still syncing - press Sync, then try again.");return await Gn("unipile-send-message",{conversation_id:g.id,text:r,...t.html?{html:t.html}:{},client_send_key:l,...await Xa(t.templateId,"inbox",{variant:t.templateVariant})},i),{delivered:!0,alreadyDelivered:!1}}if(!t.sendEmailFallback||!n.contact_id)throw new Qe("ACCOUNT_DISCONNECTED",`Connect your ${i} account to send, then try again.`);const{data:S}=await H.from("contacts").select("email").eq("id",n.contact_id).maybeSingle();if(!(S!=null&&S.email))throw new Qe("RECIPIENT_NOT_REACHABLE","This customer has no email address.");if(!(await t.sendEmailFallback({to:S.email,subject:t.emailSubject??"",body:r,html:t.html??`<div style="white-space:pre-wrap;font-family:sans-serif;">${r.replace(/\n/g,"<br/>")}</div>`,contact_id:n.contact_id,thread_id:((f=t.emailReplyTo)==null?void 0:f.threadId)??null,in_reply_to:((x=t.emailReplyTo)==null?void 0:x.messageId)??null,references:((C=t.emailReplyTo)==null?void 0:C.references)??null})).success)throw new Qe("PROVIDER_REJECTED","The email was not sent.");return{delivered:!0,alreadyDelivered:!1}}const c=await t.saveLocalMessage({org_id:s,contact_id:n.contact_id,channel:n.channel,direction:"outbound",content:r,is_automated:!1,is_internal:!1,client_send_key:l});if(n.channel==="whatsapp"){const{data:j,error:S}=await H.functions.invoke("send-whatsapp",{body:{contact_id:n.contact_id,org_id:s,message:r,message_id:c==null?void 0:c.id,client_send_key:l}});if(S)throw lt(S,i);if(j&&j.success===!1)throw lt({code:j.code,error:j.error},i)}return{delivered:!0,alreadyDelivered:!1}}const ru=5*60*1e3;function iu(t,s){return{id:`pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,clientSendKey:nu(),content:t,created_at:new Date().toISOString(),state:"sending"}}function lu(t,s){if(t.length===0)return t;const n=s.filter(r=>r.direction==="outbound"),a=t.filter(r=>{if(r.state==="failed")return!0;if(r.clientSendKey&&n.some(o=>o.client_send_key===r.clientSendKey))return!1;const l=new Date(r.created_at).getTime();return!n.some(o=>{if(o.client_send_key&&o.client_send_key!==r.clientSendKey||(o.content||"").trim()!==r.content.trim())return!1;const u=new Date(o.created_at).getTime();return Math.abs(u-l)<=ru})});return a.length===t.length?t:a}const ou=["instagram","whatsapp","linkedin","messenger","telegram","email"];function Oa(t){return t?ou.includes(t):!1}function cu(t){const s=(t??"").toLowerCase();return s?Oa(s)?s:["google","gmail","outlook","microsoft","mail","imap"].includes(s)?"email":null:null}const du=12e4,uu=3e4,mu=2e4;function hu(t){if(!Oa(t.channel))return{allowed:!1,reason:"not_provider_backed"};if(!t.accountId)return{allowed:!1,reason:"no_account"};if(t.syncing)return{allowed:!1,reason:"already_syncing"};if(t.trigger==="manual")return{allowed:!0,reason:"ready"};if(!t.documentVisible)return{allowed:!1,reason:"tab_hidden"};const s=t.now??Date.now();return t.lastSyncAt!==null&&s-t.lastSyncAt<uu?{allowed:!1,reason:"too_soon"}:{allowed:!0,reason:"ready"}}function pu(t){var r;const s=(t==null?void 0:t.results)??[],n=(r=s.find(l=>l.error))==null?void 0:r.error;if(s.length>0&&n&&s.every(l=>l.error))return{inserted:0,words:"Could not reach the channel",failed:!0,error:n};const a=s.reduce((l,i)=>l+(i.inserted??0),0);return{inserted:a,failed:!1,words:a>0?`Synced ${a} new message${a===1?"":"s"}`:"Up to date"}}function fu(t){if(t.failed||t.inserted<=0)return 0;const s=Math.max(0,t.messageCountNow-t.messageCountBefore);return Math.max(0,t.inserted-s)}const xu="New message arriving...";function vi({channel:t,accountId:s,messageCount:n=0,conversationKey:a,auto:r=!0}){const l=zt(),[i,o]=d.useState(!1),[u,h]=d.useState(null),[c,f]=d.useState(0),x=d.useRef(!1),C=d.useRef(null),j=d.useRef(n),S=d.useRef();j.current=n;const D=Oa(t)&&!!s,g=d.useCallback(async(A="manual")=>{if(!hu({channel:t,accountId:s,syncing:x.current,lastSyncAt:C.current,documentVisible:typeof document>"u"?!0:document.visibilityState!=="hidden",trigger:A}).allowed)return;x.current=!0,o(!0);const b=j.current;try{const{data:_,error:M}=await H.functions.invoke("unipile-sync-messages",{body:{connected_account_id:s}});if(M)throw M;const O=pu(_);if(O.failed){h(O.error??O.words),A==="manual"&&P.error("Could not sync messages",{description:O.error});return}
1h(null),await l.invalidateQueries({queryKey:["inbox-messages"]}),await l.invalidateQueries({queryKey:["thread-messages"]}),A==="manual"&&P.success(O.words);const U=fu({inserted:O.inserted,messageCountBefore:b,messageCountNow:j.current});U>0&&(f(U),clearTimeout(S.current),S.current=setTimeout(()=>f(0),mu))}catch(_){const M=_ instanceof Error?_.message:"Could not reach the channel";h(M),A==="manual"&&P.error("Could not sync messages",{cause:_})}finally{C.current=Date.now(),x.current=!1,o(!1)}},[s,t,l]);return d.useEffect(()=>{c>0&&(f(0),clearTimeout(S.current))},[n]),d.useEffect(()=>{!r||!D||g("open")},[r,D,a]),d.useEffect(()=>{if(!r||!D)return;const A=()=>{document.visibilityState==="visible"&&g("focus")};document.addEventListener("visibilitychange",A),window.addEventListener("focus",A);const $=setInterval(()=>void g("poll"),du);return()=>{document.removeEventListener("visibilitychange",A),window.removeEventListener("focus",A),clearInterval($)}},[r,D,g]),d.useEffect(()=>()=>clearTimeout(S.current),[]),{sync:g,syncing:i,lastError:u,arriving:c,available:D}}function Ci(t,s,n){return ce({queryKey:["lead-for-conversation",t,s,n],enabled:!!(n&&(t||s)),queryFn:async()=>{if(t){const{data:a,error:r}=await H.from("leads").select("*").eq("id",t).eq("org_id",n).maybeSingle();if(!r&&a)return a}if(s){const{data:a,error:r}=await H.from("leads").select("*").eq("contact_id",s).eq("org_id",n).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(!r&&a)return a}return null}})}function gu(t,s){const n=ce({queryKey:["conversation-contact-status",t??null,s??null],enabled:!!t&&!!s,staleTime:6e4,queryFn:async()=>{const{data:a,error:r}=await H.from("contacts").select("status").eq("id",s).eq("org_id",t).maybeSingle();if(r)throw r;return(a==null?void 0:a.status)??null}});return{status:n.data??null,isLoading:n.isLoading}}function Si({open:t,onOpenChange:s,sourceContactId:n,sourceContactName:a,onLinked:r}){const{data:l=[],isLoading:i}=Aa(),o=zt(),[u,h]=d.useState(""),[c,f]=d.useState(!1),[x,C]=d.useState(null),[j,S]=d.useState([]),[D,g]=d.useState(!1);d.useEffect(()=>{if(!t||!n)return;let _=!1;return g(!0),(async()=>{const{data:M,error:O}=await H.rpc("find_duplicate_contact_suggestions",{_contact_id:n,_limit:5});_||(O?S([]):(S(M||[]),M&&M[0]&&C(M[0].contact_id)),g(!1))})(),()=>{_=!0}},[t,n]);const A=d.useMemo(()=>new Set(j.map(_=>_.contact_id)),[j]),$=d.useMemo(()=>{const _=u.trim().toLowerCase(),M=l.filter(O=>O.id!==n&&!A.has(O.id));return _?M.filter(O=>[O.full_name,O.email,O.phone,O.company,O.whatsapp_handle,O.instagram_username].filter(Boolean).join(" ").toLowerCase().includes(_)).slice(0,25):M.slice(0,20)},[l,u,n,A]),b=async()=>{if(x){f(!0);try{const{data:_,error:M}=await H.rpc("link_inbound_contact",{source_contact_id:n,target_contact_id:x});if(M)throw M;P.success("Linked - conversations moved to existing contact"),await Promise.all([o.invalidateQueries({queryKey:["inbox"]}),o.invalidateQueries({queryKey:["conversations"]}),o.invalidateQueries({queryKey:["contacts"]}),o.invalidateQueries({queryKey:["contact",x]}),o.invalidateQueries({queryKey:["leads"]})]),r==null||r(_),s(!1)}catch(_){P.error(we(_))}finally{f(!1)}}};return e.jsx(Hs,{open:t,onOpenChange:s,children:e.jsxs(Vs,{size:"md",className:"",children:[e.jsxs(zs,{children:[e.jsx(Ks,{children:"Link to existing contact"}),e.jsxs(ja,{children:["Merge ",a?e.jsx("span",{className:"font-medium",children:a}):"this new lead"," into an existing customer. Conversations, messages, notes, tasks and deals move to the target contact, and channel handles are copied so future messages stay on one record."]})]}),e.jsxs("div",{className:"space-y-3",children:[(D||j.length>0)&&e.jsxs("div",{className:"rounded-md border border-primary/20 bg-primary/5 p-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-1 py-1 text-xs font-medium text-primary",children:[e.jsx(Ps,{className:"h-3.5 w-3.5"}),D?"Scanning for duplicates...":"Likely duplicates"]}),!D&&e.jsx("div",{className:"divide-y divide-primary/10",children:j.map(_=>{const M=x===_.contact_id;return e.jsxs("button",{onClick:()=>C(_.contact_id),className:`w-full text-left px-2 py-2 rounded transition-colors ${M?"bg-primary/15":"hover:bg-primary/10"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"font-medium text-sm truncate",children:_.full_name||"Unnamed contact"}),e.jsxs(ie,{variant:"outline",className:"text-[10px] shrink-0",children:[_.score,"% match"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[_.email,_.phone,_.company].filter(
1Boolean).join(" - ")||"-"}),_.match_reasons&&_.match_reasons.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:_.match_reasons.map(O=>e.jsx(ie,{variant:"secondary",className:"text-[9px] py-0 h-4",children:O},O))})]},_.contact_id)})})]}),e.jsx(kt,{placeholder:"Search other contacts by name, email, phone, company...",value:u,onChange:_=>h(_.target.value)}),e.jsx("div",{className:"max-h-72 overflow-y-auto rounded-md border divide-y",children:i?e.jsxs("div",{className:"flex items-center justify-center py-8 text-sm text-muted-foreground",children:[e.jsx(Is,{className:"h-4 w-4 animate-spin mr-2"})," Loading contacts"]}):$.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No matching contacts"}):$.map(_=>{const M=x===_.id;return e.jsxs("button",{onClick:()=>C(_.id),className:`w-full text-left px-3 py-2 text-sm transition-colors ${M?"bg-primary/10":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:"font-medium",children:_.full_name||"Unnamed contact"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[_.email,_.phone,_.company].filter(Boolean).join(" - ")})]},_.id)})})]}),e.jsxs(Mn,{children:[e.jsx(E,{variant:"ghost",onClick:()=>s(!1),disabled:c,children:"Cancel"}),e.jsxs(E,{onClick:b,disabled:!x||c,children:[c?e.jsx(Is,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Link contact"]})]})]})})}function ki({lead:t,contactId:s,onRefetch:n,contactName:a}){const[r,l]=d.useState(!1),[i,o]=d.useState(null),[u,h]=d.useState(!1);return d.useEffect(()=>{if(!s||(t==null?void 0:t.status)==="converted"||u){o(null);return}let c=!1;return(async()=>{const{data:f,error:x}=await H.rpc("find_duplicate_contact_suggestions",{_contact_id:s,_limit:1});if(c||x)return;const C=f==null?void 0:f[0];o(C?{contact_id:C.contact_id,full_name:C.full_name,score:C.score}:null)})(),()=>{c=!0}},[s,t==null?void 0:t.status,u]),!i||!s?null:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 border-b bg-primary/10 px-3 py-1.5 text-xs sm:px-4",children:[e.jsx(Ps,{className:"h-3.5 w-3.5 shrink-0 text-primary"}),e.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",children:["Possible duplicate of"," ",e.jsx("span",{className:"font-medium text-foreground",children:i.full_name||"an existing contact"})]}),e.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-1",children:[e.jsx(E,{size:"sm",className:"h-6 px-2 text-[11px]",onClick:()=>l(!0),children:"Review & link"}),e.jsx(E,{size:"sm",variant:"ghost",className:"h-6 px-2 text-[11px]",onClick:()=>h(!0),children:"Dismiss"})]})]}),e.jsx(Si,{open:r,onOpenChange:l,sourceContactId:s,sourceContactName:a,onLinked:n})]})}function yu(t){return t.split(/\s+/).filter(Boolean).slice(0,2).map(s=>{var n;return(n=s[0])==null?void 0:n.toUpperCase()}).join("")||"?"}function Ti({name:t,subtitle:s,subject:n,avatar:a,avatarClassName:r,onBack:l,actions:i,className:o}){return e.jsxs("div",{className:B("flex items-center gap-2 border-b bg-card px-3 py-2 sm:px-4",o),children:[l&&e.jsx(E,{variant:"ghost",size:"icon",className:"h-11 w-11 shrink-0 lg:hidden",onClick:l,"aria-label":"Back to Inbox",children:e.jsx(sa,{className:"h-4 w-4"})}),e.jsx("div",{className:B("flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-primary/10 text-xs font-semibold text-primary",r),"aria-hidden":"true",children:a??yu(t)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"truncate text-sm font-semibold",children:t}),n&&e.jsx("p",{className:"truncate text-xs font-medium text-foreground/90",title:n,children:n}),s&&e.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:s})]}),i&&e.jsx("div",{className:"shrink-0",children:i})]})}function bu({contactId:t,channel:s,channelIdentity:n,onFindOrCreate:a,onComposeEmail:r,onCall:l}){const i=Na(),o=Oe(),u=Fe(),[h,c]=d.useState(!1),{data:f}=ce({queryKey:["inbox-quick-contact",t,u],enabled:h&&!!t&&!!u,staleTime:3e4,queryFn:async()=>{const{data:S,error:D}=await H.from("contacts").select("*").eq("id",t).eq("org_id",u).maybeSingle();if(D)throw D;return S??null}}),x=e.jsx(E,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",title:"Contact details","aria-label":"Contact details",children:e.jsx(uc,{className:"h-4 w-4"})}),C=(n==null?void 0:n.handle)||(n==null?void 0:n.phone)||(n==null?void 0:n.name),j=f?e.jsx(di,{contact:f,activeChannel:s??null,onCall:l,onEmail:r,onViewFullContact:()=>{c(!1),it(o,f.id)}}):t?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading contact details…"}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"Not a saved customer yet"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:C?`All we know is this ${s?De(s):"channel"} account: ${C}.`:"This conversation has no saved customer details yet."})]}),a&&e.jsxs(E,{type:"button",size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>{c(!1),a()},children:[e.jsx(Sn,{className:"h-3.5 w-3.5"}),"Find or save as customer"]})]});return i?e.jsx(e.Fragment,{children:e.jsxs(At,{open:h,onOpenChange:c,children:[e.jsx(ol,{asChild:!0,children:x}),e.jsxs(Et,{side:"bottom",className:"flex max-h-[85dvh] flex-col pb-[env(safe-area-inset-bottom)]",children:[e.jsx(Rt,{className:"text-left",children:e.jsx(Lt,{children:"Contact details"})}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto pt-2",children:j})]})]})}):e.jsxs($s,{open:h,onOpenChange:c,children:[e.jsx(qs,{asChild:!0,children:x}),e.jsx(Fs,{align:"end",className:"w-80 p-3",children:j})]})}const wu=/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,_u=/(\+?\d[\d\s().-]{6,}\d)/g,ju=/((?:https?:\/\/|www\.)[^\s<>()"']+|\b[a-z0-9-]+\.(?:com|net|org|io|co|ng|uk|shop|app|dev|me|store|africa)(?:\/[^\s<>()"']*)?)/gi,Nu=/@([A-Za-z0-9._]{2,30})\b/g,vu=[{words:/instagram|insta\b|ig\b/i,platform:"instagram"},{words:/facebook|fb\b/i,platform:"facebook"},{words:/messenger/i,platform:"messenger"},{words:/snapchat|snap\b/i,platform:"snapchat"},{words:/tiktok|tik tok/i,platform:"tiktok"},{words:/telegram/i,platform:"telegram"},{words:/linkedin/i,platform:"linkedin"},{words:/twitter|\bx\b/i,platform:"x"},{words:/youtube/i,platform:"youtube"},{words:/threads/i,platform:"threads"},{words:/pinterest/i,platform:"pinterest"},{words:/whatsapp|whats app|wa\b/i,platform:"whatsapp"}],Cu=/\b(my|mine|i am on|i'm on|you can (call|reach|email|text|message) me|reach me|call me|email me|text me|send it to me|this is my)\b/i,Su=/\b(accountant|bookkeeper|assistant|secretary|colleague|manager|my (wife|husband|partner|brother|sister|son|daughter|boss)|our (office|admin|team|accounts?)|his|her|their)\b/i,ku=/\b(invoice|invoices|billing|bill|receipt|statement|accounts? department|accounts@|finance)\b/i,Tu=/\b(old|former|previous|used to be|no longer|don'?t use|stopped using|changed (my )?(number|email))\b/i,Au=/\b(whatsapp|whats app|wa)\b/i;function xn(t,s){const n=t.slice(0,s),a=Math.max(n.lastIndexOf("."),n.lastIndexOf("!"),n.lastIndexOf("?"),n.lastIndexOf(`
2`)),r=t.slice(s),l=r.search(/[.!?\n]/),i=s+(l===-1?r.length:l+1);return t.slice(a+1,i).trim()}function gn(t,s){return s.forwarded?{ownership:"unknown",reason:"Found inside a forwarded message, so it may belong to somebody else.",confidence:.2}:Tu.test(t)?{ownership:"former",reason:"The customer described this as an old detail, so it never replaces what you hold.",confidence:.4}:ku.test(t)?{ownership:"billing",reason:"Mentioned for billing, so it may be a billing destination rather than the customer's own detail.",confidence:.5}:Su.test(t)?{ownership:"third_party",reason:"Mentioned as somebody else's detail, not the customer's own.",confidence:.5}:Cu.test(t)?{ownership:"self",reason:"The customer offered this as their own detail.",confidence:.8}:{ownership:"unknown",reason:"Nothing in the message says whose detail this is.",confidence:.3}}function Eu(t){for(const s of vu)if(s.words.test(t))return s.platform;return null}function Ru(t){return t.trim().replace(/[.,;:]$/,"")}function Lu(t,s={}){const n=(t??"").toString();if(!n.trim())return[];const a=[],r=new Set,l=o=>{const u=`${o.kind}:${o.platform??""}:${o.normalized.toLowerCase()}`;!o.normalized||r.has(u)||(r.add(u),a.push(o))},i=[];for(const o of n.matchAll(wu)){const u=o[0];i.push([o.index??0,(o.index??0)+u.length]);const h=xn(n,o.index??0),c=gn(h,s);l({kind:"email",platform:null,raw:u,normalized:u.trim().toLowerCase(),evidence:h,...c})}for(const o of n.matchAll(ju)){const u=o[0].replace(/[).,;]+$/,""),h=o.index??0;if(i.some(([j,S])=>h>=j&&h<S)||!ui(u))continue;const f=lc(u),x=xn(n,o.index??0),C=gn(x,s);if(f&&f!=="website"){const j=oc(u,f);l({kind:"social",platform:f,raw:u,normalized:(j||Tn(u)).toLowerCase(),evidence:x,...C})}else l({kind:"website",platform:"website",raw:u,normalized:Tn(u).toLowerCase(),evidence:x,...C})}for(const o of n.matchAll(_u)){const u=Ru(o[0]),h=La(u),c=h.replace(/\D/g,"");if(c.length<7||c.length>15)continue;const f=xn(n,o.index??0),x=gn(f,s),C=Au.test(f);l({kind:C?"whatsapp":"phone",platform:C?"whatsapp":null,raw:u,normalized:h,evidence:f,...x})}for(const o of n.matchAll(Nu)){const u=o[0],h=xn(n,o.index??0),c=Eu(h);if(!c)continue;const f=gn(h,s),x=c==="instagram"?hc(u):c==="x"?pc(u):u.replace(/^@/,"");l({kind:c==="whatsapp"?"whatsapp":"social",platform:c,raw:u,normalized:x.toLowerCase(),evidence:h,...f})}return a}function Du(t){switch(t.kind){case"email":return"Email found in this conversation";case"phone":return"Phone number found in this conversation";case"whatsapp":return"WhatsApp number found in this conversation";case"website":return"Website found in this conversation";default:return"Social account found in this conversation"}}function Ou(t){return t.ownership==="third_party"?["billing"]:t.ownership==="billing"?["billing"]:t.ownership==="former"?["additional"]:t.ownership==="unknown"?["additional"]:["primary","additional"]}function cr(t){switch(t.kind){case"email":return"Email";case"phone":return"Phone number";case"whatsapp":return"WhatsApp number";case"website":return"Website";default:return"Social account"}}function Mu(t,s){const n=String(s??"").trim();if(!n)return{valid:!1,problem:"Type the value you want to save."};switch(t){case"email":return/^[^\s@]+@[^\s@]+\.[^\s@]{2,}
2$/.test(n)?{valid:!0,problem:null}:{valid:!1,problem:"That does not look like an email address."};case"phone":case"whatsapp":{const a=La(n).replace(/\D/g,"");return a.length>=7&&a.length<=15?{valid:!0,problem:null}:{valid:!1,problem:"A phone number needs between 7 and 15 digits."}}case"website":return/\.[a-z]{2,}/i.test(n)?{valid:!0,problem:null}:{valid:!1,problem:"That does not look like a web address."};default:return n.length>=2?{valid:!0,problem:null}:{valid:!1,problem:"That is too short to be an account name."}}}const Ai="duce:inbox:detail-dismissals:v1",Pu=400;function Iu(t,s){const n=`${t}:${s}`.toLowerCase();let a=2166136261,r=16777619;for(let l=0;l<n.length;l+=1){const i=n.charCodeAt(l);a=(a^i)*16777619>>>0,r=(r+i*(l+7))*2654435761>>>0}return`${a.toString(36)}${r.toString(36)}`}function Ei(t,s){return`${t??"no-org"}|${s??"no-thread"}`}function Ri(t){try{const s=t.getItem(Ai);if(!s)return{};const n=JSON.parse(s);return n&&typeof n=="object"?n:{}}catch{return{}}}function $u(t,s){try{const n=Object.keys(s);for(;n.length>Pu;)delete s[n.shift()];t.setItem(Ai,JSON.stringify(s))}catch{}}function Li(){try{return typeof window<"u"&&window.localStorage?window.localStorage:null}catch{return null}}function dr(t,s,n=Li()){if(!n)return new Set;const a=Ri(n);return new Set(a[Ei(t,s)]??[])}function ur(t,s,n,a=Li()){if(!a)return;const r=Ri(a);r[Ei(t,s)]=[...new Set(n)].slice(-60),$u(a,r)}function qu(t){return t<=0?"":t===1?"1 detail to review":`${t} details to review`}const mr={email:"email",phone:"sms",whatsapp:"whatsapp"},Fu={self:"Offered as their own",third_party:"Someone else's",billing:"For billing",former:"An old detail",unknown:"Needs a decision"};function Uu({messages:t,contactId:s,contactName:n,orgId:a,conversationId:r,onViewMessage:l}){const[i,o]=d.useState(()=>
2dr(a,r)),[u,h]=d.useState(!1),[c,f]=d.useState(!1),[x,C]=d.useState(null),[j,S]=d.useState("");d.useEffect(()=>{o(dr(a,r)),h(!1),f(!1),C(null)},[a,r]);const{data:D=[]}=nc(s??void 0),{data:g=[]}=cc("contact",s??null),A=ac(),$=dc(),{data:b}=ce({queryKey:["inbox-detail-known",a??null,s??null],enabled:!!a&&!!s,staleTime:6e4,queryFn:async()=>{const{data:L,error:z}=await H.from("contacts").select("email, phone").eq("id",s).eq("org_id",a).maybeSingle();if(z)throw z;return L??null}}),_=d.useMemo(()=>{const L=new Set;for(const z of[b==null?void 0:b.email,b==null?void 0:b.phone])z&&L.add(String(z).toLowerCase());for(const z of D)L.add(String(z.value??"").toLowerCase());for(const z of g)z.handle&&L.add(z.handle.toLowerCase()),z.url&&L.add(z.url.toLowerCase());return L},[b==null?void 0:b.email,b==null?void 0:b.phone,D,g]),M=d.useMemo(()=>{const L=[],z=new Set;for(const N of t)if(!(N.direction!=="inbound"||!N.content))for(const K of Lu(N.content)){const te=`${K.kind}:${K.normalized}`;z.has(te)||_.has(K.normalized)||(z.add(te),L.push({detail:K,messageId:N.id,at:N.created_at,print:Iu(K.kind,K.normalized)}))}return L},[_,t]),O=d.useMemo(()=>M.filter(L=>!i.has(L.print)),[M,i]),U=d.useMemo(()=>M.filter(L=>i.has(L.print)),[M,i]),I=d.useCallback(L=>{o(z=>{const N=new Set(z).add(L.print);return ur(a,r,N),N})},[r,a]),R=d.useCallback(L=>{o(z=>{const N=new Set(z);return N.delete(L.print),ur(a,r,N),N})},[r,a]),W=L=>{C(L),S(L.detail.raw)},J=d.useMemo(()=>{if(!x)return null;const L=mr[x.detail.kind];if(L){const N=D.find(K=>
2String(K.channel)===L&&String(K.value??"").trim());return N?{value:String(N.value),confirmed:String(N.verification??"")==="verified"}:null}const z=g.find(N=>x.detail.platform?String(N.platform)===x.detail.platform:!1);return z?{value:String(z.handle||z.url||""),confirmed:!1}:null},[D,g,x]),X=x?Mu(x.detail.kind,j):{valid:!1,problem:null},Y=async(L,z)=>{if(!s){P.error("Save the customer first",{description:"This conversation is not linked to a customer yet."});return}if(!X.valid)return;const{detail:N}=L,K=j.trim();try{const te=mr[N.kind];te?await A.mutateAsync({contactId:s,channel:te,value:K,verification:"unverified",makePrimary:z==="primary",mirrorToContact:z==="primary",label:z==="billing"?"Billing":null,source:"inbox"}):await $.mutateAsync({entityType:"contact",entityId:s,value:K,platform:N.platform??void 0,source:"inbox",label:z==="billing"?"Billing":null}),P.success("Saved to this customer",{description:"It shows on the contact card straight away."}),I(L),C(null)}catch{P.error("That could not be saved",{description:"Try again, or add it on the customer's profile."})}};if(!O.length&&!U.length)return null;const w=c?U:O;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border-b bg-muted/30 px-3 py-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ps,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground","aria-hidden":"true"}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:O.length?qu(O.length):`${U.length} hidden`}),e.jsx(E,{size:"sm",variant:"ghost",className:"ml-auto h-8 min-w-[44px] px-2 text-xs","aria-expanded":u,"aria-controls":"detected-details-list",onClick:()=>h(L=>!L),children:u?e.jsxs(e.Fragment,{children:["Hide ",e.jsx(Mr,{className:"ml-1 h-3.5 w-3.5"})]}):e.jsxs(e.Fragment,{children:["Review ",e.jsx(bs,{className:"ml-1 h-3.5 w-3.5"})]})})]}),u&&e.jsxs("div",{id:"detected-details-list",className:"mt-1.5 space-y-1.5",children:[w.map(L=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"min-w-0 truncate",children:[cr(L.detail)," — ",e.jsx("span",{className:"font-medium",children:L.detail.raw})]}),e.jsx(ie,{variant:"outline",className:"shrink-0 text-[10px]",children:Fu[L.detail.ownership]}),e.jsx("div",{className:"ml-auto flex shrink-0 items-center gap-0.5",children:c?e.jsxs(E,{size:"sm",variant:"ghost",className:"h-8 min-w-[44px] px-2 text-xs",onClick:()=>R(L),children:[e.jsx(xc,{className:"mr-1 h-3.5 w-3.5"})," Bring back"]}):e.jsxs(e.Fragment,{children:[e.jsx(E,{size:"sm",variant:"ghost",className:"h-8 px-2 text-xs",onClick:()=>W(L),children:"Review & save"}),l&&e.jsx(E,{size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"View message",onClick:()=>l(L.messageId),children:e.jsx(An,{className:"h-3.5 w-3.5"})}),e.jsx(E,{size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":`Dismiss ${cr(L.detail)}`,onClick:()=>I(L),children:e.jsx(Dt,{className:"h-3.5 w-3.5"})})]})})]},L.print)),!w.length&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Nothing left to review here."}),U.length>0&&e.jsx(E,{size:"sm",variant:"ghost",className:"h-8 px-2 text-xs text-muted-foreground",onClick:()=>f(L=>!L),children:c?"Back to details to review":`View dismissed (${U.length})`})]})]}),e.jsx(Hs,{open:!!x,onOpenChange:L=>!L&&C(null),children:e.jsxs(Vs,{className:"max-w-md",children:[e.jsx(zs,{children:e.jsx(Ks,{children:x?Du(x.detail):""})}),x&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-md border p-2 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:"Already on this customer"}),e.jsx("p",{className:"mt-0.5 break-all font-medium",children:(J==null?void 0:J.value)??"Nothing saved yet"}),(J==null?void 0:J.confirmed)&&e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"This one is confirmed, so saving keeps it and adds the new value as an extra."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",htmlFor:"detected-detail-value",children:"From the conversation — edit it if it is not quite right"}),e.jsx(kt,{id:"detected-detail-value",value:j,onChange:L=>S(L.target.value),className:"mt-1 h-10"}),!X.valid&&X.problem&&e.jsx("p",{className:"mt-1 text-xs text-destructive",children:X.problem})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:x.detail.reason}),e.jsxs("div",{className:"rounded-md border bg-muted/40 p-2 text-xs italic",children:["“",x.detail.evidence,"”"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n?`Saving adds this to ${n}
2. It is marked as not confirmed until someone confirms it.`:"Link this conversation to a customer before saving."}),l&&e.jsxs(E,{size:"sm",variant:"ghost",className:"h-9 gap-1.5 px-2 text-xs",onClick:()=>{l(x.messageId),C(null)},children:[e.jsx(An,{className:"h-3.5 w-3.5"}),"View the original message"]})]}),e.jsxs(Mn,{className:"flex-col gap-2 sm:flex-row",children:[x&&Ou(x.detail).map(L=>e.jsxs(E,{size:"sm",variant:L==="primary"?"default":"outline",className:"h-10 gap-1.5",disabled:!s||!X.valid||A.isPending||$.isPending,onClick:()=>void Y(x,L),children:[e.jsx(Us,{className:"h-3.5 w-3.5"}),L==="primary"?"Save as the main detail":L==="billing"?"Save as a billing detail":"Save as an extra detail"]},L)),e.jsx(E,{size:"sm",variant:"ghost",className:"h-10",onClick:()=>{x&&I(x),C(null)},children:"Not right"})]})]})})]})}const En=24*60*60*1e3,Bu=2*En,Hu="Africa/Lagos";function Di(t){for(let s=t.length-1;s>=0;s-=1){const n=t[s];if(n.content&&n.content.trim())return n}return null}function Vu(t,s){try{return new Intl.DateTimeFormat("en-GB",{timeZone:s,weekday:"short",day:"numeric",month:"short",hour:"2-digit",minute:"2-digit",hour12:!1}).format(new Date(t))}catch{return null}}function zu(t,s){const n=new Date(t+En);n.setUTCHours(9,0,0,0);const a=n.getTime()<=t?n.getTime()+En:n.getTime();return new Date(a).toISOString()}function Ku(t){const s=t.now??Date.now(),n=t.timeZone??Hu,a=Di(t.messages);if(!a)return{owes:"nobody",reason:"There are no messages here yet, so there is nothing to follow up on.",due:!1,suggestedAt:null,suggestedLabel:null};const r=Math.max(0,s-new Date(a.created_at).getTime()),l=Math.floor(r/En),i=l>=1?`${l} day${l===1?"":"s"} ago`:"today";if(t.waitingSide==="business"||a.direction==="inbound")return{owes:"business",reason:`The customer wrote last (${i}) and is still waiting on you. Answer them rather than chasing.`,due:!0,suggestedAt:null,suggestedLabel:null};const o=r>=Bu,u=zu(s);return{owes:"customer",reason:o?`You wrote last (${i}) and the customer has not replied, so a short nudge is fair.`:`You wrote last (${i}). Give the customer a little longer before chasing.`,due:o,suggestedAt:u,suggestedLabel:Vu(u,n)}}const Wu=["Write ONE short customer-facing message, 2 to 4 short lines.","Answer only the customer's newest message.","Plain text. No greeting block, no letterhead, no sign-off, no signature, no name, no job title, no contact details.","Never state an invoice number, payment link, price, amount, stock level, delivery date or appointment time. If one is needed, say you will confirm it.","If the customer's message does not say what they want, ask one clear question instead of guessing."].join(`
3- `),Yu=["Write ONE short follow-up nudge, 2 to 3 short lines, to a customer who has not replied.","Refer only to what was already said in this conversation.","Plain text. No letterhead, no sign-off, no signature, no name, no job title, no contact details.","Never state an invoice number, payment link, price, amount, stock level, delivery date or appointment time.","End with one easy question that makes replying simple."].join(`
4- `);function hr(t,s){return t.slice(-s).filter(n=>n.content&&n.content.trim()).map(n=>`${n.direction==="inbound"?"Customer":"Us"}: ${n.content.trim()}`).join(`
5`)}function Qu(t){const{mode:s,messages:n,channel:a,contactName:r}=t,l=Di(n),i=(r==null?void 0:r.trim())||"the customer";if(!l)return{ok:!1,reason:"There is nothing in this conversation yet, so tell us what you want to say and we can help you shape it."};if(s==="reply")return l.direction!=="inbound"?{ok:!1,reason:`No new customer message to reply to - ${i} has not answered your last message yet.`,offer:"followup"}:{ok:!0,mode:s,basis:`Answers the newest message from ${i}.`,prompt:[`Channel: ${a||"chat"}. Keep the same conversational tone the customer is using.`,`Rules:
6- ${Wu}`,"Conversation so far:",hr(n,8),"Write the reply now."].join(`
7
8`)};const o=Ku(t);return o.owes==="business"?{ok:!1,reason:o.reason,offer:"reply"}:{ok:!0,mode:s,basis:o.reason,plan:o,prompt:[`Channel: ${a||"chat"}. Keep the same conversational tone as the conversation.`,`Rules:
9- ${Yu}`,"Conversation so far:",hr(n,6),"Write the follow-up nudge now."].join(`
10
11`)}}const Gu=/\b(?:INV|QUO|QT|PRO)[-/]?\d[\w-]*/gi,Xu=/\b(?:https?:\/\/|www\.)\S+/gi,Ju=/(?:[₦$€£]\s?\d[\d,.]*|\b(?:NGN|USD|EUR|GBP)\s?\d[\d,.]*)/gi,Zu=/^(kind regards|best regards|regards|warm regards|sincerely|yours (faithfully|sincerely)|thanks(,| and regards)?|thank you,|cheers)\b/i,em=/^(dear\b|to whom it may concern|subject\s*:)/i,pr=/\[[^\]\n]{2,40}\]/g;function tm(t,s){const n=(s||"").toLowerCase(),a=[];let r=0;const l=[];for(const u of String(t||"").split(/\r?\n/)){const h=u.trim();if(!h){l.push("");continue}if(Zu.test(h)||em.test(h)){r+=1;continue}const c=[...h.match(Gu)??[],...h.match(Xu)??[],...h.match(Ju)??[]].filter(f=>!n.includes(f.toLowerCase().replace(/[.,;)]+$/,"")));if(c.length){for(const f of c)a.includes(f)||a.push(f);continue}l.push(h)}for(;l.length&&!l[l.length-1];)l.pop();const i=l.join(`
12`).replace(/\n{3,}/g,`
13
14`).trim(),o=[...new Set([...String(t||"").match(pr)??[],...i.match(pr)??[]])];return{text:i,removedClaims:a,trimmedLines:r,placeholders:o}}function sm(t){return t.map(s=>s.content??"").join(`
15`)}function nm(t){return t.removedClaims.length?"Some details were removed because this conversation does not prove them. Add them yourself if they are right.":t.trimmedLines>0?"A greeting or sign-off was removed so this reads like a chat message.":null}function am({open:t,onOpenChange:s,conversationId:n,channel:a,suggestedName:r,handle:l,phone:i,onAdded:o}
15){const u=Oe(),[h,c]=d.useState(""),[f,x]=d.useState(""),[C,j]=d.useState(""),[S,D]=d.useState(!1);d.useEffect(()=>{t&&(c((r??l??"").trim()),x(""),j((i??"").trim()))},[t,r,l,i]);const g=async()=>{if(n){D(!0);try{const{data:$,error:b}=await H.rpc("promote_conversation_to_contact",{_conversation_id:n,_full_name:h.trim()||null,_email:f.trim()||null,_phone:C.trim()||null,_handle:l??null});if(b)throw b;const _=$;P.success("Saved as customer",{description:"This conversation is now part of their history.",action:_?{label:"Open customer",onClick:()=>it(u,_)}:void 0}),s(!1),_&&(o==null||o(_))}catch($){P.error(we($))}finally{D(!1)}}},A=cl(l);return e.jsx(Hs,{open:t,onOpenChange:s,children:e.jsxs(Vs,{className:"max-w-lg",children:[e.jsxs(zs,{children:[e.jsx(Ks,{children:"Save as customer"}),e.jsx(ja,{children:A?`${De(a)} ${A} becomes a customer you can sell to and follow up.`:`This ${De(a)} conversation becomes a customer you can sell to and follow up.`})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(rt,{htmlFor:"convo-customer-name",children:"Name"}),e.jsx(kt,{id:"convo-customer-name",value:h,onChange:$=>c($.target.value),placeholder:A??"Customer name"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(rt,{htmlFor:"convo-customer-email",children:"Email (optional)"}),e.jsx(kt,{id:"convo-customer-email",type:"email",value:f,onChange:$=>x($.target.value),placeholder:"[email protected]"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"An email or phone lets us recognise them if they also book, buy or submit a form."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(rt,{htmlFor:"convo-customer-phone",children:"Phone (optional)"}),e.jsx(kt,{id:"convo-customer-phone",value:C,onChange:$=>j($.target.value),placeholder:"08012345678"})]})]}),e.jsxs(Mn,{children:[e.jsx(E,{variant:"ghost",onClick:()=>s(!1),disabled:S,children:"Cancel"}),e.jsxs(E,{onClick:g,disabled:S||!n,children:[e.jsx(Sn,{className:"mr-2 h-4 w-4"}),S?"Saving...":"Save as customer"]})]})]})})}const rm=/^[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}$/,fr="This conversation is not linked to a saved customer yet. Save it as a customer, or link it to one you already have.",Oi=new Set(["converted","customer","won"]),im=new Set(["qualified","converted","customer","won","lost","disqualified"]);function lm(t){const s=t.contactId&&rm.test(t.contactId)?t.contactId:null,n=t.lead??null,a=(n==null?void 0:n.id)??null,r=t.mayQualify!==!1,l=t.mayEditContacts!==!1;if(s)return{kind:"linked",contactId:s,leadId:a,showViewContact:!0,showViewLead:!1,showSaveAsContact:!1,showLinkToContact:!1,showQualify:!1,unlinkedExplanation:null};if(n){const i=Oi.has((n.status??"").toLowerCase());return{kind:"unlinked_lead",contactId:null,leadId:a,showViewContact:!1,showViewLead:!0,showSaveAsContact:!i&&l,showLinkToContact:l,showQualify:!im.has((n.status??"").toLowerCase())&&r,unlinkedExplanation:fr}}return{kind:"unknown",contactId:null,leadId:null,showViewContact:!1,showViewLead:!1,showSaveAsContact:l,showLinkToContact:!1,showQualify:!1,unlinkedExplanation:fr}}function om(t){const{contactStatus:s,leadStatus:n,linked:a}=t;if(a){const l=(s??"").toLowerCase();return l?l==="lead"?"Lead":l==="prospect"?"Prospect":l==="customer"||l==="active"?"Customer":l==="churned"||l==="inactive"?"Churned":s??null:"Customer record"}const r=(n??"").toLowerCase();return r?Oi.has(r)?"Customer":"Lead":null}function Mi({lead:t,contactId:s,orgId:n,onRefetch:a,contactName:r,contactEmail:l,conversationId:i,channel:o,providerHandle:u,providerName:h,providerPhone:c,extraItems:f,onArchiveConversation:x,onToggleContactPanel:C,contactPanelOpen:j}){const S=Oe(),{openStartBusiness:D,element:g}=Lc(),A=gc(),$=yc(),{data:b=[]}=ws(n),[_,M]=d.useState(!1),[O,U]=d.useState(!1),[I,R]=d.useState(null),{hasPermission:W}=na("leads.qualify"),{hasPermission:J}=na("contacts.edit"),X=lm({contactId:s,lead:t?{id:t.id,status:t.status,contact_id:t.contact_id}:null,mayQualify:W,mayEditContacts:J}),Y=t!=null&&t.assigned_rep_id?b.find(N=>N.id===t.assigned_rep_id):null;d.useEffect(()=>{if(!s){R(null);return}let N=!1;return(async()=>{var te;const{data:K}=await H.from("deals").select("id").eq("contact_id",s).not("stage","in","(won,lost,closed_won,closed_lost)").or("is_archived.is.null,is_archived.eq.false").order("created_at",{ascending:!1}).limit(1);N||R(((te=K==null?void 0:K[0])==null?void 0:te.id)??null)})(),()=>{N=!0}},[s]);const w=async()=>
15{if(t)try{await A.mutateAsync({id:t.id,status:"qualified"}),a(),P.success("Lead qualified")}catch(N){P.error(we(N))}},L=async()=>{if(!(!t||!n))try{await $.mutateAsync({leadId:t.id,orgId:n,contactData:{full_name:r||"Unknown",email:l||null}}),a(),P.success("Saved as contact")}catch(N){P.error(we(N))}},z=async N=>{if(t)try{await A.mutateAsync({id:t.id,assigned_rep_id:N}),a();const K=b.find(te=>te.id===N);P.success(`Assigned to ${(K==null?void 0:K.full_name)||"team member"}`)}catch(K){P.error(we(K))}};return e.jsxs(e.Fragment,{children:[e.jsxs(Pr,{children:[e.jsx(Ir,{asChild:!0,children:e.jsxs(E,{size:"sm",variant:"outline",className:"h-8 text-xs",children:["Actions ",e.jsx(bs,{className:"ml-1 h-3 w-3"})]})}),e.jsxs($r,{align:"end",className:"w-56",children:[X.showViewContact&&X.contactId&&e.jsxs(pe,{onSelect:()=>it(S,X.contactId),children:[e.jsx(hs,{className:"mr-2 h-4 w-4"})," View contact"]}),X.kind!=="linked"&&i&&e.jsxs(pe,{onSelect:()=>U(!0),children:[e.jsx(Sn,{className:"mr-2 h-4 w-4"})," Save as customer"]}),X.showViewLead&&t&&e.jsxs(pe,{onSelect:()=>S(`/leads?lead_id=${t.id}`),children:[e.jsx(hs,{className:"mr-2 h-4 w-4"})," View enquiry"]}),X.showSaveAsContact&&t&&!i&&e.jsxs(pe,{onSelect:L,disabled:$.isPending,children:[e.jsx(Sn,{className:"mr-2 h-4 w-4"})," Save as contact"]}),X.showQualify&&e.jsxs(pe,{onSelect:w,disabled:A.isPending,children:[e.jsx(qr,{className:"mr-2 h-4 w-4"})," Qualify"]}),X.showLinkToContact&&s&&e.jsxs(pe,{onSelect:()=>M(!0),children:[e.jsx(Or,{className:"mr-2 h-4 w-4"})," Link to contact"]}),s&&e.jsxs(e.Fragment,{children:[e.jsx(cs,{}),e.jsxs(pe,{onSelect:()=>D({contactId:s,name:r??null,email:l??null,phone:c??null}),children:[e.jsx(ul,{className:"mr-2 h-4 w-4"})," ",dl]}),I?e.jsxs(pe,{onSelect:()=>S(`/deals?deal_id=${I}`),children:[e.jsx(qa,{className:"mr-2 h-4 w-4"})," View deal"]}):e.jsxs(pe,{onSelect:()=>S(`/deals?create=true&contact_id=${s}`),children:[e.jsx(qa,{className:"mr-2 h-4 w-4"})," Create deal"]}),e.jsxs(pe,{onSelect:()=>S(`/tasks?action=create&contact=${s}`),children:[e.jsx(Dc,{className:"mr-2 h-4 w-4"})," Add follow-up"]})]}),t&&e.jsxs(e.Fragment,{children:[e.jsx(cs,{}),Y?e.jsxs(ml,{className:"text-[11px] font-normal text-muted-foreground",children:["Assigned to ",Y.full_name||"team member"]}):b.length>0?e.jsxs(Fr,{children:[e.jsxs(Ur,{children:[e.jsx(Tt,{className:"mr-2 h-4 w-4"})," Assign rep"]}),e.jsx(Br,{className:"w-52",children:b.map(N=>e.jsx(pe,{onSelect:()=>z(N.id),disabled:A.isPending,children:N.full_name||"Unnamed"},N.id))})]}):null]}),f&&e.jsxs(e.Fragment,{children:[e.jsx(cs,{}),f]}),C&&s&&e.jsxs(e.Fragment,{children:[e.jsx(cs,{}),e.jsxs(pe,{className:"hidden md:flex",onSelect:C,children:[e.jsx(hi,{className:"mr-2 h-4 w-4"}),j?"Hide contact panel":"Show contact panel"]})]}),x&&e.jsxs(e.Fragment,{children:[e.jsx(cs,{}),e.jsxs(pe,{onSelect:N=>{N.preventDefault(),x()},children:[e.jsx(Lr,{className:"mr-2 h-4 w-4"})," ",ue.action]})]})]})]}),s&&e.jsx(Si,{open:_,onOpenChange:M,sourceContactId:s,sourceContactName:r,onLinked:a}),i&&e.jsx(am,{open:O,onOpenChange:U,conversationId:i,channel:o||"inbox",suggestedName:h||r,handle:u,phone:c,onAdded:a}),g]})}function cm(t){if(!t||t<60)return`${t||0}s`;const s=Math.floor(t/60),n=t%60;return n?`${s}m ${n}s`:`${s}m`}function xr(t){if(!t)return null;try{return new URL(t).pathname}catch{return t}}const Pi={hot:"Hot",warm:"Warm",cold:"Cold"},dm={new:"New",contacted:"Contacted",qualified:"Qualified",converted:"Converted"};function Ii(t){const{lead:s,isLiveChat:n,sessionStatus:a,channelLabel:r,linked:l,contactStatus:i}=t;if(n&&!s)return`Live Chat • ${a==="waiting"?"Waiting":a==="closed"?"Closed":a==="escalated"?"Escalated":"Active"}`;const o=om({contactStatus:i,leadStatus:(s==null?void 0:s.status)??null,linked:!!l})||r||"Conversation",u=s!=null&&s.temperature?Pi[s.temperature]||"Cold":null;return u?`${o} • ${u}`:o}function $i({lead:t,channel:s,repName:n,lastActivityAt:a,visitorStats:r,pageViews:l=[],auditEntries:i=[],onReply:o,onAddFollowUp:u,rememberKey:h="insights:conversation"}){var g;const c=[];t&&(c.push({id:"score",text:`Lead score: ${t.score??0}.`}),t.temperature&&c.push({id:"temp",text:`Temperature: ${Pi[t.temperature]||t.temperature}.`}),c.push({id:"status",text:`Status: ${dm[t.status||""]||t.status||"New"}.`}),t.source&&c.push({id:"source",text:`Source: ${t.source}.`})),n&&c.push({id:"rep",text:`Assigned to ${n}.`}
15),a&&c.push({id:"last",text:`Last activity ${Dn(new Date(a),{addSuffix:!0})}.`});const f=xr(r==null?void 0:r.current_page);f&&c.push({id:"page",text:`Currently viewing ${f}.`}),r!=null&&r.is_returning&&c.push({id:"returning",text:"Returning visitor - they have been here before."}),r!=null&&r.page_count&&c.push({id:"pages",text:`Viewed ${r.page_count} page${r.page_count===1?"":"s"}.`});const x=(t==null?void 0:t.temperature)==="hot"||((t==null?void 0:t.score)??0)>=60,C=!!f&&/pric|plan|checkout|buy/i.test(f),j={observed:c,prediction:x||C||r!=null&&r.is_returning?{text:C?"Purchase interest may be high right now.":"This conversation may be worth prioritising today.",confidence:x&&C?"high":"medium",basis:[C?"They are on a pricing or checkout page.":null,r!=null&&r.is_returning?"They have returned to the site.":null,x?"Lead score and temperature are elevated.":null].filter(Boolean).join(" ")}:void 0,recommendation:o||u?{text:C||r!=null&&r.is_returning?"Reply now while they are still on the site.":"Reply, or set a follow-up so this does not go quiet.",actions:[...o?[{id:"reply",label:"Reply",onClick:o,primary:!0}]:[],...u?[{id:"followup",label:"Add follow-up",onClick:u}]:[]]}:void 0},S=[];(r!=null&&r.city||r!=null&&r.country)&&S.push(["Location",[r.city,r.country].filter(Boolean).join(", ")]),r!=null&&r.browser&&S.push(["Browser",r.browser]),r!=null&&r.os&&S.push(["Operating system",r.os]),r!=null&&r.device_type&&S.push(["Device",r.device_type]),r!=null&&r.total_time_seconds&&S.push(["Time on site",cm(r.total_time_seconds)]),r!=null&&r.current_page&&S.push(["Current URL",r.current_page]);const D=S.length>0||l.length>0||i.length>0;return e.jsx(er,{title:"Insights",summary:((g=c[0])==null?void 0:g.text)??"Context on this conversation",defaultOpen:!1,rememberKey:h,className:"mx-3 my-2 rounded-lg sm:mx-4",children:e.jsxs("div",{className:"space-y-3 p-3",children:[e.jsx(Oc,{observed:j.observed,prediction:j.prediction,recommendation:j.recommendation,emptyText:"Nothing recorded for this conversation yet."}),D&&e.jsx(er,{title:"More details",defaultOpen:!1,rememberKey:`${h}:details`,className:"rounded-lg",children:e.jsxs("div",{className:"space-y-3 p-3 text-xs",children:[S.length>0&&e.jsx("dl",{className:"space-y-1",children:S.map(([A,$])=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"w-32 shrink-0 text-muted-foreground",children:A}),e.jsx("dd",{className:"min-w-0 break-all",children:$})]},A))}),l.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Page journey"}),l.slice(0,10).map(A=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate flex-1 font-mono",children:xr(A.page_url)}),e.jsx("span",{className:"shrink-0 text-muted-foreground/60",children:ye(new Date(A.viewed_at),"h:mm a")})]},A.id))]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:"History"}),i.map(A=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate",children:A.action==="livechat_close"?`Closed by ${A.user_name||"team member"}`:`Transferred to ${A.target_name||"team member"} by ${A.user_name||"team member"}`}),e.jsx("span",{className:"shrink-0 text-muted-foreground/60",children:ye(new Date(A.created_at),"MMM d, h:mm a")})]},A.id))]})]})})]})})}const um=/^\s*(on\b.*|.*\bwrote\s*:?\s*)$/i,gr=/\bwrote\s*:?\s*$/i,mm=[/^\s*-{2,}\s*original message\s*-{2,}\s*$/i,/^\s*_{10,}\s*$/,/^\s*-{10,}\s*$/,/^\s*from:\s*.+$/i,/^\s*(sent from my (iphone|ipad|android|mobile|samsung|device).*)$/i,/^\s*get outlook for (ios|android)\s*$/i],hm=/^\s*--\s*$/,pm=/^\s*>/;function fm(t){for(let s=0;s<t.length;s++){const n=t[s];if(mm.some(a=>a.test(n))||hm.test(n)||pm.test(n)||um.test(n)&&gr.test(n))return s;if(/^\s*on\b/i.test(n)){for(let a=s;a<Math.min(t.length,s+4);a++)if(gr.test(t[a]))return s}}return-1}function xm(t){if(!t)return{reply:"",quoted:""};const s=t.replace(/\r\n?/g,`
16`).split(`
17`),n=fm(s);if(n<0)return{reply:t.trim(),quoted:""};const a=s.slice(0,n).join(`
18`).replace(/\s+$/,""),r=s.slice(n).join(`
19`).trim();return a.trim()?{reply:a,quoted:r}:{reply:t.trim(),quoted:""}}const gm=/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,ym=/(?:https?:\/\/|www\.)[^\s<>()"']+/gi,bm=/(?:\+?\d[\d\s().-]{6,}\d)/g;function Xn(t,s,n){const a=[];for(const r of t.matchAll(s)){const l=r[0].replace(/[).,;:]+$/,"");if(!l)continue;const i=n(l);if(!i)continue;const o=r.index??0;a.push({start:o,end:o+l.length,piece:i})}return a}function wm(t){try{const s=new URL(Tn(t));return s.protocol==="http:"||s.protocol==="https:"}catch{return!1}}function _m(t){const s=(t??"").toString();if(!s)return[];
19const n=[...Xn(s,gm,i=>({kind:"email",text:i,value:i.toLowerCase()})),...Xn(s,ym,i=>{if(!wm(i))return null;const o=Tn(i),u=ui(i);return u?{kind:"link",text:i,value:o,href:o,host:u}:null}),...Xn(s,bm,i=>{const o=La(i),u=o.replace(/\D/g,"");return u.length<7||u.length>15?null:{kind:"phone",text:i,value:o}})],a=[];for(const i of n)a.some(u=>i.start<u.end&&u.start<i.end)||a.push(i);a.sort((i,o)=>i.start-o.start);const r=[];let l=0;for(const i of a)i.start>l&&r.push({kind:"text",text:s.slice(l,i.start)}),r.push(i.piece),l=i.end;return l<s.length&&r.push({kind:"text",text:s.slice(l)}),r}function jm(){const[t,s]=d.useState(null);return{copied:t,copy:async a=>{try{await navigator.clipboard.writeText(a),s(a),window.setTimeout(()=>s(r=>r===a?null:r),1600)}catch{P.error("That could not be copied",{description:"Select the text and copy it instead."})}}}}function Nm({piece:t,actions:s}){const{copied:n,copy:a}=jm(),r=t.value??t.text;if(t.kind==="link")return e.jsxs($s,{children:[e.jsx(qs,{asChild:!0,children:e.jsx("button",{type:"button",className:"underline decoration-dotted underline-offset-2 hover:
19decoration-solid","aria-label":`Link to ${t.host}`,children:t.text})}),e.jsxs(Fs,{align:"start",className:"w-72 space-y-2 p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"This link goes to"}),e.jsx("p",{className:"break-all text-sm font-medium",children:t.host}),e.jsx("p",{className:"break-all text-[11px] text-muted-foreground",children:t.href}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(E,{size:"sm",variant:"outline",className:"gap-1.5",asChild:!0,children:e.jsxs("a",{href:t.href,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(hs,{className:"h-3.5 w-3.5"}),"Open"]})}),e.jsxs(E,{size:"sm",variant:"ghost",className:"gap-1.5",onClick:()=>a(r),children:[n===r?e.jsx(Us,{className:"h-3.5 w-3.5"}):e.jsx(Fa,{className:"h-3.5 w-3.5"}),"Copy"]})]})]})]});const l=t.kind==="phone";return e.jsxs($s,{children:[e.jsx(qs,{asChild:!0,children:e.jsx("button",{type:"button",className:"underline decoration-dotted underline-offset-2 hover:decoration-solid","aria-label":l?`Phone number ${t.text}`:`Email address ${t.text}`,children:t.text})}),e.jsxs(Fs,{align:"start",className:"w-64 space-y-2 p-3",children:[e.jsx("p",{className:"break-all text-sm font-medium",children:t.text}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[l?s.onCall?e.jsxs(E,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>{var i;return(i=s.onCall)==null?void 0:i.call(s,r)},children:[e.jsx(Ht,{className:"h-3.5 w-3.5"}),"Call"]}):e.jsx(E,{size:"sm",variant:"outline",className:"gap-1.5",asChild:!0,children:e.jsxs("a",{href:`tel:${r}`,children:[e.jsx(Ht,{className:"h-3.5 w-3.5"}),"Call"]})}):s.onEmail?e.jsxs(E,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>{var i;return(i=s.onEmail)==null?void 0:i.call(s,r)},children:[e.jsx(ot,{className:"h-3.5 w-3.5"}),"Compose email"]}):e.jsx(E,{size:"sm",variant:"outline",className:"gap-1.5",asChild:!0,children:e.jsxs("a",{href:`mailto:${r}`,children:[e.jsx(ot,{className:"h-3.5 w-3.5"}),"Compose email"]})}),e.jsxs(E,{size:"sm",variant:"ghost",className:"gap-1.5",onClick:()=>a(r),children:[n===r?e.jsx(Us,{className:"h-3.5 w-3.5"}):e.jsx(Fa,{className:"h-3.5 w-3.5"}),"Copy"]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:l?"Opening the dialler does not record a call.":"Opening the composer does not send anything."})]})]})}function vm({text:t,actions:s={},keyPrefix:n=""}){const a=_m(t);return a.every(r=>r.kind==="text")?e.jsx(e.Fragment,{children:t}):e.jsx(e.Fragment,{children:a.map((r,l)=>r.kind==="text"?e.jsx("span",{children:r.text},`${n}t${l}`):e.jsx(Nm,{piece:r,actions:s},`${n}a${l}`))})}function Ms({content:t,className:s,trimQuoted:n,actions:a}){const[r,l]=ro.useState(!1);if(!t)return null;const i=Cm(t)?Sm(t):t,{reply:o,quoted:u}=n?xm(i):{reply:i,quoted:""};return u?e.jsxs("span",{className:s,children:[Jn(o,a),e.jsx("button",{type:"button",onClick:()=>l(h=>!h),className:"mt-1.5 block text-[11px] underline underline-offset-2 opacity-60 hover:opacity-100",children:r?"Hide quoted text":"Show quoted text"}),r&&e.jsx("span",{className:"mt-1.5 block border-l-2 border-current/20 pl-2 text-xs opacity-60",children:Jn(u,a)})]}):e.jsx("span",{className:s,children:Jn(o,a)})}function Jn(t,s){const n=t.split(`
20`),a=[];let r=[];const l=()=>{r.length>0&&(a.push(e.jsx("ul",{className:"list-disc pl-4 my-1 space-y-0.5",children:r},`ul-${a.length}`)),r=[])};return n.forEach((i,o)=>{const u=i.match(/^[\*\-]\s+(.+)/);if(u){r.push(e.jsx("li",{children:yr(u[1],s,`l${o}`)},o));return}l(),i.trim()===""?a.push(e.jsx("br",{},o)):a.push(e.jsxs("span",{children:[yr(i,s,`r${o}`),o<n.length-1&&e.jsx("br",{})]},o))}),l(),e.jsx(e.Fragment,{children:a})}function yr(t,s,n=""){const a=(u,h)=>e.jsx(vm,{text:u,actions:s,keyPrefix:h},h),r=[],l=/(\*\*(.+?)\*\*|\*(.+?)\*)/g;let i=0,o;for(;(o=l.exec(t))!==null;)o.index>i&&r.push(a(t.slice(i,o.index),`${n}p${o.index}`)),o[2]?r.push(e.jsx("strong",{children:o[2]},o.index)):o[3]&&r.push(e.jsx("em",{children:o[3]},o.index)),i=l.lastIndex;return i<t.length&&r.push(a(t.slice(i),`${n}p${i}`)),r}function Cm(t){return/<\/?[a-zA-Z][^>]*>/.test(t)}function Sm(t){var n;let s=t;if(s=s.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,""),s=s.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,""),typeof window<"u"&&typeof window.DOMParser<"u")try{const a=new DOMParser().parseFromString(s,"text/html");a.querySelectorAll(".gmail_quote, blockquote").forEach(r=>r.remove()),a.querySelectorAll("br").forEach(r=>r.replaceWith(`
21`)),a.querySelectorAll("p, div, li, tr, h1, h2, h3, h4, h5, h6").forEach(r=>{r.append(`
22`)}),s=((n=a.body)==null?void 0:n.textContent)??""}catch{}return s=s.replace(/<(blockquote|div)\b[^>]*class="[^"]*gmail_quote[^"]*"[^>]*>[\s\S]*?<\/\1>/gi,""),s=s.replace(/<blockquote\b[^>]*>[\s\S]*?<\/blockquote>/gi,""),s=s.replace(/<\/?(p|div|br|li|tr|h[1-6])\b[^>]*>/gi,`
23`),s=s.replace(/<[^>]+>/g,""),s=s.replace(/&nbsp;/gi," ").replace(/&amp;/gi,"&").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&#39;|&apos;/gi,"'").replace(/&#(\d+);/g,(a,r)=>String.fromCharCode(parseInt(r,10))),s=s.replace(/\r\n?/g,`
24`),s=s.replace(/[ \t]+\n/g,`
25`),s=s.replace(/\n{3,}/g,`
26
27`),s=s.replace(/[ \t]{2,}/g," "),s.trim()}async function Ge({action:t,phase:s,orgId:n,userId:a,referenceId:r,metadata:l}){if(n)try{await H.from("activity_log").insert({org_id:n,user_id:a??null,activity_type:`destructive_action_${s}`,description:`${t} ${s}`,metadata:{action:t,phase:s,reference_id:r??null,...l??{}}})}catch{}}const km="Try again",Tm="Report problem",ga=new Map;function Am(t,s){const n=s instanceof Error?s.message:typeof s=="string"?s:s&&typeof s=="object"?String(s.code??s.message??""):"";return`${t}|${n.slice(0,120).toLowerCase()}`}function Em(t){const s=(ga.get(t)??0)+1;return ga.set(t,s),s}function Rm(t){ga.delete(t)}function Lm(t){return t==="SCHEMA_CONTRACT_ERROR"||t==="PARTIAL_OPERATION"?1:t==="DATABASE_ERROR"||t==="SERVER_ERROR"?2:3}function Dm(t,s){return t>=s?3:t>=2?2:1}
27function Om(t){const s=hl(t.cause,{message:t.message}),n=s.category==="VALIDATION_ERROR"||s.category==="DUPLICATE"||s.category==="MISSING_REQUIRED_DATA"||pl(t.cause),a=s.category==="NETWORK_ERROR"||fl(t.cause),r=s.userMessage,l=Lm(s.category),i=n||a?1:Dm(t.attempts,l);return{level:i,message:r,hint:i>=2||s.retryability==="engineering_required"?s.userAction:void 0,fix:s.fix,canReport:i>=3&&!n&&!a,retryable:t.retryable??s.retryable,businessOutcome:n,transient:a,category:s.category,retryability:s.retryability,severity:s.severity}}function Mm({recovery:t,onRetry:s,onReport:n,busy:a,alternative:r,className:l}){if(!t)return null;const i=t.level>=2&&!t.businessOutcome;return e.jsxs("div",{role:"status",className:B("space-y-1.5 rounded-md border px-2.5 py-2",i?"border-warning/40 bg-warning/5":"border-border bg-muted/40",l),children:[e.jsxs("p",{className:"flex items-center gap-1.5 text-xs font-medium text-foreground",children:[i&&e.jsx(Cn,{className:"h-3.5 w-3.5 text-warning","aria-hidden":"true"}),t.message]}),t.hint&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:t.hint}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.retryable&&e.jsxs(E,{type:"button",size:"sm",variant:"outline",className:"h-7 text-xs",disabled:a,onClick:s,children:[e.jsx(Hr,{className:"mr-1 h-3 w-3"})," ",km]}),t.fix&&e.jsx(E,{asChild:!0,type:"button",size:"sm",variant:"ghost",className:"h-7 text-xs",children:e.jsx("a",{href:t.fix.href,children:t.fix.label})}),r,t.canReport&&n&&e.jsxs(E,{type:"button",size:"sm",variant:"ghost",className:"h-7 text-xs",onClick:n,children:[e.jsx(xl,{className:"mr-1 h-3 w-3"})," ",Tm]})]})]})}function br({actions:t,onSelect:s,open:n,onOpenChange:a,align:r="end",onPrimary:l,className:i}){if(t.length===0)return null;const o=t.filter(h=>!h.secondary),u=t.filter(h=>h.secondary);return e.jsxs(Pr,{open:n,onOpenChange:a,children:[e.jsx(Ir,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":"Message actions",onPointerDown:h=>h.stopPropagation(),onClick:h=>h.stopPropagation(),className:B("shrink-0 rounded p-1 transition-opacity","opacity-100 sm:opacity-0 sm:group-hover:opacity-100 sm:focus-visible:opacity-100",l?"hover:bg-primary-foreground/20":"hover:bg-muted/80",i),children:e.jsx($c,{className:B("h-3.5 w-3.5",l?"text-primary-foreground/80":"text-muted-foreground")})})}),e.jsxs($r,{align:r,className:"w-48",children:[o.map(h=>e.jsx(pe,{className:"text-xs",onClick:()=>s(h.key),children:h.label},h.key)),u.length>0&&o.length>0&&e.jsx(cs,{}),u.map(h=>e.jsx(pe,{className:B("text-xs",h.destructive&&"text-destructive focus:text-destructive"),onClick:()=>s(h.key),children:h.label},h.key))]})]})}function Pm(){const[t,s]=d.useState(null);return{openId:t,isOpen:n=>t===n,open:n=>s(n),setOpen:(n,a)=>s(a?n:null),close:()=>s(null)}}const ve={copy:"Copy message",copied:"Message copied",copyFailed:"Could not copy that message",reply:"Reply",reuse:"Use as new message",reused:"Copied into your message box",reusedDetail:"Edit it, then send it as a new message.",saveTemplate:"Save as template",delete:"Delete",replaceTitle:"Replace what you are writing?",replaceMessage:"Your message box already has text. Using this message will replace it.",replaceConfirm:"Replace it",immutableNote:"Sent and received messages are kept exactly as they were."};function Im(t){return!!(t.content&&t.content.trim().length>0)}function wr(t,s){const n=[],a=Im(t);return a&&n.push({key:"copy",label:ve.copy}),t.isInternal||n.push({key:"reply",label:ve.reply}),a&&n.push({key:"reuse",label:ve.reuse}),a&&!t.isInternal&&s.canSaveTemplate&&n.push({key:"save_template",label:ve.saveTemplate}),s.canDelete&&n.push({key:"delete",label:ve.delete,secondary:!0,destructive:!0}),n}async function $m(t){var n;const s=(t??"").trim();if(!s)return!1;try{if((n=navigator==null?void 0:navigator.clipboard)!=null&&n.writeText)return await navigator.clipboard.writeText(s),!0}catch{}try{const a=document.createElement("textarea");a.value=s,a.setAttribute("readonly","true"),a.style.position="fixed",a.style.opacity="0",document.body.appendChild(a),a.select();const r=document.execCommand("copy");return document.body.removeChild(a),r}catch{return!1}}function qm(t){const s=(t??"").trim();return s?`${s.split(`
28`).slice(0,6).map(a=>`> ${a}`).join(`
29`)}
30
31`:""}function Fm(t){const s=(t??"").trim().split(`
32`)[0]??"";return(s.length>48?`${s.slice(0,45)}...`:s)||"Message template"}const Um=t=>t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/(^|\s)\*(\S.*?\S?)\*(?=\s|$)/g,"$1$2").replace(/^\s*[\*\-]\s+/gm,"• ").replace(/`([^`]+)`/g,"$1").replace(/_{1,2}([^_]+)_{1,2}/g,"$1").trim(),Bm={whatsapp:_s,instagram:Ea,sms:Ra,email:ot},Hm=new Set(["instagram","messenger","linkedin","telegram"]);function Vm(t){return!!t&&Hm.has(t.toLowerCase())}function zm(t,s,n){const a=s?n==null?void 0:n.find(l=>l.id===s):null;return ci({accounts:n,channel:t,presetAccount:a&&ca(a)?a:null}).best}function _r({conversation:t,orgId:s,isLiveChat:n,sourceLabel:a,onDeleted:r,onBack:l}){var at,ge;const i=Oe(),o=zt(),{profile:u,user:h}=Ot(),{data:c}=Vr(),f=Jo(),{initiateCall:x}=ri(),C=d.useMemo(()=>({onCall:m=>x({id:(t==null?void 0:t.contact_id)??"",full_name:(t==null?void 0:t.contact_name)??"Customer",phone:m})}),[t==null?void 0:t.contact_id,t==null?void 0:t.contact_name,x]),[j,S]=d.use
32State(""),D=gl(t==null?void 0:t.channel),[g,A]=d.useState(!1),$=!!t&&!f.canSendOn(t.channel,t.connected_account_id),[b,_]=d.useState(null),[M,O]=d.useState(!1),[U,I]=d.useState(!1),R=d.useRef(null),W=Pm(),[J,X]=d.useState(null),[Y,w]=d.useState(null),[L,z]=d.useState(null),[N,K]=d.useState(null),[te,ae]=d.useState(!1),[Ce,_e]=d.useState(!1),G=d.useRef(null),Z=d.useRef(null),je=Vo(t==null?void 0:t.channel),fe=je.presentation==="document",Se=d.useRef(),v=Fe(),ne=zo((t==null?void 0:t.contact_id)??null),Pa=ne.resolve(j);qo(j).length>0;const ct=Fo(Pa.text),Ws=Uo(ct),dt=t?ms(t):null,ke=d.useMemo(()=>Ga({text:j,values:ne.values,dataReady:ne.ready,orgId:v??null,contactId:(t==null?void 0:t.contact_id)??null,conversationId:dt,channel:(t==null?void 0:t.channel)??null}),[j,ne.values,ne.ready,v,t==null?void 0:t.contact_id,t==null?void 0:t.channel,dt]),ut=je.composer==="email"&&!g,Q=ut?Ls(j).length>0:!!j.trim(),xe=d.useMemo(()=>ut?{...ke,source:Ls(ke.source),text:Ls(ke.text)}:ke,[ut,ke]),Mt=d.useRef(null),Ne=d.useRef(new Map);Mt.current=ke;const qn=!ke.sendable;d.useEffect(()=>{R.current=null,_(null),I(!1)},[dt]);const Ys=m=>{const y=Z.current,T=(y==null?void 0:y.selectionStart)??j.length,V=Ho(j,T,m);S(V.text),requestAnimationFrame(()=>{y==null||y.focus(),y==null||y.setSelectionRange(V.cursor,V.cursor)})},{data:mt,refetch:Qs}=Ci(t==null?void 0:t.lead_id,t==null?void 0:t.contact_id,v),{status:Gs}=gu(v,t==null?void 0:t.contact_id),Kt=((at=u==null?void 0:u.full_name)==null?void 0:at.split(" ")[0])||"Agent",{data:He}=ws(v),js=d.useCallback(m=>{if(m===(h==null?void 0:h.id))return(u==null?void 0:u.full_name)??null;const y=(He??[]).find(T=>T.auth_id===m||T.id===m);return(y==null?void 0:y.full_name)??null},[He,h==null?void 0:h.id,u==null?void 0:u.full_name]),Xs=n?t==null?void 0:t._livechat_session_id:void 0,{peerIsTyping:Wt,peerName:Js,sendTyping:Yt}=fo(Xs,"agent"),Ns=m=>{S(m),n&&!g&&!$&&(Yt(!!m.trim(),Kt),clearTimeout(Se.current),Se.current=setTimeout(()=>Yt(!1,Kt),go))},ht=va(),Qt=yl(),vs=Er(),Zs=qc(),{viewer:Pt}=Fc(),en={canSaveTemplate:Pt.canCreate||Pt.canManage,canDelete:!0},Gt=m=>{S(m),requestAnimationFrame(()=>{const y=Z.current;y==null||y.focus();const T=m.length;y==null||y.setSelectionRange(T,T)})},Fn=m=>{Ce||N||(Ge({action:"message_delete",phase:"opened",orgId:s,userId:(h==null?void 0:h.id)??null,referenceId:m,metadata:{channel:t==null?void 0:t.channel}}),_e(!0),K(m))},tn=async(m,y,T)=>{W.close();const V=(y.content??"").trim();if(m==="copy"){await $m(V)?P.success(ve.copied):P.error(ve.copyFailed);return}if(m==="reply"){Gt(j.trim()?j:qm(V));return}if(m==="reuse"){if(j.trim()&&j.trim()!==V){X(V);return}Gt(V),P.success(ve.reused,{description:ve.reusedDetail});return}if(m==="save_template"){w({body:V,name:Fm(V)});return}m==="delete"&&T&&Fn(T)},Ze=d.useRef(),Ve=d.useRef(null),pt=()=>{Ze.current&&clearTimeout(Ze.current),Ze.current=void 0,Ve.current=null},sn=(m,y)=>({onPointerDown:T=>{!y||T.pointerType==="mouse"||(Ve.current={x:T.clientX,y:T.clientY},Ze.current=setTimeout(()=>{var V,se;(((se=(V=window.getSelection)==null?void 0:V.call(window))==null?void 0:se.toString())??"").length>0||W.open(m)},450))},onPointerMove:T=>{Ve.current&&(Math.abs(T.clientX-Ve.current.x)>10||Math.abs(T.clientY-Ve.current.y)>10)&&pt()},onPointerUp:pt,onPointerCancel:pt,onPointerLeave:pt,onContextMenu:T=>{y&&(T.preventDefault(),T.stopPropagation(),W.open(m))}}),{sendEmail:Cs,sending:Xt}=Ic(),[Me,ze]=d.useState(!1),[ft,Te]=d.useState([]),[It,Jt]=d.useState(null),Ke=d.useRef(null),nn=m=>{const y=Am("inbox.send-message",m.code);Ke.current=y;const T=Em(y);Jt(Om({cause:m,attempts:T,retryable:m.retryable,message:m.message}))},Zt=()=>{Ke.current&&Rm(Ke.current),Jt(null)},Ss=bl(),[an,es]=d.useState(!1),{data:re=[],hasOlder:xt,loadingOlder:Pe,loadOlder:rn}=zr((t==null?void 0:t.contact_id)||null,(t==null?void 0:t.channel)||null,(t==null?void 0:t.connected_account_id)||null,(t==null?void 0:t.conversation_id)||null,(t==null?void 0:t.email_thread_key)||null);d.useEffect(()=>{Te(m=>lu(m,re))},[re]);const $t=t?zm(t.channel,t.connected_account_id,c):null,Ae=vi({channel:t==null?void 0:t.channel,accountId:($t==null?void 0:$t.id)??(t==null?void 0:t.connected_account_id)??null,messageCount:re.length,conversationKey:t?ms(t):null,auto:!!t&&!n}),ln=wl(),qt={module:"Inbox",view:"Conversation",route:"/inbox",filters:{"conversation id":t==null?void 0:t.conversation_id,"contact id":t==null?void 0:t.contact_id,channel:t==null?void 0:t.channel},record:{type:"Conversation",name:(t==null?void 0:t.contact_name)||"Unknown contact",id:(t==null?void 0:t.conversation_id)??(t==null?void 0:t.contact_id)??void 0,facts:[t!=null&&t.channel?`Channel: ${t.channel}`:null,`Messages loaded: ${re.length}
32`].filter(Boolean)},starters:["Summarise this conversation","What does this person want, and what should I say next?","Have we promised them anything?"]},ts=(t==null?void 0:t._ducebot_session_id)??null,{data:Un=[]}=Wd(n?t==null?void 0:t.contact_id:null,ts,Xs);d.useEffect(()=>{if(!(!t||t.unread_count<=0)){if(t.conversation_id){Ss.mutate({conversationId:t.conversation_id});return}t.contact_id&&t.channel&&Ss.mutate({contactId:t.contact_id,channel:t.channel})}},[t==null?void 0:t.conversation_id,t==null?void 0:t.contact_id,t==null?void 0:t.channel]),d.useEffect(()=>{if(!n||!(t!=null&&t.contact_id))return;const m=H.channel(`agent-livechat-${t.contact_id}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"messages",filter:`contact_id=eq.${t.contact_id}`},y=>{y.new.channel==="livechat"&&o.invalidateQueries({queryKey:["thread-messages",t.contact_id,"livechat"]})}).subscribe();return()=>{H.removeChannel(m)}},[n,t==null?void 0:t.contact_id,o]);const Ft=()=>{var m;return((m=G.current)==null?void 0:m.querySelector("[data-radix-scroll-area-viewport]"))??G.current},Ue=(m=!1)=>{const y=Ft();y&&requestAnimationFrame(()=>requestAnimationFrame(()=>{y.scrollTo({top:y.scrollHeight,behavior:m?"auto":"smooth"})}))},Bn=(m,y=!0)=>{const T=Ft();T&&requestAnimationFrame(()=>requestAnimationFrame(()=>{const V=T.querySelector(`[data-message-id="${m}"]`);if(!V){T.scrollTo({top:T.scrollHeight,behavior:"auto"});return}T.scrollTo({top:Math.max(V.offsetTop-T.clientHeight/3,0),behavior:y?"auto":"smooth"})}))},[gt,ss]=d.useState(!0),[et,yt]=d.useState(0),bt=d.useRef(null),Ut=d.useRef(null),Hn=()=>{const m=Ft();m&&(Ut.current={height:m.scrollHeight,top:m.scrollTop}),rn()};d.useEffect(()=>{const m=Ut.current;if(!m||Pe)return;const y=Ft();if(!y)return;Ut.current=null;const T=y.scrollHeight-m.height;T>0&&(y.scrollTop=m.top+T)},[re.length,Pe]);const[wt,on]=d.useState(null),Bt=d.useRef(!1),{data:tt}=ba(),cn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ks=(t==null?void 0:t.conversation_id)??null,dn=(ks&&cn.test(ks)?ks:t==null?void 0:t.contact_id)??null;pi("conversation",dn??void 0);const{viewers:Ts,isLoading:un}=fi("conversation",dn,[tt==null?void 0:tt.id]),Be=t!=null&&t.conversation_id?Ua(t.conversation_id,t.channel||"chat"):t!=null&&t.contact_id&&(t!=null&&t.channel)?Ua(t.contact_id,t.channel):null;d.useEffect(()=>{var y;if(Bt.current||re.length===0)return;Bt.current=!0;const m=_l(re,Be?jl(Be):null);on(m),bt.current=((y=re[re.length-1])==null?void 0:y.id)??null,m.messageId?Bn(m.messageId,!0):Ue(!0)},[re,Be]),d.useEffect(()=>{const m=Ft();if(!m)return;const y=()=>{const T=m.scrollHeight-m.scrollTop-m.clientHeight<80;if(ss(T),T)yt(0),Be&&Wa(Be,null);else if(Be){const V=m.querySelectorAll("[data-message-id]");for(const se of Array.from(V))if(se.offsetTop+se.offsetHeight>=m.scrollTop){Wa(Be,se.dataset.messageId??null);break}}m.scrollTop<120&&xt&&!Pe&&Hn()};return m.addEventListener("scroll",y,{passive:!0}),y(),()=>m.removeEventListener("scroll",y)},[re.length,xt,Pe,Be]),d.useEffect(()=>{const m=re[re.length-1];if(!(!m||!Bt.current)&&!(bt.current===null||m.id===bt.current)){if(bt.current=m.id,gt){Ue(!1);return}m.direction==="inbound"&&(yt(y=>y+1),Nl())}},[re,gt]),d.useEffect(()=>{Wt&&gt&&Ue(!1)},[Wt,gt]),d.useEffect(()=>{yt(0),bt.current=null,ss(!0),on(null),Bt.current=!1,Ut.current=null,Te([])},[t==null?void 0:t.conversation_id,t==null?void 0:t.contact_id,t==null?void 0:t.channel]),d.useEffect(()=>{if(!n)return;const m=document.title.replace(/^\(\d+\)\s/,"");return document.title=et>0?`(${et}) ${m}`:m,()=>{document.title=document.title.replace(/^\(\d+\)\s/,"")}},[et,n]);const Ie=Ar((t==null?void 0:t.channel)??""),mn=(t==null?void 0:t.channel)&&Bm[t.channel]||ot,Ee=(t==null?void 0:t.instagram_handle)||(t==null?void 0:t.instagram_username)||(t==null?void 0:t.provider_handle)||null,ns=d.useMemo(()=>Dr({contactName:t==null?void 0:t.contact_name,providerName:t==null?void 0:t.provider_name,handle:Ee,phone:t==null?void 0:t.contact_phone}),[t,Ee]),hn=d.useMemo(()=>{const m=[];let y=!1;Vm(t==null?void 0:t.channel)?(m.push(ta({channelLabel:Ie.label,handle:Ee,name:ns})),y=!0):a&&(m.push(`${Ie.label} - ${a}`),y=!0);const T=!!(t!=null&&t.contact_id),V=Ii({lead:mt,channelLabel:y?null:Ie.label,linked:T,contactStatus:Gs});return(!y||mt||T)&&m.push(V),m.filter(Boolean).join(" · ")},[a,Ie.label,mt,t==null?void 0:t.channel,t==null?void 0:t.contact_id,Gs,Ee,ns]),$e=d.useMemo(()=>{var y;const m=re.length?re[re.length-1]:null;return _a({lastDirection:m?m.direction:null,lastMessageAt:(m==null?void 0:m.created_at)??null,channelHealthy:!Ae.lastError,repliedByName:m&&m.direction==="outbound"?Ba({userId:m.actor_member_id??m.user_id,isAutomated:m.is_automated,actorSource:(y=m.metadata)==null?void 0:y[Ha],nameFor:js,accountLabel:a,channelLabel:Ie.label,direction:m.direction}).label:null})},[re,Ae.lastError,js,a,Ie.label]);if(!t)return e.jsx("div",{className:"flex-1 flex items-center justify-center text-muted-foreground",children:e.jsxs("div",{className:"text-center",children:[e.jsx(_s,{className:"h-12 w-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Select a conversation to start messaging"})]})});const st=async(m,y,T,V)=>au({html:T?void 0:V,orgId:s,conversation:{channel:t.channel,contact_id:t.contact_id,conversation_id:t.conversation_id,connected_account_id:t.connected_account_id},connectedAccounts:c,content:m,clientSendKey:y,asInternal:T,templateId:T?null:L,saveLocalMessage:se=>ht.mutateAsync(se),sendEmailFallback:se=>Cs(se),emailSubject:fn(t)??"",emailReplyTo:(()=>{var de,me,Re,Le;if(t.channel!=="email")return null;const se=[...re].reverse().find(he=>{var oe;return((oe=he.metadata)==null?void 0:oe.thread_id)||he.provider_message_id});return se?{threadId:((de=se.metadata)==null?void 0:de.thread_id)??null,messageId:((me=se.metadata)==null?void 0:me.internet_message_id)??((Re=se.metadata)==null?void 0:Re.message_id_header)??null,references:((Le=se.metadata)==null?void 0:Le.references)??null}:null})()}),be=()=>{o.invalidateQueries({queryKey:["thread-messages"]}),o.invalidateQueries({queryKey:["inbox-messages"]})},As=async m=>{if(Me)return;const y=m.client_send_key||`msg_${m.id}`;try{ze(!0),await H.from("messages").update({delivery_status:"sending",client_send_key:y}).eq("id",m.id),await st(m.content||"",y,!1);const T=await Ni(s,y);T&&T.id!==m.id&&await Qt.mutateAsync(m.id),Zt(),be()}catch(T){const V=lt(T,De(t.channel));nn(V),P.error("Message not sent",{description:Qn}),await H.from("messages").update({delivery_status:"failed",provider_meta:{failure:{code:V.code,retryable:V.retryable,raw:V.raw}}}).eq("id",m.id),be()}finally{ze(!1)}},as=async()=>{const m=ut,y=m?j:j.trim(),T=m?Ls(j).length>0:!!y,V=!!t.contact_id||!!t.conversation_id;if(!T||!V||ht.isPending||Xt||Me)return;const se=g,de=Mt.current;let me=y;if(!se){const he=Ga({text:j,values:ne.values,dataReady:ne.ready,orgId:v??null,contactId:(t==null?void 0:t.contact_id)??null,conversationId:dt,channel:(t==null?void 0:t.channel)??null});if(!de||Yo(de,{text:j,context:he.context})||de.text!==he.text){P.warning("Check this message again",{description:Qo});return}if(!he.sendable){P.warning("Not ready to send",{description:he.blockedReason??"Fill in the highlighted detail before sending."});return}me=he.text}let Re;m&&(Re=Go(me,{allowImages:!0,allowLinks:!0}),me=Ls(Re));const Le=iu(me);Re&&Ne.current.set(Le.id,Re),Te(he=>[...he,Le]),S(""),A(!1),Ue(!0),n&&(Yt(!1,Kt),clearTimeout(Se.current));try{ze(!0),await st(me,Le.clientSendKey,se,Re),Te(he=>he.map(oe=>oe.id===Le.id?{...oe,state:"sent",error:void 0}:oe)),Zt(),o.invalidateQueries({queryKey:["thread-messages"]}),setTimeout(()=>
32o.invalidateQueries({queryKey:["thread-messages"]}),2500)}catch(he){const oe=lt(he,De(t.channel));nn(oe),P.error("Message not sent",{description:Qn}),Te(We=>We.map(Ye=>Ye.id===Le.id?{...Ye,state:"failed",error:oe.message,code:oe.code}:Ye)),S(We=>We.trim()?We:y)}finally{ze(!1)}},Vn=async m=>{if(!Me){Te(y=>y.map(T=>T.id===m.id?{...T,state:"sending",error:void 0}:T));try{ze(!0),await st(m.content,m.clientSendKey,!1,Ne.current.get(m.id)),Te(y=>y.map(T=>T.id===m.id?{...T,state:"sent",error:void 0}:T)),Zt(),o.invalidateQueries({queryKey:["thread-messages"]}),setTimeout(()=>o.invalidateQueries({queryKey:["thread-messages"]}),2500)}catch(y){const T=lt(y,De(t.channel));nn(T),P.error("Message not sent",{description:Qn}),Te(V=>V.map(se=>se.id===m.id?{...se,state:"failed",error:T.message,code:T.code}:se))}finally{ze(!1)}}},zn=m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),as())},_t=async(m="reply")=>{const y=Qu({mode:m,messages:re,contactName:t.contact_name,channel:t.channel,waitingSide:$e.side});if(y.ok!==!0){const V=y;_({mode:m,basis:"",text:"",blocked:V.reason,offer:V.offer});return}const T=dt;R.current=T,O(!0),_({mode:m,basis:y.basis,text:"",plan:y.plan});try{const{data:V,error:se}=await H.functions.invoke("ai-message-suggest",{body:{messages:[{role:"user",content:y.prompt}],contact_name:t.contact_name||"there",channel:t.channel,mode:m==="reply"?"inbox_reply":"inbox_followup"}});if(R.current!==T)return;if(se||V!=null&&V.error){P.error("That suggestion could not be prepared",{description:(V==null?void 0:V.error)||(se==null?void 0:se.message)||"Try again in a moment."}),_(null);return}const de=V!=null&&V.suggestion?Um(String(V.suggestion)):"",me=tm(de,sm(re));if(!me.text.trim()){_({mode:m,basis:y.basis,text:"",blocked:"Nothing here could be drafted honestly. Tell us what you want to say and we can shape it.",plan:y.plan});return}_({mode:m,basis:y.basis,text:me.text,note:nm(me),plan:y.plan})}catch(V){if(R.current!==T)return;P.error("That suggestion could not be prepared",{description:we(V)}),_(null)}finally{R.current===T&&O(!1)}},nt=m=>{b!=null&&b.text&&(S(y=>m==="append"&&y.trim()?`${y.replace(/\s+$/,"")}
33
34${b.text}`:b.text),_(null),I(!1),Ue(!0),requestAnimationFrame(()=>{var y;return(y=Z.current)==null?void 0:y.focus()}))};return vl.filter(m=>m.channel===t.channel||m.channel==="whatsapp"),e.jsxs("div",{"data-thread-workspace":!0,className:B("flex h-full min-h-0 flex-1 flex-col overflow-hidden"),children:[!n&&e.jsxs(e.Fragment,{children:[e.jsx(Ti,{name:ns,subject:Cl(t),subtitle:hn,avatar:e.jsx(mn,{className:B("h-4 w-4",Ie.color)}),avatarClassName:Ie.bg,onBack:l,actions:e.jsxs("div",{className:"flex items-center gap-1",children:[Ae.available&&e.jsx(E,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>void Ae.sync("manual"),disabled:Ae.syncing,title:Ae.lastError??"Sync messages","aria-label":Ae.syncing?"Syncing messages":"Sync messages",children:e.jsx(aa,{className:B("h-4 w-4",Ae.syncing&&"animate-spin",Ae.lastError&&!Ae.syncing&&"text-destructive")}
34)}),e.jsx(E,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>es(!0),title:"Customer context","aria-label":"Open customer context",children:e.jsx(Tt,{className:"h-4 w-4"})}),e.jsx(bu,{contactId:t.contact_id,channel:t.channel,channelIdentity:{name:t.contact_name,handle:t.instagram_handle,phone:t.contact_phone},onCall:m=>x({id:t.contact_id??"",full_name:t.contact_name??"Customer",phone:m})}),e.jsx(Mi,{lead:mt,contactId:t.contact_id,orgId:v,onRefetch:Qs,contactName:t.contact_name,conversationId:t.conversation_id,channel:t.channel,providerHandle:t.instagram_handle,providerName:t.provider_name,providerPhone:t.contact_phone,onArchiveConversation:()=>ae(!0)})]})}),$e.side!=="none"&&e.jsxs("div",{className:B("flex h-7 items-center gap-2 border-b px-4 text-[11px]",$e.overdue?"bg-amber-500/10 text-amber-700 dark:text-amber-400":"text-muted-foreground"),children:[e.jsx(Pn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:$e.systemNote??$e.label}),$e.side==="business"&&e.jsx("button",{type:"button",className:"ml-auto shrink-0 font-medium underline-offset-2 hover:underline",onClick:()=>{var m;return(m=Z.current)==null?void 0:m.focus()},children:"Reply"})]})]}),e.jsxs("div",{"data-thread-transcript":!0,className:"relative flex min-h-0 flex-1 flex-col md:min-h-[min(30rem,55dvh)] xl:min-h-[min(35rem,62dvh)]",children:[e.jsx(ys,{className:"min-h-0 flex-1 overflow-y-auto px-3 py-3 sm:px-5 sm:py-4",ref:G,children:e.jsxs("div",{className:"space-y-2.5 max-w-4xl mx-auto w-full",children:[n?e.jsx(Km,{turns:Un,visitorName:t.contact_name||t._visitor_email||"Visitor",agentName:Kt,renderActions:m=>{const y={content:m.content,direction:m.source==="visitor"?"inbound":"outbound",channel:t.channel},T=wr(y,{...en,canDelete:!1});return e.jsx(br,{actions:T,open:W.isOpen(m.id),onOpenChange:V=>W.setOpen(m.id,V),align:m.source==="visitor"?"start":"end",onPrimary:m.source==="agent",onSelect:V=>tn(V,y)})}}):e.jsxs(e.Fragment,{children:[re.length===0&&ft.length===0&&e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:"No messages yet"}),xt&&e.jsx("div",{className:"flex justify-center pb-1",children:e.jsx(E,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground",onClick:Hn,disabled:Pe,children:Pe?"Loading earlier messages...":"Load earlier messages"})}),re.map((m,y)=>{var Es,Rs,p;const T=m.direction==="inbound",V=y>0&&((Es=re[y-1])==null?void 0:Es.direction)!==m.direction,se=m.is_internal,de=(m.delivery_status||m.status||"").toLowerCase(),me=!T&&de==="failed",Re=!T&&(de==="queued"||de==="sending"||de==="pending"),Le=!T&&de==="provider_accepted",he=!T&&(de==="delivered"||de==="read"),oe=(wt==null?void 0:wt.kind)==="first_unread"&&wt.messageId===m.id?e.jsxs("div",{className:"flex items-center gap-2 py-1",children:[e.jsx("span",{className:"h-px flex-1 bg-primary/30"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide text-primary",children:Sl(wt.unreadCount)}),e.jsx("span",{className:"h-px flex-1 bg-primary/30"})]}):null,We={content:m.content,direction:m.direction,isInternal:!!se,channel:t.channel},Ye=wr(We,en),jt=e.jsx(br,{actions:Ye,open:W.isOpen(m.id),onOpenChange:k=>W.setOpen(m.id,k),align:T?"start":"end",onPrimary:!T&&!se,onSelect:k=>tn(k,We,m.id)}),Nt=sn(m.id,Ye.length>0);if(se)return e.jsxs("div",{"data-message-id":m.id,children:[oe,e.jsx("div",{className:"flex justify-center group",children:e.jsxs("div",{...Nt,className:"max-w-[85%] rounded-lg px-4 py-2.5 border-2 border-dashed border-amber-400/50 bg-amber-50 dark:bg-amber-950/30 relative",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[e.jsx(Va,{className:"h-3 w-3 text-amber-600 dark:text-amber-400"}),e.jsx(ie,{variant:"secondary",className:"text-[9px] h-4 px-1.5 bg-amber-200/60 dark:bg-amber-800/40 text-amber-800 dark:text-amber-300",children:"Internal Note"}),e.jsx("div",{className:"ml-auto",children:jt})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap break-words text-amber-900 dark:text-amber-200",children:e.jsx(Ms,{content:m.content})}),e.jsx("span",{className:"text-[10px] text-amber-600/70 dark:text-amber-400/70 mt-1 block",children:ye(new Date(m.created_at),"HH:mm")}
34)]})})]},m.id);const rs=fe||T?"text-foreground":"text-primary-foreground",vt=fe||T?"text-muted-foreground":"text-primary-foreground/70";return e.jsxs("div",{"data-message-id":m.id,className:B(V&&"pt-2.5 sm:pt-3"),children:[oe,e.jsxs("div",{className:B("flex group items-end gap-1",T?"justify-start":"justify-end"),role:"article","aria-label":`Message from ${T?t.contact_name||"visitor":"you"} at ${ye(new Date(m.created_at),"HH:mm")}`,children:[!T&&jt,e.jsxs("div",{...Nt,className:B(fe?"w-full rounded-lg border px-4 py-3 sm:px-5 sm:py-4 break-words":"max-w-[92%] sm:max-w-[78%] lg:max-w-[76%] rounded-2xl px-4 py-2.5 shadow-sm break-words",fe?T?"bg-card":"bg-primary/5 border-primary/20":T?"bg-muted rounded-bl-md":"bg-primary text-primary-foreground rounded-br-md"),"data-presentation":fe?"document":"bubble",children:[fe&&e.jsxs("div",{className:"mb-2 flex flex-wrap items-baseline gap-x-2 gap-y-0.5 border-b pb-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:T?t.contact_name||t.contact_email||"Customer":"You"}),T&&t.contact_email&&t.contact_name&&e.jsx("span",{className:"text-muted-foreground",children:t.contact_email}),((Rs=m.metadata)==null?void 0:Rs.subject)&&e.jsx("span",{className:"w-full truncate text-muted-foreground",children:m.metadata.subject})]}),e.jsx("div",{className:"flex items-start gap-2",children:e.jsx("p",{className:B("whitespace-pre-wrap break-words",fe?"text-[15px] leading-relaxed":"text-sm"),children:e.jsx(Ms,{content:m.content,trimQuoted:T,actions:C})})}),e.jsxs("div",{className:B("flex flex-wrap items-center gap-1.5 mt-1.5",T?"justify-start":"justify-end"),children:[m.is_automated&&e.jsx(ie,{variant:"inactive",className:"text-[9px] h-4 px-1",children:"Auto"}),!T&&!m.is_automated&&e.jsx("span",{className:`text-[10px] ${vt}`,children:Ba({direction:m.direction,userId:m.actor_member_id??m.user_id,isAutomated:m.is_automated,actorSource:(p=m.metadata)==null?void 0:p[Ha],nameFor:js,accountLabel:a,channelLabel:Ie.label}).label}),e.jsx("span",{className:B("text-[10px]",T?"text-muted-foreground":vt),children:ye(new Date(m.created_at),"HH:mm")}),me&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:`text-[10px] font-medium ${rs}`,role:"status",children:"Message not sent"}),e.jsx("button",{type:"button",onClick:()=>As(m),disabled:Me,className:`text-[10px] font-medium underline underline-offset-2 ${rs} hover:opacity-80 disabled:opacity-50`,children:"Try again"})]}),Re&&e.jsx("span",{className:`text-[10px] ${vt}`,role:"status",children:"Sending"}),Le&&e.jsx("span",{className:`text-[10px] ${vt}`,role:"status",children:"Accepted"}),he&&!m.read_at&&e.jsx("span",{className:`text-[10px] ${vt}`,role:"status",children:"Delivered"}),!T&&m.read_at&&za(t.channel,"read_receipts")&&e.jsxs("span",{className:`inline-flex items-center text-[10px] ${vt}`,role:"status",children:[e.jsx(Kr,{className:"h-3 w-3","aria-hidden":"true"})," Read"]})]})]}),T&&jt]})]},m.id)}),ft.map(m=>e.jsx("div",{"data-pending-message-id":m.id,children:e.jsx("div",{className:"flex group items-end gap-1 justify-end",role:"article","aria-label":"Message you just sent",children:e.jsxs("div",{className:fe?"w-full rounded-lg border border-primary/20 bg-primary/5 px-4 py-3 sm:px-5 sm:py-4 break-words text-foreground [&_.pending-muted]:text-muted-foreground":"max-w-[90%] sm:max-w-[76%] rounded-2xl rounded-br-md px-4 py-2.5 shadow-sm break-words bg-primary text-primary-foreground",children:[e.jsx("p",{className:"text-sm whitespace-pre-wrap break-words",children:e.jsx(Ms,{content:m.content})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1 justify-end",children:[e.jsx("span",{className:"text-[10px] text-primary-foreground/70 pending-muted",children:ye(new Date(m.created_at),"HH:mm")}),m.state==="sending"?e.jsx("span",{className:"text-[10px] text-primary-foreground/70 pending-muted",role:"status",children:"Sending"}):m.state==="sent"?e.jsx("span",{className:"text-[10px] text-primary-foreground/70 pending-muted",role:"status",children:"Sent"}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] font-medium text-primary-foreground",role:"status",children:"Message not sent"}),e.jsx("button",{type:"button",onClick:()=>Vn(m),disabled:Me,className:"text-[10px] font-medium underline underline-offset-2 text-primary-foreground hover:text-primary-foreground
34/80 disabled:opacity-50",children:"Try again"})]})]})]})})},m.id))]}),n&&Wt&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-muted rounded-lg rounded-bl-md px-4 py-2.5 shadow-sm",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/40 animate-bounce",style:{animationDelay:"0ms"}}),e.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/40 animate-bounce",style:{animationDelay:"150ms"}}),e.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/40 animate-bounce",style:{animationDelay:"300ms"}}),e.jsx("span",{className:"text-[10px] text-muted-foreground ml-1",children:xo(t.contact_name||(Js!=="Visitor"?Js:null))})]})})}),!n&&Ae.arriving>0&&e.jsx("div",{className:"flex justify-start",role:"status","aria-live":"polite",children:e.jsx("div",{className:"bg-muted rounded-lg rounded-bl-md px-4 py-2.5 shadow-sm",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/40 animate-bounce",style:{animationDelay:"0ms"}}),e.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/40 animate-bounce",style:{animationDelay:"150ms"}}),e.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/40 animate-bounce",style:{animationDelay:"300ms"}}),e.jsx("span",{className:"text-[10px] text-muted-foreground ml-1",children:xu})]})})})]})}),!gt&&e.jsxs("button",{onClick:()=>{Ue(!1),yt(0)},role:"status","aria-live":"polite","aria-label":Ka(et),className:B("absolute left-1/2 -translate-x-1/2 bottom-3 z-10 flex items-center gap-1.5 rounded-full text-xs font-medium shadow-lg transition animate-in fade-in slide-in-from-bottom-2",et>0?"px-3 py-1.5 bg-primary text-primary-foreground hover:bg-primary/90":"h-8 w-8 justify-center bg-card border text-muted-foreground hover:text-foreground"),children:[e.jsx(Uc,{className:"h-3 w-3"}),et>0&&Ka(et)]})]}),(b||M)&&e.jsx("div",{className:"mx-3 mb-1 rounded-lg border bg-card p-2.5 shadow-sm",role:"region","aria-label":"Suggested message",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ps,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground","aria-hidden":"true"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground",children:(b==null?void 0:b.mode)==="followup"?"Suggested follow-up (draft)":"Suggested reply (draft)"}),(b==null?void 0:b.basis)&&e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:b.basis}),M&&!(b!=null&&b.text)&&e.jsxs("p",{className:"mt-1 flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Is,{className:"h-3.5 w-3.5 animate-spin"})," Preparing a short draft..."]}),(b==null?void 0:b.blocked)&&e.jsxs("div",{className:"mt-1 space-y-1.5",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:b.blocked}),b.offer&&e.jsx(E,{size:"sm",variant:"outline",className:"h-8 text-xs",onClick:()=>_t(b.offer),children:b.offer==="followup"?"Suggest a follow-up instead":"Suggest a reply instead"})]}),(b==null?void 0:b.text)&&e.jsx("div",{className:"mt-1 max-h-32 overflow-y-auto whitespace-pre-wrap text-xs",children:b.text}),(b==null?void 0:b.note)&&e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:b.note}),(b==null?void 0:b.mode)==="followup"&&((ge=b.plan)==null?void 0:ge.suggestedLabel)&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground",children:["Suggested time: ",b.plan.suggestedLabel," (Lagos). Nothing is scheduled until you create it."]}),(b==null?void 0:b.text)&&e.jsx("div",{className:"mt-1.5 flex flex-wrap items-center gap-1",children:U?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"You already typed something:"}),e.jsx(E,{size:"sm",variant:"ghost",className:"h-8 text-xs",onClick:()=>nt("append"),children:"Add below"}),e.jsx(E,{size:"sm",variant:"ghost",className:"h-8 text-xs",onClick:()=>nt("replace"),children:"Replace it"}),e.jsx(E,{size:"sm",variant:"ghost",className:"h-8 text-xs",onClick:()=>I(!1),children:"Keep mine"})]}):e.jsxs(e.Fragment,{children:[e.jsx(E,{size:"sm",variant:"secondary",className:"h-8 text-xs",onClick:()=>j.trim()?I(!0):nt("replace"),children:"Insert into message"}),e.jsx(E,{size:"sm",variant:"ghost",className:"h-8 text-xs",disabled:M,onClick:()=>_t(b.mode),children:"Regenerate"}),b.mode==="followup"&&t.contact_id&&e.jsx(E,{size:"sm",variant:"ghost",className:"h-8 text-xs",onClick:()=>i(`/tasks?action=create&contact=${t.contact_id}`),children:"Create follow-up"})]})})]}),e.jsx(E,{size:"icon",variant:"ghost",className:"h-8 w-8 shrink-0","aria-label":"Dismiss suggestion",onClick:()=>
34{R.current=null,_(null),I(!1)},children:e.jsx(Dt,{className:"h-3.5 w-3.5"})})]})}),e.jsxs("div",{"data-thread-composer":!0,className:B("sticky bottom-0 z-20 shrink-0 border-t p-3 bg-card pb-[max(0.75rem,var(--safe-area-bottom))]",g&&"border-t-2 border-t-amber-400"),children:[g&&e.jsxs("div",{className:"flex items-center gap-1.5 mb-2 text-amber-700 dark:text-amber-400",children:[e.jsx(Va,{className:"h-3 w-3"}),e.jsx("span",{className:"text-xs font-medium",children:"Internal Note - only your team can see this"})]}),!g&&!ut&&D.usesSubject&&fn(t)&&e.jsxs("p",{className:"mb-2 truncate text-[11px] text-muted-foreground",children:["Replying with subject: ",e.jsx("span",{className:"text-foreground",children:fn(t)})]}),It&&e.jsx(Mm,{className:"mb-2",recovery:It,busy:Me,onRetry:()=>void as(),onReport:()=>kl(void 0,`Inbox send: ${It.message}`)}),Ws&&e.jsxs("div",{className:"mb-2 flex items-start gap-2 rounded-md border border-amber-400/60 bg-amber-500/10 p-2 text-[11px] text-amber-800 dark:text-amber-300",children:[e.jsx("span",{className:"min-w-0 flex-1",children:Ws}),e.jsx("button",{type:"button",className:"shrink-0 font-medium underline-offset-2 hover:underline",onClick:()=>{var m;return(m=Z.current)==null?void 0:m.focus()},children:"Edit message"})]}),!g&&e.jsx(Ko,{className:"mb-2",snapshot:xe,onlyWhenTransformed:!0,onEditMessage:()=>{var m;return(m=Z.current)==null?void 0:m.focus()},onAddDetail:t!=null&&t.contact_id?()=>i(`/contacts/${t.contact_id}`):void 0}),!g&&e.jsx("p",{className:"mb-2 truncate text-[11px] text-muted-foreground",children:$?Zo:ec(t.channel,a)}),(()=>{const m=e.jsxs(e.Fragment,{children:[za(t.channel,"attachments")&&e.jsxs(E,{size:"sm",variant:"ghost",className:"h-7 text-xs shrink-0","aria-label":"Attach file",children:[e.jsx(Bc,{className:"h-3 w-3 mr-1"})," Attach"]}),e.jsx("div",{className:"shrink-0 [&_button]:h-7 [&_button]:text-xs",children:e.jsx($o,{channels:t!=null&&t.channel?[t.channel]:void 0,onSelect:T=>{S(T.body),z(T.id??null)}})}),ln.available&&e.jsxs(E,{size:"sm",variant:"ghost",className:"h-7 text-xs shrink-0",onClick:()=>ln.ask(qt),"aria-label":"Ask DuceBot about this conversation",children:[e.jsx(Tl,{className:"h-3.5 w-3.5 mr-1"})," DuceBot"]}),e.jsxs($s,{children:[e.jsx(qs,{asChild:!0,children:e.jsx(E,{size:"sm",variant:"ghost",className:"h-7 text-xs shrink-0","aria-label":"More message tools",children:"More"})}),e.jsxs(Fs,{align:"start",className:"w-56 p-1",children:[e.jsxs(E,{size:"sm",variant:"ghost",className:B("w-full justify-start h-8 text-xs",g&&"bg-amber-100 dark:bg-amber-900/40 text-amber-800 dark:text-amber-300"),onClick:()=>A(!g),children:[e.jsx(Hc,{className:"h-3.5 w-3.5 mr-2"}),g?"Cancel internal note":"Internal note"]}),(je.attributeInMore||g)&&e.jsx("div",{className:"px-1 py-0.5 [&_button]:w-full [&_button]:justify-start [&_button]:h-8 [&_button]:text-xs",children:e.jsx(Bo,{onInsert:Ys,values:ne.values,label:"Attribute"})}),e.jsxs(E,{size:"sm",variant:"ghost",className:"w-full justify-start h-8 text-xs",onClick:()=>_t("reply"),disabled:M,children:[M?e.jsx(Is,{className:"h-3.5 w-3.5 mr-2 animate-spin"}):e.jsx(Ps,{className:"h-3.5 w-3.5 mr-2"}),"Suggest a reply"]}),e.jsxs(E,{size:"sm",variant:"ghost",className:"w-full justify-start h-8 text-xs",onClick:()=>_t("followup"),disabled:M,children:[e.jsx(Hr,{className:"h-3.5 w-3.5 mr-2"})," Suggest a follow-up"]})]})]})]}),y=!Q||qn||!g&&$||ht.isPending||Xt||Me;return ut?e.jsx(Wo,{value:j,onChange:Ns,onSend:as,sendDisabled:y,subject:fn(t),attributeValues:ne.values,tools:m,sending:Me||Xt}):e.jsx(Yd,{ref:Z,value:j,onChange:Ns,onKeyDown:zn,onSend:as,sendDisabled:y,placeholder:g?"Write an internal note...":D.inputPlaceholder,ariaLabel:g?"Write an internal note":"Type a message",internal:g,tools:m})})()]}),e.jsx(At,{open:an,onOpenChange:es,children:e.jsxs(Et,{side:"right",className:"w-full sm:max-w-md overflow-y-auto",children:[e.jsx(Rt,{children:e.jsx(Lt,{children:ns})}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsx(Pc,{viewers:Ts,noun:"conversation",loading:un}),e.jsx(Uu,{messages:re,contactId:t.contact_id,contactName:t.contact_name,orgId:v,conversationId:dt,onViewMessage:m=>{var y;es(!1),(y=document.querySelector(`[data-message-id="${m}"]`))==null||y.scrollIntoView({behavior:"smooth",block:"center"})}}),e.jsx(ki,{lead:mt,contactId:t.contact_id,orgId:v,onRefetch:Qs,contactName:t.contact_name}),e.jsx($i,{lead:mt,channel:t.channel,lastActivityAt:t.last_message_at,onReply:()=>{var m;es(!1),(m=Z.current)==null||m.focus()},onAddFollowUp:t.contact_id?()=>i(`/tasks?action=create&contact=${t.contact_id}`):void 0,rememberKey:"insights:conversation:channel"}),e.jsx(Mc,{entityType:"contact",entityId:t.contact_id,module:"inbox",title:"Activity"})]})]})}),e.jsx(Je,{open:!!N,onOpenChange:m=>{!m&&N&&(Ge({action:"message_delete",phase:"cancelled",orgId:s,userId:(h==null?void 0:h.id)??null,referenceId:N,metadata:{channel:t.channel}}),K(null),_e(!1))},title:"Delete this message?",message:"Visitors won't see it again - this can't be und
34one.",confirmLabel:"Delete message",confirmVariant:"destructive",loading:Qt.isPending,onConfirm:async()=>{if(!N)return;const m=N;try{await Qt.mutateAsync(m),Ge({action:"message_delete",phase:"confirmed",orgId:s,userId:(h==null?void 0:h.id)??null,referenceId:m,metadata:{channel:t.channel}}),P.success("Message deleted")}catch(y){P.error("Failed to delete",{description:we(y)})}finally{K(null),_e(!1)}}}),e.jsx(Je,{open:te,onOpenChange:m=>{m||ae(!1)},title:ue.confirmTitle,message:ue.confirmMessage,confirmLabel:ue.action,loading:vs.isPending,onConfirm:async()=>{try{await vs.mutateAsync(t),P.success(ue.archived,{description:ue.archivedDetail}),ae(!1),r==null||r()}catch(m){P.error("Could not archive this conversation",{description:we(m)})}}}),e.jsx(Je,{open:!!J,onOpenChange:m=>{m||X(null)},title:ve.replaceTitle,message:ve.replaceMessage,confirmLabel:ve.replaceConfirm,onConfirm:()=>{J&&Gt(J),X(null)}}),e.jsx(Je,{open:!!Y,onOpenChange:m=>{m||w(null)},title:ve.saveTemplate,message:ve.immutableNote,confirmLabel:"Save template",loading:Zs.isPending,onConfirm:async()=>{if(Y)try{await Zs.mutateAsync({name:Y.name,body:Y.body,template_type:"message",channel:t.channel}),P.success("Template saved",{description:"You will find it in My Templates."}),w(null)}catch(m){P.error("Could not save that template",{description:we(m)})}}})]})}function Km({turns:t,visitorName:s,agentName:n,renderActions:a}){if(t.length===0)return e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:"No messages yet"});let r=-1,l=!1;for(let i=0;i<t.length;i++)if(t[i].source==="bot"&&(l=!0),l&&t[i].source==="agent"){r=i;break}return e.jsx(e.Fragment,{children:t.map((i,o)=>{const u=o===r?e.jsxs("div",{className:"flex items-center gap-2 py-2",children:[e.jsx("div",{className:"flex-1 h-px bg-border"}),e.jsxs("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground flex items-center gap-1",children:[e.jsx(Tt,{className:"h-3 w-3"}),n," took over from DuceBot"]}),e.jsx("div",{className:"flex-1 h-px bg-border"})]},`handoff-${o}`):null;if(i.source==="system")return e.jsxs("div",{children:[u,e.jsx("div",{className:"flex justify-center",children:e.jsx("span",{className:"text-[10px] text-muted-foreground italic px-3 py-1 rounded-full bg-muted/60",children:i.content})})]},i.id);i.source==="agent"||i.source;const h=i.source==="agent",c=i.source==="bot"?"DuceBot":i.source==="agent"?n:s,f=i.source==="bot"?kn:i.source==="agent"?Tt:null;return e.jsxs("div",{children:[u,e.jsxs("div",{className:B("group flex flex-col",h?"items-end":"items-start"),children:[e.jsxs("div",{className:"flex items-center gap-1 mb-0.5 px-1",children:[f&&e.jsx(f,{className:B("h-3 w-3",i.source==="bot"?"text-primary":"text-emerald-600")}),e.jsx("span",{className:"text-[10px] font-medium text-muted-foreground",children:c})]}),e.jsxs("div",{className:B("max-w-[85%] sm:max-w-[75%] rounded-lg px-4 py-2.5 shadow-sm break-words",i.source==="agent"&&"bg-primary text-primary-foreground rounded-br-md",i.source==="bot"&&"bg-primary/10 text-foreground rounded-bl-md border border-primary/20",i.source==="visitor"&&"bg-muted rounded-bl-md"),children:[e.jsx("p",{className:"text-sm whitespace-pre-wrap break-words",children:e.jsx(Ms,{content:i.content})}),e.jsxs("div",{className:B("flex items-center gap-1 mt-1",h?"justify-end":"justify-start"),children:[e.jsx("span",{className:B("text-[10px]",i.source==="agent"?"text-primary-foreground/70":"text-muted-foreground"),children:ye(new Date(i.created_at),"HH:mm")}),a==null?void 0:a(i)]})]})]})]},i.id)})})}function Wm({session:t,orgId:s,onTakeover:n}){const a=Oe(),r=zt(),l=va(),i=t.messages||[],[o,u]=d.useState(""),[h,c]=d.useState(t.status==="taken_over"),[f,x]=d.useState(!1),[C,j]=d.useState(!1),[S,D]=d.useState(i);d.useEffect(()=>{D(i)},[t.id,t.messages]),d.useEffect(()=>{t.status==="taken_over"&&c(!0)},[t.status]);const g=()=>{r.invalidateQueries({queryKey:["ducebot-inbox-sessions",s]}),r.invalidateQueries({queryKey:["ducebot_sessions",s]})},A=async()=>{x(!0);try{const{error:_}=await H.from("ducebot_sessions").update({status:"taken_over"}).eq("id",t.id);if(_)throw _;c(!0),g(),P.success("Chat taken over",{description:"You are now responding as a human rep."}),n==null||n()}catch(_){P.error("That did not save",{description:we(_)})}finally{x(!1)}},$=async()=>{const _=o.trim();if(!_||C)return;const M=S,O=[...M,{role:"assistant",content:_}];u(""),j(!0),D(O);try{const{error:U}=await H.from("ducebot_sessions").update({messages:O,status:"taken_over"}).eq("id",t.id);if(U)throw U;t.contact_id&&await l.mutateAsync({org_id:s,contact_id:t.contact_id,channel:"ducebot",direction:"outbound",content:_,is_automated:!1}),g(),P.success("Message sent")}catch(U){D(M),P.error("That did not save",{description:we(U)})}finally{j(!1)}},b=_=>{_.key==="Enter"&&!_.shiftKey&&(_.preventDefault(),$())};return e.jsxs("div",{className:"flex-1 flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex items-center justify-center h-9 w-9 rounded-full bg-primary/15",children:e.jsx(kn,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"DuceBot Session"}),t.is_escalated&&e.jsxs(ie,{variant:"destructive",className:"text-[10px]",children:[e.jsx(Cn,{className:"h-3 w-3 mr-0.5"})," Escalated"]}),h&&e.jsxs(ie,{className:"text-[10px] bg-success/15 text-success border-success/30",children:[e.jsx(Tt,{className:"h-3 w-3 mr-0.5"})," Taken Over"]})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Session: ",t.session_id.slice(0,12),"… · ",ye(new Date(t.created_at),"MMM d, HH:mm")]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.contact_id&&e.jsxs(E,{size:"sm",variant:"outline",onClick:()=>it(a,t.contact_id),children:[e.jsx(hs,{className:"h-3 w-3 mr-1"})," View Contact"]}),(t.is_escalated||t.status==="escalated")&&!h&&e.jsxs(E,{size:"sm",variant:"default",onClick:A,disabled:f,children:[e.jsx(Tt,{className:"h-3 w-3 mr-1"})," ",f?"Taking over…":"Take Over"]})]})]}),e.jsx(ys,{className:"flex-1 px-4 py-3",children:e.jsxs("div",{className:"space-y-3 max-w-2xl mx-auto",children:[S.length===0&&e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:"No messages in this session"}),S.map((_,M)=>{const O=_.role==="user";return e.jsx("div",{className:B("flex",O?"justify-end":"justify-start"),children:e.jsxs("div",{className:B("max-w-[75%] rounded-lg px-4 py-2.5 shadow-sm",O?"bg-primary text-primary-foreground rounded-br-md":"bg-muted rounded-bl-md"),children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[!O&&e.jsx(kn,{className:"h-3 w-3 text-primary shrink-0"}),e.jsx("span",{className:B("text-[10px] font-medium",O?"text-primary-foreground
34/70":"text-muted-foreground"),children:O?"Visitor":"DuceBot"})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap break-words",children:e.jsx(Ms,{content:_.content,trimQuoted:O})})]})},M)}),t.is_escalated&&!h&&e.jsx("div",{className:"flex justify-center py-4",children:e.jsxs("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg px-4 py-3 text-center max-w-sm",children:[e.jsx(Cn,{className:"h-5 w-5 text-destructive mx-auto mb-1"}),e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Escalation Requested"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:'This visitor asked to speak with a human. Click "Take Over" to respond.'})]})})]})}),h&&e.jsx("div",{className:"border-t p-3 bg-card",children:e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsx("div",{className:"flex-1",children:e.jsx(Bs,{placeholder:"Type your reply...",value:o,onChange:_=>u(_.target.value),onKeyDown:b,rows:2,className:"resize-none min-h-[60px]"})}),e.jsx(E,{size:"icon",onClick:$,disabled:!o.trim()||C,children:e.jsx(On,{className:"h-4 w-4"})})]})})]})}function qi(t,s,n){const a=[...n].sort().join(",");return ce({queryKey:["destructive-audit",t,s,a],enabled:!!t&&!!s&&n.length>0,staleTime:3e4,queryFn:async()=>{const{data:r,error:l}=await H.from("activity_log").select("id, created_at, user_id, activity_type, metadata").eq("org_id",s).eq("activity_type","destructive_action_confirmed").filter("metadata->>reference_id","eq",t).order("created_at",{ascending:!1}).limit(10);if(l)throw l;const i=new Set(n),o=(r??[]).filter(c=>{var f;return i.has((f=c.metadata)==null?void 0:f.action)}),u=Array.from(new Set(o.flatMap(c=>{var f;return[c.user_id,(f=c.metadata)==null?void 0:f.target_auth_id]}).filter(Boolean))),h=new Map;if(u.length>0){const{data:c}=await H.from("users").select("auth_id, full_name").in("auth_id",u);for(const f of c??[])f.auth_id&&f.full_name&&h.set(f.auth_id,f.full_name)}return o.map(c=>{var f,x;return{id:c.id,created_at:c.created_at,user_id:c.user_id,user_name:c.user_id?h.get(c.user_id)??null:null,action:c.metadata.action,target_auth_id:((f=c.metadata)==null?void 0:f.target_auth_id)??null,target_name:(x=c.metadata)!=null&&x.target_auth_id?h.get(c.metadata.target_auth_id)??null:null}})}})}function Ym(t,s){return qi(t,s,["livechat_close","livechat_transfer"])}const Qm={urgent:"destructive",high:"warning",medium:"info",low:"secondary"},Gm={open:"warning",in_progress:"default",waiting:"info",resolved:"success",closed:"inactive"},Xm=new Set(["resolved","closed"]);function Jm({ticket:t,orgId:s}){const n=Oe(),a=bc(),r=va(),{user:l}=Ot(),[i,o]=d.useState(""),[u,h]=d.useState(t.status),[c,f]=d.useState(!1),[x,C]=d.useState(null),[j,S]=d.useState(!1),D=d.useRef(null);d.useEffect(()=>{h(t.status)},[t.status]);const{data:g=[]}=zr(t.contact_id,"support"),{data:A=[]}=qi(t.id,s,["ticket_close","ticket_resolve"]),$=d.useMemo(()=>A.slice(0,2),[A]);d.useEffect(()=>{D.current&&(D.current.scrollTop=D.current.scrollHeight)},[g.length]);const b=(w,L,z)=>{Ge({action:w,phase:L,orgId:s,userId:(l==null?void 0:l.id)??null,referenceId:t.id,metadata:z})},_=w=>w==="closed"?"ticket_close":w==="resolved"?"ticket_resolve":null,M=w=>{h(w),a.mutate({id:t.id,status:w,...w==="resolved"?{resolved_at:new Date().toISOString()}:{}},{onSuccess:()=>P.success("Status updated")})},O=w=>{if(!c){if(Xm.has(w)&&w!==u){const L=_(w);L&&b(L,"opened",{from:u}),f(!0),C(w);return}M(w)}},U=()=>{if(!x)return;const w=_(x);w&&b(w,"confirmed",{from:u}),M(x),C(null),f(!1)},I=()=>{if(x){const w=_(x);w&&b(w,"cancelled",{from:u})}C(null),f(!1)},R=()=>{const w=i.trim();w&&r.mutate({org_id:s,contact_id:t.contact_id,channel:"support",direction:"outbound",content:w},{onSuccess:()=>{a.mutate({id:t.id,resolution:w,status:"resolved",resolved_at:new Date().toISOString()}),P.success("Reply sent",{description:"Ticket marked as resolved."}),o(""),h("resolved")}})},W=()=>{!i.trim()||c||r.isPending||(b("ticket_resolve","opened",{via:"reply"}),f(!0),S(!0))},J=()=>{b("ticket_resolve","confirmed",{via:"reply"}),R(),S(!1),f(!1)},X=()=>{b("ticket_resolve","cancelled",{via:"reply"}),S(!1),f(!1)},Y=w=>{const L=w.action==="ticket_close"?"Closed":"Resolved",z=w.user_name||"A teammate",N=Dn(new Date(w.created_at),{addSuffix:!0}),K=ye(new Date(w.created_at),"MMM d, h:mm a");return e.jsxs(Ca,{children:[e.jsx(Sa,{asChild:!0,children:e.jsxs("div",{role:"status",className:"flex items-center gap-1.5 text-[11px] text-muted-foreground truncate",children:[e.jsx(Wr,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{className:"truncate",children:[L," by ",z," · ",N]})]})}),e.jsx(ka,{side:"bottom",className:"text-xs",children:K})]},w.id)};return e.jsx(Al,{delayDuration:200,children:e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"border-b p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-orange-100 flex items-center justify-center shrink-0",children:e.jsx(wa,{className:"h-4 w-4 text-orange-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-sm font-semibold truncate",children:t.title}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:wc[t.category]||t.category})]})]}),e.jsxs(E,{variant:"ghost",size:"sm",className:"text-xs shrink-0",onClick:()=>n("/customer-care?tab=complaints"),children:[e.jsx(hs,{className:"h-3.5 w-3.5 mr-1"})," View"]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(ie,{variant:Gm[u]||"secondary",children:Za[u]||u}),e.jsx(ie,{variant:Qm[t.priority]||"secondary",children:t.priority}),e.jsxs(ps,{value:u,onValueChange:O,disabled:c||a.isPending,children:[e.jsx(fs,{className:"h-7 w-auto text-xs gap-1","aria-disabled":c||a.isPending,title:c?"Processing...":void 0,children:e.jsx(xs,{})}),e.jsx(gs,{children:Object.entries(Za).map(([w,L])=>e.jsx(Xe,{value:w,className:"text-xs",children:L},w))})]})]}),$.length>0&&e.jsx("div",{className:"flex flex-col gap-0.5 pt-1",children:$.map(Y)})]}),e.jsx(ys,{className:"flex-1 p-4",ref:D,children:e.jsxs("div",{className:"space-y-3",children:[g.length===0&&e.jsx("div",{className:"flex items-center justify-center py-8 text-sm text-muted-foreground",children:"No messages yet - respond below"}),g.map(w=>{const L=w.direction==="outbound";return e.jsxs("div",{className:B("flex gap-2",L&&"justify-end"),children:[!L&&e.jsx("div",{className:"h-6 w-6 rounded-full bg-muted flex items-center justify-center shrink-0 mt-0.5",children:e.jsx("span",{className:"text-[10px] font-medium",children:"C"})}),e.jsxs("div",{className:B("rounded-lg px-3 py-2 text-sm max-w-[80%]",L?"bg-primary/10":"bg-muted"),children:[e.jsxs("p",{className:"text-[10px] text-muted-foreground mb-1",children:[L?"Agent":"Customer"," · ",new Date(w.created_at).toLocaleStr
34ing(void 0,{dateStyle:"short",timeStyle:"short"})]}),e.jsx("p",{className:"whitespace-pre-wrap",children:w.content})]}),L&&e.jsx("div",{className:"h-6 w-6 rounded-full bg-primary/20 flex items-center justify-center shrink-0 mt-0.5",children:e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"A"})})]},w.id)})]})}),e.jsxs("div",{className:"border-t p-3 space-y-2",children:[e.jsx(Bs,{placeholder:"Write a reply…",value:i,onChange:w=>o(w.target.value),rows:2,className:"resize-none text-sm"}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(E,{size:"sm",onClick:W,disabled:!i.trim()||r.isPending||c,"aria-disabled":c,title:c?"Processing...":void 0,children:[e.jsx(On,{className:"h-3.5 w-3.5 mr-1"})," Resolve & Reply"]})})]}),e.jsx(Je,{open:!!x,onOpenChange:w=>{w||I()},title:x==="closed"?"Close this ticket?":"Mark this ticket resolved?",message:x==="closed"?"Closing the ticket will end this support request. You can reopen it later if needed.":"Resolving the ticket signals the issue is fixed. The customer will be notified.",confirmLabel:x==="closed"?"Close ticket":"Mark resolved",confirmVariant:x==="closed"?"destructive":"default",onConfirm:U,loading:a.isPending}),e.jsx(Je,{open:j,onOpenChange:w=>{w||X()},title:"Send reply and mark resolved?",message:"The reply will be sent to the customer and the ticket status will flip to Resolved. This can't be undone in one click.",confirmLabel:"Send & resolve",confirmVariant:"default",onConfirm:J,loading:r.isPending||a.isPending})]})})}function Zm({open:t,onOpenChange:s,contactId:n}){const{data:a,isLoading:r}=Vc(t&&n||void 0),{channels:l}=rc(a),[i,o]=d.useState(null),u=l.filter(h=>fc.includes(h.key));return e.jsxs(e.Fragment,{children:[e.jsx(At,{open:t,onOpenChange:s,children:e.jsxs(Et,{side:"bottom",className:"max-h-[85vh] overflow-y-auto sm:max-w-md sm:side-right",children:[e.jsxs(Rt,{className:"text-left",children:[e.jsx(Lt,{children:"Continue conversation"}),e.jsx(Yr,{children:a?"Carry this conversation on the channel they prefer. Each channel keeps its own thread; the relationship stays together in Customer 360.":"This is still an anonymous website visitor. Save them as a customer first, then you can continue on another channel."})]}),r&&t&&n?e.jsxs("div",{className:"space-y-2 py-4",children:[e.jsx(ra,{className:"h-14 w-full"}),e.jsx(ra,{className:"h-14 w-full"})]}):a?e.jsx("div",{className:"space-y-2 py-4",children:u.map(h=>{const c=ic({channel:h.key,state:h.state,externalHref:h.href,connectHref:h.connectHref,canSend:h.canSend,blockedReason:h.blockedReason}),f=c.mode==="unreachable";return e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:h.label}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:f?`${h.label} details not available`:h.handle})]}),c.primary.kind==="send"?e.jsx(E,{size:"sm",className:"min-h-[36px] shrink-0",onClick:()=>{o(h.key),s(!1)},children:c.primary.label}):c.primary.href?e.jsx(E,{size:"sm",variant:"outline",className:"min-h-[36px] shrink-0",asChild:!0,children:e.jsx("a",{href:c.primary.href,target:"_blank",rel:"noopener noreferrer",children:c.primary.label})}):null]}),c.note&&e.jsx("p",{className:"mt-2 text-[11px] text-muted-foreground",children:c.note}),c.secondary.length>0&&c.secondary[0].href&&e.jsx("a",{href:c.secondary[0].href,target:"_blank",rel:"noopener noreferrer",className:"mt-2 inline-block text-[11px] font-medium text-primary hover:underline",children:c.secondary[0].label})]},h.key)})}):null]})}),a&&e.jsx(Lo,{open:!!i,onOpenChange:h=>!h&&o(null),contact:a,channel:i})]})}const Fi="livechat:lastTransferTarget";function eh(){try{const t=localStorage.getItem(Fi);return t?JSON.parse(t):{}}catch{return{}}}function th(t,s){if(!(!t||!s))try{const n=eh();n[t]=s,localStorage.setItem(Fi,JSON.stringify(n))}catch{}}function sh({session:t,onBack:s,onToggleContactPanel:n,contactPanelOpen:a,sourceLabel:r}){var L,z;const l=Oe(),{user:i}=Ot(),o=Fe(),u=yo(),h=bo(),c=wo(),{data:f=[]}=_o(t.id),{data:x=[]}=ws(o),{data:C,refetch:j}=Ci(null,t.contact_id,o),S=(L=t.metadata)==null?void 0:L.visitor_id,{data:D}=xi(t.id,S,o),{data:g=[]}=Ym(t.id,o),[A,$]=d.useState(!1),[b,_]=d.useState(null),[M,O]=d.useState(!1),[U,I]=d.useState(!1),R=x.filter(N=>N.auth_id!==(i==null?void 0:i.id)),W=C!=null&&C.assigned_rep_id?((z=x.find(N=>N.id===C.assigned_rep_id))==null?void 0:z.full_name)??null:null,J=async()=>
34{if(i!=null&&i.id)try{await u.mutateAsync({sessionId:t.id,repId:i.id}),P.success("Chat assigned to you")}catch(N){P.error(us(N))}},X=async N=>{try{await c.mutateAsync({sessionId:t.id,repId:N});const K=x.find(te=>te.auth_id===N);P.success(`Chat transferred to ${(K==null?void 0:K.full_name)||"team member"}`)}catch(K){P.error(us(K))}},Y=t.visitor_name||(t.contact_id?t.visitor_email:null)||"Website Visitor",w=e.jsxs(e.Fragment,{children:[e.jsxs(pe,{onSelect:()=>I(!0),children:[e.jsx(gi,{className:"mr-2 h-4 w-4"})," Continue conversation"]}),t.status==="waiting"&&e.jsxs(pe,{onSelect:J,disabled:u.isPending,children:[e.jsx(Tt,{className:"mr-2 h-4 w-4"})," Assign to me"]}),t.status!=="closed"&&R.length>0&&e.jsxs(Fr,{children:[e.jsxs(Ur,{children:[e.jsx(Da,{className:"mr-2 h-4 w-4"})," Transfer"]}),e.jsx(Br,{className:"w-52",children:R.map(N=>e.jsx(pe,{disabled:c.isPending||M||!!b,onSelect:()=>{M||b||(O(!0),_({authId:N.auth_id,name:N.full_name||"team member"}),th(o,N.auth_id),Ge({action:"livechat_transfer",phase:"opened",orgId:o,userId:i==null?void 0:i.id,referenceId:t.id,metadata:{target_auth_id:N.auth_id}}))},children:N.full_name||"Unnamed"},N.auth_id))})]}),t.status!=="closed"&&e.jsxs(pe,{className:"text-destructive focus:text-destructive",disabled:h.isPending||M,onSelect:N=>{N.preventDefault(),!(M||A)&&(O(!0),$(!0),Ge({action:"livechat_close",phase:"opened",orgId:o,userId:i==null?void 0:i.id,referenceId:t.id}))},children:[e.jsx(Dt,{className:"mr-2 h-4 w-4"})," Close chat"]})]});return e.jsxs("div",{className:"min-w-0 border-b bg-card",children:[e.jsx(Ti,{name:Y,subtitle:[r?`Live Chat - ${r}`:null,Ii({lead:C,isLiveChat:!0,sessionStatus:t.status})].filter(Boolean).join(" · "),avatar:e.jsx(_s,{className:"h-4 w-4 text-emerald-600"}),avatarClassName:"bg-emerald-100",onBack:s,className:"border-b-0",actions:e.jsx(Mi,{lead:C,contactId:t.contact_id,orgId:o,onRefetch:j,contactName:t.visitor_name,contactEmail:t.visitor_email,extraItems:w,onToggleContactPanel:n,contactPanelOpen:a})}),e.jsx(ki,{lead:C,contactId:t.contact_id,orgId:o,onRefetch:j,contactName:t.visitor_name,contactEmail:t.visitor_email}),e.jsx($i,{lead:C,channel:"live_chat",repName:W,lastActivityAt:t.last_message_at||t.ended_at||t.started_at,visitorStats:D,pageViews:f,auditEntries:g,onAddFollowUp:t.contact_id?()=>l(`/tasks?action=create&contact=${t.contact_id}`):void 0,rememberKey:"insights:conversation:livechat"}),e.jsx(Zm,{open:U,onOpenChange:I,contactId:t.contact_id}),e.jsx(Je,{open:A,onOpenChange:N=>{!N&&A&&!h.isPending&&(Ge({action:"livechat_close",phase:"cancelled",orgId:o,userId:i==null?void 0:i.id,referenceId:t.id}),O(!1)),$(N)},title:"Close this chat?",message:"The visitor will see the conversation as ended. They can start a new chat anytime, but this thread will be marked closed in your inbox.",confirmLabel:"Close chat",confirmVariant:"destructive",loading:h.isPending,onConfirm:async()=>{Ge({action:"livechat_close",phase:"confirmed",orgId:o,userId:i==null?void 0:i.id,referenceId:t.id});try{await h.mutateAsync(t.id),P.success("Chat session closed")}catch(N){P.error(us(N))}finally{$(!1),O(!1)}}}),e.jsx(Je,{open:!!b,onOpenChange:N=>{!N&&b&&!c.isPending&&(Ge({action:"livechat_transfer",phase:"cancelled",orgId:o,userId:i==null?void 0:i.id,referenceId:t.id,metadata:{target_auth_id:b.authId}}),_(null),O(!1))},title:b?`Transfer to ${b.name}?`:"Transfer chat?",message:"They'll be assigned this chat and notified. You won't receive new messages from this visitor unless transferred back.",confirmLabel:"Transfer",confirmVariant:"default",loading:c.isPending,onConfirm:async()=>{if(b){Ge({action:"livechat_transfer",phase:"confirmed",orgId:o,userId:i==null?void 0:i.id,referenceId:t.id,metadata:{target_auth_id:b.authId}});try{await X(b.authId)}finally{_(null),O(!1)}}}})]})}const Ui=[{key:"sales",label:"Sales",blurb:"Buying questions, pricing, packages"},{key:"support",label:"Customer Support",blurb:"Something is not working"},{key:"bookings",label:"Bookings",blurb:"Appointments and reschedules"},{key:"finance",label:"Billing",blurb:"Payments, invoices, receipts"}
34,{key:"accounts",label:"Accounts",blurb:"Account access and records"},{key:"engineering",label:"Technical Support",blurb:"Login and technical faults"},{key:"success",label:"Customer Success",blurb:"Onboarding and check-ins"},{key:"retention",label:"Retention",blurb:"Cancellations and win-backs"},{key:"operations",label:"Operations",blurb:"Delivery and fulfilment"}];function Zn(t){var s;return t?((s=Ui.find(n=>n.key===t))==null?void 0:s.label)??Bi(t):"Best available team"}function Bi(t){return t.replace(/[_-]+/g," ").replace(/\b\w/g,s=>s.toUpperCase())}function nh(t){const s=t&&typeof t=="object"?t:{},n=a=>Array.isArray(a)?a.filter(r=>typeof r=="string"):[];return{headline:typeof s.headline=="string"?s.headline:null,observed:n(s.observed),crm:n(s.crm),prediction:n(s.prediction),recommended:n(s.recommended),collected:s.collected&&typeof s.collected=="object"?Object.fromEntries(Object.entries(s.collected).filter(([,a])=>a!=null&&String(a).trim()!=="").map(([a,r])=>[a,String(r)])):{}}}const ah={name:"Name",full_name:"Name",phone:"Phone",email:"Email",company:"Company",location:"Location",service:"Service interest",product:"Product interest",budget:"Budget",preferred_date:"Preferred date",booking_date:"Booking date",order_number:"Order number",invoice_number:"Invoice number",complaint_type:"C
34omplaint type",issue:"Issue",urgency:"Urgency",channel:"Preferred channel"};function rh(t){return ah[t]??Bi(t)}function ih(t,s=Date.now()){if(!t)return"just now";const n=Math.max(0,Math.floor((s-new Date(t).getTime())/6e4));return n<1?"under a minute":n<60?`${n} min`:`${Math.floor(n/60)}h ${n%60}m`}function Hi(t){return{...t,summary:nh(t==null?void 0:t.summary)}}function lh(t){return ce({queryKey:["handoff","session",t],enabled:!!t,queryFn:async()=>{const{data:s,error:n}=await H.from("livechat_handoffs").select("*").eq("livechat_session_id",t).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(n)throw n;return s?Hi(s):null},staleTime:15e3})}function oh(t){return ce({queryKey:["handoff","history",t],enabled:!!t,queryFn:async()=>{const{data:s,error:n}=await H.from("livechat_handoffs").select("*").eq("livechat_session_id",t).order("created_at",{ascending:!0});if(n)throw n;return(s??[]).map(Hi)},staleTime:3e4})}function Ma(){const t=zt();return s=>{t.invalidateQueries({queryKey:["handoff"]}),t.invalidateQueries({queryKey:["livechat-sessions"]}),s&&t.invalidateQueries({queryKey:["handoff","session",s]})}}function ch(){const{user:t}=Ot(),s=Ma();return Ln({mutationFn:async({handoff:n})=>{const a=new Date().toISOString(),r=Math.max(0,Math.round((Date.now()-new Date(n.created_at).getTime())/1e3)),{data:l}=await H.from("users").select("id").eq("auth_id",(t==null?void 0:t.id)??"").maybeSingle(),i=(l==null?void 0:l.id)??null,{error:o}=await H.from("livechat_handoffs").update({state:"accepted",accepted_by:i,accepted_at:a,wait_seconds:r}).eq("id",n.id);if(o)throw o;if(n.livechat_session_id){const{error:u}=await H.from("livechat_sessions").update({handoff_state:"accepted",handoff_accepted_at:a,needs_human:!0,status:"active",assigned_to:i}).eq("id",n.livechat_session_id);if(u)throw u}return{myId:i}},onSuccess:(n,a)=>s(a.handoff.livechat_session_id)})}function dh(){const{user:t}=Ot(),s=Fe(),n=Ma();return Ln({mutationFn:async({handoff:a,team:r,agentId:l,note:i})=>{const{data:o}=await H.from("users").select("id").eq("auth_id",(t==null?void 0:t.id)??"").maybeSingle(),u=(o==null?void 0:o.id)??null,h={...a.summary,observed:i?[...a.summary.observed,`Transfer note: ${i}`]:a.summary.observed},{error:c}=await H.from("livechat_handoffs").insert({org_id:s,livechat_session_id:a.livechat_session_id,contact_id:a.contact_id,source:"agent",intent:a.intent,confidence:a.confidence,routing_mode:"fixed",requested_team:r,assigned_team:r,assigned_to:l,assignment_strategy:l?"existing_owner":"team_queue",assignment_reason:l?"Chosen by the agent transferring":"Sent to the team queue",reason:i||a.reason,visitor_message:a.visitor_message,summary:h,state:l?"assigned":"waiting",transferred_from:u,created_by:u});if(c)throw c;await H.from("livechat_handoffs").update({state:"transferred"}).eq("id",a.id),a.livechat_session_id&&await H.from("livechat_sessions").update({handoff_state:l?"assigned":"waiting",handoff_team:r,assigned_to:l,needs_human:!0,status:l?"active":"waiting"}).eq("id",a.livechat_session_id)},onSuccess:(a,r)=>n(r.handoff.livechat_session_id)})}function uh(){const t=Ma();return Ln({mutationFn:async({handoff:s})=>{const n=new Date().toISOString(),{error:a}=await H.from("livechat_handoffs").update({state:"resolved",resolved_at:n}).eq("id",s.id);if(a)throw a;s.livechat_session_id&&await H.from("livechat_sessions").update({handoff_state:"resolved",needs_human:!1,bot_paused_until:null}).eq("id",s.livechat_session_id)},onSuccess:(s,n)=>t(n.handoff.livechat_session_id)})}function mh(){const t=Fe();return ce({queryKey:["handoff","staff",t],enabled:!!t,queryFn:async()=>{const{data:s,error:n}=await H.from("users").select("id, full_name, first_name, last_name, department, last_seen_at, is_active").eq("org_id",t).eq("is_active",!0);if(n)throw n;return(s??[]).map(a=>({id:a.id,name:a.full_name||[a.first_name,a.last_name].filter(Boolean).join(" ")||"Team member",department:a.department??null,available:!!a.last_seen_at&&Date.now()-new Date(a.last_seen_at).getTime()<5*6e4}))},staleTime:6e4})}function hh({sessionId:t}){var I;const{data:s}=lh(t),{data:n=[]}=oh(t),{data:a=[]}
34=mh(),r=ch(),l=dh(),i=uh(),[o,u]=d.useState(!1),[h,c]=d.useState(!1),[f,x]=d.useState(""),[C,j]=d.useState("queue"),[S,D]=d.useState("");if(!s||s.state==="resolved")return null;const g=s.summary,A=s.state==="waiting",$=s.state==="accepted",b=(I=a.find(R=>R.id===s.assigned_to))==null?void 0:I.name,_=async()=>{try{await r.mutateAsync({handoff:s}),P.success("You're handling this chat")}catch(R){P.error(us(R))}},M=async()=>{try{await i.mutateAsync({handoff:s}),P.success("Marked as sorted - the assistant can reply again")}catch(R){P.error(us(R))}},O=async()=>{try{await l.mutateAsync({handoff:s,team:f||null,agentId:C==="queue"?null:C,note:S.trim()||void 0}),c(!1),D(""),P.success("Passed on with everything already collected")}catch(R){P.error(us(R))}},U=f?a.filter(R=>(R.department??"").toLowerCase()===f):a;return e.jsxs("div",{className:"border-b bg-muted/30 px-3 py-3 sm:px-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(ie,{variant:A?"destructive":$?"default":"secondary",className:"rounded-full",children:A?"Waiting for a person":$?"You're handling this":`Assigned to ${b??Zn(s.assigned_team)}`}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Pn,{className:"h-3 w-3"})," ",ih(s.created_at)]}),s.assigned_team&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Qr,{className:"h-3 w-3"})," ",Zn(s.assigned_team)]})]}),g.headline&&e.jsx("p",{className:"text-sm font-medium leading-snug",children:g.headline}),s.assignment_reason&&e.jsx("p",{className:"text-xs text-muted-foreground",children:s.assignment_reason})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[!$&&e.jsxs(E,{size:"sm",onClick:_,disabled:r.isPending,children:[e.jsx(Tt,{className:"mr-1.5 h-4 w-4"})," I've got this"]}),e.jsxs(E,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(Da,{className:"mr-1.5 h-4 w-4"})," Pass on"]}),$&&e.jsxs(E,{size:"sm",variant:"ghost",onClick:M,disabled:i.isPending,children:[e.jsx(Ta,{className:"mr-1.5 h-4 w-4"})," Sorted"]})]})]}),(g.observed.length>0||Object.keys(g.collected).length>0)&&e.jsxs("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[Object.keys(g.collected).length>0&&e.jsx(os,{title:"Already collected",children:e.jsx("dl",{className:"space-y-0.5",children:Object.entries(g.collected).map(([R,W])=>e.jsxs("div",{className:"flex gap-1.5 text-xs",children:[e.jsxs("dt",{className:"text-muted-foreground",children:[rh(R),":"]}),e.jsx("dd",{className:"min-w-0 truncate font-medium",children:W})]},R))})}),g.observed.length>0&&e.jsx(os,{title:"What they said",children:e.jsx(Ds,{items:g.observed})})]}),e.jsxs(El,{open:o,onOpenChange:u,children:[e.jsxs(Rl,{className:"mt-2 inline-flex items-center gap-1 text-xs font-medium text-muted-foreground hover:text-foreground",children:[e.jsx(bs,{className:`h-3.5 w-3.5 transition-transform ${o?"rotate-180":""}`}),o?"Hide details":"More details"]}),e.jsxs(Ll,{className:"mt-2 grid gap-2 sm:grid-cols-2",children:[g.crm.length>0&&e.jsx(os,{title:"What DuceCRM already knows",children:e.jsx(Ds,{items:g.crm})}),g.prediction.length>0&&e.jsx(os,{title:"What this might mean",hint:"A reading, not a fact",children:e.jsx(Ds,{items:g.prediction})}),g.recommended.length>0&&e.jsx(os,{title:"Suggested next step",children:e.jsx(Ds,{items:g.recommended})}),n.length>1&&e.jsx(os,{title:"Handover history",children:e.jsx(Ds,{items:n.map(R=>`${Zn(R.assigned_team)} - ${R.state} (${new Date(R.created_at).toLocaleString()})`)})})]})]}),e.jsx(Kc,{open:h,onOpenChange:c,title:"Pass this chat on",description:"Everything collected so far goes with it, so the customer never repeats themselves.",primaryLabel:"Pass on",onPrimary:O,loading:l.isPending,children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(Wn,{htmlFor:"team",children:"Which team?"}),e.jsxs(ps,{value:f,onValueChange:R=>{x(R),j("queue")},children:[e.jsx(fs,{id:"team",children:e.jsx(xs,{placeholder:"Choose a team"})}),e.jsx(gs,{children:Ui.map(R=>e.jsx(Xe,{value:R.key,children:R.label},R.key))})]})]}),e.jsxs("div",{children:[e.jsx(Wn,{htmlFor:"agent",children:"Anyone in particular?"}),e.jsxs(ps,{value:C,onValueChange:j,children:[e.jsx(fs,{id:"agent",children:e.jsx(xs,{})}),e.jsxs(gs,{children:[e.jsx(Xe,{value:"queue",children:"Anyone on the team"}),U.map(R=>e.jsxs(Xe,{value:R.id,children:[R.name,R.available?"":" (offline)"]},R.id))]})]})]}),e.jsxs("div",{children:[e.jsx(Wn,{htmlFor:"note",children:"Anything to add? (optional)"}),e.jsx(Bs,{id:"note",value:S,onChange:R=>D(R.target.value),placeholder:"They already sent proof of payment",rows:3})]})]})})]})}
34function os({title:t,hint:s,children:n}){return e.jsxs("div",{className:"rounded-lg border bg-background p-2.5",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:[t,s&&e.jsxs("span",{className:"ml-1 font-normal normal-case tracking-normal",children:["- ",s]})]}),e.jsx("div",{className:"mt-1",children:n})]})}function Ds({items:t}){return e.jsx("ul",{className:"space-y-0.5",children:t.map((s,n)=>e.jsx("li",{className:"text-xs leading-snug text-foreground/90",children:s},n))})}function ph({count:t,onMarkRead:s,onMarkUnread:n,onClear:a,markingRead:r,markingUnread:l}){const i=Na();return e.jsx("div",{className:i?`${Wc} border-t bg-card px-3 py-2 shadow-lg animate-in slide-in-from-bottom-4`:"sticky top-0 z-20 flex items-center gap-2 border-b bg-card px-4 py-2 shadow-sm animate-in fade-in",children:e.jsxs("div",{className:i?"flex flex-wrap items-center gap-2":"flex items-center gap-2 w-full",children:[e.jsxs("span",{className:"text-sm font-medium text-foreground whitespace-nowrap",children:[t," selected"]}),s&&e.jsxs(E,{variant:"outline",size:"sm",onClick:s,disabled:r,className:"min-h-11 text-xs",children:[e.jsx(Kr,{className:"h-3.5 w-3.5 mr-1"}),"Mark Read"]}),n&&e.jsxs(E,{variant:"outline",size:"sm",onClick:n,disabled:l,className:"min-h-11 text-xs",children:[e.jsx(Yc,{className:"h-3.5 w-3.5 mr-1"}),"Mark Unread"]}),e.jsxs(E,{variant:"ghost",size:"sm",onClick:a,className:"min-h-11 text-xs ml-auto",title:"Clear selection","aria-label":"Clear selection",children:[e.jsx(Dt,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]})})}const jr={created:"Created",edited:"Edited",sent:"Sent",delivered:"Delivered",opened:"Opened",clicked:"Clicked a link",replied:"Replied",read:"Read",failed:"Could not be delivered",bounced:"Bounced",viewed:"Viewed",accepted:"Accepted",declined:"Declined",paid:"Paid",called:"Called",note_added:"Added a note",task_created:"Created a task",task_completed:"Completed a task",stage_moved:"Moved the stage",overdue:"Became overdue"},fh=new Set(["whatsapp","instagram","messenger","telegram"]);function xh(t){return fh.has((t??"").toLowerCase())}function gh(t,s){return xh(t)&&!!s}function yh(t,s,n){return t==="read"&&!gh(s,n)?jr.opened:jr[t]}function Vi(t){var o;const s=yh(t.event,t.channel,t.hasReadReceipt),n=(o=t.subject)==null?void 0:o.trim(),a=t.confidence??(t.hasActor?"verified":"observed");if(t.hasActor&&a==="verified")return n?`${s} ${n}`:s;const r=n?n.replace(/^(the|this)\s+/i,""):"It",i=`${r.charAt(0).toUpperCase()+r.slice(1)} ${s.toLowerCase()}`;return a==="inferred"?`Looks like ${i.charAt(0).toLowerCase()}${i.slice(1)}`:i}const bh=new Set(["sent","replied","accepted","declined","paid","called","failed","bounced","created","stage_moved","task_completed"]);function wh(t){return bh.has(t)}function _h(t){return{event:t.event,lastOccurredAt:t.lastOccurredAt,previousOccurredAt:null,occurrenceCount:Math.max(0,t.totalCount),window:"lifetime",windowProvable:!1}}function jh(t,s,n=new Date){if(t.occurrenceCount<=1)return null;const a=t.windowProvable?Nh(t.window):"",r=ai(t.lastOccurredAt,n),l=`${s} ${t.occurrenceCount} times${a}`;return r?`${l} · last ${r.toLowerCase()}`:l}function Nh(t){const s=Do[t];return s?` ${s}`:""}function ya(t,s=new Date){return ai(t,s)}const vh={today:"Today",yesterday:"Yesterday",week:"This week",earlier:"Earlier"};function Ch(t,s=new Date,n){const a=t?new Date(t):null;if(!a||Number.isNaN(a.getTime()))return"earlier";const r=Sh(s,n),l=a.getTime();return l>=r?"today":l>=r-864e5?"yesterday":l>=r-7*864e5?"week":"earlier"}function Sh(t,s){if(!s)return new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime();try{const n=new Intl.DateTimeFormat("en-CA",{timeZone:s,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(t),a=l=>{var i;return Number(((i=n.find(o=>o.type===l))==null?void 0:i.value)??"0")},r=a("hour")%24*36e5+a("minute")*6e4+a("second")*1e3;return t.getTime()-r-t.getTime()%1e3}catch{return new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()}}function kh(t,s,n=new Date,a){const r=["today","yesterday","week","earlier"],l=new Map;for(const i of t){const o=Ch(s(i),n,a),u=l.get(o);u?u.push(i):l.set(o,[i])}return r.filter(i=>{var o;return(o=l.get(i))==null?void 0:o.length}).map(i=>({bucket:i,label:vh[i],rows:l.get(i)}))}function Th({item:t,now:s,className:n}){var o;const a=ua(t.actor),r=((o=t.sentence)==null?void 0:o.trim())||Vi({event:t.event,subject:t.subject,channel:t.channel,hasActor:a,hasReadReceipt:t.hasReadReceipt,confidence:t.actor.confidence}),l=ya(t.occurredAt,s),i=t.signal?jh(t.signal,r.split(" ")[0],s):null;return e.jsxs("div",{className:B("flex items-start gap-2.5 py-2",t.onOpen&&"-mx-2 cursor-pointer rounded-md px-2 hover:bg-muted/50",n),onClick:t.onOpen,role:t.onOpen?"button":void 0,tabIndex:t.onOpen?0:void 0,onKeyDown:u=>{t.onOpen&&(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),t.onOpen())},children:[e.jsx(mi,{actor:t.actor,channel:t.channel}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm leading-snug text-foreground",children:[a?e.jsx("span",{className:"font-medium",children:t.actor.displayName}):null,a?" ":null,e.jsx("span",{className:a?"text-muted-foreground":void 0,children:r})]}),t.detail?e.jsx("p",{className:"mt-0.5 truncate text-xs text-muted-foreground",children:t.detail}):null,e.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground
34/80",children:[l,i?` · ${i}`:"",t.actor.isFormer?" · No longer on the team":""]})]})]})}function Ah({items:t,now:s,timeZone:n,emptyLabel:a="Nothing recorded yet",className:r}){const l=d.useMemo(()=>[...t].sort((o,u)=>Date.parse(u.occurredAt)-Date.parse(o.occurredAt)),[t]),i=d.useMemo(()=>kh(l,o=>o.occurredAt,s,n),[l,s,n]);return l.length?e.jsx("div",{className:B("space-y-4",r),children:i.map(o=>e.jsxs("div",{children:[e.jsx("p",{className:"mb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground/70",children:o.label}),e.jsx("div",{className:"divide-y divide-border/50",children:Eh(o.rows).map(u=>u.kind==="single"?e.jsx(Th,{item:u.item,now:s},u.item.id):e.jsx(Rh,{items:u.items,now:s},u.key))})]},o.bucket))}):e.jsx("p",{className:B("py-4 text-sm text-muted-foreground",r),children:a})}function Eh(t){const s=new Map,n=[];for(const a of t){const r=wh(a.event)?`single:${a.id}`:`${a.event}:${a.actor.actorType}:${a.channel??""}`;s.has(r)||(s.set(r,[]),n.push(r)),s.get(r).push(a)}return n.map(a=>{const r=s.get(a);return r.length>1?{kind:"repeat",key:a,items:r}:{kind:"single",item:r[0]}})}function Rh({items:t,now:s}){var o;const[n,a]=d.useState(!1),r=t[0],l=((o=r.sentence)==null?void 0:o.trim())||Vi({event:r.event,subject:r.subject,channel:r.channel,hasActor:ua(r.actor),hasReadReceipt:r.hasReadReceipt,confidence:r.actor.confidence}),i=ya(r.occurredAt,s);return e.jsxs("div",{className:"py-2",children:[e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx(mi,{actor:r.actor,channel:r.channel}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm leading-snug text-foreground",children:[ua(r.actor)?e.jsxs("span",{className:"font-medium",children:[r.actor.displayName," "]}):null,e.jsxs("span",{className:"text-muted-foreground",children:[l," · ",t.length," times"]})]}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground/80",children:i?`Last ${i}`:null})]}),e.jsxs(E,{variant:"ghost",size:"sm",className:"h-7 shrink-0 px-2 text-xs",onClick:()=>a(u=>!u),children:[n?"Hide":"Show each",e.jsx(bs,{className:B("ml-1 h-3 w-3 transition-transform",n&&"rotate-180")})]})]}),n?e.jsx("div",{className:"mt-1 space-y-1 border-l border-border/60 pl-4",children:t.map(u=>e.jsx(d.Fragment,{children:e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ya(u.occurredAt,s),u.detail?` · ${u.detail}`:""]})},u.id))}):null]})}function Lh(t){return(!!t.authenticatedCustomer||!!t.customerDeclared||t.direction==="inbound"&&!!t.providerIdentityMatched)&&!t.trackingOnly?{contactActed:!0,confidence:"verified"}:t.contactId?{contactActed:!1,confidence:"observed"}:{contactActed:!1,confidence:"unknown"}}const Dh=30,Oh={shared:"sent",viewed:"viewed",opened:"viewed",downloaded:"viewed",accepted:"accepted",declined:"declined",payment_started:"paid",paid:"paid"};function Mh(t,s,n){const{data:a=[]}=Po(),{data:r,isLoading:l}=ce({queryKey:["contact-activity",t,s],enabled:!!(t&&s),staleTime:6e4,queryFn:async()=>{const[i,o,u]=await Promise.all([H.from("message_deliveries").select("id, channel, subject, sender_id, source, sent_at, delivered_at, opened_at, clicked_at, replied_at, failed_at, created_at").eq("org_id",t).eq("contact_id",s).order("created_at",{ascending:!1}).limit(25),H.from("document_events").select("id, event, document_kind, channel, actor_id, occurred_at").eq("org_id",t).eq("contact_id",s).order("occurred_at",{ascending:!1}).limit(25),H.rpc("contact_engagement_signals",{_org_id:t,_contact_id:s,_days:Dh})]);return{deliveries:i.data??[],documents:o.data??[],signals:u.data??[]}}});return d.useMemo(()=>{const i=s?{id:s,name:n==null?void 0:n.name,avatarUrl:n==null?void 0:n.avatarUrl}:null,o={members:a,contact:i,orgId:t??null},u=[];for(const c of(r==null?void 0:r.deliveries)??[]){const f={orgId:t??null,channel:c.channel,contactId:s};c.sent_at&&u.push({id:`${c.id}:sent`,event:"sent",occurredAt:c.sent_at,subject:c.subject?`"${c.subject}"`:"a message",channel:c.channel,actor:ls({...f,actorId:c.sender_id,eventSource:c.sender_id?null:c.source},o)}),c.replied_at&&u.push({id:`${c.id}:replied`,event:"replied",occurredAt:c.replied_at,channel:c.channel,actor:ls({...f,contactActed:!0,confidence:"verified"},o)}),c.clicked_at&&u.push({id:`${c.id}:clicked`,event:"clicked",occurredAt:c.clicked_at,subject:c.subject?`in "${c.subject}"`:null,channel:c.channel,actor:ls({...f,eventSource:"tracking",confidence:"observed"},o)}),c.opened_at&&u.push({id:`${c.id}:opened`,event:"opened",occurredAt:c.opened_at,subject:c.subject?`"${c.subject}"`:"the message",channel:c.channel,actor:ls({...f,eventSource:"tracking",confidence:"observed"},o)}),c.failed_at&&u.push({id:`${c.id}:failed`,event:"failed",occurredAt:c.failed_at,subject:c.subject?`"${c.subject}"`:"the message",channel:c.channel,actor:ls({...f,eventSource:"channel"},o)})}for(const c of(r==null?void 0:r.documents)??[]){const f=Oh[c.event];if(!f)continue;
34const x=c.actor_id?{contactActed:!1,confidence:"verified"}:Lh({contactId:s,customerDeclared:f!=="viewed",trackingOnly:f==="viewed"});u.push({id:`doc:${c.id}`,event:f,occurredAt:c.occurred_at,subject:`the ${c.document_kind??"document"}`,channel:c.channel,actor:ls({orgId:t??null,actorId:c.actor_id,contactId:s,contactActed:x.contactActed,confidence:x.confidence,eventSource:c.actor_id?null:"channel"},o)})}const h=((r==null?void 0:r.signals)??[]).map(c=>_h({event:c.event,totalCount:Number(c.occurrence_count),lastOccurredAt:c.last_occurred_at}));return{items:u,signals:h,engagementFacts:Ph(h),isLoading:l}},[r,a,t,s,n==null?void 0:n.name,n==null?void 0:n.avatarUrl,l])}function Ph(t){const s=new Map(t.map(i=>[i.event,i])),n=[],a=s.get("sent");a!=null&&a.occurrenceCount&&n.push(`${a.occurrenceCount} ${a.occurrenceCount===1?"message":"messages"} sent in 30 days`);const r=s.get("replied");r!=null&&r.occurrenceCount?n.push(`${r.occurrenceCount} ${r.occurrenceCount===1?"reply":"replies"}`):a!=null&&a.occurrenceCount&&n.push("No reply yet");const l=s.get("opened");return l!=null&&l.occurrenceCount&&n.push(`Opened ${l.occurrenceCount} ${l.occurrenceCount===1?"time":"times"}`),n}function Ih(t){return ce({queryKey:["chat-attachments",t],queryFn:async()=>{if(!t)return[];const{data:s,error:n}=await H.from("chat_attachments").select("*").eq("session_id",t).order("created_at",{ascending:!1});if(n)throw n;return s||[]},enabled:!!t})}function $h(t){return ce({queryKey:["payment-reviews",t],queryFn:async()=>{const{data:s,error:n}=await H.from("payment_evidence_reviews").select("*, chat_attachments(*)").eq("org_id",t).order("created_at",{ascending:!1}).limit(50);if(n)throw n;return s||[]},enabled:!!t})}function qh(){const t=zt();return Ln({mutationFn:async({id:s,review_status:n,review_note:a,reviewed_by:r})=>{const{error:l}=await H.from("payment_evidence_reviews").update({review_status:n,review_note:a||null,reviewed_by:r||null}).eq("id",s);if(l)throw l},onSuccess:()=>{t.invalidateQueries({queryKey:["payment-reviews"]}),P.success("Review updated")},onError:s=>P.error("Failed to update review",{cause:s})})}function Fh(t){const[s,n]=d.useState(null),[a,r]=d.useState(!1);return d.useEffect(()=>{if(!t){n(null);return}if(/^https?:\/\//i.test(t)){n(t);return}let l=!1;return r(!0),H.storage.from("chat-uploads").createSignedUrl(t,60*60).then(({data:i,error:o})=>{l||n(o?null:(i==null?void 0:i.signedUrl)??null)}).finally(()=>!l&&r(!1)),()=>{l=!0}},[t]),{url:s,loading:a}}function Uh({fileUrl:t}){const{url:s,loading:n}=Fh(t);return n?e.jsx("span",{className:"text-[10px] text-muted-foreground shrink-0",children:"..."}):s?e.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-primary hover:underline shrink-0",children:"View"}):e.jsx("span",{className:"text-[10px] text-muted-foreground shrink-0",children:"Unavailable"})}const Nr={submitted:{label:"Submitted",color:"bg-yellow-100 text-yellow-800",icon:la},under_review:{label:"Under Review",color:"bg-blue-100 text-blue-800",icon:An},verified:{label:"Verified",color:"bg-green-100 text-green-800",icon:Ta},rejected:{label:"Rejected",color:"bg-destructive/10 text-destructive",icon:Gr},needs_more_info:{label:"Needs More Info",color:"bg-orange-100 text-orange-800",icon:la}};function Bh({sessionId:t}){var S;const s=Fe(),{session:n}=Ot(),a=((S=n==null?void 0:n.user)==null?void 0:S.id)||null,{data:r=[]}=Ih(t),{data:l=[]}=$h(s),i=qh(),[o,u]=d.useState(""),[h,c]=d.useState(null),f=new Set(r.map(D=>D.id)),x=l.filter(D=>f.has(D.attachment_id)),C=(D,g)=>{if(g==="rejected"||g==="needs_more_info"){c({reviewId:D,action:g});return}i.mutate({id:D,review_status:g,reviewed_by:a||void 0})},j=()=>{h&&i.mutate({id:h.reviewId,review_status:h.action,review_note:o||void 0,reviewed_by:a||void 0},{onSuccess:()=>{c(null),u("")}})};return r.length===0?null:e.jsxs(Ct,{children:[e.jsx(jn,{className:"p-3 pb-1",children:e.jsxs(Nn,{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(ia,{className:"h-3.5 w-3.5"})," Payment Evidence",e.jsx(ie,{variant:"secondary",className:"text-[10px] ml-auto",children:r.length})]})}),e.jsx(St,{className:"p-3 pt-0 space-y-2",children:r.map(D=>{const g=x.find(b=>b.attachment_id===D.id),A=g?Nr[g.review_status]||Nr.submitted:null,$=(A==null?void 0:A.icon)||la;return e.jsxs("div",{className:"rounded-lg border p-2.5 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[D.attachment_type==="image"?e.jsx(Qc,{className:"h-4 w-4 text-muted-foreground shrink-0"}):e.jsx(ia,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-xs font-medium truncate flex-1",children:D.original_name||"Attachment"}),e.jsx(Uh,{fileUrl:D.file_url})]}),D.payment_reference&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Ref
34: ",D.payment_reference]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Dn(new Date(D.created_at),{addSuffix:!0})}),A&&e.jsxs(ie,{className:`text-[10px] ${A.color} border-0`,children:[e.jsx($,{className:"h-3 w-3 mr-0.5"}),A.label]})]}),g&&g.review_status==="submitted"&&e.jsxs("div",{className:"flex gap-1 pt-1",children:[e.jsxs(E,{size:"sm",variant:"outline",className:"text-[10px] h-6 px-2",onClick:()=>C(g.id,"verified"),children:[e.jsx(Ta,{className:"h-3 w-3 mr-0.5"})," Verify"]}),e.jsxs(E,{size:"sm",variant:"outline",className:"text-[10px] h-6 px-2",onClick:()=>C(g.id,"rejected"),children:[e.jsx(Gr,{className:"h-3 w-3 mr-0.5"})," Reject"]}),e.jsx(E,{size:"sm",variant:"outline",className:"text-[10px] h-6 px-2",onClick:()=>C(g.id,"needs_more_info"),children:"More Info"})]}),(g==null?void 0:g.review_note)&&e.jsxs("p",{className:"text-[10px] text-muted-foreground italic",children:["Note: ",g.review_note]})]},D.id)})}),e.jsx(Hs,{open:!!h,onOpenChange:()=>c(null),children:e.jsxs(Vs,{size:"sm",className:"",children:[e.jsx(zs,{children:e.jsx(Ks,{className:"text-sm",children:(h==null?void 0:h.action)==="rejected"?"Reject Evidence":"Request More Info"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(kt,{placeholder:"Add a note (reason)...",value:o,onChange:D=>u(D.target.value)}),e.jsxs(E,{onClick:j,disabled:i.isPending,className:"w-full",size:"sm",children:[i.isPending&&e.jsx(Is,{className:"h-4 w-4 mr-1 animate-spin"}),"Confirm"]})]})]})})]})}function Hh({contactId:t,orgId:s,onClose:n,livechatSessionId:a,activeChannel:r,onComposeEmail:l,onOpenConversation:i}){var j,S,D;const o=Oe(),{initiateCall:u}=ri(),{data:h}=ce({queryKey:["contact-side-panel",t],queryFn:async()=>{if(!t)return null;const{data:g,error:A}=await H.from("contacts").select("*").eq("id",t).single();if(A)throw A;return g},enabled:!!t}),{data:c=[]}=ce({queryKey:["contact-deals",t],queryFn:async()=>{if(!t)return[];const{data:g,error:A}=await H.from("deals").select("id, title, value, stage, status, currency").eq("contact_id",t).order("created_at",{ascending:!1}).limit(5);if(A)throw A;return g||[]},enabled:!!t}),f=Mh(s,t,{name:h==null?void 0:h.full_name,avatarUrl:h==null?void 0:h.avatar_url}),{data:x}=ce({queryKey:["lc-session-ctx",a],queryFn:async()=>{if(!a)return null;const{data:g}=await H.from("livechat_sessions").select("current_url, page_title, page_type, session_path, viewed_pricing, viewed_checkout, viewed_contact, utm_source").eq("id",a).single();return g},enabled:!!a});if(!t||!h)return e.jsx("div",{className:"flex items-center justify-center h-full text-sm text-muted-foreground p-4",children:"Select a conversation to see contact details"});const C=(g,A="NGN")=>new Intl.NumberFormat("en-NG",{style:"currency",currency:A,maximumFractionDigits:0}).format(g);return e.jsx(ys,{className:"h-full",children:e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-primary/10 text-primary font-semibold",children:((S=(j=h.full_name)==null?void 0:j.charAt(0))==null?void 0:S.toUpperCase())||"?"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:h.full_name}),h.company&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Dl,{className:"h-3 w-3"})," ",h.company]})]})]}),e.jsx(E,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:n,children:e.jsx(Dt,{className:"h-4 w-4"})})]}),e.jsx(di,{contact:h,activeChannel:r??null,onCall:g=>u({...h,phone:g}),onEmail:()=>l==null?void 0:l(h.email??""),onOpenConversation:i,onViewFullContact:()=>it(o,h.id)}),e.jsx(Ct,{children:e.jsxs(St,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pa,{className:"h-3 w-3 text-muted-foreground"}),e.jsxs("span",{className:"text-xs",children:["Score: ",h.lead_score||0]}),h.lifecycle_stage&&e.jsx(ie,{variant:"outline",className:"text-[10px] ml-auto",children:h.lifecycle_stage})]}),h.status&&e.jsx(ie,{variant:"secondary",className:"text-[10px]",children:h.status})]})}),h.tags&&h.tags.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:h.tags.map((g,A)=>e.jsx(ie,{variant:"outline",className:"text-[10px]",children:g},A))}),e.jsxs(Ct,{children:[e.jsx(jn,{className:"p-3 pb-1",children:e.jsxs(Nn,{className:"text-xs font-medium flex items-center justify-between",children:["Active Deals",e.jsxs(E,{variant:"ghost",size:"sm",className:"h-6 text-[10px] px-1.5",onClick:()=>it(o,t),children:["View All ",e.jsx(Xr,{className:"h-3 w-3"})]})]})}),e.jsx(St,{className:"p-3 pt-0 space-y-1.5",children:c.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No deals yet"}):c.map(g=>e.jsxs("div",{className:"flex items-center justify-between rounded border p-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:g.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:g.stage||g.status})]}),e.jsx("span",{className:"text-xs font-semibold shrink-0 ml-2",children:C(Number(g.value)||0,g.currency||"NGN")})]},g.id))})]}),e.jsxs(Ct,{children:[e.jsx(jn,{className:"p-3 pb-1",children:e.jsx(Nn,{className:"text-xs font-medium",children:"Recent Activity"})}),e.jsxs(St,{className:"p-3 pt-0",children:[f.engagementFacts.length>0&&e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:f.engagementFacts.join(" · ")}),e.jsx(Ah,{items:f.items,emptyLabel:"No recent activity"})]})]}),x&&e.jsxs(Ct,{children:[e.jsx(jn,{className:"p-3 pb-1",children:e.jsxs(Nn,{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(Gc,{
34className:"h-3.5 w-3.5"})," Visitor Journey"]})}),e.jsxs(St,{className:"p-3 pt-0 space-y-1.5",children:[x.page_title&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"font-medium",children:"Current Page:"})," ",x.page_title]}),x.page_type&&e.jsx(ie,{variant:"outline",className:"text-[10px]",children:x.page_type}),x.viewed_pricing&&e.jsx(ie,{variant:"secondary",className:"text-[10px]",children:"Viewed Pricing"}),x.viewed_checkout&&e.jsx(ie,{variant:"secondary",className:"text-[10px]",children:"Viewed Checkout"}),((D=x.session_path)==null?void 0:D.length)>1&&e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:[x.session_path.length," pages visited"]}),x.utm_source&&e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:["Source: ",x.utm_source]})]})]}),a&&e.jsx(Bh,{sessionId:a}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(E,{variant:"outline",size:"sm",className:"text-xs h-7",onClick:()=>it(o,t),children:[e.jsx(hi,{className:"h-3 w-3 mr-1"})," Full Profile"]}),e.jsxs(E,{variant:"outline",size:"sm",className:"text-xs h-7",onClick:()=>o(`/pipeline?contact=${t}`),children:[e.jsx(Jr,{className:"h-3 w-3 mr-1"})," Add deal"]})]})]})})}function Vh({call:t,open:s,onOpenChange:n,contactName:a}){pi("call",t==null?void 0:t.id,{enabled:s});const r=Oe(),l=_c(),i=jc(),o=Nc(),u=Fe(),{data:h=[]}=ws(u),{data:c}=ba(),{user:f}=Ot(),{role:x}=Zr(),C=x==="admin"||x==="manager",[j,S]=d.useState(!1),[D,g]=d.useState(!1),[A,$]=d.useState(!1),[b,_]=d.useState(!1),[M,O]=d.useState([]),[U,I]=d.useState(""),[R,W]=d.useState(""),[J,X]=d.useState(0),[Y,w]=d.use
34State("");if(fi("call",t==null?void 0:t.id,[c==null?void 0:c.id]),!t)return null;const L=wn(t.status),z=t.direction==="inbound",N=t,K=N.sentiment?parseInt(N.sentiment,10):0,te=()=>{I(N.call_purpose||""),W(N.disposition||""),X(K),w(t.notes||""),$(!0)},ae=async()=>{try{await l.mutateAsync({id:t.id,call_purpose:U||null,disposition:R||null,sentiment:J>0?String(J):null,notes:Y}),$(!1),P.success("Call updated")}catch(G){P.error("That did not save",{description:we(G)})}},Ce=async()=>{if(M.length!==0)try{C?(await i.mutateAsync({callId:t.id,recipientIds:M,orgId:t.org_id,contactName:a||"Unknown",duration:t.duration_seconds,senderName:(c==null?void 0:c.full_name)||"A team member"}),P.success("Recording shared with "+M.length+" team member(s)")):(await o.mutateAsync({orgId:t.org_id,callId:t.id,requestedBy:(f==null?void 0:f.id)||"",recipientIds:M}),P.success("Share request sent for admin approval")),_(!1),O([])}catch(G){P.error("That did not save",{description:we(G)})}},_e=G=>{O(Z=>Z.includes(G)?Z.filter(je=>je!==G):[...Z,G])};return e.jsx(At,{open:s,onOpenChange:n,children:e.jsxs(Et,{className:"w-[420px] sm:max-w-[420px] p-0 flex flex-col",children:[e.jsx(Rt,{className:"p-4 pb-0 pr-12",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Lt,{className:"text-lg",children:"Call Details"}),e.jsxs("div",{className:"flex items-center gap-1",children:[!A&&e.jsxs(E,{size:"sm",variant:"ghost",onClick:te,children:[e.jsx(bi,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),t.recording_url&&e.jsxs($s,{open:b,onOpenChange:_,children:[e.jsx(qs,{asChild:!0,children:e.jsxs(E,{size:"sm",variant:"ghost",children:[e.jsx(gi,{className:"h-3.5 w-3.5 mr-1"})," ",C?"Share":"Request Share"]})}),e.jsxs(Fs,{className:"w-64",align:"end",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Share recording with:"}),e.jsxs("div",{className:"space-y-1.5 max-h-40 overflow-y-auto",children:[!C&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted/50 p-2 mb-2",children:[e.jsx(qr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Requires admin approval"})]}),h.filter(G=>G.id!==(c==null?void 0:c.id)).map(G=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer hover:bg-muted/50 rounded p-1",children:[e.jsx(Rr,{checked:M.includes(G.id),onCheckedChange:()=>_e(G.id)}),G.full_name]},G.id))]}),e.jsx(E,{size:"sm",className:"w-full mt-2",disabled:M.length===0||i.isPending||o.isPending,onClick:Ce,children:C?`Share with ${M.length} member(s)`:`Request share with ${M.length} member(s)`})]})]})]})]})}),e.jsx(ys,{className:"flex-1 px-4 pb-4",children:e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsx("div",{className:"rounded-lg border p-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:B("h-10 w-10 rounded-full flex items-center justify-center",z?"bg-info/15":"bg-primary/15"),children:z?e.jsx(fa,{className:"h-5 w-5 text-info"}):e.jsx(xa,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:a||"Unknown Contact"}),e.jsxs("p",{className:"text-caption",children:[z?"Inbound":"Outbound"," call"]})]})]}),t.contact_id&&e.jsxs(Ca,{children:[e.jsx(Sa,{asChild:!0,children:e.jsx(E,{size:"sm",variant:"outline","aria-label":"View contact",onClick:()=>{it(r,t.contact_id),n(!1)},children:e.jsx(hs,{className:"h-3 w-3"})})}),e.jsx(ka,{children:"View Contact"})]})]})}),N.is_recorded&&e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-1.5",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-destructive animate-pulse"}),e.jsx("span",{className:"text-xs font-medium text-destructive",children:"Recorded"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-caption",children:"Status"}),e.jsx(ie,{variant:L.variant,children:L.label})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-caption",children:"Duration"}),e.jsx("span",{className:"text-sm font-medium",children:ds(t.duration_seconds)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-caption",children:"Date & Time"}),e.jsx("span",{className:"text-sm",children:t.started_at?ye(new Date(t.started_at),"MMM d, yyyy · HH:mm"):ye(new Date(t.created_at),"MMM d, yyyy · HH:mm")}
34)]})]}),A?e.jsxs(e.Fragment,{children:[e.jsx(is,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(rt,{className:"text-caption",children:"Purpose"}),e.jsx("div",{className:"mt-1",children:e.jsx(Zc,{value:U,onChange:I})})]}),e.jsxs("div",{children:[e.jsx(rt,{className:"text-caption",children:"Disposition"}),e.jsxs(ps,{value:R,onValueChange:W,children:[e.jsx(fs,{className:"mt-1",children:e.jsx(xs,{placeholder:"Select disposition"})}),e.jsx(gs,{children:vc.map(G=>e.jsx(Xe,{value:G.key,children:G.label},G.key))})]})]}),e.jsxs("div",{children:[e.jsx(rt,{className:"text-caption",children:"Sentiment"}),e.jsx("div",{className:"flex items-center gap-1 mt-1",children:[1,2,3,4,5].map(G=>e.jsx("button",{onClick:()=>X(G),children:e.jsx(pa,{className:B("h-5 w-5 cursor-pointer",G<=J?"text-warning fill-warning":"text-muted-foreground/30")})},G))})]}),e.jsxs("div",{children:[e.jsx(rt,{className:"text-caption",children:"Notes"}),e.jsx(Bs,{value:Y,onChange:G=>w(G.target.value),rows:3,className:"mt-1"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(E,{size:"sm",onClick:ae,disabled:l.isPending,children:[e.jsx(Us,{className:"h-3.5 w-3.5 mr-1"})," Save"]}),e.jsxs(E,{size:"sm",variant:"outline",onClick:()=>$(!1),children:[e.jsx(Dt,{className:"h-3.5 w-3.5 mr-1"})," Cancel"]})]})]})]}):e.jsx(e.Fragment,{children:(N.call_purpose||N.disposition||K>0||N.issue_resolved!==null)&&e.jsxs(e.Fragment,{children:[e.jsx(is,{}),e.jsxs("div",{className:"space-y-2",children:[N.call_purpose&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-caption",children:"Purpose"}),e.jsx(ie,{variant:"secondary",children:_n(N.call_purpose)})]}),N.disposition&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-caption",children:"Disposition"}),e.jsx(ie,{variant:"outline",children:ma(N.disposition)})]}),K>0&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-caption",children:"Sentiment"}),e.jsx("div",{className:"flex items-center gap-0.5",children:[1,2,3,4,5].map(G=>e.jsx(pa,{className:B("h-3.5 w-3.5",G<=K?"text-warning fill-warning":"text-muted-foreground/30")},G))})]}),N.issue_resolved!==null&&N.issue_resolved!==void 0&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-caption",children:"Issue Resolved"}),e.jsx(ie,{variant:N.issue_resolved?"success":"danger",children:N.issue_resolved?"Yes":"No"})]})]})]})}),(N.forwarded_to||N.forwarded_from)&&e.jsxs(e.Fragment,{children:[e.jsx(is,{}),e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border p-2 bg-muted/30",children:[e.jsx(Da,{className:"h-4 w-4 text-info"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:N.forwarded_to?"Forwarded to another agent":"Forwarded from another agent"})]})]}),t.recording_url&&e.jsxs(e.Fragment,{children:[e.jsx(is,{}),e.jsxs("div",{children:[e.jsx(rt,{className:"text-caption",children:"Recording"}),e.jsx("div",{className:"mt-1.5 rounded-lg border p-3 bg-muted/30",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(E,{size:"icon",variant:"outline",className:"h-9 w-9 rounded-full bg-primary text-primary-foreground hover:bg-primary/90 border-0",onClick:()=>g(!D),children:e.jsx(sd,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1 flex items-center gap-0.5 h-8",children:Array.from({length:40}).map((G,Z)=>e.jsx("div",{className:B("w-1 rounded-full transition-all",D&&Z<15?"bg-primary":"bg-muted-foreground/30"),style:{height:`${Math.random()*100}%`,minHeight:"4px"}},Z))}),e.jsx("span",{className:"text-xs text-muted-foreground",children:ds(t.duration_seconds)})]})})]})]}),t.transcript&&e.jsxs(e.Fragment,{children:[e.jsx(is,{}),e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>S(!j),className:"flex items-center gap-2 text-sm font-medium w-full",children:[e.jsx(ia,{className:"h-4 w-4"}),"Transcript",j?e.jsx(Mr,{className:"h-3 w-3 ml-auto"}):e.jsx(bs,{className:"h-3 w-3 ml-auto"})]}),j&&e.jsx("div",{className:"mt-2 rounded-lg border p-3 bg-muted/30 max-h-48 overflow-y-auto",children:e.jsx("p",{className:"text-xs whitespace-pre-wrap",children:t.transcript})})]})]}),!A&&e.jsxs(e.Fragment,{children:[e.jsx(is,{}),e.jsxs("div",{children:[e.jsx(rt,{className:"text-caption",children:"Notes"}),t.notes?e.jsx("div",{className:"mt-1.5 rounded-lg border p-3 bg-muted/30",children:e.jsx("p",{className:"text-xs whitespace-pre-wrap",children:t.notes})}):e.jsx("p",{className:"mt-1.5 text-xs text-muted-foreground italic",children:"No notes added. Click Edit to add notes."})]})]})]})})]})})}const zh=({embedded:t=!1}={})=>{const s=Fe(),n=Oe(),{user:a}=Ot(),[r,l]=d.useState(""),[i,o]=d.useState("all"),[u,h]=d.useState("all"),[c,f]=d.useState(!1),[x,C]=d.use
34State(!1),j={};i!=="all"&&(j.direction=i),u!=="all"&&(j.status=u);const{data:S=[],isLoading:D}=Cc(j),{data:g=[]}=Aa(),{data:A=[]}=ws(s),$=Sc(S),{isAdminOrManager:b}=Zr(),{data:_=[]}=kc(b?s:void 0),M=Tc(),O=Ac(),[U,I]=d.useState(null),[R,W]=d.useState(!1),[J,X]=d.useState(!1),[Y,w]=d.useState(!1),[L,z]=d.useState({contactId:null,contactName:""}),N=d.useMemo(()=>{const v=new Map;for(const ne of g)v.set(ne.id,{name:ne.full_name,phone:ne.phone||""});return v},[g]),K=v=>{var ne;return v&&((ne=N.get(v))==null?void 0:ne.name)||"Unknown"},te=r?S.filter(v=>K(v.contact_id).toLowerCase().includes(r.toLowerCase())):S,{paginatedItems:ae,...Ce}=nd(te,25,{persistKey:"calls"}),_e=d.useMemo(()=>{const v=new Set(["missed","no_answer","logged_no_answer","logged_busy","voicemail"]);return S.filter(ne=>v.has(ne.status)).slice(0,6).map(ne=>({id:ne.id,title:K(ne.contact_id),reason:`${wn(ne.status).label} - try again`,meta:ye(new Date(ne.created_at),"d MMM, HH:mm"),actionLabel:"Log a call",onAction:()=>X(!0),onOpen:()=>{I(ne),W(!0)},tone:"warning"}))},[S,N]),G=v=>{if(v.linkedDealId){P.success("Call linked to deal");return}z(v),w(!0)},{presence:Z,isLoading:je}=Io({entityType:"call",entityIds:S.map(v=>v.id),owners:Object.fromEntries(S.map(v=>[v.id,v.user_id??null]))}),fe=[{key:"contact_id",label:"Customer",render:v=>e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(li,{name:K(v.contact_id),size:"sm"}),e.jsx("span",{className:"truncate text-sm font-medium",children:K(v.contact_id)})]})},{key:"direction",label:"Direction",render:v=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[v.direction==="inbound"?e.jsx(fa,{className:"h-3.5 w-3.5 text-info"}):e.jsx(xa,{className:"h-3.5 w-3.5 text-primary"}),e.jsx("span",{className:"text-xs capitalize",children:v.direction})]})},{key:"status",label:"Status",render:v=>{const ne=wn(v.status);return e.jsx(ie,{variant:ne.variant,children:ne.label})}},{key:"duration_seconds",label:"Duration",sortable:!0,render:v=>e.jsx("span",{className:"text-sm font-mono",children:ds(v.duration_seconds)})},{key:"user_id",label:"People",className:"hidden sm:table-cell",render:v=>e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx(oi,{presence:Z[v.id],noun:"call",size:"sm",max:3,loading:je,emptyState:e.jsx("span",{className:"text-xs text-muted-foreground",children:"Nobody recorded"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:ii(Z[v.id],{noReplyLabel:""})})]})},{key:"created_at",label:"Date & Time",sortable:!0,render:v=>e.jsx("span",{className:"text-sm",children:ye(new Date(v.created_at),"MMM d, HH:mm")})},{key:"call_purpose",label:"Purpose",className:"hidden lg:table-cell",render:v=>e.jsx("span",{className:"text-xs",children:v.call_purpose?_n(v.call_purpose):"-"})},{key:"disposition",label:"Disposition",className:"hidden lg:table-cell",render:v=>e.jsx("span",{className:"text-xs",children:v.disposition?ma(v.disposition):"-"})},{key:"notes",label:"Notes",className:"hidden lg:table-cell",render:v=>e.jsx("span",{className:"text-xs text-muted-foreground truncate max-w-[150px] block",children:v.notes||"-"})},{key:"view_action",label:"",className:"w-10",render:()=>e.jsx(An,{className:"h-4 w-4 text-muted-foreground","aria-label":"View call details"})}],Se=yi("calls",{attention:{items:_e,summary:`${_e.length} ${_e.length===1?"person was":"people were"} not reached`},insights:{summary:"How your calling is going",observed:[{id:"total",text:`${$.totalCalls} call${$.totalCalls===1?"":"s"} logged this month.`},{id:"answer",text:`${$.answerRate}% of calls were answered.`}],children:e.jsx(Jc,{columns:4,items:[{label:"Calls this month",value:$.totalCalls,icon:Ht},{label:"Average length",value:ds($.avgDuration),icon:Pn},{label:"Pick-up rate",value:`${$.answerRate}%`,icon:mc},{label:"Connected",value:$.completedCalls,icon:Ol}]})}});return e.jsxs("div",{className:"space-y-4",children:[e.jsx(ni,{title:t?"":"Calls",description:t?void 0:wi("calls"),module:t?void 0:"calls",primaryLabel:"Log a call",primaryIcon:e.jsx(Ht,{className:"h-4 w-4"}),onPrimary:()=>X(!0),immediateActions:[{label:"Connect phone",icon:e.jsx(Ja,{className:"h-4 w-4"}),onClick:()=>C(!0)}],secondaryActions:[...b&&_.length>0?[{label:`Share requests (${_.length})`,icon:e.jsx(Ml,{className:"h-4 w-4"}),onClick:()=>f(!0)}]:[],...te.length>0?[{label:"Export CSV",icon:e.jsx(cd,{className:"h-4 w-4"}),onClick:()=>{id(te.map(v=>({contact:K(v.contact_id),direction:v.direction,status:v.status,duration:ds(v.duration_seconds),purpose:v.call_purpose?_n(v.call_purpose):"-",disposition:v.disposition?ma(v.disposition):"-",date:ye(new Date(v.created_at),"yyyy-MM-dd HH:mm"),notes:v.notes||""})),"calls-export")}}]:[]]}),Se.attentionTop,Se.insightsTop,e.jsxs("div",{className:"flex flex-col sm:flex-row flex-wrap items-stretch sm:items-center gap-2",children:[e.jsxs("div",{className:"relative w-full sm:w-56",children:[e.jsx(Pl,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(kt,{placeholder:"Search by contact...",value:r,onChange:v=>l(v.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ps,{value:i,onValueChange:o,children:[e.jsx(fs,{className:"w-full sm:w-32",children:e.jsx(xs,{placeholder:"Direction"})}),e.jsxs(gs,{children:[e.jsx(Xe,{value:"all",children:"All Directions"}),e.jsx(Xe,{value:"inbound",children:"Inbound"}),e.jsx(Xe,{value:"outbound",children:"Outbound"})]})]}),e.jsxs(ps,{value:u,onValueChange:h,children:[e.jsx(fs,{className:"w-full sm:w-32",children:e.jsx(xs,{placeholder:"Status"})}),e.jsxs(gs,{children:[e.jsx(Xe,{value:"all",children:"All Statuses"}),Ec.map(v=>e.jsx(Xe,{value:v.key,children:v.label},v.key))]})]})]})]}),D?e.jsx(rd,{}):te.length===0?e.jsx(Ct,{children:e.jsxs(St,{className:"py-12 text-center",children:[e.jsx(Ht,{className:"h-10 w-10 mx-auto text-muted-foreground
34/40 mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No calls logged yet"}),e.jsx("p",{className:"text-caption mt-1",children:"Start logging calls to track your sales activity and measure conversion."}),e.jsxs(E,{size:"sm",className:"mt-4",onClick:()=>X(!0),children:[e.jsx(Ht,{className:"h-4 w-4 mr-1"})," Log Your First Call"]})]})}):e.jsxs(e.Fragment,{children:[e.jsx(ld,{className:"md:hidden",children:ae.map(v=>{const ne=wn(v.status);return e.jsx(od,{title:K(v.contact_id)||v.phone_number||"Unknown caller",status:e.jsx(ie,{variant:"outline",className:"text-[10px]",children:ne.label}),value:e.jsx("span",{className:"text-xs tabular-nums",children:ds(v.duration_seconds)}),detail:e.jsxs("span",{children:[v.direction==="inbound"?"Incoming":"Outgoing"," ·"," ",ye(new Date(v.created_at),"d MMM, HH:mm"),v.call_purpose?` · ${_n(v.call_purpose)}`:""]}),leading:v.direction==="inbound"?e.jsx(fa,{className:"h-4 w-4 text-muted-foreground","aria-hidden":"true"}):e.jsx(xa,{className:"h-4 w-4 text-muted-foreground","aria-hidden":"true"}),onOpen:()=>{I(v),W(!0)}},v.id)})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(Xc,{columns:fe,data:ae,onRowClick:v=>{I(v),W(!0)}})}),e.jsx(ad,{pagination:Ce})]}),Se.attentionBottom,Se.insightsBottom,U&&e.jsx(Vh,{call:U,open:R,onOpenChange:v=>{v||(W(!1),I(null))},contactName:K(U.contact_id)}),e.jsx(ed,{open:J,onOpenChange:X,contactName:"",contactPhone:"",contactId:null,onCallLogged:G}),e.jsx(td,{open:Y,onOpenChange:w,contactName:L.contactName,onLinkDeal:()=>{w(!1),n("/pipeline")},onCreateDeal:()=>{w(!1),n("/pipeline?action=create"+(L.contactId?`&contact=${L.contactId}`:""))},onSkip:()=>w(!1)}),e.jsx(At,{open:c,onOpenChange:f,children:e.jsxs(Et,{children:[e.jsx(Rt,{children:e.jsx(Lt,{children:"Pending Share Requests"})}),e.jsx("div",{className:"space-y-3 mt-4",children:_.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No pending requests"}):_.map(v=>e.jsx(Ct,{children:e.jsxs(St,{className:"p-3 flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-medium",children:"Call Recording Share"}),e.jsx("p",{className:"text-caption",children:v.message||"Requesting access to share"})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(E,{size:"sm",variant:"outline",onClick:()=>O.mutate(v.id),children:"Deny"}),e.jsx(E,{size:"sm",onClick:()=>M.mutate({requestId:v.id,orgId:s}),children:"Approve"})]})]})},v.id))})]})}),e.jsx(Hs,{open:x,onOpenChange:C,children:e.jsxs(Vs,{size:"md",className:"",children:[e.jsxs(zs,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ks,{children:"Connect Your Phone"}),e.jsx(ie,{variant:"warning",children:"Coming Soon"})]}),e.jsx(ja,{children:"Choose a telephony provider to enable direct in-app calling, auto-logging, and call recording."})]}),e.jsx("div",{className:"space-y-3 mt-2",children:[{name:"Africa's Talking",desc:"Voice API for African markets - auto-log calls, SMS follow-ups, and local numbers.",icon:Ht},{name:"Twilio",desc:"Global voice & SMS - click-to-call, call recording, and real-time transcription.",icon:Ja},{name:"Custom SIP",desc:"Bring your own SIP trunk - connect any PBX or VoIP provider.",icon:In}].map(v=>e.jsx(Ct,{className:"relative opacity-60 pointer-events-none border-dashed",children:e.jsxs(St,{className:"p-3 flex items-start gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center shrink-0 mt-0.5",children:e.jsx(v.icon,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:v.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:v.desc})]})]})},v.name))}),e.jsx("p",{className:"text-xs text-muted-foreground text-center mt-2",children:"We're working on these integrations. You'll be notified when they're available."}),e.jsx(Mn,{children:e.jsx(E,{variant:"outline",className:"w-full",onClick:()=>C(!1),children:"Close"})})]})})]})},Vt=t=>t==null?null:Number(t);function Kh(t={}){const s=Fe(),n=t.period??_i("30d"),a=t.targetMinutes??ei;return ce({queryKey:["inbox-response-stats",s,n.from,n.to,a],enabled:(t.enabled??!0)&&!!s,staleTime:6e4,queryFn:async()=>{const{data:r,error:l}=await H.rpc("inbox_response_stats",{_org_id:s,_from:n.from,_to:n.to,_target_minutes:a});if(l)throw l;const i=(r??[])[0];return i?{repliesSent:Number(i.replies_sent??0),customersRepliedTo:Number(i.customers_replied_to??0),answered:Number(i.answered??0),awaiting:Number(i.awaiting??0),avgSeconds:Vt(i.avg_seconds),medianSeconds:Vt(i.median_seconds),sameDayRate:Vt(i.same_day_rate),replyRate:Vt(i.reply_rate),waitingNow:Number(i.waiting_now??0),overdueNow:Number(i.overdue_now??0)}:null}})}function Wh(t={}){const s=Fe(),n=t.period??_i("7d"),a=t.targetMinutes??ei,r=ce({queryKey:["inbox-team-response",s,n.from,n.to,a],enabled:(t.enabled??!0)&&!!s,staleTime:6e4,queryFn:async()=>{const{data:l,error:i}=await H.rpc("inbox_team_response",{_org_id:s,_from:n.from,_to:n.to,_target_minutes:a});if(i)throw i;return(l??[]).map(o=>
34({userId:String(o.user_id),authId:o.auth_id??null,name:o.full_name||"Unnamed",avatarUrl:o.avatar_url??null,waiting:Number(o.waiting??0),repliedToday:Number(o.replied_today??0),repliesSent:Number(o.replies_sent??0),customersRepliedTo:Number(o.customers_replied_to??0),avgSeconds:Vt(o.avg_seconds),medianSeconds:Vt(o.median_seconds),sameDayRate:Vt(o.same_day_rate),unansweredAssigned:Number(o.unanswered_assigned??0),overdueResponses:Number(o.overdue_responses??0),lastActionAt:o.last_action_at??null}))}});return{rows:r.data??[],isLoading:r.isLoading,isError:r.isError,period:n}}function Yh({open:t,onOpenChange:s}){const{rows:n,isLoading:a,isError:r}=Wh();return e.jsx(At,{open:t,onOpenChange:s,children:e.jsxs(Et,{side:"right",className:"w-full sm:max-w-md overflow-y-auto",children:[e.jsx(Rt,{children:e.jsx(Lt,{children:"Team responses"})}),e.jsxs("div",{className:"mt-4 space-y-3",children:[a&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}),r&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Response figures aren't available right now. Conversations are unaffected."}),!a&&!r&&n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No replies recorded in this period yet."}),n.map(l=>e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("p",{className:"text-sm font-medium",children:l.name}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[l.customersRepliedTo," replied to · typically ",ti(l.avgSeconds),l.waiting>0?` · ${l.waiting} waiting`:""]})]},l.userId))]})]})})}const zi={people:"all",read:"any",state:"active"};function Ki(t){return(t.people!=="all"?1:0)+(t.read!=="any"?1:0)+(t.state!=="active"?1:0)}const vr={active:"Active conversations",archived:ue.archivedListLabel},Cr={any:"Everything",unread:"Not read yet",read:"Already read"};function ea({label:t,options:s,value:n,onSelect:a}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:t}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(r=>e.jsx("button",{type:"button",onClick:()=>a(r.value),className:B("rounded-full border px-3 py-1.5 text-xs transition-colors",n===r.value?"border-primary bg-primary/10 font-medium text-primary":"border-border text-muted-foreground hover:bg-muted"),children:r.label},r.value))})]})}function Qh({open:t,onOpenChange:s,value:n,onChange:a}){const r=Ki(n);return e.jsx(At,{open:t,onOpenChange:s,children:e.jsxs(Et,{side:"right",className:"w-full sm:max-w-sm",children:[e.jsx(Rt,{children:e.jsx(Lt,{children:"Filters"})}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsx(ea,{label:"Conversations",value:n.state,onSelect:l=>a({...n,state:l}),options:Object.keys(vr).map(l=>({value:l,label:vr[l]}))}),e.jsx(ea,{label:"Read state",value:n.read,onSelect:l=>a({...n,read:l}),options:Object.keys(Cr).map(l=>({value:l,label:Cr[l]}))}),e.jsx(ea,{label:"Who is involved",value:n.people,onSelect:l=>a({...n,people:l}),options:Object.keys(oa).map(l=>({value:l,label:oa[l]}))})]}),e.jsxs(Il,{className:"gap-2 sm:justify-between",children:[e.jsx(E,{variant:"ghost",size:"sm",disabled:r===0,onClick:()=>a(zi),children:"Clear"}),e.jsx(E,{size:"sm",onClick:()=>s(!1),children:"Show conversations"})]})]})})}function yn(t){return t.kind==="site"?"Turn off":"Disconnect"}function Gh(t){return t.kind==="site"||t.kind==="account"}function Xh({open:t,onOpenChange:s,channels:n,totalConversations:a,totalUnread:r,activeKey:l,activeTypeFilter:i,onSelect:o,onConnect:u,onRename:h,onDisconnect:c}){const[f,x]=d.useState(null),[C,j]=d.useState(""),[S,D]=d.useState(!1),[g,A]=d.useState(null),[$,b]=d.useState(!1),_=async()=>{if(g){b(!0);try{await c(g),A(null)}finally{b(!1)}}},M=U=>{x(U.key),j(U.displayName)},O=async U=>{const I=C.trim();if(!I||I===U.displayName){x(null);return}D(!0);try{await h(U,I),x(null)}finally{D(!1)}};return e.jsxs(At,{open:t,onOpenChange:s,children:[e.jsxs(Et,{side:"left",className:"w-[92vw] sm:max-w-sm p-0 flex flex-col",children:[e.jsxs(Rt,{className:"px-4 pt-4 pb-2 text-left",children:[e.jsx(Lt,{className:"text-base",children:"Channels"}),e.jsx(Yr,{className:"text-xs",children:"Everything connected to this inbox. Pick one to see only its conversations."})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-2 pb-2",children:[e.jsxs("button",{type:"button",onClick:()=>{o(null),s(!1)},className:B("w-full flex items-center gap-3 rounded-lg px-3 py-2.5 text-left transition-colors",l==="all"?"bg-primary/10":"hover:bg-muted"),children:[e.jsx(Nd,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:"All conversations"}),e.jsx(Sr,{conversations:a,unread:r})]}),xd.map(U=>{const I=n.filter(R=>R.group!==U?!1:i?R.type===i:!0);return I.length===0?null:e.jsxs("div",{className:"mt-3",children:[e.jsx("p",{className:"px-3 pb-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:gd[U]}),e.jsx("div",{className:"space-y-0.5",children:I.map(R=>{const W=l===R.key,J=f===R.key;return e.jsx("div",{className:B("group flex items-center gap-2 rounded-lg px-3 py-2 transition-colors",W?"bg-primary/10":"hover:bg-muted"),children:J?e.jsxs("div",{className:"flex-1 flex items-center gap-1.5",children:[e.jsx(kt,{autoFocus:!0,value:C,onChange:X=>j(X.target.value),maxLength:80,className:"h-8 text-sm",onKeyDown:X=>{X.key==="Enter"&&O(R),X.key==="Escape"&&x(null)}}),e.jsx(E,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:S,onClick:()=>O(R),"aria-label":"Save name",children:e.jsx(Us,{className:"h-3.5 w-3.5"})}),e.jsx(E,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>x(null),"aria-label":"Cancel rename",children:e.jsx(Dt,{className:"h-3.5 w-3.5"})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>{o(R),s(!1)},children:[e.jsx("span",{className:"block text-sm font-medium truncate",children:R.displayName}),e.jsx("span",{className:"block text-[11px] text-muted-foreground truncate",children:[R.typeLabel,R.detail,R.statusLabel].filter(
34Boolean).join(" · ")})]}),R.renamable&&e.jsx(E,{size:"icon",variant:"ghost",className:"h-7 w-7 opacity-100 md:opacity-0 md:group-hover:opacity-100 focus-visible:opacity-100 shrink-0",onClick:()=>M(R),"aria-label":`Rename ${R.displayName}`,title:"Rename",children:e.jsx(bi,{className:"h-3 w-3"})}),Gh(R)&&e.jsx(E,{size:"icon",variant:"ghost",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>A(R),"aria-label":`${yn(R)} ${R.displayName}`,title:yn(R),children:e.jsx(vd,{className:"h-3.5 w-3.5"})}),e.jsx(Sr,{conversations:R.conversationCount,unread:R.unreadCount})]})},R.key)})})]},U)})]}),e.jsxs("div",{className:"border-t p-3",children:[e.jsxs(E,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{s(!1),u()},children:[e.jsx(Jr,{className:"h-3.5 w-3.5 mr-1.5"})," Connect channel"]}),e.jsx("p",{className:"mt-1.5 text-center text-[10px] text-muted-foreground",children:"Adds a new website, number, mailbox or account."})]})]}),e.jsx(Je,{open:!!g,onOpenChange:U=>{U||A(null)},title:g?`${yn(g)} ${g.displayName}?`:"Disconnect channel?",message:(g==null?void 0:g.kind)==="site"?"The chat widget stops collecting new conversations on this website. Everything already in the Inbox is kept, and you can turn it back on any time.":"New messages stop arriving from this channel. Past conversations stay in the Inbox, and you can reconnect it any time.",confirmLabel:g?yn(g):"Disconnect",loading:$,onConfirm:()=>void _()})]})}function Sr({conversations:t,unread:s}){return e.jsxs("span",{className:"shrink-0 flex items-center gap-1.5 text-xs tabular-nums",children:[s>0&&e.jsx("span",{className:"inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-semibold text-primary-foreground",children:s}),e.jsx("span",{className:B(t>0?"text-foreground font-medium":"text-muted-foreground"),children:t})]})}function Jh(t,s,n){return ce({queryKey:["livechat-previous-chats",t,s??null,n??null],queryFn:async()=>{let a=H.from("livechat_sessions").select("*").eq("org_id",t).order("started_at",{ascending:!1}).limit(25);s?a=a.eq("contact_id",s):n&&(a=a.contains("metadata",{visitor_id:n}));const{data:r,error:l}=await a;if(l)throw l;return r||[]},enabled:!!t&&(!!s||!!n),staleTime:3e4})}function Zh(t){const s=new Date(t);return Sd(s)?"Today":Cd(s)?"Yesterday":ye(s,"d MMM")}function ep({orgId:t,currentSessionId:s,contactId:n,visitorId:a,sourceLabels:r={},onOpenSession:l}){const[i,o]=d.useState(!1),{data:u=[]}=Jh(t,n,a),h=u.filter(c=>c.id!==s);return h.length===0?null:e.jsxs("div",{className:"border-b bg-muted/20 px-3 py-1.5",children:[e.jsxs("button",{type:"button",onClick:()=>o(c=>!c),className:"flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground hover:text-foreground transition-colors",children:[i?e.jsx(bs,{className:"h-3 w-3"}):e.jsx(Xr,{className:"h-3 w-3"}),e.jsx(Wr,{className:"h-3 w-3"}),"Previous chats ",h.length]}),i&&e.jsx("div",{className:"mt-1.5 space-y-0.5",children:h.map(c=>{const f=c.livechat_site_id?r[c.livechat_site_id]:null;return e.jsxs("button",{type:"button",onClick:()=>l==null?void 0:l(c),className:B("w-full flex items-center justify-between gap-2 rounded-md px-2 py-1 text-left text-[11px]","text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"),children:[e.jsx("span",{className:"truncate",children:f||"Website"}),e.jsx("span",{className:"shrink-0",children:Zh(c.started_at)})]},c.id)})})]})}const tp=6e4,bn={title:"Live now",empty:"No one is live on your connected websites right now.",emptyHint:"New visitors will appear here while they're active."};function Wi(t){var s;return!t||t.is_enabled===!1||t.is_archived||t.deleted_at?!1:((s=t.appearance)==null?void 0:s.show_live_visitors)!==!1}function $n(t,s,n=Date.now()){return!t.last_seen_at||t.status==="gone"||n-new Date(t.last_seen_at).getTime()>tp||!t.livechat_site_id?!1:Wi(s.find(a=>a.id===t.livechat_site_id))}function sp(t){let s=0;for(let n=0;n<t.length;n++)s=s*31+t.charCodeAt(n)>>>0;return`Visitor ${1e3+s%9e3}`}function np(t,s={}){var o,u,h;const n=(o=s.contactName)==null?void 0:o.trim(),a=(h=(u=s.session)==null?void 0:u.visitor_name)==null?void 0:h.trim(),r
34=n||a||sp(t.visitor_id||t.id),l=!!(n||a),i=l?r.split(/\s+/).filter(Boolean).slice(0,2).map(c=>c[0].toUpperCase()).join(""):r.slice(-2);return{name:r,known:l,initials:i}}function Rn(t){const s=Math.max(0,Math.floor(t));if(s<60)return"<1m";const n=Math.floor(s/60);return n<60?`${n}m`:`${Math.floor(n/60)}h ${n%60}m`}function Yi(t,s=Date.now()){const n=t.total_time_seconds??0,a=t.last_seen_at?Math.max(0,(s-new Date(t.last_seen_at).getTime())/1e3):0;return n+Math.min(a,15)}function Qi(t){if(!t)return null;try{const s=new URL(t);return`${s.hostname}${s.pathname==="/"?"":s.pathname}`}catch{return t.split(/[?#]/)[0]||null}}function Gi(t){var r,l;const s=(l=(r=t.current_page_title)==null?void 0:r.split(/[|\-–·]/)[0])==null?void 0:l.trim();if(s)return s;const n=Qi(t.current_page);if(!n)return null;const a=n.split("/").filter(Boolean).slice(1).pop();return a?a.replace(/[-_]+/g," ").replace(/^\w/,i=>i.toUpperCase()):"Home"}function ap(t){if(t.detected_hostname)return t.detected_hostname;const s=Qi(t.current_page);return s?s.split("/")[0]:null}function rp(t){const s=Gi(t),n=ap(t);return s&&n?`Viewing ${s} · ${n}`:s?`Viewing ${s}`:n}function ip(t){if(!t||t.ended_at)return{waiting:!1,since:null};const s=t.metadata??{};if(!(String(t.status??"").toLowerCase()==="waiting"||s.needs_human===!0||s.awaiting_reply===!0))return{waiting:!1,since:null};const r=s.last_customer_message_at??s.handoff_requested_at??t.started_at;return{waiting:!0,since:r?new Date(r).getTime():null}}function lp(t){var l,i;const s=t.now??Date.now(),n=t.sites.filter(o=>Wi(o)).length>1,a=new Set,r=[];for(const o of t.visitors){if(a.has(o.id)||(a.add(o.id),!$n(o,t.sites,s))||t.siteFilter&&o.livechat_site_id!==t.siteFilter)continue;const u=t.match(o,t.sessions),h=o.contact_id?(l=t.contactName)==null?void 0:l.call(t,o.contact_id):null,c=ip(u);r.push({visitor:o,session:u,identity:np(o,{contactName:h,session:u}),status:c.waiting?"needs_reply":"live",waitingSince:c.since,activeSeconds:Yi(o,s),siteName:n?((i=t.sites.find(f=>f.id===o.livechat_site_id))==null?void 0:i.name)??null:null})}return r.sort((o,u)=>o.status!==u.status?o.status==="needs_reply"?-1:1:o.status==="needs_reply"?(o.waitingSince??s)-(u.waitingSince??s):u.activeSeconds-o.activeSeconds)}function kr(t,s=Date.now()){return t.status==="needs_reply"&&t.waitingSince?`Waiting ${Rn((s-t.waitingSince)/1e3)}`:`Live · ${Rn(t.activeSeconds)}`}function op(t,s,n=Date.now()){if(!t)return null;const a=Gi(t);return $n(t,s,n)?["Live now",a,Rn(Yi(t,n))].filter(Boolean).join(" · "):t.last_seen_at?[`Left ${Rn((n-new Date(t.last_seen_at).getTime())/1e3)} ago`,a].filter(Boolean).join(" · "):null}const cp=[{key:"live",label:"Live now"},{key:"waiting",label:"Waiting"},{key:"unread",label:"Unread"},{key:"all",label:"All"}];function dp(t){return t==="live"||t==="waiting"||t==="unread"?t:"all"}function up(t){const s=t.now??Date.now(),n=new Set;for(const a of t.visitors){if(!$n(a,t.sites,s))continue;const r=t.match(a,t.sessions);r&&n.add(r.id)}return n}function vn(t,s,n){return s==="all"?!0:s==="unread"?(t.unread_count??0)>0:s==="waiting"?String(t._livechat_status??"").toLowerCase()==="waiting":!!t._livechat_session_id&&n.has(t._livechat_session_id)}function mp(t,s){const n={live:0,waiting:0,unread:0,all:t.length};for(const a of t)vn(a,"live",s)&&n.live++,vn(a,"waiting",s)&&n.waiting++,vn(a,"unread",s)&&n.unread++;return n}function hp({sessions:t,sites:s,siteFilter:n,contactName:a,onOpen:r}){zc();const{data:l=[],isLoading:i,isError:o}=ha({status:"all"}),[u,h]=d.useState(()=>Date.now());d.useEffect(()=>{const f=window.setInterval(()=>h(Date.now()),3e4);return()=>window.clearInterval(f)},[]);const c=d.useMemo(()=>lp({visitors:l,sessions:t,sites:s,siteFilter:n,contactName:a,now:u,match:(f,x)=>da(f,x).session}),[l,t,s,n,a,u]);return e.jsxs("section",{"aria-label":bn.title,className:"mb-2 rounded-lg border bg-card px-3 py-2","data-testid":"live-now-strip",children:[e.jsxs("h3",{className:"mb-1.5 flex items-center gap-1.5 text-xs font-semibold",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-success","aria-hidden":!0}),bn.title,c.length?e.jsxs("span",{className:"font-normal text-muted-foreground",children:["· ",c.length]}):null]}),i?e.jsx("div",{className:"flex gap-3","aria-label":"Loading live visitors",children:[0,1,2,3].map(f=>e.jsx(ra,{className:"h-11 w-11 rounded-full"},f))}):o?e.jsx("p",{className:"py-1 text-xs text-muted-foreground",role:"status",children:"Live presence reconnecting..."}):c.length===0?e.jsxs("div",{className:"py-1",children:[e.jsx("p",{className:"text-xs",children:bn.empty}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:bn.emptyHint})]}):e.jsx("ul",{className:"-mx-1 flex snap-x gap-1 overflow-x-auto pb-1",children:c.map(f=>{const x=rp(f.visitor);return e.jsx("li",{className:"snap-start",children:e.jsxs(Ca,{children:[e.jsx(Sa,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>r(f),className:"flex w-[84px] flex-col items-center gap-1 rounded-md px-1 py-1 text-center focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":`${f.identity.name}, ${kr(f,u)}${x?`, ${x}`:""}`,children:[e.jsxs("span",{className:"relative",children:[e.jsx("span",{className:B("flex h-11 w-11 items-center justify-center rounded-full text-sm font-semibold",f.identity.known?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground",f.status==="needs_reply"&&"ring-2 ring-warning ring-offset-1 ring-offset-background"),children:f.identity.initials}),e.jsx("span",{className:"absolute bottom-0 right-0 h-3 w-3 rounded-full border-2 border-card bg-success","aria-hidden":!0})]}),e.jsx("span",{className:"w-full truncate text-[11px] font-medium",children:f.identity.name}),e.jsx("span",{className:B("w-full truncate text-[10px]",f.status==="needs_reply"?"text-warning":"text-muted-foreground"),children:kr(f,u)}),f.siteName?e.jsx("span",{className:"w-full truncate text-[10px] text-muted-foreground",children:f.siteName}):null]})}),x?e.jsx(ka,{children:x}):null]})},f.visitor.id)})})]})}function pp({sessionId:t,visitorId:s,orgId:n,sites:a}){const{data:r}
34=xi(t,s??null,n??null),[l,i]=d.useState(()=>Date.now());d.useEffect(()=>{const c=window.setInterval(()=>i(Date.now()),3e4);return()=>window.clearInterval(c)},[]);const o=r??null,u=op(o,a,l);if(!u)return null;const h=!!o&&$n(o,a,l);return e.jsxs("p",{className:"flex items-center gap-1.5 border-b px-4 py-1 text-[11px] text-muted-foreground","data-testid":"livechat-presence-line",children:[e.jsx("span",{className:B("h-1.5 w-1.5 rounded-full",h?"bg-success":"bg-muted-foreground/40"),"aria-hidden":!0}),u]})}const fp=new Set(["whatsapp","instagram","sms","email","voice"]),Ny=()=>{var Es,Rs;const t=zt(),s=Fe(),[n,a]=d.useState(!1),r=$l(),{data:l=[]}=Vr();ql();const{data:i=[]}=Fl(),o=Na(),[u,h]=d.useState(()=>{var p;return typeof window<"u"&&!!((p=window.matchMedia)!=null&&p.call(window,"(max-width: 1023px)").matches)});d.useEffect(()=>{var q,F;const p=typeof window<"u"?(q=window.matchMedia)==null?void 0:q.call(window,"(max-width: 1023px)"):void 0;if(!p)return;const k=()=>h(p.matches);return(F=p.addEventListener)==null||F.call(p,"change",k),()=>{var le;return(le=p.removeEventListener)==null?void 0:le.call(p,"change",k)}},[]);const c=o||u,{ref:f,height:x}=Pd({reserveBottom:c?80:24}),[C,j]=d.useState(""),[S,D]=d.useState("all"),[g,A]=d.useState(!1),[$,b]=d.useState(zi),{archivedKeys:_}=Ul(s),[M]=io(),O=Oe(),U=oo(),I=M.get("channel"),R=M.get("source"),W=I==="livechat",J=W?R:null,X=W?"all":S==="unread"?"unread":$.read==="any"?"all":$.read,Y=W?"all":S==="mine"?"mine":$.people,w=d.useMemo(()=>l.find(p=>p.id===R)||null,[l,R]),L=vi({channel:cu(w==null?void 0:w.provider),accountId:(w==null?void 0:w.id)??null,auto:!1});d.useEffect(()=>{if(!I)return;if(I.startsWith("livechat:")){O(`/inbox?channel=livechat&source=${I.slice(9)}`,{replace:!0});return}const p=l.find(k=>k.id===I);p&&O(`/inbox?channel=${yd(p.provider)}&source=${p.id}`,{replace:!0})},[I,l,O]);const z=I==="calls",N=M.get("view");d.useEffect(()=>{W&&N==="visitors"&&U({section:"livechat",tab:"visitors",replace:!0})},[W,N,U]);const K=Bl(s),{data:te,messages:ae,isLoading:Ce}=K,_e=lo("inbox");Hl("inbox",K,te==null?void 0:te.length);const{data:G=[]}=Vl(s),{data:Z=[]}=jo(s),{data:je=[]}=pd(s),fe=d.useMemo(()=>bd({connectedAccounts:l,liveChatSites:je,providerMeta:i}),[l,je,i]),Se=d.useMemo(()=>wd(fe),[fe]),v=I?fe.find(p=>p.key===I):null,{data:ne=0}=No(s),{data:Pa=0}=vo(s);zl(s),Kl(s);const{data:ct=[]}=Aa(),{byConversation:Ws}=Id(s),{data:dt=[]}=Rc(),{data:ke=[]}=Wl(s),{data:ut=[]}=ws(s),[Q,xe]=d.useState(null),Mt=c&&!!Q,Ne=!!Q,[qn,Ys]=d.useState(!1),[mt,Qs]=d.useState(),[Gs,Kt]=d.useState(!1),[He,js]=d.useState(!1),[Xs,Wt]=d.useState(!1),[Js,Yt]=d.useState(!1),{hasPermission:Ns}=na("performance.view_team"),ht=fd(),Qt=Yl(),vs=Ql(),[Zs,Pt]=d.useState(!1),[en,Gt]=d.useState(!1),[Fn,tn]=d.useState(!1),[Ze,Ve]=d.useState(null),[pt,sn]=d.useState(!1),[Cs,Xt]=d.useState(!1),[Me,ze]=d.useState(!1),[ft,Te]=d.useState(new Set),It=Gl(),Jt=Xl(),Ke=d.useCallback((p,k)=>{const q=Kn(p),F=ct.find(le=>le.id===q.contact_id);xe({...q,contact_name:(F==null?void 0:F.full_name)||q.contact_name,contact_company:(F==null?void 0:F.company)||null,contact_phone:(F==null?void 0:F.phone)||null,_match_rule:k})},[ct]),Zt=Jl().canOpen("conversations"),[Ss,an]=d.useState(null),es=d.useCallback(p=>{var k;return((k=ct.find(q=>q.id===p))==null?void 0:k.full_name)??null},[ct]),re=d.useCallback(p=>{if(p.session){Ke(p.session,"visitor_id");return}an(p.visitor)},[Ke]),xt=M.get("session"),Pe=M.get("visitor"),{data:rn=[]}=ha(Pe?{status:"all"}:void 0),$t=d.useRef(null);d.useEffect(()=>{const p=xt||Pe;if(!p||$t.current===p)return;if(xt){const le=Z.find(ee=>ee.id===xt);if(!le)return;$t.current=p,Ke(le,"visitor_id");return}const k=rn.find(le=>le.id===Pe||le.visitor_id===Pe);if(!k)return;$t.current=p;const{session:q,rule:F}=da(k,Z);if(!q){P.info("No active chat yet - they'll appear here the moment they message.");return}Ke(q,F)},[xt,Pe,Z,rn,Ke]);const Ae=d.useCallback(p=>{ze(!0),Te(new Set([p]))},[]),ln=d.useCallback(p=>{Te(k=>{const q=new Set(k);return q.has(p)?q.delete(p):q.add(p),q.size===0&&ze(!1),q})},[]),qt=d.useCallback(()=>{ze(!1),Te(new Set)},[]),ts=d.useCallback(()=>Array.from(ft).map(p=>{const[k,q]=p.split("-");return{contactId:k,channel:q}}),[ft]),Un=d.useCallback(async()=>{const p=ts();await It.mutateAsync(p),qt()},[ts,It,qt]),Ft=d.useCallback(async()=>{const p=ts();await Jt.mutateAsync(p),qt()},[ts,Jt,qt]),Ue=M.get("contact_id"),Bn=p=>p===null?null:p==="livechat"||p!=null&&p.startsWith("livechat:")||p==="support"||p==="email"?!0:ke.some(k=>k.channel===p&&k.status==="active"),{data:gt=[]}=Co(s,W&&He);So(s);const ss=ke.some(p=>["whatsapp","sms","instagram","email"].includes(p.channel)&&p.status==="active"),{data:et=[]}=hd(),yt=et.length>0,bt=p=>{Qs(p&&fp.has(p)?p:void 0),Ys(!0)},Ut=G.map(Zl),wt=(J?Z.filter(p=>p.livechat_site_id===J):Z).map(p=>{const k=Kn(p);if(p.contact_id){const q=ae.filter(F=>F.contact_id===p.contact_id&&F.channel==="livechat"&&F.direction==="inbound"&&!F.read_at).length;k.unread_count=q}return k}),on=(J?gt.filter(p=>p.livechat_site_id===J):gt).map(Kn),Bt=(p,k,q)=>{const F=new Map,le=new Map;for(const ee of k){if(!ee.contact_id)continue;const qe=le.get(ee.contact_id);(!qe||new Date(ee.last_message_at)>new Date(qe))&&le.set(ee.contact_id,ee.last_message_at)}for(const ee of p){if(!ee.contact_id){F.set(`anon-${ee._livechat_session_id}`,ee);continue}const qe=k.find(Xi=>Xi.contact_id===ee.contact_id),Ia={...ee,_ducebot_session_id:qe?qe._ducebot_session_id:void 0},$a=F.get(ee.contact_id);(!$a||new Date(Ia.last_message_at)>=new Date($a.last_message_at))&&F.set(ee.contact_id,Ia)}for(const ee of k){if(!ee.contact_id){F.set(`bot-${ee._ducebot_session_id}`,ee);continue}F.has(ee.contact_id)||F.set(ee.contact_id,ee)}for(const ee of q){if(ee.channel!=="livechat"&&ee.channel!=="ducebot"||!ee.contact_id)continue;const qe=F.get(ee.contact_id);qe&&(new Date(ee.last_message_at)>new Date(qe.last_message_at)&&(qe.last_message=ee.last_message,qe.last_message_at=ee.last_message_at),ee.unread_count>qe.unread_count&&(qe.unread_count=ee.unread_count))}return Array.from(F.values())};let tt;if(W)tt=He?[...on]:Bt(wt,Ut,te);else if(I==="support")tt=te.filter(p=>p.channel==="support");else if(I){const p=new Set(((v==null?void 0:v.sources)??[]).map(k=>k.id));tt=te.filter(k=>R?k.connected_account_id===R:k.connected_account_id?p.has(k.connected_account_id):k.channel===I)}else{const p=Bt(wt,Ut,te);tt=[...te.filter(q=>q.channel!=="livechat"&&q.channel!=="ducebot"),...p]}const cn=tt.map(p=>{const k=p.conversation_id?Ws.get(p.conversation_id):void 0,q=qd(k,p.contact_id),F=ct.find(le=>le.id===q.contactId);return{...p,contact_id:q.contactId,contact_name:Fd(k)||(F==null?void 0:F.full_name)||p.contact_name,contact_company:(q.needsMatch?null:k==null?void 0:k.company)||(F==null?void 0:F.company)||p.contact_company,contact_phone:(k==null?void 0:k.primary_phone)||(F==null?void 0:F.phone)||p.contact_phone,_identity:q}});cn.sort((p,k)=>new Date(k.last_message_at).getTime()-new Date(p.last_message_at).getTime());const{active:ks,archived:dn}=eo(cn,_),Ts=$.state==="archived"?dn:ks,un=dp(W?M.get("lc"):null),{data:Be=[]}=ha(W?{status:"all"}:void 0),Ie=d.useMemo(()=>W?up({visitors:Be,sessions:Z,sites:je,match:(p,k)=>da(p,k).session}):new Set,[W,Be,Z,je]),mn=W?mp(Ts,Ie):null,Ee=W&&!He?Ts.filter(p=>vn(p,un,Ie)):Ts,ns=p=>{const k=new URLSearchParams(M);p==="all"?k.delete("lc"):k.set("lc",p),O(`/inbox?${k.toString()}`,{replace:!0})},hn=M.get("compose")==="1";d.useEffect(()=>{if(!Ue||Q||Ce)return;const p=Ee.find(k=>k.contact_id===Ue&&(!I||I==="all"||k.channel===I));if(p){xe(p);return}hn&&Pt(!0)},[Ue,I,Ee,hn,Q,Ce]),d.useEffect(()=>{if(!Q)return;Ee.some(k=>Ya(k,Q))||(xe(null),Te(new Set))},[I,R]);const $e=d.useMemo(()=>{const p={},k=(F,le)=>{const ee=p[F]||(p[F]={conversations:0,unread:0});ee.conversations+=1,le&&(ee.unread+=1)};for(const F of te){if(F.channel==="livechat"||F.channel==="ducebot")continue;const le=F.unread_count>0;F.connected_account_id&&k(F.connected_account_id,le),k(F.channel,le)}const q=new Set(ae.filter(F=>F.channel==="livechat"&&F.direction==="inbound"&&!F.read_at).map(F=>F.contact_id));for(const F of Z){const le=!!F.contact_id&&q.has(F.contact_id),ee=F.livechat_site_id;ee&&k(ee,le),k("livechat",le)}return p},[te,ae,Z]),st=d.useMemo(()=>_d(fe,$e),[fe,$e]),be=d.useMemo(()=>jd(st,I,R),[st,I,R]),As=d.useMemo(()=>te.filter(p=>p.channel!=="livechat"&&p.channel!=="ducebot").length+Z.length,[te,Z]),as=d.useMemo(()=>Object.entries($e).filter(([p])=>st.some(k=>k.sourceId===p)).reduce((p,[,k])=>p+k.unread,0),[$e,st]),Vn=d.useCallback(async(p,k)=>{try{p.kind==="site"&&p.sourceId?await ht.mutateAsync({id:p.sourceId,name:k}):p.kind==="account"&&p.sourceId&&await Qt.mutateAsync({id:p.sourceId,display_label:k}),P.success(`Renamed to "${k}"`)}catch(q){P.error("Could not rename this channel",{cause:q})}},[ht,Qt]),zn=d.useCallback(async p=>{if(p.sourceId)try{p.kind==="site"?(await ht.mutateAsync({id:p.sourceId,is_enabled:!1}),P.success(`${p.displayName} turned off`,{description:"Existing conversations are kept."})):await vs.mutateAsync(p.sourceId),(be==null?void 0:be.key)===p.key&&O("/inbox",{replace:!0})}catch(k){P.error("Could not disconnect this channel",{cause:k})}},[ht,vs,be,O]),_t=Ee.length,nt=Ee.filter(p=>p.unread_count>0).length;ae.length;const at=G.filter(p=>p.is_escalated).length,{data:ge,isError:m}=Kh(),y=ti((ge==null?void 0:ge.avgSeconds)??null),T=(ge==null?void 0:ge.answered)??0,V=Math.round((ge==null?void 0:ge.replyRate)??0),se=d.useMemo(()=>kd({openConversations:_t,unread:nt,waitingOverDay:(ge==null?void 0:ge.overdueNow)??0,responseDataUnavailable:m,repliedToday:T,channelsConnected:ke.f
34ilter(p=>p.status==="active").length,avgResponseTime:y,firstResponseRate:V,liveVisitors:ne,botHandedOver:at}),[ge,m,_t,nt,T,ke,y,V,ne,at]),de=d.useMemo(()=>{const p=new Set(l.filter(q=>!["ready","paused"].includes(tr(q))).map(q=>q.id)),k=Ee.map(q=>({convo:q,waiting:_a({lastDirection:q.last_direction??(q.unread_count>0?"inbound":null),lastMessageAt:q.last_message_at,channelHealthy:!(q.connected_account_id&&p.has(q.connected_account_id))})})).filter(q=>q.waiting.side==="business"&&q.waiting.overdue).sort((q,F)=>F.waiting.waitedMs-q.waiting.waitedMs).slice(0,4).map(({convo:q,waiting:F})=>({id:`${q.contact_id}-${q.channel}`,title:q.contact_name||q.provider_name||"Unknown contact",reason:`${F.label} - reply now`,meta:q.channel?q.channel.replace(/_/g," "):void 0,actionLabel:"Open chat",onAction:()=>xe(q),onOpen:()=>xe(q),tone:"urgent"}));for(const q of l){const F=tr(q);F==="ready"||F==="paused"||k.unshift({id:`channel-${q.id}`,title:`${q.display_label||q.display_name||q.provider} is not receiving messages yet`,reason:q.state_reason||`${sr[F].label} - ${sr[F].reason}`,actionLabel:pt?"Checking...":"Check again",onAction:async()=>{if(!pt){sn(!0);try{await H.functions.invoke("unipile-accounts-sync",{body:{}}),await H.functions.invoke("unipile-sync-messages",{body:{connected_account_id:q.id}}),await t.invalidateQueries({queryKey:["connected-accounts"]}),await t.invalidateQueries({queryKey:["inbox-messages"]}),P.success("Connection checked")}catch(le){P.error("Could not check the connection",{cause:le})}finally{sn(!1)}}},tone:"warning"})}return at>0&&k.push({id:"bot-escalated",title:`${at} chat${at===1?"":"s"} passed over by the chatbot`,reason:"The assistant could not finish these - take them over",actionLabel:"See chats",onAction:()=>O("/inbox?channel=livechat"),tone:"warning"}),k},[Ee,at,O,l,pt,t]),me=yi("inbox",{attention:!z&&!Ce&&(!o||!Q)?{items:de,summary:`${de.length} ${de.length===1?"conversation needs":"conversations need"} a reply`}:void 0,insights:z?void 0:{summary:"How your replies are going",...se}}),Re=Q==null?void 0:Q._ducebot_session_id,Le=Re?G.find(p=>p.session_id===Re):null,he=Q==null?void 0:Q._livechat_session_id,oe=he?Z.find(p=>p.id===he):null,We=(Q==null?void 0:Q.channel)==="support"&&(Q!=null&&Q.contact_id)?dt.find(p=>p.contact_id===Q.contact_id):null,Ye=d.useMemo(()=>Ed({capability:"inbox",steps:Rd({hasOperationalChannel:ss||yt})}),[ss,yt]),jt=md("inbox"),Nt=d.useMemo(()=>ud({capability:"inbox",readiness:Ye,canConfigure:jt.available}),[Ye,jt.available]),rs=Dd("inbox",Ye,"Connect a channel"),vt=d.useMemo(()=>{const p=[{label:"Channels",icon:e.jsx(Td,{className:"h-4 w-4"}),onClick:()=>Wt(!0)},{label:"Send a broadcast",icon:e.jsx(On,{className:"h-4 w-4"}),onClick:()=>Gt(!0)}];return Ns&&p.push({label:"Team responses",icon:e.jsx(Qr,{className:"h-4 w-4"}),onClick:()=>Yt(!0)}),rs&&jt.available&&p.push({label:rs,icon:e.jsx(Qa,{className:"h-4 w-4"}),onClick:()=>a(!0)}),w&&p.push({label:L.syncing?"Syncing...":"Sync messages",icon:e.jsx(aa,{className:B("h-4 w-4",L.syncing&&"animate-spin")}),onClick:()=>void L.sync("manual")}),(w==null?void 0:w.connection_status)==="reconnect_required"&&p.push({label:Ze===w.id?"Reconnecting...":"Reconnect this channel",icon:e.jsx(aa,{className:B("h-4 w-4",Ze===w.id&&"animate-spin")}),onClick:async()=>{if(w){Ve(w.id);try{const k=await r.mutateAsync({provider:w.provider,mode:"reconnect",account_id:w.id});window.open(k,"unipile-reconnect","width=560,height=720")||P.error("Popup blocked. Allow popups and try again.")}catch(k){P.error("Reconnect failed",{cause:k})}finally{Ve(null)}}}}),W&&p.push({label:He?"Back to active chats":"Past chats",icon:e.jsx(Pn,{className:"h-4 w-4"}),onClick:()=>js(!He)},{label:"Live Chat settings",icon:e.jsx(to,{className:"h-4 w-4"}),onClick:()=>U({section:"livechat"})},{label:"DuceBot settings",icon:e.jsx(kn,{className:"h-4 w-4"}),onClick:()=>U({base:"/settings/ducebot"})}),p},[Ns,rs,jt.available,w,L,Ze,W,He,r,U]);return e.jsxs(uo,{density:"workbench",className:B(Ne&&"!gap-0",Mt&&"max-lg:!p-0"),children:[!Mt&&e.jsx(ni,{module:"inbox",title:"Inbox",description:wi("inbox"),primaryLabel:Nt.visible?Nt.label:void 0,primaryIcon:Nt.kind==="setup"?e.jsx(Qa,{className:"h-4 w-4"}):e.jsx(ar,{className:"h-4 w-4"}),onPrimary:Nt.kind==="setup"?()=>a(!0):()=>Pt(!0),secondaryActions:vt}),!Ne&&Nt.needsSomeoneElse&&e.jsxs("div",{className:"rounded-md border border-border bg-muted/40 p-4 text-sm text-muted-foreground",children:[e.jsx("p",{className:"font-medium text-foreground",children:"Messaging is not available yet."}),e.jsx("p",{children:"Ask an administrator to connect a channel before messages can be sent from here."})]}),e.jsx(dd,{open:n,onOpenChange:a}),!Mt&&e.jsx(ho,{label:"Channels",value:I??"all",onChange:p=>{if(p==="all"){O("/inbox",{replace:!0});return}O({pathname:"/inbox",search:`?channel=${p}`},{replace:!0})},tabs:[{value:"all",label:"All",count:As},...fe.map(p=>{var k;return{value:p.key,label:p.label,count:(k=$e[p.key])==null?void 0:k.conversations}})]}),!Mt&&!z&&!W&&e.jsx(mo,{views:e.jsx(so,{label:"Conversation views",value:S,onChange:p=>D(p),tabs:[{value:"all",label:"All",count:As},{value:"unread",label:"Unread",count:nt},{value:"mine",label:"Mine"}]}),search:C,onSearchChange:j,searchPlaceholder:"Search conversations...",onOpenFilters:()=>A(!0),activeFilterCount:Ki($),metrics:[{label:"conversations",value:_t},{label:"unread",value:nt,tone:nt>0?"attention":"default"},{label:"replied",value:`${V}%`}]}),e.jsx(Yh,{open:Js,onOpenChange:Yt}),e.jsx(Qh,{open:g,onOpenChange:A,value:$,onChange:b}),e.jsx(Xh,{open:Xs,onOpenChange:Wt,channels:st,totalConversations:As,totalUnread:as,activeKey:(be==null?void 0:be.key)??I??"all",activeTypeFilter:I??null,onSelect:p=>{if(!p){O("/inbox",{replace:!0});return}const k=new URLSearchParams;k.set("channel",p.type),p.sourceId&&k.set("source",p.sourceId),O({pathname:"/inbox",search:k.toString()},{replace:!0})},onConnect:()=>a(!0),onRename:Vn,onDisconnect:zn}),!Ne&&!ss&&!yt&&!Gs&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-lg border border-dashed border-primary/30 bg-primary/5 px-4 py-2.5",children:[e.jsx(_s,{className:"h-4 w-4 text-primary shrink-0"}),e.jsxs("p",{className:"text-xs flex-1",children:[e.jsx("span",{className:"font-medium",children:"Connect email"}),e.jsx("span",{className:"text-muted-foreground ml-1",children:"so your messages show up here"})]}),e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsxs(E,{size:"sm",className:"h-7 text-xs px-2.5",onClick:()=>bt("email"),children:[e.jsx(ot,{className:"h-3 w-3 mr-1"})," Connect Email"]})}),e.jsx("button",{onClick:()=>Kt(!0),className:"text-muted-foreground hover:text-foreground",children:e.jsx(Dt,{className:"h-3.5 w-3.5"})})]}),!Ne&&me.attentionTop,!Ne&&me.insightsTop,W&&Zt&&!Ne&&e.jsx(hp,{sessions:Z,sites:je,siteFilter:J,contactName:es,onOpen:re}),W&&Zt&&!He&&!Ne&&mn&&e.jsx("div",{role:"tablist","aria-label":"Live Chat conversations",className:"-mx-1 mb-2 flex gap-1.5 overflow-x-auto px-1 pb-0.5",children:cp.map(p=>{const k=un===p.key;return e.jsxs("button",{type:"button",role:"tab","aria-selected":k,onClick:()=>
34ns(p.key),className:B("inline-flex h-9 shrink-0 items-center gap-1.5 rounded-full border px-3 text-xs font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",k?"border-primary bg-primary text-primary-foreground":"bg-card text-foreground hover:bg-muted"),children:[p.key==="live"&&e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-success","aria-hidden":!0}),p.label,e.jsx("span",{className:B("tabular-nums",k?"text-primary-foreground/80":"text-muted-foreground"),children:mn[p.key]})]},p.key)})}),e.jsx(tc,{visitor:Ss,open:!!Ss,onOpenChange:p=>{p||an(null)}}),e.jsx("div",{ref:f,style:x?{height:`${x}px`}:void 0,className:B("rounded-lg border bg-card overflow-hidden max-lg:rounded-none max-lg:border-x-0",Ne&&"min-h-[min(34rem,calc(100dvh-5rem))]",z?"p-3":x?void 0:"h-[calc(100dvh-9rem)] md:h-[calc(100vh-5rem)]"),children:z?e.jsx(zh,{embedded:!0}):e.jsxs("div",{className:"flex h-full min-h-0 relative",children:[(!c||!Q)&&e.jsx("div",{className:B("h-full min-h-0",c?"w-full":"w-80 shrink-0 border-r"),children:Ce?e.jsx("div",{className:"h-full px-3",children:e.jsx(no,{label:"Loading conversations...",rows:5,productiveContext:_e})}):e.jsx(Kd,{conversations:Ee,conversationState:$.state,selected:Q,onSelect:xe,search:C,statusFilter:X,peopleFilter:Y,parentChannel:I,sourceLabels:Se,activeChannelName:(be==null?void 0:be.displayName)??null,activeChannelConnected:be?be.connected:((v==null?void 0:v.sources.length)??0)>0,onOpenWizard:p=>bt(p),selectionMode:Me,selectedIds:ft,onToggleSelect:ln,onEnterSelectionMode:Ae,onConversationArchived:p=>{Ya(Q,p)&&xe(null)}})}),(!c||Q)&&e.jsx(e.Fragment,{children:(I==="whatsapp"||I==="instagram")&&(!Bn(I)||Ze===I)&&!Q?e.jsx("div",{className:"flex-1 h-full flex items-center justify-center p-8",children:e.jsxs("div",{className:"max-w-sm text-center space-y-3",children:[e.jsx("div",{className:"mx-auto h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(ao,{className:"h-6 w-6 text-primary"})}),e.jsxs("h3",{className:"text-base font-semibold capitalize",children:["Connect ",I]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Sign in with ",I," through our hosted-auth flow. Messages will start flowing into this inbox."]}),e.jsxs(E,{size:"sm",onClick:()=>a(!0),children:["Connect ",I]})]})}):e.jsx(e.Fragment,{children:We?e.jsxs("div",{className:"flex-1 flex min-h-0 flex-col h-full",children:[o&&e.jsxs("button",{onClick:()=>xe(null),className:"flex items-center gap-1 px-3 py-2 text-sm text-muted-foreground hover:text-foreground border-b",children:[e.jsx(sa,{className:"h-4 w-4"})," Back"]}),e.jsx(Jm,{ticket:We,orgId:s})]}):oe?e.jsxs("div",{className:"flex-1 flex flex-col h-full min-h-0 min-w-0 overflow-hidden",children:[e.jsx(sh,{session:oe,matchRule:Q==null?void 0:Q._match_rule,onBack:c?()=>xe(null):void 0,onToggleContactPanel:Q!=null&&Q.contact_id?()=>Xt(!Cs):void 0,contactPanelOpen:Cs,sourceLabel:oe.livechat_site_id?Se[oe.livechat_site_id]??null:null}),e.jsx(pp,{sessionId:oe.id,visitorId:((Es=oe.metadata)==null?void 0:Es.visitor_id)??null,orgId:s,sites:je}),e.jsx(hh,{sessionId:oe.id}),e.jsx(ep,{orgId:s,currentSessionId:oe.id,contactId:oe.contact_id,visitorId:((Rs=oe.metadata)==null?void 0:Rs.visitor_id)??null,sourceLabels:Se,onOpenSession:p=>Ke(p,"contact_id")}),e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden min-w-0",children:e.jsx(_r,{conversation:Q,orgId:s,isLiveChat:!0,onDeleted:()=>xe(null),onBack:c?()=>xe(null):void 0})})]}):Le?e.jsxs("div",{className:"flex-1 flex min-h-0 flex-col h-full",children:[o&&e.jsxs("button",{onClick:()=>xe(null),className:"flex items-center gap-1 px-3 py-2 text-sm text-muted-foreground hover:text-foreground border-b",children:[e.jsx(sa,{className:"h-4 w-4"})," Back"]}),e.jsx(Wm,{session:Le,orgId:s})]}):e.jsx("div",{className:"flex-1 flex flex-col h-full min-h-0 min-w-0 overflow-hidden",children:e.jsx(_r,{conversation:Q,orgId:s,sourceLabel:Q!=null&&Q.connected_account_id?Se[Q.connected_account_id]??null:null,onDeleted:()=>xe(null),onBack:c&&Q?()=>xe(null):void 0})})})}),!o&&Q&&Cs&&Q.contact_id&&e.jsx("div",{className:"w-72 shrink-0 border-l h-full",children:e.jsx(Hh,{contactId:Q.contact_id,orgId:s,onClose:()=>Xt(!1),activeChannel:Q.channel??null,onOpenConversation:p=>O(`/inbox?channel=${encodeURIComponent(p)}&contact_id=${Q.contact_id}`)})})]})}),!Ne&&me.attentionBottom,!Ne&&me.insightsBottom,!Ne&&!z&&e.jsxs(e.Fragment,{children:[e.jsx(nr,{module:"inbox"}),e.jsx(nr,{module:"livechat"})]}),Me&&ft.size>0&&e.jsx(ph,{count:ft.size,onMarkRead:Un,onMarkUnread:Ft,onClear:qt,markingRead:It.isPending,markingUnread:Jt.isPending}),!Q&&!Me&&e.jsx(E,{onClick:()=>Pt(!0),size:"icon",className:"fixed bottom-6 right-6 h-12 w-12 rounded-full shadow-lg z-30",children:e.jsx(ar,{className:"h-5 w-5"})}),e.jsx(Xo,{open:Zs,onOpenChange:Pt,contacts:ct,presetContactId:Ue,onConversationCreated:p=>xe(p),presetChannel:w?w.provider:I,connectedChannels:ke.filter(p=>p.status==="active"&&["whatsapp","sms","instagram","email"].includes(p.channel)).map(p=>p.channel),presetAccount:w?{id:w.id,provider:w.provider,unipile_account_id:w.unipile_account_id,display_name:w.display_name,display_label:w.display_label,connection_status:w.
34connection_status,operational_state:w.operational_state,state_reason:w.state_reason}:null,availableAccounts:l.map(p=>({id:p.id,provider:p.provider,unipile_account_id:p.unipile_account_id,display_name:p.display_name,display_label:p.display_label,connection_status:p.connection_status,operational_state:p.operational_state,state_reason:p.state_reason,last_verified_at:p.last_verified_at??null})),onReconnectAccount:async p=>{Ve(p.id);try{const k=await r.mutateAsync({provider:p.provider,mode:"reconnect",account_id:p.id});window.open(k,"unipile-reconnect","width=560,height=720")||P.error("Popup blocked. Allow popups and try again.")}catch(k){P.error("Reconnect failed",{cause:k})}finally{Ve(null)}}}),e.jsx(sc,{open:qn,onOpenChange:Ys,orgId:s,teamMembers:ut,preselectedChannel:mt}),s&&e.jsx(co,{open:en,onOpenChange:Gt,orgId:s}),s&&e.jsx(po,{open:Fn,onOpenChange:tn,orgId:s})]})};export{Ny 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.