PageSourceSearch

https://maker-connect-secure-1.replit.app/assets/Messages2Section-CBpBCptJ.js

js maker-connect-secure-1.replit.app collected 2026-10-03 03:57:58 UTC 53,861 bytes, 1 lines download raw bytes

1import{a as ha,b as xa,r as n,aP as gs,aQ as yt,aR as wt,g as A,aS as pa,e as hs,aT as xs,aU as fa,aV as ba,aW as ya,aX as ge,aY as wa,aZ as Na,a_ as Nt,j as t,L as K,T as ps,a$ as fs,b0 as bs,b1 as jt,b2 as ys,Y as Ms,X as Ct,W as he,N as ja,U as va,b3 as vt,aO as kt,b4 as ka,E as ws,b5 as Ca,b6 as Aa,b7 as Ns,b8 as Sa,b9 as Ra,ba as Ta,bb as $a,bc as qa,bd as Ia,be as Ma,bf as Da}from"./index-DgD-XLBZ.js";import{u as Ka,A as js,a as vs,b as ks,c as Cs,d as As,e as Ss,f as Rs,g as Ts}from"./alert-dialog-x_ZGfr0w.js";import{u as Ea,g as Ua,A as $s,f as La,a as Fa,b as qs}from"./AdminMessageComposer-BxrYkZ7p.js";import{C as xe,S as te,U as Pa}from"./undo-2-DqF_78pX.js";import{I as Ba}from"./adminListSearch-13HxPNaw.js";import"./stickyComposerScroll-BJCSS6Iz.js";import"./index-C4gON1Sk.js";import"./with-selector-TpwWsawr.js";import"./popover-JMyrsqZr.js";import"./settings-2-D2ijZr7S.js";function Oa(d){const g=Math.floor((Date.now()-d.getTime())/1e3);if(g<60)return"now";const w=Math.floor(g/60);if(w<60)return`${w}m`;const k=Math.floor(w/60);if(k<24)return`${k}h`;const P=Math.floor(k/24);return P<7?`${P}d`:d.toLocaleDateString([],{month:"short",day:"numeric"})}function Ha(d){const w=Math.floor((new Date().getTime()-d.getTime())/(1e3*60*60*24));return w===0?d.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):w===1?"Yesterday "+d.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):w<7?d.toLocaleDateString([],{weekday:"short"})+" "+d.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):d.toLocaleDateString([],{month:"short",day:"numeric"})+" "+d.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function Is(d){return d==="admin"?"Admin":d==="maker"?"Maker":d==="family"?"Family":d}function Ga(d,g){if(g===0)return!0;const w=new Date(d[g-1].createdAt),k=new Date(d[g].createdAt);return w.toDateString()!==k.toDateString()}function _a(d){const w=Math.floor((new Date().getTime()-d.getTime())/(1e3*60*60*24));return w===0?"Today":w===1?"Yesterday":d.toLocaleDateString([],{weekday:"long",month:"long",day:"numeric",year:"numeric"})}const se=(d,g)=>!!d&&!!g&&JSON.stringify(d)===JSON.stringify(g);function Qa({onSelect:d,selectedMaker:g,onClear:w}){const[k,P]=n.useState(""),[S,N]=n.useState([]),[pe,R]=n.useState(!1),[Ke,T]=n.useState(!1),W=n.useRef(void 0),p=n.useRef(0),ae=n.useRef(null);if(n.useEffect(()=>{const h=k.trim(),$=++p.current;let _=null;if(N([]),T(!1),R(!1),!(h.length<2))return clearTimeout(W.current),W.current=setTimeout(async()=>{_=new AbortController,T(!0),R(!0);try{const V=await(await fetch(`/api/admin/makers/search?q=${encodeURIComponent(h)}`,{credentials:"include",signal:_.signal})).json();if(p.current!==$)return;N(Array.isArray(V)?V:[])}catch{if(p.current!==$)return;N([])}finally{p.current===$&&R(!1)}},300),()=>{clearTimeout(W.current),_?.abort(),p.current===$&&p.current++}},[k]),n.useEffect(()=>{g||P("")},[g]),n.useEffect(()=>{const h=$=>{ae.current&&!ae.current.contains($.target)&&T(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]),g){const h=g.name||[g.firstName,g.lastName].filter(Boolean).join(" ");return t.jsxs("div",{className:"flex items-center gap-2 p-2 bg-white rounded-lg border border-indigo-200","data-testid":"selected-compose-maker",children:[t.jsxs("div",{className:"flex-1 min-w-0 text-xs",children:[t.jsx("span",{className:"font-semibold text-indigo-800 truncate",children:h||"Approved maker"}),t.jsx("span",{className:"block text-indigo-600 truncate",children:g.handle?`@${g.handle}`:g.email})]}),t.jsx("button",{type:"button",onClick:w,className:"p-1 text-gray-500 hover:text-gray-800 rounded","aria-label":"Clear selected maker","data-testid":"button-clear-compose-maker",children:t.jsx(Ct,{className:"w-3.5 h-3.5"})})]})}const G=Ke&&k.trim().length>=2;return t.jsxs("div",{ref:ae,className:"relative",children:[t.jsxs("div",{className:"relative",children:[t.jsx(Ms,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),t.jsx("input",{type:"text",placeholder:"Search maker by name, handle, or email…",value:k,onChange:h=>P(h.target.value),onFocus:()=>k.trim().length>=2&&T(!0),className:"w-full px-2.5 pl-8 py-1.5 bg-white border border-indigo-200 rounded-lg text-xs focus:outline-none focus:ring-1 focus:ring-indigo-300","aria-label":"Search approved makers","aria-controls":"compose-maker-results","aria-expanded":G,"data-testid":"input-compose-maker-search"}),pe&&t.jsx(K,{className:"absolute right-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 animate-spin text-indigo-500"})]}),G&&t.jsx("div",{id:"compose-maker-results",role:"listbox",className:"absolute z-50 w-full mt-1 bg-white border border-slate-200 rounded-lg shadow-lg max-h-52 overflow-y-auto",children:pe?t.jsx("p",{className:"px-3 py-2 text-xs text-gray-500",children:"Searching approved makers…"}):S.length>0?S.map(h=>t.jsxs("button",{type:"button",role:"option",className:"w-full text-left px-3 py-2 hover:bg-indigo-50 text-xs",onClick:()=>{d(h),P(""),T(!1)},"data-testid":`compose-maker-option-${h.id}`,children:[t.jsx("span",{className:"block font-semibold text-indigo-700",children:h.name||[h.firstName,h.lastName].filter(
1Boolean).join(" ")||"Approved maker"}),t.jsx("span",{className:"block text-gray-500",children:h.handle?`@${h.handle}`:h.email})]},h.id)):t.jsx("p",{className:"px-3 py-2 text-xs text-gray-500",children:"No approved makers found."})})]})}function an({deviceRequests:d,onOpenRequest:g,onOpenMaker:w}){const{user:k}=ha(),P=k?.role==="super_admin",S=xa(),[N,pe]=n.useState("all"),[R,Ke]=n.useState("newest"),[T,W]=n.useState(""),[p,ae]=n.useState(""),[G,h]=n.useState(0),[$,_]=n.useState(null),[At,V]=n.useState({generation:0,items:[]}),Ee=At.items,[ne,fe]=n.useState(1),[c,St]=n.useState(null),[re,Rt]=n.useState(null),q=n.useRef(null);q.current=c;const[Tt,$t]=n.useState(1),[Ue,qt]=n.useState(!1),[B,It]=n.useState("request"),[be,Le]=n.useState(""),[Y,ye]=n.useState(null),[we,Mt]=n.useState("family"),[le,Dt]=n.useState(""),Fe=n.useRef(null),[Ne,Kt]=n.useState([]),[je,Et]=n.useState([]),[Ut,j]=n.useState(""),[ve,E]=n.useState(!1),y=n.useRef(0),v=n.useRef(null),[Pe,Q]=n.useState(!1),[O,Be]=n.useState(""),Oe=n.useRef(null),[He,Ge]=n.useState(""),[ke,_e]=n.useState([]),[Ce,Qe]=n.useState([]),[Ds,Lt]=n.useState(0),I=n.useRef(0),[We,Ae]=n.useState(!1),Ft=n.useRef(null),[Se,oe]=n.useState(!1),[Pt,Re]=n.useState(""),[Ks,Te]=n.useState(new Set),[Es,Ve]=n.useState(null),[Ye,Bt]=n.useState(""),[ze,Ot]=n.useState(!1),[Je,Xe]=n.useState(null),[$e,ie]=n.useState(null),[Ze,Ht]=n.useState(""),[et,qe]=n.useState(new Set),[de,z]=n.useState(new Set),[Gt,_t]=n.useState(new Set),[Us,tt]=n.useState(!1),[Qt,Wt]=n.useState(!1),[Ls,st]=n.useState(!1),[J,Vt]=n.useState(!1),[Yt,at]=n.useState(""),zt=n.useRef(0),[X,Ie]=n.useState(null),M=n.useRef(null),Fs=n.useRef(null),nt=n.useRef(null),Jt=n.useRef(!1),m=n.useCallback((e=q.current)=>{gs(),S.invalidateQueries({queryKey:yt}),e&&S.invalidateQueries({queryKey:wt("v2",e)})},[S]),Ps=n.useCallback(async()=>{if(!J){Vt(!0),at("");try{await A("POST","/api/admin/messages/acknowledge-all",{expectedCount:zt.current}),st(!1),gs(),await Promise.all([S.invalidateQueries({queryKey:yt}),S.invalidateQueries({queryKey:["/api/admin/messages/unread-summary"]}),S.invalidateQueries({queryKey:pa})])}catch(e){at(e instanceof Error?e.message:"Unable to mark all messages as read")}finally{Vt(!1)}}},[J,S]),Bs=n.useCallback(()=>{const e=nt.current;if(!e)return;const r=e.scrollHeight-e.scrollTop-e.clientHeight;Jt.current=r>80},[]);n.useEffect(()=>()=>{M.current&&clearInterval(M.current)},[]),n.useEffect(()=>{const e=nt.current;c&&e&&(Jt.current=!1,e.scrollTop=0)},[c]);const{data:u,isLoading:Os,isFetching:Xt,isError:Hs,error:Zt,refetch:Gs}=hs({queryKey:["/api/admin/messages/conversations","v2",ne,N,R,p,G,$],queryFn:async()=>{const e=new URLSearchParams({page:String(ne),pageSize:"30",filter:N,sort:R,search:p});p&&$&&e.set("searchCursor",$);const r=await fetch(`/api/admin/messages/conversations?${e}`,{credentials:"include"});if(!r.ok)throw new Error(`Unable to load conversations (${r.status})`);const a=await r.json();if(!Array.isArray(a?.items))throw new Error("The conversations service returned an invalid response");return{messages:a.items.map(s=>({id:s.conversationKey,source:s.conversationKey.startsWith("request-")?"request":"maker-direct",conversationKey:s.conversationKey,channel:s.channels?.[0]||s.channel||"admin-maker",channels:Array.isArray(s.channels)?s.channels:[s.channel||"admin-maker"],requestId:s.requestId,requestNumber:s.requestNumber,makerId:s.makerId,makerName:s.conversationKey.startsWith("maker-direct-")?s.label:s.subtitle,childName:s.label,isDemo:!!s.isDemo,senderType:s.latestMessage?.senderType||"maker",recipientType:s.latestMessage?.recipientType||"admin",senderName:s.subtitle||s.label,recipientName:"Admin",content:"",createdAt:s.latestTime,isFlagged:s.hasFlagged,highlightedForSuperAdmin:s.hasHighlighted,adminAcknowledgedAt:s.unacknowledgedCount?null:s.latestTime,totalCount:Number(s.totalCount||0),unacknowledgedCount:Number(s.unacknowledgedCount||0),acknowledgedCount:Number(s.acknowledgedCount||0),priority:s.priority,hasUnansweredIncoming:!!s.hasUnansweredIncoming,oldestUnansweredTime:s.oldestUnansweredTime,lastIncomingTime:s.lastIncomingTime,lastAdminReply:s.lastAdminReply,hasAdminNote:!!s.hasAdminNote,highlightRequiresCall:!!s.requiresCall,latestMessage:s.latestMessage})),total:Number(a.total||0),totalPages:Math.max(1,Number(a.totalPages||1)),summary:a.summary&&typeof a.summary=="object"?a.summary:{},searchComplete:a.searchComplete!==!1,nextSearchCursor:typeof a.nextSearchCursor=="string"?a.nextSearchCursor:null,searchGeneration:G}}});zt.current=Number(u?.summary?.unreadMessageRows||0);const ce=p?Ee:u?.messages||[];n.useEffect(()=>{const e=setTimeout(()=>ae(T.trim()),250);return()=>clearTimeout(e)},[T]),n.useEffect(()=>{fe(1),_(null),V(e=>({generation:e.generation,items:[]})),p&&h(e=>e+1)},[N,R,p]),n.useEffect(()=>{const e=()=>{Ma(p,T)&&(S.invalidateQueries({queryKey:yt}),fe(1),_(null),V(r=>({generation:r.generation,items:[]})),h(r=>r+1))};return window.addEventListener(xs,e),()=>window.removeEventListener(xs,e)},[p,S,T]),n.useEffect(()=>{!p||!u?.messages||V(e=>fa(e,G,u.searchGeneration,$===null,u.messages,r=>r.conversationKey))},[p,u,$,G]),n.useEffect(()=>{$t(1)},[c]);const _s=async e=>{const r=c;return Da(r,async()=>{const a=await fetch(`/api/admin/messages/conversation/${encodeURIComponent(r)}?mode=v2&page=${e}&pageSize=50`,{credentials:"include"});if(!a.ok){const s=new Error(`Unable to load conversation (${a.status})`);throw s.status=a.status,s}return a.json()})},rt=Ka({queries:Array.from({length:Tt},(e,r)=>{const a=r+1;return{queryKey:wt("v2",c,a),queryFn:async()=>_s(a),enabled:!!c}})}),U=rt[Tt-1],lt=U?.error?.conversationKey===c,H=n.useMemo(()=>ba(c,rt.map((e,r)=>({page:r+1,data:e.data}))),[rt,c]),Z=hs({queryKey:[...wt("v2",c),"summary"],queryFn:async()=>{const e=await fetch(`/api/admin/messages/conversation/${encodeURIComponent(c)}/summary?mode=v2`,{credentials:"include"});if(!e.ok)throw new Error(`Unable to load conversation summary (${e.status})`);return{conversationKey:c,value:await e.json()}},enabled:!!c}),ot=H.rejectedConversationKey??(Z.data&&Z.data.conversationKey!==c?Z.data.conversationKey:void 0);n.useEffect(()=>{c&&ot&&ya(c,ot)},[ot,c]);const es=n.useMemo(()=>[...ce,...H.messages],[ce,H.messages]),ts=Ea(es),ss=Ua(es),as=ce,L=n.useMemo(()=>{const e=new Map;for(const a of as){let s;
1a.conversationKey?s=a.conversationKey:a.requestId?s=`request-${a.requestId}`:a.makerId?s=`maker-direct-${a.makerId}`:s=`other-${a.id}`,e.has(s)||e.set(s,[]),e.get(s).push(a)}const r=[];for(const[a,s]of e.entries()){s.sort((i,De)=>new Date(i.createdAt).getTime()-new Date(De.createdAt).getTime());const l=s[s.length-1],f=new Date(l.createdAt).getTime(),b=[...new Set(s.flatMap(i=>i.channels||[i.channel]))],x=s.some(i=>i.highlightedForSuperAdmin),C=s.some(i=>i.isFlagged),F=s.some(i=>i.adminNote||i.hasAdminNote),na=s.some(i=>i.highlightRequiresCall),Me=s.filter(i=>i.senderType!=="admin"),gt=Number(l.unacknowledgedCount??Me.filter(i=>!i.adminAcknowledgedAt).length),ra=Number(l.acknowledgedCount??Me.filter(i=>i.adminAcknowledgedAt).length),la=Me.length>0&&gt===0,ht=Me.filter(i=>i.adminAcknowledgedAt&&i.adminAcknowledgedBy),oa=[...new Set(ht.map(i=>i.adminAcknowledgedBy))];let is=null,ds=null;if(ht.length>0){const i=ht.reduce((De,ms)=>new Date(De.adminAcknowledgedAt).getTime()>new Date(ms.adminAcknowledgedAt).getTime()?De:ms);is=i.adminAcknowledgedBy,ds=new Date(i.adminAcknowledgedAt).getTime()}const cs=[...s].reverse().find(i=>i.senderType==="admin"),xt=l.lastAdminReply?new Date(l.lastAdminReply).getTime():cs?new Date(cs.createdAt).getTime():null,ee=[...s].reverse().find(i=>i.senderType!=="admin"),ia=l.lastIncomingTime?new Date(l.lastIncomingTime).getTime():ee?new Date(ee.createdAt).getTime():null,pt=l.hasUnansweredIncoming??(ee&&(!xt||new Date(ee.createdAt).getTime()>xt)),da=l.oldestUnansweredTime?new Date(l.oldestUnansweredTime).getTime():pt&&ee?new Date(ee.createdAt).getTime():null;let me;x?me="urgent":gt>0?me="unread":pt?me="waiting":me="done";let ft="Conversation",bt="";if(a.startsWith("request-")){const i=[];l.childName&&i.push(l.childName),l.requestNumber&&i.push(`#${l.requestNumber}`),ft=i.length?i.join(" — "):"Request",l.makerName&&(bt=l.makerName)}else a.startsWith("maker-direct-")&&(ft=l.makerName||"Direct Maker Message",bt="Direct");const us=s.find(i=>i.makerId),ca=l.makerId||us?.makerId||null,ua=l.makerName||us?.makerName||null,ma=s.find(i=>i.requestNumber),ga=l.requestNumber||ma?.requestNumber||null;r.push({groupKey:a,label:ft,subtitle:bt,requestId:l.requestId||null,requestNumber:ga,childName:l.childName||null,makerId:ca,makerName:ua,isDemo:l.isDemo===!0,channels:b,messages:s,latestTime:f,oldestUnansweredTime:da,hasHighlighted:x,hasFlagged:C,hasAdminNote:F,requiresCall:na,hasUnansweredIncoming:!!pt,totalCount:Number(l.totalCount??s.length),unacknowledgedCount:gt,acknowledgedCount:ra,allAcknowledged:la,lastAcknowledgedBy:is,lastAcknowledgedAt:ds,acknowledgedByNames:oa,lastIncomingTime:ia,lastAdminReply:xt,priority:l.priority||me})}return r},[as]),ns=n.useMemo(()=>{let e=L;const r={urgent:0,unread:1,waiting:2,done:3};return R==="newest"?e=[...e].sort((a,s)=>N==="all"?s.latestTime-a.latestTime:r[a.priority]-r[s.priority]||s.latestTime-a.latestTime):R==="oldest-unanswered"?e=[...e].sort((a,s)=>(a.oldestUnansweredTime||1/0)-(s.oldestUnansweredTime||1/0)):R==="most-messages"&&(e=[...e].sort((a,s)=>s.totalCount-a.totalCount)),e},[L,N,R]),D=n.useMemo(()=>{const e=u?.summary;if(e)return{all:Number(e.all??e.total??u?.total??0),unacknowledged:Number(e.unacknowledged??0),needsResponse:Number(e.needsResponse??e["needs-response"]??0),highlighted:Number(e.highlighted??0),acknowledged:Number(e.acknowledged??0),flagged:Number(e.flagged??0)};const r=L.length,a=L.filter(x=>!x.allAcknowledged).length,s=L.filter(x=>x.hasUnansweredIncoming).length,l=L.filter(x=>x.hasHighlighted).length,f=L.filter(x=>x.allAcknowledged).length,b=L.filter(x=>x.hasFlagged).length;return{all:r,unacknowledged:a,needsResponse:s,highlighted:l,acknowledged:f,flagged:b}},[L,u?.summary,u?.total]),o=n.useMemo(()=>{if(!re)return null;const e=Z.data?.conversationKey===c?Z.data.value:void 0;return{...re,messages:H.messages,...e?{unacknowledgedCount:Number(e.unacknowledgedCount||0),acknowledgedCount:Number(e.acknowledgedCount||0),incomingCount:Number(e.incomingCount||0),allAcknowledged:!!e.allAcknowledged,hasUnansweredIncoming:!!e.hasUnansweredIncoming,hasHighlighted:!!e.hasHighlighted,hasFlagged:!!e.hasFlagged,hasAdminNote:!!e.hasAdminNote,requiresCall:!!e.requiresCall,latestTime:new Date(e.latestTime).getTime(),totalCount:Number(e.totalCount||0)}:{}}},[H.messages,c,re,Z.data]),it=n.useCallback(()=>{I.current+=1,oe(!1),Ae(!1),St(null),Rt(null)},[]),Qs=n.useCallback(e=>{q.current!==e.groupKey&&(I.current+=1,oe(!1),Ae(!1),Be(""),Ge(""),_e([]),Qe([]),Re(""),Lt(r=>r+1)),q.current=e.groupKey,St(e.groupKey),Rt(e)},[]);n.useEffect(()=>{const e=U?.error?.status;c&&U?.isError&&lt&&(e===403||e===404)&&it()},[it,lt,U?.error,U?.isError,c]);const rs=n.useCallback(async(e,r)=>{if(r&&e.unacknowledgedCount===0)return;const a=e.groupKey;z(s=>new Set(s).add(a));try{const l=await(await A("PATCH","/api/admin/messages/acknowledge-thread",{conversationKey:e.groupKey,acknowledge:r})).json();m(e.groupKey);const f=Array.isArray(l.changedIds)?l.changedIds.map(b=>({id:b,source:e.groupKey.startsWith("maker-direct-")?"maker-direct":"request"})):[];r&&f.length>0&&typeof l.undoToken=="string"&&(M.current&&clearInterval(M.current),Ie({group:e,messageIds:f,undoToken:l.undoToken,countdown:8}),M.current=setInterval(()=>{Ie(b=>!b||b.countdown<=1?(M.current&&clearInterval(M.current),null):{...b,countdown:b.countdown-1})},1e3))}catch{}finally{z(s=>{const l=new Set(s);return l.delete(a),l})}},[m]),ls=n.useCallback((e,r)=>{rs(e,r)},[rs]),Ws=n.useCallback(async()=>
1{if(!X)return;M.current&&clearInterval(M.current);const{group:e,messageIds:r,undoToken:a}=X;Ie(null);const s=e.groupKey;z(l=>new Set(l).add(s));try{await A("PATCH","/api/admin/messages/acknowledge-thread",{conversationKey:e.groupKey,acknowledge:!1,messageIds:r,undoToken:a}),m(e.groupKey)}catch{}finally{z(l=>{const f=new Set(l);return f.delete(s),f})}},[X,m]),Vs=n.useCallback(async()=>{if(ge(O))return;const e=wa(q.current,re,H);if(!e){Re("This conversation changed while the reply was being prepared. Select it again and review your message before sending.");return}const r=e.conversationKey,a=I.current;Re(""),oe(!0);const s=ke.length?ke:void 0,l=Ce.length?Ce:void 0;try{await Na(e,{content:O,subject:He||void 0,photoUrls:s,libraryAttachmentIds:l},A),Nt(r,a,q.current||"",I.current)&&(Be(""),Ge(""),_e([]),Qe([]),oe(!1),Ae(!1),I.current+=1,Lt(f=>f+1),Ft.current&&(Ft.current.style.height="auto"),m(r))}catch(f){console.error("Failed to send admin reply:",f),Nt(r,a,q.current||"",I.current)&&Re(f?.message||"The reply could not be sent. Your draft was kept; review the conversation and try again.")}finally{Nt(r,a,q.current||"",I.current)&&oe(!1)}},[O,He,ke,Ce,re,H,m]),Ys=n.useCallback(async e=>{const r=`${e.source}-${e.id}`;z(a=>new Set(a).add(r));try{await A("PATCH",`/api/admin/messages/${e.id}/acknowledge`,{source:e.source,acknowledge:!e.adminAcknowledgedAt}),m()}catch{}finally{z(a=>{const s=new Set(a);return s.delete(r),s})}},[m]),zs=n.useCallback(async e=>{const r=`${e.source}-${e.id}`;_t(a=>new Set(a).add(r));try{await A("PATCH",`/api/admin/messages/${e.id}/unflag`,{source:e.source}),m()}catch{}finally{_t(a=>{const s=new Set(a);return s.delete(r),s})}},[m]),Js=n.useCallback(async()=>{Wt(!0);try{await A("POST","/api/admin/messages/unflag-all",{}),m()}catch{}finally{Wt(!1),tt(!1)}},[m]),Xs=n.useCallback(e=>{if(e.highlightedForSuperAdmin){const r=`${e.source}-${e.id}`;Te(a=>new Set(a).add(r)),A("PATCH",`/api/admin/messages/${e.id}/highlight`,{source:e.source,highlight:!1,highlightNote:null,highlightRequiresCall:!1}).then(()=>m()).finally(()=>{Te(a=>{const s=new Set(a);return s.delete(r),s})});return}Xe(e),Bt(""),Ot(!1),Ve(`${e.source}-${e.id}`)},[m]),Zs=n.useCallback(async()=>{if(!Je)return;const e=Je,r=`${e.source}-${e.id}`;Te(a=>new Set(a).add(r)),Ve(null);try{await A("PATCH",`/api/admin/messages/${e.id}/highlight`,{source:e.source,highlight:!0,highlightNote:Ye||null,highlightRequiresCall:ze||!1}),m()}catch{}finally{Te(a=>{const s=new Set(a);return s.delete(r),s}),Xe(null)}},[Je,Ye,ze,m]),dt=n.useCallback(e=>{const r=`${e.source}-${e.id}`;if($e===r){ie(null);return}Ht(e.adminNote||""),ie(r)},[$e]),ea=n.useCallback(async e=>{const r=`${e.source}-${e.id}`;qe(a=>new Set(a).add(r));try{await A("PATCH",`/api/admin/messages/${e.id}/note`,{source:e.source,note:Ze}),m(),ie(null)}catch{}finally{qe(a=>{const s=new Set(a);return s.delete(r),s})}},[Ze,m]),ta=n.useCallback(async e=>{const r=`${e.source}-${e.id}`;qe(a=>new Set(a).add(r));try{await A("PATCH",`/api/admin/messages/${e.id}/note`,{source:e.source,note:""}),m(),ie(null)}catch{}finally{qe(a=>{const s=new Set(a);return s.delete(r),s})}},[m]),ue=n.useCallback(()=>{y.current+=1,v.current=null,E(!1),qt(!1),It("request"),Le(""),ye(null),Mt("family"),Dt(""),Kt([]),Et([]),Q(!1),j("")},[]),os=n.useCallback(e=>{y.current+=1,v.current=null,E(!1),Q(!1),It(e),j(""),e==="request"?ye(null):Le("")},[]),sa=n.useCallback(async()=>{const e=le;if(ge(e)){j("Enter a message before sending.");return}const r=Ne.length?Ne:void 0,a=je.length?je:void 0,s=y.current;if(B==="maker"){if(!Y?.id){j("Select an approved maker before sending.");return}E(!0),j("");const C={mode:"maker",makerId:String(Y.id)};v.current=C;try{await A("POST",`/api/admin/maker-applications/${Y.id}/message`,{content:e,photoUrls:r,libraryAttachmentIds:a}),s===y.current&&se(C,v.current)&&(m(),ue())}catch(F){s===y.current&&se(C,v.current)&&j(F?.message||"Could not send the message. Check the maker and try again.")}finally{s===y.current&&se(C,v.current)&&E(!1)}return}const l=be.trim();if(!l){j("Enter a request number before sending.");return}const b=ce.find(C=>String(C.requestNumber)===l||String(C.requestNum)===l)?.requestId;if(!b){j(`Request #${l} was not found in the inbox. Open a message from that request first.`);return}E(!0),j("");const x={mode:"request",requestId:String(b),requestNumber:l,recipientType:we};v.current=x;try{await A("POST","/api/messages/admin",{requestId:b,recipientType:we,content:e,photoUrls:r,libraryAttachmentIds:a}),s===y.current&&se(x,v.current)&&(m(),ue())}catch(C){s===y.current&&se(x,v.current)&&j(C?.message||"Could not send the message. Check the request number and try again.")}finally{s===y.current&&se(x,v.current)&&E(!1)}},[ce,Y,Ne,je,le,B,we,be,m,ue]),ct=y.current,ut=q.current,mt=I.current;if(Os)return t.jsx("div",{className:"flex items-center justify-center py-20",children:t.jsx(K,{className:"w-8 h-8 animate-spin text-muted-foreground"})});if(Hs)return t.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-20 text-center","data-testid":"messages2-load-error",children:[t.jsx(ps,{className:"w-9 h-9 text-red-400"}),t.jsx("p",{className:"font-semibold text-gray-800",children:"Conversations couldn’t be loaded"}),t.jsx("p",{className:"text-sm text-gray-500",role:"alert",children:Zt instanceof Error?Zt.message:"Please try again."}),t.jsx("button",{type:"button",onClick:()=>{Gs()},className:"rounded-lg bg-indigo-600 px-3 py-2 text-sm font-medium text-white","data-testid":"button-retry-messages2-load",children:"Try again"})]});const aa=[["all","All",D.all],["unacknowledged","Unread",D.unacknowledged],["needs-response","Awaiting",D.needsResponse],["highlighted","Urgent",D.highlighted],["acknowledged","Read",D.acknowledged],["flagged","Flagged",D.flagged]];return t.jsxs("div",{className:"flex flex-col gap-3",style:{height:"calc(100vh - 140px)"},"data-testid":"messages-2-panel",children:[P&&t.jsx("div",{className:"flex justify-end",children:t.jsxs("button",{type:"button",onClick:()=>{at(""),st(!0)},disabled:Number(u?.summary?.unreadMessageRows||0)===0,className:"inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-3 py-2 text-sm font-semibold text-white hover:bg-indigo-700 disabled:cursor-not-allowed disabled:opacity-50","data-testid":"button-mark-all-admin-messages-read",children:[t.jsx(xe,{className:"h-4 w-4"}),"Mark all as read"]})}),t.jsxs("div",{className:"flex flex-1 min-h-0 rounded-2xl border border-gray-200 overflow-hidden bg-white shadow-sm",children:[t.jsxs("div",{className:`${c?"hidden sm:flex":"flex"} w-full sm:w-[300px] md:w-[340px] flex-shrink-0 border-r border-gray-200 flex-col bg-gray-50/80`,children:[t.jsxs("div",{className:"px-4 pt-4 pb-2",children:[t.jsxs("div",{className:"flex items-center justify-between mb-3",children:[t.jsxs("h2",{className:"text-lg font-bold text-gray-900 flex items-center gap-2","data-testid":"text-messages2-title",children:[t.jsx(Ba,{className:"w-5 h-5 text-indigo-600"}),"Admin Inbox"]}),t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx("button",{onClick:()=>Ue?ue():qt(!0),className:`p-1.5 rounded-lg transition-colors ${Ue?"bg-indigo-600 text-white":"text-gray-500 hover:bg-gray-200"}`,title:"New message","data-testid":"button-compose-new",children:t.jsx(fs,{className:"w-3.5 h-3.5"})}),t.jsxs("select",{value:R,onChange:e=>Ke(e.target.value),className:"text-xs text-gray-500 bg-transparent border-none focus:outline-none cursor-pointer","data-testid":"select-messages2-sort",children:[t.jsx("option",{value:"newest",children:"Newest"}),t.jsx("option",{value:"oldest-unanswered",children:"Oldest"}),t.jsx("option",{value:"most-messages",children:"Most msgs"})]})]})]}),Ue&&t.jsxs("div",{className:"mb-3 max-h-[60vh] min-h-0 overflow-y-auto rounded-xl border border-indigo-200 bg-indigo-50 p-3 pb-0","data-testid":"panel-compose-new","data-scroll-region":"admin-new-message",children:[t.jsxs("div",{className:"space-y-2 pb-3",children:[t.jsx("p",{className:"text-xs font-semibold text-indigo-800",children:"New Message"}),t.jsxs("div",{className:"grid grid-cols-2 gap-1 p-1 bg-indigo-100 rounded-lg",role:"group","aria-label":"Message recipient scope",children:[t.jsx("button",{type:"button",onClick:()=>os("request"),className:`px-2 py-1 text-[11px] rounded-md ${B==="request"?"bg-white text-indigo-700 shadow-sm font-semibold":"text-indigo-600 hover:bg-white/60"}`,"aria-pressed":B==="request","data-testid":"button-compose-by-request",children:"By Request #"}),t.jsx("button",{type:"button",onClick:()=>os("maker"),className:`px-2 py-1 text-[11px] rounded-md ${B==="maker"?"bg-white text-indigo-700 shadow-sm font-semibold":"text-indigo-600 hover:bg-white/60"}`,"aria-pressed":B==="maker","data-testid":"button-compose-by-maker",children:"By Maker"})]}),B==="request"?t.jsxs(t.Fragment,{children:[t.jsx("input",{type:"text",placeholder:"Request # (e.g. 1234)",value:be,onChange:e=>{y.current+=1,v.current=null,E(!1),Q(!1),Le(e.target.value),j("")},className:"w-full px-2.5 py-1.5 bg-white border border-indigo-200 rounded-lg text-xs focus:outline-none focus:ring-1 focus:ring-indigo-300","data-testid":"input-compose-req-num"}),t.jsxs("select",{value:we,onChange:e=>{y.current+=1,v.current=null,E(!1),Q(!1),Mt(e.target.value)},className:"w-full px-2.5 py-1.5 bg-white border border-indigo-200 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-indigo-300","data-testid":"select-compose-recipient",children:[t.jsx("option",{value:"family",children:"Family"}),t.jsx("option",{value:"maker",children:"Maker"})]})]}):t.jsx(Qa,{selectedMaker:Y,onSelect:e=>{y.current+=1,v.current={mode:"maker",makerId:String(e.id)},E(!1),Q(!1),ye(e),j("")},onClear:()=>{y.current+=1,v.current=null,E(!1),Q(!1),ye(null),j("")}}),t.jsx($s,{ref:Fe,value:le,onChange:e=>{Dt(e),j("")},placeholder:"Message...",disabled:ve||Pe,stickyActionClearance:!0,"data-testid":"textarea-compose-message"}),t.jsx(bs,{length:jt(le)}),t.jsx(ys,{photoUrls:Ne,onPhotosChange:e=>{y.current===ct&&Kt(e)},disabled:ve||Pe,onUploadingChange:e=>{y.current===ct&&Q(e)},allowLibrarySelection:!0,allowCommonLinkSelection:!0,onInsertCommonLink:e=>
1Fe.current?.insertCommonLink(e)??!1,onRestoreCommonLinkFocus:()=>Fe.current?.restoreFocus(),libraryAttachmentIds:je,onLibraryAttachmentIdsChange:e=>{y.current===ct&&Et(e)}}),Ut&&t.jsx("p",{className:"text-xs text-red-700 bg-red-50 border border-red-200 rounded-lg px-2.5 py-1.5",role:"alert","data-testid":"text-compose-error",children:Ut})]}),t.jsxs("div",{className:"sticky bottom-0 -mx-3 flex justify-end gap-1.5 border-t border-indigo-200 bg-indigo-50 px-3 py-3","data-testid":"compose-new-actions",children:[t.jsx("button",{onClick:ue,className:"px-2.5 py-1 text-xs text-gray-600 hover:bg-gray-200 rounded-lg","data-testid":"button-compose-cancel",children:"Cancel"}),t.jsx("button",{disabled:ve||Pe||ge(le)||(B==="request"?!be.trim():!Y?.id),onClick:sa,className:"px-2.5 py-1 text-xs bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50","data-testid":"button-compose-send",children:ve?"Sending…":"Send"})]})]}),t.jsxs("div",{className:"relative mb-3",children:[t.jsx(Ms,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),t.jsx("input",{type:"text",placeholder:"Search messages...",value:T,onChange:e=>W(e.target.value),className:"w-full pl-9 pr-8 py-2 bg-white border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-indigo-200 focus:border-indigo-300","data-testid":"input-messages2-search"}),T&&t.jsx("button",{onClick:()=>W(""),className:"absolute right-2 top-1/2 -translate-y-1/2","data-testid":"button-messages2-clear-search",children:t.jsx(Ct,{className:"w-4 h-4 text-gray-400"})})]}),t.jsx("div",{className:"flex gap-1 flex-wrap","data-testid":"messages2-filters",children:aa.map(([e,r,a])=>t.jsx("button",{onClick:()=>pe(e),className:`flex-1 text-center py-1.5 text-[11px] font-semibold rounded-lg transition-colors ${e==="flagged"?N===e?"bg-red-600 text-white":a>0?"text-red-600 bg-red-50 hover:bg-red-100 ring-1 ring-red-300":"text-gray-400 hover:bg-gray-200":N===e?"bg-indigo-600 text-white":"text-gray-500 hover:bg-gray-200"}`,"data-testid":`button-filter-${e}`,children:e==="flagged"&&a>0&&N!==e?t.jsxs("span",{className:"flex items-center justify-center gap-0.5",children:[t.jsx(he,{className:"w-2.5 h-2.5"}),a]}):t.jsxs(t.Fragment,{children:[r,a>0&&N!==e&&t.jsx("span",{className:"ml-0.5 text-[10px] opacity-60",children:a})]})},e))}),t.jsxs("div",{className:"mt-2 text-[11px] text-gray-500","data-testid":"messages2-demo-operational-counts",children:["Demo: ",Number(u?.summary?.demoUnacknowledged??0)," unread · ",Number(u?.summary?.demoNeedsResponse??0)," awaiting",t.jsx("span",{className:"mx-1.5",children:"·"}),"Real: ",Number(u?.summary?.realUnacknowledged??0)," unread · ",Number(u?.summary?.realNeedsResponse??0)," awaiting"]}),p&&t.jsxs("div",{className:"mt-2 rounded-lg bg-indigo-50 px-2.5 py-2 text-[11px] text-indigo-800","data-testid":"messages2-search-progress",children:[t.jsx("div",{children:u?.searchComplete?`Search complete · ${Ee.length} found`:`Search continuing · ${Ee.length} found so far`}),!u?.searchComplete&&u?.nextSearchCursor&&t.jsx("button",{type:"button",disabled:Xt,onClick:()=>_(u.nextSearchCursor),className:"mt-1 font-semibold hover:underline disabled:opacity-50","data-testid":"button-continue-messages2-search",children:Xt?"Continuing search…":"Continue search"})]}),N==="flagged"&&D.flagged>0&&t.jsxs("button",{onClick:()=>tt(!0),className:"w-full mt-1.5 py-1.5 text-[11px] font-semibold rounded-lg bg-red-50 text-red-700 hover:bg-red-100 ring-1 ring-red-300 flex items-center justify-center gap-1.5 transition-colors","data-testid":"button-clear-all-flags",children:[t.jsx(he,{className:"w-3 h-3"}),"Clear all ",D.flagged," false positive",D.flagged!==1?"s":""]})]}),t.jsx("div",{className:"flex-1 overflow-y-auto",children:ns.length===0?t.jsxs("div",{className:"px-4 py-10 text-center",children:[t.jsx(xe,{className:"w-10 h-10 mx-auto text-green-300 mb-2"}),t.jsx("p",{className:"text-sm text-gray-400 font-medium",children:"No conversations"})]}):ns.map(e=>{const r=e.messages[e.messages.length-1],a=c===e.groupKey,s=e.priority==="unread"||e.priority==="urgent";return t.jsxs("button",{onClick:()=>{Qs(e)},className:`w-full text-left px-4 py-3 flex items-center gap-3 border-b border-gray-100 transition-colors ${a?"bg-indigo-600 text-white":e.hasFlagged?"bg-red-50/60 hover:bg-red-50 border-l-[3px] border-l-red-400":e.hasAdminNote?"bg-amber-50/60 hover:bg-amber-50 border-l-[3px] border-l-amber-400":"hover:bg-gray-100"}`,"data-testid":`button-conversation-${e.groupKey}`,children:[t.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${a?"bg-white/20 text-white":e.priority==="urgent"?"bg-red-100 text-red-600":e.priority==="unread"?"bg-indigo-100 text-indigo-600":"bg-gray-200 text-gray-500"}`,children:e.channels.includes("admin-family")?t.jsx(ja,{className:"w-4.5 h-4.5"}):t.jsx(va,{className:"w-4.5 h-4.5"})}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-sm truncate ${s&&!a?"font-bold text-gray-900":a?"font-semibold":"font-medium text-gray-700"}`,children:e.label}),t.jsx("span",{className:`text-[11px] flex-shrink-0 ${a?"text-white/70":"text-gray-400"}`,children:Oa(new Date(r.createdAt))})]}),t.jsxs("div",{className:"flex items-center justify-between gap-2 mt-0.5",children:[t.jsxs("p",{className:`text-xs truncate ${a?"text-white/70":s?"text-gray-600":"text-gray-400"}`,children:[Is(r.senderType),": ",r.content?.substring(0,60),r.content?.length>60?"…":""]}),t.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.hasFlagged&&!a&&t.jsx(he,{className:"w-3 h-3 text-red-500 fill-red-100",title:"Contains flagged message"}),e.hasAdminNote&&!a&&t.jsx(te,{className:"w-3 h-3 text-amber-500 fill-amber-200"}),e.requiresCall&&!a&&t.jsxs("span",{className:"inline-flex items-center gap-0.5 bg-orange-100 text-orange-700 rounded px-1 py-px",title:"Phone call needed",children:[t.jsx(vt,{className:"w-3 h-3"}),t.jsx("span",{className:"text-[9px] font-bold",children:"CALL"})]}),e.hasHighlighted&&!a&&t.jsx(kt,{className:"w-3 h-3 text-yellow-500 fill-yellow-500"}),e.isDemo&&t.jsx("span",{className:`text-[9px] font-bold px-1 py-px rounded ${a?"bg-white/20 text-white":"bg-violet-100 text-violet-700"}`,"data-testid":`badge-demo-thread-${e.groupKey}`,children:"Demo"}),e.unacknowledgedCount>0&&!a&&t.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full bg-indigo-600 text-white text-[10px] font-bold",children:e.unacknowledgedCount}),e.allAcknowledged&&!a&&t.jsx(xe,{className:"w-3.5 h-3.5 text-green-500"})]})]})]})]},e.groupKey)})}),!p&&u&&u.totalPages>1&&t.jsxs("div",{className:"flex items-center justify-between border-t border-gray-200 px-3 py-2 text-xs",children:[t.jsx("button",{type:"button",disabled:ne<=1,onClick:()=>fe(e=>e-1),"data-testid":"button-conversation-page-prev",children:"Previous"}),t.jsxs("span",{"data-testid":"text-conversation-page",children:["Page ",ne," of ",u.totalPages]}),t.jsx("button",{type:"button",disabled:ne>=u.totalPages,onClick:()=>fe(e=>e+1),"data-testid":"button-conversation-page-next",children:"Next"})]})]}),t.jsx("div",{className:`${c?"flex":"hidden sm:flex"} flex-1 flex-col min-w-0 bg-white`,children:o?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"px-3 sm:px-5 py-2.5 border-b border-gray-200 bg-white space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx("button",{onClick:it,className:"sm:hidden flex items-center justify-center w-8 h-8 rounded-full hover:bg-gray-100 text-gray-500 flex-shrink-0","data-testid":"button-back-to-conversations","aria-label":"Back to conversations",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:t.jsx("path",{d:"M15 18l-6-6 6-6"})})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("h3",{className:"font-semibold text-gray-900 text-sm truncate",children:o.label}),t.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[o.subtitle&&t.jsx("span",{className:"text-xs text-gray-400",children:o.subtitle}),t.jsxs("span",{className:"text-xs text-gray-300",children:[o.totalCount," messages"]}),o.allAcknowledged&&o.acknowledgedByNames.length>0&&t.jsxs("span",{className:"text-[10px] text-green-600 flex items-center gap-0.5",children:[t.jsx(xe,{className:"w-3 h-3"}),"Read by ",o.acknowledgedByNames.map(e=>
1e.split("@")[0]).join(", ")]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[t.jsxs("button",{onClick:()=>{const r=o.messages.find(a=>a.adminNote)||o.messages.filter(a=>a.senderType!=="admin").pop()||o.messages[o.messages.length-1];r&&dt(r)},className:`inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1.5 rounded-lg transition-colors ${o.hasAdminNote?"text-amber-700 bg-amber-50 hover:bg-amber-100 border border-amber-200":"text-gray-500 hover:text-amber-700 hover:bg-amber-50 border border-gray-200"}`,"data-testid":`button-thread-note-${o.groupKey}`,children:[t.jsx(te,{className:`w-3.5 h-3.5 ${o.hasAdminNote?"fill-amber-200":""}`}),o.hasAdminNote?"View Note":"Add Note"]}),o.requestId&&t.jsxs("a",{href:`/admin?tab=requests&requestId=${o.requestId}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-indigo-600 hover:text-indigo-800 font-medium px-2.5 py-1.5 rounded-lg hover:bg-indigo-50 transition-colors","data-testid":`button-open-request-${o.groupKey}`,children:[t.jsx(ws,{className:"w-3 h-3"}),"Request #",o.requestNumber||""]}),o.requestNumber&&t.jsxs("a",{href:`/story/${o.requestNumber}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-emerald-600 hover:text-emerald-800 font-medium px-2.5 py-1.5 rounded-lg hover:bg-emerald-50 transition-colors","data-testid":`button-build-story-${o.groupKey}`,children:[t.jsx(Ca,{className:"w-3 h-3"}),"Build Story"]}),o.makerId&&t.jsxs("a",{href:`/admin?tab=makers&makerId=${encodeURIComponent(o.makerId)}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-purple-600 hover:text-purple-800 font-medium px-2.5 py-1.5 rounded-lg hover:bg-purple-50 transition-colors","data-testid":`button-open-maker-${o.groupKey}`,children:[t.jsx(ws,{className:"w-3 h-3"}),"Maker"]}),o.allAcknowledged?t.jsxs("button",{onClick:()=>ls(o,!1),disabled:de.has(o.groupKey),className:"inline-flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium border border-gray-200 text-gray-500 hover:bg-gray-50 transition-colors disabled:opacity-50","data-testid":`button-unack-thread-${o.groupKey}`,children:[de.has(o.groupKey)?t.jsx(K,{className:"w-3 h-3 animate-spin"}):t.jsx(Aa,{className:"w-3 h-3"}),"Mark Unread"]}):t.jsxs("button",{onClick:()=>ls(o,!0),disabled:de.has(o.groupKey),className:"inline-flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-semibold bg-green-600 text-white hover:bg-green-700 transition-colors disabled:opacity-50","data-testid":`button-ack-thread-${o.groupKey}`,children:[de.has(o.groupKey)?t.jsx(K,{className:"w-3 h-3 animate-spin"}):t.jsx(xe,{className:"w-3.5 h-3.5"}),"Mark All Read"]})]})]}),t.jsx("div",{ref:nt,onScroll:Bs,className:"flex-1 overflow-y-auto px-5 py-4 bg-gray-50/50",style:{overflowAnchor:"none"},children:t.jsxs("div",{className:"max-w-2xl mx-auto space-y-1",children:[U.isError&&lt?t.jsxs("div",{className:"py-10 text-center","data-testid":"messages2-conversation-detail-error",children:[t.jsx("p",{className:"mb-2 text-sm text-red-600",role:"alert",children:U.error instanceof Error?U.error.message:"Conversation could not be loaded."}),t.jsx("button",{type:"button",onClick:()=>{U.refetch()},className:"text-xs font-semibold text-indigo-600","data-testid":"button-retry-messages2-conversation-detail",children:"Try again"})]}):H.available?U.data?.value.hasMore&&t.jsx("button",{type:"button",onClick:()=>$t(e=>e+1),className:"mx-auto block text-xs text-indigo-600","data-testid":"button-load-older-conversation",children:"Load older messages"}):t.jsx(K,{className:"mx-auto my-8 h-5 w-5 animate-spin text-indigo-500"}),o.messages.map((e,r)=>{const a=`${e.source}-${e.id}`,s=e.senderType==="admin",l=e.requestId||o.requestId,f=e.requestNumber??o.requestNumber,b=!!e.adminAcknowledgedAt,x=de.has(a),C=Ga(o.messages,r);return t.jsxs("div",{children:[C&&t.jsxs("div",{className:"flex items-center gap-3 my-4",children:[t.jsx("div",{className:"flex-1 h-px bg-gray-200"}),t.jsx("span",{className:"text-[10px] font-semibold text-gray-400 uppercase tracking-wider",children:_a(new Date(e.createdAt))}),t.jsx("div",{className:"flex-1 h-px bg-gray-200"})]}),t.jsx("div",{className:`flex ${s?"justify-end":"justify-start"} mb-1 group`,children:t.jsxs("div",{className:"max-w-[75%] ",children:[t.jsxs("div",{className:`rounded-2xl px-4 py-2.5 ${s?"bg-indigo-600 text-white rounded-br-sm":"bg-white border border-gray-200 text-gray-800 rounded-bl-sm shadow-sm"}`,"data-testid":`message-bubble-${e.id}`,children:[t.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[t.jsx("span",{className:`text-[11px] font-semibold ${s?"text-indigo-200":e.senderType==="maker"?"text-purple-600":"text-emerald-600"}`,children:t.jsx("span",{className:"break-words",title:s&&qs(e)?`Admin user ID: ${qs(e)}`:void 0,children:e.directionLabel||La({sender:{role:e.senderType||"unknown",name:s?Fa(e):e.senderName||Is(e.senderType),id:e.senderId},recipients:e.recipientParties?.length?e.recipientParties:[{role:e.recipientType||"unknown",name:e.recipientName}]})})}),t.jsx("span",{className:`text-[10px] ${s?"text-indigo-300":"text-gray-400"}`,children:Ha(new Date(e.createdAt))}),e.messageSource==="sms"&&t.jsx("span",{className:"text-[9px] bg-teal-100 text-teal-700 px-1 py-0.5 rounded font-bold",children:"SMS"})]}),e.subject&&t.jsxs("p",{className:`text-[11px] font-medium mb-1 ${s?"text-indigo-200":"text-gray-400"}`,children:["Re: ",e.subject]}),/<(?:p|strong|em|a|ul|ol|li|br)(?:\s|>)/i.test(String(e.content||""))?t.jsx(Ns,{content:e.content,tone:s?"dark":"light",className:`text-[13px] leading-relaxed ${s?"text-white":"text-gray-800"}`,isAdmin:!0,knownRequestNumbers:ss,requestIdsByNumber:ts,conversationRequestId:l,conversationRequestNumber:f,"data-testid":`text-content-${e.id}`}):t.jsx(Ns,{content:e.content,tone:s?"dark":"light",className:`text-[13px] whitespace-pre-wrap leading-relaxed ${s?"text-white":"text-gray-800"}`,isAdmin:!0,knownRequestNumbers:ss,requestIdsByNumber:ts,conversationRequestId:l,conversationRequestNumber:f,"data-testid":`text-content-${e.id}`}),e.content&&t.jsx("div",{className:`mt-2 pt-2 border-t ${s?"border-indigo-500":"border-gray-100"}`,children:t.jsx(Sa,{text:e.content,detectedLanguage:e.detectedLanguage,compact:!0,tone:s?"dark":"light","data-testid":`translate-${e.id}`})}),!!(e.photoUrls?.length||e.messageAttachments?.length)&&t.jsx("div",{className:"mt-2",children:t.jsx(Ra,{photoUrls:e.photoUrls,messageAttachments:e.messageAttachments})}),e.highlightedForSuperAdmin&&t.jsxs("div",{className:`mt-2 pt-1.5 border-t ${s?"border-indigo-500":"border-yellow-200"} flex flex-col gap-1`,children:[e.highlightRequiresCall?t.jsxs("div",{className:"flex items-center gap-1.5 bg-orange-50 border border-orange-200 rounded px-2 py-1",children:[t.jsx(vt,{className:"w-3.5 h-3.5 text-orange-600"}),t.jsx("span",{className:"text-[11px] text-orange-700 font-bold",children:"PHONE CALL NEEDED"}),e.highlightedBy&&t.jsxs("span",{className:"text-[10px] text-orange-500",children:["— ",e.highlightedBy]})]}):t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(kt,{className:"w-3 h-3 text-yellow-500 fill-yellow-500"}),t.jsxs("span",{className:"text-[10px] text-yellow-600 font-bold",children:["URGENT",e.highlightedBy?` — ${e.highlightedBy}`:""]})]}),e.highlightNote&&t.jsxs("div",{className:"flex items-center gap-1 ml-0.5",children:[t.jsx(te,{className:"w-3 h-3 text-slate-400 flex-shrink-0"}),t.jsx("span",{className:"text-[10px] text-slate-600 italic",children:e.highlightNote})]})]}),e.isFlagged&&t.jsxs("div",{className:"mt-1 flex items-center gap-1.5 bg-red-50 border border-red-200 rounded px-2 py-1",children:[t.jsx(ps,{className:"w-3 h-3 text-red-400 flex-shrink-0"}),t.jsx("span",{className:"text-[10px] text-red-600 font-medium flex-1",children:e.flagReason||"Flagged for review"}),t.jsx("button",{onClick:()=>zs(e),disabled:Gt.has(`${e.source}-${e.id}`),className:"text-[10px] px-1.5 py-0.5 rounded bg-white border border-red-300 text-red-600 hover:bg-red-600 hover:text-white hover:border-red-600 transition-colors font-semibold flex items-center gap-0.5 flex-shrink-0",title:"Mark as false positive and clear this flag","data-testid":`button-unflag-${e.id}`,children:Gt.has(`${e.source}-${e.id}`)?t.jsx(K,{className:"w-2.5 h-2.5 animate-spin"}):t.jsxs(t.Fragment,{children:[t.jsx(he,{className:"w-2.5 h-2.5"}),"Clear"]})})]})]}),t.jsxs("div",{className:`flex items-center gap-0.5 mt-0.5 ${s?"justify-end":""}`,children:[!s&&b&&e.adminAcknowledgedBy&&t.jsxs("span",{className:"text-[10px] text-green-600 flex items-center gap-0.5 mr-1","data-testid":`text-msg-acked-${e.id}`,children:[t.jsx(Ta,{className:"w-2.5 h-2.5"}),e.adminAcknowledgedBy.split("@")[0]]}),t.jsxs("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity flex items-center gap-1",children:[!s&&t.jsxs("button",{onClick:()=>Ys(e),disabled:x,className:`text-[10px] px-1.5 py-0.5 rounded flex items-center gap-0.5 transition-colors ${b?"text-green-600 hover:bg-green-50":"text-gray-400 hover:bg-gray-100 hover:text-green-600"}`,"data-testid":`button-ack-${e.id}`,children:[x?t.jsx(K,{className:"w-2.5 h-2.5 animate-spin"}):t.jsx($a,{className:"w-2.5 h-2.5"}),"Read"]}),t.jsx("button",{onClick:()=>Xs(e),disabled:Ks.has(a),className:`text-[10px] px-1.5 py-0.5 rounded flex items-center gap-0.5 transition-colors ${e.highlightedForSuperAdmin?"text-yellow-500 hover:bg-yellow-50":"text-gray-400 hover:text-yellow-500 hover:bg-yellow-50"}`,"data-testid":`button-highlight-${e.id}`,children:t.jsx(kt,{className:`w-2.5 h-2.5 ${e.highlightedForSuperAdmin?"fill-yellow-500":""}`})}),t.jsx("button",{onClick:()=>dt(e),className:`text-[10px] px-1.5 py-0.5 rounded flex items-center gap-0.5 transition-colors ${e.adminNote?"text-amber-600 hover:bg-amber-50":"text-gray-400 hover:text-amber-600 hover:bg-amber-50"}`,"data-testid":`button-note-${e.id}`,children:t.jsx(te,{className:`w-2.5 h-2.5 ${e.adminNote?"fill-amber-200":""}`})})]})]}),Es===a&&t.jsxs("div",{className:"mt-2 p-3 bg-yellow-50 border border-yellow-200 rounded-xl space-y-2",children:[t.jsx("textarea",{value:Ye,onChange:F=>Bt(F.target.value),placeholder:"Why does this need attention?",className:"w-full text-sm border border-yellow-200 rounded-lg p-2 resize-none h-14 focus:outline-none focus:ring-2 focus:ring-yellow-300 bg-white","data-testid":`textarea-highlight-note-${e.id}`}),t.jsxs("label",{className:"flex items-center gap-2 text-xs text-gray-600",children:[t.jsx("input",{type:"checkbox",checked:ze,onChange:F=>Ot(F.target.checked),className:"rounded","data-testid":`checkbox-requires-call-${e.id}`}),t.jsx(vt,{className:"w-3 h-3 text-orange-500"})," Requires call"]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{onClick:Zs,className:"px-3 py-1 bg-yellow-500 text-white text-xs rounded-lg font-medium hover:bg-yellow-600","data-testid":`button-submit-highlight-${e.id}`,children:"Highlight"}),t.jsx("button",{onClick:()=>{Ve(null),Xe(null)},className:"px-3 py-1 bg-gray-100 text-gray-500 text-xs rounded-lg hover:bg-gray-200",children:"Cancel"})]})]}),e.adminNote&&$e!==a&&t.jsxs("div",{className:"mt-1.5 flex items-start gap-1.5 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2 shadow-sm","data-testid":`admin-note-display-${e.id}`,children:[t.jsx(te,{className:"w-3.5 h-3.5 text-amber-500 mt-0.5 flex-shrink-0"}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("p",{className:"text-[12px] text-amber-900 whitespace-pre-wrap leading-snug",children:e.adminNote}),t.jsxs("p",{className:"text-[10px] text-amber-500 mt-0.5",children:["— ",e.adminNoteBy||"Admin",e.adminNoteAt?`, ${new Date(e.adminNoteAt).toLocaleDateString()}`:""]})]}),t.jsx("button",{onClick:()=>dt(e),className:"text-amber-400 hover:text-amber-600 flex-shrink-0","data-testid":`button-edit-note-${e.id}`,children:t.jsx(fs,{className:"w-3 h-3"})})]}),$e===a&&t.jsxs("div",{className:"mt-2 p-3 bg-amber-50 border border-amber-200 rounded-xl space-y-2","data-testid":`admin-note-editor-${e.id}`,children:[t.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[t.jsx(te,{className:"w-3.5 h-3.5 text-amber-500"}),t.jsx("span",{className:"text-[11px] font-semibold text-amber-700",children:"Admin Note"})]}
1),t.jsx("textarea",{value:Ze,onChange:F=>Ht(F.target.value),placeholder:"Leave a note for other admins...",className:"w-full text-sm border border-amber-200 rounded-lg p-2 resize-none h-16 focus:outline-none focus:ring-2 focus:ring-amber-300 bg-white",autoFocus:!0,"data-testid":`textarea-admin-note-${e.id}`}),t.jsxs("div",{className:"flex gap-2",children:[t.jsxs("button",{onClick:()=>ea(e),disabled:et.has(a),className:"px-3 py-1 bg-amber-500 text-white text-xs rounded-lg font-medium hover:bg-amber-600 disabled:opacity-50 flex items-center gap-1","data-testid":`button-save-note-${e.id}`,children:[et.has(a)?t.jsx(K,{className:"w-3 h-3 animate-spin"}):null,"Save"]}),e.adminNote&&t.jsx("button",{onClick:()=>ta(e),disabled:et.has(a),className:"px-3 py-1 bg-red-50 text-red-500 text-xs rounded-lg hover:bg-red-100 disabled:opacity-50","data-testid":`button-remove-note-${e.id}`,children:"Remove"}),t.jsx("button",{onClick:()=>ie(null),className:"px-3 py-1 bg-gray-100 text-gray-500 text-xs rounded-lg hover:bg-gray-200",children:"Cancel"})]})]})]})})]},a)}),t.jsx("div",{ref:Fs})]})}),t.jsxs("div",{className:"max-h-[60%] min-h-0 overflow-y-auto border-t border-gray-200 bg-white px-5 pb-0 pt-3","data-testid":"reply-region","data-scroll-region":"admin-reply",children:[t.jsxs("div",{className:"pb-3",children:[o.messages.some(e=>e.source==="maker-direct")&&t.jsx("input",{type:"text",value:He,onChange:e=>Ge(e.target.value),placeholder:"Subject (optional)",className:"w-full text-sm border border-gray-200 rounded-lg px-3 py-1.5 mb-2 focus:outline-none focus:ring-2 focus:ring-indigo-200 focus:border-indigo-300","data-testid":"input-reply-subject"}),t.jsxs("div",{className:"flex-1",children:[t.jsx($s,{ref:Oe,value:O,onChange:Be,placeholder:"Type a message...",disabled:Se||We,stickyActionClearance:!0,"data-testid":"textarea-reply"},Ds),!ge(O)&&t.jsx(bs,{length:jt(O)}),Pt&&t.jsx("p",{className:"mt-1 text-xs text-red-600",role:"alert","data-testid":"reply-send-error",children:Pt}),t.jsx(ys,{photoUrls:ke,onPhotosChange:e=>{q.current===ut&&I.current===mt&&_e(e)},disabled:Se||We,onUploadingChange:e=>{q.current===ut&&I.current===mt&&Ae(e)},allowLibrarySelection:!0,allowCommonLinkSelection:!0,onInsertCommonLink:e=>Oe.current?.insertCommonLink(e)??!1,onRestoreCommonLinkFocus:()=>Oe.current?.restoreFocus(),libraryAttachmentIds:Ce,onLibraryAttachmentIdsChange:e=>{q.current===ut&&I.current===mt&&Qe(e)}})]})]}),t.jsx("div",{className:"sticky bottom-0 -mx-5 flex items-center justify-end gap-1 border-t border-gray-200 bg-white px-5 py-3","data-testid":"reply-actions",children:t.jsx("button",{onClick:Vs,disabled:Se||We||ge(O)||Ia(jt(O)),className:"w-9 h-9 rounded-full bg-indigo-600 text-white flex items-center justify-center hover:bg-indigo-700 disabled:opacity-40 disabled:hover:bg-indigo-600 transition-colors","data-testid":"button-send-reply",children:Se?t.jsx(K,{className:"w-4 h-4 animate-spin"}):t.jsx(qa,{className:"w-4 h-4"})})})]})]}):t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"w-20 h-20 mx-auto rounded-full bg-gray-100 flex items-center justify-center mb-4",children:t.jsx(ka,{className:"w-10 h-10 text-gray-300"})}),t.jsx("p",{className:"text-gray-400 font-medium text-lg",children:"Select a conversation"}),t.jsx("p",{className:"text-sm text-gray-300 mt-1",children:"Choose a thread from the left to view messages"})]})})})]}),X&&t.jsxs("div",{className:"fixed bottom-6 left-1/2 -translate-x-1/2 z-50 bg-gray-900 text-white rounded-2xl shadow-2xl px-5 py-3.5 flex items-center gap-4 animate-in slide-in-from-bottom-4","data-testid":"undo-ack-banner",children:[t.jsxs("span",{className:"text-sm",children:["Marked ",X.messageIds.length," messages as read"]}),t.jsxs("button",{onClick:Ws,className:"inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl text-sm font-semibold bg-white text-gray-900 hover:bg-gray-100 transition-colors","data-testid":"button-undo-ack-all",children:[t.jsx(Pa,{className:"w-3.5 h-3.5"}),"Undo (",X.countdown,"s)"]}),t.jsx("button",{onClick:()=>{M.current&&clearInterval(M.current),Ie(null)},className:"text-gray-400 hover:text-white","data-testid":"button-dismiss-undo",children:t.jsx(Ct,{className:"w-4 h-4"})})]}),t.jsx(js,{open:Us,onOpenChange:e=>{e||tt(!1)},children:t.jsxs(vs,{children:[t.jsxs(ks,{children:[t.jsx(Cs,{children:"Clear all flagged messages?"}),t.jsxs(As,{children:["This will mark all ",t.jsxs("strong",{children:[D.flagged," flagged message",D.flagged!==1?"s":""]})," as false positives and remove their flags. This cannot be undone."]})]}),t.jsxs(Ss,{children:[t.jsx(Rs,{"data-testid":"button-cancel-clear-all-flags",children:"Cancel"}),t.jsxs(Ts,{onClick:Js,disabled:Qt,className:"bg-red-600 hover:bg-red-700","data-testid":"button-confirm-clear-all-flags",children:[Qt?t.jsx(K,{className:"w-4 h-4 mr-1 animate-spin"}):t.jsx(he,{className:"w-4 h-4 mr-1"}),"Clear All Flags"]})]})]})}),t.jsx(js,{open:Ls,onOpenChange:e=>{J||st(e)},children:t.jsxs(vs,{children:[t.jsxs(ks,{children:[t.jsx(Cs,{children:"Mark all admin messages as read?"}),t.jsxs(As,{children:["This will mark exactly ",t.jsxs("strong",{children:[Number(u?.summary?.unreadMessageRows||0)," unread message ",Number(u?.summary?.unreadMessageRows||0)===1?"row":"rows"]})," across the worldwide Admin Inbox as read."]})]}),Yt&&t.jsx("p",{className:"rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700",role:"alert","data-testid":"text-mark-all-read-error",children:Yt}),t.jsxs(Ss,{children:[t.jsx(Rs,{disabled:J,"data-testid":"button-cancel-mark-all-read",children:"No"}),t.jsxs(Ts,{onClick:e=>{e.preventDefault(),Ps()},disabled:J,"data-testid":"button-confirm-mark-all-read",children:[J&&t.jsx(K,{className:"mr-1 h-4 w-4 animate-spin"}),"Yes"]})]})]})})]})}export{Qa as AdminMakerSelector,an as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.