tide-commander 1.150.6 → 1.151.1

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.
Files changed (56) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/assets/{BossLogsModal-D-tjw9Ac.js → BossLogsModal-BRXVs2zX.js} +1 -1
  3. package/dist/assets/{BossSpawnModal-DjXpREdF.js → BossSpawnModal-BqM8EeOS.js} +1 -1
  4. package/dist/assets/{ControlsModal-B0RCXoei.js → ControlsModal-Do6sfsyz.js} +1 -1
  5. package/dist/assets/{DockerLogsModal-mumJuNPo.js → DockerLogsModal-Clb8M2rL.js} +1 -1
  6. package/dist/assets/{EmbeddedEditor-DfoY9sRz.js → EmbeddedEditor-DMFNGABf.js} +1 -1
  7. package/dist/assets/{GmailOAuthSetup-BpyUQtYp.js → GmailOAuthSetup-D4-bi1Rt.js} +1 -1
  8. package/dist/assets/{GoogleOAuthSetup-C9QQjGf2.js → GoogleOAuthSetup-D2Wyhnw0.js} +1 -1
  9. package/dist/assets/{IframeModal-BWLfI74y.js → IframeModal-Zun7245W.js} +1 -1
  10. package/dist/assets/{IntegrationsPanel-0uKXKkLf.js → IntegrationsPanel-U8SIOpPt.js} +2 -2
  11. package/dist/assets/{LogViewerModal-B7Gi86T6.js → LogViewerModal-BnFRX2hq.js} +1 -1
  12. package/dist/assets/{MonitoringModal-xji_Xv-B.js → MonitoringModal-CObUxMPl.js} +1 -1
  13. package/dist/assets/{PM2LogsModal-H8nPhO-m.js → PM2LogsModal-DLf14YCU.js} +1 -1
  14. package/dist/assets/{RestoreArchivedAreaModal-Ozqt_h97.js → RestoreArchivedAreaModal-Chg4LCCi.js} +1 -1
  15. package/dist/assets/{Scene2DCanvas-s79Q3zJP.js → Scene2DCanvas-CI_QSx9i.js} +1 -1
  16. package/dist/assets/{SceneManager-BZdHLI98.js → SceneManager-SS5ahbEe.js} +1 -1
  17. package/dist/assets/{SkillsPanel-BXJS-7XJ.js → SkillsPanel-DgPHgt3c.js} +1 -1
  18. package/dist/assets/{SlackMultiInstanceSetup-DaQBxH5G.js → SlackMultiInstanceSetup-iIjyM2kW.js} +1 -1
  19. package/dist/assets/{SpawnModal-CFTdUpq9.js → SpawnModal-BDgxHGYh.js} +1 -1
  20. package/dist/assets/{StatisticsModal-BoSeR-R6.js → StatisticsModal-BuYkJsul.js} +1 -1
  21. package/dist/assets/{SubordinateAssignmentModal-C5t06fd5.js → SubordinateAssignmentModal-D71lnDXZ.js} +1 -1
  22. package/dist/assets/{TriggerManagerPanel-CBOgu5O-.js → TriggerManagerPanel-DKiXSpSu.js} +1 -1
  23. package/dist/assets/{WorkflowEditorPanel-BaGkass4.js → WorkflowEditorPanel-Dz6fJy8X.js} +1 -1
  24. package/dist/assets/{area-logos-B6OVpGpC.js → area-logos-UIiMtczR.js} +1 -1
  25. package/dist/assets/{index-COpZfWU7.js → index-4BenQ81a.js} +5 -5
  26. package/dist/assets/{index-BSc9Q00B.js → index-BAvhLzXF.js} +3 -3
  27. package/dist/assets/{index-DAFiQxXk.js → index-BXnQVuar.js} +1 -1
  28. package/dist/assets/{index-eTW--ftk.js → index-BZKCuVK4.js} +2 -2
  29. package/dist/assets/index-CLA5nZlA.css +1 -0
  30. package/dist/assets/{index-DC-CNVYP.js → index-Ci67fScw.js} +1 -1
  31. package/dist/assets/index-DgxY9KIr.js +2 -0
  32. package/dist/assets/{index-D-TSUXRk.js → index-DrUrcPns.js} +1 -1
  33. package/dist/assets/index-DvSK7N4C.js +1 -0
  34. package/dist/assets/{index-CKXhw5I3.js → index-OQ-kWRyS.js} +1 -1
  35. package/dist/assets/main-CEq_Fs_S.js +289 -0
  36. package/dist/assets/main-CX7XkoZ4.css +1 -0
  37. package/dist/assets/{web-CT5Q3JAF.js → web-BSnmr2eo.js} +1 -1
  38. package/dist/assets/{web-Hha4yEWN.js → web-DSHhrW0P.js} +1 -1
  39. package/dist/assets/{web-DxtBxLo3.js → web-jsCXVjsN.js} +1 -1
  40. package/dist/index.html +2 -2
  41. package/dist/locales/en/config.json +14 -0
  42. package/dist/locales/en/terminal.json +3 -1
  43. package/dist/src/packages/server/data/builtin-skills/release-pipeline.js +18 -16
  44. package/dist/src/packages/server/grok/backend.js +3 -2
  45. package/dist/src/packages/server/routes/system.js +66 -0
  46. package/dist/src/packages/server/services/runtime-command-execution.js +53 -34
  47. package/dist/src/packages/server/services/runtime-service.js +4 -4
  48. package/dist/src/packages/server/websocket/handlers/command-handler.js +9 -8
  49. package/dist/src/packages/server/websocket/listeners/runtime-listeners.js +2 -2
  50. package/dist/src/packages/shared/agent-types.js +22 -0
  51. package/package.json +1 -1
  52. package/dist/assets/index-BhOEfqZJ.js +0 -1
  53. package/dist/assets/index-BtQSoC86.js +0 -2
  54. package/dist/assets/index-CHvsg8e5.css +0 -1
  55. package/dist/assets/main-BsgKYLZr.css +0 -1
  56. package/dist/assets/main-KW9NTHdK.js +0 -289
@@ -1 +0,0 @@
1
- import{r as l,bl as Ue,bm as Ye,j as e,I as P,u as Z,bn as as,ag as ns,bo as hs,bp as ms,s as T,bq as gs,bd as fs,br as xs,C as he,K as se,L as X,i as ye,k as ke,bs,bt as js,bu as vs,bv as Ns,bw as ws,bx as ys,by as ks,bz as Ss,X as Cs,bA as Se,a9 as As,bB as is,bC as Ts,bD as Ve,bE as _s,bF as Es,bG as Is,bH as Ps,bI as Ls,bJ as $s,bK as Ds,as as Fs,b6 as Os,_ as Rs,S as we,bL as Us,bM as zs,b8 as Ms,bN as ze,$ as Ie,bi as Bs,bO as Me,bP as Vs,a5 as Ks,m as Hs,bQ as qs,bR as Ws,bS as Gs}from"./main-KW9NTHdK.js";import{g as Ys,d as Js,u as Zs}from"./area-logos-B6OVpGpC.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const Ke="deivid11/tide-commander",Xs=`https://api.github.com/repos/${Ke}/releases/latest`,Qs=`https://api.github.com/repos/${Ke}/releases?per_page=3`,et=3600*1e3,Je="app_update_dismissed_version",Ze="1.150.6";function st(){var y,S;const[s,a]=l.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Ze}),t=((S=(y=Ue)==null?void 0:y.getPlatform)==null?void 0:S.call(y))==="android"||!1,o=u=>u.replace(/^v/,"").split(".").map(j=>parseInt(j,10)||0),d=(u,v)=>{const j=o(u),m=o(v),f=Math.max(j.length,m.length);for(let p=0;p<f;p++){const C=j[p]||0,z=m[p]||0;if(C>z)return 1;if(C<z)return-1}return 0},r=async u=>{var j,m;if(Ue&&Ye&&((m=(j=Ue).isNativePlatform)==null?void 0:m.call(j))===!0){const f=await Ye.get({url:u,headers:{Accept:"application/vnd.github.v3+json"}});return{data:f.data,status:f.status}}else{const f=await fetch(u,{headers:{Accept:"application/vnd.github.v3+json"}});return f.ok?{data:await f.json(),status:f.status}:{data:null,status:f.status}}},c=l.useCallback(async(u=!1)=>{a(v=>({...v,isChecking:!0,error:null}));try{const[v,j]=await Promise.all([r(Xs),r(Qs)]);if(v.status!==200)throw new Error(`GitHub API error: ${v.status}`);const m=v.data,f=m.tag_name;let p=[];j.status===200&&j.data&&(p=j.data.map(F=>({version:F.tag_name,name:F.name,publishedAt:F.published_at,releaseUrl:F.html_url})));const C=localStorage.getItem(Je);if(!u&&C===f)return a(F=>({...F,isChecking:!1,updateAvailable:!1,recentReleases:p})),null;if(!(d(f,Ze)>0))return a(F=>({...F,isChecking:!1,updateAvailable:!1,recentReleases:p})),null;const O=m.assets.find(F=>F.name.endsWith(".apk")&&F.content_type==="application/vnd.android.package-archive"),K={version:f,name:m.name,changelog:m.body,releaseUrl:m.html_url,apkUrl:(O==null?void 0:O.browser_download_url)||null,apkSize:(O==null?void 0:O.size)||null,publishedAt:m.published_at};return a(F=>({...F,isChecking:!1,updateAvailable:!0,updateInfo:K,recentReleases:p})),K}catch(v){const j=v instanceof Error?v.message:"Failed to check for updates";return a(m=>({...m,isChecking:!1,error:j})),null}},[]),x=l.useCallback(async()=>{var u,v,j;if(!((u=s.updateInfo)!=null&&u.apkUrl)){(v=s.updateInfo)!=null&&v.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}if(!t){(j=s.updateInfo)!=null&&j.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}try{window.open(s.updateInfo.apkUrl,"_system"),a(m=>({...m,error:null}))}catch(m){const f=m instanceof Error?m.message:"Failed to open download";a(p=>({...p,error:f}))}},[s.updateInfo,t]),n=l.useCallback(()=>{s.updateInfo&&localStorage.setItem(Je,s.updateInfo.version),a(u=>({...u,updateAvailable:!1,updateInfo:null}))},[s.updateInfo]),b=l.useCallback(()=>{var u;(u=s.updateInfo)!=null&&u.releaseUrl?window.open(s.updateInfo.releaseUrl,"_blank"):window.open(`https://github.com/${Ke}/releases`,"_blank")},[s.updateInfo]);return l.useEffect(()=>{if(!t)return;const u=setTimeout(()=>{c()},5e3),v=setInterval(()=>{c()},et);return()=>{clearTimeout(u),clearInterval(v)}},[t,c]),{...s,isAndroid:t,checkForUpdate:c,downloadAndInstall:x,dismissUpdate:n,openReleasePage:b}}const os="tide-toolbox-collapse";function tt(s,a){try{const t=localStorage.getItem(`${os}-${s}`);if(t!==null)return t==="true"}catch{}return a}function at(s,a){try{localStorage.setItem(`${os}-${s}`,String(a))}catch{}}function G({title:s,storageKey:a,defaultOpen:t=!1,forceOpen:o=!1,children:d,headerExtra:r}){const[c,x]=l.useState(()=>a?tt(a,t):t),n=()=>{const y=!c;x(y),a&&at(a,y)},b=o||c;return e.jsxs("div",{className:`collapsible-section ${b?"open":"collapsed"}`,children:[e.jsxs("button",{className:"collapsible-header",onClick:n,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(P,{name:b?"caret-down":"caret-right",size:10})})]})]}),b&&e.jsx("div",{className:"collapsible-content",children:d})]})}function nt({area:s,isSelected:a,onClick:t,onDelete:o}){const{t:d}=Z(["config","common"]),r=s.assignedAgentIds.length,c=s.type==="rectangle"?d("config:areas.rect"):d("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:[c," ",r>0&&`• ${r} ${r>1?d("common:labels.agents").toLowerCase():d("common:labels.agent").toLowerCase()}`]})]}),e.jsx("button",{className:"area-delete-btn",onClick:o,title:d("config:areas.deleteArea"),children:"×"})]})}function it({building:s,isSelected:a,onClick:t,onEdit:o}){var x;const{t:d}=Z(["config"]),r=((x=s.pm2Status)==null?void 0:x.ports)||[],c=(n,b)=>{n.stopPropagation(),window.open(`http://${window.location.hostname}:${b}`,"_blank")};return e.jsxs("div",{className:`building-item ${a?"selected":""}`,onClick:t,children:[e.jsx("div",{className:"building-status-dot",style:{backgroundColor:as[s.status]},title:s.status}),e.jsx("div",{className:"building-icon",children:e.jsx(P,{name:ns(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(n=>e.jsxs("a",{href:`http://${window.location.hostname}:${n}`,className:"building-port-link",onClick:b=>c(b,n),title:`Open :${n}`,children:[":",n]},n))})]})]}),e.jsx("button",{className:"building-edit-btn",onClick:n=>{n.stopPropagation(),o()},title:d("config:buildings.editBuilding"),children:e.jsx(P,{name:"gear",size:14})})]})}function ot({building:s,onClose:a,onOpenModal:t}){var b,y,S,u,v,j,m,f;const{t:o}=Z(["config","common"]),r=hs().get(s.id)||[],c=ms[s.style||"server-rack"],x=p=>{T.sendBuildingCommand(s.id,p)},n=p=>{window.open(p,"_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(P,{name:ns(s.type),size:18})}),e.jsx("span",{className:"building-editor-title",children:s.name}),e.jsx("span",{className:"building-editor-status",style:{backgroundColor:as[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:o("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:o("config:buildings.style")}),e.jsx("span",{className:"building-editor-info-value",children:c.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:o("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:o("config:buildings.actions")}),e.jsxs("div",{className:"building-editor-actions",children:[e.jsxs("button",{className:"building-editor-action-btn start",onClick:()=>x("start"),disabled:!((b=s.commands)!=null&&b.start)||s.status==="running",title:((y=s.commands)==null?void 0:y.start)||o("config:buildings.noStartCommand"),children:[e.jsx(P,{name:"play",size:12})," ",o("common:buttons.start")]}),e.jsxs("button",{className:"building-editor-action-btn stop",onClick:()=>x("stop"),disabled:!((S=s.commands)!=null&&S.stop)||s.status==="stopped",title:((u=s.commands)==null?void 0:u.stop)||o("config:buildings.noStopCommand"),children:[e.jsx(P,{name:"stop",size:12,weight:"fill"})," ",o("common:buttons.stop")]}),e.jsxs("button",{className:"building-editor-action-btn restart",onClick:()=>x("restart"),disabled:!((v=s.commands)!=null&&v.restart),title:((j=s.commands)==null?void 0:j.restart)||o("config:buildings.noRestartCommand"),children:[e.jsx(P,{name:"refresh",size:12})," ",o("common:buttons.retry")]}),e.jsxs("button",{className:"building-editor-action-btn health",onClick:()=>x("healthCheck"),disabled:!((m=s.commands)!=null&&m.healthCheck),title:((f=s.commands)==null?void 0:f.healthCheck)||o("config:buildings.noHealthCheck"),children:[e.jsx(P,{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:o("config:buildings.links")}),e.jsx("div",{className:"building-editor-links",children:s.urls.map((p,C)=>e.jsxs("button",{className:"building-editor-link",onClick:()=>n(p.url),title:p.url,children:[e.jsx(P,{name:"link",size:12})," ",p.label||p.url]},C))})]}),r.length>0&&e.jsxs("div",{className:"building-editor-section",children:[e.jsxs("div",{className:"building-editor-section-title",children:[o("config:buildings.recentLogs"),e.jsx("button",{className:"building-editor-clear-logs",onClick:()=>T.clearBuildingLogs(s.id),title:o("common:buttons.clear"),children:o("common:buttons.clear")})]}),e.jsx("div",{className:"building-editor-logs",children:r.slice(-5).map((p,C)=>e.jsx("div",{className:"building-editor-log-entry",children:p},C))})]}),e.jsx("div",{className:"building-editor-footer",children:e.jsxs("button",{className:"building-editor-edit-btn",onClick:t,children:[e.jsx(P,{name:"gear",size:12})," ",o("config:buildings.fullSettings")]})})]})}const lt=[{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 ct({area:s,onClose:a,onOpenFolder:t}){var te;const{t:o}=Z(["config","common"]),[d,r]=l.useState(s.name),[c,x]=l.useState(s.prompt||""),[n,b]=l.useState(!1),[y,S]=l.useState(""),[u,v]=l.useState(!1),j=l.useRef(null);l.useEffect(()=>{r(s.name)},[s.id,s.name]),l.useEffect(()=>{x(s.prompt||"")},[s.id,s.prompt]);const m=w=>{const $=w.target.value;r($),T.updateArea(s.id,{name:$})},f=w=>{T.updateArea(s.id,{color:w})},p=w=>{const $=w.target.value;x($),T.updateArea(s.id,{prompt:$})},C=()=>{y.trim()&&(T.addDirectoryToArea(s.id,y.trim()),S(""),b(!1))},z=(w,$)=>{$.stopPropagation(),T.removeDirectoryFromArea(s.id,w)},O=()=>{T.bringAreaToFront(s.id)},K=()=>{T.sendAreaToBack(s.id)},F=l.useCallback(()=>{let w=2,$=2;s.type==="rectangle"&&s.width&&s.height?(w=s.width,$=s.height):s.type==="circle"&&s.radius&&(w=s.radius*1.414,$=s.radius*1.414);const V=Math.min(w,$)*.4;return{width:Math.round(V*10)/10,height:Math.round(V*10)/10}},[s.type,s.width,s.height,s.radius]),q=async w=>{var V;const $=(V=w.target.files)==null?void 0:V[0];if($){v(!0);try{const N=await Zs(s.id,$),L=F();T.updateArea(s.id,{logo:{filename:N.filename,position:"center",width:L.width,height:L.height,keepAspectRatio:!0,opacity:.8}})}catch(N){console.error("Failed to upload logo:",N)}finally{v(!1),j.current&&(j.current.value="")}}},M=async()=>{try{await Js(s.id),T.updateArea(s.id,{logo:void 0})}catch(w){console.error("Failed to remove logo:",w)}},H=w=>{s.logo&&T.updateArea(s.id,{logo:{...s.logo,position:w}})},h=w=>{if(!s.logo)return;const $=parseFloat(w.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.width>0){const V=s.logo.height/s.logo.width;T.updateArea(s.id,{logo:{...s.logo,width:$,height:Math.round($*V*10)/10}})}else T.updateArea(s.id,{logo:{...s.logo,width:$}})},E=w=>{if(!s.logo)return;const $=parseFloat(w.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.height>0){const V=s.logo.width/s.logo.height;T.updateArea(s.id,{logo:{...s.logo,height:$,width:Math.round($*V*10)/10}})}else T.updateArea(s.id,{logo:{...s.logo,height:$}})},B=()=>{s.logo&&T.updateArea(s.id,{logo:{...s.logo,keepAspectRatio:!s.logo.keepAspectRatio}})},W=w=>{s.logo&&T.updateArea(s.id,{logo:{...s.logo,opacity:parseFloat(w.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:o("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:o("common:labels.name")}),e.jsx("input",{type:"text",className:"area-editor-input",value:d,onChange:m,placeholder:o("config:areas.areaName")})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.color")}),e.jsx("div",{className:"color-picker-row",children:gs.map(w=>e.jsx("button",{type:"button",className:`color-swatch ${s.color===w?"selected":""}`,style:{backgroundColor:w},onClick:()=>f(w),"aria-label":`Set area color ${w}`,"aria-pressed":s.color===w,title:w},w))})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.layer")}),e.jsxs("div",{className:"area-layer-buttons",children:[e.jsxs("button",{className:"area-layer-btn",onClick:O,title:o("config:areas.bringToFront"),children:[e.jsx(P,{name:"arrow-up",size:12})," ",o("config:areas.front")]}),e.jsxs("button",{className:"area-layer-btn",onClick:K,title:o("config:areas.sendToBack"),children:[e.jsx(P,{name:"arrow-down",size:12})," ",o("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:o("config:areas.logo")}),e.jsxs("div",{className:"area-logo-section",children:[(te=s.logo)!=null&&te.filename?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"area-logo-preview",children:[e.jsx("img",{src:Ys(s.logo.filename),alt:"Logo",className:"area-logo-thumbnail"}),e.jsx("button",{className:"area-logo-remove-btn",onClick:M,children:o("config:areas.removeLogo")}),e.jsx("button",{className:"area-logo-replace-btn",onClick:()=>{var w;return(w=j.current)==null?void 0:w.click()},disabled:u,children:u?"...":e.jsx(P,{name:"refresh",size:12})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoPosition")}),e.jsx("div",{className:"area-logo-position-row",children:lt.map(({key:w,labelKey:$})=>{var V;return e.jsx("button",{className:`area-logo-pos-btn ${((V=s.logo)==null?void 0:V.position)===w?"active":""}`,onClick:()=>H(w),children:o(`config:areas.${$}`)},w)})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("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:o("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:o("config:areas.logoHeight")}),e.jsx("input",{type:"number",className:"area-logo-size-input",value:s.logo.height,onChange:E,min:.1,step:.1})]}),e.jsxs("label",{className:"area-logo-aspect-label",title:o("config:areas.keepAspectRatio"),children:[e.jsx("input",{type:"checkbox",checked:s.logo.keepAspectRatio,onChange:B}),o("config:areas.keepAspectRatio")]})]})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("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:W,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 w;return(w=j.current)==null?void 0:w.click()},disabled:u,children:u?"...":o("config:areas.uploadLogo")}),e.jsx("input",{ref:j,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:o("config:areas.folders",{count:s.directories.length})}),e.jsxs("div",{className:"area-folders-list",children:[s.directories.map(w=>e.jsxs("div",{className:"area-folder-item",title:w,children:[e.jsx("span",{className:"area-folder-icon clickable",onClick:()=>t==null?void 0:t(s.id),title:o("config:areas.openFolder"),children:e.jsx(P,{name:"folder",size:14})}),e.jsx("span",{className:"area-folder-path",children:w.split("/").pop()||w}),e.jsx("button",{className:"area-folder-remove",onClick:$=>z(w,$),title:o("config:areas.removeFolder"),children:"×"})]},w)),n?e.jsxs("div",{className:"area-add-folder-inline",children:[e.jsx(fs,{value:y,onChange:S,onSubmit:C,placeholder:o("config:areas.folderPlaceholder"),className:"area-add-folder-input",directoriesOnly:!0,autoFocus:!0}),e.jsx("button",{className:"area-add-folder-confirm",onClick:C,children:"+"})]}):e.jsx("button",{className:"area-add-folder-btn",onClick:()=>b(!0),children:o("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:o("config:areas.prompt","Prompt")}),e.jsx("textarea",{className:"area-editor-input",value:c,onChange:p,placeholder:o("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:o("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:o("config:areas.assignedAgents",{count:s.assignedAgentIds.length})}),e.jsx("div",{style:{fontSize:12,color:"var(--text-secondary)"},children:o("config:areas.rightClickUnassign")})]})]})}function rt(){const{t:s}=Z(["config","common"]),a=xs(),[t,o]=l.useState(!1),[d,r]=l.useState(null),[c,x]=l.useState({name:"",key:"",value:"",description:""}),[n,b]=l.useState(null),y=()=>{o(!0),r(null),x({name:"",key:"",value:"",description:""})},S=p=>{r(p.id),o(!1),x({name:p.name,key:p.key,value:p.value,description:p.description||""})},u=()=>{o(!1),r(null),x({name:"",key:"",value:"",description:""})},v=()=>{!c.name.trim()||!c.key.trim()||(d?T.updateSecret(d,{name:c.name.trim(),key:c.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:c.value,description:c.description.trim()||void 0}):T.createSecret({name:c.name.trim(),key:c.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:c.value,description:c.description.trim()||void 0}),u())},j=p=>{b(p)},m=()=>{n&&(T.deleteSecret(n),d===n&&u())},f=p=>{navigator.clipboard.writeText(`{{${p}}}`)};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(p=>e.jsxs("div",{className:`secret-item ${d===p.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:p.name}),e.jsx("code",{className:"secret-item-key",onClick:()=>f(p.key),title:s("config:secrets.copyPlaceholder"),children:`{{${p.key}}}`})]}),e.jsxs("div",{className:"secret-item-actions",children:[e.jsx("button",{className:"secret-item-btn edit",onClick:()=>S(p),title:s("common:buttons.edit"),children:e.jsx(P,{name:"edit",size:12})}),e.jsx("button",{className:"secret-item-btn delete",onClick:()=>j(p.id),title:s("common:buttons.delete"),children:"×"})]})]}),p.description&&e.jsx("div",{className:"secret-item-description",children:p.description})]},p.id))}),(t||d)&&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:c.name,onChange:p=>x({...c,name:p.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:c.key,onChange:p=>x({...c,key:p.target.value.toUpperCase().replace(/[^A-Z0-9_]/g,"")})}),e.jsx("span",{className:"secret-form-hint",children:s("config:secrets.usedAs",{placeholder:`{{${c.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:c.value,onChange:p=>x({...c,value:p.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:c.description,onChange:p=>x({...c,description:p.target.value})})]}),e.jsxs("div",{className:"secret-form-actions",children:[e.jsx("button",{className:"secret-form-btn cancel",onClick:u,children:s("common:buttons.cancel")}),e.jsx("button",{className:"secret-form-btn save",onClick:v,disabled:!c.name.trim()||!c.key.trim(),children:s(d?"config:secrets.update":"common:buttons.add")})]})]}),!t&&!d&&e.jsx("button",{className:"secrets-add-btn",onClick:y,children:s("config:secrets.addSecret")}),e.jsx(he,{isOpen:n!==null,title:s("common:buttons.delete"),message:s("config:secrets.deleteConfirm"),confirmLabel:s("common:buttons.delete"),cancelLabel:s("common:buttons.cancel"),variant:"danger",onConfirm:m,onClose:()=>b(null)})]})}async function dt(){const s=se(),a=await fetch(`${X()}/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 ut(s){const a=se(),t=await fetch(`${X()}/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 pt(){const s=se(),a=await fetch(`${X()}/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 ht(){const s=se(),a=await fetch(`${X()}/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 mt(s){const a=se(),t=await fetch(`${X()}/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 gt(){const s=se(),a=await fetch(`${X()}/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 ft(s){const a=se(),t=await fetch(`${X()}/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 xt(){const s=se(),a=await fetch(`${X()}/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 bt(s){const a=se(),t=await fetch(`${X()}/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 jt(){const s=se(),a=await fetch(`${X()}/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 vt(s){const a=se(),t=await fetch(`${X()}/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=se(),a=await fetch(`${X()}/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 wt(s){const a=se(),t=await fetch(`${X()}/api/agents/system-settings/backup`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok){const o=await t.json().catch(()=>({}));throw new Error(o.error||`Failed to update backup setting: ${t.statusText}`)}return t.json()}function yt({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:o=>a(o.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})}function kt(){const{t:s}=Z(["config","common"]),[a,t]=l.useState([]),[o,d]=l.useState(new Set),[r,c]=l.useState(new Set),[x,n]=l.useState(!1),[b,y]=l.useState(!1),[S,u]=l.useState(null),[v,j]=l.useState(null),[m,f]=l.useState(null),[p,C]=l.useState(null),[z,O]=l.useState(!1),[K,F]=l.useState(null);l.useEffect(()=>{ye(ke("/api/config/categories")).then(N=>N.json()).then(N=>{const L=Array.isArray(N)?N:[];t(L),d(new Set(L.map(D=>D.id)))}).catch(N=>console.error("Failed to fetch config categories:",N))},[]),l.useEffect(()=>{Nt().then(C).catch(N=>{console.error("Failed to fetch backup status:",N),F(N.message||"Failed to fetch backup status")})},[]);const q=async N=>{if(!z){O(!0),F(null);try{const L=await wt(N);C(L)}catch(L){F(L.message||"Failed to update backup setting")}finally{O(!1)}}},M=N=>{d(L=>{const D=new Set(L);return D.has(N)?D.delete(N):D.add(N),D})},H=N=>{c(L=>{const D=new Set(L);return D.has(N)?D.delete(N):D.add(N),D})},h=()=>d(new Set(a.map(N=>N.id))),E=()=>d(new Set),B=()=>{v&&c(new Set(v.categories.map(N=>N.id)))},W=()=>c(new Set),te=async()=>{var N;if(o.size!==0){n(!0),f(null);try{const L=Array.from(o).join(","),D=await ye(ke(`/api/config/export?categories=${L}`));if(!D.ok)throw new Error("Export failed");const Q=await D.blob(),ee=window.URL.createObjectURL(Q),A=document.createElement("a");A.href=ee;const k=D.headers.get("Content-Disposition"),Y=((N=k==null?void 0:k.match(/filename="(.+)"/))==null?void 0:N[1])||"tide-commander-config.zip";A.download=Y,document.body.appendChild(A),A.click(),document.body.removeChild(A),window.URL.revokeObjectURL(ee),f({type:"success",text:s("config:data.exportSuccess")})}catch(L){f({type:"error",text:L.message||"Export failed"})}finally{n(!1)}}},w=async N=>{var D;const L=(D=N.target.files)==null?void 0:D[0];if(L){u(L),f(null),j(null),c(new Set);try{const Q=await ye(ke("/api/config/preview"),{method:"POST",headers:{"Content-Type":"application/zip"},body:await L.arrayBuffer()});if(!Q.ok){const k=await Q.json();throw new Error(k.error||"Failed to preview config file")}const ee=await Q.json(),A=Array.isArray(ee.categories)?ee.categories:[];j({...ee,categories:A}),c(new Set(A.map(k=>k.id)))}catch(Q){f({type:"error",text:Q.message||"Failed to read config file"}),u(null)}}},$=async()=>{if(!(!S||r.size===0)){y(!0),f(null);try{const N=Array.from(r).join(","),L=await ye(ke(`/api/config/import?categories=${N}`),{method:"POST",headers:{"Content-Type":"application/zip"},body:await S.arrayBuffer()}),D=await L.json();if(!L.ok)throw new Error(D.error||"Import failed");f({type:"success",text:D.message||s("config:data.importSuccess")}),u(null),j(null),c(new Set)}catch(N){f({type:"error",text:N.message||"Import failed"})}finally{y(!1)}}},V=()=>{u(null),j(null),c(new Set),f(null)};return e.jsxs("div",{className:"data-section",children:[m&&e.jsx("div",{className:`data-message data-message-${m.type}`,children:m.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(yt,{checked:!!(p!=null&&p.enabled),disabled:z||!p,onChange:q})]}),e.jsxs("div",{className:"data-backup-info",children:[p?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:["Saves a compressed snapshot of your data every hour to"," ",e.jsx("code",{children:p.backupDir}),". Identical snapshots are skipped. Keeps the 8 newest plus one from each of the 2 most recent prior days."]}),!p.scriptExists&&e.jsxs("div",{style:{marginTop:6,color:"var(--dracula-red, #ff5555)"},children:["Backup script not found at ",e.jsx("code",{children:p.scriptPath})]}),p.lastRunAt&&e.jsxs("div",{style:{marginTop:6},children:["Last run: ",new Date(p.lastRunAt).toLocaleString(),p.lastRunOk===!0&&" — ok",p.lastRunOk===!1&&p.lastRunError&&e.jsxs("span",{style:{color:"var(--dracula-red, #ff5555)"},children:[" — ",p.lastRunError]})]})]}):e.jsx("div",{children:"Loading backup status…"}),K&&e.jsx("div",{className:"data-message data-message-error",style:{marginTop:6},children:K})]})]}),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:E,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:a.map(N=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:o.has(N.id),onChange:()=>M(N.id)}),e.jsx("span",{className:"data-category-name",children:N.name})]},N.id))}),e.jsx("button",{className:"data-action-btn export",onClick:te,disabled:x||o.size===0,children:x?s("config:data.exporting"):s("config:data.exportCount",{count:o.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")})}),S?v?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"data-import-info",children:[e.jsx("div",{className:"data-import-file",children:S.name}),e.jsxs("div",{className:"data-import-date",children:[s("config:data.exported"),": ",new Date(v.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:B,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:W,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:v.categories.map(N=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:r.has(N.id),onChange:()=>H(N.id)}),e.jsx("span",{className:"data-category-name",children:N.name}),N.fileCount&&e.jsxs("span",{className:"data-category-count",children:["(",N.fileCount," ",s("config:data.files"),")"]})]},N.id))}),e.jsxs("div",{className:"data-import-actions",children:[e.jsx("button",{className:"data-action-btn cancel",onClick:V,children:s("common:buttons.cancel")}),e.jsx("button",{className:"data-action-btn import",onClick:$,disabled:b||r.size===0,children:b?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:w,style:{display:"none"}}),e.jsx("span",{className:"data-file-input-label",children:s("config:data.selectFile")})]})]})]})}function St(){const[s,a]=l.useState(()=>bs()),t=o=>{a(o);const d=Ns(o);ws(d)};return e.jsx("div",{className:"theme-selector",children:e.jsx("div",{className:"theme-selector-grid",children:js.map(o=>e.jsxs("button",{className:`theme-option ${s===o.id?"active":""}`,onClick:()=>t(o.id),title:o.description,children:[e.jsx("div",{className:"theme-preview",children:e.jsxs("div",{className:"theme-preview-bg",style:{backgroundColor:o.colors.bgPrimary},children:[e.jsx("div",{className:"theme-preview-accent",style:{backgroundColor:o.colors.accentBlue}}),e.jsx("div",{className:"theme-preview-claude",style:{backgroundColor:o.colors.accentClaude}})]})}),e.jsx("span",{className:"theme-name",children:o.name})]},o.id))})})}function Ct(){const{t:s}=Z(["config"]),{installInfo:a,phase:t,output:o,error:d,newVersion:r,autoRestart:c,refreshInstallInfo:x,runUpdate:n,reset:b}=ys(),[y,S]=l.useState(!1),u=l.useRef(null);l.useEffect(()=>{x()},[x]),l.useEffect(()=>{u.current&&(u.current.scrollTop=u.current.scrollHeight)},[o]);const v=l.useCallback(()=>{S(!0)},[]),j=l.useCallback(()=>{S(!1)},[]),m=l.useCallback(()=>{S(!1),n()},[n]),f=l.useCallback(()=>{b(),S(!1),x()},[b,x]);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:s("config:about.autoUpdateTitle")}),t==="idle"&&!y&&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:v,children:s("config:about.autoUpdateButton")})]}),t==="idle"&&y&&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:j,children:s("config:about.autoUpdateCancel")}),e.jsx("button",{className:"about-update-btn download",onClick:m,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:u,className:"about-autoupdate-output",children:o||"..."}),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(c?"config:about.autoUpdateReconnectHint":"config:about.autoUpdateRestartHint")})]}),t==="failed"&&d&&e.jsx("div",{className:"about-update-error",children:d}),(t==="success"||t==="failed")&&e.jsx("div",{className:"about-autoupdate-stream-actions",children:e.jsx("button",{className:"about-update-btn changelog",onClick:f,children:s("config:about.autoUpdateClose")})})]})]}):e.jsxs("div",{className:"about-autoupdate",children:[e.jsx("div",{className:"about-autoupdate-title",children:s("config:about.autoUpdateTitle")}),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})]})]}):e.jsxs("div",{className:"about-autoupdate",children:[e.jsx("div",{className:"about-autoupdate-title",children:s("config:about.autoUpdateTitle")}),e.jsx("div",{className:"about-autoupdate-devnote",children:s("config:about.autoUpdateDevMode")})]}):null}function At(){const{t:s}=Z(["config"]),[a,t]=l.useState(null),[o,d]=l.useState(!1),[r,c]=l.useState(null);l.useEffect(()=>{ks().then(t).catch(n=>c(n.message))},[]);const x=l.useCallback(async n=>{if(!o){d(!0),c(null);try{t(await Ss(n))}catch(b){c(b.message)}finally{d(!1)}}},[o]);return!a&&!r?null:a?e.jsxs("div",{className:"about-autoupdate",children:[e.jsx("div",{className:"about-autoupdate-title",children:s("config:about.unattendedTitle")}),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:o||!a.supported,onChange:n=>void x(n.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})]}):e.jsxs("div",{className:"about-autoupdate",children:[e.jsx("div",{className:"about-autoupdate-title",children:s("config:about.unattendedTitle")}),e.jsx("div",{className:"about-update-error",children:r})]})}function Tt(){const{t:s}=Z(["config"]),{updateAvailable:a,updateInfo:t,recentReleases:o,isChecking:d,error:r,currentVersion:c,isAndroid:x,checkForUpdate:n,downloadAndInstall:b,openReleasePage:y}=st(),[S,u]=l.useState(!1),v=m=>m?`${(m/(1024*1024)).toFixed(1)} MB`:"",j=m=>new Date(m).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(P,{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:c}),a&&t?e.jsx("span",{className:"about-version-update-badge",onClick:y,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(Ct,{}),e.jsx(At,{}),e.jsx("div",{className:"about-changelog-row",children:e.jsx("button",{className:"about-update-btn changelog",onClick:()=>u(!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"),": ",v(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:y,children:s("config:about.changelog")}),x&&t.apkUrl?e.jsx("button",{className:"about-update-btn download",onClick:b,children:s("config:about.downloadAPK")}):e.jsx("button",{className:"about-update-btn download",onClick:y,children:s("config:about.viewRelease")})]})]}):e.jsxs("div",{className:"about-update-check",children:[e.jsx("span",{className:"about-update-status",children:s(d?"config:about.checkingUpdates":"config:about.upToDate")}),e.jsx("button",{className:"about-update-btn check",onClick:()=>n(!0),disabled:d,children:d?"...":s("config:about.check")})]}),o.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:o.map(m=>e.jsxs("a",{href:m.releaseUrl,target:"_blank",rel:"noopener noreferrer",className:`about-release-item ${m.version===`v${c}`||m.version===c?"current":""}`,children:[e.jsx("span",{className:"about-release-version",children:m.version}),e.jsx("span",{className:"about-release-date",children:j(m.publishedAt)})]},m.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(P,{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")})]})]}),S&&e.jsx(vs,{onClose:()=>u(!1)})]})}const _t={gmail:"✉️",slack:"💬",jira:"📋","google-calendar":"📅",docx:"📄",whatsapp:"📱"};function Et({onOpenModal:s}){const[a,t]=l.useState([]),[o,d]=l.useState(!0),r=l.useCallback(async()=>{try{const c=await ye(ke("/api/integrations"));if(!c.ok)return;const x=await c.json();t(x)}catch{}finally{d(!1)}},[]);return l.useEffect(()=>{r()},[r]),o?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(c=>{const x=_t[c.id]||"🔌",n=!!c.status.error,b=c.status.connected,y=n?"#f38ba8":b?"#a6e3a1":"#fab387",S=n?"Error":b?"Connected":"Setup Required",u=n?"✗":b?"✓":"⚠";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:x}),e.jsx("span",{style:{flex:1,minWidth:0,color:"var(--text-primary, #cdd6f4)",fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:c.name}),e.jsx("span",{style:{color:y,fontSize:10,fontWeight:500,whiteSpace:"nowrap"},title:S,children:u}),e.jsx("button",{onClick:()=>s(c.id),title:`Configure ${c.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:v=>{v.target.style.color="var(--text-primary, #cdd6f4)"},onMouseLeave:v=>{v.target.style.color="var(--text-secondary, #a6adc8)"},children:"⚙️"})]},c.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:c=>{c.target.style.borderColor="var(--accent, #89b4fa)",c.target.style.color="var(--accent, #89b4fa)"},onMouseLeave:c=>{c.target.style.borderColor="var(--border, #313244)",c.target.style.color="var(--text-secondary, #a6adc8)"},children:"Manage All Integrations"})]})}const Pe="__global__";function It({isOpen:s,onClose:a,initialAgentId:t}){const{t:o}=Z(["config"]),d=Cs(),[r,c]=l.useState(""),[x,n]=l.useState(""),[b,y]=l.useState(!1),[S,u]=l.useState(""),[v,j]=l.useState(""),[m,f]=l.useState(null),[p,C]=l.useState(null),[z,O]=l.useState(!1),[K,F]=l.useState(!1),[q,M]=l.useState(!1),[H,h]=l.useState(null),E=l.useMemo(()=>[...d].sort((A,k)=>A.name.localeCompare(k.name)),[d]),B=l.useMemo(()=>d.find(A=>A.id===r),[d,r]),W=r===Pe;l.useEffect(()=>{if(!s)return;const A=t&&d.some(k=>k.id===t)?t:Pe;c(A),y(!1),dt().then(k=>n(k)).catch(()=>n("")).finally(()=>y(!0))},[s]),l.useEffect(()=>{const A=r===Pe?x:(B==null?void 0:B.customPrompt)??"";u(A),j(A),O(!1),f(null),C(null)},[r,b]);const te=A=>{const k=A.target.value;u(k),O(k!==v),f(null),C(null)},w=async()=>{if(r)try{f(null),C(null),W?(await ut(S),n(S),C(o("config:systemPrompt.savedGlobal"))):(T.updateAgentProperties(r,{customPrompt:S}),C(o("config:systemPrompt.saved"))),j(S),O(!1)}catch(A){f(A instanceof Error?A.message:"Failed to save system prompt")}},$=()=>{F(!0)},V=async()=>{if(r)try{f(null),C(null),W?(await pt(),n(""),C(o("config:systemPrompt.clearedGlobal"))):(T.updateAgentProperties(r,{customPrompt:""}),C(o("config:systemPrompt.cleared"))),u(""),j(""),O(!1)}catch(A){f(A instanceof Error?A.message:"Failed to clear system prompt")}},N=()=>{u(v),O(!1),f(null),C(null)},L=A=>{if(A!==r){if(z){h(A),M(!0);return}c(A)}},D=()=>{if(z){h(null),M(!0);return}a()},Q=()=>{if(M(!1),H){const A=H;h(null),c(A)}else a()},ee=A=>{A.key==="Escape"&&(A.preventDefault(),D())};return s?e.jsxs(Se,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:D,children:e.jsxs("div",{className:"system-prompt-modal",onClick:A=>A.stopPropagation(),onKeyDown:ee,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:o("config:systemPrompt.title")}),e.jsx("button",{className:"modal-close",onClick:D,"aria-label":"Close",children:e.jsx(P,{name:"close",size:16})})]}),e.jsxs("div",{className:"modal-body",children:[e.jsx("p",{className:"modal-description",children:o("config:systemPrompt.description")}),e.jsxs("div",{className:"agent-picker",children:[e.jsx("label",{htmlFor:"system-prompt-agent",className:"editor-label",children:o("config:systemPrompt.agentLabel")}),e.jsxs("div",{className:"agent-picker-row",children:[W?e.jsx(P,{name:"globe",size:20,className:"agent-picker-icon"}):B&&e.jsx(As,{classId:B.class,size:20,className:"agent-picker-icon"}),e.jsxs("select",{id:"system-prompt-agent",className:"agent-picker-select",value:r,onChange:A=>L(A.target.value),children:[e.jsxs("option",{value:Pe,children:[o("config:systemPrompt.globalOption"),x?" • ✦":""]}),E.map(A=>e.jsxs("option",{value:A.id,children:[A.name,A.customPrompt?" • ✦":""]},A.id))]})]})]}),m&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(P,{name:"warn",size:14})}),m]}),p&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(P,{name:"check",size:14})}),p]}),e.jsxs("div",{className:"editor-wrapper",children:[e.jsxs("div",{className:"editor-header",children:[e.jsx("label",{htmlFor:"prompt-input",className:"editor-label",children:o("config:systemPrompt.editPrompt")}),e.jsxs("span",{className:"char-count",children:[S.length," ",o("config:systemPrompt.characters")]})]}),e.jsx("textarea",{id:"prompt-input",className:"prompt-editor",value:S,onChange:te,placeholder:o("config:systemPrompt.placeholder"),rows:18,disabled:W&&!b,autoFocus:!0}),e.jsx("div",{className:"editor-hint",children:o(W?"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:$,disabled:!S||!r,children:o("config:systemPrompt.clear")})}),e.jsxs("div",{className:"footer-buttons-right",children:[e.jsx("button",{className:"btn btn-secondary",onClick:D,children:"Close"}),e.jsx("button",{className:"btn btn-secondary",onClick:N,disabled:!z,children:o("config:systemPrompt.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:w,disabled:!z||!r,children:o("config:systemPrompt.save")})]})]})]})}),e.jsx(he,{isOpen:K,title:o("config:systemPrompt.clear"),message:o(W?"config:systemPrompt.confirmClearGlobal":"config:systemPrompt.confirmClear"),confirmLabel:o("config:systemPrompt.clear"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{V()},onClose:()=>F(!1)}),e.jsx(he,{isOpen:q,title:"Unsaved Changes",message:"You have unsaved changes for this agent. Discard them?",confirmLabel:"Discard",cancelLabel:"Keep editing",variant:"danger",onConfirm:Q,onClose:()=>{M(!1),h(null)}})]}):null}const Xe={enabled:!1,baseUrl:"",defaultSessionId:"",webhookVerifyToken:"",showIncomingToasts:!0},Pt=2500,Lt=12e4;function Qe(s){return{enabled:s.enabled??!1,baseUrl:s.baseUrl??"",defaultSessionId:s.defaultSessionId??"",webhookVerifyToken:s.webhookVerifyToken??"",showIncomingToasts:s.showIncomingToasts??!0}}function $t(s,a){return s.enabled===a.enabled&&s.baseUrl===a.baseUrl&&s.defaultSessionId===a.defaultSessionId&&s.webhookVerifyToken===a.webhookVerifyToken&&s.showIncomingToasts===a.showIncomingToasts}function Dt({isOpen:s,onClose:a}){const{t}=Z(["config"]),[o,d]=l.useState(Xe),[r,c]=l.useState(Xe),[x,n]=l.useState(!1),[b,y]=l.useState([]),[S,u]=l.useState(!0),[v,j]=l.useState(null),[m,f]=l.useState(null),[p,C]=l.useState(""),[z,O]=l.useState(!1),[K,F]=l.useState(""),[q,M]=l.useState(null),[H,h]=l.useState(null),[E,B]=l.useState(null),W=l.useRef(null),te=l.useRef(0),[w,$]=l.useState(""),[V,N]=l.useState(""),[L,D]=l.useState(null),[Q,ee]=l.useState(!1),[A,k]=l.useState(!1),[Y,ae]=l.useState(!1),[le,ie]=l.useState(!1),[ue,je]=l.useState(null),ve=!$t(o,r),re=l.useCallback(()=>{W.current&&(clearTimeout(W.current),W.current=null)},[]),me=l.useCallback(async()=>{try{u(!0),j(null),f(null);const[g,R]=await Promise.all([is(),Ts()]),oe=Qe(g);if(d(oe),c(oe),n(!!R.configured),R.configured)try{const fe=await Ve();y(Array.isArray(fe)?fe:[])}catch{y([])}else y([])}catch(g){j(g instanceof Error?g.message:t("config:whatsapp.errors.loadFailed"))}finally{u(!1)}},[t]),I=l.useCallback(async()=>{try{const g=await Ve();y(Array.isArray(g)?g:[])}catch{}},[]);l.useEffect(()=>(s?me():(re(),M(null),h(null),B(null),C(""),O(!1),D(null)),()=>{re()}),[s,me,re]);const pe=(g,R)=>{d(oe=>({...oe,[g]:R})),j(null),f(null)},ce=async()=>{try{j(null),f(null);const g=await Ls({enabled:o.enabled,baseUrl:o.baseUrl.trim(),defaultSessionId:o.defaultSessionId.trim(),webhookVerifyToken:o.webhookVerifyToken,showIncomingToasts:o.showIncomingToasts});window.dispatchEvent(new CustomEvent("tide:whatsapp-config-updated"));const R=Qe(g);d(R),c(R),f(t("config:whatsapp.saved"))}catch(g){j(g instanceof Error?g.message:t("config:whatsapp.errors.saveFailed"))}},$e=()=>{d(r),j(null),f(null)},ge=()=>{if(ve){k(!0);return}a()},De=g=>{g.key==="Escape"&&(g.preventDefault(),ge())},Fe=async()=>{const g=p.trim();if(g)try{j(null),f(null),await Es(g),C(""),O(!1),n(!0),f(t("config:whatsapp.apiKeySaved"))}catch(R){j(R instanceof Error?R.message:t("config:whatsapp.errors.apiKeySaveFailed"))}},Ce=()=>{ae(!0)},Oe=async()=>{try{j(null),f(null),await $s(),n(!1),f(t("config:whatsapp.apiKeyCleared"))}catch(g){j(g instanceof Error?g.message:t("config:whatsapp.errors.apiKeyClearFailed"))}},Ne=l.useCallback(async g=>{if(Date.now()>te.current){B(t("config:whatsapp.pairingTimeout")),M(null),h(null),re(),I();return}try{const R=await _s(g);if(R.status&&["connected","paired","open","ready"].includes(R.status.toLowerCase())){B(t("config:whatsapp.pairingSuccess")),M(null),h(null),re(),I();return}const fe=R.qrUrl??R.qr??null;fe&&h(fe)}catch(R){B(R instanceof Error?R.message:t("config:whatsapp.errors.qrFetchFailed"))}W.current=setTimeout(()=>{Ne(g)},Pt)},[I,re,t]),Ae=async()=>{const g=K.trim();if(g)try{j(null),f(null),B(null),h(null),re(),await Is(g),F(""),M(g),te.current=Date.now()+Lt,Ne(g),I()}catch(R){j(R instanceof Error?R.message:t("config:whatsapp.errors.sessionCreateFailed"))}},Te=()=>{re(),M(null),h(null),B(null)},_e=g=>{je(g),ie(!0)},Re=async()=>{if(ue)try{j(null),f(null),await Ds(ue),q===ue&&Te(),I(),f(t("config:whatsapp.sessionDeleted"))}catch(g){j(g instanceof Error?g.message:t("config:whatsapp.errors.sessionDeleteFailed"))}finally{je(null)}},Ee=async()=>{const g=w.trim(),R=V.trim();if(!(!g||!R))try{ee(!0),D(null);const oe=o.defaultSessionId.trim()||void 0;await Ps(g,R,oe),D({kind:"success",text:t("config:whatsapp.testSent")})}catch(oe){D({kind:"error",text:oe instanceof Error?oe.message:t("config:whatsapp.errors.testSendFailed")})}finally{ee(!1)}};return s?e.jsxs(Se,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:ge,children:e.jsxs("div",{className:"whatsapp-config-modal",onClick:g=>g.stopPropagation(),onKeyDown:De,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:t("config:whatsapp.title")}),e.jsx("button",{className:"modal-close",onClick:ge,"aria-label":"Close",children:e.jsx(P,{name:"close",size:16})})]}),e.jsx("div",{className:"modal-body",children:S?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")}),v&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(P,{name:"warn",size:14})}),v]}),m&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(P,{name:"check",size:14})}),m]}),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:o.enabled,onChange:g=>pe("enabled",g.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:o.showIncomingToasts,onChange:g=>pe("showIncomingToasts",g.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:o.baseUrl,onChange:g=>pe("baseUrl",g.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:o.defaultSessionId,onChange:g=>pe("defaultSessionId",g.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:o.webhookVerifyToken,onChange:g=>pe("webhookVerifyToken",g.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:x?e.jsxs("span",{className:"wa-status wa-status-ok",children:[e.jsx(P,{name:"check",size:12})," ",t("config:whatsapp.configured")]}):e.jsxs("span",{className:"wa-status wa-status-warn",children:[e.jsx(P,{name:"warn",size:12})," ",t("config:whatsapp.notConfigured")]})}),e.jsxs("div",{className:"wa-field wa-field-inline",children:[e.jsx("input",{type:z?"text":"password",className:"wa-input",placeholder:t("config:whatsapp.apiKeyPlaceholder"),value:p,onChange:g=>C(g.target.value)}),e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>O(g=>!g),title:t(z?"config:whatsapp.hideKey":"config:whatsapp.showKey"),children:e.jsx(P,{name:z?"eye-closed":"eye",size:14})}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:Fe,disabled:!p.trim(),children:t("config:whatsapp.saveKey")}),e.jsx("button",{type:"button",className:"btn btn-danger",onClick:Ce,disabled:!x,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(b)||b.length===0?e.jsx("div",{className:"wa-empty",children:t("config:whatsapp.noSessions")}):b.map(g=>e.jsxs("div",{className:"wa-session-row",children:[e.jsxs("div",{className:"wa-session-info",children:[e.jsx("span",{className:"wa-session-id",children:g.id}),e.jsx("span",{className:`wa-session-status status-${(g.status??"unknown").toLowerCase()}`,children:g.status||"—"}),g.pairedNumber&&e.jsx("span",{className:"wa-session-paired",children:g.pairedNumber})]}),e.jsx("button",{type:"button",className:"btn btn-danger btn-sm",onClick:()=>_e(g.id),children:t("config:whatsapp.deleteSession")})]},g.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:K,onChange:g=>F(g.target.value),onKeyDown:g=>{g.key==="Enter"&&Ae()}}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:Ae,disabled:!K.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:Te,children:t("config:whatsapp.cancelPairing")})]}),H?e.jsx("div",{className:"wa-qr-image",children:e.jsx("img",{src:H,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")})]})]}),E&&!q&&e.jsx("div",{className:"wa-pairing-message",children:E})]}),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:w,onChange:g=>$(g.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:V,onChange:g=>N(g.target.value)})]}),e.jsx("div",{className:"wa-field-inline wa-field-end",children:e.jsx("button",{type:"button",className:"btn btn-primary",onClick:Ee,disabled:!w.trim()||!V.trim()||Q,children:t(Q?"config:whatsapp.sending":"config:whatsapp.sendTest")})}),L&&e.jsxs("div",{className:`alert ${L.kind==="success"?"alert-success":"alert-error"}`,children:[e.jsx("span",{className:"alert-icon",children:e.jsx(P,{name:L.kind==="success"?"check":"warn",size:14})}),L.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:ge,children:t("config:whatsapp.close")}),e.jsx("button",{className:"btn btn-secondary",onClick:$e,disabled:!ve||S,children:t("config:whatsapp.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:ce,disabled:!ve||S,children:t("config:whatsapp.save")})]})]})]})}),e.jsx(he,{isOpen:A,title:t("config:whatsapp.unsavedTitle"),message:t("config:whatsapp.unsavedMessage"),confirmLabel:t("config:whatsapp.closeAnyway"),cancelLabel:t("config:whatsapp.keepEditing"),variant:"danger",onConfirm:()=>{k(!1),a()},onClose:()=>k(!1)}),e.jsx(he,{isOpen:Y,title:t("config:whatsapp.clearKey"),message:t("config:whatsapp.confirmClearKey"),confirmLabel:t("config:whatsapp.clearKey"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{Oe()},onClose:()=>ae(!1)}),e.jsx(he,{isOpen:le,title:t("config:whatsapp.deleteSession"),message:t("config:whatsapp.confirmDeleteSession",{id:ue??""}),confirmLabel:t("config:whatsapp.deleteSession"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{Re()},onClose:()=>{ie(!1),je(null)}})]}):null}const ls=["messages","statusChanges","taskComplete","errors","planReady","agentSpawned","agentStopped"];function He(s=!1){const a=se(),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 Ft(){const s=await fetch(`${X()}/api/whatsapp/notification-config`,{headers:He()});if(!s.ok)throw new Error(await qe(s,"Failed to fetch WhatsApp notification config"));return s.json()}async function Ot(s){const a=await fetch(`${X()}/api/whatsapp/notification-config`,{method:"PATCH",headers:He(!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 Rt(){const s=await fetch(`${X()}/api/whatsapp/notification-config`,{method:"DELETE",headers:He()});if(!s.ok)throw new Error(await qe(s,"Failed to reset WhatsApp notification config"));return s.json()}const Le={messages:!0,statusChanges:!0,taskComplete:!0,errors:!0,planReady:!0,agentSpawned:!0,agentStopped:!0},es={filter:{...Le},recipient:""};function Ut(s,a){if(s.recipient!==a.recipient)return!1;for(const t of ls)if(s.filter[t]!==a.filter[t])return!1;return!0}function zt({isOpen:s,onClose:a}){const{t}=Z(["config"]),[o,d]=l.useState(es),[r,c]=l.useState(es),[x,n]=l.useState(!0),[b,y]=l.useState(null),[S,u]=l.useState(null),[v,j]=l.useState(!1),[m,f]=l.useState(!1),p=!Ut(o,r),C=l.useCallback(async()=>{try{n(!0),y(null),u(null);const h=await Ft(),E={filter:{...Le,...h.filter},recipient:h.recipient??""};d(E),c(E)}catch(h){y(h instanceof Error?h.message:t("config:whatsappNotifications.errors.loadFailed"))}finally{n(!1)}},[t]);l.useEffect(()=>{s&&C()},[s,C]);const z=(h,E)=>{d(B=>({...B,filter:{...B.filter,[h]:E}})),y(null),u(null)},O=h=>{d(E=>({...E,recipient:h})),y(null),u(null)},K=async()=>{try{y(null),u(null);const h=await Ot({filter:o.filter,recipient:o.recipient.trim()}),E={filter:{...Le,...h.filter},recipient:h.recipient??""};d(E),c(E),u(t("config:whatsappNotifications.saved"))}catch(h){y(h instanceof Error?h.message:t("config:whatsappNotifications.errors.saveFailed"))}},F=()=>{d(r),y(null),u(null)},q=async()=>{try{y(null),u(null);const h=await Rt(),E={filter:{...Le,...h.filter},recipient:h.recipient??""};d(E),c(E),u(t("config:whatsappNotifications.resetDone"))}catch(h){y(h instanceof Error?h.message:t("config:whatsappNotifications.errors.resetFailed"))}},M=()=>{if(p){j(!0);return}a()},H=h=>{h.key==="Escape"&&(h.preventDefault(),M())};return s?e.jsxs(Se,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:M,children:e.jsxs("div",{className:"whatsapp-notifications-modal",onClick:h=>h.stopPropagation(),onKeyDown:H,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:t("config:whatsappNotifications.title")}),e.jsx("button",{className:"modal-close",onClick:M,"aria-label":"Close",children:e.jsx(P,{name:"close",size:16})})]}),e.jsx("div",{className:"modal-body",children:x?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")}),b&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(P,{name:"warn",size:14})}),b]}),S&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(P,{name:"check",size:14})}),S]}),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:o.recipient,onChange:h=>O(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")}),ls.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:o.filter[h],onChange:E=>z(h,E.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:()=>f(!0),disabled:x,children:t("config:whatsappNotifications.resetToDefaults")})}),e.jsxs("div",{className:"footer-buttons-right",children:[e.jsx("button",{className:"btn btn-secondary",onClick:M,children:t("config:whatsappNotifications.close")}),e.jsx("button",{className:"btn btn-secondary",onClick:F,disabled:!p||x,children:t("config:whatsappNotifications.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:K,disabled:!p||x,children:t("config:whatsappNotifications.save")})]})]})]})}),e.jsx(he,{isOpen:v,title:t("config:whatsappNotifications.unsavedTitle"),message:t("config:whatsappNotifications.unsavedMessage"),confirmLabel:t("config:whatsappNotifications.closeAnyway"),cancelLabel:t("config:whatsappNotifications.keepEditing"),variant:"danger",onConfirm:()=>{j(!1),a()},onClose:()=>j(!1)}),e.jsx(he,{isOpen:m,title:t("config:whatsappNotifications.resetToDefaults"),message:t("config:whatsappNotifications.confirmReset"),confirmLabel:t("config:whatsappNotifications.resetToDefaults"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{q(),f(!1)},onClose:()=>f(!1)})]}):null}function cs(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 Mt(s,a=Date.now()){const t=s*1e3,o=a-t;if(o<0)return ss(t);const d=Math.floor(o/6e4);if(d<1)return"now";if(d<60)return`${d}m`;const r=Math.floor(d/60);if(r<24)return`${r}h`;const c=Math.floor(r/24);return c===1?"yesterday":c<7?`${c}d`:ss(t)}function ss(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Bt(s){const a=s*1e3;return new Date(a).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}function rs(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 Vt(s,a){return s.length<=a?s:s.slice(0,Math.max(0,a-1)).trimEnd()+"…"}function Kt({chats:s,selectedChatId:a,loading:t,error:o,onSelect:d,onRefresh:r,now:c}){const{t:x}=Z(["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:x("config:whatsappHistory.chats")}),e.jsx("button",{type:"button",className:"whatsapp-history-chatlist__refresh",onClick:r,disabled:t,"aria-label":x("config:whatsappHistory.refresh"),title:x("config:whatsappHistory.refresh"),children:"⟳"})]}),o&&e.jsx("div",{className:"whatsapp-history-chatlist__error",children:o}),t&&s.length===0&&e.jsxs("div",{className:"whatsapp-history-chatlist__loading",children:[e.jsx("span",{className:"spinner"}),e.jsx("span",{children:x("config:whatsappHistory.loadingChats")})]}),!t&&!o&&s.length===0&&e.jsx("div",{className:"whatsapp-history-chatlist__empty",children:x("config:whatsappHistory.emptyChats")}),e.jsx("ul",{className:"whatsapp-history-chatlist__items",children:s.map(n=>{const b=rs(n.lastMessageType),y=n.lastMessagePreview||`[${n.lastMessageType}]`,S=n.chatId===a,u=cs(n.chatId),v=n.isGroup?n.groupName:n.fromName,j=v||u,m=!!v&&v!==u;return e.jsx("li",{className:`whatsapp-history-chatlist__item ${S?"is-selected":""}`,children:e.jsxs("button",{type:"button",className:"whatsapp-history-chatlist__button",onClick:()=>d(n.chatId),children:[e.jsxs("div",{className:"whatsapp-history-chatlist__row",children:[e.jsx("span",{className:"whatsapp-history-chatlist__name",title:n.chatId,children:j}),e.jsx("span",{className:"whatsapp-history-chatlist__time",children:Mt(n.lastTimestamp,c)})]}),m&&e.jsx("div",{className:"whatsapp-history-chatlist__row whatsapp-history-chatlist__row--jid",children:e.jsx("span",{className:"whatsapp-history-chatlist__jid",children:u})}),e.jsxs("div",{className:"whatsapp-history-chatlist__row whatsapp-history-chatlist__row--secondary",children:[e.jsxs("span",{className:"whatsapp-history-chatlist__preview",children:[n.lastDirection==="outbound"&&e.jsx("span",{className:"whatsapp-history-chatlist__direction",children:"↗ "}),b&&e.jsxs("span",{className:"whatsapp-history-chatlist__preview-icon",children:[b," "]}),Vt(y,40)]}),n.unreadCount>0&&e.jsx("span",{className:"whatsapp-history-chatlist__unread",children:n.unreadCount})]})]})},n.chatId)})})]})}function Ht({message:s}){const a=s.direction==="outbound"?"outbound":"inbound",t=rs(s.messageType),o=(s.body??"").trim(),d=o.length>0,r=d?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}),d?e.jsx("span",{className:"whatsapp-history-bubble__body",children:o}):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:Bt(s.timestamp)})]})})}const qt=["all","inbound","outbound"],Wt=["all","text","image","audio","video","document","sticker","location","contact","reaction","unknown"];function Gt({direction:s,type:a,onDirectionChange:t,onTypeChange:o,disabled:d}){const{t:r}=Z(["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:c=>t(c.target.value),disabled:d,children:qt.map(c=>e.jsx("option",{value:c,children:r(`config:whatsappHistory.directionValues.${c}`)},c))})]}),e.jsxs("label",{className:"whatsapp-history-filters__field",children:[e.jsx("span",{children:r("config:whatsappHistory.type")}),e.jsx("select",{value:a,onChange:c=>o(c.target.value),disabled:d,children:Wt.map(c=>e.jsx("option",{value:c,children:r(`config:whatsappHistory.typeValues.${c}`)},c))})]})]})}const Yt=80;function Jt({chatId:s,messages:a,loading:t,loadingMore:o,error:d,hasMore:r,direction:c,type:x,onDirectionChange:n,onTypeChange:b,onLoadMore:y}){const{t:S}=Z(["config"]),u=l.useRef(null),v=l.useRef(null),j=l.useRef(!1),m=l.useRef(null);l.useEffect(()=>{v.current!==s&&(v.current=s,j.current=!1)},[s]),l.useLayoutEffect(()=>{u.current&&(j.current||a.length!==0&&(u.current.scrollTop=u.current.scrollHeight,j.current=!0))},[s,a.length]),l.useLayoutEffect(()=>{if(!u.current||m.current===null)return;const C=u.current.scrollHeight-m.current;m.current=null,C>0&&(u.current.scrollTop+=C)},[a.length]);const f=l.useCallback(()=>{!r||o||t||(u.current&&(m.current=u.current.scrollHeight),y())},[r,o,t,y]),p=l.useCallback(C=>{if(!j.current)return;C.currentTarget.scrollTop<=Yt&&f()},[f]);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:cs(s)}),e.jsx(Gt,{direction:c,type:x,onDirectionChange:n,onTypeChange:b,disabled:t})]}),e.jsxs("div",{className:"whatsapp-history-messages__scroll",ref:u,onScroll:p,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:f,disabled:o||t,children:S(o?"config:whatsappHistory.loadingOlder":"config:whatsappHistory.loadOlder")})}),d&&e.jsx("div",{className:"whatsapp-history-messages__error",children:d}),t&&a.length===0&&e.jsxs("div",{className:"whatsapp-history-messages__loading",children:[e.jsx("span",{className:"spinner"}),e.jsx("span",{children:S("config:whatsappHistory.loadingMessages")})]}),!t&&!d&&a.length===0&&e.jsx("div",{className:"whatsapp-history-messages__empty",children:S("config:whatsappHistory.emptyMessages")}),a.map(C=>e.jsx(Ht,{message:C},Zt(C)))]})]}):e.jsx("div",{className:"whatsapp-history-messages whatsapp-history-messages--empty",children:e.jsx("div",{className:"whatsapp-history-messages__placeholder",children:S("config:whatsappHistory.selectChat")})})}function Zt(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 ds(){const s=se(),a={};return s&&(a.Authorization=`Bearer ${s}`),a}async function us(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 Xt(s){const a=`${X()}/api/whatsapp/chats/${encodeURIComponent(s)}`,t=await fetch(a,{headers:ds()});if(!t.ok)throw new Error(await us(t,"Failed to fetch WhatsApp chats"));return t.json()}async function ts(s,a,t={}){const o=new URLSearchParams;t.cursor&&o.set("cursor",t.cursor),typeof t.limit=="number"&&o.set("limit",String(t.limit)),t.direction&&o.set("direction",t.direction),t.type&&o.set("type",t.type);const d=o.toString(),r=`${X()}/api/whatsapp/chats/${encodeURIComponent(s)}/${encodeURIComponent(a)}/messages${d?`?${d}`:""}`,c=await fetch(r,{headers:ds()});if(!c.ok)throw new Error(await us(c,"Failed to fetch WhatsApp messages"));return c.json()}const Qt=50;function ea({isOpen:s,onClose:a}){const{t}=Z(["config"]),[o,d]=l.useState([]),[r,c]=l.useState(null),[x,n]=l.useState(null),[b,y]=l.useState([]),[S,u]=l.useState(!1),[v,j]=l.useState(null),[m,f]=l.useState(null),[p,C]=l.useState([]),[z,O]=l.useState(!1),[K,F]=l.useState(!1),[q,M]=l.useState(null),[H,h]=l.useState(null),[E,B]=l.useState("all"),[W,te]=l.useState("all"),[w,$]=l.useState(()=>Date.now()),V=l.useRef(0);l.useEffect(()=>{if(!s)return;const k=window.setInterval(()=>$(Date.now()),6e4);return()=>window.clearInterval(k)},[s]),l.useEffect(()=>{if(!s)return;let k=!1;return(async()=>{var Y;try{n(null);const[ae,le]=await Promise.all([Ve().catch(()=>[]),is().catch(()=>null)]);if(k)return;d(ae);const ie=(le==null?void 0:le.defaultSessionId)||((Y=ae[0])==null?void 0:Y.id)||null;c(ue=>ue??ie)}catch(ae){if(k)return;n(ae instanceof Error?ae.message:String(ae))}})(),()=>{k=!0}},[s]);const N=l.useCallback(async k=>{u(!0),j(null);try{const Y=await Xt(k);y(Y.chats)}catch(Y){j(Y instanceof Error?Y.message:String(Y))}finally{u(!1)}},[]);l.useEffect(()=>{!s||!r||(f(null),C([]),h(null),N(r))},[s,r,N]);const L=l.useMemo(()=>{const k={limit:Qt};return E!=="all"&&(k.direction=E),W!=="all"&&(k.type=W),k},[E,W]),D=l.useCallback(async(k,Y,ae)=>{const le=++V.current;O(!0),M(null),C([]),h(null);try{const ie=await ts(k,Y,ae);if(le!==V.current)return;C([...ie.messages].reverse()),h(ie.nextCursor)}catch(ie){if(le!==V.current)return;M(ie instanceof Error?ie.message:String(ie))}finally{le===V.current&&O(!1)}},[]);l.useEffect(()=>{!s||!r||!m||D(r,m,L)},[s,r,m,L,D]);const Q=l.useCallback(async()=>{if(!(!r||!m||!H)){F(!0),M(null);try{const k=await ts(r,m,{...L,cursor:H});C(Y=>[...[...k.messages].reverse(),...Y]),h(k.nextCursor)}catch(k){M(k instanceof Error?k.message:String(k))}finally{F(!1)}}},[r,m,H,L]),ee=l.useCallback(()=>{r&&N(r)},[r,N]),A=l.useCallback(k=>{k.key==="Escape"&&(k.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:k=>k.stopPropagation(),onKeyDown:A,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:k=>c(k.target.value||null),disabled:o.length===0,children:[o.length===0&&e.jsx("option",{value:"",children:t("config:whatsappHistory.noSessions")}),o.map(k=>e.jsxs("option",{value:k.id,children:[k.id,k.pairedNumber?` (${k.pairedNumber})`:""]},k.id))]})]})}),e.jsx("button",{className:"modal-close",onClick:a,"aria-label":"Close",children:e.jsx(P,{name:"close",size:16})})]}),x&&e.jsx("div",{className:"whatsapp-history-modal__alert",children:x}),e.jsxs("div",{className:"whatsapp-history-modal__body",children:[e.jsx(Kt,{chats:b,selectedChatId:m,loading:S,error:v,onSelect:f,onRefresh:ee,now:w}),e.jsx(Jt,{chatId:m,messages:p,loading:z,loadingMore:K,error:q,hasMore:H!==null,direction:E,type:W,onDirectionChange:B,onTypeChange:te,onLoadMore:Q})]})]})})}):null}function sa({isOpen:s,onClose:a,onOpenConfig:t,onOpenNotifications:o,onOpenHistory:d}){const{t:r}=Z(["config"]);if(l.useEffect(()=>{if(!s)return;const x=n=>{n.key==="Escape"&&(n.preventDefault(),a())};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[s,a]),!s)return null;const c=x=>{a(),x()};return e.jsx(Se,{children:e.jsx("div",{className:"modal-overlay visible",onClick:a,children:e.jsxs("div",{className:"whatsapp-hub-modal",onClick:x=>x.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(P,{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:()=>c(t),children:[e.jsx("span",{className:"whatsapp-hub-modal__option-icon",children:e.jsx(P,{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:()=>c(o),children:[e.jsx("span",{className:"whatsapp-hub-modal__option-icon",children:e.jsx(P,{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:()=>c(d),children:[e.jsx("span",{className:"whatsapp-hub-modal__option-icon",children:e.jsx(P,{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 ta=[{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:"🌙"}],aa=[{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:"🔴"}],na=[{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:"👎"}],ia=[{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:"💜"}],oa=[{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"}],la=[{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"}],ca={showTrees:"trees",showBushes:"bushes",showHouse:"house",showLamps:"lamps",showGrass:"grass",showClouds:"clouds"},ra={none:"grass","pokemon-stadium":"pokemon"},da={"emote-yes":"yes","emote-no":"no"},ua={"":"auto","#4a90d9":"dayBlue","#0a1a2a":"night","#ff6b35":"sunset","#1a0a2e":"purple","#2d5a27":"matrix","#8b0000":"blood","#000000":"void"};function ne({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 be({options:s,value:a,onChange:t,iconOnly:o=!1}){return e.jsx("div",{className:"chip-selector",children:s.map(d=>e.jsxs("button",{className:`chip ${a===d.value?"active":""}`,onClick:()=>t(d.value),title:d.label,children:[e.jsx("span",{className:"chip-icon",children:d.icon}),!o&&e.jsx("span",{className:"chip-label",children:d.label})]},d.value))})}function _({text:s,query:a}){if(!a.trim())return e.jsx(e.Fragment,{children:s});const t=s.toLowerCase(),o=a.toLowerCase(),d=t.indexOf(o);if(d===-1)return e.jsx(e.Fragment,{children:s});const r=s.slice(0,d),c=s.slice(d,d+a.length),x=s.slice(d+a.length);return e.jsxs(e.Fragment,{children:[r,e.jsx("mark",{className:"search-highlight",children:c}),x]})}const pa=[{id:"general",title:"General",keywords:["history","hide costs","grid","fps","power saving","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"]},{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:"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"]}],Be=[{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 ha({config:s,onChange:a,searchQuery:t="",onOpenIntegrationsModal:o,onOpenMonitoringModal:d,onOpenStatisticsModal:r,onOpenWorkflowEditor:c,onOpenTriggerManager:x}){var We;const{t:n}=Z(["config","common"]),b=Fs(),y=Os(),[S,u]=l.useState(()=>Rs(we.DEFAULT_AGENT_CLASS)||"scout"),[v,j]=l.useState(b.historyLimit),[m,f]=l.useState(()=>Us()),[p,C]=l.useState(!1),[z,O]=l.useState(""),[K,F]=l.useState(()=>se()),[q,M]=l.useState(!1),[H,h]=l.useState(!1),[E,B]=l.useState(""),[W,te]=l.useState(!1),[w,$]=l.useState(!1),[V,N]=l.useState(!1),[L,D]=l.useState(!1),[Q,ee]=l.useState(!1),[A,k]=l.useState(""),[Y,ae]=l.useState(!1);l.useEffect(()=>{gt().then(k).catch(()=>{})},[]),l.useEffect(()=>{ht().then(i=>{i!==b.experimentalEchoPrompt&&T.updateSettings({experimentalEchoPrompt:i})}).catch(()=>{})},[]),l.useEffect(()=>{xt().then(i=>{i!==b.tmuxMode&&T.updateSettings({tmuxMode:i})}).catch(()=>{})},[]),l.useEffect(()=>{jt().then(i=>{i!==b.interactiveMode&&T.updateSettings({interactiveMode:i})}).catch(()=>{})},[]),l.useEffect(()=>zs(i=>{f(i),C(!1)}),[]);const le=ta.map(i=>({...i,label:n(`config:time.${i.value}`)})),ie=aa.map(i=>({...i,label:n(`config:floor.${ra[i.value]||i.value}`)})),ue=na.map(i=>({...i,label:n(`config:animation.${da[i.value]||i.value}`)})),je=ia.map(i=>({...i,label:n(`config:colorMode.${i.value}`)})),ve=oa.map(i=>({...i,label:n(`config:terrain.${ca[i.key]}`)})),re=la.map(i=>({...i,label:n(`config:sky.${ua[i.value??""]}`)})),me=t.trim()?pa.filter(i=>{const U=t.toLowerCase();return i.title.toLowerCase().includes(U)||i.keywords.some(de=>de.toLowerCase().includes(U))}).map(i=>i.id):null,I=i=>me?me.includes(i):!0,pe=I("integrations"),ce=b.customAgentNames||[],$e=ce.length>0?ce:Ms,ge=()=>{const i=E.trim();i&&!ce.includes(i)&&(T.updateSettings({customAgentNames:[...ce,i]}),B(""))},De=i=>{T.updateSettings({customAgentNames:ce.filter(U=>U!==i)})},Fe=()=>{T.updateSettings({customAgentNames:[]})},Ce=()=>{const i=z.trim();if(i){if(m.includes(i)){O("");return}f([...m,i]),C(!0),O("")}},Oe=i=>{f(m.filter((U,de)=>de!==i)),C(!0)},Ne=(i,U)=>{const de=i+U;if(de<0||de>=m.length)return;const xe=m.slice();[xe[i],xe[de]]=[xe[de],xe[i]],f(xe),C(!0)},Ae=()=>{Vs(m),C(!1),Me()},Te=i=>{F(i),M(!0)},_e=()=>{Ie(we.AUTH_TOKEN,K),M(!1),Me()},Re=i=>{k(i),ae(!0)},Ee=()=>{ft(A).catch(()=>{}),ae(!1)},g=i=>{a({...s,terrain:{...s.terrain,...i}})},R=i=>{a({...s,modelStyle:{...s.modelStyle,...i}})},oe=i=>{a({...s,animations:{...s.animations,...i}})},fe=i=>{j(i),T.updateSettings({historyLimit:i})},ps=i=>{const U=s.terrain[i];typeof U=="boolean"&&g({[i]:!U})},J=t.trim().length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"config-section",children:[me&&me.length===0&&e.jsx("div",{className:"config-no-results",children:n("config:noResults",{query:t})}),I("general")&&e.jsxs(G,{title:n("config:sections.general"),storageKey:"general",defaultOpen:!0,forceOpen:J&&I("general"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:general.history"),query:t})}),e.jsx("input",{type:"number",className:"config-input config-input-sm",value:v,onChange:i=>fe(parseInt(i.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:n("config:general.hideCosts"),query:t})}),e.jsx(ne,{checked:b.hideCost,onChange:i=>T.updateSettings({hideCost:i})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",title:n("config:general.streamTextLiveTitle"),children:e.jsx(_,{text:n("config:general.streamTextLive"),query:t})}),e.jsx(ne,{checked:b.streamTextLive!==!1,onChange:i=>T.updateSettings({streamTextLive:i})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:general.grid"),query:t})}),e.jsx(ne,{checked:s.gridVisible,onChange:i=>a({...s,gridVisible:i})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:general.showFPS"),query:t})}),e.jsx(ne,{checked:b.showFPS,onChange:i=>T.updateSettings({showFPS:i})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:general.fpsLimit"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"120",step:"10",value:s.fpsLimit,onChange:i=>a({...s,fpsLimit:parseInt(i.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:n("config:general.powerSaving"),query:t})," ",e.jsx(P,{name:"bolt",size:12})]}),e.jsx(ne,{checked:b.powerSaving,onChange:i=>T.updateSettings({powerSaving:i})})]}),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:n("config:general.tmuxMode"),query:t})}),e.jsx(ne,{checked:b.tmuxMode,onChange:async i=>{T.updateSettings({tmuxMode:i});try{await bt(i)}catch(U){console.error("Failed to sync tmux mode setting to server:",U)}}})]}),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:n("config:general.interactiveMode"),query:t})," ",e.jsx(P,{name:"bolt",size:12})]}),e.jsx(ne,{checked:b.interactiveMode,onChange:async i=>{T.updateSettings({interactiveMode:i});try{await vt(i)}catch(U){console.error("Failed to sync interactive mode setting to server:",U)}}})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:general.vibrationIntensity"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"5",step:"1",value:b.vibrationIntensity,onChange:i=>T.updateSettings({vibrationIntensity:parseInt(i.target.value)})}),e.jsx("span",{className:"config-value",children:b.vibrationIntensity===0?n("config:vibrationValues.off"):b.vibrationIntensity===1?n("config:vibrationValues.ultraLight"):b.vibrationIntensity===2?n("config:vibrationValues.veryLight"):b.vibrationIntensity===3?n("config:vibrationValues.light"):b.vibrationIntensity===4?n("config:vibrationValues.medium"):n("config:vibrationValues.heavy")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:general.externalEditor"),query:t})}),e.jsx("input",{type:"text",className:"config-input",placeholder:n("config:general.externalEditorPlaceholder"),value:b.externalEditorCommand||"",onChange:i=>T.updateSettings({externalEditorCommand:i.target.value})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:general.tabTitle"),query:t})}),e.jsx("input",{type:"text",className:"config-input",placeholder:n("config:general.tabTitlePlaceholder"),value:b.tabTitle||"",onChange:i=>T.updateSettings({tabTitle:i.target.value})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:general.language"),query:t})}),e.jsx(be,{options:Be,value:localStorage.getItem("tide-commander-language-mode")==="manual"?((We=Be.find(i=>i.value!=="auto"&&ze.language.startsWith(i.value.split("-")[0])))==null?void 0:We.value)||"en":"auto",onChange:i=>{var U;if(i==="auto"){localStorage.setItem("tide-commander-language-mode","auto");const de=navigator.language,xe=((U=Be.find(Ge=>Ge.value!=="auto"&&de.startsWith(Ge.value.split("-")[0])))==null?void 0:U.value)||"en";ze.changeLanguage(xe)}else localStorage.setItem("tide-commander-language-mode","manual"),ze.changeLanguage(i)}})]})]}),I("agentNames")&&e.jsx(G,{title:n("config:sections.agentNames"),storageKey:"agentNames",defaultOpen:!1,forceOpen:J&&I("agentNames"),children:e.jsxs("div",{className:"agent-names-section",children:[e.jsx("span",{className:"config-hint",children:ce.length>0?n("config:agentNames.customConfigured",{count:ce.length}):n("config:agentNames.usingDefaults")}),e.jsxs("div",{className:"agent-names-input-row",children:[e.jsx("input",{type:"text",className:"config-input config-input-full",placeholder:n("config:agentNames.addPlaceholder"),value:E,onChange:i=>B(i.target.value),onKeyDown:i=>{i.key==="Enter"&&ge()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:ge,disabled:!E.trim(),title:n("config:agentNames.addName"),children:"+"})]}),e.jsx("div",{className:"agent-names-list",children:$e.map((i,U)=>e.jsxs("div",{className:"agent-name-chip",children:[e.jsx("span",{className:"agent-name-text",children:i}),ce.length>0&&e.jsx("button",{className:"agent-name-remove",onClick:()=>De(i),title:n("common:buttons.remove"),children:"x"})]},`${i}-${U}`))}),ce.length>0&&e.jsx("button",{className:"config-btn config-btn-link",onClick:Fe,children:n("common:buttons.resetToDefaults")})]})}),I("defaultClass")&&e.jsx(G,{title:"Default Spawn Class",storageKey:"defaultClass",defaultOpen:!1,forceOpen:J&&I("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${S==="random"?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{u("random"),Ie(we.DEFAULT_AGENT_CLASS,"random")},children:e.jsx("span",{className:"agent-name-text",children:"🎲 Random"})}),Object.entries(Bs).map(([i,U])=>e.jsx("div",{className:`agent-name-chip${S===i?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{u(i),Ie(we.DEFAULT_AGENT_CLASS,i)},children:e.jsxs("span",{className:"agent-name-text",children:[U.icon," ",i.charAt(0).toUpperCase()+i.slice(1)]})},i)),y.map(i=>e.jsx("div",{className:`agent-name-chip${S===i.id?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{u(i.id),Ie(we.DEFAULT_AGENT_CLASS,i.id)},children:e.jsxs("span",{className:"agent-name-text",children:[i.icon," ",i.name]})},i.id))]})]})}),I("appearance")&&e.jsx(G,{title:n("config:sections.appearance"),storageKey:"appearance",defaultOpen:!1,forceOpen:J&&I("appearance"),children:e.jsx(St,{})}),I("connection")&&e.jsxs(G,{title:n("config:sections.connection"),storageKey:"connection",defaultOpen:!1,forceOpen:J&&I("connection"),children:[e.jsxs("div",{className:"config-row config-row-stacked",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:connection.backendUrl"),query:t})}),e.jsx("div",{className:"backend-urls-list",children:m.map((i,U)=>e.jsxs("div",{className:"backend-url-row",children:[e.jsx("span",{className:"backend-url-priority",title:n("config:connection.priorityLabel",{defaultValue:"Priority"}),children:U+1}),e.jsx("span",{className:"backend-url-text",title:i,children:i}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>Ne(U,-1),disabled:U===0,title:n("config:connection.moveUp",{defaultValue:"Move up"}),children:"↑"}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>Ne(U,1),disabled:U===m.length-1,title:n("config:connection.moveDown",{defaultValue:"Move down"}),children:"↓"}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>Oe(U),title:n("common:buttons.remove"),children:"x"})]},`${i}-${U}`))}),e.jsxs("div",{className:"config-input-group",children:[e.jsx("input",{type:"text",className:"config-input config-input-full",value:z,onChange:i=>O(i.target.value),placeholder:n("config:connection.addUrlPlaceholder",{defaultValue:"http://host:port"}),onKeyDown:i=>{i.key==="Enter"&&Ce()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:Ce,disabled:!z.trim(),title:n("config:connection.addUrl",{defaultValue:"Add URL"}),children:"+"}),p&&e.jsx("button",{className:"config-btn config-btn-sm",onClick:Ae,title:n("config:connection.saveAndReconnect"),children:n("common:buttons.apply")})]}),e.jsx("span",{className:"config-hint",children:n("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:n("config:connection.authToken"),query:t})}),e.jsxs("div",{className:"config-input-group",children:[e.jsx("input",{type:H?"text":"password",className:"config-input config-input-full",value:K,onChange:i=>Te(i.target.value),placeholder:n("config:connection.tokenPlaceholder"),onKeyDown:i=>{i.key==="Enter"&&q&&_e()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>h(!H),title:n(H?"config:connection.hideToken":"config:connection.showToken"),children:e.jsx(P,{name:H?"eye-closed":"eye",size:14})}),q&&e.jsx("button",{className:"config-btn config-btn-sm",onClick:_e,title:n("config:connection.saveAndReconnect"),children:n("common:buttons.apply")})]}),e.jsx("span",{className:"config-hint",children:n("config:connection.tokenRequired")})]}),e.jsxs("div",{className:"config-row config-row-stacked",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("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:A,onChange:i=>Re(i.target.value),placeholder:n("config:connection.codexBinaryPathPlaceholder"),onKeyDown:i=>{i.key==="Enter"&&Y&&Ee()}}),Y&&e.jsx("button",{className:"config-btn config-btn-sm",onClick:Ee,children:n("common:buttons.apply")})]}),e.jsx("span",{className:"config-hint",children:n("config:connection.codexBinaryPathHint")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("common:buttons.reconnect"),query:t})}),e.jsx("button",{className:"config-btn",onClick:()=>Me(),title:"Force reconnect to server",children:n("common:buttons.reconnect")})]})]}),I("scene")&&e.jsxs(G,{title:n("config:sections.scene"),storageKey:"scene",defaultOpen:!1,forceOpen:J&&I("scene"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("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:i=>a({...s,characterScale:parseFloat(i.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:n("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:i=>a({...s,scale2d:parseFloat(i.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:n("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:i=>a({...s,scale3d:parseFloat(i.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:n("config:scene.show2DTaskLabels",{defaultValue:"Show 2D task labels"}),query:t})}),e.jsx(ne,{checked:s.show2DTaskLabels,onChange:i=>a({...s,show2DTaskLabels:i})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:scene.time"),query:t})}),e.jsx(be,{options:le,value:s.timeMode,onChange:i=>a({...s,timeMode:i}),iconOnly:!0})]})]}),I("terrain")&&e.jsxs(G,{title:n("config:sections.terrain"),storageKey:"terrain",defaultOpen:!1,forceOpen:J&&I("terrain"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:terrainSettings.simpleMode",{defaultValue:"Simple Mode"}),query:t})}),e.jsx(ne,{checked:s.terrain.simpleMode??!1,onChange:i=>g({simpleMode:i})})]}),e.jsx("div",{className:"terrain-icons",style:{opacity:s.terrain.simpleMode?.4:1,pointerEvents:s.terrain.simpleMode?"none":"auto"},children:ve.map(i=>e.jsx("button",{className:`terrain-icon-btn ${s.terrain[i.key]?"active":""}`,onClick:()=>ps(i.key),title:i.label,children:i.icon},i.key))}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("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:i=>g({fogDensity:parseFloat(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.terrain.fogDensity===0?n("config:fogValues.off"):s.terrain.fogDensity<=1?n("config:fogValues.low"):n("config:fogValues.high")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("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:i=>g({brightness:parseFloat(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.terrain.brightness<=.5?n("config:brightnessValues.dark"):s.terrain.brightness<=1.2?n("config:brightnessValues.normal"):n("config:brightnessValues.bright")})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:terrainSettings.floor"),query:t})}),e.jsx(be,{options:ie,value:s.terrain.floorStyle,onChange:i=>g({floorStyle:i}),iconOnly:!0})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:terrainSettings.sky"),query:t})}),e.jsx("div",{className:"sky-color-selector",children:re.map(i=>e.jsx("button",{className:`sky-color-btn ${s.terrain.skyColor===i.value?"active":""}`,onClick:()=>g({skyColor:i.value}),title:i.label,style:{background:i.color}},i.value??"auto"))})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:terrainSettings.battlefieldSize"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"30",max:"200",step:"10",value:s.terrain.battlefieldSize,onChange:i=>g({battlefieldSize:parseInt(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.terrain.battlefieldSize})]})]}),I("modelStyle")&&e.jsxs(G,{title:n("config:sections.modelStyle"),storageKey:"modelStyle",defaultOpen:!1,forceOpen:J&&I("modelStyle"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("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:i=>R({saturation:parseFloat(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.saturation<=.3?n("config:saturationValues.gray"):s.modelStyle.saturation<=1.2?n("config:saturationValues.normal"):n("config:saturationValues.vivid")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("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:i=>R({roughness:parseFloat(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.roughness<0?n("config:roughnessValues.auto"):s.modelStyle.roughness<=.3?n("config:roughnessValues.glossy"):s.modelStyle.roughness<=.7?n("config:roughnessValues.normal"):n("config:roughnessValues.matte")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("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:i=>R({metalness:parseFloat(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.metalness<0?n("config:metalnessValues.auto"):s.modelStyle.metalness<=.3?n("config:metalnessValues.plastic"):s.modelStyle.metalness<=.7?n("config:metalnessValues.mixed"):n("config:metalnessValues.metal")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("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:i=>R({emissiveBoost:parseFloat(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.emissiveBoost<=.1?n("config:glowValues.off"):s.modelStyle.emissiveBoost<=.4?n("config:glowValues.low"):s.modelStyle.emissiveBoost<=.7?n("config:glowValues.med"):n("config:glowValues.high")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("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:i=>R({envMapIntensity:parseFloat(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.envMapIntensity<0?n("config:reflectionValues.auto"):s.modelStyle.envMapIntensity<=.3?n("config:reflectionValues.low"):s.modelStyle.envMapIntensity<=1?n("config:reflectionValues.normal"):n("config:reflectionValues.high")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:modelStyleSettings.wireframe"),query:t})}),e.jsx(ne,{checked:s.modelStyle.wireframe,onChange:i=>R({wireframe:i})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:modelStyleSettings.colorMode"),query:t})}),e.jsx(be,{options:je,value:s.modelStyle.colorMode,onChange:i=>R({colorMode:i}),iconOnly:!0})]})]}),I("animations")&&e.jsxs(G,{title:n("config:sections.animations"),storageKey:"animations",defaultOpen:!1,forceOpen:J&&I("animations"),children:[e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:animationSettings.idle"),query:t})}),e.jsx(be,{options:ue,value:s.animations.idleAnimation,onChange:i=>oe({idleAnimation:i}),iconOnly:!0})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:animationSettings.working"),query:t})}),e.jsx(be,{options:ue,value:s.animations.workingAnimation,onChange:i=>oe({workingAnimation:i}),iconOnly:!0})]})]}),I("secrets")&&e.jsx(G,{title:n("config:sections.secrets"),storageKey:"secrets",defaultOpen:!1,forceOpen:J&&I("secrets"),children:e.jsx(rt,{})}),I("systemPrompt")&&e.jsx(G,{title:n("config:sections.systemPrompt"),storageKey:"systemPrompt",defaultOpen:!1,forceOpen:J&&I("systemPrompt"),children:e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(_,{text:n("config:systemPrompt.title"),query:t})}),e.jsx("button",{className:"config-button",onClick:()=>te(!0),children:n("config:systemPrompt.editPrompt")})]})}),I("data")&&e.jsx(G,{title:n("config:sections.data"),storageKey:"data",defaultOpen:!1,forceOpen:J&&I("data"),children:e.jsx(kt,{})}),pe&&e.jsx(G,{title:n("config:sections.integrations"),storageKey:"integrations",defaultOpen:!1,forceOpen:J&&pe,children:e.jsx(Et,{onOpenModal:i=>{i==="whatsapp"?ee(!0):o==null||o(i)}})}),I("workflows")&&e.jsxs(G,{title:"Workflows",storageKey:"workflows",defaultOpen:!1,forceOpen:J&&I("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:()=>c==null?void 0:c(),children:"Open Workflow Editor"})})]}),I("triggers")&&e.jsxs(G,{title:"Triggers",storageKey:"triggers",defaultOpen:!1,forceOpen:J&&I("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:()=>x==null?void 0:x(),children:"Open Trigger Manager"})})]}),I("monitoring")&&e.jsxs(G,{title:"Monitoring",storageKey:"monitoring",defaultOpen:!1,forceOpen:J&&I("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:()=>d==null?void 0:d(),children:"Open Monitoring & Logs"})})]}),I("statistics")&&e.jsxs(G,{title:"Statistics",storageKey:"statistics",defaultOpen:!1,forceOpen:J&&I("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"})})]}),I("experimental")&&e.jsxs(G,{title:n("config:sections.experimental"),storageKey:"experimental",defaultOpen:!1,forceOpen:J&&I("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:n("config:experimental.2dView"),query:t})," ",e.jsx(P,{name:"map",size:12})]}),e.jsx(ne,{checked:b.experimental2DView,onChange:i=>T.updateSettings({experimental2DView:i})})]}),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:n("config:experimental.voiceAssistant"),query:t})," ",e.jsx(P,{name:"microphone",size:12})]}),e.jsx(ne,{checked:b.experimentalVoiceAssistant,onChange:i=>T.updateSettings({experimentalVoiceAssistant:i})})]}),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:n("config:experimental.tts"),query:t})," ",e.jsx(P,{name:"speaker-on",size:12})]}),e.jsx(ne,{checked:b.experimentalTTS,onChange:i=>T.updateSettings({experimentalTTS:i})})]}),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:n("config:experimental.echoPrompt"),query:t})}),e.jsx(ne,{checked:b.experimentalEchoPrompt,onChange:async i=>{T.updateSettings({experimentalEchoPrompt:i});try{await mt(i)}catch(U){console.error("Failed to sync echo prompt setting to server:",U)}}})]}),e.jsx("span",{className:"config-hint",children:n("config:experimental.hint")})]}),I("about")&&e.jsx(G,{title:n("config:sections.about"),storageKey:"about",defaultOpen:!1,forceOpen:J&&I("about"),children:e.jsx(Tt,{})})]}),e.jsx(It,{isOpen:W,onClose:()=>te(!1)}),e.jsx(Dt,{isOpen:w,onClose:()=>$(!1)}),e.jsx(zt,{isOpen:V,onClose:()=>N(!1)}),e.jsx(ea,{isOpen:L,onClose:()=>D(!1)}),e.jsx(sa,{isOpen:Q,onClose:()=>ee(!1),onOpenConfig:()=>$(!0),onOpenNotifications:()=>N(!0),onOpenHistory:()=>D(!0)})]})}function ba({onConfigChange:s,onToolChange:a,config:t,isOpen:o,onClose:d,onOpenBuildingModal:r,onOpenAreaExplorer:c,onOpenIntegrationsModal:x,onOpenMonitoringModal:n,onOpenStatisticsModal:b,onOpenWorkflowEditor:y,onOpenTriggerManager:S}){const{t:u}=Z(["config","common"]),v=Ks(),j=Hs(),m=qs(),f=Ws(),p=Gs(),C=Array.from(v.values()),z=Array.from(j.values()),[O,K]=l.useState(""),F=l.useRef(null);if(l.useEffect(()=>{const h=E=>{E.key==="Escape"&&o&&d()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[o,d]),l.useEffect(()=>{if(o&&F.current){if(typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches)return;const E=setTimeout(()=>{var B;(B=F.current)==null||B.focus()},50);return()=>clearTimeout(E)}},[o]),!o)return null;const q=h=>{a(p===h?null:h)},M=h=>{T.selectArea(f===h?null:h),a("select")},H=(h,E)=>{h.stopPropagation(),T.deleteArea(E)};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"toolbox-backdrop",onClick:d}),e.jsxs("aside",{className:"toolbox",children:[e.jsxs("div",{className:"toolbox-header",children:[e.jsx("span",{children:u("config:title")}),e.jsx("button",{className:"toolbox-close-btn",onClick:d,title:u("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:F,type:"text",placeholder:u("config:searchPlaceholder"),value:O,onChange:h=>K(h.target.value),className:"toolbox-search-input"}),O&&e.jsx("button",{className:"toolbox-search-clear",onClick:()=>K(""),children:"×"})]}),e.jsxs("div",{className:"toolbox-content",children:[e.jsx("div",{className:"toolbox-section toolbox-section-collapsible",children:e.jsxs(G,{title:u("config:areas.title",{count:C.length}),storageKey:"areas",children:[e.jsxs("div",{className:"tool-buttons",children:[e.jsx("button",{className:`tool-btn ${p==="select"?"active":""}`,onClick:()=>q("select"),title:u("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 ${p==="rectangle"?"active":""}`,onClick:()=>q("rectangle"),title:u("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 ${p==="circle"?"active":""}`,onClick:()=>q("circle"),title:u("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:C.length===0?e.jsx("div",{className:"areas-empty",children:u("config:areas.drawToCreate")}):C.map(h=>e.jsx(nt,{area:h,isSelected:f===h.id,onClick:()=>M(h.id),onDelete:E=>H(E,h.id)},h.id))})]})}),f&&e.jsx(ct,{area:v.get(f),onClose:()=>T.selectArea(null),onOpenFolder:c}),e.jsx("div",{className:"toolbox-section toolbox-section-collapsible",children:e.jsx(G,{title:u("config:buildings.title",{count:z.length}),storageKey:"buildings",headerExtra:e.jsx("button",{className:"add-building-btn",onClick:h=>{h.stopPropagation(),r==null||r()},title:u("config:buildings.addBuilding"),children:"+"}),children:e.jsx("div",{className:"buildings-list",children:z.length===0?e.jsx("div",{className:"buildings-empty",children:u("config:buildings.clickToAdd")}):z.map(h=>e.jsx(it,{building:h,isSelected:m.has(h.id),onClick:()=>{T.selectBuilding(m.has(h.id)?null:h.id)},onEdit:()=>r==null?void 0:r(h.id)},h.id))})})}),m.size===1&&(()=>{const h=Array.from(m)[0],E=j.get(h);return E?e.jsx(ot,{building:E,onClose:()=>T.selectBuilding(null),onOpenModal:()=>r==null?void 0:r(h)}):null})(),e.jsx(ha,{config:t,onChange:s,searchQuery:O,onOpenIntegrationsModal:x,onOpenMonitoringModal:n,onOpenStatisticsModal:b,onOpenWorkflowEditor:y,onOpenTriggerManager:S})]})]})]})}export{ba as Toolbox};
@@ -1,2 +0,0 @@
1
- import{r as a,H as yn,J as Yt,K as cn,L as dn,j as e,M as un,N as Nn,u as Vt,O as Sn,P as An,U as En,V as In,W as Mn,X as Tn,Y as Ln,Z as Pn,_ as Kt,S as A,$ as Zt,a0 as Ut,a1 as Jt,a2 as yt,a3 as ge,a4 as Rn,s as g,a5 as pn,m as mn,a6 as Dn,z as Qt,B as en,I as m,a7 as $n,q as zn,a8 as On,a9 as fn,aa as hn,ab as gn,ac as xn,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 tn,C as Jn,aq as Qn,ar as nn,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 pa,aF as ma,aG as fa,aH as Je,aI as ha,aJ as ga,aK as xa,aL as ba,aM as lt,aN as _a,aO as wa,aP as va,aQ as ja,aR as Ca,aS as an,aT as ka}from"./main-KW9NTHdK.js";import{g as ya}from"./area-logos-B6OVpGpC.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function Na(c){const r=a.useRef(c);r.current=c,a.useEffect(()=>{if(!yn())return;let p=null,h=!1;return Yt.addListener("backButton",()=>{r.current()==="exit"&&Yt.exitApp()}).then(k=>{h?k.remove():p=k}),()=>{h=!0,p&&(p.remove(),p=null)}},[])}async function Sa(c){const r=cn(),p=await fetch(`${dn()}/api/agents/${c}/terminal`,{method:"POST",headers:{Authorization:`Bearer ${r}`}});if(!p.ok){const h=await p.json().catch(()=>({}));throw new Error((h==null?void 0:h.error)||`Failed to start terminal (${p.status})`)}return p.json()}async function Aa(c){const r=cn();await fetch(`${dn()}/api/agents/${c}/terminal`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}})}const rt=new Map;function Ea({agentId:c}){const[r,p]=a.useState(null),[h,k]=a.useState(null);return a.useEffect(()=>{let T=!1;const S=rt.get(c);return S&&(clearTimeout(S),rt.delete(c)),p(null),k(null),Sa(c).then(y=>{T||p(y.url)}).catch(y=>{T||k(y instanceof Error?y.message:"Failed to start terminal")}),()=>{T=!0;const y=rt.get(c);y&&clearTimeout(y),rt.set(c,setTimeout(()=>{rt.delete(c),Aa(c)},2500))}},[c]),h?e.jsx("div",{className:"flat-classic-terminal flat-classic-terminal--message",children:e.jsx("span",{children:h})}):r?e.jsx("div",{className:"flat-classic-terminal",children:e.jsx(un,{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 Ft=new Map,Ia=6e4;function sn(c){return Number.isFinite(c)?Math.abs(c)>=1e3?c.toLocaleString(void 0,{maximumFractionDigits:0}):c.toLocaleString(void 0,{maximumFractionDigits:2}):String(c)}function Ma(c,r){var k,T,S;const p=[];if(!c.rateLimits)return p;if(c.provider==="claude"){const y=c,Y=[{key:"fiveHour",label:r("terminal:usage.currentSession"),window:y.rateLimits.fiveHour},{key:"sevenDay",label:r("terminal:usage.currentWeekAll"),window:y.rateLimits.sevenDay},{key:"sevenDayOpus",label:r("terminal:usage.currentWeekOpus"),window:y.rateLimits.sevenDayOpus},{key:"sevenDaySonnet",label:r("terminal:usage.currentWeekSonnet"),window:y.rateLimits.sevenDaySonnet}];for(const _ of Y)_.window&&p.push({..._,window:_.window});return p}const h=c;return(k=h.rateLimits)!=null&&k.weekly&&p.push({key:"weekly",label:r("terminal:usage.weeklyLimit"),window:h.rateLimits.weekly}),(T=h.rateLimits)!=null&&T.monthly&&p.push({key:"monthly",label:r("terminal:usage.monthlyLimit"),window:h.rateLimits.monthly}),(S=h.rateLimits)!=null&&S.onDemand&&p.push({key:"onDemand",label:r("terminal:usage.onDemandLimit"),window:h.rateLimits.onDemand}),p}function Ta({agentId:c,contextSummary:r}){const{t:p}=Vt(["terminal","common"]),[h,k]=a.useState(()=>{var H;return((H=Ft.get(c))==null?void 0:H.snapshot)??null}),[T,S]=a.useState(!1),[y,Y]=a.useState(null),_=a.useRef(0);a.useEffect(()=>{const H=Ft.get(c);if(H&&Date.now()-H.fetchedAt<Ia){k(H.snapshot);return}const re=++_.current;S(!0),Y(null),Sn(c).then(P=>{re===_.current&&(Ft.set(c,{snapshot:P,fetchedAt:Date.now()}),k(P),S(!1))}).catch(P=>{re===_.current&&(Y(P.message||"Failed to load plan limits"),S(!1))})},[c]);const W=h?Ma(h,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&&!h&&e.jsxs("div",{className:"plan-limits-tooltip__muted",children:[p("common:status.loading"),"…"]}),!T&&y&&!h&&e.jsx("div",{className:"plan-limits-tooltip__muted",children:p("terminal:usage.limitsError",{message:y})}),W.length>0?e.jsx("div",{className:"plan-limits-tooltip__gauges",children:W.map(({key:H,label:re,window:P})=>{const Ee=Math.max(0,Math.min(100,P.utilization)),oe=En(Ee),ce=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:re}),e.jsx("span",{className:"plan-limits-tooltip__gauge-percent",style:{color:oe},children:p("terminal:usage.percentUsed",{percent:Math.round(Ee)})})]}),e.jsx("div",{className:"plan-limits-tooltip__bar",children:e.jsx("div",{className:"plan-limits-tooltip__bar-fill",style:{width:`${Ee}%`,background:oe}})}),e.jsxs("div",{className:"plan-limits-tooltip__reset",children:[p("terminal:usage.resets",{time:An(P.resetsAt)}),ce&&e.jsx("span",{style:{marginLeft:8},children:p("terminal:usage.creditsUsed",{used:sn(P.used),limit:sn(P.limit)})})]})]},H)})}):h&&!T&&e.jsx("div",{className:"plan-limits-tooltip__muted",children:h.rateLimitsError?p("terminal:usage.limitsError",{message:h.rateLimitsError}):h.cliHint})]})}function La({agentId:c,disabled:r,contextSummary:p,children:h}){return e.jsx(Nn,{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:h})}const Pa=a.memo(function({className:r=""}){const{t:p}=Vt(["common"]),[h,k]=In(),T=a.useRef(null),[S,y]=a.useState(null);a.useLayoutEffect(()=>{const _=T.current;if(!_)return;const W=_.querySelector(".view-mode-toggle__btn--active");W&&y({left:W.offsetLeft,width:W.offsetWidth})},[h]);const Y=a.useCallback(_=>{if(_!==h){if(typeof window<"u"&&window.dispatchEvent(new CustomEvent("tide:viewmode-switch-pressed",{detail:{mode:_}})),_==="3d"){requestAnimationFrame(()=>k(_));return}k(_)}},[h,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}}),Mn.map(_=>e.jsxs("button",{className:`view-mode-toggle__btn ${h===_?"view-mode-toggle__btn--active":""}`,onClick:()=>Y(_),title:p(`common:viewMode.descriptions.${_}`),children:[e.jsxs("span",{className:"view-mode-toggle__icon",children:[_==="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"})]}),_==="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"})]}),_==="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"})]}),_==="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.${_}`)})]},_))]})}),Nt=3,St=280,ln=320,Wt=240,rn=64,Ra=["simple","chat","advanced"],Da={simple:"Simple",chat:"Chat",advanced:"Advanced"},$a={simple:"○",chat:"◐",advanced:"◉"},za={simple:"Simple view — clean messages only",chat:"Chat view — assistant replies (no tool calls)",advanced:"Advanced view — everything including tools"},on="flat-clear-context",bn="tide:flat-embedded-panels";function _n(){try{const c=localStorage.getItem(bn),r=c?JSON.parse(c):{};return r&&typeof r=="object"?r:{}}catch{return{}}}function Ht(c,r){try{const p=_n();r?p[c]=r:delete p[c],localStorage.setItem(bn,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,y=S?an[S]:void 0;return{model:T,effort:y==null?void 0:y.label}}const r=c.model||"sonnet",p=ka[r],h=c.effort,k=h?an[h]: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,h=r.height/2;return c.x>=r.center.x-p&&c.x<=r.center.x+p&&c.z>=r.center.z-h&&c.z<=r.center.z+h}if(r.type==="circle"&&r.radius){const p=c.x-r.center.x,h=c.z-r.center.z;return p*p+h*h<=r.radius*r.radius}return!1}const Wa=Qn.memo(function({agentId:r,terminalViewMode:p,onTerminalViewModeChange:h,inspectorOpen:k,onToggleInspector:T,onShowTaskBoard:S,onImageClick:y,onFileClick:Y,onBashClick:_,onViewMarkdown:W,onRequestClearSubordinates:H,keyboard:re,canNavigateBack:P,canNavigateForward:Ee,onNavigateBack:oe,onNavigateForward:ce,agentInfoOpen:$e,onToggleAgentInfo:ot,onHeaderContextMenu:xe,onBuildingContextMenu:be}){var st,_t;const f=nn(r),O=mn(),Ie=ea(),ze=a.useRef(null),We=a.useRef(null),{displayedAgentId:Me,fadingOut:At}=ta(r),ct=nn(Me),He=!!Ie.interactiveMode&&((f==null?void 0:f.provider)??"claude")==="claude"&&!!(f!=null&&f.sessionId),[de,Ue]=a.useState(!1);a.useEffect(()=>{Ue(!1)},[r]),a.useEffect(()=>{!He&&de&&Ue(!1)},[He,de]),a.useEffect(()=>{const n=We.current;if(!n)return;const o=d=>{d.button===3?(d.preventDefault(),d.stopPropagation(),oe()):d.button===4&&(d.preventDefault(),d.stopPropagation(),ce())},i=d=>{(d.button===3||d.button===4)&&d.preventDefault()};return n.addEventListener("mouseup",o),n.addEventListener("mousedown",i),()=>{n.removeEventListener("mouseup",o),n.removeEventListener("mousedown",i)}},[oe,ce]),a.useEffect(()=>{const n=We.current;if(!n)return;let o=0,i=0,d=0;const z=250,le=600,R=80,De=1.5,Ze=D=>{let U=D instanceof HTMLElement?D:null;for(;U&&U!==n;){const vt=window.getComputedStyle(U).overflowX;if((vt==="auto"||vt==="scroll")&&U.scrollWidth>U.clientWidth)return!0;U=U.parentElement}return!1},wt=D=>{const U=Date.now();if(U<d){D.preventDefault();return}if(Math.abs(D.deltaX)<=Math.abs(D.deltaY)*De){o=0;return}if(Ze(D.target)){o=0;return}U-i>z&&(o=0),i=U,o+=D.deltaX,o<=-R?(o=0,d=U+le,D.preventDefault(),oe()):o>=R&&(o=0,d=U+le,D.preventDefault(),ce())};return n.addEventListener("wheel",wt,{passive:!1}),()=>n.removeEventListener("wheel",wt)},[oe,ce]);const Te=pn(),ue=a.useMemo(()=>{if(!f)return null;const n=new Set,o=[];for(const i of Te.values())i.archived||i.directories.length===0||i.assignedAgentIds.includes(r)&&(n.add(i.id),o.push(i));for(const i of Te.values())i.archived||i.directories.length===0||n.has(i.id)||Fa({x:f.position.x,z:f.position.z},i)&&(n.add(i.id),o.push(i));return o.length===0?null:o.flatMap(i=>i.directories.filter(d=>d&&d.trim().length>0).map(d=>({areaId:i.id,areaName:i.name,dir:d})))},[f,r,Te]),{branches:_e,fetchRemote:we,fetchingDirs:dt}=na(ue),Ve=a.useMemo(()=>{var i;const n=g.getAreaForAgent(r);if(!n)return[];const o=[];for(const d of O.values())d.type==="terminal"&&g.isPositionInArea(d.position,n)&&o.push({id:d.id,name:d.name,hasUrl:!!((i=d.terminalStatus)!=null&&i.url)});return o},[r,O]),ve=a.useMemo(()=>{var i;const n=g.getAreaForAgent(r);if(!n)return[];const o=[];for(const d of O.values())d.type==="server"&&((i=d.pm2)!=null&&i.enabled)&&g.isPositionInArea(d.position,n)&&o.push({id:d.id,name:d.name});return o},[r,O]),pe=a.useMemo(()=>{const n=g.getAreaForAgent(r);if(!n)return[];const o=[];for(const i of O.values())i.type==="database"&&i.database&&g.isPositionInArea(i.position,n)&&o.push({id:i.id,name:i.name});return o},[r,O]),Le=aa(),je=a.useMemo(()=>{const n=g.getAreaForAgent(r);if(!n)return[];const o=[];for(const i of O.values())if(i.type==="tests"&&g.isPositionInArea(i.position,n)){const d=!!i.folderPath&&Le.some(z=>sa(z,i.folderPath));o.push({id:i.id,name:i.name,working:d})}return o},[r,O,Le]),K=a.useMemo(()=>{const n=g.getAreaForAgent(r);if(!n)return[];const o=[];for(const i of O.values())i.type==="http"&&g.isPositionInArea(i.position,n)&&o.push({id:i.id,name:i.name});return o},[r,O]),[,Xe]=a.useReducer(n=>n+1,0),te=((st=ze.current)==null?void 0:st.search.searchMode)??!1,Pe=a.useCallback(()=>{var n;(n=ze.current)==null||n.search.toggleSearch(),Xe()},[]),ut=ia(),Qe=ut.isPending(on),[j,ne]=a.useState(null),Z=j?O.get(j.buildingId):null,[pt,Q]=a.useState(""),[et,Ge]=a.useState(()=>la()),B=a.useMemo(()=>{var n;return((n=g.getAreaForAgent(r))==null?void 0:n.id)??null},[r,O]),Ce=a.useCallback((n,o)=>{Q(""),ne(i=>{const d=(i==null?void 0:i.buildingId)===o?null:{type:n,buildingId:o};return B&&Ht(B,d),d})},[B]),ke=a.useCallback(()=>{Q(""),ne(null),B&&Ht(B,null)},[B]);a.useEffect(()=>{if((j==null?void 0:j.type)!=="pm2-logs")return;const n=j.buildingId;return g.startLogStreaming(n,200),()=>g.stopLogStreaming(n)},[j]);const{height:Et,onResizeStart:It}=ra(),{sidePanelWidth:Mt,handleSidePanelResizeStart:Tt}=oa(),[Oe,mt]=a.useState(()=>Ut(A.GIT_PANEL_OPEN,!1)),[ye,w]=a.useState(()=>Ut(A.BUILDINGS_PANEL_OPEN,!1)),[Be,ft]=a.useState(!1),Ne=a.useCallback(()=>{ft(n=>{const o=!n;return o&&ca.setEnabled(!0),o})},[]),ae=a.useCallback(()=>ft(!1),[]),qe=a.useCallback(()=>{mt(n=>{const o=!n;return ge(A.GIT_PANEL_OPEN,o),o})},[]),ht=a.useCallback(()=>{w(n=>{const o=!n;return ge(A.BUILDINGS_PANEL_OPEN,o),o})},[]),Lt=a.useCallback(()=>{mt(!1),ge(A.GIT_PANEL_OPEN,!1)},[]),Pt=a.useCallback(()=>{w(!1),ge(A.BUILDINGS_PANEL_OPEN,!1)},[]),Rt=da(),Re=a.useMemo(()=>({terminal:Ve,"pm2-logs":ve,database:pe,tests:je,http:K}),[Ve,ve,pe,je,K]);a.useEffect(()=>{if(!j)return;Re[j.type].some(o=>o.id===j.buildingId)||(Q(""),ne(null))},[j,Re]);const Ye=a.useRef(void 0);a.useEffect(()=>{var o;if(Ye.current===B)return;Ye.current=B;const n=B?_n()[B]:void 0;Q(""),n&&((o=Re[n.type])!=null&&o.some(i=>i.id===n.buildingId))?ne(n):ne(null)},[B,Re]),a.useEffect(()=>{const n=o=>{var z;const i=o.detail;if(!(i!=null&&i.buildingId)||!(i!=null&&i.type)||!((z=Re[i.type])!=null&&z.some(le=>le.id===i.buildingId)))return;i.handled=!0,Q("");const d={type:i.type,buildingId:i.buildingId};ne(d),B&&Ht(B,d)};return window.addEventListener("tide:dock-building-flat",n),()=>window.removeEventListener("tide:dock-building-flat",n)},[Re,B]);const[se,me]=a.useState(!1),fe=a.useRef(null);if(a.useEffect(()=>{if(!se)return;const n=o=>{fe.current&&!fe.current.contains(o.target)&&me(!1)};return document.addEventListener("mousedown",n),()=>document.removeEventListener("mousedown",n)},[se]),!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 Se=f.contextStats,J=!!Se,Ae=Se?Se.totalTokens:f.contextUsed||0,gt=Se?Se.contextWindow:f.contextLimit||(f.provider==="grok"?5e5:2e5),Dt=Se?Se.usedPercent:Math.round(Ae/gt*100),he=Math.max(0,Math.min(100,Dt)),tt=Math.round(he*10)/10,$t=Math.round((100-he)*10)/10,xt=he>=80?"#ff4a4a":he>=60?"#ff9e4a":he>=40?"#ffd700":"#4aff9e",nt=(Ae/1e3).toFixed(1),ee=(gt/1e3).toFixed(1),ie=f.cwd,at=ie?Oa(ie):null,Ke=((_t=f.subordinateIds)==null?void 0:_t.length)||0,bt=Ke>0;return e.jsxs("div",{ref:We,className:`flat-terminal-wrapper ${Oe||ye||Be?"flat-terminal-wrapper--with-side-panel":""} ${At?"pane-fading-out":""}`,style:{"--guake-side-panel-width":`min(${Mt}px, 70%)`},children:[e.jsxs("div",{className:"flat-terminal-wrapper__header",children:[e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__header-main ${$e?"flat-terminal-wrapper__header-main--active":""}`,onClick:ot,onContextMenu:n=>{n.preventDefault(),n.stopPropagation(),xe({x:n.clientX,y:n.clientY})},title:$e?"Hide agent info":"Show agent info","aria-pressed":$e,children:[e.jsx(fn,{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:xn(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:gn(f.provider,"/"),alt:f.provider,className:"flat-terminal-wrapper__header-provider-icon",title:hn(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 ${!de&&p===n?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>{Ue(!1),h(n)},title:za[n],"aria-pressed":!de&&p===n,children:[e.jsx("span",{className:"flat-terminal-wrapper__view-mode-icon","aria-hidden":"true",children:$a[n]}),e.jsx("span",{className:"flat-terminal-wrapper__view-mode-label",children:Da[n]})]},n)),He&&e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__view-mode-btn ${de?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>Ue(n=>!n),title:"Classic TUI — attach to the live interactive claude session in a terminal","aria-pressed":de,children:[e.jsx("span",{className:"flat-terminal-wrapper__view-mode-icon","aria-hidden":"true",children:e.jsx(m,{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:oe,disabled:!P,title:"Back to previous agent","aria-label":"Back to previous agent",children:e.jsx(m,{name:"arrow-left",size:14})}),e.jsx("button",{type:"button",className:"flat-terminal-wrapper__action-btn",onClick:ce,disabled:!Ee,title:"Forward to next agent","aria-label":"Forward to next agent",children:e.jsx(m,{name:"arrow-right",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${te?"flat-terminal-wrapper__action-btn--active":""}`,onClick:Pe,title:te?"Close search":"Search messages","aria-pressed":te,children:e.jsx(m,{name:te?"cross":"search",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn flat-terminal-wrapper__action-btn--danger ${Qe?"flat-terminal-wrapper__action-btn--confirm":""}`,onClick:()=>ut.handleClick(on,()=>{var n;g.clearContext(r),(n=ze.current)==null||n.historyLoader.clearHistory()}),title:Qe?"Click again to confirm clear context":"Clear context",children:e.jsx(m,{name:Qe?"question":"clear",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${Oe?"flat-terminal-wrapper__action-btn--active":""}`,onClick:qe,title:Oe?"Hide git panel":"Show git changes","aria-pressed":Oe,children:e.jsx(m,{name:"git-branch",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${ye?"flat-terminal-wrapper__action-btn--active":""}`,onClick:ht,title:ye?"Hide buildings panel":"Show area buildings","aria-pressed":ye,children:e.jsx(m,{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 ${se?"flat-terminal-wrapper__action-btn--active":""}`,onClick:()=>me(n=>!n),title:"More actions","aria-expanded":se,children:"⋮"}),se&&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 ${Be?"flat-terminal-wrapper__more-item--active":""}`,onClick:()=>{Ne(),me(!1)},title:Be?"Hide Debug Panel":"Show Debug Panel",children:[e.jsx(m,{name:"bug",size:14}),e.jsx("span",{children:Be?"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:()=>{g.collapseContext(r),me(!1)},disabled:f.status!=="idle",title:f.status!=="idle"?"Agent must be idle to collapse context":"Collapse context",children:[e.jsx(m,{name:"package",size:14}),e.jsx("span",{children:"Collapse context"})]}),bt&&e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{H(r,Ke),me(!1)},children:[e.jsx(m,{name:"crown",size:14}),e.jsxs("span",{children:["Clear ",Ke," subordinate",Ke===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:()=>{g.killAgent(r),me(!1)},children:[e.jsx(m,{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:()=>g.deselectAll(),title:"Close chat","aria-label":"Close chat",children:e.jsx(m,{name:"cross",size:14})})]})]}),e.jsx(ua,{agent:f,onClick:S}),de&&He?e.jsx(Ea,{agentId:r}):Me&&ct?e.jsx(pa,{ref:ze,agentId:Me,agent:ct,viewMode:p,isOpen:!0,onImageClick:y,onFileClick:Y,onBashClick:_,onViewMarkdown:W,keyboard:re,hasModalOpen:!1},Me):null,j&&Z&&(()=>{var z,le;const n=j.type,o={terminal:"terminal","pm2-logs":"scroll",database:"hard-drives",tests:"flask",http:"globe"},i=n==="terminal"&&!((z=Z.terminalStatus)!=null&&z.url),d=!i;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"guake-bottom-terminal-resize",onMouseDown:It,role:"separator","aria-orientation":"horizontal","aria-label":"Resize embedded panel"}),e.jsxs("div",{className:"flat-bottom-panel",role:"region","aria-label":`${Z.name} panel`,style:{height:Et},children:[e.jsxs("div",{className:"flat-bottom-panel__header",children:[e.jsxs("span",{className:"flat-bottom-panel__title",children:[e.jsx(m,{name:o[n],size:12}),e.jsx("span",{children:Z.name}),i&&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:pt,onChange:R=>Q(R.target.value),placeholder:"Filter logs","aria-label":`Filter logs for ${Z.name}`,spellCheck:!1}),e.jsx("select",{className:"guake-bottom-terminal-retention",value:et===null?"unlimited":String(et),onChange:R=>{const De=R.target.value==="unlimited"?null:Number(R.target.value);Ge(De),fa(De)},"aria-label":`Max log retention for ${Z.name}`,children:ma.map(R=>e.jsx("option",{value:R===null?"unlimited":String(R),children:R===null?"Unlimited":`${R.toLocaleString()} lines`},R===null?"unlimited":R))}),e.jsx("button",{type:"button",className:"flat-bottom-panel__close",onClick:()=>g.clearStreamingLogs(j.buildingId),title:"Clear logs",children:e.jsx(m,{name:"trash",size:12})}),e.jsx("button",{type:"button",className:"flat-bottom-panel__close",onClick:()=>g.sendBuildingCommand(j.buildingId,"restart"),title:"Restart",children:e.jsx(m,{name:"restart",size:12})})]}),d&&e.jsx("button",{type:"button",className:"flat-bottom-panel__close",onClick:()=>{ke(),Je(j.buildingId)},title:"Maximize — open as modal","aria-label":"Open as modal",children:e.jsx(m,{name:"fullscreen",size:12})}),e.jsx("button",{type:"button",className:"flat-bottom-panel__close",onClick:ke,title:"Close panel","aria-label":"Close panel",children:e.jsx(m,{name:"cross",size:12})})]})]}),e.jsx("div",{className:"flat-bottom-panel__body",children:n==="terminal"?(le=Z.terminalStatus)!=null&&le.url?e.jsx(un,{terminalUrl:Z.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:pt,maxRetention:et}):n==="database"?e.jsx(ga,{building:Z}):n==="tests"?e.jsx("div",{className:"tests-panel-host",children:e.jsx(xa,{building:Z,autoFocusSearch:!1})}):e.jsx("div",{className:"http-requests-panel-host",children:e.jsx(ba,{building:Z,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(m,{name:"refresh",size:12}),e.jsx("span",{children:"Reattaching"})]}),ie&&at&&e.jsxs("span",{className:"flat-terminal-wrapper__cwd",title:`Open in file explorer: ${ie}`,"aria-label":`Open ${ie} in file explorer`,role:"button",tabIndex:0,onClick:()=>g.openFileExplorer(ie),onKeyDown:n=>{(n.key==="Enter"||n.key===" ")&&(n.preventDefault(),g.openFileExplorer(ie))},children:[e.jsx("span",{className:"flat-terminal-wrapper__cwd-icon",children:e.jsx(m,{name:"folder",size:12})}),e.jsx("span",{className:"flat-terminal-wrapper__cwd-text",children:at})]}),ue&&ue.map(({areaId:n,areaName:o,dir:i})=>{const d=_e.get(i),z=dt.has(i),le=i.split("/").filter(Boolean).pop()||i;return e.jsxs("span",{className:"flat-terminal-wrapper__area-dir",title:`${o}: ${i}${d?` (${d.branch}${d.ahead?` ↑${d.ahead}`:""}${d.behind?` ↓${d.behind}`:""})`:""}`,onClick:()=>g.openFileExplorerForAreaFolder(n,i),children:[e.jsx(m,{name:"folder-open",size:12}),e.jsx("span",{className:"flat-terminal-wrapper__area-dir-name",children:le}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flat-terminal-wrapper__area-dir-branch",children:[e.jsx(m,{name:"git-branch",size:10})," ",d.branch]}),d.ahead>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-ahead",title:`${d.ahead} ahead`,children:[e.jsx(m,{name:"arrow-up",size:9}),d.ahead]}),d.behind>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-behind",title:`${d.behind} behind`,children:[e.jsx(m,{name:"arrow-down",size:9}),d.behind]}),e.jsx("span",{className:`flat-terminal-wrapper__area-fetch ${z?"flat-terminal-wrapper__area-fetch--fetching":""}`,title:"Git fetch",onClick:R=>{R.stopPropagation(),we(i)},children:e.jsx(m,{name:z?"hourglass":"download",size:12})})]})]},`${n}:${i}`)}),e.jsx(La,{agentId:r,disabled:((f==null?void 0:f.provider)??"claude")!=="claude"&&((f==null?void 0:f.provider)??"claude")!=="grok",contextSummary:J?`Context: ${nt}k / ${ee}k tokens (${tt}% used)`:void 0,children:e.jsxs("span",{className:"flat-terminal-wrapper__context",tabIndex:0,role:"button",onClick:()=>g.setContextModalAgentId(r),onKeyDown:n=>{(n.key==="Enter"||n.key===" ")&&(n.preventDefault(),g.setContextModalAgentId(r))},title:((f==null?void 0:f.provider)??"claude")!=="claude"&&((f==null?void 0:f.provider)??"claude")!=="grok"?J?`Context usage: ${nt}k / ${ee}k tokens (${tt}% 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(m,{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:`${he}%`,backgroundColor:xt}})}),e.jsxs("span",{className:"flat-terminal-wrapper__context-tokens",style:{color:xt},children:[nt,"k/",ee,"k"]}),e.jsxs("span",{className:"flat-terminal-wrapper__context-free",children:["(",$t,"% free)"]}),!J&&e.jsx("span",{className:"flat-terminal-wrapper__context-warning",title:"No context stats yet",children:e.jsx(m,{name:"warn",size:12})})]})}),e.jsx("div",{className:"flat-terminal-wrapper__statusbar-spacer","aria-hidden":"true"}),Ve.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area terminals",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":""} ${n.hasUrl?"":"flat-terminal-wrapper__building-btn--offline"}`,title:`${o?"Hide":"Show"} terminal: ${n.name}${n.hasUrl?"":" (starting...)"}`,onClick:()=>{if(o){ke();return}if(n.hasUrl&&lt(n.id)==="modal"){Je(n.id);return}n.hasUrl||g.sendBuildingCommand(n.id,"start"),Ce("terminal",n.id)},onContextMenu:i=>{i.preventDefault(),i.stopPropagation(),be(n.id,{x:i.clientX,y:i.clientY})},children:e.jsx(m,{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?ke():lt(n.id)==="modal"?Je(n.id):Ce("pm2-logs",n.id)},onContextMenu:i=>{i.preventDefault(),i.stopPropagation(),be(n.id,{x:i.clientX,y:i.clientY})},children:e.jsx(m,{name:"scroll",size:14})},n.id)})}),pe.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area databases",children:pe.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?ke():lt(n.id)==="modal"?Je(n.id):Ce("database",n.id)},onContextMenu:i=>{i.preventDefault(),i.stopPropagation(),be(n.id,{x:i.clientX,y:i.clientY})},children:e.jsx(m,{name:"hard-drives",size:14})},n.id)})}),je.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area tests",children:je.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?ke():lt(n.id)==="modal"?Je(n.id):Ce("tests",n.id)},onContextMenu:i=>{i.preventDefault(),i.stopPropagation(),be(n.id,{x:i.clientX,y:i.clientY})},children:e.jsx(m,{name:"flask",size:14})},n.id)})}),K.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area HTTP requests",children:K.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?ke():lt(n.id)==="modal"?Je(n.id):Ce("http",n.id)},onContextMenu:i=>{i.preventDefault(),i.stopPropagation(),be(n.id,{x:i.clientX,y:i.clientY})},children:e.jsx(m,{name:"globe",size:14})},n.id)})}),e.jsx("div",{className:"flat-terminal-wrapper__theme",children:e.jsx(_a,{})})]}),Oe&&e.jsx(wa,{agentId:r,agents:Rt,onClose:Lt,branchInfoMap:_e,fetchRemote:we,fetchingDirs:dt,onResizeStart:n=>Tt(n,"right")}),ye&&e.jsx(va,{agentId:r,onClose:Pt}),Be&&e.jsx(ja,{agentId:r,onClose:ae})]})}),Ha={groups:[],gridCols:1,gridRows:1,positions:new Map};function qa({onAgentClick:c,onBuildingClick:r,onBuildingDoubleClick:p,onBuildingPopup:h,onAreaContextMenu:k,onOpenSpawnModal:T,onOpenBossSpawnModal:S,onOpenAreaModal:y}){const{t:Y}=Vt(["common"]),_=Tn(),W=Ln(),[H,re]=a.useState(null),[P,Ee]=a.useState(null),[oe,ce]=a.useState(null);Pn("flatview-image-modal",H!==null,()=>re(null));const[$e,ot]=a.useState(null),[xe,be]=a.useState(null),[f,O]=a.useState(null),[Ie,ze]=a.useState(null),[We,Me]=a.useState(!1),At=a.useCallback(()=>{Me(t=>!t)},[]),ct=a.useCallback(()=>{Me(!1)},[]),[He,de]=a.useState(()=>{const t=Kt(A.VIEW_MODE);return t==="simple"||t==="chat"||t==="advanced"?t:"simple"}),Ue=a.useCallback(t=>{de(t),Zt(A.VIEW_MODE,t)},[]);a.useEffect(()=>{const t=s=>{if(s.key!==A.VIEW_MODE)return;const l=s.newValue;(l==="simple"||l==="chat"||l==="advanced")&&de(l)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);const[Te,ue]=a.useState(()=>Ut(A.FLAT_INSPECTOR_OPEN,!1)),[_e,we]=a.useState(!1),dt=a.useCallback(()=>we(t=>!t),[]),Ve=a.useCallback(()=>we(!1),[]);a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-agents-drawer-state",{detail:{open:_e}}))},[_e]),a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-inspector-state",{detail:{open:Te}}))},[Te]),a.useEffect(()=>{const t=()=>we(C=>!C),s=()=>{ue(C=>{const E=!C;return ge(A.FLAT_INSPECTOR_OPEN,E),E})},l=()=>{we(!1),ue(!1),ge(A.FLAT_INSPECTOR_OPEN,!1)},x=()=>we(!1),b=()=>{ue(!1),ge(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",l),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",l),window.removeEventListener("tide-close-flat-agents-drawer-only",x),window.removeEventListener("tide-close-flat-inspector-only",b)}},[]);const ve=a.useRef(null),pe=a.useRef(null),[Le,je]=a.useState(()=>{const t=Jt(A.FLAT_MIDDLE_WIDTH,0);return t>=St?t:null}),[K,Xe]=a.useState(()=>{const t=Jt(A.FLAT_INSPECTOR_WIDTH,0);return t>=Wt?t:null}),te=a.useCallback(t=>{if(typeof window>"u")return t;const s=K!==null?Nt+K:0,l=window.innerWidth-rn-Nt-ln-s;return Math.max(St,Math.min(Math.max(l,St),t))},[K]),Pe=a.useCallback(t=>{var b;if(typeof window>"u")return t;const s=(b=ve.current)==null?void 0:b.querySelector(".flat-middle"),l=(s==null?void 0:s.getBoundingClientRect().width)??St,x=window.innerWidth-rn-l-Nt-ln-Nt;return Math.max(Wt,Math.min(Math.max(x,Wt),t))},[]);a.useEffect(()=>{if(Le===null&&K===null)return;const t=()=>{je(s=>{if(s===null)return s;const l=te(s);return l===s?s:l}),Xe(s=>{if(s===null)return s;const l=Pe(s);return l===s?s:l})};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[Le,K,te,Pe]);const ut=a.useCallback(t=>{var l;if(t.button!==0)return;const s=(l=ve.current)==null?void 0:l.querySelector(".flat-middle");s&&(t.currentTarget.setPointerCapture(t.pointerId),pe.current={kind:"middle",startX:t.clientX,startWidth:s.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),Qe=a.useCallback(t=>{var l;if(t.button!==0)return;const s=(l=ve.current)==null?void 0:l.querySelector(".flat-inspector");s&&(t.currentTarget.setPointerCapture(t.pointerId),pe.current={kind:"inspector",startX:t.clientX,startWidth:s.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),j=a.useCallback(t=>{const s=pe.current;if(!s||t.pointerId!==s.pointerId)return;const l=t.clientX-s.startX;s.kind==="middle"?je(te(s.startWidth+l)):Xe(Pe(s.startWidth-l))},[te,Pe]),ne=a.useCallback(t=>{const s=pe.current;if(!s||t.pointerId!==s.pointerId)return;try{t.currentTarget.releasePointerCapture(t.pointerId)}catch{}if(pe.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=te(s.startWidth+x);je(b),yt(A.FLAT_MIDDLE_WIDTH,b)}else{const b=Pe(s.startWidth-x);Xe(b),yt(A.FLAT_INSPECTOR_WIDTH,b)}},[te,Pe]),Z=a.useCallback(()=>{je(null),yt(A.FLAT_MIDDLE_WIDTH,0)},[]),pt=a.useCallback(()=>{Xe(null),yt(A.FLAT_INSPECTOR_WIDTH,0)},[]),[Q,et]=a.useState(()=>Kt(A.FLAT_INSPECTOR_VIEW)==="tracking"?"tracking":"agent"),Ge=a.useCallback(t=>{et(t),Zt(A.FLAT_INSPECTOR_VIEW,t)},[]),B=a.useCallback(()=>{ue(t=>{const s=!t;return ge(A.FLAT_INSPECTOR_OPEN,s),s})},[]),Ce=a.useCallback(()=>{ue(!1),ge(A.FLAT_INSPECTOR_OPEN,!1)},[]),ke=a.useCallback(()=>{Ge("tracking"),ue(!0),ge(A.FLAT_INSPECTOR_OPEN,!0)},[Ge]),Et=Rn(),It=a.useCallback((t,s)=>{re({url:t,name:s})},[]),Mt=a.useCallback((t,s)=>{Ee({command:t,output:s,isLive:!1})},[]),Tt=a.useCallback((t,s)=>{var b;const l=W.size>0?Array.from(W)[0]:null,x=l?(b=g.getState().agents.get(l))==null?void 0:b.cwd:void 0;g.setFileViewerPath(t,s,x)},[W]),Oe=a.useCallback(t=>{ce(t)},[]),mt=a.useCallback((t,s)=>{ot({agentId:t,count:s})},[]),ye=a.useCallback(t=>{p?p(t):r(t)},[r,p]),w=a.useMemo(()=>W.size>0?Array.from(W)[0]:null,[W]),Be=a.useCallback(t=>{w&&be({agentId:w,position:t})},[w]),ft=a.useCallback((t,s)=>{O({buildingId:t,position:s})},[]);a.useEffect(()=>{Me(!1)},[w]);const Ne=a.useRef([]),ae=a.useRef(-1),qe=a.useRef(!1),ht=a.useRef(null),[Lt,Pt]=a.useState(!1),[Rt,Re]=a.useState(!1),Ye=a.useRef(!1),se=a.useRef(null),me=a.useRef(!1),fe=a.useMemo(()=>new Set(_.map(t=>t.id)),[_]),Se=a.useMemo(()=>{const t=new Map(_.map(l=>[l.id,l])),s=new Map;for(const l of _)if((l.isBoss||l.class==="boss")&&l.subordinateIds&&l.subordinateIds.length>0){const x=l.subordinateIds.map(b=>t.get(b)).filter(b=>b!==void 0);x.length>0&&s.set(l.id,x)}return s},[_]),J=a.useCallback(()=>{const t=Ne.current,s=ae.current;Pt(s>0),Re(s>=0&&s<t.length-1)},[]),Ae=a.useCallback(t=>{const s=Ne.current;if(s.length===0)return;let l=ae.current+t;for(;l>=0&&l<s.length;){const x=s[l];if(fe.has(x)){qe.current=!0,ae.current=l,J(),g.selectAgent(x);return}l+=t}},[fe,J]),gt=a.useCallback(()=>Ae(-1),[Ae]),Dt=a.useCallback(()=>Ae(1),[Ae]);Na(a.useCallback(()=>{const t=Ne.current,s=ae.current;return t.length>0&&s>0?(Ae(-1),"handled"):"exit"},[Ae]));const he=a.useCallback((t,s)=>{if(typeof window>"u")return;const l=window.history.state,b={...typeof l=="object"&&l!==null?l:{},__flatAgentNav:{agentId:t}};s==="replace"?window.history.replaceState(b,"",window.location.href):window.history.pushState(b,"",window.location.href)},[]);a.useEffect(()=>{if(!w){Ye.current=!1,se.current=null;return}if(!Ye.current){he(w,"replace"),Ye.current=!0,se.current=w;return}if(me.current){me.current=!1,se.current=w;return}se.current!==w&&(he(w,"push"),se.current=w)},[w,he]),a.useEffect(()=>{const t=s=>{var C,E;const l=(E=(C=s.state)==null?void 0:C.__flatAgentNav)==null?void 0:E.agentId;if(!l||typeof l!="string"||!fe.has(l)||l===w)return;me.current=!0,qe.current=!0;const x=Ne.current,b=x.lastIndexOf(l);b>=0?ae.current=b:(x.push(l),ae.current=x.length-1),J(),g.selectAgent(l)};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[fe,w,J]),a.useEffect(()=>{if(!w){Ne.current=[],ae.current=-1,J();return}if(ht.current=w,qe.current){qe.current=!1,J();return}const t=Ne.current,s=ae.current;if(s>=0&&t[s]===w){J();return}const l=s<t.length-1?t.slice(0,s+1):t.slice();l.push(w),l.length>100&&l.shift(),Ne.current=l,ae.current=l.length-1,J()},[w,J]);const tt=a.useCallback(t=>{c(t),we(!1)},[c]),$t=w??"",xt=a.useCallback(()=>{},[]),nt=a.useCallback(t=>{tt(t)},[tt]),ee=Te,[ie,at]=a.useState(ee),[Ke,bt]=a.useState(ee);a.useEffect(()=>{if(ee){at(!0);return}bt(!1);const t=setTimeout(()=>at(!1),240);return()=>clearTimeout(t)},[ee]),a.useEffect(()=>{if(!ie||!ee)return;let t=0;const s=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>bt(!0))});return()=>{cancelAnimationFrame(s),cancelAnimationFrame(t)}},[ie,ee]);const st=a.useRef(null);a.useEffect(()=>{if(w)return;const t=s=>{if(s.key!==" "&&s.key!=="Backspace")return;const l=s.target;if(l.tagName==="INPUT"||l.tagName==="TEXTAREA"||l.isContentEditable)return;const x=ht.current;!x||!fe.has(x)||(s.preventDefault(),g.selectAgent(x))};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[w,fe]);const[_t,n]=a.useState(new Set),o=a.useCallback(t=>{n(s=>{const l=new Set(s);return l.has(t)?l.delete(t):l.add(t),l})},[]),[i,d]=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=l=>d(l.matches);return t.addEventListener("change",s),()=>t.removeEventListener("change",s)},[]);const[z,le]=a.useState(null),R=a.useCallback(t=>{le(s=>s===t?null:t)},[]),De=pn(),Ze=mn(),[wt]=Dn(),D=a.useMemo(()=>{if(w)return Ha;const t=new Map,s=[];for(const v of _){const M=g.getAreaForAgent(v.id);if(!Qt((M==null?void 0:M.id)??null))continue;if(!M||M.archived){s.push(v);continue}const L=t.get(M.id);L?L.push(v):t.set(M.id,[v])}const l=new Map,x=[];for(const v of Ze.values()){let M=!1;for(const L of De.values())if(!L.archived&&en(L.id)&&g.isPositionInArea(v.position,L)){const X=l.get(L.id);X?X.push(v):l.set(L.id,[v]),M=!0;break}!M&&Qt(null)&&x.push(v)}const b=[];for(const[,v]of De){if(v.archived||!en(v.id))continue;const M=t.get(v.id),L=l.get(v.id)??[];(M&&M.length>0||L.length>0)&&b.push({area:v,agents:M??[],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 u=1,I=1;const V=new Map;if(C.length>1){let v=1/0,M=-1/0,L=1/0,X=-1/0;for(const G of C)v=Math.min(v,G.area.center.x),M=Math.max(M,G.area.center.x),L=Math.min(L,G.area.center.z),X=Math.max(X,G.area.center.z);const jt=M-v||1,Ct=X-L||1;if(C.length<=4){u=C.length,I=1;const G=[...C].sort((q,zt)=>q.area.center.x-zt.area.center.x);for(let q=0;q<G.length;q++)V.set(G[q].area.id,{row:1,col:q+1})}else{const G=[...C].sort((N,F)=>N.area.center.x-F.area.center.x),q=[];for(let N=1;N<G.length;N++)q.push(G[N].area.center.x-G[N-1].area.center.x);const zt=q.reduce((N,F)=>N+F,0)/q.length||1;let Xt=1;for(const N of q)N>zt*1.3&&Xt++;u=Math.max(2,Math.min(Xt,C.length));const Ot=[...C].sort((N,F)=>N.area.center.z-F.area.center.z),kt=[];for(let N=1;N<Ot.length;N++)kt.push(Ot[N].area.center.z-Ot[N-1].area.center.z);const vn=kt.reduce((N,F)=>N+F,0)/kt.length||1;let Gt=1;for(const N of kt)N>vn*1.3&&Gt++;I=Math.max(2,Math.min(Gt,C.length)),u=Math.max(u,Math.ceil(C.length/I)),I=Math.max(I,Math.ceil(C.length/u));const jn=jt/u,Cn=Ct/I,Bt=new Set;for(const N of C){let F=Math.min(u-1,Math.max(0,Math.floor((N.area.center.x-v)/jn))),Fe=Math.min(I-1,Math.max(0,Math.floor((N.area.center.z-L)/Cn))),it=`${Fe},${F}`,qt=0;const kn=I*u;for(;Bt.has(it)&&qt<kn;)F++,F>=u&&(F=0,Fe=(Fe+1)%I),it=`${Fe},${F}`,qt++;Bt.has(it)&&(Fe=I,F=0,it=`${Fe},${F}`,I++),Bt.add(it),V.set(N.area.id,{row:Fe+1,col:F+1})}}}const $=v=>{v.sort((M,L)=>{var jt,Ct,G,q;const X=(((jt=M.position)==null?void 0:jt.z)??0)-(((Ct=L.position)==null?void 0:Ct.z)??0);return X!==0?X:(((G=M.position)==null?void 0:G.x)??0)-(((q=L.position)==null?void 0:q.x)??0)})};for(const v of C)$(v.agents);for(const v of E)$(v.agents);return{groups:[...C,...E],gridCols:u,gridRows:I,positions:V}},[_,De,Ze,wt,w]),U=a.useMemo(()=>{if(!xe)return[];const t=_.find(s=>s.id===xe.agentId);return t?[{id:"edit-agent",label:"Edit Agent",icon:e.jsx(m,{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(m,{name:"chat",size:14}),onClick:()=>c(t.id)},{id:"clone-agent",label:"Clone Agent",icon:e.jsx(m,{name:"clipboard",size:14}),onClick:()=>g.cloneAgent(t.id)},{id:"fork-agent",label:"Fork Agent (with history)",icon:e.jsx(m,{name:"git-branch",size:14}),onClick:()=>g.forkAgent(t.id)},{id:"delete-agent",label:"Delete Agent",icon:e.jsx(m,{name:"trash",size:14}),danger:!0,onClick:()=>{ze({agentId:t.id,name:t.name})}}]:[]},[xe,_,c]),vt=a.useMemo(()=>{var C;if(!f)return[];const t=Ze.get(f.buildingId);if(!t)return[];const s=[],l=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(m,{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:()=>ye(t.id)}),l&&(x||s.push({id:"start",label:"Start",icon:e.jsx(m,{name:"play",size:14}),onClick:()=>g.sendBuildingCommand(t.id,"start")}),x&&(s.push({id:"restart",label:"Restart",icon:e.jsx(m,{name:"refresh",size:14}),onClick:()=>g.sendBuildingCommand(t.id,"restart")}),s.push({id:"stop",label:"Stop",icon:e.jsx(m,{name:"stop",size:14}),onClick:()=>g.sendBuildingCommand(t.id,"stop")}))),b&&t.subordinateBuildingIds&&t.subordinateBuildingIds.length>0&&(s.push({id:"start-all",label:"Start All Subordinates",icon:e.jsx(m,{name:"launch",size:14}),onClick:()=>{for(const E of t.subordinateBuildingIds)g.sendBuildingCommand(E,"start")}}),s.push({id:"stop-all",label:"Stop All Subordinates",icon:e.jsx(m,{name:"pause",size:14}),onClick:()=>{for(const E of t.subordinateBuildingIds)g.sendBuildingCommand(E,"stop")}}),s.push({id:"restart-all",label:"Restart All Subordinates",icon:e.jsx(m,{name:"restart",size:14}),onClick:()=>{for(const E of t.subordinateBuildingIds)g.sendBuildingCommand(E,"restart")}})),l&&s.push({id:"health-check",label:"Health Check",icon:e.jsx(m,{name:"health",size:14}),onClick:()=>g.sendBuildingCommand(t.id,"healthCheck")}),s.push({id:"divider-edit",label:"",divider:!0,onClick:()=>{}}),s.push({id:"edit",label:"Edit Building",icon:e.jsx(m,{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(m,{name:"copy",size:14}),onClick:()=>{g.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(m,{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(m,{name:"trash",size:14}),danger:!0,onClick:()=>g.deleteBuilding(t.id)}),s},[f,Ze,ye]),wn=a.useCallback(t=>{const s=new Set(D.groups.map(l=>l.area.id));s.delete(t),n(s),requestAnimationFrame(()=>{const l=st.current;if(!l)return;const x=l.querySelector(`[data-area-id="${t}"]`);if(!x)return;const b=l.getBoundingClientRect(),E=x.getBoundingClientRect().top-b.top+l.scrollTop-8;l.scrollTo({top:Math.max(0,E),behavior:"smooth"})})},[D]);return e.jsxs("div",{ref:ve,className:`flat-view ${ee?"flat-view--with-inspector":""} ${w?"flat-view--has-chat":""} ${_e?"flat-view--mobile-sidebar-open":""}`,style:(()=>{if(Le===null&&K===null)return;const t={};return Le!==null&&(t["--flat-middle-width"]=`${Le}px`),K!==null&&(t["--flat-inspector-width"]=`${K}px`),t})(),children:[_e&&e.jsx("div",{className:"flat-mobile-sidebar-backdrop",onClick:Ve,"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:y,title:"Create new area",children:"+ Area"})]})}),e.jsx("div",{className:"flat-middle__content",children:e.jsx($n,{activeAgentId:$t,onClose:xt,onSelectAgent:nt,collapsedAreas:_t,onToggleArea:o,agentListRef:st})})]}),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:ut,onPointerMove:j,onPointerUp:ne,onPointerCancel:ne,onDoubleClick:Z}),e.jsxs("div",{className:"flat-right",children:[e.jsxs("button",{type:"button",className:"flat-mobile-sidebar-toggle","aria-label":_e?"Close agents sidebar":"Open agents sidebar","aria-expanded":_e,onClick:dt,children:[e.jsx(m,{name:"list",size:18}),e.jsx("span",{className:"flat-mobile-sidebar-toggle__label",children:"Agents"})]}),w?e.jsx(Wa,{agentId:w,terminalViewMode:He,onTerminalViewModeChange:Ue,inspectorOpen:Te,onToggleInspector:B,onShowTaskBoard:ke,onImageClick:It,onFileClick:Tt,onBashClick:Mt,onViewMarkdown:Oe,onRequestClearSubordinates:mt,keyboard:Et,canNavigateBack:Lt,canNavigateForward:Rt,onNavigateBack:gt,onNavigateForward:Dt,agentInfoOpen:We,onToggleAgentInfo:At,onHeaderContextMenu:Be,onBuildingContextMenu:ft}):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(${D.gridCols}, 1fr)`},children:D.groups.length===0?e.jsx("div",{className:"flat-map__empty",children:e.jsx("span",{children:"No areas or agents yet"})}):(()=>{var s;const t=i&&z?((s=D.positions.get(z))==null?void 0:s.row)??null:null;return D.groups.map(l=>{var E;const x=l.area.id,b=D.positions.get(x),C=i&&z!==x;return i&&t!=null&&(b==null?void 0:b.row)===t&&x!==z?null:e.jsxs("div",{className:`flat-map-area-card${C?" flat-map-area-card--collapsed":""}`,style:{"--area-color":l.area.color,gridRow:b==null?void 0:b.row,gridColumn:b==null?void 0:b.col},onContextMenu:u=>{k&&(u.preventDefault(),u.stopPropagation(),k(x,{x:u.clientX,y:u.clientY}))},children:[((E=l.area.logo)==null?void 0:E.filename)&&e.jsx("img",{className:"flat-map-area-card__logo",src:ya(l.area.logo.filename),alt:"","aria-hidden":"true",onError:u=>{u.currentTarget.style.display="none"}}),e.jsxs("button",{type:"button",className:"flat-map-area-card__header",onClick:()=>i?R(x):wn(x),title:i?C?`Expand ${l.area.name}`:`Collapse ${l.area.name}`:`Focus ${l.area.name} in left panel`,"aria-expanded":i?!C:void 0,children:[e.jsx("span",{className:"flat-map-area-card__color",style:{background:l.area.color}}),e.jsx("span",{className:"flat-map-area-card__name",children:l.area.name}),e.jsx("span",{className:"flat-map-area-card__count",children:l.agents.length}),i&&e.jsx(m,{name:C?"caret-down":"caret-up",size:11,className:"flat-map-area-card__caret"})]}),e.jsx("div",{className:"flat-map-area-card__agents",children:l.agents.map(u=>{const I=u.isBoss||u.class==="boss",V=I?Se.get(u.id):void 0,$=zn(u),v=$.usedPercent>=80?"#ff4a4a":$.usedPercent>=60?"#ff9e4a":$.usedPercent>=40?"#ffd700":"#4aff9e",M=`Context: ${($.totalTokens/1e3).toFixed(1)}k / ${($.contextWindow/1e3).toFixed(1)}k (${$.usedPercent}% used, ${$.freePercent}% free)`,L=u.latestTodos&&u.latestTodos.length>0||V&&V.length>0;return e.jsx(On,{todos:u.latestTodos,subordinates:V,position:"top",children:e.jsxs("button",{type:"button",className:`flat-map-agent-chip ${u.status}`,onClick:()=>c(u.id),onContextMenu:X=>{X.preventDefault(),X.stopPropagation(),be({agentId:u.id,position:{x:X.clientX,y:X.clientY}})},title:L?void 0:`${I?"Boss · ":""}Open chat with ${u.name}
2
- ${M}`,children:[e.jsx(fn,{agent:u,size:16}),I&&e.jsx("span",{className:"flat-map-agent-chip__crown","aria-hidden":"true",children:e.jsx(m,{name:"crown",size:11,color:"#ffd700",weight:"fill"})}),e.jsx("span",{className:"flat-map-agent-chip__name",children:u.name}),e.jsx("img",{src:gn(u.provider,"/"),alt:u.provider,className:"flat-map-agent-chip__provider-icon",title:hn(u.provider)}),e.jsx("span",{className:"flat-map-agent-chip__dot",style:{backgroundColor:xn(u.status)}}),u.latestTodos&&u.latestTodos.length>0&&e.jsx(Bn,{todos:u.latestTodos,maxDots:6}),I&&V&&V.length>0&&e.jsx(Fn,{subordinates:V,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:`${$.usedPercent}%`,backgroundColor:v}})})]})},u.id)})}),l.area.directories.length>0&&e.jsx("div",{className:"flat-map-area-card__folders",role:"group","aria-label":`${l.area.name} folders`,children:l.area.directories.map(u=>{const I=u.split("/").filter(Boolean).pop()||u;return e.jsxs("button",{type:"button",className:"flat-map-folder-chip",onClick:V=>{V.stopPropagation(),g.openFileExplorerForAreaFolder(x,u)},title:`Open in file explorer: ${u}`,children:[e.jsx(m,{name:"folder-open",size:12}),e.jsx("span",{className:"flat-map-folder-chip__name",children:I})]},u)})}),l.buildings.length>0&&e.jsx("div",{className:"flat-map-area-card__buildings",children:l.buildings.map(u=>{var V;const I=(V=Wn[u.type])==null?void 0:V.color;return e.jsxs("button",{type:"button",className:`flat-map-building-chip flat-map-building-chip--${u.status}`,style:I?{"--building-type-color":I}:void 0,onClick:$=>{if(h){const v=$.currentTarget.getBoundingClientRect();h(u.id,{x:v.right,y:v.top+v.height/2})}else ye(u.id)},onContextMenu:$=>{$.preventDefault(),$.stopPropagation(),O({buildingId:u.id,position:{x:$.clientX,y:$.clientY}})},title:`${u.name} · ${u.type} · ${u.status}`,children:[e.jsx(m,{name:Hn(u.type),size:12,color:I}),e.jsx("span",{className:"flat-map-building-chip__name",children:u.name}),e.jsx("span",{className:"flat-map-building-chip__dot",style:{backgroundColor:Un(u.status)}})]},u.id)})})]},x)})})()})]})})]}),ee&&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:Qe,onPointerMove:j,onPointerUp:ne,onPointerCancel:ne,onDoubleClick:pt}),ie&&e.jsxs("aside",{className:`flat-inspector ${Ke?"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":Q==="agent",className:`flat-inspector__tab ${Q==="agent"?"flat-inspector__tab--active":""}`,onClick:()=>Ge("agent"),children:"Agent"}),e.jsx("button",{type:"button",role:"tab","aria-selected":Q==="tracking",className:`flat-inspector__tab ${Q==="tracking"?"flat-inspector__tab--active":""}`,onClick:()=>Ge("tracking"),children:"Tracking"})]}),e.jsx("button",{type:"button",className:"flat-inspector__close",onClick:Ce,title:"Close inspector","aria-label":"Close inspector",children:"✕"})]}),e.jsx("div",{className:"flat-inspector__body",children:Q==="tracking"?e.jsx(Vn,{activeAgentId:w??"",onSelectAgent:t=>{c(t),window.innerWidth<=768&&Ce()}}):(()=>{if(!w)return e.jsx("div",{className:"flat-inspector__empty",children:e.jsx("span",{children:"Select an agent to inspect"})});const t=_.find(s=>s.id===w);return t?e.jsx(Xn,{agent:t,onFocusAgent:s=>{c(s),window.innerWidth<=768&&Ce()},onKillAgent:s=>g.killAgent(s)}):e.jsx("div",{className:"flat-inspector__empty",children:e.jsx("span",{children:"Agent not found"})})})()})]}),H&&e.jsx(Gn,{url:H.url,name:H.name,onClose:()=>re(null)}),P&&e.jsx(qn,{state:P,onClose:()=>Ee(null)}),e.jsx(Yn,{agent:w?_.find(t=>t.id===w)??null:null,content:oe,onClose:()=>ce(null)}),$e&&e.jsx(Kn,{action:"clear-subordinates",selectedAgentId:$e.agentId,subordinateCount:$e.count,onClose:()=>ot(null),onClearHistory:()=>{}}),e.jsx(Zn,{agent:w?_.find(t=>t.id===w)??null:null,isOpen:We&&!!w,onClose:ct}),e.jsx(tn,{isOpen:xe!==null,position:(xe==null?void 0:xe.position)??{x:0,y:0},worldPosition:{x:0,z:0},actions:U,onClose:()=>be(null)}),e.jsx(tn,{isOpen:f!==null,position:(f==null?void 0:f.position)??{x:0,y:0},worldPosition:{x:0,z:0},actions:vt,onClose:()=>O(null)}),e.jsx(Jn,{isOpen:Ie!==null,title:Y("common:confirm.removeAgentTitle"),message:Y("common:confirm.removeAgentMessage",{name:(Ie==null?void 0:Ie.name)??""}),confirmLabel:Y("common:buttons.remove"),cancelLabel:Y("common:buttons.cancel"),variant:"danger",onConfirm:()=>{Ie&&g.removeAgentFromServer(Ie.agentId)},onClose:()=>ze(null)})]})}export{qa as FlatView};