1import{r as a,j as t}from"./query-CGHSk7ud.js";import{f as xe,w as he,s as u,q as v,v as te,B as x,I as pe}from"./index-BfrGfMD_.js";import{A as ge,a as ve,b as be,c as je,d as _e,e as Ne,f as we,g as ye,h as Ce}from"./alert-dialog-C6V0SYw2.js";import{t as se,aJ as Se,bS as ke,a7 as Ae,bn as De,ah as Re,k as Te,R as re,L as F,bB as Le,J as Ee,d as Ie,ao as Me,at as qe,Z as ze,x as Be}from"./icons-CxnfC-37.js";import"./react-vendor-BsSYYw5-.js";import"./supabase-BOCL3uOH.js";import"./charts-B3XiXjwx.js";import"./motion-B9DIfdcM.js";import"./i18n-C4HGKhfx.js";const Ue=[{label:"ð Accueil",text:"Bonjour, merci pour votre message, je regarde ça tout de suite."},{label:"ð Lien annonce",text:"Pouvez-vous m'envoyer le lien de l'annonce concernée ?"},{label:"â
Corrigé",text:"C'est corrigé de notre côté, pouvez-vous rafraîchir la page et réessayer ?"},{label:"ð Merci",text:"Merci beaucoup pour votre retour, on le remonte à l'équipe."},{label:"â±ï¸ Patience",text:"Je vérifie ça avec l'équipe technique et je reviens vers vous très vite."},{label:"ð Réinstaller",text:"Pouvez-vous mettre à jour l'extension vers la dernière version puis relancer votre navigateur ?"}],H={google:"Recherche Google",advertising:"Publicité",instagram:"Instagram",tiktok:"TikTok",word_of_mouth:"Connaissance",other:"Autre"};function ae(){try{const p=window.AudioContext||window.webkitAudioContext;if(!p)return;const c=new p,l=c.createOscillator(),m=c.createGain();l.type="sine",l.frequency.value=880,m.gain.setValueAtTime(1e-4,c.currentTime),m.gain.exponentialRampToValueAtTime(.15,c.currentTime+.02),m.gain.exponentialRampToValueAtTime(1e-4,c.currentTime+.35),l.connect(m).connect(c.destination),l.start(),l.stop(c.currentTime+.36),setTimeout(()=>c.close().catch(()=>{}),600)}catch{}}function $e(p){const c=new Date(p),l=new Date,m=new Date(Date.now()-864e5),h=(N,R)=>N.toDateString()===R.toDateString();return h(c,l)?"Aujourd'hui":h(c,m)?"Hier":c.toLocaleDateString("fr-FR",{weekday:"long",day:"numeric",month:"long"})}function Ze(){const{user:p}=xe(),{deleteChatConversation:c,users:l,fetchUsers:m}=he(),[h,N]=a.useState([]),[R,V]=a.useState(!0),[T,ne]=a.useState(""),[L,K]=a.useState(!1),[w,J]=a.useState("all"),[y,E]=a.useState([]),[I,G]=a.useState(!1),[n,M]=a.useState(null),[C,q]=a.useState([]),[ie,Q]=a.useState(!1),[z,B]=a.useState(""),[S,Z]=a.useState(!1),[oe,le]=a.useState(()=>localStorage.getItem("avs_chat_sound")!=="off"),[k,ce]=a.useState(()=>localStorage.getItem("avs_chat_notif")!=="off"),U=a.useRef(null),A=a.useRef(null),X=a.useRef(null),$=a.useRef(k),de=a.useRef(Date.now());X.current=n,$.current=k,a.useEffect(()=>{(!l||l.length===0)&&m().catch(()=>{})},[l,m]);const b=a.useMemo(()=>{const e=new Map;return(l||[]).forEach(s=>e.set(s.id,s.email)),e},[l]),f=a.useMemo(()=>{const e=new Map;return(l||[]).forEach(s=>{s.heard_about_us&&e.set(s.id,s.heard_about_us)}),e},[l]),W=a.useMemo(()=>{const e=new Set;return h.forEach(s=>{const r=f.get(s.user_id);r&&e.add(r)}),Array.from(e).sort()},[h,f]),g=a.useCallback(async()=>{const{data:e,error:s}=await u.from("support_chat_messages").select("user_id, content, created_at, sender, read_by_admin").eq("channel","team").order("created_at",{ascending:!1}).limit(1e3);if(s||!e){V(!1);return}const r=new Map;for(const i of e){const d=r.get(i.user_id);d?i.sender==="user"&&!i.read_by_admin&&(d.unread+=1):r.set(i.user_id,{user_id:i.user_id,email:null,full_name:null,last_message:i.content,last_at:i.created_at,last_sender:i.sender,unread:i.sender==="user"&&!i.read_by_admin?1:0})}const o=Array.from(r.keys());if(o.length>0){const{data:i}=await u.from("profiles").select("user_id, full_name").in("user_id",o);i?.forEach(d=>{const _=r.get(d.user_id);_&&(_.full_name=d.full_name)})}N(Array.from(r.values()).sort((i,d)=>d.last_at.localeCompare(i.last_at))),V(!1)},[]);a.useEffect(()=>{g()},[g]),a.useEffect(()=>{const e=u.channel("admin_live_chat_list").on("postgres_changes",{event:"INSERT",schema:"public",table:"support_chat_messages"},s=>{const r=s.new;if(g(),r.channel&&r.channel!=="team"||r.sender!=="user"||new Date(r.created_at).getTime()<de.current)return;if(!(X.current===r.user_id)&&$.current&&(v.message("Nouveau message client",{description:r.content.slice(0,120)}),typeof Notification<"u"&&Notification.permission==="granted"))try{new Notification("Nouveau message client",{body:r.content.slice(0,120),tag:r.user_id})}catch{}localStorage.getItem("avs_chat_sound")!=="off"&&ae()}).subscribe();return()=>{u.removeChannel(e)}},[g]);const O=a.useCallback(async e=>{await u.from("support_chat_messages").update({read_by_admin:!0}
1).eq("user_id",e).eq("channel","team").eq("sender","user").eq("read_by_admin",!1),N(s=>s.map(r=>r.user_id===e?{...r,unread:0}:r))},[]);a.useEffect(()=>{if(!n)return;let e=!1;Q(!0),u.from("support_chat_messages").select("*").eq("user_id",n).eq("channel","team").order("created_at",{ascending:!0}).then(({data:r})=>{e||(r&&q(r),Q(!1),O(n),setTimeout(()=>A.current?.focus(),50))});const s=u.channel(`admin_thread_${n}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"support_chat_messages",filter:`user_id=eq.${n}`},r=>{const o=r.new;o.channel&&o.channel!=="team"||(q(i=>i.some(d=>d.id===o.id)?i:[...i,o]),o.sender==="user"&&O(n))}).subscribe();return()=>{e=!0,u.removeChannel(s)}},[n,O]),a.useEffect(()=>{if(!n){E([]),G(!1);return}let e=!1;return E([]),u.from("vehicle_analyses").select("brand, model, created_at").eq("user_id",n).order("created_at",{ascending:!1}).limit(200).then(({data:s})=>{if(e||!s)return;const r=new Map;for(const o of s){const i=(o.brand||"").trim();if(!i)continue;const d=i.toLowerCase(),_=r.get(d);_?_.count+=1:r.set(d,{brand:i,count:1,last:o.created_at})}E(Array.from(r.values()).sort((o,i)=>i.count-o.count).slice(0,12))}),()=>{e=!0}},[n]),a.useEffect(()=>{U.current?.scrollTo({top:U.current.scrollHeight,behavior:"smooth"})},[C]);const P=async e=>{const s=(e??z).trim();if(!s||!n||!p||S)return;Z(!0);const{error:r}=await u.from("support_chat_messages").insert({user_id:n,sender:"admin",sender_id:p.id,channel:"team",content:s});r?v.error("Erreur d'envoi"):(B(""),g(),u.functions.invoke("support-notify",{body:{event:"support_reply",targetUserId:n,message:s}}).catch(()=>{})),Z(!1),A.current?.focus()},ue=()=>{le(e=>{const s=!e;return localStorage.setItem("avs_chat_sound",s?"on":"off"),s&&ae(),s})},me=e=>{ce(e),$.current=e,localStorage.setItem("avs_chat_notif",e?"on":"off")},fe=async()=>{const e=!k;if(me(e),!e){v.success("Notifications en pause");return}if(v.success("Notifications activées"),typeof Notification<"u"&&Notification.permission==="default")try{await Notification.requestPermission()}catch{}},Y=h.filter(e=>{if(L&&e.unread===0||w!=="all"&&(f.get(e.user_id)||"unknown")!==w)return!1;if(!T.trim())return!0;const s=T.toLowerCase();return(e.full_name||"").toLowerCase().includes(s)||(b.get(e.user_id)||"").toLowerCase().includes(s)||e.user_id.toLowerCase().includes(s)||e.last_message.toLowerCase().includes(s)}),D=h.reduce((e,s)=>e+s.unread,0),ee=h.find(e=>e.user_id===n),j=n?b.get(n):void 0;return t.jsxs("div",{className:"h-[calc(100vh-12rem)] flex border border-border rounded-xl overflow-hidden bg-card",children:[t.jsxs("div",{className:`w-full md:w-80 border-r border-border flex-col ${n?"hidden md:flex":"flex"}`,children:[t.jsxs("div",{className:"p-3 border-b border-border space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(se,{className:"h-4 w-4 text-primary"}),t.jsx("span",{className:"text-sm font-semibold",children:"Messagerie"}),D>0&&t.jsx(te,{variant:"destructive",className:"h-5 min-w-5 px-1.5 text-[10px]",children:D})]}),t.jsxs("div",{className:"flex items-center gap-0.5",children:[t.jsx(x,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:ue,title:"Son des nouveaux messages",children:oe?t.jsx(Se,{className:"h-3.5 w-3.5"}):t.jsx(ke,{className:"h-3.5 w-3.5 text-muted-foreground"})}),t.jsx(x,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:fe,title:"Notifications du navigateur",children:k?t.jsx(Ae,{className:"h-3.5 w-3.5 text-primary"}):t.jsx(De,{className:"h-3.5 w-3.5 text-muted-foreground"})}),t.jsx(x,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(),title:"Rafraîchir",children:t.jsx(Re,{className:"h-3.5 w-3.5"})})]})]}),t.jsxs("div",{className:"relative",children:[t.jsx(Te,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),t.jsx(pe,{placeholder:"Nom, email, messageâ¦",value:T,onChange:e=>ne(e.target.value),className:"pl-8 h-9"})]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsxs(x,{variant:L?"default":"outline",size:"sm",className:"h-8 text-xs flex-1",onClick:()=>K(e=>!e),children:["Non lus ",D>0?`(${D})`:""]}),(L||w!=="all")&&t.jsx(x,{variant:"outline",size:"sm",className:"h-8 text-xs",onClick:()=>{K(!1),J("all")},children:"Tout"})]}),W.length>0&&t.jsxs("div",{className:"flex items-center gap-1.5 overflow-x-auto pb-0.5",children:[t.jsx(re,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),["all",...W].map(e=>t.jsx("button",{onClick:()=>J(e),className:`shrink-0 text-[11px] px-2.5 h-7 rounded-full border transition-colors ${w===e?"bg-primary text-primary-foreground border-primary":"border-border text-muted-foreground hover:bg-muted"}`,children:e==="all"?"Tous canaux":H[e]||e},e))]})]}),t.jsx("div",{className:"flex-1 overflow-y-auto",children:R?t.jsx("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:t.jsx(F,{className:"h-4 w-4 animate-spin"})}):Y.length===0?t.jsx("p",{className:"text-center text-sm text-muted-foreground py-8 px-4",children:"Aucune conversation"}):Y.map(e=>t.jsxs("button",{onClick:()=>M(e.user_id),className:`w-full text-left px-3 py-3 border-b border-border/50 hover:bg-muted/50 transition-colors ${n===e.user_id?"bg-muted":""}`,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 mb-0.5",children:[t.jsx("p",{className:"text-sm font-medium truncate",children:e.full_name||b.get(e.user_id)||e.user_id.slice(0,8)}),e.unread>0?t.jsx(te,{variant:"destructive",className:"h-5 min-w-5 px-1.5 text-[10px]",children:e.unread}):e.last_sender==="admin"?t.jsx(Le,{className:"h-3.5 w-3.5 text-muted-foreground
1/60 shrink-0"}):null]}),b.get(e.user_id)&&t.jsx("p",{className:"text-[11px] text-muted-foreground/80 truncate",children:b.get(e.user_id)}),t.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[e.last_sender==="admin"?"Vous : ":"",e.last_message]}),t.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[t.jsx("p",{className:"text-[10px] text-muted-foreground/70",children:new Date(e.last_at).toLocaleString("fr-FR",{dateStyle:"short",timeStyle:"short"})}),f.get(e.user_id)&&t.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-muted text-muted-foreground",children:H[f.get(e.user_id)]||f.get(e.user_id)})]})]},e.user_id))})]}),t.jsx("div",{className:`flex-1 flex-col ${n?"flex":"hidden md:flex"}`,children:n?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"px-3 md:px-4 py-3 border-b border-border flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx(x,{variant:"ghost",size:"icon",className:"h-8 w-8 md:hidden shrink-0",onClick:()=>M(null),children:t.jsx(Ee,{className:"h-4 w-4"})}),t.jsxs("div",{className:"min-w-0",children:[t.jsx("p",{className:"text-sm font-semibold truncate",children:ee?.full_name||j||n}),t.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:j||n}),f.get(n)&&t.jsxs("span",{className:"inline-flex items-center gap-1 mt-0.5 text-[10px] text-muted-foreground",children:[t.jsx(re,{className:"h-3 w-3"}),H[f.get(n)]||f.get(n)]})]})]}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[j&&t.jsx(x,{variant:"ghost",size:"sm",asChild:!0,children:t.jsx("a",{href:`mailto:${j}`,title:"Répondre par email",children:t.jsx(Ie,{className:"h-4 w-4"})})}),t.jsxs(ge,{children:[t.jsx(ve,{asChild:!0,children:t.jsxs(x,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",children:[t.jsx(Me,{className:"h-4 w-4 md:mr-1.5"}),t.jsx("span",{className:"hidden md:inline",children:"Supprimer"})]})}),t.jsxs(be,{children:[t.jsxs(je,{children:[t.jsx(_e,{children:"Supprimer la conversation ?"}),t.jsxs(Ne,{children:["Tous les messages avec ",ee?.full_name||j||n," seront effacés définitivement."]})]}),t.jsxs(we,{children:[t.jsx(ye,{children:"Annuler"}),t.jsx(Ce,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:async()=>{try{await c(n),v.success("Conversation supprimée"),M(null),q([]),g()}catch(e){v.error(e?.message||"Erreur suppression")}},children:"Supprimer"})]})]})]})]})]}),y.length>0&&t.jsxs("div",{className:"px-3 md:px-4 py-2 border-b border-border bg-muted/30",children:[t.jsxs("button",{onClick:()=>G(e=>!e),className:"flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground",children:[t.jsx(qe,{className:"h-3.5 w-3.5"}),"Marques analysées (",y.length,")",t.jsx("span",{className:"text-muted-foreground/60",children:I?"â²":"â¼"})]}),t.jsx("div",{className:`flex gap-1.5 overflow-x-auto mt-1.5 ${I?"flex-wrap":""}`,children:(I?y:y.slice(0,6)).map(e=>t.jsxs("span",{className:"shrink-0 text-[11px] px-2 py-1 rounded-full bg-background border border-border",children:[e.brand," ",t.jsxs("span",{className:"text-muted-foreground",children:["Ã",e.count]})]},e.brand))})]}),t.jsx("div",{ref:U,className:"flex-1 overflow-y-auto p-3 md:p-4 space-y-3 bg-background",children:ie?t.jsx("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:t.jsx(F,{className:"h-4 w-4 animate-spin"})}):C.length===0?t.jsx("p",{className:"text-center text-sm text-muted-foreground py-8",children:"Aucun message dans cette conversation"}):C.map((e,s)=>{const r=C[s-1],o=!r||new Date(r.created_at).toDateString()!==new Date(e.created_at).toDateString();return t.jsxs("div",{children:[o&&t.jsx("div",{className:"flex justify-center my-3",children:t.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted-foreground bg-muted px-2 py-0.5 rounded-full",children:$e(e.created_at)})}),t.jsx("div",{className:`flex ${e.sender==="admin"?"justify-end":"justify-start"}`,children:t.jsxs("div",{className:`max-w-[85%] md:max-w-[75%] px-3 py-2 rounded-2xl text-sm whitespace-pre-wrap break-words ${e.sender==="admin"?"bg-primary text-primary-foreground rounded-br-sm":"bg-muted text-foreground rounded-bl-sm"}`,children:[e.content,t.jsx("div",{className:`text-[10px] mt-1 opacity-60 ${e.sender==="admin"?"text-right":"text-left"}`,children:new Date(e.created_at).toLocaleTimeString("fr-FR",{hour:"2-digit",minute:"2-digit"})})]})})]},e.id)})}),t.jsx("div",{className:"border-t border-border px-2 pt-2 flex gap-1.5 overflow-x-auto snap-x",children:Ue.map(e=>t.jsxs("div",{className:"shrink-0 snap-start flex items-stretch rounded-full border border-border overflow-hidden",children:[t.jsx("button",{onClick:()=>P(e.text),disabled:S,title:e.text,className:"text-xs px-3 h-9 md:h-8 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors disabled:opacity-50",children:e.label}),t.jsx("button",{onClick:()=>{B(e.text),A.current?.focus()},title:"Modifier avant envoi",className:"px-2 h-9 md:h-8 border-l border-border text-muted-foreground hover:bg-muted hover:text-foreground transition-colors",children:t.jsx(ze,{className:"h-3 w-3"})})]},e.label))}),t.jsxs("div",{className:"p-2 pb-[max(0.5rem,env(safe-area-inset-bottom))] flex items-end gap-2",children:[t.jsx("textarea",{ref:A,value:z,onChange:e=>B(e.target.value),onKeyDown:e=>{e.key==="Enter"&&!e.shiftKey&&window.matchMedia("(min-width: 768px)").matches&&(e.preventDefault(),P())},rows:1,enterKeyHint:"send",placeholder:"Répondreâ¦",className:"flex-1 resize-none rounded-xl bg-background border border-border px-3 py-2.5 text-base md:text-sm focus:outline-none focus:ring-2 focus:ring-primary/40 max-h-32"}),t.jsxs(x,{onClick:()=>P(),disabled:!z.trim()||S,className:"shrink-0 h-11 w-11 md:h-10 md:w-auto md:px-4 roun
1ded-xl",children:[S?t.jsx(F,{className:"h-4 w-4 animate-spin"}):t.jsx(Be,{className:"h-4 w-4 md:mr-1.5"}),t.jsx("span",{className:"hidden md:inline",children:"Répondre"})]})]})]}):t.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-muted-foreground gap-2",children:[t.jsx(se,{className:"h-8 w-8 opacity-50"}),t.jsx("p",{className:"text-sm",children:"Sélectionnez une conversation"})]})})]})}export{Ze as AdminLiveChat};
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.