PageSourceSearch

https://roots-officiel.com/assets/StudioAgentsHub-B_i6WRBy.js

js roots-officiel.com collected 2026-10-09 05:10:04 UTC 90,078 bytes, 86 lines download raw bytes

1import{r as l,s as O,x as k,j as e,q as G,e4 as Ft,D as bt,an as ze,a2 as Te,bx as jt,e5 as Dt,e6 as Bt,bo as yt,a9 as Pt,ar as ve,F as qt,e7 as Ut,ab as ye,B as V,ce as oe,b6 as Ht,e8 as Vt,ap as Gt,cs as Kt,k as Z,du as Jt,e9 as Wt,J as vt,o as Xt,a3 as me,bl as Qt,ea as Yt,l as Nt,bM as wt,aj as Zt,aR as es,af as ts,eb as ss,ec as nt,h as Le,cb as at,dD as rs,d$ as ns,dM as as,ed as ot,G as os,ee as is,ef as ls,eg as cs,eh as ds,ei as it,ej as lt,ek as us,dB as ms,el as ps,em as xs,en as fs}from"./index-BTrKqWIn.js";import{u as gs,S as ct}from"./useFeatureFlag-Co4nbBlZ.js";import{C as hs}from"./card-vCGE_HIz.js";import{M as ae}from"./index-kSwWhv6H.js";import{s as bs}from"./slugify-MIma3QhN.js";import{C as js}from"./article-D0OK-CZ7.js";import{a as Re,A as ys}from"./logbook-agents-CopWL80M.js";function vs(t){return["MISSION — action du journal de bord","",`Titre : ${t.title}`,`Périmètre : ${t.category}`,t.priority?`Priorité : ${t.priority}`:"",t.impact?`Impact : ${t.impact}`:"",typeof t.effort=="number"?`Effort estimé : ${t.effort}/5`:"",t.description?`
2Contexte :
3${t.description}`:"",t.expected_outcome?`
4Résultat attendu :
5${t.expected_outcome}`:"",t.lovable_prompt?`
6Consigne déjà notée :
7${t.lovable_prompt}`:"","","Traite cette mission maintenant, dans ton périmètre et jusqu'au bout de ce que","tu peux faire toi-même. Pour tout ce qui exige une modification du code, de la","base ou de l'infrastructure, termine par le bloc BRIEF LOVABLE prévu par ton","protocole, prêt à être collé tel quel."].filter(Boolean).join(`
8`)}function Ns(t){return["ÉTAT DES LIEUX — action du journal de bord","",`Titre : ${t.title}`,`Périmètre : ${t.category}`,t.description?`
9Ce qui était prévu :
10${t.description}`:"",t.expected_outcome?`
11Résultat attendu :
12${t.expected_outcome}`:"","","Avant toute production : dis-moi où on en est réellement, en te basant sur","l'état actuel du site et de la base (pages existantes, contenus déjà en ligne,","balises et données structurées présentes). Réponds en trois blocs courts :","1) Ce qui est déjà fait — 2) Ce qui manque encore — 3) Ce que tu proposes de","faire maintenant, dans l'ordre. Ne rédige rien tant que je n'ai pas tranché."].filter(Boolean).join(`
13`)}const dt="BRIEF LOVABLE";function ws(t){if(!t)return null;const r=t.toUpperCase().indexOf(dt);if(r===-1)return null;const n=t.slice(r+dt.length),o=n.match(/```(?:[a-zA-Z]*)\n([\s\S]*?)```/),a=(o?o[1]:n).replace(/^[\s:—-]+/,"").trim();return a.length>20?a:null}function Me(t){return`${t.title.trim()}|${t.angle_roots.trim()}`.slice(0,500)}function ut(t){if(!t||typeof t!="object")return null;const n=t.ideas;if(!Array.isArray(n)||n.length===0)return null;const o=[];for(const a of n){if(!a||typeof a!="object")return null;const d=a;if(typeof d.title!="string"||typeof d.angle_roots!="string"||typeof d.accroche_s1!="string"||!Array.isArray(d.matiere_brute))return null;o.push({score:typeof d.score=="number"?d.score:Number(d.score)||0,title:d.title,angle_roots:d.angle_roots,sous_format:typeof d.sous_format=="string"?d.sous_format:"factuel",accroche_s1:d.accroche_s1,matiere_brute:d.matiere_brute.filter(c=>typeof c=="string"),timing:typeof d.timing=="string"?d.timing:"tiede",potentiel:typeof d.potentiel=="string"?d.potentiel:"moyen"})}return{ideas:o}}function Ss(t){const r=t.trim();if(!r)return null;try{return ut(JSON.parse(r))}catch{const n=r.lastIndexOf("}");if(n===-1)return null;try{return ut(JSON.parse(r.slice(0,n+1)))}catch{return null}}}function ks(t){const r=(t||"").replace(/\r/g,"").trim();if(!r)return null;const n="[SCORE";if(!r.includes(n))return null;const o=[];let a=r.indexOf(n);for(;a!==-1;){const i=r.indexOf(n,a+1);o.push(r.slice(a,i===-1?void 0:i).trim()),a=i}const d=["SCORE","TITRE","ANGLE ROOTS","SOUS-FORMAT","ACCROCHE S1","MATIÈRE BRUTE","MATIERE BRUTE","TIMING","POTENTIEL"],c=(i,h)=>{const x=`[${h}`,y=i.indexOf(x);if(y===-1)return null;const f=i.indexOf("]",y);if(f===-1)return null;let p=i.length;for(const w of d){const N=i.indexOf(`[${w}`,f+1);N!==-1&&N<p&&(p=N)}let j=i.slice(f+1,p).trim();for(;j.startsWith("—")||j.startsWith("-")||j.startsWith(":");)j=j.slice(1).trim();if(!j&&h==="SCORE"){const w=i.slice(y+1,f),N=w.indexOf(":");N!==-1&&(j=w.slice(N+1).trim())}return j||null},u=[];for(const i of o){const h=c(i,"SCORE")??"",x=parseInt(h.replace(/[^0-9]/g,""),10),y=c(i,"TITRE"),f=c(i,"ANGLE ROOTS");if(!y||!f)continue;const p=c(i,"MATIÈRE BRUTE")??c(i,"MATIERE BRUTE")??"",j=p.split(/\n+|(?:^|\s)[•\-–]\s+/).map(w=>
13w.trim()).filter(Boolean);u.push({score:Number.isFinite(x)?x:0,title:y,angle_roots:f,sous_format:c(i,"SOUS-FORMAT")??"factuel",accroche_s1:c(i,"ACCROCHE S1")??"",matiere_brute:j.length?j:p?[p]:[],timing:c(i,"TIMING")??"tiede",potentiel:c(i,"POTENTIEL")??"moyen"})}return u.length?{ideas:u}:null}async function Es(t,r,n){var x,y,f,p;const{data:o}=await O.auth.getSession(),a=(x=o.session)==null?void 0:x.access_token,c=await fetch("https://eptqkkfulwbkswjinqaz.supabase.co/functions/v1/agent-sourceur-inline",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({action:t,idea:r})});if(!c.ok||!c.body){const j=await c.text().catch(()=>"");throw new Error(j||`HTTP ${c.status}`)}const u=c.body.getReader(),i=new TextDecoder;let h="";for(;;){const{done:j,value:w}=await u.read();if(j)break;h+=i.decode(w,{stream:!0});const N=h.split(`
14`);h=N.pop()||"";for(const I of N){const F=I.trim();if(!F.startsWith("data:"))continue;const T=F.slice(5).trim();if(!(!T||T==="[DONE]"))try{const b=(p=(f=(y=JSON.parse(T).choices)==null?void 0:y[0])==null?void 0:f.delta)==null?void 0:p.content;b&&n(b)}catch{}}}}const Cs={challenger:"Angle challengé",approfondir:"Matière brute enrichie",reformuler:"Variantes de titre + accroche"};function Ts({idea:t,isInDossier:r,onArchive:n,onSentToRedacteur:o,onAddedToDossier:a,onInlineExtra:d,onExpand:c}){const[u,i]=l.useState(null),[h,x]=l.useState(!1),[y,f]=l.useState(!1),[p,j]=l.useState(!1),[w,N]=l.useState(""),[I,F]=l.useState(!1),[T,L]=l.useState([]);l.useEffect(()=>{!I||T.length>0||O.from("projects").select("id, title, status, updated_at").neq("status","archived").order("updated_at",{ascending:!1}).limit(50).then(({data:A,error:z})=>{if(z){k.error("Impossible de charger les dossiers");return}L((A??[]).map(C=>({id:C.id,title:C.title??"Sans titre"})))})},[I,T.length]);const b=l.useCallback(async A=>{if(u)return;i(A),c();const z=Cs[A];d(z,"",!0);let C="";try{await Es(A,t,U=>{C+=U,d(z,C,!0)}),d(z,C||"(vide)",!1)}catch(U){const W=U instanceof Error?U.message:"Erreur";d(z,`⚠️ ${W}`,!1),k.error(W)}finally{i(null)}},[u,t,c,d]),R=l.useCallback(async()=>{var A;if(!(u||h)){i("redacteur");try{const{data:z}=await O.auth.getSession(),C=(A=z.session)==null?void 0:A.access_token,W=await fetch("https://eptqkkfulwbkswjinqaz.supabase.co/functions/v1/agent-sourceur-fiche",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C}`},body:JSON.stringify({idea:t})}),ee=await W.json();if(!W.ok)throw new Error((ee==null?void 0:ee.error)||`HTTP ${W.status}`);x(!0),k.success(ee.deduped?"Déjà envoyé au Rédacteur":"Envoyé au Rédacteur"),o()}catch(z){k.error(z instanceof Error?z.message:"Erreur")}finally{i(null)}}},[u,h,t,o]),S=l.useCallback(async()=>{const A=w.trim();if(!(!A||u)){i("newFolder");try{const z=Me(t),{data:C,error:U}=await O.from("projects").insert({title:A,status:"active",source_agent:"sourceur",source_idea:z,mode:"default",sort_order:0}).select("id").single();if(U)throw U;await O.from("project_steps").insert({project_id:C.id,agent:"sourceur",step_type:"idea",content:`${t.title}
15
16${t.angle_roots}`}),k.success(`Dossier "${A}" créé`),j(!1),N(""),a()}catch(z){k.error(z instanceof Error?z.message:"Erreur création dossier")}finally{i(null)}}}
16,[w,u,t,a]),_=l.useCallback(async(A,z)=>{if(!u){i("addFolder");try{await O.from("project_steps").insert({project_id:A,agent:"sourceur",step_type:"idea",content:`${t.title}
17
18${t.angle_roots}`}),k.success(`Ajouté à "${z}"`),F(!1),a()}catch(C){k.error(C instanceof Error?C.message:"Erreur")}finally{i(null)}}},[u,t,a]),P=l.useCallback(async()=>{if(!(u||y)){i("archive");try{const A=Me(t),{error:z}=await O.from("content_drafts").insert([{agent:"sourceur",title:t.title.slice(0,200),content:`${t.angle_roots}
19
20Matière brute :
21${(t.matiere_brute||[]).map(C=>`- ${C}`).join(`
22`)}`,status:"wishlist",source_agent:"sourceur",source_idea:A,metadata:{idea:t}}]);if(z&&z.code!=="23505")throw z;f(!0),k.success("Archivé chez l'Archiviste"),setTimeout(()=>n(),3e3)}catch(A){k.error(A instanceof Error?A.message:"Erreur archive")}finally{i(null)}}},[u,y,t,n]),M="text-[10px] sm:text-[11px] px-2.5 py-1.5 rounded-lg border border-border bg-card hover:bg-secondary/40 transition inline-flex items-center gap-1 disabled:opacity-50",K="border-green-500/40 text-green-600 hover:bg-green-500/5";return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 sm:gap-2",children:[e.jsxs("button",{className:M,disabled:!!u,onClick:()=>b("challenger"),children:[u==="challenger"?e.jsx(G,{size:11,className:"animate-spin"}):e.jsx(Ft,{size:11}),"Challenger"]}),e.jsxs("button",{className:M,disabled:!!u,onClick:()=>b("approfondir"),children:[u==="approfondir"?e.jsx(G,{size:11,className:"animate-spin"}):e.jsx(bt,{size:11}),"Approfondir"]}),e.jsxs("button",{className:M,disabled:!!u,onClick:()=>b("reformuler"),children:[u==="reformuler"?e.jsx(G,{size:11,className:"animate-spin"}):e.jsx(ze,{size:11}),"Reformuler"]}),e.jsxs("button",{className:`${M} ${h?K:""}`,disabled:!!u||h,onClick:R,children:[u==="redacteur"?e.jsx(G,{size:11,className:"animate-spin"}):h?e.jsx(Te,{size:11}):e.jsx(jt,{size:11}),h?"Envoyé":"Envoyer au Rédacteur"]}),e.jsxs("button",{className:M,disabled:!!u,onClick:()=>{j(A=>!A),F(!1)},children:[e.jsx(Dt,{size:11}),"Nouveau dossier"]}),e.jsxs("button",{className:M,disabled:!!u,onClick:()=>{F(A=>!A),j(!1)},children:[e.jsx(Bt,{size:11}),"Ajouter à un dossier"]}),e.jsxs("button",{className:`${M} ${y?K:""}`,disabled:!!u||y,onClick:P,children:[u==="archive"?e.jsx(G,{size:11,className:"animate-spin"}):y?e.jsx(Te,{size:11}):e.jsx(yt,{size:11}),y?"Archivé":"Archiver"]})]}),r&&e.jsx("div",{className:"text-[10px] text-green-600 dark:text-green-400",children:"Déjà présent dans un dossier — les nouvelles actions viendront s'ajouter."}),p&&e.jsxs("div",{className:"flex gap-1.5 items-center pt-1",children:[e.jsx("input",{autoFocus:!0,value:w,onChange:A=>N(A.target.value),onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),S()),A.key==="Escape"&&(j(!1),N(""))},placeholder:"Nom du dossier principal…",className:"flex-1 text-[12px] px-2 py-1.5 rounded-md border border-border bg-background focus:outline-none focus:ring-1 focus:ring-primary"}),e.jsxs("button",{onClick:S,disabled:!w.trim()||u==="newFolder",className:"text-[11px] px-2.5 py-1.5 rounded-md bg-primary text-primary-foreground disabled:opacity-50 inline-flex items-center gap-1",children:[u==="newFolder"?e.jsx(G,{size:11,className:"animate-spin"}):e.jsx(Te,{size:11}),"Créer"]}),e.jsx("button",{onClick:()=>{j(!1),N("")},className:"text-[11px] px-2 py-1.5 rounded-md border border-border",children:"✕"})]}),I&&e.jsx("div",{className:"pt-1",children:e.jsxs("div",{className:"max-h-[220px] overflow-y-auto rounded-lg border border-border/60 bg-card divide-y divide-border/40",children:[T.length===0&&e.jsx("div",{className:"text-[11px] text-muted-foreground px-3 py-2",children:"Aucun dossier sur le bureau"}),T.map(A=>e.jsx("button",{onClick:()=>_(A.id,A.title),disabled:u==="addFolder",className:"w-full text-left text-[12px] px-3 py-2 hover:bg-secondary/40 disabled:opacity-50",children:A.title},A.id))]})})]})}function Rs(){const[t,r]=l.useState(new Map),[n,o]=l.useState(!0),a=l.useCallback(async()=>{o(!0);const{data:c,error:u}=await O.from("projects").select("id, title, source_idea, source_agent, status").eq("source_agent","sourceur").neq("status","archived").limit(500);if(u){console.error("useSourceurDossiers",u),o(!1);return}const i=new Map;for(const h of c??[]){const x=h.source_idea??"";x&&i.set(x,{projectId:h.id,projectTitle:h.title??"Sans titre"})}r(i),o(!1)},[]);return l.useEffect(()=>{a()},[a]),{matchFor:l.useCallback(c=>t.get(Me(c)),[t]),refresh:a,loading:n}}function As(t){return t>=80?"bg-gradient-to-br from-emerald-500 to-green-600 text-white shadow-lg shadow-emerald-500/30":t>=50?"bg-gradient-to-br from-amber-400 to-orange-500 text-white shadow-lg shadow-amber-500/30":"bg-gradient-to-br from-slate-400 to-slate-500 text-white"}function _s(t){return t>=80?"Priorité haute":t>=50?"À considérer":"Secondaire"}const mt={chaud:{icon:qt,label:"Chaud",cls:"bg-red-500/10 text-red-600 border-red-500/30 dark:text-red-400"},tiede:{icon:bt,label:"Tiède",cls:"bg-amber-500/10 text-amber-600 border-amber-500/30 dark:text-amber-400"},froid:{icon:Ut,label:"Froid",cls:"bg-sky-500/10 text-sky-600 border-sky-500/30 dark:text-sky-400"}},pt={eleve:{label:"Potentiel élevé",cls:"bg-emerald-500/10 text-emerald-600 border-emerald-500/30 dark:text-emerald-400"},moyen:{label:"Potentiel moyen",cls:"bg-slate-500/10 text-slate-600 border-slate-500/30 dark:text-slate-300"},faible:{label:"Potentiel faible",cls:"bg-muted text-muted-foreground border-border"}};function xt(t){return t.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").split(/[^a-z]/)[0]||""}const $s=[{key:"angle_roots",label:"Angle ROOTS",type:"text",accent:"border-l-primary bg-primary/5",color:"text-primary"},{key:"accroche_s1",label:"Accroche · Slide 1",type:"text",accent:"border-l-fuchsia-500 bg-fuchsia-500/5",color:"text-fuchsia-600 dark:text-fuchsia-400"},{key:"matiere_brute",label:"Matière brute",type:"list",accent:"border-l-amber-500 bg-amber-500/5",color:"text-amber-700 dark:text-amber-400"},{key:"sous_format",label:"Sous-format",type:"text",accent:"border-l-sky-500 bg-sky-500/5",color:"text-sky-700 dark:text-sky-400"}];function Is({raw:t,isStreaming:r}){const n=l.useMemo(()=>Ss(t)??ks(t),[t]),[o,a]=l.useState(null),[d,c]=l.useState(new Set),[u,i]=l.useState({}),{matchFor:h,refresh:x}=Rs();if(l.useEffect(()=>{!r&&n&&x()},[r,n,x]),!n)return r?e.jsxs("div",{className:"flex items-center gap-2 text-[13px] text-muted-foreground",children:[e.jsx(G,{size:14,className:"animate-spin"}),"Le Sourceur assemble ses angles…"]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[12px] text-yellow-700 dark:text-yellow-500 bg-yellow-500/10 border border-yellow-500/30 rounded-lg px-3 py-2",children:"Réponse non conforme au format attendu. Affichage brut :"}),e.jsx("div",{className:"prose prose-sm max-w-none dark:prose-invert whitespace-pre-wrap",children:e.jsx(ae,{children:t})})]});const y=n.ideas.map((f,p)=>({idea:f,i:p,fp:`${f.title}|${f.angle_roots}`})).filter(({fp:f})=>!d.has(f));return e.jsx("div",{className:"space-y-3",children:y.map(({idea:f,i:p,fp:j})=>{const w=o===p,N=h(f),I=!!N,F=u[j],T=xt(String(f.timing)),L=xt(String(f.potentiel)),b=mt[T]??mt.tiede,R=pt[L]??pt.moyen,S=b.icon;return e.jsxs("div",{className:`rounded-2xl overflow-hidden bg-card border shadow-sm transition ${I?"border-2 border-emerald-500/40 ring-1 ring-emerald-500/10 bg-emerald-500/[0.03]":"border-border/70 hover:border-border"}`,children:[e.jsxs("button",{type:"button",onClick:()=>
22a(w?null:p),className:"w-full text-left px-4 py-4 flex items-start gap-4 hover:bg-secondary/30 transition",children:[e.jsxs("div",{className:"shrink-0 flex flex-col items-center gap-1",children:[e.jsxs("div",{className:`w-14 h-14 rounded-2xl flex flex-col items-center justify-center font-bold ${As(f.score)}`,children:[e.jsx("span",{className:"text-[18px] leading-none",children:f.score}),e.jsx("span",{className:"text-[8px] uppercase tracking-widest opacity-80 mt-0.5",children:"/100"})]}),e.jsx("span",{className:"text-[9px] font-semibold uppercase tracking-wider text-muted-foreground text-center leading-tight",children:_s(f.score)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start gap-2 flex-wrap",children:[e.jsx("h3",{className:`text-[16px] font-bold leading-snug flex-1 ${I?"text-emerald-700 dark:text-emerald-400":"text-foreground"}`,children:f.title}),I&&N&&e.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-emerald-500/15 text-emerald-700 dark:text-emerald-400 border border-emerald-500/30 font-medium",children:["✓ Dans « ",N.projectTitle," »"]})]}),e.jsxs("div",{className:"mt-2 pl-3 border-l-2 border-primary/60",children:[e.jsx("p",{className:"text-[11px] font-bold uppercase tracking-wider text-primary/80 mb-0.5",children:"Angle ROOTS"}),e.jsx("p",{className:"text-[13px] text-foreground/90 line-clamp-2 leading-snug",children:f.angle_roots})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-2.5 flex-wrap",children:[e.jsxs("span",{className:`inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-full border ${b.cls}`,children:[e.jsx(S,{size:10}),b.label]}),e.jsxs("span",{className:`inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-full border ${R.cls}`,children:[e.jsx(Pt,{size:10}),R.label]}),f.sous_format&&e.jsx("span",{className:"text-[10px] font-semibold px-2 py-0.5 rounded-full border border-border bg-secondary/50 text-muted-foreground capitalize",children:String(f.sous_format)}),e.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 text-[10px] text-muted-foreground",children:[e.jsx(ve,{size:12,className:`transition-transform ${w?"rotate-180":""}`}),w?"Réduire":"Voir le détail"]})]})]})]}),w&&e.jsx("div",{className:"px-4 pb-4 pt-1 space-y-2 border-t border-border/50 bg-secondary/10",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2 pt-3",children:[$s.map(_=>{const P=f[_.key];return P==null||P===""||Array.isArray(P)&&P.length===0?null:e.jsxs("div",{className:`rounded-lg border-l-4 pl-3 pr-3 py-2.5 ${_.accent}`,children:[e.jsx("p",{className:`text-[10px] font-bold uppercase tracking-wider mb-1 ${_.color}`,children:_.label}),_.type==="list"&&Array.isArray(P)?e.jsx("ul",{className:"text-[12.5px] text-foreground space-y-1 leading-relaxed",children:P.map((M,K)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:`shrink-0 ${_.color}`,children:"›"}),e.jsx("span",{children:M})]},K))}):e.jsx("p",{className:"text-[12.5px] text-foreground whitespace-pre-wrap leading-relaxed",children:String(P)})]},_.key)}),F&&e.jsxs("div",{className:"md:col-span-2 rounded-lg border-l-4 border-l-accent bg-accent/10 pl-3 pr-3 py-2.5",children:[e.jsxs("p",{className:"text-[10px] font-bold uppercase tracking-wider text-accent inline-flex items-center gap-1 mb-1",children:[F.loading&&e.jsx(G,{size:11,className:"animate-spin"}),F.label]}),e.jsx("div",{className:"text-[12.5px] text-foreground whitespace-pre-wrap leading-relaxed",children:F.text||(F.loading?"…":"")})]})]})}),e.jsx("div",{className:"px-4 py-3 border-t border-border/50 bg-card",children:e.jsx(Ts,{idea:f,isInDossier:I,onArchive:()=>c(_=>new Set(_).add(j)),onSentToRedacteur:()=>x(),onAddedToDossier:()=>x(),onInlineExtra:(_,P,M)=>i(K=>({...K,[j]:{label:_,text:P,loading:M}})),onExpand:()=>a(p)})})]},j)})})}const Os={metaTitle:"",metaDescription:"",h1:"",slug:"",shortAnswer:"",keywords:[]};function Fe(t){const r=t.search(/(?:^|\n)\s*(?:#{1,3}\s*)?(?:\*\*)?(?:MISSION\s*[—–-]|MISSION\s*:|Compte de mots r[ée]el|Identifiant du brouillon|CE QUE JE FAIS|BRIEF LOVABLE)/i);return r>0?t.slice(0,r).trim():t.trim()}function St(t){const r={...Os,keywords:[]},n=[];for(const a of t.split(`
23`)){const d=a.replace(/\*\*/g,"").replace(/`/g,"").trim();let c;if(c=d.match(/^(?:balise\s*)?<?\s*title\s*>?\s*(?:seo)?\s*:\s*(.+)$/i)){r.metaTitle=c[1].trim();continue}
23if(c=d.match(/^(?:meta[\s-]*(?:description|desc))\s*:\s*(.+)$/i)){r.metaDescription=c[1].trim();continue}if(c=d.match(/^h1\s*:\s*(.+)$/i)){r.h1=c[1].trim();continue}if(c=d.match(/^(?:slug|url)\s*:\s*(.+)$/i)){r.slug=c[1].trim().replace(/^\/+|\/+$/g,"").split("/").pop()||"";continue}if(c=d.match(/^(?:mots?[\s-]*cl[ée]s?|keywords?)\s*:\s*(.+)$/i)){r.keywords=c[1].split(/[,;]/).map(u=>u.trim()).filter(Boolean);continue}if(c=d.match(/^(?:r[ée]ponse\s+(?:courte|citable)|chap[oô]|extrait)\s*:\s*(.+)$/i)){r.shortAnswer=c[1].trim();continue}n.push(a)}const o=n.join(`
24`).replace(/\n{3,}/g,`
25
26`).trim();if(!r.shortAnswer){const a=o.split(/\n{2,}/).map(d=>d.trim()).find(d=>d&&!/^[#>*\-|]/.test(d));a&&(r.shortAnswer=a.replace(/[*`]/g,"").trim())}return{seo:r,body:o}}function Ls(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function ge(t){let r=Ls(t.trim());return r=r.replace(/`([^`]+)`/g,"$1"),r=r.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g,'<a href="$2">$1</a>'),r=r.replace(/\[([^\]]+)\]\((?:link|url|#)?\)/gi,"$1"),r=r.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),r=r.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g,"$1<em>$2</em>"),r=r.replace(/(^|\s)_([^_\n]+)_(?=\s|$)/g,"$1<em>$2</em>"),r}function Ms(t){const r=Fe(t).split(`
27`),n=[];let o=[],a=null;const d=()=>{o.length&&(n.push(`<p>${o.map(ge).join("<br/>")}</p>`),o=[])},c=()=>{if(!a)return;const i=a.ordered?"ol":"ul",h=a.items.filter(x=>x.trim().length>0);h.length&&n.push(`<${i}>${h.map(x=>`<li>${ge(x)}</li>`).join("")}</${i}>`),a=null},u=()=>{d(),c()};for(const i of r){const x=i.replace(/\s+$/,"").trim();if(!x){u();continue}if(/^(-{3,}|\*{3,}|_{3,})$/.test(x)){u(),n.push("<hr/>");continue}const y=x.match(/^(#{1,6})\s+(.*)$/);if(y){u();const w=y[1].length<=2?2:3;n.push(`<h${w}>${ge(y[2].replace(/#+\s*$/,""))}</h${w}>`);continue}const f=x.match(/^[-*•]\s+(.*)$/);if(f){d(),(!a||a.ordered)&&(c(),a={ordered:!1,items:[]}),a.items.push(f[1]);continue}const p=x.match(/^\d+[.)]\s+(.*)$/);if(p){d(),(!a||!a.ordered)&&(c(),a={ordered:!0,items:[]}),a.items.push(p[1]);continue}const j=x.match(/^>\s?(.*)$/);if(j){u(),n.push(`<blockquote><p>${ge(j[1])}</p></blockquote>`);continue}if(a){a.items[a.items.length-1]+=` ${x}`;continue}o.push(x)}return u(),n.join(`
28`)}function kt(t){var N,I,F,T,L,b;if(!t)return null;const r=t.match(/(?:^|\n)\s*(?:={2,}\s*)?(?:#{1,3}\s*)?(?:\*\*)?ARTICLE(?:\*\*)?\s*(?:={2,})?\s*(?:\n|$)/i),n=t.match(/(?:^|\n)\s*(?:#{1,3}\s*)?(?:\*\*)?(?:PHASE\s*2\s*[—–:-]\s*)?R[ÉE]DACTION\s+D[ÉE]FINITIVE(?:\*\*)?\s*(?:\n|$)/i),o=/(?:^|\n)\s*(?:\*\*)?TITRE\s*(?:\*\*)?\s*:/i.test(t);if(!r&&!n&&!o)return null;const a=r??n,d=a?t.slice((a.index??0)+a[0].length):t,c=Fe(d),u=((I=(N=c.match(/(?:^|\n)\s*(?:\*\*)?TITRE(?:\*\*)?\s*:\s*(.+)/i))==null?void 0:N[1])==null?void 0:I.trim())??"",i=((T=(F=c.match(/(?:^|\n)\s*#{1,3}\s+(.+)/))==null?void 0:F[1])==null?void 0:T.trim())??"",h=((b=(L=c.match(/(?:^|\n)\s*(?:\*\*)?CHAPO(?:\*\*)?\s*:\s*([\s\S]*?)(?=\n\s*(?:\*\*)?CONTENU|\n{2,}#|$)/i))==null?void 0:L[1])==null?void 0:b.trim())??"",x=c.match(/(?:^|\n)\s*(?:\*\*)?CONTENU(?:\*\*)?\s*:\s*([\s\S]*)/i),y=((x==null?void 0:x[1])??(i?c.replace(/(?:^|\n)\s*#{1,3}\s+.+(?:\n|$)/,`
29`):c)).trim(),{seo:f,body:p}=St(y),j=(u||f.h1||i).replace(/\*\*/g,"").trim(),w=(h||f.shortAnswer).replace(/\*\*/g,"").replace(/`/g,"").trim();return!j&&p.length<200?null:{titre:j||"Article sans titre",chapo:w,contenu:p,seo:f}}function zs(t){const r=kt(t);if(r)return r;if(!t)return null;const n=Fe(t.trim());if(n.split(/\s+/).filter(Boolean).length<250)return null;const o=n.split(`
30`),a=o.findIndex(h=>/^#{1,3}\s+\S/.test(h)),d=a===-1?n:o.slice(a+1).join(`
31`).trim(),{seo:c,body:u}=St(d),i=c.h1||(a===-1?"":o[a].replace(/^#{1,3}\s+/,"").replace(/\*\*/g,"").trim());return u.length<200?null:{titre:i||"Article sans titre",chapo:c.shortAnswer,contenu:u,seo:c}}const ft=Ms;function Fs(t){return`${t.titre}
32
33${t.chapo}
34
35${t.contenu}`}function Ae({text:t,onRework:r}){const[n,o]=l.useState(!1),[a,d]=l.useState(""),c=/^#{1,3}\s/.test(t),u=()=>{!a.trim()||!r||(r(t,a.trim()),o(!1),d(""))};return e.jsxs("div",{className:"group/passage relative -mx-3 px-3 rounded-lg hover:bg-muted/40 transition-colors",children:[e.jsx("div",{className:Z("prose prose-sm dark:prose-invert max-w-none","prose-p:my-3 prose-p:leading-[1.85] prose-p:text-[15px]","prose-headings:font-bold prose-h2:text-[17px] prose-h2:mt-6 prose-h2:mb-2 prose-h3:text-[15px]","prose-li:my-1.5 prose-strong:text-foreground"),children:e.jsx(ae,{children:t})}),e.jsxs("div",{className:"absolute right-1 top-1 flex items-center gap-1 opacity-0 group-hover/passage:opacity-100 transition-opacity",children:[e.jsx("button",{type:"button",title:"Copier ce passage",onClick:()=>{navigator.clipboard.writeText(t),k.success("Passage copié")},className:"h-6 w-6 rounded-md bg-card border border-border flex items-center justify-center text-muted-foreground hover:text-foreground",children:e.jsx(oe,{size:11})}),r&&e.jsx("button",{type:"button",title:"Retravailler uniquement ce passage",onClick:()=>o(i=>
35!i),className:"h-6 w-6 rounded-md bg-card border border-border flex items-center justify-center text-muted-foreground hover:text-foreground",children:e.jsx(ze,{size:11})})]}),n&&e.jsxs("div",{className:"my-2 flex gap-2",children:[e.jsx("input",{autoFocus:!0,value:a,onChange:i=>d(i.target.value),onKeyDown:i=>{i.key==="Enter"&&(i.preventDefault(),u())},placeholder:c?"Ex : titre plus corrosif…":"Ex : coupe la dernière phrase, garde le reste…",className:"flex-1 text-[12px] px-3 py-2 rounded-lg border border-border bg-background focus:outline-none focus:ring-1 focus:ring-primary/30"}),e.jsx(V,{size:"sm",className:"h-8 text-[11px]",onClick:u,children:"Retoucher"})]})]})}function Ds({article:t,onSend:r}){const[n,o]=l.useState(!1),[a,d]=l.useState(null),[c,u]=l.useState("analyse"),i=l.useMemo(()=>t.contenu.split(/\s+/).filter(Boolean).length,[t.contenu]),h=l.useMemo(()=>t.contenu.split(/\n{2,}/).map(f=>f.trim()).filter(Boolean),[t.contenu]),x=r?(f,p)=>{r(`RETOUCHE CIBLÉE — ne réécris pas l'article.
36
37Passage concerné :
38"""
39${f}
40"""
41
42Instruction : ${p}
43
44Réponds uniquement avec la nouvelle version de ce passage, rien d'autre. Ne change ni le titre, ni la structure, ni les autres paragraphes.`)}:void 0,y=async()=>{var f;o(!0);try{const p=t.seo,j=bs((p==null?void 0:p.slug)||t.titre)||`article-${Date.now()}`;let w=j;const{data:N}=await O.from("articles").select("slug").eq("slug",j).maybeSingle();N&&(w=`${j}-${Date.now().toString().slice(-5)}`);const I=ft(t.contenu);if(!I.trim())throw new Error("Contenu vide : impossible de créer le brouillon");const F=Math.max(1,Math.round(i/220)),T=(t.chapo||(p==null?void 0:p.shortAnswer)||"").trim(),{data:L,error:b}=await O.from("articles").insert({title:t.titre,slug:w,excerpt:T||null,content:I,category:c,author:"ROOTS",read_time:F,meta_title:((p==null?void 0:p.metaTitle)||t.titre).slice(0,60),meta_description:((p==null?void 0:p.metaDescription)||T).slice(0,155)||null,tags:(f=p==null?void 0:p.keywords)!=null&&f.length?p.keywords.slice(0,8):null,is_published:!1}).select("id").single();if(b)throw b;d(L.id),k.success("Brouillon prérempli dans Articles (titre, chapô, HTML, SEO)")}catch(p){k.error(p instanceof Error?p.message:"Échec de l'enregistrement")}finally{o(!1)}};return e.jsxs("div",{className:"my-4 rounded-2xl border border-border bg-card overflow-hidden",children:[e.jsxs("div",{className:"sticky top-0 z-10 flex flex-wrap items-center gap-1.5 px-5 py-3 border-b border-border bg-card/95 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:[e.jsx(ye,{size:15,className:"text-primary"}),e.jsx("span",{className:"text-[12px] font-bold uppercase tracking-wider text-muted-foreground",children:"Article"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["· ",i," mots"]}),e.jsxs("div",{className:"ml-auto flex flex-wrap items-center gap-1",children:[e.jsxs(V,{variant:"ghost",size:"sm",className:"h-7 text-[11px] gap-1.5",onClick:()=>{navigator.clipboard.writeText(Fs(t)),k.success("Article copié")},children:[e.jsx(oe,{size:12})," Tout copier"]}),e.jsxs(V,{variant:"ghost",size:"sm",className:"h-7 text-[11px] gap-1.5",onClick:()=>{navigator.clipboard.writeText(t.titre),k.success("Titre copié")},children:[e.jsx(Ht,{size:12})," Titre"]}),e.jsxs(V,{variant:"ghost",size:"sm",className:"h-7 text-[11px] gap-1.5",onClick:()=>{navigator.clipboard.writeText(ft(t.contenu)),k.success("HTML copié")},children:[e.jsx(Vt,{size:12})," HTML"]}),a?e.jsxs("a",{href:`/admin?section=articles&edit=${a}`,className:"inline-flex items-center gap-1.5 h-7 px-3 rounded-lg bg-emerald-500/15 text-emerald-600 text-[11px] font-semibold",children:[e.jsx(Gt,{size:12})," Ouvrir dans Articles"]}):e.jsxs(e.Fragment,{children:[e.jsxs("select",{value:c,onChange:f=>u(f.target.value),className:"h-7 text-[11px] px-2 rounded-lg border border-border bg-background","aria-label":"Catégorie du brouillon",children:[js.filter(f=>f.slug!=="all").map(f=>e.jsx("option",{value:f.slug,children:f.name},f.slug)),e.jsx("option",{value:"religion",children:"Religion"})]}),e.jsxs(V,{size:"sm",className:"h-7 text-[11px] gap-1.5",onClick:y,disabled:n,children:[n?e.jsx(G,{size:12,className:"animate-spin"}):e.jsx(Kt,{size:12}),"Créer le brouillon"]})]})]})]}),e.jsxs("div",{className:"px-5 py-6",children:[e.jsxs("div",{className:"mx-auto max-w-[70ch]",children:[e.jsx(Ae,{text:`# ${t.titre}`,onRework:x}),t.chapo&&e.jsx("div",{className:"mt-1 mb-4 border-l-2 border-primary/40 pl-4",children:e.jsx(Ae,{text:`*${t.chapo}*`,onRework:x})}),e.jsx("div",{className:"mt-4 space-y-1",children:h.map((f,p)=>e.jsx(Ae,{text:f,onRework:x},p))})]}),r&&e.jsxs("div",{className:"mx-auto max-w-[70ch] mt-6 pt-4 border-t border-border/50 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Survole un paragraphe pour le copier ou le retoucher seul."}),e.jsx("button",{type:"button",onClick:()=>r("Propose 3 variantes de titre pour cet article, sans toucher au corps du texte."),className:"ml-auto text-[11px] text-muted-foreground hover:text-foreground underline underline-offset-2",children:"3 variantes de titre"})]})]})]})}function Bs(t){const r=t.match(/\[FICHE SUJET\]([\s\S]*?)\[\/FICHE SUJET\]/i);if(!r)return null;const n=r[1],o=d=>{const c=n.match(new RegExp(`${d}\\s*:\\s*(.+?)(?=\\n[A-Z_]+\\s*:|$)`,"is"));return c?c[1].trim():""},a=o("TITRE");return a?{titre:a,angle_roots:o("ANGLE_ROOTS"),format:o("FORMAT")||"carrousel",sous_format:o("SOUS_FORMAT")||"factuel",nb_slides:parseInt(o("NB_SLIDES"))||9,arc:o("ARC"),accroche_s1:o("ACCROCHE_S1"),matiere_brute:o("MATIERE_BRUTE"),limite_editoriale:o("LIMITE_EDITORIALE")}:null}function Ps(t){const r=/\[APPROCHE \d+\]\s*TITRE:\s*(.+?)\s*DESCRIPTION:\s*([\s\S]*?)\[\/APPROCHE\]/gi,n=[];let o;for(;(o=r.exec(t))!==null;)n.push({titre:o[1].trim(),description:o[2].trim()});return n}function qs(t){return t.replace(/\[APPROCHES\][\s\S]*?\[\/APPROCHES\]/gi,"").trim()}function Us(t){const r=/\[SLIDE (\d+)\s*[—–-]\s*([^\]]+)\]\s*TEXTE\s*:\s*([\s\S]*?)NOTE GRAPHISTE\s*:\s*([\s\S]*?)(?=\[SLIDE|\s*$)/gi,n=[];let o;for(;(o=r.exec(t))!==null;){const a=o[3].trim();n.push({num:parseInt(o[1]),nom:o[2].trim(),texte:a,noteGraphiste:o[4].trim(),wordCount:a.split(/\s+/).filter(
44Boolean).length})}return n}function Hs(t){var c,u,i;const r=t.match(/VERDICT GLOBAL\s*:\s*(APPROUVÉ|À RETRAVAILLER|REJETÉ)/i);if(!r)return null;const n=t.match(/SYNTHÈSE\s*:\s*(.+?)(?=\[SLIDE|\n\n)/is),o=/\[SLIDE (\d+)\s*[—–-]?\s*([^\]]*)\]\s*STATUT\s*:\s*(OK ✓|À RETRAVAILLER ↻|À SUPPRIMER ✗)\s*(?:PROBLÈME\s*:\s*(.*?))?\s*(?:REFORMULATION\s*:\s*(.*?))?(?=\[SLIDE|$)/gis,a=[];let d;for(;(d=o.exec(t))!==null;)a.push({num:parseInt(d[1]),nom:((c=d[2])==null?void 0:c.trim())||"",statut:d[3].trim(),probleme:((u=d[4])==null?void 0:u.trim())||null,reformulation:((i=d[5])==null?void 0:i.trim())||null});return{global:r[1],synthese:(n==null?void 0:n[1].trim())||"",slides:a}}function Vs(t){return t<=30?"ok":t<=35?"warning":"danger"}function ne({label:t,value:r,accent:n}){return e.jsxs("div",{className:"py-2.5 border-t border-border/40 first:border-t-0",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1",children:t}),e.jsx("p",{className:Z("text-[13px] leading-relaxed text-foreground",n==="danger"&&"text-destructive",n==="italic"&&"italic"),children:r})]})}function ue({fiche:t}){const[r,n]=l.useState(!0);return e.jsxs("div",{className:"mb-5 rounded-2xl border border-border bg-card overflow-hidden",children:[e.jsxs("button",{onClick:()=>n(!r),className:"w-full flex items-start justify-between gap-3 px-5 py-4 text-left hover:bg-muted/40 transition-colors",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx(ye,{size:13,className:"text-primary shrink-0"}),e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-muted-foreground",children:"Brief éditorial"}),e.jsxs("span",{className:"text-[9px] font-medium px-2 py-0.5 rounded-full bg-secondary text-muted-foreground",children:[t.format," · ",t.sous_format]})]}),e.jsx("p",{className:"text-[15px] font-bold leading-snug text-foreground",children:t.titre})]}),e.jsx(ve,{size:14,className:Z("mt-1 text-muted-foreground shrink-0 transition-transform",r&&"rotate-180")})]}),r&&e.jsxs("div",{className:"px-5 pb-4 max-w-[70ch]",children:[e.jsx(ne,{label:"Angle ROOTS",value:t.angle_roots}),e.jsx(ne,{label:"Arc narratif",value:t.arc}),e.jsx(ne,{label:"Accroche",value:t.accroche_s1,accent:"italic"}),t.matiere_brute&&e.jsx(ne,{label:"Matière brute",value:t.matiere_brute}),t.nb_slides&&e.jsx(ne,{label:"Volume",value:`${t.nb_slides} slides`}),t.limite_editoriale&&e.jsx(ne,{label:"⚠️ Limite éditoriale",value:t.limite_editoriale,accent:"danger"})]})]})}function Gs({approches:t,onSelect:r}){return e.jsxs("div",{className:"space-y-3 my-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"w-5 h-5 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx("span",{className:"text-[10px] font-bold text-primary",children:"1"})}),e.jsx("p",{className:"text-[12px] font-semibold text-foreground",children:"Choisis ton approche"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"— sélectionne pour lancer le squelette"})]}),e.jsx("div",{className:"grid gap-3",children:t.map((n,o)=>e.jsxs("div",{className:"rounded-xl border-2 border-border bg-card hover:border-primary/40 transition-all cursor-pointer p-4",onClick:()=>r(n),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-[10px] font-bold text-muted-foreground bg-secondary px-2 py-0.5 rounded-full",children:o+1}),e.jsx("p",{className:"text-[13px] font-bold text-foreground",children:n.titre})]}),e.jsx("p",{className:"text-[12px] text-muted-foreground leading-relaxed",children:n.description})]},o))})]})}function Ks({slides:t,onReworkSlide:r}){const[n,o]=l.useState(null),[a,d]=l.useState(""),c=Math.round(t.reduce((u,i)=>u+i.wordCount,0)/t.length);return e.jsxs("div",{className:"space-y-1 my-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("div",{className:"w-5 h-5 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx("span",{className:"text-[10px] font-bold text-primary",children:"2"})}),e.jsxs("p",{className:"text-[12px] font-semibold text-foreground",children:["Rédaction — ",t.length," slides"]}),e.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",children:[e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["Moy. ",c," mots/slide"]}),e.jsxs(V,{variant:"ghost",size:"sm",className:"h-6 text-[10px] gap-1 text-muted-foreground hover:text-foreground",onClick:()=>{const u=t.map(i=>{let h=`SLIDE ${String(i.num).padStart(2,"0")} — ${i.nom}
45
46TEXTE :
47${i.texte}`;return i.noteGraphiste&&(h+=`
48
49NOTE GRAPHISTE :
50${i.noteGraphiste}`),h}).join(`
51
52---
53
54`);navigator.clipboard.writeText(u),k.success("Carrousel copié")},children:[e.jsx(oe,{size:12})," Copier"]})]})]}),t.map((u,i)=>{const h=Vs(u.wordCount),x=n===u.num;
54return e.jsxs("div",{className:"group/slide",children:[e.jsxs("div",{className:"rounded-xl border border-border bg-card overflow-hidden hover:border-primary/20 transition-colors",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 bg-secondary/20",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"w-7 h-7 rounded-lg bg-foreground/5 flex items-center justify-center text-[11px] font-bold text-foreground",children:u.num}),e.jsx("span",{className:"text-[12px] font-semibold text-foreground tracking-tight",children:u.nom})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:Z("text-[10px] font-bold px-2 py-1 rounded-full",h==="ok"?"bg-emerald-500/15 text-emerald-600":h==="warning"?"bg-amber-500/15 text-amber-600":"bg-destructive/15 text-destructive"),children:[u.wordCount," mots"]}),e.jsx("button",{onClick:()=>{o(x?null:u.num),d("")},className:"text-[10px] text-muted-foreground hover:text-foreground opacity-0 group-hover/slide:opacity-100 transition-opacity","aria-label":"Retravailler cette slide",children:e.jsx(ze,{size:12})})]})]}),e.jsxs("div",{className:"px-4 py-4",children:[e.jsx("div",{className:"mb-3",children:e.jsx("p",{className:"text-[13px] text-foreground leading-[1.7] whitespace-pre-wrap font-medium",children:u.texte})}),u.noteGraphiste&&e.jsxs("div",{className:"p-3 rounded-lg bg-muted/30 border border-border/50",children:[e.jsx("p",{className:"text-[9px] font-semibold text-muted-foreground uppercase tracking-wider mb-1.5",children:"🎨 Note Graphiste"}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed italic",children:u.noteGraphiste})]})]}),x&&e.jsxs("div",{className:"px-4 pb-3 flex gap-2",children:[e.jsx("input",{type:"text",value:a,onChange:y=>d(y.target.value),onKeyDown:y=>{y.key==="Enter"&&a.trim()&&(r(u.num,a),o(null),d(""))},placeholder:"Instruction de retravail…",className:"flex-1 text-[12px] px-3 py-2 rounded-lg border border-border bg-background focus:outline-none focus:ring-1 focus:ring-primary/30",autoFocus:!0}),e.jsx(V,{size:"sm",onClick:()=>{a.trim()&&(r(u.num,a),o(null),d(""))},className:"text-[11px] h-8",children:"Retoucher"})]})]}),i<t.length-1&&e.jsx("div",{className:"flex justify-center py-0.5",children:e.jsx("div",{className:"w-px h-3 bg-border"})})]},u.num)})]})}function Js({verdict:t}){const r=t.global==="APPROUVÉ"?"text-emerald-600":t.global==="REJETÉ"?"text-destructive":"text-amber-600",n=t.global==="APPROUVÉ"?"bg-emerald-500/10 border-emerald-500/30":t.global==="REJETÉ"?"bg-destructive/10 border-destructive/30":"bg-amber-500/10 border-amber-500/30";return e.jsxs("div",{className:"space-y-3 my-3",children:[e.jsxs("div",{className:Z("rounded-xl border p-4",n),children:[e.jsxs("p",{className:Z("text-[14px] font-bold",r),children:["Verdict : ",t.global]}),t.synthese&&e.jsx("p",{className:"text-[12px] text-foreground mt-1",children:t.synthese})]}),t.slides.map(o=>{const a=o.statut.includes("OK")?"border-l-emerald-500":o.statut.includes("SUPPRIMER")?"border-l-destructive":"border-l-amber-500";return e.jsxs("div",{className:Z("border-l-4 rounded-r-lg bg-card border border-border p-3",a),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"text-[10px] font-bold text-accent",children:["S",o.num]}),e.jsx("span",{className:"text-[11px] font-medium text-foreground",children:o.nom}),e.jsx("span",{className:"text-[9px] font-bold ml-auto",children:o.statut})]}),o.probleme&&e.jsxs("p",{className:"text-[11px] text-destructive",children:["⚠️ ",o.probleme]}),o.reformulation&&e.jsxs("p",{className:"text-[11px] text-muted-foreground italic mt-1",children:["💡 ",o.reformulation]})]},o.num)})]})}const Ws=`Passe maintenant à la RÉDACTION DE L'ARTICLE complet à partir de ce brief.
55Respecte l'ADN ROOTS (ton incarné, corrosif, jamais neutre).
56Réponds UNIQUEMENT dans ce format, sans commentaire autour :
57
58=== ARTICLE ===
59TITRE : (titre on-page façon Vice, percutant)
60CHAPO : (2 phrases d'accroche)
61CONTENU :
62(article complet en markdown, intertitres ## , 800 à 1200 mots)`;function he({onSend:t}){return e.jsxs("div",{className:"mt-5 pt-4 border-t border-border/50 flex flex-wrap items-center gap-2",children:[e.jsxs(V,{size:"sm",className:"h-9 text-[12px] gap-1.5 font-semibold",onClick:()=>t(Ws),children:[e.jsx(Jt,{size:13})," Passer à la rédaction de l'article"]}),e.jsx("button",{type:"button",onClick:()=>t("Avant d'écrire, propose-moi 3 angles alternatifs pour cet article, en une ligne chacun."),className:"text-[11px] text-muted-foreground hover:text-foreground",children:"Explorer d'autres angles"})]})}function be({content:t}){const[r,n]=l.useState(!0);return t!=null&&t.trim()?e.jsxs("div",{className:"mt-4 rounded-xl border border-border/60 bg-muted/20 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 hover:bg-muted/40 transition-colors",children:[e.jsxs("button",{type:"button",onClick:()=>n(o=>!o),className:"flex min-w-0 flex-1 items-center gap-2 text-left","aria-expanded":r,children:[e.jsx(Wt,{size:13,className:"text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Analyse et réponse originales de l'agent"}),e.jsx(ve,{size:14,className:Z("ml-auto shrink-0 text-muted-foreground transition-transform",r&&"rotate-180")}
62)]}),e.jsx("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(t),k.success("Réponse copiée")},className:"shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Copier l'analyse et la réponse originales",children:e.jsx(oe,{size:12})})]}),r&&e.jsx("div",{className:`border-t border-border/40 px-4 pb-4 pt-2 prose prose-sm max-w-[70ch] dark:prose-invert
63          prose-p:my-3 prose-p:leading-[1.75] prose-headings:font-bold prose-headings:mt-5 prose-headings:mb-2
64          prose-h2:text-base prose-h3:text-sm prose-ul:my-2 prose-ol:my-2 prose-li:my-1.5
65          prose-strong:text-foreground`,children:e.jsx(ae,{children:t})})]}):null}function Xs({content:t,onSend:r,isLast:n=!1,streaming:o=!1}){const a=l.useMemo(()=>Bs(t),[t]),d=l.useMemo(()=>Us(t),[t]),c=l.useMemo(()=>Hs(t),[t]),u=l.useMemo(()=>Ps(t),[t]),i=l.useMemo(()=>kt(t),[t]),h=l.useMemo(()=>zs(t),[t]),x=d.length>0,y=u.length>0,p=x||y||!!c?null:i??h,j=qs(t),w=n&&!o&&!p;return p&&!o?e.jsxs("div",{children:[a&&e.jsx(ue,{fiche:a}),e.jsx(Ds,{article:p,onSend:r}),e.jsx(be,{content:t})]}):c?e.jsxs("div",{children:[a&&e.jsx(ue,{fiche:a}),e.jsx(Js,{verdict:c}),e.jsx(be,{content:t}),w&&e.jsx(he,{onSend:r})]}):x?e.jsxs("div",{children:[a&&e.jsx(ue,{fiche:a}),e.jsx(Ks,{slides:d,onReworkSlide:(N,I)=>r(`Retravaille la slide ${N} : ${I}`)}),e.jsx(be,{content:t}),w&&e.jsx(he,{onSend:r})]}):y?e.jsxs("div",{children:[a&&e.jsx(ue,{fiche:a}),j&&e.jsx("div",{className:`prose prose-sm max-w-[70ch] dark:prose-invert
66            prose-p:my-3 prose-p:leading-[1.75] prose-headings:font-bold prose-headings:mt-5 prose-headings:mb-2
67            prose-h2:text-base prose-h3:text-sm prose-ul:my-2 prose-ol:my-2 prose-li:my-1.5
68            prose-strong:text-foreground`,children:e.jsx(ae,{children:j})}),e.jsx(Gs,{approches:u,onSelect:N=>r(`Je choisis l'approche : "${N.titre}".
69
70${N.description}
71
72Commence par le SQUELETTE (Phase 1) : liste uniquement les titres de slides, un par ligne. N'écris PAS le contenu.`)}),e.jsx(be,{content:t}),w&&e.jsx(he,{onSend:r})]}):e.jsxs("div",{children:[a&&e.jsx(ue,{fiche:a}),e.jsx("div",{className:`prose prose-sm max-w-[70ch] dark:prose-invert
73        prose-p:my-3 prose-p:leading-[1.75] prose-headings:font-bold prose-headings:mt-5 prose-headings:mb-2
74        prose-h2:text-base prose-h3:text-sm prose-ul:my-2 prose-ol:my-2 prose-li:my-1.5
75        prose-strong:text-foreground`,children:e.jsx(ae,{children:t})}),w&&e.jsx(he,{onSend:r})]})}const _e={sourceur:"Sourceur",redacteur:"Rédacteur",croissance:"Croissance",ingenieur:"Ingénieur",archiviste:"Bibliothèque"},$e={sourceur:"#3B82F6",redacteur:"#10B981",croissance:"#F59E0B",ingenieur:"#0EA5E9",archiviste:"#8B5CF6"};function Qs({onForward:t,onAsk:r,refreshKey:n=0}){const[o,a]=l.useState([]),[d,c]=l.useState(!0),[u,i]=l.useState(""),[h,x]=l.useState(null),[y,f]=l.useState(null),[p,j]=l.useState(null),w=l.useCallback(async()=>{c(!0);const{data:b,error:R}=await O.from("content_drafts").select("id, title, content, agent, created_at, metadata, keywords").eq("status","wishlist").order("created_at",{ascending:!1});R?k.error("Erreur chargement archives"):b&&a(b),c(!1)},[]);l.useEffect(()=>{w()},[w,n]);const N=l.useMemo(()=>{const b=new Set;return o.forEach(R=>(R.keywords||[]).forEach(S=>b.add(S))),[...b].sort()},[o]),I=l.useMemo(()=>{const b=u.trim().toLowerCase();return o.filter(R=>h&&!(R.keywords||[]).includes(h)?!1:b?(R.title||"").toLowerCase().includes(b)||R.content.toLowerCase().includes(b)||R.agent.toLowerCase().includes(b)||(R.keywords||[]).some(S=>S.toLowerCase().includes(b)):!0)},[o,u,h]),F=l.useMemo(()=>{var R;const b={};for(const S of I)(b[R=S.agent]||(b[R]=[])).push(S);return b},[I]),T=async b=>{if(!confirm("Supprimer cette idée archivée ?"))return;const{error:R}=await O.from("content_drafts").delete().eq("id",b);if(R)return k.error(R.message);a(S=>S.filter(_=>_.id!==b)),y===b&&f(null),k.success("Idée supprimée")},L=b=>new Date(b).toLocaleDateString("fr-FR",{day:"numeric",month:"short",year:"numeric"});return e.jsxs("aside",{className:"hidden lg:flex w-[320px] shrink-0 flex-col border-r border-border bg-background",children:[e.jsxs("div",{className:"px-3 h-12 flex items-center gap-2 border-b border-border shrink-0",children:[e.jsx(yt,{size:14,className:"text-primary"}),e.jsx("h3",{className:"text-[13px] font-semibold",children:"Bibliothèque"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[o.length," idée",o.length>
751?"s":""]})]}),e.jsxs("div",{className:"px-3 py-2 border-b border-border",children:[e.jsxs("div",{className:"relative",children:[e.jsx(vt,{size:12,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(Xt,{value:u,onChange:b=>i(b.target.value),placeholder:"Rechercher…",className:"pl-7 h-8 text-[12px]"})]}),N.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[h&&e.jsxs("button",{onClick:()=>x(null),className:"text-[10px] px-1.5 py-0.5 rounded bg-primary text-primary-foreground inline-flex items-center gap-1",children:[h," ",e.jsx(me,{size:9})]}),N.slice(0,12).filter(b=>b!==h).map(b=>e.jsx("button",{onClick:()=>x(b),className:"text-[10px] px-1.5 py-0.5 rounded bg-muted hover:bg-muted/70 text-muted-foreground",children:b},b))]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto scrollbar-thin",children:d?e.jsx("div",{className:"text-center py-8",children:e.jsx(G,{className:"h-4 w-4 animate-spin mx-auto text-muted-foreground"})}):I.length===0?e.jsx("div",{className:"text-center py-8 px-4 text-[12px] text-muted-foreground",children:o.length===0?'Aucune idée archivée pour le moment. Les autres agents peuvent archiver ici via leur bouton "Archiver".':"Aucun résultat pour ce filtre."}):Object.entries(F).map(([b,R])=>e.jsxs("div",{className:"border-b border-border/50 last:border-b-0",children:[e.jsxs("div",{className:"px-3 py-1.5 text-[10px] font-bold uppercase tracking-wider flex items-center gap-1.5",style:{color:$e[b]||"hsl(var(--muted-foreground))"},children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{backgroundColor:$e[b]||"currentColor"}}),_e[b]||b," · ",R.length]}),R.map(S=>{var P;const _=y===S.id;return e.jsxs("div",{className:`px-3 py-2 border-t border-border/30 cursor-pointer transition ${_?"bg-primary/5":"hover:bg-muted/40"}`,onClick:()=>f(_?null:S.id),children:[e.jsx("div",{className:"text-[12px] font-medium leading-snug line-clamp-2",children:S.title||"Sans titre"}),e.jsx("div",{className:"text-[10px] text-muted-foreground mt-0.5",children:L(S.created_at)}),(((P=S.keywords)==null?void 0:P.length)??0)>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:S.keywords.slice(0,3).map(M=>e.jsx("span",{className:"text-[9px] px-1 py-0.5 rounded bg-muted text-muted-foreground",children:M},M))}),_&&e.jsxs("div",{className:"mt-2 space-y-2",onClick:M=>M.stopPropagation(),children:[e.jsx("div",{className:"text-[11px] text-foreground/80 line-clamp-4 whitespace-pre-wrap",children:S.content}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[e.jsxs("button",{onClick:()=>r(`Explore l'idée archivée "${S.title||"Sans titre"}" — est-elle encore pertinente aujourd'hui ?`),className:"text-[10px] px-2 py-1 rounded border border-border bg-card hover:bg-muted inline-flex items-center gap-1",children:[e.jsx(Qt,{size:10})," Challenger"]}),e.jsxs("div",{className:"relative",children:[e.jsxs("button",{onClick:()=>j(p===S.id?null:S.id),className:"text-[10px] px-2 py-1 rounded border border-border bg-card hover:bg-muted inline-flex items-center gap-1",children:[e.jsx(Yt,{size:10})," Transférer ",e.jsx(ve,{size:9})]}),p===S.id&&e.jsx("div",{className:"absolute left-0 top-full mt-1 z-10 bg-popover border border-border rounded-lg shadow-lg py-1 min-w-[140px]",children:Object.keys(_e).filter(M=>M!=="archiviste").map(M=>e.jsxs("button",{onClick:()=>{const K=`Voici une idée archivée à travailler :
76
77**${S.title||"Sans titre"}**
78
79${S.content}`;t(M,K),j(null)},className:"w-full text-left text-[11px] px-3 py-1.5 hover:bg-muted flex items-center gap-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{backgroundColor:$e[M]}}),_e[M]]},M))})]}),e.jsxs("button",{onClick:()=>T(S.id),className:"text-[10px] px-2 py-1 rounded border border-border bg-card hover:bg-destructive/10 hover:text-destructive hover:border-destructive/30 inline-flex items-center gap-1 ml-auto",children:[e.jsx(Nt,{size:10})," Suppr."]})]})]})]},S.id)})]},b))})]})}function Ys(t,r,n=16e3){const o=t.reduce((p,j)=>p+j.length,0),a=new Float32Array(o);let d=0;for(const p of t)a.set(p,d),d+=p.length;const c=r/n,u=Math.floor(a.length/c),i=new Float32Array(u);for(let p=0;p<u;p++)i[p]=a[Math.floor(p*c)]||0;
79const h=new ArrayBuffer(44+i.length*2),x=new DataView(h),y=(p,j)=>{for(let w=0;w<j.length;w++)x.setUint8(p+w,j.charCodeAt(w))};y(0,"RIFF"),x.setUint32(4,36+i.length*2,!0),y(8,"WAVE"),y(12,"fmt "),x.setUint32(16,16,!0),x.setUint16(20,1,!0),x.setUint16(22,1,!0),x.setUint32(24,n,!0),x.setUint32(28,n*2,!0),x.setUint16(32,2,!0),x.setUint16(34,16,!0),y(36,"data"),x.setUint32(40,i.length*2,!0);let f=44;for(let p=0;p<i.length;p++,f+=2){const j=Math.max(-1,Math.min(1,i[p]));x.setInt16(f,j<0?j*32768:j*32767,!0)}return new Blob([h],{type:"audio/wav"})}function Zs(){const t=window,r=t.SpeechRecognition||t.webkitSpeechRecognition;return r?new r:null}function er({onTranscript:t,onInterim:r,disabled:n}){const[o,a]=l.useState(!1),[d,c]=l.useState(!1),[u,i]=l.useState(0),h=l.useRef(null),x=l.useRef(null),y=l.useRef(null),f=l.useRef([]),p=l.useRef(null),j=l.useRef(null),w=l.useRef(""),N=l.useCallback(()=>{var T,L;p.current&&(clearInterval(p.current),p.current=null),(T=y.current)==null||T.disconnect(),y.current=null,(L=h.current)==null||L.getTracks().forEach(b=>b.stop()),h.current=null},[]),I=async()=>{const T=Zs();if(T&&r)try{w.current="",T.lang="fr-FR",T.continuous=!0,T.interimResults=!0,T.onresult=L=>{let b="";for(let R=L.resultIndex;R<L.results.length;R++){const S=L.results[R];S.isFinal?w.current+=S[0].transcript:b+=S[0].transcript}r(`${w.current}${b}`.trim())},T.onerror=()=>{},T.start(),j.current=T,i(0),a(!0),p.current=setInterval(()=>i(L=>L+1),1e3);return}catch{j.current=null}try{const L=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});h.current=L;const b=new AudioContext;x.current=b;const R=b.createMediaStreamSource(L),S=b.createScriptProcessor(4096,1,1);y.current=S,f.current=[],S.onaudioprocess=_=>f.current.push(new Float32Array(_.inputBuffer.getChannelData(0))),R.connect(S),S.connect(b.destination),i(0),a(!0),p.current=setInterval(()=>i(_=>_+1),1e3)}catch{k.error("Micro indisponible",{description:"Autorise l'accès au microphone."})}},F=async()=>{if(j.current){try{j.current.stop()}catch{}j.current=null,p.current&&(clearInterval(p.current),p.current=null),a(!1);const R=w.current.trim();if(w.current="",!R){k.error("Rien n'a été compris"),r==null||r("");return}r==null||r(""),t(R);return}const T=x.current,L=(T==null?void 0:T.sampleRate)||44100;N(),a(!1);const b=Ys(f.current,L);if(f.current=[],await(T==null?void 0:T.close().catch(()=>{})),x.current=null,b.size<4096){k.error("Enregistrement trop court");return}c(!0);try{const R=await new Promise((M,K)=>{const A=new FileReader;A.onload=()=>M(String(A.result).split(",")[1]||""),A.onerror=()=>K(new Error("Lecture audio impossible")),A.readAsDataURL(b)}),{data:S,error:_}=await O.functions.invoke("transcribe-audio",{body:{audio:R,mime:"audio/wav",filename:"recording.wav"}});if(_)throw _;if(S!=null&&S.error)throw new Error(S.error);const P=((S==null?void 0:S.text)||"").trim();if(!P){k.error("Rien n'a été compris",{description:"Réessaie en parlant plus près du micro."});return}t(P)}catch(R){k.error("Transcription échouée",{description:R==null?void 0:R.message})}finally{c(!1)}};return e.jsxs("button",{type:"button",disabled:n||d,onClick:o?F:I,title:o?"Arrêter et transcrire":"Dicter un message","aria-label":o?"Arrêter l'enregistrement":"Enregistrer un message vocal",className:`shrink-0 h-[42px] rounded-xl border flex items-center justify-center gap-1.5 px-3 text-xs font-semibold transition disabled:opacity-50 ${o?"border-destructive bg-destructive/10 text-destructive animate-pulse":"border-border bg-background text-muted-foreground hover:text-foreground hover:bg-muted"}`,children:[d?e.jsx(G,{className:"h-4 w-4 animate-spin"}):o?e.jsx(wt,{className:"h-4 w-4"}):e.jsx(Zt,{className:"h-4 w-4"}),o&&e.jsxs("span",{className:"tabular-nums",children:[Math.floor(u/60),":",String(u%60).padStart(2,"0")]})]})}function tr(t){return t.replace(/```[\s\S]*?```/g," ").replace(/`([^`]+)`/g,"$1").replace(/!\[[^\]]*\]\([^)]*\)/g," ").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/[#>*_~|-]{1,}/g," ").replace(/\s+/g," ").trim()}function sr({text:t}){const[r,n]=l.useState("idle"),o=l.useRef(null),a=l.useRef(null),d=()=>{var h;(h=o.current)==null||h.pause(),o.current=null,a.current&&URL.revokeObjectURL(a.current),a.current=null,typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()};l.useEffect(()=>d,[]);const c=h=>{if(!("speechSynthesis"in window))return k.error("Lecture audio indisponible"),n("idle"),!1;const x=new SpeechSynthesisUtterance(h.slice(0,3e3));return x.lang="fr-FR",x.onend=()=>n("idle"),x.onerror=()=>n("idle"),window.speechSynthesis.cancel(),window.speechSynthesis.speak(x),n("playing"),!0},u=async()=>
79{if(r!=="idle"){d(),n("idle");return}const h=tr(t);if(h){n("loading");try{const{data:x,error:y}=await O.functions.invoke("tts-speak",{body:{text:h}});if(y||!(x!=null&&x.audio))throw new Error((y==null?void 0:y.message)||"TTS indisponible");const f=Uint8Array.from(atob(x.audio),w=>w.charCodeAt(0)),p=URL.createObjectURL(new Blob([f],{type:x.mime||"audio/mpeg"}));a.current=p;const j=new Audio(p);o.current=j,j.onended=()=>{d(),n("idle")},j.onerror=()=>{d(),n("idle"),k.error("Lecture audio impossible")},await j.play(),n("playing")}catch(x){console.error("TTS error",x),c(h)}}},i=r==="playing"?"Stop":r==="loading"?"…":"Écouter";return e.jsxs("button",{type:"button",title:r==="playing"?"Arrêter la lecture":"Écouter la réponse",onClick:u,className:`text-[11px] inline-flex items-center gap-1.5 transition-colors ${r==="playing"?"text-destructive":"text-muted-foreground hover:text-foreground"}`,children:[r==="loading"?e.jsx(G,{size:12,className:"animate-spin"}):r==="playing"?e.jsx(wt,{size:12}):e.jsx(es,{size:12}),i]})}const Q=[{id:"sourceur",name:"Le Sourceur",shortName:"SRC",description:"Identifie les sujets à fort potentiel — recherche web temps réel.",color:"#3B82F6",supportsLiveSearch:!0,starters:["Quels sujets urgents pour ROOTS cette semaine ?","Donne-moi 3 angles sur l'antisémitisme actuel","Quoi de neuf sur Israël à exploiter ?"]},{id:"redacteur",name:"Le Rédacteur",shortName:"RED",description:"Rédige carrousels, stories, reels, visuels à partir d'une fiche sujet.",color:"#10B981",starters:["Transforme cette idée en carrousel 10 slides","Écris un reel court de 30 secondes","Rédige une story en 5 écrans"]},{id:"croissance",name:"La Croissance",shortName:"CRO",description:"SEO, monétisation, pub, newsletter, dons. Tout ce qui ramène de l'audience et de l'argent.",color:"#F59E0B",starters:["Où sont mes gisements SEO cette semaine ?","Comment monétiser le trafic des pages piliers ?","Quel levier active-t-on en priorité pour le revenu ?"]},{id:"ingenieur",name:"L'Ingénieur",shortName:"ING",description:"Technique, structurel, fonctionnel, sécurité, données. Vide le journal de bord.",color:"#0EA5E9",starters:["Les 3 chantiers techniques de la semaine","Quelles actions critiques restent ouvertes ?","Donne-moi le prompt pour corriger le mobile"]},{id:"archiviste",name:"La Bibliothèque",shortName:"BIB",description:"Mémoire du studio : retrouve tout ce qui a déjà été produit.",color:"#8B5CF6",starters:["On a déjà parlé de ce sujet ?","Sors-moi les contenus liés à Israël","Qu'a-t-on publié ce mois-ci ?"]}],rr=12*1024*1024,Ie=20,nr=/^(text\/|application\/(json|xml|x-yaml|yaml))/,ar=/\.(md|markdown|txt|csv|json|yml|yaml|html|srt|vtt)$/i;async function or(t){if(t.size>rr)throw new Error(`${t.name} dépasse 12 Mo`);if(nr.test(t.type)||ar.test(t.name)){const o=await t.text();return{name:t.name,mime:t.type||"text/plain",text:o,size:t.size}}const n=await new Promise((o,a)=>{const d=new FileReader;d.onload=()=>o(String(d.result)),d.onerror=()=>a(new Error(`Lecture impossible : ${t.name}`)),d.readAsDataURL(t)});return{name:t.name,mime:t.type||"application/octet-stream",dataUrl:n,size:t.size}}function ir(t){return t>1024*1024?`${(t/1024/1024).toFixed(1)} Mo`:`${Math.max(1,Math.round(t/1024))} Ko`}function lr({text:t}){const[r,n]=l.useState(!1);return e.jsxs("button",{type:"button",title:"Copier la réponse",onClick:()=>{navigator.clipboard.writeText(t).then(()=>{n(!0),k.success("Réponse copiée"),setTimeout(()=>n(!1),1800)})},className:"text-[11px] text-muted-foreground hover:text-foreground inline-flex items-center gap-1.5 transition-colors",children:[r?e.jsx(Le,{size:12}):e.jsx(oe,{size:12}),r?"Copié":"Copier"]})}const cr={planifie:"À faire",en_cours:"En cours",livre:"Traitée",abandonne:"Écartée"},dr={planifie:"bg-muted text-muted-foreground",en_cours:"bg-amber-500/15 text-amber-600",livre:"bg-emerald-500/15 text-emerald-600",abandonne:"bg-muted text-muted-foreground line-through"};async function Et(t){var r,n,o,a;try{const{data:d}=await O.auth.getSession(),c=(r=d.session)==null?void 0:r.access_token,i=await fetch("https://eptqkkfulwbkswjinqaz.supabase.co/functions/v1/agent-chat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`},body:JSON.stringify({agent:t.agent,messages:t.messages.map((f,p)=>p===t.messages.length-1?f:{role:f.role,content:f.content}),liveSearch:t.liveSearch})});if(!i.ok||!i.body){const f=await i.text().catch(()=>"");t.onError(`Erreur agent (${i.status}) ${f.slice(0,200)}`);return}const h=i.body.getReader(),x=new TextDecoder;let y="";for(;;){const{done:f,value:p}=await h.read();if(f)break;y+=x.decode(p,{stream:!0});const j=y.split(`
80`);y=j.pop()||"";for(const w of j){const N=w.trim();if(!N.startsWith("data:"))continue;const I=N.slice(5).trim();if(!(!I||I==="[DONE]"))try{const T=(a=(o=(n=JSON.parse(I).choices)==null?void 0:n[0])==null?void 0:o.delta)==null?void 0:a.content;T&&t.onDelta(T)}catch{}}}t.onDone()}catch(d){t.onError((d==null?void 0:d.message)||"Erreur réseau")}}const Oe="studio_active_agent",gt="studio_mission_started",ur="studio_active_session",je=t=>`${ur}:${t}`;function ht(){var st,rt;const{enabled:t,isLoading:r}=gs(ct),[n,o]=l.useState(()=>localStorage.getItem(Oe)||"sourceur"),[a,d]=l.useState([]),[c,u]=l.useState(()=>{const s=localStorage.getItem(Oe)||"sourceur";return localStorage.getItem(je(s))}),[i,h]=l.useState([]),[x,y]=l.useState(""),[f,p]=l.useState([]),[j,w]=l.useState(!1),[N,I]=l.useState(!1),[F,T]=l.useState(!1),[L,b]=l.useState(!1),[R,S]=l.useState("chat"),[_,P]=l.useState(""),[M,K]=l.useState([]),[A,z]=l.useState(!1),[C,U]=l.useState(null),[W,ee]=l.useState(null),De=l.useRef(null),[te,mr]=ts(),Ne=l.useRef(null),re=l.useRef(null),ie=l.useRef(null),D=Q.find(s=>s.id===n),pe=l.useMemo(()=>{const s=a.find(m=>m.id===c);return s!=null&&s.fromAgent&&(s!=null&&s.fromSession)?{agent:s.fromAgent,session:s.fromSession}:null},[a,c]),le=l.useRef(0),ce=l.useCallback(async s=>{const m=++le.current,{data:v,error:g}=await O.from("agent_sessions").select("id, agent, title, messages, updated_at, context").eq("agent",s).order("updated_at",{ascending:!1}).limit(40);if(g){console.error(g);return}if(m!==le.current)return;const E=(v??[]).map($=>{var H,q;
80return{id:$.id,agent:$.agent,title:$.title,messages:Array.isArray($.messages)?$.messages:[],updated_at:$.updated_at,taskId:($.context&&typeof $.context=="object"?$.context.task_id:null)??null,fromAgent:((H=$.context)==null?void 0:H.from_agent)??null,fromSession:((q=$.context)==null?void 0:q.from_session)??null}}),B=Array.from(new Set(E.map($=>$.taskId).filter(Boolean)));if(B.length){const{data:$}=await O.from("logbook_entries").select("id, title, status").in("id",B),H=new Map(($??[]).map(q=>[q.id,q]));E.forEach(q=>{const Y=q.taskId?H.get(q.taskId):null;Y&&(q.taskTitle=Y.title,q.taskStatus=Y.status)})}m===le.current&&d(E)},[]);l.useEffect(()=>{ce(n)},[n,ce]);const se=l.useRef(null);l.useEffect(()=>{if(!c){se.current=null,h([]);return}if(se.current===c)return;const s=a.find(m=>m.id===c&&m.agent===n);s&&(se.current=c,h(s.messages))},[n,c,a]),l.useEffect(()=>{n&&localStorage.setItem(Oe,n)},[n]),l.useEffect(()=>{c?localStorage.setItem(je(n),c):localStorage.removeItem(je(n))},[n,c]),l.useEffect(()=>{if(_.trim().toLocaleLowerCase("fr").length<2){K([]),z(!1);return}let m=!1;const v=window.setTimeout(async()=>{z(!0);const{data:g,error:E}=await O.rpc("admin_search_agent_sessions",{p_query:_.trim(),p_limit:80});if(m)return;if(E){console.error(E),K([]),z(!1);return}const B=(g??[]).map($=>{var H,q,Y;return{id:$.id,agent:$.agent,title:$.title,messages:Array.isArray($.messages)?$.messages:[],updated_at:$.updated_at,taskId:((H=$.context)==null?void 0:H.task_id)??null,fromAgent:((q=$.context)==null?void 0:q.from_agent)??null,fromSession:((Y=$.context)==null?void 0:Y.from_session)??null}});K(B),z(!1)},250);return()=>{m=!0,window.clearTimeout(v)}},[_]),l.useEffect(()=>{var s;(s=Ne.current)==null||s.scrollTo({top:Ne.current.scrollHeight,behavior:"smooth"})},[i,N]);const J=l.useRef(null);l.useEffect(()=>{J.current=C},[C]);const Be=l.useCallback(async(s,m)=>{var $,H;const v=J.current,g=v?`MISSION · ${v.title}`:((H=($=s.find(q=>q.role==="user"))==null?void 0:$.content)==null?void 0:H.slice(0,120))??"Nouvelle session";if(m){const{error:q}=await O.from("agent_sessions").update({messages:s,title:g,updated_at:new Date().toISOString(),...v?{context:{task_id:v.id}}:{}}).eq("id",m).eq("agent",n);if(q)throw q;return m}const{data:E,error:B}=await O.from("agent_sessions").insert({agent:n,title:g,messages:s,mode:v?"mission":"default",context:v?{task_id:v.id}:{}}).select("id").single();if(B)throw B;return E.id},[n]),Pe=()=>{U(null),J.current=null,u(null),h([]),setTimeout(()=>{var s;return(s=re.current)==null?void 0:s.focus()},50)},Ct=async s=>{var v,g,E;if(s.agent!==n){le.current+=1;const{data:B,error:$}=await O.from("agent_sessions").select("id, agent, title, messages, updated_at, context").eq("id",s.id).eq("agent",s.agent).maybeSingle();if($||!B){k.error("Cette conversation n’a pas pu être ouverte.");return}const H={id:B.id,agent:B.agent,title:B.title,messages:Array.isArray(B.messages)?B.messages:[],updated_at:B.updated_at,taskId:((v=B.context)==null?void 0:v.task_id)??null,fromAgent:((g=B.context)==null?void 0:g.from_agent)??null,fromSession:((E=B.context)==null?void 0:E.from_session)??null};if(se.current=H.id,o(H.agent),d([H]),u(H.id),h(H.messages),H.taskId){const{data:q}=await O.from("logbook_entries").select("id, title, description, category, impact, status, date, assigned_agent, related_url, metadata").eq("id",H.taskId).maybeSingle();if(q){const Y=q;U(Y),J.current=Y}}else U(null),J.current=null;b(!1),P("");return}if(u(s.id),b(!1),!s.taskId){U(null),J.current=null;return}const{data:m}=await O.from("logbook_entries").select("id, title, description, category, priority, impact, effort, expected_outcome, lovable_prompt").eq("id",s.taskId).maybeSingle();m&&(U(m),J.current=m)},qe=s=>{le.current+=1,se.current=null,o(s),u(localStorage.getItem(je(s))),d([]),h([]),U(null),J.current=null},Tt=async(s,m)=>{if(m.stopPropagation(),!confirm("Supprimer cette session ?"))return;const{error:v}=await O.from("agent_sessions").delete().eq("id",s);if(v){k.error(v.message);return}d(g=>g.filter(E=>E.id!==s)),c===s&&(u(null),h([]))},Ue=async(s,m)=>{I(!0);let v="";await Et({agent:n,messages:s,liveSearch:D.supportsLiveSearch?F:!1,onDelta:g=>{v+=g,h([...s,{role:"assistant",content:v}])},onDone:async()=>{I(!1);try{const g=[...s,{role:"assistant",content:v}],E=await Be(g,m);se.current=E,m||u(E),ce(n)}catch(g){k.error("Erreur sauvegarde session",{description:g.message})}setTimeout(()=>{var g;return(g=re.current)==null?void 0:g.focus()},50)},onError:g=>{k.error(g),h([...s,{role:"assistant",content:`⚠️ ${g}`}]),I(!1)}})},we=async s=>{w(!0);try{const v=(await Promise.all(Array.from(s).map(async g=>{try{return await or(g)}catch(E){return k.error((E==null?void 0:E.message)||`Fichier illisible : ${g.name}`),null}}
80))).filter(Boolean);v.length&&p(g=>{const E=[...g,...v];return E.length>Ie&&k.error(`${Ie} pièces jointes maximum — les suivantes ont été ignorées.`),E.slice(0,Ie)})}finally{w(!1)}},He=(s,m,v=!1)=>{U(null),J.current=null,se.current=null,v&&localStorage.setItem("studio_autorun_session",m),o(s),u(m),b(!1)},Rt=async(s,m)=>{const v=Q.find(g=>g.id===s);try{const g=c??(i.length?await Be(i,null):null),E=`BRIEF TRANSMIS PAR ${D.name.toUpperCase()}
81
82${m}`,{data:B,error:$}=await O.from("agent_sessions").insert({agent:s,title:`Brief de ${D.name} · ${m.replace(/[#*\n]+/g," ").trim().slice(0,60)}`,messages:[{role:"user",content:E}],mode:"default",context:{source:"handoff",from_agent:n,from_session:g}}).select("id").single();if($)throw $;k.success(`Brief envoyé à ${v.name}`),He(s,B.id,!0)}catch(g){k.error("Transmission échouée",{description:g==null?void 0:g.message})}},At=s=>{const m=Q.find(v=>v.id===s);X(`Rédige un brief complet et autonome destiné à ${m.name} (${m.description}). Il ne verra pas cette conversation : reprends le contexte, l'objectif, les faits établis, ce qui reste [À VÉRIFIER], les contraintes ROOTS et le livrable attendu. Ne rends que le brief.`)},X=async s=>{const m=(s||x).trim(),v=s?[]:f;if(!m&&v.length===0||N)return;y(""),s||p([]),re.current&&(re.current.style.height="auto");const g={role:"user",content:m||"Analyse la ou les pièces jointes.",...v.length?{attachments:v}:{}},E=[...i,g];h(E),await Ue(E,c)},Ve=l.useRef(null),Ge=l.useRef(null);l.useEffect(()=>{const s=te.get("session"),m=te.get("agent");!s||Ge.current===s||(Ge.current=s,m&&Q.some(v=>v.id===m)&&o(m),u(s),te.get("autorun")==="1"&&localStorage.setItem("studio_autorun_session",s))},[te]),l.useEffect(()=>{const s=localStorage.getItem("studio_autorun_session");if(!(!s||!c||s!==c)&&!(N||Ve.current===s)&&i.length){if(i[i.length-1].role!=="user"){localStorage.removeItem("studio_autorun_session");return}Ve.current=s,localStorage.removeItem("studio_autorun_session"),Ue(i,c)}},[c,i,N,n]),l.useEffect(()=>{const s=te.get("task");if(!s||De.current===s)return;De.current=s;const m=sessionStorage.getItem(gt)===s;(async()=>{const{data:v,error:g}=await O.from("logbook_entries").select("id, title, description, category, priority, impact, effort, expected_outcome, lovable_prompt").eq("id",s).maybeSingle();if(g||!v){k.error("Action introuvable dans le journal");return}const E=v;U(E),o(Re(E.category)),m||(sessionStorage.setItem(gt,s),u(null),h([]),ee(te.get("mode")==="etat"?Ns(E):vs(E)))})()},[te]),l.useEffect(()=>{if(!W||!C||N||n!==Re(C.category))return;const s=W;ee(null),X(s)},[W,C,n]);const _t=((st=[...i].reverse().find(s=>s.role==="assistant"))==null?void 0:st.content)??"",de=C&&!N?ws(_t):null,$t=async()=>{if(!C||!de)return;const{error:s}=await O.from("logbook_entries").update({lovable_prompt:de,status:"en_cours",next_step:"Brief prêt à exécuter dans Lovable"}).eq("id",C.id);if(s){k.error(s.message);return}k.success("Brief enregistré dans le journal de bord")},It=async s=>{if(C){{const{error:m}=await O.from("logbook_entries").update({status:"livre",completed_at:new Date().toISOString()}).eq("id",C.id);if(m){k.error(m.message);return}k.success("Action marquée comme faite"),ce(n)}U(null),J.current=null}},[Ot,Se]=l.useState(!1),[Ke,Je]=l.useState(""),[xe,ke]=l.useState([]),[Ee,We]=l.useState(""),Ce=l.useMemo(()=>ss(C==null?void 0:C.title,C==null?void 0:C.description,C==null?void 0:C.lovable_prompt,...i.map(s=>s.content)),[C,i]),Lt=()=>{ke(Ce),Se(!0)},Mt=s=>ke(m=>m.includes(s)?m.filter(v=>v!==s):[...m,s]),Xe=()=>{const s=xs(Ee);if(!s){k.error("URL invalide (chemin /article/… ou https://roots-officiel.com/…)");return}ke(m=>m.includes(s)?m:[...m,s]),We("")},Qe=async s=>{if(!C)return;const m=Ke.trim(),v=[...xe];Se(!1),Je(""),s?await O.from("logbook_entries").update({status:"livre",completed_at:new Date().toISOString()}).eq("id",C.id):await O.from("logbook_entries").update({status:"en_cours",next_step:m||"Étape exécutée, suite en cours"}).eq("id",C.id);let g=0;if(v.length)try{g=await fs(v,{source:"agent",reason:`Action validée : ${C.title}`.slice(0,200)}),k.success(`${g} URL${g>1?"s":""} en file d'indexation (SEO → Indexation)`)}catch(E){k.error(`File d'indexation : ${E instanceof Error?E.message:String(E)}`)}ce(n),X([`✅ Étape traitée pour la mission « ${C.title} ».`,m?`Ce qui a été fait : ${m}`:"Le brief que tu avais produit a été exécuté.",g?`${g} URL(s) ont été mises en file de réindexation Search Console.`:"",s?"Vérifie s'il reste quelque chose à contrôler ou à mesurer, sinon clôture.":"Reprends la mission : dis-moi précisément la prochaine étape, ce que tu fais toi et ce qui reste manuel."].filter(
82Boolean).join(`
83`))};if(r)return e.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:"Chargement…"});if(!t)return e.jsx("div",{className:"p-6",children:e.jsxs(hs,{className:"p-8 text-center max-w-xl mx-auto",children:[e.jsx("h2",{className:"text-xl font-bold mb-2",children:"Studio Team IA — désactivé"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Active le feature flag ",e.jsx("code",{className:"font-mono text-xs",children:ct})," pour utiliser les agents."]})]})});const Ye=s=>!!s.taskId||(s.title??"").startsWith("MISSION"),Ze=a.filter(Ye),et=a.filter(s=>!Ye(s)),fe=_.trim().length>=2,tt=fe?M:R==="task"?Ze:et,zt=s=>{const m=new Date(s),v=Date.now()-m.getTime(),g=Math.floor(v/864e5);return g===0?"Aujourd'hui":g===1?"Hier":g<7?`Il y a ${g}j`:m.toLocaleDateString("fr-FR",{day:"numeric",month:"short"})};return e.jsxs("div",{className:"flex flex-col gap-4",children:[C&&e.jsxs("div",{className:"rounded-xl border-l-4 border-l-primary border border-border bg-primary/[0.04] p-3 md:p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"text-[10px] uppercase tracking-[0.18em] text-primary font-bold",children:["Tâche · journal de bord → ",ys[Re(C.category)]]}),e.jsx("p",{className:"text-sm font-semibold",children:C.title})]}),e.jsx("button",{onClick:()=>{U(null),J.current=null},className:"text-muted-foreground hover:text-foreground shrink-0","aria-label":"Fermer la mission",children:e.jsx(me,{className:"h-4 w-4"})})]}),de&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("pre",{className:"text-xs whitespace-pre-wrap rounded-lg bg-background border border-border p-3 max-h-52 overflow-y-auto leading-relaxed",children:de}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(V,{size:"sm",onClick:$t,children:[e.jsx(nt,{className:"h-3.5 w-3.5 mr-1.5"})," Enregistrer le brief dans le journal"]}),e.jsxs(V,{size:"sm",variant:"outline",onClick:async()=>{await navigator.clipboard.writeText(de),k.success("Brief copié — colle-le dans le chat Lovable")},children:[e.jsx(oe,{className:"h-3.5 w-3.5 mr-1.5"})," Copier"]})]})]}),e.jsx("div",{className:"mt-3 pt-3 border-t border-border/60",children:Ot?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{value:Ke,onChange:s=>Je(s.target.value),rows:2,autoFocus:!0,placeholder:"Ce qui a été fait (ex. : brief exécuté dans Lovable, encart de don en ligne)…",className:"w-full resize-none rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary"}),e.jsxs("div",{className:"rounded-lg border border-border bg-background p-3 space-y-2",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.14em] font-bold text-muted-foreground",children:"URLs à réindexer sur Search Console"}),Ce.length===0&&xe.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Aucune URL détectée dans la conversation — ajoute-la ci-dessous si besoin."}),Array.from(new Set([...Ce,...xe])).map(s=>e.jsxs("label",{className:"flex items-start gap-2 text-xs cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:xe.includes(s),onChange:()=>Mt(s),className:"mt-0.5 accent-[hsl(var(--primary))]"}),e.jsx("span",{className:"break-all",children:s.replace("https://roots-officiel.com","")})]},s)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{value:Ee,onChange:s=>We(s.target.value),onKeyDown:s=>{s.key==="Enter"&&(s.preventDefault(),Xe())},placeholder:"/article/mon-slug",className:"flex-1 rounded-lg border border-border bg-background px-2 py-1.5 text-xs"}),e.jsx(V,{size:"sm",variant:"outline",onClick:Xe,disabled:!Ee.trim(),children:"Ajouter"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(V,{size:"sm",onClick:()=>Qe(!1),disabled:N,children:[e.jsx(Le,{className:"h-3.5 w-3.5 mr-1.5"})," Traité — l'agent enchaîne"]}),e.jsx(V,{size:"sm",variant:"outline",onClick:()=>Qe(!0),disabled:N,children:"Traité & action clôturée"}),e.jsx(V,{size:"sm",variant:"ghost",onClick:()=>Se(!1),children:"Annuler"})]})]}):e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(V,{size:"sm",variant:"outline",onClick:Lt,disabled:N,children:[e.jsx(Le,{className:"h-3.5 w-3.5 mr-1.5"})," Valider ce qui a été fait"]}),e.jsx(V,{size:"sm",variant:"ghost",onClick:()=>It(),children:"Clôturer sans relancer l'agent"})]})})]}),e.jsx("div",{className:"flex gap-1.5 overflow-x-auto pb-1 -mx-1 px-1 scrollbar-none",children:Q.map(s=>{const m=n===s.id;return e.jsxs("button",{onClick:()=>qe(s.id),title:s.description,className:`shrink-0 inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition ${m?"border-primary bg-primary/10 text-primary font-semibold ring-1 ring-primary/20":"border-border bg-card hover:bg-muted text-foreground"}`,children:[e.jsx("span",{className:"w-5 h-5 rounded-full flex items-center justify-center text-[9px] font-bold",style:{backgroundColor:`${s.color}20`,color:s.color},children:s.shortName}),e.jsx("span",{className:"whitespace-nowrap",children:s.name})]},s.id)})}),e.jsxs("div",{className:"relative flex h-[calc(100vh-300px)] min-h-[560px] rounded-2xl border border-border bg-card overflow-hidden",children:[n==="archiviste"&&e.jsx(Qs,{onAsk:s=>X(s),onForward:(s,m)=>{qe(s),setTimeout(()=>X(m),80)}}),L&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute inset-0 bg-background/40 backdrop-blur-[2px] z-20",onClick:()=>b(!1)}),e.jsxs("aside",{className:"absolute top-0 left-0 bottom-0 w-[24rem] max-w-[92%] bg-card border-r border-border shadow-2xl z-30 flex flex-col animate-in slide-in-from-left duration-200",children:[e.jsxs("div",{className:"p-3 border-b border-border flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-sm font-bold",children:["Historique · ",D.name]}),e.jsx("button",{onClick:()=>b(!1),className:"h-7 w-7 flex items-center justify-center rounded-md hover:bg-muted","aria-label":"Fermer",children:e.jsx(me,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"p-2 border-b border-border space-y-2",children:[e.jsxs("button",{onClick:()=>{Pe(),b(!1)},className:"w-full flex items-center justify-center gap-2 px-2.5 py-2 rounded-lg bg-primary text-primary-foreground text-sm font-semibold hover:opacity-90",children:[e.jsx(at,{className:"h-4 w-4"})," Nouvelle conversation"]}),e.jsxs("div",{className:"relative",children:[e.jsx(vt,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}
83),e.jsx("input",{value:_,onChange:s=>P(s.target.value),placeholder:"Rechercher un sujet, un article, une réponse…",className:"h-9 w-full rounded-lg border border-border bg-background pl-8 pr-8 text-xs outline-none focus:ring-2 focus:ring-primary",autoFocus:!0}),_&&e.jsx("button",{type:"button",onClick:()=>P(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Effacer la recherche",children:e.jsx(me,{className:"h-3.5 w-3.5"})})]}),!fe&&e.jsx("div",{className:"flex gap-1 rounded-lg bg-muted p-1",children:[{id:"chat",label:"Conversations",count:et.length},{id:"task",label:"Tâches",count:Ze.length}].map(s=>e.jsxs("button",{onClick:()=>S(s.id),className:`flex-1 rounded-md px-2 py-1.5 text-[12px] font-semibold transition ${R===s.id?"bg-card shadow-sm text-foreground":"text-muted-foreground hover:text-foreground"}`,children:[s.label," ",e.jsxs("span",{className:"opacity-60",children:["(",s.count,")"]})]},s.id))})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-2 space-y-1.5",children:A?e.jsxs("div",{className:"flex items-center justify-center gap-2 py-8 text-xs text-muted-foreground",children:[e.jsx(G,{className:"h-3.5 w-3.5 animate-spin"})," Recherche dans tous les agents…"]}):tt.length===0?e.jsx("div",{className:"text-xs text-muted-foreground text-center py-6 px-2",children:fe?"Aucune conversation ne correspond à cette recherche.":R==="task"?`Aucune tâche confiée à ${D.name}.`:`Aucune conversation avec ${D.name}.`}):tt.map(s=>{var E;const m=!!s.taskId||(s.title??"").startsWith("MISSION"),v=s.taskTitle||(s.title??"").replace(/^MISSION\s*[·—-]\s*/i,"")||"(sans titre)",g=c===s.id;return e.jsx("div",{onClick:()=>Ct(s),className:`group cursor-pointer rounded-lg px-2.5 py-2 text-sm transition-colors border ${g?"bg-amber-400/20 border-amber-500 ring-2 ring-amber-500/40":"border-transparent hover:bg-muted"} ${m&&!g?"border-l-4 border-l-primary/70":""}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[m?e.jsx(nt,{className:"h-3.5 w-3.5 mt-0.5 flex-shrink-0 text-primary"}):e.jsx(rs,{className:"h-3.5 w-3.5 mt-0.5 flex-shrink-0 opacity-60"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[g&&e.jsx("div",{className:"text-[9px] uppercase tracking-[0.16em] font-bold text-amber-700 dark:text-amber-400 mb-0.5",children:"Conversation en cours"}),m&&!g&&e.jsx("div",{className:"text-[9px] uppercase tracking-[0.16em] font-bold text-primary mb-0.5",children:"Tâche · journal de bord"}),e.jsx("div",{className:`leading-snug break-words line-clamp-3 ${g?"font-bold":"font-medium"}`,children:v}),e.jsxs("div",{className:"text-[10px] text-muted-foreground mt-1 flex items-center gap-2 flex-wrap",children:[fe&&e.jsx("span",{className:"font-semibold text-foreground",children:((E=Q.find(B=>B.id===s.agent))==null?void 0:E.name)??s.agent}),e.jsx("span",{children:zt(s.updated_at)}),m&&s.taskStatus&&e.jsx("span",{className:`px-1.5 py-0.5 rounded-full font-semibold ${dr[s.taskStatus]??"bg-muted text-muted-foreground"}`,children:cr[s.taskStatus]??s.taskStatus})]})]}),e.jsx("button",{onClick:B=>Tt(s.id,B),className:"h-7 w-7 flex items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition","aria-label":"Supprimer la conversation",title:"Supprimer la conversation",children:e.jsx(Nt,{className:"h-3.5 w-3.5"})})]})},s.id)})})]})]}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsxs("button",{onClick:()=>b(!0),className:"h-9 px-2.5 flex items-center gap-1.5 rounded-lg border border-border bg-card hover:bg-muted text-[12px] font-medium transition",title:"Historique des sessions",children:[e.jsx(ns,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Historique"}),a.length>0&&e.jsx("span",{className:"ml-1 text-[10px] px-1.5 py-0.5 rounded-full bg-muted text-muted-foreground",children:a.length})]}),e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center",style:{backgroundColor:`${D.color}15`,color:D.color},children:e.jsx(as,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-sm truncate",children:D.name}),pe?e.jsxs("button",{onClick:()=>He(pe.agent,pe.session),className:"text-[11px] text-primary hover:underline flex items-center gap-1 truncate",children:[e.jsx(ot,{className:"h-3 w-3"})," Brief reçu de ",((rt=Q.find(s=>s.id===pe.agent))==null?void 0:rt.name)??"un agent"," · revenir"]}):e.jsx("div",{className:"text-[11px] text-muted-foreground truncate hidden sm:block",children:D.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[D.supportsLiveSearch&&e.jsxs("button",{onClick:()=>T(s=>!s),className:`px-2.5 py-1.5 rounded-lg text-[11px] font-medium flex items-center gap-1.5 transition ${F?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-muted/80"}`,title:"Recherche web temps réel",children:[e.jsx(os,{className:"h-3.5 w-3.5"})," Live"]}),e.jsxs("button",{onClick:Pe,className:"flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-[11px] bg-primary text-primary-foreground hover:opacity-90",children:[e.jsx(at,{className:"h-3.5 w-3.5"})," Nouveau"]})]})]}),e.jsxs("div",{ref:Ne,className:"flex-1 overflow-y-auto px-4 md:px-6 py-5 space-y-5",children:[i.length===0?e.jsxs("div",{className:"text-center py-6 max-w-2xl mx-auto",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl flex items-center justify-center mx-auto mb-3",style:{backgroundColor:`${D.color}15`,color:D.color},children:e.jsx("span",{className:"font-bold",children:D.shortName})}),e.jsx("h3",{className:"font-bold text-lg",children:D.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:D.description}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-2 mt-5",children:D.starters.map(s=>e.jsx("button",{onClick:()=>X(s),className:"text-left text-sm px-3 py-2.5 rounded-xl border border-border hover:bg-muted transition",children:s},s))})]}):i.map((s,m)=>{var v;return e.jsxs("div",{className:`flex gap-3 ${s.role==="user"?"flex-row-reverse":""}`,children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex-shrink-0 flex items-center justify-center text-[10px] font-bold ${s.role==="user"?"bg-foreground text-background":""}`,style:s.role==="assistant"?{backgroundColor:`${D.color}15`,color:D.color}:void 0,children:s.role==="user"?"Toi":D.shortName}),e.jsxs("div",{className:`${s.role==="assistant"&&n==="redacteur"?"w-full":"max-w-[85%]"} rounded-2xl px-4 py-3 text-[14px] leading-relaxed ${s.role==="user"?"bg-foreground text-background":"bg-muted"}`,children:[s.role==="assistant"?n==="sourceur"?e.jsxs(e.Fragment,{children:[e.jsx(Is,{raw:s.content,isStreaming:N&&m===i.length-1}),!N&&m===i.length-1&&e.jsxs("button",{type:"button",onClick:()=>X("Propose-moi de nouveaux sujets différents, avec la même rigueur d'analyse."),className:"mt-3 pt-3 border-t border-border/50 text-[11px] text-muted-foreground hover:text-foreground inline-flex items-center gap-1.5",children:[e.jsx(is,{size:11}),"Regénérer avec la même rigueur"]})]}):n==="redacteur"?e.jsx(Xs,{content:s.content,onSend:g=>X(g),isLast:m===i.length-1,streaming:N&&m===i.length-1}):e.jsx("div",{className:`prose prose-sm max-w-none dark:prose-invert
84                        prose-p:my-2.5 prose-headings:font-bold prose-headings:mt-4 prose-headings:mb-2
85                        prose-h2:text-base prose-h3:text-sm prose-ul:my-2 prose-ol:my-2 prose-li:my-1
86                        prose-strong:text-foreground`,children:e.jsx(ae,{children:s.content})}):e.jsxs("div",{className:"space-y-2",children:[!!((v=s.attachments)!=null&&v.length)&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.attachments.map((g,E)=>g.mime.startsWith("image/")&&g.dataUrl?e.jsx("img",{src:g.dataUrl,alt:g.name,className:"h-20 w-20 object-cover rounded-lg border border-background/30"},E):e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-1 rounded-lg bg-background/15 text-[11px]",children:[e.jsx(ye,{className:"h-3 w-3"})," ",g.name]},E))}),e.jsx("div",{className:"whitespace-pre-wrap",children:s.content})]}),s.role==="assistant"&&!(N&&m===i.length-1)&&e.jsxs("div",{className:"mt-2 pt-2 border-t border-border/40 flex items-center gap-4 flex-wrap",children:[e.jsx(lr,{text:s.content}),e.jsx(sr,{text:s.content}),e.jsxs(ls,{children:[e.jsxs(cs,{className:"flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground",children:[e.jsx(ot,{className:"h-3.5 w-3.5"})," Passer à un agent"]}),e.jsxs(ds,{align:"start",className:"w-64",children:[e.jsx(it,{className:"text-[11px]",children:"Envoyer cette réponse comme brief à…"}),Q.filter(g=>g.id!==n).map(g=>e.jsx(lt,{onClick:()=>Rt(g.id,s.content),children:g.name},`s-${g.id}`)),e.jsx(us,{}),e.jsxs(it,{className:"text-[11px]",children:["Demander d'abord à ",D.name," un brief pour…"]}),Q.filter(g=>g.id!==n).map(g=>e.jsx(lt,{onClick:()=>At(g.id),children:g.name},`b-${g.id}`))]})]})]})]})]},m)}),N&&e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center text-[10px] font-bold",style:{backgroundColor:`${D.color}15`,color:D.color},children:D.shortName}),e.jsxs("div",{className:"bg-muted rounded-2xl px-4 py-3 flex gap-1.5",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-muted-foreground
86/60 animate-bounce"}),e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-muted-foreground/60 animate-bounce",style:{animationDelay:"0.1s"}}),e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-muted-foreground/60 animate-bounce",style:{animationDelay:"0.2s"}})]})]})]}),e.jsxs("form",{onSubmit:s=>{s.preventDefault(),X()},onDragOver:s=>s.preventDefault(),onDrop:s=>{var m;s.preventDefault(),(m=s.dataTransfer.files)!=null&&m.length&&we(s.dataTransfer.files)},className:"border-t border-border p-3 bg-background",children:[f.length>0&&e.jsx("div",{className:"max-w-3xl mx-auto mb-2 flex flex-wrap gap-2",children:f.map((s,m)=>e.jsxs("span",{className:"group inline-flex items-center gap-1.5 pl-2 pr-1 py-1 rounded-lg border border-border bg-muted text-[11px]",children:[s.mime.startsWith("image/")?e.jsx(ms,{className:"h-3 w-3"}):e.jsx(ye,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[160px] truncate",children:s.name}),e.jsx("span",{className:"text-muted-foreground",children:ir(s.size)}),e.jsx("button",{type:"button","aria-label":"Retirer",onClick:()=>p(v=>v.filter((g,E)=>E!==m)),className:"h-4 w-4 rounded flex items-center justify-center hover:bg-background",children:e.jsx(me,{className:"h-3 w-3"})})]},m))}),e.jsxs("div",{className:"flex gap-2 items-end max-w-3xl mx-auto",children:[e.jsxs("label",{className:"shrink-0",children:[e.jsx("input",{type:"file",multiple:!0,className:"hidden",accept:".md,.markdown,.txt,.csv,.json,.yml,.yaml,.html,application/pdf,image/*",disabled:N||j,onChange:s=>{var m;(m=s.target.files)!=null&&m.length&&we(s.target.files),s.currentTarget.value=""}}),e.jsx("span",{title:"Joindre des fichiers (MD, TXT, PDF, image…) — 20 max, 12 Mo chacun",className:"cursor-pointer h-[42px] w-[42px] rounded-xl border border-border bg-background flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted transition",children:j?e.jsx(G,{className:"h-4 w-4 animate-spin"}):e.jsx(ps,{className:"h-4 w-4"})})]}),e.jsx(er,{disabled:N,onInterim:s=>{ie.current===null&&(ie.current=x);const m=ie.current||"";y(s?m?`${m.trim()} ${s}`:s:m)},onTranscript:s=>{const m=ie.current??x;ie.current=null,y(m?`${m.trim()} ${s}`:s),setTimeout(()=>{const v=re.current;v&&(v.focus(),v.style.height="auto",v.style.height=`${Math.min(v.scrollHeight,320)}px`)},30)}}),e.jsx("textarea",{ref:re,value:x,onChange:s=>{y(s.target.value);const m=s.target;m.style.height="auto",m.style.height=`${Math.min(m.scrollHeight,320)}px`},onPaste:s=>{const m=Array.from(s.clipboardData.files||[]);m.length&&(s.preventDefault(),we(m))},onKeyDown:s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),X())},placeholder:`Parle à ${D.name}…`,rows:1,disabled:N,className:"flex-1 resize-none overflow-y-auto rounded-xl border border-border bg-background px-3 py-2.5 text-sm leading-relaxed focus:outline-none focus:ring-2 focus:ring-primary",style:{maxHeight:320}}),e.jsx("button",{type:"submit",disabled:N||!x.trim()&&f.length===0,className:"rounded-xl bg-primary text-primary-foreground px-4 py-2.5 disabled:opacity-50 flex items-center gap-1.5 text-sm font-semibold",children:N?e.jsx(G,{className:"h-4 w-4 animate-spin"}):e.jsx(jt,{className:"h-4 w-4"})})]})]})]})]})]})}const yr=Object.freeze(Object.defineProperty({__proto__:null,AGENTS:Q,StudioAgentsHub:ht,default:ht,streamAgentChat:Et},Symbol.toStringTag,{value:"Module"}));export{Q as A,yr as S,er as V,Et as s};

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.