1(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[7157,32317,51140],{10179:(e,t,a)=>{"use strict";a.d(t,{A:()=>r});let r=(0,a(48375).A)("map-pin",[["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"}]])},17321:(e,t,a)=>{"use strict";a.r(t),a.d(t,{default:()=>eL});var r=a(37876),s=a(89099),n=a(14232),i=a(48230),l=a.n(i),o=a(98957),d=a(75845),c=a(75513),u=a(82909).Buffer;class g{async sendMessage(e){try{let s="".concat(this.baseURL,"/me/messages"),n={recipient:{id:e.recipientId},message:{}};e.text&&(n.message.text=e.text),e.attachment&&(n.message.attachment=e.attachment),e.quick_replies&&(n.message.quick_replies=e.quick_replies);let i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(this.config.pageAccessToken)},body:JSON.stringify(n)}),l=await i.json();if(!i.ok){var t,a,r;return console.error("â Instagram API Error:",l),{success:!1,error:{message:(null===(t=l.error)||void 0===t?void 0:t.message)||"Unknown error",code:(null===(a=l.error)||void 0===a?void 0:a.code)||i.status,error_subcode:null===(r=l.error)||void 0===r?void 0:r.error_subcode}}}return{success:!0,data:l}}catch(e){return console.error("\uD83D\uDCA5 Instagram send message error:",e),{success:!1,error:{message:e instanceof Error?e.message:"Network error",code:500}}}}async getUserProfile(e){try{let r="".concat(this.baseURL,"/").concat(e),s=await fetch("".concat(r,"?fields=").concat("id,username,name,profile_picture_url,followers_count,is_verified,is_business_account","&access_token=").concat(this.config.pageAccessToken)),n=await s.json();if(!s.ok){var t,a;return console.error("â Instagram User Profile Error:",n),{success:!1,error:{message:(null===(t=n.error)||void 0===t?void 0:t.message)||"Failed to get user profile",code:(null===(a=n.error)||void 0===a?void 0:a.code)||s.status}}}return{success:!0,data:n}}catch(e){return console.error("\uD83D\uDCA5 Instagram user profile error:",e),{success:!1,error:{message:e instanceof Error?e.message:"Network error",code:500}}}}static verifyWebhookSignature(e,t,r){try{let s=a(63426),n=s.createHmac("sha256",r).update(e).digest("hex"),i=t.replace("sha256=","");return s.timingSafeEqual(u.from(n,"hex"),u.from(i,"hex"))}catch(e){return console.error("\uD83D\uDD10 Webhook signature verification failed:",e),!1}}static parseWebhookMessage(e){var t,a,r,s,n,i;return{senderId:null===(t=e.sender)||void 0===t?void 0:t.id,recipientId:null===(a=e.recipient)||void 0===a?void 0:a.id,timestamp:new Date(e.timestamp),messageId:null===(r=e.message)||void 0===r?void 0:r.mid,text:null===(s=e.message)||void 0===s?void 0:s.text,attachments:(null===(n=e.message)||void 0===n?void 0:n.attachments)||[],quickReply:null===(i=e.message)||void 0===i?void 0:i.quick_reply,delivery:e.delivery,read:e.read}}static formatInstagramUser(e){return{id:e.id,name:e.name||e.username||"Instagram User",username:e.username,avatar:e.profile_picture_url,isVerified:e.is_verified||!1,isBusiness:e.is_business_account||!1,followersCount:e.followers_count||0}}async getMediaUrl(e){try{let t="".concat(this.baseURL,"/").concat(e),a=await fetch("".concat(t,"?fields=media_url&access_token=").concat(this.config.pageAccessToken)),r=await a.json();if(!a.ok)return console.error("â Instagram media error:",r),null;return r.media_url||null}catch(e){return console.error("\uD83D\uDCA5 Instagram media URL error:",e),null}}constructor(e){this.baseURL="https://graph.instagram.com/v18.0",this.config=e}}var m=a(73875),h=a(99742);class x extends c.S{static async sendChannelMessage(e,t,a,r,s){let n=arguments.length>5&&void 0!==arguments[5]?arguments[5]:"website",i=arguments.length>6?arguments[6]:void 0,l=arguments.length>7?arguments[7]:void 0;try{let o=(0,m.g5)({channel:n,channelData:{[n]:{recipientId:i}}});await c.S.sendMessage(e,t,a,r,s,o),"agent"===r&&"website"!==n&&await this.sendToExternalChannel(n,i,s,l)}catch(e){throw console.error("\uD83D\uDCA5 Error sending ".concat(n," message:"),e),e}}static async sendToExternalChannel(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",a=arguments.length>2?arguments[2]:void 0,r=arguments.length>3?arguments[3]:void 0;switch(e){case"instagram":await this.sendInstagramMessage(t,a);break;case"whatsapp":await this.sendWhatsAppMessage(t,a,r);break;case"email":await this.sendEmailMessage(t,a)}}static async sendInstagramMessage(e,t){try{if(!h.env.INSTAGRAM_PAGE_ACCESS_TOKEN)throw Error("Instagram not configured");let r=new g({pageAccessToken:h.env.INSTAGRAM_PAGE_ACCESS_TOKEN,appSecret:h.env.INSTAGRAM_APP_SECRET||"",verifyToken:h.env.INSTAGRAM_VERIFY_TOKEN||"",businessAccountId:h.env.INSTAGRAM_BUSINESS_ACCOUNT_ID||""}),s=await r.sendMessage({recipientId:e,text:t});if(!s.success){var a;throw Error("Instagram API error: ".concat(null===(a=s.error)||void 0===a?void 0:a.message))}}catch(e){throw console.error("â Failed to send Instagram message:",e),e}}static async sendWhatsAppMessage(e,t,a){let r=String(e).replace(/\D/g,"");if(!r)throw Error("Invalid WhatsApp recipient");let s={"Content-Type":"application/json"};(null==a?void 0:a.parseSessionToken)&&(s.Authorization="Bearer ".concat(a.parseSessionToken));let n={recipientPhone:r,message:t,customerName:null==a?void 0:a.whatsappCustomerDisplayName};(null==a?void 0:a.parseSessionToken)&&(n.sessionToken=a.parseSessionToken);let i=await fetch("/api/whatsapp/send-agent-reply",{method:"POST",headers:s,credentials:"include",body:JSON.stringify(n)}),l={};try{l=await i.json()}catch(e){}if(!i.ok)throw Error(l.error||"WhatsApp send failed (".concat(i.status,")"))}static async sendEmailMessage(e,t){}
1static async getChatWithChannel(e){try{let t=await c.S.getChat(e);if(!t)return null;return{...t,channel:t.channel||"website",channelData:t.channelData||{}}}catch(e){return console.error("\uD83D\uDCA5 Error getting chat with channel:",e),null}}static getChannelInfo(e){let t={website:{name:"Website",icon:"\uD83C\uDF10",color:"#00bfff",description:"Web chat widget"},instagram:{name:"Instagram",icon:"\uD83D\uDCF7",color:"#E4405F",description:"Instagram Direct Message"},whatsapp:{name:"WhatsApp",icon:"\uD83D\uDCAC",color:"#25D366",description:"WhatsApp Business"},email:{name:"Email",icon:"âï¸",color:"#4285F4",description:"Email support"}};return t[e]||t.website}isInstagramConfigured(){return!!(h.env.INSTAGRAM_PAGE_ACCESS_TOKEN&&h.env.INSTAGRAM_APP_SECRET&&h.env.INSTAGRAM_BUSINESS_ACCOUNT_ID)}static formatCustomerName(e,t,a){var r,s;switch(t){case"instagram":let n=null==a?void 0:null===(r=a.instagram)||void 0===r?void 0:r.username;return n?"".concat(e," (@").concat(n,")"):e;case"whatsapp":let i=null==a?void 0:null===(s=a.whatsapp)||void 0===s?void 0:s.phoneNumber;return i?"".concat(e," (").concat(i,")"):e;default:return e}}static async getChannelStats(){try{return{website:45,instagram:12,whatsapp:0,email:3}}catch(e){return console.error("\uD83D\uDCA5 Error getting channel stats:",e),{website:0,instagram:0,whatsapp:0,email:0}}}constructor(){super(),this.isInstagramConfigured()&&(this.instagramService=new g({pageAccessToken:h.env.INSTAGRAM_PAGE_ACCESS_TOKEN||"",appSecret:h.env.INSTAGRAM_APP_SECRET||"",verifyToken:h.env.INSTAGRAM_VERIFY_TOKEN||"",businessAccountId:h.env.INSTAGRAM_BUSINESS_ACCOUNT_ID||""}))}}var p=a(39050),y=a(59524),b=a(69667),f=a(50438),v=a(10179),k=a(66929),w=a(84455),N=a(95979),j=a(91521),A=a(97685),C=a(58593),T=a(19680);async function S(e){try{let{getBrowserFirestore:t,collection:r,query:s,where:n,getDocs:i,orderBy:l,limit:o}=await Promise.resolve().then(a.bind(a,72279)),d=t();if(!d)return null;let c=s(r(d,"chats"),n("customerId","==",e),n("isEmailOriginated","==",!0),l("createdAt","desc"),o(1)),u=await i(c);if(!u.empty){let e=u.docs[0].data();return{customerName:e.customerName,customerEmail:e.customerEmail}}}catch(e){}return null}function I(e){return e.replace(/\D/g,"")}let E=e=>{let{customerId:t,customerType:a,className:s="",hidePhone:i=!1,compact:l=!1,chatCustomerName:o,chatCustomerPhone:d}
1=e,[c,u]=(0,n.useState)(null),[g,m]=(0,n.useState)(!0),[h,x]=(0,n.useState)(null);(0,n.useEffect)(()=>{E()},[t,o,d]);let E=async()=>{try{m(!0),x(null);let e=t.startsWith("email_");if(function(e){return"string"==typeof e&&e.startsWith("whatsapp_")}(t)){let e=function(e,t){let a=I(t||"");return a.length>=8?a:I(e.replace(/^whatsapp_/,""))}(t,d),a=e?"+".concat(e):"â";u({id:t,fullName:o&&o.trim()||"WhatsApp contact",email:"Not on app",phoneNumber:a,country:function(e){return e.startsWith("965")?"Kuwait":e.startsWith("966")?"Saudi Arabia":e.startsWith("973")?"Bahrain":e.startsWith("971")?"United Arab Emirates":e.startsWith("974")?"Qatar":e.startsWith("968")?"Oman":e.startsWith("20")?"Egypt":"Unknown"}(e),userType:"WhatsApp",accountStatus:"new",creditBalance:{kwd:0,sar:0,bhd:0},totalRewards:0,usedPromoCount:0,lastSeen:null,isWhatsAppContact:!0}),m(!1);return}if("guest"===a){u({id:t,fullName:t.replace("guest_","Guest ").substring(0,20),email:"Not provided",phoneNumber:"Not provided",country:"Unknown",userType:"Guest",accountStatus:"new",creditBalance:{kwd:0,sar:0,bhd:0},totalRewards:0,usedPromoCount:0,lastSeen:new Date}),m(!1);return}if(e){let e=await S(t);u({id:t,fullName:(null==e?void 0:e.customerName)||"Email Customer",email:(null==e?void 0:e.customerEmail)||"Email contact",phoneNumber:"Not provided",country:"Unknown",userType:"Email Contact",accountStatus:"new",creditBalance:{kwd:0,sar:0,bhd:0},totalRewards:0,usedPromoCount:0,lastSeen:new Date}),m(!1);return}let r=await (0,C.zZ)(t),s=r.phonelocal?"".concat(r.phonecode).concat(r.phonelocal).trim():"Phone not available",n="kw"===r.country?"Kuwait":"sa"===r.country?"Saudi Arabia":"bh"===r.country?"Bahrain":r.country||"Country not specified",i=r.creditKWD+r.creditSAR+r.creditBHD,l="active";i>50||r.totalRewards>100||r.usedPromoCount>5?l="vip":0===r.usedPromoCount&&0===r.totalRewards&&(l="new"),u({id:r.objectId,fullName:r.fullName||"Unknown Customer",email:r.email||"Not provided",phoneNumber:s,country:n,userType:r.userType||"customer",accountStatus:l,creditBalance:{kwd:r.creditKWD,sar:r.creditSAR,bhd:r.creditBHD},totalRewards:r.totalRewards,usedPromoCount:r.usedPromoCount,lastSeen:r.updatedAt?new Date(r.updatedAt):null})}catch(e){console.error("Error loading customer profile:",e),x(e instanceof Error?e.message:"Failed to load customer profile")}finally{m(!1)}};if(g)return(0,r.jsx)("div",{className:"".concat(l?"space-y-3":"space-y-4"," ").concat(s),children:(0,r.jsxs)("div",{className:"animate-pulse",children:[(0,r.jsxs)("div",{className:"flex items-center ".concat(l?"gap-2":"gap-3"),children:[(0,r.jsx)("div",{className:"".concat(l?"w-8 h-8":"w-10 h-10"," bg-gray-100 dark:bg-gray-700 rounded-full flex-shrink-0")}),(0,r.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,r.jsx)("div",{className:"h-3.5 bg-gray-100 dark:bg-gray-700 rounded mb-1.5 ".concat(l?"w-24":"w-32")}),(0,r.jsx)("div",{className:"h-2.5 bg-gray-100 dark:bg-gray-700 rounded ".concat(l?"w-16":"w-20")})]})]}),(0,r.jsx)("div",{className:"space-y-0 divide-y divide-gray-100 dark:divide-gray-700/50 mt-3",children:[1,2,3,4,5].map(e=>(0,r.jsxs)("div",{className:"flex items-center gap-2 py-2",children:[(0,r.jsx)("div",{className:"w-3 h-3 bg-gray-100 dark:bg-gray-700 rounded flex-shrink-0"}),(0,r.jsx)("div",{className:"h-2.5 bg-gray-100 dark:bg-gray-700 rounded flex-1 max-w-[60%]"}),(0,r.jsx)("div",{className:"h-2.5 bg-gray-100 dark:bg-gray-700 rounded w-16"})]},e))})]})});if(h)return(0,r.jsx)("div",{className:"p-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 ".concat(s),children:(0,r.jsxs)("div",{className:"text-center text-red-600 dark:text-red-400",children:[(0,r.jsx)(p.A,{size:32,className:"mx-auto mb-2 opacity-50"}),(0,r.jsx)("p",{className:"text-sm",children:h}),(0,r.jsx)("button",{onClick:E,className:"text-xs text-red-500 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 mt-2 underline",children:"Retry"})]})});if(!c)return null;let M=localStorage.getItem("adminSelectedCountry")||(0,T.Uv)(),O="sa"===M?c.creditBalance.sar:"bh"===M?c.creditBalance.bhd:c.creditBalance.kwd,D="sa"===M?"SAR":"bh"===M?"BHD":"KWD",R=(e,t)=>{navigator.clipboard.writeText(e),A.oR.success(t?"Copied ".concat(t):"Copied")},P=e=>{let{icon:t,label:a,value:s,valueAccent:n=!1,copyable:i=!1}=e;return(0,r.jsxs)("div",{className:"flex items-center gap-3 py-2 min-w-0 group",children:[(0,r.jsx)(t,{size:l?12:13,className:"text-gray-400 dark:text-gray-500 flex-shrink-0"}),(0,r.jsx)("span",{className:"text-gray-500 dark:text-gray-400 flex-shrink-0 ".concat(l?"text-xs":"text-sm"),children:a}),(0,r.jsx)("span",{className:"truncate min-w-0 ml-auto ".concat(l?"text-xs":"text-sm"," ").concat(n?"font-medium text-gray-900 dark:text-gray-100":"text-gray-700 dark:text-gray-300"),children:s}),i&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),R(String(s),a.toLowerCase())},className:"p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-500 opacity-0 group-hover:opacity-100 transition-opacity",title:"Copy",children:(0,r.jsx)(y.A,{size:11})})]})};
1return(0,r.jsxs)("div",{className:"".concat(l?"space-y-3":"space-y-4"," ").concat(s),children:[(0,r.jsxs)("div",{className:"flex items-center ".concat(l?"gap-2":"gap-3"),children:[(0,r.jsx)("div",{className:"rounded-full flex items-center justify-center text-white font-medium bg-gray-500 dark:bg-gray-600 flex-shrink-0 ".concat(l?"w-8 h-8 text-xs":"w-10 h-10 text-sm"),children:c.fullName.charAt(0).toUpperCase()}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,r.jsx)("h3",{className:"font-medium text-gray-900 dark:text-white truncate ".concat(l?"text-sm":""),children:c.fullName}),c.isWhatsAppContact?(0,r.jsx)("span",{className:"text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded border bg-gray-50 dark:bg-gray-700/80 border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-400",title:"Messaging via WhatsApp â not linked to an app account",children:"WhatsApp"}):(0,r.jsx)("span",{className:"text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded border bg-gray-50 dark:bg-gray-700/80 border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-400",children:c.accountStatus})]}),(0,r.jsxs)("button",{onClick:()=>R(c.id,"ID"),className:"text-xs text-gray-500 dark:text-gray-400 truncate mt-0.5 hover:text-gray-700 dark:hover:text-gray-300 flex items-center gap-1 group/ids",title:"Copy ID",children:[c.id.substring(0,8),"â¦",(0,r.jsx)(y.A,{size:10,className:"opacity-0 group-hover/ids:opacity-100"})]})]})]}),(0,r.jsxs)("div",{className:"space-y-0 divide-y divide-gray-100 dark:divide-gray-700/50",children:[!i&&(0,r.jsx)(P,{icon:b.A,label:"Phone",value:c.phoneNumber,copyable:!0}),(0,r.jsx)(P,{icon:f.A,label:"Email",value:c.email,copyable:!0}),(0,r.jsx)(P,{icon:v.A,label:"Location",value:c.country}),!c.isWhatsAppContact&&O>0&&(0,r.jsx)(P,{icon:k.A,label:"Wallet",value:"".concat(O.toFixed("KWD"===D||"BHD"===D?3:2)," ").concat(D),valueAccent:!0}),!c.isWhatsAppContact&&c.totalRewards>0&&(0,r.jsx)(P,{icon:w.A,label:"Rewards",value:c.totalRewards}),!c.isWhatsAppContact&&(0,r.jsx)(P,{icon:N.A,label:"Promos",value:c.usedPromoCount}),c.lastSeen&&(0,r.jsx)(P,{icon:j.A,label:"Last seen",value:(e=>{let t=new Date;if(e.getTime()>t.getTime())return"â";let a=Math.floor((t.getTime()-e.getTime())/864e5);return 0===a?"Today":1===a?"Yesterday":a<7?"".concat(a," days ago"):e.toLocaleDateString("en-US",{month:"short",day:"numeric",year:a>365?"numeric":void 0})})(c.lastSeen)})]})]})},M=e=>{let{customerId:t,customerType:s,initialPhone:i,className:l="",compact:o=!1}=e,[d,c]=(0,n.useState)(i||null),[u,g]=(0,n.useState)(!i);(0,n.useEffect)(()=>{if(i&&i.trim()){c(i),g(!1);return}c(null),m()},[t,s,i]);let m=async()=>{try{if(g(!0),"guest"===s){c("Not provided");return}if(t.startsWith("whatsapp_")){let e=t.replace(/^whatsapp_/,"").replace(/\D/g,"");c(e?"+".concat(e):"â");return}if(t.startsWith("email_")){let{getBrowserFirestore:e,collection:r,query:s,where:n,getDocs:i,orderBy:l,limit:o}=await Promise.resolve().then(a.bind(a,72279)),d=e();if(!d){c("Email contact");return}let u=s(r(d,"chats"),n("customerId","==",t),n("isEmailOriginated","==",!0),l("createdAt","desc"),o(1)),g=await i(u),m=g.empty?null:g.docs[0].data();c((null==m?void 0:m.customerEmail)||"Email contact");return}let e=await (0,C.zZ)(t);c(e.phonelocal?"".concat(e.phonecode).concat(e.phonelocal).trim():"Phone not available")}catch(e){c("Not available")}finally{g(!1)}};return u?(0,r.jsxs)("div",{className:"flex items-center gap-2 ".concat(o?"py-0":"py-2.5 px-3"," ").concat(l),children:[(0,r.jsx)("div",{className:"rounded bg-gray-100 dark:bg-gray-700 flex-shrink-0 animate-pulse ".concat(o?"w-3 h-3":"w-3.5 h-3.5")}),(0,r.jsx)("div",{className:"h-3 bg-gray-100 dark:bg-gray-700 rounded animate-pulse ".concat(o?"w-20":"w-24")})]}):(0,r.jsxs)("div",{className:"flex items-center gap-2 ".concat(o?"py-0":"py-2.5 px-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg"," ").concat(l),children:[(0,r.jsx)(b.A,{size:o?12:14,className:"text-gray-500 dark:text-gray-400 flex-shrink-0"}),(0,r.jsx)("span",{className:"font-medium text-gray-900 dark:text-gray-100 truncate ".concat(o?"text-xs":"text-sm"),children:d})]})};var O=a(46197),D=a(65323),R=a(63977),P=a(85491),z=a(32317);let _=e=>{let{customerId:t,customerType:a,className:s="",fullHeight:i=!1,customerPhone:l}=e,{currentUser:o}
1=(0,R.As)(),[d,c]=(0,n.useState)([]),[u,g]=(0,n.useState)(!0),[m,h]=(0,n.useState)(null),[x,p]=(0,n.useState)("all");(0,n.useEffect)(()=>{y()},[t,l,a,o]);let y=async()=>{try{g(!0),h(null);let e=await (0,P.m)({customerId:t,customerPhone:l,customerType:a},o);c(e.map(e=>({id:e.id,status:e.status,dayDate:e.dayDate?new Date(e.dayDate):new Date,serviceTime:e.serviceTime,customerName:e.customerName,address:e.address,details:e.details,totalPrice:e.totalPrice,paymentMethod:e.paymentMethod,companyName:e.companyName,companyLogo:e.companyLogo,createdAt:e.createdAt?new Date(e.createdAt):new Date,isPaid:e.isPaid,country:e.country})))}catch(e){console.error("Error loading customer orders:",e),h(e instanceof Error?e.message:"Failed to load orders")}finally{g(!1)}},b=e=>{if(!e)return"";try{return(0,O.GP)(new Date(e),"EEE d MMM, yyyy")}catch(e){return""}},f=e=>{if(null==e)return"";try{return"".concat(e>12?e-12:0===e?12:e).concat(e>=12?"pm":"am")}catch(e){return""}},v=(e,t)=>{let a=(null==t?void 0:t.toLowerCase())||"kw";return"".concat((0,z.formatCurrencyAmount)(e,a)," ").concat("sa"===a?"SAR":"bh"===a?"BHD":"KWD")},k=e=>{let t=e.toLowerCase();return"new"===t?"bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-300 border-blue-200 dark:border-blue-700":"confirmed"===t?"bg-emerald-100 dark:bg-emerald-900/50 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-700":"delivered"===t?"bg-green-100 dark:bg-green-900/50 text-green-700 dark:text-green-300 border-green-200 dark:border-green-700":"canceled"===t||"cancelled"===t?"bg-amber-100 dark:bg-amber-900/50 text-amber-700 dark:text-amber-300 border-amber-200 dark:border-amber-700":"failed"===t?"bg-red-100 dark:bg-red-900/50 text-red-700 dark:text-red-300 border-red-200 dark:border-red-700":"bg-gray-100 dark:bg-gray-700/50 text-gray-700 dark:text-gray-300 border-gray-200 dark:border-gray-600"},w=d.filter(e=>{if("all"===x)return!0;let t=e.status.toLowerCase(),a=x.toLowerCase();return"canceled"===a?"canceled"===t||"cancelled"===t:t===a}),N=[{value:"all",label:"All",count:d.length},{value:"confirmed",label:"Confirmed",count:d.filter(e=>"confirmed"===e.status.toLowerCase()).length},{value:"delivered",label:"Delivered",count:d.filter(e=>"delivered"===e.status.toLowerCase()).length},{value:"canceled",label:"Canceled",count:d.filter(e=>"canceled"===e.status.toLowerCase()||"cancelled"===e.status.toLowerCase()).length},{value:"failed",label:"Failed",count:d.filter(e=>"failed"===e.status.toLowerCase()).length},{value:"new",label:"New",count:d.filter(e=>"new"===e.status.toLowerCase()).length}].filter(e=>"all"===e.value||e.count>0);return u?(0,r.jsx)("div",{className:"space-y-0 divide-y divide-gray-100 dark:divide-gray-700 ".concat(s),children:[1,2,3,4].map(e=>(0,r.jsxs)("div",{className:"py-2 flex items-center justify-between gap-3 animate-pulse",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[(0,r.jsx)("div",{className:"w-8 h-8 rounded bg-gray-100 dark:bg-gray-700 flex-shrink-0"}),(0,r.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,r.jsx)("div",{className:"h-3.5 bg-gray-100 dark:bg-gray-700 rounded w-3/4"}),(0,r.jsx)("div",{className:"h-2.5 bg-gray-100 dark:bg-gray-700 rounded w-1/2"})]})]}),(0,r.jsxs)("div",{className:"text-right flex-shrink-0 space-y-1",children:[(0,r.jsx)("div",{className:"h-2.5 bg-gray-100 dark:bg-gray-700 rounded w-16 ml-auto"}),(0,r.jsx)("div",{className:"h-3.5 bg-gray-100 dark:bg-gray-700 rounded w-14 ml-auto"})]})]},e))}):m?(0,r.jsx)("div",{className:"py-4 ".concat(s),children:(0,r.jsxs)("div",{className:"text-center text-red-600 dark:text-red-400",children:[(0,r.jsx)("p",{className:"text-sm",children:m}),(0,r.jsx)("button",{onClick:y,className:"text-xs text-red-500 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 mt-2 underline",children:"Retry"})]})}):(0,r.jsxs)("div",{className:"space-y-3 ".concat(s),children:[d.length>0&&N.length>1&&(0,r.jsx)("select",{value:x,onChange:e=>p(e.target.value),className:"w-full text-[11px] px-2 py-1 rounded border border-gray-100 dark:border-gray-600 bg-transparent dark:bg-gray-700/50 text-gray-500 dark:text-gray-400 focus:ring-0 focus:border-gray-300 dark:focus:border-gray-500",children:N.map(e=>(0,r.jsxs)("option",{value:e.value,children:[e.label," (",e.count,")"]},e.value))}),0===w.length?(0,r.jsx)("div",{className:"text-center py-8 text-sm text-gray-500 dark:text-gray-400",children:0===d.length?"guest"===a?"No orders":!function(e){return"string"==typeof e&&e.startsWith("whatsapp_")}(t)?"No orders found":"No orders for this phone number":"No ".concat("all"===x?"":x," orders")}):(0,r.jsx)("div",{className:"space-y-0 divide-y divide-gray-100 dark:divide-gray-700 ".concat(i?"":"max-h-80 overflow-y-auto"),children:w.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>window.open("/admin/order-details/".concat(e.id,"?tab=details"),"_blank","noopener,noreferrer"),className:"w-full text-left py-2 px-0 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors flex items-center justify-between gap-4",title:"View order",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 min-w-0 flex-1 max-w-[65%]",children:[(0,r.jsx)("div",{className:"w-8 h-8 rounded flex items-center justify-center bg-gray-100 dark:bg-gray-700 flex-shrink-0 overflow-hidden",children:e.companyLogo?(0,r.jsx)("img",{src:e.companyLogo,alt:"",className:"w-full h-full object-cover",onError:e=>{e.target.style.display="none"}}):(0,r.jsx)(D.A,{size:14,className:"text-gray-400"})}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsx)("div",{className:"text-sm font-medium text-gray-900 dark:text-white truncate",children:e.details}),(0,r.jsx)("div",{className:"text-xs text-gray-500 dark:text-gray-400 truncate",children:e.companyName}),(0,r.jsxs)("div",{className:"text-xs font-medium text-gray-700 dark:text-gray-200 mt-1 whitespace-nowrap",children:[(0,r.jsx)("span",{children:b(e.dayDate)}),null!=e.serviceTime&&(0,r.jsxs)("span",{className:"text-gray-600 dark:text-gray-300",children:[" \xb7 ",f(e.serviceTime)]})]})]})]}),(0,r.jsxs)("div",{className:"text-right flex-shrink-0 space-y-1 min-w-0",children:[(0,r.jsx)("div",{className:"text-[10px] font-semibold px-1.5 py-0.5 rounded border capitalize inline-block ".concat(k(e.status)),children:e.status}),(0,r.jsx)("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:v(e.totalPrice,e.country)})]})]},e.id))})]})};var F=a(19766),U=a(13843),W=a(90163),L=a(72279);function B(){let e=(0,L.getBrowserFirestore)();if(!e)throw Error("Firebase Firestore is not initialized");return e}let H=e=>{let{customerId:t,customerType:a,currentChatId:s,className:i="",fullHeight:l=!1}
1=e,[o,d]=(0,n.useState)([]),[c,u]=(0,n.useState)(!0),[g,h]=(0,n.useState)(null),[x,p]=(0,n.useState)(null),[b,f]=(0,n.useState)([]),[v,k]=(0,n.useState)(!1);(0,n.useEffect)(()=>{w()},[t]);let w=async()=>{try{u(!0),h(null);let e=t.startsWith("email_");if("guest"===a||e){d([]),u(!1);return}let r=(0,L.query)((0,L.collection)(B(),"chats"),(0,L.where)("customerId","==",t),(0,L.where)("status","==","closed"),(0,L.orderBy)("createdAt","desc"),(0,L.limit)(10));return(0,L.aQ)(r,e=>{let t=e.docs.map(e=>{var t,a,r;let n=e.data();return s&&e.id===s?null:{id:e.id,subject:n.subject||void 0,status:n.status||"closed",createdAt:(null===(t=n.createdAt)||void 0===t?void 0:t.toDate())||new Date,closedAt:(null===(a=n.closedAt)||void 0===a?void 0:a.toDate())||void 0,agentId:n.agentId||void 0,agentName:n.agentName||void 0,lastMessageContent:n.lastMessageContent||void 0,lastMessageAt:(null===(r=n.lastMessageAt)||void 0===r?void 0:r.toDate())||void 0,customerName:n.customerName||"Customer",channel:n.channel||"website",totalMessages:n.totalMessages||0}}).filter(Boolean);d(t),u(!1)},e=>{console.error("Error loading chat history:",e),h(e.message||"Failed to load chat history"),u(!1)})}catch(e){console.error("Error setting up chat history subscription:",e),h(e instanceof Error?e.message:"Failed to load chat history"),u(!1)}},N=(e,t)=>{if(!t)return"Open";let a=Math.floor((t.getTime()-e.getTime())/6e4);if(a<1)return"< 1min";if(a<60)return"".concat(a,"min");let r=Math.floor(a/60),s=a%60;return r<24?s>0?"".concat(r,"h ").concat(s,"m"):"".concat(r,"h"):"".concat(Math.floor(r/24),"d")},j=async e=>{try{k(!0);let t=(0,L.query)((0,L.collection)(B(),"chats",e,"messages"),(0,L.orderBy)("createdAt","asc")),a=(await (0,L.getDocs)(t)).docs.map(e=>{var t;let a=e.data();return{id:e.id,content:a.content||"",senderId:a.senderId||"",senderName:a.senderName||"Unknown",senderType:a.senderType||"system",createdAt:(null===(t=a.createdAt)||void 0===t?void 0:t.toDate())||new Date,isResolution:a.isResolution||!1}});f(a)}catch(e){console.error("Error loading chat messages:",e)}finally{k(!1)}},A=async e=>{x===e?(p(null),f([])):(p(e),await j(e))},C=e=>{navigator.clipboard.writeText(e)};return c?(0,r.jsx)("div",{className:"space-y-0 divide-y divide-gray-100 dark:divide-gray-700 ".concat(i),children:[1,2,3,4].map(e=>(0,r.jsx)("div",{className:"animate-pulse py-3",children:(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,r.jsx)("div",{className:"h-3 bg-gray-100 dark:bg-gray-700 rounded w-3/4"}),(0,r.jsx)("div",{className:"h-2 bg-gray-100 dark:bg-gray-700 rounded w-1/2"})]}),(0,r.jsx)("div",{className:"h-3 w-5 bg-gray-100 dark:bg-gray-700 rounded flex-shrink-0"})]})},e))}):g?(0,r.jsxs)("div",{className:"py-4 text-center text-sm text-red-600 dark:text-red-400 ".concat(i),children:[(0,r.jsx)("p",{children:g}),(0,r.jsx)("button",{onClick:w,className:"mt-2 text-xs underline hover:no-underline",children:"Retry"})]}):(0,r.jsx)("div",{className:"space-y-2 ".concat(i),children:0===o.length?(0,r.jsx)("div",{className:"text-center py-8 text-sm text-gray-500 dark:text-gray-400",children:"guest"===a?"No chat history":"No previous chats"}):(0,r.jsx)("div",{className:"space-y-0 divide-y divide-gray-200 dark:divide-gray-600 ".concat(l?"":"max-h-80 overflow-y-auto"),children:o.map(e=>{let t=x===e.id;return(0,r.jsxs)("div",{className:"transition-colors rounded-sm ".concat(t?"bg-gray-100 dark:bg-gray-700":"bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700/80"),children:[(0,r.jsx)("div",{className:"py-3 cursor-pointer",onClick:()=>A(e.id),children:(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,r.jsx)("span",{className:"text-sm font-medium text-gray-900 dark:text-white truncate",children:e.lastMessageContent?e.lastMessageContent.length>35?e.lastMessageContent.slice(0,35)+"â¦":e.lastMessageContent:e.subject||"Chat"}),(0,r.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400",children:e.channel||"Web"})]}),(0,r.jsxs)("div",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:[e.agentName&&(0,r.jsx)("span",{children:e.agentName}),e.agentName&&(0,r.jsx)("span",{className:"mx-1",children:"\xb7"}),(0,r.jsx)("span",{children:(0,m.OM)(e.createdAt)})]})]}),(0,r.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0",children:[(0,r.jsx)("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:e.totalMessages||0}),t?(0,r.jsx)(F.A,{size:14,className:"text-gray-400 dark:text-gray-500"}):(0,r.jsx)(U.A,{size:14,className:"text-gray-400 dark:text-gray-500"})]})]})}),t&&(0,r.jsx)("div",{className:"border-t border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-800",children:(0,r.jsx)("div",{className:"p-3",children:v?(0,r.jsx)("div",{className:"text-center py-4 text-gray-500 dark:text-gray-400",children:(0,r.jsx)("div",{className:"animate-pulse",children:"Loading conversation..."})}):0===b.length?(0,r.jsx)("div",{className:"text-center py-4 text-gray-500 dark:text-gray-400 text-xs",children:"No messages found for this conversation"}):(0,r.jsxs)("div",{className:"space-y-2 ".concat(l?"":"max-h-64 overflow-y-auto"),children:[b.map((e,t)=>(0,r.jsxs)("div",{className:"p-2 rounded text-xs border ".concat("agent"===e.senderType?"bg-blue-100 dar
1k:bg-blue-900 border-blue-200 dark:border-blue-700 text-blue-900 dark:text-blue-100 ml-4":"customer"===e.senderType?"bg-gray-100 dark:bg-gray-600 border-gray-200 dark:border-gray-500 text-gray-900 dark:text-gray-100 mr-4":"bg-amber-50 dark:bg-amber-900/80 border-amber-200 dark:border-amber-700 text-amber-900 dark:text-amber-100 mx-2 text-center"),children:[(0,r.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,r.jsx)("span",{className:"font-medium",children:e.senderName}),(0,r.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,r.jsx)("span",{className:"text-gray-500 dark:text-gray-400",children:(0,m.kp)(e.createdAt)}),"agent"===e.senderType&&(0,r.jsx)("button",{onClick:t=>{t.stopPropagation(),C(e.content)},className:"text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400",title:"Copy this response",children:(0,r.jsx)(y.A,{size:10})})]})]}),(0,r.jsx)("div",{className:"text-gray-700 dark:text-gray-300 whitespace-pre-wrap",children:e.content}),e.isResolution&&(0,r.jsxs)("div",{className:"mt-1 flex items-center space-x-1",children:[(0,r.jsx)(W.A,{size:10,className:"text-green-500 dark:text-green-400"}),(0,r.jsx)("span",{className:"text-green-600 dark:text-green-400 font-medium",children:"Resolution"})]})]},e.id)),b.length>0&&(0,r.jsxs)("div",{className:"mt-2 pt-2 border-t border-gray-200 dark:border-gray-600 text-[10px] text-gray-500 dark:text-gray-400",children:[b.length," messages \xb7 ",N(e.createdAt,e.closedAt),e.agentName&&" \xb7 ".concat(e.agentName)]})]})})})]},e.id)})})})};var q=a(98477),G=a(14131),V=a(84315),K=a(10405),Y=a(42615),Q=a(51855);let J=e=>{let{onInsertTemplate:t,currentMessage:a="",customerName:s="",orderId:i="",agentName:l="",language:o="en",className:d="",variant:c="default"}=e,[u,g]=(0,n.useState)(!1),[m,h]=(0,n.useState)(""),[x,p]=(0,n.useState)("all"),[b,f]=(0,n.useState)([]),[v,k]=(0,n.useState)(o||"en"),[w,N]=(0,n.useState)(!1),[j,A]=(0,n.use
1State)(null),[C,T]=(0,n.useState)(!1),S=(0,n.useRef)(null),I=(0,n.useRef)(0),E=(0,n.useRef)(!1);(0,n.useEffect)(()=>{T(!0)},[]);let M=[{id:"welcome-greeting",category:"general",shortcut:"/welcome",english:{title:"Welcome Greeting",content:"Hello, welcome to Ghaseel Live Chat."},arabic:{title:"ترØÙب",content:"ÙØ¹ÙÙÙÙ
Ø§ÙØ³ÙاÙ
â¦ Ø´ÙØ±Ø§Ù ÙØ¥Ø®ØªÙار٠تطبÙ٠غسÙÙ"},variables:[],sentiment:"positive"},{id:"how-can-help",category:"general",shortcut:"/help",english:{title:"How Can We Help",content:"How can we assist you?"},arabic:{title:"ÙÙÙ ÙÙ
ÙÙÙØ§ اÙÙ
ساعدة",content:"ØªÙØ¶Ù ØÙÙÙ Ø§ÙØ¯Ø± اساعد٠اÙÙÙÙ
Ø"},variables:[],sentiment:"positive"},{id:"phone-request",category:"general",shortcut:"/phone",english:{title:"Phone Number Request",content:"Please send us your mobile number to follow-up your order?"},arabic:{title:"Ø·ÙØ¨ رÙÙ
اÙÙØ§ØªÙ",content:"Ø§ÙØ±Ø¬Ø§Ø¡ إرسا٠رÙÙ
اÙÙØ§ØªÙ Ø§ÙØ®Ø§Øµ ÙÙÙ ÙÙ
تابعة Ø§ÙØ·Ùب Ø"},variables:[],sentiment:"neutral"},{id:"follow-up-confirmation",category:"general",shortcut:"/followup",english:{title:"Follow-up Confirmation",content:"We will follow up with your order request and get back to you in a minute."},arabic:{title:"تأÙÙØ¯ اÙÙ
تابعة",content:"عÙÙØ§Ù ØØ¯ÙØ§Ø¦Ù ÙØªØ£Ùد Ù
Ù Ø§ÙØ·Ùب ÙÙØ±Ø¯ عÙÙ٠بأسرع ÙÙØª Ù
Ù
ÙÙ."},variables:[],sentiment:"positive"},{id:"waiting-apology",category:"general",shortcut:"/waiting",english:{title:"Waiting Apology",content:"Thank y
1ou for waiting and sorry for the delay"},arabic:{title:"اعتذار Ø¹Ù Ø§ÙØ§Ùتظار",content:"Ø´ÙØ±Ø§Ù عÙÙ Ø§ÙØ¥Ùتظار ÙÙØ¹ØªØ°Ø± عÙÙ Ø§ÙØ¥Ø·Ø§ÙÙ"},variables:[],sentiment:"negative"},{id:"additional-help",category:"general",shortcut:"/morehelp",english:{title:"Additional Help Offer",content:"Let me know if there's anything else I can help you with"},arabic:{title:"عرض Ù
ساعدة إضاÙÙØ©",content:"ا٠Ù
Ø³Ø§Ø¹Ø¯Ù Ø§Ù Ø§Ø³ØªÙØ³Ø§Ø± اخر Ø§ÙØ¯Ø± اÙÙØ¯Ù ÙÙÙ Ø"},variables:[],sentiment:"positive"},{id:"thank-you-closing",category:"general",shortcut:"/thanks",english:{title:"Thank You & Closing",content:"Thanks again for choosing Ghaseel! I wish you a happy day!"},arabic:{title:"Ø´ÙØ± ÙØ¥ÙÙØ§Ø¡",content:"Ø´ÙØ±Ø§Ù ÙÙ Ù
رة أخر٠عÙÙ Ø§Ø®ØªÙØ§Ø±Ù غسÙÙ ! أتÙ
ÙÙ ÙÙ ÙÙÙ
Ø§Ù Ø³Ø¹ÙØ¯Ø§Ù"},variables:[],sentiment:"positive"},{id:"arrival-time-confirmation",category:"delivery",shortcut:"/arrivaltime",english:{title:"Arrival Time Confirmation",content:"The arrival time you selected is from to. During that hour the company will arrive at your location. and we will contact them now to contact you shortly."},arabic:{title:"تأÙÙØ¯ ÙÙØª اÙÙØµÙÙ",content:"ÙÙØª اÙÙØµÙ٠اÙÙ
ØØ¯Ø¯ Ù
Ù Ø®ÙØ§ÙÙÙ
Ù
Ù ( ) Ø¥ÙÙ ( ) ÙÙ Ø®ÙØ§Ù ÙØ°Ù Ø§ÙØ³Ø§Ø¹Ø© سÙÙ ÙØªÙ
اÙÙØµÙÙ ÙÙÙ
ÙÙØ¹ اÙÙ
ØØ¯Ø¯ ÙØ³ÙÙ ÙØªÙ
اÙÙØ§ØµÙ Ù
ع Ø§ÙØ´Ø±ÙÙ ÙÙØªÙاص٠Ù
عاÙÙ
ÙÙ Ø§ÙØ±Ø¨ ÙÙØª Ù
Ù
ÙÙ"},variables:[],sentiment:"positive"},{id:"bank-refund-processing",category:"refund",shortcut:"/bankrefund",english:{title:"Bank Refund Processing",content:"For the payment do you prefer it to be returned to your wallet or bank(for the bank it will take ( 2-5 work days)?"},arabic:{title:"Ù
Ø¹Ø§ÙØ¬Ø© Ø§ÙØ§Ø³ØªØ±Ø¯Ø§Ø¯ Ø§ÙØ¨ÙÙÙ",content:"تÙ
ØªÙØ¯ÙÙ
Ø·ÙØ¨ Ø§ÙØ§Ø³ØªØ±Ø¬Ø§Ø¹ Ø§ÙØ¨ÙÙÙ ÙÙ
تÙÙØ¹ Ø§Ø³ØªÙØ§Ù
اÙÙ
Ø¨ÙØº ÙÙ Ø®ÙØ§Ù Ù¢-Ù¥ Ø§ÙØ§Ù
عÙ
Ù"},variables:[],sentiment:"neutral"},{id:"delay-apology-company-contact",category:"delivery",shortcut:"/delaycontact",english:{title:"Delay Apology with Company Contact",content:"We apologize for the delay. We have contacted the company and the team will c
1ontact you as soon as possible."},arabic:{title:"اعتذار Ø¹Ù Ø§ÙØªØ£Ø®Ùر Ù
ع ØªÙØ§ØµÙ Ø§ÙØ´Ø±ÙØ©",content:"ÙØ¹ØªØ°Ø± Ù
ÙÙÙ
عÙÙ Ø§ÙØªØ§Ø®Ùر تÙ
Ø§ÙØªÙاص٠Ù
ع Ø§ÙØ´Ø±ÙÙ ÙØ³ÙÙ ÙØªÙ
Ø§ÙØªÙاص٠Ù
عاÙÙ
Ù
Ù Ø®ÙØ§Ù اÙÙØ±ÙÙ Ù٠اسرع ÙÙØª Ù
Ù
ÙÙ"},variables:[],sentiment:"negative"},{id:"order-cancellation-wallet",category:"refund",shortcut:"/cancelwallet",english:{title:"Order Cancellation with Wallet Refund",content:"Your order has been cancelled and the amount has been put to your app wallet. You can use the amount at any time convenient for you."},arabic:{title:"Ø¥ÙØºØ§Ø¡ Ø§ÙØ·Ùب Ù
ع استرداد اÙÙ
ØÙظة",content:"تÙ
Ø§ÙØºØ§Ø¡ Ø§ÙØ·Ùب Ø§ÙØ®Ø§Øµ ÙÙÙÙ
ÙØ¥Ø¶Ø§ÙØ© اÙÙ
Ø¨ÙØº ÙÙÙ
بÙ
ØÙظة Ø§ÙØªØ·Ø¨ÙÙ ØªØ³ØªØ·ÙØ¹ استخداÙ
اÙÙ
Ø¨ÙØº Ù٠ا٠ÙÙØª Ù
ÙØ§Ø³Ø¨ ÙÙÙ
"},variables:[],sentiment:"neutral"}];(0,n.useEffect)(()=>{f(M)},[]),(0,n.useEffect)(()=>{if(!E.current)if(a&&a.includes("/")){let e=a.split("/"),t=e[e.length-1];e.length>1&&t.length>0?(h(t),N(!0),g(!0)):a.endsWith("/")?(h(""),N(!0),g(!0)):N(!1)}else N(!1),w&&g(!1)},[a,w]);let O=()=>{E.current=!0,g(!1),N(!1),I.current+=1,setTimeout(()=>{E.current=!1},100)},D=()=>{E.current=!0,g(!1),N(!1),A(null),I.current+=1,setTimeout(()=>{E.current=!1},100)};(0,n.useEffect)(()=>{if(!u)return;let e=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),O(),setTimeout(()=>{u&&D()},50))};return document.addEventListener("keydown",e,{capture:!0}),()=>document.removeEventListener("keydown",e,{capture:!0})},[u]),(0,n.useEffect)(()=>(u?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[u]);let R=b.filter(e=>{let t=""===m||e.english.title.toLowerCase().includes(m.toLowerCase())||e.english.content.toLowerCase().includes(m.toLowerCase())||e.arabic.title.includes(m)||e.arabic.content.includes(m)||e.shortcut.toLowerCase().includes(m.toLowerCase()),a="all"===x||e.category===x;return t&&a}),P=e=>{t("ar"===v?e.arabic.content:e.english.content),g(!1),N(!1)},z=async e=>{let t="ar"===v?e.arabic.content:e.english.content;try{await navigator.clipboard.writeText(t),A(e.id),setTimeout(()=>A(null),2e3)}catch(e){console.error("Failed to copy template:",e)}},_=e=>{switch(e){case"positive":return"text-green-600 dark:text-green-400";case"negative":return"text-red-600 dark:text-red-400";default:return"text-blue-600 dark:text-blue-400"}},F=e=>{switch(e){case"positive":return"bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800";case"negative":return"bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800";default:return"bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800"}},U=["all",...Array.from(new Set(b.map(e=>e.category)))],W=u&&C?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-[9998]",onClick:e=>{e.preventDefault(),e.stopPropagation(),O(),setTimeout(()=>{u&&D()},50)}}),(0,r.jsxs)("div",{ref:S,className:"fixed top-0 left-0 right-0 bottom-0 sm:top-1/2 sm:left-1/2 sm:right-auto sm:bottom-auto sm:transform sm:-translate-x-1/2 sm:-translate-y-1/2 w-full sm:w-[500px] max-w-none sm:max-w-[95vw] h-full sm:h-auto sm:max-h-[90vh] bg-white dark:bg-gray-800 border-0 sm:border border-gray-200 dark:border-gray-700 rounded-none sm:rounded-2xl shadow-2xl z-[9999] overflow-hidden flex flex-col",onClick:e=>e.stopPropagation(),children:[(0,r.jsxs)("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700 bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-gray-800 dark:to-gray-700",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between mb-3",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[(0,r.jsx)("div",{className:"p-1.5 bg-blue-100 dark:bg-blue-900/30 rounded-lg flex-shrink-0",children:(0,r.jsx)(G.A,{className:"w-4 h-4 text-blue-600 dark:text-blue-400"})}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsx)("h3",{className:"text-lg font-bold text-gray-900 dark:text-white truncate",children:"Qu
1ick Response Templates"}),(0,r.jsxs)("p",{className:"text-xs text-gray-600 dark:text-gray-400",children:[R.length," template",1!==R.length?"s":""," available"]})]})]}),(0,r.jsx)("button",{onClick:e=>{e.preventDefault(),e.stopPropagation(),O(),setTimeout(()=>{u&&D()},50)},className:"p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors flex-shrink-0",children:(0,r.jsx)(V.A,{className:"w-5 h-5"})})]}),(0,r.jsxs)("div",{className:"relative mb-3",children:[(0,r.jsx)(K.A,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),(0,r.jsx)("input",{type:"text",placeholder:"Search templates...",value:m,onChange:e=>h(e.target.value),className:"w-full pl-10 pr-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400 focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"})]}),(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1 bg-gray-100 dark:bg-gray-700 rounded-lg p-0.5",children:[(0,r.jsx)("button",{onClick:()=>k("en"),className:"px-2 py-1 text-xs font-medium rounded-md transition-all duration-200 ".concat("en"===v?"bg-white dark:bg-gray-600 text-blue-700 dark:text-blue-300 shadow-sm":"text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200"),children:"\uD83C\uDDFA\uD83C\uDDF8 EN"}),(0,r.jsx)("button",{onClick:()=>k("ar"),className:"px-2 py-1 text-xs font-medium rounded-md transition-all duration-200 ".concat("ar"===v?"bg-white dark:bg-gray-600 text-blue-700 dark:text-blue-300 shadow-sm":"text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200"),children:"\uD83C\uDDF8\uD83C\uDDE6 ع"})]}),(0,r.jsx)("div",{className:"flex items-center gap-1",children:U.map(e=>(0,r.jsx)("button",{onClick:()=>p(e),className:"px-2 py-1 text-xs font-medium rounded-md transition-all duration-200 ".concat(x===e?"bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 shadow-sm":"text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-600 hover:text-gray-900 dark:hover:text-gray-200"),children:"all"===e?"All":e.charAt(0).toUpperCase()+e.slice(1)},e))})]})]}),(0,r.jsx)("div",{className:"flex-1 overflow-y-auto scrollbar-thin scrollbar-thumb-gray-300 dark:scrollbar-thumb-gray-600 scrollbar-track-gray-100 dark:scrollbar-track-gray-800",children:0===R.length?(0,r.jsxs)("div",{className:"p-6 sm:p-8 text-center",children:[(0,r.jsx)("div",{className:"w-12 h-12 sm:w-16 sm:h-16 mx-auto mb-4 bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center",children:(0,r.jsx)(K.A,{className:"w-6 h-6 sm:w-8 sm:h-8 text-gray-400"})}),(0,r.jsx)("h4",{className:"text-base sm:text-lg font-medium text-gray-900 dark:text-white mb-2",children:"No templates found"}),(0,r.jsx)("p",{className:"text-xs sm:text-sm text-gray-500 dark:text-gray-400",children:"Try adjusting your search or category filter"})]}):(0,r.jsx)("div",{className:"p-2",children:R.map((e,t)=>{let a="ar"===v?e.arabic.content:e.english.content,s="ar"===v?e.arabic.title:e.english.title;return(0,r.jsx)("div",{className:"group p-3 sm:p-4 mb-2 sm:mb-3 rounded-xl border transition-all duration-200 hover:shadow-md hover:scale-[1.01] sm:hover:scale-[1.02] cursor-pointer ".concat(F(e.sentiment)," border-gray-200 dark:border-gray-600 hover:border-blue-300 dark:hover:border-blue-600"),onClick:()=>P(e),children:(0,r.jsxs)("div",{className:"flex items-start justify-between gap-2 sm:gap-3",children:[(0,r.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1 sm:gap-2 mb-2 flex-wrap",children:[(0,r.jsx)("span",{className:"text-xs font-mono text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-700 px-2 py-1 rounded-md font-medium",children:e.shortcut}),(0,r.jsx)("span",{className:"text-xs font-semibold px-2 py-1 rounded-full ".concat(_(e.sentiment)," bg-opacity-20"),children:e.sentiment}),(0,r.jsx)("span",{className:"text-xs text-gray-400 dark:text-gray-500 uppercase tracking-wide hidden sm:inline",children:e.category})]}),(0,r.jsx)("h4",{className:"font-semibold text-gray-900 dark:text-white mb-2 text-sm sm:text-base",children:s}),(0,r.jsx)("p",{className:"text-xs sm:text-sm text-gray-600 dark:text-gray-300 leading-relaxed line-clamp-2 sm:line-clamp-3",children:a})]}),(0,r.jsxs)("div",{className:"flex items-center gap-1 opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity duration-200",children:[(0,r.jsx)("button",{onClick:t=>{t.stopPropagation(),z(e)},className:"p-1.5 sm:p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-all duration-200",title:"Copy template",children:j===e.id?(0,r.jsx)(Y.A,{className:"w-3 h-3 sm:w-4 sm:h-4 text-green-500"}):(0,r.jsx)(y.A,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),(0,r.jsx)("button",{onClick:t=>{t.stopPropagation(),P(e)}
1,className:"p-1.5 sm:p-2 text-blue-500 hover:text-blue-600 dark:hover:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg transition-all duration-200",title:"Insert template",children:(0,r.jsx)(Q.A,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]})]})},e.id)})})}),(0,r.jsx)("div",{className:"p-3 sm:p-4 border-t border-gray-200 dark:border-gray-700 bg-gradient-to-r from-gray-50 to-blue-50 dark:from-gray-800 dark:to-gray-700",children:(0,r.jsxs)("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-2 sm:gap-0",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 sm:gap-4 text-xs text-gray-500 dark:text-gray-400",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1",children:[(0,r.jsx)("kbd",{className:"px-1.5 sm:px-2 py-1 bg-gray-200 dark:bg-gray-600 rounded text-xs font-mono",children:"/"}),(0,r.jsx)("span",{className:"hidden sm:inline",children:"for shortcuts"}),(0,r.jsx)("span",{className:"sm:hidden",children:"shortcuts"})]}),(0,r.jsxs)("div",{className:"flex items-center gap-1",children:[(0,r.jsx)("kbd",{className:"px-1.5 sm:px-2 py-1 bg-gray-200 dark:bg-gray-600 rounded text-xs font-mono",children:"Esc"}),(0,r.jsx)("span",{className:"hidden sm:inline",children:"to close"}),(0,r.jsx)("span",{className:"sm:hidden",children:"close"})]})]}),(0,r.jsxs)("div",{className:"text-xs text-gray-400 dark:text-gray-500",children:[R.length," of ",b.length," templates"]})]})})]})]}):null,L="compact"===c;return(0,r.jsxs)("div",{className:"relative ".concat(d),children:[(0,r.jsxs)("button",{onClick:()=>g(!u),className:"flex items-center justify-center text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors flex-shrink-0 ".concat(L?"w-[38px] h-[38px] rounded-lg border border-gray-300 dark:border-gray-600":"gap-2 px-3 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"),title:"Templates",children:[(0,r.jsx)(G.A,{className:"w-4 h-4"}),!L&&(0,r.jsx)("span",{children:"Templates"})]}),C&&(0,q.createPortal)(W,document.body)]})};var X=a(44065),Z=a(98578),$=a(97174),ee=a(2678),et=a(48375);let ea=(0,et.A)("thumbs-down",[["path",{d:"M17 14V2",key:"8ymqnk"}],["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"}]]);async function er(e){let t=await fetch("/api/admin/chat-copilot-feedback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),a=await t.json();if(!t.ok||!a.success)throw Error(a.error||"Failed to save feedback")}function es(e){let{chatId:t,orderId:a,onInsertDraft:s,onDraftSessionStarted:i,disabled:l=!1,preload:o=!1,refreshKey:d="",className:c=""}=e,[u,g]=(0,n.useState)(!1),[m,h]=(0,n.useState)(!1),[x,p]=(0,n.useState)(!1),[y,b]=(0,n.useState)(null),[f,v]=(0,n.useState)(null),k=(0,n.useRef)(0),w=(0,n.useRef)(!1);(0,n.useEffect)(()=>{k.current+=1,p(!1),b(null),g(!1),h(!1),v(null),w.current=!1},[t,a]);let N=(0,n.useCallback)(async e=>{var r,s;let n=++k.current,i=null!==(r=null==e?void 0:e.silent)&&void 0!==r&&r;null!==(s=null==e?void 0:e.openOnComplete)&&void 0!==s&&s&&(w.current=!0),g(!0),h(!1),v(null);let l=i?null:A.oR.loading("Generating suggestionâ¦");try{let e=await fetch("/api/admin/chat-suggestions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chatId:t,...a?{orderId:a}:{}})}),r=await e.json();if(!e.ok||!r.success)throw Error(r.error||"Failed to generate suggestion");if(n!==k.current)return;let s=r.data;b(s),h(!0),(openWhenComplete||w.current)&&(p(!0),w.current=!1)}catch(e){if(n!==k.current)return;i||A.oR.error(e instanceof Error?e.message:"Could not generate suggestion"),h(!1)}finally{l&&A.oR.dismiss(l),n===k.current&&g(!1)}},[t,a]);(0,n.useEffect)(()=>{if(!o||l){o||(k.current+=1,h(!1),b(null),g(!1),p(!1));return}N({silent:!0,openOnComplete:!1})},[o,l,t,a,d,N]);let j=async e=>{if(!(null==y?void 0:y.feedbackId)){s(e),p(!1);return}try{await er({feedbackId:y.feedbackId,action:"use_draft",suggestedReply:e}),null==i||i({feedbackId:y.feedbackId,suggestedReply:e})}catch(e){console.warn("[ChatSuggestionPanel] use_draft feedback failed",e)}s(e),p(!1)},C=async e=>{if((null==y?void 0:y.feedbackId)&&!f)try{await er({feedbackId:y.feedbackId,action:"rate",rating:e}),v(e),A.oR.success("Thanks for the feedback")}catch(e){A.oR.error(e instanceof Error?e.message:"Could not save rating")}};return(0,r.jsxs)("div",{className:"relative ".concat(c),children:[(0,r.jsxs)("button",{type:"button",onClick:()=>
1{if(y&&m){p(!0);return}N({openOnComplete:!0})},disabled:l,title:m?"Suggested reply ready":u?"Generating suggestionâ¦":"Suggest reply (AI)",className:"relative flex items-center justify-center min-w-[38px] h-[38px] rounded-lg border transition-colors ".concat(l?"border-gray-200 dark:border-gray-700 text-gray-400 cursor-not-allowed":m?"border-violet-300 dark:border-violet-700 text-violet-700 dark:text-violet-300 bg-violet-50 dark:bg-violet-950/40":"border-violet-200 dark:border-violet-800 text-violet-600 dark:text-violet-400 hover:bg-violet-50 dark:hover:bg-violet-950/40"),children:[u?(0,r.jsx)(X.A,{size:18,className:"animate-spin"}):(0,r.jsx)(Z.A,{size:18}),m&&!u?(0,r.jsx)("span",{className:"absolute -top-0.5 -right-0.5 h-2.5 w-2.5 rounded-full bg-green-500 ring-2 ring-white dark:ring-gray-800"}):null]}),x&&y?(0,r.jsx)("div",{className:"absolute bottom-full right-0 mb-2 z-50 w-[min(24rem,calc(100vw-1.5rem))]",children:(0,r.jsxs)("div",{className:"rounded-lg border border-violet-200 dark:border-violet-800 bg-white dark:bg-gray-900 shadow-lg p-3 text-sm",children:[(0,r.jsxs)("div",{className:"flex items-start justify-between gap-2 mb-2",children:[(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsx)("p",{className:"font-medium text-violet-700 dark:text-violet-300",children:"Suggested reply"}),(0,r.jsxs)("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:[y.suggestion.intent," \xb7 ",y.suggestion.confidence," confidence",y.focusedOrder?" \xb7 order ".concat(y.focusedOrder.id):""]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>p(!1),className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 p-1","aria-label":"Dismiss suggestion",children:(0,r.jsx)(V.A,{size:16})})]}),y.suggestion.reasoning?(0,r.jsx)("p",{className:"text-xs text-gray-600 dark:text-gray-400 mb-2",children:y.suggestion.reasoning}):null,y.warnings.length>0?(0,r.jsx)("div",{className:"mb-2 rounded-md bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 px-2 py-1.5",children:y.warnings.map(e=>(0,r.jsxs)("p",{className:"text-xs text-amber-800 dark:text-amber-200 flex gap-1",children:[(0,r.jsx)($.A,{size:12,className:"shrink-0 mt-0.5"}),(0,r.jsx)("span",{children:e.message})]},e.code))}):null,(0,r.jsx)("div",{className:"rounded-md bg-gray-50 dark:bg-gray-800 p-2 text-gray-900 dark:text-gray-100 whitespace-pre-wrap max-h-40 overflow-y-auto",children:y.suggestion.suggestedReply}),y.suggestion.suggestedReplyAlt?(0,r.jsxs)("div",{className:"mt-2",children:[(0,r.jsx)("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1",children:"Alternate language"}),(0,r.jsx)("div",{className:"rounded-md bg-gray-50 dark:bg-gray-800 p-2 text-gray-700 dark:text-gray-300 whitespace-pre-wrap max-h-32 overflow-y-auto text-xs",children:y.suggestion.suggestedReplyAlt})]}):null,(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-2 mt-3",children:[(0,r.jsx)("button",{type:"button",onClick:()=>void j(y.suggestion.suggestedReply),className:"px-3 py-1.5 rounded-md bg-violet-600 hover:bg-violet-700 text-white text-xs font-medium",children:"Use draft"}),y.suggestion.suggestedReplyAlt?(0,r.jsx)("button",{type:"button",onClick:()=>void j(y.suggestion.suggestedReplyAlt),className:"px-3 py-1.5 rounded-md border border-violet-300 dark:border-violet-700 text-violet-700 dark:text-violet-300 text-xs font-medium hover:bg-violet-50 dark:hover:bg-violet-950/30",children:"Use alternate"}):null,(0,r.jsx)("button",{type:"button",onClick:()=>void N({openOnComplete:!0}),disabled:u,className:"px-3 py-1.5 rounded-md text-xs text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200",children:"Regenerate"}),(0,r.jsxs)("div",{className:"flex items-center gap-1 ml-auto",children:[(0,r.jsx)("button",{type:"button",onClick:()=>void C("up"),disabled:!!f,title:"Useful suggestion",className:"p-1.5 rounded-md border text-xs ".concat("up"===f?"border-green-300 bg-green-50 text-green-700 dark:border-green-800 dark:bg-green-950/40 dark:text-green-300":"border-gray-200 dark:border-gray-700 text-gray-500 hover:text-green-600"),children:(0,r.jsx)(ee.A,{size:14})}),(0,r.jsx)("button",{type:"button",onClick:()=>void C("down"),disabled:!!f,title:"Not useful",className:"p-1.5 rounded-md border text-xs ".concat("down"===f?"border-red-300 bg-red-50 text-red-700 dark:border-red-800 dark:bg-red-950/40 dark:text-red-300":"border-gray-200 dark:border-gray-700 text-gray-500 hover:text-red-600"),children:(0,r.jsx)(ea,{size:14})})]})]})]})}):null]})}let en={mentioned_in_chat:"Mentioned in chat",chat_linked:"Linked to chat",nearest_slot:"Nearest active order",none:"No order focus"};function ei(e){let{orderId:t,focusedOrder:a,candidates:s=[],reason:i="none",loading:l=!1,onSelectOrder:o,className:d=""}
1=e,[c,u]=(0,n.useState)(!1);if(l)return(0,r.jsxs)("div",{className:"flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400 ".concat(d),children:[(0,r.jsx)(X.A,{size:12,className:"animate-spin"}),(0,r.jsx)("span",{children:"Focusing order for AIâ¦"})]});let g=s.length>0,m=a?"".concat(a.service," \xb7 ").concat(a.status," \xb7 ").concat(a.companyName):"No order focus";return(0,r.jsxs)("div",{className:"relative ".concat(d),children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,r.jsxs)("button",{type:"button",onClick:()=>g&&u(e=>!e),disabled:!g,className:"inline-flex items-center gap-1.5 max-w-full rounded-md border px-2 py-1 text-xs ".concat(t?"border-violet-200 dark:border-violet-800 bg-violet-50/70 dark:bg-violet-950/30 text-violet-800 dark:text-violet-200":"border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800 text-gray-600 dark:text-gray-400"," ").concat(g?"hover:bg-violet-100/80 dark:hover:bg-violet-950/50":""),title:en[i],children:[(0,r.jsx)(D.A,{size:12,className:"shrink-0"}),(0,r.jsx)("span",{className:"truncate",children:t?"#".concat(t.slice(0,8)," \xb7 ").concat(m):m}),g?(0,r.jsx)(U.A,{size:12,className:"shrink-0"}):null]}),(0,r.jsx)("span",{className:"text-[11px] text-gray-500 dark:text-gray-400",children:en[i]})]}),c&&g?(0,r.jsxs)("div",{className:"absolute bottom-full left-0 mb-1 z-50 w-[min(20rem,calc(100vw-2rem))] rounded-md border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 shadow-lg py-1",children:[(0,r.jsx)("button",{type:"button",onClick:()=>{o(void 0),u(!1)},className:"w-full text-left px-3 py-2 text-xs text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-800",children:"Auto focus"}),s.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>{o(e.id),u(!1)},className:"w-full text-left px-3 py-2 text-xs hover:bg-gray-50 dark:hover:bg-gray-800 ".concat(e.id===t?"text-violet-700 dark:text-violet-300":"text-gray-800 dark:text-gray-200"),children:[(0,r.jsxs)("div",{className:"font-medium",children:["#",e.id.slice(0,8)," \xb7 ",e.service]}),(0,r.jsxs)("div",{className:"text-[11px] text-gray-500 dark:text-gray-400",children:[e.status," \xb7 ",e.companyName,e.dayDate?" \xb7 ".concat(function(e){let t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}(e.dayDate)):""]})]},e.id))]}):null]})}var el=a(89406);function eo(){let e=(0,L.getBrowserFirestore)();if(!e)throw Error("Firebase Firestore is not initialized");return e}let ed="presenceSessions";async function ec(e){let t=(0,L.query)((0,L.collection)(eo(),ed),(0,L.where)("agentId","==",e),(0,L.where)("isOpen","==",!0),(0,L.limit)(5)),a=await (0,L.getDocs)(t);if(a.empty)return;let r=(0,L.wP)(eo());a.docs.forEach(e=>{r.update(e.ref,{isOpen:!1,endedAt:(0,L.O5)(),status:"offline"})}),await r.commit()}
1async function eu(e,t){if(null==e?void 0:e.trim())try{if(await ec(e),"offline"===t)return;let a=(0,L.doc)((0,L.collection)(eo(),ed));await (0,L.BN)(a,{agentId:e.trim(),status:t,startedAt:(0,L.O5)(),endedAt:null,isOpen:!0})}catch(a){console.warn("[presenceSessionService] logAgentPresenceChange",e,t,a)}}function eg(){let e=(0,L.getBrowserFirestore)();if(!e)throw Error("Firebase Firestore is not initialized");return e}class em{static timestampToMillis(e){if(null==e)return null;try{if("function"==typeof e.toDate){var t;let a=e.toDate(),r=null==a?void 0:null===(t=a.getTime)||void 0===t?void 0:t.call(a);if("number"==typeof r&&!Number.isNaN(r))return r}let a=e.seconds;if("number"==typeof a){let t=e.nanoseconds||0;return 1e3*a+Math.floor(t/1e6)}}catch(e){}return null}static getTimeSinceActivityMillis(e,t){var a;let r=this.timestampToMillis(e.lastActivity),s=this.timestampToMillis(e.lastSeen),n=null!==(a=null!=r?r:s)&&void 0!==a?a:null;return null==n?e.isOnline?0:Number.POSITIVE_INFINITY:t-n}static async setUserOnline(e,t){let a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"available",r=arguments.length>3?arguments[3]:void 0;try{let s={userId:e,userType:t,isOnline:!0,status:a,lastSeen:(0,L.O5)(),lastActivity:(0,L.O5)(),...r};await (0,L.BN)((0,L.doc)(eg(),"userPresence",e),s),"agent"===t&&eu(e,a),this.startHeartbeat(e,t)}catch(e){console.error("Error setting user online:",e)}}static async updatePresenceStatus(e,t,a){try{await (0,L.updateDoc)((0,L.doc)(eg(),"userPresence",e),{status:t,lastActivity:(0,L.O5)()}),"agent"===a&&eu(e,t)}catch(e){console.error("Error updating presence status:",e)}}static async updateActivity(e){try{await (0,L.updateDoc)((0,L.doc)(eg(),"userPresence",e),{lastActivity:(0,L.O5)(),isOnline:!0})}catch(e){console.error("Error updating user activity:",e)}}static async setUserOffline(e,t){try{await (0,L.updateDoc)((0,L.doc)(eg(),"userPresence",e),{isOnline:!1,status:"offline",lastSeen:(0,L.O5)()}),"agent"===t&&eu(e,"offline"),this.stopHeartbeat(e)}catch(e){console.error("Error setting user offline:",e)}}static startHeartbeat(e,t){this.stopHeartbeat(e);let a=setInterval(()=>{this.updateActivity(e)},this.HEARTBEAT_INTERVAL);this.heartbeatIntervals.set(e,a)}static stopHeartbeat(e){let t=this.heartbeatIntervals.get(e);t&&(clearInterval(t),this.heartbeatIntervals.delete(e))}static subscribeToOnlineStatus(e,t){let a=(0,L.collection)(eg(),"userPresence");return(0,L.aQ)(a,t=>{let a=[],r=[];t.forEach(e=>{let t=e.data(),s=t.userId||e.id,n={...t,userId:s},i=Date.now(),l=this.getTimeSinceActivityMillis(t,i);t.isOnline&&l<this.OFFLINE_TIMEOUT?a.push(n):(r.push({...n,isOnline:!1,status:"offline"}),t.isOnline&&this.setUserOffline(s,t.userType))}),e({onlineUsers:a,offlineUsers:r,totalOnline:a.length})},t)}static subscribeToUserStatus(e,t,a){return(0,L.aQ)((0,L.doc)(eg(),"userPresence",e),a=>{if(a.exists()){let r=a.data(),s=Date.now(),n=this.getTimeSinceActivityMillis(r,s);r.isOnline&&n>=this.OFFLINE_TIMEOUT?(t({...r,isOnline:!1,status:"offline"}),this.setUserOffline(e,r.userType)):t(r)}else t(null)},a)}static subscribeToOnlineUsersByType(e,t,a){let r=(0,L.query)((0,L.collection)(eg(),"userPresence"),(0,L.where)("userType","==",e),(0,L.where)("isOnline","==",!0));return(0,L.aQ)(r,e=>{let a=[];e.forEach(e=>{let t=e.data(),r=Date.now();this.getTimeSinceActivityMillis(t,r)<this.OFFLINE_TIMEOUT&&a.push({...t,userId:t.userId||e.id})}),t(a)},a)}static async cleanup(e,t){try{await this.setUserOffline(e,t),this.stopHeartbeat(e)}catch(e){console.error("Error during cleanup:",e)}}static initializeBrowserCleanup(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"agent",a=()=>{navigator,this.cleanup(e,t)};window.addEventListener("beforeunload",a),window.addEventListener("unload",a),window.addEventListener("pagehide",a);let r=()=>{this.updatePresenceStatus(e,"available",t),this.updateActivity(e)};document.addEventListener("visibilitychange",()=>{document.hidden?this.updatePresenceStatus(e,"away",t):r()}),window.addEventListener("pageshow",e=>{e.persisted&&r()}),window.addEventListener("focus",()=>{r()}),window.addEventListener("blur",()=>{this.updatePresenceStatus(e,"away",t)})}static async getMultipleUsersStatus(e){let t=new Map;try{let a=e.map(async e=>{var a;let r=(0,L.doc)(eg(),"userPresence",e),s=await (null===(a=r.get)||void 0===a?void 0:a.call(r))||null;if(s&&s.exists()){let a=s.data(),r=Date.now(),n=this.getTimeSinceActivityMillis(a,r);a.isOnline&&n<this.OFFLINE_TIMEOUT?t.set(e,a):t.set(e,{...a,isOnline:!1,status:"offline"})}else t.set(e,null)});await Promise.all(a)}catch(e){console.error("Error getting multiple users status:",e)}return t}}em.heartbeatIntervals=new Map,em.HEARTBEAT_INTERVAL=3e4,em.OFFLINE_TIMEOUT=24e4;var eh=a(51140),ex=a(93427),ep=a(95487),ey=a(29362);a(73701);var eb=a(56861),ef=a(33029),ev=a(98689),ek=a(48922);let ew=(0,et.A)("circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);var eN=a(31400),ej=a(13974);let eA=(0,et.A)("menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]),eC=(0,et.A)("chart-column",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]]),eT=(0,et.A)("wifi",[["path",{d:"M12 20h.01",key:"zekei9"}
1],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]);var eS=a(72043),eI=a(42387);let eE=(0,et.A)("panel-right",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);var eM=a(60857),eO=a(78641);let eD=(0,et.A)("history",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);var eR=a(98928);function eP(e){return"open"===e.status&&(!e.agentId||!!(e.hasUnreadMessages&&"customer"===e.lastMessageSender))}function ez(e){let t=(0,eh.getChatWaitSeconds)(e);return t<86400?(0,ex.nI)(t):(0,m.OM)(e.lastMessageAt||e.createdAt)}function e_(e){return"whatsapp"===e.channel||"string"==typeof e.customerId&&e.customerId.startsWith("whatsapp_")}function eF(e){return"whatsapp"===e.channel}function eU(e){var t;return"image"===e.messageType&&!!(null===(t=e.fileUrl)||void 0===t?void 0:t.trim())}function eW(e,t,a){var r;let s=null!==(r=t[e.id])&&void 0!==r?r:"unknown",n=e.id===a?" (you)":"";return"".concat("available"===s?"\uD83D\uDFE2":"busy"===s?"\uD83D\uDD34":"away"===s?"\uD83D\uDFE1":"offline"===s?"â«":"âª"," ").concat("available"===s?"Available":"busy"===s?"Busy":"away"===s?"Away":"offline"===s?"Offline":"Unknown"," \xb7 ").concat(e.fullName).concat(n)}let eL=()=>{var e,t,i;let u=(0,s.useRouter)(),{currentUser:g}=(0,R.As)(),h=(0,ev.Lz)("chats"),[p,y]=(0,n.useState)([]),[f,v]=(0,n.useState)([]),[k,w]=(0,n.useState)(null),[N,j]=(0,n.useState)([]),[T,S]=(0,n.useState)(""),[I,O]=(0,n.useState)(""),[P,z]=(0,n.useState)("open"),[W,L]=(0,n.useState)({totalOpen:0,totalClosed:0,totalToday:0,myActive:0}),[B,q]=(0,n.useState)(!1),[X,Z]=(0,n.useState)(!1),[$,ee]=(0,n.use
1State)(!1),[et,ea]=(0,n.useState)(!1),er=(0,n.useRef)(null),en=(0,n.useRef)(null),[eo,ed]=(0,n.useState)(null),[ec,eu]=(0,n.useState)(!1),[eg,ex]=(0,n.useState)(void 0),[eL,eB]=(0,n.useState)(!1),[eH,eq]=(0,n.useState)(!0),[eG,eV]=(0,n.useState)(!1),[eK,eY]=(0,n.useState)(!1),[eQ,eJ]=(0,n.useState)(!1),[eX,eZ]=(0,n.useState)(!1),[e$,e0]=(0,n.useState)("chat"),[e1,e2]=(0,n.useState)(!1),[e5,e4]=(0,n.useState)(!1),e3=(0,n.useMemo)(()=>{if(k)return function(e){var t;let a=null===(t=e.customerPhone)||void 0===t?void 0:t.trim();if(a)return a;let r=e.channelData,s=null==r?void 0:r.whatsapp;if(!s)return;let n="string"==typeof s.phoneNumber&&s.phoneNumber.trim()?s.phoneNumber.trim():"";if(n)return n;let i="string"==typeof s.waId?s.waId.replace(/\D/g,""):"";return i.length>=8?"+".concat(i):void 0}(k)},[k]);(0,n.useEffect)(()=>{k&&e_(k)&&e2(!0)},[null==k?void 0:k.id]),(0,n.useEffect)(()=>{en.current=null,ex(void 0)},[null==k?void 0:k.id]);let e7=!!((null==k?void 0:k.agentId)&&(null==g?void 0:g.id)&&k.agentId===g.id),e6=(0,n.useMemo)(()=>{let e=[...N].reverse().find(e=>"customer"===e.senderType);return e?"".concat(e.createdAt||"",":").concat((e.content||"").slice(0,80)):"none"},[N]),e8=(0,n.useMemo)(()=>{let e=N[N.length-1];return(null==e?void 0:e.senderType)==="customer"},[N]),e9=e7&&e8,te=null!==(t=null!==(e=null!=eg?eg:null==eo?void 0:eo.orderId)&&void 0!==e?e:null==k?void 0:k.orderId)&&void 0!==t?t:void 0;(0,n.useEffect)(()=>{if(!(null==k?void 0:k.id)||!e7){ed(null),eu(!1);return}let e=!1;eu(!0);let t=new URLSearchParams({chatId:k.id});return eg&&t.set("orderId",eg),fetch("/api/admin/chat-order-focus?".concat(t.toString())).then(e=>e.json()).then(t=>{!e&&t.success&&ed(t.data)}).catch(()=>{e||ed(null)}).finally(()=>{e||eu(!1)}),()=>{e=!0}},[null==k?void 0:k.id,e7,eg,e6]);let[tt,ta]=(0,n.useState)(null),[tr,ts]=(0,n.useState)(new Set),[tn,ti]=(0,n.useState)({}),tl=(0,n.useRef)("offline"),to=(0,n.useRef)(g);(0,n.useEffect)(()=>{tt&&(tl.current=tt)},[tt]),(0,n.useEffect)(()=>{to.current=g},[g]);let[td,tc]=(0,n.useState)({}),[tu,tg]=(0,n.useState)({}),[tm,th]=(0,n.useState)("default"),tx=g&&(0,ef.xf)(g),tp=(null==g?void 0:g.get("userType"))==="aa";(0,n.useEffect)(()=>{g&&null===tt&&ta("aa"===g.get("userType")?"offline":"available")},[g,tt]);let[ty,tb]=(0,n.useState)([]),[tf,tv]=(0,n.useState)(0),[tk,tw]=(0,n.useState)(null),[tN,tj]=(0,n.useState)(0);(0,n.useEffect)(()=>{let e=window.setInterval(()=>tj(e=>e+1),3e4);return()=>window.clearInterval(e)},[]);let{scrollToBottom:tA,scrollTargetRef:tC,containerRef:tT}=function(e,t){let{scrollToBottom:a,scrollTargetRef:r,containerRef:s}=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{dependencies:t=[],delay:a=100,behavior:r="smooth",enabled:s=!0}=e,i=(0,n.useRef)(null),l=(0,n.useRef)(null),o=()=>{s&&(i.current?i.current.scrollIntoView({behavior:r,block:"end"}):l.current&&(l.current.scrollTop=l.current.scrollHeight))};return(0,n.useEffect)(()=>{if(t.some(e=>null!=e)){let e=setTimeout(o,a);return()=>clearTimeout(e)}},t),{scrollToBottom:o,scrollTargetRef:i,containerRef:l}}({dependencies:[e.length,t],delay:100,behavior:"smooth"});return{scrollToBottom:a,scrollTargetRef:r,containerRef:s}}(N,null==k?void 0:k.id);(0,n.useEffect)(()=>{if(tx&&g)return c.S.subscribeToOpenChats(e=>{y(e),L(t=>({...t,totalOpen:e.length,myActive:e.filter(e=>e.agentId===g.id).length}))},e=>{console.error("[Chat] Failed to load open chats"),A.oR.error("Failed to load open chats. Please refresh the page.")})},[g,tx]),(0,n.useEffect)(()=>{if(tx&&g)return c.S.subscribeToClosedChats(e=>{v(e),L(t=>({...t,totalClosed:e.length}))},e=>{console.error("[Chat] Failed to load closed chats"),A.oR.error("Failed to load chat history. Please refresh the page.")})},[g,tx]),(0,n.useEffect)(()=>{if(!tx||!(null==k?void 0:k.id))return;let e=c.S.subscribeToMessages(k.id,e=>j(e),e=>{console.error("[Chat] Failed to load messages"),A.oR.error("Failed to load messages. Please refresh the chat.")}),t=el.D.subscribeToTypingStatus(k.id,e=>{Z(!!e.find(e=>"customer"===e.userType))},e=>{console.error("[Chat] Failed to load typing status")});return()=>{e(),t()}},[null==k?void 0:k.id,tx]),(0,n.useEffect)(()=>{tx&&c.S.getBasicStats().then(e=>{L(t=>({...t,totalToday:e.totalChatsToday}))})},[tx]),(0,n.useEffect)(()=>
1{if(!tp||!tx||!g)return;let e=!1;return(async()=>{try{let t=[],a=1,r=1/0;for(;t.length<Math.min(r,1e3);){let e=await (0,C.eR)({userTypes:"a,aa",page:a,pageSize:100,sortField:"createdAt",sortDirection:"asc"},g);if(t.push(...e.users.map(e=>({id:e.objectId,fullName:e.fullName||e.email||"Agent"}))),r=e.total,0===e.users.length||a>=10)break;a+=1}if(e)return;t.sort((e,t)=>e.fullName.localeCompare(t.fullName,void 0,{sensitivity:"base"})),tb(t)}catch(e){console.error("[Chat] Failed to load agents for assignment"),A.oR.error("Could not load team list for assignment.")}})(),()=>{e=!0}},[tp,tx,g]),(0,n.useEffect)(()=>{"Notification"in window&&"default"===tm&&Notification.requestPermission().then(e=>{th(e)})},[tm]),(0,n.useEffect)(()=>{if(tx&&(null==k?void 0:k.id))return c.S.subscribeToMessages(k.id,e=>{let t=N[N.length-1],a=e[e.length-1];a&&(!t||a.id!==t.id)&&("agent"!==a.senderType||a.senderId!==(null==g?void 0:g.id))&&(tH(),tq("New message from ".concat(k.customerName),a.content.substring(0,100)+(a.content.length>100?"...":""),k.id)),j(e)},e=>{console.error("[Chat] Enhanced message subscription failed")})},[null==k?void 0:k.id,tx,g]),(0,n.useEffect)(()=>{if(tx)return em.subscribeToOnlineStatus(e=>{ts(new Set(e.onlineUsers.map(e=>e.userId)));let t={};e.onlineUsers.forEach(e=>{let a=e.userId;if(!a)return;let r=e.status;"busy"===r||"away"===r||"available"===r?t[a]=r:t[a]="available"}),e.offlineUsers.forEach(e=>{let a=e.userId;a&&(t[a]="offline")});let a=to.current,r=tl.current;(null==a?void 0:a.id)&&"offline"===r?t[a.id]="offline":(null==a?void 0:a.id)&&("available"===r||"busy"===r||"away"===r)&&(t[a.id]=r),ti(t);let s={};e.offlineUsers.forEach(e=>{e.lastSeen&&(s[e.userId]=e.lastSeen.toDate())}),tg(e=>({...e,...s}))},e=>{console.error("[Chat] Failed to subscribe to online status")})},[tx]),(0,n.useEffect)(()=>{let e=null==g?void 0:g.id;e&&tt&&ti(t=>({...t,[e]:tt}))},[tt,null==g?void 0:g.id]),(0,n.useEffect)(()=>{if(tx&&g&&tt)return"offline"===tt?(em.setUserOffline(g.id,"agent"),()=>{em.cleanup(g.id,"agent")}):(em.setUserOnline(g.id,"agent",tt,{userAgent:navigator.userAgent,displayName:g.get("fullName")||g.get("username")||g.get("email")||"Agent"}),em.initializeBrowserCleanup(g.id,"agent"),()=>{em.cleanup(g.id,"agent")})},[tx,g,tt]),(0,n.useEffect)(()=>{if(!tx||"available"!==tt||!p.some(e=>!e.agentId))return;let e=window.setTimeout(()=>{Promise.resolve().then(a.bind(a,51140)).then(e=>e.processUnassignedOpenChats())},800);return()=>window.clearTimeout(e)},[tx,tt,p]),(0,n.useEffect)(()=>{if(!u.isReady||!tx)return;let e=u.query.chatId,t="string"==typeof e?e:Array.isArray(e)&&"string"==typeof e[0]?e[0]:"";if(!t)return;let a=!1;return(async()=>{let e=p.find(e=>e.id===t);if(e){a||(z("open"),w(e),e0("chat"));return}let r=f.find(e=>e.id===t);if(r){a||(z("closed"),w(r),e0("chat"));return}let s=await c.S.getChatRoom(t);if(a||!s){a||s||A.oR.error("Chat not found or you no longer have access.");return}z("closed"===s.status?"closed":"open"),w(s),e0("chat")})(),()=>{a=!0}},[u.isReady,u.query.chatId,tx,p,f]);let tS="open"===P?p:f,tI=(0,n.useMemo)(()=>{let e=tS.filter(e=>e.customerName.toLowerCase().includes(I.toLowerCase())||e.subject&&e.subject.toLowerCase().includes(I.toLowerCase())||e.orderId&&e.orderId.includes(I));return"open"===P?(0,eh.sortChatsByUrgency)(e):e},[tS,I,P]);if(h.hasNoAccess)return(0,r.jsx)(o.A,{title:"Chat Support",children:(0,r.jsx)("div",{className:"flex items-center justify-center min-h-[400px] bg-gray-50 dark:bg-gray-900",children:(0,r.jsxs)("div",{className:"text-center max-w-md mx-auto",children:[(0,r.jsx)("div",{className:"p-4 bg-red-50 dark:bg-red-900/30 rounded-full w-16 h-16 mx-auto mb-4 flex items-center justify-center",children:(0,r.jsx)(G.A,{className:"h-8 w-8 text-red-500 dark:text-red-400"})}),(0,r.jsx)("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white mb-2",children:"Access Restricted"}),(0,r.jsx)("p",{className:"text-gray-600 dark:text-gray-300 mb-4",children:"You don't have permission to access chat support."}),(0,r.jsx)("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Contact your administrator to request access to this section."})]})})});let tE=async e=>{try{if(!e.id||!g)return;let a=g.get("fullName")||"Agent",r=!!(e.agentId&&e.agentId!==g.id);if(r){var t;let a=(null===(t=e.agentName)||void 0===t?void 0:t.trim())||"another agent";if(!window.confirm("This chat is assigned to ".concat(a,". Take it over and assign it to you?")))return}if(!await c.S.assignAgent(e.id,g.id,a,{allowReassign:r})){A.oR.error(r?"Could not take this chat â it may have just changed assignment.":"This chat was just assigned to another agent.");return}w({...e,agentId:g.id,agentName:a}),setTimeout(tA,500),A.oR.success(r?"Chat reassigned to you":"Chat assigned to you")}catch(e){console.error("[Chat] Failed to take chat"),A.oR.error("Failed to take chat. Please try again.")}},tM=async(e,t,a)=>{if(e.id&&!tk&&e.agentId!==t){tw(e.id);try{let r=p.filter(e=>e.agentId===t).length;r>=ep.pg&&(0,A.oR)("".concat(a," has ").concat(r," open chats (recommended max ").concat(ep.pg,"). Assigning anyway."),{icon:"â ï¸"}),await c.S.assignAgent(e.id,t,a,{allowReassign:!0}),(null==k?void 0:k.id)===e.id&&w({...e,agentId:t,agentName:a}),A.oR.success(t===(null==g?void 0:g.id)?"Chat assigned to you":"Chat assigned to ".concat(a)),tv(e=>e+1)}catch(e){console.error("[Chat] Failed to assign chat"),A.oR.error("Failed to assign chat. Please try again.")}finally{tw(null)}}},tO=()=>{(null==k?void 0:k.id)&&g&&tx&&(q(!0),el.D.setAgentTyping(k.id,g.id,g.get("fullName")||"Agent",!0),er.current&&clearTimeout(er.current),er.current=setTimeout(()=>{(null==k?void 0:k.id)&&g&&(el.D.setAgentTyping(k.id,g.id,g.get("fullName")||"Agent",!1),q(!1))},3e3))},tD=()=>{(null==k?void 0:k.id)&&g&&(q(!1),el.D.setAgentTyping(k.id,g.id,g.get("fullName")||"Agent",!1),er.current&&clearTimeout(er.current))},tR=e=>{S(e),setTimeout(()=>{let e=document.querySelector('textarea[placeholder*="Type your response"]');e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),e.style.height="auto",e.style.height=Math.min(e.scrollHeight,120)+"px")},100)},tP=e=>{en.current=e},tz=async e=>{let t=en.current;if(t){en.current=null;try{await fetch("/api/admin/chat-copilot-feedback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({feedbackId:t.feedbackId,action:"record_send",suggestedReply:t.suggestedReply,sentMessage:e})})}catch(e){console.warn("[Chat] Failed to record copilot send feedback",e)}}},t_=async()=>{var e,t,a,r,s;if(!T.trim()||!(null==k?void 0:k.id)||!g||$)return;ee(!0),tD();let n=T.trim();S("");try{if("closed"===k.status){ea(!0);try{await tU(k)}finally{ea(!1)}}let s=(null==k?void 0:k.channel)||"website",i=null==k?void 0:k.channelData,l="instagram"===s?null==i?void 0:null===(e=i.instagram)||void 0===e?void 0:e.userId:"whatsapp"===s?(null==i?void 0:null===(t=i.whatsapp)||void 0===t?void 0:t.waId)||(null==i?void 0:null===(r=i.whatsapp)||void 0===r?void 0:null===(a=r.phoneNumber)||void 0===a?void 0:a.replace(/\D/g,""))||"":void 0;"website"!==s&&l?await x.sendChannelMessage(k.id,g.id,g.get("fullName")||"Agent","agent",n,s,l,"whatsapp"===s?{whatsappCustomerDisplayName:k.customerName,parseSessionToken:g.getSessionToken()||void 0}:void 0):await c.S.sendMessage(k.id,g.id,g.get("fullName")||"Agent","agent",n),tz(n),setTimeout(()=>{let e=document.querySelector('textarea[placeholder*="Type your response"]');e&&(e.style.height="auto")},50),setTimeout(tA,100)}catch(a){console.error("[Chat] Failed to send message",a),S(n);let e=a instanceof Error&&(null===(s=a.message)||void 0===s?void 0:s.trim())?a.message.trim():"Failed to send message. Please try again.",t=e.length>240?"".concat(e.slice(0,237),"â¦"):e;A.oR.error(t)}finally{ee(!1)}},tF=async e=>{if(e.id&&g)try{await c.S.closeChat(e.id,g.id),(null==k?void 0:k.id)===e.id&&(w(null),j([])),A.oR.success("Chat closed successfully")}catch(e){console.error("[Chat] Failed to close chat"),A.oR.error("Failed to close chat. Please try again.")}},tU=async e=>{if(e.id&&g)try{let t=g.get("fullName")||"Agent";if(await c.S.reactivateChat(e.id,g.id,t),z("open"),w({...e,status:"open",agentId:g.id,agentName:t}),e.id){let t=c.S.subscribeToMessages(e.id,e=>j(e),e=>{console.error("[Chat] Failed to load messages after reactivation")});setTimeout(()=>t(),100)}A.oR.success("Chat reactivated successfully")}catch(e){console.error("[Chat] Failed to reactivate chat"),A.oR.error("Failed to reactivate chat. Please try again.")}},tW=e=>{"Enter"!==e.key||e.shiftKey||$?tO():(e.preventDefault(),t_())},tL=e=>{let t=e.target.value;S(t),tO();let a=e.target;a.style.height="auto",a.style.height=Math.min(a.scrollHeight,120)+"px",eB(t.endsWith("/"))},tB=e=>{w(e),e0("chat"),e.hasUnreadMessages&&e.id&&tG(e.id)},tH=()=>{Promise.resolve().then(a.bind(a,59493)).then(e=>{let{default:t}=e;t.messageReceived()})},tq=(e,t,a)=>{if("granted"===tm&&document.hidden){let r=new Notification(e,{body:t,icon:"/images/logo.png",tag:a||"chat-notification"});r.onclick=()=>
1{if(window.focus(),a){let e=p.find(e=>e.id===a);e&&w(e)}r.close()},setTimeout(()=>r.close(),5e3)}},tG=async e=>{if(g)try{await ey.A.markChatAsRead(e,g.id)}catch(e){console.error("[Chat] Failed to mark chat as read")}},tV=e=>{switch(td[e]){case"sent":return(0,r.jsx)(Y.A,{size:12,className:"opacity-55"});case"delivered":return(0,r.jsx)(ek.A,{size:12,className:"opacity-55"});case"read":return(0,r.jsx)(ek.A,{size:12,className:"text-sky-400 opacity-90"});default:return(0,r.jsx)(ew,{size:12,className:"opacity-40"})}},tK=async e=>{if(g){ta(e);try{if("offline"===e){await em.setUserOffline(g.id,"agent"),A.oR.success("You are offline â no new chats will be assigned");return}await em.setUserOnline(g.id,"agent",e,{userAgent:navigator.userAgent,displayName:g.get("fullName")||g.get("username")||g.get("email")||"Agent"}),A.oR.success("Status changed to ".concat(e)),"available"===e&&Promise.resolve().then(a.bind(a,51140)).then(e=>e.processUnassignedOpenChats())}catch(e){console.error("[Chat] Failed to update agent presence"),A.oR.error("Failed to update status. Please try again.")}}};return tx?(0,r.jsx)(d.o,{value:{activeTab:P,setActiveTab:z,openChatsCount:p.length,closedChatsCount:f.length,isSearchOpen:eX,setIsSearchOpen:eZ},children:(0,r.jsx)(o.A,{title:"Chat Support",children:(0,r.jsxs)("div",{className:"admin-dash admin-chat",children:[(0,r.jsx)("div",{className:"fixed top-0 left-0 right-0 lg:left-16 chat-page-header h-14 lg:h-14 z-40 chat-mobile-safe-x hidden lg:flex items-center border-b border-[var(--dash-line)]",children:(0,r.jsxs)("div",{className:"hidden lg:flex items-center justify-between gap-2 min-w-0 px-5 flex-1",children:[(0,r.jsxs)("div",{className:"flex items-center space-x-2 min-w-0 flex-1",children:[(0,r.jsx)("button",{onClick:()=>eq(!eH),className:"p-2 text-[var(--dash-ink-soft)] hover:text-[var(--dash-ink)] hover:bg-[var(--dash-accent-soft)] rounded-lg transition-colors",title:eH?"Hide Sidebar":"Show Sidebar",children:eH?(0,r.jsx)(ej.A,{size:18}):(0,r.jsx)(eA,{size:18})}),(0,r.jsx)("h1",{className:"dash-display text-base font-semibold text-[var(--dash-ink)] flex items-center tracking-tight",children:"Chats"})]}),(0,r.jsxs)("div",{className:"flex items-center gap-3 flex-shrink-0",children:[(0,r.jsxs)("div",{className:"relative",children:[(0,r.jsxs)("button",{onClick:()=>eJ(!eQ),className:"flex items-center gap-1.5 px-2 py-1 text-xs text-[var(--dash-muted)] hover:text-[var(--dash-ink)] hover:bg-[var(--dash-accent-soft)] rounded-md transition-colors",title:"View stats",children:[(0,r.jsx)(eC,{size:14}),(0,r.jsxs)("span",{className:"tabular-nums",children:[W.totalOpen," open"]}),(0,r.jsx)(U.A,{size:12,className:eQ?"rotate-180":""})]}),eQ&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"fixed inset-0 z-40",onClick:()=>eJ(!1),"aria-hidden":"true"}),(0,r.jsxs)("div",{className:"absolute right-0 top-full mt-1 py-2 px-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-600 z-50 min-w-[140px]",children:[(0,r.jsx)("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-2",children:"Stats"}),(0,r.jsxs)("div",{className:"space-y-1.5 text-sm",children:[(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{children:"Open"}),(0,r.jsx)("span",{className:"font-medium text-gray-900 dark:text-gray-100",children:W.totalOpen})]}),(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{children:"Closed"}),(0,r.jsx)("span",{className:"font-medium text-gray-600 dark:text-gray-400",children:W.totalClosed})]}),(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{children:"Today"}),(0,r.jsx)("span",{className:"font-medium text-emerald-600",children:W.totalToday})]}),(0,r.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,r.jsx)("span",{children:"Mine"}),(0,r.jsx)("span",{className:"font-medium text-gray-600 dark:text-gray-400",children:W.myActive})]})]}),h.canAccessPage("otp_status")&&(0,r.jsx)("div",{className:"mt-2 pt-2 border-t border-gray-100 dark:border-gray-700",children:(0,r.jsx)(l(),{href:"/admin/otp-status",className:"text-xs text-green-600 hover:underline",children:"OTP Status"})})]})]})]}),(0,r.jsxs)("div",{className:"flex items-center space-x-4 border-l border-gray-200 dark:border-gray-600 pl-4",children:[(0,r.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,r.jsx)("div",{className:"w-2 h-2 rounded-full ".concat((e=>{switch(e){case"available":return"bg-green-500";case"busy":return"bg-red-500";case"away":return"bg-yellow-500";case"offline":return"bg-gray-500";default:return"bg-gray-400"}})(tt||"offline"))}),(0,r.jsxs)("select",{value:tt||"offline",onChange:e=>tK(e.target.value),className:"text-xs text-gray-600 dark:text-gray-400 border-none bg-transparent focus:ring-2 focus:ring-blue-500 rounded",title:tp?"Super admins stay Offline until you choose Available":void 0,children:[(0,r.jsx)("option",{value:"available",children:"Available"}),(0,r.jsx)("option",{value:"busy",children:"Busy"}),(0,r.jsx)("option",{value:"away",children:"Away"}),(0,r.jsx)("option",{value:"offline",children:"Offline"})]})]}),(0,r.jsxs)("div",{className:"flex items-center space-x-1 ".concat(0===tr.size?"text-gray-400 dark:text-gray-500":"text-gray-500 dark:text-gray-400"),children:[(0,r.jsx)(eT,{size:14}),(0,r.jsxs)("span",{className:"text-xs",children:[tr.size," online"]})]})]})]})]})}),(0,r.jsxs)("div",{className:"hidden lg:flex fixed top-14 left-0 lg:left-16 right-0 bottom-0 bg-gray-50 dark:bg-gray-900 z-20",children:[(0,r.jsx)("div",{className:"bg-[var(--chat-surface)] border-r-2 border-[var(--border-primary)] transition-all duration-300 flex-shrink-0 relative ".concat(eH?"w-72":"w-0 overflow-hidden"),children:(0,r.jsxs)("div",{className:"w-72 h-full flex flex-col",children:[(0,r.jsxs)("div",{className:"flex-shrink-0 p-3 border-b border-[var(--border-primary)] bg-[var(--chat-surface)] space-y-2",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsxs)("div",{className:"flex-1 flex space-x-0.5 bg-[var(--chat-tab-bg)] p-1 rounded-md",children:[(0,r.jsxs)("button",{onClick:()=>z("open"),className:"flex-1 py-1.5 px-3 text-xs font-medium rounded transition-colors ".concat("open"===P?"bg-[var(--chat-tab-active)] text-[var(--text-primary)] shadow-sm":"text-[var(--text-tertiary)] hover:text-[var(--text-secondary)]"),children:["Chats (",p.length,")"]}),(0,r.jsxs)("button",{onClick:()=>z("closed"),className:"flex-1 py-1.5 px-3 text-xs font-medium rounded transition-colors ".concat("closed"===P?"bg-[var(--chat-tab-active)] text-[var(--text-primary)] shadow-sm":"text-[var(--text-tertiary)] hover:text-[var(--text-secondary)]"),children:["History (",f.length,")"]})]}),(0,r.jsx)("button",{onClick:()=>eZ(!eX),className:"p-1.5 rounded transition-colors flex-shrink-0 ".concat(eX?"bg-[var(--chat-tab-active)] text-[var(--text-primary)]":"text-[var(--text-tertiary)] hover:bg-[var(--chat-surface-hover)]"),title:eX?"Hide search":"Search chats",children:(0,r.jsx)(K.A,{size:16})})]}),eX&&(0,r.jsxs)("div",{className:"relative",children:[(0,r.jsx)(K.A,{className:"absolute left-2.5 top-1/2 transform -translate-y-1/2 text-[var(--text-tertiary)]",size:12}),(0,r.jsx)("input",{type:"text",placeholder:"Search ".concat("open"===P?"open":"closed"," chats..."),value:
1I,onChange:e=>O(e.target.value),className:"w-full pl-8 pr-2 py-1.5 text-xs border border-[var(--border-primary)] bg-[var(--surface-tertiary)] text-[var(--text-primary)] placeholder-[var(--text-tertiary)] rounded-md focus:outline-none focus:ring-1 focus:ring-blue-400 focus:border-transparent"})]})]}),(0,r.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto",children:0===tI.length?(0,r.jsxs)("div",{className:"p-8 text-center",children:[(0,r.jsx)(G.A,{size:40,className:"mx-auto mb-3 text-gray-300 dark:text-gray-600"}),(0,r.jsxs)("p",{className:"text-sm font-medium text-gray-600 dark:text-gray-400",children:["No ","open"===P?"open":"closed"," chats"]}),(0,r.jsx)("p",{className:"text-xs text-gray-400 dark:text-gray-500 mt-1",children:"open"===P?"New conversations will appear here when customers reach out":"Resolved chats will appear in History"})]}):(0,r.jsx)("div",{className:"divide-y divide-[var(--dash-line)]",children:tI.map(e=>{let t=!e.agentId&&"open"===P,a=eP(e),s=(0,eh.getChatWaitSeconds)(e),n=a?ez(e):(0,m.OM)(e.lastMessageAt||e.createdAt),i=e.agentId?e.agentId===(null==g?void 0:g.id)?"You":e.agentName?e.agentName:"Assigned":"Waiting";return(0,r.jsxs)("div",{className:"chat-queue-row group/card ".concat((null==k?void 0:k.id)===e.id?"is-selected":""," ").concat(t?"is-waiting":""),onClick:()=>{w(e),e.hasUnreadMessages&&e.id&&tG(e.id)},children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[(0,r.jsx)("span",{className:"chat-queue-name truncate",children:e.customerName}),e_(e)&&(0,r.jsx)(eR.EcP,{className:"flex-shrink-0 text-[#25D366]",size:12,title:"WhatsApp","aria-label":"WhatsApp"}),tr.has(e.customerId)?(0,r.jsx)("div",{className:"w-1.5 h-1.5 bg-[var(--dash-good)] rounded-full flex-shrink-0",title:"Online"}):(0,r.jsx)("div",{className:"w-1.5 h-1.5 bg-[var(--dash-fill-soft)] rounded-full flex-shrink-0",title:"Offline"}),e.hasUnreadMessages&&(0,r.jsx)("div",{className:"w-1.5 h-1.5 bg-[var(--dash-accent)] rounded-full flex-shrink-0",title:"Unread"})]}),(0,r.jsx)("span",{className:"chat-queue-meta flex-shrink-0 ".concat(a&&s<86400?"is-urgent":""),children:n})]}),e.lastMessageContent&&(0,r.jsx)("p",{className:"chat-queue-preview truncate mt-0.5 ".concat(e.hasUnreadMessages?"is-unread":""),children:e.lastMessageContent}),(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2 mt-1 min-h-[1.25rem]",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1 flex-wrap min-w-0 flex-1",children:["guest"===e.customerType&&(0,r.jsx)("span",{className:"dash-pill",children:"Guest"}),e.isEmailOriginated&&(0,r.jsx)("span",{className:"dash-pill",children:"Email"}),(0,r.jsx)("span",{className:"dash-pill ".concat(t?"dash-pill-cncl":e.agentId===(null==g?void 0:g.id)?"dash-pill-cnf":""),title:e.agentId&&e.agentName?"Assigned to ".concat(e.agentName):void 0,children:i}),(null==k?void 0:k.id)===e.id&&X&&(0,r.jsx)("span",{className:"text-[0.625rem] dash-muted animate-pulse",children:"typingâ¦"})]}),(0,r.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0",children:[t&&(0,r.jsxs)("button",{type:"button",onClick:t=>{t.stopPropagation(),tE(e)},className:"chat-take-btn",children:[(0,r.jsx)(eS.A,{size:10})," Take"]}),e.agentId===(null==g?void 0:g.id)&&"open"===P&&(0,r.jsx)("button",{type:"button",onClick:t=>{t.stopPropagation(),tF(e)},className:"p-1 text-[var(--dash-muted)] hover:text-[var(--dash-danger)] rounded",title:"Close chat",children:(0,r.jsx)(V.A,{size:12})}),"closed"===P&&(0,r.jsx)("button",{type:"button",onClick:t=>{t.stopPropagation(),tU(e)},className:"chat-reactivate-btn",children:"Reactivate"})]})]})]},e.id)})})})]})}),!eH&&(0,r.jsx)("div",{className:"absolute top-4 left-4 z-50",children:(0,r.jsx)("button",{onClick:()=>eq(!0),className:"p-3 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg shadow-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors",title:"Show Chat List",children:(0,r.jsx)(eI.A,{size:20,className:"text-gray-600 dark:text-gray-300"})})}),(0,r.jsx)("div",{className:"flex-1 flex relative",children:k?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"flex-1 flex flex-col relative bg-white dark:bg-gray-800 border-r-2 border-gray-200 dark:border-gray-700",children:[(0,r.jsxs)("div",{className:"absolute top-0 left-0 right-0 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-4 py-2.5 z-30 shadow-sm",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,r.jsxs)("div",{className:"flex flex-col gap-0.5 min-w-0 flex-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsxs)("h3",{className:"font-medium text-gray-900 dark:text-white truncate flex items-center gap-2",children:[k.customerName,e_(k)&&(0,r.jsx)(eR.EcP,{className:"flex-shrink-0 text-[#25D366]",size:15,title:"WhatsApp chat","aria-label":"WhatsApp"}),tr.has(k.customerId)?(0,r.jsx)("div",{className:"w-1.5 h-1.5 bg-emerald-500 rounded-full flex-shrink-0",title:"Online"}):(0,r.jsx)("div",{className:"w-1.5 h-1.5 bg-gray-400 rounded-full flex-shrink-0",title:"Offline"}),X&&(0,r.jsx)("span",{className:"text-xs text-gray-500 animate-pulse",children:"typing..."}
1),et&&(0,r.jsx)("span",{className:"text-xs text-amber-600 dark:text-amber-400 animate-pulse",children:"Reactivating..."})]}),(0,r.jsx)("button",{onClick:()=>eY(!eK),className:"p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded flex-shrink-0",title:eK?"Hide details":"Show details",children:(0,r.jsx)(U.A,{size:16,className:eK?"rotate-180":""})})]}),!eG&&e3&&(0,r.jsxs)("span",{className:"text-xs text-gray-500 dark:text-gray-400 flex items-center gap-1 truncate",children:[(0,r.jsx)(b.A,{size:10}),e3]})]}),(0,r.jsxs)("div",{className:"flex items-center gap-2 flex-shrink-0",children:[k.orderId&&(0,r.jsxs)("button",{onClick:()=>window.open("/admin/order-details/".concat(k.orderId,"?tab=details"),"_blank","noopener,noreferrer"),className:"text-gray-500 hover:text-blue-600 px-2 py-1 rounded text-xs flex items-center gap-1",title:"View order",children:[(0,r.jsx)(D.A,{size:12})," Order"]}),(0,r.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded border ".concat(k.agentId?"bg-[var(--dash-fill-soft)] border-[var(--dash-line)] text-[var(--dash-ink-soft)]":"bg-[var(--dash-warn-soft)] border-transparent text-[var(--dash-warn)]"),children:k.agentId?k.agentId===(null==g?void 0:g.id)?"You":"Assigned":"Waiting".concat(eP(k)?" \xb7 ".concat(ez(k)):"")}),tp&&"open"===P&&"open"===k.status&&(0,r.jsxs)("select",{disabled:!!tk,defaultValue:"",onChange:e=>{let t=e.target.value;if(e.target.value="",!t)return;let a=ty.find(e=>e.id===t);a&&tM(k,a.id,a.fullName)},className:"text-[10px] px-1.5 py-1 rounded border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-200 max-w-[min(100%,18rem)] min-w-[10rem]",title:"Assign chat to agent","aria-label":"Assign chat to agent",children:[(0,r.jsx)("option",{value:"",children:"Assignâ¦"}),ty.map(e=>(0,r.jsx)("option",{value:e.id,children:eW(e,tn,null==g?void 0:g.id)},e.id))]},"hdr-".concat(tf,"-").concat(k.id)),(0,r.jsx)("button",{onClick:()=>eV(!eG),className:"p-2 rounded-lg transition-colors ".concat(eG?"bg-[var(--dash-accent-soft)] text-[var(--dash-accent)]":"text-[var(--dash-muted)] hover:text-[var(--dash-ink)] hover:bg-[var(--dash-fill-soft)]"),title:eG?"Hide profile":"View profile & orders",children:(0,r.jsx)(eE,{size:18})})]})]}),eK&&(0,r.jsxs)("div",{className:"mt-2 pt-2 border-t border-gray-100 dark:border-gray-700 text-xs text-gray-500 dark:text-gray-400 space-y-1",children:[(0,r.jsxs)("div",{children:[(0,m.kp)(k.createdAt),e3&&" ⢠".concat(e3)]}),k.customerEmail&&k.isEmailOriginated&&(0,r.jsx)("div",{children:k.customerEmail}),k.subject&&(0,r.jsx)("div",{children:k.subject}),tu[k.customerId]&&!tr.has(k.customerId)&&(0,r.jsxs)("div",{children:["Last seen ",(0,m.kp)(tu[k.customerId])]})]}),(()=>{let e="number"==typeof k.customerRating?k.customerRating:0,t="string"==typeof k.customerFeedback?k.customerFeedback.trim():"";return"closed"!==k.status||e<=0&&!t?null:(0,r.jsxs)("div",{className:"mt-2 pt-2 border-t border-amber-200/80 dark:border-amber-800/60 text-[11px] text-gray-700 dark:text-gray-200 space-y-1",children:[(0,r.jsx)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:(0,r.jsxs)("span",{className:"inline-flex items-center gap-1 rounded bg-amber-100/90 dark:bg-amber-900/35 px-1.5 py-0.5 font-medium text-amber-900 dark:text-amber-200",children:[(0,r.jsx)(eM.A,{size:11,className:"shrink-0 fill-amber-500 text-amber-500","aria-hidden":!0}),e>0?(0,r.jsxs)(r.Fragment,{children:["Customer rated ",e,"/5"]}):(0,r.jsx)("span",{children:"No star rating â feedback only"})]})}),t?(0,r.jsx)("p",{className:"whitespace-pre-wrap break-words text-gray-600 dark:text-gray-300 leading-relaxed border-l-2 border-amber-300/70 dark:border-amber-600 pl-2",children:t}):null]})})()]}),(0,r.jsxs)("div",{ref:tT,className:"absolute bottom-20 left-0 right-0 overflow-y-auto p-4 space-y-4 bg-gray-50 dark:bg-gray-900 ".concat("closed"===k.status&&((null!==(i=k.customerRating)&&void 0!==i?i:0)>0||("string"==typeof k.customerFeedback?k.customerFeedback.trim():""))?"top-[6.75rem]":"top-16"),children:[0===N.length&&k?(0,r.jsx)("div",{className:"flex justify-center py-8",children:(0,r.jsx)("div",{className:"text-sm text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-700 px-4 py-2 rounded-full animate-pulse",children:"Loading conversation..."})}):N.map((e,t)=>{let a=N[t-1],s=!a||a.senderId!==e.senderId||a.senderType!==e.senderType||"system"===e.senderType;return(0,r.jsx)("div",{className:"flex ".concat("agent"===e.senderType?"justify-end":"justify-start"," animate-fadeInUp"),style:{animationDelay:"".concat(.05*t,"s")},children:(0,r.jsxs)("div",{className:"max-w-xs lg:max-w-md w-fit roun
1ded-xl shadow-sm transition-all duration-200 ".concat("agent"===e.senderType?"chat-agent-bubble px-4 py-3":"system"===e.senderType?"bg-gray-100 dark:bg-gray-700 dark:border-gray-600 text-gray-600 dark:text-gray-200 text-center px-3 py-2 text-xs max-w-[85%] mx-auto border border-gray-200 dark:border-gray-600":"bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-600 px-4 py-3 hover:border-gray-300 dark:hover:border-gray-500"," ").concat("system"!==e.senderType&&eF(e)?"relative":""),children:[eU(e)?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("a",{href:e.fileUrl,target:"_blank",rel:"noopener noreferrer",className:"block focus:outline-none focus:ring-2 focus:ring-blue-400 rounded-lg",title:"Open image",children:(0,r.jsx)("img",{src:e.fileUrl,alt:"WhatsApp attachment",className:"max-h-64 max-w-full rounded-lg object-contain bg-black/5 dark:bg-black/20"})}),e.content&&"\uD83D\uDCF7 Image"!==e.content&&(0,r.jsx)("p",{className:"whitespace-pre-wrap mt-2 ".concat("system"===e.senderType?"text-xs":"text-sm"),children:e.content})]}):(0,r.jsx)("p",{className:"whitespace-pre-wrap ".concat("system"===e.senderType?"text-xs":"text-sm"),children:e.content}),s&&"system"!==e.senderType&&(0,r.jsxs)("div",{className:"flex items-center justify-between mt-2 text-xs gap-2 ".concat("agent"===e.senderType?"chat-agent-bubble-meta":"text-gray-600 dark:text-gray-400"),children:[(0,r.jsxs)("span",{className:"font-medium min-w-0 truncate flex items-center gap-1",children:[e.senderName,eF(e)&&(0,r.jsx)(eR.EcP,{className:"flex-shrink-0 opacity-90 text-[#25D366]",size:12,title:"Sent via WhatsApp","aria-label":"WhatsApp"})]}),(0,r.jsxs)("div",{className:"flex items-center space-x-1 flex-shrink-0",children:[(0,r.jsx)("span",{children:(0,m.kp)(e.createdAt)}),"agent"===e.senderType&&e.senderId===(null==g?void 0:g.id)&&e.id&&(0,r.jsx)("div",{className:"ml-1",title:"Message ".concat(td[e.id]||"sent"),children:tV(e.id)})]})]}),!s&&"system"!==e.senderType&&eF(e)&&(0,r.jsx)("span",{className:"absolute bottom-1.5 right-2 pointer-events-none",title:"Sent via WhatsApp","aria-hidden":!0,children:(0,r.jsx)(eR.EcP,{className:"text-[#25D366] opacity-90",size:11})})]})},e.id)}),X&&(0,r.jsx)(eb.A,{agentName:"Customer",isVisible:X,variant:"agent"}),(0,r.jsx)("div",{ref:tC,className:"h-4"})]}),k.agentId===(null==g?void 0:g.id)&&(0,r.jsxs)("div",{className:"absolute bottom-0 left-0 right-0 bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 p-3 z-30 shadow-lg",children:[(0,r.jsx)(ei,{orderId:te,focusedOrder:null==eo?void 0:eo.focusedOrder,candidates:null==eo?void 0:eo.candidates,reason:null==eo?void 0:eo.reason,loading:ec,onSelectOrder:ex,className:"mb-2"}),(0,r.jsxs)("div",{className:"relative flex items-center gap-2",children:[(0,r.jsx)(J,{onInsertTemplate:tR,currentMessage:T,customerName:k.customerName,orderId:te,agentName:(null==g?void 0:g.get("fullName"))||"Agent",language:"en",variant:"compact"}),(0,r.jsx)(es,{chatId:k.id,orderId:te,onInsertDraft:tR,onDraftSessionStarted:tP,preload:e9,refreshKey:e6}),(0,r.jsx)("textarea",{value:T,onChange:tL,onKeyPress:tW,onBlur:tD,placeholder:"Type your response...",className:"flex-1 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 placeholder:text-gray-500 dark:placeholder:text-gray-400 caret-gray-900 dark:caret-gray-100 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none overflow-hidden text-sm",rows:1,style:{minHeight:"38px",maxHeight:"120px"}}),(0,r.jsx)("button",{onClick:t_,disabled:!T.trim()||$||et,className:"p-2 rounded-full transition-all duration-200 flex items-center justify-center min-w-[38px] h-[38px] shadow-sm ".concat(!T.trim()||$||et?"text-gray-400 dark:text-gray-500 bg-gray-200 dark:bg-gray-600 cursor-not-allowed":"chat-composer-send"),children:$?(0,r.jsx)("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"}):et?(0,r.jsx)("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"}):(0,r.jsx)(Q.A,{size:18})})]})]}),"open"===P&&"open"===k.status&&k.agentId!==(null==g?void 0:g.id)&&(0,r.jsx)("div",{className:"absolute bottom-0 left-0 right-0 bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 p-3 z-30 shadow-lg",children:(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,r.jsxs)("button",{type:"button",onClick:()=>tE(k),disabled:!!tk,className:"text-xs px-3 py-2 rounded-lg bg-[var(--dash-ink)] text-[var(--dash-on-ink)] hover:bg-[var(--dash-accent)] hover:text-[var(--dash-on-accent)] transition-colors flex items-center gap-1.5 disabled:opacity-50",children:[(0,r.jsx)(eS.A,{size:14}),k.agentId?"Assign to me":"Take chat"]}),tp&&(0,r.jsxs)("select",{disabled:!!tk,defaultValue:"",onChange:e=>{let t=e.target.value;if(e.target.value="",!t)return;let a=ty.find(e=>e.id===t);a&&tM(k,a.id,a.fullName)},className:"text-xs px-2 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-100 min-w-[10rem] max-w-[min(100%,20rem)]",title:"Assign chat to another agent","aria-label":"Assign chat to another agent",children:[(0,r.jsx)("option",{value:"",children:"Assign to agentâ¦"}),ty.map(e=>(0,r.jsx)("option",{value:e.id,children:eW(e,tn,null==g?void 0:g.id)},e.id))]},"ft-".concat(tf,"-").concat(k.id))]})})]}),eG&&(0,r.jsxs)("div",{className:"w-80 bg-gray-50 dark:bg-gray-900 border-l border-gray-200 dark:border-gray-700 flex-shrink-0 relative",children:[(0,r.jsx)("button",{onClick:()=>eV(!1),className:"absolute top-3 right-3 p-1.5 text-gray-500 hover:text-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded z-10",title:"Close",children:(0,r.jsx)(eI.A,{size:18})}),(0,r.jsx)("div",{className:"absolute top-0 bottom-0 left-0 right-0 overflow-y-auto p-4 pt-12",children:(0,r.jsxs)("div",{className:"rounded-lg bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 overflow-hidden",children:[(0,r.jsx)("div",{className:"p-3 border-b border-gray-200 dark:border-gray-700",children:(0,r.jsx)(M,{customerId:k.customerId,customerType:k.customerType||"customer",initialPhone:e3,compact:!0})}),(0,r.jsx)("div",{className:"p-3 border-b border-gray-200 dark:border-gray-700",children:(0,r.jsx)(E,{customerId:k.customerId,customerType:k.customerType||"customer",hidePhone:!0,compact:!0,chatCustomerName:k.customerName,chatCustomerPhone:e3})}),(0,r.jsxs)("div",{className:"border-b border-gray-200 dark:border-gray-700 last:border-b-0",children:[(0,r.jsxs)("button",{onClick:()=>e2(!e1),className:"w-full flex items-center justify-between p-3 text-left hover:bg-gray-50/50 dark:hover:bg-gray-700/30 transition-colors",children:[(0,r.jsx)("span",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Order History"}),e1?(0,r.jsx)(F.A,{size:14,className:"text-gray-400"}):(0,r.jsx)(U.A,{size:14,className:"text-gray-400"})]}),e1&&(0,r.jsx)("div",{className:"px-3 pb-3 pt-0",children:(0,r.jsx)(_,{customerId:k.customerId,customerType:k.customerType||"customer",customerPhone:e3})})]}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("button",{onClick:()=>e4(!e5),className:"w-full flex items-center justify-between p-3 text-left hover:bg-gray-50/50 dark:hover:bg-gray-700/30 transition-colors",children:[(0,r.jsx)("span",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Previous Chats"}),e5?(0,r.jsx)(F.A,{size:14,className:"text-gray-400"}):(0,r.jsx)(U.A,{size:14,className:"text-gray-400"})]}),e5&&(0,r.jsx)("div",{className:"px-3 pb-3 pt-0",children:(0,r.jsx)(H,{customerId:k.customerId,customerType:k.customerType||"customer",currentChatId:k.id})})]})]})})]})]}):(0,r.jsx)("div",{className:"flex-1 flex items-center justify-center bg-gray-50 dark:bg-gray-900",children:(0,r.jsxs)("div",{className:"text-center px-6",children:[(0,r.jsx)(G.A,{size:48,className:"mx-auto mb-3 text-gray-300 dark:text-gray-600"}),(0,r.jsx)("h3",{className:"text-base font-medium text-gray-700 dark:text-gray-300",children:"Select a chat"}),(0,r.jsx)("p",{className:"text-sm text-gray-500 dark:text-gray-500 mt-1",children:"Choose a conversation from the list to view and reply"})]})})})]}),(0,r.jsxs)("div",{className:"lg:hidden",children:[!k&&(0,r.jsxs)("div",{className:"fixed left-0 right-0 bottom-0 bg-[var(--chat-surface)] z-30 flex flex-col chat-mobile-scroll chat-mobile-content-top",children:[eX&&(0,r.jsx)("div",{className:"flex-shrink-0 p-2 border-b border-[var(--border-primary)] bg-[var(--chat-surface)]",children:(0,r.jsxs)("div",{className:"relative",children:[(0,r.jsx)(K.A,{className:"absolute left-2.5 top-1/2 transform -translate-y-1/2 text-[var(--text-tertiary)]",size:12}),(0,r.jsx)("input",{type:"text",placeholder:"Search ".concat("open"===P?"open":"closed"," chats..."),value:
1I,onChange:e=>O(e.target.value),className:"w-full pl-7 pr-2 py-2 text-sm border border-[var(--border-primary)] bg-[var(--surface-tertiary)] text-[var(--text-primary)] placeholder-[var(--text-tertiary)] rounded-md focus:outline-none focus:ring-1 focus:ring-blue-400 focus:border-transparent",autoFocus:!0})]})}),(0,r.jsx)("div",{className:"flex-1 overflow-y-auto overflow-x-hidden chat-mobile-scroll overscroll-contain",children:0===tI.length?(0,r.jsxs)("div",{className:"p-8 text-center",children:[(0,r.jsx)(G.A,{size:40,className:"mx-auto mb-3 text-[var(--text-tertiary)]"}),(0,r.jsxs)("p",{className:"text-sm font-medium text-[var(--text-secondary)]",children:["No ","open"===P?"open":"closed"," chats"]}),(0,r.jsx)("p",{className:"text-xs text-[var(--chat-preview-muted)] mt-1",children:"open"===P?"New conversations will appear when customers reach out":"Resolved chats appear in History"}),"open"===P&&(0,r.jsx)("p",{className:"mt-2 text-xs text-gray-500 dark:text-gray-500",children:"Switch to History for past conversations"})]}):(0,r.jsx)("div",{className:"divide-y divide-[var(--dash-line)]",children:tI.map(e=>{let t=!e.agentId&&"open"===P,a=eP(e),s=(0,eh.getChatWaitSeconds)(e),n=a?ez(e):(0,m.OM)(e.lastMessageAt||e.createdAt),i=e.agentId?e.agentId===(null==g?void 0:g.id)?"You":"Assigned":"Waiting";return(0,r.jsxs)("div",{className:"chat-queue-row ".concat(t?"is-waiting":""),onClick:()=>tB(e),children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[(0,r.jsx)("span",{className:"chat-queue-name truncate",children:e.customerName}),e_(e)&&(0,r.jsx)(eR.EcP,{className:"flex-shrink-0 text-[#25D366]",size:12,title:"WhatsApp","aria-label":"WhatsApp"}),tr.has(e.customerId)?(0,r.jsx)("div",{className:"w-1.5 h-1.5 bg-[var(--dash-good)] rounded-full flex-shrink-0",title:"Online"}):(0,r.jsx)("div",{className:"w-1.5 h-1.5 bg-[var(--dash-fill-soft)] rounded-full flex-shrink-0",title:"Offline"}),e.hasUnreadMessages&&(0,r.jsx)("div",{className:"w-1.5 h-1.5 bg-[var(--dash-accent)] rounded-full flex-shrink-0",title:"Unread"})]}),(0,r.jsxs)("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[(0,r.jsx)("span",{className:"chat-queue-meta ".concat(a&&s<86400?"is-urgent":""),children:n}),e.agentId===(null==g?void 0:g.id)&&"open"===P&&(0,r.jsx)("button",{onClick:t=>{t.stopPropagation(),tF(e)},className:"p-1 text-[var(--dash-muted)] hover:text-[var(--dash-danger)] rounded touch-manipulation",title:"Close chat",children:(0,r.jsx)(V.A,{size:14})}),t&&(0,r.jsxs)("button",{type:"button",onClick:t=>{t.stopPropagation(),tE(e)},className:"chat-take-btn touch-manipulation",children:[(0,r.jsx)(eS.A,{size:10})," Take"]}),"closed"===P&&(0,r.jsx)("button",{type:"button",onClick:t=>{t.stopPropagation(),tU(e)},className:"chat-reactivate-btn touch-manipulation",children:"Reactivate"})]})]}),(0,r.jsxs)("div",{className:"flex items-center gap-1.5 flex-wrap min-w-0 mt-0.5",children:["guest"===e.customerType&&(0,r.jsx)("span",{className:"dash-pill",children:"Guest"}),(0,r.jsx)("span",{className:"dash-pill ".concat(t?"dash-pill-cncl":e.agentId===(null==g?void 0:g.id)?"dash-pill-cnf":""),title:e.agentId&&e.agentName?"Assigned to ".concat(e.agentName):void 0,children:i}),e.lastMessageContent&&(0,r.jsx)("span",{className:"chat-queue-preview truncate flex-1 min-w-0 ".concat(e.hasUnreadMessages?"is-unread":""),children:e.lastMessageContent})]})]},e.id)})})})]}),k&&(0,r.jsxs)("div",{className:"fixed inset-0 bg-white dark:bg-gray-800 z-[70] flex flex-col chat-mobile-scroll",children:[(0,r.jsxs)("div",{className:"flex-shrink-0 flex items-center gap-2 px-2 py-3 border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 chat-mobile-safe-x",style:{paddingTop:"max(0.75rem, env(safe-area-inset-top, 0px))"},children:[(0,r.jsx)("button",{onClick:"chat"===e$?()=>{w(null),e0("chat")}:()=>{e0("chat")},className:"min-w-[44px] min-h-[44px] flex items-center justify-center -ml-1 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors touch-manipulation",children:(0,r.jsx)(ej.A,{size:24})}),(0,r.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,r.jsxs)("h2",{className:"font-semibold text-gray-900 dark:text-gray-100 truncate flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"truncate",children:k.customerName}),e_(k)&&(0,r.jsx)(eR.EcP,{className:"flex-shrink-0 text-[#25D366]",size:16,title:"WhatsApp chat","aria-label":"WhatsApp"})]}),(0,r.jsx)("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:k.agentId===(null==g?void 0:g.id)?"Assigned to you":k.agentName?"Assigned to ".concat(k.agentName):"Waiting"})]}),(0,r.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0",children:[(0,r.jsx)("button",{onClick:()=>e0("info"),className:"p-2 rounded-lg touch-manipulation transition-colors ".concat("info"===e$?"bg-blue-100 dar
1k:bg-blue-900/30 text-blue-600 dark:text-blue-400":"text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700"),title:"Customer info",children:(0,r.jsx)(eO.A,{size:20})}),(0,r.jsx)("button",{onClick:()=>e0("orders"),className:"p-2 rounded-lg touch-manipulation transition-colors ".concat("orders"===e$?"bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400":"text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700"),title:"Orders",children:(0,r.jsx)(D.A,{size:20})}),(0,r.jsx)("button",{onClick:()=>e0("previous-chats"),className:"p-2 rounded-lg touch-manipulation transition-colors ".concat("previous-chats"===e$?"bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400":"text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700"),title:"Previous chats",children:(0,r.jsx)(eD,{size:20})})]})]}),"chat"===e$&&"closed"===k.status&&(()=>{let e="number"==typeof k.customerRating?k.customerRating:0,t="string"==typeof k.customerFeedback?k.customerFeedback.trim():"";return e>0||t})()&&(0,r.jsxs)("div",{className:"flex-shrink-0 px-4 py-2 border-b border-amber-200/80 dark:border-amber-800/60 bg-amber-50/60 dark:bg-amber-950/25 text-[11px] text-gray-800 dark:text-gray-100 chat-mobile-safe-x",children:[(0,r.jsx)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:("number"==typeof k.customerRating?k.customerRating:0)>0?(0,r.jsxs)("span",{className:"inline-flex items-center gap-1 font-medium text-amber-900 dark:text-amber-200",children:[(0,r.jsx)(eM.A,{size:11,className:"fill-amber-500 text-amber-500"}),"Customer"," ",k.customerRating,"/5"]}):(0,r.jsx)("span",{className:"font-medium text-amber-900 dark:text-amber-200",children:"Customer feedback"})}),"string"==typeof k.customerFeedback&&k.customerFeedback.trim()?(0,r.jsx)("p",{className:"mt-1 whitespace-pre-wrap break-words text-gray-600 dark:text-gray-300 leading-relaxed",children:k.customerFeedback.trim()}):null]}),"info"===e$&&(0,r.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto overflow-x-hidden chat-mobile-scroll flex flex-col bg-white dark:bg-gray-800 chat-mobile-panel-fill",style:{paddingBottom:"max(1rem, env(safe-area-inset-bottom, 0px))"},children:(0,r.jsxs)("div",{className:"flex-1 min-h-0 flex flex-col",children:[(0,r.jsx)("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0",children:(0,r.jsx)(M,{customerId:k.customerId,customerType:k.customerType||"customer",initialPhone:e3,compact:!0})}),(0,r.jsx)("div",{className:"p-4 flex-1 min-h-0",children:(0,r.jsx)(E,{customerId:k.customerId,customerType:k.customerType||"customer",hidePhone:!0,compact:!0,chatCustomerName:k.customerName,chatCustomerPhone:e3})})]})}),"orders"===e$&&(0,r.jsx)("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden bg-white dark:bg-gray-800",style:{paddingBottom:"max(1rem, env(safe-area-inset-bottom, 0px))"},children:(0,r.jsxs)("div",{className:"flex-1 min-h-0 flex flex-col p-4 overflow-hidden",children:[(0,r.jsx)("h3",{className:"text-sm font-medium text-gray-900 dark:text-white mb-3 flex-shrink-0",children:"Order History"}),(0,r.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto chat-mobile-scroll",children:(0,r.jsx)(_,{customerId:k.customerId,customerType:k.customerType||"customer",customerPhone:e3,fullHeight:!0})})]})}),"previous-chats"===e$&&(0,r.jsx)("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden bg-white dark:bg-gray-800",style:{paddingBottom:"max(1rem, env(safe-area-inset-bottom, 0px))"},children:(0,r.jsxs)("div",{className:"flex-1 min-h-0 flex flex-col p-4 overflow-hidden",children:[(0,r.jsx)("h3",{className:"text-sm font-medium text-gray-900 dark:text-white mb-3 flex-shrink-0",children:"Previous Chats"}),(0,r.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto chat-mobile-scroll",children:(0,r.jsx)(H,{customerId:k.customerId,customerType:k.customerType||"customer",currentChatId:k.id,fullHeight:!0})})]})}),"chat"===e$&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"flex-1 overflow-y-auto overflow-x-hidden chat-mobile-scroll overscroll-contain min-h-0",ref:tT,children:(0,r.jsxs)("div",{className:"p-4 space-y-4",children:[N.map((e,t)=>{let a=N[t-1],s=!a||a.senderId!==e.senderId||a.senderType!==e.senderType||"system"===e.senderType,n="system"===e.senderType;return(0,r.jsx)("div",{className:"flex ".concat("agent"===e.senderType?"justify-end":"justify-start"),children:(0,r.jsxs)("div",{className:"max-w-[85%] w-fit roun
1ded-xl ".concat("agent"===e.senderType?"chat-agent-bubble px-4 py-3":n?"bg-gray-100 dark:bg-gray-700 dark:border-gray-600 text-gray-600 dark:text-gray-200 text-center px-3 py-2 text-xs mx-auto border border-gray-200 dark:border-gray-600":"bg-gray-100 dark:bg-gray-700 text-gray-900 dark:text-gray-100 px-4 py-3 border border-gray-200 dark:border-gray-600"," ").concat(!n&&eF(e)?"relative":""),children:[eU(e)?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("a",{href:e.fileUrl,target:"_blank",rel:"noopener noreferrer",className:"block",children:(0,r.jsx)("img",{src:e.fileUrl,alt:"WhatsApp attachment",className:"max-h-56 w-full rounded-lg object-contain bg-black/5 dark:bg-black/20"})}),e.content&&"\uD83D\uDCF7 Image"!==e.content&&(0,r.jsx)("div",{className:"text-sm mt-2 whitespace-pre-wrap",children:e.content})]}):(0,r.jsx)("div",{className:n?"text-xs":"text-sm",children:e.content}),s&&!n&&(0,r.jsx)("div",{className:"text-xs mt-1 flex items-center justify-between gap-2 ".concat("agent"===e.senderType?"chat-agent-bubble-meta":"text-gray-600 dark:text-gray-400"),children:(0,r.jsxs)("span",{className:"flex items-center gap-1 min-w-0",children:[eF(e)&&(0,r.jsx)(eR.EcP,{className:"flex-shrink-0 text-[#25D366]",size:12,title:"Sent via WhatsApp","aria-label":"WhatsApp"}),(0,r.jsx)("span",{children:(0,m.kp)(e.createdAt)})]})}),!s&&!n&&eF(e)&&(0,r.jsx)("span",{className:"absolute bottom-1.5 right-2 pointer-events-none",title:"Sent via WhatsApp","aria-hidden":!0,children:(0,r.jsx)(eR.EcP,{className:"text-[#25D366] opacity-90",size:11})})]})},t)}),X&&(0,r.jsx)("div",{className:"flex justify-start",children:(0,r.jsx)(eb.A,{agentName:"Customer",isVisible:!0,variant:"agent"})}),(0,r.jsx)("div",{ref:tC})]})}),k.agentId===(null==g?void 0:g.id)?(0,r.jsxs)("div",{className:"flex-shrink-0 border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-3 chat-mobile-safe-x",style:{paddingBottom:"max(0.75rem, env(safe-area-inset-bottom, 0px))"},children:[(0,r.jsx)(ei,{orderId:te,focusedOrder:null==eo?void 0:eo.focusedOrder,candidates:null==eo?void 0:eo.candidates,reason:null==eo?void 0:eo.reason,loading:ec,onSelectOrder:ex,className:"mb-2"}),(0,r.jsxs)("div",{className:"relative flex items-end gap-2",children:[(0,r.jsx)(J,{onInsertTemplate:tR,currentMessage:T,customerName:k.customerName,orderId:te,agentName:(null==g?void 0:g.get("fullName"))||"Agent",language:"en",variant:"compact"}),(0,r.jsx)(es,{chatId:k.id,orderId:te,onInsertDraft:tR,onDraftSessionStarted:tP,preload:e9,refreshKey:e6}),(0,r.jsx)("div",{className:"flex-1 relative min-w-0",children:(0,r.jsx)("textarea",{value:T,onChange:tL,onKeyPress:tW,placeholder:"Type your response...",className:"w-full p-3 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none text-sm placeholder-gray-500 dark:placeholder-gray-400",rows:1,style:{minHeight:"44px",maxHeight:"120px"}})}),(0,r.jsx)("button",{onClick:t_,disabled:!T.trim()||$||et,className:"min-w-[44px] min-h-[44px] p-3 rounded-lg transition-colors flex-shrink-0 flex items-center justify-center touch-manipulation ".concat(!T.trim()||$||et?"bg-gray-100 dark:bg-gray-600 text-gray-400 dark:text-gray-500 cursor-not-allowed":"chat-composer-send"),children:$?(0,r.jsx)("div",{className:"w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"}):et?(0,r.jsx)("div",{className:"w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"}):(0,r.jsx)(Q.A,{size:20})})]})]}):(0,r.jsxs)("div",{className:"flex-shrink-0 p-4 text-center text-sm text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700 space-y-2",children:[(0,r.jsx)("p",{children:"You need to take this chat to reply"}),(0,r.jsxs)("div",{className:"flex flex-col sm:flex-row gap-2 justify-center items-stretch sm:items-center",children:[(0,r.jsx)("button",{type:"button",onClick:()=>tE(k),disabled:!!tk,className:"px-4 py-2 bg-[var(--dash-ink)] text-[var(--dash-on-ink)] rounded-lg font-medium touch-manipulation disabled:opacity-50",children:k.agentId?"Assign to me":"Take chat"}),tp&&"open"===P&&(0,r.jsxs)("select",{disabled:!!tk,defaultValue:"",onChange:e=>{let t=e.target.value;if(e.target.value="",!t)return;let a=ty.find(e=>e.id===t);a&&tM(k,a.id,a.fullName)},className:"text-sm px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-100 min-w-[12rem] max-w-[min(100%,22rem)] touch-manipulation","aria-label":"Assign chat to agent",children:[(0,r.jsx)("option",{value:"",children:"Assign to agentâ¦"}),ty.map(e=>(0,r.jsx)("option",{value:e.id,children:eW(e,tn,null==g?void 0:g.id)},e.id))]},"mf-".concat(tf,"-").concat(k.id))]})]})]})]})]})]})})}):(0,r.jsx)(o.A,{title:"Chat Support",children:(0,r.jsx)("div",{className:"p-8 text-center bg-gray-50 dark:bg-gray-900",children:(0,r.jsxs)("div",{className:"bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-700 rounded-lg p-6 max-w-md mx-auto",children:[(0,r.jsx)(eN.A,{className:"w-12 h-12 text-red-500 dark:text-red-400 mx-auto mb-4"}),(0,r.jsx)("h2",{className:"text-xl font-semibold text-red-700 dark:text-red-300 mb-2",children:"Access Denied"}),(0,r.jsx)("p",{className:"text-red-600 dark:text-red-300",children:"Only admin users (userType 'a' or 'aa') can access the chat dashboard."}),(0,r.jsxs)("p",{className:"text-red-500 dark:text-red-400 text-sm mt-2",children:["Current userType: ",(null==g?void 0:g.get("userType"))||"none"]})]})})})}},19766:(e,t,a)=>{"use strict";a.d(t,{A:()=>r});let r=(0,a(48375).A)("chevron-up",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]])},21304:(e,t,a)=>{(window.__NEXT_P=window.__NEXT_P||[]).push(["/admin/chats",function(){return a(17321)}])},29362:(e,t,a)=>{"use strict";a.d(t,{A:()=>i,z:()=>n});var r=a(72279);function s(){let e=(0,r.getBrowserFirestore)();if(!e)throw Error("Firebase Firestore is not initialized");return e}class n{static async markAsDelivered(e,t){try{await (0,r.updateDoc)((0,r.doc)(s(),"chats",e,"messages",t),{status:"delivered",deliveredAt:(0,r.O5)()})}catch(e){console.error("Error marking message as delivered:",e)}}static async markAsRead(e,t){try{await (0,r.updateDoc)((0,r.doc)(s(),"chats",e,"messages",t),{status:"read",readAt:(0,r.O5)()})}catch(e){console.error("Error marking message as read:",e)}}static async markChatAsRead(e,t){try{await (0,r.updateDoc)((0,r.doc)(s(),"chats",e),{hasUnreadMessages:!1,lastReadBy:t,lastReadAt:(0,r.O5)()})}catch(e){console.error("Error marking chat as read:",e)}}static subscribeToMessageStatus(e,t,a){return()=>{}}}let i=n},31400:(e,t,a)=>{"use strict";a.d(t,{A:()=>r});let r=(0,a(48375).A)("circle-x",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]])},32317:(e,t)=>{"use strict";function a(e){let t=e.toLowerCase();return"kw"===t||"bh"===t?3:2}function r(e){if(!Number.isFinite(e))return 0;let t=5*Math.ceil(Math.round(1e3*Math.abs(e))/5);return(e<0?-1:1)*t/1e3}function s(e){let t=r(e),a=t<0?"-":"",s=Math.round(1e3*Math.abs(t));if(s%1e3==0)return"".concat(a).concat(s/1e3);let n=Math.floor(s/1e3),i=String(s%1e3).padStart(3,"0");return"".concat(a).concat(n,".").concat(i)}
1Object.defineProperty(t,"__esModule",{value:!0}),t.getCurrencyDecimalPlaces=a,t.roundKwdToNext005=r,t.formatKwdAmount=s,t.formatCurrencyAmount=function(e,t){if(!Number.isFinite(e))return"0";let r=t.toLowerCase();if("kw"===r)return s(e);let n=a(r);return parseFloat(e.toFixed(n)).toString()}},42615:(e,t,a)=>{"use strict";a.d(t,{A:()=>r});let r=(0,a(48375).A)("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]])},48922:(e,t,a)=>{"use strict";a.d(t,{A:()=>r});let r=(0,a(48375).A)("check-check",[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]])},50438:(e,t,a)=>{"use strict";a.d(t,{A:()=>r});let r=(0,a(48375).A)("mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]])},51140:(e,t,a)=>{"use strict";a.r(t),a.d(t,{ChatAssignmentService:()=>j,countOpenChatsByAgent:()=>y,default:()=>A,getAgentOpenChatCount:()=>f,getAssignableAgentCandidates:()=>b,getChatUrgencyScore:()=>h,getChatWaitSeconds:()=>m,getCustomerQueueState:()=>w,maybeSendQueueDelayReminder:()=>N,processUnassignedOpenChats:()=>k,sortChatsByUrgency:()=>x,tryAutoAssignChat:()=>v});var r=a(72279),s=a(68634),n=a(50473);let i=null,l=0;async function o(){let e=Date.now();if(i&&e-l<3e5)return i;let t=new Map;try{(await (0,r.getDocs)((0,r.collection)(function(){let e=(0,r.getBrowserFirestore)();if(!e)throw Error("Firebase Firestore is not initialized");return e}(),"agentSchedules"))).forEach(e=>{let a=e.data(),r=function(e){if(!e||"object"!=typeof e)return null;let t={};for(let a of n.o){let r=e[a];if(null==r){t[a]=null;continue}if("object"!=typeof r)return null;let s=r.start,n=r.end;if("string"!=typeof s||"string"!=typeof n)return null;t[a]={start:s,end:n}}return t}(a.weekly);t.set(e.id,{agentId:e.id,displayName:"string"==typeof a.displayName?a.displayName:void 0,timezone:"string"==typeof a.timezone?a.timezone:"Asia/Kuwait",weekly:null!=r?r:(0,s.O5)(e.id).weekly})})}catch(e){console.warn("[getAgentSchedulesMapClient] could not load schedules, using defaults",e)}return i=t,l=e,t}var d=a(95487),c=a(93427),u=a(75513);function g(){let e=(0,r.getBrowserFirestore)();if(!e)throw Error("Firebase Firestore is not initialized");return e}function m(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now(),a=(0,c.kU)(e.lastMessageAt),r=(0,c.kU)(e.createdAt),s=null!=a?a:r;return s?Math.max(0,(t-s.getTime())/1e3):0}function h(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();if("open"!==e.status)return 0;let a=m(e,t);return 0!==a||(0,c.kU)(e.lastMessageAt)||(0,c.kU)(e.createdAt)?e.agentId?e.hasUnreadMessages&&"customer"===e.lastMessageSender?a+1e5:0:e.hasUnreadMessages||"customer"===e.lastMessageSender||!e.lastMessageSender?a+1e6:a+5e5:0}function x(e){let t=Date.now();return[...e].sort((e,a)=>{var r,s,n,i;let l=h(a,t)-h(e,t);return 0!==l?l:(null!==(n=null===(r=(0,c.kU)(a.lastMessageAt))||void 0===r?void 0:r.getTime())&&void 0!==n?n:0)-(null!==(i=null===(s=(0,c.kU)(e.lastMessageAt))||void 0===s?void 0:s.getTime())&&void 0!==i?i:0)})}function p(e){var t,a,r,s;return null!==(s=null!==(r=null===(t=(0,c.kU)(e.createdAt))||void 0===t?void 0:t.getTime())&&void 0!==r?r:null===(a=(0,c.kU)(e.lastMessageAt))||void 0===a?void 0:a.getTime())&&void 0!==s?s:0}async function y(){let e=await (0,r.getDocs)((0,r.query)((0,r.collection)(g(),"chats"),(0,r.where)("status","==","open"))),t=new Map;return e.forEach(e=>{let a=e.data().agentId;a&&t.set(a,(t.get(a)||0)+1)}),t}async function b(){let e=Date.now(),[t,a,n]=await Promise.all([(0,r.getDocs)((0,r.query)((0,r.collection)(g(),"userPresence"),(0,r.where)("userType","==","agent"))),y(),o()]),i=[];return t.forEach(t=>{var r;let l=t.data(),o=l.userId||t.id;if(!o||!(l.isOnline&&24e4>function(e,t){let a=(0,c.kU)(e.lastActivity),r=(0,c.kU)(e.lastSeen),s=null!=a?a:r;return s?t-s.getTime():e.isOnline?0:Number.POSITIVE_INFINITY}(l,e))||"available"!==l.status)return;let u="string"==typeof l.displayName&&l.displayName.trim()?l.displayName.trim():"Support Agent",g=null!==(r=n.get(o))&&void 0!==r?r:(0,s.O5)(o,u);if(!(0,s.l2)(g))return;let m=a.get(o)||0;m>=d.pg||i.push({userId:o,displayName:u,openChatCount:m})}),i.sort((e,t)=>
1e.openChatCount!==t.openChatCount?e.openChatCount-t.openChatCount:e.userId.localeCompare(t.userId))}async function f(e){return(await y()).get(e)||0}async function v(e){if(!(0,d.mR)())return!1;try{let t=await (0,r.getDoc)((0,r.doc)(g(),"chats",e));if(!t.exists())return!1;let a=t.data();if("open"!==a.status||a.agentId)return!1;let s=await b(),n=function(e,t){if(0===e.length)return null;let a=Math.min(...e.map(e=>e.openChatCount)),r=e.filter(e=>e.openChatCount===a);if(1===r.length)return r[0];let s=[...r].sort((e,t)=>e.userId.localeCompare(t.userId)),n=function(e){let t=0x811c9dc5;for(let a=0;a<e.length;a++)t^=e.charCodeAt(a),t=Math.imul(t,0x1000193);return t>>>0}(t)%s.length;return s[n]}(s,e);if(!n)return!1;return await u.S.assignAgent(e,n.userId,n.displayName,{allowReassign:!1})}catch(t){return console.warn("[tryAutoAssignChat]",e,t),!1}}async function k(){if(!(0,d.mR)())return 0;try{let e=(await (0,r.getDocs)((0,r.query)((0,r.collection)(g(),"chats"),(0,r.where)("status","==","open")))).docs.filter(e=>!e.data().agentId).map(e=>({id:e.id,data:e.data()})).sort((e,t)=>p(e.data)-p(t.data)),t=0;for(let a of e)await v(a.id)&&(t+=1);return t}catch(e){return console.warn("[processUnassignedOpenChats]",e),0}}async function w(e){try{let t=await (0,r.getDoc)((0,r.doc)(g(),"chats",e));if(!t.exists())return null;let a={id:t.id,...t.data()};if("open"!==a.status||a.agentId)return null;let s=(await (0,r.getDocs)((0,r.query)((0,r.collection)(g(),"chats"),(0,r.where)("status","==","open")))).docs.filter(e=>!e.data().agentId).map(e=>({id:e.id,data:e.data()})).sort((e,t)=>p(e.data)-p(t.data)),n=s.findIndex(t=>t.id===e);if(n<0)return null;let i=n+1;return{position:i,totalWaiting:s.length,estimatedWaitMinutes:Math.max(1,i*d.Hy)}}catch(t){return console.warn("[getCustomerQueueState]",e,t),null}}async function N(e){try{var t;let a=await (0,r.getDoc)((0,r.doc)(g(),"chats",e));if(!a.exists())return;let s=a.data();if("open"!==s.status||s.agentId)return;let n=null!==(t=(0,c.kU)(s.lastMessageAt))&&void 0!==t?t:(0,c.kU)(s.createdAt);if(!n||(Date.now()-n.getTime())/1e3<d.x4||(await (0,r.getDocs)((0,r.collection)(g(),"chats",e,"messages"))).docs.some(e=>{let t=e.data();return"system"===t.senderType&&"string"==typeof t.content&&t.content.toLowerCase().includes("still with you")}))return;let i=await w(e),l=i?"You're #".concat(i.position," in line â we're still with you and an agent will join shortly."):"Thanks for your patience â we're still with you and an agent will join shortly.";await u.S.sendMessage(e,"system","Ghaseel Support","system",l)}catch(t){console.warn("[maybeSendQueueDelayReminder]",e,t)}}let j={sortChatsByUrgency:x,getChatUrgencyScore:h,getChatWaitSeconds:m,tryAutoAssignChat:v,processUnassignedOpenChats:k,getCustomerQueueState:w,maybeSendQueueDelayReminder:N,getAssignableAgentCandidates:b,getAgentOpenChatCount:f,countOpenChatsByAgent:y},A=j},56861:(e,t,a)=>{"use strict";a.d(t,{A:()=>s});var r=a(37876);a(14232);let s=e=>{let{agentName:t="Support agent",isVisible:a,variant:s="customer"}=e;return a?(0,r.jsxs)("div",{className:"flex justify-start mb-4 animate-fadeInUp",children:[(0,r.jsx)("div",{className:"mr-3 mt-1 flex-shrink-0",children:(0,r.jsx)("div",{className:"w-8 h-8 bg-gradient-to-br from-blue-100 to-blue-200 rounded-full flex items-center justify-center shadow-md border-2 border-white",children:(0,r.jsx)("span",{className:"text-xs font-bold text-blue-700",children:t.split(" ").map(e=>e[0]).join("").substr(0,2).toUpperCase()})})}),(0,r.jsxs)("div",{className:"max-w-xs lg:max-w-md",children:[(0,r.jsx)("div",{className:"text-xs text-gray-400 mb-1 opacity-100 transition-opacity duration-200",children:"Just now"}),(0,r.jsx)("div",{className:"bg-white text-gray-900 border border-gray-200 rounded-lg shadow-sm hover:shadow-md px-4 py-3 transition-all duration-200",children:(0,r.jsxs)("div",{className:"flex items-center space-x-3",children:[(0,r.jsx)("div",{className:"text-sm text-gray-600 font-medium",children:"customer"===s?"".concat(t," is typing"):"Customer is typing"}),(0,r.jsxs)("div",{className:"flex space-x-1",children:[(0,r.jsx)("div",{className:"w-2.5 h-2.5 rounded-full typing-dot",style:{backgroundColor:"#00bfff",animation:"typing-dot 1s infinite 0s"}}),(0,r.jsx)("div",{className:"w-2.5 h-2.5 rounded-full typing-dot",style:{backgroundColor:"#00bfff",animation:"typing-dot 1s infinite 0.2s"}}),(0,r.jsx)("div",{className:"w-2.5 h-2.5 rounded-full typing-dot",style:{backgroundColor:"#00bfff",animation:"typing-dot 1s infinite 0.4s"}})]})]})})]})]}):null}},59524:(e,t,a)=>{"use strict";a.d(t,{A:()=>r});
1let r=(0,a(48375).A)("copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]])},65323:(e,t,a)=>{"use strict";a.d(t,{A:()=>r});let r=(0,a(48375).A)("package",[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]])},66929:(e,t,a)=>{"use strict";a.d(t,{A:()=>r});let r=(0,a(48375).A)("credit-card",[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]])},69667:(e,t,a)=>{"use strict";a.d(t,{A:()=>r});let r=(0,a(48375).A)("phone",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]])},78641:(e,t,a)=>{"use strict";a.d(t,{A:()=>r});let r=(0,a(48375).A)("info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]])},84315:(e,t,a)=>{"use strict";a.d(t,{A:()=>r});let r=(0,a(48375).A)("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]])},84455:(e,t,a)=>{"use strict";a.d(t,{A:()=>r});let r=(0,a(48375).A)("gift",[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]])},89406:(e,t,a)=>{"use strict";a.d(t,{D:()=>n});var r=a(72279);function s(){let e=(0,r.getBrowserFirestore)();if(!e)throw Error("Firebase Firestore is not initialized");return e}class n{static async startTyping(e,t,a,n){try{let i="".concat(e,"_").concat(t);await (0,r.BN)((0,r.doc)(s(),"typingStatus",i),{chatId:e,userId:t,userName:a,userType:n,isTyping:!0,startedAt:(0,r.O5)(),lastActivity:(0,r.O5)()});let l=this.typingTimeouts.get(i);l&&clearTimeout(l);let o=setTimeout(()=>{this.stopTyping(e,t)},this.TYPING_TIMEOUT);this.typingTimeouts.set(i,o)}catch(e){console.error("Error starting typing status:",e)}}static async updateTypingActivity(e,t){try{let a="".concat(e,"_").concat(t);await (0,r.updateDoc)((0,r.doc)(s(),"typingStatus",a),{lastActivity:(0,r.O5)()});let n=this.typingTimeouts.get(a);n&&clearTimeout(n);let i=setTimeout(()=>{this.stopTyping(e,t)},this.TYPING_TIMEOUT);this.typingTimeouts.set(a,i)}catch(e){console.error("Error updating typing activity:",e)}}static async stopTyping(e,t){try{let a="".concat(e,"_").concat(t);await (0,r.kd)((0,r.doc)(s(),"typingStatus",a));let n=this.typingTimeouts.get(a);n&&(clearTimeout(n),this.typingTimeouts.delete(a))}catch(e){console.error("Error stopping typing status:",e)}}static subscribeToTypingStatus(e,t,a){let n=(0,r.doc)(s(),"chats",e);return(0,r.aQ)(n,a=>{if(a.exists()){let r=a.data(),s=[];r.agentTyping&&s.push({chatId:e,userId:r.agentId||"",userName:r.agentName||"Agent",userType:"agent",isTyping:!0,startedAt:r.agentTypingStarted}),r.customerTyping&&s.push({chatId:e,userId:r.customerId||"",userName:r.customerName||"Customer",userType:"customer",isTyping:!0,startedAt:r.customerTypingStarted}),t(s)}},a)}static async setAgentTyping(e,t,a,n){try{let i=n?{agentTyping:!0,agentTypingStarted:(0,r.O5)()}:{agentTyping:!1,agentTypingStarted:null};await (0,r.updateDoc)((0,r.doc)(s(),"chats",e),i),n&&setTimeout(()=>{this.setAgentTyping(e,t,a,!1)},this.TYPING_TIMEOUT)}catch(e){console.error("Error setting agent typing status:",e)}}static async setCustomerTyping(e,t,a,n){try{let i=n?{customerTyping:!0,customerTypingStarted:(0,r.O5)()}:{customerTyping:!1,customerTypingStarted:null};await (0,r.updateDoc)((0,r.doc)(s(),"chats",e),i),n&&setTimeout(()=>{this.setCustomerTyping(e,t,a,!1)},this.TYPING_TIMEOUT)}catch(e){console.error("Error setting customer typing status:",e)}}static async cleanupTypingStatus(e,t){try{await (0,r.updateDoc)((0,r.doc)(s(),"chats",e),{agentTyping:!1,customerTyping:!1,agentTypingStarted:null,customerTypingStarted:null})}catch(e){console.error("Error cleaning up typing status:",e)}}}n.typingTimeouts=new Map,n.TYPING_TIMEOUT=1e4},90163:(e,t,a)=>{"use strict";a.d(t,{A:()=>r});let r=(0,a(48375).A)("circle-check-big",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]])},95487:(e,t,a)=>{"use strict";a.d(t,{Hy:()=>i,mR:()=>n,pg:()=>s,x4:()=>l});var r=a(99742);let s=6;function n(){let e=r.env.NEXT_PUBLIC_CHAT_AUTO_ASSIGN;return"false"!==e&&"0"!==e}let i=3,l=300},95979:(e,t,a)=>{"use strict";a.d(t,{A:()=>r});let r=(0,a(48375).A)("tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.
1172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]])},98578:(e,t,a)=>{"use strict";a.d(t,{A:()=>r});let r=(0,a(48375).A)("sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]])}},e=>{var t=t=>e(e.s=t);e.O(0,[7708,38513,74938,23427,48230,42749,1126,81560,46197,58900,59025,34377,29551,75513,12569,38458,90636,46593,38792],()=>t(21304)),_N_E=e.O()}]);
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.