1import{r as n,j as e,l as $s,u as Ms,k as Rs}from"./vendor-react-DgB3iddG.js";import{d as J}from"./vendor-mui-dates-KAGm-C0e.js";import{r as us}from"./relativeTime-CxkCVA_Y.js";import{u as Ls}from"./usePageTitle-DrV3LWkF.js";import{L as Fs}from"./Loader-CS_NcaeR.js";import{B as A}from"./Button-Db-HvAAM.js";import{C as V,a as G,b as K,c as q}from"./Card-Cw165hpS.js";import{S as pe,a as he,b as ge,c as fe,d as X}from"./Select-70f5R9tb.js";import{e as $e,d as L,a as B,t as w,T as xe,A as Es,u as Ws,l as Os,L as ye,f as Bs}from"./index-BsRQWV7N.js";import{I as F}from"./Input-9YFrCCg-.js";import{L as y}from"./Label-ve9PMxD-.js";import{C as Ae}from"./ColorPicker-DsR4V7KY.js";import{D as xs,a as ps,b as hs,c as gs,d as Us,e as zs}from"./Dialog-BHIUuuFq.js";import{C as Vs,S as Ys}from"./Slider-BXQZm8q9.js";import{C as qs}from"./vendor-crop-Co4vAK2x.js";import{Z as Hs,a as Gs,g as Ks}from"./cropImage-DZupTcg-.js";import{T as ee,U as Zs}from"./TeamStyleSwitch-CfqiVYxn.js";import{T as Me}from"./trash-2-De6jbET0.js";import{M as ce}from"./message-circle-BrUoq2LQ.js";import{V as Qs}from"./volume-2-D5gaJ3Gf.js";import{P as ve}from"./play-B_RNSV1J.js";import{C as Pe}from"./ConfirmationModal-C-Mdj4uA.js";import{C as Js}from"./Checkbox-vlTLcfXh.js";import{R as de}from"./rotate-ccw-9SCdCg1_.js";import{P as fs}from"./plus-ApsWvHpL.js";import{G as Xs}from"./grip-vertical-B3V2KOOz.js";import{P as et}from"./pause-U9mO8IqT.js";import{C as st}from"./chevron-up-daRQHEXm.js";import{C as tt}from"./chevron-down-C2bolbZ7.js";import{T as Ne}from"./ticket-CbZ__K99.js";import{P as Qe}from"./PromptRefiner-BIyAEhPp.js";import{s as at,r as rt}from"./savedReplyUtils-BK4mydd2.js";import{A as bs,M as nt}from"./AiTesterImproveModal-BEYjES5W.js";import{c as ot}from"./debugLogMarkdown-HVt_4OVx.js";import{B as Ie}from"./bot-V4-GaM5X.js";import{W as js}from"./wand-sparkles-B8-El2QK.js";import{T as it,a as lt}from"./thumbs-up-CvtdXIwU.js";import{U as ct}from"./user-BSW88z6a.js";import{S as Je}from"./smartphone-Cx049nuU.js";import{T as Xe,B as dt,W as mt}from"./WebChatAnalytics-FxOpPcls.js";import{M as es}from"./monitor-O2IJsrDH.js";import{H as ut}from"./hourglass-DVMmes1i.js";import{L as xt}from"./log-out-B9sbBzJf.js";import{M as pt}from"./mouse-pointer-click-CmWi-HZu.js";import{C as ht}from"./clock-a58MzTpI.js";import{C as ys}from"./check-DYtTEDZg.js";import{C as De}from"./copy-DBlEVzEc.js";import{C as gt}from"./circle-check-big-BlMKzsun.js";import{G as vs}from"./globe-CnwG3Yxz.js";import{S as Ns}from"./send-BHYlAYq7.js";import{C as ft}from"./code-Kq9tq5Ic.js";
1import{X as ss}from"./x-DWKg9FV8.js";import{F as ts}from"./flask-conical-kKjhAJI_.js";import{T as bt}from"./TicketingAddonModal-DitsNBU1.js";import{L as as}from"./life-buoy-D79BpOx3.js";import{S as Re}from"./sparkles-CclfS-zl.js";import{C as jt}from"./clipboard-BiIDLCIB.js";import{A as yt}from"./arrow-left-DjjddyBh.js";import{H as vt}from"./hash-BnfmGt8P.js";import{P as rs}from"./package-C9nhAtz9.js";import{E as Nt}from"./external-link-BXZZjxTv.js";import"./vendor-radix-Cc5wg9nu.js";import"./vendor-realtime-BWTNjo9H.js";import"./productAiContext-DE9OCemd.js";import"./eye-DERChyZO.js";import"./ContextEditSuggestionCard-lABALD6R.js";import"./shield-alert-B-wHTuvb.js";import"./circle-alert--s34Tx7J.js";import"./info-BHJQcz8S.js";import"./PeriodSelector-DEavvSQ5.js";import"./AnalyticsBackgroundNotice-B1FZPN5q.js";import"./vendor-charts-DKo9vBq6.js";import"./message-square-D7Ghlg3r.js";import"./chart-column-xO_L2eeK.js";import"./users-C-8OuGS6.js";import"./activity-C8J7gRVG.js";import"./arrow-up-right-CMFlUzg7.js";import"./arrow-down-right-BC3-H-rW.js";import"./minus-CsP4swHL.js";import"./paddleCheckout-CNZgUm8-.js";import"./useDismissableModal-BQmfYHyf.js";import"./mail-C1UYTvO6.js";/** 2 * @license lucide-react v0.554.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const _t=[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]],wt=$e("arrow-down-to-line",_t);/** 7 * @license lucide-react v0.554.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const kt=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]],St=$e("circle-user",kt);/** 12 * @license lucide-react v0.554.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const Ct=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],At=$e("square",Ct);function Tt({webChat:t,onUpdate:u,saving:g}){var k,m,N,a;const l=i=>({theme_color:i.theme_color||"#7C3AED",text_color:i.text_color||"#FFFFFF",bg_color:i.bg_color||"#FFFFFF",position:i.position||"bottom-right",chat_title:i.chat_title||"Hi there!",chat_subtitle:i.chat_subtitle||"We usually reply within minutes",agent_name:i.agent_name||"Assistant",agent_avatar:i.agent_avatar||"",show_branding:i.show_branding??!0,mobile_fullscreen:i.mobile_fullscreen??!1,launcher_text:i.launcher_text||"",launcher_cta_text:i.launcher_cta_text||"Open Live Chat"}),[s,r]=n.useState(()=>l(t));n.useEffect(()=>{r(l(t))},[t.id,t.agent_avatar]);const[p,S]=n.useState(null),[D,b]=n.useState({x:0,y:0}),[c,C]=n.useState(1),[T,U]=n.useState(null),[E,h]=n.useState(!1),[M,$]=n.useState(!1),I=n.useRef(null),v=(i,j)=>r(z=>({...z,[i]:j})),O=async i=>{if(i.target.files&&i.target.files.length>0){const j=i.target.files[0],z=new FileReader;z.addEventListener("load",()=>{S(z.result),C(1),b({x:0,y:0}),h(!0)}),z.readAsDataURL(j)}I.current&&(I.current.value="")},P=async()=>{$(!0);try{const i=await Ks(p,T,0,{horizontal:!1,vertical:!1},256,256),j=new FormData;j.append("avatar",i,"avatar.jpg");const Z=(await B.post(`/web-chats/${t.id}/avatar`,j)).agent_avatar;v("agent_avatar",Z),h(!1),w.success("Avatar uploaded")}catch{w.error("Failed to upload avatar")}finally{$(!1)}},H=async()=>{try{await B.delete(`/web-chats/${t.id}/avatar`),v("agent_avatar",""),w.success("Avatar removed")}catch{w.error("Failed to remove avatar")}},W=s.agent_avatar;return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs(V,{children:[e.jsx(G,{children:e.jsx(K,{className:"text-base",children:"Colors"})}),e.jsx(q,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsx(Ae,{label:"Theme",value:s.theme_color,onChange:i=>v("theme_color",i)}),e.jsx(Ae,{label:"Text",value:s.text_color,onChange:i=>v("text_color",i)}
16),e.jsx(Ae,{label:"Background",value:s.bg_color,onChange:i=>v("bg_color",i)})]})})]}),e.jsxs(V,{children:[e.jsx(G,{children:e.jsx(K,{className:"text-base",children:"Chat Window"})}),e.jsxs(q,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Title"}),e.jsx(F,{value:s.chat_title,onChange:i=>v("chat_title",i.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Subtitle"}),e.jsx(F,{value:s.chat_subtitle,onChange:i=>v("chat_subtitle",i.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Agent Name"}),e.jsx(F,{value:s.agent_name,onChange:i=>v("agent_name",i.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Agent Avatar"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative group",children:[e.jsx("div",{className:"w-12 h-12 rounded-full flex items-center justify-center overflow-hidden border-2 border-border cursor-pointer hover:border-primary/40 transition-colors",onClick:()=>{var i;return(i=I.current)==null?void 0:i.click()},style:{backgroundColor:W?"transparent":s.theme_color+"20"},children:W?e.jsx("img",{src:W,alt:"",className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-lg font-bold",style:{color:s.theme_color},children:((m=(k=s.agent_name)==null?void 0:k[0])==null?void 0:m.toUpperCase())||"A"})}),e.jsx("button",{onClick:()=>{var i;return(i=I.current)==null?void 0:i.click()},className:"absolute -bottom-1 -right-1 w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center shadow-sm hover:bg-primary/90 transition-colors",children:e.jsx(Vs,{className:"w-3 h-3"})})]}),W&&e.jsxs(A,{variant:"ghost",size:"sm",onClick:H,className:"text-destructive hover:text-destructive hover:bg-destructive/10 text-xs h-8 px-2",children:[e.jsx(Me,{className:"w-3.5 h-3.5 mr-1"})," Remove"]})]}),e.jsx("input",{ref:I,type:"file",accept:"image/*",onChange:O,className:"hidden"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Position"}),e.jsx("div",{className:"flex gap-2",children:["bottom-left","bottom-right"].map(i=>e.jsx("button",{onClick:()=>v("position",i),className:L("px-4 py-2 rounded-lg text-sm font-medium border transition-all",s.position===i?"border-primary bg-primary/10 text-primary":"border-border text-muted-foreground hover:border-primary/30"),children:i.replace("-"," ")},i))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(y,{children:["Launcher Bubble Text ",e.jsx("span",{className:"text-muted-foreground font-normal",children:"(optional)"})]}),e.jsx(F,{value:s.launcher_text,onChange:i=>v("launcher_text",i.target.value),placeholder:"Chat with us"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Shown as subtitle in the expanded launcher card (e.g. "Eugene is online").'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Open Chat Button Text"}),e.jsx(F,{value:s.launcher_cta_text,onChange:i=>v("launcher_cta_text",i.target.value),placeholder:"Open Live Chat"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Text on the CTA button in the expanded launcher card."})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ee,{checked:s.show_branding,onCheckedChange:i=>v("show_branding",i),"aria-label":'Show "Powered by PageDock"'}),e.jsx(y,{className:"cursor-pointer",onClick:()=>v("show_branding",!s.show_branding),children:'Show "Powered by PageDock"'})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ee,{checked:s.mobile_fullscreen,onCheckedChange:i=>v("mobile_fullscreen",i),"aria-label":"Full screen on mobile"}),e.jsxs("div",{children:[e.jsx(y,{className:"cursor-pointer",onClick:()=>v("mobile_fullscreen",!s.mobile_fullscreen),children:"Full screen on mobile"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When enabled, the chat takes the entire screen on phones. Otherwise it floats with rounded corners."})]})]})]})]}),e.jsx(A,{onClick:()=>u(s),disabled:g,className:"w-full",children:g?"Saving...":"Save Appearance"})]}),e.jsx("div",{className:"lg:sticky lg:top-6 self-start",children:e.jsxs(V,{children:[e.jsx(G,{children:e.jsx(K,{className:"text-base",children:"Preview"})}),e.jsx(q,{children:e.jsxs("div",{className:"bg-secondary/50 rounded-2xl p-4 min-h-[580px] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-4 flex flex-col gap-3 opacity-[0.07] pointer-events-none",children:[...Array(10)].map((i,j)=>e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"h-3 bg-foreground rounded",style:{width:`${40+j*13%50}%`}}),e.jsx("div",{className:"h-3 bg-foreground rounded flex-1"})]},j))}),e.jsxs("div",{className:L("absolute w-[260px] rounded-2xl overflow-hidden shadow-xl border border-border transition-all duration-300",s.position==="bottom-right"?"right-4":"left-4"),style:{backgroundColor:s.bg_color,bottom:"140px"},children:[e.jsxs("div",{className:"p-3 flex items-center gap-2.5",style:{backgroundColor:s.theme_color},children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-white/20 flex items-center justify-center shrink-0 overflow-hidden",children:W?e.jsx("img",{src:W,alt:"",className:"w-8 h-8 rounded-full object-cover"}):e.jsx(ce,{className:"w-4 h-4",style:{color:s.text_color}})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-semibold truncate",style:{color:s.text_color},children:s.chat_title}),e.jsx("p",{className:"text-[10px] opacity-80 truncate",style:{color:s.text_color},children:s.chat_subtitle})]})]}),e.jsxs("div",{className:"p-3 space-y-2.5 min-h-[160px]",style:{backgroundColor:s.bg_color},children:[e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("div",{className:"w-6 h-6 rounded-full flex-shrink-0 flex items-center justify-center text-[8px] font-bold overflow-hidden",style:{backgroundColor:s.theme_color+"20",color:s.theme_color},children:W?e.jsx("img",{src:W,alt:"",className:"w-6 h-6 object-cover"}):((N=s.agent_name)==null?void 0:N[0])||"A"}),e.jsxs("div",{className:"rounded-2xl rounded-tl-sm px-2.5 py-1.5 text-[11px] max-w-[82%]",style:{backgroundColor:s.theme_color+"15",color:"#333"},children:["Hi! I'm ",s.agent_name,". How can I help?"]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx("div",{className:"rounded-2xl rounded-tr-sm px-2.5 py-1.5 text-[11px] max-w-[82%] text-white",style:{backgroundColor:s.theme_color},children:"Tell me about pricing"})})]}),e.jsx("div",{className:"p-2 border-t",style:{borderColor:"#eee"},children:e.jsx("div",{className:"rounded-full bg-secondary px-3 py-1.5 text-[10px] text-muted-foreground",children:"Type a message..."})}),s.show_branding&&e.jsx("div",{className:"text-center py-1 text-[8px] text-muted-foreground",children:"Powered by PageDock"})]}),e.jsx("div",{className:L("absolute bottom-4 transition-all duration-300",s.position==="bottom-right"?"right-4":"left-4"),children:e.jsxs("div",{className:"bg-white rounded-2xl p-3 border border-gray-100 w-[220px]",style:{boxShadow:"0 6px 24px rgba(0,0,0,0.14)"},children:[e.jsxs("div",{className:"flex items-center justify-between gap-2.5 mb-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[11px] font-semibold text-gray-900 leading-tight",children:s.chat_title||"Questions? Chat with us."}),e.jsxs("p",{className:"text-[10px] text-gray-500 flex items-center gap-1 mt-0.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0 inline-block",style:{animation:"pdock-pulse 2s ease-in-out infinite"}}),s.launcher_text||(s.agent_name?`${s.agent_name} is online`:"We're online")]})]}),e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold shrink-0 overflow-hidden",style:{backgroundColor:s.theme_color,color:s.text_color},children:W?e.jsx("img",{src:W,alt:"",className:"w-full h-full object-cover rounded-full"}):(((a=s.agent_name)==null?void 0:a[0])||"A").toUpperCase()})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("div",{className:"flex-1 flex items-center justify-center gap-1.5 py-2 rounded-lg text-[11px] font-semibold",style:{backgroundColor:s.theme_color,color:s.text_color},children:[e.jsx(ce,{className:"w-3.5 h-3.5"}),s.launcher_cta_text||"Open Live Chat"]}),e.jsx("div",{className:"w-9 h-9 rounded-full flex items-center justify-center shadow-lg shrink-0",style:{backgroundColor:s.theme_color},children:e.jsx(ce,{className:"w-4 h-4",style:{color:s.text_color}})})]})]})}),e.jsx("style",{children:` 17 @keyframes pdock-pulse { 18 0% { box-shadow: 0 0 0 0 rgba(34,197,94,0.55); } 19 60% { box-shadow: 0 0 0 5px rgba(34,197,94,0); } 20 100% { box-shadow: 0 0 0 0 rgba(34,197,94,0); } 21 } 22 `})]})})]})}),e.jsx(xs,{open:E,onOpenChange:h,children:e.jsxs(ps,{className:"sm:max-w-[500px] bg-card border-border",children:[e.jsx(hs,{children:e.jsx(gs,{children:"Adjust Agent Avatar"})}),e.jsx("div",{className:"relative w-full h-[300px] bg-secondary rounded-xl overflow-hidden",children:p&&e.jsx(qs,{image:p,crop:D,zoom:c,aspect:1,cropShape:"round",showGrid:!1,onCropChange:b,onZoomChange:C,onCropComplete:(i,j)=>U(j)})}),e.jsxs("div",{className:"flex items-center gap-3 px-2",children:[e.jsx(Hs,{className:"w-4 h-4 text-muted-foreground shrink-0"}),e.jsx(Ys,{value:[c],min:1,max:3,step:.05,onValueChange:([i])=>C(i)}),e.jsx(Gs,{className:"w-4 h-4 text-muted-foreground shrink-0"})]}),e.jsxs(Us,{children:[e.jsx(A,{variant:"outline",onClick:()=>h(!1),disabled:M,children:"Cancel"}),e.jsx(A,{onClick:P,disabled:M,children:M?"Uploading...":"Apply"})]})]})})]})}const Pt=[{id:"gentle-chime",name:"Gentle Chime"},{id:"bright-pop",name:"Bright Pop"},{id:"soft-ping",name:"Soft Ping"},{id:"pluck",name:"Pluck"},{id:"droplet",name:"Droplet"},{id:"bubble",name:"Bubble"},{id:"sunrise",name:"Sunrise"},{id:"crystal",name:"Crystal"},{id:"bell",name:"Bell"},{id:"chime",name:"Chime"}];function It({webChat:t,onUpdate:u,saving:g}){const[l,s]=n.useState({auto_open_delay:t.auto_open_delay||0,auto_open_once:t.auto_open_once??!1,disable_auto_open_mobile:t.disable_auto_open_mobile??!1,open_on_exit_intent:t.open_on_exit_intent??!1,open_on_scroll_end:t.open_on_scroll_end??!1,open_on_i
22dle:t.open_on_idle??!1,idle_timeout:t.idle_timeout??60,sound_enabled:t.sound_enabled??!0,notification_sound:t.notification_sound||"gentle-chime",offline_message:t.offline_message||"",max_conversation_messages:t.max_conversation_messages||50,response_coalesce_ms:t.response_coalesce_ms||3e3,reply_delay_min:t.reply_delay_min??3,reply_delay_max:t.reply_delay_max??8,privacy_url:t.privacy_url||""}),r=(c,C)=>s(T=>({...T,[c]:C})),p=n.useRef(null),[S,D]=n.useState(null),b=n.useCallback(c=>{if(p.current&&(p.current.pause(),p.current.currentTime=0),S===c){D(null);return}const C=window.location.origin,T=new Audio(`${C}/webchat/sounds/${c}.mp3`);p.current=T,D(c),T.play().catch(()=>{}),T.onended=()=>D(null)},[S]);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs(V,{children:[e.jsx(G,{children:e.jsx(K,{className:"text-base",children:"Auto-Open"})}),e.jsxs(q,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Auto-open delay (seconds)"}),e.jsx(F,{type:"number",min:0,max:300,value:l.auto_open_delay,onChange:c=>r("auto_open_delay",parseInt(c.target.value)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Set to 0 to disable. Widget opens automatically after this many seconds."})]}),l.auto_open_delay>0&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ee,{checked:l.auto_open_once,onCheckedChange:c=>r("auto_open_once",c),"aria-label":"Auto-open once per visitor"}),e.jsx(y,{className:"cursor-pointer",onClick:()=>r("auto_open_once",!l.auto_open_once),children:"Auto-open once per visitor"})]}),l.auto_open_delay>0&&l.auto_open_once&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"The widget will only auto-open on the visitor's first visit. On subsequent visits it stays closed until they click."}),l.auto_open_delay>0&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ee,{checked:l.disable_auto_open_mobile,onCheckedChange:c=>r("disable_auto_open_mobile",c),"aria-label":"Disable auto open on mobile"}),e.jsx(y,{className:"cursor-pointer",onClick:()=>r("disable_auto_open_mobile",!l.disable_auto_open_mobile),children:"Disable auto open on mobile"})]}),l.auto_open_delay>0&&l.disable_auto_open_mobile&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"On phones and small screens (â¤768px), the widget will not open automatically after the delay. Visitors can still open it manually."}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ee,{checked:l.sound_enabled,onCheckedChange:c=>r("sound_enabled",c),"aria-label":"Play sound on new messages"}),e.jsx(y,{className:"cursor-pointer",onClick:()=>r("sound_enabled",!l.sound_enabled),children:"Play sound on new messages"})]}),l.sound_enabled&&e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs(y,{className:"text-xs flex items-center gap-1.5",children:[e.jsx(Qs,{className:"w-3.5 h-3.5"}),"Notification sound"]}),e.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:Pt.map(c=>{const C=l.notification_sound===c.id,T=S===c.id;return e.jsxs("button",{type:"button",onClick:()=>{r("notification_sound",c.id),b(c.id)},className:L("flex items-center gap-2 px-2.5 py-2 rounded-lg border text-xs font-medium transition-all text-left",C?"border-primary bg-primary/5 text-primary ring-1 ring-primary/20":"border-border hover:bg-secondary/50 text-foreground"),children:[e.jsx("span",{className:L("w-6 h-6 rounded-full flex items-center justify-center shrink-0 transition-colors",C?"bg-primary text-primary-foreground":"bg-secondary text-muted-foreground"),children:T?e.jsx(At,{className:"w-2.5 h-2.5"}):e.jsx(ve,{className:"w-2.5 h-2.5 ml-0.5"})}),e.jsx("span",{className:"truncate",children:c.name})]},c.id)})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click any sound to preview and select it."})]})]})]}),e.jsxs(V,{children:[e.jsx(G,{children:e.jsx(K,{className:"text-base",children:"Offline & Privacy"})}),e.jsxs(q,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Offline message"}),e.jsx("textarea",{value:l.offline_message,onChange:c=>r("offline_message",c.target.value),maxLength:1e3,placeholder:"We're currently away. Leave us a message and we'll get back to you!",className:"w-full min-h-[80px] rounded-xl border border-input bg-background px-4 py-3 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/20 focus-visible:border-primary transition-all resize-none"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Privacy Policy URL"}),e.jsx(F,{value:l.privacy_url,onChange:c=>r("privacy_url",c.target.value),placeholder:"https://example.com/privacy"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown in the widget footer. Recommended for GDPR compliance."})]})]})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(V,{children:[e.jsx(G,{children:e.jsx(K,{className:"text-base",children:"Smart Triggers"})}),e.jsxs(q,{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Automatically open the chat when visitors show specific behaviors. These only fire if the chat is not already open."}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ee,{checked:l.open_on_exit_intent,onCheckedChange:c=>r("open_on_exit_intent",c),"aria-label":"Open on exit intent"}),e.jsx(y,{className:"cursor-pointer",onClick:()=>r("open_on_exit_intent",!l.open_on_exit_intent),children:"Open on exit intent"})]}),l.open_on_exit_intent&&e.jsx("p",{className:"text-xs text-muted-foreground ml-14",children:"Opens the chat when the visitor moves their cursor toward the browser's close/tab area, signaling they may be leaving."}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ee,{checked:l.open_on_scroll_end,onCheckedChange:c=>r("open_on_scroll_end",c),"aria-label":"Open when reaching page end"}),e.jsx(y,{className:"cursor-pointer",onClick:()=>r("open_on_scroll_end",!l.open_on_scroll_end),children:"Open when reaching page end"})]}),l.open_on_scroll_end&&e.jsx("p",{className:"text-xs text-muted-foreground ml-14",children:"Opens the chat when the visitor scrolls to the bottom of the page â a great moment to engage after they've seen your content."}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ee,{checked:l.open_on_i
22dle,onCheckedChange:c=>r("open_on_idle",c),"aria-label":"Open after idle period"}),e.jsx(y,{className:"cursor-pointer",onClick:()=>r("open_on_idle",!l.open_on_idle),children:"Open after idle period"})]}),l.open_on_idle&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground ml-14",children:"Opens the chat when the visitor has been idle (no mouse movement, scroll, or keyboard) for the specified duration."}),e.jsxs("div",{className:"ml-14 space-y-1",children:[e.jsx(y,{className:"text-xs",children:"Idle timeout (seconds)"}),e.jsx(F,{type:"number",min:10,max:300,value:l.idle_timeout,onChange:c=>r("idle_timeout",parseInt(c.target.value)||60),className:"w-32"})]})]})]})]}),e.jsxs(V,{children:[e.jsx(G,{children:e.jsx(K,{className:"text-base",children:"AI Settings"})}),e.jsxs(q,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Reply delay (seconds)"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Minimum"}),e.jsx(F,{type:"number",min:1,max:30,value:l.reply_delay_min,onChange:c=>r("reply_delay_min",parseInt(c.target.value)||3)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Maximum"}),e.jsx(F,{type:"number",min:2,max:60,value:l.reply_delay_max,onChange:c=>r("reply_delay_max",parseInt(c.target.value)||8)})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Random delay before replying. Visitor sees "typing" indicator during this time.'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Max conversation messages"}),e.jsx(F,{type:"number",min:10,max:200,value:l.max_conversation_messages,onChange:c=>r("max_conversation_messages",parseInt(c.target.value)||50)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Messages included in AI history. Higher = better context, more tokens."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Rapid message coalesce (ms)"}),e.jsx(F,{type:"number",min:1e3,max:1e4,step:500,value:l.response_coalesce_ms,onChange:c=>r("response_coalesce_ms",parseInt(c.target.value)||3e3)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Wait before responding if visitor sends multiple messages quickly."})]})]})]})]})]}),e.jsx(A,{onClick:()=>u(l),disabled:g,className:"w-full",children:g?"Saving...":"Save Behavior Settings"})]})}const ns=[{value:"auto",label:"Auto (conversation start)"},{value:"always",label:"Always active (default)"},{value:"message_count",label:"After N visitor messages"},{value:"visitor_idle",label:"Visitor idle for N seconds"},{value:"keyword",label:"Keyword match"}],os={greeting:"bg-blue-500/10 text-blue-600 border-blue-500/20",auto_engage:"bg-amber-500/10 text-amber-600 border-amber-500/20",engagement:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",lead_capture:"bg-purple-500/10 text-purple-600 border-purple-500/20",coupon:"bg-orange-500/10 text-orange-600 border-orange-500/20",closing:"bg-cyan-500/10 text-cyan-600 border-cyan-500/20",custom:"bg-secondary text-muted-foreground border-border"};function Dt({webChat:t,onReload:u}){const[g,l]=n.useState([]),[s,r]=n.useState(!0),[p,S]=n.useState(null),[D,b]=n.useState(null),[c,C]=n.useState(null),[T,U]=n.useState(!1),[E,h]=n.useState(!1),[M,$]=n.useState(!1),[I,v]=n.useState(!1);n.useEffect(()=>{O()},[t.id]);const O=async()=>{try{r(!0);const a=await B.get(`/web-chats/${t.id}/phases`);l(Array.isArray(a)?a:[])}catch{w.error("Failed to load phases")}finally{r(!1)}},P=async()=>{try{const a=await B.post(`/web-chats/${t.id}/phases`,{name:"New Phase",phase_type:"custom",trigger_type:"message_count",trigger_value:{count:3},llm_instruction:"Answer the visitor helpfully.",is_active:!0,max_triggers:1});l(i=>[...i,a]),S(a.id),w.success("Phase added")}catch{w.error("Failed to add phase")}},H=async a=>{b(a.id);try{await B.put(`/web-chats/${t.id}/phases/${a.id}`,{name:a.name,trigger_type:a.trigger_type,trigger_value:a.trigger_value,llm_instruction:a.llm_instruction,quick_replies:a.quick_replies,max_triggers:a.max_triggers,is_active:a.is_active}),w.success("Phase saved")}catch{w.error("Failed to save phase")}finally{b(null)}},W=async a=>{const i={...a,is_active:!a.is_active};l(j=>j.map(z=>z.id===a.id?i:z)),b(a.id);try{await B.put(`/web-chats/${t.id}/phases/${a.id}`,{is_active:i.is_active})}catch{l(z=>z.map(Z=>Z.id===a.id?a:Z)),w.error("Failed to update")}finally{b(null)}},k=async()=>
22{if(c){U(!0);try{await B.delete(`/web-chats/${t.id}/phases/${c.id}`),l(a=>a.filter(i=>i.id!==c.id)),p===c.id&&S(null),w.success("Phase deleted")}catch{w.error("Failed to delete")}finally{U(!1),C(null)}}},m=async()=>{$(!0);try{const a=await B.post(`/web-chats/${t.id}/phases/reset`,{reset_pricing_playbook:I});l(Array.isArray(a)?a:[]),S(null),I&&(u==null||u()),w.success(I?"Phases and pricing playbook reset to defaults":"Phases reset to defaults")}catch{w.error("Failed to reset phases")}finally{$(!1),h(!1),v(!1)}},N=(a,i,j)=>{l(z=>z.map(Z=>Z.id===a?{...Z,[i]:j}:Z))};return s?e.jsx("div",{className:"py-12 text-center text-muted-foreground",children:"Loading phases..."}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Conversation Phases"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Define when and how the AI responds at each stage of the conversation."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(A,{size:"sm",variant:"outline",onClick:()=>h(!0),className:"gap-1.5 text-xs",children:[e.jsx(de,{className:"w-3.5 h-3.5"})," Reset"]}),e.jsxs(A,{size:"sm",onClick:P,className:"gap-1.5",children:[e.jsx(fs,{className:"w-4 h-4"})," Add Phase"]})]})]}),e.jsxs("div",{className:"space-y-3",children:[g.map((a,i)=>{var ie,re,se,ne;const j=p===a.id,z=os[a.phase_type]||os.custom,Z=((ie=ns.find(x=>x.value===a.trigger_type))==null?void 0:ie.label)||a.trigger_type;return e.jsxs("div",{className:L("rounded-xl border border-border bg-card transition-all",!a.is_active&&"opacity-50",j&&"ring-1 ring-primary/20"),children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 cursor-pointer hover:bg-secondary/30 transition-colors rounded-xl",onClick:()=>S(j?null:a.id),children:[e.jsx("span",{className:"text-muted-foreground/40 hidden sm:block",children:e.jsx(Xs,{className:"w-4 h-4"})}),e.jsx("span",{className:"text-xs font-mono text-muted-foreground/50 w-5 text-center hidden sm:block",children:i+1}),e.jsx("span",{className:L("text-[10px] font-semibold uppercase tracking-wide px-2 py-0.5 rounded-full border whitespace-nowrap",z),children:a.phase_type.replace("_"," ")}),e.jsx("span",{className:"text-sm font-medium text-foreground truncate flex-1 min-w-0",children:a.name}),e.jsx("span",{className:"text-xs text-muted-foreground hidden md:block whitespace-nowrap",children:Z}),a.max_triggers<9999&&e.jsxs("span",{className:"text-[10px] text-muted-foreground bg-secondary/50 px-1.5 py-0.5 rounded hidden sm:block",children:["max ",a.max_triggers,"x"]}),e.jsx(xe,{title:a.is_active?"Pause phase":"Enable phase",description:a.is_active?"Stop using this phase in conversations. You can re-enable it later.":"Make this phase active so the bot can use it in conversations.",children:e.jsx(A,{variant:a.is_active?"default":"secondary",size:"sm",className:"h-7 w-7 p-0 rounded-lg shrink-0",onClick:x=>{x.stopPropagation(),W(a)},"aria-label":a.is_active?"Pause":"Enable",children:a.is_active?e.jsx(et,{className:"w-3 h-3"}):e.jsx(ve,{className:"w-3 h-3"})})}),e.jsx("div",{className:"shrink-0 text-muted-foreground",children:j?e.jsx(st,{className:"w-4 h-4"}):e.jsx(tt,{className:"w-4 h-4"})})]}),j&&e.jsxs("div",{className:"px-4 pb-4 pt-2 border-t border-border space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(y,{className:"text-xs",children:"Phase Name"}),e.jsx(F,{value:a.name,onChange:x=>N(a.id,"name",x.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(y,{className:"text-xs",children:"Trigger Type"}),e.jsxs(pe,{value:a.trigger_type,onValueChange:x=>N(a.id,"trigger_type",x),children:[e.jsx(he,{children:e.jsx(ge,{})}),e.jsx(fe,{children:ns.map(x=>e.jsx(X,{value:x.value,children:x.label},x.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[a.trigger_type==="message_count"&&e.jsxs(e.Fragment,{children:[e.jsx(y,{className:"text-xs",children:"After N messages"}),e.jsx(F,{type:"number",min:1,value:((re=a.trigger_value)==null?void 0:re.count)||1,onChange:x=>N(a.id,"trigger_value",{count:parseInt(x.target.value)||1})})]}),a.trigger_type==="visitor_idle"&&e.jsxs(e.Fragment,{children:[e.jsx(y,{className:"text-xs",children:"Idle seconds"}),e.jsx(F,{type:"number",min:5,value:((se=a.trigger_value)==null?void 0:se.seconds)||15,onChange:x=>N(a.id,"trigger_value",{seconds:parseInt(x.target.value)||15})})]}
22),a.trigger_type==="keyword"&&e.jsxs(e.Fragment,{children:[e.jsx(y,{className:"text-xs",children:"Keywords (comma-separated)"}),e.jsx(F,{value:(((ne=a.trigger_value)==null?void 0:ne.keywords)||[]).join(", "),onChange:x=>N(a.id,"trigger_value",{keywords:x.target.value.split(",").map(Q=>Q.trim()).filter(Boolean)}),placeholder:"bye, thanks, thank you"})]}),(a.trigger_type==="auto"||a.trigger_type==="always")&&e.jsxs(e.Fragment,{children:[e.jsx(y,{className:"text-xs",children:"Max Triggers"}),e.jsx(F,{type:"number",min:1,max:9999,value:a.max_triggers,onChange:x=>N(a.id,"max_triggers",parseInt(x.target.value)||1)})]})]})]}),a.trigger_type!=="auto"&&a.trigger_type!=="always"&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(y,{className:"text-xs",children:"Max Triggers"}),e.jsx(F,{type:"number",min:1,max:9999,value:a.max_triggers,onChange:x=>N(a.id,"max_triggers",parseInt(x.target.value)||1)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(y,{className:"text-xs",children:"Quick Replies (comma-separated)"}),e.jsx(F,{value:(a.quick_replies||[]).join(", "),onChange:x=>N(a.id,"quick_replies",x.target.value?x.target.value.split(",").map(Q=>Q.trim()).filter(Boolean):null),placeholder:"Pricing, Features, Support"})]})]}),(a.trigger_type==="auto"||a.trigger_type==="always")&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(y,{className:"text-xs",children:"Quick Replies (comma-separated)"}),e.jsx(F,{value:(a.quick_replies||[]).join(", "),onChange:x=>N(a.id,"quick_replies",x.target.value?x.target.value.split(",").map(Q=>Q.trim()).filter(Boolean):null),placeholder:"Pricing, Features, Support"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(y,{className:"text-xs",children:"LLM Instruction"}),e.jsx("textarea",{value:a.llm_instruction,onChange:x=>N(a.id,"llm_instruction",x.target.value),maxLength:5e3,rows:4,className:"w-full rounded-xl border border-input bg-background px-4 py-3 text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/20 focus-visible:border-primary transition-all resize-y",placeholder:"Tell the LLM what to do in this phase..."}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Variables: ",e.jsx("code",{className:"text-primary/70",children:"{agent_name}"}),", ",e.jsx("code",{className:"text-primary/70",children:"{product_name}"}),", ",e.jsx("code",{className:"text-primary/70",children:"{coupon_code}"}),", ",e.jsx("code",{className:"text-primary/70",children:"{coupon_message}"})]})]}),e.jsxs("div",{className:"flex justify-between pt-2",children:[e.jsxs(A,{variant:"ghost",size:"sm",className:"text-destructive hover:bg-destructive/10 hover:text-destructive rounded-xl text-xs",onClick:()=>C(a),children:[e.jsx(Me,{className:"w-3.5 h-3.5 mr-1.5"})," Delete Phase"]}),e.jsx(A,{size:"sm",onClick:()=>H(a),disabled:D===a.id,className:"rounded-xl",children:D===a.id?"Saving...":"Save Changes"})]})]})]},a.id)}),g.length===0&&e.jsxs("div",{className:"py-12 text-center text-muted-foreground border border-dashed border-border rounded-xl",children:[e.jsx("p",{className:"text-sm",children:"No phases configured."}),e.jsx("p",{className:"text-xs mt-1",children:"Add a phase or reset to defaults to get started."})]})]}),e.jsx(Pe,{isOpen:!!c,isLoading:T,title:`Delete "${c==null?void 0:c.name}"?`,description:"This phase will be permanently removed. The bot will no longer use it in conversations.",confirmLabel:"Delete Phase",cancelLabel:"Cancel",variant:"destructive",onConfirm:k,onCancel:()=>C(null)}),e.jsx(Pe,{isOpen:E,isLoading:M,title:"Reset all phases to defaults?",description:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"This will delete all current phases and recreate the default ones (Greeting, Auto-Engage, Engagement, Closing). Any custom phases will be lost."}),e.jsxs("label",{className:"flex items-start gap-3 rounded-lg border border-border bg-background/60 p-3 text-left",children:[e.jsx(Js,{checked:I,onCheckedChange:a=>v(a===!0),disabled:M,className:"mt-0.5"}),e.jsxs("span",{className:"space-y-1",children:[e.jsx("span",{className:"block text-sm font-medium text-foreground",children:"Also reset Pricing & Playbook policy"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Use this if you want to restore the default coupon, trial, refund, and pricing guidance too."})]})]})]}),confirmLabel:"Reset to Defaults",cancelLabel:"Cancel",variant:"destructive",onConfirm:m,onCancel:()=>{h(!1),v(!1)}})]})}function $t({webChat:t,onUpdate:u,saving:g}){const[l,s]=n.useState({coupon_enabled:t.coupon_enabled||!1,coupon_code:t.coupon_code||"",coupon_message:t.coupon_message||"",coupon_delay_messages:t.coupon_delay_messages||7}),r=(p,S)=>s(D=>({...D,[p]:S}));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(V,{children:[e.jsx(G,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(K,{className:"text-base flex items-center gap-2",children:[e.jsx(Ne,{className:"w-5 h-5 text-amber-600"}),"Coupon Settings"]}),e.jsx(ee,{checked:l.coupon_enabled,onCheckedChange:p=>r("coupon_enabled",p),"aria-label":"Enable coupon"})]})}),e.jsxs(q,{className:L("space-y-4",!l.coupon_enabled&&"opacity-50 pointer-events-none"),children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Coupon Code"}),e.jsx(F,{value:l.coupon_code,onChange:p=>r("coupon_code",p.target.value),placeholder:"SAVE20"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Coupon Message"}),e.jsx(F,{value:l.coupon_message,onChange:p=>r("coupon_message",p.target.value),placeholder:"Get 20% off your first purchase!"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The AI will naturally offer this coupon when the visitor shows purchase intent or asks about pricing. You don't need to configure when â the AI decides the best moment."})]})]}),e.jsx("div",{className:"lg:sticky lg:top-6 self-start",children:e.jsxs(V,{children:[e.jsx(G,{children:e.jsx(K,{className:"text-base",children:"Preview"})}),e.jsx(q,{children:l.coupon_enabled&&l.coupon_code?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-4 rounded-xl bg-amber-500/10 border border-amber-500/20",children:[e.jsx("p",{className:"text-xs font-bold text-amber-600 uppercase tracking-wider mb-2",children:"How visitors will see it"}),e.jsxs("div",{className:"bg-card rounded-xl p-4 border border-border",children:[e.jsx("p",{className:"text-sm text-foreground mb-3",children:l.coupon_message||"Here's a special offer for you!"}),e.jsxs("div",{className:"flex items-center justify-between bg-secondary rounded-lg p-3",children:[e.jsx("span",{className:"font-mono font-bold text-lg text-primary",children:l.coupon_code}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Click to copy"})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-xl p-4 space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold text-foreground",children:"How it works:"}),e.jsxs("ul",{className:"text-xs text-muted-foreground space-y-1.5",children:[e.jsx("li",{children:"The AI offers the coupon when the moment feels natural"}),e.jsx("li",{children:"Good moments: pricing questions, purchase intent, hesitation"}),e.jsx("li",{children:"The coupon is offered only once per conversation"}),e.jsx("li",{children:"If the visitor asks about it again, the AI will remind them"})]})]})]}):e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Ne,{className:"w-10 h-10 mx-auto mb-3 text-muted-foreground
22/20"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.coupon_enabled?"Enter a coupon code to see the preview":"Enable the coupon to configure it"})]})})]})})]}),e.jsx(A,{onClick:()=>u(l),disabled:g,className:"w-full",children:g?"Saving...":"Save Coupon Settings"})]})}function Mt({webChat:t,onUpdate:u,saving:g}){const[l,s]=n.useState(t.system_prompt||""),[r,p]=n.useState(t.pricing_playbook||""),[S,D]=n.useState(null),[b,c]=n.useState(null),C=n.useCallback(async()=>{try{const h=await B.get("/web-chats/default-prompt");D(h.prompt),c(h.pricing_playbook),t.system_prompt||s(h.prompt),t.pricing_playbook||p(h.pricing_playbook)}catch{w.error("Failed to load default prompt")}},[t.pricing_playbook,t.system_prompt]);n.useEffect(()=>{C()},[C]),n.useEffect(()=>{t.system_prompt?s(t.system_prompt):S&&s(S)},[S,t.system_prompt]),n.useEffect(()=>{t.pricing_playbook?p(t.pricing_playbook):b&&p(b)},[b,t.pricing_playbook]);const T=()=>{S&&(s(S),w.info("Reset to default template"))},U=()=>{b&&(p(b),w.info("Reset pricing playbook to default. Click Save Pricing & Playbook to apply it."))},E=[{var:"{agent_name}",desc:"The agent name configured for this chat"},{var:"{product_name}",desc:"The assigned product name"},{var:"{support_url}",desc:"The product support ticket URL"},{var:"{current_page_url}",desc:"The page URL the visitor is on"},{var:"{visit_count}",desc:"How many times this visitor has visited"},{var:"{message_count}",desc:"Messages exchanged so far"},{var:"{visitor_name}",desc:"The visitor's name (if collected)"},{var:"{visitor_email}",desc:"The visitor's email (if collected)"},{var:"{coupon_delivered}",desc:"Whether the coupon was already shared"},{var:"{ticketing_policy}",desc:"Injected ticket escalation policy for this chat"},{var:"{pricing_playbook}",desc:"Editable pricing and coupon timing policy"},{var:"{phase_instruction}",desc:"Injected automatically from the active phase"},{var:"{selected_ai_context}",desc:"The selected product AI context"},{var:"{coupon_code}",desc:"The coupon code (if configured)"},{var:"{coupon_message}",desc:"The coupon message (if configured)"},{var:"{conversation_started_at}",desc:"How long ago the conversation started"}];return e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsxs(V,{children:[e.jsx(G,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(K,{className:"text-base",children:"System Prompt Template"}),e.jsxs(A,{variant:"outline",size:"sm",onClick:T,className:"gap-1 text-xs",children:[e.jsx(de,{className:"w-3.5 h-3.5"})," Reset to Default"]})]})}),e.jsxs(q,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Master instruction sent to the AI for every message."}),e.jsxs("div",{className:"relative",children:[e.jsx("textarea",{value:l,onChange:h=>s(h.target.value),maxLength:1e4,className:"w-full min-h-[500px] rounded-xl border border-input bg-background px-4 py-3 text-sm font-mono text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/20 focus-visible:border-primary transition-all resize-y"}),e.jsxs("span",{className:L("absolute bottom-2 right-2 text-[10px]",l.length>1e4?"text-destructive":"text-muted-foreground"),children:[l.length.toLocaleString()," / 10,000"]})]}),e.jsx(Qe,{currentText:l,onApply:h=>s(h),label:"Refine with AI"}),e.jsx(A,{onClick:()=>u({system_prompt:l}),disabled:g,className:"w-full",children:g?"Saving...":"Save System Prompt"})]})]}),e.jsxs(V,{children:[e.jsx(G,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(K,{className:"text-base",children:"Pricing & Playbook Policy"}),e.jsxs(A,{variant:"outline",size:"sm",onClick:U,className:"gap-1 text-xs",children:[e.jsx(de,{className:"w-3.5 h-3.5"})," Reset to Default"]})]})}),e.jsxs(q,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Coupon timing, trial replies, refund reassurance, and pricing guidance. This is injected into every Web Chat prompt and should be the single source of truth for pricing behavior."}),e.jsxs("div",{className:"relative",children:[e.jsx("textarea",{value:r,onChange:h=>p(h.target.value),maxLength:1e4,className:"w-full min-h-[360px] rounded-xl border border-input bg-background px-4 py-3 text-sm font-mono text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/20 focus-visible:border-primary transition-all resize-y"}),e.jsxs("span",{className:L("absolute bottom-2 right-2 text-[10px]",r.length>1e4?"text-destructive":"text-muted-foreground"),children:[r.length.toLocaleStr
22ing()," / 10,000"]})]}),e.jsx(Qe,{currentText:r,onApply:h=>p(h),label:"Refine Policy with AI"}),e.jsx(A,{onClick:()=>u({pricing_playbook:r.trim()||null}),disabled:g,className:"w-full",children:g?"Saving...":"Save Pricing & Playbook"})]})]})]}),e.jsx("div",{className:"lg:sticky lg:top-6 self-start",children:e.jsxs(V,{children:[e.jsx(G,{children:e.jsx(K,{className:"text-base",children:"Available Variables"})}),e.jsx(q,{children:e.jsx("div",{className:"space-y-2",children:E.map(h=>e.jsxs("div",{className:"flex flex-col gap-0.5 p-2 rounded-lg bg-secondary/50",children:[e.jsx("code",{className:"text-xs font-mono text-primary bg-primary/10 px-1.5 py-0.5 rounded w-fit",children:h.var}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:h.desc})]},h.var))})})]})})]})})}async function Rt(t,u){var D,b;if(!t||!u)return{ok:!1,reason:"missing_id"};const g=localStorage.getItem("auth_token")||"",l=await fetch(`${Es}/web-chats/${t}/conversations/${u}/debug-markdown`,{headers:{Accept:"text/markdown",...g?{Authorization:`Bearer ${g}`}:{}}});if(!l.ok)return{ok:!1,reason:"http_error",status:l.status};const s=((b=(D=l.headers)==null?void 0:D.get)==null?void 0:b.call(D,"content-type"))||"",r=await l.text(),p=r.trimStart().toLowerCase();return s.includes("text/html")||p.startsWith("<!doctype html")||p.startsWith("<html")?{ok:!1,reason:"html_response"}:await ot(r)?{ok:!0}:{ok:!1,reason:"clipboard"}}J.extend(us);function Lt(t){if(!t)return"";const u=J(t),g=J().format("YYYY-MM-DD");return u.format("YYYY-MM-DD")===g?u.format("h:mm A"):u.format("MMM D · h:mm A")}function te(t){return t?J(t).format("MMM D, YYYY h:mm A"):""}function is(t){switch(t){case"coupon":return"Coupon";case"quick_reply":return"Quick reply";case"system":return"System";case"typing":return"Typing";default:return null}}function Ft({webChat:t}){var Ue,ze,Ve,Ye,qe,He,Ge;const{user:u}=Ws(),[g,l]=n.useState([]),[s,r]=n.useState(null),[p,S]=n.useState(null),[D,b]=n.useState(!1),[c,C]=n.useState(!0),[T,U]=n.useState(""),[E,h]=n.useState(!1),[M,$]=n.useState([]),[I,v]=n.useState("all"),[O,P]=n.useState(!1),[H,W]=n.useState(!1),[k,m]=n.useState(""),[N,a]=n.useState(""),[i,j]=n.useState(""),[z,Z]=n.useState(""),[ie,re]=n.useState(!1),[se,ne]=n.useState(!1),[x,Q]=n.useState(!1),[oe,_e]=n.useState(!1),[we,Le]=n.useState(null),be=n.useRef(0),ke=n.useRef(null),je=((Ue=t.agent_name)==null?void 0:Ue.trim())||"Assistant",Se={visitor:{label:"Manual",color:"bg-slate-500/10 text-slate-600 dark:text-slate-400 border-slate-500/20",icon:pt},auto_open:{label:"Auto-open",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20",icon:dt},exit_intent:{label:"Exit intent",color:"bg-rose-500/10 text-rose-600 dar
22k:text-rose-400 border-rose-500/20",icon:xt},scroll_end:{label:"Page end",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20",icon:wt},idle_timeout:{label:"Idle",color:"bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/20",icon:ut}};n.useEffect(()=>()=>{var o;(o=ke.current)==null||o.abort()},[t.id]),n.useEffect(()=>{if(!(t!=null&&t.id))return;const o=at("web_chat",{webChatId:t.id});B.get("/saved-replies",{params:o}).then(f=>{var _;const d=f.replies||((_=f.data)==null?void 0:_.replies)||f.data||[];$(Array.isArray(d)?d:[])}).catch(()=>$([]))},[t==null?void 0:t.id]),n.useEffect(()=>{const o=setTimeout(()=>a(k.trim()),400);return()=>clearTimeout(o)},[k]);const ws=()=>{var f;if(!((f=s==null?void 0:s.messages)!=null&&f.length))return;const o=s.messages.map(d=>{const _=d.sender_type==="visitor"?"Visitor":d.sender_type==="bot"?`${je} (AI)`:d.sender_type==="agent"?"Agent":"System",R=te(d.created_at),Y=d.message_type&&d.message_type!=="text"?` [${is(d.message_type)||d.message_type}]`:"";return`[${R}] [${_}]${Y}: ${d.content}`}).join(` 23 24`);navigator.clipboard.writeText(o).catch(()=>{}),re(!0),w.success("Conversation copied to clipboard"),setTimeout(()=>re(!1),2e3)},ks=async()=>{if(!(!(s!=null&&s.id)||se)){ne(!0);try{const o=await Rt(t.id,s.id);o.ok?w.success("Debug markdown copied to clipboard"):o.reason==="html_response"?w.error("Debug export returned the app shell instead of markdown. Please refresh and try again."):o.reason==="clipboard"?w.error("Clipboard write failed."):w.error("Could not copy debug markdown.")}catch(o){w.error((o==null?void 0:o.message)||"Could not copy debug markdown.")}finally{ne(!1)}}},Ss=async()=>{Q(!0);try{await B.delete(`/web-chats/${t.id}/conversations`),l([]),r(null),S(null),_e(!1),w.success("All conversations archived â analytics data preserved")}catch(o){w.error(o.message||"Failed to archive conversations")}finally{Q(!1)}};n.useEffect(()=>{const o={};I!=="all"&&(o.status=I),O&&(o.has_visitor_reply="1"),H&&(o.coupon_shown="1"),N&&(o.search=N),i&&(o.date_from=i),z&&(o.date_to=z);let f=!1;return(async()=>{try{C(!0);const d=await B.get(`/web-chats/${t.id}/conversations`,{params:o});if(!f){const _=Array.isArray(d)?d:Array.isArray(d==null?void 0:d.data)?d.data:[];l(_)}}catch(d){f||w.error(d.message||"Failed to load conversations")}finally{f||C(!1)}})(),()=>{f=!0}},[t.id,I,O,H,N,i,z]);const Fe=n.useRef(p);n.useEffect(()=>{Fe.current=p},[p]);const Cs=n.useMemo(()=>{const o=t==null?void 0:t.id;return{".new-conversation":()=>{(async()=>{try{const f=await B.get(`/web-chats/${o}/conversations`),d=Array.isArray(f)?f:Array.isArray(f==null?void 0:f.data)?f.data:[];l(d)}catch{}})()},".new-message":f=>{!f||!f.conversationId||(l(d=>d.map(_=>_.id===f.conversationId?{..._,updated_at:new Date().toISOString(),messages_count:(_.messages_count||0)+1}:_)),Fe.current===f.conversationId&&B.get(`/web-chats/${o}/conversations/${f.conversationId}`).then(d=>r(d)).catch(()=>{}))}}},[t==null?void 0:t.id]),Ee=(u==null?void 0:u.workspace_owner_id)||(u==null?void 0:u.id);Os(Ee?`webchat.${Ee}`:null,Cs,[t==null?void 0:t.id]);const We=async o=>{var _,R;(_=ke.current)==null||_.abort();const f=new AbortController;ke.current=f;const d=++be.current;S(o),b(!0),r(Y=>Y&&Y.id!==o?null:Y);try{const Y=await B.get(`/web-chats/${t.id}/conversations/${o}`,{signal:f.signal});if(be.current!==d)return;r(Y)}catch(Y){if((Y==null?void 0:Y.name)==="AbortError"||((R=Y==null?void 0:Y.cause)==null?void 0:R.name)==="AbortError"||be.current!==d)return;w.error("Failed to load conversation"),r(null)}finally{be.current===d&&b(!1)}},Oe=async()=>{if(!T.trim()||!s)return;const o=T.trim();h(!0),U("");const f={id:"temp_"+Date.now(),sender_type:"agent",content:o,message_type:"text",created_at:new Date().toISOString()};r(d=>d&&{...d,messages:[...d.messages||[],f]});try{const d=await B.post(`/web-chats/${t.id}/conversations/${s.id}/message`,{content:o});r(_=>{if(!_)return _;const R=(_.messages||[]).filter(Y=>Y.id!==f.id);return{..._,messages:[...R,d],is_bot:!1}}),l(_=>_.map(R=>R.id===s.id?{...R,messages_count:(R.messages_count||0)+1}:R))}catch{r(_=>_&&{..._,messages:(_.messages||[]).filter(R=>R.id!==f.id)}),U(o),w.error("Failed to send")}finally{h(!1)}},As=async o=>{try{await B.post(`/web-chats/${t.id}/conversations/${o}/resolve`),l(f=>f.map(d=>d.id===o?{...d,status:"resolved"}:d)),(s==null?void 0:s.id)===o&&r(f=>f&&{...f,status:"resolved",resolved_at:new Date().toISOString()}),w.success("Conversation resolved")}catch{w.error("Failed to resolve")}},me=s==null?void 0:s.current_page_url,Ce=n.useMemo(()=>
24{if(!me)return null;try{const o=new URL(me);return{href:me,label:o.hostname+(o.pathname==="/"?"":o.pathname)}}catch{return{href:me,label:me.slice(0,80)}}},[me]),Ts=n.useMemo(()=>t!=null&&t.product?[t.product]:[],[t==null?void 0:t.product]),le=n.useMemo(()=>!(s!=null&&s.messages)||we===null?null:s.messages.find(o=>String(o.id)===String(we))||null,[s==null?void 0:s.messages,we]),Be=n.useMemo(()=>{var d,_;if(!le)return null;const f=(Array.isArray((d=t==null?void 0:t.product)==null?void 0:d.contexts)?t.product.contexts:[]).map(R=>({context_id:Number(R.id),context_name:R.name,product_id:Number(t.product.id),product_name:t.product.name})).filter(R=>Number.isFinite(R.context_id));return{role:"assistant",body:le.content||"",debug:((_=le.metadata)==null?void 0:_.webchat_ai_debug)||{candidate_pool:f,selector:{}}}},[le,t==null?void 0:t.product]),Ps=n.useMemo(()=>{const o=(s==null?void 0:s.messages)||[],f=le?o.findIndex(_=>String(_.id)===String(le.id)):-1;return(f>=0?o.slice(0,f+1):o).map(_=>{const R=_.sender_type==="visitor"?"customer":_.sender_type==="bot"?"assistant":_.sender_type==="agent"?"agent":null;return R?{role:R,body:_.content||""}:null}).filter(Boolean)},[s==null?void 0:s.messages,le]),Is=n.useMemo(()=>{const o=(s==null?void 0:s.messages)||[],f=[];return o.forEach((d,_)=>{const R=o[_-1],Y=d.created_at?J(d.created_at).format("YYYY-MM-DD"):"",Ke=R!=null&&R.created_at?J(R.created_at).format("YYYY-MM-DD"):"";(_===0||Y!==Ke)&&f.push(e.jsx("div",{className:"flex justify-center py-3",children:e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground bg-muted/80 px-3 py-1.5 rounded-full border border-border/60 shadow-sm",children:d.created_at?J(d.created_at).format("dddd, MMMM D, YYYY"):"Unknown date"})},`day-${d.id}-${Y}`));const Ze=is(d.message_type),ue=d.sender_type==="visitor",Ds=d.sender_type==="system"||d.message_type==="system";f.push(e.jsxs("div",{className:L("flex gap-2",ue?"justify-end":"justify-start"),children:[!ue&&e.jsx(xe,{title:d.sender_type==="bot"?je:d.sender_type==="agent"?"Team member":"System",description:d.sender_type==="bot"?"This reply was generated by your AI assistant.":d.sender_type==="agent"?"This reply was sent by a teammate.":"Automated system event.",children:e.jsx("div",{className:L("w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 text-[10px] font-bold border border-border/60 cursor-help",d.sender_type==="bot"?"bg-primary/10 text-primary":d.sender_type==="agent"?"bg-emerald-500/10 text-emerald-700 dark:text-emerald-400":"bg-secondary text-muted-foreground"),children:d.sender_type==="bot"?e.jsx(Ie,{className:"w-4 h-4"}):d.sender_type==="agent"?e.jsx(St,{className:"w-4 h-4"}):"S"})}),e.jsxs("div",{className:L("flex max-w-[min(100%,28rem)] flex-col gap-0.5",ue?"items-end":"items-start"),children:[e.jsxs("div",{className:"flex items-center gap-2 px-0.5 min-h-[14px]",children:[!ue&&e.jsx("span",{className:"text-[10px] font-medium text-muted-foreground",children:d.sender_type==="bot"?je:d.sender_type==="agent"?"Agent":"System"}),ue&&e.jsx("span",{className:"text-[10px] font-medium text-muted-foreground",children:"Visitor"}),e.jsx(xe,{title:"Sent",description:te(d.created_at),children:e.jsx("time",{className:"text-[10px] tabular-nums text-muted-foreground cursor-help",dateTime:d.created_at||void 0,children:Lt(d.created_at)})}),Ze&&e.jsx("span",{className:"text-[9px] uppercase tracking-wide px-1.5 py-0 rounded bg-muted text-muted-foreground font-semibold",children:Ze})]}),d.sender_type==="bot"&&e.jsxs(A,{type:"button",variant:"ghost",size:"sm",onClick:()=>Le(d.id),className:"h-7 rounded-lg px-2 text-[11px] text-primary hover:text-primary",children:[e.jsx(js,{className:"w-3 h-3 mr-1"}),"Improve this reply"]}),e.jsxs("div",{className:L("rounded-2xl px-3.5 py-2.5 text-sm shadow-sm border",ue?"bg-primary text-primary-foreground border-primary/20 rounded-tr-md":Ds?"bg-muted/50 text-muted-foreground text-xs italic w-full text-center border-dashed max-w-md":d.message_type==="coupon"?"bg-amber-500/15 text-amber-950 dark:text-amber-100 border-amber-500/30 rounded-tl-md":"bg-card text-foreground border-border rounded-tl-md"),children:[e.jsx("p",{className:"whitespace-pre-wrap break-words",children:d.content}),d.feedback&&e.jsx("span",{className:"mt-1 inline-flex",children:d.feedback==="thumbs_up"?e.jsx(it,{className:"w-3.5 h-3.5 text-emerald-600","aria-label":"Thumbs up"}):e.jsx(lt,{className:"w-3.5 h-3.5 text-red-500","aria-label":"Thumbs down"})})]})]})]},d.id))}),f},[s==null?void 0:s.messages,je]);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-12 gap-4 min-h-[min(72vh,760px)] lg:min-h-[620px]",children:[e.jsxs(V,{className:"lg:col-span-4 flex flex-col min-h-0 border-border/80 shadow-sm",children:[e.jsxs(G,{className:"pb-3 space-y-3 shrink-0 border-b border-border/60 bg-muted/20",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(K,{className:"text-base font-semibold",children:"Inbox"}),e.jsxs(A,{type:"button",variant:"destructive",size:"sm",className:"h-8 text-xs",disabled:x||c,onClick:()=>_e(!0),children:[e.jsx(Me,{className:"w-3.5 h-3.5 mr-1"}),"Archive all"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{className:"text-xs text-muted-foreground",children:"Status"}),e.jsxs(pe,{value:I,onValueChange:v,children:[e.jsx(he,{className:"h-9 text-xs bg-background",children:e.jsx(ge,{})}),e.jsxs(fe,{children:[e.jsx(X,{value:"all",children:"All"}),e.jsx(X,{value:"active",children:"Active"}),e.jsx(X,{value:"resolved",children:"Resolved"})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>P(o=>!o),className:L("flex items-center justify-between rounded-lg border px-3 py-2 text-xs transition-colors",O?"border-primary bg-primary/5":"border-border hover:bg-secondary/50"),children:[e.jsx("span",{className:"font-medium",children:"Has user reply"}),e.jsx("span",{className:L("text-[10px] uppercase",O?"text-primary":"text-muted-foreground"),children:O?"On":"Off"})]}),e.jsxs("button",{type:"button",onClick:()=>W(o=>!o),className:L("flex items-center justify-between rounded-lg border px-3 py-2 text-xs transition-colors",H?"border-primary bg-primary/5":"border-border hover:bg-secondary/50"),children:[e.jsx("span",{className:"font-medium",children:"Coupon shown"}),e.jsx("span",{className:L("text-[10px] uppercase",H?"text-primary":"text-muted-foreground"),children:H?"On":"Off"})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(y,{className:"text-xs text-muted-foreground",children:"Search visitor"}),e.jsx(F,{className:"h-9 text-xs bg-background",placeholder:"Name or emailâ¦",value:k,onChange:o=>m(o.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(y,{className:"text-xs text-muted-foreground",children:"From"}),e.jsx(F,{type:"date",className:"h-9 text-xs bg-background",value:i,onChange:o=>j(o.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(y,{className:"text-xs text-muted-foreground",children:"To"}),e.jsx(F,{type:"date",className:"h-9 text-xs bg-background",value:z,onChange:o=>Z(o.target.value)})]})]})]}),e.jsx(q,{className:"p-0 flex-1 min-h-0 flex flex-col",children:e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto divide-y divide-border",children:c?e.jsx("p",{className:"text-center text-sm text-muted-foreground py-10",children:"Loadingâ¦"}):g.length===0?e.jsx("p",{className:"text-center text-sm text-muted-foreground py-10 px-4",children:"No conversations match these filters."}):g.map(o=>{var f,d,_;return e.jsx("button",{type:"button",onClick:()=>We(o.id),className:L("w-full text-left p-3.5 hover:bg-secondary/40 transition-colors",p===o.id&&"bg-primary/[0.07] ring-inset ring-1 ring-primary/15"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-full bg-secondary flex items-center justify-center flex-shrink-0 border border-border/50",children:e.jsx(ct,{className:"w-4 h-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:((f=o.visitor)==null?void 0:f.name)||((d=o.visitor)==null?void 0:d.email)||"Anonymous"}),o.device_type==="mobile"&&e.jsx(Je,{className:"w-3.5 h-3.5 text-muted-foreground shrink-0","aria-label":"Mobile"}),o.device_type==="tablet"&&e.jsx(Xe,{className:"w-3.5 h-3.5 text-muted-foreground shrink-0","aria-label":"Tablet"}),o.device_type==="desktop"&&e.jsx(es,{className:"w-3.5 h-3.5 text-muted-foreground shrink-0","aria-label":"Desktop"}),o.coupon_delivered&&e.jsx(Ne,{className:"w-3.5 h-3.5 text-amber-600 shrink-0","aria-label":"Coupon delivered"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 flex-wrap",children:[(()=>{const R=Se[o.initiated_by]||Se.visitor,Y=R.icon;return e.jsxs("span",{className:L("inline-flex items-center gap-1 text-[9px] font-semibold px-1.5 py-0.5 rounded border",R.color),children:[e.jsx(Y,{className:"w-2.5 h-2.5"}),R.label]})})(),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[o.messages_count??0," msgs",(_=o.visitor)!=null&&_.phone?` · ${o.visitor.phone}`:""]})]}
24),e.jsxs("p",{className:"text-[10px] text-muted-foreground/90 mt-1 flex flex-wrap items-center gap-x-1 gap-y-0.5 tabular-nums",children:[e.jsx(ht,{className:"w-3 h-3 shrink-0","aria-hidden":!0}),e.jsxs("span",{"aria-label":o.updated_at?`Updated ${te(o.updated_at)}`:void 0,children:[e.jsx("span",{className:"text-muted-foreground/80",children:"Updated "}),o.updated_at?J(o.updated_at).fromNow():"â"]}),e.jsx("span",{className:"text-muted-foreground/50","aria-hidden":!0,children:"·"}),e.jsxs("span",{"aria-label":o.created_at?`Started ${te(o.created_at)}`:void 0,children:[e.jsx("span",{className:"text-muted-foreground/80",children:"Started "}),o.created_at?te(o.created_at):"â"]})]})]}),e.jsx("span",{className:L("text-[9px] font-semibold uppercase px-2 py-0.5 rounded-md shrink-0",o.status==="active"?"bg-emerald-500/15 text-emerald-700 dark:text-emerald-400":"bg-muted text-muted-foreground"),children:o.status})]})},o.id)})})})]}),e.jsx(V,{className:"lg:col-span-8 flex flex-col min-h-0 border-border/80 shadow-sm overflow-hidden",children:D&&!s?e.jsx("div",{className:"flex-1 flex items-center justify-center text-muted-foreground min-h-[320px]",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ye,{className:"w-8 h-8 mx-auto mb-3 animate-spin opacity-40"}),e.jsx("p",{className:"text-sm",children:"Loading conversationâ¦"})]})}):s?e.jsxs(e.Fragment,{children:[e.jsxs(G,{className:"pb-3 border-b border-border shrink-0 space-y-3 bg-muted/15",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(K,{className:"text-base font-semibold truncate",children:((ze=s.visitor)==null?void 0:ze.name)||"Anonymous"}),e.jsx("span",{className:L("text-[10px] font-bold uppercase px-2 py-0.5 rounded-md",s.status==="active"?"bg-emerald-500/15 text-emerald-700 dark:text-emerald-400":"bg-muted text-muted-foreground"),children:s.status})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[((Ve=s.visitor)==null?void 0:Ve.email)&&e.jsx(xe,{title:"Visitor email",description:s.visitor.email,children:e.jsx("span",{className:"truncate max-w-full cursor-help",children:s.visitor.email})}),((Ye=s.visitor)==null?void 0:Ye.phone)&&e.jsx("span",{className:"tabular-nums",children:s.visitor.phone}),((qe=s.visitor)==null?void 0:qe.visit_count)!=null&&e.jsxs("span",{children:[s.visitor.visit_count," visits"]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[e.jsx(A,{size:"sm",variant:"outline",onClick:ws,className:"gap-1.5 text-xs h-8",children:ie?e.jsxs(e.Fragment,{children:[e.jsx(ys,{className:"w-3.5 h-3.5"})," Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"w-3.5 h-3.5"})," Copy transcript"]})}),e.jsxs(A,{size:"sm",variant:"outline",onClick:ks,disabled:se,className:"gap-1.5 text-xs h-8",children:[se?e.jsx(ye,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(De,{className:"w-3.5 h-3.5"}),"Copy markdown"]}),s.status==="active"&&e.jsxs(A,{size:"sm",variant:"outline",onClick:()=>As(s.id),className:"h-8 text-xs",children:[e.jsx(gt,{className:"w-3.5 h-3.5 mr-1"}),"Resolve"]})]})]}),e.jsxs("dl",{className:"grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-2 text-[11px] rounded-xl border border-border/60 bg-background/80 p-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-muted-foreground shrink-0 w-24",children:"Conversation"}),e.jsxs("dd",{className:"font-mono text-foreground tabular-nums",children:["#",s.id]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-muted-foreground shrink-0 w-24",children:"Widget"}),e.jsx("dd",{className:"truncate",children:e.jsx(xe,{title:"Widget",description:t.name,children:e.jsx("span",{className:"cursor-help",children:t.name})})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-muted-foreground shrink-0 w-24",children:"Started"}),e.jsx("dd",{children:te(s.started_at||s.created_at)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-muted-foreground shrink-0 w-24",children:"Last activity"}),e.jsx("dd",{"aria-label":s.updated_at?te(s.updated_at):void 0,children:s.updated_at?e.jsxs(e.Fragment,{children:[J(s.updated_at).fromNow(),e.jsxs("span",{className:"text-muted-foreground
24/70 ml-1",children:["(",te(s.updated_at),")"]})]}):"â"})]}),s.resolved_at&&e.jsxs("div",{className:"flex gap-2 sm:col-span-2",children:[e.jsx("dt",{className:"text-muted-foreground shrink-0 w-24",children:"Resolved"}),e.jsx("dd",{children:te(s.resolved_at)})]}),Ce&&e.jsxs("div",{className:"flex gap-2 sm:col-span-2 items-start",children:[e.jsx("dt",{className:"text-muted-foreground shrink-0 w-24 pt-0.5",children:"Page"}),e.jsxs("dd",{className:"min-w-0 flex items-start gap-1.5",children:[e.jsx(vs,{className:"w-3.5 h-3.5 text-muted-foreground mt-0.5 shrink-0","aria-hidden":!0}),e.jsx("a",{href:Ce.href,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline break-all line-clamp-2",children:Ce.label})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-muted-foreground shrink-0 w-24",children:"Lead captured"}),e.jsx("dd",{children:s.lead_captured?"Yes":"No"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-muted-foreground shrink-0 w-24",children:"Coupon"}),e.jsx("dd",{className:"flex items-center gap-1",children:s.coupon_delivered?e.jsxs(e.Fragment,{children:[e.jsx(Ne,{className:"w-3.5 h-3.5 text-amber-600","aria-hidden":!0}),"Delivered"]}):"Not shown"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-muted-foreground shrink-0 w-24",children:"Routing"}),e.jsx("dd",{children:s.is_bot?"AI / bot":"Human agent"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-muted-foreground shrink-0 w-24",children:"Device"}),e.jsxs("dd",{className:"flex items-center gap-1.5",children:[s.device_type==="mobile"&&e.jsx(Je,{className:"w-3.5 h-3.5"}),s.device_type==="tablet"&&e.jsx(Xe,{className:"w-3.5 h-3.5"}),s.device_type==="desktop"&&e.jsx(es,{className:"w-3.5 h-3.5"}),s.device_type?s.device_type.charAt(0).toUpperCase()+s.device_type.slice(1):"Unknown"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-muted-foreground shrink-0 w-24",children:"Initiated by"}),e.jsx("dd",{className:"flex items-center gap-1.5",children:(()=>{const o=Se[s.initiated_by]||{label:s.initiated_by||"Unknown",color:"bg-muted text-muted-foreground border-border",icon:ce},f=o.icon;return e.jsxs("span",{className:L("inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded border",o.color),children:[e.jsx(f,{className:"w-3 h-3"}),o.label]})})()})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-muted-foreground shrink-0 w-24",children:"Messages"}),e.jsxs("dd",{children:[s.message_count??(((He=s.messages)==null?void 0:He.length)||0)," total",s.visitor_message_count!=null&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",s.visitor_message_count," from visitor"]})]})]})]})]}),e.jsx(q,{className:"flex-1 min-h-0 overflow-y-auto p-4 sm:p-5 space-y-1 bg-gradient-to-b from-muted/20 to-background",children:Is}),s.status==="active"&&e.jsxs("div",{className:"p-3 sm:p-4 border-t border-border shrink-0 bg-card space-y-2",children:[M.length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:M.slice(0,8).map(o=>e.jsx("button",{type:"button",className:"text-xs px-2.5 py-1 rounded-full bg-violet-500/10 text-violet-700 dark:text-violet-300 border border-violet-500/20 hover:bg-violet-500/20",onClick:()=>{U(rt(o)),B.post(`/saved-replies/${o.id}/use`).catch(()=>{})},children:o.title},o.id))}):null,e.jsxs("div",{className:"flex gap-2",children:[e.jsx(F,{value:T,onChange:o=>U(o.target.value),placeholder:`Reply as agent to ${((Ge=s.visitor)==null?void 0:Ge.name)||"visitor"}â¦`,onKeyDown:o=>o.key==="Enter"&&!o.shiftKey&&Oe(),disabled:E,className:"rounded-xl"}),e.jsx(A,{onClick:Oe,disabled:E||!T.trim(),size:"icon",className:"rounded-xl shrink-0",children:e.jsx(Ns,{className:"w-4 h-4"})})]})]})]}):p?e.jsx("div",{className:"flex-1 flex items-center justify-center text-muted-foreground min-h-[320px] px-4",children:e.jsxs("div",{className:"text-center max-w-sm space-y-3",children:[e.jsx("p",{className:"text-sm text-foreground font-medium",children:"Couldn't load this conversation"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Check your connection and try again."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-1",onClick:()=>We(p),children:"Try again"})]})}):e.jsx("div",{className:"flex-1 flex items-center justify-center text-muted-foreground text-sm min-h-[320px]",children:e.jsxs("div",{className:"text-center px-6 max-w-sm",children:[e.jsx(ce,{className:"w-12 h-12 mx-auto mb-4 opacity-15"}),e.jsx("p",{className:"font-medium text-foreground",children:"Select a conversation"}),e.jsx("p",{className:"mt-2 text-muted-foreground text-xs leading-relaxed",children:"Choose a thread on the left to read the full transcript with timestamps, page context, and resolution tools."})]})})})]}
24),e.jsx(Pe,{isOpen:oe,title:"Archive all conversations?",description:"Conversations will be hidden from the inbox but kept for analytics. They will be permanently deleted after the retention period set in your settings.",confirmLabel:"Archive all",cancelLabel:"Cancel",variant:"destructive",requireConfirmText:"ARCHIVE",isLoading:x,onConfirm:Ss,onCancel:()=>{x||_e(!1)}}),e.jsx(bs,{open:!!Be,onClose:()=>Le(null),endpointBase:`/web-chats/${t.id}/ai-tester`,contextProducts:Ts,turn:Be,fullTranscript:Ps,onApplied:()=>w.success("Product AI context updated")})]})}function Et({webChat:t}){return e.jsx(mt,{webChatId:t.id})}function Wt({webChat:t,onUpdate:u,saving:g}){const[l,s]=n.useState(!1),[r,p]=n.useState(""),[S,D]=n.useState(t.domain_whitelist||[]),[b,c]=n.useState(!1);n.useRef(null),n.useRef(null);const C="https://app.pagedock.ai/api".replace("/api","")||window.location.origin,T=window.location.origin,U=`<script src="${C}/webchat/widget.js" data-token="${t.embed_token}" async defer><\/script>`,E=()=>{navigator.clipboard.writeText(U).catch(()=>{}),s(!0),w.success("Embed code copied!"),setTimeout(()=>s(!1),2e3)},h=()=>{if(!r.trim())return;let k=r.trim().toLowerCase();k.startsWith("http")||(k="https://"+k);try{k=new URL(k).hostname}catch{k=r.trim()}if(S.includes(k)){w.error("Domain already added");return}const m=[...S,k];D(m),p(""),u({domain_whitelist:m})},M=k=>{const m=S.filter((N,a)=>a!==k);D(m),u({domain_whitelist:m})},$=n.useCallback(()=>{const k=document.getElementById("pagedock-webchat-root");k&&k.remove();const m=document.getElementById("pagedock-widget-app-script");m&&m.remove(),delete window.__pagedockWidgetInit},[]),I=n.useCallback(()=>{try{localStorage.removeItem("pdock_wc_conversation_id"),localStorage.removeItem("pdock_wc_state"),localStorage.removeItem("pdock_wc_visitor_token"),localStorage.removeItem("pdock_wc_auto_opened"),localStorage.removeItem("pdock_wc_launcher_expanded")}catch{}},[]),v=n.useCallback(()=>{const k=document.getElementById("pagedock-webchat-root");k&&k.remove();const m=document.getElementById("pagedock-widget-css");m&&m.remove();const N=document.createElement("link");N.rel="stylesheet",N.href=T+"/webchat/widget.css?v="+Date.now(),N.id="pagedock-widget-css",document.head.appendChild(N);const a=document.getElementById("pagedock-widget-app-script");a&&a.remove(),delete window.__pagedockWidgetInit;const i=document.createElement("div");i.id="pagedock-webchat-root",i.setAttribute("data-token",t.embed_token),i.setAttribute("data-base-url",T),document.body.appendChild(i);const j=document.createElement("script");j.src=T+"/webchat/widget-app.js?v="+Date.now(),j.async=!0,j.id="pagedock-widget-app-script",document.body.appendChild(j),c(!0)},[t.embed_token,T]),O=n.useCallback(()=>{v(),w.success("Widget test resumed â check the bottom-right corner")},[v]),P=n.useCallback(()=>{I(),v(),w.success("Fresh test started â new conversation")},[I,v]),H=n.useCallback(()=>{$(),c(!1),w.info("Widget test stopped")},[$]),W=n.useCallback(()=>{$(),I(),setTimeout(()=>{v(),w.success("Test restarted â new conversation")},500)},[$,I,v]);return n.useEffect(()=>()=>{$()},[$]),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs(V,{children:[e.jsx(G,{children:e.jsxs(K,{className:"text-base flex items-center gap-2",children:[e.jsx(ft,{className:"w-5 h-5 text-primary"}),"Embed Code"]})}),e.jsxs(q,{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Paste this code before the closing ",e.jsx("code",{className:"px-1 py-0.5 rounded bg-secondary text-xs",children:"</body>"})," tag on any page."]}),e.jsxs("div",{className:"relative",children:[e.jsx("pre",{className:"bg-secondary rounded-xl p-4 text-xs font-mono text-foreground overflow-x-auto whitespace-pre-wrap break-all border border-border",children:U}),e.jsx(A,{size:"sm",variant:"outline",className:"absolute top-2 right-2 h-8",onClick:E,children:l?e.jsxs(e.Fragment,{children:[e.jsx(ys,{className:"w-3.5 h-3.5 mr-1 text-emerald-600"})," Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"w-3.5 h-3.5 mr-1"})," Copy"]})})]}),e.jsx("div",{className:"bg-blue-500/10 border border-blue-500/20 rounded-xl p-4",children:e.jsxs("p",{className:"text-xs text-blue-700 dark:text-blue-300",children:[e.jsx("strong",{children:"Embed Token:"})," ",e.jsx("code",{className:"bg-blue-500/10 px-1.5 py-0.5 rounded",children:t.embed_token})]})})]})]}),e.jsxs(V,{children:[e.jsx(G,{children:e.jsxs(K,{className:"text-base flex items-center gap-2",children:[e.jsx(vs,{className:"w-5 h-5 text-primary"}),"Domain Whitelist"]})}),e.jsxs(q,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Restrict which domains can use this widget. Leave empty to allow all domains."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(F,{value:r,onChange:k=>p(k.target.value),placeholder:"example.com",onKeyDown:k=>k.key==="Enter"&&h()}),e.jsxs(A,{onClick:h,size:"sm",disabled:!r.trim(),children:[e.jsx(fs,{className:"w-4 h-4 mr-1"})," Add"]})]}),S.length>0?e.jsx("div",{className:"flex flex-wrap gap-2",children:S.map((k,m)=>e.jsxs("span",{className:"flex items-center gap-1.5 bg-secondary text-sm px-3 py-1.5 rounded-lg border border-border",children:[k,e.jsx("button",{onClick:()=>M(m),className:"text-muted-foreground hover:text-destructive",children:e.jsx(ss,{className:"w-3.5 h-3.5"})})]},m))}):e.jsx("p",{className:"text-xs text-muted-foreground bg-secondary/50 p-3 rounded-lg",children:"No domains added. Widget will work on any domain."})]})]})]}),e.jsx("div",{className:"lg:sticky lg:top-6 self-start",children:e.jsxs(V,{children:[e.jsx(G,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(K,{className:"text-base flex items-center gap-2",children:[e.jsx(ts,{className:"w-5 h-5 text-rose-600"}),"Live Test"]}),b?e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(A,{size:"sm",variant:"outline",onClick:H,className:"gap-1.5 text-xs",children:[e.jsx(ss,{className:"w-3.5 h-3.5"})," Stop"]}),e.jsxs(A,{size:"sm",variant:"outline",onClick:W,className:"gap-1.5 text-xs",children:[e.jsx(de,{className:"w-3.5 h-3.5"})," Restart Fresh"]})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(A,{size:"sm",onClick:O,className:"gap-1.5",children:[e.jsx(ve,{className:"w-3.5 h-3.5"})," Resume Test"]}),e.jsxs(A,{size:"sm",variant:"outline",onClick:P,className:"gap-1.5",children:[e.jsx(de,{className:"w-3.5 h-3.5"})," Fresh Test"]})]})]})}),e.jsx(q,{children:b?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-xl bg-emerald-500/10 border border-emerald-500/20",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-500 animate-pulse"}),e.jsx("span",{className:"text-xs font-medium text-emerald-700 dark:text-emerald-400",children:"Widget is running"})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-xl p-4 space-y-3",children:[e.jsx("p",{className:"text-xs font-semibold text-foreground",children:"Test checklist:"}),e.jsxs("ul",{className:"text-xs text-muted-foreground space-y-2",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-4 h-4 rounded border border-border flex-shrink-0 mt-0.5"}),"Chat launcher appears in the ",t.position||"bottom-right"," corner"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-4 h-4 rounded border border-border flex-shrink-0 mt-0.5"}),t.auto_open_delay>0?`Widget auto-opens after ${t.auto_open_delay} seconds`:"Click the launcher to open the chat"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-4 h-4 rounded border border-border flex-shrink-0 mt-0.5"}),'Greeting message appears from "',t.agent_name||"Assistant",'"']}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-4 h-4 rounded border border-border flex-shrink-0 mt-0.5"}),"Send a message and verify the AI responds"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-4 h-4 rounded border border-border flex-shrink-0 mt-0.5"}),"Theme colors (",t.theme_color,") match your branding"]}),t.coupon_enabled&&e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-4 h-4 rounded border border-border flex-shrink-0 mt-0.5"}),'Coupon "',t.coupon_code,'" appears after ',t.coupon_delay_messages," messages"]})]})]}),e.jsx("div",{className:"bg-secondary/30 rounded-xl p-3",children:e.jsx("p",{className:"text-[10px] text-muted-foreground",children:'The widget is loaded on this page exactly as it would appear on your website. Conversations created during testing are real and will appear in the Conversations tab. Click "Stop Test" or navigate away to remove the widget.'})})]}):e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-rose-500/10 flex items-center justify-center mx-auto mb-4",children:e.jsx(ts,{className:"w-7 h-7 text-rose-600"})}),e.jsx("p",{className:"text-sm font-medium text-foreground mb-1",children:"Test your widget"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-4 max-w-[250px] mx-auto",children:"Launch the chat widget on this page to test its appearance, behavior, and AI responses before embedding it on your site."}),e.jsxs("div",{className:"flex gap-2 justify-center",children:[e.jsxs(A,{onClick:O,className:"gap-2",children:[e.jsx(ve,{className:"w-4 h-4"})," Resume Test"]}),e.jsxs(A,{variant:"outline",onClick:P,className:"gap-2",children:[e.jsx(de,{className:"w-4 h-4"})," Fresh Test"]})]})]})})]})})]})}function Ot({webChat:t,onUpdate:u,saving:g}){const{hasAddon:l}=Bs(),s=l("ticketing_system"),[r,p]=n.useState([]),[S,D]=n.useState(!1);if(n.useEffect(()=>{if(!s){p([]);return}B.get("/support-desks").then(c=>p(Array.isArray(c)?c:[])).catch(()=>p([]))},[s]),!s)return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center bg-muted",children:e.jsx(as,{className:"w-4 h-4 text-muted-foreground"})}),e.jsx("span",{className:"text-xs font-bold text-muted-foreground uppercase tracking-wider",children:"Ticketing"})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Connect this chat to PageDock ticketing when you enable the Ticketing System add-on. Visitor ticket requests stay off until you turn them on here."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"rounded-xl",onClick:()=>D(!0),children:"View add-on"}),S&&e.jsx(bt,{onClose:()=>D(!1)})]});const b=!!t.ticketing_integration_enabled;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center bg-sky-500/10",children:e.jsx(as,{className:"w-4 h-4 text-sky-600"})}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-bold text-muted-foreground uppercase tracking-wider",children:"Ticketing"}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:"Optional â only affects this web chat."})]})]}
24),e.jsxs("div",{className:L("rounded-xl border bg-card/40 p-3 sm:p-4 space-y-4",b?"border-sky-500/25 ring-1 ring-sky-500/10":"border-border/70"),children:[e.jsxs("div",{className:"flex items-start gap-3 sm:gap-4",children:[e.jsx(ee,{className:"mt-0.5",checked:b,disabled:g,onCheckedChange:c=>{g||u({ticketing_integration_enabled:c})},"aria-label":"Allow visitors to open a support ticket from this chat"}),e.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[e.jsx(y,{className:"cursor-pointer text-sm font-medium text-foreground leading-snug",onClick:()=>!g&&u({ticketing_integration_enabled:!b}),children:"Allow visitors to open a support ticket"}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"When off, the widget behaves as before: no ticket flow from chat. When on, the widget may offer ticketing only if a help desk is selected below."})]})]}),e.jsxs("div",{className:"space-y-2 pt-1 border-t border-border/60",children:[e.jsx(y,{className:"text-xs font-medium text-muted-foreground",children:"Help desk"}),e.jsxs(pe,{value:t.support_desk_id?String(t.support_desk_id):"none",onValueChange:c=>u({support_desk_id:c==="none"?null:Number(c)}),disabled:g,children:[e.jsx(he,{className:"rounded-xl h-11",children:e.jsx(ge,{placeholder:"Select a desk"})}),e.jsxs(fe,{children:[e.jsx(X,{value:"none",children:"No desk selected"}),r.map(c=>e.jsx(X,{value:String(c.id),children:c.name},c.id))]})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground flex items-start gap-1.5",children:[e.jsx(Re,{className:"w-3.5 h-3.5 shrink-0 mt-0.5 opacity-70","aria-hidden":!0}),e.jsx("span",{children:"New tickets use this desk and appear in Ticket Inbox. The server still requires this desk plus the toggle above for any visitor escalation â leaving the toggle off is safe."})]})]})]})]})}function ls(t){return t.filter(u=>["customer","assistant","agent"].includes(u.role)&&u.body).map(u=>({role:u.role,body:u.body}))}function cs(t){return String(t||"(empty)").split(` 25`).map(g=>`> ${g}`).join(` 26`)}function ds(t){return["```json",JSON.stringify(t??null,null,2),"```"].join(` 27`)}function ae(t,u="text"){return[`\`\`\`${u}`,String(t||""),"```"].join(` 28`)}function Bt({webChat:t,product:u,email:g,name:l,turns:s}){var S,D,b,c,C,T,U;const r=[];r.push(`# Web Chat AI Tester â ${(t==null?void 0:t.name)||"Web Chat"}`),r.push(""),r.push(`- **Visitor**: ${l?`${l} <${g||"no email"}>`:g||"anonymous"}`),r.push(`- **Product**: ${(u==null?void 0:u.name)||"No product selected"}`),r.push(`- **Widget ID**: ${(t==null?void 0:t.id)||"â"}`),r.push(`- **Tested at**: ${new Date().toISOString()}`),r.push(`- **Turns**: ${Array.isArray(s)?s.length:0}`),r.push(""),r.push("---"),r.push("");let p=0;for(const E of s||[]){if(E.role==="customer"){p+=1,r.push(`## Turn ${p} â Visitor`),r.push(""),r.push(cs(E.body)),r.push("");continue}if(r.push(`## Turn ${p||1} â AI Reply`),r.push(""),E.error){r.push(`**Error**: ${E.body||"Unknown error"}`),r.push("");continue}r.push("**Reply:**"),r.push(""),r.push(cs(E.body)),r.push("");const h=E.debug||{},M=E.meta||{},$=h.llm||{},I=h.phase||{},v=h.selector||{},O=Array.isArray(h.candidate_pool)?h.candidate_pool:[];if(r.push("**Run summary:**"),r.push(`- phase: \`${I.name||h.phase_name||"â"}\` / \`${I.type||h.phase_type||"â"}\``),r.push(`- product: \`${((S=h.product)==null?void 0:S.name)||h.product_name||(u==null?void 0:u.name)||"â"}\``),r.push(`- selected context: \`${h.context_selected||v.selected_context_name||"â"}\``),r.push(`- model: \`${$.model_identifier||$.model||M.model||"â"}\``),r.push(`- provider: \`${$.provider||M.provider||"â"}\``),r.push(`- latency: ${$.latency_ms||M.latency_ms||0} ms`),r.push(`- tokens: ${((D=$.tokens)==null?void 0:D.input)||((b=M.tokens)==null?void 0:b.input)||0} in / ${((c=$.tokens)==null?void 0:c.output)||((C=M.tokens)==null?void 0:C.output)||0} out`),r.push(""),r.push("**Phase and system prompts:**"),r.push("- raw phase instruction:"),r.push(ae(I.raw_instruction||"")),r.push("- resolved phase instruction:"),r.push(ae(I.resolved_instruction||h.phase_instruction||"")),r.push("- web chat system prompt template:"),r.push(ae(((T=h.web_chat)==null?void 0:T.system_prompt_template)||"")),r.push("- final system prompt sent:"),r.push(ae(h.system_prompt||"")),r.push(""),r.push("**Context selection:**"),r.push(`- pool size: ${v.pool_size??O.length}`),r.push(`- chosen context ids: ${JSON.stringify(v.chosen_context_ids||(v.chosen_context_id?[v.chosen_context_id]:[]))}`),h.selected_context_text&&(r.push("- exact selected context text sent:"),r.push(ae(h.selected_context_text))),O.length>0){r.push("- candidate pool:");for(const P of O){const W=(v.chosen_context_ids||(v.chosen_context_id?[v.chosen_context_id]:[])).map(Number).includes(Number(P.context_id))?" **[used]**":"";if(r.push(` -${W} #${P.context_id} ${P.product_name||(u==null?void 0:u.name)||"Product"} · ${P.context_name}${P.must_use_on_all_replies?" (always include)":""}`),P.description&&r.push(` - description: ${P.description}`),P.current_base_text&&(r.push(" - base context:"),r.push(ae(P.current_base_text))),Array.isArray(P.current_snippets)&&P.current_snippets.length>0){r.push(" - refined snippets:");for(const k of P.current_snippets)r.push(` - ${k.id||"(no id)"}`),r.push(ae(k.body||""))}P.composed_context_text&&(r.push(" - exact composed context:"),r.push(ae(P.composed_context_text)))}}r.push(""),r.push("**Exact request sent to the LLM:**"),r.push(ds(Array.isArray($.prompt_messages)?$.prompt_messages:[])),r.push(""),r.push("**Raw LLM response:**"),r.push(ae($.raw_text||((U=E.ai)==null?void 0:U.answer)||E.body||"")),r.push(""),r.push("**Full debug payload:**"),r.push(ds({debug:h,meta:M,ai:E.ai||null})),r.push("")}return r.join(` 29`)}function Ut({turn:t}){var r;const u=(t==null?void 0:t.debug)||{},g=Array.isArray(u.candidate_pool)?u.candidate_pool:[],l=u.selector||{},s=(t==null?void 0:t.meta)||{};return e.jsxs("div",{className:"mt-3 rounded-xl border border-border/60 bg-muted/25 p-3 text-xs text-muted-foreground space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("span",{className:"font-medium text-foreground
29/80",children:"Debug"}),(r=u.phase)!=null&&r.name?e.jsxs("span",{children:["Phase: ",u.phase.name]}):null,l.chosen_context_id?e.jsxs("span",{children:["Context #",l.chosen_context_id]}):null,s.model?e.jsxs("span",{children:["Model: ",s.model]}):null,s.latency_ms?e.jsxs("span",{children:[s.latency_ms,"ms"]}):null]}),g.length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:g.map(p=>e.jsx("span",{className:"rounded-full border border-border/70 bg-background/70 px-2 py-0.5 text-[11px]",children:p.context_name},p.context_id))}):e.jsx("p",{children:"No candidate contexts were available for this turn."})]})}function zt({webChat:t,onContextUpdated:u}){const g=(t==null?void 0:t.product)||null,l=t!=null&&t.id?`/web-chats/${t.id}/ai-tester`:"",[s,r]=n.useState("[email protected]"),[p,S]=n.useState("Test Visitor"),[D,b]=n.useState(""),[c,C]=n.useState([]),[T,U]=n.useState(!1),[E,h]=n.useState(null),[M,$]=n.useState("improve"),[I,v]=n.useState(""),O=n.useRef(null),P=n.useMemo(()=>g?[g]:[],[g]),H=E===null?null:c[E],W=async(a=null)=>{var Z,ie,re,se,ne;const i=a===null?D.trim():(ie=(Z=c[a])==null?void 0:Z.body)==null?void 0:ie.trim();if(!i||T||!l)return;const j=a===null?c:c.slice(0,a),z={role:"customer",body:i};a===null?(C(x=>[...x,z]),b("")):C(x=>[...x.slice(0,a),z]),U(!0);try{const x=await B.post(`${l}/turn`,{email:s.trim()||void 0,name:p.trim()||void 0,transcript:ls(j),latest_question:i});if(!(x!=null&&x.ok))throw new Error((x==null?void 0:x.message)||(x==null?void 0:x.error)||"Web Chat tester failed");const Q={role:"assistant",body:((re=x.ai)==null?void 0:re.answer)||"",ai:x.ai,debug:x.debug,meta:x.meta};C(oe=>[...oe,Q]),window.setTimeout(()=>{var oe;(oe=O.current)==null||oe.scrollTo({top:O.current.scrollHeight,behavior:"smooth"})},0)}catch(x){const Q=((ne=(se=x==null?void 0:x.response)==null?void 0:se.data)==null?void 0:ne.message)||(x==null?void 0:x.message)||"Web Chat tester failed";w.error(Q),C(oe=>[...oe,{role:"assistant",body:Q,error:!0}])}finally{U(!1)}},k=async()=>{var i;const a=Bt({webChat:t,product:g,email:s,name:p,turns:c});try{if(!((i=navigator==null?void 0:navigator.clipboard)!=null&&i.writeText))throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(a),w.success("Copied tester transcript as Markdown")}catch{v(a),w.error("Could not copy transcript")}},m=()=>{C([]),b(""),h(null)},N=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),W())};return g?e.jsxs("div",{className:"space-y-5",children:[e.jsx(V,{children:e.jsxs(q,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"h-10 w-10 shrink-0 rounded-xl bg-primary/10 grid place-items-center text-primary",children:e.jsx(Re,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-base font-semibold text-foreground",children:"AI Web Chat Tester"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 leading-relaxed",children:"Simulate Web Chat replies using this widgetâs selected product, phases, prompt, and product AI contexts."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(A,{type:"button",variant:"outline",size:"sm",onClick:k,disabled:c.length===0,className:"rounded-xl",children:[e.jsx(jt,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy as Markdown"]}),e.jsxs(A,{type:"button",variant:"ghost",size:"sm",onClick:m,disabled:T||c.length===0,className:"rounded-xl",children:[e.jsx(de,{className:"h-3.5 w-3.5 mr-1.5"}),"Reset"]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(y,{htmlFor:"webchat-ai-tester-email",children:"Visitor email"}),e.jsx(F,{id:"webchat-ai-tester-email",type:"email",value:s,onChange:a=>r(a.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(y,{htmlFor:"webchat-ai-tester-name",children:"Visitor name"}),e.jsx(F,{id:"webchat-ai-tester-name",value:p,onChange:a=>S(a.target.value)})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/60 bg-muted/20 px-3 py-2 text-xs text-muted-foreground flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"font-medium text-foreground
29/80",children:"Product in scope:"}),e.jsx("span",{className:"rounded-full border border-border/70 bg-background/60 px-2 py-0.5 text-[11px] font-medium text-foreground/85",children:g.name})]})]})}),e.jsxs(V,{className:"overflow-hidden",children:[e.jsxs("div",{ref:O,className:"max-h-[60vh] min-h-[320px] overflow-y-auto p-4 sm:p-5 space-y-4 bg-gradient-to-b from-background/40 to-muted/20",children:[c.length===0?e.jsxs("div",{className:"text-center py-10",children:[e.jsx(Ie,{className:"h-8 w-8 mx-auto text-muted-foreground/60 mb-2","aria-hidden":!0}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Start a conversation below to see how the Web Chat AI would reply."})]}):c.map((a,i)=>{const j=a.role==="customer";return e.jsx("div",{className:`flex ${j?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[85%] ${j?"items-end":"items-start"} flex flex-col`,children:[!j&&!a.error?e.jsxs(A,{type:"button",variant:"ghost",size:"sm",onClick:()=>{$("diagnose"),h(i)},className:"mb-1 h-7 rounded-lg px-2 text-[11px] text-violet-700 hover:text-violet-700 dark:text-violet-300 dark:hover:text-violet-300",children:[e.jsx(nt,{className:"h-3 w-3 mr-1"}),"Diagnose this answer"]}):null,!j&&!a.error?e.jsxs(A,{type:"button",variant:"ghost",size:"sm",onClick:()=>{$("improve"),h(i)},className:"mb-1 h-7 rounded-lg px-2 text-[11px] text-primary hover:text-primary",children:[e.jsx(js,{className:"h-3 w-3 mr-1"}),"Improve this reply"]}):null,e.jsx("div",{className:`rounded-2xl px-4 py-3 shadow-sm ${j?"bg-primary text-primary-foreground rounded-br-md":a.error?"bg-destructive/10 text-destructive border border-destructive/30 rounded-bl-md":"bg-card border border-border rounded-bl-md"}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[j?e.jsx(Zs,{className:"h-4 w-4 mt-0.5 shrink-0"}):e.jsx(Ie,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsx("p",{className:"text-sm whitespace-pre-wrap break-words",children:a.body})]})}),!j&&!a.error?e.jsx(Ut,{turn:a}):null]})},`${a.role}-${i}`)}),T?e.jsx("div",{className:"flex justify-start",children:e.jsxs("div",{className:"rounded-2xl rounded-bl-md border border-border bg-card px-4 py-3 text-sm text-muted-foreground inline-flex items-center gap-2",children:[e.jsx(ye,{className:"h-4 w-4 animate-spin"}),"Running Web Chat AIâ¦"]})}):null]}),e.jsx("div",{className:"border-t border-border p-4 bg-background",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx("textarea",{value:D,onChange:a=>b(a.target.value),onKeyDown:N,placeholder:"Ask the Web Chat AI a questionâ¦",rows:2,className:"min-h-[48px] flex-1 resize-y rounded-xl border border-border bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40",disabled:T}),e.jsx(A,{type:"button",onClick:()=>W(),disabled:!D.trim()||T,className:"self-end rounded-xl",children:T?e.jsx(ye,{className:"h-4 w-4 animate-spin"}):e.jsx(Ns,{className:"h-4 w-4"})})]})})]}),e.jsx(bs,{open:E!==null,onClose:()=>h(null),endpointBase:l,contextProducts:P,turn:H,title:M==="diagnose"?"Why did it answer like this?":void 0,description:M==="diagnose"?"Ask PageDock to inspect the web chat phase, prompts, selected contexts, transcript, and raw LLM call to identify the most likely source of the answer.":void 0,instructionLabel:M==="diagnose"?"What should the AI have answered?":void 0,instructionPlaceholder:M==="diagnose"?"Why did the AI answer like this? It should have answered ...":void 0,initialInstruction:M==="diagnose"?"Why did the AI answer like this? It should have answered ":"",fullTranscript:ls(c),onApplied:u,onTestAgain:()=>{var i;let a=-1;for(let j=(E??0)-1;j>=0;j-=1)if(((i=c[j])==null?void 0:i.role)==="customer"){a=j;break}a>=0&&W(a)}}),e.jsx(xs,{open:I!=="",onOpenChange:a=>{a||v("")},children:e.jsxs(ps,{className:"max-w-3xl",children:[e.jsxs(hs,{children:[e.jsx(gs,{children:"Copy Markdown manually"}),e.jsx(zs,{children:"Your browser blocked clipboard access. Select the Markdown below and copy it."})]}),e.jsx("textarea",{value:I,readOnly:!0,className:"min-h-[420px] w-full rounded-xl border border-border bg-background p-3 font-mono text-xs text-foreground",onF
29ocus:a=>a.target.select()})]})})]}):e.jsx(V,{children:e.jsx(q,{className:"p-6 text-sm text-muted-foreground",children:"Select a product on the General tab before using the Web Chat AI Tester. Replies and improvements are scoped to that productâs AI contexts."})})}J.extend(us);const _s=[{id:"general",label:"General"},{id:"appearance",label:"Appearance"},{id:"behavior",label:"Behavior"},{id:"phases",label:"Phases"},{id:"coupon",label:"Coupon"},{id:"prompt",label:"System Prompt"},{id:"ai-tester",label:"AI Tester"},{id:"conversations",label:"Conversations"},{id:"analytics",label:"Analytics"},{id:"embed",label:"Embed & Test"}],ms=_s.map(t=>t.id),Te="general";function br(){var H,W,k;const{id:t}=$s(),u=Ms(),[g,l]=Rs(),[s,r]=n.useState(null),[p,S]=n.useState(!0),D=(()=>{const m=g.get("tab");return m==="ticketing"?Te:m&&ms.includes(m)?m:Te})(),[b,c]=n.useState(D),[C,T]=n.useState(!1),[U,E]=n.useState([]);n.useEffect(()=>{const m=g.get("tab");if(m==="ticketing"){const N=new URLSearchParams(g);N.delete("tab"),l(N,{replace:!0}),c("general");return}m&&ms.includes(m)&&m!==b&&c(m)},[g]);const h=n.useCallback(m=>{c(m);const N=new URLSearchParams(g);m===Te?N.delete("tab"):N.set("tab",m),l(N,{replace:!0})},[g,l]);Ls((s==null?void 0:s.name)||"Web Chat Config"),n.useEffect(()=>{B.get("/products").then(m=>E(Array.isArray(m)?m:[])).catch(()=>{})},[]);const M=n.useCallback(async()=>{try{S(!0),B.invalidateCache(`/web-chats/${t}`);const m=await B.get(`/web-chats/${t}`);r(m)}catch{w.error("Failed to load web chat"),u("/dashboard/web-chats")}finally{S(!1)}},[t,u]);n.useEffect(()=>{M()},[M]);const $=n.useRef({}),I=n.useRef(null),v=350,O=n.useCallback(()=>{if(Object.keys($.current).length===0)return;const m=$.current;$.current={},I.current=null,T(!0),B.put(`/web-chats/${t}`,m).catch(N=>{w.error(N.message||"Failed to save"),M()}).finally(()=>T(!1))},[t,M]),P=m=>{r(N=>({...N,...m})),$.current={...$.current,...m},I.current&&clearTimeout(I.current),I.current=setTimeout(O,v)};return n.useEffect(()=>()=>{I.current&&(clearTimeout(I.current),O())},[O]),p||!s?e.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:e.jsx(Fs,{text:"Loading...",size:"lg"})}):e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 sm:gap-4",children:[e.jsx(A,{variant:"ghost",size:"icon",className:"rounded-xl flex-shrink-0",onClick:()=>u("/dashboard/web-chats"),children:e.jsx(yt,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0",style:{backgroundColor:s.theme_color+"20"},children:e.jsx(ce,{className:"w-5 h-5",style:{color:s.theme_color}})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-lg sm:text-xl font-bold text-foreground truncate",children:s.name}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 tabular-nums",children:[e.jsx(vt,{className:"w-3.5 h-3.5 opacity-70","aria-hidden":!0}),t]}),((H=s.product)==null?void 0:H.name)&&e.jsxs("span",{className:"inline-flex items-center gap-1 min-w-0",children:[e.jsx(rs,{className:"w-3.5 h-3.5 shrink-0 opacity-70","aria-hidden":!0}),e.jsx("span",{className:"truncate max-w-[200px]",children:s.product.name})]}),s.created_at&&e.jsx(xe,{title:"Created",description:J(s.created_at).format("MMMM D, YYYY h:mm A"),children:e.jsxs("span",{className:"cursor-help",children:["Created ",J(s.created_at).fromNow()]})})]})]})]}),e.jsxs(pe,{value:s.status,onValueChange:m=>P({status:m}),children:[e.jsx(he,{className:L("w-[130px] h-9 text-xs font-semibold uppercase",s.status==="active"?"border-emerald-500/30 text-emerald-600":s.status==="paused"?"border-amber-500/30 text-amber-600":"text-muted-foreground"),children:e.jsx(ge,{})}),e.jsxs(fe,{children:[e.jsx(X,{value:"active",children:"Active"}),e.jsx(X,{value:"paused",children:"Paused"}),e.jsx(X,{value:"archived",children:"Archived"})]})]})]}),e.jsx("div",{className:"flex gap-1 bg-secondary/50 p-1 rounded-xl overflow-x-auto",children:_s.map(m=>e.jsx("button",{type:"button",onClick:()=>h(m.id),className:L("px-4 py-2 rounded-lg text-sm font-medium transition-all whitespace-nowrap",b===m.id?"bg-card text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:m.label},m.id))}),e.jsxs("div",{children:[b==="general"&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsx(V,{className:"border-l-[3px] border-l-primary overflow-hidden",children:e.jsxs(q,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center bg-primary/10",children:e.jsx(ce,{className:"w-4 h-4 text-primary"})}),e.jsx("span",{className:"text-xs font-bold text-muted-foreground uppercase tracking-wider",children:"Chat Settings"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Chat Name"}),e.jsx("input",{defaultValue:s.name,onBlur:m=>{m.target.value!==s.name&&P({name:m.target.value})},className:"flex h-11 w-full rounded-xl border border-input bg-background px-4 py-2 text-sm r
29ing-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/20 focus-visible:border-primary transition-all"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Agent Name"}),e.jsx("input",{defaultValue:s.agent_name||"",onBlur:m=>{m.target.value!==(s.agent_name||"")&&P({agent_name:m.target.value})},placeholder:'e.g. Sarah, Alex (leave empty for "Assistant")',className:"flex h-11 w-full rounded-xl border border-input bg-background px-4 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/20 focus-visible:border-primary transition-all"}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["The name the AI uses to introduce itself. Available as ","{agent_name}"," in phases and system prompt."]})]}),e.jsx("div",{className:"p-3 rounded-xl bg-secondary/50 mt-2",children:e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Use the status selector in the header to pause or archive this chat. Configure appearance, behavior, and AI settings in the other tabs. Use the ",e.jsx("strong",{children:"Embed & Test"})," tab to get the embed code and test your widget live."]})})]})}),e.jsx(V,{className:L("border-l-[3px] overflow-hidden",s.product_id?"border-l-teal-500":"border-l-amber-500"),children:e.jsxs(q,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:L("w-8 h-8 rounded-lg flex items-center justify-center",s.product_id?"bg-teal-500/10":"bg-amber-500/10"),children:e.jsx(rs,{className:L("w-4 h-4",s.product_id?"text-teal-600":"text-amber-600")})}),e.jsx("span",{className:"text-xs font-bold text-muted-foreground uppercase tracking-wider",children:"Product"})]}),((W=s.product)==null?void 0:W.support_url)&&e.jsxs("a",{href:s.product.support_url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-primary flex items-center gap-1",children:["Support ",e.jsx(Nt,{className:"w-3 h-3"})]})]}),e.jsxs(pe,{value:String(s.product_id||"none"),onValueChange:m=>{const N=m==="none"?null:parseInt(m);P({product_id:N});const a=U.find(i=>i.id===N);r(i=>({...i,product_id:N,product:a?{id:a.id,name:a.name,contexts:a.contexts,support_url:a.support_url}:null}))},children:[e.jsx(he,{children:e.jsx(ge,{placeholder:"Select a product"})}),e.jsxs(fe,{children:[e.jsx(X,{value:"none",children:"No product"}),U.filter(m=>m.is_active).map(m=>e.jsx(X,{value:String(m.id),children:m.reference?`${m.name} - ${m.reference}`:m.name},m.id))]})]}),s.product?e.jsx("div",{className:"space-y-3",children:(((k=s.product)==null?void 0:k.contexts)||[]).length>0?e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-2",children:"AI Contexts available"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.product.contexts.map((m,N)=>e.jsxs("span",{className:"text-[11px] px-2 py-1 rounded-lg bg-teal-500/10 text-teal-600 font-medium border border-teal-500/20",children:[e.jsx(Re,{className:"w-3 h-3 inline mr-1"}),m.name]},N))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-2",children:"The AI will automatically pick the best context for each visitor question."})]}):e.jsx("div",{className:"p-3 rounded-xl bg-amber-500/10 border border-amber-500/20",children:e.jsxs("p",{className:"text-xs text-amber-700 dark:text-amber-400",children:["This product has no AI contexts configured. ",e.jsx("a",{href:"/dashboard/products",className:"underline",children:"Add contexts"})]})})}):e.jsx("div",{className:"p-3 rounded-xl bg-secondary/50",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assign a product to give the AI knowledge about what to sell and support."})}),e.jsx("div",{className:"pt-5 mt-5 border-t border-border/60",children:e.jsx(Ot,{webChat:s,onUpdate:P,saving:C})})]})})]}),b==="appearance"&&e.jsx(Tt,{webChat:s,onUpdate:P,saving:C}),b==="behavior"&&e.jsx(It,{webChat:s,onUpdate:P,saving:C}),b==="phases"&&e.jsx(Dt,{webChat:s,onReload:M}),b==="coupon"&&e.jsx($t,{webChat:s,onUpdate:P,saving:C}),b==="prompt"&&e.jsx(Mt,{webChat:s,onUpdate:P,saving:C}),b==="ai-tester"&&e.jsx(zt,{webChat:s,onContextUpdated:M}),b==="conversations"&&e.jsx(Ft,{webChat:s}),b==="analytics"&&e.jsx(Et,{webChat:s}),b==="embed"&&e.jsx(Wt,{webChat:s,onUpdate:P,saving:C})]})]})}export{br as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.