tide-commander 1.154.0 → 1.156.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/dist/assets/{BossLogsModal-Bo0pUCWU.js → BossLogsModal-CwkpdKon.js} +1 -1
- package/dist/assets/{BossSpawnModal-BOOHaqaD.js → BossSpawnModal-q2-ZjkYi.js} +1 -1
- package/dist/assets/{ControlsModal-DItGV-CW.js → ControlsModal-CihuU69p.js} +1 -1
- package/dist/assets/{DockerLogsModal-DjAZ3GL7.js → DockerLogsModal-BFHVU_1p.js} +1 -1
- package/dist/assets/{EmbeddedEditor-Cihkr8Xb.js → EmbeddedEditor-DZ5bE7j_.js} +1 -1
- package/dist/assets/{GmailOAuthSetup-G1XqiM44.js → GmailOAuthSetup-Dj_nP_GS.js} +1 -1
- package/dist/assets/{GoogleOAuthSetup-Ce6gojdm.js → GoogleOAuthSetup-CWs9nRX5.js} +1 -1
- package/dist/assets/{IframeModal-CSSZJzPv.js → IframeModal-CfItUAJ8.js} +1 -1
- package/dist/assets/{IntegrationsPanel-EspPH09n.js → IntegrationsPanel-BVjniF4n.js} +2 -2
- package/dist/assets/{LogViewerModal-Bn-HDysM.js → LogViewerModal-B7Jgt6ds.js} +1 -1
- package/dist/assets/{MonitoringModal-DuSLTKVR.js → MonitoringModal-CS8nfYl3.js} +1 -1
- package/dist/assets/{PM2LogsModal-Bo2OtaQd.js → PM2LogsModal-DmToSbls.js} +1 -1
- package/dist/assets/{RestoreArchivedAreaModal-BOx-V6tl.js → RestoreArchivedAreaModal-DD9YQJ47.js} +1 -1
- package/dist/assets/{Scene2DCanvas-BIUbi14G.js → Scene2DCanvas-CxLa2T6K.js} +1 -1
- package/dist/assets/{SceneManager-CIWrGc-K.js → SceneManager-gVDwrjJj.js} +1 -1
- package/dist/assets/{SkillsPanel-_KHtTDhC.js → SkillsPanel-DMmqzmAb.js} +1 -1
- package/dist/assets/{SlackMultiInstanceSetup-DbQ3rUtd.js → SlackMultiInstanceSetup-CvOqPr4x.js} +1 -1
- package/dist/assets/{SpawnModal-CYEoOMPW.js → SpawnModal-DwpQZPIm.js} +1 -1
- package/dist/assets/{StatisticsModal-BJ-coeis.js → StatisticsModal-DHwmDvMq.js} +1 -1
- package/dist/assets/{SubordinateAssignmentModal-5Z3jvbM9.js → SubordinateAssignmentModal-vJ3xMaqe.js} +1 -1
- package/dist/assets/{TriggerManagerPanel-DvC0xP9r.js → TriggerManagerPanel-B8iv-tyr.js} +1 -1
- package/dist/assets/{WorkflowEditorPanel-6ym1_csr.js → WorkflowEditorPanel-CznY7cLk.js} +1 -1
- package/dist/assets/{area-logos-mWPCtCnf.js → area-logos-CkHS76Vd.js} +1 -1
- package/dist/assets/{index-DZiNmiyC.js → index-B2XtMSw5.js} +1 -1
- package/dist/assets/{index-8VVbTmtb.js → index-BTvXV7CT.js} +1 -1
- package/dist/assets/index-BdDicCLy.js +2 -0
- package/dist/assets/index-CO38FP9S.js +1 -0
- package/dist/assets/{index-DxyZ-rYT.js → index-Ce90LqMC.js} +1 -1
- package/dist/assets/{index-CY_NzVPm.js → index-Cout14yl.js} +1 -1
- package/dist/assets/{index-CnESn83U.js → index-DpRKadlB.js} +2 -2
- package/dist/assets/{index-BPjQZacc.css → index-Ja-ujZ-0.css} +1 -1
- package/dist/assets/{index-CiKbhMfN.js → index-krziBkQk.js} +1 -1
- package/dist/assets/{index-CT2vtbed.js → index-oQI2DZbz.js} +3 -3
- package/dist/assets/{main-BHBs2E1L.css → main-C10O3GdP.css} +1 -1
- package/dist/assets/{main-D5j8Ul0m.js → main-Du_kWg5E.js} +10 -10
- package/dist/assets/{web-DMxl9AVF.js → web-C9cC59SM.js} +1 -1
- package/dist/assets/{web-Cd0-XOkz.js → web-DF-qnU6X.js} +1 -1
- package/dist/assets/{web-BvAQVbIF.js → web-tQ-Hwgn-.js} +1 -1
- package/dist/build-info.json +1 -1
- package/dist/index.html +2 -2
- package/dist/locales/en/config.json +1 -0
- package/dist/src/packages/server/opencode/json-event-parser.js +3 -1
- package/dist/src/packages/server/opencode/server/opencode-server-event-adapter.js +127 -0
- package/dist/src/packages/server/opencode/server/opencode-server-process.js +285 -0
- package/dist/src/packages/server/opencode/server/opencode-server-recovery-store.js +73 -0
- package/dist/src/packages/server/opencode/server/opencode-server-runner.js +384 -0
- package/dist/src/packages/server/routes/agents.js +29 -1
- package/dist/src/packages/server/runtime/opencode-runner-router.js +93 -0
- package/dist/src/packages/server/runtime/opencode-runtime-provider.js +5 -3
- package/dist/src/packages/server/services/system-prompt-service.js +49 -1
- package/package.json +1 -1
- package/dist/assets/index-C34l72MW.js +0 -1
- package/dist/assets/index-CS8OutmQ.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{r as a,H as yn,J as Zt,K as dn,L as un,j as e,M as mn,N as Sn,u as Gt,O as An,P as En,U as Mn,V as In,W as Tn,X as Ln,Y as Pn,Z as pn,_ as Jt,S as A,$ as Qt,a0 as Xt,a1 as en,a2 as yt,a3 as be,a4 as Rn,s as h,a5 as fn,m as hn,a6 as Dn,z as tn,B as nn,I as d,a7 as zn,q as $n,a8 as On,a9 as gn,aa as xn,ab as bn,ac as _n,ad as Bn,ae as Fn,af as Wn,ag as Hn,ah as Un,ai as Vn,aj as Xn,ak as Gn,al as qn,am as Yn,an as Kn,ao as Zn,ap as an,C as Jn,aq as Qn,ar as sn,as as ea,at as ta,au as na,av as aa,aw as sa,ax as ia,ay as la,az as ra,aA as oa,aB as ca,aC as da,aD as ua,aE as ma,aF as pa,aG as fa,aH as et,aI as ha,aJ as ga,aK as xa,aL as ba,aM as mt,aN as _a,aO as wa,aP as va,aQ as ja,aR as Ca,aS as ln,aT as ka}from"./main-Du_kWg5E.js";import{g as Na}from"./area-logos-CkHS76Vd.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function ya(c){const r=a.useRef(c);r.current=c,a.useEffect(()=>{if(!yn())return;let p=null,g=!1;return Zt.addListener("backButton",()=>{r.current()==="exit"&&Zt.exitApp()}).then(k=>{g?k.remove():p=k}),()=>{g=!0,p&&(p.remove(),p=null)}},[])}async function Sa(c){const r=dn(),p=await fetch(`${un()}/api/agents/${c}/terminal`,{method:"POST",headers:{Authorization:`Bearer ${r}`}});if(!p.ok){const g=await p.json().catch(()=>({}));throw new Error((g==null?void 0:g.error)||`Failed to start terminal (${p.status})`)}return p.json()}async function Aa(c){const r=dn();await fetch(`${un()}/api/agents/${c}/terminal`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}})}const pt=new Map;function Ea({agentId:c}){const[r,p]=a.useState(null),[g,k]=a.useState(null);return a.useEffect(()=>{let T=!1;const S=pt.get(c);return S&&(clearTimeout(S),pt.delete(c)),p(null),k(null),Sa(c).then(N=>{T||p(N.url)}).catch(N=>{T||k(N instanceof Error?N.message:"Failed to start terminal")}),()=>{T=!0;const N=pt.get(c);N&&clearTimeout(N),pt.set(c,setTimeout(()=>{pt.delete(c),Aa(c)},2500))}},[c]),g?e.jsx("div",{className:"flat-classic-terminal flat-classic-terminal--message",children:e.jsx("span",{children:g})}):r?e.jsx("div",{className:"flat-classic-terminal",children:e.jsx(mn,{terminalUrl:r,visible:!0})}):e.jsx("div",{className:"flat-classic-terminal flat-classic-terminal--message",children:e.jsx("span",{children:"Attaching to interactive session…"})})}const Wt=new Map,Ma=6e4;function rn(c){return Number.isFinite(c)?Math.abs(c)>=1e3?c.toLocaleString(void 0,{maximumFractionDigits:0}):c.toLocaleString(void 0,{maximumFractionDigits:2}):String(c)}function Ia(c,r){var k,T,S;const p=[];if(!c.rateLimits)return p;if(c.provider==="claude"){const N=c,Z=[{key:"fiveHour",label:r("terminal:usage.currentSession"),window:N.rateLimits.fiveHour},{key:"sevenDay",label:r("terminal:usage.currentWeekAll"),window:N.rateLimits.sevenDay},{key:"sevenDayOpus",label:r("terminal:usage.currentWeekOpus"),window:N.rateLimits.sevenDayOpus},{key:"sevenDaySonnet",label:r("terminal:usage.currentWeekSonnet"),window:N.rateLimits.sevenDaySonnet}];for(const w of Z)w.window&&p.push({...w,window:w.window});return p}const g=c;return(k=g.rateLimits)!=null&&k.weekly&&p.push({key:"weekly",label:r("terminal:usage.weeklyLimit"),window:g.rateLimits.weekly}),(T=g.rateLimits)!=null&&T.monthly&&p.push({key:"monthly",label:r("terminal:usage.monthlyLimit"),window:g.rateLimits.monthly}),(S=g.rateLimits)!=null&&S.onDemand&&p.push({key:"onDemand",label:r("terminal:usage.onDemandLimit"),window:g.rateLimits.onDemand}),p}function Ta({agentId:c,contextSummary:r}){const{t:p}=Gt(["terminal","common"]),[g,k]=a.useState(()=>{var $;return(($=Wt.get(c))==null?void 0:$.snapshot)??null}),[T,S]=a.useState(!1),[N,Z]=a.useState(null),w=a.useRef(0);a.useEffect(()=>{const $=Wt.get(c);if($&&Date.now()-$.fetchedAt<Ma){k($.snapshot);return}const ie=++w.current;S(!0),Z(null),An(c).then(P=>{ie===w.current&&(Wt.set(c,{snapshot:P,fetchedAt:Date.now()}),k(P),S(!1))}).catch(P=>{ie===w.current&&(Z(P.message||"Failed to load plan limits"),S(!1))})},[c]);const V=g?Ia(g,p):[];return e.jsxs("div",{className:"plan-limits-tooltip",children:[r&&e.jsx("div",{className:"plan-limits-tooltip__context",children:r}),e.jsx("div",{className:"plan-limits-tooltip__title",children:p("terminal:usage.limits")}),T&&!g&&e.jsxs("div",{className:"plan-limits-tooltip__muted",children:[p("common:status.loading"),"…"]}),!T&&N&&!g&&e.jsx("div",{className:"plan-limits-tooltip__muted",children:p("terminal:usage.limitsError",{message:N})}),V.length>0?e.jsx("div",{className:"plan-limits-tooltip__gauges",children:V.map(({key:$,label:ie,window:P})=>{const Se=Math.max(0,Math.min(100,P.utilization)),le=Mn(Se),re=typeof P.used=="number"&&typeof P.limit=="number"&&Number.isFinite(P.used)&&Number.isFinite(P.limit);return e.jsxs("div",{className:"plan-limits-tooltip__gauge",children:[e.jsxs("div",{className:"plan-limits-tooltip__gauge-head",children:[e.jsx("span",{className:"plan-limits-tooltip__gauge-label",children:ie}),e.jsx("span",{className:"plan-limits-tooltip__gauge-percent",style:{color:le},children:p("terminal:usage.percentUsed",{percent:Math.round(Se)})})]}),e.jsx("div",{className:"plan-limits-tooltip__bar",children:e.jsx("div",{className:"plan-limits-tooltip__bar-fill",style:{width:`${Se}%`,background:le}})}),e.jsxs("div",{className:"plan-limits-tooltip__reset",children:[p("terminal:usage.resets",{time:En(P.resetsAt)}),re&&e.jsx("span",{style:{marginLeft:8},children:p("terminal:usage.creditsUsed",{used:rn(P.used),limit:rn(P.limit)})})]})]},$)})}):g&&!T&&e.jsx("div",{className:"plan-limits-tooltip__muted",children:g.rateLimitsError?p("terminal:usage.limitsError",{message:g.rateLimitsError}):g.cliHint})]})}function La({agentId:c,disabled:r,contextSummary:p,children:g}){return e.jsx(Sn,{position:"top",maxWidth:320,disabled:r,className:"plan-limits-tooltip-wrapper",triggerStyle:{display:"inline-flex",alignItems:"center"},content:e.jsx(Ta,{agentId:c,contextSummary:p}),children:g})}const Pa=a.memo(function({className:r=""}){const{t:p}=Gt(["common"]),[g,k]=In(),T=a.useRef(null),[S,N]=a.useState(null);a.useLayoutEffect(()=>{const w=T.current;if(!w)return;const V=w.querySelector(".view-mode-toggle__btn--active");V&&N({left:V.offsetLeft,width:V.offsetWidth})},[g]);const Z=a.useCallback(w=>{if(w!==g){if(typeof window<"u"&&window.dispatchEvent(new CustomEvent("tide:viewmode-switch-pressed",{detail:{mode:w}})),w==="3d"){requestAnimationFrame(()=>k(w));return}k(w)}},[g,k]);return e.jsxs("div",{className:`view-mode-toggle ${r}`,ref:T,children:[S&&e.jsx("div",{className:"view-mode-toggle__indicator",style:{left:S.left,width:S.width}}),Tn.map(w=>e.jsxs("button",{className:`view-mode-toggle__btn ${g===w?"view-mode-toggle__btn--active":""}`,onClick:()=>Z(w),title:p(`common:viewMode.descriptions.${w}`),children:[e.jsxs("span",{className:"view-mode-toggle__icon",children:[w==="2d"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),e.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),e.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"})]}),w==="3d"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M12 2L2 7l10 5 10-5-10-5z"}),e.jsx("path",{d:"M2 17l10 5 10-5"}),e.jsx("path",{d:"M2 12l10 5 10-5"})]}),w==="flat"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"13",y:"3",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"3",y:"13",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"13",y:"13",width:"8",height:"8",rx:"1"})]}),w==="dashboard"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"7",height:"9",rx:"1"}),e.jsx("rect",{x:"14",y:"3",width:"7",height:"5",rx:"1"}),e.jsx("rect",{x:"14",y:"12",width:"7",height:"9",rx:"1"}),e.jsx("rect",{x:"3",y:"16",width:"7",height:"5",rx:"1"})]})]}),e.jsx("span",{className:"view-mode-toggle__label",children:p(`common:viewMode.labels.${w}`)})]},w))]})}),St=3,At=280,on=320,Ht=240,cn=64,Ra=["simple","chat","advanced"],Da={simple:"Simple",chat:"Chat",advanced:"Advanced"},za={simple:"○",chat:"◐",advanced:"◉"},$a={simple:"Simple view — clean messages only",chat:"Chat view — assistant replies (no tool calls)",advanced:"Advanced view — everything including tools"},Ut="flat-clear-context",wn="tide:flat-embedded-panels";function vn(){try{const c=localStorage.getItem(wn),r=c?JSON.parse(c):{};return r&&typeof r=="object"?r:{}}catch{return{}}}function Vt(c,r){try{const p=vn();r?p[c]=r:delete p[c],localStorage.setItem(wn,JSON.stringify(p))}catch{}}function Oa(c){const r=c.split("/").filter(Boolean);return r.length===0?c:r.slice(-2).join("/")}function Ba(c){if(c.provider==="codex"){const T=c.codexModel||"gpt-5.6-luna",S=Ca[T];return{model:(S==null?void 0:S.label)||T}}if(c.provider==="opencode")return{model:c.opencodeModel||"opencode"};if(c.provider==="grok"){const T=c.grokModel||"grok-4.5",S=c.effort,N=S?ln[S]:void 0;return{model:T,effort:N==null?void 0:N.label}}const r=c.model||"sonnet",p=ka[r],g=c.effort,k=g?ln[g]:void 0;return{model:(p==null?void 0:p.label)||r,effort:k==null?void 0:k.label}}function Fa(c,r){if(r.type==="rectangle"&&r.width&&r.height){const p=r.width/2,g=r.height/2;return c.x>=r.center.x-p&&c.x<=r.center.x+p&&c.z>=r.center.z-g&&c.z<=r.center.z+g}if(r.type==="circle"&&r.radius){const p=c.x-r.center.x,g=c.z-r.center.z;return p*p+g*g<=r.radius*r.radius}return!1}const Wa=Qn.memo(function({agentId:r,terminalViewMode:p,onTerminalViewModeChange:g,inspectorOpen:k,onToggleInspector:T,onShowTaskBoard:S,onImageClick:N,onFileClick:Z,onBashClick:w,onViewMarkdown:V,onRequestClearSubordinates:$,keyboard:ie,canNavigateBack:P,canNavigateForward:Se,onNavigateBack:le,onNavigateForward:re,agentInfoOpen:ze,onToggleAgentInfo:ft,onHeaderContextMenu:_e,onBuildingContextMenu:we}){var vt,xe;const f=sn(r),O=hn(),Ae=ea(),Ee=a.useRef(null),qe=a.useRef(null),{displayedAgentId:Me,fadingOut:Et}=ta(r),ht=sn(Me),Ye=!!Ae.interactiveMode&&((f==null?void 0:f.provider)??"claude")==="claude"&&!!(f!=null&&f.sessionId),[oe,Ke]=a.useState(!1),[$e,ce]=a.useState(!1),R=a.useCallback(()=>ce(!1),[]);pn("flat-chat-actions",$e,R),a.useEffect(()=>{const n=()=>ce(o=>!o);return window.addEventListener("tide:toggle-chat-actions",n),()=>window.removeEventListener("tide:toggle-chat-actions",n)},[]),a.useEffect(()=>{Ke(!1),ce(!1)},[r]),a.useEffect(()=>{!Ye&&oe&&Ke(!1)},[Ye,oe]),a.useEffect(()=>{const n=qe.current;if(!n)return;const o=u=>{u.button===3?(u.preventDefault(),u.stopPropagation(),le()):u.button===4&&(u.preventDefault(),u.stopPropagation(),re())},l=u=>{(u.button===3||u.button===4)&&u.preventDefault()};return n.addEventListener("mouseup",o),n.addEventListener("mousedown",l),()=>{n.removeEventListener("mouseup",o),n.removeEventListener("mousedown",l)}},[le,re]),a.useEffect(()=>{const n=qe.current;if(!n)return;let o=0,l=0,u=0;const H=250,G=600,D=80,te=1.5,$t=ne=>{let t=ne instanceof HTMLElement?ne:null;for(;t&&t!==n;){const s=window.getComputedStyle(t).overflowX;if((s==="auto"||s==="scroll")&&t.scrollWidth>t.clientWidth)return!0;t=t.parentElement}return!1},jt=ne=>{const t=Date.now();if(t<u){ne.preventDefault();return}if(Math.abs(ne.deltaX)<=Math.abs(ne.deltaY)*te){o=0;return}if($t(ne.target)){o=0;return}t-l>H&&(o=0),l=t,o+=ne.deltaX,o<=-D?(o=0,u=t+G,ne.preventDefault(),le()):o>=D&&(o=0,u=t+G,ne.preventDefault(),re())};return n.addEventListener("wheel",jt,{passive:!1}),()=>n.removeEventListener("wheel",jt)},[le,re]);const de=fn(),tt=a.useMemo(()=>{if(!f)return null;const n=new Set,o=[];for(const l of de.values())l.archived||l.directories.length===0||l.assignedAgentIds.includes(r)&&(n.add(l.id),o.push(l));for(const l of de.values())l.archived||l.directories.length===0||n.has(l.id)||Fa({x:f.position.x,z:f.position.z},l)&&(n.add(l.id),o.push(l));return o.length===0?null:o.flatMap(l=>l.directories.filter(u=>u&&u.trim().length>0).map(u=>({areaId:l.id,areaName:l.name,dir:u})))},[f,r,de]),{branches:gt,fetchRemote:Oe,fetchingDirs:Ie}=na(tt),ue=a.useMemo(()=>{var l;const n=h.getAreaForAgent(r);if(!n)return[];const o=[];for(const u of O.values())u.type==="terminal"&&h.isPositionInArea(u.position,n)&&o.push({id:u.id,name:u.name,hasUrl:!!((l=u.terminalStatus)!=null&&l.url)});return o},[r,O]),ve=a.useMemo(()=>{var l;const n=h.getAreaForAgent(r);if(!n)return[];const o=[];for(const u of O.values())u.type==="server"&&((l=u.pm2)!=null&&l.enabled)&&h.isPositionInArea(u.position,n)&&o.push({id:u.id,name:u.name});return o},[r,O]),J=a.useMemo(()=>{const n=h.getAreaForAgent(r);if(!n)return[];const o=[];for(const l of O.values())l.type==="database"&&l.database&&h.isPositionInArea(l.position,n)&&o.push({id:l.id,name:l.name});return o},[r,O]),Be=aa(),ae=a.useMemo(()=>{const n=h.getAreaForAgent(r);if(!n)return[];const o=[];for(const l of O.values())if(l.type==="tests"&&h.isPositionInArea(l.position,n)){const u=!!l.folderPath&&Be.some(H=>sa(H,l.folderPath));o.push({id:l.id,name:l.name,working:u})}return o},[r,O,Be]),se=a.useMemo(()=>{const n=h.getAreaForAgent(r);if(!n)return[];const o=[];for(const l of O.values())l.type==="http"&&h.isPositionInArea(l.position,n)&&o.push({id:l.id,name:l.name});return o},[r,O]),[,Mt]=a.useReducer(n=>n+1,0),je=((vt=Ee.current)==null?void 0:vt.search.searchMode)??!1,nt=a.useCallback(()=>{var n;(n=Ee.current)==null||n.search.toggleSearch(),Mt()},[]),Te=ia(),Le=Te.isPending(Ut),[j,ee]=a.useState(null),Q=j?O.get(j.buildingId):null,[Fe,Pe]=a.useState(""),[We,It]=a.useState(()=>la()),B=a.useMemo(()=>{var n;return((n=h.getAreaForAgent(r))==null?void 0:n.id)??null},[r,O]),He=a.useCallback((n,o)=>{Pe(""),ee(l=>{const u=(l==null?void 0:l.buildingId)===o?null:{type:n,buildingId:o};return B&&Vt(B,u),u})},[B]),Ce=a.useCallback(()=>{Pe(""),ee(null),B&&Vt(B,null)},[B]);a.useEffect(()=>{if((j==null?void 0:j.type)!=="pm2-logs")return;const n=j.buildingId;return h.startLogStreaming(n,200),()=>h.stopLogStreaming(n)},[j]);const{height:Tt,onResizeStart:Lt}=ra(),{sidePanelWidth:Pt,handleSidePanelResizeStart:at}=oa(),[_,xt]=a.useState(()=>Xt(A.GIT_PANEL_OPEN,!1)),[Re,me]=a.useState(()=>Xt(A.BUILDINGS_PANEL_OPEN,!1)),[F,Ue]=a.useState(!1),st=a.useCallback(()=>{Ue(n=>{const o=!n;return o&&ca.setEnabled(!0),o})},[]),Rt=a.useCallback(()=>Ue(!1),[]),bt=a.useCallback(()=>{xt(n=>{const o=!n;return be(A.GIT_PANEL_OPEN,o),o})},[]),_t=a.useCallback(()=>{me(n=>{const o=!n;return be(A.BUILDINGS_PANEL_OPEN,o),o})},[]),Dt=a.useCallback(()=>{xt(!1),be(A.GIT_PANEL_OPEN,!1)},[]),it=a.useCallback(()=>{me(!1),be(A.BUILDINGS_PANEL_OPEN,!1)},[]),Ve=da(),pe=a.useMemo(()=>({terminal:ue,"pm2-logs":ve,database:J,tests:ae,http:se}),[ue,ve,J,ae,se]);a.useEffect(()=>{if(!j)return;pe[j.type].some(o=>o.id===j.buildingId)||(Pe(""),ee(null))},[j,pe]);const ke=a.useRef(void 0);a.useEffect(()=>{var o;if(ke.current===B)return;ke.current=B;const n=B?vn()[B]:void 0;Pe(""),n&&((o=pe[n.type])!=null&&o.some(l=>l.id===n.buildingId))?ee(n):ee(null)},[B,pe]),a.useEffect(()=>{const n=o=>{var H;const l=o.detail;if(!(l!=null&&l.buildingId)||!(l!=null&&l.type)||!((H=pe[l.type])!=null&&H.some(G=>G.id===l.buildingId)))return;l.handled=!0,Pe("");const u={type:l.type,buildingId:l.buildingId};ee(u),B&&Vt(B,u)};return window.addEventListener("tide:dock-building-flat",n),()=>window.removeEventListener("tide:dock-building-flat",n)},[pe,B]);const[Xe,W]=a.useState(!1),fe=a.useRef(null);if(a.useEffect(()=>{if(!Xe)return;const n=o=>{fe.current&&!fe.current.contains(o.target)&&W(!1)};return document.addEventListener("mousedown",n),()=>document.removeEventListener("mousedown",n)},[Xe]),!f)return e.jsx("div",{className:"flat-chat flat-chat--empty",children:e.jsxs("div",{className:"flat-chat__placeholder",children:[e.jsx("span",{className:"flat-chat__placeholder-icon",children:"💬"}),e.jsx("span",{className:"flat-chat__placeholder-text",children:"Select an agent to start chatting"})]})});const Ne=f.contextStats,lt=!!Ne,Ze=Ne?Ne.totalTokens:f.contextUsed||0,rt=Ne?Ne.contextWindow:f.contextLimit||(f.provider==="grok"?5e5:2e5),zt=Ne?Ne.usedPercent:Math.round(Ze/rt*100),De=Math.max(0,Math.min(100,zt)),wt=Math.round(De*10)/10,he=Math.round((100-De)*10)/10,Je=De>=80?"#ff4a4a":De>=60?"#ff9e4a":De>=40?"#ffd700":"#4aff9e",Qe=(Ze/1e3).toFixed(1),ot=(rt/1e3).toFixed(1),ge=f.cwd,ct=ge?Oa(ge):null,ye=((xe=f.subordinateIds)==null?void 0:xe.length)||0,dt=ye>0;return e.jsxs("div",{ref:qe,className:`flat-terminal-wrapper ${_||Re||F?"flat-terminal-wrapper--with-side-panel":""} ${Et?"pane-fading-out":""}`,style:{"--guake-side-panel-width":`min(${Pt}px, 70%)`},children:[e.jsxs("div",{className:"flat-terminal-wrapper__header",children:[e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__header-main ${ze?"flat-terminal-wrapper__header-main--active":""}`,onClick:ft,onContextMenu:n=>{n.preventDefault(),n.stopPropagation(),_e({x:n.clientX,y:n.clientY})},title:ze?"Hide agent info":"Show agent info","aria-pressed":ze,children:[e.jsx("span",{className:`flat-terminal-wrapper__header-avatar${f.status==="working"?" is-working":""}`,children:e.jsx(gn,{agent:f,size:28})}),e.jsxs("span",{className:"flat-terminal-wrapper__header-info",children:[e.jsx("span",{className:"flat-terminal-wrapper__header-name",children:f.name}),e.jsx("span",{className:"flat-terminal-wrapper__header-status",style:{color:_n(f.status)},children:f.status})]}),f.taskLabel&&e.jsxs("span",{className:"flat-terminal-wrapper__header-task",title:f.taskLabel,children:["📋 ",f.taskLabel]}),e.jsxs("span",{className:"flat-terminal-wrapper__header-model",children:[e.jsx("img",{src:bn(f.provider,"/"),alt:f.provider,className:"flat-terminal-wrapper__header-provider-icon",title:xn(f.provider)}),(()=>{const{model:n,effort:o}=Ba(f);return e.jsxs("span",{className:"flat-terminal-wrapper__header-model-chip",title:o?`Model: ${n} · Effort: ${o}`:`Model: ${n}`,children:[e.jsx("span",{className:"flat-terminal-wrapper__header-model-name",children:n}),o&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flat-terminal-wrapper__header-model-sep","aria-hidden":"true",children:"·"}),e.jsx("span",{className:"flat-terminal-wrapper__header-model-effort",children:o})]})]})})()]})]}),e.jsxs("div",{className:"flat-terminal-wrapper__header-meta",children:[e.jsxs("div",{className:"flat-terminal-wrapper__view-mode",role:"group","aria-label":"Message view mode",children:[Ra.map(n=>e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__view-mode-btn ${!oe&&p===n?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>{Ke(!1),g(n)},title:$a[n],"aria-pressed":!oe&&p===n,children:[e.jsx("span",{className:"flat-terminal-wrapper__view-mode-icon","aria-hidden":"true",children:za[n]}),e.jsx("span",{className:"flat-terminal-wrapper__view-mode-label",children:Da[n]})]},n)),Ye&&e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__view-mode-btn ${oe?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>Ke(n=>!n),title:"Classic TUI — attach to the live interactive claude session in a terminal","aria-pressed":oe,children:[e.jsx("span",{className:"flat-terminal-wrapper__view-mode-icon","aria-hidden":"true",children:e.jsx(d,{name:"terminal",size:13})}),e.jsx("span",{className:"flat-terminal-wrapper__view-mode-label",children:"Classic TUI"})]})]}),e.jsxs("div",{className:"flat-terminal-wrapper__actions",role:"group","aria-label":"Terminal actions",children:[e.jsx("button",{type:"button",className:"flat-terminal-wrapper__action-btn",onClick:le,disabled:!P,title:"Back to previous agent","aria-label":"Back to previous agent",children:e.jsx(d,{name:"arrow-left",size:14})}),e.jsx("button",{type:"button",className:"flat-terminal-wrapper__action-btn",onClick:re,disabled:!Se,title:"Forward to next agent","aria-label":"Forward to next agent",children:e.jsx(d,{name:"arrow-right",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${je?"flat-terminal-wrapper__action-btn--active":""}`,onClick:nt,title:je?"Close search":"Search messages","aria-pressed":je,children:e.jsx(d,{name:je?"cross":"search",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn flat-terminal-wrapper__action-btn--danger ${Le?"flat-terminal-wrapper__action-btn--confirm":""}`,onClick:()=>Te.handleClick(Ut,()=>{var n;h.clearContext(r),(n=Ee.current)==null||n.historyLoader.clearHistory()}),title:Le?"Click again to confirm clear context":"Clear context",children:e.jsx(d,{name:Le?"question":"clear",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${_?"flat-terminal-wrapper__action-btn--active":""}`,onClick:bt,title:_?"Hide git panel":"Show git changes","aria-pressed":_,children:e.jsx(d,{name:"git-branch",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${Re?"flat-terminal-wrapper__action-btn--active":""}`,onClick:_t,title:Re?"Hide buildings panel":"Show area buildings","aria-pressed":Re,children:e.jsx(d,{name:"buildings",size:14})}),e.jsxs("div",{className:"flat-terminal-wrapper__more",ref:fe,children:[e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${Xe?"flat-terminal-wrapper__action-btn--active":""}`,onClick:()=>W(n=>!n),title:"More actions","aria-expanded":Xe,children:"⋮"}),Xe&&e.jsxs("div",{className:"flat-terminal-wrapper__more-menu",role:"menu",children:[e.jsxs("button",{type:"button",role:"menuitem",className:`flat-terminal-wrapper__more-item ${F?"flat-terminal-wrapper__more-item--active":""}`,onClick:()=>{st(),W(!1)},title:F?"Hide Debug Panel":"Show Debug Panel",children:[e.jsx(d,{name:"bug",size:14}),e.jsx("span",{children:F?"Hide Debug Panel":"Show Debug Panel"})]}),e.jsx("div",{className:"flat-terminal-wrapper__more-divider"}),e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item",onClick:()=>{h.collapseContext(r),W(!1)},disabled:f.status!=="idle",title:f.status!=="idle"?"Agent must be idle to collapse context":"Collapse context",children:[e.jsx(d,{name:"package",size:14}),e.jsx("span",{children:"Collapse context"})]}),dt&&e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{$(r,ye),W(!1)},children:[e.jsx(d,{name:"crown",size:14}),e.jsxs("span",{children:["Clear ",ye," subordinate",ye===1?"":"s"]})]}),e.jsx("div",{className:"flat-terminal-wrapper__more-divider"}),e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{h.killAgent(r),W(!1)},children:[e.jsx(d,{name:"cross",size:14}),e.jsx("span",{children:"Remove agent"})]})]})]})]}),e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__inspector-toggle ${k?"flat-terminal-wrapper__inspector-toggle--active":""}`,onClick:T,title:k?"Hide inspector panel":"Show inspector panel","aria-label":k?"Hide inspector panel":"Show inspector panel","aria-pressed":k,children:[e.jsx("span",{className:"flat-terminal-wrapper__inspector-icon","aria-hidden":"true",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"}),e.jsx("line",{x1:"10",y1:"2.5",x2:"10",y2:"13.5"})]})}),e.jsx("span",{className:"flat-terminal-wrapper__inspector-label",children:"Inspector"})]}),e.jsx("button",{type:"button",className:"flat-terminal-wrapper__close",onClick:()=>h.deselectAll(),title:"Close chat","aria-label":"Close chat",children:e.jsx(d,{name:"cross",size:14})})]})]}),$e&&e.jsxs("div",{className:"flat-chat-actions-sheet-root",role:"presentation",children:[e.jsx("div",{className:"flat-chat-actions-sheet__backdrop",onClick:R}),e.jsxs("div",{className:"flat-chat-actions-sheet",role:"menu","aria-label":"Chat actions",children:[e.jsx("div",{className:"flat-chat-actions-sheet__grabber","aria-hidden":"true"}),e.jsxs("div",{className:"flat-chat-actions-sheet__title-row",children:[e.jsx("span",{className:"flat-chat-actions-sheet__title",children:f.name}),e.jsx("button",{type:"button",className:"flat-chat-actions-sheet__done",onClick:R,children:"Done"})]}),e.jsxs("div",{className:"flat-chat-actions-sheet__grid",children:[e.jsxs("button",{type:"button",role:"menuitem",className:`flat-chat-actions-sheet__item ${je?"is-active":""}`,onClick:()=>{nt(),R()},children:[e.jsx(d,{name:je?"cross":"search",size:20}),e.jsx("span",{children:je?"Close search":"Search"})]}),e.jsxs("button",{type:"button",role:"menuitem",className:`flat-chat-actions-sheet__item ${_?"is-active":""}`,onClick:()=>{bt(),R()},children:[e.jsx(d,{name:"git-branch",size:20}),e.jsx("span",{children:"Git changes"})]}),e.jsxs("button",{type:"button",role:"menuitem",className:`flat-chat-actions-sheet__item ${Re?"is-active":""}`,onClick:()=>{_t(),R()},children:[e.jsx(d,{name:"buildings",size:20}),e.jsx("span",{children:"Buildings"})]}),e.jsxs("button",{type:"button",role:"menuitem",className:`flat-chat-actions-sheet__item ${F?"is-active":""}`,onClick:()=>{st(),R()},children:[e.jsx(d,{name:"bug",size:20}),e.jsx("span",{children:"Debug"})]})]}),e.jsxs("div",{className:"flat-chat-actions-sheet__list",children:[e.jsxs("button",{type:"button",role:"menuitem",className:`flat-chat-actions-sheet__row flat-chat-actions-sheet__row--danger ${Le?"is-armed":""}`,onClick:()=>Te.handleClick(Ut,()=>{var n;h.clearContext(r),(n=Ee.current)==null||n.historyLoader.clearHistory(),R()}),children:[e.jsx(d,{name:Le?"question":"clear",size:18}),e.jsx("span",{children:Le?"Tap again to confirm clear":"Clear context"})]}),e.jsxs("button",{type:"button",role:"menuitem",className:"flat-chat-actions-sheet__row",disabled:f.status!=="idle",onClick:()=>{h.collapseContext(r),R()},children:[e.jsx(d,{name:"package",size:18}),e.jsx("span",{children:"Collapse context"})]}),dt&&e.jsxs("button",{type:"button",role:"menuitem",className:"flat-chat-actions-sheet__row flat-chat-actions-sheet__row--danger",onClick:()=>{$(r,ye),R()},children:[e.jsx(d,{name:"crown",size:18}),e.jsxs("span",{children:["Clear ",ye," subordinate",ye===1?"":"s"]})]}),e.jsxs("button",{type:"button",role:"menuitem",className:"flat-chat-actions-sheet__row flat-chat-actions-sheet__row--danger",onClick:()=>{h.killAgent(r),R()},children:[e.jsx(d,{name:"cross",size:18}),e.jsx("span",{children:"Remove agent"})]})]})]})]}),e.jsx(ua,{agent:f,onClick:S}),oe&&Ye?e.jsx(Ea,{agentId:r}):Me&&ht?e.jsx(ma,{ref:Ee,agentId:Me,agent:ht,viewMode:p,isOpen:!0,onImageClick:N,onFileClick:Z,onBashClick:w,onViewMarkdown:V,keyboard:ie,hasModalOpen:!1},Me):null,j&&Q&&(()=>{var H,G;const n=j.type,o={terminal:"terminal","pm2-logs":"scroll",database:"hard-drives",tests:"flask",http:"globe"},l=n==="terminal"&&!((H=Q.terminalStatus)!=null&&H.url),u=!l;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"guake-bottom-terminal-resize",onMouseDown:Lt,role:"separator","aria-orientation":"horizontal","aria-label":"Resize embedded panel"}),e.jsxs("div",{className:"flat-bottom-panel",role:"region","aria-label":`${Q.name} panel`,style:{height:Tt},children:[e.jsxs("div",{className:"flat-bottom-panel__header",children:[e.jsxs("span",{className:"flat-bottom-panel__title",children:[e.jsx(d,{name:o[n],size:12}),e.jsx("span",{children:Q.name}),l&&e.jsx("span",{className:"flat-bottom-panel__muted",children:"(starting...)"})]}),e.jsxs("span",{className:"flat-bottom-panel__header-actions",children:[n==="pm2-logs"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"text",className:"guake-bottom-terminal-filter",value:Fe,onChange:D=>Pe(D.target.value),placeholder:"Filter logs","aria-label":`Filter logs for ${Q.name}`,spellCheck:!1}),e.jsx("select",{className:"guake-bottom-terminal-retention",value:We===null?"unlimited":String(We),onChange:D=>{const te=D.target.value==="unlimited"?null:Number(D.target.value);It(te),fa(te)},"aria-label":`Max log retention for ${Q.name}`,children:pa.map(D=>e.jsx("option",{value:D===null?"unlimited":String(D),children:D===null?"Unlimited":`${D.toLocaleString()} lines`},D===null?"unlimited":D))}),e.jsx("button",{type:"button",className:"flat-bottom-panel__close",onClick:()=>h.clearStreamingLogs(j.buildingId),title:"Clear logs",children:e.jsx(d,{name:"trash",size:12})}),e.jsx("button",{type:"button",className:"flat-bottom-panel__close",onClick:()=>h.sendBuildingCommand(j.buildingId,"restart"),title:"Restart",children:e.jsx(d,{name:"restart",size:12})})]}),u&&e.jsx("button",{type:"button",className:"flat-bottom-panel__close",onClick:()=>{Ce(),et(j.buildingId)},title:"Maximize — open as modal","aria-label":"Open as modal",children:e.jsx(d,{name:"fullscreen",size:12})}),e.jsx("button",{type:"button",className:"flat-bottom-panel__close",onClick:Ce,title:"Close panel","aria-label":"Close panel",children:e.jsx(d,{name:"cross",size:12})})]})]}),e.jsx("div",{className:"flat-bottom-panel__body",children:n==="terminal"?(G=Q.terminalStatus)!=null&&G.url?e.jsx(mn,{terminalUrl:Q.terminalStatus.url,visible:!0}):e.jsx("div",{className:"flat-bottom-panel__placeholder",children:"Starting terminal..."}):n==="pm2-logs"?e.jsx(ha,{buildingId:j.buildingId,filterText:Fe,maxRetention:We}):n==="database"?e.jsx(ga,{building:Q}):n==="tests"?e.jsx("div",{className:"tests-panel-host",children:e.jsx(xa,{building:Q,autoFocusSearch:!1})}):e.jsx("div",{className:"http-requests-panel-host",children:e.jsx(ba,{building:Q,autoFocusSearch:!1})})})]})]})})(),e.jsxs("div",{className:"flat-terminal-wrapper__statusbar",role:"contentinfo",children:[f.isDetached&&e.jsxs("span",{className:"flat-terminal-wrapper__detached",title:"Reattaching session...",children:[e.jsx(d,{name:"refresh",size:12}),e.jsx("span",{children:"Reattaching"})]}),ge&&ct&&e.jsxs("span",{className:"flat-terminal-wrapper__cwd",title:`Open in file explorer: ${ge}`,"aria-label":`Open ${ge} in file explorer`,role:"button",tabIndex:0,onClick:()=>h.openFileExplorer(ge),onKeyDown:n=>{(n.key==="Enter"||n.key===" ")&&(n.preventDefault(),h.openFileExplorer(ge))},children:[e.jsx("span",{className:"flat-terminal-wrapper__cwd-icon",children:e.jsx(d,{name:"folder",size:12})}),e.jsx("span",{className:"flat-terminal-wrapper__cwd-text",children:ct})]}),tt&&tt.map(({areaId:n,areaName:o,dir:l})=>{const u=gt.get(l),H=Ie.has(l),G=l.split("/").filter(Boolean).pop()||l;return e.jsxs("span",{className:"flat-terminal-wrapper__area-dir",title:`${o}: ${l}${u?` (${u.branch}${u.ahead?` ↑${u.ahead}`:""}${u.behind?` ↓${u.behind}`:""})`:""}`,onClick:()=>h.openFileExplorerForAreaFolder(n,l),children:[e.jsx(d,{name:"folder-open",size:12}),e.jsx("span",{className:"flat-terminal-wrapper__area-dir-name",children:G}),u&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flat-terminal-wrapper__area-dir-branch",children:[e.jsx(d,{name:"git-branch",size:10})," ",u.branch]}),u.ahead>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-ahead",title:`${u.ahead} ahead`,children:[e.jsx(d,{name:"arrow-up",size:9}),u.ahead]}),u.behind>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-behind",title:`${u.behind} behind`,children:[e.jsx(d,{name:"arrow-down",size:9}),u.behind]}),e.jsx("span",{className:`flat-terminal-wrapper__area-fetch ${H?"flat-terminal-wrapper__area-fetch--fetching":""}`,title:"Git fetch",onClick:D=>{D.stopPropagation(),Oe(l)},children:e.jsx(d,{name:H?"hourglass":"download",size:12})})]})]},`${n}:${l}`)}),e.jsx(La,{agentId:r,disabled:((f==null?void 0:f.provider)??"claude")!=="claude"&&((f==null?void 0:f.provider)??"claude")!=="grok",contextSummary:lt?`Context: ${Qe}k / ${ot}k tokens (${wt}% used)`:void 0,children:e.jsxs("span",{className:"flat-terminal-wrapper__context",tabIndex:0,role:"button",onClick:()=>h.setContextModalAgentId(r),onKeyDown:n=>{(n.key==="Enter"||n.key===" ")&&(n.preventDefault(),h.setContextModalAgentId(r))},title:((f==null?void 0:f.provider)??"claude")!=="claude"&&((f==null?void 0:f.provider)??"claude")!=="grok"?lt?`Context usage: ${Qe}k / ${ot}k tokens (${wt}% used). Click to view stats.`:"Click to fetch context stats":void 0,children:[e.jsx("span",{className:"flat-terminal-wrapper__context-icon",children:e.jsx(d,{name:"dashboard",size:12})}),e.jsx("span",{className:"flat-terminal-wrapper__context-label",children:"Ctx:"}),e.jsx("span",{className:"flat-terminal-wrapper__context-bar",children:e.jsx("span",{className:"flat-terminal-wrapper__context-bar-fill",style:{width:`${De}%`,backgroundColor:Je}})}),e.jsxs("span",{className:"flat-terminal-wrapper__context-tokens",style:{color:Je},children:[Qe,"k/",ot,"k"]}),e.jsxs("span",{className:"flat-terminal-wrapper__context-free",children:["(",he,"% free)"]}),!lt&&e.jsx("span",{className:"flat-terminal-wrapper__context-warning",title:"No context stats yet",children:e.jsx(d,{name:"warn",size:12})})]})}),e.jsx("div",{className:"flat-terminal-wrapper__statusbar-spacer","aria-hidden":"true"}),ue.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area terminals",children:ue.map(n=>{const o=(j==null?void 0:j.buildingId)===n.id;return e.jsx("button",{type:"button",className:`flat-terminal-wrapper__building-btn ${o?"flat-terminal-wrapper__building-btn--active":""} ${n.hasUrl?"":"flat-terminal-wrapper__building-btn--offline"}`,title:`${o?"Hide":"Show"} terminal: ${n.name}${n.hasUrl?"":" (starting...)"}`,onClick:()=>{if(o){Ce();return}if(n.hasUrl&&mt(n.id)==="modal"){et(n.id);return}n.hasUrl||h.sendBuildingCommand(n.id,"start"),He("terminal",n.id)},onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),we(n.id,{x:l.clientX,y:l.clientY})},children:e.jsx(d,{name:"terminal",size:14})},n.id)})}),ve.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area PM2 logs",children:ve.map(n=>{const o=(j==null?void 0:j.buildingId)===n.id;return e.jsx("button",{type:"button",className:`flat-terminal-wrapper__building-btn ${o?"flat-terminal-wrapper__building-btn--active":""}`,title:`${o?"Hide":"Show"} logs: ${n.name}`,onClick:()=>{o?Ce():mt(n.id)==="modal"?et(n.id):He("pm2-logs",n.id)},onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),we(n.id,{x:l.clientX,y:l.clientY})},children:e.jsx(d,{name:"scroll",size:14})},n.id)})}),J.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area databases",children:J.map(n=>{const o=(j==null?void 0:j.buildingId)===n.id;return e.jsx("button",{type:"button",className:`flat-terminal-wrapper__building-btn ${o?"flat-terminal-wrapper__building-btn--active":""}`,title:`${o?"Hide":"Show"} database: ${n.name}`,onClick:()=>{o?Ce():mt(n.id)==="modal"?et(n.id):He("database",n.id)},onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),we(n.id,{x:l.clientX,y:l.clientY})},children:e.jsx(d,{name:"hard-drives",size:14})},n.id)})}),ae.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area tests",children:ae.map(n=>{const o=(j==null?void 0:j.buildingId)===n.id;return e.jsx("button",{type:"button",className:`flat-terminal-wrapper__building-btn ${o?"flat-terminal-wrapper__building-btn--active":""} ${n.working?"flat-terminal-wrapper__building-btn--tests-working":""}`,title:n.working?`Running tests: ${n.name}`:`${o?"Hide":"Show"} tests: ${n.name}`,onClick:()=>{o?Ce():mt(n.id)==="modal"?et(n.id):He("tests",n.id)},onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),we(n.id,{x:l.clientX,y:l.clientY})},children:e.jsx(d,{name:"flask",size:14})},n.id)})}),se.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area HTTP requests",children:se.map(n=>{const o=(j==null?void 0:j.buildingId)===n.id;return e.jsx("button",{type:"button",className:`flat-terminal-wrapper__building-btn ${o?"flat-terminal-wrapper__building-btn--active":""}`,title:`${o?"Hide":"Show"} HTTP requests: ${n.name}`,onClick:()=>{o?Ce():mt(n.id)==="modal"?et(n.id):He("http",n.id)},onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),we(n.id,{x:l.clientX,y:l.clientY})},children:e.jsx(d,{name:"globe",size:14})},n.id)})}),e.jsx("div",{className:"flat-terminal-wrapper__theme",children:e.jsx(_a,{})})]}),_&&e.jsx(wa,{agentId:r,agents:Ve,onClose:Dt,branchInfoMap:gt,fetchRemote:Oe,fetchingDirs:Ie,onResizeStart:n=>at(n,"right")}),Re&&e.jsx(va,{agentId:r,onClose:it}),F&&e.jsx(ja,{agentId:r,onClose:Rt})]})}),Ha={groups:[],gridCols:1,gridRows:1,positions:new Map};function qa({onAgentClick:c,onBuildingClick:r,onBuildingDoubleClick:p,onBuildingPopup:g,onAreaContextMenu:k,onOpenSpawnModal:T,onOpenBossSpawnModal:S,onOpenAreaModal:N}){const{t:Z}=Gt(["common"]),w=Ln(),V=Pn(),[$,ie]=a.useState(null),[P,Se]=a.useState(null),[le,re]=a.useState(null);pn("flatview-image-modal",$!==null,()=>ie(null));const[ze,ft]=a.useState(null),[_e,we]=a.useState(null),[f,O]=a.useState(null),[Ae,Ee]=a.useState(null),[qe,Me]=a.useState(!1),Et=a.useCallback(()=>{Me(t=>!t)},[]),ht=a.useCallback(()=>{Me(!1)},[]),[Ye,oe]=a.useState(()=>{const t=Jt(A.VIEW_MODE);return t==="simple"||t==="chat"||t==="advanced"?t:"simple"}),Ke=a.useCallback(t=>{oe(t),Qt(A.VIEW_MODE,t)},[]);a.useEffect(()=>{const t=s=>{if(s.key!==A.VIEW_MODE)return;const i=s.newValue;(i==="simple"||i==="chat"||i==="advanced")&&oe(i)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);const[$e,ce]=a.useState(()=>Xt(A.FLAT_INSPECTOR_OPEN,!1)),[R,de]=a.useState(!1),tt=a.useCallback(()=>de(t=>!t),[]),gt=a.useCallback(()=>de(!1),[]);a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-agents-drawer-state",{detail:{open:R}}))},[R]),a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-inspector-state",{detail:{open:$e}}))},[$e]),a.useEffect(()=>{const t=()=>de(C=>!C),s=()=>{ce(C=>{const E=!C;return be(A.FLAT_INSPECTOR_OPEN,E),E})},i=()=>{de(!1),ce(!1),be(A.FLAT_INSPECTOR_OPEN,!1)},x=()=>de(!1),b=()=>{ce(!1),be(A.FLAT_INSPECTOR_OPEN,!1)};return window.addEventListener("tide-toggle-flat-agents-drawer",t),window.addEventListener("tide-toggle-flat-inspector",s),window.addEventListener("tide-close-flat-side-views",i),window.addEventListener("tide-close-flat-agents-drawer-only",x),window.addEventListener("tide-close-flat-inspector-only",b),()=>{window.removeEventListener("tide-toggle-flat-agents-drawer",t),window.removeEventListener("tide-toggle-flat-inspector",s),window.removeEventListener("tide-close-flat-side-views",i),window.removeEventListener("tide-close-flat-agents-drawer-only",x),window.removeEventListener("tide-close-flat-inspector-only",b)}},[]);const Oe=a.useRef(null),Ie=a.useRef(null),[ue,ve]=a.useState(()=>{const t=en(A.FLAT_MIDDLE_WIDTH,0);return t>=At?t:null}),[J,Be]=a.useState(()=>{const t=en(A.FLAT_INSPECTOR_WIDTH,0);return t>=Ht?t:null}),ae=a.useCallback(t=>{if(typeof window>"u")return t;const s=J!==null?St+J:0,i=window.innerWidth-cn-St-on-s;return Math.max(At,Math.min(Math.max(i,At),t))},[J]),se=a.useCallback(t=>{var b;if(typeof window>"u")return t;const s=(b=Oe.current)==null?void 0:b.querySelector(".flat-middle"),i=(s==null?void 0:s.getBoundingClientRect().width)??At,x=window.innerWidth-cn-i-St-on-St;return Math.max(Ht,Math.min(Math.max(x,Ht),t))},[]);a.useEffect(()=>{if(ue===null&&J===null)return;const t=()=>{ve(s=>{if(s===null)return s;const i=ae(s);return i===s?s:i}),Be(s=>{if(s===null)return s;const i=se(s);return i===s?s:i})};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[ue,J,ae,se]);const Mt=a.useCallback(t=>{var i;if(t.button!==0)return;const s=(i=Oe.current)==null?void 0:i.querySelector(".flat-middle");s&&(t.currentTarget.setPointerCapture(t.pointerId),Ie.current={kind:"middle",startX:t.clientX,startWidth:s.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),je=a.useCallback(t=>{var i;if(t.button!==0)return;const s=(i=Oe.current)==null?void 0:i.querySelector(".flat-inspector");s&&(t.currentTarget.setPointerCapture(t.pointerId),Ie.current={kind:"inspector",startX:t.clientX,startWidth:s.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),nt=a.useCallback(t=>{const s=Ie.current;if(!s||t.pointerId!==s.pointerId)return;const i=t.clientX-s.startX;s.kind==="middle"?ve(ae(s.startWidth+i)):Be(se(s.startWidth-i))},[ae,se]),Te=a.useCallback(t=>{const s=Ie.current;if(!s||t.pointerId!==s.pointerId)return;try{t.currentTarget.releasePointerCapture(t.pointerId)}catch{}if(Ie.current=null,document.body.classList.remove("flat-splitter-dragging"),!(Math.abs(t.clientX-s.startX)>2))return;const x=t.clientX-s.startX;if(s.kind==="middle"){const b=ae(s.startWidth+x);ve(b),yt(A.FLAT_MIDDLE_WIDTH,b)}else{const b=se(s.startWidth-x);Be(b),yt(A.FLAT_INSPECTOR_WIDTH,b)}},[ae,se]),Le=a.useCallback(()=>{ve(null),yt(A.FLAT_MIDDLE_WIDTH,0)},[]),j=a.useCallback(()=>{Be(null),yt(A.FLAT_INSPECTOR_WIDTH,0)},[]),[ee,Q]=a.useState(()=>Jt(A.FLAT_INSPECTOR_VIEW)==="tracking"?"tracking":"agent"),Fe=a.useCallback(t=>{Q(t),Qt(A.FLAT_INSPECTOR_VIEW,t)},[]),Pe=a.useCallback(()=>{ce(t=>{const s=!t;return be(A.FLAT_INSPECTOR_OPEN,s),s})},[]),We=a.useCallback(()=>{ce(!1),be(A.FLAT_INSPECTOR_OPEN,!1)},[]),It=a.useCallback(()=>{Fe("tracking"),ce(!0),be(A.FLAT_INSPECTOR_OPEN,!0)},[Fe]),B=Rn(),He=a.useCallback((t,s)=>{ie({url:t,name:s})},[]),Ce=a.useCallback((t,s)=>{Se({command:t,output:s,isLive:!1})},[]),Tt=a.useCallback((t,s)=>{var b;const i=V.size>0?Array.from(V)[0]:null,x=i?(b=h.getState().agents.get(i))==null?void 0:b.cwd:void 0;h.setFileViewerPath(t,s,x)},[V]),Lt=a.useCallback(t=>{re(t)},[]),Pt=a.useCallback((t,s)=>{ft({agentId:t,count:s})},[]),at=a.useCallback(t=>{p?p(t):r(t)},[r,p]),_=a.useMemo(()=>V.size>0?Array.from(V)[0]:null,[V]),xt=a.useCallback(t=>{_&&we({agentId:_,position:t})},[_]),Re=a.useCallback((t,s)=>{O({buildingId:t,position:s})},[]);a.useEffect(()=>{Me(!1)},[_]);const me=a.useRef([]),F=a.useRef(-1),Ue=a.useRef(!1),st=a.useRef(null),[Rt,bt]=a.useState(!1),[_t,Dt]=a.useState(!1),it=a.useRef(!1),Ve=a.useRef(null),pe=a.useRef(!1),ke=a.useMemo(()=>new Set(w.map(t=>t.id)),[w]),Xe=a.useMemo(()=>{const t=new Map(w.map(i=>[i.id,i])),s=new Map;for(const i of w)if((i.isBoss||i.class==="boss")&&i.subordinateIds&&i.subordinateIds.length>0){const x=i.subordinateIds.map(b=>t.get(b)).filter(b=>b!==void 0);x.length>0&&s.set(i.id,x)}return s},[w]),W=a.useCallback(()=>{const t=me.current,s=F.current;bt(s>0),Dt(s>=0&&s<t.length-1)},[]),fe=a.useCallback(t=>{const s=me.current;if(s.length===0)return;let i=F.current+t;for(;i>=0&&i<s.length;){const x=s[i];if(ke.has(x)){Ue.current=!0,F.current=i,W(),h.selectAgent(x);return}i+=t}},[ke,W]),Ne=a.useCallback(()=>fe(-1),[fe]),lt=a.useCallback(()=>fe(1),[fe]);ya(a.useCallback(()=>{const t=me.current,s=F.current;return t.length>0&&s>0?(fe(-1),"handled"):"exit"},[fe]));const Ze=a.useCallback((t,s)=>{if(typeof window>"u")return;const i=window.history.state,b={...typeof i=="object"&&i!==null?i:{},__flatAgentNav:{agentId:t}};s==="replace"?window.history.replaceState(b,"",window.location.href):window.history.pushState(b,"",window.location.href)},[]);a.useEffect(()=>{if(!_){it.current=!1,Ve.current=null;return}if(!it.current){Ze(_,"replace"),it.current=!0,Ve.current=_;return}if(pe.current){pe.current=!1,Ve.current=_;return}Ve.current!==_&&(Ze(_,"push"),Ve.current=_)},[_,Ze]),a.useEffect(()=>{const t=s=>{var C,E;const i=(E=(C=s.state)==null?void 0:C.__flatAgentNav)==null?void 0:E.agentId;if(!i||typeof i!="string"||!ke.has(i)||i===_)return;pe.current=!0,Ue.current=!0;const x=me.current,b=x.lastIndexOf(i);b>=0?F.current=b:(x.push(i),F.current=x.length-1),W(),h.selectAgent(i)};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[ke,_,W]),a.useEffect(()=>{if(!_){me.current=[],F.current=-1,W();return}if(st.current=_,Ue.current){Ue.current=!1,W();return}const t=me.current,s=F.current;if(s>=0&&t[s]===_){W();return}const i=s<t.length-1?t.slice(0,s+1):t.slice();i.push(_),i.length>100&&i.shift(),me.current=i,F.current=i.length-1,W()},[_,W]);const rt=a.useCallback(t=>{c(t),de(!1)},[c]),zt=_??"",De=a.useCallback(()=>{},[]),wt=a.useCallback(t=>{rt(t)},[rt]),he=$e,[Je,Qe]=a.useState(he),[ot,ge]=a.useState(he);a.useEffect(()=>{if(he){Qe(!0);return}ge(!1);const t=setTimeout(()=>Qe(!1),240);return()=>clearTimeout(t)},[he]),a.useEffect(()=>{if(!Je||!he)return;let t=0;const s=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>ge(!0))});return()=>{cancelAnimationFrame(s),cancelAnimationFrame(t)}},[Je,he]);const ct=a.useRef(null);a.useEffect(()=>{if(_)return;const t=s=>{if(s.key!==" "&&s.key!=="Backspace")return;const i=s.target;if(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.isContentEditable)return;const x=st.current;!x||!ke.has(x)||(s.preventDefault(),h.selectAgent(x))};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[_,ke]);const[ye,dt]=a.useState(new Set),vt=a.useCallback(t=>{dt(s=>{const i=new Set(s);return i.has(t)?i.delete(t):i.add(t),i})},[]),[xe,n]=a.useState(()=>typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches);a.useEffect(()=>{if(typeof window>"u")return;const t=window.matchMedia("(max-width: 768px)"),s=i=>n(i.matches);return t.addEventListener("change",s),()=>t.removeEventListener("change",s)},[]);const[o,l]=a.useState(null),u=a.useCallback(t=>{l(s=>s===t?null:t)},[]),H=fn(),G=hn(),[D]=Dn(),te=a.useMemo(()=>{if(_)return Ha;const t=new Map,s=[];for(const v of w){const I=h.getAreaForAgent(v.id);if(!tn((I==null?void 0:I.id)??null))continue;if(!I||I.archived){s.push(v);continue}const L=t.get(I.id);L?L.push(v):t.set(I.id,[v])}const i=new Map,x=[];for(const v of G.values()){let I=!1;for(const L of H.values())if(!L.archived&&nn(L.id)&&h.isPositionInArea(v.position,L)){const q=i.get(L.id);q?q.push(v):i.set(L.id,[v]),I=!0;break}!I&&tn(null)&&x.push(v)}const b=[];for(const[,v]of H){if(v.archived||!nn(v.id))continue;const I=t.get(v.id),L=i.get(v.id)??[];(I&&I.length>0||L.length>0)&&b.push({area:v,agents:I??[],buildings:L})}(s.length>0||x.length>0)&&b.push({area:{id:"__unassigned__",name:"Unassigned",color:"#6272a4",center:{x:0,z:0},type:"circle",radius:0,directories:[],archived:!1,assignedAgentIds:[],zIndex:0},agents:s,buildings:x});const C=b.filter(v=>v.area.id!=="__unassigned__"),E=b.filter(v=>v.area.id==="__unassigned__");let m=1,M=1;const X=new Map;if(C.length>1){let v=1/0,I=-1/0,L=1/0,q=-1/0;for(const Y of C)v=Math.min(v,Y.area.center.x),I=Math.max(I,Y.area.center.x),L=Math.min(L,Y.area.center.z),q=Math.max(q,Y.area.center.z);const Ct=I-v||1,kt=q-L||1;if(C.length<=4){m=C.length,M=1;const Y=[...C].sort((K,Ot)=>K.area.center.x-Ot.area.center.x);for(let K=0;K<Y.length;K++)X.set(Y[K].area.id,{row:1,col:K+1})}else{const Y=[...C].sort((y,U)=>y.area.center.x-U.area.center.x),K=[];for(let y=1;y<Y.length;y++)K.push(Y[y].area.center.x-Y[y-1].area.center.x);const Ot=K.reduce((y,U)=>y+U,0)/K.length||1;let qt=1;for(const y of K)y>Ot*1.3&&qt++;m=Math.max(2,Math.min(qt,C.length));const Bt=[...C].sort((y,U)=>y.area.center.z-U.area.center.z),Nt=[];for(let y=1;y<Bt.length;y++)Nt.push(Bt[y].area.center.z-Bt[y-1].area.center.z);const jn=Nt.reduce((y,U)=>y+U,0)/Nt.length||1;let Yt=1;for(const y of Nt)y>jn*1.3&&Yt++;M=Math.max(2,Math.min(Yt,C.length)),m=Math.max(m,Math.ceil(C.length/M)),M=Math.max(M,Math.ceil(C.length/m));const Cn=Ct/m,kn=kt/M,Ft=new Set;for(const y of C){let U=Math.min(m-1,Math.max(0,Math.floor((y.area.center.x-v)/Cn))),Ge=Math.min(M-1,Math.max(0,Math.floor((y.area.center.z-L)/kn))),ut=`${Ge},${U}`,Kt=0;const Nn=M*m;for(;Ft.has(ut)&&Kt<Nn;)U++,U>=m&&(U=0,Ge=(Ge+1)%M),ut=`${Ge},${U}`,Kt++;Ft.has(ut)&&(Ge=M,U=0,ut=`${Ge},${U}`,M++),Ft.add(ut),X.set(y.area.id,{row:Ge+1,col:U+1})}}}const z=v=>{v.sort((I,L)=>{var Ct,kt,Y,K;const q=(((Ct=I.position)==null?void 0:Ct.z)??0)-(((kt=L.position)==null?void 0:kt.z)??0);return q!==0?q:(((Y=I.position)==null?void 0:Y.x)??0)-(((K=L.position)==null?void 0:K.x)??0)})};for(const v of C)z(v.agents);for(const v of E)z(v.agents);return{groups:[...C,...E],gridCols:m,gridRows:M,positions:X}},[w,H,G,D,_]),$t=a.useMemo(()=>{if(!_e)return[];const t=w.find(s=>s.id===_e.agentId);return t?[{id:"edit-agent",label:"Edit Agent",icon:e.jsx(d,{name:"edit",size:14}),onClick:()=>{window.dispatchEvent(new CustomEvent("tide:open-agent-edit",{detail:{agentId:t.id}}))}},{id:"open-chat",label:"Open Chat",icon:e.jsx(d,{name:"chat",size:14}),onClick:()=>c(t.id)},{id:"clone-agent",label:"Clone Agent",icon:e.jsx(d,{name:"clipboard",size:14}),onClick:()=>h.cloneAgent(t.id)},{id:"fork-agent",label:"Fork Agent (with history)",icon:e.jsx(d,{name:"git-branch",size:14}),onClick:()=>h.forkAgent(t.id)},{id:"delete-agent",label:"Delete Agent",icon:e.jsx(d,{name:"trash",size:14}),danger:!0,onClick:()=>{Ee({agentId:t.id,name:t.name})}}]:[]},[_e,w,c]),jt=a.useMemo(()=>{var C;if(!f)return[];const t=G.get(f.buildingId);if(!t)return[];const s=[],i=t.type==="server"||t.type==="docker"||t.type==="terminal",x=t.status==="running",b=t.type==="boss";if(s.push({id:"open",label:t.type==="database"?"Open Database":t.type==="folder"?"Open Folder":t.type==="tests"?"Open Tests":t.type==="http"?"Open Requests":t.type==="boss"?"View Boss Logs":t.type==="terminal"?"Open Terminal":t.type==="server"&&((C=t.pm2)!=null&&C.enabled)?"View PM2 Logs":"Open",icon:e.jsx(d,{name:t.type==="database"?"database":t.type==="folder"?"folder":t.type==="tests"?"flask":t.type==="http"?"globe":t.type==="terminal"?"terminal":"eye",size:14}),onClick:()=>at(t.id)}),i&&(x||s.push({id:"start",label:"Start",icon:e.jsx(d,{name:"play",size:14}),onClick:()=>h.sendBuildingCommand(t.id,"start")}),x&&(s.push({id:"restart",label:"Restart",icon:e.jsx(d,{name:"refresh",size:14}),onClick:()=>h.sendBuildingCommand(t.id,"restart")}),s.push({id:"stop",label:"Stop",icon:e.jsx(d,{name:"stop",size:14}),onClick:()=>h.sendBuildingCommand(t.id,"stop")}))),b&&t.subordinateBuildingIds&&t.subordinateBuildingIds.length>0&&(s.push({id:"start-all",label:"Start All Subordinates",icon:e.jsx(d,{name:"launch",size:14}),onClick:()=>{for(const E of t.subordinateBuildingIds)h.sendBuildingCommand(E,"start")}}),s.push({id:"stop-all",label:"Stop All Subordinates",icon:e.jsx(d,{name:"pause",size:14}),onClick:()=>{for(const E of t.subordinateBuildingIds)h.sendBuildingCommand(E,"stop")}}),s.push({id:"restart-all",label:"Restart All Subordinates",icon:e.jsx(d,{name:"restart",size:14}),onClick:()=>{for(const E of t.subordinateBuildingIds)h.sendBuildingCommand(E,"restart")}})),i&&s.push({id:"health-check",label:"Health Check",icon:e.jsx(d,{name:"health",size:14}),onClick:()=>h.sendBuildingCommand(t.id,"healthCheck")}),s.push({id:"divider-edit",label:"",divider:!0,onClick:()=>{}}),s.push({id:"edit",label:"Edit Building",icon:e.jsx(d,{name:"edit",size:14}),onClick:()=>{window.dispatchEvent(new CustomEvent("tide:building-edit",{detail:{buildingId:t.id}}))}}),s.push({id:"clone",label:"Clone Building",icon:e.jsx(d,{name:"copy",size:14}),onClick:()=>{h.createBuilding({name:`${t.name} (Copy)`,type:t.type,style:t.style,color:t.color,scale:t.scale,position:{x:t.position.x+2,z:t.position.z+2},cwd:t.cwd,folderPath:t.folderPath,commands:t.commands,pm2:t.pm2,docker:t.docker,database:t.database,terminal:t.terminal,urls:t.urls,subordinateBuildingIds:t.subordinateBuildingIds})}}),t.urls&&t.urls.length>0)for(const E of t.urls)s.push({id:`url-${E.label}`,label:E.label,icon:e.jsx(d,{name:"link",size:14}),onClick:()=>window.open(E.url,"_blank","noopener,noreferrer")});return s.push({id:"divider-danger",label:"",divider:!0,onClick:()=>{}}),s.push({id:"delete",label:"Delete Building",icon:e.jsx(d,{name:"trash",size:14}),danger:!0,onClick:()=>h.deleteBuilding(t.id)}),s},[f,G,at]),ne=a.useCallback(t=>{const s=new Set(te.groups.map(i=>i.area.id));s.delete(t),dt(s),requestAnimationFrame(()=>{const i=ct.current;if(!i)return;const x=i.querySelector(`[data-area-id="${t}"]`);if(!x)return;const b=i.getBoundingClientRect(),E=x.getBoundingClientRect().top-b.top+i.scrollTop-8;i.scrollTo({top:Math.max(0,E),behavior:"smooth"})})},[te]);return e.jsxs("div",{ref:Oe,className:`flat-view ${he?"flat-view--with-inspector":""} ${_?"flat-view--has-chat":""} ${R?"flat-view--mobile-sidebar-open":""}`,style:(()=>{if(ue===null&&J===null)return;const t={};return ue!==null&&(t["--flat-middle-width"]=`${ue}px`),J!==null&&(t["--flat-inspector-width"]=`${J}px`),t})(),children:[R&&e.jsx("div",{className:"flat-mobile-sidebar-backdrop",onClick:gt,"aria-hidden":"true"}),e.jsxs("div",{className:"flat-middle",children:[e.jsx("div",{className:"flat-middle__header",children:e.jsxs("div",{className:"flat-middle__actions",children:[e.jsx("button",{className:"flat-cta-btn flat-cta-btn--agent",onClick:T,title:"Create new agent",children:"+ Agent"}),e.jsx("button",{className:"flat-cta-btn flat-cta-btn--boss",onClick:S,title:"Create new boss agent",children:"+ Boss"}),e.jsx("button",{className:"flat-cta-btn flat-cta-btn--area",onClick:N,title:"Create new area",children:"+ Area"})]})}),e.jsx("div",{className:"flat-middle__content",children:e.jsx(zn,{activeAgentId:zt,onClose:De,onSelectAgent:wt,collapsedAreas:ye,onToggleArea:vt,agentListRef:ct})})]}),e.jsx("div",{className:"flat-splitter flat-splitter--middle",role:"separator","aria-orientation":"vertical","aria-label":"Resize agents panel",title:"Drag to resize · Double-click to reset",onPointerDown:Mt,onPointerMove:nt,onPointerUp:Te,onPointerCancel:Te,onDoubleClick:Le}),e.jsxs("div",{className:"flat-right",children:[e.jsxs("button",{type:"button",className:"flat-mobile-sidebar-toggle","aria-label":R?"Close agents sidebar":"Open agents sidebar","aria-expanded":R,onClick:tt,children:[e.jsx(d,{name:"list",size:18}),e.jsx("span",{className:"flat-mobile-sidebar-toggle__label",children:"Agents"})]}),_?e.jsx(Wa,{agentId:_,terminalViewMode:Ye,onTerminalViewModeChange:Ke,inspectorOpen:$e,onToggleInspector:Pe,onShowTaskBoard:It,onImageClick:He,onFileClick:Tt,onBashClick:Ce,onViewMarkdown:Lt,onRequestClearSubordinates:Pt,keyboard:B,canNavigateBack:Rt,canNavigateForward:_t,onNavigateBack:Ne,onNavigateForward:lt,agentInfoOpen:qe,onToggleAgentInfo:Et,onHeaderContextMenu:xt,onBuildingContextMenu:Re}):e.jsx("div",{className:"flat-chat flat-chat--empty",children:e.jsxs("div",{className:"flat-map",children:[e.jsxs("div",{className:"flat-map__header",children:[e.jsx("span",{className:"flat-map__title",children:"🗺️ Areas"}),e.jsx("span",{className:"flat-map__hint",children:"Click an area to focus it, or an agent to chat"}),e.jsx(Pa,{className:"flat-map__view-mode"})]}),e.jsx("div",{className:"flat-map__grid",style:{gridTemplateColumns:`repeat(${te.gridCols}, 1fr)`},children:te.groups.length===0?e.jsx("div",{className:"flat-map__empty",children:e.jsx("span",{children:"No areas or agents yet"})}):(()=>{var s;const t=xe&&o?((s=te.positions.get(o))==null?void 0:s.row)??null:null;return te.groups.map(i=>{var E;const x=i.area.id,b=te.positions.get(x),C=xe&&o!==x;return xe&&t!=null&&(b==null?void 0:b.row)===t&&x!==o?null:e.jsxs("div",{className:`flat-map-area-card${C?" flat-map-area-card--collapsed":""}`,style:{"--area-color":i.area.color,gridRow:b==null?void 0:b.row,gridColumn:b==null?void 0:b.col},onContextMenu:m=>{k&&(m.preventDefault(),m.stopPropagation(),k(x,{x:m.clientX,y:m.clientY}))},children:[((E=i.area.logo)==null?void 0:E.filename)&&e.jsx("img",{className:"flat-map-area-card__logo",src:Na(i.area.logo.filename),alt:"","aria-hidden":"true",onError:m=>{m.currentTarget.style.display="none"}}),e.jsxs("button",{type:"button",className:"flat-map-area-card__header",onClick:()=>xe?u(x):ne(x),title:xe?C?`Expand ${i.area.name}`:`Collapse ${i.area.name}`:`Focus ${i.area.name} in left panel`,"aria-expanded":xe?!C:void 0,children:[e.jsx("span",{className:"flat-map-area-card__color",style:{background:i.area.color}}),e.jsx("span",{className:"flat-map-area-card__name",children:i.area.name}),e.jsx("span",{className:"flat-map-area-card__count",children:i.agents.length}),xe&&e.jsx(d,{name:C?"caret-down":"caret-up",size:11,className:"flat-map-area-card__caret"})]}),e.jsx("div",{className:"flat-map-area-card__agents",children:i.agents.map(m=>{const M=m.isBoss||m.class==="boss",X=M?Xe.get(m.id):void 0,z=$n(m),v=z.usedPercent>=80?"#ff4a4a":z.usedPercent>=60?"#ff9e4a":z.usedPercent>=40?"#ffd700":"#4aff9e",I=`Context: ${(z.totalTokens/1e3).toFixed(1)}k / ${(z.contextWindow/1e3).toFixed(1)}k (${z.usedPercent}% used, ${z.freePercent}% free)`,L=m.latestTodos&&m.latestTodos.length>0||X&&X.length>0;return e.jsx(On,{todos:m.latestTodos,subordinates:X,position:"top",children:e.jsxs("button",{type:"button",className:`flat-map-agent-chip ${m.status}`,onClick:()=>c(m.id),onContextMenu:q=>{q.preventDefault(),q.stopPropagation(),we({agentId:m.id,position:{x:q.clientX,y:q.clientY}})},title:L?void 0:`${M?"Boss · ":""}Open chat with ${m.name}
|
|
2
|
+
${I}`,children:[e.jsx(gn,{agent:m,size:16}),M&&e.jsx("span",{className:"flat-map-agent-chip__crown","aria-hidden":"true",children:e.jsx(d,{name:"crown",size:11,color:"#ffd700",weight:"fill"})}),e.jsx("span",{className:"flat-map-agent-chip__name",children:m.name}),e.jsx("img",{src:bn(m.provider,"/"),alt:m.provider,className:"flat-map-agent-chip__provider-icon",title:xn(m.provider)}),e.jsx("span",{className:"flat-map-agent-chip__dot",style:{backgroundColor:_n(m.status)}}),m.latestTodos&&m.latestTodos.length>0&&e.jsx(Bn,{todos:m.latestTodos,maxDots:6}),M&&X&&X.length>0&&e.jsx(Fn,{subordinates:X,maxDots:6}),e.jsx("span",{className:"flat-map-agent-chip__context-bar","aria-hidden":"true",children:e.jsx("span",{className:"flat-map-agent-chip__context-bar-fill",style:{width:`${z.usedPercent}%`,backgroundColor:v}})})]})},m.id)})}),i.area.directories.length>0&&e.jsx("div",{className:"flat-map-area-card__folders",role:"group","aria-label":`${i.area.name} folders`,children:i.area.directories.map(m=>{const M=m.split("/").filter(Boolean).pop()||m;return e.jsxs("button",{type:"button",className:"flat-map-folder-chip",onClick:X=>{X.stopPropagation(),h.openFileExplorerForAreaFolder(x,m)},title:`Open in file explorer: ${m}`,children:[e.jsx(d,{name:"folder-open",size:12}),e.jsx("span",{className:"flat-map-folder-chip__name",children:M})]},m)})}),i.buildings.length>0&&e.jsx("div",{className:"flat-map-area-card__buildings",children:i.buildings.map(m=>{var X;const M=(X=Wn[m.type])==null?void 0:X.color;return e.jsxs("button",{type:"button",className:`flat-map-building-chip flat-map-building-chip--${m.status}`,style:M?{"--building-type-color":M}:void 0,onClick:z=>{if(g){const v=z.currentTarget.getBoundingClientRect();g(m.id,{x:v.right,y:v.top+v.height/2})}else at(m.id)},onContextMenu:z=>{z.preventDefault(),z.stopPropagation(),O({buildingId:m.id,position:{x:z.clientX,y:z.clientY}})},title:`${m.name} · ${m.type} · ${m.status}`,children:[e.jsx(d,{name:Hn(m.type),size:12,color:M}),e.jsx("span",{className:"flat-map-building-chip__name",children:m.name}),e.jsx("span",{className:"flat-map-building-chip__dot",style:{backgroundColor:Un(m.status)}})]},m.id)})})]},x)})})()})]})})]}),he&&e.jsx("div",{className:"flat-splitter flat-splitter--inspector",role:"separator","aria-orientation":"vertical","aria-label":"Resize inspector panel",title:"Drag to resize · Double-click to reset",onPointerDown:je,onPointerMove:nt,onPointerUp:Te,onPointerCancel:Te,onDoubleClick:j}),Je&&e.jsxs("aside",{className:`flat-inspector ${ot?"flat-inspector--open":"flat-inspector--closing"}`,"aria-label":"Inspector panel",children:[e.jsxs("div",{className:"flat-inspector__header",children:[e.jsxs("div",{className:"flat-inspector__tabs",role:"tablist","aria-label":"Inspector view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":ee==="agent",className:`flat-inspector__tab ${ee==="agent"?"flat-inspector__tab--active":""}`,onClick:()=>Fe("agent"),children:"Agent"}),e.jsx("button",{type:"button",role:"tab","aria-selected":ee==="tracking",className:`flat-inspector__tab ${ee==="tracking"?"flat-inspector__tab--active":""}`,onClick:()=>Fe("tracking"),children:"Tracking"})]}),e.jsx("button",{type:"button",className:"flat-inspector__close",onClick:We,title:"Close inspector","aria-label":"Close inspector",children:"✕"})]}),e.jsx("div",{className:"flat-inspector__body",children:ee==="tracking"?e.jsx(Vn,{activeAgentId:_??"",onSelectAgent:t=>{c(t),window.innerWidth<=768&&We()}}):(()=>{if(!_)return e.jsx("div",{className:"flat-inspector__empty",children:e.jsx("span",{children:"Select an agent to inspect"})});const t=w.find(s=>s.id===_);return t?e.jsx(Xn,{agent:t,onFocusAgent:s=>{c(s),window.innerWidth<=768&&We()},onKillAgent:s=>h.killAgent(s)}):e.jsx("div",{className:"flat-inspector__empty",children:e.jsx("span",{children:"Agent not found"})})})()})]}),$&&e.jsx(Gn,{url:$.url,name:$.name,onClose:()=>ie(null)}),P&&e.jsx(qn,{state:P,onClose:()=>Se(null)}),e.jsx(Yn,{agent:_?w.find(t=>t.id===_)??null:null,content:le,onClose:()=>re(null)}),ze&&e.jsx(Kn,{action:"clear-subordinates",selectedAgentId:ze.agentId,subordinateCount:ze.count,onClose:()=>ft(null),onClearHistory:()=>{}}),e.jsx(Zn,{agent:_?w.find(t=>t.id===_)??null:null,isOpen:qe&&!!_,onClose:ht}),e.jsx(an,{isOpen:_e!==null,position:(_e==null?void 0:_e.position)??{x:0,y:0},worldPosition:{x:0,z:0},actions:$t,onClose:()=>we(null)}),e.jsx(an,{isOpen:f!==null,position:(f==null?void 0:f.position)??{x:0,y:0},worldPosition:{x:0,z:0},actions:jt,onClose:()=>O(null)}),e.jsx(Jn,{isOpen:Ae!==null,title:Z("common:confirm.removeAgentTitle"),message:Z("common:confirm.removeAgentMessage",{name:(Ae==null?void 0:Ae.name)??""}),confirmLabel:Z("common:buttons.remove"),cancelLabel:Z("common:buttons.cancel"),variant:"danger",onConfirm:()=>{Ae&&h.removeAgentFromServer(Ae.agentId)},onClose:()=>Ee(null)})]})}export{qa as FlatView};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as l,j as e,I,u as J,bl as ns,ag as is,bm as gs,bn as fs,s as A,bo as xs,bd as bs,bp as js,C as ge,K as Q,L as Z,i as ue,k as pe,bq as vs,br as ys,bs as ws,bt as Ns,bu as ks,bv as Ss,bw as Cs,bx as os,by as As,bz as Ts,bA as Es,J as Ps,X as _s,bB as Se,a9 as Is,bC as ls,bD as $s,bE as He,bF as Ls,bG as Os,bH as Ds,bI as Fs,bJ as zs,bK as Bs,bL as Rs,as as Ms,b6 as Us,_ as Vs,S as ke,bM as Ks,bN as Hs,b8 as Ws,bO as Ue,$ as $e,bi as qs,bP as Ve,bQ as Gs,bR as Ys,a5 as Js,m as Zs,bS as Xs,bT as Qs,bU as et}from"./main-Du_kWg5E.js";import{g as st,d as tt,u as at}from"./area-logos-CkHS76Vd.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const cs="tide-toolbox-collapse";function nt(s,a){try{const t=localStorage.getItem(`${cs}-${s}`);if(t!==null)return t==="true"}catch{}return a}function it(s,a){try{localStorage.setItem(`${cs}-${s}`,String(a))}catch{}}function G({title:s,storageKey:a,defaultOpen:t=!1,forceOpen:n=!1,children:c,headerExtra:r}){const[d,f]=l.useState(()=>a?nt(a,t):t),i=()=>{const w=!d;f(w),a&&it(a,w)},m=n||d;return e.jsxs("div",{className:`collapsible-section ${m?"open":"collapsed"}`,children:[e.jsxs("button",{className:"collapsible-header",onClick:i,children:[e.jsx("span",{className:"collapsible-title",children:s}),e.jsxs("span",{className:"collapsible-header-right",children:[r,e.jsx("span",{className:"collapsible-arrow",children:e.jsx(I,{name:m?"caret-down":"caret-right",size:10})})]})]}),m&&e.jsx("div",{className:"collapsible-content",children:c})]})}function ot({area:s,isSelected:a,onClick:t,onDelete:n}){const{t:c}=J(["config","common"]),r=s.assignedAgentIds.length,d=s.type==="rectangle"?c("config:areas.rect"):c("config:areas.circle");return e.jsxs("div",{className:`area-item ${a?"selected":""}`,onClick:t,children:[e.jsx("div",{className:"area-color-dot",style:{backgroundColor:s.color}}),e.jsxs("div",{className:"area-info",children:[e.jsx("div",{className:"area-name",children:s.name}),e.jsxs("div",{className:"area-meta",children:[d," ",r>0&&`• ${r} ${r>1?c("common:labels.agents").toLowerCase():c("common:labels.agent").toLowerCase()}`]})]}),e.jsx("button",{className:"area-delete-btn",onClick:n,title:c("config:areas.deleteArea"),children:"×"})]})}function lt({building:s,isSelected:a,onClick:t,onEdit:n}){var f;const{t:c}=J(["config"]),r=((f=s.pm2Status)==null?void 0:f.ports)||[],d=(i,m)=>{i.stopPropagation(),window.open(`http://${window.location.hostname}:${m}`,"_blank")};return e.jsxs("div",{className:`building-item ${a?"selected":""}`,onClick:t,children:[e.jsx("div",{className:"building-status-dot",style:{backgroundColor:ns[s.status]},title:s.status}),e.jsx("div",{className:"building-icon",children:e.jsx(I,{name:is(s.type),size:16})}),e.jsxs("div",{className:"building-info",children:[e.jsx("div",{className:"building-name",children:s.name}),e.jsxs("div",{className:"building-meta",children:[s.type,r.length>0&&e.jsx("span",{className:"building-ports",children:r.map(i=>e.jsxs("a",{href:`http://${window.location.hostname}:${i}`,className:"building-port-link",onClick:m=>d(m,i),title:`Open :${i}`,children:[":",i]},i))})]})]}),e.jsx("button",{className:"building-edit-btn",onClick:i=>{i.stopPropagation(),n()},title:c("config:buildings.editBuilding"),children:e.jsx(I,{name:"gear",size:14})})]})}function ct({building:s,onClose:a,onOpenModal:t}){var m,w,j,g,E,y,S,v;const{t:n}=J(["config","common"]),r=gs().get(s.id)||[],d=fs[s.style||"server-rack"],f=u=>{A.sendBuildingCommand(s.id,u)},i=u=>{window.open(u,"_blank")};return e.jsxs("div",{className:"building-editor",children:[e.jsxs("div",{className:"building-editor-header",children:[e.jsxs("div",{className:"building-editor-title-row",children:[e.jsx("span",{className:"building-editor-icon",children:e.jsx(I,{name:is(s.type),size:18})}),e.jsx("span",{className:"building-editor-title",children:s.name}),e.jsx("span",{className:"building-editor-status",style:{backgroundColor:ns[s.status]},children:s.status})]}),e.jsx("button",{className:"building-editor-close",onClick:a,children:"×"})]}),e.jsx("div",{className:"building-editor-section",children:e.jsxs("div",{className:"building-editor-info-grid",children:[e.jsxs("div",{className:"building-editor-info-item",children:[e.jsx("span",{className:"building-editor-info-label",children:n("common:labels.type")}),e.jsx("span",{className:"building-editor-info-value",children:s.type})]}),e.jsxs("div",{className:"building-editor-info-item",children:[e.jsx("span",{className:"building-editor-info-label",children:n("config:buildings.style")}),e.jsx("span",{className:"building-editor-info-value",children:d.label})]}),s.cwd&&e.jsxs("div",{className:"building-editor-info-item building-editor-info-wide",children:[e.jsx("span",{className:"building-editor-info-label",children:n("config:buildings.directory")}),e.jsx("span",{className:"building-editor-info-value building-editor-cwd",title:s.cwd,children:s.cwd.split("/").pop()||s.cwd})]})]})}),s.type==="server"&&e.jsxs("div",{className:"building-editor-section",children:[e.jsx("div",{className:"building-editor-section-title",children:n("config:buildings.actions")}),e.jsxs("div",{className:"building-editor-actions",children:[e.jsxs("button",{className:"building-editor-action-btn start",onClick:()=>f("start"),disabled:!((m=s.commands)!=null&&m.start)||s.status==="running",title:((w=s.commands)==null?void 0:w.start)||n("config:buildings.noStartCommand"),children:[e.jsx(I,{name:"play",size:12})," ",n("common:buttons.start")]}),e.jsxs("button",{className:"building-editor-action-btn stop",onClick:()=>f("stop"),disabled:!((j=s.commands)!=null&&j.stop)||s.status==="stopped",title:((g=s.commands)==null?void 0:g.stop)||n("config:buildings.noStopCommand"),children:[e.jsx(I,{name:"stop",size:12,weight:"fill"})," ",n("common:buttons.stop")]}),e.jsxs("button",{className:"building-editor-action-btn restart",onClick:()=>f("restart"),disabled:!((E=s.commands)!=null&&E.restart),title:((y=s.commands)==null?void 0:y.restart)||n("config:buildings.noRestartCommand"),children:[e.jsx(I,{name:"refresh",size:12})," ",n("common:buttons.retry")]}),e.jsxs("button",{className:"building-editor-action-btn health",onClick:()=>f("healthCheck"),disabled:!((S=s.commands)!=null&&S.healthCheck),title:((v=s.commands)==null?void 0:v.healthCheck)||n("config:buildings.noHealthCheck"),children:[e.jsx(I,{name:"heart",size:12})," Health"]})]})]}),s.urls&&s.urls.length>0&&e.jsxs("div",{className:"building-editor-section",children:[e.jsx("div",{className:"building-editor-section-title",children:n("config:buildings.links")}),e.jsx("div",{className:"building-editor-links",children:s.urls.map((u,k)=>e.jsxs("button",{className:"building-editor-link",onClick:()=>i(u.url),title:u.url,children:[e.jsx(I,{name:"link",size:12})," ",u.label||u.url]},k))})]}),r.length>0&&e.jsxs("div",{className:"building-editor-section",children:[e.jsxs("div",{className:"building-editor-section-title",children:[n("config:buildings.recentLogs"),e.jsx("button",{className:"building-editor-clear-logs",onClick:()=>A.clearBuildingLogs(s.id),title:n("common:buttons.clear"),children:n("common:buttons.clear")})]}),e.jsx("div",{className:"building-editor-logs",children:r.slice(-5).map((u,k)=>e.jsx("div",{className:"building-editor-log-entry",children:u},k))})]}),e.jsx("div",{className:"building-editor-footer",children:e.jsxs("button",{className:"building-editor-edit-btn",onClick:t,children:[e.jsx(I,{name:"gear",size:12})," ",n("config:buildings.fullSettings")]})})]})}const rt=[{key:"center",labelKey:"posCenter"},{key:"top-left",labelKey:"posTopLeft"},{key:"top-right",labelKey:"posTopRight"},{key:"bottom-left",labelKey:"posBottomLeft"},{key:"bottom-right",labelKey:"posBottomRight"}];function dt({area:s,onClose:a,onOpenFolder:t}){var se;const{t:n}=J(["config","common"]),[c,r]=l.useState(s.name),[d,f]=l.useState(s.prompt||""),[i,m]=l.useState(!1),[w,j]=l.useState(""),[g,E]=l.useState(!1),y=l.useRef(null);l.useEffect(()=>{r(s.name)},[s.id,s.name]),l.useEffect(()=>{f(s.prompt||"")},[s.id,s.prompt]);const S=N=>{const O=N.target.value;r(O),A.updateArea(s.id,{name:O})},v=N=>{A.updateArea(s.id,{color:N})},u=N=>{const O=N.target.value;f(O),A.updateArea(s.id,{prompt:O})},k=()=>{w.trim()&&(A.addDirectoryToArea(s.id,w.trim()),j(""),m(!1))},D=(N,O)=>{O.stopPropagation(),A.removeDirectoryFromArea(s.id,N)},F=()=>{A.bringAreaToFront(s.id)},V=()=>{A.sendAreaToBack(s.id)},W=l.useCallback(()=>{let N=2,O=2;s.type==="rectangle"&&s.width&&s.height?(N=s.width,O=s.height):s.type==="circle"&&s.radius&&(N=s.radius*1.414,O=s.radius*1.414);const M=Math.min(N,O)*.4;return{width:Math.round(M*10)/10,height:Math.round(M*10)/10}},[s.type,s.width,s.height,s.radius]),q=async N=>{var M;const O=(M=N.target.files)==null?void 0:M[0];if(O){E(!0);try{const p=await at(s.id,O),b=W();A.updateArea(s.id,{logo:{filename:p.filename,position:"center",width:b.width,height:b.height,keepAspectRatio:!0,opacity:.8}})}catch(p){console.error("Failed to upload logo:",p)}finally{E(!1),y.current&&(y.current.value="")}}},R=async()=>{try{await tt(s.id),A.updateArea(s.id,{logo:void 0})}catch(N){console.error("Failed to remove logo:",N)}},K=N=>{s.logo&&A.updateArea(s.id,{logo:{...s.logo,position:N}})},h=N=>{if(!s.logo)return;const O=parseFloat(N.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.width>0){const M=s.logo.height/s.logo.width;A.updateArea(s.id,{logo:{...s.logo,width:O,height:Math.round(O*M*10)/10}})}else A.updateArea(s.id,{logo:{...s.logo,width:O}})},$=N=>{if(!s.logo)return;const O=parseFloat(N.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.height>0){const M=s.logo.width/s.logo.height;A.updateArea(s.id,{logo:{...s.logo,height:O,width:Math.round(O*M*10)/10}})}else A.updateArea(s.id,{logo:{...s.logo,height:O}})},U=()=>{s.logo&&A.updateArea(s.id,{logo:{...s.logo,keepAspectRatio:!s.logo.keepAspectRatio}})},H=N=>{s.logo&&A.updateArea(s.id,{logo:{...s.logo,opacity:parseFloat(N.target.value)}})};return e.jsxs("div",{className:"area-editor",children:[e.jsxs("div",{className:"area-editor-header",children:[e.jsx("span",{className:"area-editor-title",children:n("config:areas.editArea")}),e.jsx("button",{className:"area-editor-close",onClick:a,children:"×"})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:n("common:labels.name")}),e.jsx("input",{type:"text",className:"area-editor-input",value:c,onChange:S,placeholder:n("config:areas.areaName")})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:n("config:areas.color")}),e.jsx("div",{className:"color-picker-row",children:xs.map(N=>e.jsx("button",{type:"button",className:`color-swatch ${s.color===N?"selected":""}`,style:{backgroundColor:N},onClick:()=>v(N),"aria-label":`Set area color ${N}`,"aria-pressed":s.color===N,title:N},N))})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:n("config:areas.layer")}),e.jsxs("div",{className:"area-layer-buttons",children:[e.jsxs("button",{className:"area-layer-btn",onClick:F,title:n("config:areas.bringToFront"),children:[e.jsx(I,{name:"arrow-up",size:12})," ",n("config:areas.front")]}),e.jsxs("button",{className:"area-layer-btn",onClick:V,title:n("config:areas.sendToBack"),children:[e.jsx(I,{name:"arrow-down",size:12})," ",n("config:areas.back")]})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:n("config:areas.logo")}),e.jsxs("div",{className:"area-logo-section",children:[(se=s.logo)!=null&&se.filename?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"area-logo-preview",children:[e.jsx("img",{src:st(s.logo.filename),alt:"Logo",className:"area-logo-thumbnail"}),e.jsx("button",{className:"area-logo-remove-btn",onClick:R,children:n("config:areas.removeLogo")}),e.jsx("button",{className:"area-logo-replace-btn",onClick:()=>{var N;return(N=y.current)==null?void 0:N.click()},disabled:g,children:g?"...":e.jsx(I,{name:"refresh",size:12})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:n("config:areas.logoPosition")}),e.jsx("div",{className:"area-logo-position-row",children:rt.map(({key:N,labelKey:O})=>{var M;return e.jsx("button",{className:`area-logo-pos-btn ${((M=s.logo)==null?void 0:M.position)===N?"active":""}`,onClick:()=>K(N),children:n(`config:areas.${O}`)},N)})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:n("config:areas.logoSize")}),e.jsxs("div",{className:"area-logo-size-row",children:[e.jsxs("label",{className:"area-logo-size-field",children:[e.jsx("span",{children:n("config:areas.logoWidth")}),e.jsx("input",{type:"number",className:"area-logo-size-input",value:s.logo.width,onChange:h,min:.1,step:.1})]}),e.jsxs("label",{className:"area-logo-size-field",children:[e.jsx("span",{children:n("config:areas.logoHeight")}),e.jsx("input",{type:"number",className:"area-logo-size-input",value:s.logo.height,onChange:$,min:.1,step:.1})]}),e.jsxs("label",{className:"area-logo-aspect-label",title:n("config:areas.keepAspectRatio"),children:[e.jsx("input",{type:"checkbox",checked:s.logo.keepAspectRatio,onChange:U}),n("config:areas.keepAspectRatio")]})]})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:n("config:areas.logoOpacity")}),e.jsxs("div",{className:"area-logo-opacity-row",children:[e.jsx("input",{type:"range",min:0,max:1,step:.05,value:s.logo.opacity??.8,onChange:H,className:"area-logo-opacity-slider"}),e.jsxs("span",{className:"area-logo-opacity-value",children:[Math.round((s.logo.opacity??.8)*100),"%"]})]})]})]}):e.jsx("button",{className:"area-logo-upload-btn",onClick:()=>{var N;return(N=y.current)==null?void 0:N.click()},disabled:g,children:g?"...":n("config:areas.uploadLogo")}),e.jsx("input",{ref:y,type:"file",accept:"image/*",style:{display:"none"},onChange:q})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:n("config:areas.folders",{count:s.directories.length})}),e.jsxs("div",{className:"area-folders-list",children:[s.directories.map(N=>e.jsxs("div",{className:"area-folder-item",title:N,children:[e.jsx("span",{className:"area-folder-icon clickable",onClick:()=>t==null?void 0:t(s.id),title:n("config:areas.openFolder"),children:e.jsx(I,{name:"folder",size:14})}),e.jsx("span",{className:"area-folder-path",children:N.split("/").pop()||N}),e.jsx("button",{className:"area-folder-remove",onClick:O=>D(N,O),title:n("config:areas.removeFolder"),children:"×"})]},N)),i?e.jsxs("div",{className:"area-add-folder-inline",children:[e.jsx(bs,{value:w,onChange:j,onSubmit:k,placeholder:n("config:areas.folderPlaceholder"),className:"area-add-folder-input",directoriesOnly:!0,autoFocus:!0}),e.jsx("button",{className:"area-add-folder-confirm",onClick:k,children:"+"})]}):e.jsx("button",{className:"area-add-folder-btn",onClick:()=>m(!0),children:n("config:areas.addFolder")})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:n("config:areas.prompt","Prompt")}),e.jsx("textarea",{className:"area-editor-input",value:d,onChange:u,placeholder:n("config:areas.promptPlaceholder","System prompt for agents in this area..."),rows:4,style:{resize:"vertical",fontFamily:"monospace",fontSize:12}}),e.jsx("div",{style:{fontSize:11,color:"var(--text-secondary)",marginTop:4},children:n("config:areas.promptHint","This prompt is injected into agents assigned to this area. Takes effect on next context refresh.")})]}),s.assignedAgentIds.length>0&&e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:n("config:areas.assignedAgents",{count:s.assignedAgentIds.length})}),e.jsx("div",{style:{fontSize:12,color:"var(--text-secondary)"},children:n("config:areas.rightClickUnassign")})]})]})}function ut(){const{t:s}=J(["config","common"]),a=js(),[t,n]=l.useState(!1),[c,r]=l.useState(null),[d,f]=l.useState({name:"",key:"",value:"",description:""}),[i,m]=l.useState(null),w=()=>{n(!0),r(null),f({name:"",key:"",value:"",description:""})},j=u=>{r(u.id),n(!1),f({name:u.name,key:u.key,value:u.value,description:u.description||""})},g=()=>{n(!1),r(null),f({name:"",key:"",value:"",description:""})},E=()=>{!d.name.trim()||!d.key.trim()||(c?A.updateSecret(c,{name:d.name.trim(),key:d.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:d.value,description:d.description.trim()||void 0}):A.createSecret({name:d.name.trim(),key:d.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:d.value,description:d.description.trim()||void 0}),g())},y=u=>{m(u)},S=()=>{i&&(A.deleteSecret(i),c===i&&g())},v=u=>{navigator.clipboard.writeText(`{{${u}}}`)};return e.jsxs("div",{className:"secrets-section",children:[e.jsx("div",{className:"secrets-description",children:s("config:secrets.description",{placeholder:"{{KEY}}"})}),e.jsx("div",{className:"secrets-list",children:a.length===0&&!t?e.jsx("div",{className:"secrets-empty",children:s("config:secrets.noSecrets")}):a.map(u=>e.jsxs("div",{className:`secret-item ${c===u.id?"editing":""}`,children:[e.jsxs("div",{className:"secret-item-header",children:[e.jsxs("div",{className:"secret-item-info",children:[e.jsx("span",{className:"secret-item-name",children:u.name}),e.jsx("code",{className:"secret-item-key",onClick:()=>v(u.key),title:s("config:secrets.copyPlaceholder"),children:`{{${u.key}}}`})]}),e.jsxs("div",{className:"secret-item-actions",children:[e.jsx("button",{className:"secret-item-btn edit",onClick:()=>j(u),title:s("common:buttons.edit"),children:e.jsx(I,{name:"edit",size:12})}),e.jsx("button",{className:"secret-item-btn delete",onClick:()=>y(u.id),title:s("common:buttons.delete"),children:"×"})]})]}),u.description&&e.jsx("div",{className:"secret-item-description",children:u.description})]},u.id))}),(t||c)&&e.jsxs("div",{className:"secret-form",children:[e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("common:labels.name")}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.namePlaceholder"),value:d.name,onChange:u=>f({...d,name:u.target.value}),autoFocus:!0})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:"Key"}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.keyPlaceholder"),value:d.key,onChange:u=>f({...d,key:u.target.value.toUpperCase().replace(/[^A-Z0-9_]/g,"")})}),e.jsx("span",{className:"secret-form-hint",children:s("config:secrets.usedAs",{placeholder:`{{${d.key||"KEY"}}}`})})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("config:secrets.secretValue")}),e.jsx("input",{type:"password",className:"secret-form-input",placeholder:s("config:secrets.valuePlaceholder"),value:d.value,onChange:u=>f({...d,value:u.target.value})})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("common:labels.description")}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.descriptionPlaceholder"),value:d.description,onChange:u=>f({...d,description:u.target.value})})]}),e.jsxs("div",{className:"secret-form-actions",children:[e.jsx("button",{className:"secret-form-btn cancel",onClick:g,children:s("common:buttons.cancel")}),e.jsx("button",{className:"secret-form-btn save",onClick:E,disabled:!d.name.trim()||!d.key.trim(),children:s(c?"config:secrets.update":"common:buttons.add")})]})]}),!t&&!c&&e.jsx("button",{className:"secrets-add-btn",onClick:w,children:s("config:secrets.addSecret")}),e.jsx(ge,{isOpen:i!==null,title:s("common:buttons.delete"),message:s("config:secrets.deleteConfirm"),confirmLabel:s("common:buttons.delete"),cancelLabel:s("common:buttons.cancel"),variant:"danger",onConfirm:S,onClose:()=>m(null)})]})}async function pt(){const s=Q(),a=await fetch(`${Z()}/api/agents/system-settings/prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch system prompt: ${a.statusText}`);return(await a.json()).prompt||""}async function mt(s){const a=Q(),t=await fetch(`${Z()}/api/agents/system-settings/prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({prompt:s})});if(!t.ok)throw new Error(`Failed to update system prompt: ${t.statusText}`)}async function ht(){const s=Q(),a=await fetch(`${Z()}/api/agents/system-settings/prompt`,{method:"DELETE",headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to clear system prompt: ${a.statusText}`)}async function gt(){const s=Q(),a=await fetch(`${Z()}/api/agents/system-settings/echo-prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch echo prompt setting: ${a.statusText}`);return(await a.json()).enabled||!1}async function ft(s){const a=Q(),t=await fetch(`${Z()}/api/agents/system-settings/echo-prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update echo prompt setting: ${t.statusText}`)}async function xt(){const s=Q(),a=await fetch(`${Z()}/api/agents/system-settings/codex-binary`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch codex binary path: ${a.statusText}`);return(await a.json()).path||""}async function bt(s){const a=Q(),t=await fetch(`${Z()}/api/agents/system-settings/codex-binary`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({path:s})});if(!t.ok)throw new Error(`Failed to update codex binary path: ${t.statusText}`)}async function jt(){const s=Q(),a=await fetch(`${Z()}/api/agents/system-settings/tmux-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch tmux mode setting: ${a.statusText}`);return(await a.json()).enabled||!1}async function vt(s){const a=Q(),t=await fetch(`${Z()}/api/agents/system-settings/tmux-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update tmux mode setting: ${t.statusText}`)}async function yt(){const s=Q(),a=await fetch(`${Z()}/api/agents/system-settings/interactive-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch interactive mode setting: ${a.statusText}`);return(await a.json()).enabled||!1}async function wt(s){const a=Q(),t=await fetch(`${Z()}/api/agents/system-settings/interactive-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update interactive mode setting: ${t.statusText}`)}async function Nt(){const s=Q(),a=await fetch(`${Z()}/api/agents/system-settings/codex-app-server-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch codex app-server mode setting: ${a.statusText}`);return(await a.json()).enabled||!1}async function kt(s){const a=Q(),t=await fetch(`${Z()}/api/agents/system-settings/codex-app-server-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update codex app-server mode setting: ${t.statusText}`)}async function St(){const s=Q(),a=await fetch(`${Z()}/api/agents/system-settings/opencode-server-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch opencode server mode setting: ${a.statusText}`);return(await a.json()).enabled||!1}async function Ct(s){const a=Q(),t=await fetch(`${Z()}/api/agents/system-settings/opencode-server-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update opencode server mode setting: ${t.statusText}`)}async function At(){const s=Q(),a=await fetch(`${Z()}/api/agents/system-settings/backup`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch backup status: ${a.statusText}`);return a.json()}async function Tt(s){const a=Q(),t=await fetch(`${Z()}/api/agents/system-settings/backup`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error||`Failed to update backup setting: ${t.statusText}`)}return t.json()}function Et({checked:s,onChange:a,disabled:t}){return e.jsxs("label",{className:"config-toggle",children:[e.jsx("input",{type:"checkbox",className:"config-toggle-input",checked:s,disabled:t,onChange:n=>a(n.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})}function Pt(){const{t:s}=J(["config","common"]),[a,t]=l.useState([]),[n,c]=l.useState(new Set),[r,d]=l.useState(new Set),[f,i]=l.useState(!1),[m,w]=l.useState(!1),[j,g]=l.useState(null),[E,y]=l.useState(null),[S,v]=l.useState(null),[u,k]=l.useState(null),[D,F]=l.useState(!1),[V,W]=l.useState(null);l.useEffect(()=>{ue(pe("/api/config/categories")).then(p=>p.json()).then(p=>{const b=Array.isArray(p)?p:[];t(b),c(new Set(b.map(L=>L.id)))}).catch(p=>console.error("Failed to fetch config categories:",p))},[]),l.useEffect(()=>{At().then(k).catch(p=>{console.error("Failed to fetch backup status:",p),W(p.message||"Failed to fetch backup status")})},[]);const q=async p=>{if(!D){F(!0),W(null);try{const b=await Tt(p);k(b)}catch(b){W(b.message||"Failed to update backup setting")}finally{F(!1)}}},R=p=>{c(b=>{const L=new Set(b);return L.has(p)?L.delete(p):L.add(p),L})},K=p=>{d(b=>{const L=new Set(b);return L.has(p)?L.delete(p):L.add(p),L})},h=()=>c(new Set(a.map(p=>p.id))),$=()=>c(new Set),U=()=>{E&&d(new Set(E.categories.map(p=>p.id)))},H=()=>d(new Set),se=async()=>{var p;if(n.size!==0){i(!0),v(null);try{const b=Array.from(n).join(","),L=await ue(pe(`/api/config/export?categories=${b}`));if(!L.ok)throw new Error("Export failed");const X=await L.blob(),ae=window.URL.createObjectURL(X),T=document.createElement("a");T.href=ae;const C=L.headers.get("Content-Disposition"),ee=((p=C==null?void 0:C.match(/filename="(.+)"/))==null?void 0:p[1])||"tide-commander-config.zip";T.download=ee,document.body.appendChild(T),T.click(),document.body.removeChild(T),window.URL.revokeObjectURL(ae),v({type:"success",text:s("config:data.exportSuccess")})}catch(b){v({type:"error",text:b.message||"Export failed"})}finally{i(!1)}}},N=async p=>{var L;const b=(L=p.target.files)==null?void 0:L[0];if(b){g(b),v(null),y(null),d(new Set);try{const X=await ue(pe("/api/config/preview"),{method:"POST",headers:{"Content-Type":"application/zip"},body:await b.arrayBuffer()});if(!X.ok){const C=await X.json();throw new Error(C.error||"Failed to preview config file")}const ae=await X.json(),T=Array.isArray(ae.categories)?ae.categories:[];y({...ae,categories:T}),d(new Set(T.map(C=>C.id)))}catch(X){v({type:"error",text:X.message||"Failed to read config file"}),g(null)}}},O=async()=>{if(!(!j||r.size===0)){w(!0),v(null);try{const p=Array.from(r).join(","),b=await ue(pe(`/api/config/import?categories=${p}`),{method:"POST",headers:{"Content-Type":"application/zip"},body:await j.arrayBuffer()}),L=await b.json();if(!b.ok)throw new Error(L.error||"Import failed");v({type:"success",text:L.message||s("config:data.importSuccess")}),g(null),y(null),d(new Set)}catch(p){v({type:"error",text:p.message||"Import failed"})}finally{w(!1)}}},M=()=>{g(null),y(null),d(new Set),v(null)};return e.jsxs("div",{className:"data-section",children:[S&&e.jsx("div",{className:`data-message data-message-${S.type}`,children:S.text}),e.jsxs("div",{className:"data-subsection",children:[e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-title",children:"Hourly Backups"}),e.jsx(Et,{checked:!!(u!=null&&u.enabled),disabled:D||!u,onChange:q})]}),e.jsxs("div",{className:"data-backup-info",children:[u?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:["Saves a compressed snapshot of your data every hour to"," ",e.jsx("code",{children:u.backupDir}),". Identical snapshots are skipped. Keeps the 8 newest plus one from each of the 2 most recent prior days."]}),!u.scriptExists&&e.jsxs("div",{style:{marginTop:6,color:"var(--dracula-red, #ff5555)"},children:["Backup script not found at ",e.jsx("code",{children:u.scriptPath})]}),u.lastRunAt&&e.jsxs("div",{style:{marginTop:6},children:["Last run: ",new Date(u.lastRunAt).toLocaleString(),u.lastRunOk===!0&&" — ok",u.lastRunOk===!1&&u.lastRunError&&e.jsxs("span",{style:{color:"var(--dracula-red, #ff5555)"},children:[" — ",u.lastRunError]})]})]}):e.jsx("div",{children:"Loading backup status…"}),V&&e.jsx("div",{className:"data-message data-message-error",style:{marginTop:6},children:V})]})]}),e.jsxs("div",{className:"data-subsection",children:[e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-title",children:s("config:data.exportData")}),e.jsxs("div",{className:"data-select-controls",children:[e.jsx("button",{className:"data-select-btn",onClick:h,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:$,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:a.map(p=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:n.has(p.id),onChange:()=>R(p.id)}),e.jsx("span",{className:"data-category-name",children:p.name})]},p.id))}),e.jsx("button",{className:"data-action-btn export",onClick:se,disabled:f||n.size===0,children:f?s("config:data.exporting"):s("config:data.exportCount",{count:n.size})})]}),e.jsxs("div",{className:"data-subsection",children:[e.jsx("div",{className:"data-subsection-header",children:e.jsx("span",{className:"data-subsection-title",children:s("config:data.importData")})}),j?E?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"data-import-info",children:[e.jsx("div",{className:"data-import-file",children:j.name}),e.jsxs("div",{className:"data-import-date",children:[s("config:data.exported"),": ",new Date(E.exportedAt).toLocaleDateString()]})]}),e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-subtitle",children:s("config:data.selectToImport")}),e.jsxs("div",{className:"data-select-controls",children:[e.jsx("button",{className:"data-select-btn",onClick:U,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:H,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:E.categories.map(p=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:r.has(p.id),onChange:()=>K(p.id)}),e.jsx("span",{className:"data-category-name",children:p.name}),p.fileCount&&e.jsxs("span",{className:"data-category-count",children:["(",p.fileCount," ",s("config:data.files"),")"]})]},p.id))}),e.jsxs("div",{className:"data-import-actions",children:[e.jsx("button",{className:"data-action-btn cancel",onClick:M,children:s("common:buttons.cancel")}),e.jsx("button",{className:"data-action-btn import",onClick:O,disabled:m||r.size===0,children:m?s("config:data.importing"):s("config:data.importCount",{count:r.size})})]})]}):e.jsx("div",{className:"data-loading",children:s("config:data.readingFile")}):e.jsxs("label",{className:"data-file-input",children:[e.jsx("input",{type:"file",accept:".zip",onChange:N,style:{display:"none"}}),e.jsx("span",{className:"data-file-input-label",children:s("config:data.selectFile")})]})]})]})}function _t(){const[s,a]=l.useState(()=>vs()),t=n=>{a(n);const c=ks(n);Ss(c)};return e.jsx("div",{className:"theme-selector",children:e.jsx("div",{className:"theme-selector-grid",children:ys.map(n=>e.jsxs("button",{className:`theme-option ${s===n.id?"active":""}`,onClick:()=>t(n.id),title:n.description,children:[e.jsx("div",{className:"theme-preview",children:e.jsxs("div",{className:"theme-preview-bg",style:{backgroundColor:n.colors.bgPrimary},children:[e.jsx("div",{className:"theme-preview-accent",style:{backgroundColor:n.colors.accentBlue}}),e.jsx("div",{className:"theme-preview-claude",style:{backgroundColor:n.colors.accentClaude}})]})}),e.jsx("span",{className:"theme-name",children:n.name})]},n.id))})})}function It(){const{t:s}=J(["config"]),{installInfo:a,phase:t,output:n,error:c,newVersion:r,autoRestart:d,refreshInstallInfo:f,runUpdate:i,reset:m}=Cs(),[w,j]=l.useState(!1),g=l.useRef(null);l.useEffect(()=>{f()},[f]),l.useEffect(()=>{g.current&&(g.current.scrollTop=g.current.scrollHeight)},[n]);const E=l.useCallback(()=>{j(!0)},[]),y=l.useCallback(()=>{j(!1)},[]),S=l.useCallback(()=>{j(!1),i()},[i]),v=l.useCallback(()=>{m(),j(!1),f()},[m,f]),u=os.isNativePlatform(),k=s(u?"config:about.autoUpdateServerTitle":"config:about.autoUpdateTitle");return a?a.isGlobalInstall?a.autoUpdateSupported?!a.updateAvailable&&t==="idle"?null:e.jsxs("div",{className:"about-autoupdate",children:[e.jsx("div",{className:"about-autoupdate-title",children:k}),t==="idle"&&!w&&a.updateAvailable&&e.jsxs("div",{className:"about-autoupdate-row",children:[e.jsxs("span",{className:"about-autoupdate-versions",children:[e.jsx("span",{className:"about-autoupdate-current",children:a.currentVersion}),e.jsx("span",{className:"about-autoupdate-arrow",children:"→"}),e.jsx("span",{className:"about-autoupdate-latest",children:a.latestVersion})]}),e.jsx("button",{className:"about-update-btn download",onClick:E,children:s("config:about.autoUpdateButton")})]}),t==="idle"&&w&&e.jsxs("div",{className:"about-autoupdate-confirm",children:[e.jsx("div",{className:"about-autoupdate-confirm-title",children:s("config:about.autoUpdateConfirmTitle")}),e.jsx("div",{className:"about-autoupdate-confirm-body",children:s("config:about.autoUpdateConfirmBody")}),e.jsxs("div",{className:"about-autoupdate-confirm-actions",children:[e.jsx("button",{className:"about-update-btn changelog",onClick:y,children:s("config:about.autoUpdateCancel")}),e.jsx("button",{className:"about-update-btn download",onClick:S,children:s("config:about.autoUpdateConfirm")})]})]}),(t==="running"||t==="success"||t==="failed")&&e.jsxs("div",{className:"about-autoupdate-stream",children:[e.jsxs("div",{className:"about-autoupdate-stream-title",children:[t==="running"&&s("config:about.autoUpdateRunning"),t==="success"&&s("config:about.autoUpdateSuccess"),t==="failed"&&s("config:about.autoUpdateFailed")]}),e.jsx("pre",{ref:g,className:"about-autoupdate-output",children:n||"..."}),t==="success"&&e.jsxs("div",{className:"about-autoupdate-success-hint",children:[r&&e.jsxs("div",{className:"about-autoupdate-newversion",children:["v",r]}),e.jsx("div",{children:s(d?"config:about.autoUpdateReconnectHint":"config:about.autoUpdateRestartHint")})]}),t==="failed"&&c&&e.jsx("div",{className:"about-update-error",children:c}),(t==="success"||t==="failed")&&e.jsx("div",{className:"about-autoupdate-stream-actions",children:e.jsx("button",{className:"about-update-btn changelog",onClick:v,children:s("config:about.autoUpdateClose")})})]})]}):u?null:e.jsxs("div",{className:"about-autoupdate",children:[e.jsx("div",{className:"about-autoupdate-title",children:k}),e.jsx("div",{className:"about-autoupdate-devnote",children:s("config:about.autoUpdatePackageManagerNotice",{pm:a.packageManager})}),a.suggestedManualCommand&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"about-autoupdate-manualhint",children:s("config:about.autoUpdateManualCommand")}),e.jsx("pre",{className:"about-autoupdate-manualcmd",children:a.suggestedManualCommand})]})]}):u?null:e.jsxs("div",{className:"about-autoupdate",children:[e.jsx("div",{className:"about-autoupdate-title",children:k}),e.jsx("div",{className:"about-autoupdate-devnote",children:s("config:about.autoUpdateDevMode")})]}):null}function $t(){const{t:s}=J(["config"]),[a,t]=l.useState(null),[n,c]=l.useState(!1),[r,d]=l.useState(null);l.useEffect(()=>{As().then(t).catch(w=>d(w.message))},[]);const f=l.useCallback(async w=>{if(!n){c(!0),d(null);try{t(await Ts(w))}catch(j){d(j.message)}finally{c(!1)}}},[n]),i=os.isNativePlatform(),m=s(i?"config:about.unattendedServerTitle":"config:about.unattendedTitle");return!a&&!r?null:a?i&&!a.supported?null:e.jsxs("div",{className:"about-autoupdate",children:[e.jsx("div",{className:"about-autoupdate-title",children:m}),e.jsxs("div",{className:"about-autoupdate-row",children:[e.jsx("span",{className:"about-autoupdate-devnote",children:s("config:about.unattendedDesc")}),e.jsxs("label",{className:"config-toggle",style:a.supported?void 0:{opacity:.5},children:[e.jsx("input",{type:"checkbox",className:"config-toggle-input",checked:a.enabled,disabled:n||!a.supported,onChange:w=>void f(w.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})]}),!a.supported&&e.jsx("div",{className:"about-autoupdate-devnote",children:s("config:about.unattendedUnsupported")}),a.supported&&a.enabled&&a.pendingRestartVersion&&e.jsx("div",{className:"about-autoupdate-devnote",children:s("config:about.unattendedPendingRestart",{version:a.pendingRestartVersion})}),a.supported&&a.enabled&&!a.pendingRestartVersion&&a.lastResult&&e.jsx("div",{className:"about-autoupdate-devnote",children:a.lastResult}),r&&e.jsx("div",{className:"about-update-error",children:r})]}):i?null:e.jsxs("div",{className:"about-autoupdate",children:[e.jsx("div",{className:"about-autoupdate-title",children:m}),e.jsx("div",{className:"about-update-error",children:r})]})}function Lt(){var D;const{t:s}=J(["config"]),{isAndroid:a,supported:t,otaActive:n,bundleState:c,serverInfo:r,infoError:d,updateAvailable:f,phase:i,progress:m,error:w,autoSync:j,checkNow:g,syncNow:E,resetToBundled:y,setAutoSync:S}=Es(),[v,u]=l.useState(null),k=l.useRef(g);return k.current=g,l.useEffect(()=>{a&&(k.current(!1),Ps.getInfo().then(F=>u(F.version)).catch(()=>{}))},[a]),!a||t===!1?null:e.jsxs("div",{className:"about-autoupdate",children:[e.jsx("div",{className:"about-autoupdate-title",children:s("config:webBundle.title")}),e.jsxs("div",{className:"about-autoupdate-devnote",children:[n?s("config:webBundle.sourceOta",{hash:((D=c==null?void 0:c.hash)==null?void 0:D.slice(0,8))??"?"}):s("config:webBundle.sourceBundled"),v&&` · ${s("config:webBundle.apkVersion",{version:v})}`]}),r?e.jsxs("div",{className:"about-autoupdate-devnote",children:[s("config:webBundle.serverBundle",{version:r.version,hash:r.hash.slice(0,8)})," — ",s(f?"config:webBundle.updateAvailable":"config:webBundle.upToDate")]}):d&&e.jsx("div",{className:"about-autoupdate-devnote",children:s("config:webBundle.serverUnavailable")}),w&&e.jsx("div",{className:"about-update-error",children:w}),e.jsxs("div",{className:"about-autoupdate-row",children:[e.jsx("span",{className:"about-autoupdate-devnote",children:s("config:webBundle.autoSync")}),e.jsxs("label",{className:"config-toggle",children:[e.jsx("input",{type:"checkbox",className:"config-toggle-input",checked:j,onChange:F=>S(F.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})]}),e.jsxs("div",{className:"about-update-actions",children:[e.jsx("button",{className:"about-update-btn download",onClick:()=>void E(),disabled:i!=="idle"||!r,children:i==="syncing"?s("config:webBundle.syncingPct",{percent:m??0}):s("config:webBundle.syncNow")}),n&&e.jsx("button",{className:"about-update-btn changelog",onClick:()=>void y(),children:s("config:webBundle.reset")})]})]})}function Ot(){const{t:s}=J(["config"]),{updateAvailable:a,updateInfo:t,recentReleases:n,isChecking:c,error:r,currentVersion:d,isAndroid:f,downloadPhase:i,downloadProgress:m,checkForUpdate:w,downloadAndInstall:j,openReleasePage:g}=ws(),[E,y]=l.useState(!1),S=u=>u?`${(u/(1024*1024)).toFixed(1)} MB`:"",v=u=>new Date(u).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"});return e.jsxs("div",{className:"about-section",children:[e.jsxs("div",{className:"about-logo",children:[e.jsx("span",{className:"about-logo-icon",children:e.jsx(I,{name:"waves",size:24})}),e.jsx("span",{className:"about-logo-text",children:"Tide Commander"})]}),e.jsxs("div",{className:"about-version",children:[e.jsx("span",{className:"about-version-label",children:s("config:about.version")}),e.jsxs("div",{className:"about-version-info",children:[e.jsx("span",{className:"about-version-value",children:d}),a&&t?e.jsx("span",{className:"about-version-update-badge",onClick:g,title:`Update available: ${t.version}`,children:t.version}):e.jsxs("a",{href:"https://github.com/deivid11/tide-commander/releases",target:"_blank",rel:"noopener noreferrer",className:"about-version-status",children:["(",s("config:about.updated"),")"]})]})]}),e.jsx(It,{}),e.jsx($t,{}),e.jsx(Lt,{}),e.jsx("div",{className:"about-changelog-row",children:e.jsx("button",{className:"about-update-btn changelog",onClick:()=>y(!0),children:s("config:about.changelog")})}),e.jsxs("div",{className:"about-update",children:[a&&t?e.jsxs("div",{className:"about-update-available",children:[e.jsxs("div",{className:"about-update-header",children:[e.jsx("span",{className:"about-update-badge",children:s("config:about.updateAvailable")}),e.jsx("span",{className:"about-update-version",children:t.version})]}),t.apkSize&&e.jsxs("div",{className:"about-update-size",children:[s("config:about.sizeLabel"),": ",S(t.apkSize)]}),r&&e.jsx("div",{className:"about-update-error",children:r}),e.jsxs("div",{className:"about-update-actions",children:[e.jsx("button",{className:"about-update-btn changelog",onClick:g,children:s("config:about.changelog")}),f&&t.apkUrl?e.jsx("button",{className:"about-update-btn download",onClick:()=>void j(),disabled:i!=="idle",children:i==="downloading"?s("config:appUpdateBanner.downloadingPct",{percent:m??0}):s(i==="installing"?"config:appUpdateBanner.installHint":"config:about.downloadAPK")}):e.jsx("button",{className:"about-update-btn download",onClick:g,children:s("config:about.viewRelease")})]})]}):e.jsxs("div",{className:"about-update-check",children:[e.jsx("span",{className:"about-update-status",children:s(c?"config:about.checkingUpdates":"config:about.upToDate")}),e.jsx("button",{className:"about-update-btn check",onClick:()=>w(!0),disabled:c,children:c?"...":s("config:about.check")})]}),n.length>0&&e.jsxs("div",{className:"about-releases",children:[e.jsx("div",{className:"about-releases-title",children:s("config:about.recentReleases")}),e.jsx("div",{className:"about-releases-list",children:n.map(u=>e.jsxs("a",{href:u.releaseUrl,target:"_blank",rel:"noopener noreferrer",className:`about-release-item ${u.version===`v${d}`||u.version===d?"current":""}`,children:[e.jsx("span",{className:"about-release-version",children:u.version}),e.jsx("span",{className:"about-release-date",children:v(u.publishedAt)})]},u.version))})]})]}),e.jsx("div",{className:"about-description",children:s("config:about.tagline")}),e.jsxs("div",{className:"about-principles",children:[e.jsx("div",{className:"about-principles-title",children:s("config:about.corePrinciples")}),e.jsxs("ul",{className:"about-principles-list",children:[e.jsx("li",{children:s("config:about.principle1")}),e.jsx("li",{children:s("config:about.principle2")}),e.jsx("li",{children:s("config:about.principle3")}),e.jsx("li",{children:s("config:about.principle4")})]})]}),e.jsx("div",{className:"about-links",children:e.jsxs("a",{href:"https://github.com/deivid11/tide-commander",target:"_blank",rel:"noopener noreferrer",className:"about-link",children:[e.jsx("span",{className:"about-link-icon",children:e.jsx(I,{name:"package",size:14})}),e.jsx("span",{children:s("config:about.repository")})]})}),e.jsxs("div",{className:"about-credits",children:[e.jsx("div",{className:"about-credits-title",children:s("config:about.specialThanks")}),e.jsxs("div",{className:"about-credit-item",children:[e.jsx("a",{href:"https://kenney.nl",target:"_blank",rel:"noopener noreferrer",className:"about-credit-link",children:"Kenney.nl"}),e.jsx("span",{className:"about-credit-desc",children:s("config:about.kenneyCredit")})]}),e.jsxs("div",{className:"about-credit-item",children:[e.jsx("a",{href:"https://claude.ai/code",target:"_blank",rel:"noopener noreferrer",className:"about-credit-link",children:"Claude Code"}),e.jsx("span",{className:"about-credit-desc",children:s("config:about.claudeCodeCredit")})]})]}),E&&e.jsx(Ns,{onClose:()=>y(!1)})]})}const Dt={gmail:"✉️",slack:"💬",jira:"📋","google-calendar":"📅",docx:"📄",whatsapp:"📱"};function Ft({onOpenModal:s}){const[a,t]=l.useState([]),[n,c]=l.useState(!0),r=l.useCallback(async()=>{try{const d=await ue(pe("/api/integrations"));if(!d.ok)return;const f=await d.json();t(f)}catch{}finally{c(!1)}},[]);return l.useEffect(()=>{r()},[r]),n?e.jsx("div",{style:{color:"var(--text-secondary, #a6adc8)",fontSize:12,padding:"4px 0"},children:"Loading..."}):a.length===0?e.jsx("div",{style:{color:"var(--text-secondary, #a6adc8)",fontSize:12,padding:"4px 0"},children:"No integrations available."}):e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[a.map(d=>{const f=Dt[d.id]||"🔌",i=!!d.status.error,m=d.status.connected,w=i?"#f38ba8":m?"#a6e3a1":"#fab387",j=i?"Error":m?"Connected":"Setup Required",g=i?"✗":m?"✓":"⚠";return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"3px 8px",borderRadius:4,background:"var(--surface-1, #181825)",border:"1px solid var(--border, #313244)",fontSize:12,minHeight:26},children:[e.jsx("span",{style:{fontSize:13,flexShrink:0},children:f}),e.jsx("span",{style:{flex:1,minWidth:0,color:"var(--text-primary, #cdd6f4)",fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:d.name}),e.jsx("span",{style:{color:w,fontSize:10,fontWeight:500,whiteSpace:"nowrap"},title:j,children:g}),e.jsx("button",{onClick:()=>s(d.id),title:`Configure ${d.name}`,style:{background:"none",border:"none",cursor:"pointer",padding:"1px 3px",fontSize:12,color:"var(--text-secondary, #a6adc8)",borderRadius:3,flexShrink:0,lineHeight:1},onMouseEnter:E=>{E.target.style.color="var(--text-primary, #cdd6f4)"},onMouseLeave:E=>{E.target.style.color="var(--text-secondary, #a6adc8)"},children:"⚙️"})]},d.id)}),e.jsx("button",{onClick:()=>s(),style:{background:"none",border:"1px dashed var(--border, #313244)",borderRadius:4,padding:"3px 8px",cursor:"pointer",color:"var(--text-secondary, #a6adc8)",fontSize:11,textAlign:"center",marginTop:2},onMouseEnter:d=>{d.target.style.borderColor="var(--accent, #89b4fa)",d.target.style.color="var(--accent, #89b4fa)"},onMouseLeave:d=>{d.target.style.borderColor="var(--border, #313244)",d.target.style.color="var(--text-secondary, #a6adc8)"},children:"Manage All Integrations"})]})}function Ce(s){return`/api/system/${s}-credentials`}async function Ae(s,a){try{const t=await s.json();if(t!=null&&t.error&&typeof t.error=="string")return t.error}catch{}return a}async function zt(s){const a=await ue(pe(Ce(s)));if(!a.ok)throw new Error(await Ae(a,`Failed to list ${s} credentials: ${a.status}`));return await a.json()}async function Je(s,a,t={}){const n=await ue(pe(`${Ce(s)}/switch`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:a,stashActiveAs:t.stashActiveAs})});if(!n.ok)throw new Error(await Ae(n,`Failed to switch ${s} credentials: ${n.status}`));return await n.json()}async function Ze(s,a,t={}){const n=await ue(pe(`${Ce(s)}/save`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:a,force:t.force})});if(!n.ok)throw new Error(await Ae(n,`Failed to save ${s} credentials: ${n.status}`));return await n.json()}async function Bt(s,a,t){const n=await ue(pe(`${Ce(s)}/rename`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:a,to:t})});if(!n.ok)throw new Error(await Ae(n,`Failed to rename ${s} credentials: ${n.status}`));return await n.json()}async function Rt(s,a){const t=await ue(pe(`${Ce(s)}/${encodeURIComponent(a)}`),{method:"DELETE"});if(!t.ok)throw new Error(await Ae(t,`Failed to delete ${s} credentials: ${t.status}`));return await t.json()}const Le={grok:"Grok",codex:"Codex"};function Mt(s){if(s==null||!Number.isFinite(s))return"—";const a=new Date(s);return Number.isNaN(a.getTime())?"—":a.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Ut({profile:s,busy:a,onUse:t,onRename:n,onDelete:c}){const{t:r}=J(["terminal","common"]),d=s.expiresAt!=null&&s.expiresAt<=Date.now(),f=[s.label,s.email].filter(Boolean).join(" · ");return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",padding:"8px 10px",background:s.isActive?"rgba(74, 158, 255, 0.1)":"var(--bg-tertiary, var(--bg-secondary))",border:s.isActive?"1px solid rgba(74, 158, 255, 0.45)":"1px solid var(--border-color)",borderRadius:"6px",marginBottom:"6px"},children:[e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},children:[e.jsx("span",{style:{fontWeight:600,fontSize:"13px"},children:s.name}),s.isActive&&e.jsx("span",{style:{fontSize:"10px",textTransform:"uppercase",letterSpacing:"0.4px",color:"#4a9eff",border:"1px solid rgba(74, 158, 255, 0.5)",borderRadius:"4px",padding:"1px 6px"},children:r("terminal:credentials.activeBadge")}),!s.valid&&e.jsx("span",{style:{fontSize:"10px",color:"#ff8a8a"},children:r("terminal:credentials.invalid")})]}),e.jsxs("div",{style:{fontSize:"11px",color:"var(--text-secondary)",marginTop:"2px"},children:[f,s.expiresAt!=null&&e.jsxs("span",{style:{color:d?"#ff8a8a":void 0},children:[f?" · ":"",r("terminal:credentials.tokenExpires",{time:Mt(s.expiresAt)})]})]})]}),e.jsxs("div",{style:{display:"flex",gap:"4px",flexShrink:0},children:[!s.isActive&&e.jsx("button",{type:"button",className:"btn btn-primary",disabled:a||!s.valid,onClick:()=>t(s.name),style:{padding:"4px 10px",fontSize:"11px"},title:r("terminal:credentials.useTitle"),children:r("terminal:credentials.use")}),e.jsx("button",{type:"button",className:"btn btn-secondary",disabled:a,onClick:()=>n(s.name),style:{padding:"4px 8px",fontSize:"11px"},title:r("terminal:credentials.rename"),children:e.jsx(I,{name:"edit",size:12})}),e.jsx("button",{type:"button",className:"btn btn-secondary",disabled:a,onClick:()=>c(s.name),style:{padding:"4px 8px",fontSize:"11px",color:"#ff8a8a"},title:r("terminal:credentials.delete"),children:e.jsx(I,{name:"trash",size:12})})]})]})}function Xe({provider:s,onSwitched:a,compact:t}){var H,se,N,O,M;const{t:n}=J(["terminal","common"]),[c,r]=l.useState(null),[d,f]=l.useState(!1),[i,m]=l.useState(!1),[w,j]=l.useState(null),[g,E]=l.useState(""),[y,S]=l.useState(""),[v,u]=l.useState(null),[k,D]=l.useState(null),F=l.useCallback(async()=>{f(!0),j(null);try{r(await zt(s))}catch(p){j(p instanceof Error?p.message:String(p))}finally{f(!1)}},[s]);l.useEffect(()=>{F()},[F]);const V=p=>r(p),W=!!((H=c==null?void 0:c.active)!=null&&H.valid&&!c.active.matchesNamed),q=async p=>{if(j(null),D(null),W){u(p);return}m(!0);try{const b=await Je(s,p);r({provider:s,dir:(c==null?void 0:c.dir)??"",active:b.active,profiles:b.profiles}),D(n("terminal:credentials.switched",{name:p})),u(null),a==null||a()}catch(b){j(b instanceof Error?b.message:String(b))}finally{m(!1)}},R=async()=>{if(!v)return;const p=y.trim();if(!p){j(n("terminal:credentials.stashRequired"));return}m(!0),j(null);try{const b=await Je(s,v,{stashActiveAs:p});r({provider:s,dir:(c==null?void 0:c.dir)??"",active:b.active,profiles:b.profiles}),D(b.stashedAs?n("terminal:credentials.switchedWithStash",{name:v,stash:b.stashedAs}):n("terminal:credentials.switched",{name:v})),u(null),S(""),a==null||a()}catch(b){j(b instanceof Error?b.message:String(b))}finally{m(!1)}},K=async()=>{const p=g.trim();if(!p){j(n("terminal:credentials.nameRequired"));return}m(!0),j(null),D(null);try{V(await Ze(s,p)),E(""),D(n("terminal:credentials.saved",{name:p}))}catch(b){const L=b instanceof Error?b.message:String(b);if(/already exists/i.test(L)&&window.confirm(n("terminal:credentials.confirmOverwrite",{name:p})))try{V(await Ze(s,p,{force:!0})),E(""),D(n("terminal:credentials.saved",{name:p})),m(!1);return}catch(X){j(X instanceof Error?X.message:String(X)),m(!1);return}j(L)}finally{m(!1)}},h=async p=>{const b=window.prompt(n("terminal:credentials.renamePrompt",{name:p}),p);if(!(!b||b.trim()===p)){m(!0),j(null);try{V(await Bt(s,p,b.trim())),D(n("terminal:credentials.renamed",{from:p,to:b.trim()}))}catch(L){j(L instanceof Error?L.message:String(L))}finally{m(!1)}}},$=async p=>{if(window.confirm(n("terminal:credentials.confirmDelete",{name:p}))){m(!0),j(null);try{V(await Rt(s,p)),D(n("terminal:credentials.deleted",{name:p}))}catch(b){j(b instanceof Error?b.message:String(b))}finally{m(!1)}}},U=c!=null&&c.active?c.active.matchesNamed?c.active.matchesNamed:n("terminal:credentials.unsavedActive"):n("terminal:credentials.noActive");return e.jsxs("div",{className:"claude-credentials-panel",style:{marginTop:t?"12px":"0",paddingTop:t?"12px":"0",borderTop:t?"1px solid var(--border-color)":void 0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"10px",gap:"8px"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"12px",color:"var(--text-secondary)",textTransform:"uppercase",letterSpacing:"0.5px"},children:n("terminal:credentials.providerTitle",{provider:Le[s],defaultValue:`${Le[s]} Accounts`})}),e.jsxs("div",{style:{fontSize:"12px",marginTop:"4px"},children:[n("terminal:credentials.current",{name:U}),((se=c==null?void 0:c.active)==null?void 0:se.email)&&e.jsxs("span",{style:{color:"var(--text-secondary)"},children:[" · ",c.active.email]}),((N=c==null?void 0:c.active)==null?void 0:N.label)&&e.jsxs("span",{style:{color:"var(--text-secondary)"},children:[" (",c.active.label,")"]})]})]}),e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>void F(),disabled:d||i,style:{padding:"4px 10px",fontSize:"11px",display:"inline-flex",gap:"6px",alignItems:"center"},title:n("common:buttons.refresh"),children:e.jsx("span",{style:{display:"inline-block",animation:d?"spin 1s linear infinite":"none"},children:e.jsx(I,{name:"refresh",size:12})})})]}),e.jsx("p",{style:{fontSize:"11px",color:"var(--text-secondary)",margin:"0 0 10px",lineHeight:1.45},children:n("terminal:credentials.providerHelp",{provider:Le[s],dir:(c==null?void 0:c.dir)??`~/.${s}`,defaultValue:`Named copies of ${(c==null?void 0:c.dir)??`~/.${s}`}/auth.json. Switch the active ${Le[s]} account when you hit rate limits — same as renaming the file manually.`})}),w&&e.jsx("div",{style:{padding:"8px 10px",marginBottom:"8px",background:"rgba(255, 74, 74, 0.08)",border:"1px solid rgba(255, 74, 74, 0.3)",borderRadius:"6px",color:"#ff8a8a",fontSize:"12px"},children:w}),k&&e.jsx("div",{style:{padding:"8px 10px",marginBottom:"8px",background:"rgba(74, 255, 158, 0.08)",border:"1px solid rgba(74, 255, 158, 0.3)",borderRadius:"6px",color:"#7dffb0",fontSize:"12px"},children:k}),v&&e.jsxs("div",{style:{padding:"10px 12px",marginBottom:"10px",background:"rgba(255, 158, 74, 0.08)",border:"1px solid rgba(255, 158, 74, 0.35)",borderRadius:"6px"},children:[e.jsx("div",{style:{fontSize:"12px",marginBottom:"8px",lineHeight:1.45},children:n("terminal:credentials.stashPrompt",{name:v})}),e.jsxs("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap"},children:[e.jsx("input",{type:"text",value:y,onChange:p=>S(p.target.value),placeholder:n("terminal:credentials.stashPlaceholder"),disabled:i,style:{flex:1,minWidth:"120px",padding:"6px 8px",fontSize:"12px",borderRadius:"4px",border:"1px solid var(--border-color)",background:"var(--bg-primary)",color:"var(--text-primary)"}}),e.jsx("button",{type:"button",className:"btn btn-primary",disabled:i,onClick:()=>void R(),style:{padding:"6px 12px",fontSize:"12px"},children:n("terminal:credentials.confirmSwitch")}),e.jsx("button",{type:"button",className:"btn btn-secondary",disabled:i,onClick:()=>u(null),style:{padding:"6px 12px",fontSize:"12px"},children:n("common:buttons.cancel")})]})]}),d&&!c&&e.jsxs("div",{style:{fontSize:"12px",color:"var(--text-secondary)",padding:"8px 0"},children:[n("common:status.loading"),"…"]}),c&&c.profiles.length===0&&e.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",marginBottom:"10px"},children:n("terminal:credentials.noProfiles")}),c==null?void 0:c.profiles.map(p=>e.jsx(Ut,{profile:p,busy:i,onUse:b=>void q(b),onRename:b=>void h(b),onDelete:b=>void $(b)},p.name)),e.jsxs("div",{style:{display:"flex",gap:"6px",marginTop:"10px",flexWrap:"wrap",alignItems:"center"},children:[e.jsx("input",{type:"text",value:g,onChange:p=>E(p.target.value),placeholder:n("terminal:credentials.savePlaceholder"),disabled:i||!((O=c==null?void 0:c.active)!=null&&O.valid),style:{flex:1,minWidth:"140px",padding:"6px 8px",fontSize:"12px",borderRadius:"4px",border:"1px solid var(--border-color)",background:"var(--bg-primary)",color:"var(--text-primary)"}}),e.jsx("button",{type:"button",className:"btn btn-secondary",disabled:i||!((M=c==null?void 0:c.active)!=null&&M.valid)||!g.trim(),onClick:()=>void K(),style:{padding:"6px 12px",fontSize:"12px"},children:n("terminal:credentials.saveActive")})]}),(c==null?void 0:c.dir)&&e.jsx("div",{style:{fontSize:"10px",color:"var(--text-muted)",marginTop:"8px",wordBreak:"break-all"},children:c.dir})]})}const Oe="__global__";function Vt({isOpen:s,onClose:a,initialAgentId:t}){const{t:n}=J(["config"]),c=_s(),[r,d]=l.useState(""),[f,i]=l.useState(""),[m,w]=l.useState(!1),[j,g]=l.useState(""),[E,y]=l.useState(""),[S,v]=l.useState(null),[u,k]=l.useState(null),[D,F]=l.useState(!1),[V,W]=l.useState(!1),[q,R]=l.useState(!1),[K,h]=l.useState(null),$=l.useMemo(()=>[...c].sort((T,C)=>T.name.localeCompare(C.name)),[c]),U=l.useMemo(()=>c.find(T=>T.id===r),[c,r]),H=r===Oe;l.useEffect(()=>{if(!s)return;const T=t&&c.some(C=>C.id===t)?t:Oe;d(T),w(!1),pt().then(C=>i(C)).catch(()=>i("")).finally(()=>w(!0))},[s]),l.useEffect(()=>{const T=r===Oe?f:(U==null?void 0:U.customPrompt)??"";g(T),y(T),F(!1),v(null),k(null)},[r,m]);const se=T=>{const C=T.target.value;g(C),F(C!==E),v(null),k(null)},N=async()=>{if(r)try{v(null),k(null),H?(await mt(j),i(j),k(n("config:systemPrompt.savedGlobal"))):(A.updateAgentProperties(r,{customPrompt:j}),k(n("config:systemPrompt.saved"))),y(j),F(!1)}catch(T){v(T instanceof Error?T.message:"Failed to save system prompt")}},O=()=>{W(!0)},M=async()=>{if(r)try{v(null),k(null),H?(await ht(),i(""),k(n("config:systemPrompt.clearedGlobal"))):(A.updateAgentProperties(r,{customPrompt:""}),k(n("config:systemPrompt.cleared"))),g(""),y(""),F(!1)}catch(T){v(T instanceof Error?T.message:"Failed to clear system prompt")}},p=()=>{g(E),F(!1),v(null),k(null)},b=T=>{if(T!==r){if(D){h(T),R(!0);return}d(T)}},L=()=>{if(D){h(null),R(!0);return}a()},X=()=>{if(R(!1),K){const T=K;h(null),d(T)}else a()},ae=T=>{T.key==="Escape"&&(T.preventDefault(),L())};return s?e.jsxs(Se,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:L,children:e.jsxs("div",{className:"system-prompt-modal",onClick:T=>T.stopPropagation(),onKeyDown:ae,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:n("config:systemPrompt.title")}),e.jsx("button",{className:"modal-close",onClick:L,"aria-label":"Close",children:e.jsx(I,{name:"close",size:16})})]}),e.jsxs("div",{className:"modal-body",children:[e.jsx("p",{className:"modal-description",children:n("config:systemPrompt.description")}),e.jsxs("div",{className:"agent-picker",children:[e.jsx("label",{htmlFor:"system-prompt-agent",className:"editor-label",children:n("config:systemPrompt.agentLabel")}),e.jsxs("div",{className:"agent-picker-row",children:[H?e.jsx(I,{name:"globe",size:20,className:"agent-picker-icon"}):U&&e.jsx(Is,{classId:U.class,size:20,className:"agent-picker-icon"}),e.jsxs("select",{id:"system-prompt-agent",className:"agent-picker-select",value:r,onChange:T=>b(T.target.value),children:[e.jsxs("option",{value:Oe,children:[n("config:systemPrompt.globalOption"),f?" • ✦":""]}),$.map(T=>e.jsxs("option",{value:T.id,children:[T.name,T.customPrompt?" • ✦":""]},T.id))]})]})]}),S&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(I,{name:"warn",size:14})}),S]}),u&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(I,{name:"check",size:14})}),u]}),e.jsxs("div",{className:"editor-wrapper",children:[e.jsxs("div",{className:"editor-header",children:[e.jsx("label",{htmlFor:"prompt-input",className:"editor-label",children:n("config:systemPrompt.editPrompt")}),e.jsxs("span",{className:"char-count",children:[j.length," ",n("config:systemPrompt.characters")]})]}),e.jsx("textarea",{id:"prompt-input",className:"prompt-editor",value:j,onChange:se,placeholder:n("config:systemPrompt.placeholder"),rows:18,disabled:H&&!m,autoFocus:!0}),e.jsx("div",{className:"editor-hint",children:n(H?"config:systemPrompt.hintGlobal":"config:systemPrompt.hint")})]})]}),e.jsxs("div",{className:"modal-footer",children:[e.jsx("div",{className:"footer-buttons-left",children:e.jsx("button",{className:"btn btn-danger",onClick:O,disabled:!j||!r,children:n("config:systemPrompt.clear")})}),e.jsxs("div",{className:"footer-buttons-right",children:[e.jsx("button",{className:"btn btn-secondary",onClick:L,children:"Close"}),e.jsx("button",{className:"btn btn-secondary",onClick:p,disabled:!D,children:n("config:systemPrompt.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:N,disabled:!D||!r,children:n("config:systemPrompt.save")})]})]})]})}),e.jsx(ge,{isOpen:V,title:n("config:systemPrompt.clear"),message:n(H?"config:systemPrompt.confirmClearGlobal":"config:systemPrompt.confirmClear"),confirmLabel:n("config:systemPrompt.clear"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{M()},onClose:()=>W(!1)}),e.jsx(ge,{isOpen:q,title:"Unsaved Changes",message:"You have unsaved changes for this agent. Discard them?",confirmLabel:"Discard",cancelLabel:"Keep editing",variant:"danger",onConfirm:X,onClose:()=>{R(!1),h(null)}})]}):null}const Qe={enabled:!1,baseUrl:"",defaultSessionId:"",webhookVerifyToken:"",showIncomingToasts:!0},Kt=2500,Ht=12e4;function es(s){return{enabled:s.enabled??!1,baseUrl:s.baseUrl??"",defaultSessionId:s.defaultSessionId??"",webhookVerifyToken:s.webhookVerifyToken??"",showIncomingToasts:s.showIncomingToasts??!0}}function Wt(s,a){return s.enabled===a.enabled&&s.baseUrl===a.baseUrl&&s.defaultSessionId===a.defaultSessionId&&s.webhookVerifyToken===a.webhookVerifyToken&&s.showIncomingToasts===a.showIncomingToasts}function qt({isOpen:s,onClose:a}){const{t}=J(["config"]),[n,c]=l.useState(Qe),[r,d]=l.useState(Qe),[f,i]=l.useState(!1),[m,w]=l.useState([]),[j,g]=l.useState(!0),[E,y]=l.useState(null),[S,v]=l.useState(null),[u,k]=l.useState(""),[D,F]=l.useState(!1),[V,W]=l.useState(""),[q,R]=l.useState(null),[K,h]=l.useState(null),[$,U]=l.useState(null),H=l.useRef(null),se=l.useRef(0),[N,O]=l.useState(""),[M,p]=l.useState(""),[b,L]=l.useState(null),[X,ae]=l.useState(!1),[T,C]=l.useState(!1),[ee,ne]=l.useState(!1),[le,ie]=l.useState(!1),[me,ye]=l.useState(null),we=!Wt(n,r),re=l.useCallback(()=>{H.current&&(clearTimeout(H.current),H.current=null)},[]),fe=l.useCallback(async()=>{try{g(!0),y(null),v(null);const[x,B]=await Promise.all([ls(),$s()]),oe=es(x);if(c(oe),d(oe),i(!!B.configured),B.configured)try{const be=await He();w(Array.isArray(be)?be:[])}catch{w([])}else w([])}catch(x){y(x instanceof Error?x.message:t("config:whatsapp.errors.loadFailed"))}finally{g(!1)}},[t]),P=l.useCallback(async()=>{try{const x=await He();w(Array.isArray(x)?x:[])}catch{}},[]);l.useEffect(()=>(s?fe():(re(),R(null),h(null),U(null),k(""),F(!1),L(null)),()=>{re()}),[s,fe,re]);const he=(x,B)=>{c(oe=>({...oe,[x]:B})),y(null),v(null)},ce=async()=>{try{y(null),v(null);const x=await zs({enabled:n.enabled,baseUrl:n.baseUrl.trim(),defaultSessionId:n.defaultSessionId.trim(),webhookVerifyToken:n.webhookVerifyToken,showIncomingToasts:n.showIncomingToasts});window.dispatchEvent(new CustomEvent("tide:whatsapp-config-updated"));const B=es(x);c(B),d(B),v(t("config:whatsapp.saved"))}catch(x){y(x instanceof Error?x.message:t("config:whatsapp.errors.saveFailed"))}},Fe=()=>{c(r),y(null),v(null)},xe=()=>{if(we){C(!0);return}a()},ze=x=>{x.key==="Escape"&&(x.preventDefault(),xe())},Be=async()=>{const x=u.trim();if(x)try{y(null),v(null),await Os(x),k(""),F(!1),i(!0),v(t("config:whatsapp.apiKeySaved"))}catch(B){y(B instanceof Error?B.message:t("config:whatsapp.errors.apiKeySaveFailed"))}},Te=()=>{ne(!0)},Re=async()=>{try{y(null),v(null),await Bs(),i(!1),v(t("config:whatsapp.apiKeyCleared"))}catch(x){y(x instanceof Error?x.message:t("config:whatsapp.errors.apiKeyClearFailed"))}},Ne=l.useCallback(async x=>{if(Date.now()>se.current){U(t("config:whatsapp.pairingTimeout")),R(null),h(null),re(),P();return}try{const B=await Ls(x);if(B.status&&["connected","paired","open","ready"].includes(B.status.toLowerCase())){U(t("config:whatsapp.pairingSuccess")),R(null),h(null),re(),P();return}const be=B.qrUrl??B.qr??null;be&&h(be)}catch(B){U(B instanceof Error?B.message:t("config:whatsapp.errors.qrFetchFailed"))}H.current=setTimeout(()=>{Ne(x)},Kt)},[P,re,t]),Ee=async()=>{const x=V.trim();if(x)try{y(null),v(null),U(null),h(null),re(),await Ds(x),W(""),R(x),se.current=Date.now()+Ht,Ne(x),P()}catch(B){y(B instanceof Error?B.message:t("config:whatsapp.errors.sessionCreateFailed"))}},Pe=()=>{re(),R(null),h(null),U(null)},_e=x=>{ye(x),ie(!0)},Me=async()=>{if(me)try{y(null),v(null),await Rs(me),q===me&&Pe(),P(),v(t("config:whatsapp.sessionDeleted"))}catch(x){y(x instanceof Error?x.message:t("config:whatsapp.errors.sessionDeleteFailed"))}finally{ye(null)}},Ie=async()=>{const x=N.trim(),B=M.trim();if(!(!x||!B))try{ae(!0),L(null);const oe=n.defaultSessionId.trim()||void 0;await Fs(x,B,oe),L({kind:"success",text:t("config:whatsapp.testSent")})}catch(oe){L({kind:"error",text:oe instanceof Error?oe.message:t("config:whatsapp.errors.testSendFailed")})}finally{ae(!1)}};return s?e.jsxs(Se,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:xe,children:e.jsxs("div",{className:"whatsapp-config-modal",onClick:x=>x.stopPropagation(),onKeyDown:ze,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:t("config:whatsapp.title")}),e.jsx("button",{className:"modal-close",onClick:xe,"aria-label":"Close",children:e.jsx(I,{name:"close",size:16})})]}),e.jsx("div",{className:"modal-body",children:j?e.jsxs("div",{className:"loading-state",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:t("config:whatsapp.loading")})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"modal-description",children:t("config:whatsapp.description")}),E&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(I,{name:"warn",size:14})}),E]}),S&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(I,{name:"check",size:14})}),S]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:t("config:whatsapp.sections.general")}),e.jsxs("div",{className:"wa-field wa-field-row",children:[e.jsx("label",{htmlFor:"wa-enabled",className:"wa-label",children:t("config:whatsapp.enabled")}),e.jsxs("label",{className:"wa-toggle",children:[e.jsx("input",{id:"wa-enabled",type:"checkbox",checked:n.enabled,onChange:x=>he("enabled",x.target.checked)}),e.jsx("span",{className:"wa-toggle-track",children:e.jsx("span",{className:"wa-toggle-thumb"})})]})]}),e.jsxs("div",{className:"wa-field wa-field-row",children:[e.jsx("label",{htmlFor:"wa-show-toasts",className:"wa-label",children:t("config:whatsapp.showIncomingToasts")}),e.jsxs("label",{className:"wa-toggle",children:[e.jsx("input",{id:"wa-show-toasts",type:"checkbox",checked:n.showIncomingToasts,onChange:x=>he("showIncomingToasts",x.target.checked)}),e.jsx("span",{className:"wa-toggle-track",children:e.jsx("span",{className:"wa-toggle-thumb"})})]})]}),e.jsx("span",{className:"wa-hint",children:t("config:whatsapp.showIncomingToastsHelp")}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-base-url",className:"wa-label",children:t("config:whatsapp.baseUrl")}),e.jsx("input",{id:"wa-base-url",type:"text",className:"wa-input",placeholder:"http://localhost:3007",value:n.baseUrl,onChange:x=>he("baseUrl",x.target.value)})]}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-default-session",className:"wa-label",children:t("config:whatsapp.defaultSessionId")}),e.jsx("input",{id:"wa-default-session",type:"text",className:"wa-input",placeholder:t("config:whatsapp.defaultSessionIdPlaceholder"),value:n.defaultSessionId,onChange:x=>he("defaultSessionId",x.target.value)})]}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-webhook-token",className:"wa-label",children:t("config:whatsapp.webhookVerifyToken")}),e.jsx("input",{id:"wa-webhook-token",type:"text",className:"wa-input",placeholder:t("config:whatsapp.webhookVerifyTokenPlaceholder"),value:n.webhookVerifyToken,onChange:x=>he("webhookVerifyToken",x.target.value)})]})]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:t("config:whatsapp.sections.apiKey")}),e.jsx("div",{className:"wa-key-status",children:f?e.jsxs("span",{className:"wa-status wa-status-ok",children:[e.jsx(I,{name:"check",size:12})," ",t("config:whatsapp.configured")]}):e.jsxs("span",{className:"wa-status wa-status-warn",children:[e.jsx(I,{name:"warn",size:12})," ",t("config:whatsapp.notConfigured")]})}),e.jsxs("div",{className:"wa-field wa-field-inline",children:[e.jsx("input",{type:D?"text":"password",className:"wa-input",placeholder:t("config:whatsapp.apiKeyPlaceholder"),value:u,onChange:x=>k(x.target.value)}),e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>F(x=>!x),title:t(D?"config:whatsapp.hideKey":"config:whatsapp.showKey"),children:e.jsx(I,{name:D?"eye-closed":"eye",size:14})}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:Be,disabled:!u.trim(),children:t("config:whatsapp.saveKey")}),e.jsx("button",{type:"button",className:"btn btn-danger",onClick:Te,disabled:!f,children:t("config:whatsapp.clearKey")})]}),e.jsx("span",{className:"wa-hint",children:t("config:whatsapp.apiKeyHint")})]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:t("config:whatsapp.sections.sessions")}),e.jsx("div",{className:"wa-sessions-list",children:!Array.isArray(m)||m.length===0?e.jsx("div",{className:"wa-empty",children:t("config:whatsapp.noSessions")}):m.map(x=>e.jsxs("div",{className:"wa-session-row",children:[e.jsxs("div",{className:"wa-session-info",children:[e.jsx("span",{className:"wa-session-id",children:x.id}),e.jsx("span",{className:`wa-session-status status-${(x.status??"unknown").toLowerCase()}`,children:x.status||"—"}),x.pairedNumber&&e.jsx("span",{className:"wa-session-paired",children:x.pairedNumber})]}),e.jsx("button",{type:"button",className:"btn btn-danger btn-sm",onClick:()=>_e(x.id),children:t("config:whatsapp.deleteSession")})]},x.id))}),e.jsxs("div",{className:"wa-field wa-field-inline",children:[e.jsx("input",{type:"text",className:"wa-input",placeholder:t("config:whatsapp.addSessionPlaceholder"),value:V,onChange:x=>W(x.target.value),onKeyDown:x=>{x.key==="Enter"&&Ee()}}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:Ee,disabled:!V.trim()||q!==null,children:t("config:whatsapp.addSession")})]}),q&&e.jsxs("div",{className:"wa-qr-panel",children:[e.jsxs("div",{className:"wa-qr-header",children:[e.jsx("span",{children:t("config:whatsapp.qrPrompt",{id:q})}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Pe,children:t("config:whatsapp.cancelPairing")})]}),K?e.jsx("div",{className:"wa-qr-image",children:e.jsx("img",{src:K,alt:"WhatsApp pairing QR code"})}):e.jsxs("div",{className:"wa-qr-loading",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:t("config:whatsapp.waitingForQr")})]})]}),$&&!q&&e.jsx("div",{className:"wa-pairing-message",children:$})]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:t("config:whatsapp.sections.testMessage")}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-test-to",className:"wa-label",children:t("config:whatsapp.testTo")}),e.jsx("input",{id:"wa-test-to",type:"text",className:"wa-input",placeholder:t("config:whatsapp.testToPlaceholder"),value:N,onChange:x=>O(x.target.value)})]}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-test-message",className:"wa-label",children:t("config:whatsapp.testMessageBody")}),e.jsx("textarea",{id:"wa-test-message",className:"wa-textarea",rows:4,placeholder:t("config:whatsapp.testMessageBodyPlaceholder"),value:M,onChange:x=>p(x.target.value)})]}),e.jsx("div",{className:"wa-field-inline wa-field-end",children:e.jsx("button",{type:"button",className:"btn btn-primary",onClick:Ie,disabled:!N.trim()||!M.trim()||X,children:t(X?"config:whatsapp.sending":"config:whatsapp.sendTest")})}),b&&e.jsxs("div",{className:`alert ${b.kind==="success"?"alert-success":"alert-error"}`,children:[e.jsx("span",{className:"alert-icon",children:e.jsx(I,{name:b.kind==="success"?"check":"warn",size:14})}),b.text]})]})]})}),e.jsxs("div",{className:"modal-footer",children:[e.jsx("div",{className:"footer-buttons-left"}),e.jsxs("div",{className:"footer-buttons-right",children:[e.jsx("button",{className:"btn btn-secondary",onClick:xe,children:t("config:whatsapp.close")}),e.jsx("button",{className:"btn btn-secondary",onClick:Fe,disabled:!we||j,children:t("config:whatsapp.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:ce,disabled:!we||j,children:t("config:whatsapp.save")})]})]})]})}),e.jsx(ge,{isOpen:T,title:t("config:whatsapp.unsavedTitle"),message:t("config:whatsapp.unsavedMessage"),confirmLabel:t("config:whatsapp.closeAnyway"),cancelLabel:t("config:whatsapp.keepEditing"),variant:"danger",onConfirm:()=>{C(!1),a()},onClose:()=>C(!1)}),e.jsx(ge,{isOpen:ee,title:t("config:whatsapp.clearKey"),message:t("config:whatsapp.confirmClearKey"),confirmLabel:t("config:whatsapp.clearKey"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{Re()},onClose:()=>ne(!1)}),e.jsx(ge,{isOpen:le,title:t("config:whatsapp.deleteSession"),message:t("config:whatsapp.confirmDeleteSession",{id:me??""}),confirmLabel:t("config:whatsapp.deleteSession"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{Me()},onClose:()=>{ie(!1),ye(null)}})]}):null}const rs=["messages","statusChanges","taskComplete","errors","planReady","agentSpawned","agentStopped"];function We(s=!1){const a=Q(),t={};return a&&(t.Authorization=`Bearer ${a}`),s&&(t["Content-Type"]="application/json"),t}async function qe(s,a){try{const t=await s.json();if(t&&typeof t.error=="string")return t.error;if(t&&typeof t.message=="string")return t.message}catch{}return`${a}: ${s.statusText}`}async function Gt(){const s=await fetch(`${Z()}/api/whatsapp/notification-config`,{headers:We()});if(!s.ok)throw new Error(await qe(s,"Failed to fetch WhatsApp notification config"));return s.json()}async function Yt(s){const a=await fetch(`${Z()}/api/whatsapp/notification-config`,{method:"PATCH",headers:We(!0),body:JSON.stringify(s)});if(!a.ok)throw new Error(await qe(a,"Failed to update WhatsApp notification config"));return a.json()}async function Jt(){const s=await fetch(`${Z()}/api/whatsapp/notification-config`,{method:"DELETE",headers:We()});if(!s.ok)throw new Error(await qe(s,"Failed to reset WhatsApp notification config"));return s.json()}const De={messages:!0,statusChanges:!0,taskComplete:!0,errors:!0,planReady:!0,agentSpawned:!0,agentStopped:!0},ss={filter:{...De},recipient:""};function Zt(s,a){if(s.recipient!==a.recipient)return!1;for(const t of rs)if(s.filter[t]!==a.filter[t])return!1;return!0}function Xt({isOpen:s,onClose:a}){const{t}=J(["config"]),[n,c]=l.useState(ss),[r,d]=l.useState(ss),[f,i]=l.useState(!0),[m,w]=l.useState(null),[j,g]=l.useState(null),[E,y]=l.useState(!1),[S,v]=l.useState(!1),u=!Zt(n,r),k=l.useCallback(async()=>{try{i(!0),w(null),g(null);const h=await Gt(),$={filter:{...De,...h.filter},recipient:h.recipient??""};c($),d($)}catch(h){w(h instanceof Error?h.message:t("config:whatsappNotifications.errors.loadFailed"))}finally{i(!1)}},[t]);l.useEffect(()=>{s&&k()},[s,k]);const D=(h,$)=>{c(U=>({...U,filter:{...U.filter,[h]:$}})),w(null),g(null)},F=h=>{c($=>({...$,recipient:h})),w(null),g(null)},V=async()=>{try{w(null),g(null);const h=await Yt({filter:n.filter,recipient:n.recipient.trim()}),$={filter:{...De,...h.filter},recipient:h.recipient??""};c($),d($),g(t("config:whatsappNotifications.saved"))}catch(h){w(h instanceof Error?h.message:t("config:whatsappNotifications.errors.saveFailed"))}},W=()=>{c(r),w(null),g(null)},q=async()=>{try{w(null),g(null);const h=await Jt(),$={filter:{...De,...h.filter},recipient:h.recipient??""};c($),d($),g(t("config:whatsappNotifications.resetDone"))}catch(h){w(h instanceof Error?h.message:t("config:whatsappNotifications.errors.resetFailed"))}},R=()=>{if(u){y(!0);return}a()},K=h=>{h.key==="Escape"&&(h.preventDefault(),R())};return s?e.jsxs(Se,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:R,children:e.jsxs("div",{className:"whatsapp-notifications-modal",onClick:h=>h.stopPropagation(),onKeyDown:K,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:t("config:whatsappNotifications.title")}),e.jsx("button",{className:"modal-close",onClick:R,"aria-label":"Close",children:e.jsx(I,{name:"close",size:16})})]}),e.jsx("div",{className:"modal-body",children:f?e.jsxs("div",{className:"loading-state",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:t("config:whatsappNotifications.loading")})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"modal-description",children:t("config:whatsappNotifications.description")}),m&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(I,{name:"warn",size:14})}),m]}),j&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(I,{name:"check",size:14})}),j]}),e.jsxs("section",{className:"wan-section",children:[e.jsx("h3",{className:"wan-section-title",children:t("config:whatsappNotifications.sections.recipient")}),e.jsxs("div",{className:"wan-field",children:[e.jsx("label",{htmlFor:"wan-recipient",className:"wan-label",children:t("config:whatsappNotifications.recipientLabel")}),e.jsx("input",{id:"wan-recipient",type:"text",className:"wan-input",placeholder:t("config:whatsappNotifications.recipientPlaceholder"),value:n.recipient,onChange:h=>F(h.target.value)}),e.jsx("span",{className:"wan-hint",children:t("config:whatsappNotifications.recipientHint")})]})]}),e.jsxs("section",{className:"wan-section",children:[e.jsx("h3",{className:"wan-section-title",children:t("config:whatsappNotifications.sections.events")}),e.jsx("p",{className:"wan-section-hint",children:t("config:whatsappNotifications.eventsHint")}),rs.map(h=>e.jsxs("div",{className:"wan-toggle-row",children:[e.jsxs("div",{className:"wan-toggle-info",children:[e.jsx("span",{className:"wan-toggle-title",children:t(`config:whatsappNotifications.events.${h}.title`)}),e.jsx("span",{className:"wan-toggle-help",children:t(`config:whatsappNotifications.events.${h}.help`)})]}),e.jsxs("label",{className:"wan-toggle",children:[e.jsx("input",{type:"checkbox",checked:n.filter[h],onChange:$=>D(h,$.target.checked)}),e.jsx("span",{className:"wan-toggle-track",children:e.jsx("span",{className:"wan-toggle-thumb"})})]})]},h))]})]})}),e.jsxs("div",{className:"modal-footer",children:[e.jsx("div",{className:"footer-buttons-left",children:e.jsx("button",{className:"btn btn-danger",onClick:()=>v(!0),disabled:f,children:t("config:whatsappNotifications.resetToDefaults")})}),e.jsxs("div",{className:"footer-buttons-right",children:[e.jsx("button",{className:"btn btn-secondary",onClick:R,children:t("config:whatsappNotifications.close")}),e.jsx("button",{className:"btn btn-secondary",onClick:W,disabled:!u||f,children:t("config:whatsappNotifications.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:V,disabled:!u||f,children:t("config:whatsappNotifications.save")})]})]})]})}),e.jsx(ge,{isOpen:E,title:t("config:whatsappNotifications.unsavedTitle"),message:t("config:whatsappNotifications.unsavedMessage"),confirmLabel:t("config:whatsappNotifications.closeAnyway"),cancelLabel:t("config:whatsappNotifications.keepEditing"),variant:"danger",onConfirm:()=>{y(!1),a()},onClose:()=>y(!1)}),e.jsx(ge,{isOpen:S,title:t("config:whatsappNotifications.resetToDefaults"),message:t("config:whatsappNotifications.confirmReset"),confirmLabel:t("config:whatsappNotifications.resetToDefaults"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{q(),v(!1)},onClose:()=>v(!1)})]}):null}function ds(s){const a=s.replace(/@.*$/,"");return/^\d{10,15}$/.test(a)?a.startsWith("521")&&a.length===13?`+52 1 ${a.slice(3,5)} ${a.slice(5,9)} ${a.slice(9)}`:a.startsWith("52")&&a.length===12?`+52 ${a.slice(2,4)} ${a.slice(4,8)} ${a.slice(8)}`:a.startsWith("1")&&a.length===11?`+1 ${a.slice(1,4)} ${a.slice(4,7)} ${a.slice(7)}`:`+${a}`:s}function Qt(s,a=Date.now()){const t=s*1e3,n=a-t;if(n<0)return ts(t);const c=Math.floor(n/6e4);if(c<1)return"now";if(c<60)return`${c}m`;const r=Math.floor(c/60);if(r<24)return`${r}h`;const d=Math.floor(r/24);return d===1?"yesterday":d<7?`${d}d`:ts(t)}function ts(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function ea(s){const a=s*1e3;return new Date(a).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}function us(s){switch(s){case"image":return"📷";case"audio":return"🎤";case"video":return"📹";case"document":return"📎";case"location":return"📍";case"contact":return"👤";case"sticker":return"🌟";case"reaction":return"👍";case"unknown":return"❓";case"text":default:return null}}function sa(s,a){return s.length<=a?s:s.slice(0,Math.max(0,a-1)).trimEnd()+"…"}function ta({chats:s,selectedChatId:a,loading:t,error:n,onSelect:c,onRefresh:r,now:d}){const{t:f}=J(["config","common"]);return e.jsxs("div",{className:"whatsapp-history-chatlist",children:[e.jsxs("div",{className:"whatsapp-history-chatlist__header",children:[e.jsx("span",{className:"whatsapp-history-chatlist__title",children:f("config:whatsappHistory.chats")}),e.jsx("button",{type:"button",className:"whatsapp-history-chatlist__refresh",onClick:r,disabled:t,"aria-label":f("config:whatsappHistory.refresh"),title:f("config:whatsappHistory.refresh"),children:"⟳"})]}),n&&e.jsx("div",{className:"whatsapp-history-chatlist__error",children:n}),t&&s.length===0&&e.jsxs("div",{className:"whatsapp-history-chatlist__loading",children:[e.jsx("span",{className:"spinner"}),e.jsx("span",{children:f("config:whatsappHistory.loadingChats")})]}),!t&&!n&&s.length===0&&e.jsx("div",{className:"whatsapp-history-chatlist__empty",children:f("config:whatsappHistory.emptyChats")}),e.jsx("ul",{className:"whatsapp-history-chatlist__items",children:s.map(i=>{const m=us(i.lastMessageType),w=i.lastMessagePreview||`[${i.lastMessageType}]`,j=i.chatId===a,g=ds(i.chatId),E=i.isGroup?i.groupName:i.fromName,y=E||g,S=!!E&&E!==g;return e.jsx("li",{className:`whatsapp-history-chatlist__item ${j?"is-selected":""}`,children:e.jsxs("button",{type:"button",className:"whatsapp-history-chatlist__button",onClick:()=>c(i.chatId),children:[e.jsxs("div",{className:"whatsapp-history-chatlist__row",children:[e.jsx("span",{className:"whatsapp-history-chatlist__name",title:i.chatId,children:y}),e.jsx("span",{className:"whatsapp-history-chatlist__time",children:Qt(i.lastTimestamp,d)})]}),S&&e.jsx("div",{className:"whatsapp-history-chatlist__row whatsapp-history-chatlist__row--jid",children:e.jsx("span",{className:"whatsapp-history-chatlist__jid",children:g})}),e.jsxs("div",{className:"whatsapp-history-chatlist__row whatsapp-history-chatlist__row--secondary",children:[e.jsxs("span",{className:"whatsapp-history-chatlist__preview",children:[i.lastDirection==="outbound"&&e.jsx("span",{className:"whatsapp-history-chatlist__direction",children:"↗ "}),m&&e.jsxs("span",{className:"whatsapp-history-chatlist__preview-icon",children:[m," "]}),sa(w,40)]}),i.unreadCount>0&&e.jsx("span",{className:"whatsapp-history-chatlist__unread",children:i.unreadCount})]})]})},i.chatId)})})]})}function aa({message:s}){const a=s.direction==="outbound"?"outbound":"inbound",t=us(s.messageType),n=(s.body??"").trim(),c=n.length>0,r=c?null:`[${s.messageType}]`;return e.jsx("div",{className:`whatsapp-history-bubble whatsapp-history-bubble--${a}`,children:e.jsxs("div",{className:"whatsapp-history-bubble__inner",children:[t&&e.jsx("span",{className:"whatsapp-history-bubble__type-icon",title:s.messageType,children:t}),c?e.jsx("span",{className:"whatsapp-history-bubble__body",children:n}):e.jsx("span",{className:"whatsapp-history-bubble__placeholder",children:r}),s.audioTranscription&&e.jsxs("span",{className:"whatsapp-history-bubble__transcription",children:["“",s.audioTranscription,"”"]}),s.mediaPath&&e.jsx("a",{className:"whatsapp-history-bubble__media-link",href:s.mediaPath,target:"_blank",rel:"noopener noreferrer",children:s.mediaFilename||"open media"}),e.jsx("span",{className:"whatsapp-history-bubble__time",children:ea(s.timestamp)})]})})}const na=["all","inbound","outbound"],ia=["all","text","image","audio","video","document","sticker","location","contact","reaction","unknown"];function oa({direction:s,type:a,onDirectionChange:t,onTypeChange:n,disabled:c}){const{t:r}=J(["config"]);return e.jsxs("div",{className:"whatsapp-history-filters",children:[e.jsxs("label",{className:"whatsapp-history-filters__field",children:[e.jsx("span",{children:r("config:whatsappHistory.direction")}),e.jsx("select",{value:s,onChange:d=>t(d.target.value),disabled:c,children:na.map(d=>e.jsx("option",{value:d,children:r(`config:whatsappHistory.directionValues.${d}`)},d))})]}),e.jsxs("label",{className:"whatsapp-history-filters__field",children:[e.jsx("span",{children:r("config:whatsappHistory.type")}),e.jsx("select",{value:a,onChange:d=>n(d.target.value),disabled:c,children:ia.map(d=>e.jsx("option",{value:d,children:r(`config:whatsappHistory.typeValues.${d}`)},d))})]})]})}const la=80;function ca({chatId:s,messages:a,loading:t,loadingMore:n,error:c,hasMore:r,direction:d,type:f,onDirectionChange:i,onTypeChange:m,onLoadMore:w}){const{t:j}=J(["config"]),g=l.useRef(null),E=l.useRef(null),y=l.useRef(!1),S=l.useRef(null);l.useEffect(()=>{E.current!==s&&(E.current=s,y.current=!1)},[s]),l.useLayoutEffect(()=>{g.current&&(y.current||a.length!==0&&(g.current.scrollTop=g.current.scrollHeight,y.current=!0))},[s,a.length]),l.useLayoutEffect(()=>{if(!g.current||S.current===null)return;const k=g.current.scrollHeight-S.current;S.current=null,k>0&&(g.current.scrollTop+=k)},[a.length]);const v=l.useCallback(()=>{!r||n||t||(g.current&&(S.current=g.current.scrollHeight),w())},[r,n,t,w]),u=l.useCallback(k=>{if(!y.current)return;k.currentTarget.scrollTop<=la&&v()},[v]);return s?e.jsxs("div",{className:"whatsapp-history-messages",children:[e.jsxs("div",{className:"whatsapp-history-messages__header",children:[e.jsx("div",{className:"whatsapp-history-messages__title",children:ds(s)}),e.jsx(oa,{direction:d,type:f,onDirectionChange:i,onTypeChange:m,disabled:t})]}),e.jsxs("div",{className:"whatsapp-history-messages__scroll",ref:g,onScroll:u,children:[r&&e.jsx("div",{className:"whatsapp-history-messages__load-more-row",children:e.jsx("button",{type:"button",className:"whatsapp-history-messages__load-more",onClick:v,disabled:n||t,children:j(n?"config:whatsappHistory.loadingOlder":"config:whatsappHistory.loadOlder")})}),c&&e.jsx("div",{className:"whatsapp-history-messages__error",children:c}),t&&a.length===0&&e.jsxs("div",{className:"whatsapp-history-messages__loading",children:[e.jsx("span",{className:"spinner"}),e.jsx("span",{children:j("config:whatsappHistory.loadingMessages")})]}),!t&&!c&&a.length===0&&e.jsx("div",{className:"whatsapp-history-messages__empty",children:j("config:whatsappHistory.emptyMessages")}),a.map(k=>e.jsx(aa,{message:k},ra(k)))]})]}):e.jsx("div",{className:"whatsapp-history-messages whatsapp-history-messages--empty",children:e.jsx("div",{className:"whatsapp-history-messages__placeholder",children:j("config:whatsappHistory.selectChat")})})}function ra(s){return typeof s.id=="number"?`id:${s.id}`:s.messageId?`mid:${s.messageId}`:`t:${s.timestamp}:${s.fromJid}:${(s.body??"").slice(0,16)}`}function ps(){const s=Q(),a={};return s&&(a.Authorization=`Bearer ${s}`),a}async function ms(s,a){try{const t=await s.json();if(t&&typeof t.error=="string")return t.error;if(t&&typeof t.message=="string")return t.message}catch{}return`${a}: ${s.statusText}`}async function da(s){const a=`${Z()}/api/whatsapp/chats/${encodeURIComponent(s)}`,t=await fetch(a,{headers:ps()});if(!t.ok)throw new Error(await ms(t,"Failed to fetch WhatsApp chats"));return t.json()}async function as(s,a,t={}){const n=new URLSearchParams;t.cursor&&n.set("cursor",t.cursor),typeof t.limit=="number"&&n.set("limit",String(t.limit)),t.direction&&n.set("direction",t.direction),t.type&&n.set("type",t.type);const c=n.toString(),r=`${Z()}/api/whatsapp/chats/${encodeURIComponent(s)}/${encodeURIComponent(a)}/messages${c?`?${c}`:""}`,d=await fetch(r,{headers:ps()});if(!d.ok)throw new Error(await ms(d,"Failed to fetch WhatsApp messages"));return d.json()}const ua=50;function pa({isOpen:s,onClose:a}){const{t}=J(["config"]),[n,c]=l.useState([]),[r,d]=l.useState(null),[f,i]=l.useState(null),[m,w]=l.useState([]),[j,g]=l.useState(!1),[E,y]=l.useState(null),[S,v]=l.useState(null),[u,k]=l.useState([]),[D,F]=l.useState(!1),[V,W]=l.useState(!1),[q,R]=l.useState(null),[K,h]=l.useState(null),[$,U]=l.useState("all"),[H,se]=l.useState("all"),[N,O]=l.useState(()=>Date.now()),M=l.useRef(0);l.useEffect(()=>{if(!s)return;const C=window.setInterval(()=>O(Date.now()),6e4);return()=>window.clearInterval(C)},[s]),l.useEffect(()=>{if(!s)return;let C=!1;return(async()=>{var ee;try{i(null);const[ne,le]=await Promise.all([He().catch(()=>[]),ls().catch(()=>null)]);if(C)return;c(ne);const ie=(le==null?void 0:le.defaultSessionId)||((ee=ne[0])==null?void 0:ee.id)||null;d(me=>me??ie)}catch(ne){if(C)return;i(ne instanceof Error?ne.message:String(ne))}})(),()=>{C=!0}},[s]);const p=l.useCallback(async C=>{g(!0),y(null);try{const ee=await da(C);w(ee.chats)}catch(ee){y(ee instanceof Error?ee.message:String(ee))}finally{g(!1)}},[]);l.useEffect(()=>{!s||!r||(v(null),k([]),h(null),p(r))},[s,r,p]);const b=l.useMemo(()=>{const C={limit:ua};return $!=="all"&&(C.direction=$),H!=="all"&&(C.type=H),C},[$,H]),L=l.useCallback(async(C,ee,ne)=>{const le=++M.current;F(!0),R(null),k([]),h(null);try{const ie=await as(C,ee,ne);if(le!==M.current)return;k([...ie.messages].reverse()),h(ie.nextCursor)}catch(ie){if(le!==M.current)return;R(ie instanceof Error?ie.message:String(ie))}finally{le===M.current&&F(!1)}},[]);l.useEffect(()=>{!s||!r||!S||L(r,S,b)},[s,r,S,b,L]);const X=l.useCallback(async()=>{if(!(!r||!S||!K)){W(!0),R(null);try{const C=await as(r,S,{...b,cursor:K});k(ee=>[...[...C.messages].reverse(),...ee]),h(C.nextCursor)}catch(C){R(C instanceof Error?C.message:String(C))}finally{W(!1)}}},[r,S,K,b]),ae=l.useCallback(()=>{r&&p(r)},[r,p]),T=l.useCallback(C=>{C.key==="Escape"&&(C.preventDefault(),a())},[a]);return s?e.jsx(Se,{children:e.jsx("div",{className:"modal-overlay visible",onClick:a,children:e.jsxs("div",{className:"whatsapp-history-modal",onClick:C=>C.stopPropagation(),onKeyDown:T,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:t("config:whatsappHistory.title")}),e.jsx("div",{className:"whatsapp-history-modal__session",children:e.jsxs("label",{children:[e.jsx("span",{children:t("config:whatsappHistory.session")}),e.jsxs("select",{value:r??"",onChange:C=>d(C.target.value||null),disabled:n.length===0,children:[n.length===0&&e.jsx("option",{value:"",children:t("config:whatsappHistory.noSessions")}),n.map(C=>e.jsxs("option",{value:C.id,children:[C.id,C.pairedNumber?` (${C.pairedNumber})`:""]},C.id))]})]})}),e.jsx("button",{className:"modal-close",onClick:a,"aria-label":"Close",children:e.jsx(I,{name:"close",size:16})})]}),f&&e.jsx("div",{className:"whatsapp-history-modal__alert",children:f}),e.jsxs("div",{className:"whatsapp-history-modal__body",children:[e.jsx(ta,{chats:m,selectedChatId:S,loading:j,error:E,onSelect:v,onRefresh:ae,now:N}),e.jsx(ca,{chatId:S,messages:u,loading:D,loadingMore:V,error:q,hasMore:K!==null,direction:$,type:H,onDirectionChange:U,onTypeChange:se,onLoadMore:X})]})]})})}):null}function ma({isOpen:s,onClose:a,onOpenConfig:t,onOpenNotifications:n,onOpenHistory:c}){const{t:r}=J(["config"]);if(l.useEffect(()=>{if(!s)return;const f=i=>{i.key==="Escape"&&(i.preventDefault(),a())};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[s,a]),!s)return null;const d=f=>{a(),f()};return e.jsx(Se,{children:e.jsx("div",{className:"modal-overlay visible",onClick:a,children:e.jsxs("div",{className:"whatsapp-hub-modal",onClick:f=>f.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("h2",{children:[e.jsx("span",{className:"whatsapp-hub-modal__icon",children:"📱"}),r("config:whatsappHub.title",{defaultValue:"WhatsApp"})]}),e.jsx("button",{className:"modal-close",onClick:a,"aria-label":"Close",children:e.jsx(I,{name:"close",size:16})})]}),e.jsxs("div",{className:"modal-body",children:[e.jsx("p",{className:"whatsapp-hub-modal__intro",children:r("config:whatsappHub.intro",{defaultValue:"Pick what you want to manage for the WhatsApp integration."})}),e.jsxs("div",{className:"whatsapp-hub-modal__options",children:[e.jsxs("button",{type:"button",className:"whatsapp-hub-modal__option",onClick:()=>d(t),children:[e.jsx("span",{className:"whatsapp-hub-modal__option-icon",children:e.jsx(I,{name:"gear",size:18})}),e.jsxs("span",{className:"whatsapp-hub-modal__option-text",children:[e.jsx("span",{className:"whatsapp-hub-modal__option-title",children:r("config:whatsappHub.config",{defaultValue:"Integration config"})}),e.jsx("span",{className:"whatsapp-hub-modal__option-desc",children:r("config:whatsappHub.configDesc",{defaultValue:"Server URL, API key, sessions and pairing."})})]})]}),e.jsxs("button",{type:"button",className:"whatsapp-hub-modal__option",onClick:()=>d(n),children:[e.jsx("span",{className:"whatsapp-hub-modal__option-icon",children:e.jsx(I,{name:"bell",size:18})}),e.jsxs("span",{className:"whatsapp-hub-modal__option-text",children:[e.jsx("span",{className:"whatsapp-hub-modal__option-title",children:r("config:whatsappHub.notifications",{defaultValue:"Notifications"})}),e.jsx("span",{className:"whatsapp-hub-modal__option-desc",children:r("config:whatsappHub.notificationsDesc",{defaultValue:"Which agent events get forwarded and to whom."})})]})]}),e.jsxs("button",{type:"button",className:"whatsapp-hub-modal__option",onClick:()=>d(c),children:[e.jsx("span",{className:"whatsapp-hub-modal__option-icon",children:e.jsx(I,{name:"hourglass",size:18})}),e.jsxs("span",{className:"whatsapp-hub-modal__option-text",children:[e.jsx("span",{className:"whatsapp-hub-modal__option-title",children:r("config:whatsappHub.history",{defaultValue:"History"})}),e.jsx("span",{className:"whatsapp-hub-modal__option-desc",children:r("config:whatsappHub.historyDesc",{defaultValue:"Browse persisted chats and messages."})})]})]})]})]})]})})})}const ha=[{value:"auto",label:"Auto",icon:"🕐"},{value:"dawn",label:"Dawn",icon:"🌅"},{value:"day",label:"Day",icon:"☀️"},{value:"dusk",label:"Dusk",icon:"🌇"},{value:"night",label:"Night",icon:"🌙"}],ga=[{value:"none",label:"Grass",icon:"🌱"},{value:"concrete",label:"Concrete",icon:"🏗️"},{value:"galactic",label:"Galactic",icon:"🌌"},{value:"metal",label:"Metal",icon:"⚙️"},{value:"hex",label:"Hex",icon:"⬡"},{value:"circuit",label:"Circuit",icon:"🔌"},{value:"pokemon-stadium",label:"Pokemon",icon:"🔴"}],fa=[{value:"static",label:"Static",icon:"🧍"},{value:"idle",label:"Idle",icon:"🚶"},{value:"walk",label:"Walk",icon:"🚶♂️"},{value:"sprint",label:"Sprint",icon:"🏃"},{value:"jump",label:"Jump",icon:"⬆️"},{value:"fall",label:"Fall",icon:"⬇️"},{value:"crouch",label:"Crouch",icon:"🧎"},{value:"sit",label:"Sit",icon:"🪑"},{value:"die",label:"Die",icon:"💀"},{value:"emote-yes",label:"Yes",icon:"👍"},{value:"emote-no",label:"No",icon:"👎"}],xa=[{value:"normal",label:"Normal",icon:"🎨"},{value:"bw",label:"B&W",icon:"⬛"},{value:"sepia",label:"Sepia",icon:"🟤"},{value:"cool",label:"Cool",icon:"❄️"},{value:"warm",label:"Warm",icon:"🔥"},{value:"neon",label:"Neon",icon:"💜"}],ba=[{key:"showTrees",icon:"🌳",label:"Trees"},{key:"showBushes",icon:"🌿",label:"Bushes"},{key:"showHouse",icon:"🏠",label:"House"},{key:"showLamps",icon:"💡",label:"Lamps"},{key:"showGrass",icon:"🟩",label:"Grass"},{key:"showClouds",icon:"☁️",label:"Clouds"}],ja=[{value:null,label:"Auto",color:"linear-gradient(135deg, #4a90d9 0%, #0a1a2a 100%)"},{value:"#4a90d9",label:"Day Blue",color:"#4a90d9"},{value:"#0a1a2a",label:"Night",color:"#0a1a2a"},{value:"#ff6b35",label:"Sunset",color:"#ff6b35"},{value:"#1a0a2e",label:"Purple",color:"#1a0a2e"},{value:"#2d5a27",label:"Matrix",color:"#2d5a27"},{value:"#8b0000",label:"Blood",color:"#8b0000"},{value:"#000000",label:"Void",color:"#000000"}],va={showTrees:"trees",showBushes:"bushes",showHouse:"house",showLamps:"lamps",showGrass:"grass",showClouds:"clouds"},ya={none:"grass","pokemon-stadium":"pokemon"},wa={"emote-yes":"yes","emote-no":"no"},Na={"":"auto","#4a90d9":"dayBlue","#0a1a2a":"night","#ff6b35":"sunset","#1a0a2e":"purple","#2d5a27":"matrix","#8b0000":"blood","#000000":"void"};function te({checked:s,onChange:a}){return e.jsxs("label",{className:"config-toggle",children:[e.jsx("input",{type:"checkbox",className:"config-toggle-input",checked:s,onChange:t=>a(t.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})}function ve({options:s,value:a,onChange:t,iconOnly:n=!1}){return e.jsx("div",{className:"chip-selector",children:s.map(c=>e.jsxs("button",{className:`chip ${a===c.value?"active":""}`,onClick:()=>t(c.value),title:c.label,children:[e.jsx("span",{className:"chip-icon",children:c.icon}),!n&&e.jsx("span",{className:"chip-label",children:c.label})]},c.value))})}function _({text:s,query:a}){if(!a.trim())return e.jsx(e.Fragment,{children:s});const t=s.toLowerCase(),n=a.toLowerCase(),c=t.indexOf(n);if(c===-1)return e.jsx(e.Fragment,{children:s});const r=s.slice(0,c),d=s.slice(c,c+a.length),f=s.slice(c+a.length);return e.jsxs(e.Fragment,{children:[r,e.jsx("mark",{className:"search-highlight",children:d}),f]})}const ka=[{id:"general",title:"General",keywords:["history","hide costs","grid","fps","power saving","low power","battery","bajo consumo","performance","limit","editor","external editor","language","idioma","语言","vibration","haptic","intensity","tab title","tmux","process persistence","interactive","tui","terminal","experimental","claude","stream","streaming","word by word","live text","grok","codex","app-server","app server","opencode","serve"]},{id:"agentNames",title:"Agent Names",keywords:["agent","names","custom","characters","rename"]},{id:"defaultClass",title:"Default Spawn Class",keywords:["default","class","spawn","agent","scout","builder","random"]},{id:"appearance",title:"Appearance",keywords:["theme","appearance","color","dark","light","style","look"]},{id:"connection",title:"Connection",keywords:["backend","url","auth","token","reconnect","server","api","connect","codex","opencode","binary","path"]},{id:"scene",title:"Scene",keywords:["character","size","indicator","scale","time","dawn","day","dusk","night","auto"]},{id:"terrain",title:"Terrain",keywords:["trees","bushes","house","lamps","grass","clouds","fog","brightness","floor","sky","color","environment","battlefield","size","grid","simple","minimal","dark","clean"]},{id:"modelStyle",title:"Agent Model Style",keywords:["saturation","roughness","metalness","glow","emissive","reflections","wireframe","color mode","material","shader"]},{id:"animations",title:"Animations",keywords:["idle","working","animation","walk","run","sprint","jump","sit","crouch"]},{id:"secrets",title:"Secrets",keywords:["secrets","api","key","password","credentials","env","environment"]},{id:"claudeAccounts",title:"Claude Accounts",keywords:["claude","accounts","credentials","oauth","rate limit","session","david","profile","switch account","subscription"]},{id:"grokAccounts",title:"Grok Accounts",keywords:["grok","xai","x.ai","accounts","credentials","oauth","session","profile","switch account","subscription"]},{id:"codexAccounts",title:"Codex Accounts",keywords:["codex","openai","chatgpt","accounts","credentials","oauth","session","profile","switch account","subscription"]},{id:"systemPrompt",title:"System Prompt",keywords:["system","prompt","global","instructions","ai","agent","rules","guidelines"]},{id:"data",title:"Data",keywords:["export","import","backup","restore","save","load","json"]},{id:"integrations",title:"Integrations",keywords:["integrations","integraciones","plugins","gmail","slack","jira","calendar","docx","email","whatsapp","notifications","notification","baileys","history","historial","chat","messages","inbox","config","setup"]},{id:"workflows",title:"Workflows",keywords:["workflow","automation","state machine","editor","actions","transitions","pipeline"]},{id:"triggers",title:"Triggers",keywords:["trigger","event","webhook","cron","slack","email","jira","matching","fire"]},{id:"monitoring",title:"Monitoring",keywords:["monitoring","logs","triggers","events","history","workflow","traces","audit","timeline"]},{id:"statistics",title:"Statistics",keywords:["statistics","stats","usage","tokens","token","claude","chart","graph","pie","cost"]},{id:"experimental",title:"Experimental",keywords:["experimental","2d","view","voice","assistant","speech","tts","text to speech","echo","prompt","duplicate"]},{id:"about",title:"About",keywords:["about","version","update","credits","github","releases"]}],Ke=[{value:"auto",label:"Auto",icon:"🌐"},{value:"en",label:"English",icon:"🇺🇸"},{value:"zh-CN",label:"中文",icon:"🇨🇳"},{value:"es",label:"Español",icon:"🇪🇸"},{value:"hi",label:"हिन्दी",icon:"🇮🇳"},{value:"pt",label:"Português",icon:"🇧🇷"},{value:"ru",label:"Русский",icon:"🇷🇺"},{value:"ja",label:"日本語",icon:"🇯🇵"},{value:"de",label:"Deutsch",icon:"🇩🇪"},{value:"fr",label:"Français",icon:"🇫🇷"},{value:"it",label:"Italiano",icon:"🇮🇹"}];function Sa({config:s,onChange:a,searchQuery:t="",onOpenIntegrationsModal:n,onOpenMonitoringModal:c,onOpenStatisticsModal:r,onOpenWorkflowEditor:d,onOpenTriggerManager:f}){var Ge;const{t:i}=J(["config","common"]),m=Ms(),w=Us(),[j,g]=l.useState(()=>Vs(ke.DEFAULT_AGENT_CLASS)||"scout"),[E,y]=l.useState(m.historyLimit),[S,v]=l.useState(()=>Ks()),[u,k]=l.useState(!1),[D,F]=l.useState(""),[V,W]=l.useState(()=>Q()),[q,R]=l.useState(!1),[K,h]=l.useState(!1),[$,U]=l.useState(""),[H,se]=l.useState(!1),[N,O]=l.useState(!1),[M,p]=l.useState(!1),[b,L]=l.useState(!1),[X,ae]=l.useState(!1),[T,C]=l.useState(""),[ee,ne]=l.useState(!1);l.useEffect(()=>{xt().then(C).catch(()=>{})},[]),l.useEffect(()=>{gt().then(o=>{o!==m.experimentalEchoPrompt&&A.updateSettings({experimentalEchoPrompt:o})}).catch(()=>{})},[]),l.useEffect(()=>{jt().then(o=>{o!==m.tmuxMode&&A.updateSettings({tmuxMode:o})}).catch(()=>{})},[]),l.useEffect(()=>{yt().then(o=>{o!==m.interactiveMode&&A.updateSettings({interactiveMode:o})}).catch(()=>{})},[]),l.useEffect(()=>{Nt().then(o=>{o!==m.codexAppServerMode&&A.updateSettings({codexAppServerMode:o})}).catch(()=>{})},[]),l.useEffect(()=>{St().then(o=>{o!==m.opencodeServerMode&&A.updateSettings({opencodeServerMode:o})}).catch(()=>{})},[]),l.useEffect(()=>Hs(o=>{v(o),k(!1)}),[]);const le=ha.map(o=>({...o,label:i(`config:time.${o.value}`)})),ie=ga.map(o=>({...o,label:i(`config:floor.${ya[o.value]||o.value}`)})),me=fa.map(o=>({...o,label:i(`config:animation.${wa[o.value]||o.value}`)})),ye=xa.map(o=>({...o,label:i(`config:colorMode.${o.value}`)})),we=ba.map(o=>({...o,label:i(`config:terrain.${va[o.key]}`)})),re=ja.map(o=>({...o,label:i(`config:sky.${Na[o.value??""]}`)})),fe=t.trim()?ka.filter(o=>{const z=t.toLowerCase();return o.title.toLowerCase().includes(z)||o.keywords.some(de=>de.toLowerCase().includes(z))}).map(o=>o.id):null,P=o=>fe?fe.includes(o):!0,he=P("integrations"),ce=m.customAgentNames||[],Fe=ce.length>0?ce:Ws,xe=()=>{const o=$.trim();o&&!ce.includes(o)&&(A.updateSettings({customAgentNames:[...ce,o]}),U(""))},ze=o=>{A.updateSettings({customAgentNames:ce.filter(z=>z!==o)})},Be=()=>{A.updateSettings({customAgentNames:[]})},Te=()=>{const o=D.trim();if(o){if(S.includes(o)){F("");return}v([...S,o]),k(!0),F("")}},Re=o=>{v(S.filter((z,de)=>de!==o)),k(!0)},Ne=(o,z)=>{const de=o+z;if(de<0||de>=S.length)return;const je=S.slice();[je[o],je[de]]=[je[de],je[o]],v(je),k(!0)},Ee=()=>{Ys(S),k(!1),Ve()},Pe=o=>{W(o),R(!0)},_e=()=>{$e(ke.AUTH_TOKEN,V),R(!1),Ve()},Me=o=>{C(o),ne(!0)},Ie=()=>{bt(T).catch(()=>{}),ne(!1)},x=o=>{a({...s,terrain:{...s.terrain,...o}})},B=o=>{a({...s,modelStyle:{...s.modelStyle,...o}})},oe=o=>{a({...s,animations:{...s.animations,...o}})},be=o=>{y(o),A.updateSettings({historyLimit:o})},hs=o=>{const z=s.terrain[o];typeof z=="boolean"&&x({[o]:!z})},Y=t.trim().length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"config-section",children:[fe&&fe.length===0&&e.jsx("div",{className:"config-no-results",children:i("config:noResults",{query:t})}),P("general")&&e.jsxs(G,{title:i("config:sections.general"),storageKey:"general",defaultOpen:!0,forceOpen:Y&&P("general"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:general.history"),query:t})}),e.jsx("input",{type:"number",className:"config-input config-input-sm",value:E,onChange:o=>be(parseInt(o.target.value)||100),min:50,max:2e3,step:50})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:general.hideCosts"),query:t})}),e.jsx(te,{checked:m.hideCost,onChange:o=>A.updateSettings({hideCost:o})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",title:i("config:general.streamTextLiveTitle"),children:e.jsx(_,{text:i("config:general.streamTextLive"),query:t})}),e.jsx(te,{checked:m.streamTextLive!==!1,onChange:o=>A.updateSettings({streamTextLive:o})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:general.grid"),query:t})}),e.jsx(te,{checked:s.gridVisible,onChange:o=>a({...s,gridVisible:o})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:general.showFPS"),query:t})}),e.jsx(te,{checked:m.showFPS,onChange:o=>A.updateSettings({showFPS:o})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:general.fpsLimit"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"120",step:"10",value:s.fpsLimit,onChange:o=>a({...s,fpsLimit:parseInt(o.target.value)})}),e.jsx("span",{className:"config-value",children:s.fpsLimit===0?"∞":s.fpsLimit})]}),e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Experimental: Reduce FPS when idle to save power",children:[e.jsx(_,{text:i("config:general.powerSaving"),query:t})," ",e.jsx(I,{name:"bolt",size:12})]}),e.jsx(te,{checked:m.powerSaving,onChange:o=>A.updateSettings({powerSaving:o})})]}),e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Battery saver for mobile: caps scene FPS (20 active / 5 idle), freezes decorative animations and disables word-by-word streaming. Off = normal mode.",children:[e.jsx(_,{text:i("config:general.lowPowerMode"),query:t})," ",e.jsx(I,{name:"bolt",size:12})]}),e.jsx(te,{checked:m.lowPowerMode===!0,onChange:o=>A.updateSettings({lowPowerMode:o})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",title:"Wrap agent processes in tmux sessions so they survive server restarts (requires tmux installed)",children:e.jsx(_,{text:i("config:general.tmuxMode"),query:t})}),e.jsx(te,{checked:m.tmuxMode,onChange:async o=>{A.updateSettings({tmuxMode:o});try{await vt(o)}catch(z){console.error("Failed to sync tmux mode setting to server:",z)}}})]}),e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Experimental: run Claude agents as the real interactive `claude` TUI inside tmux, reconstructing the conversation from the session transcript (requires tmux). Takes effect on server restart.",children:[e.jsx(_,{text:i("config:general.interactiveMode"),query:t})," ",e.jsx(I,{name:"bolt",size:12})]}),e.jsx(te,{checked:m.interactiveMode,onChange:async o=>{A.updateSettings({interactiveMode:o});try{await wt(o)}catch(z){console.error("Failed to sync interactive mode setting to server:",z)}}})]}),e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Experimental: run Codex agents through a persistent `codex app-server` so replies stream word-by-word (token deltas) instead of appearing as one block. The app-server runs detached and survives commander restarts — in-flight turns keep running and reconnect automatically. Applies to new Codex turns; no server restart needed to toggle.",children:[e.jsx(_,{text:i("config:general.codexAppServerMode"),query:t})," ",e.jsx(I,{name:"bolt",size:12})]}),e.jsx(te,{checked:m.codexAppServerMode,onChange:async o=>{A.updateSettings({codexAppServerMode:o});try{await kt(o)}catch(z){console.error("Failed to sync codex app-server mode setting to server:",z)}}})]}),e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Experimental: run OpenCode agents through a persistent, detached `opencode serve` HTTP server so replies stream word-by-word (token deltas over SSE) instead of appearing as one block. The server survives commander restarts — in-flight turns keep running and reconnect automatically. Applies to new OpenCode turns; no server restart needed to toggle.",children:[e.jsx(_,{text:i("config:general.opencodeServerMode"),query:t})," ",e.jsx(I,{name:"bolt",size:12})]}),e.jsx(te,{checked:m.opencodeServerMode,onChange:async o=>{A.updateSettings({opencodeServerMode:o});try{await Ct(o)}catch(z){console.error("Failed to sync opencode server mode setting to server:",z)}}})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:general.vibrationIntensity"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"5",step:"1",value:m.vibrationIntensity,onChange:o=>A.updateSettings({vibrationIntensity:parseInt(o.target.value)})}),e.jsx("span",{className:"config-value",children:m.vibrationIntensity===0?i("config:vibrationValues.off"):m.vibrationIntensity===1?i("config:vibrationValues.ultraLight"):m.vibrationIntensity===2?i("config:vibrationValues.veryLight"):m.vibrationIntensity===3?i("config:vibrationValues.light"):m.vibrationIntensity===4?i("config:vibrationValues.medium"):i("config:vibrationValues.heavy")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:general.externalEditor"),query:t})}),e.jsx("input",{type:"text",className:"config-input",placeholder:i("config:general.externalEditorPlaceholder"),value:m.externalEditorCommand||"",onChange:o=>A.updateSettings({externalEditorCommand:o.target.value})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:general.tabTitle"),query:t})}),e.jsx("input",{type:"text",className:"config-input",placeholder:i("config:general.tabTitlePlaceholder"),value:m.tabTitle||"",onChange:o=>A.updateSettings({tabTitle:o.target.value})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:general.language"),query:t})}),e.jsx(ve,{options:Ke,value:localStorage.getItem("tide-commander-language-mode")==="manual"?((Ge=Ke.find(o=>o.value!=="auto"&&Ue.language.startsWith(o.value.split("-")[0])))==null?void 0:Ge.value)||"en":"auto",onChange:o=>{var z;if(o==="auto"){localStorage.setItem("tide-commander-language-mode","auto");const de=navigator.language,je=((z=Ke.find(Ye=>Ye.value!=="auto"&&de.startsWith(Ye.value.split("-")[0])))==null?void 0:z.value)||"en";Ue.changeLanguage(je)}else localStorage.setItem("tide-commander-language-mode","manual"),Ue.changeLanguage(o)}})]})]}),P("agentNames")&&e.jsx(G,{title:i("config:sections.agentNames"),storageKey:"agentNames",defaultOpen:!1,forceOpen:Y&&P("agentNames"),children:e.jsxs("div",{className:"agent-names-section",children:[e.jsx("span",{className:"config-hint",children:ce.length>0?i("config:agentNames.customConfigured",{count:ce.length}):i("config:agentNames.usingDefaults")}),e.jsxs("div",{className:"agent-names-input-row",children:[e.jsx("input",{type:"text",className:"config-input config-input-full",placeholder:i("config:agentNames.addPlaceholder"),value:$,onChange:o=>U(o.target.value),onKeyDown:o=>{o.key==="Enter"&&xe()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:xe,disabled:!$.trim(),title:i("config:agentNames.addName"),children:"+"})]}),e.jsx("div",{className:"agent-names-list",children:Fe.map((o,z)=>e.jsxs("div",{className:"agent-name-chip",children:[e.jsx("span",{className:"agent-name-text",children:o}),ce.length>0&&e.jsx("button",{className:"agent-name-remove",onClick:()=>ze(o),title:i("common:buttons.remove"),children:"x"})]},`${o}-${z}`))}),ce.length>0&&e.jsx("button",{className:"config-btn config-btn-link",onClick:Be,children:i("common:buttons.resetToDefaults")})]})}),P("defaultClass")&&e.jsx(G,{title:"Default Spawn Class",storageKey:"defaultClass",defaultOpen:!1,forceOpen:Y&&P("defaultClass"),children:e.jsxs("div",{className:"config-row config-row-stacked",children:[e.jsx("span",{className:"config-hint",children:'Class pre-selected when the spawn modal opens. "Random" picks a different class each time.'}),e.jsxs("div",{className:"agent-names-list",style:{flexWrap:"wrap",gap:"6px",marginTop:"8px"},children:[e.jsx("div",{className:`agent-name-chip${j==="random"?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{g("random"),$e(ke.DEFAULT_AGENT_CLASS,"random")},children:e.jsx("span",{className:"agent-name-text",children:"🎲 Random"})}),Object.entries(qs).map(([o,z])=>e.jsx("div",{className:`agent-name-chip${j===o?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{g(o),$e(ke.DEFAULT_AGENT_CLASS,o)},children:e.jsxs("span",{className:"agent-name-text",children:[z.icon," ",o.charAt(0).toUpperCase()+o.slice(1)]})},o)),w.map(o=>e.jsx("div",{className:`agent-name-chip${j===o.id?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{g(o.id),$e(ke.DEFAULT_AGENT_CLASS,o.id)},children:e.jsxs("span",{className:"agent-name-text",children:[o.icon," ",o.name]})},o.id))]})]})}),P("appearance")&&e.jsx(G,{title:i("config:sections.appearance"),storageKey:"appearance",defaultOpen:!1,forceOpen:Y&&P("appearance"),children:e.jsx(_t,{})}),P("connection")&&e.jsxs(G,{title:i("config:sections.connection"),storageKey:"connection",defaultOpen:!1,forceOpen:Y&&P("connection"),children:[e.jsxs("div",{className:"config-row config-row-stacked",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:connection.backendUrl"),query:t})}),e.jsx("div",{className:"backend-urls-list",children:S.map((o,z)=>e.jsxs("div",{className:"backend-url-row",children:[e.jsx("span",{className:"backend-url-priority",title:i("config:connection.priorityLabel",{defaultValue:"Priority"}),children:z+1}),e.jsx("span",{className:"backend-url-text",title:o,children:o}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>Ne(z,-1),disabled:z===0,title:i("config:connection.moveUp",{defaultValue:"Move up"}),children:"↑"}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>Ne(z,1),disabled:z===S.length-1,title:i("config:connection.moveDown",{defaultValue:"Move down"}),children:"↓"}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>Re(z),title:i("common:buttons.remove"),children:"x"})]},`${o}-${z}`))}),e.jsxs("div",{className:"config-input-group",children:[e.jsx("input",{type:"text",className:"config-input config-input-full",value:D,onChange:o=>F(o.target.value),placeholder:i("config:connection.addUrlPlaceholder",{defaultValue:"http://host:port"}),onKeyDown:o=>{o.key==="Enter"&&Te()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:Te,disabled:!D.trim(),title:i("config:connection.addUrl",{defaultValue:"Add URL"}),children:"+"}),u&&e.jsx("button",{className:"config-btn config-btn-sm",onClick:Ee,title:i("config:connection.saveAndReconnect"),children:i("common:buttons.apply")})]}),e.jsx("span",{className:"config-hint",children:i("config:connection.urlsHint",{defaultValue:"Tried in order on connect; the first reachable host wins. Leave empty for auto-detect."})})]}),e.jsxs("div",{className:"config-row config-row-stacked",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:connection.authToken"),query:t})}),e.jsxs("div",{className:"config-input-group",children:[e.jsx("input",{type:K?"text":"password",className:"config-input config-input-full",value:V,onChange:o=>Pe(o.target.value),placeholder:i("config:connection.tokenPlaceholder"),onKeyDown:o=>{o.key==="Enter"&&q&&_e()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>h(!K),title:i(K?"config:connection.hideToken":"config:connection.showToken"),children:e.jsx(I,{name:K?"eye-closed":"eye",size:14})}),q&&e.jsx("button",{className:"config-btn config-btn-sm",onClick:_e,title:i("config:connection.saveAndReconnect"),children:i("common:buttons.apply")})]}),e.jsx("span",{className:"config-hint",children:i("config:connection.tokenRequired")})]}),e.jsxs("div",{className:"config-row config-row-stacked",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:connection.codexBinaryPath"),query:t})}),e.jsxs("div",{className:"config-input-group",children:[e.jsx("input",{type:"text",className:"config-input config-input-full",value:T,onChange:o=>Me(o.target.value),placeholder:i("config:connection.codexBinaryPathPlaceholder"),onKeyDown:o=>{o.key==="Enter"&&ee&&Ie()}}),ee&&e.jsx("button",{className:"config-btn config-btn-sm",onClick:Ie,children:i("common:buttons.apply")})]}),e.jsx("span",{className:"config-hint",children:i("config:connection.codexBinaryPathHint")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("common:buttons.reconnect"),query:t})}),e.jsx("button",{className:"config-btn",onClick:()=>Ve(),title:"Force reconnect to server",children:i("common:buttons.reconnect")})]})]}),P("scene")&&e.jsxs(G,{title:i("config:sections.scene"),storageKey:"scene",defaultOpen:!1,forceOpen:Y&&P("scene"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:scene.characterSize"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.3",max:"3.0",step:"0.1",value:s.characterScale,onChange:o=>a({...s,characterScale:parseFloat(o.target.value)})}),e.jsxs("span",{className:"config-value",children:[s.characterScale.toFixed(1),"x"]})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:scene.scale2d",{defaultValue:"2D Scale"}),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.3",max:"2.0",step:"0.1",value:s.scale2d,onChange:o=>a({...s,scale2d:parseFloat(o.target.value)})}),e.jsxs("span",{className:"config-value",children:[s.scale2d.toFixed(1),"x"]})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:scene.scale3d",{defaultValue:"3D Scale"}),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.3",max:"2.0",step:"0.1",value:s.scale3d,onChange:o=>a({...s,scale3d:parseFloat(o.target.value)})}),e.jsxs("span",{className:"config-value",children:[s.scale3d.toFixed(1),"x"]})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:scene.show2DTaskLabels",{defaultValue:"Show 2D task labels"}),query:t})}),e.jsx(te,{checked:s.show2DTaskLabels,onChange:o=>a({...s,show2DTaskLabels:o})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:scene.time"),query:t})}),e.jsx(ve,{options:le,value:s.timeMode,onChange:o=>a({...s,timeMode:o}),iconOnly:!0})]})]}),P("terrain")&&e.jsxs(G,{title:i("config:sections.terrain"),storageKey:"terrain",defaultOpen:!1,forceOpen:Y&&P("terrain"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:terrainSettings.simpleMode",{defaultValue:"Simple Mode"}),query:t})}),e.jsx(te,{checked:s.terrain.simpleMode??!1,onChange:o=>x({simpleMode:o})})]}),e.jsx("div",{className:"terrain-icons",style:{opacity:s.terrain.simpleMode?.4:1,pointerEvents:s.terrain.simpleMode?"none":"auto"},children:we.map(o=>e.jsx("button",{className:`terrain-icon-btn ${s.terrain[o.key]?"active":""}`,onClick:()=>hs(o.key),title:o.label,children:o.icon},o.key))}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:terrainSettings.fog"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"2",step:"0.1",value:s.terrain.fogDensity,onChange:o=>x({fogDensity:parseFloat(o.target.value)})}),e.jsx("span",{className:"config-value",children:s.terrain.fogDensity===0?i("config:fogValues.off"):s.terrain.fogDensity<=1?i("config:fogValues.low"):i("config:fogValues.high")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:terrainSettings.brightness"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.2",max:"2",step:"0.1",value:s.terrain.brightness,onChange:o=>x({brightness:parseFloat(o.target.value)})}),e.jsx("span",{className:"config-value",children:s.terrain.brightness<=.5?i("config:brightnessValues.dark"):s.terrain.brightness<=1.2?i("config:brightnessValues.normal"):i("config:brightnessValues.bright")})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:terrainSettings.floor"),query:t})}),e.jsx(ve,{options:ie,value:s.terrain.floorStyle,onChange:o=>x({floorStyle:o}),iconOnly:!0})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:terrainSettings.sky"),query:t})}),e.jsx("div",{className:"sky-color-selector",children:re.map(o=>e.jsx("button",{className:`sky-color-btn ${s.terrain.skyColor===o.value?"active":""}`,onClick:()=>x({skyColor:o.value}),title:o.label,style:{background:o.color}},o.value??"auto"))})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:terrainSettings.battlefieldSize"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"30",max:"200",step:"10",value:s.terrain.battlefieldSize,onChange:o=>x({battlefieldSize:parseInt(o.target.value)})}),e.jsx("span",{className:"config-value",children:s.terrain.battlefieldSize})]})]}),P("modelStyle")&&e.jsxs(G,{title:i("config:sections.modelStyle"),storageKey:"modelStyle",defaultOpen:!1,forceOpen:Y&&P("modelStyle"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:modelStyleSettings.saturation"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"2",step:"0.1",value:s.modelStyle.saturation,onChange:o=>B({saturation:parseFloat(o.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.saturation<=.3?i("config:saturationValues.gray"):s.modelStyle.saturation<=1.2?i("config:saturationValues.normal"):i("config:saturationValues.vivid")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:modelStyleSettings.roughness"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"-1",max:"1",step:"0.1",value:s.modelStyle.roughness,onChange:o=>B({roughness:parseFloat(o.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.roughness<0?i("config:roughnessValues.auto"):s.modelStyle.roughness<=.3?i("config:roughnessValues.glossy"):s.modelStyle.roughness<=.7?i("config:roughnessValues.normal"):i("config:roughnessValues.matte")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:modelStyleSettings.metalness"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"-1",max:"1",step:"0.1",value:s.modelStyle.metalness,onChange:o=>B({metalness:parseFloat(o.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.metalness<0?i("config:metalnessValues.auto"):s.modelStyle.metalness<=.3?i("config:metalnessValues.plastic"):s.modelStyle.metalness<=.7?i("config:metalnessValues.mixed"):i("config:metalnessValues.metal")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:modelStyleSettings.glow"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"1",step:"0.05",value:s.modelStyle.emissiveBoost,onChange:o=>B({emissiveBoost:parseFloat(o.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.emissiveBoost<=.1?i("config:glowValues.off"):s.modelStyle.emissiveBoost<=.4?i("config:glowValues.low"):s.modelStyle.emissiveBoost<=.7?i("config:glowValues.med"):i("config:glowValues.high")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:modelStyleSettings.reflections"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"-1",max:"2",step:"0.1",value:s.modelStyle.envMapIntensity,onChange:o=>B({envMapIntensity:parseFloat(o.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.envMapIntensity<0?i("config:reflectionValues.auto"):s.modelStyle.envMapIntensity<=.3?i("config:reflectionValues.low"):s.modelStyle.envMapIntensity<=1?i("config:reflectionValues.normal"):i("config:reflectionValues.high")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:modelStyleSettings.wireframe"),query:t})}),e.jsx(te,{checked:s.modelStyle.wireframe,onChange:o=>B({wireframe:o})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:modelStyleSettings.colorMode"),query:t})}),e.jsx(ve,{options:ye,value:s.modelStyle.colorMode,onChange:o=>B({colorMode:o}),iconOnly:!0})]})]}),P("animations")&&e.jsxs(G,{title:i("config:sections.animations"),storageKey:"animations",defaultOpen:!1,forceOpen:Y&&P("animations"),children:[e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:animationSettings.idle"),query:t})}),e.jsx(ve,{options:me,value:s.animations.idleAnimation,onChange:o=>oe({idleAnimation:o}),iconOnly:!0})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:animationSettings.working"),query:t})}),e.jsx(ve,{options:me,value:s.animations.workingAnimation,onChange:o=>oe({workingAnimation:o}),iconOnly:!0})]})]}),P("secrets")&&e.jsx(G,{title:i("config:sections.secrets"),storageKey:"secrets",defaultOpen:!1,forceOpen:Y&&P("secrets"),children:e.jsx(ut,{})}),P("claudeAccounts")&&e.jsx(G,{title:i("config:sections.claudeAccounts",{defaultValue:"Claude Accounts"}),storageKey:"claudeAccounts",defaultOpen:!1,forceOpen:Y&&P("claudeAccounts"),children:e.jsx(Gs,{})}),P("grokAccounts")&&e.jsx(G,{title:i("config:sections.grokAccounts",{defaultValue:"Grok Accounts"}),storageKey:"grokAccounts",defaultOpen:!1,forceOpen:Y&&P("grokAccounts"),children:e.jsx(Xe,{provider:"grok"})}),P("codexAccounts")&&e.jsx(G,{title:i("config:sections.codexAccounts",{defaultValue:"Codex Accounts"}),storageKey:"codexAccounts",defaultOpen:!1,forceOpen:Y&&P("codexAccounts"),children:e.jsx(Xe,{provider:"codex"})}),P("systemPrompt")&&e.jsx(G,{title:i("config:sections.systemPrompt"),storageKey:"systemPrompt",defaultOpen:!1,forceOpen:Y&&P("systemPrompt"),children:e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:i("config:systemPrompt.title"),query:t})}),e.jsx("button",{className:"config-button",onClick:()=>se(!0),children:i("config:systemPrompt.editPrompt")})]})}),P("data")&&e.jsx(G,{title:i("config:sections.data"),storageKey:"data",defaultOpen:!1,forceOpen:Y&&P("data"),children:e.jsx(Pt,{})}),he&&e.jsx(G,{title:i("config:sections.integrations"),storageKey:"integrations",defaultOpen:!1,forceOpen:Y&&he,children:e.jsx(Ft,{onOpenModal:o=>{o==="whatsapp"?ae(!0):n==null||n(o)}})}),P("workflows")&&e.jsxs(G,{title:"Workflows",storageKey:"workflows",defaultOpen:!1,forceOpen:Y&&P("workflows"),children:[e.jsx("div",{className:"config-row",children:e.jsx("span",{className:"config-label",children:e.jsx(_,{text:"Create and manage automated workflow pipelines with visual state machine editor",query:t})})}),e.jsx("div",{className:"config-row",children:e.jsx("button",{className:"config-button",onClick:()=>d==null?void 0:d(),children:"Open Workflow Editor"})})]}),P("triggers")&&e.jsxs(G,{title:"Triggers",storageKey:"triggers",defaultOpen:!1,forceOpen:Y&&P("triggers"),children:[e.jsx("div",{className:"config-row",children:e.jsx("span",{className:"config-label",children:e.jsx(_,{text:"Create and manage event-driven triggers that fire agents with templates",query:t})})}),e.jsx("div",{className:"config-row",children:e.jsx("button",{className:"config-button",onClick:()=>f==null?void 0:f(),children:"Open Trigger Manager"})})]}),P("monitoring")&&e.jsxs(G,{title:"Monitoring",storageKey:"monitoring",defaultOpen:!1,forceOpen:Y&&P("monitoring"),children:[e.jsx("div",{className:"config-row",children:e.jsx("span",{className:"config-label",children:e.jsx(_,{text:"View event logs, trigger history, workflow traces, and system stats",query:t})})}),e.jsx("div",{className:"config-row",children:e.jsx("button",{className:"config-button",onClick:()=>c==null?void 0:c(),children:"Open Monitoring & Logs"})})]}),P("statistics")&&e.jsxs(G,{title:"Statistics",storageKey:"statistics",defaultOpen:!1,forceOpen:Y&&P("statistics"),children:[e.jsx("div",{className:"config-row",children:e.jsx("span",{className:"config-label",children:e.jsx(_,{text:"View token usage charts and system-wide agent statistics",query:t})})}),e.jsx("div",{className:"config-row",children:e.jsx("button",{className:"config-button",onClick:()=>r==null?void 0:r(),children:"Open Statistics"})})]}),P("experimental")&&e.jsxs(G,{title:i("config:sections.experimental"),storageKey:"experimental",defaultOpen:!1,forceOpen:Y&&P("experimental"),children:[e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Lightweight 2D top-down view for better performance",children:[e.jsx(_,{text:i("config:experimental.2dView"),query:t})," ",e.jsx(I,{name:"map",size:12})]}),e.jsx(te,{checked:m.experimental2DView,onChange:o=>A.updateSettings({experimental2DView:o})})]}),e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Voice assistant for hands-free agent control",children:[e.jsx(_,{text:i("config:experimental.voiceAssistant"),query:t})," ",e.jsx(I,{name:"microphone",size:12})]}),e.jsx(te,{checked:m.experimentalVoiceAssistant,onChange:o=>A.updateSettings({experimentalVoiceAssistant:o})})]}),e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Text-to-speech for reading agent responses",children:[e.jsx(_,{text:i("config:experimental.tts"),query:t})," ",e.jsx(I,{name:"speaker-on",size:12})]}),e.jsx(te,{checked:m.experimentalTTS,onChange:o=>A.updateSettings({experimentalTTS:o})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",title:"Duplicate system prompt for improved LLM attention coverage. Increases input token usage.",children:e.jsx(_,{text:i("config:experimental.echoPrompt"),query:t})}),e.jsx(te,{checked:m.experimentalEchoPrompt,onChange:async o=>{A.updateSettings({experimentalEchoPrompt:o});try{await ft(o)}catch(z){console.error("Failed to sync echo prompt setting to server:",z)}}})]}),e.jsx("span",{className:"config-hint",children:i("config:experimental.hint")})]}),P("about")&&e.jsx(G,{title:i("config:sections.about"),storageKey:"about",defaultOpen:!1,forceOpen:Y&&P("about"),children:e.jsx(Ot,{})})]}),e.jsx(Vt,{isOpen:H,onClose:()=>se(!1)}),e.jsx(qt,{isOpen:N,onClose:()=>O(!1)}),e.jsx(Xt,{isOpen:M,onClose:()=>p(!1)}),e.jsx(pa,{isOpen:b,onClose:()=>L(!1)}),e.jsx(ma,{isOpen:X,onClose:()=>ae(!1),onOpenConfig:()=>O(!0),onOpenNotifications:()=>p(!0),onOpenHistory:()=>L(!0)})]})}function Pa({onConfigChange:s,onToolChange:a,config:t,isOpen:n,onClose:c,onOpenBuildingModal:r,onOpenAreaExplorer:d,onOpenIntegrationsModal:f,onOpenMonitoringModal:i,onOpenStatisticsModal:m,onOpenWorkflowEditor:w,onOpenTriggerManager:j}){const{t:g}=J(["config","common"]),E=Js(),y=Zs(),S=Xs(),v=Qs(),u=et(),k=Array.from(E.values()),D=Array.from(y.values()),[F,V]=l.useState(""),W=l.useRef(null);if(l.useEffect(()=>{const h=$=>{$.key==="Escape"&&n&&c()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[n,c]),l.useEffect(()=>{if(n&&W.current){if(typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches)return;const $=setTimeout(()=>{var U;(U=W.current)==null||U.focus()},50);return()=>clearTimeout($)}},[n]),!n)return null;const q=h=>{a(u===h?null:h)},R=h=>{A.selectArea(v===h?null:h),a("select")},K=(h,$)=>{h.stopPropagation(),A.deleteArea($)};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"toolbox-backdrop",onClick:c}),e.jsxs("aside",{className:"toolbox",children:[e.jsxs("div",{className:"toolbox-header",children:[e.jsx("span",{children:g("config:title")}),e.jsx("button",{className:"toolbox-close-btn",onClick:c,title:g("common:buttons.close"),children:"×"})]}),e.jsxs("div",{className:"toolbox-search",children:[e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("circle",{cx:"11",cy:"11",r:"8"}),e.jsx("path",{d:"M21 21l-4.35-4.35"})]}),e.jsx("input",{ref:W,type:"text",placeholder:g("config:searchPlaceholder"),value:F,onChange:h=>V(h.target.value),className:"toolbox-search-input"}),F&&e.jsx("button",{className:"toolbox-search-clear",onClick:()=>V(""),children:"×"})]}),e.jsxs("div",{className:"toolbox-content",children:[e.jsx("div",{className:"toolbox-section toolbox-section-collapsible",children:e.jsxs(G,{title:g("config:areas.title",{count:k.length}),storageKey:"areas",children:[e.jsxs("div",{className:"tool-buttons",children:[e.jsx("button",{className:`tool-btn ${u==="select"?"active":""}`,onClick:()=>q("select"),title:g("config:tools.select"),children:e.jsx("span",{children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M3 3l7.07 16.97 2.51-7.39 7.39-2.51L3 3z"})})})}),e.jsx("button",{className:`tool-btn ${u==="rectangle"?"active":""}`,onClick:()=>q("rectangle"),title:g("config:tools.rectangle"),children:e.jsx("span",{children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"})})})}),e.jsx("button",{className:`tool-btn ${u==="circle"?"active":""}`,onClick:()=>q("circle"),title:g("config:tools.circle"),children:e.jsx("span",{children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("circle",{cx:"12",cy:"12",r:"9"})})})})]}),e.jsx("div",{className:"areas-list",children:k.length===0?e.jsx("div",{className:"areas-empty",children:g("config:areas.drawToCreate")}):k.map(h=>e.jsx(ot,{area:h,isSelected:v===h.id,onClick:()=>R(h.id),onDelete:$=>K($,h.id)},h.id))})]})}),v&&e.jsx(dt,{area:E.get(v),onClose:()=>A.selectArea(null),onOpenFolder:d}),e.jsx("div",{className:"toolbox-section toolbox-section-collapsible",children:e.jsx(G,{title:g("config:buildings.title",{count:D.length}),storageKey:"buildings",headerExtra:e.jsx("button",{className:"add-building-btn",onClick:h=>{h.stopPropagation(),r==null||r()},title:g("config:buildings.addBuilding"),children:"+"}),children:e.jsx("div",{className:"buildings-list",children:D.length===0?e.jsx("div",{className:"buildings-empty",children:g("config:buildings.clickToAdd")}):D.map(h=>e.jsx(lt,{building:h,isSelected:S.has(h.id),onClick:()=>{A.selectBuilding(S.has(h.id)?null:h.id)},onEdit:()=>r==null?void 0:r(h.id)},h.id))})})}),S.size===1&&(()=>{const h=Array.from(S)[0],$=y.get(h);return $?e.jsx(ct,{building:$,onClose:()=>A.selectBuilding(null),onOpenModal:()=>r==null?void 0:r(h)}):null})(),e.jsx(Sa,{config:t,onChange:s,searchQuery:F,onOpenIntegrationsModal:f,onOpenMonitoringModal:i,onOpenStatisticsModal:m,onOpenWorkflowEditor:w,onOpenTriggerManager:j})]})]})]})}export{Pa as Toolbox};
|