PageSourceSearch

https://comms-weave-link.lovable.app/assets/inbox-BBR3DXmS.js

js comms-weave-link.lovable.app collected 2026-10-03 03:26:56 UTC 127,745 bytes, 4 lines download raw bytes

1import{c as he,b as we,d as ke,e as Ce,r as o,j as e,s as A,t as C,X as se,T as na,v as Mt,a as Ze,u as ge,S as Ut,B as Qt,I as ra,q as Ht,k as Tt,l as Wt,w as oa,F as Gt,x as At,n as ia,_ as da}from"./index-Cjiu4FUh.js";import{u as Q}from"./useQuery-Dhz9AfLP.js";import{u as _}from"./useServerFn-BULoe4Hg.js";import{c as la,l as ca,t as ua,a as ma}from"./stores.functions-DuaX__i6.js";import{h as Yt,i as xa,j as Vt,k as pa,l as fa}from"./whatsapp.functions-CDvd6qQ_.js";import{f as Zt,a as ha,b as ga,c as ba}from"./facebook.functions-DuT02Vzt.js";import{c as Xt,u as ya,a as Jt,b as va}from"./contacts.functions-DY3oR_dz.js";import{l as ft}from"./team.functions-qNVnSQ3o.js";import{b as es,d as mt,P as ja,c as Ge,a as Na}from"./index-MK5GK15k.js";import{c as wa}from"./index-2-P1Y5Ij.js";import{s as ka,R as Ca}from"./index-BRVy4jfC.js";import{c as S}from"./utils-0exNfmSl.js";import{M as ts,R as _a,E as Sa,T as Ma,c as Ta,n as Aa}from"./emoji-picker-react.esm-BW-XZCim.js";import{u as Ye,b as zt,B as za}from"./inbox-read-broadcast-yGVccAnG.js";import{g as Ia,m as Pa,a as Ra,b as ss}from"./activity.functions-3iVucYdn.js";import{s as qa,S as Ea,a as Fa}from"./csat.functions-DYeo_pFJ.js";import{f as Da,A as La,g as as,P as Oa,C as $a,I as Ba,G as Ka,L as Ua,h as Qa,i as Ha,j as Wa,k as Ga,S as Ya,l as Va,m as Za,n as Xa,o as Ja,D as It,a as Pt,b as Rt,d as ut,R as qt}from"./dropdown-menu-6H6eNL_K.js";import{C as en}from"./chevron-right-R0YDa3l3.js";import{C as ht}from"./check-BiuagQd1.js";import{C as tn}from"./checkbox-DGAOpP5Z.js";import{S as sn,b as an,d as nn,c as rn}from"./sheet-65rC9d0-.js";import{u as on}from"./useMutation-D-jcgcgU.js";import{g as dn,l as ln,B as gt,G as cn,a as un}from"./copilot.functions-DDpuxA5B.js";import{L as Ne}from"./loader-circle-CdMlWBWt.js";import{R as mn}from"./refresh-cw-Dmc3wwYp.js";import{T as xn}from"./triangle-alert-DyYhFJYk.js";import{U as xt}from"./user-plus-DxXlhLNS.js";import{M as pn}from"./message-square-text-CxAON9xa.js";import{M as Et}from"./mail-open-Dj-PxGbu.js";import{M as Ft}from"./mail-DYHVnAYX.js";import{T as nt}from"./trash-2-5_Q0B7vm.js";import{S as pt}from"./sticky-note-t5ypjjdR.js";import{C as fn}from"./chevron-left-B8PN4Ti6.js";import{I as hn}from"./info-D7o8rdmW.js";import{P as Dt}from"./pencil-CLSY226k.js";import{P as gn}from"./paperclip-C6jBwoKn.js";import{S as ns}from"./shopping-cart-CTdLemZT.js";import{P as qe}from"./plus-DHAzVCAR.js";import{C as bn}from"./circle-check-Csl0TWWm.js";import{D as rt}from"./download-BOYGHVCP.js";import{C as yn}from"./circle-alert-B-35ydJL.js";import{M as vn}from"./mic-Cm4pZmFc.js";import{H as jn}from"./history-DoQGAxVD.js";import"./index-kwCmYQPB.js";import"./clsx-B-dksMZM.js";import"./link-2-BkMh-O-q.js";import"./external-link-CPgUrqmx.js";import"./index-CvoaQvSr.js";import"./index-CZEPzyqZ.js";import"./index-BBH4XXtj.js";import"./index-CPUGv1gQ.js";import"./index-Cb-OvuMQ.js";import"./index-BzU50n7h.js";import"./index-B8k91cqS.js";const Nn=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],wn=he("arrow-right",Nn);const kn=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z",key:"oz39mx"}]],rs=he("bookmark",kn);const Cn=[["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}],["path",{d:"m9 10-5 5 5 5",key:"1kshq7"}]],Lt=he("corner-down-left",Cn);const _n=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],Sn=he("ellipsis",_n);const Mn=[["path",{d:"M13 22h5a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v3.3",key:"cvl1xm"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"m7.69 16.479 1.29 4.88a.5.5 0 0 1-.698.591l-1.843-.849a1 1 0 0 0-.879.001l-1.846.85a.5.5 0 0 1-.692-.593l1.29-4.88",key:"1ff7gj"}],["circle",{cx:"6",cy:"14",r:"3",key:"a1xfv6"}]],Tn=he("file-badge",Mn);const An=[["path",{d:"m22 11-1.296-1.296a2.4 2.4 0 0 0-3.408 0L11 16",key:"9kzy35"}],["path",{d:"M4 8a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2",ke
1y:"1t0f0t"}],["circle",{cx:"13",cy:"7",r:"1",fill:"currentColor",key:"1obus6"}],["rect",{x:"8",y:"2",width:"14",height:"14",rx:"2",key:"1gvhby"}]],zn=he("images",An);const In=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]],Pn=he("map-pin",In);const Rn=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],qn=he("square",Rn);const En=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}],["path",{d:"M17 14V2",key:"8ymqnk"}]],Fn=he("thumbs-down",En);const Dn=[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]],Ln=he("wand-sparkles",Dn),os=we({method:"POST"}).middleware([ke]).handler(Ce("b988111ac9e5e1617e8c9eceac53e7804a7cb2fb5c3feb063df6614cfa1b55c5")),is=we({method:"POST"}).middleware([ke]).handler(Ce("2598d64ebddcb143d86d0ad9c018e8fcd3a453fde11cc23f1e01a3207c8597f2")),On=we({method:"POST"}).middleware([ke]).handler(Ce("d232f68454b5c12a15be9f034eb3a83f902de421a963c6f1b8a881fac9ec0b40")),$n=we({method:"POST"}).middleware([ke]).handler(Ce("4b9965a9ffbdd146538a0472d49837b0ab24a42e949bc9ed176c59f57419098e")),Bn=we({method:"POST"}).middleware([ke]).handler(Ce("fa73963d6d380519c4b0e83a6b599b7462dd96e1daa3662888ef1c03c64d68bd")),Kn=we({method:"POST"}).middleware([ke]).handler(Ce("23842e0d8986b1d13a8b304930f1f1990b6ac50676814ecbaf9c995a21421543")),Un=we({method:"POST"}).middleware([ke]).handler(Ce("33739b0f4af9317e326da78c8aaa1b71d0fe11be4dc9b25f5402c5b64cd2bef2"));function Qn(t,s=[]){let a=[];function r(d,c){const l=o.createContext(c);l.displayName=d+"Context";const u=a.length;a=[...a,c];const x=h=>{const{scope:p,children:N,...y}=h,I=p?.[t]?.[u]||l,k=o.useMemo(()=>y,Object.values(y));return e.jsx(I.Provider,{value:k,children:N})};x.displayName=d+"Provider";function m(h,p){const N=p?.[t]?.[u]||l,y=o.useContext(N);if(y)return y;if(c!==void 0)return c;throw new Error(`\`${h}\` must be used within \`${d}\``)}return[x,m]}const i=()=>{const d=a.map(c=>o.createContext(c));return function(l){const u=l?.[t]||d;return o.useMemo(()=>({[`__scope${t}`]:{...l,[t]:u}}),[l,u])}};return i.scopeName=t,[r,Hn(i,...s)]}function Hn(...t){const s=t[0];if(t.length===1)return s;const a=()=>{const r=t.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(d){const c=r.reduce((l,{useScope:u,scopeName:x})=>{const h=u(d)[`__scope${x}`];return{...l,...h}},{});return o.useMemo(()=>({[`__scope${s.scopeName}`]:c}),[c])}};return a.scopeName=s.scopeName,a}var Wn=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],bt=Wn.reduce((t,s)=>{const a=wa(`Primitive.${s}`),r=o.forwardRef((i,d)=>{const{asChild:c,...l}=i,u=c?a:s;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),e.jsx(u,{...l,ref:d})});return r.displayName=`Primitive.${s}`,{...t,[s]:r}},{});function Gn(){return ka.useSyncExternalStore(Yn,()=>!0,()=>!1)}function Yn(){return()=>{}}var yt="Avatar",[Vn]=Qn(yt),[Zn,ds]=Vn(yt),ls=o.forwardRef((t,s)=>{const{__scopeAvatar:a,...r}
1=t,[i,d]=o.useState("idle");return e.jsx(Zn,{scope:a,imageLoadingStatus:i,onImageLoadingStatusChange:d,children:e.jsx(bt.span,{...r,ref:s})})});ls.displayName=yt;var cs="AvatarImage",us=o.forwardRef((t,s)=>{const{__scopeAvatar:a,src:r,onLoadingStatusChange:i=()=>{},...d}=t,c=ds(cs,a),l=Xn(r,d),u=es(x=>{i(x),c.onImageLoadingStatusChange(x)});return mt(()=>{l!=="idle"&&u(l)},[l,u]),l==="loaded"?e.jsx(bt.img,{...d,ref:s,src:r}):null});us.displayName=cs;var ms="AvatarFallback",xs=o.forwardRef((t,s)=>{const{__scopeAvatar:a,delayMs:r,...i}=t,d=ds(ms,a),[c,l]=o.useState(r===void 0);return o.useEffect(()=>{if(r!==void 0){const u=window.setTimeout(()=>l(!0),r);return()=>window.clearTimeout(u)}},[r]),c&&d.imageLoadingStatus!=="loaded"?e.jsx(bt.span,{...i,ref:s}):null});xs.displayName=ms;function Ot(t,s){return t?s?(t.src!==s&&(t.src=s),t.complete&&t.naturalWidth>0?"loaded":"loading"):"error":"idle"}function Xn(t,{referrerPolicy:s,crossOrigin:a}){const r=Gn(),i=o.useRef(null),d=r?(i.current||(i.current=new window.Image),i.current):null,[c,l]=o.useState(()=>Ot(d,t));return mt(()=>{l(Ot(d,t))},[d,t]),mt(()=>{const u=h=>()=>{l(h)};if(!d)return;const x=u("loaded"),m=u("error");return d.addEventListener("load",x),d.addEventListener("error",m),s&&(d.referrerPolicy=s),typeof a=="string"&&(d.crossOrigin=a),()=>{d.removeEventListener("load",x),d.removeEventListener("error",m)}},[d,a,s]),c}var ps=ls,fs=us,hs=xs;const gs=o.forwardRef(({className:t,...s},a)=>e.jsx(ps,{ref:a,className:S("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...s}));gs.displayName=ps.displayName;const bs=o.forwardRef(({className:t,...s},a)=>e.jsx(fs,{ref:a,className:S("aspect-square h-full w-full",t),...s}));bs.displayName=fs.displayName;const ys=o.forwardRef(({className:t,...s},a)=>e.jsx(hs,{ref:a,className:S("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...s}));ys.displayName=hs.displayName;function Jn(t,s){const r=(t&&t.trim()||s&&s.trim()||"?").split(/\s+/).filter(Boolean);return r.length===1?r[0].slice(0,2).toUpperCase():(r[0][0]+r[r.length-1][0]).toUpperCase()}function er(t){let s=0;for(let a=0;a<t.length;a++)s=s*31+t.charCodeAt(a)>>>0;return s%360}function tr(t){const s=(t??"").toLowerCase();return s==="whatsapp"?"bg-emerald-500":s==="facebook"||s==="facebook_feed"?"bg-blue-500":s==="instagram"?"bg-pink-500":"bg-muted-foreground"}function sr({name:t,phone:s,url:a,channel:r,size:i=40,className:d,showChannelDot:c=!0}){const l=(t||s||"x").toLowerCase(),x=`hsl(${er(l)} 55% 45%)`;return e.jsxs("div",{className:S("relative shrink-0",d),style:{width:i,height:i},children:[e.jsxs(gs,{className:"h-full w-full",children:[a?e.jsx(bs,{src:a,alt:t??s??"contact"}):null,e.jsx(ys,{className:"text-white font-semibold",style:{backgroundColor:x,fontSize:Math.max(11,i*.36)},children:Jn(t,s)})]}),c&&r&&e.jsx("span",{className:S("absolute -bottom-0.5 -right-0.5 rounded-full ring-2 ring-background",tr(r)),style:{width:Math.max(10,i*.28),height:Math.max(10,i*.28)},"aria-label":r})]})}const $t=["#22c55e","#facc15","#38bdf8","#fb7185","#f97316","#a78bfa"];function ar({onComplete:t}){const s=o.useRef(null);return o.useEffect(()=>{const a=s.current;if(!a)return;if(window.matchMedia("(prefers-reduced-motion: reduce)").matches){const m=window.setTimeout(t,2e3);return()=>window.clearTimeout(m)}const i=a.getContext("2d");if(!i)return;const d=()=>{const m=Math.min(window.devicePixelRatio||1,2);a.width=window.innerWidth*m,a.height=window.innerHeight*m,a.style.width=`${window.innerWidth}px`,a.style.height=`${window.innerHeight}px`,i.setTransform(m,0,0,m,0,0)};d(),window.addEventListener("resize",d);const c=Array.from({length:150},(m,h)=>{const p=h%2===0;return{x:p?-12:window.innerWidth+12,y:window.innerHeight*(.25+Math.random()*.45),vx:(p?1:-1)*(5+Math.random()*8),vy:-8-Math.random()*9,size:5+Math.random()*7,color:$t[h%$t.length],rotation:Math.random()*Math.PI,spin:(Math.random()-.5)*.35}}),l=performance.now();let u=0;const x=m=>{const h=m-l;i.clearRect(0,0,window.innerWidth,window.innerHeight);for(const p of c)p.x+=p.vx,p.y+=p.vy,p.vy+=.28,p.vx*=.992,p.rotation+=p.spin,i.save(),i.globalAlpha=h>1500?Math.max(0,(2e3-h)/500):1,i.translate(p.x,p.y),i.rotate(p.rotation),i.fillStyle=p.color,i.fillRect(-p.size/2,-p.size/3,p.size,p.size*.66),i.restore(
1);h<2e3?u=requestAnimationFrame(x):t()};return u=requestAnimationFrame(x),()=>{cancelAnimationFrame(u),window.removeEventListener("resize",d)}},[t]),e.jsx("canvas",{ref:s,className:"pointer-events-none fixed inset-0 z-[100]","aria-hidden":"true"})}var vt="ContextMenu",[nr]=Na(vt,[as]),X=as(),[rr,vs]=nr(vt),js=t=>{const{__scopeContextMenu:s,children:a,onOpenChange:r,dir:i,modal:d=!0}=t,[c,l]=o.useState(!1),u=X(s),x=es(r),m=o.useCallback(h=>{l(h),x(h)},[x]);return e.jsx(rr,{scope:s,open:c,onOpenChange:m,modal:d,children:e.jsx(Da,{...u,dir:i,open:c,onOpenChange:m,modal:d,children:a})})};js.displayName=vt;var Ns="ContextMenuTrigger",ws=o.forwardRef((t,s)=>{const{__scopeContextMenu:a,disabled:r=!1,...i}=t,d=vs(Ns,a),c=X(a),l=o.useRef({x:0,y:0}),u=o.useRef({getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...l.current})}),x=o.useRef(0),m=o.useCallback(()=>window.clearTimeout(x.current),[]),h=p=>{l.current={x:p.clientX,y:p.clientY},d.onOpenChange(!0)};return o.useEffect(()=>m,[m]),o.useEffect(()=>{r&&m()},[r,m]),e.jsxs(e.Fragment,{children:[e.jsx(La,{...c,virtualRef:u}),e.jsx(ja.span,{"data-state":d.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:s,style:{WebkitTouchCallout:"none",...t.style},onContextMenu:r?t.onContextMenu:Ge(t.onContextMenu,p=>{m(),h(p),p.preventDefault()}),onPointerDown:r?t.onPointerDown:Ge(t.onPointerDown,st(p=>{m(),x.current=window.setTimeout(()=>h(p),700)})),onPointerMove:r?t.onPointerMove:Ge(t.onPointerMove,st(m)),onPointerCancel:r?t.onPointerCancel:Ge(t.onPointerCancel,st(m)),onPointerUp:r?t.onPointerUp:Ge(t.onPointerUp,st(m))})]})});ws.displayName=Ns;var or="ContextMenuPortal",ks=t=>{const{__scopeContextMenu:s,...a}=t,r=X(s);return e.jsx(Oa,{...r,...a})};ks.displayName=or;var Cs="ContextMenuContent",_s=o.forwardRef((t,s)=>{const{__scopeContextMenu:a,...r}=t,i=vs(Cs,a),d=X(a),c=o.useRef(!1);return e.jsx($a,{...d,...r,ref:s,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:l=>{t.onCloseAutoFocus?.(l),!l.defaultPrevented&&c.current&&l.preventDefault(),c.current=!1},onInteractOutside:l=>{t.onInteractOutside?.(l),!l.defaultPrevented&&!i.modal&&(c.current=!0)},style:{...t.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});_s.displayName=Cs;var ir="ContextMenuGroup",dr=o.forwardRef((t,s)=>{const{__scopeContextMenu:a,...r}=t,i=X(a);return e.jsx(Ka,{...i,...r,ref:s})});dr.displayName=ir;var lr="ContextMenuLabel",Ss=o.forwardRef((t,s)=>{const{__scopeContextMenu:a,...r}=t,i=X(a);return e.jsx(Ua,{...i,...r,ref:s})});Ss.displayName=lr;var cr="ContextMenuItem",Ms=o.forwardRef((t,s)=>{const{__scopeContextMenu:a,...r}=t,i=X(a);return e.jsx(Ba,{...i,...r,ref:s})});Ms.displayName=cr;var ur="ContextMenuCheckboxItem",Ts=o.forwardRef((t,s)=>{const{__scopeContextMenu:a,...r}=t,i=X(a);return e.jsx(Qa,{...i,...r,ref:s})});Ts.displayName=ur;var mr="ContextMenuRadioGroup",xr=o.forwardRef((t,s)=>{const{__scopeContextMenu:a,...r}=t,i=X(a);return e.jsx(Ha,{...i,...r,ref:s})});xr.displayName=mr;var pr="ContextMenuRadioItem",As=o.forwardRef((t,s)=>{const{__scopeContextMenu:a,...r}=t,i=X(a);return e.jsx(Wa,{...i,...r,ref:s})});As.displayName=pr;var fr="ContextMenuItemIndicator",zs=o.forwardRef((t,s)=>{const{__scopeContextMenu:a,...r}=t,i=X(a);return e.jsx(Ga,{...i,...r,ref:s})});zs.displayName=fr;var hr="ContextMenuSeparator",Is=o.forwardRef((t,s)=>{const{__scopeContextMenu:a,...r}=t,i=X(a);return e.jsx(Ya,{...i,...r,ref:s})});Is.displayName=hr;var gr="ContextMenuArrow",br=o.forwardRef((t,s)=>{const{__scopeContextMenu:a,...r}=t,i=X(a);return e.jsx(Va,{...i,...r,ref:s})});br.displayName=gr;var yr="ContextMenuSubTrigger",Ps=o.forwardRef((t,s)=>{const{__scopeContextMenu:a,...r}=t,i=X(a);return e.jsx(Za,{...i,...r,ref:s})});Ps.displayName=yr;var vr="ContextMenuSubContent",Rs=o.forwardRef((t,s)=>{const{__scopeContextMenu:a,...r}=t,i=X(a);return e.jsx(Xa,{...i,...r,ref:s,style:{...t.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Rs.displayName=vr;function st(t){return s=>s.pointerType!=="mouse"?t(s):void 0}var jr=js,Nr=ws,wr=ks,qs=_s,Es=Ss,Fs=Ms,Ds=Ts,Ls=As,Os=zs,$s=Is,Bs=Ps,Ks=Rs;const kr=jr,Cr=Nr,_r=o.forwardRef(({className:t,inset:s,children:a,...r},i)=>e.jsxs(Bs,{ref:i,className:S("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",s&&"pl-8",t),...r,children:[a,e.jsx(en,{className:"ml-auto h-4 w-4"})]}));_r.displayName=Bs.displayName;const Sr=o.forwardRef(({className:t,...s},a)=>e.jsx(Ks,{ref:a,className:S("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:sli
1de-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-(--radix-context-menu-content-transform-origin)",t),...s}));Sr.displayName=Ks.displayName;const Us=o.forwardRef(({className:t,...s},a)=>e.jsx(wr,{children:e.jsx(qs,{ref:a,className:S("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-(--radix-context-menu-content-transform-origin)",t),...s})}));Us.displayName=qs.displayName;const at=o.forwardRef(({className:t,inset:s,...a},r)=>e.jsx(Fs,{ref:r,className:S("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s&&"pl-8",t),...a}));at.displayName=Fs.displayName;const Mr=o.forwardRef(({className:t,children:s,checked:a,...r},i)=>e.jsxs(Ds,{ref:i,className:S("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:a,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Os,{children:e.jsx(ht,{className:"h-4 w-4"})})}),s]}));Mr.displayName=Ds.displayName;const Tr=o.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(Ls,{ref:r,className:S("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...a,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Os,{children:e.jsx(Ja,{className:"h-4 w-4 fill-current"})})}),s]}));Tr.displayName=Ls.displayName;const Ar=o.forwardRef(({className:t,inset:s,...a},r)=>e.jsx(Es,{ref:r,className:S("px-2 py-1.5 text-sm font-semibold text-foreground",s&&"pl-8",t),...a}));Ar.displayName=Es.displayName;const zr=o.forwardRef(({className:t,...s},a)=>e.jsx($s,{ref:a,className:S("-mx-1 my-1 h-px bg-border",t),...s}));zr.displayName=$s.displayName;function Ir(t,s){const[a,r]=o.useState([]),[i,d]=o.useState([]),c=o.useRef(null),l=o.useRef(0);o.useEffect(()=>{if(!t||!s)return;const x=A.channel(`conv-presence:${t}`,{config:{presence:{key:s.userId}}});c.current=x,x.on("presence",{event:"sync"},()=>{const h=x.presenceState(),p=[];for(const[N,y]of Object.entries(h)){if(N===s.userId)continue;const I=y[0]?.name??"Agent";p.push({userId:N,name:I})}r(p)}),x.on("broadcast",{event:"typing"},({payload:h})=>{const p=h;if(!p?.userId||p.userId===s.userId)return;const N=Date.now();d(y=>[...y.filter(k=>k.userId!==p.userId),{userId:p.userId,name:p.name,at:N}])}),x.subscribe(async h=>{h==="SUBSCRIBED"&&await x.track({name:s.name})});const m=setInterval(()=>{const h=Date.now()-4e3;d(p=>p.filter(N=>N.at>h))},1e3);return()=>{clearInterval(m),A.removeChannel(x),c.current=null,r([]),d([])}},[t,s?.userId,s?.name]);const u=o.useCallback(()=>{if(!c.current||!s)return;const x=Date.now();x-l.current<1500||(l.current=x,c.current.send({type:"broadcast",event:"typing",payload:{userId:s.userId,name:s.name}}))},[s?.userId,s?.name]);return{viewers:a,typers:i,broadcastTyping:u}}const Pr=we({method:"POST"}).middleware([ke]).handler(Ce("2ee2a87d959dacba2bfb44d3d718c19cba06af301dfb51d452a8724cfdbcf677")),Rr=we({method:"POST"}).middleware([ke]).handler(Ce("3e5928c659dae0a5f7226579de3d2ce3d9f3989ed16f2c99b0eea309fbd2d78a")),Bt={positive:"bg-emerald-500/15 text-emerald-600 dark:text-emerald-300 border-emerald-500/30",neutral:"bg-muted text-muted-foreground border-border",negative:"bg-orange-500/15 text-orange-600 dar
1k:text-orange-300 border-orange-500/30",at_risk:"bg-red-500/15 text-red-600 dark:text-red-300 border-red-500/30"},qr={positive:"Positive",neutral:"Neutral",negative:"Frustrated",at_risk:"At risk"};function Er({conversationId:t,channel:s,signal:a,onInsert:r,onClose:i}){const d=_(dn),c=_(ln),[l,u]=o.useState(!0),x=Q({queryKey:["copilot",t,l?a:"manual"],queryFn:()=>d({data:{conversationId:t}}),staleTime:6e4,retry:!1});o.useEffect(()=>{x.error&&C.error(x.error.message)},[x.error]);const m=on({mutationFn:y=>c({data:{conversationId:t,channel:s,sentiment:x.data?.sentiment??null,action:y.action,objection:y.objection??null,suggestion:y.suggestion??null,finalText:y.suggestion??null,snippetId:y.snippetId??null}})}),h=(y,I,k)=>{r(y),m.mutate({action:"used",objection:I??null,suggestion:y,snippetId:k??null})},p=x.data,N=o.useMemo(()=>Math.round(((p?.sentimentScore??0)+1)/2*100),[p?.sentimentScore]);return e.jsxs("div",{className:"mx-4 mb-2 rounded-xl border border-primary/30 bg-card/80 backdrop-blur max-h-[45vh] overflow-y-auto",children:[e.jsxs("div",{className:"sticky top-0 z-10 flex items-center gap-2 px-3 py-2 border-b border-border bg-card/95",children:[e.jsx(gt,{className:"size-4 text-primary"}),e.jsx("span",{className:"text-sm font-semibold",children:"Copilot"}),p&&e.jsx("span",{className:S("text-[10px] font-semibold uppercase tracking-wide px-2 py-0.5 rounded-full border",Bt[p.sentiment]??Bt.neutral),children:qr[p.sentiment]??p.sentiment}),p&&p.urgency!=="low"&&e.jsxs("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-2 py-0.5 rounded-full border bg-amber-500/15 text-amber-600 dark:text-amber-300 border-amber-500/30",children:[p.urgency," urgency"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[e.jsx("button",{onClick:()=>u(y=>!y),title:l?"Auto re-analysis on (updates with each new message)":"Auto re-analysis off",className:S("text-[10px] px-2 py-1 rounded-lg border",l?"border-primary/40 text-primary bg-primary/10":"border-border text-muted-foreground"),children:"Auto"}),e.jsx("button",{onClick:()=>x.refetch(),title:"Re-analyse now",className:"p-1.5 rounded-lg hover:bg-muted text-muted-foreground",children:x.isFetching?e.jsx(Ne,{className:"size-3.5 animate-spin"}):e.jsx(mn,{className:"size-3.5"})}),e.jsx("button",{onClick:i,title:"Close copilot",className:"p-1.5 rounded-lg hover:bg-muted text-muted-foreground",children:e.jsx(se,{className:"size-3.5"})})]})]}),x.isPending&&e.jsxs("div",{className:"p-4 text-xs text-muted-foreground flex items-center gap-2",children:[e.jsx(Ne,{className:"size-3.5 animate-spin"})," Reading the conversation…"]}),x.isError&&!x.isPending&&e.jsx("div",{className:"p-4 text-xs text-red-500",children:x.error.message}),p&&!x.isPending&&e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:S("h-full rounded-full transition-all",p.sentiment==="positive"?"bg-emerald-500":p.sentiment==="neutral"?"bg-sky-500":p.sentiment==="negative"?"bg-orange-500":"bg-red-500"),style:{width:`${Math.max(4,N)}%`}})}),p.mood&&e.jsx("div",{className:"mt-1.5 text-[11px] text-muted-foreground",children:p.mood})]}),p.summary&&e.jsx("p",{className:"text-xs leading-relaxed",children:p.summary}),p.buyingSignals.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:p.buyingSignals.map((y,I)=>e.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-300 border border-emerald-500/25 inline-flex items-center gap-1",children:[e.jsx(na,{className:"size-3"})," ",y]},I))}),p.objections.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground flex items-center gap-1.5",children:[e.jsx(xn,{className:"size-3.5"})," Objections to handle"]}),p.objections.map((y,I)=>e.jsxs("div",{className:"rounded-lg border border-border bg-muted/40 p-2.5",children:[e.jsx("div",{className:"text-xs font-medium mb-1",children:y.label}),e.jsx("div",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:y.snippet}),e.jsxs("div",{className:"mt-2 flex gap-1.5",children:[e.jsxs("button",{onClick:()=>
1h(y.snippet,y.label,y.snippetId??null),className:"text-[11px] px-2 py-1 rounded-lg bg-primary/15 text-primary hover:bg-primary/25 inline-flex items-center gap-1",children:[e.jsx(Lt,{className:"size-3"})," Use snippet"]}),e.jsxs("button",{onClick:()=>m.mutate({action:"dismissed",objection:y.label,snippetId:y.snippetId??null}),title:"Not useful — teach the copilot",className:"text-[11px] px-2 py-1 rounded-lg bg-muted text-muted-foreground hover:text-foreground inline-flex items-center gap-1",children:[e.jsx(Fn,{className:"size-3"})," Not useful"]})]})]},I))]}),p.drafts.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Pre-drafted replies"}),p.drafts.map((y,I)=>e.jsxs("div",{className:"rounded-lg border border-border p-2.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-primary font-semibold mb-1",children:y.tone}),e.jsx("div",{className:"text-xs whitespace-pre-wrap",children:y.text}),e.jsxs("button",{onClick:()=>h(y.text,p.objections[0]?.label??null,p.objections[0]?.snippetId??null),className:"mt-2 text-[11px] px-2 py-1 rounded-lg bg-primary/15 text-primary hover:bg-primary/25 inline-flex items-center gap-1",children:[e.jsx(Lt,{className:"size-3"})," Use this reply"]})]},I))]}),p.nextBestAction&&e.jsxs("div",{className:"rounded-lg border border-primary/25 bg-primary/5 p-2.5 text-xs",children:[e.jsx("span",{className:"font-semibold",children:"Next best action: "}),p.nextBestAction]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground flex items-center gap-1.5",children:[e.jsx(cn,{className:"size-3"})," Learned from ",p.learnedFrom," past winning replies & snippets"]})]})]})}function Fr({status:t,error:s}){return s||t==="failed"?e.jsx(yn,{className:"size-3 text-red-300","aria-label":s??"failed"}):t==="read"||t==="played"?e.jsx(At,{className:"size-3 text-sky-300","aria-label":t}):t==="delivered"?e.jsx(At,{className:"size-3 text-muted-foreground","aria-label":"delivered"}):t==="sent"?e.jsx(ht,{className:"size-3 text-muted-foreground","aria-label":"sent"}):e.jsx(ia,{className:"size-3 text-red-300","aria-label":"pending"})}function Ke({text:t,className:s}){if(!t)return null;const a=/(\b(?:https?:\/\/|www\.)[^\s]+|\b[a-zA-Z0-9][-a-zA-Z0-9]*\.[a-zA-Z]{2,}(?:\/[^\s]*)?)/gi,r=[];let i=0,d;for(;(d=a.exec(t))!==null;){d.index>i&&r.push(t.slice(i,d.index));const c=d[0];let l=c;/^https?:\/\//i.test(l)||(l=l.startsWith("www.")?`https://${l}`:`https://${l}`),r.push(e.jsx("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:S("underline break-all hover:opacity-80",s),onClick:u=>u.stopPropagation(),children:c},d.index)),i=d.index+c.length}return i<t.length&&r.push(t.slice(i)),e.jsx(e.Fragment,{children:r})}function Ve(t,s){const a=new Date(t),r=new Date(s);return a.getFullYear()===r.getFullYear()&&a.getMonth()===r.getMonth()&&a.getDate()===r.getDate()}function Qs(t){const s=new Date(t),a=new Date,r=new Date(a);return r.setDate(a.getDate()-1),Ve(t,a.toISOString())?"Today":Ve(t,r.toISOString())?"Yesterday":Math.floor((a.getTime()-s.getTime())/864e5)<7?s.toLocaleDateString([],{weekday:"long"}):s.toLocaleDateString([],{day:"numeric",month:"short",year:s.getFullYear()===a.getFullYear()?void 0:"numeric"})}function Dr(t){if(!t)return"";const s=new Date(t);if(Number.isNaN(s.getTime()))return"";const a=new Date,r=new Date(a);return r.setDate(a.getDate()-1),Ve(s.toISOString(),a.toISOString())?s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):Ve(s.toISOString(),r.toISOString())?"Yesterday":Math.floor((a.getTime()-s.getTime())/864e5)<7?s.toLocaleDateString([],{weekday:"short"}):s.toLocaleDateString([],{day:"2-digit",month:"2-digit",year:"2-digit"})}function Ue(t){return t.contacts?.name??t.contacts?.phone??t.facebook_page?.name??"Unknown"}function jt(t){if(t.channel==="facebook")return t.facebook_page?.name?`Facebook • ${t.facebook_page.name}`:"Facebook";if(t.channel==="facebook_feed"){const s=t.fb_item_type==="ad"?"Ad comment":t.fb_item_type==="comment"?"Comment reply":"Post comment";return t.facebook_page?.name?`Facebook ${s} • ${t.facebook_page.name}`:`Facebook ${s}`}if(t.channel==="whatsapp"){const s=t.whatsapp_instance,a=s?.name||s?.phone_number||s?.instance_name;return a?`WhatsApp • ${a}`:"WhatsApp"}return t.channel}function Kt(t){if(t.channel==="whatsapp"){const s=t.whatsapp_instance;if(!s)return!0;const a=(s.status??"").toLowerCase();return a!=="connected"&&a!=="open"&&a!=="ready"}return t.channel==="facebook"||t.channel==="facebook_feed"?!t.facebook_page:!1}function ui(){const[t,s]=o.useState(""),[a,r]=o.useState(!1),[i,d]=o.use
1State("contacts"),[c,l]=o.useState(!1),[u,x]=o.useState(!1),[m,h]=o.useState(null),p=Mt.useSearch(),N=Mt.useNavigate(),{user:y,isAdmin:I,can:k}=Ze();k("can_assign_chats");const E=k("can_delete_chats"),D=k("can_send_broadcasts"),O=ge(),b=_(os),v=o.useRef(null),M=_(Ia),L=_(Pa),J=_(Ra),W=_(ss),[H,ce]=o.useState(new Set),[_e,Qe]=o.useState("all"),[ee,Ee]=o.useState("open"),[ie,ue]=o.useState("newest"),[ae,Se]=o.useState(!1),[de,Fe]=o.useState(!1),te=Q({queryKey:["my-read-state"],queryFn:()=>M(),refetchInterval:3e4,refetchIntervalInBackground:!1}).data??{};o.useEffect(()=>(v.current=m,typeof window<"u"&&(window.__activeConvId=m),m&&(Ye.resetConv(m),zt(m),W({data:{conversationId:m,eventType:"conversation_opened"}}).catch(()=>{}),L({data:{conversationId:m}}).then(()=>O.invalidateQueries({queryKey:["my-read-state"]})).catch(()=>{})),()=>{typeof window<"u"&&(window.__activeConvId=null)}),[m,W,L,O]);const[De,le]=o.useState(()=>Ye.getPerConv());o.useEffect(()=>{const w=Ye.subscribePerConv(le);return()=>{w()}},[]);async function Le(w){try{m===w&&h(null),await J({data:{conversationId:w}}),Ye.incrementConv(w),O.invalidateQueries({queryKey:["my-read-state"]}),C.success("Marked as unread")}catch(q){C.error(q.message)}}async function Me(w){try{await L({data:{conversationId:w}}),Ye.resetConv(w),zt(w),O.invalidateQueries({queryKey:["my-read-state"]}),C.success("Marked as read")}catch(q){C.error(q.message)}}async function Oe(w){if(confirm("Permanently delete this chat and all its messages? This cannot be undone."))try{await A.from("messages").delete().eq("conversation_id",w);const{error:q}=await A.from("conversations").delete().eq("id",w);if(q)throw q;m===w&&h(null),O.invalidateQueries({queryKey:["conversations"]}),C.success("Chat deleted")}catch(q){C.error(q.message)}}const[me,He]=o.useState(typeof window<"u"&&"Notification"in window?Notification.permission:"unsupported"),$e=()=>{typeof window>"u"||!("Notification"in window)||Notification.requestPermission().then(w=>He(w)).catch(()=>{})},g=Ws(i==="contacts"?t.trim():"",400),[T,$]=o.useState(500),z=Q({queryKey:["conversations",g,T],queryFn:()=>b({data:{q:g,limit:T}}),placeholderData:w=>w,refetchInterval:18e4,refetchIntervalInBackground:!1,staleTime:3e4});o.useEffect(()=>{p.conv&&z.data?.some(w=>w.id===p.conv)&&(h(p.conv),N({search:{conv:void 0},replace:!0}))},[p.conv,z.data,N]);const P=o.useMemo(()=>new Set(z.data?.filter(w=>Kt(w)).map(w=>w.id)??[]),[z.data]);function V(w){const q=new Set(H);q.has(w)?q.delete(w):q.add(w),ce(q)}function Z(){const w=P.size>0&&Array.from(P).every(q=>H.has(q));ce(w?new Set:new Set(P))}
1async function Xe(){if(!E||H.size===0)return;const w=H.size;if(confirm(`Permanently delete ${w} disconnected chats and all their messages? This cannot be undone.`))try{const q=Array.from(H);await A.from("messages").delete().in("conversation_id",q);const{error:xe}=await A.from("conversations").delete().in("id",q);if(xe)throw xe;m&&H.has(m)&&h(null),ce(new Set),O.invalidateQueries({queryKey:["conversations"]}),C.success(`${w} chats deleted`)}catch(q){C.error(q.message)}}o.useEffect(()=>{let w=null;const q=()=>{w||(w=setTimeout(()=>{w=null,O.invalidateQueries({queryKey:["conversations"]})},2e4))},xe=A.channel(`inbox-rt-${crypto.randomUUID()}`).on("postgres_changes",{event:"*",schema:"public",table:"messages"},be=>{const re=be.new??be.old;re?.conversation_id&&O.invalidateQueries({queryKey:["messages",re.conversation_id]}),q()}).on("postgres_changes",{event:"*",schema:"public",table:"conversations"},be=>{const re=be.new;if(be.eventType==="UPDATE"&&re?.id){let ye=!1;O.setQueriesData({queryKey:["conversations"]},ve=>Array.isArray(ve)?ve.map(oe=>oe.id!==re.id?oe:(ye=!0,{...oe,...re,contacts:oe.contacts})).sort((oe,Be)=>new Date(Be.last_message_at??0).getTime()-new Date(oe.last_message_at??0).getTime()):ve),ye?q():O.invalidateQueries({queryKey:["conversations"]})}else O.invalidateQueries({queryKey:["conversations"]})}).subscribe();return()=>{w&&clearTimeout(w),A.removeChannel(xe)}},[O]);const ne=z.data?.find(w=>w.id===m);return e.jsxs("div",{className:"h-full min-h-0 grid grid-cols-12 grid-rows-[minmax(0,1fr)]",children:[e.jsxs("div",{className:S("col-span-12 md:col-span-4 lg:col-span-3 border-r border-border flex-col h-full min-h-0",m?"hidden md:flex":"flex"),children:[e.jsxs("div",{className:"p-3 border-b border-border flex items-center gap-2",children:[e.jsx("button",{onClick:()=>r(w=>!w),title:"Search",className:S("p-2 rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground",a&&"bg-primary/15 text-primary"),children:e.jsx(Ut,{className:"size-4"})}),k("can_edit_contacts")&&e.jsx("button",{onClick:()=>l(!0),title:"Create contact",className:"p-2 rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground",children:e.jsx(xt,{className:"size-4"})}),D&&e.jsx("button",{onClick:()=>x(!0),title:"Broadcast template",className:"p-2 rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground",children:e.jsx(ts,{className:"size-4"})}),e.jsx("div",{className:"text-xs text-muted-foreground ml-1 truncate",children:"Inbox"}),e.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[me!=="granted"&&me!=="unsupported"&&e.jsx("button",{onClick:$e,title:"Enable desktop notifications",className:"p-2 rounded-lg bg-primary/15 text-primary hover:bg-primary/25",children:me==="denied"?e.jsx(za,{className:"size-4"}):e.jsx(Qt,{className:"size-4"})}),E&&P.size>0&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:Z,title:"Toggle selection of all disconnected chats",className:"text-[11px] px-2 py-1.5 rounded-md bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground whitespace-nowrap",children:H.size>0&&Array.from(P).every(w=>H.has(w))?"Clear selection":"Select all disconnected"}),H.size>0&&e.jsxs("button",{onClick:Xe,title:"Delete selected chats",className:"text-[11px] px-2 py-1.5 rounded-md bg-red-500/15 hover:bg-red-500/25 text-red-400 whitespace-nowrap",children:["Delete ",H.size]})]})]})]}),me==="default"&&e.jsxs("div",{className:"px-3 py-2 text-[11px] bg-primary/10 text-primary border-b border-primary/20 flex items-center justify-between gap-2",children:[e.jsx("span",{children:"Get a sound + popup for new messages."}),e.jsx("button",{onClick:$e,className:"px-2 py-0.5 rounded bg-primary text-primary-foreground font-medium",children:"Enable"})]}),me==="denied"&&e.jsx("div",{className:"px-3 py-2 text-[11px] bg-yellow-100 text-yellow-900 border-b border-yellow-300 dark:bg-yellow-500/10 dark:text-yellow-300 dark:border-yellow-500/20",children:"Notifications are blocked. Enable them in your browser site settings to get popups."}),a&&e.jsx(Lr,{q:t,setQ:s,tab:i,setTab:d,onClose:()=>{r(!1),s("")},onPick:w=>{h(w),r(!1)}}),!a&&z.isError&&e.jsxs("div",{className:"m-3 rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-sm",children:[e.jsx("div",{className:"font-medium text-destructive",children:"Inbox could not load"}),e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:z.error.message||"Please try again."}),e.jsx("button",{onClick:()=>z.refetch(),className:"mt-3 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground",children:"Try again"})]}),!a&&!z.isError&&(()=>{const w=z.data??[],q=f=>
1(f.status??"open")!=="closed"&&(f.status??"open")!=="snoozed",xe=f=>f.status??"open",be=f=>ee==="all"?!0:ee==="open"?q(f):xe(f)===ee,re=f=>new Date(f.last_message_at??f.updated_at??f.created_at??0).getTime(),ye=f=>new Date(f.created_at??f.last_message_at??0).getTime(),ve=f=>f.awaiting_human??f.last_message_direction==="in",je=w.filter(q),oe=f=>f.assigned_agent_id??f.contacts?.assigned_agent_id??null,Be={all:je.length,mine:je.filter(f=>oe(f)===y?.id).length,unassigned:je.filter(f=>!oe(f)).length};let Te=w.filter(f=>!be(f)||ae&&!ve(f)?!1:_e==="all"?!0:_e==="mine"?oe(f)===y?.id:!oe(f));Te=[...Te].sort((f,Y)=>ie==="newest"?re(Y)-re(f):ie==="oldest"?re(f)-re(Y):ie==="longest_open"?ye(f)-ye(Y):ye(Y)-ye(f));const ot=[{key:"all",label:"All",Icon:ra},{key:"mine",label:"Mine",Icon:rs},{key:"unassigned",label:"Unassigned",Icon:xt}],Je=ee==="all"?"All":ee==="open"?"Open":ee==="closed"?"Closed":"Snoozed",it=ie==="newest"?"Newest":ie==="oldest"?"Oldest":ie==="longest_open"?"Longest Open":"Shortest Open";return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 py-2 border-b border-border flex flex-col gap-0.5",children:ot.map(f=>{const Y=_e===f.key,G=Be[f.key];return e.jsxs("button",{onClick:()=>Qe(f.key),className:S("flex items-center gap-2 px-2.5 py-1.5 rounded-md text-sm transition",Y?"bg-sidebar-accent text-foreground font-medium":"text-muted-foreground hover:bg-sidebar-accent/50 hover:text-foreground"),children:[e.jsx(f.Icon,{className:"size-4"}),e.jsx("span",{className:"flex-1 text-left",children:f.label}),G>0&&e.jsx("span",{className:"text-xs tabular-nums text-muted-foreground",children:G})]},f.key)})}),e.jsxs("div",{className:"px-3 py-2 border-b border-border flex items-center gap-2 relative",children:[e.jsxs(It,{open:de,onOpenChange:Fe,children:[e.jsx(Pt,{asChild:!0,children:e.jsxs("button",{className:"flex items-center gap-1 text-sm font-medium text-primary hover:underline",children:[Je,", ",it,e.jsx(Ht,{className:"size-3.5"})]})}),e.jsxs(Rt,{align:"start",className:"w-56 p-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground px-2 pt-1 pb-1.5",children:"Show"}),[["all","All conversations"],["open","Open conversations"],["closed","Closed conversations"],["snoozed","Snoozed conversations"]].map(([f,Y])=>e.jsxs("button",{onClick:()=>Ee(f),className:"w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent text-left",children:[e.jsx("span",{className:S("size-3.5 rounded-full border",ee===f?"border-primary border-[5px]":"border-muted-foreground/50")}),Y]},f)),e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground px-2 pt-3 pb-1.5",children:"Sort by"}),[["newest","Newest"],["oldest","Oldest"],["longest_open","Longest Open"],["shortest_open","Shortest Open"]].map(([f,Y])=>e.jsxs("button",{onClick:()=>ue(f),className:"w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent text-left",children:[e.jsx("span",{className:S("size-3.5 rounded-full border",ie===f?"border-primary border-[5px]":"border-muted-foreground/50")}),Y]},f))]})]}),e.jsxs("label",{className:"ml-auto flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",checked:ae,onChange:f=>Se(f.target.checked),className:"sr-only peer"}),e.jsx("span",{className:"relative inline-block w-8 h-4 bg-muted rounded-full peer-checked:bg-primary transition",children:e.jsx("span",{className:S("absolute top-0.5 left-0.5 size-3 bg-background rounded-full transition",ae&&"translate-x-4")})}),"Unreplied"]})]}),e.jsxs("div",{className:"flex-1 overflow-auto",children:[Te.length===0&&e.jsxs("div",{className:"p-8 text-center text-muted-foreground text-sm",children:[e.jsx(pn,{className:"size-8 mx-auto mb-2 opacity-50"}),w.length===0?"No conversations yet. Connect a WhatsApp channel to begin.":"No conversations in this view."]}),Te.map(f=>{const Y=De[f.id]??0,G=te[f.id]?.manually_unread?1:0,pe=Math.max(Y,G),Ie=Kt(f);return e.jsxs(kr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsxs("div",{onClick:()=>h(f.id),className:S("group relative w-full text-left px-3 sm:px-4 py-3 border-b border-border/50 hover:bg-sidebar-accent/40 transition cursor-pointer flex items-start gap-3",m===f.id&&"bg-sidebar-accent",H.has(f.id)&&"bg-primary/10"),children:[e.jsx(sr,{name:f.contacts?.name,phone:f.contacts?.phone,url:f.contacts?.avatar_url,channel:f.channel,size:40,className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:S("text-sm truncate flex items-center gap-1.5",pe>0?"font-semibold":"font-medium"),children:[E&&Ie&&e.jsx(tn,{checked:H.has(f.id),onCheckedChange:()=>V(f.id),onClick:Pe=>{Pe.stopPropagation()},"aria-label":`Select ${Ue(f)}`}),e.jsx("span",{className:"truncate",children:Ue(f)}),pe>0&&e.jsx("span",{className:"shrink-0 inline-flex items-center justify-center min-w-[1.25rem] h-5 px-1.5 rounded-full bg-primary text-primary-foreground text-[10px] font-bold",children:Y>0?Y>99?"99+":Y:"•"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx("span",{className:S("text-[10px] tabular-nums whitespace-nowrap",pe>0?"text-primary font-semibold":"text-muted-foreground"),children:Dr(f.last_message_at??f.updated_at??f.created_at)}),e.jsx("span",{className:S("text-[10px] px-1.5 py-0.5 rounded uppercase tracking-wider",f.channel==="whatsapp"?"bg-primary/15 text-primary":f.channel==="facebook_feed"?"bg-indigo-500/15 text-indigo-400":"bg-blue-500/15 text-blue-400"),children:f.channel==="facebook_feed"?"FB Feed":f.channel}),e.jsxs(It,{children:[e.jsx(Pt,{asChild:!0,children:e.jsx("button",{onClick:Pe=>{Pe.stopPropagation()},className:"p-1 rounded opacity-0 group-hover:opacity-100 hover:bg-muted text-muted-foreground","aria-label":"Conversation actions",children:e.jsx(Sn,{className:"size-3.5"})})}
1),e.jsxs(Rt,{align:"end",onClick:Pe=>Pe.stopPropagation(),children:[pe>0?e.jsxs(ut,{onClick:()=>Me(f.id),children:[e.jsx(Et,{className:"size-4 mr-2"})," Mark as read"]}):e.jsxs(ut,{onClick:()=>Le(f.id),children:[e.jsx(Ft,{className:"size-4 mr-2"})," Mark as unread"]}),E&&e.jsxs(ut,{onClick:()=>Oe(f.id),className:"text-red-400 focus:text-red-400",children:[e.jsx(nt,{className:"size-4 mr-2"})," Delete chat"]})]})]})]})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground truncate mt-0.5",children:jt(f)}),e.jsx("div",{className:S("text-xs truncate mt-1",pe>0?"text-foreground":"text-muted-foreground"),children:f.last_message??"—"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1.5",children:[f.needs_template&&e.jsx("div",{className:"inline-flex items-center gap-1 text-[10px] font-semibold text-red-300 bg-red-500/15 border border-red-500/30 rounded px-1.5 py-0.5",children:"🔴 Template Required"}),f.ai_replied_last&&e.jsxs("div",{className:"inline-flex items-center gap-1 text-[10px] font-semibold text-violet-700 bg-violet-500/15 border border-violet-500/30 rounded px-1.5 py-0.5 dark:text-violet-300",children:[e.jsx(gt,{className:"size-3"})," AI replied · needs human"]}),(f.internal_note_count??0)>0&&e.jsxs("div",{className:"inline-flex items-center gap-1 text-[10px] font-semibold text-yellow-900 bg-yellow-100 border border-yellow-300 rounded px-1.5 py-0.5 dark:text-yellow-200 dark:bg-yellow-500/15 dark:border-yellow-500/30",children:[e.jsx(pt,{className:"size-3"}),f.internal_note_count," note",f.internal_note_count===1?"":"s"]}),Ie&&e.jsxs("div",{className:"inline-flex items-center gap-1 text-[10px] font-semibold text-amber-300 bg-amber-500/15 border border-amber-500/30 rounded px-1.5 py-0.5",children:["⚠ Not connected",f.channel==="whatsapp"&&e.jsxs("span",{className:"text-amber-400/80 font-normal",children:["(",f.whatsapp_instance?.phone_number??f.whatsapp_instance?.instance_name??f.whatsapp_instance?.name??"unknown number",")"]}),E?" — you can delete":""]})]})]})]})}),e.jsxs(Us,{children:[pe>0?e.jsxs(at,{onClick:()=>Me(f.id),children:[e.jsx(Et,{className:"size-4 mr-2"})," Mark as read"]}):e.jsxs(at,{onClick:()=>Le(f.id),children:[e.jsx(Ft,{className:"size-4 mr-2"})," Mark as unread"]}),E&&e.jsxs(at,{onClick:()=>Oe(f.id),className:"text-red-400 focus:text-red-400",children:[e.jsx(nt,{className:"size-4 mr-2"})," Delete chat"]})]})]},f.id)}),!g&&w.length>=T&&e.jsx("div",{className:"p-3 text-center",children:e.jsx("button",{disabled:z.isFetching,onClick:()=>$(f=>f+500),className:"rounded-md border border-border px-3 py-1.5 text-xs font-medium text-foreground hover:bg-muted disabled:opacity-50",children:z.isFetching?"Loading…":"Load older chats"})})]})]})})()]}),e.jsx("div",{className:S("col-span-12 md:col-span-8 lg:col-span-7 flex-col h-full min-h-0",m?"flex":"hidden md:flex"),children:ne?e.jsx($r,{conv:ne,userId:y.id,onBack:()=>h(null)}):e.jsx("div",{className:"flex-1 flex items-center justify-center text-muted-foreground text-sm",children:"Select a conversation"})}),e.jsx("div",{className:"hidden lg:flex col-span-2 border-l border-border flex-col p-5 overflow-auto min-h-0 h-full",children:ne?e.jsx(Gs,{contact:ne.contacts,conv:ne}):e.jsx("div",{className:"text-muted-foreground text-sm",children:"No contact selected"})}),c&&e.jsx(Or,{onClose:()=>l(!1),onCreated:()=>{l(!1),O.invalidateQueries({queryKey:["conversations"]})}}),u&&e.jsx(io,{onClose:()=>x(!1)})]})}function Lr({q:t,setQ:s,tab:a,setTab:r,onClose:i,onPick:d}){const c=Ws(t,300),l=_(os),u=Q({queryKey:["search-contacts",c],queryFn:()=>l({data:{q:c}}),enabled:a==="contacts"&&c.trim().length>=2,staleTime:3e4}),x=Q({queryKey:["search-messages",a,c],queryFn:async()=>{if(!c)return[];const{data:m,error:h}=await A.from("messages").select("id, content, conversation_id, is_internal_note, created_at, conversations(id, contacts(name, phone))").ilike("content",`%${c}%`).eq("is_internal_note",a==="comments").order("created_at",{ascending:!1}).limit(40);if(h)throw h;return m},enabled:a!=="contacts"&&c.length>0});return e.jsxs("div",{className:"flex flex-col flex-1 overflow-hidden",children:[e.jsxs("div",{className:"p-3 border-b border-border space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Ut,{className:"size-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx("input",{autoFocus:!0,value:t,onChange:m=>s(m.target.value),placeholder:`Search for ${a==="contacts"?"Contacts":a==="messages"?"Messages":"Comments"}`,className:"w-full pl-9 pr-9 py-2 rounded-lg bg-input border border-border focus:border-primary outline-none text-sm"}),e.jsx("button",{onClick:i,className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 rounded-md hover:bg-muted text-muted-foreground",children:e.jsx(se,{className:"size-4"})})]}),e.jsx("div",{className:"flex gap-4 text-sm",children:["contacts","messages","comments"].map(m=>e.jsx("button",{onClick:()=>r(m),className:S("pb-1 capitalize transition border-b-2",a===m?"text-primary border-primary":"text-muted-foreground border-transparent hover:text-foreground"),children:m},m))})]}),e.jsxs("div",{className:"flex-1 overflow-auto",children:[a==="contacts"&&u.data?.map(m=>e.jsxs("button",{onClick:()=>d(m.id),className:"w-full text-left px-4 py-3 border-b border-border/50 hover:bg-sidebar-accent/40",children:[e.jsx("div",{className:"font-medium text-sm truncate",children:Ue(m)}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:m.last_message??"—"})]},m.id)),a!=="contacts"&&x.data?.map(m=>e.jsxs("button",{onClick:()=>d(m.conversation_id),className:"w-full text-left px-4 py-3 border-b border-border/50 hover:bg-sidebar-accent/40",children:[e.jsx("div",{className:"font-medium text-sm truncate",children:m.conversations?.contacts?.name??m.conversations?.contacts?.phone??"Unknown"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:e.jsx(Ke,{text:Hs(m.content)})})]},m.id)),a!=="contacts"&&c&&!x.isLoading&&(x.data?.length??0)===0&&e.jsx("div",{className:"p-6 text-center text-xs text-muted-foreground",children:"No matches"}),(u.isLoading||x.isLoading)&&e.jsx("div",{className:"p-6 text-center text-xs text-muted-foreground",children:"Searching…"})]})]})}function Or({onClose:t,onCreated:s}
1){const[a,r]=o.useState(""),[i,d]=o.useState(""),[c,l]=o.useState("whatsapp"),[u,x]=o.useState(!1),m=async()=>{if(!a.trim()&&!i.trim()){C.error("Name or phone required");return}x(!0);try{const h=i.replace(/\D/g,"")||`manual-${Date.now()}`,{error:p}=await A.from("contacts").insert({name:a.trim()||null,phone:i.trim()||null,channel:c,external_id:h});if(p)throw p;C.success("Contact created"),s()}catch(h){C.error(h.message)}finally{x(!1)}};return e.jsx("div",{className:"fixed inset-0 z-50 bg-background/70 backdrop-blur-sm flex items-center justify-center p-4",onClick:t,children:e.jsxs("div",{onClick:h=>h.stopPropagation(),className:"w-full max-w-md bg-card border border-border rounded-xl p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"font-semibold",children:"Create contact"}),e.jsx("button",{onClick:t,className:"p-1 text-muted-foreground hover:text-foreground",children:e.jsx(se,{className:"size-4"})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Name"}),e.jsx("input",{value:a,onChange:h=>r(h.target.value),placeholder:"Full name",className:"w-full px-3 py-2 rounded-lg bg-input border border-border outline-none focus:border-primary text-sm"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Phone"}),e.jsx("input",{value:i,onChange:h=>d(h.target.value),placeholder:"+27 000 000 0000",className:"w-full px-3 py-2 rounded-lg bg-input border border-border outline-none focus:border-primary text-sm"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Channel"}),e.jsxs("select",{value:c,onChange:h=>l(h.target.value),className:"w-full px-3 py-2 rounded-lg bg-input border border-border outline-none focus:border-primary text-sm",children:[e.jsx("option",{value:"whatsapp",children:"WhatsApp"}),e.jsx("option",{value:"facebook",children:"Facebook"})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{onClick:t,className:"px-3 py-2 rounded-lg bg-muted text-sm",children:"Cancel"}),e.jsx("button",{onClick:m,disabled:u,className:"px-3 py-2 rounded-lg bg-gradient-primary text-primary-foreground text-sm disabled:opacity-50",children:u?"Creating…":"Create"})]})]})})}function $r({conv:t,userId:s,onBack:a}){const[r,i]=o.useState(""),[d,c]=o.useState(!1),[l,u]=o.useState([]),[x,m]=o.useState(!1),[h,p]=o.useState(!1),[N,y]=o.useState(!1),[I,k]=o.useState(!1),[E,D]=o.useState(!1),[O,b]=o.useState(!1),[v,M]=o.useState(null),[L,J]=o.useState(null),[W,H]=o.useState(null),[ce,_e]=o.useState(!0),[Qe,ee]=o.useState(!1),[Ee,ie]=o.useState(!1),[ue,ae]=o.useState(!1),Se=_(un),[de,Fe]=o.useState(!0),[K,te]=o.useState(null),[De,le]=o.useState(!1),[Le,Me]=o.useState(!1),Oe=_(Yt),me=_(xa),He=_(Zt),$e=_(ha),g=_(ga),T=_($n),$=_(is),z=_(Xt),P=_(la),V=o.useRef(null),Z=o.useRef(null),Xe=o.useRef(null),ne=ge(),{user:w,can:q}=Ze(),xe=q("can_send_messages"),be=q("can_assign_chats"),re=q("can_close_chats"),ye=q("can_send_csat"),ve=q("can_use_copilot"),je=q("can_post_internal_notes"),oe=w?.user_metadata?.full_name??(w?.email?w.email.split("@")[0]:"Agent"),{viewers:Be,typers:Te,broadcastTyping:ot}=Ir(t.id,{userId:s,name:oe}),Je=_(Pr),it=_(Rr);o.useEffect(()=>{t.id&&Je({data:{conversationId:t.id}}).catch(()=>{})},[t.id,Je]),o.useEffect(()=>{let n=!0;return ae(!1),P({data:{conversationId:t.id}}).then(j=>{n&&j.show&&ae(!0)}).catch(()=>{}),()=>{n=!1}},[t.id,P]);const f=o.useRef(0),Y=()=>{const n=Date.now();n-f.current<8e3||(f.current=n,it({data:{conversationId:t.id,on:!0}}).catch(()=>{}))},G=Q({queryKey:["messages",t.id],queryFn:async()=>{const{data:n,error:j}=await A.from("messages").select("*").eq("conversation_id",t.id).order("created_at");if(j)throw j;return n},refetchInterval:1e4,refetchIntervalInBackground:!1}),pe=Q({queryKey:["templates"],queryFn:async()=>{const{data:n,error:j}=await A.from("templates").select("*").order("shortcut");if(j)throw j;return n}}),Ie=Q({queryKey:["team-directory"],queryFn:async()=>{const{data:n}=await A.rpc("get_team_directory");return n??[]}}),Pe=o.useMemo(()=>{const n=new Map;for(const j of Ie.data??[])n.set(j.id,j.full_name?.trim()||"Teammate");return n},[Ie.data]),et=n=>(n.full_name?.trim()||"user").replace(/\s+/g," "),Ae=o.useMemo(()=>{const n=r.match(/(^|\s)\/([\w-]*)$/);if(!n)return null;const j=n[2].toLowerCase(),F=(pe.data??[]).filter(R=>R.shortcut.toLowerCase().startsWith(j)).slice(0,6);return{term:j,matches:F,start:n.index+n[1].length}},[r,pe.data]),ze=o.useMemo(()=>
1{if(!d)return null;const n=r.match(/(^|\s)@([\w ]{0,30})$/);if(!n)return null;const j=n[2].toLowerCase().trim(),F=(Ie.data??[]).filter(R=>{const B=et(R).toLowerCase();return!j||B.includes(j)}).slice(0,6);return{term:j,items:F,start:n.index+n[1].length}},[r,Ie.data,d]),Nt=n=>{if(!Ae)return;const j=r.slice(0,Ae.start);i(j+n.body),setTimeout(()=>Z.current?.focus(),0)},wt=n=>{if(!ze)return;const j=et(n),F=r.slice(0,ze.start);i(F+"@"+j+" "),u(R=>R.find(B=>B.id===n.id)?R:[...R,{id:n.id,label:j}]),setTimeout(()=>Z.current?.focus(),0)};o.useEffect(()=>{const n=V.current;n&&ce&&n.scrollTo({top:n.scrollHeight,behavior:"smooth"})},[G.data,ce]),o.useEffect(()=>{const n=V.current;n&&(requestAnimationFrame(()=>{n.scrollTop=n.scrollHeight,_e(!0)}),J(null),i(""),Z.current&&(Z.current.style.height="auto"))},[t.id]),o.useEffect(()=>{const n=Z.current;n&&(n.style.height="auto",n.style.height=Math.min(n.scrollHeight,200)+"px")},[r]),o.useEffect(()=>{if(!de||d||W){te(null);return}const n=r;if(n.trim().length<8){te(null);return}if(K&&K.forDraft===n)return;let j=!1;const F=setTimeout(async()=>{le(!0);try{const R=await Se({data:{conversationId:t.id,draft:n}});if(!j){const B=R?.completion??"",fe=R?.full??"";te(B||fe?{forDraft:n,completion:B,full:fe}:null)}}catch{j||te(null)}finally{j||le(!1)}},900);return()=>{j=!0,clearTimeout(F)}},[r,de,d,W,t.id]);const dt=(n="append")=>{if(!K)return;const j=n==="polish"&&K.full?K.full:K.forDraft+K.completion;i(j),te(null),setTimeout(()=>Z.current?.focus(),0)},Vs=()=>{const n=V.current;if(!n)return;const j=n.scrollHeight-n.scrollTop-n.clientHeight<80;_e(j)},Zs=o.useMemo(()=>{const n=new Map;return(G.data??[]).forEach(j=>n.set(j.id,j)),n},[G.data]);o.useEffect(()=>{const n=A.channel(`messages-rt-${t.id}-${crypto.randomUUID()}`).on("postgres_changes",{event:"*",schema:"public",table:"messages",filter:`conversation_id=eq.${t.id}`},()=>{ne.invalidateQueries({queryKey:["messages",t.id]}),ne.invalidateQueries({queryKey:["conversations"]})}).subscribe();return()=>{A.removeChannel(n)}},[t.id,ne]);const lt=Q({queryKey:["me-profile",s],queryFn:async()=>{const{data:n}=await A.from("profiles").select("full_name").eq("id",s).maybeSingle(),{data:j}=await A.auth.getUser();return{full_name:n?.full_name??null,email:j.user?.email??null}}});o.useMemo(()=>{const n=lt.data?.full_name?.trim();return n?n.split(/\s+/)[0]:(lt.data?.email??"").split("@")[0]||"Agent"},[lt.data]);const Xs=_(On),Js=n=>{H(n),J(null),i(n.content??""),setTimeout(()=>Z.current?.focus(),0)},kt=()=>{H(null),i("")},ea=async()=>{if(!W||!r.trim()||x)return;const n=W,j=r.trim();m(!0),ne.setQueryData(["messages",t.id],F=>(F??[]).map(R=>R.id===n.id?{...R,content:j,edited_at:new Date().toISOString()}:R));try{await Xs({data:{messageId:n.id,content:j}}),H(null),i(""),G.refetch(),ne.invalidateQueries({queryKey:["conversations"]})}catch(F){C.error(F?.message??"Could not edit message"),G.refetch()}finally{m(!1)}},Ct=async()=>{if(!d&&!xe||d&&!je)return;if(W){await ea();return}if(!r.trim()||x)return;if(!d&&t.needs_template&&t.channel==="whatsapp"){C.error('This chat is older than 24 hours. WhatsApp requires an approved template — click "Send Template".'),ee(!0);return}const n=r,j=L,F=d,R=F?l.filter(U=>n.includes("@"+U.label)).map(U=>U.id):[],B=`temp-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,fe=new Date().toISOString(),tt={id:B,conversation_id:t.id,direction:F?"system":"out",content:n,is_internal_note:F,created_at:fe,sender_id:s,media_url:null,media_type:null,status:"sending",error_message:null,mentions:R.length?R:null,quoted_message_id:j?.id??null,external_id:null};ne.setQueryData(["messages",t.id],U=>[...U??[],tt]),i(""),J(null),F&&u([]),m(!0);const ct=U=>{ne.setQueryData(["messages",t.id],Re=>(Re??[]).map(We=>We.id===B?{...We,status:"failed",error_message:U}:We)),C.error(U)};try{if(F){const U=await $({data:{conversationId:t.id,content:n,mentions:R,quotedMessageId:j?.id??null}});U?.id&&R.length>0&&T({data:{messageId:U.id}}).catch(()=>{})}else{const U=n;let Re=null;if(t.channel==="whatsapp"&&t.contacts?.phone){const{data:We}=await A.rpc("list_whatsapp_instances_public"),St=(We??[]).find(aa=>aa.id===t.instance_id);if(!St?.instance_name)throw new Error("No instance linked");Re=(await Oe({data:{instanceName:St.instance_name,to:t.contacts.phone,text:U,quotedWamid:j?.external_id??void 0}}))?.wamid??null}else t.channel==="facebook"?await He({data:{conversationId:t.id,text:U}}):t.channel==="facebook_feed"&&await g({data:{conversationId:t.id,text:U,parentCommentId:j?.external_id??void 0}});t.channel!=="facebook"&&t.channel!=="facebook_feed"&&(await A.from("messages").insert({conversation_id:t.
1id,direction:"out",content:U,sender_id:s,external_id:Re,status:Re?"sent":null,quoted_message_id:j?.id??null}),await A.from("conversations").update({last_message:U,last_message_at:new Date().toISOString()}).eq("id",t.id)),z({data:{conversationId:t.id}}).catch(()=>{})}G.refetch()}catch(U){ct(U?.message??"Send failed")}finally{m(!1)}},ta=async n=>{const j=`${s}/${t.id}/${Date.now()}-${n.name.replace(/[^\w.\-]+/g,"_")}`,{error:F}=await A.storage.from("chat-uploads").upload(j,n,{upsert:!1,contentType:n.type});if(F)throw F;const{data:R,error:B}=await A.storage.from("chat-uploads").createSignedUrl(j,3600*24*365);if(B||!R?.signedUrl)throw B??new Error("Signed URL failed");return R.signedUrl},sa=n=>n.startsWith("image/")?"image":n.startsWith("video/")?"video":n.startsWith("audio/")?"audio":"document",_t=async n=>{const j=Ta(n,d?"internal":t.channel==="facebook"?"facebook":"whatsapp");if(!j.ok){C.error(j.message,{duration:8e3});return}p(!0);try{const F=await Aa(n),R=await ta(F),B=sa(F.type);if(d)await A.from("messages").insert({conversation_id:t.id,direction:"system",content:F.name,media_url:R,media_type:B,is_internal_note:!0,sender_id:s});else if(t.channel==="whatsapp"&&t.contacts?.phone){const{data:fe}=await A.rpc("list_whatsapp_instances_public"),tt=(fe??[]).find(Re=>Re.id===t.instance_id);if(!tt?.instance_name)throw new Error("No instance linked");const ct=B==="audio"&&!/^audio\/(aac|mp4|mpeg|amr|ogg)/.test(F.type)?"document":B,U=await me({data:{instanceName:tt.instance_name,to:t.contacts.phone,mediaUrl:R,mediaType:ct,fileName:F.name,caption:r||void 0}});await A.from("messages").insert({conversation_id:t.id,direction:"out",content:r||F.name,media_url:R,media_type:B,sender_id:s,external_id:U?.wamid??null,status:U?.wamid?"sent":null}),await A.from("conversations").update({last_message:`[${B}] ${F.name}`,last_message_at:new Date().toISOString()}).eq("id",t.id)}else if(t.channel==="facebook"){const fe=B==="document"?"file":B;await $e({data:{conversationId:t.id,mediaUrl:R,mediaType:fe,caption:r||void 0}})}d||z({data:{conversationId:t.id}}).catch(()=>{}),i(""),G.refetch()}catch(F){C.error(F.message)}finally{p(!1)}};return e.jsxs(e.Fragment,{children:[ue?e.jsx(ar,{onComplete:()=>ae(!1)}):null,e.jsxs("div",{className:"p-4 border-b border-border flex items-start justify-between gap-3",children:[a&&e.jsx("button",{onClick:a,title:"Back to inbox",className:"md:hidden p-2 -ml-1 rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground shrink-0",children:e.jsx(fn,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"font-semibold truncate flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:Ue(t)}),t.channel==="facebook_feed"&&e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider bg-indigo-500/15 text-indigo-500 dark:text-indigo-300 rounded px-1.5 py-0.5 shrink-0",children:t.fb_item_type==="ad"?"Ad comment":t.fb_item_type==="comment"?"Comment reply":"Post comment"})]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Te.length>0?e.jsxs("span",{className:"text-primary italic",children:[Te.map(n=>n.name).join(", ")," ",Te.length===1?"is":"are"," typing…"]}):Be.length>0?e.jsxs("span",{children:[e.jsx("span",{className:"inline-block size-1.5 rounded-full bg-emerald-500 mr-1.5 align-middle animate-pulse"}),Be.map(n=>n.name).join(", ")," viewing"]}):jt(t)}),e.jsx(_a,{referral:t,className:"mt-1"}),e.jsx(ao,{conv:t})]}),be&&e.jsx(Zr,{contact:t.contacts}),e.jsx(Xr,{conv:t}),ye&&e.jsx(Jr,{conv:t}),re&&e.jsx(eo,{conv:t,userId:s}),ve&&e.jsx("button",{onClick:()=>ie(n=>!n),title:"Sales copilot — sentiment, objections & draft replies",className:S("p-2 rounded-lg shrink-0",Ee?"bg-primary/20 text-primary":"bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground"),children:e.jsx(gt,{className:"size-4"})}),je&&e.jsx("button",{onClick:()=>D(!0),title:"Internal notes",className:"p-2 rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground shrink-0",children:e.jsx(pt,{className:"size-4"})}),e.jsx("button",{onClick:()=>k(!0),title:"View shared media & files",className:"hidden sm:inline-flex p-2 rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground shrink-0",children:e.jsx(zn,{className:"size-4"})}),e.jsx("button",{onClick:()=>b(!0),title:"Contact info",className:"lg:hidden p-2 rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground shrink-0",children:e.jsx(hn,{className:"size-4"})})]}),e.jsx(sn,{open:O,onOpenChange:b,children:e.jsxs(an,{side:"right",className:"w-full sm:max-w-md overflow-y-auto p-5",children:[e.jsx(nn,{className:"mb-4",children:e.jsx(rn,{children:"Contact info"})}),e.jsx(Gs,{contact:t.contacts,conv:t})]})}),t.needs_template&&t.channel==="whatsapp"&&e.jsxs("div",{className:"mx-4 mt-3 rounded-lg border border-red-500/30 bg-red-500/10 p-3 flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"text-xs",children:[e.jsx("div",{className:"font-semibold text-red-300 mb-0.5",children:"⚠️ Customer follow-up required"}),e.jsx("div",{className:"text-muted-foreground",children:"This conversation is older than 24 hours. WhatsApp requires an approved template message to continue."})]}),e.jsx("button",{onClick:()=>ee(!0),className:"shrink-0 text-xs px-3 py-1.5 rounded-lg bg-red-500/20 text-red-200 hover:bg-red-500/30 border border-red-500/30",children:"Send Template"})]}),I&&e.jsx(no,{conversationId:t.id,onClose:()=>k(!1),onImageClick:M}),E&&e.jsx(so,{conv:t,userId:s,onClose:()=>D(!1)}),v&&e.jsx(Hr,{url:v,onClose:()=>M(null)}),Qe&&e.jsx(ro,{conv:t,userId:s,onClose:()=>ee(!1)}),Le&&e.jsx(lo,{conv:t,userId:s,onClose:()=>Me(!1),onSent:()=>{G.refetch(),Me(!1)}}),e.jsxs("div",{className:"relative flex-1 min-h-0 flex flex-col",children:[e.jsx("div",{ref:V,onScroll:Vs,className:"flex-1 min-h-0 overflow-y-auto overscroll-contain p-4 space-y-2",children:G.data?.map((n,j,F)=>{const R=n.quoted_message_id?Zs.get(n.quoted_message_id):null,B=j>0?F[j-1]:null,fe=!B||!Ve(B.created_at,n.created_at);return e.jsxs("div",{children:[fe&&e.jsx("div",{className:"flex justify-center my-3",children:e.jsx("span",{className:"px-3 py-1 rounded-lg bg-muted text-muted-foreground text-[11px] font-medium shadow-sm uppercase tracking-wide",children:Qs(n.created_at)})}),e.jsxs("div",{className:S("group flex items-center gap-2",n.direction==="out"?"justify-end":n.direction==="system"?"justify-center":"justify-start"),children:[n.sender_id===s&&!n.id.startsWith("temp-")&&n.content&&e.jsx("button",{onClick:()=>Js(n),title:"Edit message",className:"opacity-0 group-hover:opacity-100 transition p-1.5 rounded-full bg-muted hover:bg-muted/70 text-muted-foreground",children:e.jsx(Dt,{className:"size-3.5"})}),n.direction==="out"&&!n.is_internal_note&&e.jsx("button",{onClick:()=>J(n),title:"Reply",className:"opacity-0 group-hover:opacity-100 transition p-1.5 rounded-full bg-muted hover:bg-muted/70 text-muted-foreground",children:e.jsx(qt,{className:"size-3.5"})}),e.jsxs("div",{className:S("px-3.5 py-2 rounded-2xl text-sm whitespace-pre-wrap",n.media_type==="audio"?"w-[min(22rem,85vw)] max-w-[85%]":"max-w-[70%]",n.is_internal_note?"bg-yellow-100 text-yellow-900 border border-yellow-300 italic dark:bg-yellow-500/15 dark:text-yellow-100 dark:border-yellow-500/30":n.direction==="out"?"bg-gradient-primary text-primary-foreground":n.direction==="system"?"bg-muted text-muted-foreground text-xs":"bg-secondary text-secondary-foreground"),children:[R&&e.jsxs("div",{className:S("mb-1.5 pl-2 border-l-2 rounded-sm px-2 py-1 text-[11px] opacity-90",n.direction==="out"?"border-white/60 bg-white/10":"border-primary bg-background/40"),children:[e.jsx("div",{className:"font-semibold opacity-80 mb-0.5",children:R.direction==="out"?"You":t.contacts?.name??"Customer"}),e.jsxs("div",{className:"truncate max-w-[260px]",children:[e.jsx(Ke,{text:R.content}),!R.content&&(R.media_type?`[${R.media_type}]`:"")]})]}),e.jsx(Kr,{url:n.media_url,type:n.media_type,onImageClick:M,content:n.content}),n.content&&!["reaction","location","order","product"].includes(n.media_type??"")&&e.jsx("div",{children:e.jsx(Ke,{text:Hs(n.content)})}
1),(n.direction==="out"||n.is_internal_note)&&n.sender_id&&e.jsx("div",{className:"text-[10px] opacity-70 mt-1",children:n.sender_id===s?"You":Pe.get(n.sender_id)??"Teammate"}),n.direction==="out"&&!n.is_internal_note&&e.jsxs("div",{className:"flex items-center justify-end gap-1 mt-1 text-[10px] opacity-80",children:[n.edited_at&&e.jsx("span",{className:"italic",children:"edited"}),e.jsx("span",{children:new Date(n.created_at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),e.jsx(Fr,{status:n.status,error:n.error_message})]}),n.direction!=="out"&&n.edited_at&&e.jsx("div",{className:"text-right text-[10px] opacity-60 mt-0.5 italic",children:"edited"}),n.direction==="in"&&!n.is_internal_note&&e.jsx("div",{className:"text-right text-[10px] opacity-60 mt-1",children:new Date(n.created_at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),n.direction!=="out"&&n.direction!=="system"&&!n.is_internal_note&&e.jsx("button",{onClick:()=>J(n),title:"Reply",className:"opacity-0 group-hover:opacity-100 transition p-1.5 rounded-full bg-muted hover:bg-muted/70 text-muted-foreground",children:e.jsx(qt,{className:"size-3.5"})})]})]},n.id)})}),!ce&&e.jsx("button",{onClick:()=>{const n=V.current;n&&n.scrollTo({top:n.scrollHeight,behavior:"smooth"})},title:"Scroll to latest",className:"absolute bottom-4 right-4 size-10 rounded-full bg-card border border-border shadow-lg flex items-center justify-center hover:bg-muted",children:e.jsx(Ht,{className:"size-5"})})]}),Ee&&ve&&e.jsx(Er,{conversationId:t.id,channel:t.channel??null,signal:(G.data??[]).length?`${(G.data??[]).length}-${(G.data??[])[(G.data??[]).length-1]?.id}`:"empty",onInsert:n=>{i(n),setTimeout(()=>Z.current?.focus(),0)},onClose:()=>ie(!1)}),xe||je?e.jsxs("div",{className:S("p-3 border-t border-border relative",d&&"bg-yellow-50 dark:bg-yellow-500/5"),children:[Ae&&Ae.matches.length>0&&e.jsxs("div",{className:"absolute bottom-full left-3 right-3 mb-2 glass rounded-xl overflow-hidden shadow-2xl border border-border z-10",children:[e.jsx("div",{className:"px-3 py-1.5 text-[10px] uppercase tracking-wider text-muted-foreground border-b border-border",children:"Snippets"}),Ae.matches.map(n=>e.jsxs("button",{onClick:()=>Nt(n),className:"w-full text-left px-3 py-2 hover:bg-sidebar-accent/60 transition flex flex-col gap-0.5",children:[e.jsxs("span",{className:"text-xs font-mono text-primary",children:["/",n.shortcut]}),e.jsx("span",{className:"text-xs text-muted-foreground truncate",children:n.body})]},n.id))]}),ze&&ze.items.length>0&&e.jsxs("div",{className:"absolute bottom-full left-3 right-3 mb-2 glass rounded-xl overflow-hidden shadow-2xl border border-border z-10",children:[e.jsx("div",{className:"px-3 py-1.5 text-[10px] uppercase tracking-wider text-muted-foreground border-b border-border",children:"Mention teammate"}),ze.items.map(n=>e.jsxs("button",{onClick:()=>wt(n),className:"w-full text-left px-3 py-2 hover:bg-sidebar-accent/60 transition flex items-center gap-2",children:[e.jsx("span",{className:"size-6 rounded-full bg-primary/20 text-primary text-[10px] font-semibold flex items-center justify-center",children:et(n).slice(0,1).toUpperCase()}),e.jsx("span",{className:"flex flex-col",children:e.jsxs("span",{className:"text-xs font-medium",children:["@",et(n)]})})]},n.id))]}),N&&e.jsx("div",{className:"absolute bottom-full left-3 mb-2 z-20",children:e.jsx(Sa,{theme:Ma.DARK,onEmojiClick:n=>{i(j=>j+n.emoji),y(!1),Z.current?.focus()}})}),L&&e.jsxs("div",{className:"mb-2 flex items-start gap-2 rounded-lg border border-primary/40 bg-primary/10 px-3 py-2",children:[e.jsx("div",{className:"w-1 self-stretch rounded bg-primary"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-primary font-semibold",children:["Replying to ",L.direction==="out"?"yourself":t.contacts?.name??"Customer"]}),e.jsxs("div",{className:"text-xs text-foreground/80 truncate",children:[e.jsx(Ke,{text:L.content}),!L.content&&(L.media_type?`[${L.media_type}]`:"")]})]}),e.jsx("button",{onClick:()=>J(null),className:"p-1 rounded hover:bg-muted text-muted-foreground",children:e.jsx(se,{className:"size-3.5"})})]}),W&&e.jsxs("div",{className:"mb-2 flex items-start gap-2 rounded-lg border border-amber-400/50 bg-amber-400/10 px-3 py-2",children:[e.jsx(Dt,{className:"size-3.5 mt-0.5 text-amber-500 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-amber-500 font-semibold",children:"Editing message"}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Press Enter to save. This fixes the text in your inbox history — the copy already delivered to the customer can't be changed."})]}),e.jsx("button",{onClick:kt,title:"Cancel edit",className:"p-1 rounded hover:bg-muted text-muted-foreground",children:e.jsx(se,{className:"size-3.5"})})]}),!d&&!W&&de&&(K?.completion||De)&&e.jsx("div",{className:"mb-2 rounded-lg border border-primary/30 bg-primary/5 px-3 py-2",children:De&&!K?.completion?e.jsxs("div",{className:"text-[11px] text-muted-foreground flex items-center gap-1.5",children:[e.jsx(Ne,{className:"size-3 animate-spin"})," AI is thinking of how to finish this…"]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-primary font-semibold flex items-center gap-1.5 mb-1",children:[e.jsx(Tt,{className:"size-3"})," Suggested ending · press Tab"]}),e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:K.forDraft}),e.jsx("span",{className:"text-primary font-medium",children:K.completion})]}),e.jsxs("div",{className:"mt-2 flex gap-1.5",children:[e.jsx("button",{onClick:()=>dt("append"),className:"text-[11px] px-2 py-1 rounded-lg bg-primary/15 text-primary hover:bg-primary/25",children:"Accept"}),K.full&&K.full!==K.forDraft+K.completion&&e.jsxs("button",{onClick:()=>dt("polish"),className:"text-[11px] px-2 py-1 rounded-lg bg-muted text-muted-foreground hover:text-foreground inline-flex items-center gap-1",children:[e.jsx(Ln,{className:"size-3"})," Use polished version"]}),e.jsx("button",{onClick:()=>te(null),className:"text-[11px] px-2 py-1 rounded-lg bg-muted text-muted-foreground hover:text-foreground",children:"Dismiss"})]})]})}),e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[je&&e.jsxs("button",{onClick:()=>c(!d),className:S("text-xs px-2 py-1 rounded flex items-center gap-1.5 transition",d?"bg-yellow-200 text-yellow-900 dark:bg-yellow-500/20 dark:text-yellow-300":"bg-muted text-muted-foreground hover:text-foreground"),children:[e.jsx(pt,{className:"size-3"})," Internal note"]}),ve&&xe&&e.jsxs("button",{onClick:()=>{Fe(n=>!n),te(null)},title:de?"AI writing help on — it suggests how to finish your message":"AI writing help off",className:S("text-xs px-2 py-1 rounded flex items-center gap-1.5 transition",de?"bg-primary/15 text-primary":"bg-muted text-muted-foreground hover:text-foreground"),children:[e.jsx(Tt,{className:"size-3"})," AI help"]}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["Type ",e.jsx("kbd",{className:"px-1 rounded bg-muted",children:"/"})," for Snippets",d&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("kbd",{className:"px-1 rounded bg-muted",children:"@"})," to mention"]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("input",{ref:Xe,type:"file",className:"hidden",accept:"image/*,video/*,audio/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.zip,.webp",onChange:n=>{const j=n.target.files?.[0];j&&_t(j),n.currentTarget.value=""}}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx("textarea",{ref:Z,value:r,rows:2,onChange:n=>{i(n.target.value),d||(ot(),Y())},onKeyDown:n=>{if(ze&&ze.items[0]&&(n.key==="Tab"||n.key==="Enter")){n.preventDefault(),wt(ze.items[0]);return}if(n.key==="Tab"&&Ae&&Ae.matches[0]){n.preventDefault(),Nt(Ae.matches[0]);return}if(n.key==="Tab"&&K?.completion&&K.forDraft===r){n.preventDefault(),dt("append");return}if(n.key==="Escape"&&K){n.preventDefault(),te(null);return}if(n.key==="Escape"&&W){n.preventDefault(),kt();return}n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),Ct())},placeholder:W?"Fix your message…":d?"Private team note — type @ to mention someone…":"Type a message…",style:{resize:"none"},className:S("flex-1 min-w-0 px-3 py-3 rounded-lg bg-input border border-border focus:border-primary outline-none text-sm min-h-[72px] max-h-[200px]",d&&"bg-yellow-50 border-yellow-300 dark:bg-yellow-500/10 dark:border-yellow-500/30",W&&"border-amber-400/60")}),e.jsx("button",{onClick:Ct,disabled:x,"aria-label":W?"Save edit":"Send",className:"shrink-0 h-[72px] w-12 grid place-items-center rounded-lg bg-gradient-primary text-primary-foreground glow-primary disabled:opacity-50",children:W?e.jsx(ht,{className:"size-5"}):e.jsx(Wt,{className:"size-5"})})]}),e.jsxs("div",{className:"flex gap-1.5 items-center overflow-x-auto -mx-1 px-1 pb-1",children:[e.jsx("button",{onClick:()=>Xe.current?.click(),disabled:h,title:"Attach file",className:"shrink-0 p-2 rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground disabled:opacity-50",children:h?e.jsx(Ne,{className:"size-4 animate-spin"}):e.jsx(gn,{className:"size-4"})}),e.jsx("button",{onClick:()=>y(n=>!n),title:"Emoji",className:"shrink-0 p-2 rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground",children:e.jsx(oa,{className:"size-4"})}),e.jsx(oo,{templates:pe.data??[],onPick:n=>{i(r+n),setTimeout(()=>
1Z.current?.focus(),0)}}),t.channel==="whatsapp"&&e.jsx("button",{onClick:()=>ee(!0),title:"WhatsApp Business templates",className:"shrink-0 p-2 rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground",children:e.jsx(Tn,{className:"size-4"})}),t.channel==="whatsapp"&&!t.needs_template&&e.jsx("button",{onClick:()=>Me(!0),title:"Store cart & payment link",className:"shrink-0 p-2 rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground",children:e.jsx(ns,{className:"size-4"})}),e.jsx(Wr,{onRecorded:n=>_t(n),disabled:h||x})]})]})]}):e.jsx("div",{className:"border-t border-border p-3 text-center text-xs text-muted-foreground",children:"You can read this chat, but you do not have permission to send messages or notes."})]})}const Br={"[reaction]":"👍 Reacted to a message","[unsupported]":"⚠️ Unsupported message type","[sticker]":"🎨 Sticker","[contacts]":"👤 Shared a contact","[location]":"📍 Shared a location","[ephemeral]":"⏳ Disappearing message"};function Hs(t){return Br[t.trim().toLowerCase()]??t}function Kr({url:t,type:s,onImageClick:a,content:r}){if(!t&&!s)return null;const i=s??"";return i==="location"?e.jsx("div",{className:"mb-1 rounded-lg overflow-hidden border border-border/40",children:e.jsxs("a",{href:r?Ur(r):"#",target:"_blank",rel:"noreferrer",className:"block",children:[e.jsx("div",{className:"h-28 bg-gradient-to-br from-emerald-500/20 to-sky-500/20 grid place-items-center",children:e.jsx(Pn,{className:"size-8 text-emerald-400"})}),r&&e.jsx("div",{className:"px-3 py-2 text-xs whitespace-pre-wrap",children:r.replace(/^📍\s*/,"")})]})}):i==="order"||i==="product"?e.jsxs("div",{className:"mb-1 rounded-lg border border-border/40 p-3 bg-muted/30",children:[r&&e.jsx("div",{className:"text-sm whitespace-pre-wrap",children:e.jsx(Ke,{text:r})}),t&&e.jsx("img",{src:t,alt:"",className:"mt-2 max-h-40 rounded-lg object-contain"})]}):i==="reaction"?e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-3xl leading-none",children:r||"👍"}),e.jsx("span",{className:"text-[10px] opacity-70",children:"reacted"})]}):i==="sticker"?t?e.jsx("img",{src:t,alt:"sticker",className:"max-h-40 max-w-40 object-contain"}):e.jsx("div",{className:"text-sm opacity-80",children:"🎨 Sticker"}):i==="image"?e.jsx("button",{type:"button",onClick:()=>a?.(t),className:"block",children:e.jsx("img",{src:t??"",alt:"",className:"max-h-64 rounded-lg mb-1 object-contain cursor-zoom-in hover:opacity-90 transition"})}):i==="video"?e.jsx("video",{src:t??void 0,controls:!0,className:"max-h-64 rounded-lg mb-1"}):i==="audio"?e.jsx(Qr,{url:t}):t?e.jsxs("a",{href:t,target:"_blank",rel:"noreferrer",className:"flex items-center gap-2 underline text-xs mb-1",children:[e.jsx(Gt,{className:"size-4"})," ",e.jsx("span",{children:"Download file"})," ",e.jsx(rt,{className:"size-3"})]}):null}function Ur(t){const s=t.match(/(-?\d+\.\d+),\s*(-?\d+\.\d+)/);return s?`https://maps.google.com/?q=${s[1]},${s[2]}`:"https://maps.google.com"}function Qr({url:t}){return e.jsxs("div",{className:"mb-1 w-full min-w-64 space-y-1",children:[e.jsx("audio",{src:t,controls:!0,preload:"metadata",className:"w-full min-w-64"}),e.jsx("div",{className:"flex justify-end gap-2 text-[10px] opacity-80",children:e.jsxs("a",{href:t,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 underline",children:["Open ",e.jsx(rt,{className:"size-3"})]})})]})}function Hr({url:t,onClose:s}){return o.useEffect(()=>{const a=r=>{r.key==="Escape"&&s()};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[s]),e.jsxs("div",{className:"fixed inset-0 z-[60] bg-black/90 backdrop-blur-sm flex items-center justify-center p-4",onClick:s,children:[e.jsx("button",{onClick:s,className:"absolute top-4 right-4 p-2 rounded-full bg-white/10 hover:bg-white/20 text-white",children:e.jsx(se,{className:"size-5"})}),e.jsx("a",{href:t,target:"_blank",rel:"noreferrer",download:!0,className:"absolute top-4 right-16 p-2 rounded-full bg-white/10 hover:bg-white/20 text-white",onClick:a=>a.stopPropagation(),children:e.jsx(rt,{className:"size-5"})}),e.jsx("img",{src:t,alt:"",onClick:a=>a.stopPropagation(),className:"max-h-[90vh] max-w-[95vw] object-contain rounded-lg shadow-2xl"})]})}function Wr({onRecorded:t,disabled:s}
1){const[a,r]=o.useState(!1),[i,d]=o.useState(0),[c,l]=o.useState(!1),u=o.useRef(null),x=o.useRef([]),m=o.useRef(null),h=async()=>{if(!s)try{const y=await navigator.mediaDevices.getUserMedia({audio:!0}),k=["audio/webm;codecs=opus","audio/webm","audio/mp4","audio/ogg;codecs=opus","audio/ogg"].find(D=>MediaRecorder.isTypeSupported(D))??"",E=new MediaRecorder(y,k?{mimeType:k}:void 0);x.current=[],E.ondataavailable=D=>{D.data.size&&x.current.push(D.data)},E.onstop=async()=>{y.getTracks().forEach(D=>D.stop()),l(!0);try{const D=E.mimeType||k||"audio/webm",O=new Blob(x.current,{type:D}),b=await Gr(O);await t(b)}catch(D){C.error(D.message??"Could not prepare voice note")}finally{l(!1)}},E.start(),u.current=E,r(!0),d(0),m.current=window.setInterval(()=>d(D=>D+1),1e3)}catch(y){C.error(y.message??"Microphone permission denied")}},p=()=>{u.current?.stop(),u.current=null,r(!1),m.current&&(clearInterval(m.current),m.current=null)},N=y=>`${Math.floor(y/60)}:${(y%60).toString().padStart(2,"0")}`;return a?e.jsxs("button",{onClick:p,title:"Stop recording",className:"px-2.5 py-2 rounded-lg bg-red-500/20 text-red-300 hover:bg-red-500/30 flex items-center gap-1.5",children:[e.jsx(qn,{
1className:"size-3.5 fill-current"})," ",e.jsx("span",{className:"text-xs tabular-nums",children:N(i)})]}):e.jsx("button",{onClick:h,disabled:s||c,title:"Record voice message",className:"p-2 rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground disabled:opacity-50",children:c?e.jsx(Ne,{className:"size-4 animate-spin"}):e.jsx(vn,{className:"size-4"})})}async function Gr(t){const s=window.AudioContext||window.webkitAudioContext;if(!s)throw new Error("Audio recording is not supported in this browser.");const a=new s;try{const r=await a.decodeAudioData(await t.arrayBuffer()),i=Yr(r),d=await da(()=>import("./lamejs-Do3B6Rdb.js"),[]),c=d.Mp3Encoder??d.default?.Mp3Encoder;if(!c)throw new Error("Voice-note encoder could not load.");const l=new c(1,r.sampleRate,64),u=[];for(let h=0;h<i.length;h+=1152){const p=l.encodeBuffer(i.subarray(h,h+1152));p.length&&u.push(p)}const x=l.flush();if(x.length&&u.push(x),!u.length)throw new Error("No voice audio was recorded.");const m=u.map(h=>{const p=new ArrayBuffer(h.byteLength);return new Uint8Array(p).set(new Uint8Array(h.buffer,h.byteOffset,h.byteLength)),p});return new File(m,`voice-${Date.now()}.mp3`,{type:"audio/mpeg"})}finally{a.close?.()}}function Yr(t){const s=new Int16Array(t.length),a=Math.max(1,t.numberOfChannels),r=Array.from({length:a},(i,d)=>t.getChannelData(d));for(let i=0;i<t.length;i++){let d=0;for(let c=0;c<a;c++)d+=r[c][i]??0;d=Math.max(-1,Math.min(1,d/a)),s[i]=d<0?d*32768:d*32767}return s}function Ws(t,s){const[a,r]=o.useState(t);return o.useEffect(()=>{const i=setTimeout(()=>r(t),s);return()=>clearTimeout(i)},[t,s]),a}function Gs({contact:t,conv:s}){const a=_(ya),r=_(Jt),i=_(ft),d=ge(),[c,l]=o.useState(""),u=Q({queryKey:["assignable-agents"],queryFn:()=>i()});if(!t)return null;const x=t.tags??[],m=async()=>{const N=c.trim();if(!N||x.includes(N)){l("");return}try{await a({data:{contactId:t.id,tags:[...x,N]}}),l(""),d.invalidateQueries({queryKey:["conversations"]})}catch(y){C.error(y.message)}},h=async N=>{try{await a({data:{contactId:t.id,tags:x.filter(y=>y!==N)}}),d.invalidateQueries({queryKey:["conversations"]})}catch(y){C.error(y.message)}},p=async N=>{try{await r({data:{contactId:t.id,agentId:N}}),d.invalidateQueries({queryKey:["assignment-history",t.id]}),C.success(N?"Assigned":"Unassigned"),d.invalidateQueries({queryKey:["conversations"]})}catch(y){C.error(y.message)}};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-semibold",children:t.name??Ue(s)}),e.jsx("div",{className:"text-sm text-muted-foreground",children:t.phone}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:jt(s)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground mb-2",children:"Assigned agent"}),u.isError&&e.jsxs("div",{className:"mb-2 text-xs text-red-300 bg-red-500/10 border border-red-500/20 rounded-lg px-2 py-1.5",children:["Could not load agents: ",u.error.message]}),e.jsxs("select",{value:t.assigned_agent_id??"",onChange:N=>p(N.target.value||null),className:"w-full px-2 py-2 rounded-lg bg-input border border-border text-sm",children:[e.jsx("option",{value:"",children:"— Unassigned —"}),u.data?.map(N=>e.jsx("option",{value:N.id,children:N.full_name??"Agent"},N.id))]})]}),e.jsx(Vr,{contactId:t.id}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground mb-2",children:"Tags"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[x.map(N=>e.jsxs("span",{className:"text-xs bg-primary/15 text-primary px-2 py-0.5 rounded inline-flex items-center gap-1 group",children:[N,e.jsx("button",{onClick:()=>h(N),className:"opacity-60 hover:opacity-100",children:e.jsx(se,{className:"size-3"})})]},N)),x.length===0&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"No tags yet"})]}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("input",{value:c,onChange:N=>l(N.target.value),onKeyDown:N=>N.key==="Enter"&&m(),placeholder:"Add tag…",className:"flex-1 px-2 py-1.5 rounded-lg bg-input border border-border text-xs outline-none focus:border-primary"}),e.jsx("button",{onClick:m,className:"px-2 py-1.5 rounded-lg bg-primary/20 text-primary hover:bg-primary/30",children:e.jsx(qe,{className:"size-3"})})]})]}),e.jsx(to,{conv:s}
1)]})}function Vr({contactId:t}){const s=_(va),a=Q({queryKey:["assignment-history",t],queryFn:()=>s({data:{contactId:t}})}),r=c=>{const l=new Date(c);return`${Qs(c)} · ${l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`},i=(c,l)=>{const u=(l?new Date(l).getTime():Date.now())-new Date(c).getTime(),x=Math.max(0,Math.round(u/6e4));if(x<60)return`${x}m`;const m=Math.floor(x/60);return m<24?`${m}h ${x%60}m`:`${Math.floor(m/24)}d ${m%24}h`},d=a.data??[];return e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs uppercase tracking-wider text-muted-foreground mb-2 flex items-center gap-1.5",children:[e.jsx(jn,{className:"size-3.5"})," Handover history"]}),a.isLoading&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Loading…"}),a.isError&&e.jsx("div",{className:"text-xs text-red-300",children:a.error.message}),!a.isLoading&&d.length===0&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"No handovers recorded yet."}),e.jsx("ol",{className:"space-y-2",children:d.map((c,l)=>{const u=d[l-1];return e.jsxs("li",{className:"rounded-lg border border-border bg-muted/30 px-2.5 py-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium flex-wrap",children:[e.jsx("span",{className:"text-muted-foreground",children:c.from_name??"Unassigned"}),e.jsx(wn,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"text-primary",children:c.to_name??"Unassigned"})]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground mt-0.5",children:[r(c.created_at),c.by_name&&e.jsxs(e.Fragment,{children:[" · by ",c.by_name]})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:c.to_name?e.jsxs(e.Fragment,{children:["Held ",i(c.created_at,u?.created_at??null),!u&&" (current)"]}):"Unassigned"}),c.note&&e.jsx("div",{className:"text-[11px] italic mt-1",children:c.note})]},c.id)})})]})}function Zr({contact:t}){const s=_(Jt),a=_(ft),r=ge(),[i,d]=o.useState(!1),c=Q({queryKey:["assignable-agents"],queryFn:()=>a(),enabled:i});if(!t)return null;const l=async u=>{try{await s({data:{contactId:t.id,agentId:u}}),r.invalidateQueries({queryKey:["assignment-history",t.id]}),C.success(u?"Assigned":"Unassigned"),d(!1),r.invalidateQueries({queryKey:["conversations"]})}catch(x){C.error(x.message)}};return e.jsxs("div",{className:"relative shrink-0",children:[e.jsx("button",{onClick:()=>d(u=>!u),title:"Assign chat",className:S("p-2 rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground",t.assigned_agent_id&&"text-primary bg-primary/15"),children:e.jsx(xt,{className:"size-4"})}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-30",onClick:()=>d(!1)}),e.jsxs("div",{className:"absolute right-0 top-full mt-2 z-40 w-64 glass rounded-xl border border-border shadow-xl overflow-hidden",children:[e.jsx("div",{className:"px-3 py-2 border-b border-border text-[10px] uppercase tracking-wider text-muted-foreground",children:"Assign chat"}),e.jsx("button",{onClick:()=>l(null),className:"w-full text-left px-3 py-2 text-sm hover:bg-muted/50",children:"— Unassigned —"}),c.data?.map(u=>e.jsxs("button",{onClick:()=>l(u.id),className:S("w-full text-left px-3 py-2 text-sm hover:bg-muted/50 flex items-center justify-between gap-2",t.assigned_agent_id===u.id&&"text-primary bg-primary/10"),children:[e.jsx("span",{className:"truncate",children:u.full_name??"Agent"}),e.jsx("span",{className:"text-[10px] text-muted-foreground capitalize",children:u.role})]},u.id)),c.isLoading&&e.jsx("div",{className:"px-3 py-3 text-xs text-muted-foreground",children:"Loading agents…"}),c.isError&&e.jsx("div",{className:"px-3 py-3 text-xs text-red-300",children:c.error.message})]})]})]})}function Xr({conv:t}){const s=ge(),a=_(ba),[r,i]=o.useState(!1),d=(t.channel??"").toLowerCase()==="facebook",c=Q({queryKey:["fb-otn",t.id],queryFn:async()=>{const{data:u}=await A.from("fb_otn_tokens").select("id").eq("conversation_id",t.id).is("used_at",null).limit(1);return(u?.length??0)>0},staleTime:3e4,enabled:d});if(!d)return null;const l=async()=>{const u=window.prompt("What should we ask the customer? They'll see a 'Notify me' button.","Can we message you with an update?");if(u?.trim()){i(!0);try{await a({data:{conversationId:t.id,title:u.trim().slice(0,65)}}),C.success("Permission request sent — once they tap “Notify me” you can reply later"),s.invalidateQueries({queryKey:["messages",t.id]}),s.invalidateQueries({queryKey:["fb-otn",t.id]})}catch(x){C.error(x.message)}finally{i(!1)}}};return e.jsx("button",{onClick:l,disabled:r,title:c.data?"This customer allowed one message outside the 24-hour window — your next reply will use it":"Ask this customer for permission to message them later",className:S("p-2 rounded-lg shrink-0 disabled:opacity-50",c.data?"bg-emerald-500/15 hover:bg-emerald-500/25 text-emerald-500":"bg-sky-500/15 hover:bg-sky-500/25 text-sky-500 hover:text-sky-400"),children:r?e.jsx(Ne,{className:"size-4 animate-spin"}):e.jsx(Qt,{className:"size-4"})})}function Jr({conv:t}){const s=ge(),a=_(qa),[r,i]=o.useState(!1),d=(t.channel??"").toLowerCase();if(d!=="whatsapp"&&d!=="facebook")return null;const c=async()=>
1{if(confirm("Send this client a rating request now?")){i(!0);try{const l=await a({data:{conversationId:t.id}});if(l?.sent)C.success("Rating request sent"),s.invalidateQueries({queryKey:["messages",t.id]}),s.invalidateQueries({queryKey:["conversations"]});else{const u={pending:"This client already has a rating request waiting for an answer",window_closed:"WhatsApp only allows this within 24 hours of the client's last message",no_window:"The client hasn't messaged yet, so we can't send this",channel:"Rating requests only work on WhatsApp and Facebook chats"};C.error(u[l?.reason]??"Could not send the rating request")}}catch(l){C.error(l.message)}finally{i(!1)}}};return e.jsx("button",{onClick:c,disabled:r,title:"Ask this client for a rating now",className:"p-2 rounded-lg bg-amber-500/15 hover:bg-amber-500/25 text-amber-500 hover:text-amber-400 shrink-0 disabled:opacity-50",children:r?e.jsx(Ne,{className:"size-4 animate-spin"}):e.jsx(Ea,{className:"size-4"})})}function eo({conv:t,userId:s}){const a=ge(),r=_(ss),i=_(Fa),[d,c]=o.useState(!1),l=(t.status??"open")==="closed",u=async()=>{if(!(!l&&!confirm("End this chat with the client?"))){c(!0);try{const x=l?"open":"closed",{error:m}=await A.from("conversations").update({status:x}).eq("id",t.id);if(m)throw m;try{await r({data:{conversationId:t.id,eventType:l?"conversation_reopened":"conversation_closed",metadata:{by:s}}})}catch{}if(!l)try{(await i({data:{conversationId:t.id}}))?.sent&&C.success("Chat closed — rating request sent to the customer")}catch{}C.success(l?"Conversation reopened":"Conversation closed"),a.invalidateQueries({queryKey:["conversations"]})}catch(x){C.error(x.message)}finally{c(!1)}}};return e.jsx("button",{onClick:u,disabled:d,title:l?"Reopen conversation":"Close / end chat",className:S("p-2 rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground shrink-0",l&&"text-emerald-300 bg-emerald-500/15"),children:d?e.jsx(Ne,{className:"size-4 animate-spin"}):l?e.jsx(Ca,{className:"size-4"}):e.jsx(bn,{className:"size-4"})})}function to({conv:t}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground mb-2",children:"Internal notes"}),e.jsx(Ys,{conv:t,compact:!0})]})}function so({conv:t,userId:s,onClose:a}){return e.jsx("div",{className:"fixed inset-0 z-50 bg-background/70 backdrop-blur-sm flex items-center justify-center p-4",onClick:a,children:e.jsxs("div",{onClick:r=>r.stopPropagation(),className:"w-full max-w-xl max-h-[85vh] glass rounded-2xl border border-border flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"p-4 border-b border-border flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:"Internal notes"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Ue(t)})]}),e.jsx("button",{onClick:a,className:"p-1.5 rounded hover:bg-muted text-muted-foreground hover:text-foreground",children:e.jsx(se,{className:"size-4"})})]}),e.jsx("div",{className:"p-4 overflow-auto",children:e.jsx(Ys,{conv:t,userId:s})})]})})}function Ys({conv:t,userId:s,compact:a=!1}){const{user:r}=Ze(),i=s??r?.id,d=ge(),[c,l]=o.useState(""),[u,x]=o.useState(!1),m=_(ft),h=_(is),p=Q({queryKey:["internal-notes",t.id],queryFn:async()=>{const{data:k,error:E}=await A.from("messages").select("id, content, created_at, sender_id").eq("conversation_id",t.id).eq("is_internal_note",!0).order("created_at",{ascending:!1}).limit(a?5:50);if(E)throw E;return k}}),N=Q({queryKey:["assignable-agents"],queryFn:()=>m()}),y=o.useMemo(()=>{const k=new Map;for(const E of N.data??[])k.set(E.id,E.full_name?.trim()||"Agent");return k},[N.data]),I=async()=>{if(!(!c.trim()||!i)){x(!0);try{await h({data:{conversationId:t.id,content:c.trim()}}),l(""),p.refetch(),d.invalidateQueries({queryKey:["messages",t.id]})}catch(k){C.error(k.message)}finally{x(!1)}}};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("input",{value:c,onChange:k=>l(k.target.value),onKeyDown:k=>k.key==="Enter"&&I(),placeholder:"Add private note — type @ to mention a teammate…",className:"flex-1 px-2 py-1.5 rounded-lg bg-input border border-border text-xs outline-none focus:border-primary"}),e.jsx("button",{onClick:I,disabled:u||!c.trim(),className:"px-2 py-1.5 rounded-lg bg-yellow-200 text-yellow-900 hover:bg-yellow-300 dark:bg-yellow-500/20 dark:text-yellow-300 dark:hover:bg-yellow-500/30 disabled:opacity-40",children:e.jsx(qe,{className:"size-3"})})]}),e.jsxs("div",{className:S("space-y-2",a&&"max-h-52 overflow-auto pr-1"),children:[p.data?.map(k=>e.jsxs("div",{className:"rounded-lg border border-yellow-300 bg-yellow-50 px-3 py-2 dark:border-yellow-500/20 dark:bg-yellow-500/10",children:[e.jsx("div",{className:"text-xs whitespace-pre-wrap text-yellow-900 dark:text-yellow-50",children:e.jsx(Ke,{text:k.content})}),e.jsxs("div",{className:"mt-1 text-[10px] text-muted-foreground flex justify-between gap-2",children:[e.jsx("span",{className:"truncate",children:k.sender_id===i?"You"
1:k.sender_id?y.get(k.sender_id)??"Teammate":"Teammate"}),e.jsx("span",{children:new Date(k.created_at).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})})]})]},k.id)),p.isLoading&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Loading notes…"}),!p.isLoading&&(p.data?.length??0)===0&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"No internal notes yet"})]})]})}function ao({conv:t}){const{isAdmin:s}=Ze(),a=ge(),r=_(Un),i=_(Bn),d=_(Kn),[c,l]=o.useState(!1),[u,x]=o.useState(!1),[m,h]=o.useState(""),[p,N]=o.useState("#8b5cf6"),y=Q({queryKey:["conversation-tags"],queryFn:async()=>{const{data:b,error:v}=await A.from("conversation_tags").select("*").order("is_default",{ascending:!1}).order("name");if(v)throw v;return b??[]}}),I=t.tag_ids??[],k=(y.data??[]).filter(b=>I.includes(b.id)),E=async b=>{const v=I.includes(b)?I.filter(M=>M!==b):[...I,b];try{await r({data:{conversationId:t.id,tagIds:v}}),a.invalidateQueries({queryKey:["conversations"]})}catch(M){C.error(M.message)}},D=async()=>{const b=m.trim();if(b)try{await i({data:{name:b,color:p}}),h(""),y.refetch(),C.success("Tag created")}catch(v){C.error(v.message)}},O=async b=>{try{await d({data:{id:b}}),y.refetch(),a.invalidateQueries({queryKey:["conversations"]})}catch(v){C.error(v.message)}};return e.jsxs("div",{className:"mt-2 relative",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[k.map(b=>e.jsxs("button",{onClick:()=>E(b.id),className:"text-[11px] px-2 py-0.5 rounded-full inline-flex items-center gap-1 border transition hover:opacity-80",style:{backgroundColor:`${b.color}22`,color:b.color,borderColor:`${b.color}55`},children:[b.name,e.jsx(se,{className:"size-3 opacity-60"})]},b.id)),e.jsxs("button",{onClick:()=>l(b=>!b),className:"text-[11px] px-2 py-0.5 rounded-full border border-dashed border-border text-muted-foreground hover:text-foreground hover:border-primary/50 transition inline-flex items-center gap-1",children:[e.jsx(qe,{className:"size-3"})," Tag"]})]}),c&&e.jsxs("div",{className:"absolute top-full left-0 mt-2 z-20 glass rounded-xl border border-border shadow-2xl p-3 w-72",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Tag this conversation"}),e.jsx("button",{onClick:()=>l(!1),className:"text-muted-foreground hover:text-foreground",children:e.jsx(se,{className:"size-3"})})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:(y.data??[]).map(b=>{const v=I.includes(b.id);return e.jsx("button",{onClick:()=>E(b.id),className:S("text-[11px] px-2 py-0.5 rounded-full border transition",v?"ring-1 ring-offset-1 ring-offset-background":"opacity-70 hover:opacity-100"),style:{backgroundColor:v?`${b.color}33`:"transparent",color:b.color,borderColor:`${b.color}66`},children:b.name},b.id)})}),s&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>x(b=>!b),className:"mt-3 text-[11px] text-primary hover:underline",children:u?"Hide manager":"Manage tags"}),u&&e.jsxs("div",{className:"mt-2 space-y-2 border-t border-border pt-2",children:[e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("input",{value:m,onChange:b=>h(b.target.value),placeholder:"New tag name",className:"flex-1 px-2 py-1 rounded bg-input border border-border text-xs outline-none focus:border-primary"}),e.jsx("input",{type:"color",value:p,onChange:b=>N(b.target.value),className:"w-9 h-7 rounded bg-input border border-border cursor-pointer"}),e.jsx("button",{onClick:D,className:"px-2 rounded bg-primary/20 text-primary text-xs",children:e.jsx(qe,{className:"size-3"})})]}),e.jsxs("div",{className:"space-y-1 max-h-32 overflow-auto",children:[(y.data??[]).filter(b=>!b.is_default).map(b=>e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"size-2 rounded-full",style:{background:b.color}}),b.name]}),e.jsx("button",{onClick:()=>O(b.id),className:"text-muted-foreground hover:text-destructive",children:e.jsx(nt,{className:"size-3"})})]},b.id)),(y.data??[]).filter(b=>
1!b.is_default).length===0&&e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"No custom tags yet"})]})]})]})]})]})}function no({conversationId:t,onClose:s,onImageClick:a}){const[r,i]=o.useState("all"),c=(Q({queryKey:["conv-media",t],queryFn:async()=>{const{data:u,error:x}=await A.from("messages").select("id, media_url, media_type, content, created_at, direction").eq("conversation_id",t).not("media_url","is",null).order("created_at",{ascending:!1});if(x)throw x;return u}}).data??[]).filter(u=>{if(r==="all")return!0;const x=u.media_type??"";return r==="image"?x==="image"||x==="sticker":x===r}),l=[{key:"all",label:"All"},{key:"image",label:"Images"},{key:"video",label:"Videos"},{key:"audio",label:"Audio"},{key:"document",label:"Files"}];return e.jsx("div",{className:"fixed inset-0 z-40 bg-background/70 backdrop-blur-sm flex items-center justify-center p-4",onClick:s,children:e.jsxs("div",{className:"glass rounded-2xl border border-border max-w-3xl w-full max-h-[85vh] flex flex-col",onClick:u=>u.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:"Shared media & files"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[c.length," item",c.length===1?"":"s"]})]}),e.jsx("button",{onClick:s,className:"p-1.5 rounded hover:bg-muted",children:e.jsx(se,{className:"size-4"})})]}),e.jsx("div",{className:"px-4 pt-3 flex gap-1 flex-wrap",children:l.map(u=>e.jsx("button",{onClick:()=>i(u.key),className:S("text-xs px-3 py-1.5 rounded-full transition",r===u.key?"bg-primary/20 text-primary":"bg-muted text-muted-foreground hover:text-foreground"),children:u.label},u.key))}),e.jsx("div",{className:"p-4 overflow-auto",children:c.length===0?e.jsxs("div",{className:"text-center text-sm text-muted-foreground py-12",children:["No ",r==="all"?"media":r," shared in this conversation yet."]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:c.map(u=>{const x=u.media_type??"",m=x==="image"||x==="sticker",h=x==="video",p=x==="audio";return e.jsxs("div",{className:"group block rounded-lg overflow-hidden border border-border bg-background/60 hover:border-primary transition",children:[e.jsxs("div",{className:"aspect-square bg-muted flex items-center justify-center",children:[m&&e.jsx("button",{type:"button",onClick:()=>a?.(u.media_url),className:"w-full h-full",children:e.jsx("img",{src:u.media_url,alt:"",className:"w-full h-full object-cover cursor-zoom-in",loading:"lazy"})}),h&&e.jsx("video",{src:u.media_url,controls:!0,className:"w-full h-full object-cover"}),p&&e.jsx("div",{className:"p-3 w-full",children:e.jsx("audio",{src:u.media_url,controls:!0,className:"w-full"})}),!m&&!h&&!p&&e.jsxs("a",{href:u.media_url,target:"_blank",rel:"noreferrer",className:"flex flex-col items-center gap-1 text-muted-foreground p-3 text-center",children:[e.jsx(Gt,{className:"size-8"}),e.jsx("span",{className:"text-[10px] truncate w-full",children:u.content??"file"})]})]}),e.jsxs("div",{className:"px-2 py-1.5 text-[10px] text-muted-foreground flex items-center justify-between gap-1",children:[e.jsx("span",{className:"truncate",children:new Date(u.created_at).toLocaleDateString()}),e.jsx("a",{href:u.media_url,target:"_blank",rel:"noreferrer",download:!0,className:"opacity-0 group-hover:opacity-100 transition",children:e.jsx(rt,{className:"size-3"})})]})]},u.id)})})})]})})}function ro({conv:t,userId:s,onClose:a}){const r=_(Vt),i=_(fa),d=_(Xt),[c,l]=o.useState(null),[u,x]=o.useState(null),[m,h]=o.useState([]),[p,N]=o.useState(!1);o.useEffect(()=>{(async()=>{if(!t.instance_id)return;const{data:b}=await A.rpc("list_whatsapp_instances_public"),v=(b??[]).find(M=>M.id===t.instance_id);l(v?.instance_name??null)})()},[t.instance_id]);const y=Q({queryKey:["meta-templates-picker",c],enabled:!!c,queryFn:async()=>(await r({data:{instanceName:c}}))?.templates??[]}),I=(y.data??[]).filter(b=>(b.status??"").toUpperCase()==="APPROVED"),k=o.useMemo(()=>u?.components?.find(b=>b.type==="BODY"),[u]),E=o.useMemo(()=>{const b=k?.text??"",v=Array.from(b.matchAll(/{{\s*(\d+)\s*}}/g)).map(M=>Number(M[1]));return v.length?Math.max(...v):0},[k]);o.useEffect(()=>{h(Array(E).fill(""))},[E]);const D=o.useMemo(()=>{let b=k?.text??"";return m.forEach((v,M)=>{b=b.replaceAll(`{{${M+1}}}`,v||`{{${M+1}}}`)}),b},[k,m]),O=async()=>
1{if(!(!u||!c||!t.contacts?.phone)){if(m.some(b=>!b.trim()))return C.error("Fill all template variables");N(!0);try{const b=await i({data:{instanceName:c,to:t.contacts.phone,templateName:u.name,language:u.language,bodyParams:m}});await A.from("messages").insert({conversation_id:t.id,direction:"out",content:D,sender_id:s,external_id:b?.wamid??null,status:"sent"}),await A.from("conversations").update({last_message:D,last_message_at:new Date().toISOString()}).eq("id",t.id),d({data:{conversationId:t.id}}).catch(()=>{}),C.success("Template sent"),a()}catch(b){C.error(b.message??"Send failed")}finally{N(!1)}}};return e.jsx("div",{className:"fixed inset-0 z-50 bg-background/80 backdrop-blur flex items-center justify-center p-4",onClick:a,children:e.jsxs("div",{className:"glass rounded-2xl p-6 w-full max-w-xl space-y-4",onClick:b=>b.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"font-semibold",children:"Send WhatsApp template"}),e.jsx("button",{onClick:a,children:e.jsx(se,{className:"size-4"})})]}),y.isLoading&&e.jsx("div",{className:"text-sm text-muted-foreground py-6 text-center",children:"Loading templates from Meta…"}),y.isError&&e.jsxs("div",{className:"text-xs text-red-300 bg-red-500/10 border border-red-500/20 rounded p-3",children:["Couldn't load templates: ",y.error?.message??"Unknown error"]}),y.data&&I.length===0&&e.jsx("div",{className:"text-sm text-muted-foreground py-6 text-center",children:"No approved templates on this WABA."}),!u&&I.length>0&&e.jsx("div",{className:"max-h-72 overflow-auto space-y-1",children:I.map(b=>e.jsxs("button",{onClick:()=>x(b),className:"w-full text-left p-3 rounded-lg bg-muted/40 hover:bg-muted/70 transition",children:[e.jsx("div",{className:"text-sm font-mono",children:b.name}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[b.language," • ",b.category]}),e.jsx("div",{className:"text-xs mt-1 line-clamp-2",children:b.components?.find(v=>v.type==="BODY")?.text})]},`${b.name}-${b.language}`))}),u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:[u.name," • ",u.language]}),E>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs",children:"Fill variables:"}),Array.from({length:E}).map((b,v)=>e.jsx("input",{value:m[v]??"",onChange:M=>{const L=[...m];L[v]=M.target.value,h(L)},placeholder:`{{${v+1}}}`,className:"w-full px-3 py-2 rounded-lg bg-input border border-border focus:border-primary outline-none text-sm"},v))]}),e.jsx("div",{className:"rounded-lg bg-muted/40 p-3 text-sm whitespace-pre-wrap",children:D}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{onClick:()=>x(null),className:"px-3 py-2 rounded-lg bg-muted text-sm",children:"Back"}),e.jsx("button",{onClick:O,disabled:p,className:"px-4 py-2 rounded-lg bg-gradient-primary text-primary-foreground text-sm disabled:opacity-50",children:p?"Sending…":"Send template"})]})]})]})})}function oo({templates:t,onPick:s}){const[a,r]=o.useState(!1),[i,d]=o.useState(""),c=t.filter(l=>!i||l.shortcut.toLowerCase().includes(i.toLowerCase())||l.body.toLowerCase().includes(i.toLowerCase()));return e.jsxs("div",{className:"relative",children:[e.jsx("button",{onClick:()=>r(l=>!l),title:"Saved replies (or type / in the message)",className:"p-2 rounded-lg bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground",children:e.jsx(rs,{className:"size-4"})}),a&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-30",onClick:()=>r(!1)}),e.jsxs("div",{className:"absolute bottom-full right-0 mb-2 w-80 max-h-96 glass rounded-xl border border-border shadow-xl z-40 overflow-hidden flex flex-col",children:[e.jsx("div",{className:"p-2 border-b border-border",children:e.jsx("input",{autoFocus:!0,value:i,onChange:l=>d(l.target.value),placeholder:"Search saved replies…",className:"w-full px-2 py-1.5 text-xs bg-input rounded outline-none"})}),e.jsxs("div",{className:"overflow-y-auto flex-1",children:[t.length===0&&e.jsx("div",{className:"p-6 text-center text-xs text-muted-foreground",children:"No saved replies. Add some in Templates."}),t.length>0&&c.length===0&&e.jsx("div",{className:"p-6 text-center text-xs text-muted-foreground",children:"No matches."}),c.map(l=>e.jsxs("button",{onClick:()=>{s(l.body),r(!1),d("")},className:"w-full text-left px-3 py-2 hover:bg-muted/50 border-b border-border/40 last:border-0",children:[e.jsxs("div",{className:"text-xs font-mono text-primary",children:["/",l.shortcut]}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:l.body})]},l.id))]}),e.jsxs("div",{className:"p-2 border-t border-border text-[10px] text-muted-foreground text-center",children:["Tip: type ",e.jsx("kbd",{className:"font-mono bg-muted px-1 rounded",children:"/shortcut"})," in the message"]})]})]})]})}function io({onClose:t}){const{isAdmin:s}=Ze(),a=ge(),r=_(Vt),i=_(pa),[d,c]=o.useState(null),[l,u]=o.useState(null),[x,m]=o.useState([]),[h,p]=o.use
1State(""),[N,y]=o.useState(!1),[I,k]=o.useState(null),E=Q({queryKey:["wa-instances-public"],queryFn:async()=>{const{data:v}=await A.rpc("list_whatsapp_instances_public");return v??[]}}),D=Q({queryKey:["meta-templates",d],enabled:!!d,queryFn:async()=>(await r({data:{instanceName:d}}))?.templates??[]}),O=(D.data??[]).filter(v=>(v.status??"").toUpperCase()==="APPROVED");o.useEffect(()=>{if(l){const v=l.components?.find(L=>L.type==="BODY"),M=v?.text?[...v.text.matchAll(/{{\s*(\d+)\s*}}/g)].map(L=>Number(L[1])):[];m(Array(M.length?Math.max(...M):0).fill(""))}},[l]);const b=async()=>{if(!d||!l)return;const v=h.split(/[\n,\s]+/).map(M=>M.trim()).filter(M=>/^\d{6,}$/.test(M));if(v.length===0)return C.error("Enter at least one valid phone number");y(!0),k(null);try{const M=await i({data:{instanceName:d,templateName:l.name,language:l.language,...x.some(L=>L.trim())?{bodyParams:x}:{},recipients:v.map(L=>({to:L}))}});k({sent:M.sent,failed:M.failed,total:M.total}),C.success(`Broadcast complete: ${M.sent} sent, ${M.failed} failed`),a.invalidateQueries({queryKey:["conversations"]})}catch(M){C.error(M.message)}finally{y(!1)}};return s?e.jsx("div",{className:"fixed inset-0 z-50 bg-background/80 backdrop-blur flex items-center justify-center p-4",onClick:t,children:e.jsxs("div",{className:"glass rounded-2xl p-6 w-full max-w-lg space-y-4 max-h-[85vh] overflow-auto",onClick:v=>v.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(ts,{className:"size-5"})," Broadcast template"]}),e.jsx("button",{onClick:t,children:e.jsx(se,{className:"size-4"})})]}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Select a WhatsApp number:"}),(E.data??[]).map(v=>e.jsxs("button",{onClick:()=>c(v.instance_name),className:"w-full text-left p-3 rounded-lg bg-muted/40 hover:bg-muted/70 flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:v.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:v.phone_number??""})]},v.id))]}),d&&!l&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Pick an approved template:"}),e.jsx("button",{onClick:()=>c(null),className:"text-xs text-primary hover:underline",children:"← Change number"})]}),D.isLoading&&e.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center",children:"Loading…"}),O.length===0&&!D.isLoading&&e.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center",children:"No approved templates."}),e.jsx("div",{className:"max-h-60 overflow-auto space-y-1",children:O.map(v=>e.jsxs("button",{onClick:()=>u(v),className:"w-full text-left p-3 rounded-lg bg-muted/40 hover:bg-muted/70",children:[e.jsx("div",{className:"text-sm font-mono",children:v.name}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[v.language," • ",v.category]})]},`${v.name}-${v.language}`))})]}),d&&l&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-sm font-mono",children:l.name}),e.jsx("button",{onClick:()=>u(null),className:"text-xs text-primary hover:underline",children:"← Change template"})]}),x.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Template variables (applied to all recipients):"}),x.map((v,M)=>e.jsx("input",{value:v,onChange:L=>{const J=[...x];J[M]=L.target.value,m(J)},placeholder:`{{${M+1}}}`,className:"w-full px-3 py-2 rounded-lg bg-input border border-border text-sm outline-none focus:border-primary"},M))]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Recipients (one per line or comma-separated):"}),e.jsx("textarea",{value:h,onChange:v=>p(v.target.value),rows:5,placeholder:`27123456789
2279876543210`,className:"w-full px-3 py-2 rounded-lg bg-input border border-border text-sm outline-none focus:border-primary resize-none font-mono"})]}),I&&e.jsxs("div",{className:"rounded-lg bg-muted/40 p-3 text-sm text-center",children:["Sent: ",e.jsx("span",{className:"font-semibold text-emerald-400",children:I.sent})," · Failed: ",e.jsx("span",{className:"font-semibold text-red-400",children:I.failed})," · Total: ",I.total]}),e.jsx("button",{onClick:b,disabled:N,className:"w-full py-2.5 rounded-lg bg-gradient-primary text-primary-foreground text-sm font-medium disabled:opacity-50",children:N?"Sending broadcast…":"Send broadcast"})]})]})}):null}function lo({conv:t,userId:s,onClose:a,onSent:r}
2){const[i,d]=o.useState(""),[c,l]=o.useState(""),[u,x]=o.useState(""),[m,h]=o.useState([]),[p,N]=o.useState(0),[y,I]=o.useState(0),[k,E]=o.useState(""),[D,O]=o.useState(""),[b,v]=o.useState(!1),[M,L]=o.useState(""),[J,W]=o.useState(""),[H,ce]=o.useState("1"),_e=_(ca),Qe=_(ua),ee=_(ma),Ee=_(Yt),ie=_(Zt),ue=Q({queryKey:["agent-stores"],queryFn:async()=>{const{data:g,error:T}=await A.rpc("list_stores_public");if(T)throw new Error(T.message);return g??[]}});o.useEffect(()=>{!i&&ue.data?.length&&d(ue.data[0].id)},[ue.data,i]);const ae=Q({queryKey:["store-products",i,u],queryFn:()=>_e({data:{storeId:i,q:u||void 0}}),enabled:!!i}),Se=ue.data?.find(g=>g.id===i)?.currency??"ZAR",de=m.reduce((g,T)=>g+T.unit_price_cents*T.qty,0),Fe=m.reduce((g,T)=>g+T.qty,0),K=Math.round((Number(k)||0)*100),te=Math.min(de,Math.round(de*y/100)+K),De=Math.round((de-te)*(1+p/100)),le=g=>`${Se} ${(g/100).toFixed(2)}`,[Le,Me]=o.useState({}),Oe=o.useMemo(()=>{const g=ae.data??[],T=new Map,$=[];for(const z of g){if(String(z.id).includes(":"))continue;const P={...z,variations:[]};T.set(String(z.id),P),$.push(P)}for(const z of g){const P=String(z.id);if(!P.includes(":"))continue;const V=T.get(P.split(":")[0]);V?V.variations.push(z):$.push({...z,variations:[]})}return $},[ae.data]),me=g=>{i&&g?.id&&Qe({data:{storeId:i,productId:String(g.id),name:String(g.name??"")}}).catch(()=>{}),h(T=>{const $=T.findIndex(z=>z.external_product_id===String(g.id));if($>=0){const z=[...T];return z[$]={...z[$],qty:z[$].qty+1},z}return[...T,{external_product_id:String(g.id),name:g.name,qty:1,unit_price_cents:g.price_cents,image_url:g.image_url,sku:g.sku}]})},He=()=>{const g=M.trim(),T=Math.round((Number(J)||0)*100);if(!g||T<=0){C.error("Add a product name and a price");return}h($=>[...$,{external_product_id:null,name:g,qty:Math.max(1,Number(H)||1),unit_price_cents:T,image_url:null,sku:null}]),L(""),W(""),ce("1")},$e=async()=>{if(!(!i||m.length===0)){v(!0);try{const g=await ee({data:{conversationId:t.id,storeId:i,title:"Your cart",notes:D||void 0,taxPct:p,discountPct:y,discountCents:K,origin:window.location.origin,items:m}}),T=`🛒 Here is your cart from ${g.storeName||"our store"} — ${Se} ${(g.total_cents/100).toFixed(2)}.
3Approve and pay securely here:
4${g.url}`;let $=null;if(t.channel==="whatsapp"&&t.contacts?.phone){const{data:z}=await A.rpc("list_whatsapp_instances_public"),P=(z??[]).find(Z=>Z.id===t.instance_id);if(!P?.instance_name)throw new Error("No instance linked");$=(await Ee({data:{instanceName:P.instance_name,to:t.contacts.phone,text:T}}))?.wamid??null}else t.channel==="facebook"&&await ie({data:{conversationId:t.id,text:T}});t.channel!=="facebook"&&t.channel!=="facebook_feed"&&(await A.from("messages").insert({conversation_id:t.id,direction:"out",content:T,sender_id:s,external_id:$,status:$?"sent":null}),await A.from("conversations").update({last_message:"🛒 Cart sent for approval",last_message_at:new Date().toISOString()}).eq("id",t.id)),C.success("Cart sent for approval"),r()}catch(g){C.error(g?.message??"Could not send the cart")}finally{v(!1)}}};return e.jsx("div",{className:"fixed inset-0 z-50 bg-background/80 backdrop-blur-sm grid place-items-center p-4",onClick:a,children:e.jsxs("div",{className:"w-full max-w-3xl max-h-[88vh] overflow-hidden flex flex-col glass rounded-2xl border border-border shadow-2xl",onClick:g=>g.stopPropagation(),children:[e.jsxs("div",{className:"p-4 border-b border-border flex items-center justify-between gap-2",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(ns,{className:"size-5"})," Store cart"]}),e.jsx("button",{onClick:a,className:"p-2 rounded-lg hover:bg-muted/60",children:e.jsx(se,{className:"size-4"})})]}),e.jsx("div",{className:"p-4 space-y-3 overflow-y-auto",children:ue.isLoading?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading stores…"}):(ue.data??[]).length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No stores connected yet. An admin can add them in Settings → Stores."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:(ue.data??[]).map(g=>e.jsx("button",{onClick:()=>{d(g.id),h(T=>T.filter($=>!$.external_product_id))},className:`px-3 py-1.5 rounded-lg text-sm border ${i===g.id?"bg-primary text-primary-foreground border-transparent":"border-border hover:bg-muted/50"}`,children:g.name},g.id))}),e.jsxs("form",{onSubmit:g=>{g.preventDefault(),x(c.trim())},className:"flex gap-2",children:[e.jsx("input",{value:c,onChange:g=>l(g.target.value),placeholder:"Search products in this store…",className:"flex-1 bg-muted/50 rounded-lg px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-primary"}),e.jsx("button",{type:"submit",className:"px-3 py-2 rounded-lg bg-muted hover:bg-muted/70 text-sm",children:"Search"})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-2",children:[ae.isLoading&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading products…"}),ae.isError&&e.jsx("p",{className:"text-sm text-destructive",children:ae.error?.message}),Oe.map(g=>{const T=g.variations??[];if(T.length){const $=Le[g.id]??T[0].id,z=T.find(P=>P.id===$)??T[0];return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-border",children:[g.image_url?e.jsx("img",{src:g.image_url,alt:g.name,className:"size-10 rounded object-cover bg-muted shrink-0"}):e.jsx("div",{className:"size-10 rounded bg-muted shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:g.name}),e.jsx("select",{value:z.id,onChange:P=>Me(V=>({...V,[g.id]:P.target.value})),className:"w-full bg-muted/50 rounded-lg px-2 py-1 text-xs outline-none focus:ring-1 focus:ring-primary",children:T.map(P=>e.jsxs("option",{value:P.id,children:[P.name.includes(" — ")?P.name.split(" — ").slice(1).join(" — "):P.name," — ",le(P.price_cents),P.stock_status&&P.stock_status!=="instock"?" (out of stock)":""]},P.id))})]}),e.jsx("button",{type:"button",onClick:()=>me(z),className:"p-2 rounded-lg hover:bg-muted/60 shrink-0",title:"Add option",children:e.jsx(qe,{className:"size-4 text-muted-foreground"})})]},g.id)}return e.jsxs("button",{onClick:()=>me(g),className:"flex items-center gap-2 p-2 rounded-lg border border-border text-left hover:bg-muted/40",children:[g.image_url?e.jsx("img",{src:g.image_url,alt:g.name,className:"size-10 rounded object-cover bg-muted shrink-0"}):e.jsx("div",{className:"size-10 rounded bg-muted shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:g.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[le(g.price_cents),g.stock_status&&g.stock_status!=="instock"?" • out of stock":""]})]}),e.jsx(qe,{className:"size-4 text-muted-foreground shrink-0"})]},g.id)})]}),e.jsxs("div",{className:"rounded-xl border border-dashed border-border p-3 space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"Custom product"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("input",{value:M,onChange:g=>L(g.target.value),placeholder:"Product / service name",className:"flex-1 min-w-[160px] bg-muted/50 rounded-lg px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-primary"}),e.jsx("input",{value:J,onChange:g=>W(g.target.value),inputMode:"decimal",placeholder:`Price (${Se})`,className:"w-32 bg-muted/50 rounded-lg px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-primary"}),e.jsx("input",{value:H,onChange:g=>ce(g.target.value),inputMode:"numeric",placeholder:"Qty",className:"w-20 bg-muted/50 rounded-lg px-3 py-2 text-sm text-center outline-none focus:ring-1 focus:ring-primary"}),e.jsxs("button",{type:"button",onClick:He,className:"px-3 py-2 rounded-lg bg-muted hover:bg-muted/70 text-sm flex items-center gap-1",children:[e.jsx(qe,{className:"size-4"})," Add"]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Custom items aren't sent to the store — the client just approves and pays them via Yoco."})]}),m.length>0&&e.jsx("div",{className:"rounded-xl border border-border divide-y divide-border",children:m.map((g,T)=>e.jsxs("div",{className:"flex items-center gap-2 p-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:g.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[le(g.unit_price_cents)," each"]})]}),e.jsx("input",{type:"number",min:1,value:g.qty,onChange:$=>h(z=>z.map((P,V)=>V===T?{...P,qty:Math.max(1,Number($.target.value)||1)}:P)),className:"w-16 bg-muted/50 rounded px-2 py-1 text-sm text-center outline-none"}),e.jsx("p",{className:"w-24 text-right text-sm font-semibold",children:le(g.unit_price_cents*g.qty)}),e.jsx("button",{onClick:()=>h($=>$.filter((z,P)=>P!==T)),className:"p-1.5 rounded hover:bg-muted/60 text-muted-foreground",children:e.jsx(nt,{className:"size-4"})})]},T))}),m.length>0&&e.jsxs("div",{className:"rounded-xl border border-border p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm font-medium",children:"Bulk discount"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Fe," item",Fe===1?"":"s"," in cart"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[[0,5,10,15,20].map(g=>e.jsx("button",{type:"button",onClick:()=>I(g),className:`px-2.5 py-1 rounded-lg text-xs border ${y===g?"bg-primary text-primary-foreground border-transparent":"border-border text-muted-foreground hover:bg-muted/60"}`,children:g===0?"None":`${g}%`},g)),e.jsxs("label",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:["%",e.jsx("input",{type:"number",min:0,max:100,value:y,onChange:g=>I(Math.min(100,Math.max(0,Number(g.target.value)||0))),className:"w-16 bg-muted/50 rounded px-2 py-1 text-sm outline-none"})]}),e.jsxs("label",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:["or ",Se," off",e.jsx("input",{type:"number",min:0,step:"0.01",value:k,placeholder:"0.00",onChange:g=>E(g.target.value),className:"w-24 bg-muted/50 rounded px-2 py-1 text-sm outline-none"})]})]}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:"Subtotal"}),e.jsx("span",{children:le(de)})]}),te>0&&e.jsxs("div",{className:"flex justify-between text-xs text-emerald-600 dark:text-emerald-400 font-medium",children:[e.jsx("span",{children:"Discount"}),e.jsxs("span",{children:["-",le(te)]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("label",{className:"text-sm text-muted-foreground flex items-center gap-2",children:["Tax %",e.jsx("input",{type:"number",min:0,max:100,value:p,onChange:g=>N(Math.min(100,Math.max(0,Number(g.target.value)||0))),className:"w-20 bg-muted/50 rounded px-2 py-1 text-sm outline-none"})]}),e.jsxs("div",{className:"ml-auto text-sm",children:[e.jsx("span",{className:"text-muted-foreground mr-2",children:"Total"}),e.jsx("span",{className:"font-bold",children:le(De)}
4)]})]}),e.jsx("textarea",{value:D,onChange:g=>O(g.target.value),rows:2,placeholder:"Note for the client (optional)",className:"w-full bg-muted/50 rounded-lg px-3 py-2 text-sm outline-none resize-none"})]})}),e.jsxs("div",{className:"p-4 border-t border-border flex justify-end gap-2",children:[e.jsx("button",{onClick:a,className:"px-4 py-2 rounded-lg border border-border text-sm",children:"Cancel"}),e.jsxs("button",{onClick:$e,disabled:b||m.length===0||!i,className:"px-4 py-2 rounded-lg bg-gradient-primary text-primary-foreground text-sm font-semibold disabled:opacity-50 flex items-center gap-2",children:[b?e.jsx(Ne,{className:"size-4 animate-spin"}):e.jsx(Wt,{className:"size-4"})," Send for approval"]})]})]})})}export{ui as component,Hs as prettyBody};

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.