PageSourceSearch

https://www.chatgrid.ai/assets/BoardCanvas-BGgjYA4r.js

js chatgrid.ai collected 2026-10-05 11:55:39 UTC 305,386 bytes, 59 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/serverApi-QuCfAnKQ.js","assets/index-CCG9MGz0.js","assets/index-BikwTqmh.css"])))=>i.map(i=>d[i]);
2var Ji=Object.defineProperty;var Xi=(t,r,s)=>r in t?Ji(t,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[r]=s;var _t=(t,r,s)=>Xi(t,typeof r!="symbol"?r+"":r,s);import{z as Ua,a as ci,b as Zi,j as e,r as n,s as Et,f as di,e as Un,l as Qi,u as el}from"./index-CCG9MGz0.js";import{a as is,m as ui,h as vo,i as tl,j as rl,s as sl,p as nl,k as al,b as ol,u as Pe,n as il,P as ll,l as cl,t as dl,B as ko,g as ul,R as pl,d as hl,e as fl,f as gl,C as ml}from"./CanvasBackground-C-oLv0Qu.js";import{buildChatgridAiBackendUrl as $t,getSupabaseAccessToken as pi}from"./serverApi-QuCfAnKQ.js";import{I as xl,u as bl,a as yl,b as wl,c as vl,d as kl,e as jl,f as Sl,g as Nl,h as Cl,i as _l,j as $l,k as Rl,l as Al,m as Tl,n as Pl,o as Il,p as El,s as Ll,B as jo,S as So,T as No,D as zl,C as Co,W as _o,q as $o,r as Ro,t as Dl,v as Fl,F as Ol,w as Bl,x as Ml,y as Ul,G as Vl,z as Ao,A as Wl,E as Hl,H as ql}from"./useNodeDragHandlers-CdUza83W.js";import{D as Gl}from"./modelCategories-CLRrvYvq.js";import{L as Yl,V as Kl,C as Jl,A as Xl,i as Zl,j as Ql,h as hi}from"./darkSidebarPrimitives-WYA5Xfg0.js";import{u as ec,L as To}from"./useDocumentProcessing-CT8XIZZ3.js";import{c as ds}from"./createLucideIcon-BNie9-yg.js";import{M as Va,C as tc}from"./CursorAgent-BuNh2nyN.js";import{P as ls,C as Yn,M as rc}from"./xlsx-DHg_MbFl.js";import{U as Wa}from"./users-DQEZsmGe.js";import{m as _e}from"./proxy-DCcAtm3e.js";import{A as Jt}from"./index-C8GGNDku.js";import{X as qt}from"./x-B90hvd2h.js";import{P as Rs}from"./plus-CtL5uaTS.js";import{S as ea}from"./sparkles-CTgZB_rD.js";import{S as Ha}from"./send-D8LswkWg.js";import{A as sc}from"./arrow-left-CcFLG1c6.js";import{S as fi}from"./search-bFUysiSs.js";import{L as nc}from"./layers-Cfhp7pij.js";import{C as cs}from"./check-DpxvuY1B.js";import{C as gi}from"./chevron-down-BkupgjqY.js";import{T as ac}from"./trash-2-CtdTlm-l.js";import{E as ta}from"./eye-Q6TnMbDD.js";import{S as oc}from"./star-DJBVjYDR.js";import{E as ic}from"./CreditModal-DjwbWnX-.js";import{u as lc}from"./use-reduced-motion-m11mlRrx.js";import{L as Ur}from"./loader-circle-D1HdQVTP.js";import{C as Kn}from"./chevron-right-DiFWwGWb.js";import{R as cc}from"./refresh-ccw-jjHTDDvN.js";import{T as qa,P as Po}from"./terminal-95uvLlXP.js";import{I as dc}from"./instagram-Bi7mlEYr.js";import{Y as Ga}from"./youtube-Cw30aRrf.js";import{H as mi,M as xi,S as uc,a as pc}from"./skip-forward-BAQeE2Kc.js";import{B as bi}from"./PromptInput-4yJAxUuC.js";import{F as As}from"./file-text-Bb28mgmh.js";import{S as yi}from"./sticky-note-BU7melLr.js";import{L as wi}from"./layout-grid-r7b0xkTH.js";import{U as vi}from"./upload-DMPPaHWe.js";import{L as ki}from"./link-2-BHizDc4l.js";import{C as Ya}from"./circle-alert-B_9MDH1R.js";import{G as Io}from"./globe-DsFaVgLl.js";import{H as hc}from"./palette-StQ3SUWt.js";import{T as fc}from"./trending-up-CH8ZhGcV.js";import{r as za,i as Eo}from"./agentBuildReplay-B7wiZA5l.js";import{M as gc}from"./minus-B3hFNsNz.js";import{R as mc}from"./Response-DwD38_jg.js";/**
3 * @license lucide-react v0.548.0 - ISC
4 *
5 * This source code is licensed under the ISC license.
6 * See the LICENSE file in the root directory of this source tree.
7 */const xc=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2Z",key:"169p4p"}],["path",{d:"m9 10 2 2 4-4",key:"1gnqz4"}]],bc=ds("bookmark-check",xc);/**
8 * @license lucide-react v0.548.0 - ISC
9 *
10 * This source code is licensed under the ISC license.
11 * See the LICENSE file in the root directory of this source tree.
12 */const yc=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],wc=ds("bookmark",yc);/**
13 * @license lucide-react v0.548.0 - ISC
14 *
15 * This source code is licensed under the ISC license.
16 * See the LICENSE file in the root directory of this source tree.
17 */const vc=[["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5",key:"1ue2ih"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]],ji=ds("image-plus",vc);/**
18 * @license lucide-react v0.548.0 - ISC
19 *
20 * This source code is licensed under the ISC license.
21 * See the LICENSE file in the root directory of this source tree.
22 */const kc=[["path",{d:"M19.07 4.93A10 10 0 0 0 6.99 3.34",key:"z3du51"}
22],["path",{d:"M4 6h.01",key:"oypzma"}],["path",{d:"M2.29 9.62A10 10 0 1 0 21.31 8.35",key:"qzzz0"}],["path",{d:"M16.24 7.76A6 6 0 1 0 8.23 16.67",key:"1yjesh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M17.99 11.66A6 6 0 0 1 15.77 16.67",key:"1u2y91"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"m13.41 10.59 5.66-5.66",key:"mhq4k0"}]],jc=ds("radar",kc);/**
23 * @license lucide-react v0.548.0 - ISC
24 *
25 * This source code is licensed under the ISC license.
26 * See the LICENSE file in the root directory of this source tree.
27 */const Sc=[["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}],["path",{d:"M3.103 6.034h17.794",key:"awc11p"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z",key:"o988cm"}]],Si=ds("shopping-bag",Sc);/**
28 * @license lucide-react v0.548.0 - ISC
29 *
30 * This source code is licensed under the ISC license.
31 * See the LICENSE file in the root directory of this source tree.
32 */const Nc=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],Cc=ds("sliders-horizontal",Nc);/**
33 * @license lucide-react v0.548.0 - ISC
34 *
35 * This source code is licensed under the ISC license.
36 * See the LICENSE file in the root directory of this source tree.
37 */const _c=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],$c=ds("square-pen",_c),Ni={note:"blockNoteNode",youtube:"youtubeNode",pdf:"pdfNode",website:"websiteNode",image:"imageNode"};let on=0;function Rc(){if(on===0){const t=is.temporal.getState();t.isTracking!==!1&&t.pause()}on+=1}function Ac(){if(on=Math.max(0,on-1),on===0){is.temporal.getState().resume();const r=is.getState().snapshotState;typeof r=="function"&&r()}}function Ci(t,r,s,a){const i=is.getState().nodes||[];if(t._preplaced&&typeof t.x=="number"&&typeof t.y=="number")return{x:t.x,y:t.y};if(typeof t.x=="number"&&typeof t.y=="number")return vo({x:t.x,y:t.y},r,i,{preferredDirection:"down"});let o={x:0,y:0};return s!=null&&s.screenToFlowPosition&&(o=s.screenToFlowPosition(a||{x:window.innerWidth/2,y:window.innerHeight/2})),vo(o,r,i,{preferredDirection:"down"})}function Tc(t){if(!t)return null;const r=t.match(/(?:youtube\.com\/(?:watch\?v=|shorts\/|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);return r?r[1]:null}function Vn(t){return{timestamp:Date.now(),source:"cursor-operator",...t.sourceId?{sourceTrayId:t.sourceId}:{}}}function Pc(t,r,s){const a=Ni[t.kind||"note"]||"txtNode",i=Ci(t,a,r,s),o=t.id||`${t.kind||"node"}-${Date.now()}`;if(a==="youtubeNode"){const h=t.videoId||Tc(t.url);return{id:o,type:"youtubeNode",position:i,width:360,height:280,data:{videoId:h,...t.title?{title:t.title,sourceTitle:t.title}:{},url:t.url||(h?`https://www.youtube.com/watch?v=${h}`:""),processingStatus:null,aiProcessed:!1,metadata:Vn(t)}}}if(a==="pdfNode"){const h=t.fileName||t.title||"Document.pdf",y=String(t.url||""),f=y.startsWith("/api/")?$t(y):y;return{id:o,type:"pdfNode",position:i,width:360,height:480,data:{title:h,fileName:h,url:f,processingStatus:null,aiProcessed:!1,metadata:Vn(t)}}}if(a==="websiteNode")return{id:o,type:"websiteNode",position:i,width:420,height:320,data:{url:t.url||"",title:t.title||t.url||"Website",metadata:Vn(t)}};if(a==="imageNode"){const h=t.url||"";return{id:o,type:"imageNode",position:i,data:{publicUrl:h,content:h,url:h,title:t.title||"Image",metadata:Vn(t)}}}const d=t.text||"";let p;try{p=ui(d)}catch{p=[{type:"paragraph",content:[]}]}return{id:o,type:"blockNoteNode",position:i,width:360,height:480,data:{title:t.title||"Note",content:JSON.stringify(p),initialContent:p,metadata:"From AI"}}}function ka(t,r={}){const s=is.getState(),a=r.reactFlowInstance??null;try{switch(t.op){case"create_node":{const i=Pc(t,a,r.screenAnchor);s.setNodes(o=>[...o,i]);break}case"connect":{if(!t.source||!t.target)return;const i={id:`edge-${t.source}-${t.target}-${Date.now()}`,source:t.source,target:t.target,type:"default"};s.setEdges(o=>o.some(p=>p.source===t.source&&p.target===t.target)?o:[...o,i]);break}case"move":{if(!t.id)return;s.setNodes(i=>i.map(o=>o.id===t.id?{...o,position:{x:t.x??o.position.x,y:t.y??o.position.y}}:o));break}case"delete":{if(!t.id)return;
37const i=is.getState().nodes||[],o=new Set([t.id]);let d=!0;for(;d;){d=!1;for(const p of i){const h=p.parentNode??p.parentId;h&&o.has(h)&&!o.has(p.id)&&(o.add(p.id),d=!0)}}s.setNodes(p=>p.filter(h=>!o.has(h.id))),s.setEdges(p=>p.filter(h=>!o.has(h.source)&&!o.has(h.target)));break}case"group":break;default:console.warn("[canvasActionExecutor] unknown action op:",t==null?void 0:t.op)}}catch(i){console.error("[canvasActionExecutor] failed to apply action:",t,i)}}function Lo(t,r,s){var i;const a=((i=r==null?void 0:r.getViewport)==null?void 0:i.call(r))||{x:0,y:0,zoom:1};return{x:t.x*a.zoom+a.x+Number((s==null?void 0:s.x)||0),y:t.y*a.zoom+a.y+Number((s==null?void 0:s.y)||0)}}function en(t){if(!t)return null;const r=document.querySelector(`[data-id="${t}"]`);if(!r)return null;const s=r.getBoundingClientRect();return{x:s.left+s.width/2,y:s.top+s.height/2}}function zo(t,r={}){const s=r.reactFlowInstance??null;if(t.op==="create_node"){const a=Ni[t.kind||"note"]||"textNode",i=Ci(t,a,s,r.screenAnchor),o={...t,x:i.x,y:i.y,_preplaced:!0};return{screenPoint:Lo(i,s,r.screenOffset),resolvedAction:o}}if(t.op==="move")return{screenPoint:en(t.id)||(typeof t.x=="number"&&typeof t.y=="number"?Lo({x:t.x,y:t.y},s,r.screenOffset):null),resolvedAction:t};if(t.op==="delete")return{screenPoint:en(t.id),resolvedAction:t};if(t.op==="connect")return{screenPoint:en(t.source)||en(t.target),resolvedAction:t};if(t.op==="group"){const a=(t.ids||[]).map(o=>en(o)).filter(Boolean);return{screenPoint:a.length?{x:a.reduce((o,d)=>o+d.x,0)/a.length,y:a.reduce((o,d)=>o+d.y,0)/a.length}:null,resolvedAction:t}}return{screenPoint:null,resolvedAction:t}}let Do=!1;function tn(t){if(!t)return;if(!Do&&typeof document<"u"){const s=document.createElement("style");s.textContent=`
38      @keyframes cg-operator-pulse {
39        0%   { box-shadow: 0 0 0 0 rgba(124,58,237,0.55); }
40        70%  { box-shadow: 0 0 0 16px rgba(124,58,237,0); }
41        100% { box-shadow: 0 0 0 0 rgba(124,58,237,0); }
42      }
43      .cg-operator-pulse { animation: cg-operator-pulse 0.75s ease-out; border-radius: 12px; }
44    `,document.head.appendChild(s),Do=!0}const r=document.querySelector(`[data-id="${t}"]`);r&&(r.classList.add("cg-operator-pulse"),setTimeout(()=>r.classList.remove("cg-operator-pulse"),800))}const Ic={a:1,an:1,one:1,two:2,three:3,four:4,five:5,six:6},Ka=String.raw`\d+|a|an|one|two|three|four|five|six`,Ja=String.raw`youtube(?:\s+(?:videos?|clips?))?|videos?\s+(?:from|on)\s+youtube|videos?|clips?`,Xa=String.raw`pdfs?(?:\s+(?:files?|documents?|papers?))?|research\s+papers?|papers?\s+(?:as\s+)?pdfs?`,Ec={youtube:new RegExp(`\\b(?:${Ja})\\b`,"gi"),pdf:new RegExp(`\\b(?:${Xa})\\b`,"gi")};function Lc(t=""){const r=t.toLowerCase().trim(),s=Ic[r]??Number(r);return Number.isFinite(s)?Math.max(1,Math.min(6,Math.round(s))):null}function zc(t,r){const s=new RegExp(Ec[r].source,"gi");return Array.from(t.matchAll(s))}function Fo(t,r){const s=Number(r.index||0),i=t.slice(Math.max(0,s-48),s).match(new RegExp(String.raw`(?:\b(?:exactly|only)\s+)?\b(${Ka})\s*$`,"i")),o=i?Lc(i[1]):null;if(o!==null)return{count:o,explicit:!0};const d=String(r[0]||"");return{count:/\b(?:videos|clips|pdfs|files|documents|papers)\b/i.test(d)?4:1,explicit:!1}}function Dc(t){const r=s=>new RegExp(String.raw`(?:\b(?:exactly|only)\s+)?(?:\b(?:${Ka})\s+)?\b(?:${s})\b`,"gi");return t.replace(r(Ja)," ").replace(r(Xa)," ")}function Fc(t){return Dc(t).replace(/^\/agent\b/i," ").replace(/\b(?:find|search\s+for|search|look(?:ing)?\s+for|show|bring|pull|surface|add|put|drop|get|give|fetch|want|need|would|like|can|could|you|i|me|please|exactly|only)\b/gi," ").replace(/\b(?:as\s+well\s+as|and|plus|together)\b/gi," ").replace(/[“”"'()[\]{}?!,;:]+/g," ").replace(/\s+/g," ").trim().replace(/^(?:about|on|for|of|regarding|covering|related\s+to)\s+/i,"").trim()}function Oc(t){const r=String(t||"").trim();if(!r||!(/\b(find|search(?:\s+for)?|look(?:ing)?\s+for|show|bring|pull|surface|add|put|drop|get|give|fetch|want|need)\b/i.test(r)||new RegExp(String.raw`^\s*(?:exactly\s+|only\s+)?(?:${Ka})\s+(?:${Ja}|${Xa})\b`,"i").test(r)))return null;const a={youtube:0,pdf:0},i={youtube:!1,pdf:!1},o=[];if(["youtube","pdf"].forEach(p=>{const h=zc(r,p);if(!h.length)return;const f=h.map(u=>({match:u,parsed:Fo(r,u)})).find(({parsed:u})=>u.explicit)||{match:h[0],parsed:Fo(r,h[0])};a[p]=f.parsed.count,i[p]=f.parsed.explicit,o.push({kind:p,index:Number(f.match.index||0)})}),a.youtube===0&&a.pdf===0)return null;const d=Fc(r);return d?{query:d,counts:a,explicitCounts:i,order:o.sort((p,h)=>p.index-h.index).map(({kind:p})=>p)}:null}function Bc(t){return t.counts.youtube<=0?t.query:`Find YouTube video about ${t.query}`}function Mc(t){const r=String((t==null?void 0:t.kind)||(t==null?void 0:t.type)||"").toLowerCase();return r==="youtube"||r==="youtubenode"?"youtube":r==="pdf"||r==="pdfnode"?"pdf":null}function Uc(t){const r={youtube:0,pdf:0},s=()=>({...r}),a=()=>({youtube:Math.max(0,t.counts.youtube-r.youtube),pdf:Math.max(0,t.counts.pdf-r.pdf)});return{accept(i){if((i==null?void 0:i.op)!=="create_node")return!0;const o=Mc(i);return!o||t.counts[o]<=r[o]?!1:(r[o]+=1,!0)},accepted:s,remaining:a,isSatisfied(){const i=a();return i.youtube===0&&i.pdf===0}}}function Vc(t,r){const s=(t==null?void 0:t.tool)==="youtube"?"youtube":(t==null?void 0:t.tool)==="pdf"?"pdf":null;if(!s||t.stage!=="found"||r.counts[s]<=0)return t;const a=r.counts[s];return{...t,label:`Found ${a} ${s==="youtube"?"video":"PDF"}${a===1?"":"s"}`,items:Array.isArray(t.items)?t.items.slice(0,a):t.items}}function Oo(t,r){const s=["youtube","pdf"].filter(o=>r[o]>0).map(o=>{const d=r[o];return`${d} ${o==="youtube"?"YouTube video":"PDF"}${d===1?"":"s"}`}),a=["youtube","pdf"].filter(o=>r[o]<t.counts[o]).map(o=>{const d=t.counts[o]-r[o];return`${d} ${o==="youtube"?"YouTube video":"PDF"}${d===1?"":"s"}`});return a.length===0?`Found exactly ${s.join(" and ")} about “${t.query}”. Drag or tap + on any card below to add it to the board.`:`${s.length?`Found ${s.join(" and ")}, but`:"I couldn't complete the request because"} I couldn't find ${a.join(" and ")} about “${t.query}”.`}const Wc=/\b(?:on\s+(?:the\s+)?(?:screen|board|canvas)|like\s+(?:this|that|these|those|the|it)|similar(?:\s+to)?|more\s+(?:like|of)|the\s+ones?|these|those)\b/i,Hc=new Set(["the","of","a","an","to","and","on","in","for","with","is","are","
44was","how","why","what","who","dr","ep","vs","from","by","at","this","that","your","you","new","official","video","videos","music","full","part","feat","ft","hd","4k"]);function qc(t){return Wc.test(String(t||""))}function Za(t){return String(t||"").toLowerCase().replace(/\s+/g," ").trim()}function _i(t){const r=String(t||"").match(/(?:youtube\.com\/(?:watch\?v=|shorts\/|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);return r?r[1]:""}function Jn(t){const r=t==null?void 0:t.data;return String((r==null?void 0:r.title)||(r==null?void 0:r.sourceTitle)||(r==null?void 0:r.videoTitle)||(r==null?void 0:r.pageName)||(r==null?void 0:r.label)||"").trim()}function Da(t){var a,i;const r=String((t==null?void 0:t.type)||"").toLowerCase(),s=String(((a=t==null?void 0:t.data)==null?void 0:a.url)||"");return r.includes("youtube")||r.includes("tiktok")||((i=t==null?void 0:t.data)==null?void 0:i.kind)==="youtube"||/youtube\.com|youtu\.be|tiktok\.com/.test(s)}function Gc(t){return Za(t).replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(r=>r.length>=3&&!Hc.has(r)&&!/^\d+$/.test(r))}function Bo(t,r=6){const s=new Map,a=new Map;t.forEach(p=>{const h=new Set;Gc(p).forEach(y=>{s.set(y,(s.get(y)||0)+1),h.has(y)||(a.set(y,(a.get(y)||0)+1),h.add(y))})});const i=Array.from(s.keys());i.sort((p,h)=>(a.get(h)||0)-(a.get(p)||0)||(s.get(h)||0)-(s.get(p)||0));const o=t.length>1?i.filter(p=>(a.get(p)||0)>=2):i;return(o.length?o:i).slice(0,r).join(" ")}function Yc(t,r,s){if(!qc(t))return r;const a=Array.isArray(s)?s:[],i=a.filter(y=>(y==null?void 0:y.selected)&&Da(y)),o=a.filter(Da),p=(i.length?i:o).map(Jn).filter(Boolean);if(p.length)return Bo(p)||p[0];const h=Jn(a.find(y=>Jn(y)));return h?Bo([h])||h:r}function Kc(t){const r=new Set;return(Array.isArray(t)?t:[]).forEach(s=>{var o,d;if(!Da(s))return;const a=String(((o=s==null?void 0:s.data)==null?void 0:o.videoId)||_i(((d=s==null?void 0:s.data)==null?void 0:d.url)||""));a&&r.add("v:"+a);const i=Za(Jn(s));i&&r.add("t:"+i)}),r}function Jc(t,r){const s=String((t==null?void 0:t.videoId)||_i((t==null?void 0:t.url)||""));if(s&&r.has("v:"+s))return!0;const a=Za(String((t==null?void 0:t.title)||""));return!!(a&&r.has("t:"+a))}const Xc=["<role>","You are the intent router for a visual canvas research assistant. The user is","looking at a board of cards (YouTube videos, PDFs, notes) and is talking to an","assistant beside it. You decide, for the user's LATEST message, exactly ONE","action: FIND resources to add to the board (videos or pdfs), or ANSWER in text.","</role>","","<critical>","The conversation history is the MOST IMPORTANT input. Short follow-ups only make","sense in context. You MUST read the prior turns and resolve every pronoun and",'ellipsis ("more", "another", "these", "those", "the ones", "like that", "he",','"it", "older", "newer", "different") against them BEFORE deciding.',"","STRONG BIAS: if the previous assistant turn FOUND videos/pdfs (or the user is","clearly browsing resources) and the new message is a short continuation such as",'"find more", "more", "another", "keep going", "find older ones", "newer ones",','"different ones", "no find more" — this is NOT a question. It means CONTINUE',"finding the SAME kind of resource about the SAME subject. Choose videos/pdfs,","never answer. Only choose answer when the user genuinely asks to be told or","explained something.","</critical>","","<modes>",'videos — the user wants YouTube videos ON the board. Triggers: "find/add/get/','  show/pull videos", "more like these", "similar videos", and (in a video-','  finding flow) bare follow-ups like "find more", "older ones", "no find more".',"pdfs — the user wants PDFs / papers / documents / research on the board.","answer — the user wants something explained, summarized, compared, or a","  question answered in words (NOT added to the board).","</modes>","","<query_rules>","For videos/pdfs, write query as a clean web-search string, 2-8 words:",'- Resolve context: after MrBeast videos, "find older ones" -> "MrBeast earliest','  first videos"; "find more" -> the subject of the last search.','- "like the ones on the screen"/"like these" -> the board videos SHARED topic',`  (e.g. "Dr Joshua Little hadith criticism"), NOT one video's exact title.`,"- If the user quotes a specific term or name, keep it EXACTLY.",'- NEVER put pronouns or filler ("more", "like", "ones", "the one on the screen")',"  in the query. NEVER use a whole verbatim video title.",'For answer mode, query is a short topic label (or "").',"</query_rules>","","<count>1-6, default 4. For a fresh 'find more' use 4.</count>","","<examples>",'History: (assistant just found 4 MrBeast videos) | User: "find more" ->','  {"mode":"videos","query":"MrBeast videos","count":4}','History: (MrBeast videos) | User: "no find older ones, when he first started" ->','  {"mode":"videos","query":"MrBeast earliest first videos 2012","count":4}','Board has Dr Joshua Little hadith videos | User: "find videos like these" ->','  {"mode":"videos","query":"Dr Joshua Little hadith criticism","count":4}','User: "add 3 pdfs about spatial computing" ->','  {"mode":"pdfs","query":"spatial computing","count":3}','User: "explain the refutations against Joshua Little" ->','  {"mode":"answer","query":"Joshua Little refutations","count":4}','User: "what is this board about?" -> {"mode":"answer","query":"","count":4}',"</examples>","","<output>","Respond with ONLY a single-line JSON object. No prose, no explanation, no","markdown fences. Exactly these keys:",'{"mode":"videos"|"pdfs"|"answer","query":string,"count":number}',"</output>"].join(`
45`);function Zc(t,r=24){const s=o=>{var d,p,h,y,f;return String(((d=o==null?void 0:o.data)==null?void 0:d.title)||((p=o==null?void 0:o.data)==null?void 0:p.sourceTitle)||((h=o==null?void 0:o.data)==null?void 0:h.videoTitle)||((y=o==null?void 0:o.data)==null?void 0:y.pageName)||((f=o==null?void 0:o.data)==null?void 0:f.label)||"").trim()},a=o=>{var p;const d=String((o==null?void 0:o.type)||"").toLowerCase();return d.includes("youtube")||d.includes("tiktok")||((p=o==null?void 0:o.data)==null?void 0:p.kind)==="youtube"},i=(Array.isArray(t)?t:[]).map(o=>{const d=s(o);return d?`- ${a(o)?"[video] ":""}${d}`:""}
45).filter(Boolean).slice(0,r);return i.length?i.join(`
46`):"(the board is empty)"}function Qc(t){const r=(t.history||[]).slice(-6),s=r.length?r.map(i=>`${i.role==="user"?"User":"Assistant"}: ${i.content}`).join(`
47`):"(no earlier messages)",a=["Board content:",t.boardSummary,"","Recent conversation:",s,"",`User's latest message: ${t.prompt}`,"","JSON:"].join(`
48`);return[{role:"user",content:`${Xc}
49
50${a}`}]}function ed(t){const s=String(t||"").match(/\{[\s\S]*\}/);if(!s)return null;let a;try{a=JSON.parse(s[0])}catch{return null}const i=String((a==null?void 0:a.mode)||"").toLowerCase();if(i!=="videos"&&i!=="pdfs"&&i!=="answer")return null;const o=String((a==null?void 0:a.query)||"").trim();if((i==="videos"||i==="pdfs")&&!o)return null;let d=Number(a==null?void 0:a.count);return Number.isFinite(d)||(d=4),d=Math.max(1,Math.min(6,Math.round(d))),{mode:i,query:o,count:d}}const td=600;function ja(t){return!!(t&&Number.isFinite(Number(t.x))&&Number.isFinite(Number(t.y)))}function Mo(t,r){const s=typeof t=="string"?Number.parseFloat(t):Number(t);return Number.isFinite(s)&&s>0?s:r}function rd(t){var s,a;const r=(t==null?void 0:t.type)==="threadNode"?{width:720,height:600}:(t==null?void 0:t.type)==="pdfNode"?{width:360,height:480}:{width:360,height:280};return{width:Mo((t==null?void 0:t.width)??((s=t==null?void 0:t.style)==null?void 0:s.width),r.width),height:Mo((t==null?void 0:t.height)??((a=t==null?void 0:t.style)==null?void 0:a.height),r.height)}}function Wn(t){var s,a;const r=rd(t);return{x:Number(((s=t.position)==null?void 0:s.x)||0)+r.width/2,y:Number(((a=t.position)==null?void 0:a.y)||0)+r.height/2}}function sd(t,r){return Math.hypot(t.x-r.x,t.y-r.y)}function nd({nodes:t,pointer:r,fallback:s}){var d;const a=Array.isArray(t)?t.filter(p=>ja(p==null?void 0:p.position)):[],i=a.find(p=>p.selected&&p.type==="threadNode");if(i)return{anchor:Wn(i),node:i,kind:"thread"};const o=a.find(p=>p.selected);if(o)return{anchor:Wn(o),node:o,kind:"node"};if(ja(r)){const p=(d=a.filter(h=>h.type==="threadNode").map(h=>({node:h,distance:sd(Wn(h),r)})).filter(h=>h.distance<td).sort((h,y)=>h.distance-y.distance)[0])==null?void 0:d.node;return p?{anchor:Wn(p),node:p,kind:"thread"}:{anchor:r,node:null,kind:"pointer"}}return{anchor:ja(s)?s:{x:0,y:0},node:null,kind:"fallback"}}function ad(t,r,s){const a=Number((r==null?void 0:r.zoom)||1);return{x:t.x*a+Number((r==null?void 0:r.x)||0)+Number((s==null?void 0:s.x)||0),y:t.y*a+Number((r==null?void 0:r.y)||0)+Number((s==null?void 0:s.y)||0)}}function od(t,r,s){const a=Math.max(1e-4,Number((r==null?void 0:r.zoom)||1));return{x:(t.x-Number((s==null?void 0:s.x)||0)-Number((r==null?void 0:r.x)||0))/a,y:(t.y-Number((s==null?void 0:s.y)||0)-Number((r==null?void 0:r.y)||0))/a}}function id(t){return`${String(t||"Research paper").normalize("NFKD").replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"_").slice(0,72)||"Research_paper"}.pdf`}function ld({request:t,batchId:r,papers:s}){return(Array.isArray(s)?s:[]).filter(a=>{var i;return!!((i=a==null?void 0:a.openAccessPdf)!=null&&i.url)}).slice(0,t.counts.pdf).map((a,i)=>{var d;const o=new URLSearchParams({url:String(((d=a.openAccessPdf)==null?void 0:d.url)||"")});return a.doi&&o.set("doi",String(a.doi)),a.paperId&&o.set("paperId",String(a.paperId)),{op:"create_node",kind:"pdf",id:`pdf-${r}-${i+1}`,title:String(a.title||"Research paper"),fileName:id(a.title),url:`/api/proxy/pdf?${o.toString()}`}})}async function cd({request:t,batchId:r,fetcher:s=fetch}){if(t.counts.pdf<=0)return[];const{buildChatgridAiBackendUrl:a}=await Ua(async()=>{const{buildChatgridAiBackendUrl:p}=await import("./serverApi-QuCfAnKQ.js");return{buildChatgridAiBackendUrl:p}},__vite__mapDeps([0,1,2])),i=new URLSearchParams({query:t.query,limit:String(Math.max(1,t.counts.pdf)),oaOnly:"true"}),o=await s(a(`/api/search/papers?${i.toString()}`));if(!o.ok)throw new Error(`PDF search failed (${o.status})`);const d=await o.json();return ld({request:t,batchId:r,papers:Array.isArray(d==null?void 0:d.data)?d.data:[]})}const Fa="application/x-chatgrid-source-artifact";function dd(t){return t.op!=="create_node"||t.kind!=="youtube"&&t.kind!=="pdf"||!t.url?null:{id:t.
50id||`${t.kind}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,kind:t.kind,title:t.title||t.fileName||(t.kind==="youtube"?"YouTube video":"PDF"),url:t.url,videoId:t.videoId,fileName:t.fileName}}function Uo(t,r,s){return{op:"create_node",id:`${t.kind}-source-${s}`,kind:t.kind,title:t.title,fileName:t.fileName,url:t.url,videoId:t.videoId,x:r.x,y:r.y,_preplaced:!0,sourceId:t.id}}function ud(t){return JSON.stringify({id:t.id,kind:t.kind,title:t.title,url:t.url,videoId:t.videoId,fileName:t.fileName})}function pd(t){try{const r=JSON.parse(String(t||""));return!r||r.kind!=="youtube"&&r.kind!=="pdf"||typeof r.id!="string"||typeof r.title!="string"||typeof r.url!="string"||!r.url?null:{id:r.id,kind:r.kind,title:r.title,url:r.url,videoId:typeof r.videoId=="string"?r.videoId:void 0,fileName:typeof r.fileName=="string"?r.fileName:void 0}}catch{return null}}function Vo({identity:t}){const r=ci(),s=Zi(),a=()=>{const i=`${s.pathname}${s.search}`;r(`/login?redirect=${encodeURIComponent(i)}`)};return e.jsx("div",{className:"fixed bottom-4 left-1/2 -translate-x-1/2 z-[9998] animate-in fade-in slide-in-from-bottom-2 duration-500",children:e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 rounded-full bg-black/80 text-white text-sm font-medium shadow-lg backdrop-blur-sm border border-white/10",children:[e.jsx("div",{className:"w-2.5 h-2.5 rounded-full shrink-0",style:{backgroundColor:t.color}}),e.jsxs("span",{className:"opacity-90",children:["Viewing as ",e.jsx("span",{className:"font-bold",children:t.name})]}),e.jsx("span",{className:"opacity-40",children:"|"}),e.jsxs("button",{onClick:a,className:"flex items-center gap-1.5 text-white/80 hover:text-white transition-colors",children:[e.jsx(Yl,{size:14}),e.jsx("span",{children:"Sign in to save your work"})]})]})})}const Wo="chatgrid:vault:recent",Ho="chatgrid:vault:saved",qo="chatgrid:vault:watchlist",hd=20;function Sa(t){try{const r=localStorage.getItem(t);if(!r)return[];const s=JSON.parse(r);return Array.isArray(s)?s:[]}catch(r){return console.error(`Failed to read ${t}:`,r),[]}}function Na(t,r){try{localStorage.setItem(t,JSON.stringify(r))}catch(s){console.error(`Failed to write ${t}:`,s)}}const fd={Today:"today","Last 7 days":"this_week","Last 30 days":"this_month","Viral now":"this_week"},gd={"Under 50k":{maxFollowers:5e4},"50k-250k":{minFollowers:5e4,maxFollowers:25e4},"250k+":{minFollowers:25e4}},md={Fitness:["fitness","gym","workout","muscle","protein","yoga","sport"],Beauty:["beauty","skin","skincare","makeup","hair","lip","face","serum","cosmetic","nail"],Home:["home","kitchen","cleaning","decor","bed","bath","organizer"],Tech:["tech","electronic","wireless","charger","led","smart","phone","earbud","camera"]};function xd(t,r){const s=md[r];if(!s)return t;const a=t.filter(i=>s.some(o=>i.title.toLowerCase().includes(o)));return a.length?a:t}function bd(t,r){let s=t;return r==="Video"||r==="UGC"?s=t.filter(a=>a.videoUrls.length>0):r==="Static"?s=t.filter(a=>a.videoUrls.length===0&&a.imageUrls.length>0):r==="Carousel"&&(s=t.filter(a=>String(a.displayFormat||"").toLowerCase().includes("carousel"))),s.length?s:t}async function yd(){const t={"Content-Type":"application/json"};try{const{data:{session:r}}=await Et.auth.getSession();r!=null&&r.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}catch(r){console.error("Failed to get auth session:",r)}return t}function wd(){const[t,r]=n.useState(null),[s,a]=n.useState(!1),[i,o]=n.useState(null),[d,p]=n.useState(()=>Sa(Wo)),[h,y]=n.useState(()=>Sa(Ho)),[f,u]=n.useState(()=>Sa(qo));n.useEffect(()=>Na(Wo,d),[d]),n.useEffect(()=>Na(Ho,h),[h]),n.useEffect(()=>Na(qo,f),[f]);const $=n.useCallback(L=>{p(_=>{const J=_.filter(O=>!(O.query.toLowerCase()===L.query.toLowerCase()&&O.type===L.type));return J.unshift({...L,id:`${L.type}:${L.query.toLowerCase()}`,at:new Date().toISOString()}),J.slice(0,hd)})},[]),N=n.useCallback(async({type:L,query:_,platform:J="All",filter:O=""})=>{var Z;const U=_.trim();if(U){a(!0),o(null),$({query:U,type:L,platform:J,filter:O});try{const b=await yd(),q={type:L,query:U,platform:J,filter:O,products:[],ads:[],videos:[],creators:[],advertiser:null,notice:null};if(L==="products"){const Q=await fetch($t("/api/vault/products"),{method:"POST",headers:b,body:JSON.stringify({query:U,limit:36})}),P=await Q.json();if(!Q.ok)throw new Error((P==null?void 0:P.error)||"Product search failed");const Ne=xd(P.products||[],O);r({...q,products:Ne})}else if(L==="ads"){const Q=await fetch($t("/api/vault/ads"),{method:"POST",headers:b,body:JSON.stringify({query:U,platform:J==="Instagram"?"instagram":J==="Google"?"google":"facebook",limit:36})}),P=await Q.json();if(!Q.ok)throw new Error((P==null?void 0:P.error)||"Ad search failed");const Ne=bd(P.ads||[],O);r({...q,ads:Ne,advertiser:P.advertiser||null,notice:P.intentNote||null})}else if(L==="influencers"){const Q=await fetch($t("/api/vault/creators"),{method:"POST",headers:b,body:JSON.stringify({query:U,...gd[O],limit:12})}),P=await Q.json();if(!Q.ok)throw new Error((P==null?void 0:P.error)||"Influencer search failed");r({...q,creators:P.creators||[],notice:(Z=P.warnings)!=null&&Z.length?P.warnings[0]:null})}else{const Q=await fetch($t("/api/vault/videos"),{method:"POST",headers:b,body:JSON.stringify({query:U,platform:J==="YouTube"?"youtube":"tiktok",timePeriod:fd[O]||"this_week",limit:36})}),P=await Q.json();if(!Q.ok)throw new Error((P==null?void 0:P.error)||"Video search failed");r({...q,videos:P.videos||[]})}}catch(b){console.error("Vault search failed:",b),o(b instanceof Error?b.message:"Search failed"),r(null)}finally{a(!1)}}},[$]),C=n.useCallback(()=>{r(null),o(null)},[]),F=n.useCallback(L=>{y(_=>_.some(J=>J.id===L.id)?_.filter(J=>
50J.id!==L.id):[{...L,savedAt:new Date().toISOString()},..._])},[]),te=n.useCallback(L=>h.some(_=>_.id===L),[h]),E=n.useCallback(L=>{u(_=>_.some(J=>J.id===L.id)?_.filter(J=>J.id!==L.id):[{...L,addedAt:new Date().toISOString()},..._])},[]),Y=n.useCallback(L=>f.some(_=>_.id===L),[f]),V=n.useCallback(L=>{p(_=>_.filter(J=>J.id!==L))},[]);return{results:t,isSearching:s,error:i,search:N,clearResults:C,recent:d,removeRecent:V,saved:h,toggleSaved:F,isSaved:te,watchlist:f,toggleWatch:E,isWatched:Y}}function Zn(t){return t===null?"—":t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(t>=1e4?0:1)}k`:String(t)}function Cs(t){return Zn(t)}function Go(t){const r=new Date(t).getTime();if(Number.isNaN(r))return"";const s=Math.max(1,Math.round((Date.now()-r)/6e4));if(s<60)return`${s}m ago`;const a=Math.round(s/60);if(a<24)return`${a}h ago`;const i=Math.round(a/24);return i===1?"yesterday":`${i} days ago`}const Qa="#3d7fce",vd="rgba(74,144,226,0.16)",xr="#7fb2ee",Ns=[.16,1,.3,1],kd=640,_s=[{id:"products",label:"Winning products",icon:Si,placeholder:"Find hot products… e.g. led face mask",platforms:["TikTok Shop"]},{id:"ads",label:"Paid ads",icon:Va,placeholder:"Spy on a brand or niche… e.g. Gymshark, or competitors of a domain",platforms:["Facebook","Instagram","Google"]},{id:"trending",label:"Trending videos",icon:ls,placeholder:"Search trending videos… e.g. skincare routine",platforms:["TikTok","YouTube"]},{id:"influencers",label:"Influencers",icon:Wa,placeholder:"Find creators by niche… e.g. fitness under 50k",platforms:["TikTok"]}],Mr={products:["All categories","Fitness","Beauty","Home","Tech"],ads:["All formats","Static","Video","Carousel"],trending:["Last 7 days","Today","Last 30 days"],influencers:["Any size","Under 50k","50k-250k","250k+"]},It=_s.reduce((t,r)=>(t[r.id]=r,t),{}),$i={products:"Category",ads:"Format",trending:"Window",influencers:"Creator size"},jd="Ask ChatGrid…",Sd="Search posts, ads, products, and creators…",Yo=[{rotate:-9,y:12},{rotate:-3,y:2},{rotate:3,y:2},{rotate:9,y:12}],ln={border:"1px solid rgba(255,255,255,.10)",borderRadius:999,padding:"2px 8px",color:"rgba(237,237,240,.58)",fontSize:12,whiteSpace:"nowrap"},ra={...ln,border:"1px solid rgba(61,127,206,.35)",color:xr,background:"rgba(61,127,206,.10)"},sa={borderRadius:14,border:"1px solid rgba(255,255,255,.10)",background:"linear-gradient(180deg, rgba(255,255,255,.055), rgba(255,255,255,.02))",display:"flex",flexDirection:"column",overflow:"hidden"},rn={width:30,height:30,borderRadius:8,border:"1px solid rgba(255,255,255,.10)",background:"rgba(10,10,12,.78)",color:"#a2a2a8",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer"};function Nd({autoExpand:t,onClose:r}){const[s,a]=n.useState(!1),[i,o]=n.useState(null),[d,p]=n.useState(null),[h,y]=n.useState("TikTok"),[f,u]=n.useState("Last 7 days"),[$,N]=n.useState(""),[C,F]=n.useState(null),[te,E]=n.useState("home"),[Y,V]=n.useState("recent"),[L,_]=n.useState([]),[J,O]=n.useState(0),U=wd(),{search:Z,clearResults:b}=U;n.useEffect(()=>{if(!t)return;const v=requestAnimationFrame(()=>a(!0));return()=>cancelAnimationFrame(v)},[t]);const q=d??i,Q=q?It[q]:null,P=i?It[i]:It.trending,Ne=(Q==null?void 0:Q.placeholder)??(s?Sd:jd),m=$.trim().length>0&&!U.isSearching,ue=()=>{a(!1),window.setTimeout(()=>{o(null),p(null),E("home"),N(""),_([]),b(),r&&r()},kd)},ce=v=>{o(v),y(It[v].platforms[0]),u(Mr[v][0])},Oe=v=>{o(v.type),y(v.platform),u(v.filter),N(v.query),E("results"),Z(v)},j=()=>{if(!m)return;const v=i??"trending";Oe({type:v,query:$.trim(),platform:i?h:It[v].platforms[0],filter:i?f:Mr[v][0]})},I=v=>{_(be=>be.some(M=>M.url===v.url)?be.filter(M=>M.url!==v.url):[...be,v])},me=()=>{L.length&&(window.dispatchEvent(new CustomEvent("chatgrid:vault-add-to-canvas",{detail:{items:L}})),O(v=>v+L.length),_([]))},D=()=>{E("home"),b()};return e.jsxs("div",{style:{position:"relative",width:"100%",maxWidth:1060,margin:"0 auto",color:"#ededf0",fontFamily:"inherit"},children:[e.jsx(_e.div,{"aria-hidden":!0,initial:!1,animate:{opacity:s?1:0},transition:{duration:.55,ease:Ns},style:{position:"fixed",inset:0,zIndex:-1,pointerEvents:"none",backgroundColor:"#0d0d0f",backgroundImage:"linear-gradient(rgba(255,255,255,.04) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.04) 1px, transparent 1px)",backgroundSize:"40px 40px"}}),te==="results"?e.jsx(Cd,{vault:U,source:P,query:$,setQuery:N,platform:h,modeFilter:f,staged:L,stageItem:I,commitStaged:me,stackCount:J,onBack:D,onClose:ue,runSearch:Oe}):e.jsxs(e.Fragment,{children:[e.jsx(Jt,{initial:!1,children:s&&e.jsxs(_e.div,{initial:{height:0,opacity:0}
50,animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.5,ease:Ns},style:{overflow:"hidden"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:16,marginBottom:16,padding:"0 4px"},children:[e.jsxs("div",{style:{minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{style:{fontFamily:"Georgia, serif",fontSize:18},children:"Viral Vault"}),e.jsx("span",{style:{fontSize:11,color:"#6c6c72",border:"1px solid rgba(255,255,255,.10)",borderRadius:999,padding:"1px 8px"},children:"Beta"}),J>0&&e.jsxs("span",{style:ra,children:[J," on canvas"]})]}),e.jsx("div",{style:{marginTop:10,fontFamily:"Georgia, serif",fontSize:34,lineHeight:"38px",color:"#f7f7f8"},children:"What do you want to find?"}),e.jsx("div",{style:{marginTop:6,maxWidth:520,fontSize:14,lineHeight:"21px",color:"rgba(237,237,240,.58)"},children:"Search products, paid ads, trending videos, and creators with source-aware filters."})]}),e.jsx("button",{onClick:ue,"aria-label":"Close",style:{width:32,height:32,borderRadius:999,background:"rgba(255,255,255,.06)",border:"none",color:"#a2a2a8",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(qt,{size:15})})]}),e.jsx("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-end",gap:16,padding:"18px 2px 12px"},children:_s.map((v,be)=>{const M=v.icon,Ye=d===v.id,ye=i===v.id,Re=Ye||ye;return e.jsxs("button",{onMouseEnter:()=>p(v.id),onMouseLeave:()=>p(null),onClick:()=>ce(v.id),style:{flex:"1 1 0",minWidth:0,height:178,padding:"13px 13px 0",display:"flex",flexDirection:"column",cursor:"pointer",borderRadius:16,border:`2px solid ${Re?Qa:"rgba(255,255,255,.10)"}`,background:"#161619",transformOrigin:"bottom center",transform:Ye?"rotate(0deg) translateY(-10px) scale(1.025)":`rotate(${Yo[be].rotate/2}deg) translateY(${Yo[be].y/2}px)`,boxShadow:Ye?"0 24px 44px rgba(0,0,0,.6), 0 6px 14px rgba(0,0,0,.4)":"0 8px 20px rgba(0,0,0,.45), 0 2px 5px rgba(0,0,0,.35)",zIndex:Ye?5:1,transition:"transform .22s ease, box-shadow .22s ease, border-color .22s ease"},children:[e.jsx("div",{style:{flex:1,background:"#0b0b0d",border:"1px solid rgba(255,255,255,.10)",borderRadius:12,display:"flex",alignItems:"center",justifyContent:"center",marginBottom:9},children:e.jsx(M,{size:38,strokeWidth:1.5,color:Re?xr:"#a2a2a8",style:{transition:"color .22s ease"}})}),e.jsx("div",{style:{textAlign:"center",fontSize:13,fontWeight:500,paddingBottom:11},children:v.label})]},v.id)})})]},"above")}),e.jsxs("div",{style:{border:"1px solid rgba(255,255,255,.10)",background:"rgba(20,20,22,.92)",borderRadius:24,boxShadow:"0 24px 70px rgba(0,0,0,.5)",backdropFilter:"blur(24px) saturate(160%)",WebkitBackdropFilter:"blur(24px) saturate(160%)",padding:"14px 14px 10px"},children:[e.jsx(_e.textarea,{value:$,onChange:v=>N(v.target.value),onKeyDown:v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),j())},rows:s?3:1,placeholder:Ne,animate:{minHeight:s?76:40},transition:{duration:.5,ease:Ns},style:{width:"100%",resize:"none",background:"transparent",border:"none",outline:"none",padding:"6px 6px 10px",fontSize:15,fontWeight:500,lineHeight:"24px",color:"#fff"}}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[!s&&e.jsx(Ko,{label:"Add",children:e.jsx(Rs,{size:18})}),e.jsx(Ko,{label:"Viral Vault",onClick:()=>s?ue():a(!0),accent:s,children:e.jsx(ea,{size:18})}),e.jsx(Jt,{initial:!1,children:s&&e.jsxs(_e.div,{initial:{opacity:0,width:0},animate:{opacity:1,width:"auto"},exit:{opacity:0,width:0},transition:{duration:.4,ease:Ns},style:{display:"flex",alignItems:"center",gap:8,overflow:"visible"},children:[e.jsx($s,{label:"Platform",value:h,options:P.platforms,onSelect:y}),e.jsx($s,{label:$i[P.id],value:f,options:Mr[P.id],onSelect:u}),e.jsx($s,{label:"Type",value:(Q==null?void 0:Q.label)??"Trending videos",options:_s.map(v=>v.label),accent:!!Q,onSelect:v=>{const be=_s.find(M=>M.label===v);be&&ce(be.id)}})]},"fields")}),e.jsx("div",{style:{flex:1}}),e.jsx("button",{"aria-label":"Search",onClick:j,disabled:!m,style:{width:38,height:38,borderRadius:999,border:"none",display:"flex",alignItems:"center",justifyContent:"center",cursor:m?"pointer":"default",background:m?"#fff":"rgba(255,255,255,.07)",color:m?"#000":"rgba(255,255,255,.45)",transition:"background .18s, color .18s"},children:e.jsx(Ha,{size:17})})]})]}),e.jsx(Jt,{initial:!1,children:s&&e.jsx(_e.div,{initial:{height:0,opacity:0,marginTop:0},animate:{height:"auto",opacity:1,marginTop:20},exit:{height:0,opacity:0,marginTop:0},transition:{duration:.55,ease:Ns},style:{overflow:"hidden"},children:e.jsxs("div",{onMouseLeave:()=>F(null),style:{opacity:C?1:.72,transition:"opacity .22s ease"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,marginBottom:8},children:[e.jsx(_a,{active:Y==="recent",onClick:()=>V("recent"),children:"Recent"}),e.jsxs(_a,{active:Y==="saved",onClick:()=>V("saved"),children:["Saved ",U.saved.length>0?`(${U.saved.length})`:""]}),e.jsxs(_a,{active:Y==="watchlist",onClick:()=>V("watchlist"),children:["Watchlist"," ",U.watchlist.length>0?`(${U.watchlist.length})`:""]})]}),Y==="recent"&&e.jsx(Ca,{empty:"No searches yet. Pick a source card above and search.",rows:U.recent.map(v=>({id:v.id,icon:It[v.type].icon,title:v.query,middle:Go(v.at),right:It[v.type].label,onClick:()=>Oe({type:v.type,query:v.query,platform:v.platform&&It[v.type].platforms.includes(v.platform)?v.platform:It[v.type].platforms[0],filter:v.filter||Mr[v.type][0]}),onRemove:()=>U.removeRecent(v.id)})),hoveredRow:C,setHoveredRow:F}),Y==="saved"&&e.jsx(Ca,{empty:"Nothing saved yet. Star results to keep them here.",rows:U.saved.map(v
50=>({id:v.id,icon:It[v.type].icon,imageUrl:v.imageUrl,title:v.title,middle:v.subtitle,right:It[v.type].label,onClick:()=>{v.url&&window.open(v.url,"_blank")},onRemove:()=>U.toggleSaved(v)})),hoveredRow:C,setHoveredRow:F}),Y==="watchlist"&&e.jsx(Ca,{empty:"Watch creators or brands to track them here.",rows:U.watchlist.map(v=>({id:v.id,icon:It[v.type].icon,imageUrl:v.avatarUrl,title:v.name,middle:Go(v.addedAt),right:It[v.type].label,onClick:()=>Oe({type:v.type,query:v.query,platform:v.platform&&It[v.type].platforms.includes(v.platform)?v.platform:It[v.type].platforms[0],filter:Mr[v.type][0]}),onRemove:()=>U.toggleWatch(v)})),hoveredRow:C,setHoveredRow:F})]})},"library")})]})]})}function Cd({vault:t,source:r,query:s,setQuery:a,platform:i,modeFilter:o,staged:d,stageItem:p,commitStaged:h,stackCount:y,onBack:f,onClose:u,runSearch:$}){const N=n.useRef(null),{results:C,isSearching:F,error:te}=t,E=(C==null?void 0:C.query)??s,Y=L=>{const _=L.type??r.id,J=It[_];$({type:_,query:(L.query??E).trim(),platform:L.platform??(J.platforms.includes(i)?i:J.platforms[0]),filter:L.filter??(Mr[_].includes(o)?o:Mr[_][0])})},V=C?C.type==="products"?C.products.length:C.type==="ads"?C.ads.length:C.type==="influencers"?C.creators.length:C.videos.length:0;return e.jsxs(_e.div,{initial:{opacity:0}
50,animate:{opacity:1},transition:{duration:.3,ease:Ns},onClick:L=>L.stopPropagation(),style:{position:"fixed",inset:0,display:"flex",flexDirection:"column",backgroundColor:"#0d0d0f",backgroundImage:"linear-gradient(rgba(255,255,255,.035) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.035) 1px, transparent 1px)",backgroundSize:"40px 40px",color:"#ededf0"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 18px",borderBottom:"1px solid rgba(255,255,255,.08)",background:"rgba(13,13,15,.88)",backdropFilter:"blur(18px)",WebkitBackdropFilter:"blur(18px)",flexWrap:"wrap"},children:[e.jsx("button",{type:"button",onClick:f,"aria-label":"Back to vault",style:{width:34,height:34,borderRadius:10,border:"1px solid rgba(255,255,255,.10)",background:"rgba(255,255,255,.04)",color:"#a2a2a8",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",flexShrink:0},children:e.jsx(sc,{size:16})}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:"1 1 260px",minWidth:200,height:38,padding:"0 12px",borderRadius:12,border:"1px solid rgba(255,255,255,.12)",background:"rgba(255,255,255,.045)"},children:[e.jsx(fi,{size:14,color:"#6c6c72",style:{flexShrink:0}}),e.jsx("input",{ref:N,value:s,onChange:L=>a(L.target.value),onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),s.trim()&&Y({query:s}))},placeholder:r.placeholder,style:{flex:1,minWidth:0,background:"transparent",border:"none",outline:"none",fontSize:14,color:"#fff"}})]}),e.jsx($s,{label:"Type",value:r.label,options:_s.map(L=>L.label),compact:!0,onSelect:L=>{const _=_s.find(J=>J.label===L);
50_&&_.id!==r.id&&Y({type:_.id})}}),e.jsx($s,{label:"Platform",value:i,options:r.platforms,compact:!0,onSelect:L=>{L!==i&&Y({platform:L})}}),e.jsx($s,{label:$i[r.id],value:o,options:Mr[r.id],compact:!0,onSelect:L=>{L!==o&&Y({filter:L})}}),e.jsx("div",{style:{flex:1}}),!F&&C&&e.jsxs("span",{style:{fontSize:12,color:"rgba(237,237,240,.45)"},children:[V," results"]}),e.jsx("button",{type:"button",onClick:u,"aria-label":"Close vault",style:{width:34,height:34,borderRadius:999,border:"none",background:"rgba(255,255,255,.06)",color:"#a2a2a8",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",flexShrink:0},children:e.jsx(qt,{size:15})})]}),(C==null?void 0:C.notice)&&!F&&e.jsx("div",{style:{padding:"8px 20px",fontSize:12.5,color:xr,background:"rgba(61,127,206,.07)",borderBottom:"1px solid rgba(61,127,206,.14)"},children:C.notice}),e.jsx("div",{style:{flex:1,overflowY:"auto",padding:"18px 18px 120px"},children:F?e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{marginBottom:14,fontSize:13,color:"rgba(237,237,240,.5)"},children:["Searching ",r.label.toLowerCase(),' for "',s.trim(),'"…']}),e.jsx(_d,{})]}):te?e.jsx("div",{style:{maxWidth:520,margin:"60px auto",borderRadius:12,border:"1px solid rgba(248,113,113,.25)",background:"rgba(248,113,113,.08)",padding:"14px 16px",color:"#fca5a5",fontSize:13,textAlign:"center"},children:te}):C?e.jsx($d,{results:C,vault:t,staged:d,stageItem:p}):null}),e.jsx(Jt,{children:(d.length>0||y>0)&&e.jsx(_e.div,{initial:{y:80,opacity:0},animate:{y:0,opacity:1},exit:{y:80,opacity:0},transition:{type:"spring",damping:26,stiffness:380},style:{position:"absolute",bottom:18,left:"50%",transform:"translateX(-50%)",display:"flex",alignItems:"center",gap:12,padding:"10px 14px",borderRadius:18,border:"1px solid rgba(255,255,255,.12)",background:"rgba(18,18,21,.92)",backdropFilter:"blur(20px)",WebkitBackdropFilter:"blur(20px)",boxShadow:"0 18px 50px rgba(0,0,0,.55)"},children:d.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{display:"flex",marginLeft:6},children:d.slice(0,5).map((L,_)=>e.jsx("div",{style:{width:34,height:34,borderRadius:8,border:"1px solid rgba(255,255,255,.2)",background:"#0b0b0d",overflow:"hidden",marginLeft:_===0?0:-10,transform:`rotate(${(_-2)*3}deg)`,flexShrink:0},children:L.thumbnailUrl&&e.jsx("img",{src:L.thumbnailUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}})},L.url))}),e.jsxs("span",{style:{fontSize:13,color:"rgba(237,237,240,.75)"},children:[d.length," staged"]}),e.jsxs("button",{type:"button",onClick:h,style:{display:"flex",alignItems:"center",gap:7,height:36,padding:"0 14px",borderRadius:12,border:"none",background:"#fff",color:"#000",fontSize:13,fontWeight:600,cursor:"pointer"},children:[e.jsx(nc,{size:14}),"Add to canvas"]})]}):e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,color:"rgba(237,237,240,.7)",padding:"0 4px"},children:[e.jsx(cs,{size:14,color:"#4ade80"}),y," stacked on your canvas — close the vault to see them"]})},"tray")})]})}function _d(){return e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))",gap:14},children:[Array.from({length:12},(t,r)=>e.jsx("div",{style:{height:250,borderRadius:14,border:"1px solid rgba(255,255,255,.07)",background:"linear-gradient(90deg, rgba(255,255,255,.035) 25%, rgba(255,255,255,.07) 50%, rgba(255,255,255,.035) 75%)",backgroundSize:"400% 100%",animation:"vaultShimmer 1.2s ease-in-out infinite"}},r)),e.jsx("style",{children:"@keyframes vaultShimmer { 0% { background-position: 100% 0; } 100% { background-position: 0 0; } }"})]})}function $d({results:t,vault:r,staged:s,stageItem:a}){const{isSaved:i,toggleSaved:o,isWatched:d,toggleWatch:p}=r,h=f=>!!(f&&s.some(u=>u.url===f));return(t.type==="products"?t.products:t.type==="ads"?t.ads:t.type==="influencers"?t.creators:t.videos).length?e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))",gap:14},children:[t.type==="products"&&t.products.map(f=>e.jsx(Rd,{product:f,saved:i(`product:${f.id}`),stagedActive:h(f.url),onStage:()=>a({kind:"product",url:f.url||"",title:f.title,thumbnailUrl:f.imageUrl,platform:"tiktok_shop",subtitle:`${f.currency}${f.price??"?"}${f.soldCount!==null?` · ${Cs(f.soldCount)} sold`:""}`}),onSave:()=>o({id:`product:${f.id}`,type:"products",savedAt:"",title:f.title,subtitle:`${f.currency}${f.price??"?"} · ${f.soldCount!==null?`${Cs(f.soldCount)} sold`:f.shopName||""}`,imageUrl:f.imageUrl,url:f.url})},f.id)),t.type==="ads"&&t.ads.map(f=>e.jsx(Ad,{ad:f,saved:i(`ad:${f.id}`),watched:d(`brand:${f.advertiserName.toLowerCase()}`),stagedActive:h(f.adLibraryUrl||f.linkUrl),onStage:()=>a({kind:"ad",url:f.adLibraryUrl||f.linkUrl||"",title:f.title||f.bodyText.slice(0,90)||f.advertiserName,thumbnailUrl:f.thumbnailUrl,platform:f.platform,subtitle:`${f.advertiserName}${f.runningDays!==null?` · running ${f.runningDays}d`:""}`}),onSave:()=>o({id:`ad:${f.id}`,type:"ads",savedAt:"",title:f.title||f.bodyText.slice(0,80)||f.advertiserName,subtitle:`${f.advertiserName}${f.runningDays!==null?` · running ${f.runningDays}d`:""}`,imageUrl:f.thumbnailUrl,url:f.adLibraryUrl}),onWatch:()=>p({id:`brand:${f.advertiserName.toLowerCase()}`,name:f.advertiserName,type:"ads",query:f.advertiserName,platform:"Facebook",avatarUrl:null})},f.id)),t.type==="trending"&&t.videos.map(f=>e.jsx(Td,{video:f,saved:i(`video:${f.id}`),stagedActive:h(f.url),onStage:()=>
50a({kind:"video",url:f.url,title:f.title,thumbnailUrl:f.thumbnailUrl,platform:f.platform,creatorHandle:f.creatorHandle,viewCount:f.viewCount,likeCount:f.likeCount,durationFormatted:f.durationFormatted}),onSave:()=>o({id:`video:${f.id}`,type:"trending",savedAt:"",title:f.title,subtitle:`@${f.creatorHandle} · ${Cs(f.viewCount)} views`,imageUrl:f.thumbnailUrl,url:f.url})},f.id)),t.type==="influencers"&&t.creators.map(f=>e.jsx(Pd,{creator:f,saved:i(`creator:${f.handle}`),watched:d(`creator:${f.handle}`),stagedActive:h(f.url),onStage:()=>a({kind:"creator",url:f.url,title:f.displayName||`@${f.handle}`,thumbnailUrl:f.avatarUrl,platform:"tiktok",subtitle:`${Zn(f.followers)} followers`}),onSave:()=>o({id:`creator:${f.handle}`,type:"influencers",savedAt:"",title:f.displayName||`@${f.handle}`,subtitle:`${Zn(f.followers)} followers`,imageUrl:f.avatarUrl,url:f.url}),onWatch:()=>p({id:`creator:${f.handle}`,name:f.displayName||`@${f.handle}`,type:"influencers",query:`@${f.handle}`,platform:"TikTok",avatarUrl:f.avatarUrl})},f.id))]}):e.jsxs("div",{style:{maxWidth:460,margin:"80px auto",textAlign:"center",color:"rgba(237,237,240,.5)",fontSize:14,lineHeight:"22px"},children:['No results for "',t.query,'".',e.jsx("br",{}),"Try a broader term, another platform, or a different source type."]})}function eo({imageUrl:t,fallbackIcon:r,aspectRatio:s="4 / 3",overlay:a}){return e.jsxs("div",{style:{position:"relative",aspectRatio:s,background:"#0b0b0d",borderBottom:"1px solid rgba(255,255,255,.08)"},children:[t?e.jsx("img",{src:t,alt:"",loading:"lazy",style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover"}}):e.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:"#3a3a40"},children:e.jsx(r,{size:30,strokeWidth:1.5})}),a]})}function na({saved:t,onSave:r,watched:s,onWatch:a,stagedActive:i,onStage:o,url:d}){return e.jsxs("div",{style:{position:"absolute",top:8,right:8,display:"flex",gap:6},children:[e.jsx("button",{type:"button","aria-label":i?"Remove from canvas stack":"Add to canvas",title:i?"Remove from canvas stack":"Add to canvas",onClick:p=>{p.preventDefault(),p.stopPropagation(),o()},style:{...rn,color:i?"#0b0b0d":"#a2a2a8",background:i?xr:rn.background,borderColor:i?xr:void 0},children:i?e.jsx(cs,{size:14}):e.jsx(Rs,{size:14})}),a&&e.jsx("button",{type:"button","aria-label":s?"Remove from watchlist":"Add to watchlist",title:"Watchlist",onClick:p=>{p.preventDefault(),p.stopPropagation(),a()},style:{...rn,color:s?xr:"#a2a2a8",borderColor:s?"rgba(61,127,206,.45)":void 0},children:e.jsx(jc,{size:14})}),e.jsx("button",{type:"button","aria-label":t?"Remove from saved":"Save",title:"Save",onClick:p=>{p.preventDefault(),p.stopPropagation(),r()},style:{...rn,color:t?xr:"#a2a2a8",borderColor:t?"rgba(61,127,206,.45)":void 0},children:t?e.jsx(bc,{size:14}):e.jsx(oc,{size:14})}),d&&e.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer","aria-label":"Open",title:"Open",onClick:p=>p.stopPropagation(),style:{...rn,textDecoration:"none"},children:e.jsx(ic,{size:14})})]})}function Rd({product:t,saved:r,stagedActive:s,onStage:a,onSave:i}){return e.jsxs("div",{style:sa,children:[e.jsx(eo,{imageUrl:t.imageUrl,fallbackIcon:Si,aspectRatio:"1 / 1",overlay:e.jsx(na,{saved:r,onSave:i,stagedActive:s,onStage:a,url:t.url})}),e.jsxs("div",{style:{padding:11,display:"flex",flexDirection:"column",gap:8,flex:1},children:[e.jsx("div",{style:{fontSize:13,fontWeight:600,lineHeight:"18px",color:"#f7f7f8",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:t.title}),e.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginTop:"auto"},children:[e.jsxs("span",{style:ra,children:[t.currency,t.price??"—"]}),t.soldCount!==null&&e.jsxs("span",{style:ln,children:[Cs(t.soldCount)," sold"]})]}),t.shopName&&e.jsx("div",{style:{fontSize:11,color:"rgba(237,237,240,.45)"},children:t.shopName})]})]})}function Ad({ad:t,saved:r,watched:s,stagedActive:a,onStage:i,onSave:o,onWatch:d}){const p=t.videoUrls.length>0;return e.jsxs("div",{style:sa,children:[e.jsx(eo,{imageUrl:t.thumbnailUrl,fallbackIcon:Va,overlay:e.jsxs(e.Fragment,{children:[e.jsx(na,{saved:r,onSave:o,watched:s,onWatch:d,stagedActive:a,onStage:i,url:t.adLibraryUrl}),p&&e.jsxs("span",{style:{position:"absolute",bottom:8,left:8,display:"flex",alignItems:"center",gap:4,borderRadius:999,background:"rgba(0,0,0,.65)",padding:"2px 8px",fontSize:11,color:"#fff"},children:[e.jsx(ls,{size:10})," Video"]})]})}),e.jsxs("div",{style:{padding:11,display:"flex",flexDirection:"column",gap:8,flex:1},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{fontSize:13,fontWeight:650,color:"#f7f7f8",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.advertiserName||"Unknown advertiser"}),t.isActive&&e.jsx("span",{style:{width:7,height:7,borderRadius:999,background:"#4ade80",flexShrink:0}})]}),e.jsx("div",{style:{fontSize:12,lineHeight:"17px",color:"rgba(237,237,240,.58)",display:"-webkit-box",WebkitLineClamp:3,WebkitBoxOrient:"vertical",overflow:"hidden"},children:t.bodyText||t.title||"No ad copy"}),e.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginTop:"auto"},children:[t.runningDays!==null&&e.jsxs("span",{style:t.runningDays>=30?ra:ln,title:t.runningDays>=30?"Running 30+ days — likely a proven winner":void 0,children:[t.runningDays,"d running"]}),t.ctaText&&e.jsx("span",{style:ln,children:t.ctaText})]})]})]})}function Td({video:t,saved:r,stagedActive:s,onStage:a,onSave:i}){return e.jsxs("div",{style:sa,children:[e.jsx(eo,{imageUrl:t.thumbnailUrl,fallbackIcon:ls,aspectRatio:"16 / 10",overlay:e.jsxs(e.Fragment,{children:[e.jsx(na,{saved:r,onSave:i,stagedActive:s,onStage:a,url:t.url}),t.durationFormatted&&e.jsx("span",{style:{position:"absolute",bottom:8,right:8,borderRadius:6,background:"rgba(0,0,0,.65)",padding:"1px 6px",fontSize:10,fontFamily:"monospace",color:"#fff"},children:t.durationFormatted})]})}),e.jsxs("div",{style:{padding:11,display:"flex",flexDirection:"column",gap:7,flex:1},children:[e.jsx("div",{style:{fontSize:13,fontWeight:600,lineHeight:"18px",color:"#f7f7f8",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:t.title}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:"auto",fontSize:11,color:"rgba(237,237,240,.5)"},children:[e.jsxs("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["@",t.creatorHandle]}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:3,flexShrink:0,marginLeft:"auto"},children:[e.jsx(ta,{size:11})," ",Cs(t.viewCount)]})]})]})]})}function Pd({creator:t,saved:r,watched:s,stagedActive:a,onStage:i,onSave:o,onWatch:d}){return e.jsxs("div",{style:{...sa,position:"relative",padding:12,gap:9},children:[e.jsx(na,{saved:r,onSave:o,watched:s,onWatch:d,stagedActive:a,onStage:i,url:t.url}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,paddingRight:140}
50,children:[e.jsx("div",{style:{width:42,height:42,borderRadius:999,overflow:"hidden",background:"#0b0b0d",border:"1px solid rgba(255,255,255,.12)",flexShrink:0},children:t.avatarUrl?e.jsx("img",{src:t.avatarUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):e.jsx("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#3a3a40"},children:e.jsx(Wa,{size:18})})}),e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{style:{fontSize:14,fontWeight:650,color:"#f7f7f8",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.displayName||`@${t.handle}`}),e.jsxs("div",{style:{fontSize:11,color:"rgba(237,237,240,.45)"},children:["@",t.handle]})]})]}),t.bio&&e.jsx("div",{style:{fontSize:12,lineHeight:"17px",color:"rgba(237,237,240,.58)",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:t.bio}),e.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginTop:"auto"},children:[e.jsxs("span",{style:ra,children:[Zn(t.followers)," followers"]}),t.topVideoViews!==null&&e.jsxs("span",{style:ln,children:["top video ",Cs(t.topVideoViews)," views"]})]})]})}function Ca({rows:t,empty:r,hoveredRow:s,setHoveredRow:a}){return t.length?e.jsxs("div",{children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 130px 150px 34px",alignItems:"center",gap:12,padding:8,color:"#6c6c72",fontSize:13,borderBottom:"1px solid rgba(255,255,255,.10)"},children:[e.jsx("div",{children:"Name"}),e.jsx("div",{children:"When"}),e.jsx("div",{children:"Source"}),e.jsx("div",{})]}),t.map(i=>{const o=i.icon;return e.jsxs("div",{onMouseEnter:()=>a(i.id),onMouseLeave:()=>a(null),onClick:i.onClick,style:{display:"grid",gridTemplateColumns:"1fr 130px 150px 34px",alignItems:"center",gap:12,padding:"9px 8px",borderRadius:10,cursor:"pointer",background:s===i.id?"rgba(255,255,255,.045)":"transparent"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,minWidth:0},children:[e.jsx("div",{style:{width:50,height:36,borderRadius:8,background:"#0b0b0d",border:"1px solid rgba(255,255,255,.10)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,overflow:"hidden"},children:i.imageUrl?e.jsx("img",{src:i.imageUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):e.jsx(o,{size:17,color:"#a2a2a8"})}),e.jsx("span",{style:{fontSize:15,fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.title})]}),e.jsx("div",{style:{fontSize:13,color:"#a2a2a8",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.middle}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx(o,{size:15,color:xr}),e.jsx("span",{style:{fontSize:13,color:"#a2a2a8"},children:i.right})]}),e.jsx("button",{type:"button","aria-label":"Remove",onClick:d=>{d.stopPropagation(),i.onRemove()},style:{width:28,height:28,borderRadius:8,border:"none",background:"transparent",color:s===i.id?"#a2a2a8":"transparent",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(ac,{size:14})})]},i.id)})]}):e.jsx("div",{style:{padding:"22px 8px",textAlign:"center",color:"rgba(237,237,240,.42)",fontSize:13},children:r})}function $s({label:t,value:r,options:s,onSelect:a,compact:i,accent:o}){const[d,p]=n.useState(!1),h=n.useRef(null);return n.useEffect(()=>{if(!d)return;const y=f=>{var u;(u=h.current)!=null&&u.contains(f.target)||p(!1)};return window.addEventListener("mousedown",y),()=>window.removeEventListener("mousedown",y)},[d]),e.jsxs("div",{ref:h,style:{position:"relative",flexShrink:0},children:[e.jsxs("button",{type:"button",onClick:()=>p(y=>!y),style:{display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:"center",border:`1px solid ${o||d?Qa:"rgba(255,255,255,.10)"}`,borderRadius:12,padding:i?"4px 10px":"5px 12px",minWidth:i?104:120,height:i?38:void 0,cursor:"pointer",background:"rgba(255,255,255,.03)",transition:"border-color .22s ease",textAlign:"left"},children:[e.jsx("span",{style:{fontSize:10.5,color:"#6c6c72"},children:t}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6,width:"100%",fontSize:i?13:14,fontWeight:500,color:o?xr:"#ededf0",whiteSpace:"nowrap"},children:[e.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",maxWidth:i?120:150},children:r}),e.jsx(gi,{size:13,color:"#6c6c72",style:{marginLeft:"auto",flexShrink:0}})]})]}),d&&e.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,minWidth:160,padding:4,background:"#161619",border:"1px solid rgba(255,255,255,.18)",borderRadius:12,boxShadow:"0 16px 40px rgba(0,0,0,.6)",zIndex:60},children:s.map(y=>e.jsx("button",{type:"button",onClick:()=>{p(!1),a(y)},style:{display:"block",width:"100%",textAlign:"left",padding:"8px 10px",borderRadius:6,border:"none",background:r===y?"rgba(61,127,206,.18)":"transparent",color:"#ededf0",fontSize:14,cursor:"pointer",whiteSpace:"nowrap"},children:y},y))})]})}function Ko({children:t,label:r,onClick:s,accent:a}){return e.jsx("button",{"aria-label":r,onClick:s,style:{width:38,height:38,borderRadius:999,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",border:`1px solid ${a?Qa:"rgba(255,255,255,.07)"}`,background:a?vd:"rgba(255,255,255,.045)",color:a?xr:"rgba(255,255,255,.68)",transition:"background .18s, color .18s, border-color .18s"},children:t})}function _a({children:t,active:r,onClick:s}){return e.jsx("button",{type:"button",onClick:s,style:{padding:"6px 13px",borderRadius:8,fontSize:14,cursor:"pointer",border:"none",background:r?"rgba(255,255,255,.08)":"transparent",color:r?"#ededf0":"#a2a2a8"},children:t})}function Id({question:t,options:r,onAnswer:s,onDismiss:a,darkMode:i=!1}){const o=lc(),d=n.useRef(null),[p,h]=n.useState(""),y=n.useMemo(()=>
50(Array.isArray(r)?r:[]).slice(0,3).filter(Boolean),[r]);n.useEffect(()=>{const _=window.setTimeout(()=>{var J;(J=d.current)==null||J.focus()},120);return()=>window.clearTimeout(_)},[]);const f=()=>{const _=d.current;_&&(_.style.height="0px",_.style.height=`${Math.min(_.scrollHeight,96)}px`)};n.useEffect(()=>{f()},[p]);const u=p.trim().length>0,$=()=>{const _=p.trim();_&&(s==null||s(_),h(""))},N=_=>{if(_.key==="Escape"){_.preventDefault(),a==null||a();return}_.key==="Enter"&&!_.shiftKey&&(_.preventDefault(),$())},C=i?"border-white/12 bg-white/[0.06] text-white/85 hover:border-violet-400/60 hover:bg-violet-400/15 hover:text-white":"border-black/10 bg-black/[0.03] text-black/75 hover:border-violet-500/50 hover:bg-violet-500/10 hover:text-black",F=i?"text-white/40 hover:bg-white/10 hover:text-white/70":"text-black/35 hover:bg-black/5 hover:text-black/60",te=i?"text-white placeholder:text-white/[0.38]":"text-black placeholder:text-black/[0.36]",E=i?"border-white/[0.09] bg-white/[0.04]":"border-black/[0.07] bg-black/[0.02]",Y=u?i?"bg-white text-black shadow-[0_10px_28px_rgba(255,255,255,0.12)] hover:bg-white/90":"bg-black text-white shadow-[0_10px_28px_rgba(15,23,42,0.18)] hover:bg-black/90":i?"bg-white/[0.07] text-white/45":"bg-black/[0.05] text-black/35",V=o?0:.06,L=o?{duration:0}:{type:"spring",damping:26,stiffness:420};return e.jsxs(_e.div,{layout:!o,initial:o?{opacity:0}:{opacity:0,y:8,scale:.99},animate:{opacity:1,y:0,scale:1},exit:o?{opacity:0}:{opacity:0,y:8,scale:.99},transition:o?{duration:0}:{type:"spring",damping:30,stiffness:380},className:"flex flex-col gap-2.5",role:"group","aria-label":"Operator clarification",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[e.jsx("span",{className:`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full ${i?"bg-violet-400/15":"bg-violet-500/10"}`,children:e.jsx(ea,{size:12,className:i?"text-violet-200":"text-violet-600"})}),e.jsx("p",{className:`text-[13px] font-semibold leading-5 ${i?"text-white/90":"text-black/80"}`,children:t})]}),e.jsx("button",{type:"button",onClick:()=>a==null?void 0:a(),className:`shrink-0 rounded-full p-1 transition ${F}`,"aria-label":"Dismiss question",children:e.jsx(qt,{size:14})})]}),y.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:y.map((_,J)=>e.jsx(_e.button,{type:"button",initial:o?{opacity:0}:{opacity:0,y:6,scale:.97},animate:{opacity:1,y:0,scale:1},transition:{...L,delay:V+J*.05},onClick:()=>s==null?void 0:s(_),className:`rounded-full border px-3 py-1.5 text-left text-[13px] font-medium leading-4 transition ${C}`,children:_},`${_}-${J}`))}),e.jsxs(_e.div,{initial:o?{opacity:0}:{opacity:0,y:6,scale:.99},animate:{opacity:1,y:0,scale:1},transition:{...L,delay:V+y.length*.05},className:`flex items-end gap-2 rounded-2xl border px-3 py-1.5 transition ${E}`,children:[e.jsx("textarea",{ref:d,value:p,onChange:_=>h(_.target.value),onInput:f,onKeyDown:N,rows:1,placeholder:"Type your own answer…","aria-label":"Type your own answer",className:`max-h-24 min-h-7 w-full resize-none overflow-y-auto bg-transparent px-0 py-1 text-[14px] font-medium leading-6 outline-none ${te}`}),e.jsx("button",{type:"button",onClick:$,disabled:!u,className:`mb-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition disabled:cursor-not-allowed disabled:opacity-35 ${Y}`,"aria-label":"Send answer",title:"Send answer",children:e.jsx(Ha,{size:15})})]})]})}function Ed(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function Ld(t){if(!t||t<=0)return"0:00";const r=Math.floor(t/3600),s=Math.floor(t%3600/60),a=t%60;return r>0?`${r}:${String(s).padStart(2,"0")}:${String(a).padStart(2,"0")}`:`${s}:${String(a).padStart(2,"0")}`}const $a=5e3,Jo=2,Xo=3,Ra=4,Zo=180,Aa=1e4,Pt="Live search results are still processing in the background. You can search something else while this finishes.",sn="Showing cached matches. Live refresh is unavailable right now.",Ta="Live search is unavailable right now. Try a cached starter search or check back shortly.",Qo=["tiktok","youtube","instagram"];function ct(t){const r=typeof t=="string"?t.trim():"";return r?r.replace(/\bVirlo\b/gi,"live search").replace(/dev\.virlo\.ai/gi,"the provider dashboard"):null}function zd(t){if(t instanceof TypeError&&t.message==="Failed to fetch")return"Search service is unreachable. Check that the API server is running, then try again.";const r=t instanceof Error?t.message:String(t||""),s=ct(r)||"";return/\((5\d\d)\)/.test(s)||/\b5\d\d\b/.test(s)?"Search is having trouble right now. Try another query in a minute.":/\((401|403)\)/.test(s)||/\b(401|403)\b/.test(s)||/missing bearer token|not authenticated|unauthorized|forbidden/i.test(s)?"Sign in again to search ads and videos.":s||"Search failed. Try another query in a minute."}function an(t){if(!Array.isArray(t))return null;const r=[...new Set(t.map(s=>String(s||"").toLowerCase()).filter(s=>Qo.includes(s)))];return r.length===0||r.length===Qo.length?null:r}function Pa(t,r){var a;const s=((a=an(r))==null?void 0:a.sort().join(","))||"all";return`${t.trim().toLowerCase()}::${s}`}function Dd(){const[t,r]=n.useState(null),[s,a]=n.useState(!1),[i,o]=n.useState(null),[d,p]=n.useState(null),[h,y]=n.useState(null),[f,u]=n.useState(0),[$,N]=n.useState(null),[C,F]=n.useState(null),[te,E]=n.useState(null),[Y,V]=n.useState(!1),[L,_]=n.useState(!1),[J,O]=n.useState(null),[U,Z]=n.useState(null),[b,q]=n.useState(null),[Q,P]=n.useState("idle"),[Ne,m]=n.useState([]),[ue,ce]=n.useState([]),[Oe,j]=n.useState([]),[I,me]=n.useState(!1),D=n.useRef(null),v=n.useRef(0),be=n.useRef(0),M=n.useRef(null),Ye=n.useRef(null),ye=n.useRef(null),Re=n.useRef(null),qe=n.useRef(null),Rt=n.useRef(null),at=n.useRef(null),Ee=n.useRef(null),Ge=n.useRef(null),Xt=n.useRef("idle"),Be=n.useRef(null),Gt=n.useRef([]),ft=n.useRef(new Map),vt=n.useRef(new Map),ar=n.useRef(new Map),ot=n.useCallback(T=>{if("canLiveRefresh"in T&&_(!!T.canLiveRefresh),"estimatedCostCredits"in T){const z=Number(T.estimatedCostCredits);O(Number.isFinite(z)?z:null)}if("providerBalanceCredits"in T){const z=T.providerBalanceCredits===null||T.providerBalanceCredits===void 0?null:Number(T.providerBalanceCredits);Z(z!==null&&Number.isFinite(z)?z:null)}"budgetStatus"in T&&q(T.budgetStatus&&typeof T.budgetStatus=="object"?T.budgetStatus:null)},[]);n.useEffect(()=>{qe.current=t},[t]),n.useEffect(()=>{at.current=i},[i]),n.useEffect(()=>{Ee.current=d},[d]),n.useEffect(()=>{Xt.current=Q},[Q]),n.useEffect(()=>{Be.current=te},[te]),n.useEffect(()=>{Gt.current=Ne},[Ne]),n.useEffect(()=>()=>{var T,z;D.current&&(clearTimeout(D.current),D.current=null),ye.current&&(clearTimeout(ye.current),ye.current=null),Re.current&&(clearTimeout(Re.current),Re.current=null),(T=M.current)==null||T.abort(),(z=Ye.current)==null||z.abort();for(const oe of ft.current.values())clearTimeout(oe);ft.current.clear();for(const oe of vt.current.values())oe.abort();vt.current.clear(),ar.current.clear()},[]);const Qe=n.useCallback(async()=>{const T={"Content-Type":"application/json"};try{const{data:{session:z}}=await Et.auth.getSession();z!=null&&z.access_token&&(T.Authorization=`Bearer ${z.access_token}`)}catch(z){console.error("Failed to get auth session:",z)}return T},[]),Ue=n.useCallback(T=>{if(!T.searchId||!T.query.trim())return;const z=new Date().toISOString();m(oe=>{const pe=oe.find(we=>we.searchId===T.searchId),Ie=T.videos&&T.videos.length>0?T.videos:pe==null?void 0:pe.videos,Le={searchId:T.searchId,query:T.query.trim(),platforms:T.platforms!==void 0?an(T.platforms):(pe==null?void 0:pe.platforms)??null,status:T.status,startedAt:(pe==null?void 0:pe.startedAt)||z,updatedAt:z,resultCount:T.resultCount??(Ie==null?void 0:Ie.length)??(pe==null?void 0:pe.resultCount)??0,notice:ct(T.notice)??ct(pe==null?void 0:pe.notice)??null,videos:Ie},de=Pa(Le.query,Le.platforms),xe=oe.filter(we=>we.searchId!==T.searchId&&Pa(we.query,we.platforms)!==de);return[Le,...xe].slice(0,6)})},[]),dt=n.useCallback(T=>{const z=ft.current.get(T);z&&(clearTimeout(z),ft.current.delete(T));const oe=vt.current.get(T);oe&&(oe.abort(),vt.current.delete(T)),ar.current.delete(T)},[]),gt=n.useCallback((T,z,oe)=>
50{if(!T||!z.trim()||ft.current.has(T))return;const pe=async()=>{var Le,de,xe;const Ie=(ar.current.get(T)||0)+1;if(ar.current.set(T,Ie),Ie>=Zo){dt(T),Ue({searchId:T,query:z,platforms:oe,status:"failed",notice:"Live search is still processing this topic."});return}try{(Le=vt.current.get(T))==null||Le.abort();const we=new AbortController;vt.current.set(T,we);const le=await Qe(),Ae=await(await fetch(`/api/viral-vault/search/${T}`,{headers:le,signal:we.signal})).json();if(Ae.status==="completed"){dt(T);const ve=os(Ae.videos||[]);Ue({searchId:T,query:z,platforms:oe,status:"completed",resultCount:ve.length||Ae.total||0,notice:"Ready"}),at.current===T&&(qe.current=ve,r(ve),u(Ae.total||ve.length),y(Ae.analysis||null),a(!1),F(ct(Ae.notice)),E(Ae.source||null),V(!!Ae.isCacheOnly),P(ve.length>0?"results":"empty"));return}if(Ae.status==="failed"){dt(T);const ve=Gt.current.find(xt=>xt.searchId===T);if((((de=ve==null?void 0:ve.videos)==null?void 0:de.length)||(ve==null?void 0:ve.resultCount)||0)>0){Ue({searchId:T,query:z,platforms:oe,status:"completed",resultCount:((xe=ve==null?void 0:ve.videos)==null?void 0:xe.length)||(ve==null?void 0:ve.resultCount)||0,notice:sn,videos:ve==null?void 0:ve.videos});return}Ue({searchId:T,query:z,platforms:oe,status:"failed",notice:"Failed"});return}Ue({searchId:T,query:z,platforms:oe,status:Ae.status==="queued"?"queued":"processing",notice:Pt}),ft.current.set(T,setTimeout(pe,Aa))}catch(we){if(we instanceof DOMException&&we.name==="AbortError")return;console.error("Background viral search poll error:",we),ft.current.set(T,setTimeout(pe,Aa))}};ft.current.set(T,setTimeout(pe,Aa))},[Qe,dt,Ue]),et=n.useCallback(()=>{var T;D.current&&(clearTimeout(D.current),D.current=null),ye.current&&(clearTimeout(ye.current),ye.current=null),Re.current&&(clearTimeout(Re.current),Re.current=null),(T=Ye.current)==null||T.abort(),Ye.current=null,v.current=0},[]),br=n.useCallback(T=>{ye.current&&clearTimeout(ye.current),ye.current=setTimeout(()=>{var oe;const z=((oe=qe.current)==null?void 0:oe.length)||0;be.current!==T||z>=Ra||(a(!1),z>0?(F(`Showing ${z} cached ${z===1?"match":"matches"}. ${Pt}`),E("background_cache"),P("results")):(F(Pt),E("background_processing"),P("search_slow")))},Xo*$a)},[et]),Ot=n.useCallback((T,z)=>{et(),v.current=0;const oe=async()=>{var Ie,Le;if(be.current!==z)return;if(v.current+=1,v.current>=Zo){et(),a(!1),P("error"),N("Live search is still processing this topic. Try a narrower keyword phrase, or check back in a few minutes.");return}const pe=((Ie=qe.current)==null?void 0:Ie.length)||0;v.current>=Xo&&pe<Ra&&(a(!1),pe>0?(F(`Showing ${pe} cached ${pe===1?"match":"matches"}. ${Pt}`),E("background_cache"),P("results")):(F(Pt),E("background_processing"),P("search_slow"))),v.current===Jo&&(a(!1),P(de=>de==="results"?"results":"search_slow"),F(Pt),E(de=>de==="partial_cache"?"background_cache":"background_processing"));try{(Le=Ye.current)==null||Le.abort();const de=new AbortController;Ye.current=de;const xe=await Qe(),le=await(await fetch(`/api/viral-vault/search/${T}`,{headers:xe,signal:de.signal})).json();if(be.current!==z)return;if(le.status==="completed"){et();const re=os(le.videos||[]);qe.current=re,Ue({searchId:T,query:Ee.current||"",platforms:Ge.current,status:"completed",resultCount:re.length||le.total||0,notice:"Ready"}),ye.current&&(clearTimeout(ye.current),ye.current=null),r(re),u(le.total||0),y(le.analysis||null),a(!1),F(ct(le.notice)),E(le.source||null),V(!!le.isCacheOnly),P(re.length>0?"results":"empty")}else if(le.status==="failed"){et();const re=os(le.videos||[]),Ae=re.length>0?re:qe.current||[];if(Ae.length>0){qe.current=Ae,r(Ae),u(le.total||Ae.length),y(le.analysis||null),a(!1),F(ct(le.notice)||ct(le.error)||sn),E(le.source==="partial_cache"||!le.source?"failed_cache":le.source),V(!!le.isCacheOnly),P("results"),Ue({searchId:T,query:Ee.current||"",platforms:Ge.current,status:"completed",resultCount:Ae.length||le.total||0,notice:sn,videos:Ae});return}Ue({searchId:T,query:Ee.current||"",platforms:Ge.current,status:"failed",notice:"Failed"}),a(!1),F(null),E(null),V(!1),P("error"),N(ct(le.error)||Ta)}else Ue({searchId:T,query:Ee.current||"",platforms:Ge.current,status:le.
50status==="queued"?"queued":"processing",resultCount:pe,notice:Pt}),P(re=>Rt.current===z?"search_slow":re==="results"?"results":v.current>=Jo?"search_slow":"search_polling"),D.current=setTimeout(oe,$a)}catch(de){if(de instanceof DOMException&&de.name==="AbortError")return;console.error("Poll error:",de),et(),a(!1),F(null),P("error"),N("Failed to check search status.")}};D.current=setTimeout(oe,$a)},[Qe,et,Ue]),kt=n.useCallback(async(T,z)=>{var le,re;if(!T.trim())return;const oe=at.current,pe=Ee.current,Ie=Ge.current,Le=Xt.current,de=Be.current,xe=Le==="search_polling"||Le==="search_slow"||Le==="results"&&["partial_cache","background_cache","background_processing"].includes(de||"");oe&&pe&&xe&&(Ue({searchId:oe,query:pe,platforms:Ie,status:"processing",resultCount:((le=qe.current)==null?void 0:le.length)||0,notice:Pt,videos:qe.current||void 0}),gt(oe,pe,Ie)),be.current+=1;const we=be.current;(re=M.current)==null||re.abort(),et(),Rt.current=null,N(null),F(null),a(!0),qe.current=null,r(null),y(null),o(null),p(T.trim()),Ge.current=an(z==null?void 0:z.platforms),P("search_submitting");try{Re.current&&clearTimeout(Re.current),Re.current=setTimeout(()=>{var Lt;be.current!==we||(Lt=qe.current)!=null&&Lt.length||(Rt.current=we,a(!1),F(Pt),E("background_processing"),P("search_slow"))},8e3);const Ae=new AbortController;M.current=Ae;const ve=await Qe(),xt=await fetch("/api/viral-vault/search",{method:"POST",headers:ve,signal:Ae.signal,body:JSON.stringify({query:T.trim(),platforms:z==null?void 0:z.platforms,minViews:z==null?void 0:z.minViews,timePeriod:(z==null?void 0:z.timePeriod)||"this_week",limit:(z==null?void 0:z.limit)||25,orderBy:z==null?void 0:z.orderBy,mode:(z==null?void 0:z.mode)||"cache"})});if(!xt.ok){const Lt=await xt.json().catch(()=>({}));throw new Error(ct(Lt.error)||`Search failed (${xt.status})`)}const fe=await xt.json();if(be.current!==we)return;ot(fe),Re.current&&(clearTimeout(Re.current),Re.current=null);const ze=os(fe.videos||[]);fe.status==="completed"?(qe.current=ze,ye.current&&(clearTimeout(ye.current),ye.current=null),r(ze),u(fe.total||0),y(fe.analysis||null),o(fe.searchId),a(!1),F(ct(fe.notice)),E(fe.source||null),V(!!fe.isCacheOnly),P(ze.length>0?"results":"empty")):fe.status==="failed"?(qe.current=ze.length>0?ze:null,r(ze.length>0?ze:null),u(fe.total||ze.length),y(null),o(fe.searchId),a(!1),F(ze.length>0?ct(fe.notice)||ct(fe.error)||"Showing cached matches. Live refresh failed.":null),E(ze.length>0&&fe.source==="partial_cache"?"failed_cache":fe.source||null),V(!!fe.isCacheOnly),P(ze.length>0?"results":"error"),ze.length===0&&N(ct(fe.error)||Ta)):(Ue({searchId:fe.searchId,query:T.trim(),platforms:Ge.current,status:fe.status==="queued"?"queued":"processing",resultCount:ze.length,notice:ct(fe.notice)||Pt,videos:ze.length>0?ze:void 0}),ze.length>0?(qe.current=ze,ye.current&&(clearTimeout(ye.current),ye.current=null),r(ze),u(fe.total||ze.length),F(ct(fe.notice)),E(fe.source||"partial_cache"),V(!!fe.isCacheOnly),P("results")):(F(ct(fe.notice)),E(fe.source||null),V(!1),Rt.current===we?(F(Pt),E("background_processing"),P("search_slow")):P("search_polling")),o(fe.searchId),Ot(fe.searchId,we),ze.length<Ra&&br(we))}catch(Ae){if(Ae instanceof DOMException&&Ae.name==="AbortError")return;console.error("Ad + video vault search error:",Ae),Re.current&&(clearTimeout(Re.current),Re.current=null),a(!1),F(null),E(null),V(!1),P("error"),N(zd(Ae))}},[Qe,gt,br,Ot,et,Ue,ot]),Zt=n.useCallback(async T=>{var Ie;const z=Gt.current.find(Le=>Le.searchId===T);if(!z)return;const oe=z.videos||[];be.current+=1;const pe=be.current;(Ie=M.current)==null||Ie.abort(),et(),dt(T),Rt.current=null,N(null),F(null),E(null),a(!1),qe.current=oe.length>0?oe:null,r(oe.length>0?oe:null),y(null),u(oe.length||z.resultCount||0),o(T),p(z.query),Ge.current=z.platforms,P(z.status==="completed"?"search_polling":oe.length>0?"results":"search_slow"),oe.length>0&&(F(ct(z.notice)||Pt),E("background_cache"));try{const Le=await Qe(),xe=await(await fetch(`/api/viral-vault/search/${T}`,{headers:Le})).json();if(be.current!==pe)return;if(xe.status==="completed"){const re=os(xe.videos||[]);
50qe.current=re,r(re),u(xe.total||re.length),y(xe.analysis||null),a(!1),F(ct(xe.notice)),E(xe.source||null),V(!!xe.isCacheOnly),P(re.length>0?"results":"empty"),Ue({searchId:T,query:z.query,platforms:z.platforms,status:"completed",resultCount:re.length||xe.total||0,notice:"Ready"});return}if(xe.status==="failed"){if(oe.length>0||z.resultCount>0){const re=oe;re.length>0&&(qe.current=re,r(re)),u(z.resultCount||re.length),y(null),a(!1),F(sn),E("failed_cache"),V(!1),P(re.length>0?"results":"search_slow"),Ue({searchId:T,query:z.query,platforms:z.platforms,status:"completed",resultCount:z.resultCount||re.length,notice:sn,videos:re.length>0?re:void 0});return}P("error"),N(ct(xe.error)||Ta),Ue({searchId:T,query:z.query,platforms:z.platforms,status:"failed",notice:"Failed"});return}const we=os(xe.videos||[]),le=we.length>0?we:oe;le.length>0?(qe.current=le,r(le),u(xe.total||z.resultCount||le.length),y(xe.analysis||null),F(ct(xe.notice)||Pt),E(xe.source||"background_cache"),V(!!xe.isCacheOnly),P("results")):(F(Pt),E("background_processing"),P("search_slow")),Ue({searchId:T,query:z.query,platforms:z.platforms,status:xe.status==="queued"?"queued":"processing",resultCount:we.length||z.resultCount||oe.length,notice:Pt,videos:le.length>0?le:void 0}),Ot(T,pe)}catch(Le){console.error("Failed to open pending viral search:",Le),P("error"),N("Failed to check search status.")}},[Qe,Ot,dt,et,Ue]),mt=n.useCallback(async()=>{try{const T=await Qe(),z=await fetch("/api/viral-vault/searches/active",{headers:T});if(!z.ok)return;const oe=await z.json(),pe=Array.isArray(oe.searches)?oe.searches:[],Ie=new Map,Le=Date.now();for(const de of pe){const xe=String(de.query||"").trim(),we=String(de.searchId||"").trim(),le=an(de.platforms);if(!we||!xe)continue;const re=Date.parse(String(de.updatedAt||de.startedAt||""));if(Number.isFinite(re)&&Le-re>20*60*1e3)continue;const Ae=Pa(xe,le),ve=Ie.get(Ae),xt=Date.parse(String((ve==null?void 0:ve.updatedAt)||(ve==null?void 0:ve.startedAt)||""));ve&&Number.isFinite(xt)&&Number.isFinite(re)&&xt>=re||Ie.set(Ae,de)}for(const de of Ie.values()){const xe=String(de.query||"").trim(),we=String(de.searchId||"").trim(),le=de.status==="queued"?"queued":"processing",re=an(de.platforms);Ue({searchId:we,query:xe,platforms:re,status:le,resultCount:Number(de.resultCount||0),notice:ct(de.notice)||Pt}),gt(we,xe,re)}}catch(T){console.error("Failed to load pending viral searches:",T)}},[Qe,gt,Ue]),Ke=n.useCallback(async()=>{t||P(T=>T==="idle"?"digest_loading":T),me(!0);try{const T=await Qe(),z=await fetch("/api/viral-vault/digest",{headers:T});if(!z.ok){console.error("Digest fetch failed:",z.status),N("Failed to load Ad + Video Vault digest."),P("error");return}const oe=await z.json();ot(oe),N(null),P(pe=>pe==="error"?"idle":pe),ce(os(oe.videos||[])),j((oe.trends||[]).map(pe=>({id:pe.id,name:pe.name,description:pe.description||"",trendType:pe.trendType||"",ranking:pe.ranking||0})))}catch(T){console.error("Digest fetch error:",T),N("Failed to load Ad + Video Vault digest."),P("error")}finally{me(!1),P(T=>T==="digest_loading"?"idle":T)}},[Qe,t,ot]),Qt=n.useCallback(()=>{et(),qe.current=null,r(null),a(!1),o(null),p(null),Ge.current=null,y(null),u(0),N(null),F(null),E(null),V(!1),P("idle")},[et]);return{results:t,isSearching:s,searchId:i,activeQuery:d,analysis:h,total:f,error:$,searchNotice:C,searchSource:te,isCacheOnly:Y,canLiveRefresh:L,estimatedCostCredits:J,providerBalanceCredits:U,budgetStatus:b,status:Q,digest:ue,trends:Oe,digestLoading:I,pendingSearches:Ne,search:kt,openPendingSearch:Zt,fetchPendingSearches:mt,fetchDigest:Ke,reset:Qt}}function os(t){return t.map(r=>({id:r.id||"",externalId:r.externalId||r.external_id||"",platform:r.platform||"tiktok",url:r.url||"",title:r.title||"",description:r.description||"",thumbnailUrl:r.thumbnailUrl||r.thumbnail_url||"",previewUrl:r.previewUrl||r.preview_url||r.videoUrl||r.video_url||r.mediaUrl||r.media_url||r.playbackUrl||r.playback_url||"",creatorHandle:r.creatorHandle||r.creator_handle||"",creatorAvatarUrl:r.creatorAvatarUrl||r.creator_avatar||null,creatorFollowers:r.creatorFollowers||r.creator_followers||null,publishedAt:r.publishedAt||r.published_at||"",viewCount:r.viewCount||r.view_count||0,likeCount:r.likeCount||r.like_count||0,commentCount:r.commentCount||r.comment_count||0,shareCount:r.shareCount||r.share_count||0,bookmarkCount:r.bookmarkCount||r.bookmark_count||0,duration:r.duration||0,durationFormatted:r.durationFormatted||Ld(r.duration||0),hashtags:r.hashtags||[],niche:r.niche||null,region:r.region||null,viralScore:r.viralScore||r.viral_score||0,engagementRatio:r.engagementRatio||r.engagement_ratio||0}))}function Fd(){const[t,r]=n.useState(""),[s,a]=n.useState("All"),[i,o]=n.useState("All"),[d,p]=n.useState("views"),[h,y]=n.useState("search"),[f,u]=n.useState(null),[$,N]=n.useState({}),C=Dd(),F=n.useMemo(()=>{const Z=new Map;for(const b of[...C.digest,...C.results||[]])Z.set(b.id,b);return Z},[C.digest,C.results]),te=n.useMemo(()=>Object.values($).map(Z=>F.get(Z.id)||Z),[F,$]),E=n.useMemo(()=>h==="saved"?te:C.activeQuery||t.trim()?C.results??[]:C.results??C.digest.slice(0,12),[t,te,C.activeQuery,C.digest,C.results,h]),Y=n.useMemo(()=>[...E.filter(b=>i==="All"||String(b.platform||"").toLowerCase()===i.toLowerCase())].sort((b,q)=>d==="views"?q.viewCount-b.viewCount:new Date(q.publishedAt).getTime()-new Date(b.publishedAt).getTime()),[E,i,d]),V=Z=>{N(b=>{if(b[Z.id]){const q={...b};return delete q[Z.id],q}return{...b,[Z.id]:Z}})},L=()=>{r(""),o("All"),a("All"),y("search"),C.reset()},_=async Z=>{const b=C.pendingSearches.find(q=>q.searchId===Z);b&&(r(b.query),o("All"),a(b.platforms&&b.platforms.length===1?b.platforms[0]:"All"),y("search"),await C.openPendingSearch(Z))},J=async(Z,b,q="cache")=>{const Q=(Z??t).trim();if(!Q)return;const P=b||s;r(Q),a(P),o("All"),y("search"),await C.search(Q,{platforms:P==="All"?void 0:[P.toLowerCase()],timePeriod:"this_week",limit:25,orderBy:d==="recent"?"publish_date":"views",mode:q})},O=async(Z,b)=>J(Z,b,"cache"),U=async(Z,b)=>J(Z,b,"live");return{...C,draftQuery:t,setDraftQuery:r,searchPlatform:s,setSearchPlatform:a,platformFilter:i,setPlatformFilter:o,sort:d,setSort:p,view:h,setVie
50w:y,hoveredId:f,setHoveredId:u,savedById:$,savedItems:te,visibleItems:Y,toggleSaved:V,clearSearch:L,openPendingSearch:_,fetchPendingSearches:C.fetchPendingSearches,submitSearch:O,submitLiveRefresh:U}}function Od({src:t,poster:r,active:s,onReady:a}){const i=n.useRef(null),[o,d]=n.useState(!1),[p,h]=n.useState(!1),[y,f]=n.useState(!1);n.useEffect(()=>{const $=i.current;$&&(s?($.muted=!1,$.volume=1,$.play().then(()=>f(!1)).catch(()=>f(!0))):($.pause(),$.currentTime=0,f(!1)))},[s]);const u=()=>{const $=i.current;$&&($.muted=!1,$.volume=1,$.play().then(()=>f(!1)).catch(()=>f(!0)))};return e.jsxs(e.Fragment,{children:[r?e.jsx("img",{src:r,alt:"",className:`absolute inset-0 h-full w-full object-cover brightness-[1.07] saturate-[1.08] transition duration-500 group-hover:scale-105 ${s&&o&&!p?"opacity-0":"opacity-100"}`}):null,e.jsx("video",{ref:i,src:t,poster:r,playsInline:!0,loop:!0,preload:"metadata",onLoadedData:()=>{d(!0),a==null||a()},onError:()=>h(!0),className:`absolute inset-0 h-full w-full object-cover brightness-[1.07] saturate-[1.08] transition duration-500 group-hover:scale-105 ${s&&o&&!p?"opacity-100":"opacity-0"}`}),s&&y?e.jsx("button",{type:"button",onClick:$=>{$.stopPropagation(),u()},className:"absolute left-2 top-11 flex h-7 w-7 items-center justify-center rounded-full bg-white/90 text-gray-950 shadow-lg ring-1 ring-black/10 backdrop-blur dark:bg-black/70 dark:text-white dark:ring-white/10",title:"Enable audio","aria-label":"Enable audio",children:e.jsx(Kl,{size:14})}):null]})}function Bd({src:t,poster:r,title:s,active:a,preload:i,platform:o,onReady:d}){const[p,h]=n.useState(!1),[y,f]=n.useState(!1),u=o==="youtube",$=u?"absolute inset-0 h-full w-full":"absolute left-1/2 top-1/2 h-[575px] w-[325px] origin-center -translate-x-1/2 -translate-y-1/2 scale-[0.44] sm:scale-[0.47]",N=n.useMemo(()=>{if(a)return t;try{const C=new URL(t);return C.searchParams.delete("autoplay"),C.toString()}catch{return t}},[a,t]);return n.useEffect(()=>{if(!a){f(!1);return}if(!u){const C=window.setTimeout(()=>{f(!0),d==null||d()},1800);return()=>window.clearTimeout(C)}},[a,u,d,t]),n.useEffect(()=>{h(!1),f(!1)},[t]),n.useEffect(()=>{if(!a||!p)return;const C=u?350:650,F=window.setTimeout(()=>{f(!0),d==null||d()},C);return()=>window.clearTimeout(F)},[a,u,p,d]),e.jsxs(e.Fragment,{children:[r?e.jsx("img",{src:r,alt:"",className:`absolute inset-0 h-full w-full object-cover brightness-[1.07] saturate-[1.08] transition duration-500 group-hover:scale-105 ${y?"o
50pacity-0":"opacity-100"}`}):null,a||i?e.jsx("iframe",{src:N,title:s,allow:"autoplay; encrypted-media; picture-in-picture; fullscreen",allowFullScreen:!0,loading:i&&!a?"eager":void 0,onLoad:()=>h(!0),onError:()=>f(!1),className:`${$} border-0 bg-black transition-opacity duration-300 ${y?"pointer-events-auto opacity-100":"pointer-events-none opacity-0"}`}):null,a&&!y?e.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-black/20 backdrop-blur-[1px]",children:e.jsxs("div",{className:"flex items-center gap-2 rounded-full bg-black/70 px-3 py-1.5 text-[11px] font-bold text-white shadow-lg ring-1 ring-white/10",children:[e.jsx(Ur,{size:13,className:"animate-spin"}),e.jsx("span",{children:"Loading"})]})}):null]})}function Md({className:t="h-4 w-4"}){return e.jsx("svg",{className:t,viewBox:"0 0 448 512",fill:"currentColor",children:e.jsx("path",{d:"M448 209.91a210.06 210.06 0 0 1-122.77-39.25v178.72A162.55 162.55 0 1 1 185 188.31v89.89a74.62 74.62 0 1 0 52.23 71.18V0h88a121.18 121.18 0 0 0 1.86 22.17A122.18 122.18 0 0 0 381 102.39a121.43 121.43 0 0 0 67 20.14z"})})}function ei(t){return String(t||"").replace(/\bVirlo\b/gi,"live search").replace(/dev\.virlo\.ai/gi,"the provider dashboard").trim()}const Ud=new Set(["blueprint","mint","lavender","rose","sunset","midnight"]);function sr(...t){return t.filter(Boolean).join(" ")}function Vd({isOwner:t,isViewer:r,activeTool:s,setActiveTool:a,addChatNode:i,addNotepadNode:o,addStickyNoteNode:d,addFileNode:p,addGroupNode:h,onDragStart:y,onShowLinkPrompt:f,onFileUpload:u,fileCount:$,onOpenLibrary:N,position:C="bottom",isDocsView:F=!1,workspaceOffset:te=0,promptValue:E,onPromptChange:Y,onPromptSubmit:V,promptAttachments:L=null,onAttachFiles:_,onRemoveAttachment:J,promptPlaceholder:O="Ask ChatGrid...",promptFocusKey:U=null,promptDisabled:Z=!1,operatorQuestion:b=null,onOperatorAnswer:q,onDismissOperatorQuestion:Q,missionSession:P=null,onExpandMission:Ne,isMissionTerminalActive:m=!1,missionColumnWidth:ue=440,centerPrompt:ce=!1,dockBottomRight:Oe=!1,hidePromptTools:j=!1,promptDarkModeOverride:I}){var mn;if(r)return null;const{darkMode:me,canvasColor:D}=di(),[v,be]=n.useState(()=>typeof document<"u"&&document.documentElement.classList.contains("dark")),M=me||v||Ud.has(String(D)),Ye=n.useMemo(()=>["#ffffff","#e5e7eb","#fecaca","#fed7aa","#fde68a","#bbf7d0","#a5f3fc","#bfdbfe","#ddd6fe","#fbcfe8"],[]),[ye,Re]=n.useState({open:!1,x:0,y:0,placement:"top"}),[qe,Rt]=n.useState(""),[at,Ee]=n.useState(null),[Ge,Xt]=n.useState(!1),[Be,Gt]=n.useState(!1),[ft,vt]=n.useState(!1),[ar,ot]=n.useState({}),Qe=n.useRef(null),Ue=n.useRef(null),[dt,gt]=n.useState(!1),et=n.useRef(null),br=n.useRef(null),Ot=n.useRef(null),kt=n.useRef(null),Zt=n.useRef(null),mt=n.useRef(null),{results:Ke,isSearching:Qt,error:T,searchNotice:z,searchSource:oe,isCacheOnly:pe,canLiveRefresh:Ie,estimatedCostCredits:Le,status:de,searchId:xe,digest:we,activeQuery:le,draftQuery:re,setDraftQuery:Ae,searchPlatform:ve,setSearchPlatform:xt,platformFilter:fe,setPlatformFilter:ze,sort:Lt,setSort:us,view:jt,setView:fr,hoveredId:yr,setHoveredId:St,savedItems:wr,savedById:vr,visibleItems:Ar,toggleSaved:kr,pendingSearches:or,openPendingSearch:jr,fetchPendingSearches:Vr,submitSearch:Wr,submitLiveRefresh:Ps,fetchDigest:Nt,clearSearch:Bt}=Fd();n.useEffect(()=>{if(typeof document>"u")return;const g=()=>{be(document.documentElement.classList.contains("dark"))};g();const G=new MutationObserver(g);return G.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),()=>G.disconnect()},[]);const w=de==="search_submitting"||de==="search_polling",[ge,Ve]=n.useState(!1);n.useEffect(()=>{if(!w){Ve(!1);return}Ve(!1);const g=window.setTimeout(()=>{Ve(!0)},8e3);return()=>window.clearTimeout(g)},[w,le,re]);const se=w&&!ge,Sr=!re.trim()||se&&(de==="search_submitting"||de==="search_polling"),cn=n.useRef(Nt);cn.current=Nt;const Is=n.useRef(Vr);Is.current=Vr;const dn=n.useRef(Bt);dn.current=Bt;const ne=()=>{dn.current(),St(null),ot({}),Gt(!1),setTimeout(()=>{var g,G;return(G=(g=mt.current)==null?void 0:g.focus)==null?void 0:G.call(g)},0)};n.useEffect(()=>{Be&&(mt.current=document.activeElement,setTimeout(()=>{var g;return(g=Ot.current)==null?void 0:g.focus()},60),cn.current(),Is.current())},[Be]),n.useEffect(()=>{const g=()=>gt(!0);return window.addEventListener("chatgrid:open-viral-vault",g),()=>{window.removeEventListener("chatgrid:open-viral-vault",g)}},[]),n.useEffect(()=>{if(!Be)return;const G=["https://www.tiktok.com","https://www.youtube.com","https://www.instagram.com"].map(ae=>{const $e=document.createElement("link");
50return $e.rel="preconnect",$e.href=ae,$e.crossOrigin="",document.head.appendChild($e),$e});return()=>{G.forEach(ae=>ae.remove())}},[Be]),n.useEffect(()=>{const g=G=>{G.key==="Escape"&&(Be&&ne(),dt&&gt(!1),ye.open&&Re({open:!1,x:0,y:0,placement:"top"}),Ge&&Xt(!1))};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[Ge,Be,dt,ye.open]),n.useEffect(()=>{if(!Ge)return;const g=G=>{var $e,bt;const ae=G.target;ae instanceof Node&&(($e=br.current)!=null&&$e.contains(ae)||(bt=et.current)!=null&&bt.contains(ae))||Xt(!1)};return window.addEventListener("pointerdown",g),()=>window.removeEventListener("pointerdown",g)},[Ge]),n.useEffect(()=>{const g=()=>vt(!1);return window.addEventListener("dragend",g),window.addEventListener("drop",g),()=>{window.removeEventListener("dragend",g),window.removeEventListener("drop",g)}},[]),n.useEffect(()=>{if(!Be)return;const g=Zt.current;if(!g)return;const G=ae=>{if(ae.key!=="Tab")return;const $e=g.querySelectorAll('button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])');if($e.length===0)return;const bt=$e[0],At=$e[$e.length-1],De=document.activeElement;if(ae.shiftKey){(!De||De===bt||!g.contains(De))&&(ae.preventDefault(),At.focus());return}(!De||De===At||!g.contains(De))&&(ae.preventDefault(),bt.focus())};return g.addEventListener("keydown",G),()=>g.removeEventListener("keydown",G)},[Be]);const ps=g=>{const G=String(g.platform||"").toLowerCase(),ae=String(g.url||"").toLowerCase();return G.includes("youtube")||ae.includes("youtu")?"youtube":G.includes("instagram")||ae.includes("instagram.com")?"instagram":G.includes("tiktok")||ae.includes("tiktok.com")?"tiktok":"youtube"},ir=g=>({videoId:g.externalId||g.id,platform:ps(g),title:g.title,sourceTitle:g.title,thumbnailUrl:g.thumbnailUrl,previewUrl:Te(g)||void 0,url:g.url,creatorHandle:g.creatorHandle||"",viewCount:g.viewCount,likeCount:g.likeCount,commentCount:g.commentCount,shareCount:g.shareCount,bookmarkCount:g.bookmarkCount,durationFormatted:g.durationFormatted}),Yt=(g,G)=>{const ae=JSON.stringify(ir(G));vt(!0),g.dataTransfer.setData("application/viral-video",ae),g.dataTransfer.effectAllowed="copy"},er=g=>{switch(g){case"tiktok":return"TikTok";case"youtube":return"YouTube";case"instagram":return"Instagram";default:return g||"Video"}},tr=(g,G=14)=>{switch(g){case"youtube":return e.jsx(Ga,{size:G});case"instagram":return e.jsx(dc,{size:G});case"tiktok":return e.jsx(Md,{className:"h-3 w-3"});default:return e.jsx(ls,{size:G,fill:"currentColor"})}},je=g=>String(g||"Untitled creative").replace(/[\p{Extended_Pictographic}\uFE0F]/gu,"").replace(/#[\w-]+/g,"").replace(/\s+/g," ").trim()||"Untitled creative",hs=g=>{const G=Number(g.duration||0),ae=String(g.durationFormatted||"").trim();return G>0&&ae&&ae!=="0:00"?ae:""},Hr=g=>{if(!g)return"";const G=new Date(g).getTime();if(Number.isNaN(G))return"";const ae=Date.now()-G,$e=Math.max(0,Math.floor(ae/864e5));return $e===0?"Today":$e===1?"1d ago":$e<7?`${$e}d ago`:$e<30?`${Math.floor($e/7)}w ago`:$e<365?`${Math.floor($e/30)}mo ago`:new Date(G).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})},Te=g=>{const G=g;return G.previewUrl||G.preview_url||G.videoUrl||G.video_url||G.mediaUrl||G.media_url||G.playbackUrl||G.playback_url||""},fs=g=>{var $e,bt,At;const G=ps(g),ae=String(g.url||"");if(!ae)return"";try{const De=new URL(ae);if(G==="youtube"){let it="";
50return De.hostname.includes("youtu.be")?it=De.pathname.split("/").filter(Boolean)[0]||"":De.pathname.includes("/shorts/")?it=(($e=De.pathname.split("/shorts/")[1])==null?void 0:$e.split(/[/?#]/)[0])||"":De.pathname.includes("/watch")&&(it=De.searchParams.get("v")||""),it?`https://www.youtube.com/embed/${it}?autoplay=1&playsinline=1&rel=0`:""}if(G==="tiktok"){const it=((bt=De.pathname.match(/\/video\/(\d+)/))==null?void 0:bt[1])||((At=String(g.externalId||"").match(/\d{8,}/))==null?void 0:At[0])||"";return it?`https://www.tiktok.com/embed/v2/${it}?autoplay=1`:""}if(G==="instagram"){const it=De.pathname.match(/\/(?:reel|p|tv)\/([^/?#]+)/);return it!=null&&it[1]?`https://www.instagram.com/reel/${it[1]}/embed/`:""}}catch{return""}return""},un=g=>{var G;(G=kt.current)==null||G.scrollBy({left:g*Math.min(360,window.innerWidth*.62),behavior:"smooth"})},ke=C==="right"?"fixed top-1/2 -translate-y-1/2 right-4 z-40":Oe?"relative w-full z-[116]":ce?"fixed bottom-6 left-1/2 -translate-x-1/2 z-[116]":m?"fixed bottom-6 right-3 z-[116] flex justify-center transition-[right] duration-300 ease-out":"fixed bottom-6 left-1/2 -translate-x-1/2 z-50",pn=Oe?void 0:C==="bottom"&&ce&&te?{left:`calc(50% + ${te/2}px)`}:C==="bottom"&&m?{width:ue}:C==="bottom"&&te&&!m?{left:`calc(50% + ${te/2}px)`}:void 0,qr=typeof E=="string"?E:qe,Es=typeof _=="function",Ls=Es&&Array.isArray(L)?L:[],zs=qr.trim().length>0&&!Z,Ds=n.useRef(U),Tr=g=>{typeof Y=="function"?Y(g):Rt(g)},hn=()=>{const g=Qe.current;g&&(g.style.height="0px",g.style.height=`${Math.min(g.scrollHeight,96)}px`)};n.useEffect(()=>{hn()},[qr]),n.useEffect(()=>{if(!m||U==null||Ds.current===U)return;Ds.current=U;const g=requestAnimationFrame(()=>{var G;(G=Qe.current)==null||G.focus(),hn()});return()=>cancelAnimationFrame(g)},[m,U]);const Fs=()=>{const g=qr.trim();g&&(typeof V=="function"?V(g):i==null||i(g),Tr(""),requestAnimationFrame(()=>{var G;return(G=Qe.current)==null?void 0:G.focus()}))},fn=g=>{g.key!=="Enter"||g.shiftKey||(g.preventDefault(),Fs())},Pr=(g,G)=>{typeof y!="function"||!G||y(g,G)},tt=typeof I=="boolean"?I:!!(me||m),aa=tt?"border-white/10 bg-[#141416]/[0.9] text-white shadow-[0_24px_70px_rgba(0,0,0,0.48)]":"border-black/10 bg-white/90 text-gray-950 shadow-[0_24px_70px_rgba(15,23,42,0.18)]",Os=tt?"border-white/[0.07] bg-white/[0.045]":"border-black/[0.055] bg-black/[0.03]",oa=tt?"border-white/[0.09] bg-[#1a1a1d]/[0.94] text-white shadow-[0_22px_70px_rgba(0,0,0,0.52),inset_0_1px_0_rgba(255,255,255,0.06)]":"border-black/[0.08] bg-white/[0.96] text-gray-950 shadow-[0_22px_60px_rgba(15,23,42,0.22),inset_0_1px_0_rgba(255,255,255,0.8)]",ia=tt?"text-white/[0.86] hover:bg-white/[0.08] hover:text-white focus-visible:bg-white/[0.10]":"text-black/[0.76] hover:bg-black/[0.045] hover:text-black focus-visible:bg-black/[0.06]",Gr="flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition outline-none",la=tt?"text-white/[0.58] hover:bg-white/[0.08] hover:text-white focus-visible:bg-white/[0.10]":"text-black/[0.46] hover:bg-black/[0.055] hover:text-black focus-visible:bg-black/[0.07]",gn=tt?"bg-white/[0.12] text-white shadow-sm":"bg-black/[0.075] text-black shadow-sm",lr=(g,G)=>{const ae=G.getBoundingClientRect();Ee({label:g,x:ae.left+ae.width/2,y:ae.top})},gs=({label:g,icon:G,onClick:ae,active:$e=!1,draggableType:bt="",disabled:At=!1})=>e.jsx("button",{type:"button","aria-label":g,onClick:De=>{Ee(null),ae==null||ae(De)},onMouseEnter:De=>lr(g,De.currentTarget),onMouseLeave:()=>Ee(null),onFocus:De=>lr(g,De.currentTarget),onBlur:()=>Ee(null),disabled:At,draggable:!!bt&&!At,onDragStart:De=>Pr(De,bt),className:`${Gr} ${$e?gn:la} disabled:cursor-not-allowed disabled:opacity-35 ${bt?"cursor-grab active:cursor-grabbing":""}`,children:G}),Ce=({label:g,icon:G,onClick:ae,draggableType:$e="",disabled:bt=!1})=>e.jsxs("button",{type:"button","aria-label":g,disabled:bt,draggable:!!$e&&!bt,onDragStart:At=>Pr(At,$e),onClick:At=>{Xt(!1),ae==null||ae(At)},className:`flex min-h-14 items-center gap-3 rounded-2xl px-3 text-left outline-none transition disabled:cursor-not-allowed disabled:opacity-35 ${ia} ${$e?"cursor-grab active:cursor-grabbing":""}`,children:[e.jsx("span",{className:`flex h-9 w-9 shrink-0 items-center justify-center rounded-xl ${tt?"bg-white/[0.07]":"bg-black/[0.045]"}`,children:G}),e.jsx("span",{className:"min-w-0 truncate text-[13px] font-semibold",children:g})]});return F&&!m?e.jsxs("div",{className:"fixed top-1/2 -translate-y-1/2 right-4 z-40",children:[e.jsxs("div",{className:"flex flex-col gap-1 bg-white dark:bg-surface rounded-2xl border border-[var(--card-border)] p-1.5",style:{boxShadow:"0 2px 12px rgba(0,0,0,0.06)"},children:[!r&&e.jsx("button",{onClick:o,className:"p-2 rounded-xl text-gray-500 hover:text-gray-700 hover:bg-gray-50 transition-colors",title:"Add Notepad",children:e.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),e.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),!r&&e.jsx("button",{onClick:()=>{const g=document.getElementById("file-upload-input");g&&g.click()},className:"p-2 rounded-xl text-gray-500 hover:text-gray-700 hover:bg-gray-50 transition-colors",title:"Upload Files",children:e.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),e.jsx("path",{d:"M12 12v9"}),e.jsx("path",{d:"m16 16-4-4-4 4"})]})}),!r&&e.jsx("button",{onClick:f,className:"p-2 rounded-xl text-gray-500 hover:text-gray-700 hover:bg-gray-50 transition-colors",title:"Paste Link",children:e.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),e.jsx("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"})]})}),e.jsx("div",{className:"w-full h-[1px] bg-gray-100 my-0.5"}),!r&&N&&e.jsxs("button",{onClick:N,className:"p-2 rounded-xl text-gray-500 hover:text-gray-700 hover:bg-gray-50 transition-colors relative",title:"Files Library",children:[e.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}),$>0&&e.jsx("div",{className:"absolute -top-0.5 -right-0.5 min-w-[12px] h-[12px] flex items-center justify-center px-[2px] rounded-full bg-gray-500 text-white text-[7px] font-bold leading-none",children:$>99?"99+":$})]})]}),!r&&e.jsx("input",{id:"file-upload-input",type:"file",multiple:!0,accept:".pdf,.txt,.json,.jpg,.jpeg,.png,.gif,.webp,.bmp,.svg,.mp4,.mov,.m4v,.webm",onChange:g=>{u(g),g.target.value=""},style:{display:"none"}})]}):e.jsxs(e.Fragment,{children:[Be&&typeof document<"u"&&Un.createPortal((()=>{const g=["All","tiktok","youtube","instagram"],G=jt==="saved"?wr:Ke??we.slice(0,12),ae=Ar,$e=jt!=="saved"&&!Ke&&!le&&!re.trim()&&!Qt,bt=[{query:"UGC ads",title:"UGC Ad Hooks",kicker:"TikTok, Reels, Shorts",platform:"All",image:"/viral-search-previews/ugc-ad-hooks.webp"},{query:"product demos",title:"Product Demo Ads",kicker:"Show the offer fast",platform:"youtube",image:"/viral-search-previews/product-demo-shorts.webp"},{query:"AI tools",title:"AI Tool Ads",kicker:"Software angles",platform:"All",image:"/viral-search-previews/ai-tool-launches.webp"},{query:"restaurant",title:"Restaurant Ads",kicker:"Local food hooks",platform:"All",image:"/viral-search-previews/restaurant-reels.webp"}],At=["Meta Ads","TikTok","Instagram","YouTube","LinkedIn"],De=fe==="All"?"All platforms":er(fe),it=ve==="All"?"All platforms":er(ve),ms=Ke&&fe==="All"&&ve!=="All"?it:De,Ir=jt==="saved"?"Saved assets":Ke?`"${le||re}" in ${it}`:"Trending ads and videos",xn=A=>A==="All"?G.length:G.filter(ut=>ps(ut)===A).length,Er=!!(Ke!=null&&Ke.length)&&(Qt||oe==="partial_cache"),bn=!!(Ke!=null&&Ke.length)&&pe&&!Er,yn=!!(Ke!=null&&Ke.length)&&["failed_cache","provider_unavailable_cache","rate_limited_cache"].includes(String(oe)),cr=!!(Ke!=null&&Ke.length)&&oe==="background_cache",Yr=ei(z),Bs=ei(T),wn=Er?ae.length:0,vn=Er&&wn<4,Kr=vn?`Found ${wn} cached match${wn===1?"":"es"}; checking live search for more`:Yr||(de==="digest_loading"?"Pulling the latest ads and videos":"Preparing live search results"),Ms=!!(T!=null&&T.toLowerCase().includes("rate-limiting"))||oe==="rate_limited",xs=sr("mb-2 overflow-hidden rounded-[22px] border p-4 backdrop-blur-[28px] backdrop-saturate-[1.65]",M?"border-white/20 bg-[#101113] text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.08),0_22px_70px_rgba(0,0,0,0.58)]":"border-white/70 bg-white/95 text-gray-950 shadow-[inset_0_1px_0_rgba(255,255,255,0.78),0_18px_54px_rgba(2,6,23,0.2)]"),bs=sr("mb-2 overflow-hidden rounded-[22px] border p-3 backdrop-blur-[28px] backdrop-saturate-[1.65]",M?"border-white/20 bg-[#101113] text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.08),0_22px_70px_rgba(0,0,0,0.58)]":"border-white/70 bg-white/95 text-gray-950 shadow-[inset_0_1px_0_rgba(255,255,255,0.78),0_18px_58px_rgba(2,6,23,0.2)]"),kn=sr("mb-2 rounded-[22px] border p-4 backdrop-blur-[28px] backdrop-saturate-[1.65]",M?"border-amber-300/70 bg-[#101113] text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.08),0_22px_70px_rgba(0,0,0,0.58)]":"border-amber-300 bg-white text-gray-950 shadow-[inset_0_1px_0_rgba(255,255,255,0.78),0_18px_54px_rgba(2,6,23,0.18)]"),jn=sr("mb-2 rounded-[22px] border p-3 text-sm font-semibold backdrop-blur-[28px] backdrop-saturate-[1.65]",Ms?M?"border-amber-300/70 bg-[#101113] text-amber-50 shadow-[inset_0_1px_0_rgba(255,255,255,0.08),0_22px_70px_rgba(0,0,0,0.58)]":"border-amber-300 bg-white text-amber-800 shadow-[inset_0_1px_0_rgba(255,255,255,0.75),0_18px_54px_rgba(2,6,23,0.18)]":M?"border-red-300/70 bg-[#101113] text-red-100 shadow-[inset_0_1px_0_rgba(255,255,255,0.08),0_22px_70px_rgba(0,0,0,0.58)]":"border-red-300 bg-white text-red-700 shadow-[inset_0_1px_0_rgba(255,255,255,0.75),0_18px_54px_rgba(2,6,23,0.18)]"),Mt=M?"text-white":"text-gray-950",Jr=M?"text-white/80":"text-gray-700",ys=M?"text-white/70":"text-gray-600",ca=M?"shrink-0 animate-spin text-white/70":"shrink-0 animate-spin text-gray-500",da=sr("mb-2 flex items-center gap-2 overflow-hidden rounded-[18px] border px-2.5 py-2 backdrop-blur-[24px]",M?"border-white/20 bg-[#101113] text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.08),0_16px_44px_rgba(0,0,0,0.56)]":"border-gray-200 bg-white text-gray-950 shadow-[inset_0_1px_0_rgba(255,255,255,0.82),0_10px_32px_rgba(2,6,23,0.16)]"),Us=M?"shrink-0 text-[10px] font-bold uppercase tracking-[0.08em] text-white/75":"shrink-0 text-[10px] font-bold uppercase tracking-[0.08em] text-gray-600",Lr=(A,ut,Tt)=>sr("flex h-8 max-w-[260px] shrink-0 items-center gap-1.5 rounded-full border px-2.5 text-[11px] font-semibold transition",A?M?"border-white bg-white text-gray-950 shadow-[0_10px_22px_rgba(255,255,255,0.12)]":"border-gray-950 bg-gray-950 text-white shadow-[0_10px_22px_rgba(15,23,42,0.18)]":ut?M?"border-emerald-200/80 bg-emerald-300/20 text-emerald-50 hover:bg-emerald-300/30":"border-emerald-400 bg-emerald-100 text-emerald-950 hover:bg-emerald-200":Tt?M?"border-red-200/80 bg-red-400/20 text-red-50 hover:bg-red-400/30":"border-red-400 bg-red-100 text-red-950 hover:bg-red-200":M?"border-amber-200/80 bg-amber-300/20 text-amber-50 hover:bg-amber-300/30":"border-amber-400 bg-amber-100 text-amber-950 hover:bg-amber-200"),Sn=A=>sr("shrink-0 rounded-full px-1.5 text-[10px]",A?M?"bg-black/10 text-current":"bg-white/20 text-current":M?"bg-black/40 text-current":"bg-white/90 text-current"),ua=sr("flex items-center gap-2 rounded-[22px] border p-1.5 backdrop-blur-[28px] backdrop-saturate-[1.65]",M?"border-white/20 bg-[#101113] text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.08),0_20px_64px_rgba(0,0,0,0.58)]":"border-white/70 bg-white/95 text-gray-950 shadow-[inset_0_1px_0_rgba(255,255,255,0.78),0_16px_48px_rgba(2,6,23,0.22)]"),pa=M?"flex h-10 shrink-0 items-center gap-0.5 rounded-[17px] bg-white/10 p-1":"flex h-10 shrink-0 items-center gap-0.5 rounded-[17px] bg-gray-950/5 p-1",ha=A=>sr("flex h-8 items-center justify-center rounded-[13px] text-[12px] font-bold transition",A?"w-10 bg-white text-gray-950 shadow-sm ring-1 ring-black/5":M?"w-8 text-white/70 hover:bg-white/20 hover:text-white":"w-8 text-gray-500 hover:bg-white/70 hover:text-gray-900"),Vs=A=>sr("rounded-full px-1.5 text-[10px]",A?M?"bg-black/10 text-current":"bg-white/20 text-current":M?"bg-black/25 text-white/70":"bg-white/80 text-gray-500"),Nn=M?"flex h-7 items-center gap-1 rounded-full border border-white/20 bg-white/10 px-2 text-white/90 shadow-sm":"flex h-7 items-center gap-1 rounded-full border border-gray-200/70 bg-white/90 px-2 text-gray-700 shadow-sm",Ws=M?"pointer-events-auto flex h-8 w-8 items-center justify-center rounded-full border border-white/20 bg-black/70 text-white shadow-[0_10px_28px_rgba(0,0,0,0.35)] backdrop-blur transition hover:-translate-y-0.5 hover:bg-black/80":"pointer-events-auto flex h-8 w-8 items-center justify-center rounded-full border border-white/80 bg-white/95 text-gray-900 shadow-[0_10px_28px_rgba(15,23,42,0.18)] backdrop-blur transition hover:-translate-y-0.5",Cn=M?"ml-1 shrink-0 text-white/70":"ml-1 shrink-0 text-gray-500",fa=M?"h-10 min-w-0 flex-1 bg-transparent text-[15px] font-semibold text-white placeholder:text-white/50 outline-none":"h-10 min-w-0 flex-1 bg-transparent text-[15px] font-semibold text-gray-950 placeholder:text-gray-500 outline-none",ga=M?"flex h-9 w-9 items-center justify-center rounded-[15p
50x] text-white/70 transition hover:bg-white/10 hover:text-white":"flex h-9 w-9 items-center justify-center rounded-[15px] text-gray-500 transition hover:bg-gray-950/5 hover:text-gray-800",ma=M?"flex h-10 w-10 items-center justify-center rounded-[17px] text-white/70 transition hover:bg-white/10 hover:text-white":"flex h-10 w-10 items-center justify-center rounded-[17px] text-gray-500 transition hover:bg-gray-950/5 hover:text-gray-800",Xr=M?"flex h-10 items-center gap-2 rounded-[17px] bg-white px-4 text-[13px] font-semibold text-gray-950 shadow-[0_12px_30px_rgba(255,255,255,0.12)] transition hover:bg-white/90 disabled:cursor-not-allowed disabled:opacity-35":"flex h-10 items-center gap-2 rounded-[17px] bg-gray-950 px-4 text-[13px] font-semibold text-white shadow-[0_10px_26px_rgba(15,23,42,0.18)] transition hover:bg-black hover:shadow-[0_14px_34px_rgba(15,23,42,0.24)] disabled:cursor-not-allowed disabled:opacity-35",xa=M?"flex h-10 items-center gap-2 rounded-[17px] border border-white/20 bg-white/10 px-3 text-[13px] font-semibold text-white/85 transition hover:bg-white/20 hover:text-white disabled:cursor-not-allowed disabled:opacity-35":"flex h-10 items-center gap-2 rounded-[17px] border border-gray-200 bg-white px-3 text-[13px] font-semibold text-gray-700 shadow-sm transition hover:border-gray-300 hover:text-gray-950 disabled:cursor-not-allowed disabled:opacity-35";return e.jsx(_e.div,{initial:{opacity:0,y:28,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:18,scale:.98},transition:{type:"spring",damping:32,stiffness:420},className:"fixed inset-x-0 bottom-3 z-[99999] flex justify-center px-4 pointer-events-none",style:{paddingBottom:"max(0px, env(safe-area-inset-bottom))"},role:"dialog","aria-modal":"true","aria-label":"Ad and Video Vault",children:e.jsxs("div",{ref:Zt,className:`pointer-events-auto w-[min(780px,calc(100vw-28px))] transition-opacity duration-200 ${ft?"opacity-72":"opacity-100"}`,children:[e.jsx(Jt,{mode:"wait",children:de==="digest_loading"&&!$e||se||vn?e.jsxs(_e.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},exit:{opacity:0,y:14},transition:{duration:.22,ease:[.16,1,.3,1]},className:xs,children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-4",children:[e.jsxs("div",{className:`min-w-0 ${Mt}`,children:[e.jsx("p",{className:"truncate text-[15px] font-semibold",children:de==="digest_loading"?"Loading ads and videos":`Searching ${it.toLowerCase()} for "${le||re}"`}),e.jsx("p",{className:`mt-0.5 truncate text-[12px] font-medium ${ys}`,children:Kr})]}),e.jsx(Ur,{size:17,className:ca})]}),e.jsx("div",{className:"flex gap-3 overflow-hidden",children:[0,1,2,3,4].map(A=>e.jsxs("div",{className:"relative h-[214px] min-w-[120px] overflow-hidden rounded-[20px] bg-gray-200/80 ring-1 ring-black/5 dark:bg-white/[0.07] dark:ring-white/8 sm:h-[226px] sm:min-w-[128px]",children:[e.jsx("div",{className:"absolute inset-0 animate-pulse bg-gradient-to-b from-white/25 via-transparent to-black/10 dark:from-white/8 dark:to-black/20"}),e.jsx("div",{className:"absolute left-2 top-2 h-5 w-12 animate-pulse rounded-full bg-white/70 dark:bg-white/10"}),e.jsxs("div",{className:"absolute inset-x-2 bottom-2 rounded-[15px] bg-white/70 p-2 dark:bg-black/30",children:[e.jsx("div",{className:"h-3 w-5/6 animate-pulse rounded-full bg-gray-300 dark:bg-white/10"}),e.jsx("div",{className:"mt-2 h-2.5 w-1/2 animate-pulse rounded-full bg-gray-300/80 dark:bg-white/10"})]})]},A))})]},"loading"):ge&&!ae.length?e.jsxs(_e.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},exit:{opacity:0,y:12},className:kn,children:[e.jsx("div",{className:`mb-1 text-[15px] font-semibold ${Mt}`,children:"Live search is running in the background"}),e.jsxs("div",{className:`text-[12px] font-medium ${Jr}`,children:['Live search has not returned results for "',le||re,'" yet. Search another topic while it finishes.']})]},"detached-search"):de==="error"&&Bs?e.jsx(_e.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},exit:{opacity:0,y:14},className:jn,children:Bs},"error"):de==="search_slow"&&!ae.length?e.jsxs(_e.div,{initial:{opacity:0,y:12}
50,animate:{opacity:1,y:0},exit:{opacity:0,y:12},className:kn,children:[e.jsx("div",{className:`mb-1 text-[15px] font-semibold ${Mt}`,children:"Live search is still running"}),e.jsx("div",{className:`text-[12px] font-medium ${Jr}`,children:Yr||"Live search is processing this in the background. Search another topic while it finishes."})]},"background-search"):$e?e.jsxs(_e.div,{initial:{opacity:0,y:18},animate:{opacity:1,y:0},exit:{opacity:0,y:12},transition:{duration:.28,ease:[.16,1,.3,1]},className:bs,children:[e.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3 px-1",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:`truncate text-[15px] font-semibold ${Mt}`,children:"Find ads and videos"}),e.jsx("div",{className:"mt-1 flex flex-wrap gap-1",children:At.map(A=>e.jsx("span",{className:`rounded-full px-2 py-0.5 text-[10px] font-bold ${M?"bg-white/10 text-white/70":"bg-gray-950/5 text-gray-600"}`,children:A},A))})]}),e.jsx("div",{className:`shrink-0 rounded-full px-2.5 py-1 text-[10px] font-bold uppercase tracking-[0.08em] ${M?"bg-white/10 text-white/70":"bg-gray-950/5 text-gray-600"}`,children:"Search"})]}),e.jsx("div",{className:"scrollbar-hide flex snap-x snap-mandatory gap-3 overflow-x-auto px-1 pb-1 pt-0.5",style:{maskImage:"linear-gradient(90deg, transparent 0, black 18px, black calc(100% - 18px), transparent 100%)"},children:bt.map((A,ut)=>e.jsxs(_e.button,{type:"button",onClick:()=>{fr("search"),Ae(A.query),xt(A.platform),Wr(A.query,A.platform)},initial:{opacity:0,y:16,scale:.96},animate:{opacity:1,y:0,scale:1},transition:{delay:ut*.035,duration:.22,ease:[.16,1,.3,1]},whileHover:{y:-4},whileTap:{scale:.985},className:sr("group relative h-[238px] min-w-[158px] snap-start overflow-hidden rounded-[20px] text-left ring-1 transition duration-200 sm:h-[252px] sm:min-w-[176px]",M?"bg-white/10 ring-white/20 shadow-[0_12px_34px_rgba(0,0,0,0.38)]":"bg-gray-100 ring-black/10 shadow-[0_12px_30px_rgba(15,23,42,0.17)]"),children:[e.jsx("img",{"aria-hidden":"true",src:A.image,alt:"",loading:"eager",className:"absolute inset-0 h-full w-full object-cover transition duration-500 group-hover:scale-105"}),e.jsx("div",{"aria-hidden":"true",className:"absolute inset-0 bg-[linear-gradient(180deg,rgba(0,0,0,0.04)_0%,rgba(0,0,0,0.1)_38%,rgba(0,0,0,0.86)_100%)]"}),e.jsxs("div",{className:"absolute inset-x-2 bottom-2 rounded-[15px] bg-black/76 p-2.5 shadow-[0_10px_26px_rgba(0,0,0,0.32)] ring-1 ring-white/10 backdrop-blur-md",children:[e.jsx("p",{className:"text-[12px] font-bold leading-[1.08] text-white drop-shadow-[0_2px_8px_rgba(0,0,0,0.9)]",children:A.title}),e.jsx("p",{className:"mt-1 line-clamp-1 text-[10px] font-bold text-white/82 drop-shadow-[0_1px_4px_rgba(0,0,0,0.85)]",children:A.kicker})]})]},A.query))})]},"search-ideas"):ae.length>0?e.jsxs(_e.div,{initial:{opacity:0,y:18},animate:{opacity:1,y:0},exit:{opacity:0,y:12},transition:{duration:.28,ease:[.16,1,.3,1]},className:bs,children:[e.jsxs("div",{className:"mb-3 space-y-3 px-1",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:`truncate text-[15px] font-semibold ${Mt}`,children:jt==="saved"?`${wr.length} saved`:Ke?Er?`${ae.length} cached ${ms.toLowerCase()} results`:yn||bn?`${ae.length} cached ${ms.toLowerCase()} ${ae.length===1?"match":"matches"}`:`${ae.length} ${ms.toLowerCase()} results`:"Trending now"}),e.jsx("p",{className:`truncate text-[11px] font-medium ${ys}`,children:Er?`${Ir} · searching for more`:yn?`${Ir} · ${Yr||"cached results only"}`:bn?`${Ir} · cached results`:cr?`${Ir} · ${Yr||"live results are still processing"}`:Ke||jt==="saved"?`${Ir} · this filter only changes the results shown below`:"Fresh ad/video signals"})]}),Er?e.jsxs("div",{className:`flex shrink-0 items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-bold ${M?"bg-white/10 text-white/75":"bg-gray-950/5 text-gray-600"}`,children:[e.jsx(Ur,{size:12,className:"animate-spin"}),"Updating"]}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:`mr-0.5 text-[10px] font-bold uppercase tracking-[0.08em] ${M?"text-white/60":"text-gray-500"}`,children:"Show"}),g.map(A=>e.jsxs("button",{onClick:()=>ze(A),className:`flex h-7 items-center gap-1.5 rounded-full px-2.5 text-[11px] font-semibold transition ${fe===A?M?"bg-white text-gray-950 shadow-[0_8px_18px_rgba(255,255,255,0.12)]":"bg-gray-950 text-white shadow-[0_8px_18px_rgba(15,23,42,0.18)]":M?"bg-white/10 text-white/70 hover:bg-white/20 hover:text-white":"bg-gray-950/5 text-gray-600 hover:bg-gray-950/10 hover:text-gray-950"}`,children:[A!=="All"&&tr(A,12),e.jsx("span",{children:A==="All"?"All":er(A)}),e.jsx("span",{className:Vs(fe===A),children:xn(A)})]},A))]}),e.jsxs("div",{className:Nn,children:[e.jsx(Cc,{size:12}),e.jsxs("select",{value:Lt,onChange:A=>us(A.target.value),className:"h-6 bg-transparent text-[11px] font-semibold outline-none",children:[e.jsx("option",{value:"views",children:"Views"}),e.jsx("option",{value:"recent",children:"Newest"})]})]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{ref:kt,className:"scrollbar-hide flex snap-x snap-mandatory gap-3 overflow-x-auto scroll-smooth px-1 pb-1 pt-0.5",style:{maskImage:"linear-gradient(90deg, transparent 0, black 18px, black calc(100% - 18px), transparent 100%)"},children:ae.map((A,ut)=>{const Tt=!!vr[A.id],zr=ps(A),Nr=Te(A),gr=Nr?"":fs(A),Cr=yr===A.id,Dr=Cr&&!!ar[A.id]&&!!(Nr||gr),_n=Hr(A.publishedAt),$n=hs(A),dr=!!gr&&ut<5&&!ft;return e.jsxs(_e.div,{draggable:!0,onDragStart:rt=>Yt(rt,A),onDragEnd:()=>vt(!1),onPointerEnter:()=>{St(A.id),ot(rt=>({...rt,[A.id]:!1}))},onPointerLeave:()=>{St(null),ot(rt=>({...rt,[A.id]:!1}))},onPointerMove:()=>St(A.id),onMouseEnter:()=>{St(A.id),ot(rt=>({...rt,[A.id]:!1}))},onMouseLeave:()=>{St(null),ot(rt=>({...rt,[A.id]:!1}))},onFocus:()=>{St(A.id),ot(rt=>({...rt,[A.id]:!1}))},onBlur:()=>{St(null),ot(rt=>({...rt,[A.id]:!1}))},initial:{opacity:0,y:16,scale:.96}
50,animate:{opacity:1,y:0,scale:1},transition:{delay:Math.min(ut,8)*.025,duration:.22,ease:[.16,1,.3,1]},whileHover:{y:-4},whileTap:{scale:.985},className:sr("group relative h-[238px] min-w-[144px] snap-start cursor-grab overflow-hidden rounded-[20px] ring-1 transition duration-200 active:cursor-grabbing sm:h-[252px] sm:min-w-[154px]",M?"bg-white/10 ring-white/20 shadow-[0_12px_34px_rgba(0,0,0,0.38)]":"bg-gray-100 ring-black/10 shadow-[0_12px_30px_rgba(15,23,42,0.17)]",Tt?M?"ring-2 ring-white/80":"ring-2 ring-gray-950/80":""),children:[Nr?e.jsx(Od,{src:Nr,poster:A.thumbnailUrl,active:Cr,onReady:()=>ot(rt=>({...rt,[A.id]:!0}))}):gr?e.jsx(Bd,{src:gr,poster:A.thumbnailUrl,title:je(A.title),active:Cr,preload:dr,platform:zr,onReady:()=>ot(rt=>({...rt,[A.id]:!0}))}):A.thumbnailUrl?e.jsx("img",{src:A.thumbnailUrl,alt:"",className:"h-full w-full object-cover brightness-[1.07] saturate-[1.08] transition duration-500 group-hover:scale-105"}):e.jsx("div",{className:"h-full w-full bg-gray-200 dark:bg-white/10"}),e.jsx("div",{className:`pointer-events-none absolute inset-0 bg-gradient-to-t from-black/80 via-black/10 to-black/0 transition-opacity duration-200 ${Dr?"opacity-0":"opacity-100"}`}),e.jsx("div",{className:`pointer-events-none absolute inset-x-0 top-0 h-16 bg-gradient-to-b from-black/36 to-transparent transition-opacity duration-200 ${Dr?"opacity-0":"opacity-100"}`}),e.jsxs("div",{className:`absolute left-2 top-2 flex max-w-[calc(100%-16px)] items-center gap-1.5 transition-opacity duration-200 ${Dr?"opacity-0":"opacity-100"}`,children:[e.jsx("span",{className:"rounded-full bg-black/70 px-1.5 py-0.5 text-[10px] font-bold text-white shadow ring-1 ring-white/10 backdrop-blur",children:er(zr)}),$n?e.jsx("span",{className:"rounded-full bg-black/70 px-1.5 py-0.5 text-[10px] font-mono font-semibold text-white shadow ring-1 ring-white/10 backdrop-blur",children:$n}):null,e.jsx("span",{className:"rounded-full bg-white px-1.5 py-0.5 text-[10px] font-black text-gray-950 shadow ring-1 ring-black/10",children:"Drag"})]}),e.jsx("div",{className:`absolute right-2 top-2 flex flex-col gap-1.5 transition-opacity duration-200 ${Dr?"opacity-0":"opacity-100"}`,children:e.jsx("button",{onClick:rt=>{rt.stopPropagation(),kr(A)},className:`flex h-8 w-8 items-center justify-center rounded-full shadow-lg ring-1 backdrop-blur transition ${Tt?"bg-white text-gray-950 ring-black/10 dark:bg-white dark:text-gray-950":"bg-black/70 text-white ring-white/10 hover:bg-white hover:text-gray-950 hover:ring-black/10"}`,title:Tt?"Saved":"Save","aria-label":Tt?"Remove from saved":"Save asset",children:Tt?e.jsx(cs,{size:14,strokeWidth:3}):e.jsx(wc,{size:14})})}),e.jsxs("div",{className:`absolute inset-x-2 bottom-2 rounded-[15px] bg-black/75 p-2 shadow-[0_10px_26px_rgba(0,0,0,0.32)] ring-1 ring-white/10 backdrop-blur-md transition-opacity duration-200 ${Dr?"pointer-events-none opacity-0":"opacity-100"}`,children:[e.jsx("p",{className:"line-clamp-2 text-[12px] font-bold leading-[1.08] text-white drop-shadow-[0_2px_8px_rgba(0,0,0,0.9)]",children:je(A.title)}),e.jsxs("div",{className:"mt-1.5 flex min-w-0 items-center gap-1.5 text-[10px] font-bold text-white drop-shadow-[0_1px_4px_rgba(0,0,0,0.85)]",children:[e.jsx(ta,{size:11,strokeWidth:2.3,className:"shrink-0 text-white"}),e.jsx("span",{className:"shrink-0 text-white",children:Ed(A.viewCount)}),_n?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"shrink-0 text-white/60",children:"·"}),e.jsx("span",{className:"min-w-0 truncate text-white/90",children:_n})]}):null]})]})]},A.id)})}),e.jsx("div",{className:"pointer-events-none absolute inset-y-0 left-0 flex items-center",children:e.jsx("button",{type:"button",onClick:()=>un(-1),className:Ws,title:"Scroll left",children:e.jsx(Yn,{size:14})})}),e.jsx("div",{className:"pointer-events-none absolute inset-y-0 right-0 flex items-center",children:e.jsx("button",{type:"button",onClick:()=>un(1),className:Ws,title:"Scroll right",children:e.jsx(Kn,{size:14})})})]})]},"rail"):G.length>0&&fe!=="All"?e.jsx(_e.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},exit:{opacity:0,y:12},className:xs,children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsxs("p",{className:`text-[15px] font-semibold ${Mt}`,children:["No ",De," results here"]}),e.jsxs("p",{className:`mt-0.5 text-[12px] font-medium ${ys}`,children:["Switch back to All, or run a new search scoped to ",De,"."]})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:`mr-0.5 text-[10px] font-bold uppercase tracking-[0.08em] ${M?"text-white/60":"text-gray-500"}`,children:"Show"}),g.map(A=>e.jsxs("button",{onClick:()=>ze(A),className:`flex h-7 items-center gap-1.5 rounded-full px-2.5 text-[11px] font-semibold transition ${fe===A?M?"bg-white text-gray-950 shadow-[0_8px_18px_rgba(255,255,255,0.12)]":"bg-gray-950 text-white shadow-[0_8px_18px_rgba(15,23,42,0.18)]":M?"bg-white/10 text-white/70 hover:bg-white/20 hover:text-white":"bg-gray-950/5 text-gray-600 hover:bg-gray-950/10 hover:text-gray-950"}`,children:[A!=="All"&&tr(A,12),e.jsx("span",{children:A==="All"?"All":er(A)}),e.jsx("span",{className:Vs(fe===A),children:xn(A)})]},A))]})]})},"empty-filter"):de==="empty"?e.jsxs(_e.div,{initial:{opacity:0,y:12}
50,animate:{opacity:1,y:0},exit:{opacity:0,y:12},className:xs,children:[e.jsxs("div",{className:`mb-2 text-[15px] font-semibold ${Mt}`,children:['No results for "',le||re,'"']}),e.jsx("div",{className:`text-[12px] font-medium ${ys}`,children:"Try a broader topic, fewer constraints, or a creator name."})]},"empty-results"):e.jsxs(_e.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},exit:{opacity:0,y:12},className:xs,children:[e.jsx("div",{className:`mb-3 flex items-center gap-2 text-[15px] font-semibold ${Mt}`,children:e.jsx("span",{children:jt==="saved"?"No saved assets yet":"Search ads and videos"})}),e.jsx("div",{className:"flex flex-wrap gap-2",children:["AI tools","UGC ads","Product demos","Founder stories"].map(A=>e.jsx("button",{onClick:()=>void Wr(A),className:`rounded-full border px-3.5 py-2 text-[12px] font-semibold shadow-sm transition hover:-translate-y-0.5 hover:shadow-md ${M?"border-white/20 bg-white/10 text-white/80 hover:bg-white/20 hover:text-white":"border-gray-200/80 bg-white text-gray-800 hover:border-gray-300 hover:text-gray-950"}`,children:A},A))})]},"empty")}),or.length>0?e.jsxs(_e.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},exit:{opacity:0,y:8},className:da,children:[e.jsx("span",{className:Us,children:"Searches"}),e.jsx("div",{className:"scrollbar-hide flex min-w-0 flex-1 gap-1.5 overflow-x-auto",children:or.map(A=>{var Cr;const ut=A.status==="completed",Tt=A.status==="failed",zr=A.searchId===xe,Nr=(Cr=A.platforms)!=null&&Cr.length?A.platforms.map(er).join(", "):"All",gr=ut?A.resultCount>0?`${A.resultCount} ready`:"Ready":Tt?"Failed":A.status==="queued"?"Queued":"Running";return e.jsxs("button",{type:"button",onClick:()=>void jr(A.searchId),className:Lr(zr,ut,Tt),title:`${A.query} - ${Nr} - ${gr}`,children:[ut?e.jsx(cs,{size:12,strokeWidth:3}):Tt?e.jsx(qt,{size:12,strokeWidth:3}):e.jsx(Ur,{size:12,className:"animate-spin"}),e.jsx("span",{className:"min-w-0 truncate",children:A.query}),e.jsx("span",{className:Sn(zr),children:Nr}),e.jsx("span",{className:Sn(zr),children:gr})]},A.searchId)})})]}):null,e.jsxs(_e.form,{layout:!0,onSubmit:A=>{A.preventDefault(),fr("search"),Wr(re)},className:ua,children:[e.jsx("div",{className:pa,"aria-label":"Search platform",children:g.map(A=>{const ut=ve===A,Tt=A==="All"?"All":er(A);return e.jsx("button",{type:"button",onClick:()=>xt(A),className:ha(ut),title:`Search ${Tt}`,"aria-pressed":ut,"aria-label":`Search ${Tt}`,children:A==="All"?e.jsx("span",{children:"All"}):e.jsx("span",{className:ut?"text-gray-950":A==="youtube"?"text-red-500":A==="instagram"?"text-pink-500":"text-cyan-400",children:tr(A,15)})},A)})}),e.jsx(fi,{size:18,className:Cn}),e.jsx("input",{ref:Ot,type:"text",value:re,onChange:A=>Ae(A.target.value),placeholder:`Search ${it.toLowerCase()} ads and videos...`,className:fa}),re&&e.jsx("button",{type:"button",onClick:()=>{Bt()},className:ga,title:"Clear","aria-label":"Clear ad search",children:e.jsx(qt,{size:16})}),Ie&&re.trim()?e.jsxs("button",{type:"button",disabled:Sr,onClick:()=>{fr("search"),Ps(re)},className:xa,title:`Live refresh uses ${Le||50} Virlo credits`,"aria-label":"Live refresh ad search",children:[e.jsx(cc,{size:14}),"Live refresh"]}):null,e.jsxs("button",{type:"submit",disabled:Sr,className:Xr,children:[se?e.jsx(Ur,{size:15,className:"animate-spin"}):e.jsx(Rs,{size:15}),"Find"]}),e.jsx("button",{type:"button",onClick:()=>{ne()},className:ma,title:"Close","aria-label":"Close Ad and Video Vault",children:e.jsx(qt,{size:17})})]})]})})})(),document.body),e.jsx("div",{className:ke,style:pn,children:e.jsx(Jt,{mode:"wait",children:Be?null:e.jsxs(_e.div,{initial:{opacity:0,y:10,scale:.985},animate:{opacity:1,y:0},exit:{opacity:0,y:24,scale:.96},transition:{type:"spring",damping:28,stiffness:400},className:Oe?"w-full min-w-0 pointer-events-auto":m&&!ce?"mx-auto w-[calc(100%_-_48px)] max-w-[420px] min-w-0 pointer-events-auto transition-[width] duration-300 ease-out":"w-[min(540px,calc(100vw-32px))] pointer-events-auto",children:[P&&e.jsxs(_e.button,{type:"button",initial:{opacity:0,y:6},animate:{opacity:1,y:0},exit:{opacity:0,y:6},onClick:()=>Ne==null?void 0:Ne(),className:`flex items-center gap-2 w-full mb-2 px-4 py-2 rounded-2xl text-left transition-colors ${tt?"bg-surface/80 border border-white/10 hover:bg-white/10 text-white/80":"bg-white/80 border border-black/10 hover:bg-black/5 text-gray-800"}`,style:{WebkitBackdropFilter:"blur(24px) saturate(180%)",backdropFilter:"blur(24px) saturate(180%)"},children:[e.jsx(qa,{size:14,className:`flex-shrink-0 ${tt?"text-white/50":"text-gray-500"}`}),e.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${P.status==="error"?"bg-red-500":P.status==="completed"?"bg-green-500":"bg-purple-500 animate-pulse"}`}),e.jsx("span",{className:"text-xs font-medium truncate flex-1",children:(mn=P.logs)!=null&&mn.length?P.logs[P.logs.length-1].message:"Starting agent mission..."}),e.jsx("span",{className:`text-[10px] uppercase tracking-wider font-bold flex-shrink-0 ${tt?"text-white/30":"text-gray-400"}`,children:P.status})]}),e.jsxs("form",{onSubmit:g=>{g.preventDefault(),Fs()},className:`relative overflow-visible rounded-[24px] border px-3 pb-2 pt-3 backdrop-blur-2xl transition ${aa}`,style:{WebkitBackdropFilter:"blur(24px) saturate(160%)",backdropFilter:"blur(24px) saturate(160%)"},children:[Ls.length>0&&e.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:Ls.map(g=>e.jsxs("span",{className:`flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-medium ${tt?"border-white/[0.12] bg-white/[0.07] text-white/85":"border-black/[0.08] bg-black/[0.04] text-black/75"}`,children:[e.jsx(Po,{size:11,className:"shrink-0 opacity-60"}),e.jsx("span",{className:"max-w-[180px] truncate",children:g.name}),e.jsx("button",{type:"button","aria-label":`Remove ${g.name}`,onClick:()=>J==null?void 0:J(g.name),className:`shrink-0 rounded-full p-0.5 transition ${tt?"hover:bg-white/15 text-white/60 hover:text-white":"hover:bg-black/10 text-black/50 hover:text-black"}`,children:e.jsx(qt,{size:11})})]},`${g.name}-${g.size}`))}),e.jsx(Jt,{mode:"wait",initial:!1,children:b?e.jsx(Id,{question:b.question,options:b.options||[],onAnswer:g=>q==null?void 0:q(g),onDismiss:()=>Q==null?void 0:Q(),darkMode:tt},"operator-question"):e.jsx(_e.div,{initial:{opacity:0}
50,animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},className:"flex min-w-0 items-end",children:e.jsx("textarea",{ref:Qe,value:qr,onChange:g=>Tr(g.target.value),onInput:hn,onKeyDown:fn,rows:1,placeholder:O,className:`max-h-20 min-h-8 w-full resize-none overflow-y-auto bg-transparent px-0 py-1 text-[15px] font-medium leading-6 outline-none ${tt?"text-white placeholder:text-white/[0.38]":"text-black placeholder:text-black/[0.36]"}`})},"prompt-input")}),e.jsxs("div",{className:"mt-1.5 flex items-center justify-between gap-2.5",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2","aria-label":"Canvas tools",children:[!j&&e.jsxs("div",{className:`flex shrink-0 items-center gap-0.5 rounded-full border p-0.5 ${Os}`,children:[!F&&gs({label:"Pan",icon:e.jsx(mi,{size:16}),onClick:()=>a("pan"),active:s==="pan"}),!r&&!F&&gs({label:"Select",icon:e.jsx(xi,{size:16}),onClick:()=>a("select"),active:s==="select"})]}),!r&&!j&&e.jsxs("div",{className:"relative shrink-0",children:[e.jsx("button",{ref:et,type:"button","aria-label":"Tools","aria-expanded":Ge,onClick:()=>{Ee(null),Xt(g=>!g)},onMouseEnter:g=>lr("Tools",g.currentTarget),onMouseLeave:()=>Ee(null),onFocus:g=>lr("Tools",g.currentTarget),onBlur:()=>Ee(null),className:`flex h-9 w-9 shrink-0 items-center justify-center rounded-full border transition outline-none ${Ge?tt?"border-white/[0.12] bg-white/[0.14] text-white":"border-black/[0.08] bg-black/[0.08] text-black":`${Os} ${tt?"text-white/[0.68] hover:bg-white/[0.08] hover:text-white":"text-black/[0.56] hover:bg-black/[0.045] hover:text-black"}`}`,children:e.jsx(Rs,{size:17,className:`transition-transform duration-200 ${Ge?"rotate-45":""}`})}),e.jsx(Jt,{children:Ge&&e.jsx(_e.div,{ref:br,initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:8,scale:.98},transition:{type:"spring",damping:28,stiffness:420},className:`absolute bottom-full left-0 z-[80] mb-3 w-[min(360px,calc(100vw-48px))] rounded-[26px] border p-2 backdrop-blur-2xl ${oa}`,style:{WebkitBackdropFilter:"blur(26px) saturate(170%)",backdropFilter:"blur(26px) saturate(170%)"},children:e.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[!F&&Ce({label:"Chat",icon:e.jsx(bi,{size:20}),onClick:()=>i==null?void 0:i(),draggableType:"threadNode"}),Ce({label:"Notepad",icon:e.jsx(As,{size:20}),onClick:o,draggableType:"notepadNode"}),d&&Ce({label:"Sticky",icon:e.jsx(yi,{size:20}),onClick:g=>{const G=g.currentTarget.getBoundingClientRect();Re(ae=>({open:!ae.open,x:G.left+G.width/2,y:G.top,placement:"top"}))}}),!F&&h&&Ce({label:"Group",icon:e.jsx(wi,{size:20}),onClick:h}),Ce({label:"Upload",icon:e.jsx(vi,{size:20}),onClick:()=>{const g=document.getElementById("file-upload-input");g&&g.click()}}),Ce({label:"Link",icon:e.jsx(ki,{size:20}),onClick:f}),N&&Ce({label:"Library",icon:e.jsxs("span",{className:"relative flex h-full w-full items-center justify-center",children:[e.jsx(As,{size:20}),$>0&&e.jsx("span",{className:"absolute -right-1 -top-1 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-blue-500 px-1 text-[8px] font-bold leading-none text-white",children:$>99?"99+":$})]}),onClick:N})]})})})]}),Es&&!r&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:Ue,type:"file",multiple:!0,accept:".pdf,.docx,.doc,.xlsx,.xls,.csv,.pptx,.txt,.md,.json,.png,.jpg,.jpeg",className:"hidden",onChange:g=>{_==null||_(g.target.files),g.target.value=""}}),e.jsx("button",{type:"button","aria-label":"Attach a file for the agent",onClick:()=>{var g;Ee(null),(g=Ue.current)==null||g.click()},onMouseEnter:g=>lr("Attach file",g.currentTarget),onMouseLeave:()=>Ee(null),onFocus:g=>lr("Attach file",g.currentTarget),onBlur:()=>Ee(null),className:`flex h-9 w-9 shrink-0 items-center justify-center rounded-full border transition outline-none ${Os} ${tt?"text-white/[0.68] hover:bg-white/[0.08] hover:text-white":"text-black/[0.56] hover:bg-black/[0.045] hover:text-black"}`,children:e.jsx(Po,{size:15})})]})]}),e.jsx("button",{type:"submit",disabled:!zs,className:`flex h-9 w-9 shrink-0 items-center justify-center rounded-full transition disabled:cursor-not-allowed disabled:opacity-35 ${zs?tt?"bg-white text-black shadow-[0_10px_28px_rgba(255,255,255,0.12)] hover:bg-white/90":"bg-black text-white shadow-[0_10px_28px_rgba(15,23,42,0.18)] hover:bg-black/90":tt?"bg-white/[0.07] text-white/45":"bg-black/[0.05] text-black/35"}`,"aria-label":"Send prompt",title:"Send prompt",children:e.jsx(Ha,{size:16})})]})]})]},"canvas-prompt")})}),dt&&typeof document<"u"&&Un.createPortal(e.jsx(_e.div,{initial:{opacity:0}
50,animate:{opacity:1},exit:{opacity:0},transition:{duration:.3},className:"fixed inset-0 z-[100000] flex items-end justify-center px-4 pb-6",style:{backgroundColor:"#0d0d0f",backgroundImage:"linear-gradient(rgba(255,255,255,.04) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.04) 1px, transparent 1px)",backgroundSize:"40px 40px"},onClick:()=>gt(!1),children:e.jsx("div",{className:"w-full max-w-[min(1080px,calc(100vw-32px))]",onClick:g=>g.stopPropagation(),children:e.jsx(Nd,{autoExpand:!0,onClose:()=>gt(!1)})})}),document.body),at&&typeof document<"u"&&Un.createPortal(e.jsx(Jt,{children:e.jsx(_e.div,{initial:{opacity:0,y:4,scale:.96},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:4,scale:.96},transition:{duration:.12},className:`pointer-events-none fixed z-[100000] -translate-x-1/2 -translate-y-full whitespace-nowrap rounded-lg px-2.5 py-1 text-[11px] font-semibold shadow-lg ${tt?"bg-white text-black":"bg-black text-white"}`,style:{left:at.x,top:at.y-8},children:at.label},at.label)}),document.body),!r&&e.jsx("input",{id:"file-upload-input",type:"file",multiple:!0,accept:".pdf,.txt,.json,.jpg,.jpeg,.png,.gif,.webp,.bmp,.svg,.mp4,.mov,.m4v,.webm",onChange:g=>{u(g),g.target.value=""},style:{display:"none"}}),ye.open&&typeof document<"u"&&Un.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[60]",onMouseDown:()=>Re({open:!1,x:0,y:0,placement:"top"})}),e.jsx("div",{className:"fixed z-[70] bg-white/95 dark:bg-surface/95 backdrop-blur-xl rounded-2xl shadow-2xl border border-gray-200 dark:border-gray-800 px-4 py-3",style:{left:ye.x,top:ye.placement==="bottom"?ye.y+12:ye.y-12,transform:ye.placement==="bottom"?"translate(-50%, 0)":"translate(-50%, -100%)",boxShadow:"0 10px 30px rgba(0,0,0,0.12)"},onMouseDown:g=>g.stopPropagation(),children:e.jsx("div",{className:"flex items-center gap-3",children:Ye.map(g=>e.jsx("button",{className:"w-7 h-7 rounded-full border border-black/10 dark:border-white/10",style:{background:g},title:`Sticky note color ${g}`,onClick:()=>{d(g),Re({open:!1,x:0,y:0,placement:"top"})}},g))})})]}),document.body)]})}const Ri=n.memo(function({item:r,darkMode:s,onAdd:a}){const i=r.kind==="youtube",o=i?Ga:As,d=i&&r.videoId?`https://img.youtube.com/vi/${r.videoId}/mqdefault.jpg`:null;return e.jsxs("div",{draggable:!r.placed,tabIndex:r.placed?-1:0,"aria-label":r.placed?`${r.title} is on the canvas`:`Drag ${r.title} onto the canvas to add it`,onDragStart:p=>{if(r.placed){p.preventDefault();return}p.dataTransfer.effectAllowed="copy",p.dataTransfer.setData(Fa,ud(r))},className:`group flex items-center gap-2.5 rounded-xl border px-2.5 py-2 transition ${r.placed?s?"border-white/5 bg-white/[0.025] opacity-60":"border-slate-200 bg-slate-50 opacity-65":s?"cursor-grab border-white/10 bg-white/[0.055] hover:border-white/20 hover:bg-white/[0.09] active:cursor-grabbing":"cursor-grab border-slate-200 bg-white hover:border-slate-300 hover:bg-slate-50 active:cursor-grabbing"}`,"data-canvas-source-kind":r.kind,"data-canvas-source-placed":r.placed?"true":"false",children:[e.jsx("div",{className:`relative flex h-11 w-14 shrink-0 items-center justify-center overflow-hidden rounded-lg ${s?"bg-white/10":"bg-slate-100"}`,children:d?e.jsx("img",{src:d,alt:"",className:"h-full w-full object-cover",draggable:!1,loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx(o,{size:21,className:i?"text-red-500":"text-violet-500"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:`mb-0.5 text-[10px] font-semibold uppercase tracking-[0.12em] ${s?"text-white/40":"text-slate-400"}`,children:i?"YouTube":"PDF"}),e.jsx("div",{className:`line-clamp-2 text-xs font-medium leading-4 ${s?"text-white/85":"text-slate-700"}`,title:r.title,children:r.title})]}),r.placed?e.jsx(cs,{size:16,className:s?"text-emerald-400":"text-emerald-600","aria-label":"On canvas"}):a?e.jsx("button",{type:"button",onClick:()=>a(r),"aria-label":`Add ${r.title} to the board`,title:"Add to board",className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border transition ${s?"border-white/15 text-white/70 hover:bg-white/10 hover:text-white":"border-slate-200 text-slate-500 hover:bg-slate-100 hover:text-slate-900"}`,children:e.jsx(Rs,{size:15})}):e.jsx(xl,{size:16,className:`shrink-0 transition ${s?"text-white/25 group-hover:text-white/55":"text-slate-300 group-hover:text-slate-500"}`,"aria-hidden":"true"})]})});n.memo(function({tray:r,darkMode:s=!1,onClose:a,onAddSource:i,docked:o=!1}){const d=(r==null?void 0:r.status)==="searching",p=r?r.expected.youtube+r.expected.pdf:0,h=(r==null?void 0:r.items.length)??0,y=s?"border-white/10 bg-[#161719]/[0.96] text-white shadow-black/40":"border-slate-200/90 bg-white/[0.96] text-slate-900 shadow-slate-900/15",f=o?"relative w-full":"fixed bottom-5 right-5 z-[115] w-[min(360px,calc(100vw-40px))]";return e.jsxs("section",{role:"region","aria-label":"Sources","data-canvas-source-tray":!0,"data-canvas-source-docked":o?"true":"false",className:`flex flex-col overflow-hidden rounded-2xl border shadow-2xl backdrop-blur-2xl ${f} ${y}`,onMouseMove:u=>u.stopPropagation(),onMouseDown:u=>u.stopPropagation(),onDragOver:u=>{u.preventDefault(),u.stopPropagation(),u.dataTransfer.dropEffect="none"},onDrop:u=>{u.preventDefault(),u.stopPropagation()},children:[e.jsxs("div",{className:"flex items-center gap-2 px-3.5 pt-3",children:[e.jsx("h2",{className:"text-sm font-semibold",children:"Sources"}),e.jsx("span",{className:`rounded-full px-1.5 py-0.5 text-[10px] font-semibold ${s?"bg-white/10 text-white/55":"bg-slate-100 text-slate-500"}`,children:p>0?`${h}/${p}`:h}),d?e.jsx(Ur,{size:13,className:"animate-spin text-violet-500","aria-label":"Searching"}):null,e.jsx("span",{className:"flex-1"}),r?e.jsx("button",{type:"button",onClick:a,className:`rounded-lg p-1 transition ${s?"text-white/35 hover:bg-white/10 hover:text-white/75":"text-slate-400 hover:bg-slate-100 hover:text-slate-700"}`,"aria-label":"Clear sources",children:e.jsx(qt,{size:15})}):null]}),e.jsxs("div",{className:"space-y-2 overflow-y-auto px-3 pb-2 pt-2",style:{maxHeight:"min(46vh, 340px)"},children:[((r==null?void 0:r.items)??[]).map(u=>e.jsx(Ri,{item:u,darkMode:s,onAdd:i},u.id)),d&&h<p?e.jsx("div",{className:`flex h-14 items-center justify-center rounded-xl border border-dashed text-[11px] ${s?"border-white/10 text-white/35":"border-slate-200 text-slate-400"}`,children:"Finding the remaining source…"}):null,r?null:e.jsx("div",{className:`flex h-16 items-center justify-center rounded-xl border border-dashed px-4 text-center text-[11px] ${s?"border-white/10 text-white/35":"border-slate-200 text-slate-400"}`,children:"Sources you find will appear here."})]}),e.jsx("div",{className:`border-t px-3.5 py-2 text-[10px] ${s?"border-white/10 text-white/35":"border-slate-200 text-slate-400"}`,children:(r==null?void 0:r.status)==="partial"?"Some sources were unavailable. Drag or tap + to add any result.":r?"Drag a source onto the canvas to add it.":"Search from the composer and results land here."})]})});async function Wd(t){try{const{data:{user:r}}=await Et.auth.getUser();if(!r)return"";const s=t.type||"audio/webm",a=s.includes("mp4")?"mp4":s.includes("ogg")?"ogg":s.includes("wav")?"wav":"webm",i=`${r.id}/voice-notes/${Date.now()}.${a}`,{data:o,error:d}=await Et.storage.from("board-files").upload(i,t,{contentType:s,upsert:!1});if(d||!(o!=null&&o.path))return console.error("[audioTranscription] audio upload failed:",d),"";const{data:p}=Et.storage.from("board-files").getPublicUrl(o.path);return(p==null?void 0:p.publicUrl)||""}catch(r){return console.error("[audioTranscription] audio upload error:",r),""}}async function Hd(t){const r=await pi();let s;try{s=await fetch($t("/api/transcribe-voice"),{method:"POST",headers:{"Content-Type":t.type||"audio/webm",...r?{Authorization:`Bearer ${r}`}:{}},body:t})}catch(i){throw console.error("[audioTranscription] transcription network error:",i),new Error("VOICE_API_UNAVAILABLE")}const a=await s.json().catch(()=>({}));if(!s.ok)throw s.status===501||(a==null?void 0:a.error)==="VOICE_API_KEY_MISSING"?new Error("VOICE_API_KEY_MISSING"):s.status===429||s.status===503||(a==null?void 0:a.error)==="VOICE_API_UNAVAILABLE"?new Error("VOICE_API_UNAVAILABLE"):new Error((a==null?void 0:a.error)||`TRANSCRIBE_FAILED_${s.status}`);return String((a==null?void 0:a.text)||"").trim()}async function qd(t){const[r,s]=await Promise.all([Wd(t),Hd(t)]);return{text:s,audioUrl:r}}const Ia=32;function Gd({darkMode:t=!1,surfaceClass:r,onComplete:s,onClose:a}){const[i,o]=n.useState("recording"),[d,p]=n.useState(""),[h,y]=n.useState(0),f=n.useRef(null),u=n.useRef(null),$=n.useRef([]),N=n.useRef(null),C=n.useRef(null),F=n.useRef(null),te=n.useRef(null),E=n.useRef([]),Y=n.useRef(!1),V=n.useRef(s);n.useEffect(()=>{V.current=s},[s]);const L=n.useCallback(()=>{var Z,b;F.current!=null&&cancelAnimationFrame(F.current),F.current=null,te.current!=null&&window.clearInterval(te.current),te.current=null;try{(Z=C.current)==null||Z.disconnect()}catch{}C.current=null,N.current&&N.current.state!=="closed"&&N.current.close().catch(()=>{}
50),N.current=null,(b=f.current)==null||b.getTracks().forEach(q=>q.stop()),f.current=null},[]);n.useEffect(()=>{let Z=!1;return Y.current=!1,(async()=>{try{const q=await navigator.mediaDevices.getUserMedia({audio:!0});if(Z){q.getTracks().forEach(me=>me.stop());return}f.current=q;const Q=window.AudioContext||window.webkitAudioContext,P=new Q;if(N.current=P,P.state==="suspended")try{await P.resume()}catch{}if(Z){q.getTracks().forEach(me=>me.stop()),P.close().catch(()=>{});return}const Ne=P.createMediaStreamSource(q),m=P.createAnalyser();m.fftSize=128,m.smoothingTimeConstant=.75,Ne.connect(m),C.current=m;const ue=new Uint8Array(m.frequencyBinCount),ce=()=>{const me=C.current;if(me){me.getByteFrequencyData(ue);const D=ue.length;for(let v=0;v<Ia;v+=1){const be=ue[Math.floor(v/Ia*D)]/255,M=Math.max(.14,Math.min(1,be*1.25)),Ye=E.current[v];Ye&&(Ye.style.transform=`scaleY(${M.toFixed(3)})`)}}F.current=requestAnimationFrame(ce)};F.current=requestAnimationFrame(ce);const Oe=performance.now();te.current=window.setInterval(()=>{y(Math.floor((performance.now()-Oe)/1e3))},250);const j=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm",I=new MediaRecorder(q,{mimeType:j});u.current=I,$.current=[],I.ondataavailable=me=>{me.data.size>0&&$.current.push(me.data)},I.onstop=async()=>{if(L(),Y.current)return;const me=new Blob($.current,{type:"audio/webm"});if(!me.size){o("error"),p("No audio captured. Try again.");return}o("transcribing");try{const D=await qd(me);if(!D.text){o("error"),p("No speech detected. Try again.");return}V.current(D)}catch(D){const v=D instanceof Error?D.message:"";o("error"),p(v==="VOICE_API_KEY_MISSING"?"Voice transcription isn't set up on the server yet.":v==="VOICE_API_UNAVAILABLE"?"Transcription is temporarily unavailable.":"Couldn't transcribe that. Try again.")}},I.start()}catch(q){if(Z)return;console.error("[VoiceRecorder] could not start:",q),L(),o("error"),p("Microphone access was blocked. Enable it and try again.")}})(),()=>{Z=!0,L()}},[L]);const _=()=>{const Z=u.current;Z&&Z.state!=="inactive"?Z.stop():(L(),a())},J=()=>{Y.current=!0;const Z=u.current;if(Z&&Z.state!=="inactive")try{Z.stop()}catch{}L(),a()},O=String(Math.floor(h/60)).padStart(2,"0"),U=String(h%60).padStart(2,"0");return e.jsxs("div",{role:"dialog","aria-label":"Voice note recorder",className:`absolute bottom-[calc(100%+10px)] left-1/2 w-[300px] -translate-x-1/2 rounded-2xl border p-3.5 shadow-2xl backdrop-blur-2xl ${r}`,children:[i==="recording"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",children:[e.jsxs("span",{className:"relative flex h-2.5 w-2.5",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-red-500 opacity-60"}),e.jsx("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-red-500"})]}),"Recording"]}),e.jsxs("span",{className:`font-mono text-xs tabular-nums ${t?"text-white/55":"text-slate-500"}`,children:[O,":",U]})]}),e.jsx("div",{className:"flex h-12 items-center justify-center gap-[3px] px-1",children:Array.from({length:Ia}).map((Z,b)=>e.jsx("span",{ref:q=>{E.current[b]=q},className:"w-[3px] flex-1 rounded-full bg-gradient-to-b from-blue-400 to-blue-600",style:{height:"100%",transform:"scaleY(0.14)",transformOrigin:"center",transition:"transform 80ms linear"}},b))}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:J,className:`flex h-9 flex-1 items-center justify-center gap-1.5 rounded-xl text-sm font-medium transition ${t?"text-white/70 hover:bg-white/10 hover:text-white":"text-slate-600 hover:bg-slate-100 hover:text-slate-900"}`,children:[e.jsx(qt,{size:16}),"Cancel"]}),e.jsxs("button",{type:"button",onClick:_,className:"flex h-9 flex-[1.4] items-center justify-center gap-1.5 rounded-xl bg-blue-500 text-sm font-semibold text-white shadow-sm shadow-blue-500/30 transition hover:bg-blue-600",children:[e.jsx(cs,{size:16}),"Stop & add"]})]})]}),i==="transcribing"&&e.jsxs("div",{className:"flex items-center gap-3 py-1.5",children:[e.jsx(Ur,{size:18,className:"animate-spin text-blue-500"}),e.jsx("div",{className:"text-sm font-medium",children:"Transcribing…"})]}),i==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx(Ya,{size:18,className:"mt-0.5 shrink-0 text-red-500"}),e.jsx("div",{className:"text-sm font-medium leading-snug",children:d})]}),e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:a,className:`flex h-9 items-center justify-center rounded-xl px-4 text-sm font-medium transition ${t?"text-white/70 hover:bg-white/10 hover:text-white":"text-slate-600 hover:bg-slate-100 hover:text-slate-900"}`,children:"Close"})})]})]})}async function Yd(t,r={}){const s=await pi();let a;try{a=await fetch($t("/api/generate-image"),{method:"POST",headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{}},body:JSON.stringify({prompt:t,aspect_ratio:r.aspectRatio||"1:1",output_format:r.outputFormat||"png"})})}catch(o){console.error("[canvasImageGen] network error:",o);
50const d=new Error("NETWORK_ERROR");throw d.userMessage="Couldn't reach the image service. Check your connection.",d}const i=await a.json().catch(()=>({}));if(!a.ok||!(i!=null&&i.url)){const o=new Error((i==null?void 0:i.error)||`IMAGE_GEN_FAILED_${a.status}`);throw o.userMessage=(i==null?void 0:i.message)||"Couldn't generate that image. Please try again.",o}return i}const Kd=[{id:"1:1",label:"Square"},{id:"16:9",label:"Wide"},{id:"9:16",label:"Tall"},{id:"4:3",label:"Photo"}];function Jd({darkMode:t=!1,surfaceClass:r,onComplete:s,onClose:a}){const[i,o]=n.useState(""),[d,p]=n.useState("1:1"),[h,y]=n.useState("idle"),[f,u]=n.useState(""),$=n.useRef(null),N=n.useRef(!1);n.useEffect(()=>{var E;return(E=$.current)==null||E.focus(),()=>{N.current=!0}},[]);const C=async()=>{const E=i.trim();if(!(!E||h==="generating")){y("generating"),u("");try{const Y=await Yd(E,{aspectRatio:d});if(N.current)return;s(Y.url,E)}catch(Y){if(N.current)return;const V=(Y==null?void 0:Y.userMessage)||"Couldn't generate that image. Please try again.";y("error"),u(V)}}},F=t?"bg-white/[0.06] text-white placeholder:text-white/40 border-white/10 focus:border-white/25":"bg-slate-50 text-slate-900 placeholder:text-slate-400 border-slate-200 focus:border-slate-400",te=E=>`rounded-lg px-2.5 py-1 text-xs font-medium transition ${E?"bg-blue-500 text-white":t?"bg-white/[0.06] text-white/70 hover:bg-white/10":"bg-slate-100 text-slate-600 hover:bg-slate-200"}`;return e.jsxs("div",{role:"dialog","aria-label":"Generate image",className:`absolute bottom-[calc(100%+10px)] left-1/2 w-[320px] -translate-x-1/2 rounded-2xl border p-3.5 shadow-2xl backdrop-blur-2xl ${r}`,children:[e.jsxs("div",{className:"mb-2.5 flex items-center gap-2 text-sm font-semibold",children:[e.jsx(ea,{size:16,className:"text-blue-500"}),"Create image"]}),e.jsx("textarea",{ref:$,value:i,onChange:E=>o(E.target.value),onKeyDown:E=>{(E.metaKey||E.ctrlKey)&&E.key==="Enter"&&(E.preventDefault(),C())},rows:3,maxLength:5e3,placeholder:"Describe the image you want…",disabled:h==="generating",className:`w-full resize-none rounded-xl border px-3 py-2 text-sm outline-none transition disabled:opacity-60 ${F}`}),e.jsx("div",{className:"mt-2.5 flex flex-wrap items-center gap-1.5",children:Kd.map(E=>e.jsx("button",{type:"button",onClick:()=>p(E.id),disabled:h==="generating",className:te(d===E.id),children:E.label},E.id))}),h==="error"&&f?e.jsxs("div",{className:"mt-2.5 flex items-start gap-2 text-xs leading-snug text-red-500",children:[e.jsx(Ya,{size:14,className:"mt-0.5 shrink-0"}),e.jsx("span",{children:f})]}):null,e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsx("button",{type:"button",onClick:a,className:`flex h-9 flex-1 items-center justify-center rounded-xl text-sm font-medium transition ${t?"text-white/70 hover:bg-white/10 hover:text-white":"text-slate-600 hover:bg-slate-100 hover:text-slate-900"}`,children:"Cancel"}),e.jsx("button",{type:"button",onClick:()=>void C(),disabled:!i.trim()||h==="generating",className:"flex h-9 flex-[1.6] items-center justify-center gap-1.5 rounded-xl bg-blue-500 text-sm font-semibold text-white shadow-sm shadow-blue-500/30 transition hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:h==="generating"?e.jsxs(e.Fragment,{children:[e.jsx(Ur,{size:16,className:"animate-spin"}),"Generating…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ji,{size:16}),"Generate"]})})]})]})}const Xd=["#fde68a","#fecaca","#fed7aa","#bbf7d0","#a5f3fc","#bfdbfe","#ddd6fe","#fbcfe8"];function Zd({darkMode:t=!1,workspaceOffset:r=0,activeTool:s="pan",onSetTool:a,onAddChat:i,onAddNote:o,onAddSticky:d,onAddGroup:p,onUpload:h,onShowLinkPrompt:y,onAddVoiceNote:f,onAddImage:u}){const[$,N]=n.useState(!1),[C,F]=n.useState(!1),[te,E]=n.useState(!1),[Y,V]=n.useState(null),L=n.useRef(null),_=n.useRef(null);n.useEffect(()=>{if(!$)return;const m=ue=>{var ce;(ce=L.current)!=null&&ce.contains(ue.target)||N(!1)};return window.addEventListener("pointerdown",m),()=>window.removeEventListener("pointerdown",m)},[$]);const J=t?"border-white/10 bg-[#161719]/[0.96] text-white shadow-black/40":"border-slate-200/90 bg-white/[0.97] text-slate-900 shadow-slate-900/10",O=`flex h-10 w-10 items-center justify-center rounded-xl transition ${t?"text-white/70 hover:bg-white/10 hover:text-white":"text-slate-600 hover:bg-slate-100 hover:text-slate-900"}`,U=m=>`flex h-10 w-10 items-center justify-center rounded-xl transition ${m?"bg-blue-500 text-white shadow-sm shadow-blue-500/30 hover:bg-blue-500":t?"text-white/70 hover:bg-white/10 hover:text-white":"text-slate-600 hover:bg-slate-100 hover:text-slate-900"}`,Z=t?"bg-white/10":"bg-slate-200",b={chat:{title:"Add Chat",description:"Create a new AI chat thread on your board",gif:"/chattool.gif"}
50,notepad:{title:"Add Notepad",description:"Rich text + drawing"},sticky:{title:"Sticky Note",description:"Pick a color and drop a note"},group:{title:"Add Group",description:"Create an empty group container"},upload:{title:"Upload Files",description:"Add files from your computer"},link:{title:"Paste Link",description:"Import a website or webpage"},record:{title:"Record Voice Note",description:"Speak — we transcribe it into a note on your board"},image:{title:"Create Image",description:"Describe an image and generate it onto your board"}},q=({id:m})=>{if(Y!==m||$||C||te)return null;const ue=b[m];return ue?e.jsxs("div",{role:"tooltip",className:`pointer-events-none absolute bottom-[calc(100%+10px)] left-1/2 -translate-x-1/2 rounded-xl border p-2.5 text-center shadow-2xl backdrop-blur-2xl ${J}`,style:{width:ue.gif?232:190},children:[ue.gif?e.jsx("img",{src:ue.gif,alt:"",loading:"lazy",className:"mb-2 w-full rounded-lg border border-black/10 object-cover",style:{maxHeight:132}}):null,e.jsx("div",{className:"text-xs font-semibold",children:ue.title}),e.jsx("div",{className:`mt-0.5 text-[11px] leading-snug ${t?"text-white/55":"text-slate-500"}`,children:ue.description})]}):null},Q=[{key:"chat",title:b.chat.title,description:b.chat.description,icon:e.jsx(bi,{size:19,strokeWidth:1.8}),onClick:i},{key:"notepad",title:b.notepad.title,description:b.notepad.description,icon:e.jsx(As,{size:19,strokeWidth:1.8}),onClick:o}],P=[{key:"group",title:b.group.title,description:b.group.description,icon:e.jsx(wi,{size:19,strokeWidth:1.8}),onClick:p},{key:"upload",title:b.upload.title,description:b.upload.description,icon:e.jsx(vi,{size:19,strokeWidth:1.8}),onClick:()=>{var m;return(m=_.current)==null?void 0:m.click()}},{key:"link",title:b.link.title,description:b.link.description,icon:e.jsx(ki,{size:19,strokeWidth:1.8}),onClick:y}],Ne=m=>e.jsxs("div",{className:"relative",children:[e.jsx(q,{id:m.key}),e.jsx("button",{type:"button","aria-label":m.title,className:O,onClick:m.onClick,onMouseEnter:()=>V(m.key),onMouseLeave:()=>V(ue=>ue===m.key?null:ue),onFocus:()=>V(m.key),onBlur:()=>V(ue=>ue===m.key?null:ue),children:m.icon})]},m.key);return e.jsxs("div",{"data-canvas-tool-palette":!0,className:"fixed bottom-6 left-1/2 z-[60] -translate-x-1/2",style:{left:r?`calc(50% + ${r/2}px)`:"50%"},children:[e.jsx("input",{ref:_,type:"file",multiple:!0,className:"hidden",onChange:m=>{h(m),m.target.value=""}}),e.jsxs("div",{className:`flex items-center gap-1 rounded-2xl border p-1.5 shadow-2xl backdrop-blur-2xl ${J}`,children:[e.jsx("button",{type:"button","aria-label":"Pan","aria-pressed":s==="pan",className:U(s==="pan"),onClick:()=>
50a==null?void 0:a("pan"),children:e.jsx(mi,{size:19,strokeWidth:1.8})}),e.jsx("button",{type:"button","aria-label":"Select","aria-pressed":s==="select",className:U(s==="select"),onClick:()=>a==null?void 0:a("select"),children:e.jsx(xi,{size:19,strokeWidth:1.8})}),e.jsx("div",{className:`mx-1 h-6 w-px shrink-0 rounded-full ${Z}`}),Q.map(Ne),e.jsxs("div",{className:"relative",ref:L,children:[e.jsx(q,{id:"sticky"}),e.jsx("button",{type:"button","aria-label":"Sticky Note","aria-expanded":$,className:`${O} ${$?t?"bg-white/10 text-white":"bg-slate-100 text-slate-900":""}`,onClick:()=>N(m=>!m),onMouseEnter:()=>V("sticky"),onMouseLeave:()=>V(m=>m==="sticky"?null:m),children:e.jsx(yi,{size:19,strokeWidth:1.8})}),$?e.jsxs("div",{className:`absolute bottom-[calc(100%+10px)] left-1/2 -translate-x-1/2 rounded-2xl border p-2.5 shadow-2xl backdrop-blur-2xl ${J}`,children:[e.jsx("div",{className:`mb-2 text-center text-[11px] font-medium ${t?"text-white/55":"text-slate-500"}`,children:"Pick a color"}),e.jsx("div",{className:"flex items-center gap-2",children:Xd.map(m=>e.jsx("button",{type:"button","aria-label":`Sticky note ${m}`,className:"h-6 w-6 rounded-full border border-black/10 shadow-sm ring-1 ring-black/5 transition hover:scale-110",style:{background:m},onClick:()=>{d(m),N(!1)}},m))})]}):null]}),P.map(Ne),u||f?e.jsx("div",{className:`mx-1 h-6 w-px shrink-0 rounded-full ${Z}`}):null,u?e.jsxs("div",{className:"relative",children:[e.jsx(q,{id:"image"}),e.jsx("button",{type:"button","aria-label":"Create Image","aria-pressed":te,className:`${O} ${te?t?"bg-white/10 text-white":"bg-slate-100 text-slate-900":""}`,onClick:()=>{N(!1),F(!1),V(null),E(m=>!m)},onMouseEnter:()=>V("image"),onMouseLeave:()=>V(m=>m==="image"?null:m),children:e.jsx(ji,{size:19,strokeWidth:1.8})}),te?e.jsx(Jd,{darkMode:t,surfaceClass:J,onComplete:(m,ue)=>{u(m,ue),E(!1)},onClose:()=>E(!1)}):null]}):null,f?e.jsxs("div",{className:"relative",children:[e.jsx(q,{id:"record"}),e.jsx("button",{type:"button","aria-label":"Record Voice Note","aria-pressed":C,className:`${O} ${C?t?"bg-white/10 text-white":"bg-slate-100 text-slate-900":""}`,onClick:()=>{N(!1),E(!1),V(null),F(m=>!m)},onMouseEnter:()=>V("record"),onMouseLeave:()=>V(m=>m==="record"?null:m),children:e.jsx(rc,{size:19,strokeWidth:1.8})}),C?e.jsx(Gd,{darkMode:t,surfaceClass:J,onComplete:m=>{f(m.text,m.audioUrl),F(!1)},onClose:()=>F(!1)}):null]}):null]})]})}function Qd({open:t,onToggle:r,onNewChat:s,darkMode:a=!1,conversation:i,hasMessages:o=!1,composer:d,activity:p,sources:h,scrollSignal:y,width:f=384}){const u=n.useRef(null);n.useEffect(()=>{if(!t)return;const te=u.current;te&&(te.scrollTop=te.scrollHeight)},[t,y]);const $=a?"border-white/10 bg-[#0f1012] text-white":"border-slate-200 bg-white text-slate-900",N=a?"border-white/10":"border-slate-200",C=`flex h-8 w-8 items-center justify-center rounded-lg transition ${a?"text-white/55 hover:bg-white/10 hover:text-white":"text-slate-500 hover:bg-slate-100 hover:text-slate-900"}`,F=a?"border-white/10 bg-[#161719] text-white shadow-black/50 hover:bg-[#1d1f22]":"border-slate-200 bg-white text-slate-900 shadow-slate-900/15 hover:bg-slate-50";return e.jsxs(e.Fragment,{children:[e.jsx(Jt,{children:t?e.jsxs(_e.aside,{"data-canvas-chat-sidebar":!0,initial:{x:"100%",opacity:.6},animate:{x:0,opacity:1},exit:{x:"100%",opacity:.6},transition:{type:"spring",damping:30,stiffness:320},className:`fixed inset-y-0 right-0 z-[116] flex flex-col border-l shadow-2xl ${$}`,style:{width:`min(${f}px, 100vw)`},children:[e.jsxs("header",{className:`flex items-center gap-1 border-b px-2.5 py-2 ${N}`,children:[s?e.jsx("button",{type:"button","aria-label":"New chat",title:"New chat",className:C,onClick:s,children:e.jsx($c,{size:17})}):e.jsx("span",{className:"h-8 w-8"}),e.jsx("span",{className:"flex-1 text-center text-sm font-semibold",children:"Assistant"}),e.jsx("button",{type:"button","aria-label":"Close assistant",title:"Close",className:C,onClick:r,children:e.jsx(qt,{size:17})})]}),e.jsxs("div",{ref:u,className:"flex-1 overflow-y-auto px-3 py-3",children:[o?i:e.jsxs("div",{className:`flex h-full flex-col items-center justify-center gap-2 px-6 text-center ${a?"text-white/45":"text-slate-400"}`,children:[e.jsx(ea,{size:26,strokeWidth:1.6}),e.jsx("p",{className:"text-sm font-medium",children:"Your ChatGrid assistant"}),e.jsx("p",{className:"text-[13px] leading-snug",children:"Ask how anything works, or ask me to find resources — videos, PDFs, links — to drop on your canvas."})]}),p]}),h?e.jsx("div",{className:"px-3 pb-1",children:h}):null,e.jsx("div",{className:`border-t p-2.5 ${N}`,children:d})]},"canvas-chat-sidebar"):null}),t?null:e.jsx("button",{type:"button",onClick:r,"aria-label":"Ask ChatGrid",title:"Ask ChatGrid","data-canvas-chat-fab":!0,className:`fixed bottom-6 right-6 z-[116] flex h-14 w-14 items-center justify-center rounded-full border shadow-2xl backdrop-blur-2xl transition hover:scale-105 ${F}`,children:e.jsx(tl,{size:24,strokeWidth:1.9})})]})}function ti(t){return!t||!/^https:\/\//i.test(t)?t:$t(`/api/img?url=${encodeURIComponent(t)}`)}
50const Ai="application/chatgrid-social-post",eu={youtube:"YouTube",tiktok:"TikTok",instagram:"Instagram",twitter:"X",linkedin:"LinkedIn",facebook:"Facebook",rumble:"Rumble"};function ri(t){const r=typeof t=="number"?t:Number(t);return!Number.isFinite(r)||r<=0?null:r>=1e6?`${(r/1e6).toFixed(1).replace(/\.0$/,"")}M`:r>=1e3?`${(r/1e3).toFixed(1).replace(/\.0$/,"")}K`:String(r)}function tu(t,r){return JSON.stringify({platform:t.platform,url:r.url,author:t.author,authorHandle:t.authorHandle,avatarUrl:t.avatarUrl,caption:r.title,thumbnailUrl:r.thumbnailUrl,mediaUrl:r.url,likeCount:r.likeCount,viewCount:r.viewCount,commentCount:r.commentCount})}function ru({open:t,onClose:r,darkMode:s=!1,loading:a=!1,error:i=null,feed:o=null,onAddPost:d}){const[p,h]=n.useState("recent"),[y,f]=n.useState({}),[u,$]=n.useState({}),[N,C]=n.useState(!1),F=s?"border-white/10 bg-[#0f1012] text-white":"border-slate-200 bg-white text-slate-900",te=s?"border-white/10":"border-slate-200",E=s?"text-white/50":"text-slate-500",Y=s?"bg-white/10 animate-pulse":"bg-slate-200/70 animate-pulse",V=(o==null?void 0:o.posts)||[],L=p==="anomalies"?rl(V):sl(V),_=eu[String((o==null?void 0:o.platform)||"")]||"Social",J=ri(o==null?void 0:o.followerCount),O=(U,Z)=>e.jsx("button",{type:"button",onClick:()=>h(U),className:`flex-1 rounded-lg py-1.5 text-xs font-semibold transition ${p===U?"bg-blue-500/10 text-blue-600 dark:text-blue-400":`${E} hover:text-current`}`,children:Z});return e.jsx(Jt,{children:t?e.jsxs(_e.aside,{"data-profile-feed-panel":!0,initial:{x:"100%",opacity:.6},animate:{x:0,opacity:1},exit:{x:"100%",opacity:.6},transition:{type:"spring",damping:30,stiffness:320},className:`fixed inset-y-0 right-0 z-[117] flex w-[min(420px,100vw)] flex-col border-l shadow-2xl ${F}`,children:[e.jsxs("header",{className:`flex items-center gap-2.5 border-b px-3 py-2.5 ${te}`,children:[e.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full bg-blue-500/10 text-blue-500",children:o!=null&&o.avatarUrl&&!N?e.jsx("img",{src:ti(o.avatarUrl),alt:o.author||_,className:"h-full w-full object-cover",referrerPolicy:"no-referrer",draggable:!1,onError:()=>C(!0)}):e.jsx(Io,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-sm font-semibold",children:(o==null?void 0:o.author)||(a?"Loading…":_)}),e.jsxs("div",{className:`flex items-center gap-2 truncate text-[11px] ${E}`,children:[o!=null&&o.authorHandle?e.jsxs("span",{children:["@",o.authorHandle]}):null,J?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Wa,{className:"h-3 w-3"}),J]}):null]})]}),e.jsx("span",{className:"shrink-0 rounded-full bg-black/[0.06] px-2 py-0.5 text-[10px] font-semibold text-neutral-600 dar
50k:bg-white/10 dark:text-white/60",children:_}),e.jsx("button",{type:"button","aria-label":"Close",onClick:r,className:`flex h-8 w-8 items-center justify-center rounded-lg transition ${s?"text-white/55 hover:bg-white/10":"text-slate-500 hover:bg-slate-100"}`,children:e.jsx(qt,{size:17})})]}),e.jsxs("div",{className:`flex gap-1 border-b p-2 ${te}`,children:[O("recent","Recent"),O("anomalies","Anomalies")]}),e.jsx("p",{className:`px-3 pt-2 text-[11px] ${E}`,children:"Drag a post onto the board, or tap +."}),e.jsx("div",{className:"flex-1 overflow-y-auto px-2 py-2",children:a?e.jsx("ul",{className:"flex flex-col gap-1.5",children:Array.from({length:7}).map((U,Z)=>e.jsxs("li",{className:`flex items-center gap-2.5 rounded-xl border p-2 ${s?"border-white/10":"border-slate-200"}`,children:[e.jsx("div",{className:`h-14 w-14 shrink-0 rounded-lg ${Y}`}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("div",{className:`h-3 w-4/5 rounded ${Y}`}),e.jsx("div",{className:`h-3 w-1/3 rounded ${Y}`})]}),e.jsx("div",{className:`h-8 w-8 shrink-0 rounded-full ${Y}`})]},Z))}):i?e.jsxs("div",{className:"flex items-start gap-2 px-2 py-5 text-xs text-red-500",children:[e.jsx(Ya,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("span",{children:i})]}):L.length===0?e.jsx("div",{className:`px-2 py-6 text-center text-sm ${E}`,children:p==="anomalies"?"No standout posts yet":"No recent posts"}):e.jsx("ul",{className:"flex flex-col gap-1.5",children:L.map(U=>{const Z=ri(nl(U)),b=U.isVideo?ls:U.viewCount?ta:hc;return e.jsxs("li",{draggable:!!o,onDragStart:q=>{o&&(q.dataTransfer.setData(Ai,tu(o,U)),q.dataTransfer.effectAllowed="copy")},className:`group flex cursor-grab items-center gap-2.5 rounded-xl border p-2 transition active:cursor-grabbing ${s?"border-white/10 hover:bg-white/[0.04]":"border-slate-200 hover:bg-slate-50"}`,children:[e.jsx("button",{type:"button",onClick:()=>{U.url&&window.open(U.url,"_blank","noopener,noreferrer")},className:"relative flex h-14 w-14 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-gradient-to-br from-blue-500/[0.12] to-blue-500/[0.03]",title:"Open post",children:U.thumbnailUrl&&!u[U.id||U.url]?e.jsx("img",{src:ti(U.thumbnailUrl),alt:"",loading:"lazy",referrerPolicy:"no-referrer",className:"h-full w-full object-cover",draggable:!1,onError:()=>$(q=>({...q,[U.id||U.url]:!0}))}):U.isVideo?e.jsx(ls,{className:"h-5 w-5 text-blue-500/70"}):e.jsx(Io,{className:"h-5 w-5 text-blue-500/50"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"line-clamp-2 text-xs font-medium leading-snug",children:U.title||"Untitled"}),Z?e.jsxs("div",{className:`mt-1 flex items-center gap-1 text-[11px] ${E}`,children:[e.jsx(b,{className:"h-3 w-3"}),Z]}):null,p==="anomalies"?(()=>{const q=al(U,V);return q>=1.5?e.jsxs("div",{className:"mt-1 inline-flex items-center gap-1 rounded-full bg-amber-500/15 px-2 py-0.5 text-[10px] font-semibold text-amber-600 dark:text-amber-400",children:[e.jsx(fc,{className:"h-2.5 w-2.5"}),q.toFixed(1),"× their usual"," ",U.viewCount?"views":"likes"]}):null})():null]}),e.jsx("button",{type:"button","aria-label":"Add to board",onClick:()=>{d(U),f(q=>({...q,[U.id||U.url]:!0}))},className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition ${y[U.id||U.url]?"bg-emerald-500 text-white":"bg-blue-500 text-white hover:bg-blue-600"}`,title:"Add to board",children:e.jsx(Rs,{size:16})})]},U.id||U.url)})})})]},"profile-feed-panel"):null})}const Hn=960,qn=540,su="/assets/operator-room/pixel-office/operator-room-base.png",wt=480,nn=270,nu=[{x:62,y:45,w:106,h:68},{x:187,y:36,w:106,h:76},{x:312,y:45,w:106,h:68}];function Qn(t){const r=String(t||"").toLowerCase();return r==="error"||r==="failed"}function au(t){const r=String(t.summary||"").trim();return r||(Qn(t.status)?"Needs attention":t.status==="completed"?"Completed":"Working")}function Ti(t=[]){const r=t.length,s=t.filter(d=>d.status==="running").length,a=t.filter(d=>Qn(d.status)).length,i=t.filter(d=>d.status==="completed").length,o=a?"issue":s?"running":r?"complete":"idle";return o==="issue"?{mood:o,taskCount:r,runningCount:s,issueCount:a,completedCount:i,label:"Needs Attention",detail
50:`${a} issue${a===1?"":"s"}`,accentColor:16478597,accentHex:"#fb7185"}:o==="running"?{mood:o,taskCount:r,runningCount:s,issueCount:a,completedCount:i,label:`${s} Live`,detail:`${r} task${r===1?"":"s"}`,accentColor:6809849,accentHex:"#67e8f9"}:o==="complete"?{mood:o,taskCount:r,runningCount:s,issueCount:a,completedCount:i,label:"Tasks Complete",detail:`${i||r} done`,accentColor:7268279,accentHex:"#6ee7b7"}:{mood:o,taskCount:r,runningCount:s,issueCount:a,completedCount:i,label:"Operator Online",detail:"Standing by",accentColor:6809849,accentHex:"#67e8f9"}}function ou({compact:t=!1,highlightedTaskId:r=null,tasks:s=[],onSelectTask:a}){return t?e.jsx(lu,{compact:t,highlightedTaskId:r,tasks:s,onSelectTask:a}):e.jsx(iu,{highlightedTaskId:r,tasks:s,onSelectTask:a})}function iu({tasks:t=[]}){const r=n.useRef(null),s=n.useRef(null),[a,i]=n.useState(!0),[o,d]=n.useState(!1),p=Ti(t),h=n.useRef(p);return n.useEffect(()=>{h.current=p},[p]),n.useEffect(()=>{let y=!1;async function f(){i(!0),d(!1);try{const u=await Ua(()=>import("./phaser.esm-BwbH0K_e.js"),[]),$=u.default||u;if(y||!r.current)return;const N=()=>{y||i(!1)};class C extends $.Scene{constructor(){super("operator-pixel-office");_t(this,"monitorGlow");_t(this,"monitorLines");_t(this,"statusDot");_t(this,"statusText");_t(this,"sweep")}preload(){this.load.image("operatorRoomBase",su)}create(){this.cameras.main.setBackgroundColor("#111827"),this.add.image(Hn/2,qn/2,"operatorRoomBase").setDisplaySize(Hn,qn).setDepth(0),this.createSceneOverlays(),N()}update(){const Y=h.current,V=this.time.now;this.renderSceneOverlays(Y,V)}createSceneOverlays(){this.monitorGlow=this.add.graphics().setDepth(5),this.monitorLines=this.add.graphics().setDepth(6),this.sweep=this.add.graphics().setDepth(7),this.statusDot=this.add.graphics().setDepth(8),this.statusText=this.add.text(34,494,"",{fontFamily:"monospace",fontSize:"16px",color:"#cbd5e1"}).setResolution(1)}renderSceneOverlays(Y,V){const L=Y.mood==="issue"?Math.abs(Math.sin(V/150)):Math.abs(Math.sin(V/420)),_=Y.mood==="idle"?.12:.18+L*(Y.mood==="issue"?.18:.1);this.monitorGlow.clear(),this.monitorGlow.fillStyle(Y.accentColor,_),this.monitorGlow.fillRect(526,288,104,54),this.monitorLines.clear(),this.monitorLines.fillStyle(2371898,.72),this.monitorLines.fillRect(526,288,104,54),this.monitorLines.fillStyle(Y.accentColor,.72);const J=Math.max(3,Math.min(7,Y.taskCount+3));for(let O=0;O<J;O+=1){const U=20+(O+Y.runningCount+Y.issueCount)%4*10;this.monitorLines.fillRect(536,298+O*9,U,4)}if(this.monitorLines.fillStyle(14153966,Y.mood==="idle"?.28:.42),this.monitorLines.fillRect(580,298,14,5),this.monitorLines.fillRect(604,298,16,5),this.sweep.clear(),Y.mood!=="idle"){const O=528+V/24%98;this.sweep.fillStyle(16777215,.1+L*.08),this.sweep.fillRect(O,289,3,52)}this.statusDot.clear(),this.statusDot.fillStyle(Y.accentColor,.78+L*.2),this.statusDot.fillCircle(22,504,5),this.statusText.setText(Y.label.toUpperCase()),this.statusText.setColor(Y.accentHex)}}const F={type:$.AUTO,parent:r.current,width:Hn,height:qn,backgroundColor:"#080b12",antialias:!1,pixelArt:!0,roundPixels:!0,scene:C,scale:{mode:$.Scale.FIT,autoCenter:$.Scale.CENTER_BOTH,width:Hn,height:qn}};s.current=new $.Game(F)}catch(u){console.warn("[OperatingFloorScene] Full operator room boot failed:",u),y||(d(!0),i(!1))}}return f(),()=>{y=!0,s.current&&(s.current.destroy(!0),s.current=null),r.current&&(r.current.innerHTML="")}},[]),e.jsxs("div",{"data-operating-floor-scene":!0,"data-operator-room-fullscreen":!0,"data-operator-room-layer-mode":"phaser-scene","data-operator-room-renderer":o?"fallback":"phaser","data-operator-room-state":p.mood,"data-operator-room-task-count":p.taskCount,"data-operator-room-running-count":p.runningCount,"data-operator-room-issue-count":p.issueCount,"data-operator-room-art":"pixel-office",className:"relative h-full min-h-[520px] w-full overflow-hidden rounded-[24px] border border-black/20 bg-[#10151a] text-white shadow-[inset_0_0_0_1px_rgba(255,255,255,0.08),0_26px_90px_rgba(0,0,0,0.42)]",children:[e.jsx("div",{ref:r,className:"absolute inset-0 [&_canvas]:!h-full [&_canvas]:!w-full [&_canvas]:[image-rendering:pixelated]"}),o?e.jsx("div",{"data-operator-room-fallback":!0,className:"absolute inset-0 z-[70] flex items-center justify-center bg-[#080b
5012] font-mono text-[11px] uppercase tracking-[0.18em] text-cyan-100/75",role:"status",children:"Operator room renderer unavailable"}):null,a?e.jsx("div",{className:"absolute inset-0 z-[90] flex items-center justify-center bg-[#080b12] font-mono text-[11px] uppercase tracking-[0.18em] text-cyan-100/80",role:"status",children:"Loading operator room..."}):null,e.jsx("div",{className:"pointer-events-none absolute inset-0 rounded-[24px] border border-white/[0.08]"})]})}function lu({compact:t=!1,highlightedTaskId:r=null,tasks:s=[],onSelectTask:a}){const i=n.useRef(null),o=n.useRef(null),d=n.useRef(null),p=n.useRef(null),h=n.useRef(null),[y,f]=n.useState(0),[u,$]=n.useState(!0),[N,C]=n.useState(!1),[F,te]=n.useState(!1),[E,Y]=n.useState(!1),V=n.useMemo(()=>Ti(s),[s]),L=n.useRef(V),_=n.useMemo(()=>s.map((b,q)=>({...b,screenNumber:q+1})),[s]),J=y>0&&y<320?2:3,O=n.useMemo(()=>_.slice(-J),[_,J]),U=n.useMemo(()=>_.slice(0,-J),[_,J]),Z=U.length;return n.useEffect(()=>{const b=i.current;if(!b)return;const q=()=>f(b.getBoundingClientRect().width);if(q(),typeof ResizeObserver>"u")return window.addEventListener("resize",q),()=>window.removeEventListener("resize",q);const Q=new ResizeObserver(P=>{var m,ue;const Ne=(ue=(m=P[0])==null?void 0:m.contentRect)==null?void 0:ue.width;f(Ne||b.getBoundingClientRect().width)});return Q.observe(b),()=>Q.disconnect()},[]),n.useEffect(()=>{L.current=V},[V]),n.useEffect(()=>{Z===0&&Y(!1)},[Z]),n.useEffect(()=>{if(!E)return;const b=requestAnimationFrame(()=>{var q;(q=h.current)==null||q.focus()});return()=>cancelAnimationFrame(b)},[E]),n.useEffect(()=>{if(!E)return;const b=q=>{q.key==="Escape"&&(q.preventDefault(),Y(!1),requestAnimationFrame(()=>{var Q;(Q=p.current)==null||Q.focus()}))};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[E]),n.useEffect(()=>{if(!u||F){C(!1);return}const b=window.setTimeout(()=>{C(!0)},320);return()=>window.clearTimeout(b)},[u,F]),n.useEffect(()=>{let b=!1;async function q(){$(!0),te(!1);try{const Q=await Ua(()=>import("./phaser.esm-BwbH0K_e.js"),[]),P=Q.default||Q;if(b||!o.current)return;const Ne=()=>{b||$(!1)};class m extends P.Scene{constructor(){super("assistant-idle");_t(this,"assistant");_t(this,"deskGlow");_t(this,"isBlinking",!1);_t(this,"lastMood","");_t(this,"pulse");_t(this,"statusConsole");_t(this,"statusDetailText");_t(this,"statusRails");_t(this,"statusText");_t(this,"statusWash");_t(this,"screenSweep")}create(){this.cameras.main.setBackgroundColor("#0a0d16"),this.createOfficeShell(),this.createRuntimeOverlays(),this.createAssistantTextures(),this.assistant=this.add.sprite(wt/2,160,this.getAssistantTexture(!1,L.current.mood)).setOrigin(.5).setScale(t?2.18:2.45),this.tweens.add({targets:this.assistant,y:this.assistant.y-2,duration:1550,yoyo:!0,repeat:-1,ease:"Sine.easeInOut"}),this.tweens.add({targets:this.assistant,scaleX:this.assistant.scaleX*1.01,duration:1800,yoyo:!0,repeat:-1,ease:"Sine.easeInOut"}),this.time.addEvent({delay:2600,loop:!0,callback:()=>{var j;this.isBlinking=!0,(j=this.assistant)==null||j.setTexture(this.getAssistantTexture(!0)),this.time.delayedCall(120,()=>{var I;this.isBlinking=!1,(I=this.assistant)==null||I.setTexture(this.getAssistantTexture(!1))})}}),Ne()}update(){const j=L.current;if(this.renderRuntimeState(j,this.time.now),this.pulse&&(this.pulse.alpha=j.mood==="issue"?.24+Math.abs(Math.sin(this.time.now/150))*.15:.24+Math.sin(this.time.now/360)*.07),this.deskGlow&&(this.deskGlow.alpha=j.mood==="running"?.2+Math.sin(this.time.now/340)*.08:.16+Math.sin(this.time.now/520)*.05),this.screenSweep){const I=j.mood==="issue"?18:j.mood==="running"?26:42;this.screenSweep.x=46+this.time.now/I%388}}createOfficeShell(){const j=this.add.graphics();j.fillStyle(658710,1),j.fillRect(0,0,wt,nn),j.fillStyle(1120295,1),j.fillRoundedRect(12,10,wt-24,nn-20,16),j.lineStyle(1,3359061,.86),j.strokeRoundedRect(12,10,wt-24,nn-20,16),j.fillStyle(1317675,1),j.fillRect(20,20,wt-40,128),j.lineStyle(1,2700361,.78);for(let I=24;I<wt-20;I+=38)j.lineBetween(I,20,I,148);for(let I=36;I<148;I+=24)j.lineBetween(20,I,wt-20,I);j.fillStyle(791072,1),j.fillRoundedRect(32,27,416,104,11),j.lineStyle(2,3718648,.32),j.strokeRoundedRect(32,27,416,104,11),j.lineStyle(1,1357990,.16);for(let I=47;I<436;I+=21)j.lineBetween(I,36,I,122);for(let I=43;I<124;I+=13)j.lineBetween(41,I,440,I);nu.forEach((I,me)=>{const D=me===1;j.fillStyle(132631,1),j.fillRoundedRect(I.x-6,I.y-8,I.w+12,I.h+16,8),j.fillStyle(463397,1),j.fillRoundedRect(I.x,I.y,I.w,I.h,5),j.lineStyle(1,6809849,D?.54:.34),j.strokeRoundedRect(I.x,I.y,I.w,I.h,5),j.fillStyle(988970,1),j.fillRect(I.x+I.w/2-8,I.y+I.h+8,16,9),j.fillStyle(1976635,1),j.fillRoundedRect(I.x+I.w/2-27,I.y+I.h+17,54,5,2);for(let v=0;v<4;v+=1)j.fillStyle(v===1?16436245:6809849,.38+v*.08),j.fillRect(I.x+14,I.y+16+v*11,34+(v+me)%3*14,3);j.fillStyle(7268279,.42),j.fillRect(I.x+I.w-32,I.y+15,12,12),j.fillRect(I.x+I.w-48,I.y+42,26,3)}),j.fillStyle(988970,1),j.fillRect(20,148,wt-40,98),j.fillStyle(1976635,1),j.fillRect(20,154,wt-40,92),j.lineStyle(1,3359061,.78);for(let I=-20;I<wt+40;I+=31)j.lineBetween(I,246,I+67,154);for(let I=166;I<246;I+=16)j.lineBetween(20,I,wt-20,I);j.fillStyle(988196,1),j.fillRoundedRect(74,171,332,62,8),j.fillStyle(2962248,1),j.fillRoundedRect(59,158,362,30,9),j.fillStyle(4674921,1),j.fillRect(80,161,321,4),j.fillStyle(1120295,1),j.fillRoundedRect(104,185,96,14,4),j.fillRoundedRect(218,185,58,14,4),j.fillRoundedRect(293,185,84,14,4),j.fillStyle(3718648,.58);for(let I=112;I<191;I+=10)j.fillRect(I,190,5,3);j.fillStyle(16436245,.56);for(let I=226;I<266;I+=10)j.fillRect(I,190,5,3);j.fillStyle(7268279,.48);for(let I=302;I<368;I+=11)j.fillRect(I,190,6,3);j.fillStyle(1054759,1),j.fillRect(105,233,20,27),j.fillRect(355,233,20,27),j.fillStyle(1120295,1),j.fillRoundedRect(184,156,112,82,22),j.lineStyle(2,132631,.62),j.strokeRoundedRect(184,156,112,82,22),j.fillStyle(3359061,1),j.fillRoundedRect(195,164,90,58,18),j.fillStyle(463135,1),j.fillRoundedRect(174,126,132,56,8),j.fillStyle(857897,1),j.fillRoundedRect(181,132,118,43,5),j.lineStyle(1,6809849,.45),j.strokeRoundedRect(181,132,118,43,5),j.fillStyle(6809849,.82),j.fillRect(194,144,42,4),j.fillStyle(16436245,.78),j.fillRect(194,155,70,4),j.fillStyle(7268279,.75),j.fillRect(194,166,54,4),this.add.text(31,18,"OPERATOR CONTROL",{fontFamily:"monospace",fontSize:"9px",color:"#e5f7ff"}).setResolution(1),this.add.text(wt-91,18,"ONLINE",{fontFamily:"monospace",fontSize:"9px",color:"#86efac"}).setResolution(1)}createRuntimeOverlays(){this.statusWash=this.add.graphics(),this.pulse=this.add.graphics(),this.deskGlow=this.add.graphics(),this.statusRails=this.add.graphics(),this.statusConsole=this.add.graphics(),this.screenSweep=this.add.graphics(),this.screenSweep.fillStyle(16777215,.12),this.screenSweep.fillRect(0,34,3,91),this.statusText=this.add.text(wt/2,18,"",{fontFamily:"monospace",fontSize:"8px",color:"#67e8f9"}).setOrigin(.5,0).setResolution(1),this.statusDetailText=this.add.text(wt/2,29,"",{fontFamily:"monospace",fontSize:"7px",color:"#cbd5e1"}).setOrigin(.5,0).setResolution(1)}renderRuntimeState(j,I){var Ye,ye,Re,qe,Rt;const me=j.accentColor,D=j.mood==="issue"?Math.abs(Math.sin(I/140)):0,v=j.mood==="running"?Math.abs(Math.sin(I/260)):0;this.statusWash.clear(),this.statusWash.fillStyle(me,j.mood==="idle"?.045:.075+D*.05),this.statusWash.fillEllipse(wt/2,116,360,126),this.pulse.clear(),this.pulse.fillStyle(me,j.mood==="issue"?.18+D*.1:.15+v*.08),this.pulse.fillEllipse(wt/2,160,178,88),this.deskGlow.clear(),this.deskGlow.fillStyle(me,.14+v*.
5008+D*.08),this.deskGlow.fillRoundedRect(88,158,304,12,5),this.statusRails.clear(),this.statusRails.fillStyle(me,.34+v*.22+D*.28),this.statusRails.fillRoundedRect(42,135,396,3,1),this.statusRails.fillRoundedRect(42,31,396,2,1),j.mood==="issue"&&(this.statusRails.fillStyle(16478597,.46+D*.28),this.statusRails.fillRoundedRect(33,44,4,80,2),this.statusRails.fillRoundedRect(443,44,4,80,2)),this.statusConsole.clear();const be=j.mood==="idle"?.42:.58+v*.24+D*.24;this.statusConsole.fillStyle(me,be);const M=Math.max(3,Math.min(8,j.taskCount+3));for(let at=0;at<M;at+=1){const Ee=3+(at+j.runningCount+j.issueCount)%4*4;this.statusConsole.fillRect(166+at*7,151-Ee,4,Ee),this.statusConsole.fillRect(292+at*7,150,5,3)}(Ye=this.statusText)==null||Ye.setText(j.label.toUpperCase()),(ye=this.statusText)==null||ye.setColor(j.accentHex),(Re=this.statusDetailText)==null||Re.setText(j.detail.toUpperCase()),(qe=this.statusDetailText)==null||qe.setColor(j.mood==="issue"?"#fecdd3":"#cbd5e1"),(Rt=this.screenSweep)==null||Rt.setAlpha(j.mood==="idle"?.06:.12+v*.08+D*.12),!this.isBlinking&&this.assistant&&this.lastMood!==j.mood&&(this.assistant.setTexture(this.getAssistantTexture(!1,j.mood)),this.lastMood=j.mood)}getAssistantTexture(j,I=L.current.mood){return`assistant-${I}-${j?"blink":"open"}`}createAssistantTextures(){["idle","running","issue","complete"].forEach(j=>{this.createAssistantTexture(this.getAssistantTexture(!1,j),j,!1),this.createAssistantTexture(this.getAssistantTexture(!0,j),j,!0)})}createAssistantTexture(j,I,me){const D=this.make.graphics({x:0,y:0,add:!1}),v=I==="issue"?16478597:I==="complete"?2278750:3718648;if(D.fillStyle(0,0),D.fillRect(0,0,64,64),D.fillStyle(1976635,1),D.fillRect(14,43,36,12),D.fillStyle(v,1),D.fillRect(12,48,40,6),D.fillStyle(1920728,1),D.fillRect(17,53,30,5),D.fillStyle(988970,1),D.fillRect(15,11,34,14),D.fillStyle(2825240,1),D.fillRect(16,14,32,10),D.fillRect(13,22,6,16),D.fillRect(45,21,5,13),D.fillRect(38,11,8,5),D.fillStyle(15910556,1),D.fillRect(18,20,29,25),D.fillRect(23,44,18,5),D.fillStyle(2825240,1),D.fillRect(17,17,31,6),D.fillRect(14,22,5,13),D.fillRect(44,20,5,12),D.fillRect(36,15,10,4),D.fillStyle(1120295,1),me)D.fillRect(23,31,7,2),D.fillRect(36,31,7,2);else{const be=I==="running"?1:0;D.fillRect(24+be,29,4,4),D.fillRect(37+be,29,4,4),D.fillStyle(15204342,1),D.fillRect(25+be,29,1,1),D.fillRect(38+be,29,1,1),I==="issue"&&(D.fillStyle(8330525,1),D.fillRect(22,27,8,1),D.fillRect(36,27,8,1))}D.fillStyle(8142634,1),I==="complete"?(D.fillRect(27,38,12,2),D.fillRect(29,40,8,1)):I==="issue"?D.fillRect(26,40,12,2):D.fillRect(28,39,10,2),D.fillStyle(16317180,1),D.fillRect(24,48,17,3),D.fillStyle(1120295,1),D.fillRect(30,48,5,5),D.generateTexture(j,64,64),D.destroy()}}const ue={type:P.AUTO,parent:o.current,width:wt,height:nn,backgroundColor:"#0b0f17",pixelArt:!0,roundPixels:!0,scene:m,scale:{mode:P.Scale.FIT,autoCenter:P.Scale.CENTER_BOTH,width:wt,height:nn}};d.current=new P.Game(ue)}catch(Q){console.warn("[OperatingFloorScene] Phaser boot failed:",Q),b||(te(!0),$(!1))}}return q(),()=>{b=!0,d.current&&(d.current.destroy(!0),d.current=null),o.current&&(o.current.innerHTML="")}},[t]),e.jsxs("div",{ref:i,"data-operating-floor-scene":!0,"data-operator-room-mini":!0,"data-operator-room-state":V.mood,"data-operator-room-task-count":V.taskCount,"data-operator-room-running-count":V.runningCount,"data-operator-room-issue-count":V.issueCount,className:"relative h-full min-h-[220px] w-full overflow-hidden rounded-[18px] bg-[#10131d] text-white",children:[e.jsx("div",{ref:o,className:"absolute inset-0 [&_canvas]:!h-full [&_canvas]:!w-full [&_canvas]:[image-rendering:pixelated]"}),F?e.jsxs("div",{className:"absolute inset-0 bg-[#0a0d16]",children:[e.jsx("div",{className:"absolute inset-[4%] rounded-[16px] border border-cyan-200/[0.14] bg-[#111827]"}),e.jsx("div",{className:"absolute left-[7%] right-[7%] top-[10%] h-[40%] rounded-[12px] border border-cyan-200/[0.22] bg-[#0c1220] shadow-[inset_0_0_40px_rgba(34,211,238,0.08)]"}),e.jsx("div",{className:"absolute left-[13%] top-[16.5%] h-[25%] w-[22%] rounded-[7px] border border-cyan-200/[0.28] bg-[#071225]"}),e.jsx("div",{className:"absolute left-[39%] top-[14%] h-[28%] w-[22%] rounded-[7px] border border-cyan-200/[0.38] bg-[#071225]"}),e.jsx("div",{className:"absolute right-[13%] top-[16.5%] h-[25%] w-[22%] rounded-[7px] border border-cyan-200/[0.28] bg-[#071225]"}
50),e.jsx("div",{className:"absolute bottom-[14%] left-[13%] right-[13%] h-[27%] rounded-t-[10px] bg-[#2d3348] shadow-[0_-8px_24px_rgba(34,211,238,0.08)]"}),e.jsx("div",{className:"absolute bottom-[21%] left-1/2 h-[31%] w-[24%] -translate-x-1/2 rounded-t-[20px] border border-black/[0.45] bg-[#334155]"}),e.jsxs("div",{className:"absolute bottom-[33%] left-1/2 h-[24%] w-[18%] -translate-x-1/2 rounded-t-[3px] bg-[#f2c69c]",children:[e.jsx("span",{className:"absolute left-[25%] top-[34%] h-[9%] w-[9%] bg-[#111827]"}),e.jsx("span",{className:"absolute right-[25%] top-[34%] h-[9%] w-[9%] bg-[#111827]"}),e.jsx("span",{className:"absolute bottom-[24%] left-[39%] h-[5%] w-[22%] bg-[#7c3f2a]"})]}),e.jsx("div",{className:"absolute left-4 top-4 font-mono text-[9px] uppercase tracking-[0.14em] text-cyan-50/70",children:"Operator Control"}),e.jsxs("div",{className:"absolute bottom-3 left-3 rounded-full border border-white/10 bg-black/[0.24] px-2.5 py-1 font-mono text-[9px] uppercase tracking-[0.14em] text-white/[0.58]",children:["Tasks ",s.length]})]}):null,O.length>0?e.jsxs("div",{className:`absolute top-[16.5%] grid gap-[3.6%] ${J===2?"left-[16%] right-[16%] grid-cols-2":"left-[12.9%] right-[12.9%] grid-cols-3"}`,children:[O.map((b,q)=>{const Q=b.status==="running",P=Qn(b.status),Ne=String(b.id)===String(r||""),m=P?"Issue":Q?"Live":"Done",ue=au(b);return e.jsxs("button",{"data-operator-task-id":b.id,"data-operator-task-screen-number":b.screenNumber,"data-operator-task-activity":ue,"data-operator-task-highlighted":Ne?"true":void 0,type:"button","aria-current":Ne?"true":void 0,"aria-label":`Open task screen ${b.screenNumber}: ${b.title}`,onClick:()=>a==null?void 0:a(b.id),className:`group relative isolate aspect-[1.56/1] overflow-visible rounded-[7px] border bg-[#071225] px-1.5 py-1.5 text-left shadow-[inset_0_0_20px_rgba(34,211,238,0.09),0_10px_24px_rgba(0,0,0,0.28)] outline-none transition hover:-translate-y-0.5 hover:border-cyan-200/70 focus-visible:border-cyan-200 ${Ne?"border-cyan-100/[0.82] ring-1 ring-cyan-100/[0.58]":P?"border-rose-300/[0.45]":"border-cyan-200/[0.32]"}`,children:[e.jsx("span",{className:`pointer-events-none absolute -inset-[7px] -z-10 rounded-[10px] ${Ne?"bg-cyan-200/[0.12] shadow-[0_0_22px_rgba(103,232,249,0.32),0_12px_22px_rgba(0,0,0,0.28)]":"bg-black/[0.64] shadow-[0_12px_22px_rgba(0,0,0,0.28)]"}`}),e.jsx("span",{className:"pointer-events-none absolute bottom-[-11px] left-1/2 h-[10px] w-[16px] -translate-x-1/2 bg-[#0f172a]"}),e.jsx("span",{className:"pointer-events-none absolute bottom-[-16px] left-1/2 h-[5px] w-[54px] -translate-x-1/2 rounded-[3px] bg-[#1e293b]"}),e.jsxs("span",{className:"pointer-events-none absolute inset-0 overflow-hidden rounded-[7px]",children:[e.jsx("span",{className:"absolute inset-x-0 top-0 h-px bg-cyan-100/[0.28]"}),e.jsx("span",{className:"absolute inset-0 opacity-[0.08] [background-image:linear-gradient(to_bottom,transparent_0,transparent_5px,rgba(255,255,255,0.8)_6px)] [background-size:100%_7px]"}),e.jsx("span",{className:"absolute -left-6 top-0 h-full w-7 rotate-12 bg-white/[0.07] transition-transform duration-500 group-hover:translate-x-28"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${P?"bg-rose-400":Q?"animate-pulse bg-cyan-300":"bg-emerald-300"}`}),e.jsxs("span",{className:"shrink-0 font-mono text-[8px] uppercase tracking-[0.12em] text-cyan-100/[0.82]",children:["T",b.screenNumber]}),e.jsx("span",{className:`ml-auto font-mono text-[6.5px] uppercase tracking-[0.1em] ${P?"text-rose-200/[0.82]":Q?"text-cyan-100/[0.82]":"text-emerald-100/[0.78]"}`,children:m})]}),Ne?e.jsx("div",{className:"pointer-events-none absolute -top-2 left-1/2 -translate-x-1/2 rounded-full border border-cyan-100/[0.42] bg-black/[0.72] px-1.5 py-px font-mono text-[6px] uppercase tracking-[0.12em] text-cyan-50/[0.88]",children:"Last"}):null,e.jsx("div",{className:"mt-1.5 line-clamp-2 min-h-[20px] text-[9.5px] font-semibold leading-[1.12] text-white/[0.92]",children:b.title}),e.jsx("div",{className:"sr-only",children:ue}),e.jsx("div",{className:"mt-1 grid gap-0.5","aria-hidden":"true",children:[0,1,2].map(ce=>e.jsx("span",{className:`block h-[2px] rounded-full ${P?"bg-rose-200/[0.48]":Q?"bg-cyan-100/[0.46]":"bg-emerald-100/[0.42]"}`,style:{width:`${ce===0?70:ce===1?46:58}%`}},ce))}),e.jsx("div",{className:"mt-1 h-1.5 overflow-hidden rounded-[3px] bg-black/[0.28]",children:e.jsx("div",{className:`h-full rounded-[3px] ${P?"w-[82%] bg-rose-300/[0.48]":Q?"w-[64%] animate-pulse bg-cyan-200/[0.52]":"w-full bg-emerald-200/[0.48]"}`})}),e.jsx("div",{className:`absolute -bottom-[4px] left-3 right-3 h-1 rounded-full ${P?"bg-rose-300/[0.38]":Q?"bg-cyan-200/[0.42]":"bg-emerald-200/40"}`})]},b.id)}),Z>0?e.jsxs("button",{ref:p,type:"button","data-operator-overflow-toggle":!0,"aria-label":`Show ${Z} more task screen${Z===1?"":"s"}`,"aria-controls":"operator-task-overflow-panel","aria-expanded":E,onClick:b=>{b.stopPropagation(),Y(q=>!q)},className:"absolute -right-5 -top-5 rounded-full border border-cyan-100/[0.28] bg-black/[0.62] px-2 py-0.5 font-mono text-[8px] uppercase tracking-[0.12em] text-cyan-50/[0.78] outline-none transition hover:border-cyan-100/60 hover:bg-black/[0.76] focu
50s-visible:border-cyan-100",children:["+",Z," more"]}):null,E?e.jsx("div",{id:"operator-task-overflow-panel","data-operator-overflow-panel":!0,role:"group","aria-label":"Hidden task screens",className:"absolute right-[-18px] top-[calc(100%+18px)] z-30 flex max-h-[124px] w-[78%] flex-col gap-1 overflow-y-auto rounded-[10px] border border-cyan-100/[0.24] bg-[#071225]/95 p-1.5 shadow-[0_18px_32px_rgba(0,0,0,0.36)] backdrop-blur-sm",children:U.map((b,q)=>{const Q=String(b.status||"running"),P=Q==="running",Ne=Qn(Q),m=String(b.id)===String(r||""),ue=Ne?"Issue":P?"Live":"Done";return e.jsxs("button",{ref:q===0?h:void 0,type:"button","data-operator-overflow-task-id":b.id,"data-operator-overflow-screen-number":b.screenNumber,"data-operator-overflow-highlighted":m?"true":void 0,"aria-current":m?"true":void 0,"aria-label":`Open task screen ${b.screenNumber}: ${b.title}`,onClick:()=>{Y(!1),a==null||a(b.id)},className:`group flex min-h-9 items-center gap-2 rounded-[7px] px-2 py-1 text-left outline-none transition hover:bg-cyan-100/10 focus-visible:bg-cyan-100/12 ${m?"bg-cyan-100/[0.1] ring-1 ring-cyan-100/[0.28]":""}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${Ne?"bg-rose-400":P?"animate-pulse bg-cyan-300":"bg-emerald-300"}`}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsxs("span",{className:"shrink-0 font-mono text-[7px] uppercase tracking-[0.12em] text-cyan-100/[0.52]",children:["Task ",b.screenNumber]}),e.jsx("span",{className:"block min-w-0 truncate text-[9px] font-semibold text-white/[0.92]",children:b.title})]}),e.jsx("span",{className:"block truncate text-[7px] text-white/[0.42]",children:b.summary})]}),e.jsx("span",{className:`shrink-0 font-mono text-[7px] uppercase tracking-[0.1em] ${Ne?"text-rose-200/[0.82]":P?"text-cyan-100/[0.82]":"text-emerald-100/[0.78]"}`,children:ue})]},b.id)})}):null]}):null,e.jsxs("div",{className:"absolute bottom-3 left-3 rounded-full border border-white/10 bg-black/[0.26] px-2.5 py-1 font-mono text-[9px] uppercase tracking-[0.14em] text-white/[0.62]",children:["Tasks ",s.length]}),e.jsx("div",{className:"absolute bottom-3 right-3 rounded-full border px-2.5 py-1 font-mono text-[9px] uppercase tracking-[0.14em]",style:{backgroundColor:`${V.accentHex}18`,borderColor:`${V.accentHex}30`,color:V.accentHex},children:V.label}),N?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-[#10131d] font-mono text-[10px] uppercase tracking-[0.18em] text-cyan-100/80",role:"status",children:"Loading assistant..."}):null,e.jsx("div",{className:"pointer-events-none absolute inset-0 rounded-[18px] border border-white/10 shadow-[inset_0_0_0_1px_rgba(255,255,255,0.04)]"}),e.jsx("div",{className:"pointer-events-none absolute inset-0 bg-[linear-gradient(to_bottom,rgba(255,255,255,0.055),transparent_18%,transparent_78%,rgba(0,0,0,0.4))]"})]})}const cu="h-[72vh] max-h-[860px]";function nr(t={}){return typeof(t==null?void 0:t.message)=="string"?t.message:typeof(t==null?void 0:t.text)=="string"?t.text:typeof(t==null?void 0:t.summary)=="string"?t.summary:""}function du(t){return Math.max(0,(Number(t)||0)-1)}function uu({index:t,maxPlaybackIndex:r}){const s=Number(r)||0,a=Number(t);return!Number.isFinite(a)||a<0?-1:Math.min(s,a)}function pu(){return-1}function hu(){return""}function Oa(t={}){const r=t!=null&&t.detail&&typeof t.detail=="object"?t.detail:{},s=r!=null&&r.payload&&typeof r.payload=="object"?r.payload:{},a=(t==null?void 0:t.imageUrl)||(t==null?void 0:t.previewImage)||(r==null?void 0:r.imageUrl)||(s==null?void 0:s.imageUrl)||"";if(typeof a=="string"&&a.trim())return a.trim();const i=(s==null?void 0:s.base64)||(r==null?void 0:r.base64)||(t==null?void 0:t.base64)||"";return typeof i!="string"||!i.trim()?"":i.startsWith("data:")?i:`data:image/jpeg;base64,${i}`}function hr(t="",r=180){const s=String(t||"").replace(/\s+/g," ").trim();return s.length<=r?s:`${s.slice(0,Math.max(0,r-1)).trim()}...`}function fu(t={}){const r=t==null?void 0:t.detail;if(!r)return"";if(typeof r=="string")return r;if(typeof r!="object")return"";const s=[r.path,r.file,r.filename,r.name,r.url,r.liveUrl,r.command,r.summary,r.title,r.message].filter(
50Boolean);if(s.length)return s.join(`
51`);try{return JSON.stringify(r).slice(0,1200)}catch{return""}}function Pi(t={}){return[nr(t),fu(t),t==null?void 0:t.kind,t==null?void 0:t.type].filter(Boolean).join(`
52`)}function gu(t={},r=""){var d;const s=t!=null&&t.detail&&typeof t.detail=="object"?t.detail:{},i=[t==null?void 0:t.path,t==null?void 0:t.filePath,t==null?void 0:t.file,t==null?void 0:t.filename,s==null?void 0:s.path,s==null?void 0:s.file,s==null?void 0:s.filename,s==null?void 0:s.name].find(p=>typeof p=="string"&&p.trim());if(i)return i.trim();const o=String(r||"").match(/(?:creating|editing|modified|writing|reading|file|open|save)\s+(?:file\s+)?([~/.A-Za-z0-9_@-][A-Za-z0-9_./@+\-\s]*\.(?:tsx|ts|jsx|js|css|html|md|json|geojson|csv|txt|png|jpe?g|webp|svg|mp4|wav|pdf))/i);return((d=o==null?void 0:o[1])==null?void 0:d.trim())||""}function mu(t=""){const r=String(t||"").trim();return r?r.split(/[\\/]/).filter(Boolean).pop()||r:""}function Ii(t=""){return String(t||"").replace(/\r/g,"").split(`
53`).map(r=>r.replace(/^\s*(?:›|>|-|\*)\s*/,"").replace(/\s+/g," ").trim()).filter(Boolean).filter(r=>!/^thinking.*tokens/i.test(r)).filter(r=>!/^save checkpoint/i.test(r)).filter(r=>!/^[\w .-]{2,40}\s+is\s+using\b/i.test(r)).filter(r=>!/^chatgpt is thinking/i.test(r))}const Ts={product:{label:"Product Preview",title:"Previewing the app",empty:"A runnable page or browser surface is available."},asset:{label:"Generated Asset",title:"Generating an asset",empty:"A visual asset was created or updated."},research:{label:"Research",title:"Researching sources",empty:"Search results or source material are being gathered."},data:{label:"Data",title:"Loading data",empty:"A dataset or structured source was inspected."},build:{label:"Build",title:"Running the build",empty:"Dependencies or project tooling are being prepared."}
53,code:{label:"Code",title:"Editing source",empty:"A source file was created or changed."},checklist:{label:"Checklist",title:"Checking progress",empty:"A task list or validation note was updated."},plan:{label:"Plan",title:"Planning the approach",empty:"The agent is shaping the implementation plan."},terminal:{label:"Terminal",title:"Running command",empty:"A command ran in the workspace."},status:{label:"Status",title:"Preparing workspace",empty:"Waiting for the first previewable object."},visual:{label:"Visual Checkpoint",title:"Captured screen",empty:"A visual checkpoint was captured."}};function Ba(t={}){const r=Pi(t),s=r.toLowerCase(),a=gu(t,r),i=mu(a),o=String((t==null?void 0:t.kind)||(t==null?void 0:t.type)||"").toLowerCase();return Oa(t)?{category:"visual",path:a,filename:i,isLowValue:!1}:/thinking.*tokens|navigator:\s*attempt|building browser plan/i.test(s)?{category:"status",path:a,filename:i,isLowValue:!0}:/\.(?:png|jpe?g|webp|svg|gif|mp4|wav|mp3)$/i.test(a)||/media viewer|generating image|generated image|creating image|static-assets|asset/i.test(s)?{category:"asset",path:a,filename:i,isLowValue:!1}:/preview mode|live preview|browser preview|public link|published|localhost|127\.0\.0\.1|https?:\/\/[^\s]+/i.test(s)&&!/searching|curl|raw\.githubusercontent/i.test(s)?{category:"product",path:a,filename:i,isLowValue:!1}:/scholar|search results|searching|web search|hugging\s*face|datasets at|source material|literature|current #?1 story/i.test(s)?{category:"research",path:a,filename:i,isLowValue:!1}:/geojson|featurecollection|features:\s*\d+|sample props|dataset|csv|jsonl|database schema|seed/i.test(s)||/\.(?:geojson|csv|json|jsonl)$/i.test(a)?{category:"data",path:a,filename:i,isLowValue:!1}:/pnpm|npm|yarn|bun|package|dependencies|install|build|vite|warning|deprecated|unmet peer|downloaded|resolved/i.test(s)?{category:"build",path:a,filename:i,isLowValue:!1}:/todo|checklist|test observations|working features|\[[ x]\]/i.test(s)||/(?:todo|test|observations)\.md$/i.test(a)?{category:"checklist",path:a,filename:i,isLowValue:!1}:/\.(?:tsx|ts|jsx|js|css|html|md)$/i.test(a)||/editing file|creating file|modified|write file|diff|source/i.test(s)?{category:"code",path:a,filename:i,isLowValue:!1}:/brainstorm|design direction|architecture|requirements|planner:|planning|prepare data scripts|core principles/i.test(s)?{category:"plan",path:a,filename:i,isLowValue:!1}:/terminal|executing command|ubuntu@sandbox|\$\s|curl|python3|bash|sh -c/i.test(s)||o.includes("terminal")?{category:"terminal",path:a,filename:i,isLowValue:!1}:{category:"status",path:a,filename:i,isLowValue:!1}}function xu({item:t={},classification:r,text:s}){const{category:a,path:i,filename:o}=r,d=Ii(s).filter(h=>!/^\{|\}$/.test(h)).filter(h=>!/^\s*["'][A-Za-z0-9_ -]+["']\s*:/.test(h)),p=d[0]||"";return a==="status"?[hr(p||Ts.status.empty,110)]:a==="code"?[i||o||"Source file updated",p&&!p.includes(i)?hr(p,120):"The source changed at this point in the timeline."].filter(Boolean):a==="asset"?[i||o||"Generated media",p&&!p.includes(i)?hr(p,120):"A media asset was produced for the project."].filter(Boolean):a==="checklist"?d.filter(h=>/\[[ x]\]|working features|todo|test|feature/i.test(h)).slice(0,4).map(h=>hr(h,120)):a==="build"||a==="terminal"||a==="data"?d.slice(0,4).map(h=>hr(h,128)):a==="research"?d.filter(h=>!/^read more$/i.test(h)).slice(0,4).map(h=>hr(h,128)):d.slice(0,3).map(h=>hr(h,128))}function bu(t,r=""){const s=Ts[t.category]||Ts.status,a=t.path||"",i=t.filename||"",o=r.toLowerCase();if(t.category==="code"&&i)return/creating file|created file/i.test(o)?`Creating ${i}`:/editing file|modified|diff/i.test(o)?`Editing ${i}`:`Updated ${i}`;if(t.category==="asset"&&i)return`Created ${i}`;if(t.category==="data"&&i)return`Inspecting ${i}`;if(t.category==="checklist"&&i)return i;if(t.category==="build"&&/install|pnpm add|npm install|yarn add/i.test(o))return"Installing dependencies";if(t.category==="research"&&/scholar/i.test(o))return"Searching scholarly sources";if(t.category==="product"&&/preview|localhost|127\.0\.0\.1/i.test(o))return"Previewing the product";const d=Ii(r)[0]||"";return t.category!=="status"&&d?hr(d,80):a||s.title}function yu({item:t={},index:r=0,total:s=0,finalPreviewUrl:a="",finalPreviewSrcDoc:i=""}={}){const o=Pi(t),d=Ba(t),p=Ts[d.category]||Ts.status,h=xu({item:t,classification:d,text:o}),y=h[0]||hr(nr(t),140)||p.empty;return{useFinalSurface:d.category==="product"&&!!(a||i),previewUrl:"",imageUrl:"",title:bu(d,o),label:`${r+1}/${Math.max(s,1)}`,summary:y,detailLines:h,eventType:(t==null?void 0:t.kind)||(t==null?void 0:t.type)||d.category,category:d.category,categoryLabel:p.label,isSemantic:!0,isLowValue:d.isLowValue}}function si(t,r,s,a){const i=nr(t)||"Visual checkpoint";return{useFinalSurface:!1,previewUrl:"",imageUrl:a,title:hr(i,90),label:`${r+1}/${Math.max(s,1)}`,summary:hr(i,160),eventType:(t==null?void 0:t.kind)||(t==null?void 0:t.type)||"browser_frame",category:"visual",categoryLabel:Ts.visual.label,isSemantic:!1}}function wu({feed:t=[],activeIndex:r=-1,isLive:s=!0,finalPreviewUrl:a="",finalPreviewSrcDoc:i=""}={}){if(s)return{useFinalSurface:!0,previewUrl:a||"",imageUrl:"",title:"Live",label:"live",summary:"",eventType:"",category:"product",categoryLabel:"Live"};const o=Math.min(Math.max(Number(r)||0,0),t.length-1),d=t[o]||{},p=Oa(d);if(p)return si(d,o,t.length,p);let h=d,y=o,f=Ba(d);if(f.isLowValue)for(let $=o-1;$>=0;$-=1){const N=t[$]||{},C=Ba(N);if(!C.isLowValue){h=N,y=$,f=C;break}}const u=Oa(h);return u?{...si(h,y,t.length,u),label:`${o+1}
53/${t.length}`}:{...yu({item:h,index:o,total:t.length,finalPreviewUrl:a,finalPreviewSrcDoc:i}),isLowValue:f.isLowValue}}function vu(){return null}function ku(){return!1}function ju(){return[]}function Su(t){return Array.isArray(t)?t.length:0}function Nu(){return null}function Cu(){return"Close"}function _u(){return"Close"}function $u(){return!1}function Ru(){return null}function Au({task:t,darkMode:r,onClose:s,onMinimize:a,onToggleProgress:i,isWorkspacePanelOpen:o=!1,onToggleWorkspace:d,durableData:p={},size:h="default",onHeaderPointerDown:y,hideWindowControls:f=!1}){var Wr,Ps,Nt,Bt;const u=t||{},$=u.artifactFocus&&typeof u.artifactFocus=="object"?u.artifactFocus:null,N=h==="split",C=h==="large"||N,F=C?N?"h-full w-full":"w-full max-w-[1700px]":"w-[min(473px,calc(100vw-40px))]",te=C?N?"h-full":cu:"h-[286px]",E=Array.isArray(u.feed)?u.feed:[],Y=Array.isArray(u.planSteps)?u.planSteps:[],V=Array.isArray(u.searchResults)?u.searchResults:[],L=String(u.screenMode||"activity"),_=Number(u.currentStepIndex||0),J=Number(u.totalSteps||0),O=n.useMemo(()=>E.filter(w=>nr(w)),[E]),U=C&&O.length>1,Z=C&&O.length>0,b=du(O.length),q=String(u.runId||u.id||"").trim(),[Q,P]=n.useState(-1),[Ne,m]=n.useState("result"),ue=n.useCallback(w=>{P(ge=>{const Ve=typeof w=="function"?w(ge):w;return uu({index:Ve,maxPlaybackIndex:b})})},[b,q]),ce=!U||Q<0||Q>=b,Oe=ce?b:Q,j=ce?b:Oe,I=b>0?Math.max(0,Math.min(100,j/b*100)):100,me=ce?O:O.slice(0,Oe+1),D=me.slice(-5),v="",be=n.useMemo(()=>{const w=p!=null&&p.workspacePreview&&typeof p.workspacePreview=="object"&&typeof p.workspacePreview.srcDoc=="string"?p.workspacePreview.srcDoc:"";return w||hu((p==null?void 0:p.files)||u.workspaceFiles||[],{title:u.screenLabel||"ChatGrid artifact preview"})},[p==null?void 0:p.files,p==null?void 0:p.workspacePreview,u.screenLabel,u.workspaceFiles]),M=n.useMemo(()=>wu({feed:O,activeIndex:Oe,isLive:ce,finalPreviewUrl:v,finalPreviewSrcDoc:be}),[Oe,v,be,ce,O]),Ye=M.useFinalSurface?v:M.previewUrl,ye=M.useFinalSurface?be:"",Re=M.useFinalSurface?"":M.imageUrl,qe=u.previewImage?ce?u.previewImage:Re||u.previewImage:"",Rt=String(u.finalAnswer||"").trim(),at=U&&!ce,Ee=M.categoryLabel||"Workspace State",Xt=(Array.isArray(M.detailLines)?M.detailLines:[]).slice(1,4),Be=u.streamingFile&&u.streamingFile.path?u.streamingFile:null,Gt=n.useMemo(()=>{const w=za(O);if(!Be)return w;const ge=w.findIndex(Ve=>Ve.path===Be.path);if(ge>=0){const Ve=w.slice();return Ve[ge]={path:Be.path,content:Be.content},Ve}return[...w,{path:Be.path,content:Be.content}]},[O,Be]),ft=n.useMemo(()=>ce?Gt:za(O.slice(0,Oe+1)),[ce,Gt,O,Oe]),vt=Gt.length>0,ar=n.useMemo(()=>E.some(w=>/sandbox ready/i.test(nr(w)||"")),[E]),ot=n.useMemo(()=>vt?ce?String(u.previewHtml||"")||Eo(Gt):Eo(ft)||String(u.previewHtml||""):"",[vt,ce,u.previewHtml,Gt,ft]),Qe=C&&(vt||u.isProcessing&&ar)&&!u.previewImage,Ue=ce&&u.previewUrl?u.previewUrl:"",dt=n.useRef(!1);n.useEffect(()=>{dt.current||m(u.isProcessing?"code":"result")},[u.isProcessing]);const gt=$?`${$.id||""}:${$.kind||""}:${$.path||""}:${$.at||""}`:"";n.useEffect(()=>{if(!gt)return;const w=O.findIndex(Ve=>String((Ve==null?void 0:Ve.id)||"")===String(($==null?void 0:$.id)||""));w>=0&&ue(w>=b?-1:w);const ge=String(($==null?void 0:$.kind)||"");ge==="file"?(dt.current=!0,m("code")):(ge==="preview"||ge==="browser")&&(dt.current=!0,m("result"))},[$,gt,b,O,ue]);const et=vu(),br={},Ot=nr(et),kt=String(br.url||br.liveUrl||"").trim(),Zt=!!et,mt=Zt?"terminal":L;E.some(ku);const Ke=!!((Ye||ye||Re||at)&&!Zt),Qt=Y.slice(0,5),T=(V.length?V:me.map(w=>nr(w))).slice(-5),z=String(u.statusLine||"").trim()||"Working...",oe=String(u.summaryLine||"").trim()||z,pe=String(u.status||((Wr=u.run)==null?void 0:Wr.status)||"").toLowerCase(),Ie=pe==="error"||pe==="failed",Le=!ce&&me.length>0&&nr(me[me.length-1])||oe,de=J>0?`${Math.min(Math.max(_,0),J)}/${J}`:u.isProcessing?"running":Ie?"issue":"done",xe=D.slice(-4),we=!!u.progressExpanded,le=ju(),re=!!(u.isProcessing&&Su(Y)===0&&D.length<=1),Ae=!!(u.previewUrl||u.previewImage||u.previewHtml||Qe),ve=r?"border-white/[0.08] bg-white/[0.035] text-neutral-300 hover:bg-white/[0.08] hover:text-neutral-100":"border-slate-200 bg-white/88 text-slate-500 hover:bg-slate-50 hover:text-slate-900",xt=r?"border-white/[0.08] bg-white/[0.035] text-neutral-300 hover:bg-rose-500/14 hover:text-rose-100":"border-slate-200 bg-white/88 text-slate-500 hover:bg-rose-50 hover:text-rose-700",fe=r?"border-white/[0.07] bg-[#101011]/92 shadow-[inset_0_1px_0_rgba(255,255,255,0.035)]":"border-slate-200 bg-white/92 shadow-[0_6px_16px_rgba(15,23,42,0.06),inset_0_1px_0_rgba(255,255,255,0.7)]",ze=r?"text-neutral-400 hover:bg-white/[0.06] hover:text-neutral-100":"text-slate-500 hover:bg-slate-100 hover:text-slate-900",Lt=r?"bg-white/[0.06] text-neutral-100 hover:bg-white/[0.09]":"bg-slate-100 text-slate-700 hover:bg-slate-200",us=r?"bg-[#0b0b0c] text-[#e6e6e6]":"bg-slate-50 text-slate-800",jt=r?"border-white/[0.08]":"border-slate-200",fr=Y.length?Y.slice(0,8):D.slice(-6).map((w,ge)=>({id:w.id||`feed-progress-${ge}`,narration:nr(w),status:ge===D.length-1&&u.isProcessing?"executing":"pending"})),yr=n.useMemo(()=>Nu({session:{...u,isProcessing:!!(u.isProcessing&&ce),statusLine:ce?u.statusLine:Le,summaryLine:ce?u.summaryLine:Le,primaryOutcome:ce?u.primaryOutcome:null,primaryDeliverable:ce?u.primaryDeliverable:null,run:ce?u.run:null,previewUrl:ce?u.previewUrl:"",publicUrl:ce?u.publicUrl:"",liveUrl:ce?u.liveUrl:"",browserUseLiveUrl:ce?u.browserUseLiveUrl:"",workspaceFiles:ce?u.workspaceFiles:[],workspacePreview:ce?u.workspacePreview:null,artifacts:ce?u.artifacts:[]}}),[p,ce,u,Ye,ye,me]),St=Cu({label:u.screenLabel||"worker",runId:u.runId||u.id,isProcessing:u.isProcessing,status:u.status||((Ps=u.run)==null?void 0:Ps.status)}),wr=_u({runId:u.runId||u.id,isProcessing:u.isProcessing,status:u.status||((Nt=u.run)==null?void 0:Nt.status)}),vr=(u.runId||u.id,u.isProcessing,u.status||((Bt=u.run)==null||Bt.status),void 0),Ar=n.useCallback(w=>
53{s&&$u({target:w.target,currentTarget:w.currentTarget})},[s]);n.useEffect(()=>{P(pu({isProcessing:!!u.isProcessing}))},[b,u.isProcessing,q]);const kr=n.useCallback(w=>{const ge=Number(w);Number.isFinite(ge)&&ue(ge>=b?-1:ge)},[b,ue]),or=n.useCallback(w=>{ue(ge=>{const Ve=ge<0?b:ge,se=Math.max(0,Math.min(b,Ve+w));return se>=b?-1:se})},[b,ue]),jr=n.useCallback(()=>{ue(-1)},[ue]),Vr=n.useCallback(w=>{if(w.key==="Home"){w.preventDefault(),w.stopPropagation(),kr(0);return}if(w.key==="End"){w.preventDefault(),w.stopPropagation(),jr();return}if(w.key==="ArrowLeft"||w.key==="ArrowDown"){w.preventDefault(),w.stopPropagation(),or(-1);return}(w.key==="ArrowRight"||w.key==="ArrowUp")&&(w.preventDefault(),w.stopPropagation(),or(1))},[kr,jr,or]);return e.jsx("div",{className:F,onContextMenu:Ar,"data-testid":"tldraw-expanded-worker-console","data-context-menu-action":s?vr:void 0,children:e.jsxs("div",{className:"relative h-full w-full",children:[N?null:e.jsx("div",{className:`pointer-events-none absolute inset-0 translate-x-[4px] translate-y-[4px] rounded-[20px] border ${r?"border-white/[0.025] bg-black/20 shadow-[0_8px_18px_rgba(0,0,0,0.42)]":"border-white/55 bg-[#dfe8f3]/16 shadow-[0_5px_10px_rgba(30,41,59,0.08)]"}`}),e.jsxs("div",{className:`relative h-full w-full overflow-hidden border ${N?r?"rounded-[22px] border-white/[0.08] bg-[#171719]/90 p-[3px] text-neutral-100 shadow-[0_22px_54px_rgba(0,0,0,0.36),0_8px_18px_rgba(0,0,0,0.26),inset_0_1px_0_rgba(255,255,255,0.045)]":"rounded-[22px] border-white/80 bg-white/88 p-[3px] text-slate-900 shadow-[0_18px_42px_rgba(15,23,42,0.14),0_6px_14px_rgba(15,23,42,0.08),inset_0_1px_0_rgba(255,255,255,0.72)]":r?"rounded-[20px] border-white/[0.04] bg-[#141416]/[0.9] p-2 text-neutral-100 shadow-[0_4px_10px_rgba(15,23,42,0.08),0_18px_52px_-28px_rgba(0,0,0,0.94),inset_0_1px_0_rgba(255,255,255,0.04)] backdrop-blur-xl":"rounded-[20px] border-white/88 bg-white/90 p-2 text-slate-900 shadow-[0_4px_10px_rgba(15,23,42,0.08)] backdrop-blur-xl"}`,children:[e.jsx("div",{className:`pointer-events-none absolute inset-[1px] ${N?r?"rounded-[21px] shadow-[inset_0_0_0_1px_rgba(255,255,255,0.018)]":"rounded-[21px] shadow-[inset_0_1px_0_rgba(255,255,255,0.68)]":r?"rounded-[19px] shadow-[inset_0_0_0_1px_rgba(255,255,255,0.012)]":"rounded-[19px] shadow-[inset_0_1px_0_rgba(255,255,255,0.72)]"}`}),e.jsx("div",{className:`pointer-events-none absolute inset-0 ${N?r?"bg-[linear-gradient(to_bottom,rgba(255,255,255,0.055),transparent_26%)]":"bg-[linear-gradient(to_bottom,rgba(255,255,255,0.42),transparent_28%)]":r?"bg-[radial-gradient(circle_at_14%_0%,rgba(255,255,255,0.045),transparent_42%),radial-gradient(circle_at_84%_100%,rgba(255,255,255,0.025),transparent_38%)]":"bg-[radial-gradient(circle_at_16%_0%,rgba(255,255,255,0.34),transparent_40%),radial-gradient(circle_at_88%_100%,rgba(148,163,184,0.09),transparent_36%)]"}`}),e.jsx("div",{className:`pointer-events-none absolute -left-[16%] top-0 h-full w-[32%] rotate-[8deg] ${N?"hidden":r?"bg-gradient-to-r from-transparent via-transparent to-transparent":"bg-gradient-to-r from-transparent via-white/18 to-transparent"}`}),e.jsx("div",{className:`pointer-events-none absolute -right-[14%] top-0 h-full w-[28%] rotate-[-10deg] ${N?"hidden":r?"bg-gradient-to-r from-transparent via-white/[0.035] to-transparent":"bg-gradient-to-r from-transparent via-sky-100/12 to-transparent"}`}),e.jsxs("div",{className:`flex min-h-0 ${te} flex-col overflow-hidden`,children:[e.jsxs("div",{className:`relative min-h-0 flex flex-1 flex-col overflow-hidden border ${N?r?"rounded-[18px] border-white/[0.075] bg-[#090a0b] shadow-[inset_0_1px_0_rgba(255,255,255,0.035)]":"rounded-[18px] border-slate-200/85 bg-white shadow-[inset_0_1px_0_rgba(255,255,255,0.72)]":r?"rounded-[14px] border-white/[0.06] bg-transparent":"rounded-[14px] border-white/80 bg-transparent"}`,children:[e.jsxs("div",{onPointerDown:y,style:{cursor:y?"grab":void 0},className:`flex items-center justify-between border-b ${N?"px-3 py-2":"px-3 py-1.5"} ${N?r?"border-white/[0.07]":"border-slate-200/85":r?"border-white/[0.07]":"border-slate-200/80"}`,children:[e.jsx("div",{title:u.screenLabel||"Live Console",className:`min-w-0 flex-1 truncate font-medium uppercase ${N?"text-[9px] tracking-[0.18em]":"text-[10px] tracking-[0.16em]"} ${N?r?"text-neutral-300":"text-slate-500":r?"text-neutral-100":"text-slate-500"}`,children:u.screenLabel||"Live Console"}),C?e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[null,d?e.jsxs("button",{type:"button",onClick:w=>{w.stopPropagation(),d==null||d()},className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-[10px] font-semibold transition-colors ${r?"border-white/[0.08] bg-[#171717] text-neutral-200 hover:bg-[#1f1f1f]":"border-slate-300 bg-white/85 text-slate-600 hover:bg-white"}`,title:o?"Hide workspace panel":"Show workspace panel",children:[e.jsx("span",{className:"hidden sm:inline",children:o?"Hide":"Workspace"}),o?e.jsx(Kn,{size:12}):e.jsx(Yn,{size:12})]}):null,f?null:e.jsx("button",{type:"button",className:`inline-flex items-center justify-center border ${N?"h-5 w-5 rounded-[8px]":"h-6 w-6 rounded-full"} ${N?ve:r?"border-white/[0.08] bg-[#171717] text-neutral-200 hover:bg-[#1f1f1f]":"border-slate-300 bg-white/85 text-slate-600 hover:bg-white"}`,title:"Minimize task viewport",onClick:w=>{w.stopPropagation(),a==null||a()},children:e.jsx(gc,{size:N?11:12})}),!f&&s?e.jsx("button",{type:"button","data-testid":"tldraw-expanded-worker-close",className:`inline-flex items-center justify-center border ${N?"h-5 w-5 rounded-[8px]":"h-6 w-6 rounded-full"} ${N?xt:r?"border-white/[0.08] bg-[#171717] text-neutral-200 hover:bg-rose-500/14 hover:text-rose-100":"border-slate-300 bg-white/85 text-slate-600 hover:bg-rose-50 hover:text-rose-700"}`,title:wr,"aria-label":St,onClick:w=>{w.stopPropagation(),s==null||s()},children:e.jsx(qt,{size:N?11:12})}):null]}):e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${u.isProcessing?r?"animate-pulse bg-cyan-300":"animate-pulse bg-cyan-600":Ie?r?"bg-rose-300":"bg-rose-600":r?"bg-emerald-300":"bg-emerald-600"}`})]}),C?e.jsx(Ru,{surface:yr,darkMode:r,compact:!0}):null,u.previewImage||u.previewUrl&&!vt?e.jsxs("div",{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border ${jt}`,children:[e.jsxs("div",{className:`flex shrink-0 items-center gap-2 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] ${r?"bg-[#171717] text-neutral-300":"bg-slate-100 text-slate-600"}`,children:[e.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-red-500"}),u.previewImage?"Live — Your Chrome Tab":"Live Browser"]}),u.previewImage?e.jsx("div",{className:"min-h-0 flex-1 w-full overflow-auto bg-[#0c0c0d] flex items-start justify-center",children:e.jsx("img",{alt:"Your live Chrome tab",src:qe||u.previewImage,className:"w-full h-auto object-contain",draggable:!1})}):e.jsx("iframe",{title:"Agent live browser",src:u.previewUrl,className:"min-h-0 flex-1 w-full border-0 bg-white",sandbox:"allow-scripts allow-same-origin allow-forms"})]}):null,Qe?e.jsxs("div",{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border ${jt}`,children:[e.jsxs("div",{className:`flex shrink-0 items-center justify-between gap-2 px-2 py-1 ${r?"bg-[#171717]":"bg-slate-100"}`,children:[e.jsx("div",{className:"flex items-center gap-1",children:[{key:"result",label:"Result",Icon:ta},{key:"code",label:"Code",Icon:Jl}].map(({key:w,label:ge,Icon:Ve})=>{const se=Ne===w;return e.jsxs("button",{type:"button",onClick:Sr=>{Sr.stopPropagation(),dt.current=!0,m(w)},className:`inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] font-semibold transition-colors ${se?r?"bg-[#0c0c0d] text-neutral-100":"bg-white text-slate-900 shadow-sm":r?"text-neutral-400 hover:text-neutral-200":"text-slate-500 hover:text-slate-700"}`,children:[e.jsx(Ve,{size:12}),ge,w==="code"?e.jsx("span",{className:`ml-0.5 rounded-full px-1.5 text-[9px] ${r?"bg-white/[0.08] text-neutral-400":"bg-slate-200 text-slate-600"}`,children:ft.length}):null]},w)})}),e.jsx("div",{className:`shrink-0 pr-1 text-[10px] font-medium uppercase tracking-[0.12em] ${r?"text-neutral-500":"text-slate-400"}`,children:ce?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${r?"bg-emerald-300":"bg-emerald-600"}`}),u.isProcessing?"Building":"Result"]}):`Step ${Oe+1}/${O.length}`})]}),Ne==="code"?e.jsx(Xl,{files:ft,darkMode:r,statusText:u.statusLine,focu
53sPath:String(($==null?void 0:$.kind)||"")==="file"?String(($==null?void 0:$.path)||""):""}):Ue?e.jsx("iframe",{title:"Agent live preview",src:Ue,className:"min-h-0 flex-1 w-full border-0 bg-white",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-pointer-lock",allow:"autoplay; fullscreen; pointer-lock; microphone; camera"}):ot?e.jsx("iframe",{title:"Agent output preview",srcDoc:ot,className:"min-h-0 flex-1 w-full border-0 bg-white",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-pointer-lock",allow:"autoplay; fullscreen; pointer-lock"}):e.jsx("div",{className:`flex min-h-0 flex-1 items-center justify-center px-4 text-center text-[12px] ${r?"bg-[#0c0c0d] text-neutral-500":"bg-white text-slate-500"}`,children:"No previewable page yet — check the Code tab to see what's been written."})]}):null,u.previewHtml&&!Qe&&!u.previewUrl&&!u.previewImage?e.jsxs("div",{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border ${jt}`,children:[e.jsxs("div",{className:`flex shrink-0 items-center gap-2 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] ${r?"bg-[#171717] text-neutral-300":"bg-slate-100 text-slate-600"}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${r?"bg-emerald-300":"bg-emerald-600"}`}),"Result"]}),e.jsx("iframe",{title:"Agent output preview",srcDoc:u.previewHtml,className:"min-h-0 flex-1 w-full border-0 bg-white",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups"})]}):null,e.jsxs("div",{className:`min-h-0 overflow-y-auto font-mono ${us} ${N?"rounded-[15px] px-3 py-2.5 text-[13px] leading-6":"rounded-lg px-4 py-3 text-[15px] leading-7"} ${Ae?"hidden":"flex-1"}`,children:[re?e.jsx("div",{className:"flex h-full min-h-[120px] items-center justify-center",children:e.jsxs("div",{className:`flex items-center gap-2 rounded-full border px-3 py-1.5 ${r?"border-white/[0.08] bg-[#171717] text-neutral-200":"border-slate-200/85 bg-white/88 text-slate-700"}`,children:[e.jsx("span",{className:`h-3.5 w-3.5 animate-spin rounded-full border-2 ${r?"border-slate-500 border-t-cyan-300":"border-slate-300 border-t-cyan-600"}`}),e.jsx("span",{className:"text-[11px]",children:"Booting agent..."})]})}):null,null,Ke||mt==="browser"?e.jsx("div",{className:`h-full ${re?"hidden":""}`,children:Re?e.jsxs("div",{className:"flex h-full min-h-[320px] flex-col",children:[e.jsxs("div",{className:`mb-2 flex items-center justify-between gap-3 rounded-lg border px-3 py-2 font-sans ${r?"border-white/[0.08] bg-[#171717]/90 text-neutral-300":"border-slate-200 bg-white/82 text-slate-700"}`,children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:`truncate text-[10px] font-semibold uppercase tracking-[0.14em] ${r?"text-cyan-200":"text-cyan-700"}`,children:Ee}),e.jsx("div",{className:"truncate text-[12px] font-semibold",children:M.title})]}),e.jsx("div",{className:`shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold ${r?"bg-white/[0.06] text-neutral-300":"bg-slate-100 text-slate-600"}`,children:M.label})]}),e.jsx("img",{src:Re,alt:M.title,className:"min-h-0 flex-1 rounded-lg border border-slate-200/70 bg-white object-contain"})]}):Ye||ye?e.jsx("iframe",{src:ye?void 0:Ye,srcDoc:ye||void 0,title:M.useFinalSurface?u.screenLabel||"Browser worker live view":M.title,className:"h-full min-h-[320px] w-full rounded-lg border-0 bg-black",allow:"clipboard-read; clipboard-write; fullscreen"}):at?e.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center",children:e.jsxs("div",{className:`w-full max-w-xl rounded-[18px] border px-5 py-5 font-sans shadow-[0_18px_46px_rgba(0,0,0,0.22)] ${r?"border-white/[0.075] bg-[#141416]/94 text-neutral-200":"border-slate-200 bg-white/90 text-slate-800"}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${r?"text-cyan-200":"text-cyan-700"}`,children:Ee}),e.jsx("div",{className:"mt-2 text-lg font-semibold leading-6",children:M.title})]}),e.jsx("div",{className:`shrink-0 rounded-full px-2.5 py-1 text-[11px] font-semibold ${r?"bg-white/[0.06] text-neutral-300":"bg-slate-100 text-slate-600"}`,children:M.label})]}),M.summary?e.jsx("p",{className:`mt-4 text-sm leading-6 ${r?"text-neutral-300":"text-slate-600"}`,children:M.summary}):null,Xt.length?e.jsx("div",{className:"mt-4 space-y-2",children:Xt.map((w,ge)=>e.jsx("div",{className:`rounded-lg border px-3 py-2 text-xs leading-5 ${r?"border-white/[0.06] bg-black/24 text-neutral-400":"border-slate-200 bg-slate-50/90 text-slate-600"}`,children:w},`timeline-detail-${ge}`))}):null]})}):e.jsxs("div",{className:"flex h-full min-h-[320px] flex-col",children:[e.jsx("div",{className:`mb-3 rounded-lg border px-3 py-2 font-sans text-[12px] leading-5 ${r?"border-cyan-300/10 bg-cyan-300/[0.035] text-neutral-300":"border-cyan-200/80 bg-cyan-50/70 text-slate-700"}`,children:"Browser live view was not provided for this run, so ChatGrid is showing the durable worker output instead."}),e.jsxs("div",{className:"space-y-1",children:[(me.length?me:D).map((w,ge)=>e.jsxs("div",{className:"flex items-start gap-2 whitespace-pre-wrap break-words",children:[e.jsx("span",{className:`select-none ${r?"text-[#34d399]":"text-emerald-600"}`,children:"›"}),e.jsx("span",{children:nr(w)})]},w.id||`floating-browser-fallback-${ge}`)),!me.length&&!D.length?e.jsx("div",{className:r?"text-neutral-500":"text-slate-500",children:"Waiting for browser worker output..."}):null]})]})}):null,mt==="search"?e.jsx("div",{className:`space-y-1.5 ${re?"hidden":""}`,children:T.length?T.map((w,ge)=>{const Ve=String(w||"");let se=Ve;try{se=new URL(Ve).hostname.replace(/^www\./,"")}catch{}return e.jsxs("div",{className:`rounded-lg px-2 py-1.5 ${r?"bg-[#181818]":"bg-white/58"}`,children:[e.jsx("div",{className:`truncate text-[11px] font-semibold ${r?"text-neutral-100":"text-slate-900"}`,children:se}),Ve!==se?e.jsx("div",{className:`truncate text-[10.5px] ${r?"text-neutral-500":"text-slate-500"}`,children:Ve}):null,ge<T.length-1?e.jsx("div",{className:`mt-1 h-px w-full ${r?"bg-white/[0.07]":"bg-slate-200/80"}`}):null]},`floating-search-${ge}`)}):e.jsx("div",{className:r?"text-neutral-500":"text-slate-500",children:"Searching the web..."})}):null,mt==="editor"?e.jsxs("div",{className:`space-y-1 ${re?"hidden":""}`,children:[e.jsx("div",{className:r?"text-slate-300/75":"text-slate-500",children:"# todo.md"}),Qt.length?Qt.map((w,ge)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:["done","skipped"].includes(w.status)?r?"text-emerald-400":"text-emerald-600":r?"text-slate-400":"text-slate-500",children:["done","skipped"].includes(w.status)?"[x]":"[ ]"}),e.jsxs("span",{className:`truncate ${w.status==="executing"?r?"text-cyan-300":"text-cyan-700":""}`,children:[ge+1,". ",w.narration]})]},w.id||`floating-plan-${ge}`)):e.jsx("pre",{className:`whitespace-pre-wrap ${r?"text-slate-100":"text-slate-700"}`,children:oe}),le.length?e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx("div",{className:r?"text-slate-300/75":"text-slate-500",children:"## browserbase.session"}),le.map(w=>e.jsxs("div",{className:"flex items-center gap-2 truncate",children:[e.jsx("span",{className:r?"text-cyan-300":"text-cyan-700",children:"-"}),e.jsx("span",{className:"truncate",children:w.message}),w.sessionUrl?e.jsx("a",{href:w.sessionUrl,target:"_blank",rel:"noreferrer",onClick:ge=>ge.stopPropagation(),className:r?"shrink-0 text-cyan-300 underline underline-offset-2":"shrink-0 text-cyan-700 underline underline-offset-2",children:w.sessionId?w.sessionId.slice(0,8):"open"}):null]},w.id))]}):null]}):null,mt==="terminal"?e.jsx("div",{className:`space-y-1 ${re?"hidden":""}`,children:Zt?e.jsxs("div",{className:`flex min-h-[220px] flex-col justify-center rounded-xl border px-4 py-5 font-sans ${r?"border-emerald-300/14 bg-emerald-300/[0.045]":"border-emerald-200 bg-emerald-50/70"}`,children:[e.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.14em] ${r?"text-emerald-100/80":"text-emerald-800"}`,children:"Result"}),e.jsx("div",{className:`mt-3 text-sm font-semibold leading-6 ${r?"text-neutral-100":"text-slate-900"}`,children:Ot||Le}),kt?e.jsx("a",{href:kt,target:"_blank",rel:"noreferrer",onClick:w=>w.stopPropagation(),className:`mt-3 truncate text-xs font-semibold underline underline-offset-2 ${r?"text-cyan-200":"text-cyan-700"}`,children:kt}):null]}):e.jsxs(e.Fragment,{children:[D.length?D.map((w,ge)=>e.jsxs("div",{className:"flex items-start gap-2 whitespace-pre-wrap break-words",children:[e.jsx("span",{className:`select-none ${r?"text-[#34d399]":"text-emerald-600"}`,children:"›"}),e.jsx("span",{children:nr(w)})]},w.id||`floating-terminal-${ge}`)):e.jsxs("div",{className:`rounded-xl border px-4 py-4 font-sans ${r?"border-white/[0.08] bg-white/[0.035] text-neutral-200":"border-slate-200 bg-white/82 text-slate-800"}`,children:[e.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.14em] ${r?"text-cyan-200/80":"text-cyan-700"}`,children:"Task screen"}),e.jsx("div",{className:"mt-2 text-sm font-semibold leading-6",children:Rt||Le})]}),u.isProcessing?e.jsxs("div",{className:`flex items-center gap-2 ${r?"text-[#34d399]":"text-emerald-600"}`,children:[e.jsx("span",{children:"›"}),e.jsx("span",{className:"animate-pulse",children:"_"})]}):null]})}):null,mt==="activity"?e.jsx("div",{className:`space-y-1.5 ${re?"hidden":""}`,children:xe.length?xe.map((w,ge)=>e.jsxs("div",{className:"truncate",children:[">"," ",nr(w)]},w.id||`floating-activity-${ge}`)):e.jsx("div",{className:r?"text-slate-300/75":"text-slate-500",children:"Preparing agent..."})}):null]}),e.jsx("div",{className:`pointer-events-none absolute inset-x-2 bottom-2 z-30 transition-all duration-220 ${we?"translate-y-0 opacity-100":"translate-y-8 opacity-0"}`,children:e.jsxs("div",{className:`pointer-events-auto rounded-xl border px-3 py-2 ${r?"border-white/[0.08] bg-[#171717]/96":"border-slate-200 bg-white"}`,children:[e.jsx("div",{className:`mb-1.5 text-[10px] font-semibold uppercase tracking-[0.12em] ${r?"text-neutral-400":"text-slate-500"}`,children:"Task Progress"}),e.jsx("div",{className:"space-y-1",children:fr.map((w,ge)=>{const Ve=String((w==null?void 0:w.status)||"pending"),se=["done","skipped"].includes(Ve),Sr=Ve==="executing";return e.jsxs("div",{className:"flex items-start gap-2 text-[11px] leading-4",children:[e.jsx("span",{className:`mt-0.5 inline-block h-2 w-2 rounded-full ${se?"bg-emerald-500":Sr?"animate-pulse bg-cyan-500":r?"bg-slate-500":"bg-slate-400"}`}),e.jsx("span",{className:`truncate ${se?r?"text-slate-300/85":"text-slate-600":r?"text-neutral-100":"text-slate-800"}
53`,children:(w==null?void 0:w.narration)||"Untitled task"})]},(w==null?void 0:w.id)||`floating-drawer-${ge}`)})})]})})]}),Z?e.jsxs("div",{className:`${N?"mt-1.5 flex h-7 w-full shrink-0 items-center gap-1.5 rounded-[12px] border px-2":"mt-1.5 flex shrink-0 items-center gap-2 rounded-[12px] border px-3 py-1.5"} ${N?fe:r?"border-white/[0.08] bg-[#171717]/95":"border-slate-200 bg-white"}`,children:[e.jsx("button",{type:"button",onClick:w=>{w.stopPropagation(),or(-1)},onPointerDown:w=>w.stopPropagation(),className:`inline-flex ${N?"h-5 w-5 rounded-[7px]":"h-6 w-6 rounded-md"} items-center justify-center transition-colors ${N?ze:r?"text-neutral-400 hover:bg-[#1f1f1f] hover:text-neutral-100":"text-slate-600 hover:bg-slate-100"}`,"aria-label":"Previous timeline step",title:"Previous step",disabled:b<=0,children:e.jsx(uc,{size:N?11:13})}),e.jsx("button",{type:"button",onClick:w=>{w.stopPropagation(),or(1)},onPointerDown:w=>w.stopPropagation(),className:`inline-flex ${N?"h-5 w-5 rounded-[7px]":"h-6 w-6 rounded-md"} items-center justify-center transition-colors ${N?ze:r?"text-neutral-400 hover:bg-[#1f1f1f] hover:text-neutral-100":"text-slate-600 hover:bg-slate-100"}`,"aria-label":"Next timeline step",title:"Next step",disabled:b<=0,children:e.jsx(pc,{size:N?11:13})}),e.jsxs("div",{className:`relative min-w-0 flex-1 ${N?"h-5":"h-6"}`,children:[e.jsx("div",{className:`absolute left-0 right-0 top-1/2 -translate-y-1/2 rounded-full ${N?"h-[3px]":"h-1"} ${r?"bg-white/[0.11]":"bg-slate-200"}`,children:e.jsx("div",{className:`h-full rounded-full ${r?"bg-cyan-300/90":"bg-cyan-500"}`,style:{width:`${I}%`}})}),e.jsx("div",{className:`pointer-events-none absolute top-1/2 -translate-y-1/2 rounded-full ${N?"h-2 w-2":"h-2.5 w-2.5"} ${r?"bg-cyan-300 shadow-[0_0_12px_rgba(103,232,249,0.4)]":"bg-cyan-500 shadow-[0_0_10px_rgba(6,182,212,0.28)]"}`,style:{left:`calc(${I}% - ${N?"4px":"5px"})`}}),e.jsx("input",{type:"range",min:0,max:b,value:j,disabled:b<=0,onInput:w=>{w.stopPropagation(),kr(w.target.value)},onChange:w=>{w.stopPropagation(),kr(w.target.value)},onKeyDown:Vr,onPointerDown:w=>w.stopPropagation(),onPointerMove:w=>w.stopPropagation(),"aria-label":"Scrub timeline","data-testid":"tldraw-timeline-scrubber",title:"Scrub timeline",className:"absolute inset-0 h-full w-full cursor-pointer opacity-0"})]}),e.jsx("span",{className:`${N?"w-7 text-[9px]":"w-16 text-[11px]"} shrink-0 text-right font-medium ${N?r?"text-neutral-400":"text-slate-500":r?"text-neutral-400":"text-slate-600"}`,children:ce?"live":`${Oe+1}/${O.length}`}),ce?null:e.jsxs("button",{type:"button",onClick:w=>{w.stopPropagation(),jr()},onPointerDown:w=>w.stopPropagation(),className:`inline-flex items-center gap-1 rounded-md ${N?"px-1.5 py-0.5 text-[10px]":"px-2 py-1 text-[11px]"} font-medium transition-colors ${N?Lt:r?"bg-[#1f1f1f] text-neutral-100 hover:bg-[#262626]":"bg-slate-100 text-slate-700 hover:bg-slate-200"}`,"aria-label":"Jump timeline to live",title:"Jump to live output",children:[e.jsx(ls,{size:N?10:11}),"Live"]}),d?e.jsxs("button",{type:"button",onClick:w=>{w.stopPropagation(),d==null||d()},className:`inline-flex items-center gap-1 rounded-md ${N?"px-1.5 py-0.5 text-[10px]":"px-2 py-1 text-[11px]"} font-medium transition-colors ${N?Lt:r?"bg-[#1f1f1f] text-neutral-100 hover:bg-[#262626]":"bg-slate-100 text-slate-700 hover:bg-slate-200"}`,title:o?"Hide workspace panel":"Show workspace panel",children:[e.jsx("span",{children:N?"Workspace":o?"Hide Workspace":"Show Workspace"}),o?e.jsx(Kn,{size:N?10:11}):e.jsx(Yn,{size:N?10:11})]}):null]}):null,!U&&C&&d?e.jsx("div",{className:`mt-1.5 flex shrink-0 items-center justify-end rounded-[12px] border px-3 py-1.5 ${r?"border-white/[0.08] bg-[#171717]/95":"border-slate-200 bg-white"}`,children:e.jsxs("button",{type:"button",onClick:w=>{w.stopPropagation(),d==null||d()},className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-[11px] font-medium transition-colors ${r?"bg-[#1f1f1f] text-neutral-100 hover:bg-[#262626]":"bg-slate-100 text-slate-700 hover:bg-slate-200"}`,title:o?"Hide workspace panel":"Show workspace panel",children:[e.jsx("span",{children:o?"Hide Workspace":"Show Workspace"}),o?e.jsx(Kn,{size:11}):e.jsx(Yn,{size:11})]})}):null,N?null:e.jsxs("button",{type:"button",className:`mt-1.5 flex shrink-0 items-center justify-between gap-3 rounded-[12px] border px-3 py-1.5 text-left transition-colors ${r?"border-white/[0.08] bg-[#171717] hover:bg-[#1f1f1f]":"border-slate-200 bg-white hover:bg-slate-50"}`,onClick:w=>{w.stopPropagation(),i==null||i()},children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(gi,{className:`h-3.5 w-3.5 shrink-0 transition-transform ${we?"rotate-180":""} ${r?"text-neutral-400":"text-slate-500"}`}),e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${u.isProcessing?r?"animate-pulse bg-cyan-300":"animate-pulse bg-cyan-600":r?"bg-emerald-300":"bg-emerald-600"}`}),e.jsx("div",{className:`min-w-0 truncate text-[12px] ${r?"text-neutral-100":"text-slate-900"}`,children:Le})]}),e.jsx("div",{className:`shrink-0 text-[10px] font-medium ${r?"text-neutral-500":"text-slate-500"}`,children:de})]})]})]})]})})}const Ei=312,Gn=272,ni={x:22,y:18};function Ss(t,r,s,a,i=8){const o=s+i,d=a-r-i;return d<o?o:Math.min(Math.max(o,t),d)}
53function Tu({placement:t,position:r,bounds:s,viewport:a,cardWidth:i=Ei}){const o=Math.max(1,Number(a.width)),d=Math.max(1,Number(a.height)),p=Number.isFinite(s==null?void 0:s.left)?Number(s==null?void 0:s.left):0,h=Number.isFinite(s==null?void 0:s.right)?Number(s==null?void 0:s.right):o,y=Number.isFinite(s==null?void 0:s.top)?Number(s==null?void 0:s.top):0,f=Number.isFinite(s==null?void 0:s.bottom)?Number(s==null?void 0:s.bottom):d,u=Math.min(i,Math.max(220,h-p-16),Math.max(1,o-16));return t==="top-right"?{width:u,top:Ss(y+14,Gn,y,f),left:Ss(h-u-14,u,p,h)}:r?{width:u,left:Ss(Number(r.x||0)+ni.x,u,p,h),top:Ss(Number(r.y||0)+ni.y,Gn,y,f)}:{width:u,top:Ss(f-Gn-24,Gn,y,f),left:Ss(o/2-u/2,u,p,h)}}const Ze={bg:"rgba(17, 18, 20, 0.92)",border:"rgba(255, 255, 255, 0.08)",titleBar:"rgba(255, 255, 255, 0.04)",text:"rgba(233, 235, 238, 0.95)",textDim:"rgba(233, 235, 238, 0.55)",textFaint:"rgba(233, 235, 238, 0.38)",prompt:"rgba(148, 163, 184, 0.8)",accent:"rgba(96, 165, 250, 0.9)",success:"rgba(52, 211, 153, 0.95)",error:"rgba(248, 113, 113, 0.75)",dotRed:"#ff5f57",dotYellow:"#febc2e",dotGreen:"#28c840",shadow:"0 18px 40px -12px rgba(0, 0, 0, 0.7)"},Pu={youtube:Ga,pdf:As,ads:Va,transcript:As,generic:qa};function Li(t){return t==="searching"||t==="working"}function Iu(){const[t,r]=n.useState(!1);return n.useEffect(()=>{var i;if(typeof window>"u"||!window.matchMedia)return;const s=window.matchMedia("(prefers-reduced-motion: reduce)"),a=()=>r(!!(s!=null&&s.matches));return a(),s.addEventListener?(s.addEventListener("change",a),()=>s.removeEventListener("change",a)):((i=s.addListener)==null||i.call(s,a),()=>{var o;return(o=s.removeListener)==null?void 0:o.call(s,a)})},[]),t}function ai({open:t,lines:r,position:s,bounds:a,placement:i="cursor",darkMode:o=!0,inline:d=!1}){const p=Iu(),h=n.useRef(null);n.useEffect(()=>{if(!t||!h.current)return;const C=window.setTimeout(()=>{const F=h.current;F&&(F.scrollTop=F.scrollHeight)},30);return()=>window.clearTimeout(C)},[t,r]);const y=n.useMemo(()=>{if(d)return{width:"100%",position:"relative",zIndex:1};const N={width:Ei,maxWidth:"calc(100vw - 16px)",position:"fixed",zIndex:9999};if(typeof window>"u")return{...N,bottom:24,left:"50%",transform:"translateX(-50%)"};const C=Tu({placement:i,position:s,bounds:a,viewport:{width:window.innerWidth||1280,height:window.innerHeight||800}});return{...N,...C}},[d,s,a==null?void 0:a.left,a==null?void 0:a.right,a==null?void 0:a.top,a==null?void 0:a.bottom,i]),f=n.useMemo(()=>(r??[]).filter(N=>Li(N.stage)).length,[r]),u=f>0?"cursor · working":"cursor · idle",$=p?{duration:0}:{type:"spring",stiffness:320,damping:26};return e.jsx(Jt,{children:t&&e.jsx(_e.div,{initial:p?{opacity:1}:{opacity:0,scale:.94,y:6},animate:{opacity:1,scale:1,y:0},exit:p?{opacity:0}:{opacity:0,scale:.96,y:4},transition:$,style:y,role:"status","aria-live":"polite","data-cursor-activity-terminal":!0,children:e.jsxs("div",{style:{borderRadius:16,overflow:"hidden",background:Ze.bg,border:`1px solid ${Ze.border}`,boxShadow:Ze.shadow,backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace'},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",background:Ze.titleBar,borderBottom:`1px solid ${Ze.border}`},children:[e.jsxs("span",{style:{display:"flex",gap:6},children:[e.jsx("span",{style:Ea(Ze.dotRed)}),e.jsx("span",{style:Ea(Ze.dotYellow)}),e.jsx("span",{style:Ea(Ze.dotGreen)})]}),e.jsx("span",{style:{fontSize:11,letterSpacing:.3,color:Ze.textDim,marginLeft:2},children:u}),e.jsx(Fu,{active:f>0})]}),e.jsx("div",{ref:h,style:{maxHeight:220,overflowY:"auto",padding:"8px 10px 10px"},children:(r??[]).length===0?e.jsxs("div",{style:{fontSize:12,color:Ze.textFaint,padding:"6px 2px",display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{color:Ze.prompt},children:"›"}),e.jsx("span",{children:"waiting…"}),!p&&e.jsx(Du,{})]}):e.jsx(Jt,{initial:!1,children:(r??[]).map((N,C)=>e.jsx(Eu,{line:N,index:C,reducedMotion:p},(N==null?void 0:N.id)??`line-${C}`))})})]})}
53,"cursor-activity-terminal")})}function Eu({line:t,index:r,reducedMotion:s}){const a=Pu[t==null?void 0:t.tool]??qa,i=Li(t==null?void 0:t.stage),o=(t==null?void 0:t.stage)==="error",d=(t==null?void 0:t.stage)==="found"||(t==null?void 0:t.stage)==="done",p=o?Ze.error:i?Ze.text:Ze.textDim;return e.jsxs(_e.div,{layout:!s,initial:s?{opacity:1}:{opacity:0,y:6},animate:{opacity:1,y:0},exit:s?{opacity:0}:{opacity:0,y:-4},transition:s?{duration:0}:{delay:Math.min(r,4)*.03,duration:.22,ease:"easeOut"},style:{padding:"3px 2px"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{style:{display:"inline-flex",color:o?Ze.error:Ze.accent,opacity:d?.85:1},children:e.jsx(a,{size:13,strokeWidth:1.9})}),e.jsx("span",{style:{color:Ze.prompt,fontSize:12},children:"›"}),e.jsx("span",{style:{fontSize:12,color:p,flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:t==null?void 0:t.label,children:t==null?void 0:t.label}),e.jsx(Lu,{stage:t==null?void 0:t.stage,reducedMotion:s})]}),d&&Array.isArray(t==null?void 0:t.items)&&t.items.length>0&&e.jsx("ul",{style:{listStyle:"none",margin:"3px 0 2px 0",padding:"0 0 0 30px"},children:t.items.slice(0,5).map((h,y)=>e.jsxs("li",{style:{fontSize:11,color:Ze.textFaint,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",lineHeight:1.5},title:h,children:[e.jsx("span",{style:{opacity:.6,marginRight:5},children:"·"}),h]},`${t.id}-item-${y}`))})]})}function Lu({stage:t,reducedMotion:r}){return t==="found"||t==="done"?e.jsx("span",{style:{display:"inline-flex",color:Ze.success},children:e.jsx(cs,{size:13,strokeWidth:2.4})}):t==="error"?e.jsx("span",{style:{display:"inline-flex",color:Ze.error},children:e.jsx(qt,{size:13,strokeWidth:2.2})}):e.jsx(zu,{reducedMotion:r})}function zu({reducedMotion:t}){return t?e.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:Ze.accent,display:"inline-block"}}):e.jsx(_e.span,{animate:{opacity:[.35,1,.35],scale:[.85,1.1,.85]},transition:{duration:1.1,repeat:1/0,ease:"easeInOut"},style:{width:6,height:6,borderRadius:"50%",background:Ze.accent,display:"inline-block"}})}function Du(){return e.jsx(_e.span,{animate:{opacity:[1,0,1]},transition:{duration:1,repeat:1/0,ease:"linear"},style:{display:"inline-block",width:6,height:12,background:Ze.textDim,marginLeft:2}})}function Fu({active:t}){return e.jsxs("span",{"aria-hidden":"true",title:"Operator","data-cursor-operator-avatar":!0,style:{position:"relative",marginLeft:"auto",width:34,height:34,borderRadius:10,overflow:"hidden",border:`1px solid ${t?"rgba(103,232,249,0.42)":Ze.border}`,background:"linear-gradient(180deg, rgba(15,23,42,0.96), rgba(2,6,23,0.98))",boxShadow:t?"0 0 18px rgba(96,165,250,0.24), inset 0 0 18px rgba(103,232,249,0.08)":"inset 0 0 14px rgba(255,255,255,0.04)",flexShrink:0},children:[e.jsx("span",{style:{position:"absolute",inset:0,opacity:.22,backgroundImage:"linear-gradient(to bottom, transparent 0, transparent 5px, rgba(255,255,255,0.9) 6px)",backgroundSize:"100% 7px"}}),e.jsx("span",{style:{position:"absolute",left:11,top:8,width:14,height:5,background:"#2b1c18",boxShadow:"-3px 4px 0 #2b1c18, 9px 2px 0 #2b1c18"}}),e.jsx("span",{style:{position:"absolute",left:10,top:13,width:16,height:14,background:"#f2c69c",boxShadow:"0 4px 0 #e8b88d"}}),e.jsx("span",{style:{position:"absolute",left:13,top:18,width:3,height:3,background:"#111827",boxShadow:"8px 0 0 #111827"}}),e.jsx("span",{style:{position:"absolute",left:16,top:24,width:8,height:2,background:t?"#7c3f2a":"#8b5a44"}}),e.jsx("span",{style:{position:"absolute",left:8,right:7,bottom:0,height:7,background:"#60a5fa",boxShadow:"0 4px 0 #2563eb"}}),t?e.jsx(_e.span,{animate:{opacity:[.2,.9,.2]},transition:{duration:1.4,repeat:1/0,ease:"easeInOut"},style:{position:"absolute",right:3,top:3,width:5,height:5,borderRadius:"50%",background:Ze.success,boxShadow:"0 0 10px rgba(52,211,153,0.75)"}}):null]})}function Ea(t){return{width:9,height:9,borderRadius:"50%",background:t,display:"inline-block"}}const oi="chatgrid:vault-add-to-canvas",ii=30;function Ou(t,r,s){const a=`vault-${t.kind}-${Date.now()}-${s}`;if(t.kind==="video"){const o=String(t.platform||"").toLowerCase();return{id:a,type:o==="tiktok"?"tiktokNode":o==="youtube"?"youtubeNode":"websiteNode",position:r,data:{url:t.url,videoUrl:t.url,t
53itle:t.title,displayTitle:t.title,sourceTitle:t.title,hasCustomTitle:!1,thumbnailUrl:t.thumbnailUrl||"",previewUrl:t.previewUrl||"",platform:o,creatorHandle:t.creatorHandle||"",viewCount:t.viewCount||0,likeCount:t.likeCount||0,commentCount:t.commentCount||0,shareCount:t.shareCount||0,bookmarkCount:t.bookmarkCount||0,durationFormatted:t.durationFormatted||"",pageName:t.title,pageDescription:t.creatorHandle?`${o} video by ${t.creatorHandle}`:`${o} video`,ogImage:t.thumbnailUrl||""}}}const i=t.kind==="product"?"Product":t.kind==="ad"?"Ad":"Creator";return{id:a,type:"websiteNode",position:r,data:{url:t.url,title:t.title,displayTitle:t.title,hasCustomTitle:!1,platform:t.platform,pageName:t.title,pageDescription:t.subtitle||`${i} from Viral Vault`,ogImage:t.thumbnailUrl||"",thumbnailUrl:t.thumbnailUrl||"",aiProcessed:!0,processingStatus:null,processingMessage:null,errorMessage:null}}}function Bu({reactFlowInstance:t,isViewer:r,setNodes:s,setHasUnsavedChanges:a,showToast:i,broadcastEvent:o}){n.useEffect(()=>{if(r)return;const d=p=>{var y;const h=(y=p.detail)==null?void 0:y.items;if(!(!Array.isArray(h)||!h.length||!t))try{const f=t.screenToFlowPosition({x:window.innerWidth/2,y:window.innerHeight/2.4}),u=h.filter($=>($==null?void 0:$.url)&&($==null?void 0:$.title)).map(($,N)=>Ou($,{x:f.x-180+N*ii,y:f.y-140+N*ii},N));if(!u.length)return;s($=>[...$,...u]);for(const $ of u)o==null||o("node-data",{id:$.id,data:$.data});a(!0),i==null||i(`Added ${u.length} item${u.length===1?"":"s"} to the canvas`,"success")}catch(f){console.error("Failed to add vault items to canvas:",f),i==null||i("Failed to add items to the canvas","error")}};return window.addEventListener(oi,d),()=>window.removeEventListener(oi,d)},[t,r,s,a,i,o])}const Mu={textNode:"note",txtNode:"note",blockNoteNode:"notepad",notepadNode:"notepad",stickyNoteNode:"sticky note",fileNode:"note",youtubeNode:"youtube video",tiktokNode:"tiktok video",facebookNode:"facebook post",videoNode:"video",voiceNode:"voice note",pdfNode:"pdf",docNode:"doc",imageNode:"image",websiteNode:"website",threadNode:"chat thread",spreadsheetNode:"spreadsheet",googleSheetsNode:"spreadsheet"};function Uu(t){switch(t==null?void 0:t.op){case"create_node":return t.kind==="youtube"?"Adding the video…":t.kind==="pdf"?"Adding the PDF…":t.kind==="website"?"Adding the page…":t.kind==="image"?"Adding the image…":"Writing a note…";case"group":return"Grouping them…";case"connect":return"Connecting to the chat…";case"move":return"Moving it…";case"delete":return"Removing it…";default:return"Working on it…"}}function Ma(t){return String((t==null?void 0:t.prompt)||"Agent task").trim()}function zi(t){const r=Array.isArray(t==null?void 0:t.logs)?t.logs[t.logs.length-1]:null;return String((t==null?void 0:t.liveThought)||(r==null?void 0:r.message)||hi(t)||"Waiting").trim()}function Vu(t,r=null){if(!t)return null;const s=t.logs||[],a=t.files||[],i=t.previewFrames||[],o=[...s.filter(h=>h.role!=="assistant_final").map(h=>({id:String(h.id),message:h.detail?`${h.message}
54${h.detail}`:h.message,detail:h.detail||null,role:h.role||"assistant",timestamp:h.timestamp||0})),...i.map((h,y)=>({id:`browser-frame-${y}-${h.id}`,message:h.message||h.label||"Browser frame",imageUrl:h.imageUrl,detail:{imageUrl:h.imageUrl},kind:"browser_frame",timestamp:h.timestamp||0})),...a.map((h,y)=>({id:`file-${y}-${h.id}`,message:h.content&&h.content!==h.name?`${h.name}
55${h.content}`:h.name,timestamp:h.timestamp||0}))].sort((h,y)=>(h.timestamp||0)-(y.timestamp||0)),d=hi(t),p=t.status==="running";return{runId:t.id,id:t.id,feed:o,screenMode:"terminal",screenLabel:Ma(t),isProcessing:p,status:t.status,statusLine:p?d||"Working":d||"Completed",summaryLine:d||zi(t),currentStepIndex:o.length,totalSteps:o.length,previewHtml:t.previewHtml||null,previewUrl:t.previewUrl||null,previewImage:t.previewImage||null,streamingFile:t.streamingFile||null,finalAnswer:String(t.finalAnswer||"").trim(),artifactFocus:r}}function Wu({darkMode:t,onBackToOperator:r,onSelectTask:s,onTerminateTask:a,selectedTaskId:i,sessions:o,workspaceOffset:d,workspaceReserve:p}){const[h,y]=n.useState(null),[f,u]=n.useState(null),$=i?o==null?void 0:o[i]:null,N=n.useMemo(()=>Vu($,f),[f,$]),C=h?o==null?void 0:o[h]:null,F=n.useMemo(()=>Object.values(o||{}).sort((te,E)=>Number((te==null?void 0:te.startTime)||0)-Number((E==null?void 0:E.startTime)||0)).map(te=>({id:String(te.id),title:Ma(te),status:String(te.status||"running"),summary:zi(te)})),[o]);return n.useEffect(()=>{h&&!(o!=null&&o[h])&&y(null)},[h,o]),n.useEffect(()=>{i||u(null)},[i]),e.jsxs("div",{"data-operator-workspace-mode":!0,className:`pointer-events-auto fixed bottom-0 top-0 z-[90] overflow-hidden ${t||!$?"bg-[#020409]":"bg-slate-100"}`,style:{left:d,right:p},children:[e.jsx("div",{className:"pointer-events-none absolute inset-0",style:{background:t||!$?"radial-gradient(circle at 50% 16%, rgba(34,211,238,0.12), transparent 36%), linear-gradient(180deg, rgba(2,6,23,0.98), rgba(0,0,0,1))":"radial-gradient(circle at 50% 8%, rgba(14,165,233,0.08), transparent 38%), linear-gradient(180deg, rgba(248,250,252,0.98), rgba(226,232,240,0.92))"}}),e.jsx("div",{className:"relative h-full min-h-0",children:e.jsx("div",{className:`h-full min-h-0 overflow-hidden border-r shadow-[0_30px_110px_rgba(0,0,0,0.22),inset_0_0_0_1px_rgba(255,255,255,0.04)] ${t||!$?"border-cyan-100/[0.14] bg-black":"border-slate-200 bg-white"}`,children:$&&N?e.jsx("div",{"data-operator-workspace-task-detail":!0,"data-operator-workspace-selected-task-id":i||"",className:`relative h-full min-h-0 overflow-hidden p-2 ${t?"bg-[#060914]/[0.94]":"bg-slate-50/90"}`,children:e.jsx("div",{"data-operator-workspace-task-terminal":!0,className:"h-full min-h-0",children:e.jsx(Au,{task:N,darkMode:t,size:"split",onClose:()=>y(String(i||"")),onMinimize:r,onToggleProgress:()=>{}})})}):e.jsx("div",{"data-operator-workspace-operator-room":!0,className:"relative h-full min-h-0 bg-[#04070d]",children:e.jsx(ou,{highlightedTaskId:i,tasks:F,onSelectTask:s})})})}),C?e.jsx("div",{"data-operator-workspace-terminate-dialog":!0,className:"absolute inset-0 z-40 flex items-end bg-black/[0.52] p-4 backdrop-blur-sm",role:"dialog","aria-modal":"true","aria-labelledby":"operator-workspace-terminate-title",children:e.jsxs("div",{className:"w-full rounded-[22px] border border-white/[0.1] bg-[#151821] p-4 text-white shadow-2xl",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"mt-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-rose-500/[0.16] text-rose-100",children:e.jsx(qt,{size:16})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{id:"operator-workspace-terminate-title",className:"text-[14px] font-semibold",children:"Terminate this task?"}),e.jsx("div",{className:"mt-1 line-clamp-2 text-[12px] text-white/[0.52]",children:Ma(C)})]})]}),e.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:()=>y(null),className:"rounded-full bg-white/[0.07] px-3.5 py-2 text-[12px] font-semibold text-white/[0.7] transition hover:bg-white/[0.1] hover:text-white",children:"Cancel"}),e.jsx("button",{type:"button",onClick:()=>{const te=String(h||"");y(null),te&&a(te)},className:"rounded-full bg-rose-600 px-3.5 py-2 text-[12px] font-semibold text-white shadow-lg shadow-rose-950/18 transition hover:bg-rose-500",children:"Terminate"})]})]})}):null]})}const La=.35,li=.8,Xn=440,Di=340,Fi=760,Oi="chatgrid.operatorRailWidth.v1";function Bi(t){return Number.isFinite(t)?Math.max(Di,Math.min(Fi,Math.round(t))):Xn}function Hu(){if(typeof window>"u")return Xn;try{const t=window.localStorage.getItem(Oi);return t?Bi(Number(t)):Xn}catch{return Xn}}function qu(t=""){const r=String(t||"").trim();if(!r)return null;const s=/\b(ad|ads|advert|advertising|campaign|campaigns|creative|creatives)\b/i.test(r),a=/\b(show|find|search|pull|get|look\s+for|research|surface)\b/i.test(r);if(!s||!a)return null;const o=/\b(image|images|creative|creatives|copy|text|caption|captions|wording|landing\s+page|screenshots?|summary|video|videos|all\s+of\s+the\s+above)\b/i.test(r)?.92:.68;return o>=li?null:{confidence:o,threshold:li,question:"What should I pull for this ad search?",options:[{id:"creative_and_copy",label:"Creative images and ad copy",helper:"Show the visual ad assets plus the written hook/body text."},{id:"creative_only",label:"Creative images only",helper:"Focus on screenshots, thumbnails, or video creative previews."},{id:"copy_summary",label:"Copy and competitor summary",helper:"Focus on hooks, claims, offer language, and launch angle."}]}}function Gu({originalPrompt:t,selectedOption:r,customAnswer:s}){const a=String(t||"").trim(),i=String((r==null?void 0:r.id)||"").trim(),o=String(s||"").trim(),d=i==="creative_and_copy"?"Return ad creative/images plus ad copy/text when available.":i==="creative_only"?"Return ad creative/images, thumbnails, screenshots, or video creative previews when available.":i==="copy_summary"?"Return the ad copy/text, hooks, claims, offer language, and a concise competitor summary.":o?`Use this custom output preference: ${o}.`:"Return the most relevant ad creative/images and ad copy/text when available.";return[a,d,"Use Viral Vault/ad discovery sources where possible, preserve source URLs, and make clear when an image, copy field, or platform is unavailable."].filter(
55Boolean).join(" ")}function Yu(t=""){const r=String(t||"").toLowerCase().replace(/[^a-z0-9'\s]/g," ").replace(/\s+/g," ").trim();return r?/^(hi|hello|hey|yo|sup|hiya|howdy|hi there|hey there|hello there)$/.test(r)?"Hi. I'm here. What should we work on?":/^(thanks|thank you|thx|ty|appreciate it)$/.test(r)?"You're welcome.":/^(ok|okay|cool|nice|got it|sounds good)$/.test(r)?"Got it.":null:null}function Ku({boardId:t,workspaceOffset:r=0,headerInset:s=0,workspaceBoards:a,workspaceBoardName:i,onBoardRenamed:o,showSidebarToggle:d=!1,onRevealSidebar:p,embedded:h=!1}={}){var bo,yo,wo;const{darkMode:y,canvasPattern:f,canvasColor:u,canvasSize:$}=di(),N=Qi(),C=t||N.boardId;ci();const[F,te]=el(),E=F.get("admin_view")==="true",Y=n.useRef(null),V=n.useRef(!0),L=n.useRef(null),{nodes:_,edges:J,setNodes:O,setEdges:U,setNodesAndEdges:Z,updateNodeData:b,updateEdgesWithoutHistory:q,setIsDragging:Q,onNodesChange:P,onEdgesChange:Ne}=is(ol(l=>({nodes:l.nodes,edges:l.edges,setNodes:l.setNodes,setEdges:l.setEdges,setNodesAndEdges:l.setNodesAndEdges,updateNodeData:l.updateNodeData,updateEdgesWithoutHistory:l.updateEdgesWithoutHistory,setIsDragging:l.setIsDragging,onNodesChange:l.onNodesChange,onEdgesChange:l.onEdgesChange}))),[m,ue]=n.useState(null),[ce,Oe]=n.useState(""),[j,I]=n.useState([]),[me,D]=n.useState(!1),[v,be]=n.useState(null),[M,Ye]=n.useState(Hu),[ye,Re]=n.useState(!1),[qe,Rt]=n.useState(null);n.useCallback(l=>{const c=Bi(l);if(Ye(c),!(typeof window>"u"))try{window.localStorage.setItem(Oi,String(c))}catch{}},[]);const at=Pe(l=>l.sessions),Ee=v?at[v]:null,[Ge,Xt]=n.useState(()=>typeof window<"u"?window.innerWidth:1280),[Be,Gt]=n.useState(()=>typeof window<"u"?window.innerHeight:720),ft=Ge<768,vt=Math.max(Di,Math.min(Fi,Ge-320)),ar=ft?Math.max(280,Ge-24):Math.min(M,vt),ot=0,[Qe,Ue]=n.useState(null),dt=n.useRef(null),gt=n.useRef(new Map);n.useMemo(()=>{if(!v||!(Ee!=null&&Ee.prompt))return null;const l=Zl(Ee);return{key:Ee.id,title:Ee.prompt||"Agent",messages:l,isRunning:Ee.status==="running",placeholder:"Message this task...",onSubmit:c=>{var x;!v||!c.trim()||(x=dt.current)==null||x.call(dt,c.trim(),{sessionId:v})}}},[Ee,v]);const[et,br]=n.useState(Gl),[Ot,kt]=n.useState(""),[Zt,mt]=n.useState(!1),[Ke,Qt]=n.useState(()=>{const l=typeof window<"u"?window.innerWidth:1280,c=typeof window<"u"?window.innerHeight:720;return{x:Math.max(24,l-ot-360),y:c*.35}}),[T,z]=n.useState("files");n.useEffect(()=>{let l=!1;return(async()=>{var c,x,k,R,W,S;try{const{data:{session:K}}=await Et.auth.getSession(),H=K==null?void 0:K.access_token;if(!H)return;const B={Authorization:`Bearer ${H}`},We=await fetch($t("/api/agent-sdk-mission/sessions"),{headers:B});if(!We.ok)return;const ie=await We.json().catch(()=>null);if(l||!(ie!=null&&ie.success)||!Array.isArray(ie.sessions))return;(x=(c=Pe.getState()).hydrateSessions)==null||x.call(c,ie.sessions);let Je=null;try{Je=localStorage.getItem("chatgrid:activeMissionSession")}catch{Je=null}if(!(Je&&ie.sessions.some(Or=>(Or==null?void 0:Or.sessionId)===Je)))return;const yt=await fetch($t(`/api/agent-sdk-mission/sessions/${encodeURIComponent(Je)}`),{headers:B});if(!yt.ok)return;const Rr=await yt.json().catch(()=>null);if(l||!(Rr!=null&&Rr.success))return;(R=(k=Pe.getState()).hydrateSession)==null||R.call(k,Je,Rr),(S=(W=Pe.getState()).setActiveSession)==null||S.call(W,Je)}catch(K){console.error("[AgentMission] hydrate on mount failed:",K)}})(),()=>{l=!0}},[]),n.useEffect(()=>{if(typeof window>"u")return;let l=0,c=null;const x=S=>{Ue(K=>K===null&&S===null||K!==null&&S!==null&&Math.abs(K-S)<1?K:S)},k=()=>{const S=document.querySelector("[data-chatgrid-operator-rail]");if(!S){x(null);return}const K=S.getBoundingClientRect();x(Number.isFinite(K.left)?Math.max(0,K.left):null),c==null||c.disconnect(),c=new ResizeObserver(()=>R()),c.observe(S)},R=()=>{l&&window.cancelAnimationFrame(l),l=window.requestAnimationFrame(k)};R();const W=window.setTimeout(R,120);return window.addEventListener("resize",R),()=>{l&&window.cancelAnimationFrame(l),window.clearTimeout(W),window.removeEventListener("resize",R),c==null||c.disconnect()}},[v,ft,ye,ar]);const oe=Math.max(r+320,Ge-ot),pe=Qe===null?oe:Qe-12,Ie=Math.max(r+24,Math.min(oe,pe)),Le=Ie-r>=260,de=n.useMemo(()=>({left:r,right:Ie,top:0,bottom:Be}),[Ie,Be,r]),xe=n.useMemo(()=>({x:r+Math.max(0,Ie-r)/2,y:Be/2}),[Ie,Be,r]),we=n.useCallback(l=>{const c=Number((l==null?void 0:l.x)??xe.x),x=Number((l==null?void 0:l.y)??xe.y),k=r+18,R=Math.max(k,Ie-378),W=18,S=Math.max(W,Be-260);return{x:Math.min(Math.max(c,k),R),y:Math.min(Math.max(x,W),S)}},[xe,Ie,Be,r]);n.useEffect(()=>{const l=()=>{Xt(window.innerWidth),Gt(window.innerHeight)};return window.addEventListener("resize",l),()=>window.removeEventListener("resize",l)},[]),n.useEffect(()=>{Qt(l=>we(l))},[we]);const[le,re]=n.useState("pan"),[Ae,ve]=n.useState(null),[xt,fe]=n.useState({isOpen:!1,url:""}),[ze,Lt]=n.useState({isOpen:!1,url:""}),[us,jt]=n.useState(!1),[fr,yr]=n.useState(""),[St,wr]=n.useState(!1),[vr,Ar]=n.useState(!1),[kr,or]=n.useState(new Set),[jr,Vr]=n.useState({}),[Wr,Ps]=n.useState(!1),[Nt,Bt]=n.useState([{id:"page-1",nodes:[],edges:[]}]),[w,ge]=n.useState(0),{toasts:Ve,showToast:se,removeToast:Sr}=bl(),{checkmarkAnimations:cn,showCheckmark:Is}=yl(),dn=n.useCallback(()=>({colorLegend:jr}),[jr]),{currentBoard:ne,allBoards:ps,currentUser:ir,loading:Yt,isSaving:er,hasUnsavedChanges:tr,setHasUnsavedChanges:je,isBoardPublished:hs,anonymousIdentity:Hr,isViewer:Te,isGuest:fs,isOwner:un,debouncedSave:ke,handleBackToBoards:pn,handleSwitchBoard:qr,handleRenameBoard:Es,handleUpdateSharing:Ls}=wl({boardId:C,reactFlowInstance:m,setNodesAndEdges:Z,showToast:se,getExtraData:dn}),zs=a!=null&&a.length?a:ps,Ds=i||(ne==null?void 0:ne.name)||"Board",Tr=((bo=ne==null?void 0:ne.flow_state)==null?void 0:bo.viewMode)||"canvas",Fs={width:`calc(100vw - ${r+ot}px)`,height:"100vh",marginLeft:r?`${r}px`:0},fn=r+s,Pr=n.useMemo(()=>{var R;const l=(R=ne==null?void 0:ne.flow_state)==null?void 0:R.viewport;if(l&&Number.isFinite(l.x)&&Number.isFinite(l.y)&&Number.isFinite(l.zoom)&&l.zoom>=La)return l;const c=Number(ne==null?void 0:ne.viewport_x),x=Number(ne==null?void 0:ne.viewport_y),k=Number(ne==null?void 0:ne.viewport_zoom);return Number.isFinite(c)&&Number.isFinite(x)&&Number.isFinite(k)&&k>=La?{x:c,y:x,zoom:k}:null},[ne]),tt=n.useCallback(async(l,c)=>{await Es(l,c),o==null||o(l,c)},[Es,o]),aa=n.useCallback((l,c)=>{var k;if(Yt||Te||!m)return;const x=c||((k=m.getViewport)==null?void 0:k.call(m));x&&Number.isFinite(x.x)&&Number.isFinite(x.y)&&Number.isFinite(x.zoom)&&Rt({x:x.x,y:x.y,zoom:x.zoom}),je(!0),ke()},[ke,Te,Yt,m,je]);n.useEffect(()=>{ue(null),V.current=!0,L.current=null},[C]),n.useEffect(()=>{if(Yt||!m||!ne||L.current===C)return;const l=window.setTimeout(()=>{Pr?(m.setViewport(Pr,{duration:0}),Rt(Pr)):_.length>
550&&(m.fitView({padding:.1,minZoom:La,maxZoom:.85}),window.setTimeout(()=>{var x;const c=(x=m.getViewport)==null?void 0:x.call(m);c&&Rt(c)},0)),L.current=C},0);return()=>window.clearTimeout(l)},[C,ne,Yt,_.length,m,Pr]),n.useEffect(()=>{var l;(l=ne==null?void 0:ne.flow_state)!=null&&l.colorLegend&&Vr(ne.flow_state.colorLegend)},[ne]),n.useEffect(()=>{if(Yt||!_.length)return;const l=_.filter(c=>{var x,k,R;return((x=c.data)==null?void 0:x.processingBatchState)&&((k=c.data)==null?void 0:k.processingStatus)!=="completed"&&((R=c.data)==null?void 0:R.processingStatus)!=="failed"});l.length>0&&(l.forEach(c=>{b(c.id,{processingStatus:"interrupted",processingBatchState:void 0,errorMessage:"Processing was interrupted. Connect to a chat to restart."})}),se(`${l.length} document${l.length>1?"s were":" was"} interrupted. Connect to a chat to restart processing.`,"warning"))},[Yt,_.length]),n.useEffect(()=>{Yt||!_.length||O(l=>{let c=!1;const x=l.map(k=>{var W,S,K,H,B;if(k.type!=="youtubeNode")return k;const R=String(((W=k.data)==null?void 0:W.url)||((S=k.data)==null?void 0:S.videoUrl)||"").toLowerCase();return R.includes("tiktok.com")?(c=!0,{...k,type:"tiktokNode",data:{...k.data,platform:"tiktok",processingStatus:null,processingMessage:null,errorMessage:null}}):R.includes("instagram.com")?(c=!0,{...k,type:"websiteNode",data:{...k.data,platform:"instagram",pageName:((K=k.data)==null?void 0:K.pageName)||((H=k.data)==null?void 0:H.title)||"Instagram Reel",pageDescription:((B=k.data)==null?void 0:B.pageDescription)||"Instagram viral video",aiProcessed:!0,processingStatus:null,processingMessage:null,errorMessage:null}}):k});return c?x:l})},[Yt,_.length,O]);const Os=n.useCallback(l=>{Vr(l),je(!0),ke()},[je,ke]),oa=n.useCallback((l,c)=>{O(x=>x.map(k=>k.id===l?k.type==="blockNoteNode"?{...k,style:{...k.style,border:void 0,boxShadow:void 0},data:{...k.data,customColor:c}}:{...k,style:{...k.style,border:c?`3px solid ${c}`:void 0,boxShadow:c?`0 0 15px ${c}40`:void 0},data:{...k.data,customColor:c}}:k)),je(!0),ke()},[O,je,ke]),ia=n.useCallback((l,c)=>{const x=(c||"").trim();x&&(b(l,{title:x,label:x}),je(!0),ke())},[b,je,ke]),{channel:Gr,mySessionId:la,presenceUsers:gn,lastMousePos:lr,trackMouse:gs,broadcastAuthoritativeState:Ce,broadcastNodeChanges:mn,broadcastEvent:g}=vl({boardId:C,currentUser:ir,currentBoard:ne,reactFlowInstance:m,setNodes:O,setEdges:U,isAdminView:E,anonymousIdentity:Hr}),{triggerDocumentProcessing:G}=ec({boardId:C,setNodes:O,updateNodeData:b,showToast:se}),{handleConnection:ae,onConnect:$e,onConnectStart:bt,onConnectEnd:At}=kl({nodes:_,setNodes:O,setEdges:U,reactFlowInstance:m,isViewer:Te,triggerDocumentProcessing:G,broadcastAuthoritativeState:Ce}),{navigateToNode:De,focusOnNodes:it,handleLinkSubmit:ms}=jl({nodes:_,reactFlowInstance:m,setNodes:O,setWebsiteModal:Lt,handleConnection:ae,broadcastAuthoritativeState:Ce,showToast:se}),Ir=n.useCallback(()=>{ms(fr,()=>{jt(!1),yr("")})},[fr,ms]),{onNodeContextMenu:xn,onEdgeContextMenu:Er,handleDeleteEdge:bn,handleDisconnectNode:yn,handleDeleteNode:cr}=Sl({nodes:_,edges:J,setNodes:O,setEdges:U,setContextMenu:ve,setHasUnsavedChanges:je,debouncedSave:ke,channel:Gr,broadcastAuthoritativeState:Ce,isViewer:Te,reactFlowInstance:m,reactFlowWrapper:Y}),Yr=n.useCallback(l=>{var W;const c=(l==null?void 0:l.data)||{},x=l.type,k=c.title||c.label||c.fileName||c.name||c.videoTitle||c.urlTitle;if(k&&String(k).trim())return String(k).trim();if(x==="youtubeNode"&&(c.url||c.videoUrl)){const S=c.url||c.videoUrl;if(S.includes("youtube.com/@")){const K=(W=S.split("@")[1])==null?void 0:W.split(/[?/]/)[0];if(K)return`@${K}`}return"YouTube Video"}if((x==="websiteNode"||x==="linkNode")&&c.url)try{return new URL(c.url).hostname.replace("www.","")}catch{return"Website"}return{blockNoteNode:"Notepad",notepadNode:"Notepad",pdfNode:c.fileName?`PDF: ${c.fileName}`:"PDF Document",txtNode:c.fileName?`Text: ${c.fileName}`:"Text Document",stickyNoteNode:"Sticky Note",youtubeNode:"YouTube Video",imageNode:c.fileName?`Image: ${c.fileName}`:"Image",websiteNode:"Website",linkNode:"Link",googleSheetsNode:"Google Sheet",jsonNode:"JSON File",docNode:c.fileName?`Document: ${c.fileName}`:"Document",firefliesNode:"Fireflies Recording",tiktokNode:"TikTok Video",facebookNode:"Facebook Post",responseNode:"Response",spatialArtifactNode:"Spatial Artifact",flashcardsArtifactNode:"Flashcards"}[x]||`${x.replace("Node","")}`},[]),Bs=n.useMemo(()=>{const l=_.filter(c=>c.type!=="threadNode"&&c.type!=="groupNode");return l.sort((c,x)=>{var K,H,B,We;
55const k=c.zIndex||0,R=x.zIndex||0;if(k!==R)return R-k;const W=((K=c.position)==null?void 0:K.y)||0,S=((H=x.position)==null?void 0:H.y)||0;return Math.abs(W-S)>100?W-S:(((B=c.position)==null?void 0:B.x)||0)-(((We=x.position)==null?void 0:We.x)||0)}),l.map(c=>{var x,k,R,W;return{id:c.id,title:Yr(c),content:((x=c.data)==null?void 0:x.content)||((k=c.data)==null?void 0:k.extractedText)||((R=c.data)==null?void 0:R.rawContent),type:"page",_nodeType:c.type,_color:((W=c.data)==null?void 0:W.customColor)||null}})},[_,Yr]),[wn,vn]=n.useState(0),[Kr,Ms]=n.useState(null),[xs,bs]=n.useState(null),[kn,jn]=n.useState(!1);n.useEffect(()=>{const l=c=>{var k,R,W;const x=!!((k=c==null?void 0:c.detail)!=null&&k.switching);jn(x),x?((R=window.clearTimeout)==null||R.call(window,l.__t),l.__t=window.setTimeout(()=>jn(!1),1200)):(W=window.clearTimeout)==null||W.call(window,l.__t)};return window.addEventListener("cg-expanded-switch",l),()=>window.removeEventListener("cg-expanded-switch",l)},[]);const Mt=n.useCallback(l=>{if(!l)return;const c=_.find(k=>k.id===l);if(!c)return;window.dispatchEvent(new CustomEvent("cg-expanded-switch",{detail:{switching:!0}}));const x=c.type;if(["blockNoteNode","notepadNode","txtNode","stickyNoteNode"].includes(x)){Ms(null),bs(null),b(l,{autoMaximizeOnLoad:!0});return}window.dispatchEvent(new CustomEvent("open-file-overlay",{detail:{nodeId:l}}))},[_,b]);n.useCallback(l=>{vn(l);const c=Bs[l];c&&(typeof document<"u"&&!!document.querySelector('[data-maximized-view="true"]')||!!Kr?Mt(c.id):De(c.id))},[Bs,De,Mt,Kr]);const Jr=n.useMemo(()=>Kr?_.find(l=>l.id===Kr):null,[_,Kr]);n.useEffect(()=>{const l=c=>{const{nodeId:x,collaboration:k}=c.detail;Ms(x),bs(k||null)};return window.addEventListener("open-file-overlay",l),()=>{window.removeEventListener("open-file-overlay",l)}},[]),n.useCallback(l=>{cr(l)},[cr]),n.useEffect(()=>{var l;Tr==="docs"&&((l=ne==null?void 0:ne.flow_state)!=null&&l.pages)&&Bt(il(ne.flow_state.pages))},[ne,Tr]),n.useEffect(()=>{if(Tr!=="docs")return;const l=F.get("page");if(!l)return;const c=Number(l);if(!Number.isFinite(c)||!Nt||Nt.length===0)return;const x=Math.max(0,Math.min(Nt.length-1,c));x!==w&&ge(x)},[Tr,F,Nt==null?void 0:Nt.length]),n.useEffect(()=>{const l=F.get("file");l&&_!=null&&_.length&&(Mt(l),te(c=>{const x=new URLSearchParams(c);return x.delete("file"),x},{replace:!0}))},[F,_==null?void 0:_.length]);const ys=25*1024*1024,ca=n.useCallback(l=>{const c=Array.from(l||[]);c.length&&I(x=>{const k=[...x];for(const R of c)if(!(!R||typeof R.size!="number")){if(R.size>ys){se==null||se(`${R.name} is larger than the 25 MB limit`,"warning");continue}if(k.length>=5){se==null||se("Up to 5 attachments per message","warning");break}k.some(W=>W.name===R.name&&W.size===R.size)||k.push({file:R,name:R.name,size:R.size})}return k})},[se]),da=n.useCallback(l=>{I(c=>c.filter(x=>x.name!==l))},[]),Us=n.useCallback(async(l,c)=>{var k;const x=[];for(const R of l)try{const W=await fetch($t("/api/agent-sdk-mission/upload"),{method:"POST",headers:{"Content-Type":"application/octet-stream","x-file-name":encodeURIComponent(R.name),"x-file-type":((k=R.file)==null?void 0:k.type)||"application/octet-stream",...c?{Authorization:`Bearer ${c}`}:{}},body:R.file}),S=await W.json().catch(()=>null);W.ok&&(S!=null&&S.attachment)?x.push(S.attachment):(console.error("[AgentMission] attachment upload failed:",(S==null?void 0:S.error)||W.status),se==null||se(`Couldn't upload ${R.name}`,"error"))}catch(W){console.error("[AgentMission] attachment upload failed:",W),se==null||se(`Couldn't upload ${R.name}`,"error")}return x},[se]),Lr=n.useCallback(async(l,c={})=>{var H,B,We,ie,Je,ur,yt,Rr,Or,Ys,Ks,Dn,es,Fn,Ut,ts,Kt,rs,On,Js;const x=String(l||"").trim();if(!x)return;const k=Array.isArray(c.attachments)?c.attachments.filter(Fe=>Fe==null?void 0:Fe.file):[],R=Pe.getState(),W=c.sessionId||null;let S,K=null;if(W&&((H=R.getSession)!=null&&H.call(R,W))){S=W;const Fe=R.getSession(W),ss=(Fe==null?void 0:Fe.status)==="running";if(R.addUserMessage(S,x),R.setActiveSession(S),be(S),ss){try{const{data:{session:st}}=await Et.auth.getSession(),zt=k.length?await Us(k,st==null?void 0:st.access_token):[];await fetch($t("/api/agent-sdk-mission/message"),{method:"POST",headers:{"Content-Type":"application/json",...st!=null&&st.access_token?{Authorization:`Bearer ${st.access_token}`}:{}}
55,body:JSON.stringify({sessionId:S,text:x,attachments:zt.length?zt:void 0})})}catch(st){console.error("[AgentMission] steer failed:",st)}return}gt.current.delete(S);try{const st=za((Fe==null?void 0:Fe.logs)||[]).slice(0,20).map(zt=>({path:zt.path,content:String(zt.content||"").slice(0,8e4)}));st.length&&(K={priorGoal:(Fe==null?void 0:Fe.prompt)||"",files:st})}catch(st){console.error("[AgentMission] failed to build follow-up context:",st)}}else S=`mission_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`,R.createSession(S,x),gt.current.delete(S),be(null);try{localStorage.setItem("chatgrid:activeMissionSession",S)}catch(Fe){console.error("[AgentMission] persist active session failed:",Fe)}try{const{data:{session:Fe}}=await Et.auth.getSession(),ss=Fe==null?void 0:Fe.access_token;let st=[];if(k.length&&(Pe.getState().addLog(S,`uploading ${k.length} attachment(s)...`),st=await Us(k,ss),!st.length)){Pe.getState().addLog(S,"attachment upload failed — message not sent"),Pe.getState().updateSessionStatus(S,"error"),se==null||se("Attachment upload failed — please try again.","error");return}const zt=await fetch($t("/api/agent-sdk-mission/stream"),{method:"POST",headers:{"Content-Type":"application/json",...ss?{Authorization:`Bearer ${ss}`}:{}},body:JSON.stringify({prompt:x,sessionId:S,userId:((B=Fe==null?void 0:Fe.user)==null?void 0:B.id)||"dev-user",continuation:K||void 0,attachments:st.length?st:void 0})});if(!zt.ok||!zt.body){const ks=await zt.text().catch(()=>"");throw new Error(`Mission failed (${zt.status}): ${ks}`)}const va=zt.body.getReader(),Bn=new TextDecoder;let vs="",Vt="message";for(;;){const{done:ks,value:Mn}=await va.read();if(ks)break;vs+=Bn.decode(Mn,{stream:!0});const Xs=vs.split(`
56`);vs=Xs.pop()||"";for(const ns of Xs){if(ns.startsWith("event:")){Vt=ns.slice(6).trim();continue}if(!ns.startsWith("data:"))continue;const X=ns.slice(5).trim();if(!X)continue;let ee;try{ee=JSON.parse(X)}catch(Se){console.error("[AgentMission] failed to parse SSE payload:",Se);continue}if((ie=(We=Pe.getState()).addEvent)==null||ie.call(We,S,Vt,ee),Vt==="log")Pe.getState().addLog(S,ee.message||"",ee.detail),/^write\s+/.test(String(ee.message||"").trim())&&((ur=(Je=Pe.getState()).setStreamingFile)==null||ur.call(Je,S,null,null));else if(Vt==="file_stream")(Rr=(yt=Pe.getState()).setStreamingFile)==null||Rr.call(yt,S,ee.path,ee.content);else if(Vt==="agent_text"){const Se=ee.text||"";(Ys=(Or=Pe.getState()).setLiveThought)==null||Ys.call(Or,S,Se);const he=Date.now(),Xe=gt.current.get(S)||{},He=Ql(Se,Xe,he);He&&(gt.current.set(S,{lastText:He.text,lastAt:he}),Pe.getState().addLog(S,He.text,null,"assistant_update"))}else if(Vt==="artifact")ee.url&&ee.name?((Dn=(Ks=Pe.getState()).addArtifact)==null||Dn.call(Ks,S,{name:ee.name,url:ee.url,size:ee.size,contentType:ee.contentType}),Pe.getState().addLog(S,`delivered: ${ee.name}`)):Pe.getState().addFile(S,{name:ee.summary||ee.kind||"artifact",type:ee.kind||"text",meta:ee.kind,content:ee.summary||""});else if(Vt==="preview")if(ee.kind==="browser_image"&&ee.base64){const Se=ee.base64.startsWith("data:")?ee.base64:`data:image/jpeg;base64,${ee.base64}`;Pe.getState().setPreviewImage(S,Se),(Fn=(es=Pe.getState()).addPreviewFrame)==null||Fn.call(es,S,{imageUrl:Se,label:ee.label||"Browser frame",message:ee.label||"Browser frame",timestamp:Date.now()})}else ee.kind==="browser"&&ee.url?Pe.getState().setPreviewUrl(S,ee.url):ee.html&&(Pe.getState().setPreview(S,ee.html),Pe.getState().setPreviewUrl(S,null),Pe.getState().setPreviewImage(S,null));else if(Vt==="final"||Vt==="done"){const Se=ee.terminalState;if(Vt==="final"&&ee.message){const he=String(ee.message||"").trim();he&&((ts=(Ut=Pe.getState()).setFinalAnswer)==null||ts.call(Ut,S,he),Pe.getState().addLog(S,he,null,"assistant_final"))}(rs=(Kt=Pe.getState()).setStreamingFile)==null||rs.call(Kt,S,null,null),(Js=(On=Pe.getState()).setLiveThought)==null||Js.call(On,S,""),gt.current.delete(S),Pe.getState().updateSessionStatus(S,Se==="failed_terminal"?"error":"completed")}else Vt==="error"&&(Pe.getState().addLog(S,`Error: ${ee.message||"unknown error"}`),Pe.getState().updateSessionStatus(S,"error"))}}}catch(Fe){console.error("[AgentMission] stream error:",Fe),Pe.getState().addLog(S,`Error: ${(Fe==null?void 0:Fe.message)||Fe}`),Pe.getState().updateSessionStatus(S,"error")}},[Us,se]);n.useEffect(()=>{dt.current=Lr},[Lr]);const Sn=n.useCallback(async l=>{var x,k;const c=String(l||"").trim();if(c)try{const{data:{session:R}}=await Et.auth.getSession(),W=R==null?void 0:R.access_token;await fetch($t("/api/agent-sdk-mission/close"),{method:"POST",headers:{"Content-Type":"application/json",...W?{Authorization:`Bearer ${W}`}:{}},body:JSON.stringify({sessionId:c})})}catch(R){console.warn("[AgentMission] terminate failed:",R)}finally{gt.current.delete(c),(k=(x=Pe.getState()).removeSession)==null||k.call(x,c),be(R=>R===c?null:R)}},[]),ua=n.useCallback(()=>{const l={id:`page-${Date.now()}`,nodes:[],edges:[]};Bt(c=>[...c,l]),je(!0)},[je]),pa=n.useCallback(l=>{Bt(c=>c.filter(x=>x.id!==l)),je(!0)},[je]),ha=n.useCallback(l=>{Bt(c=>{const x=c.findIndex(S=>S.id===l);if(x===-1)return c;const k=c[x],R={id:`page-${Date.now()}`,nodes:k.nodes.map(S=>({...S,id:`${S.id}-copy-${Date.now()}`})),edges:k.edges.map(S=>({...S,id:`${S.id}-copy-${Date.now()}`}))},W=[...c];return W.splice(x+1,0,R),W}),je(!0)},[je]),Vs=n.useCallback(()=>{var W;const l=`thread-${Date.now()}`,x=(((W=Nt[w])==null?void 0:W.nodes)||[]).length,k={x:100+x%2*900,y:100+Math.floor(x/2)*700},R={id:l,type:"threadNode",position:k,data:{title:"New Chat",messageCount:0,sourceCount:0,lastActivity:"Just now",chatHistory:[]}};Bt(S=>S.map((K,H)=>H===w?{...K,nodes:[...K.nodes,R]}:K)),je(!0)},[w,Nt,je]),Nn=n.useCallback(()=>{var W;const l=`notepad-${Date.now()}`,x=(((W=Nt[w])==null?void 0:W.nodes)||[]).length,k={x:100+x%3*700,y:100+Math.floor(x/3)*500},R={id:l,type:"blockNoteNode",position:k,width:400,height:300,data:{title:"Untitled",content:JSON.stringify([{type:"paragraph",content:"Start typing..."}])}};Bt(S=>S.map((K,H)=>H===w?{...K,nodes:[...K.nodes,R]}:K)),je(!0)},[w,Nt,je]),Ws=n.useCallback((l,c,x={})=>{const{broadcast:k=!0,flush:R=!1}=x||{};
56b(l,c),je(!0),ke(),k&&(g==null||g("node-data",{id:l,data:c})),R&&typeof(ke==null?void 0:ke.flush)=="function"&&ke.flush()},[b,je,ke,g]),Cn=n.useCallback(()=>{typeof(ke==null?void 0:ke.flush)=="function"&&ke.flush()},[ke]),{onNodeDrag:fa,onNodeDragStart:ga,onNodeDragStop:ma}=Nl({setNodes:O,setEdges:U,setIsDragging:Q,trackMouse:gs,debouncedSave:ke,setHasUnsavedChanges:je});Cl({nodes:_,updateEdgesWithoutHistory:q});const{handleGroupNodes:Xr,handleUngroupNode:xa,handleGroupTitleUpdate:A,handleGroupCollapseToggle:ut}=_l({nodes:_,edges:J,setNodes:O,setEdges:U,handleDeleteNode:cr,broadcastAuthoritativeState:Ce}),{onNodesChange:Tt,onEdgesChange:zr}=$l({edges:J,channel:Gr,isViewer:Te,setNodesAndEdges:Z,onNodesChangeDefault:P,onEdgesChangeDefault:Ne,broadcastAuthoritativeState:Ce,broadcastNodeChanges:mn,debouncedSave:ke,setHasUnsavedChanges:je}),{handleAddResponseToCanvas:Nr,addChatNode:gr,addNotepadNode:Cr,addStickyNoteNode:Dr,addVoiceNoteNode:_n,addFileNode:$n}=Rl({reactFlowInstance:m,setNodes:O,handleConnection:ae,broadcastAuthoritativeState:Ce}),dr=n.useRef([]),rt=n.useRef([]),[Zr,mr]=n.useState(null),Mi=n.useCallback(()=>{be(null),Re(!1),Pe.getState().setActiveSession(null)},[]);n.useCallback(()=>{mr(null),be(null),Re(!0)},[]);const Ui=n.useCallback(l=>{mr(null),Pe.getState().setActiveSession(l),be(l),Re(!0)},[]),[_r,rr]=n.useState([]),[Rn,ba]=n.useState({}),to=n.useCallback(async(l,c)=>{var K;if(!m||!(l!=null&&l.trim()))return;const x=Rn[c];if(x){const H=(K=m.getNode)==null?void 0:K.call(m,x);H&&m.setCenter(H.position.x+180,H.position.y+100,{zoom:1,duration:500});return}const k=`blocknote-${Date.now()}`;ba(H=>({...H,[c]:k}));let R;try{R=ui(l)}catch(H){console.error("Failed to convert answer to BlockNote:",H),ba(B=>{const We={...B};return delete We[c],We});return}const W=m.screenToFlowPosition({x:window.innerWidth/2,y:window.innerHeight/2}),S={id:k,type:"blockNoteNode",position:W,width:360,height:480,data:{title:"AI Response",content:JSON.stringify(R),initialContent:R,metadata:"From AI"}};O(H=>[...H,S]);try{const{error:H}=await Et.from("nodes").insert({id:S.id,board_id:C||window.location.pathname.split("/").pop(),type:S.type,position:S.position,data:S.data});H&&console.error("Error persisting pinned answer:",H)}catch(H){console.error("Failed to persist pinned answer:",H)}se==null||se("Pinned to board","success")},[m,Rn,O,C,se]),$r=!!y,ro=n.useRef(()=>{}),Vi=n.useMemo(()=>_r.length?e.jsx("div",{className:"imsg py-1",style:{"--imsg-bg":$r?"#0b0f17":"#ffffff","--imsg-recv":$r?"#242b38":"#e9e9eb","--imsg-recv-text":$r?"#ffffff":"#000000"},children:_r.map((l,c)=>{const x=_r[c-1],k=_r[c+1],R=(x==null?void 0:x.role)===l.role,W=!k||k.role!==l.role,S=l.role==="assistant"&&!l.content,K=l.role==="assistant",H=!!Rn[c];return e.jsxs("div",{className:"flex w-full flex-col items-start",children:[e.jsx("div",{className:`imsg-bubble ${l.role==="user"?"imsg-sent":"imsg-recv"} ${W?"imsg-tail":""}`,style:{marginTop:R?2:8},children:S?e.jsxs("span",{className:"imsg-typing","aria-label":"Typing",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}):K?e.jsx(mc,{textSize:"text-[15px]",proseSize:"prose-sm",children:l.content}):l.content}),K&&l.content&&e.jsx("div",{className:"mt-1 flex w-full items-center",children:e.jsxs("button",{type:"button",onClick:()=>to(l.content,c),title:H?"View on board":"Pin to board",className:`imsg-pin flex items-center gap-1.5 rounded-lg px-2 py-1 text-xs font-medium transition-colors ${H?"text-green-600 hover:bg-green-50":$r?"text-white/50 hover:text-white/80 hover:bg-white/10":"text-gray-500 hover:text-gray-800 hover:bg-gray-100"}`,children:[e.jsx(ll,{size:12}),H?"Pinned":"Pin To Board"]})}),K&&Array.isArray(l.sources)&&l.sources.length>0?e.jsx("div",{className:"mt-2 flex w-full flex-col gap-2 self-stretch",children:l.sources.map(B=>e.jsx(Ri,{item:B,darkMode:$r,onAdd:We=>ro.current(We)},B.id))}):null]},l.id||c)})}):null,[_r,to,$r,Rn]),[An,Tn]=n.useState([]),[Pn,ws]=n.useState(!1),[Ju,Hs]=n.useState(null),[so,Wi]=n.useState(!1),qs=n.useRef(0),[Gs,In]=n.useState({open:!1,loading:!1,error:null,feed:null});n.useEffect(()=>{if(!Zt||!Ot)return;const l=setTimeout(()=>{kt(""),mt(!1)},3500);return()=>clearTimeout(l)},[Ot,Zt]);const Fr=n.useRef(null),no=n.useRef(0),Qr=n.useRef(0);n.useEffect(()=>()=>{Fr.current&&clearTimeout(Fr.current)},[]);const En=n.useCallback(l=>{if(!l)return;const c=[l,...rt.current.filter(x=>x!==l)];rt.current=c.slice(0,6)},[]),Ln=n.useRef(Xr);n.useEffect(()=>{Ln.current=Xr},[Xr]);const ao=n.useCallback(l=>
56{const c=new Set((l||[]).filter(Boolean));c.size<2||(O(x=>x.map(k=>({...k,selected:c.has(k.id)}))),setTimeout(()=>{var x;return(x=Ln.current)==null?void 0:x.call(Ln)},80))},[O]),zn=n.useCallback(l=>{const c=String(l||"").trim();if(!c)return;if(j.length){const H=c.replace(/^\/agent\b/i,"").trim()||c,B=j;Oe(""),I([]),mr(null),Lr(H,{sessionId:v||void 0,attachments:B});return}if(v){const H=c.replace(/^\/agent\b/i,"").trim()||c;Oe(""),mr(null),Lr(H,{sessionId:v});return}if(/^\/agent(?:\s+|$)/i.test(c)){const H=c.replace(/^\/agent\b/i,"").trim();if(Oe(""),!H){se==null||se("Tell the agent what to do after /agent.","warning");return}Lr(H);return}const x=Yu(c);if(x){Oe(""),mr(null),kt(""),mt(!1),ws(!1),rr(H=>[...H,{role:"user",content:c},{role:"assistant",content:x}]),dr.current=[...dr.current,{role:"user",content:c},{role:"assistant",content:x}].slice(-12);return}const k=Zr,R=(k==null?void 0:k.kind)==="ad_discovery";if(!R){const H=qu(c);if(H){mr({kind:"ad_discovery",question:H.question,options:H.options.map(B=>B.label),originalPrompt:c,confidence:H.confidence,threshold:H.threshold}),Oe("");return}}const W=c.toLowerCase(),S=W.includes("creative images and ad copy")?{id:"creative_and_copy"}:W.includes("creative images only")?{id:"creative_only"}:W.includes("copy and competitor summary")?{id:"copy_summary"}:null,K=R?Gu({originalPrompt:(k==null?void 0:k.originalPrompt)||"",selectedOption:S,customAnswer:c}):c;Oe(""),(async()=>{var Bn,vs,Vt,ks,Mn,Xs,ns;const H=()=>{const X=Oc(K);return X?{...X,query:Yc(K,X.query,_)}:null};let B=null;try{const{data:{session:X}}=await Et.auth.getSession(),ee=X==null?void 0:X.access_token,Se=await fetch($t("/api/simple-chat"),{method:"POST",headers:{"Content-Type":"application/json",...ee?{Authorization:`Bearer ${ee}`}:{}},body:JSON.stringify({messages:Qc({prompt:K,history:dr.current,boardSummary:Zc(_)}),model:"google/gemini-3-flash-preview"})});let he="";if(Se.ok&&Se.body){const He=Se.body.getReader(),pr=new TextDecoder;let Me="";for(;;){const{done:lt,value:pt}=await He.read();if(lt)break;Me+=pr.decode(pt,{stream:!0});const Dt=Me.split(`
57`);Me=Dt.pop()||"";for(const ht of Dt){const Wt=ht.trim();if(!Wt.startsWith("data:"))continue;const Ct=Wt.slice(5).trim();if(Ct!=="[DONE]")try{const Ht=(ks=(Vt=(vs=(Bn=JSON.parse(Ct))==null?void 0:Bn.choices)==null?void 0:vs[0])==null?void 0:Vt.delta)==null?void 0:ks.content;Ht&&(he+=Ht)}catch{}}}}const Xe=ed(he);Xe&&Xe.mode==="videos"?B={query:Xe.query,counts:{youtube:Xe.count,pdf:0},explicitCounts:{youtube:!0,pdf:!1},order:["youtube"]}:Xe&&Xe.mode==="pdfs"?B={query:Xe.query,counts:{youtube:0,pdf:Xe.count},explicitCounts:{youtube:!1,pdf:!0},order:["pdf"]}:Xe&&Xe.mode==="answer"?B=null:B=H()}catch{B=H()}const We=B?Bc(B):K,ie=(Mn=Y.current)==null?void 0:Mn.getBoundingClientRect(),Je={x:Number((ie==null?void 0:ie.left)||0),y:Number((ie==null?void 0:ie.top)||0)},ur=((Xs=m==null?void 0:m.getViewport)==null?void 0:Xs.call(m))||{x:0,y:0,zoom:1},yt=lr.current,Rr=Math.min(Number((ie==null?void 0:ie.bottom)||Be),de.bottom)-140,Or=Number(yt==null?void 0:yt.x)>=Math.max(Number((ie==null?void 0:ie.left)||0),de.left)&&Number(yt==null?void 0:yt.x)<=Math.min(Number((ie==null?void 0:ie.right)||Ge),de.right)&&Number(yt==null?void 0:yt.y)>=Math.max(Number((ie==null?void 0:ie.top)||0),de.top)&&Number(yt==null?void 0:yt.y)<=Rr,Ys=X=>m!=null&&m.screenToFlowPosition?m.screenToFlowPosition(X):od(X,ur,Je),Ks=nd({nodes:_,pointer:Or?Ys(yt):null,fallback:Ys(xe)}),Dn=((ns=m==null?void 0:m.flowToScreenPosition)==null?void 0:ns.call(m,Ks.anchor))||ad(Ks.anchor,ur,Je),es=we(Dn);mr(null);const Fn=(_||[]).map(X=>{var ee,Se,he,Xe,He,pr;return{id:X.id,type:X.type,kind:Mu[X.type]||X.type,title:((ee=X==null?void 0:X.data)==null?void 0:ee.title)||((Se=X==null?void 0:X.data)==null?void 0:Se.label)||((he=X==null?void 0:X.data)==null?void 0:he.url)||((pr=(He=(Xe=X==null?void 0:X.data)==null?void 0:Xe.content)==null?void 0:He.slice)==null?void 0:pr.call(He,0,60))||""}});Qr.current+=1,D(!0),kt(""),no.current+=1;const Ut=`assistant-${Date.now()}-${no.current}`,ts=`artifact-${Ut}`,Kt=B?Uc(B):null,rs=[];B&&Hs({id:ts,query:B.query,items:[],expected:{...B.counts},status:"searching"});const On=Kc(_),Js=X=>{if(!B||!Kt)return!1;const ee=dd(X);return!ee||Jc(ee,On)||!Kt.accept(X)?!1:(Hs(Se=>!Se||Se.id!==ts||Se.items.some(he=>
57he.id===ee.id)?Se:{...Se,items:[...Se.items,ee]}),rs.some(Se=>Se.id===ee.id)||rs.push(ee),!0)};if(Fr.current&&(clearTimeout(Fr.current),Fr.current=null),Qt(es),B){const X=[];B.counts.youtube>0&&X.push({id:`act-${X.length}`,tool:"youtube",stage:"searching",label:`Searching for ${B.counts.youtube} video${B.counts.youtube===1?"":"s"}`}),B.counts.pdf>0&&X.push({id:`act-${X.length}`,tool:"pdf",stage:"searching",label:`Searching for ${B.counts.pdf} PDF${B.counts.pdf===1?"":"s"}`}),qs.current=X.length,Tn(X),ws(!0),mt(!0)}else qs.current=0,Tn([]),ws(!1);if(rr(X=>[...X,{role:"user",content:K},{role:"assistant",content:"",id:Ut}]),!B){(async()=>{var ee,Se;let X="";try{const{data:{session:he}}=await Et.auth.getSession(),Xe=he==null?void 0:he.access_token,He="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inpuc2VkanR6aHhiZnNjcWlodGxwIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjAzNzAwMTMsImV4cCI6MjA3NTk0NjAxM30.oR3-P5ydxgJ_372Iae4zg4lKgw06fX-gsLHxQ4GzKl8",pr=(_||[]).map(Wt=>({id:Wt.id,type:Wt.type,data:cl(Wt)})),Me=new Date,lt=await fetch(`${Et.supabaseUrl}/functions/v1/chat-completion`,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":Ut,...He?{apikey:He}:{},...Xe?{Authorization:`Bearer ${Xe}`}:{}},body:JSON.stringify({messages:[...dr.current,{role:"user",content:K}],threadNodeId:`assistant-${C}`,boardId:C,model:et,connectedNodesData:pr,connectedEdges:[],userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userLocalTime:Me.toLocaleString()})});if(!lt.ok||!lt.body)throw new Error(`Assistant failed (${lt.status})`);const pt=lt.body.getReader(),Dt=new TextDecoder;let ht="";for(;;){const{done:Wt,value:Ct}=await pt.read();if(Wt)break;ht+=Dt.decode(Ct,{stream:!0});const Ht=ht.split(`
58`);ht=Ht.pop()||"";for(const Br of Ht){const js=Br.trim();if(!js.startsWith("data:"))continue;const Zs=js.slice(5).trim();if(Zs!=="[DONE]")try{const nt=JSON.parse(Zs),Ft=(Se=(ee=nt==null?void 0:nt.choices)==null?void 0:ee[0])==null?void 0:Se.delta;Ft!=null&&Ft.content&&(X+=Ft.content,rr(as=>as.map(Qs=>Qs.id===Ut?{...Qs,content:X}:Qs)))}catch{}}}X.trim()||(X="I couldn't find an answer to that. Try rephrasing?",rr(Wt=>Wt.map(Ct=>Ct.id===Ut?{...Ct,content:X}:Ct)))}catch(he){console.error("[BoardAssistant] error:",he),X="Sorry, something went wrong answering that.",rr(Xe=>Xe.map(He=>He.id===Ut?{...He,content:X}:He))}finally{const he=[{role:"user",content:K}];X.trim()&&he.push({role:"assistant",content:X.trim()}),dr.current=[...dr.current,...he].slice(-12),Qr.current=Math.max(0,Qr.current-1),Qr.current===0&&(D(!1),mt(!1),kt(""))}})();return}B||Rc();let Fe=!1;const ss=()=>{Fe||(Fe=!0,B||Ac())},st=X=>new Promise(ee=>setTimeout(ee,X));let zt=Promise.resolve();const va=X=>(zt=zt.then(async()=>{var ee;try{let{screenPoint:Se,resolvedAction:he}=zo(X,{reactFlowInstance:m,screenAnchor:es,screenOffset:Je});if((he.op==="create_node"||he.op==="move")&&Number.isFinite(Number(he.x))&&Number.isFinite(Number(he.y))&&(m!=null&&m.setCenter)){const He=(ee=m.getViewport)==null?void 0:ee.call(m),pr=Math.max(.55,Math.min(1.15,Number((He==null?void 0:He.zoom)||1)));m.setCenter(Number(he.x)+180,Number(he.y)+140,{zoom:pr,duration:460}),await st(420),{screenPoint:Se,resolvedAction:he}=zo(he,{reactFlowInstance:m,screenAnchor:es,screenOffset:Je})}const Xe=qs.current===0;mt(!0),kt(Xe?Uu(he):""),Se&&(Qt(we(Se)),await st(520)),he.op==="group"?((he.ids||[]).forEach(He=>tn(He)),ao(he.ids||[]),(he.ids||[]).forEach(He=>En(He))):(ka(he,{reactFlowInstance:m,screenAnchor:es,screenOffset:Je}),tn(he.id||he.source),En(he.id||he.source),he.op==="connect"&&(tn(he.target),En(he.target))),typeof Ce=="function"&&setTimeout(()=>Ce(),0),await st(260)}catch(Se){console.error("[CanvasPrompt] choreography error:",Se)}}),!0);(async()=>{let X="",ee=!1,Se=!1;const he=B&&B.counts.pdf>0?cd({request:B,batchId:ts}).then(Me=>({actions:Me,error:null})).catch(Me=>({actions:[],error:Me instanceof Error?Me:new Error(String(Me||"PDF search failed"))})):Promise.resolve({actions:[],error:null});let Xe=!1;const He=async()=>{if(Xe||!B||!Kt)return;Xe=!0;const Me=await he,lt=[];Me.actions.forEach(ht=>{Js(ht)&&(ee=!0,lt.push(ht.title||ht.fileName||"PDF"))});const pt=Kt.accepted().pdf,Dt={id:`act-${qs.current++}`,tool:"pdf",stage:pt>
580?"found":"error",label:pt>0?`Found ${pt} PDF${pt===1?"":"s"}`:"No open-access PDF found",items:lt.length?lt:void 0};Tn(ht=>[...ht,Dt]),ws(!0),Me.error&&console.error("[CanvasPrompt] PDF discovery error:",Me.error)},pr=()=>{Kt&&Hs(Me=>(Me==null?void 0:Me.id)===ts?{...Me,status:Kt.isSatisfied()?"ready":"partial"}:Me)};try{const{data:{session:Me}}=await Et.auth.getSession(),lt=Me==null?void 0:Me.access_token,pt=await fetch($t("/api/canvas-agent"),{method:"POST",headers:{"Content-Type":"application/json",...lt?{Authorization:`Bearer ${lt}`}:{}},body:JSON.stringify({messages:[...dr.current,{role:"user",content:We}],canvasSummary:Fn,recentNodeIds:rt.current,model:et})});if(!pt.ok){const Ct=await pt.text();throw new Error(`Canvas agent failed (${pt.status}): ${Ct}`)}if(!pt.body)throw new Error("No response body");const Dt=pt.body.getReader(),ht=new TextDecoder;let Wt="";for(;;){const{done:Ct,value:Ht}=await Dt.read();if(Ct)break;Wt+=ht.decode(Ht,{stream:!0});const Br=Wt.split(`
59`);Wt=Br.pop()||"";for(const js of Br){if(!js.trim()||!js.startsWith("data:"))continue;const Zs=js.slice(5).trim();if(Zs!=="[DONE]")try{const nt=JSON.parse(Zs);if(nt.type==="action"&&nt.action)(B?Js(nt.action):va(nt.action))&&(ee=!0);else if(nt.type==="text-delta")X+=nt.delta||"",B||rr(Ft=>Ft.map(as=>as.id===Ut?{...as,content:X}:as));else if(nt.type==="question")ee=!0,mr({question:String(nt.question||""),options:Array.isArray(nt.options)?nt.options.slice(0,3).map(Ft=>String(Ft)):[]});else if(nt.type==="activity"&&nt.activity){const Ft=B?Vc(nt.activity,B):nt.activity,as={id:`act-${qs.current++}`,tool:Ft.tool||"generic",stage:Ft.stage||"working",label:String(Ft.label||""),items:Array.isArray(Ft.items)?Ft.items:void 0};Tn(Qs=>[...Qs,as]),ws(!0),mt(!0),kt("")}else nt.type==="error"&&(Se=!0,console.error("[CanvasPrompt] stream error:",nt.error))}catch{}}}if(B&&Kt)await He(),pr(),X=Oo(B,Kt.accepted()),rr(Ct=>Ct.map(Ht=>Ht.id===Ut?{...Ht,content:X,sources:rs.slice()}:Ht));else if(!X.trim()){const Ct=Se?"I hit a snag while answering that. Please try again.":ee?"Done.":"I'm here. What would you like me to do on the canvas?";X=Ct,rr(Ht=>Ht.map(Br=>Br.id===Ut?{...Br,content:Ct}:Br))}}catch(Me){if(console.error("[CanvasPrompt] Canvas agent error:",Me),B&&Kt)await He(),pr(),X=Oo(B,Kt.accepted()),rr(lt=>lt.map(pt=>pt.id===Ut?{...pt,content:X,sources:rs.slice()}:pt));else{const lt="Sorry, something went wrong. Please try again.";X=lt,rr(pt=>{const Dt=[...pt];for(let ht=Dt.length-1;ht>=0;ht--)if(Dt[ht].id===Ut||Dt[ht].role==="assistant"){Dt[ht]={...Dt[ht],content:lt};break}return Dt})}}finally{try{await Promise.race([zt,new Promise(lt=>setTimeout(lt,6e3))])}catch{}ss(),Fr.current&&clearTimeout(Fr.current),Fr.current=setTimeout(()=>ws(!1),1800),typeof Ce=="function"&&setTimeout(()=>Ce(),0);const Me=[{role:"user",content:K}];X.trim()&&Me.push({role:"assistant",content:X.trim()}),dr.current=[...dr.current,...Me].slice(-12),Qr.current=Math.max(0,Qr.current-1),Qr.current===0&&(D(!1),mt(!1),kt(""))}})()})()},[et,C,_,Zr,j,m,Lr,se,En,Ce,ao,v,xe,de,we,lr,Be,Ge]),Hi=n.useCallback(l=>{const c=String(l||"").trim();if(c){if((Zr==null?void 0:Zr.kind)==="ad_discovery"){zn(c);return}mr(null),zn(c)}},[zn,Zr]),oo=n.useCallback(()=>{if(!m||Te)return;const l=`group-${Date.now()}`,c=900,x=900,k={x:60,y:100},R=m.screenToFlowPosition({x:window.innerWidth/2,y:window.innerHeight/2}),W={id:l,type:"groupNode",zIndex:0,position:{x:R.x-c/2,y:R.y-x/2},style:{width:c,height:x},data:{title:"New Group",isCollapsed:!1,childCount:0,minWidth:400,minHeight:300,onDelete:cr,onTitleUpdate:A,onCollapseToggle:ut,onOptimize:S=>{O(K=>{const H=K.filter(ie=>ie.parentNode===S),B=Ao(H,k);return B?K.map(ie=>ie.parentNode===S&&B.positionedNodes.find(ur=>ur.id===ie.id)||ie).map(ie=>ie.id===S?{...ie,style:{...ie.style,width:B.groupWidth,height:B.groupHeight}}:ie):K})},onResizeEnd:(S,K)=>{O(H=>H.map(B=>B.id===S?{...B,style:{...B.style,width:K.width,height:K.height}}:B))}}};O(S=>[...S,W]),setTimeout(()=>{Ce()},0)},[m,Te,O,cr,A,ut,Ce]);Al({isViewer:Te,handleGroupNodes:Xr,setActiveTool:re}),Tl({reactFlowInstance:m,lastMousePos:lr,isViewer:Te,setNodes:O,setChannelModal:fe,setWebsiteModal:Lt,handleConnection:ae,triggerDocumentProcessing:G,broadcastAuthoritativeState:Ce,showToast:se});const{onDrop:io,onDragOver:lo}=Pl({reactFlowInstance:m,boardId:C,isViewer:Te,setNodes:O,setHasUnsavedChanges:je,showToast:se,handleDeleteNode:cr,handleAddResponseToCanvas:Nr,handleConnection:ae,triggerDocumentProcessing:G,broadcastEvent:g,broadcastAuthoritativeState:Ce}),ya=n.useCallback((l,c)=>{if(!l)return;const x=String(l.platform||"").toLowerCase(),k=String(l.url||"");let R;if(x==="youtube"){const W=k.match(/(?:youtube\.com\/(?:watch\?v=|shorts\/|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);R={id:`youtube-${Date.now()}`,type:"youtubeNode",position:c,width:360,height:280,data:{videoId:W?W[1]:"",url:k,processingStatus:null,aiProcessed:!1,metadata:{timestamp:Date.now()}}}}else x==="tiktok"?R={id:`tiktok-${Date.now()}`,type:"tiktokNode",position:c,width:220,height:390,data:{url:k,videoUrl:k,title:l.caption||"TikTok Video",processingStatus:null,aiProcessed:!1,metadata:{timestamp:Date.now()}}}:R={id:`social-${Date.now()}`,type:"socialNode",position:c,data:{...l,loading:!1,aiProcessed:!1,title:l.author||l.caption||"Social post"}};O(W=>[...W,R]),je(!0),ke(),window.setTimeout(()=>Ce==null?void 0:Ce(),0)},[O,je,ke,Ce]),co=n.useCallback(l=>{var H;const c=l.dataTransfer.getData(Ai);if(c){if(l.preventDefault(),l.stopPropagation(),Te||!m)return;let B=null;try{B=JSON.parse(c)}catch(ie){console.error("[BoardCanvas] bad social-post drop payload:",ie)}if(!B)return;const We=m.screenToFlowPosition({x:l.clientX,y:l.clientY});ya(B,We),l.dataTransfer.dropEffect="copy";return}const x=l.dataTransfer.getData(Fa);if(!x){io(l);return}if(l.preventDefault(),l.stopPropagation(),Te||!m)return;const k=pd(x);if(!k){se==null||se("That source could not be added.","error");return}const R=m.screenToFlowPosition({x:l.clientX,y:l.clientY}),W=`${Date.now()}`,S=Uo(k,R,W),K=(H=Y.current)==null?void 0:H.getBoundingClientRect();ka(S,{reactFlowInstance:m,screenAnchor:{x:l.clientX,y:l.clientY},screenOffset:{x:Number((K==null?void 0:K.left)||0),y:Number((K==null?void 0:K.top)||0)}}),Hs(B=>B&&{...B,items:B.items.map(We=>We.id===k.id?{...We,placed:!0}:We)}),je(!0),ke(),window.setTimeout(()=>{tn(S.id),Ce==null||Ce()}
59,0),l.dataTransfer.dropEffect="copy"},[Ce,ke,Te,io,m,je,se,ya]);n.useEffect(()=>{const l=c=>{const x=c.detail||{},k=String(x.url||"").trim();k&&(In({open:!0,loading:!0,error:null,feed:{platform:x.platform||"",posts:[]}}),(async()=>{try{const{data:{session:R}}=await Et.auth.getSession(),W=R==null?void 0:R.access_token,S=await fetch($t("/api/social-profile"),{method:"POST",headers:{"Content-Type":"application/json",...W?{Authorization:`Bearer ${W}`}:{}},body:JSON.stringify({url:k})});if(!S.ok){const H=await S.json().catch(()=>({}));throw new Error((H==null?void 0:H.message)||`Request failed (${S.status})`)}const K=await S.json();In({open:!0,loading:!1,error:null,feed:K})}catch(R){In(W=>({...W,loading:!1,error:R&&R.message||"Couldn't fetch that profile."}))}})())};return window.addEventListener("chatgrid:open-profile-feed",l),()=>window.removeEventListener("chatgrid:open-profile-feed",l)},[]);const uo=n.useRef(0),po=n.useCallback(l=>{var We;if(Te||!m)return;const c=(We=Y.current)==null?void 0:We.getBoundingClientRect(),x=Number((c==null?void 0:c.left)||0)+Number((c==null?void 0:c.width)||900)/2,k=Number((c==null?void 0:c.top)||0)+Number((c==null?void 0:c.height)||600)/2,R=uo.current++%6*34,W={x:x+R,y:k+R},S=m.screenToFlowPosition?m.screenToFlowPosition(W):{x:0,y:0},K=`${Date.now()}-${uo.current}`,H=Uo(l,S,K);ka(H,{reactFlowInstance:m,screenAnchor:W,screenOffset:{x:Number((c==null?void 0:c.left)||0),y:Number((c==null?void 0:c.top)||0)}});const B=ie=>ie.id===l.id?{...ie,placed:!0}:ie;Hs(ie=>ie&&{...ie,items:ie.items.map(B)}),rr(ie=>ie.map(Je=>Je.sources?{...Je,sources:Je.sources.map(B)}:Je)),je(!0),ke(),window.setTimeout(()=>{tn(H.id),Ce==null||Ce()},0),se==null||se("Added to board","success")},[Ce,ke,Te,m,je,se]);n.useEffect(()=>{ro.current=po},[po]);const ho=n.useCallback(l=>{if(Array.from(l.dataTransfer.types||[]).includes(Fa)){l.preventDefault(),l.stopPropagation(),l.dataTransfer.dropEffect="copy";return}lo(l)},[lo]);Bu({reactFlowInstance:m,isViewer:Te,setNodes:O,setHasUnsavedChanges:je,showToast:se,broadcastEvent:g});const{handleChannelImport:fo,handleWebsiteImport:go}=Il({reactFlowInstance:m,boardId:C,setNodes:O,setChannelModal:fe,setWebsiteModal:Lt,handleDeleteNode:cr,broadcastAuthoritativeState:Ce,showToast:se,lastMousePos:lr}),{handleFileUpload:wa}=El({reactFlowInstance:m,boardId:C,setNodes:O,setHasUnsavedChanges:je,handleDeleteNode:cr,handleConnection:ae,triggerDocumentProcessing:G,broadcastAuthoritativeState:Ce,showToast:se,updateNodeData:b,broadcastEvent:g}),qi=n.useCallback((l,c)=>{if(vr){window.dispatchEvent(new CustomEvent("comment-select-node",{detail:{nodeId:c.id}}));const x=l.currentTarget.getBoundingClientRect();Is(c.id,x.left+x.width/2,x.top+x.height/2),l.stopPropagation()}},[vr,Is]),Gi=n.useCallback(l=>{const c=l.filter(x=>{var k;return(k=x.data)==null?void 0:k.storagePath});c.length>0&&Et.storage.from("board-files").remove(c.map(x=>x.data.storagePath))},[]);n.useEffect(()=>{const l=x=>{(x.metaKey||x.ctrlKey)&&x.preventDefault()},c=x=>x.preventDefault();return window.addEventListener("wheel",l,{passive:!1}),window.addEventListener("gesturestart",c),window.addEventListener("gesturechange",c),window.addEventListener("gestureend",c),()=>{window.removeEventListener("wheel",l),window.removeEventListener("gesturestart",c),window.removeEventListener("gesturechange",c),window.removeEventListener("gestureend",c)}},[]),n.useEffect(()=>{const l=c=>{if(tr&&!Te)return typeof(ke==null?void 0:ke.flush)=="function"&&ke.flush(),c.preventDefault(),c.returnValue="You have unsaved changes. Are you sure you want to leave?",c.returnValue};return window.addEventListener("beforeunload",l),()=>window.removeEventListener("beforeunload",l)},[tr,Te,ke]),n.useEffect(()=>{if(V.current){V.current=!1;return}!Yt&&m&&!Te&&ke()},[_,Yt,ke,m,Te]),n.useEffect(()=>()=>{tr&&m&&C&&Ll(C,m.toObject()).catch(console.error)},[C,m,tr]);const mo=n.useMemo(()=>dl(_).sort((l,c)=>{const x=l.zIndex||0;return(c.zIndex||0)-x}),[_]),Yi=(l,c)=>{l.dataTransfer.setData("application/reactflow",c),l.dataTransfer.effectAllowed="move"};n.useCallback(l=>{const c=l.length,x={};l.forEach((k,R)=>{x[k.id]=100+(c-R)}),O(k=>k.map(R=>x[R.id]!==void 0?{...R,zIndex:x[R.id]}:R)),je(!0),ke()},[O,je,ke]);const Ki=n.useCallback((l,c)=>{O(x=>{const k=[...x].sort((H,B)=>{var Je,ur;
59const We=H.zIndex||0,ie=B.zIndex||0;return We!==ie?ie-We:(((Je=H.position)==null?void 0:Je.y)||0)-(((ur=B.position)==null?void 0:ur.y)||0)}),R=k.findIndex(H=>H.id===l);if(R===-1)return x;const[W]=k.splice(R,1);let S=R;c==="front"?S=0:c==="back"?S=k.length:c==="forward"?S=Math.max(0,R-1):c==="backward"&&(S=Math.min(k.length,R+1)),k.splice(S,0,W);const K=k.length+100;return k.map((H,B)=>({...H,zIndex:K-B}))}),je(!0),ke()},[O,je,ke]),xo=(l=!1,c=!1)=>e.jsx(Vd,{isOwner:un,isViewer:Te,activeTool:le,setActiveTool:re,addChatNode:l?Vs:gr,addNotepadNode:l?Nn:Cr,addStickyNoteNode:l?void 0:Dr,addFileNode:$n,addGroupNode:l?void 0:oo,onDragStart:l?void 0:Yi,onShowLinkPrompt:()=>jt(!0),onFileUpload:wa,fileCount:mo.length,onOpenLibrary:void 0,isDocsView:l,workspaceOffset:r,promptValue:ce,onPromptChange:Oe,onPromptSubmit:zn,promptAttachments:j,onAttachFiles:ca,onRemoveAttachment:da,promptPlaceholder:v?"Message this task...":"Ask ChatGrid...",promptFocusKey:v||"operator",promptDisabled:!1,operatorQuestion:v?null:Zr,onOperatorAnswer:Hi,onDismissOperatorQuestion:()=>mr(null),missionSession:null,onExpandMission:()=>{},isMissionTerminalActive:!0,missionColumnWidth:ar,centerPrompt:!c,dockBottomRight:c,hidePromptTools:c,promptDarkModeOverride:$r});return Yt?e.jsx("div",{className:"flex items-center justify-center h-screen bg-white dark:bg-surface text-gray-900 dark:text-white",children:"Loading board..."}):Tr==="docs"?e.jsxs(ko.Provider,{value:{channel:Gr,isViewer:Te,currentUser:ir,persistNodeData:Ws,flushSave:Cn,openLibraryModal:l=>{Mt(l)}},children:[e.jsxs("div",{style:{...Fs,position:"relative",background:y?"var(--surface)":"#f3f4f6"},children:[e.jsx(jo,{boardName:Ds,onBack:pn,boards:zs,currentBoardId:C,onSwitchBoard:qr,onRenameBoard:tt,onUpdateSharing:Ls,isPublic:ne==null?void 0:ne.is_public,accessLevel:ne==null?void 0:ne.public_access_level,isSaving:er,hasUnsavedChanges:tr,presenceUsers:gn,currentUserId:ir==null?void 0:ir.id,ownerId:ne==null?void 0:ne.user_id,isViewer:Te,isGuest:fs,isBoardPublished:hs,onToggleComments:()=>wr(!St),isCommentPanelOpen:St,showCredits:!0,isDocsView:!0,layoutOffset:fn,showSidebarToggle:d,onRevealSidebar:p}),e.jsx(So,{isSaving:er,hasUnsavedChanges:tr,leftOffset:r}),e.jsx(No,{toasts:Ve,onRemoveToast:Sr}),Hr&&e.jsx(Vo,{identity:Hr}),e.jsxs("div",{style:{height:"100%",paddingTop:"0px"},children:[" ",e.jsx(zl,{boardId:C,pages:Nt,setPages:Bt,isViewer:Te,onAddPage:ua,onDeletePage:pa,onDuplicatePage:ha,currentPageIndex:w,onPageChange:ge,onAddNotepad:Nn,onAddChat:Vs,onOpenLibrary:void 0,onShowLinkPrompt:()=>jt(!0),onFileUpload:wa,libraryFiles:mo,showLegacyAiRail:!1})]}),e.jsx(Co,{isOpen:xt.isOpen,channelUrl:xt.url,onClose:()=>fe({isOpen:!1,url:""}),onImport:fo}),e.jsx(_o,{isOpen:ze.isOpen,websiteUrl:ze.url,onClose:()=>Lt({isOpen:!1,url:""}),onImport:go}),e.jsx(To,{isOpen:us,linkInputValue:fr,onLinkInputChange:yr,onSubmit:Ir,onClose:()=>{jt(!1),yr("")}}),xo(!0)]}),e.jsx($o,{isActive:vr,onCancel:()=>Ar(!1)}),(hs||fs||(ne==null?void 0:ne.is_public))&&e.jsx(Ro,{boardId:C,isOpen:St,onClose:()=>wr(!1),nodes:_,onSelectionModeChange:l=>{Ar(l),l||or(new Set)},highlightedNodeIds:kr,onFocusNodes:it})]}):e.jsxs(ko.Provider,{value:{channel:Gr,isViewer:Te,currentUser:ir,persistNodeData:Ws,flushSave:Cn,openLibraryModal:l=>{Mt(l)}},children:[e.jsxs("div",{ref:Y,className:`${le==="select"?"select-tool-active":""} ${vr?"comment-selection-mode":""}`,style:{...Fs,position:"relative",backgroundColor:ul(u,y),overscrollBehaviorX:"none"},onDrop:co,onDragOver:ho,onMouseMove:gs,onMouseDown:gs,children:[kn&&e.jsx("div",{className:"fixed inset-0 z-[10000] transition-opacity duration-150",style:{background:y?"var(--surface)":"#f5f5f5",opacity:1}}),e.jsx(Dl,{channel:Gr,mySessionId:la,reactFlowInstance:m}),e.jsx(Fl,{checkmarkAnimations:cn}),Jr&&e.jsx(Ol,{node:Jr,nodes:_,onClose:()=>{Ms(null),bs(null)},darkMode:y,collaboration:xs}),!h&&!Jr&&e.jsxs(e.Fragment,{children:[e.jsx(jo,{boardName:Ds,onBack:pn,boards:zs,currentBoardId:C,onSwitchBoard:qr,onRenameBoard:tt,onUpdateSharing:Ls,isPublic:ne==null?void 0:ne.is_public,accessLevel:ne==null?void 0:ne.public_access_level,isSaving:er,hasUnsavedChanges:tr,presenceUsers:gn,currentUserId:ir==null?void 0:ir.id,ownerId:ne==null?void 0:ne.user_id,isViewer:Te,isGuest:fs,isBoardPublished:hs,onToggleComments:()=>wr(!St),isCommentPanelOpen:St,showCredits:!0,layoutOffset:fn,showSidebarToggle:d,onRevealSidebar:p}),e.jsx(Bl,{nodes:_,onGroup:Xr}),e.jsx(Ml,{nodes:_,colorLegend:jr,onUpdateLegend:Os,onNavigateToNode:(l,c)=>De(l,c),onRenameNode:ia}),e.jsx(So,{isSaving:er,hasUnsavedChanges:tr,leftOffset:r}),e.jsx(tc,{isVisible:Zt&&Le,isProcessing:me,response:Ot,darkMode:y,showBubble:!!Ot&&!Pn,position:Ke,onPositionChange:l=>Qt(we(l)),onClose:()=>{mt(!1),kt("")}}),e.jsx(ai,{open:!h&&Pn&&Le&&!so,lines:An,position:Ke,bounds:de,placement:"cursor",darkMode:y}),h?null:e.jsx(Zd,{darkMode:y,workspaceOffset:r,activeTool:le,onSetTool:re,onAddChat:()=>gr(),onAddNote:Cr,onAddSticky:l=>Dr(l),onAddGroup:oo,onUpload:wa,onShowLinkPrompt:()=>jt(!0),onAddVoiceNote:(l,c)=>_n(l,c),onAddImage:void 0}),h?null:e.jsx(ru,{open:Gs.open,onClose:()=>In(l=>({...l,open:!1})),darkMode:y,loading:Gs.loading,error:Gs.error,feed:Gs.feed,onAddPost:l=>{const c=Gs.feed||{},x=(m==null?void 0:m.screenToFlowPosition({x:window.innerWidth/2,y:window.innerHeight/2}))||{x:200,y:200};ya({platform:c.platform,url:l.url,author:c.author,authorHandle:c.authorHandle,avatarUrl:c.avatarUrl,caption:l.title,thumbnailUrl:l.thumbnailUrl,mediaUrl:l.url,likeCount:l.likeCount,viewCount:l.viewCount,commentCount:l.commentCount},x)}}),h?null:e.jsx(Qd,{open:so,onToggle:()=>Wi(l=>!l),onNewChat:()=>{rr([]),ba({})},darkMode:$r,conversation:Vi,hasMessages:_r.length>0,scrollSignal:`${_r.length}:${((wo=(yo=_r[_r.length-1])==null?void 0:yo.content)==null?void 0:wo.length)||0}:${An.length}:${Pn?1:0}
59`,composer:xo(!1,!0),activity:Pn&&An.length>0?e.jsx("div",{className:"mt-3",children:e.jsx(ai,{inline:!0,open:!0,lines:An,darkMode:$r})}):null})]}),e.jsxs(pl,{onInit:ue,nodes:_,edges:J,onNodesChange:Tt,onEdgesChange:zr,onConnect:$e,onConnectStart:bt,onConnectEnd:At,onNodeClick:qi,onNodeContextMenu:xn,onEdgeContextMenu:Er,onNodeDrag:fa,onNodeDragStart:ga,onNodeDragStop:ma,onNodesDelete:Gi,onDrop:co,onDragOver:ho,nodeTypes:gl,edgeTypes:fl,connectionLineComponent:Ul,defaultViewport:Pr||void 0,minZoom:.01,maxZoom:4,panOnDrag:le==="pan",selectionOnDrag:le==="select",panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,nodesDraggable:!Te,elementsSelectable:!Te,nodesConnectable:!Te,edgesFocusable:!Te,edgesUpdatable:!Te,deleteKeyCode:Te?null:["Backspace","Delete"],defaultEdgeOptions:hl,multiSelectionKeyCode:["Shift"],selectionKeyCode:["Shift"],elevateNodesOnSelect:!1,onMoveEnd:aa,children:[e.jsx(ml,{darkMode:y,canvasPattern:f,canvasColor:u,canvasSize:$}),e.jsx(Vl,{nodes:_,onTitleUpdate:A,onCollapseToggle:ut,onOptimize:l=>{const c={x:60,y:100};O(x=>{const k=x.filter(S=>S.parentNode===l),R=Ao(k,c);return R?x.map(S=>S.parentNode===l&&R.positionedNodes.find(H=>H.id===S.id)||S).map(S=>S.id===l?{...S,style:{...S.style,width:R.groupWidth,height:R.groupHeight}}:S):x})}}),e.jsx(Wl,{})]},C),!h&&(ye||v)&&!Jr?e.jsx(Wu,{darkMode:y,onBackToOperator:Mi,onSelectTask:Ui,onTerminateTask:Sn,selectedTaskId:v,sessions:at,workspaceOffset:r,workspaceReserve:0}):null,e.jsx(Hl,{contextMenu:Ae,onClose:()=>ve(null),onUngroupNode:xa,onDisconnectNode:yn,onDeleteNode:cr,onDeleteEdge:bn,onColorNode:oa,onLayering:Ki}),e.jsx(ql,{nodes:_,reactFlowInstance:m,reactFlowWrapper:Y}),e.jsx(No,{toasts:Ve,onRemoveToast:Sr}),Hr&&e.jsx(Vo,{identity:Hr}),e.jsx(Co,{isOpen:xt.isOpen,channelUrl:xt.url,onClose:()=>fe({isOpen:!1,url:""}),onImport:fo}),e.jsx(_o,{isOpen:ze.isOpen,websiteUrl:ze.url,onClose:()=>Lt({isOpen:!1,url:""}),onImport:go}),e.jsx(To,{isOpen:us,linkInputValue:fr,onLinkInputChange:yr,onSubmit:Ir,onClose:()=>{jt(!1),yr("")}})]}),e.jsx($o,{isActive:vr,onCancel:()=>Ar(!1)}),(hs||fs||(ne==null?void 0:ne.is_public))&&e.jsx(Ro,{boardId:C,isOpen:St,onClose:()=>wr(!1),nodes:_,onSelectionModeChange:l=>{Ar(l),l||or(new Set)},highlightedNodeIds:kr,onFocusNodes:it})]})}const Hp=Object.freeze(Object.defineProperty({__proto__:null,default:Ku},Symbol.toStringTag,{value:"Module"}));export{wc as B,Cc as S,Ku as a,Hp as b,Ed as f,Fd as u};

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.