tide-commander 1.98.0 → 1.100.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{BossLogsModal-P6MiZVuY.js → BossLogsModal-CgiqbrpI.js} +1 -1
- package/dist/assets/{BossSpawnModal-DZJ1Ngsz.js → BossSpawnModal-Dm-Rlit6.js} +1 -1
- package/dist/assets/{ControlsModal-BjV0a1kc.js → ControlsModal-CS5PL1Dr.js} +1 -1
- package/dist/assets/{DockerLogsModal-DtddubKa.js → DockerLogsModal-CoDsW7Zf.js} +1 -1
- package/dist/assets/{EmbeddedEditor-ByRepTwR.js → EmbeddedEditor-B53miU1u.js} +1 -1
- package/dist/assets/{GmailOAuthSetup-DS6NmxUi.js → GmailOAuthSetup-DHYC56vA.js} +1 -1
- package/dist/assets/{GoogleOAuthSetup-kQyKInRW.js → GoogleOAuthSetup-BrXFYUFW.js} +1 -1
- package/dist/assets/{IframeModal-BuTPDTx1.js → IframeModal-BrGdxNuG.js} +1 -1
- package/dist/assets/{IntegrationsPanel-Bm19ZAd6.js → IntegrationsPanel-B5D_jOhk.js} +2 -2
- package/dist/assets/{LogViewerModal-DFlUtkDD.js → LogViewerModal-KHXuxGNe.js} +1 -1
- package/dist/assets/{MonitoringModal-BEEPwGu5.js → MonitoringModal-Co_fx9fM.js} +1 -1
- package/dist/assets/{PM2LogsModal-Di5MjyxZ.js → PM2LogsModal-CzSWbJw2.js} +1 -1
- package/dist/assets/{RestoreArchivedAreaModal-CNjmR7BX.js → RestoreArchivedAreaModal-DEgMLH7w.js} +1 -1
- package/dist/assets/{Scene2DCanvas-CA29sh9R.js → Scene2DCanvas-bKf_xYPZ.js} +1 -1
- package/dist/assets/{SceneManager-duyCA_TD.js → SceneManager-Djv8JsV0.js} +1 -1
- package/dist/assets/{SkillsPanel-CkV4ci4Q.js → SkillsPanel-DolU9i4d.js} +1 -1
- package/dist/assets/{SlackMultiInstanceSetup-iHZNQX3B.js → SlackMultiInstanceSetup-sRiMZQ6x.js} +1 -1
- package/dist/assets/{SpawnModal-bzQlnSQy.js → SpawnModal-Cwb4vyWw.js} +1 -1
- package/dist/assets/{SubordinateAssignmentModal-D6Ak_XQ1.js → SubordinateAssignmentModal-D2AUyLhd.js} +1 -1
- package/dist/assets/{TriggerManagerPanel-CT8aMQ5P.js → TriggerManagerPanel-WEJXvsjq.js} +1 -1
- package/dist/assets/{WorkflowEditorPanel-DcV9ErU4.js → WorkflowEditorPanel-CqCKn-BW.js} +1 -1
- package/dist/assets/{index-BQQV5Xax.js → index-BGpBSg5x.js} +1 -1
- package/dist/assets/{index-Cirz97EK.js → index-Bi9RecAa.js} +2 -2
- package/dist/assets/{index-DR7uaDtK.js → index-BqTABon1.js} +1 -1
- package/dist/assets/{index-D2L5oc5D.js → index-C2z1QKUl.js} +1 -1
- package/dist/assets/index-CJXhFnBD.js +11 -0
- package/dist/assets/{index-Dww2MWLN.js → index-C_tlEtg3.js} +1 -1
- package/dist/assets/{index-Ba8umpS_.js → index-Ck5CfDGK.js} +1 -1
- package/dist/assets/{index-Cnj2pM08.js → index-D1nrHGW6.js} +3 -3
- package/dist/assets/{index-C0fIrrTS.js → index-DThdfn9f.js} +1 -1
- package/dist/assets/{main-XbhAPjbi.js → main-CBiZdw6w.js} +91 -91
- package/dist/assets/main-DLzFxLC1.css +1 -0
- package/dist/assets/{web-CaPUSaID.js → web-C6kv8URU.js} +1 -1
- package/dist/assets/{web-C4LpSGoH.js → web-hRik7e7W.js} +1 -1
- package/dist/assets/{web-C-JnApw7.js → web-ns0ZWeh3.js} +1 -1
- package/dist/index.html +2 -2
- package/dist/locales/en/config.json +16 -1
- package/dist/src/packages/server/cli.js +26 -0
- package/dist/src/packages/server/routes/index.js +2 -0
- package/dist/src/packages/server/routes/system.js +156 -0
- package/dist/src/packages/server/services/self-update-service.js +191 -0
- package/package.json +1 -1
- package/dist/assets/index-CDHzSAgq.js +0 -1
- package/dist/assets/main-CD03IZnY.css +0 -1
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{r as l,aT as Re,aU as Ye,j as e,I as $,u as Y,aV as ts,a2 as ns,f as Ve,s as E,aW as hs,k as is,l as me,aX as X,aY as ms,aM as gs,aZ as fs,C as ge,a_ as J,aJ as we,a$ as xs,b0 as bs,b1 as js,b2 as ws,b3 as Ce,b4 as os,b5 as ys,b6 as Be,b7 as vs,b8 as Ns,b9 as ks,ba as Cs,bb as Ss,bc as Ts,bd as As,aF as _s,J as Es,S as ke,be as Is,bf as Ps,aH as $s,bg as Ue,K as Pe,aQ as Ls,bh as ze,bi as Ds}from"./main-CBiZdw6w.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const Ke="deivid11/tide-commander",Fs=`https://api.github.com/repos/${Ke}/releases/latest`,Os=`https://api.github.com/repos/${Ke}/releases?per_page=3`,Rs=3600*1e3,Je="app_update_dismissed_version",Ze="1.100.0";function Us(){var x,b;const[s,t]=l.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Ze}),a=((b=(x=Re)==null?void 0:x.getPlatform)==null?void 0:b.call(x))==="android"||!1,o=p=>p.replace(/^v/,"").split(".").map(m=>parseInt(m,10)||0),r=(p,f)=>{const m=o(p),y=o(f),j=Math.max(m.length,y.length);for(let h=0;h<j;h++){const _=m[h]||0,D=y[h]||0;if(_>D)return 1;if(_<D)return-1}return 0},d=async p=>{var m,y;if(Re&&Ye&&((y=(m=Re).isNativePlatform)==null?void 0:y.call(m))===!0){const j=await Ye.get({url:p,headers:{Accept:"application/vnd.github.v3+json"}});return{data:j.data,status:j.status}}else{const j=await fetch(p,{headers:{Accept:"application/vnd.github.v3+json"}});return j.ok?{data:await j.json(),status:j.status}:{data:null,status:j.status}}},c=l.useCallback(async(p=!1)=>{t(f=>({...f,isChecking:!0,error:null}));try{const[f,m]=await Promise.all([d(Fs),d(Os)]);if(f.status!==200)throw new Error(`GitHub API error: ${f.status}`);const y=f.data,j=y.tag_name;let h=[];m.status===200&&m.data&&(h=m.data.map(A=>({version:A.tag_name,name:A.name,publishedAt:A.published_at,releaseUrl:A.html_url})));const _=localStorage.getItem(Je);if(!p&&_===j)return t(A=>({...A,isChecking:!1,updateAvailable:!1,recentReleases:h})),null;if(!(r(j,Ze)>0))return t(A=>({...A,isChecking:!1,updateAvailable:!1,recentReleases:h})),null;const P=y.assets.find(A=>A.name.endsWith(".apk")&&A.content_type==="application/vnd.android.package-archive"),C={version:j,name:y.name,changelog:y.body,releaseUrl:y.html_url,apkUrl:(P==null?void 0:P.browser_download_url)||null,apkSize:(P==null?void 0:P.size)||null,publishedAt:y.published_at};return t(A=>({...A,isChecking:!1,updateAvailable:!0,updateInfo:C,recentReleases:h})),C}catch(f){const m=f instanceof Error?f.message:"Failed to check for updates";return t(y=>({...y,isChecking:!1,error:m})),null}},[]),n=l.useCallback(async()=>{var p,f,m;if(!((p=s.updateInfo)!=null&&p.apkUrl)){(f=s.updateInfo)!=null&&f.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}if(!a){(m=s.updateInfo)!=null&&m.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}try{window.open(s.updateInfo.apkUrl,"_system"),t(y=>({...y,error:null}))}catch(y){const j=y instanceof Error?y.message:"Failed to open download";t(h=>({...h,error:j}))}},[s.updateInfo,a]),u=l.useCallback(()=>{s.updateInfo&&localStorage.setItem(Je,s.updateInfo.version),t(p=>({...p,updateAvailable:!1,updateInfo:null}))},[s.updateInfo]),w=l.useCallback(()=>{var p;(p=s.updateInfo)!=null&&p.releaseUrl?window.open(s.updateInfo.releaseUrl,"_blank"):window.open(`https://github.com/${Ke}/releases`,"_blank")},[s.updateInfo]);return l.useEffect(()=>{if(!a)return;const p=setTimeout(()=>{c()},5e3),f=setInterval(()=>{c()},Rs);return()=>{clearTimeout(p),clearInterval(f)}},[a,c]),{...s,isAndroid:a,checkForUpdate:c,downloadAndInstall:n,dismissUpdate:u,openReleasePage:w}}const ls="tide-toolbox-collapse";function zs(s,t){try{const a=localStorage.getItem(`${ls}-${s}`);if(a!==null)return a==="true"}catch{}return t}function Ms(s,t){try{localStorage.setItem(`${ls}-${s}`,String(t))}catch{}}function W({title:s,storageKey:t,defaultOpen:a=!1,forceOpen:o=!1,children:r,headerExtra:d}){const[c,n]=l.useState(()=>t?zs(t,a):a),u=()=>{const x=!c;n(x),t&&Ms(t,x)},w=o||c;return e.jsxs("div",{className:`collapsible-section ${w?"open":"collapsed"}`,children:[e.jsxs("button",{className:"collapsible-header",onClick:u,children:[e.jsx("span",{className:"collapsible-title",children:s}),e.jsxs("span",{className:"collapsible-header-right",children:[d,e.jsx("span",{className:"collapsible-arrow",children:e.jsx($,{name:w?"caret-down":"caret-right",size:10})})]})]}),w&&e.jsx("div",{className:"collapsible-content",children:r})]})}function Bs({area:s,isSelected:t,onClick:a,onDelete:o}){const{t:r}=Y(["config","common"]),d=s.assignedAgentIds.length,c=s.type==="rectangle"?r("config:areas.rect"):r("config:areas.circle");return e.jsxs("div",{className:`area-item ${t?"selected":""}`,onClick:a,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," ",d>0&&`• ${d} ${d>1?r("common:labels.agents").toLowerCase():r("common:labels.agent").toLowerCase()}`]})]}),e.jsx("button",{className:"area-delete-btn",onClick:o,title:r("config:areas.deleteArea"),children:"×"})]})}function Vs({building:s,isSelected:t,onClick:a,onEdit:o}){var n;const{t:r}=Y(["config"]),d=((n=s.pm2Status)==null?void 0:n.ports)||[],c=(u,w)=>{u.stopPropagation(),window.open(`http://${window.location.hostname}:${w}`,"_blank")};return e.jsxs("div",{className:`building-item ${t?"selected":""}`,onClick:a,children:[e.jsx("div",{className:"building-status-dot",style:{backgroundColor:ts[s.status]},title:s.status}),e.jsx("div",{className:"building-icon",children:e.jsx($,{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,d.length>0&&e.jsx("span",{className:"building-ports",children:d.map(u=>e.jsxs("a",{href:`http://${window.location.hostname}:${u}`,className:"building-port-link",onClick:w=>c(w,u),title:`Open :${u}`,children:[":",u]},u))})]})]}),e.jsx("button",{className:"building-edit-btn",onClick:u=>{u.stopPropagation(),o()},title:r("config:buildings.editBuilding"),children:e.jsx($,{name:"gear",size:14})})]})}function Ks({building:s,onClose:t,onOpenModal:a}){var w,x,b,p,f,m,y,j;const{t:o}=Y(["config","common"]),{buildingLogs:r}=Ve(),d=E.getBuildingLogs(s.id),c=hs[s.style||"server-rack"],n=h=>{E.sendBuildingCommand(s.id,h)},u=h=>{window.open(h,"_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($,{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:ts[s.status]},children:s.status})]}),e.jsx("button",{className:"building-editor-close",onClick:t,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:()=>n("start"),disabled:!((w=s.commands)!=null&&w.start)||s.status==="running",title:((x=s.commands)==null?void 0:x.start)||o("config:buildings.noStartCommand"),children:[e.jsx($,{name:"play",size:12})," ",o("common:buttons.start")]}),e.jsxs("button",{className:"building-editor-action-btn stop",onClick:()=>n("stop"),disabled:!((b=s.commands)!=null&&b.stop)||s.status==="stopped",title:((p=s.commands)==null?void 0:p.stop)||o("config:buildings.noStopCommand"),children:[e.jsx($,{name:"stop",size:12,weight:"fill"})," ",o("common:buttons.stop")]}),e.jsxs("button",{className:"building-editor-action-btn restart",onClick:()=>n("restart"),disabled:!((f=s.commands)!=null&&f.restart),title:((m=s.commands)==null?void 0:m.restart)||o("config:buildings.noRestartCommand"),children:[e.jsx($,{name:"refresh",size:12})," ",o("common:buttons.retry")]}),e.jsxs("button",{className:"building-editor-action-btn health",onClick:()=>n("healthCheck"),disabled:!((y=s.commands)!=null&&y.healthCheck),title:((j=s.commands)==null?void 0:j.healthCheck)||o("config:buildings.noHealthCheck"),children:[e.jsx($,{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((h,_)=>e.jsxs("button",{className:"building-editor-link",onClick:()=>u(h.url),title:h.url,children:[e.jsx($,{name:"link",size:12})," ",h.label||h.url]},_))})]}),d.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:()=>E.clearBuildingLogs(s.id),title:o("common:buttons.clear"),children:o("common:buttons.clear")})]}),e.jsx("div",{className:"building-editor-logs",children:d.slice(-5).map((h,_)=>e.jsx("div",{className:"building-editor-log-entry",children:h},_))})]}),e.jsx("div",{className:"building-editor-footer",children:e.jsxs("button",{className:"building-editor-edit-btn",onClick:a,children:[e.jsx($,{name:"gear",size:12})," ",o("config:buildings.fullSettings")]})})]})}async function Hs(s,t){const a=X(),o=await fetch(me(`/api/areas/${s}/logo`),{method:"POST",headers:{"Content-Type":t.type||"image/png","X-Filename":encodeURIComponent(t.name),...a?{Authorization:`Bearer ${a}`}:{}},body:t});if(!o.ok){const r=await o.json().catch(()=>({error:o.statusText}));throw new Error(r.error||`Upload failed: ${o.statusText}`)}return o.json()}async function Ws(s){const t=X(),a=await fetch(me(`/api/areas/${s}/logo`),{method:"DELETE",headers:{...t?{Authorization:`Bearer ${t}`}:{}}});if(!a.ok)throw new Error(`Failed to delete logo: ${a.statusText}`)}function qs(s){return is(me(`/api/areas/logos/${s}`))}const Gs=[{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 Ys({area:s,onClose:t,onOpenFolder:a}){var ce;const{t:o}=Y(["config","common"]),[r,d]=l.useState(s.name),[c,n]=l.useState(s.prompt||""),[u,w]=l.useState(!1),[x,b]=l.useState(""),[p,f]=l.useState(!1),m=l.useRef(null);l.useEffect(()=>{d(s.name)},[s.id,s.name]),l.useEffect(()=>{n(s.prompt||"")},[s.id,s.prompt]);const y=k=>{const O=k.target.value;d(O),E.updateArea(s.id,{name:O})},j=k=>{E.updateArea(s.id,{color:k})},h=k=>{const O=k.target.value;n(O),E.updateArea(s.id,{prompt:O})},_=()=>{x.trim()&&(E.addDirectoryToArea(s.id,x.trim()),b(""),w(!1))},D=(k,O)=>{O.stopPropagation(),E.removeDirectoryFromArea(s.id,k)},P=()=>{E.bringAreaToFront(s.id)},C=()=>{E.sendAreaToBack(s.id)},A=l.useCallback(()=>{let k=2,O=2;s.type==="rectangle"&&s.width&&s.height?(k=s.width,O=s.height):s.type==="circle"&&s.radius&&(k=s.radius*1.414,O=s.radius*1.414);const B=Math.min(k,O)*.4;return{width:Math.round(B*10)/10,height:Math.round(B*10)/10}},[s.type,s.width,s.height,s.radius]),V=async k=>{var B;const O=(B=k.target.files)==null?void 0:B[0];if(O){f(!0);try{const v=await Hs(s.id,O),F=A();E.updateArea(s.id,{logo:{filename:v.filename,position:"center",width:F.width,height:F.height,keepAspectRatio:!0,opacity:.8}})}catch(v){console.error("Failed to upload logo:",v)}finally{f(!1),m.current&&(m.current.value="")}}},M=async()=>{try{await Ws(s.id),E.updateArea(s.id,{logo:void 0})}catch(k){console.error("Failed to remove logo:",k)}},K=k=>{s.logo&&E.updateArea(s.id,{logo:{...s.logo,position:k}})},N=k=>{if(!s.logo)return;const O=parseFloat(k.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.width>0){const B=s.logo.height/s.logo.width;E.updateArea(s.id,{logo:{...s.logo,width:O,height:Math.round(O*B*10)/10}})}else E.updateArea(s.id,{logo:{...s.logo,width:O}})},S=k=>{if(!s.logo)return;const O=parseFloat(k.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.height>0){const B=s.logo.width/s.logo.height;E.updateArea(s.id,{logo:{...s.logo,height:O,width:Math.round(O*B*10)/10}})}else E.updateArea(s.id,{logo:{...s.logo,height:O}})},H=()=>{s.logo&&E.updateArea(s.id,{logo:{...s.logo,keepAspectRatio:!s.logo.keepAspectRatio}})},Z=k=>{s.logo&&E.updateArea(s.id,{logo:{...s.logo,opacity:parseFloat(k.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:t,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:r,onChange:y,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:ms.map(k=>e.jsx("div",{className:`color-swatch ${s.color===k?"selected":""}`,style:{backgroundColor:k},onClick:()=>j(k)},k))})]}),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:P,title:o("config:areas.bringToFront"),children:[e.jsx($,{name:"arrow-up",size:12})," ",o("config:areas.front")]}),e.jsxs("button",{className:"area-layer-btn",onClick:C,title:o("config:areas.sendToBack"),children:[e.jsx($,{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:[(ce=s.logo)!=null&&ce.filename?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"area-logo-preview",children:[e.jsx("img",{src:qs(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 k;return(k=m.current)==null?void 0:k.click()},disabled:p,children:p?"...":e.jsx($,{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:Gs.map(({key:k,labelKey:O})=>{var B;return e.jsx("button",{className:`area-logo-pos-btn ${((B=s.logo)==null?void 0:B.position)===k?"active":""}`,onClick:()=>K(k),children:o(`config:areas.${O}`)},k)})})]}),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:N,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:S,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:H}),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:Z,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 k;return(k=m.current)==null?void 0:k.click()},disabled:p,children:p?"...":o("config:areas.uploadLogo")}),e.jsx("input",{ref:m,type:"file",accept:"image/*",style:{display:"none"},onChange:V})]})]}),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(k=>e.jsxs("div",{className:"area-folder-item",title:k,children:[e.jsx("span",{className:"area-folder-icon clickable",onClick:()=>a==null?void 0:a(s.id),title:o("config:areas.openFolder"),children:e.jsx($,{name:"folder",size:14})}),e.jsx("span",{className:"area-folder-path",children:k.split("/").pop()||k}),e.jsx("button",{className:"area-folder-remove",onClick:O=>D(k,O),title:o("config:areas.removeFolder"),children:"×"})]},k)),u?e.jsxs("div",{className:"area-add-folder-inline",children:[e.jsx(gs,{value:x,onChange:b,onSubmit:_,placeholder:o("config:areas.folderPlaceholder"),className:"area-add-folder-input",directoriesOnly:!0,autoFocus:!0}),e.jsx("button",{className:"area-add-folder-confirm",onClick:_,children:"+"})]}):e.jsx("button",{className:"area-add-folder-btn",onClick:()=>w(!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:h,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 Js(){const{t:s}=Y(["config","common"]),t=fs(),[a,o]=l.useState(!1),[r,d]=l.useState(null),[c,n]=l.useState({name:"",key:"",value:"",description:""}),[u,w]=l.useState(null),x=()=>{o(!0),d(null),n({name:"",key:"",value:"",description:""})},b=h=>{d(h.id),o(!1),n({name:h.name,key:h.key,value:h.value,description:h.description||""})},p=()=>{o(!1),d(null),n({name:"",key:"",value:"",description:""})},f=()=>{!c.name.trim()||!c.key.trim()||(r?E.updateSecret(r,{name:c.name.trim(),key:c.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:c.value,description:c.description.trim()||void 0}):E.createSecret({name:c.name.trim(),key:c.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:c.value,description:c.description.trim()||void 0}),p())},m=h=>{w(h)},y=()=>{u&&(E.deleteSecret(u),r===u&&p())},j=h=>{navigator.clipboard.writeText(`{{${h}}}`)};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:t.length===0&&!a?e.jsx("div",{className:"secrets-empty",children:s("config:secrets.noSecrets")}):t.map(h=>e.jsxs("div",{className:`secret-item ${r===h.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:h.name}),e.jsx("code",{className:"secret-item-key",onClick:()=>j(h.key),title:s("config:secrets.copyPlaceholder"),children:`{{${h.key}}}`})]}),e.jsxs("div",{className:"secret-item-actions",children:[e.jsx("button",{className:"secret-item-btn edit",onClick:()=>b(h),title:s("common:buttons.edit"),children:e.jsx($,{name:"edit",size:12})}),e.jsx("button",{className:"secret-item-btn delete",onClick:()=>m(h.id),title:s("common:buttons.delete"),children:"×"})]})]}),h.description&&e.jsx("div",{className:"secret-item-description",children:h.description})]},h.id))}),(a||r)&&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:h=>n({...c,name:h.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:h=>n({...c,key:h.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:h=>n({...c,value:h.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:h=>n({...c,description:h.target.value})})]}),e.jsxs("div",{className:"secret-form-actions",children:[e.jsx("button",{className:"secret-form-btn cancel",onClick:p,children:s("common:buttons.cancel")}),e.jsx("button",{className:"secret-form-btn save",onClick:f,disabled:!c.name.trim()||!c.key.trim(),children:s(r?"config:secrets.update":"common:buttons.add")})]})]}),!a&&!r&&e.jsx("button",{className:"secrets-add-btn",onClick:x,children:s("config:secrets.addSecret")}),e.jsx(ge,{isOpen:u!==null,title:s("common:buttons.delete"),message:s("config:secrets.deleteConfirm"),confirmLabel:s("common:buttons.delete"),cancelLabel:s("common:buttons.cancel"),variant:"danger",onConfirm:y,onClose:()=>w(null)})]})}async function Zs(){const s=X(),t=await fetch(`${J()}/api/agents/system-settings/prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!t.ok)throw new Error(`Failed to fetch system prompt: ${t.statusText}`);return(await t.json()).prompt||""}async function Xs(s){const t=X(),a=await fetch(`${J()}/api/agents/system-settings/prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({prompt:s})});if(!a.ok)throw new Error(`Failed to update system prompt: ${a.statusText}`)}async function Qs(){const s=X(),t=await fetch(`${J()}/api/agents/system-settings/prompt`,{method:"DELETE",headers:{Authorization:`Bearer ${s}`}});if(!t.ok)throw new Error(`Failed to clear system prompt: ${t.statusText}`)}async function ea(){const s=X(),t=await fetch(`${J()}/api/agents/system-settings/echo-prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!t.ok)throw new Error(`Failed to fetch echo prompt setting: ${t.statusText}`);return(await t.json()).enabled||!1}async function sa(s){const t=X(),a=await fetch(`${J()}/api/agents/system-settings/echo-prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({enabled:s})});if(!a.ok)throw new Error(`Failed to update echo prompt setting: ${a.statusText}`)}async function aa(){const s=X(),t=await fetch(`${J()}/api/agents/system-settings/codex-binary`,{headers:{Authorization:`Bearer ${s}`}});if(!t.ok)throw new Error(`Failed to fetch codex binary path: ${t.statusText}`);return(await t.json()).path||""}async function ta(s){const t=X(),a=await fetch(`${J()}/api/agents/system-settings/codex-binary`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({path:s})});if(!a.ok)throw new Error(`Failed to update codex binary path: ${a.statusText}`)}async function na(){const s=X(),t=await fetch(`${J()}/api/agents/system-settings/tmux-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!t.ok)throw new Error(`Failed to fetch tmux mode setting: ${t.statusText}`);return(await t.json()).enabled||!1}async function ia(s){const t=X(),a=await fetch(`${J()}/api/agents/system-settings/tmux-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({enabled:s})});if(!a.ok)throw new Error(`Failed to update tmux mode setting: ${a.statusText}`)}async function oa(){const s=X(),t=await fetch(`${J()}/api/agents/system-settings/backup`,{headers:{Authorization:`Bearer ${s}`}});if(!t.ok)throw new Error(`Failed to fetch backup status: ${t.statusText}`);return t.json()}async function la(s){const t=X(),a=await fetch(`${J()}/api/agents/system-settings/backup`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({enabled:s})});if(!a.ok){const o=await a.json().catch(()=>({}));throw new Error(o.error||`Failed to update backup setting: ${a.statusText}`)}return a.json()}function ca({checked:s,onChange:t,disabled:a}){return e.jsxs("label",{className:"config-toggle",children:[e.jsx("input",{type:"checkbox",className:"config-toggle-input",checked:s,disabled:a,onChange:o=>t(o.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})}function ra(){const{t:s}=Y(["config","common"]),[t,a]=l.useState([]),[o,r]=l.useState(new Set),[d,c]=l.useState(new Set),[n,u]=l.useState(!1),[w,x]=l.useState(!1),[b,p]=l.useState(null),[f,m]=l.useState(null),[y,j]=l.useState(null),[h,_]=l.useState(null),[D,P]=l.useState(!1),[C,A]=l.useState(null);l.useEffect(()=>{we(me("/api/config/categories")).then(v=>v.json()).then(v=>{const F=Array.isArray(v)?v:[];a(F),r(new Set(F.map(R=>R.id)))}).catch(v=>console.error("Failed to fetch config categories:",v))},[]),l.useEffect(()=>{oa().then(_).catch(v=>{console.error("Failed to fetch backup status:",v),A(v.message||"Failed to fetch backup status")})},[]);const V=async v=>{if(!D){P(!0),A(null);try{const F=await la(v);_(F)}catch(F){A(F.message||"Failed to update backup setting")}finally{P(!1)}}},M=v=>{r(F=>{const R=new Set(F);return R.has(v)?R.delete(v):R.add(v),R})},K=v=>{c(F=>{const R=new Set(F);return R.has(v)?R.delete(v):R.add(v),R})},N=()=>r(new Set(t.map(v=>v.id))),S=()=>r(new Set),H=()=>{f&&c(new Set(f.categories.map(v=>v.id)))},Z=()=>c(new Set),ce=async()=>{var v;if(o.size!==0){u(!0),j(null);try{const F=Array.from(o).join(","),R=await we(me(`/api/config/export?categories=${F}`));if(!R.ok)throw new Error("Export failed");const Q=await R.blob(),ae=window.URL.createObjectURL(Q),ee=document.createElement("a");ee.href=ae;const T=R.headers.get("Content-Disposition"),q=((v=T==null?void 0:T.match(/filename="(.+)"/))==null?void 0:v[1])||"tide-commander-config.zip";ee.download=q,document.body.appendChild(ee),ee.click(),document.body.removeChild(ee),window.URL.revokeObjectURL(ae),j({type:"success",text:s("config:data.exportSuccess")})}catch(F){j({type:"error",text:F.message||"Export failed"})}finally{u(!1)}}},k=async v=>{var R;const F=(R=v.target.files)==null?void 0:R[0];if(F){p(F),j(null),m(null),c(new Set);try{const Q=await we(me("/api/config/preview"),{method:"POST",headers:{"Content-Type":"application/zip"},body:await F.arrayBuffer()});if(!Q.ok){const T=await Q.json();throw new Error(T.error||"Failed to preview config file")}const ae=await Q.json(),ee=Array.isArray(ae.categories)?ae.categories:[];m({...ae,categories:ee}),c(new Set(ee.map(T=>T.id)))}catch(Q){j({type:"error",text:Q.message||"Failed to read config file"}),p(null)}}},O=async()=>{if(!(!b||d.size===0)){x(!0),j(null);try{const v=Array.from(d).join(","),F=await we(me(`/api/config/import?categories=${v}`),{method:"POST",headers:{"Content-Type":"application/zip"},body:await b.arrayBuffer()}),R=await F.json();if(!F.ok)throw new Error(R.error||"Import failed");j({type:"success",text:R.message||s("config:data.importSuccess")}),p(null),m(null),c(new Set)}catch(v){j({type:"error",text:v.message||"Import failed"})}finally{x(!1)}}},B=()=>{p(null),m(null),c(new Set),j(null)};return e.jsxs("div",{className:"data-section",children:[y&&e.jsx("div",{className:`data-message data-message-${y.type}`,children:y.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(ca,{checked:!!(h!=null&&h.enabled),disabled:D||!h,onChange:V})]}),e.jsxs("div",{className:"data-backup-info",children:[h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:["Saves a compressed snapshot of your data every hour to"," ",e.jsx("code",{children:h.backupDir}),". Identical snapshots are skipped. Keeps the 8 newest plus one from each of the 2 most recent prior days."]}),!h.scriptExists&&e.jsxs("div",{style:{marginTop:6,color:"var(--dracula-red, #ff5555)"},children:["Backup script not found at ",e.jsx("code",{children:h.scriptPath})]}),h.lastRunAt&&e.jsxs("div",{style:{marginTop:6},children:["Last run: ",new Date(h.lastRunAt).toLocaleString(),h.lastRunOk===!0&&" — ok",h.lastRunOk===!1&&h.lastRunError&&e.jsxs("span",{style:{color:"var(--dracula-red, #ff5555)"},children:[" — ",h.lastRunError]})]})]}):e.jsx("div",{children:"Loading backup status…"}),C&&e.jsx("div",{className:"data-message data-message-error",style:{marginTop:6},children:C})]})]}),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:N,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:S,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:t.map(v=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:o.has(v.id),onChange:()=>M(v.id)}),e.jsx("span",{className:"data-category-name",children:v.name})]},v.id))}),e.jsx("button",{className:"data-action-btn export",onClick:ce,disabled:n||o.size===0,children:n?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")})}),b?f?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"data-import-info",children:[e.jsx("div",{className:"data-import-file",children:b.name}),e.jsxs("div",{className:"data-import-date",children:[s("config:data.exported"),": ",new Date(f.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:H,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:Z,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:f.categories.map(v=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:d.has(v.id),onChange:()=>K(v.id)}),e.jsx("span",{className:"data-category-name",children:v.name}),v.fileCount&&e.jsxs("span",{className:"data-category-count",children:["(",v.fileCount," ",s("config:data.files"),")"]})]},v.id))}),e.jsxs("div",{className:"data-import-actions",children:[e.jsx("button",{className:"data-action-btn cancel",onClick:B,children:s("common:buttons.cancel")}),e.jsx("button",{className:"data-action-btn import",onClick:O,disabled:w||d.size===0,children:w?s("config:data.importing"):s("config:data.importCount",{count:d.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:k,style:{display:"none"}}),e.jsx("span",{className:"data-file-input-label",children:s("config:data.selectFile")})]})]})]})}async function da(){const s=await we(`${J()}/api/system/install-info`);if(!s.ok)throw new Error(`Failed to fetch install info: ${s.statusText}`);return s.json()}function ua(s,t){const a=new AbortController;return(async()=>{try{const o=await fetch(is(`${J()}/api/system/self-update`),{method:"POST",signal:a.signal,headers:{Accept:"text/event-stream"}});if(!o.ok||!o.body){const n=await o.text().catch(()=>"");let u=null;try{u=JSON.parse(n)}catch{}const w=u&&typeof u=="object"&&"error"in u&&typeof u.error=="string"?u.error:`Self-update failed: ${o.status} ${o.statusText}`;s({type:"error",message:w}),t(new Error(w));return}const r=o.body.getReader(),d=new TextDecoder("utf-8");let c="";for(;;){const{value:n,done:u}=await r.read();if(u)break;c+=d.decode(n,{stream:!0});let w=c.indexOf(`
|
|
2
|
+
|
|
3
|
+
`);for(;w!==-1;){const x=c.slice(0,w);c=c.slice(w+2);const b=x.split(`
|
|
4
|
+
`);let p="message",f="";for(const m of b)m.startsWith(":")||(m.startsWith("event:")?p=m.slice(6).trim():m.startsWith("data:")&&(f+=(f?`
|
|
5
|
+
`:"")+m.slice(5).trim()));if(f)try{const m=JSON.parse(f);s({type:p,...m})}catch{}w=c.indexOf(`
|
|
6
|
+
|
|
7
|
+
`)}}t()}catch(o){if(o.name==="AbortError"){t();return}t(o)}})(),()=>a.abort()}function pa(){const[s,t]=l.useState(()=>xs()),a=o=>{t(o);const r=js(o);ws(r)};return e.jsx("div",{className:"theme-selector",children:e.jsx("div",{className:"theme-selector-grid",children:bs.map(o=>e.jsxs("button",{className:`theme-option ${s===o.id?"active":""}`,onClick:()=>a(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 ha(){const{t:s}=Y(["config"]),[t,a]=l.useState(null),[o,r]=l.useState("idle"),[d,c]=l.useState(""),[n,u]=l.useState(null),[w,x]=l.useState(null),b=l.useRef(null),p=l.useRef(null),f=l.useCallback(async()=>{try{const _=await da();a(_)}catch{a(null)}},[]);l.useEffect(()=>{f()},[f]),l.useEffect(()=>{p.current&&(p.current.scrollTop=p.current.scrollHeight)},[d]);const m=l.useCallback(()=>{r("confirm")},[]),y=l.useCallback(()=>{r("idle")},[]),j=l.useCallback(()=>{r("running"),c(""),u(null),x(null);const _=ua(D=>{switch(D.type){case"start":c(P=>P+`${D.message}
|
|
8
|
+
`);break;case"stdout":c(P=>P+D.chunk);break;case"stderr":c(P=>P+D.chunk);break;case"error":u(D.message),D.suggestedManualCommand&&c(P=>P+`
|
|
9
|
+
|
|
10
|
+
Suggested manual command: ${D.suggestedManualCommand}
|
|
11
|
+
`);break;case"done":D.success?(x(D.newVersion),r("success")):r("failed");break}},D=>{D&&u(P=>P??D.message),r(P=>P==="running"?n?"failed":"success":P)});b.current=_},[n]),h=l.useCallback(()=>{var _;(_=b.current)==null||_.call(b),b.current=null,r("idle"),f()},[f]);return t?t.isGlobalInstall?t.autoUpdateSupported?!t.updateAvailable&&o==="idle"?null:e.jsxs("div",{className:"about-autoupdate",children:[e.jsx("div",{className:"about-autoupdate-title",children:s("config:about.autoUpdateTitle")}),o==="idle"&&t.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:t.currentVersion}),e.jsx("span",{className:"about-autoupdate-arrow",children:"→"}),e.jsx("span",{className:"about-autoupdate-latest",children:t.latestVersion})]}),e.jsx("button",{className:"about-update-btn download",onClick:m,children:s("config:about.autoUpdateButton")})]}),o==="confirm"&&e.jsxs("div",{className:"about-autoupdate-confirm",children:[e.jsx("div",{className:"about-autoupdate-confirm-title",children:s("config:about.autoUpdateConfirmTitle")}),e.jsx("div",{className:"about-autoupdate-confirm-body",children:s("config:about.autoUpdateConfirmBody")}),e.jsxs("div",{className:"about-autoupdate-confirm-actions",children:[e.jsx("button",{className:"about-update-btn changelog",onClick:y,children:s("config:about.autoUpdateCancel")}),e.jsx("button",{className:"about-update-btn download",onClick:j,children:s("config:about.autoUpdateConfirm")})]})]}),(o==="running"||o==="success"||o==="failed")&&e.jsxs("div",{className:"about-autoupdate-stream",children:[e.jsxs("div",{className:"about-autoupdate-stream-title",children:[o==="running"&&s("config:about.autoUpdateRunning"),o==="success"&&s("config:about.autoUpdateSuccess"),o==="failed"&&s("config:about.autoUpdateFailed")]}),e.jsx("pre",{ref:p,className:"about-autoupdate-output",children:d||"..."}),o==="success"&&e.jsxs("div",{className:"about-autoupdate-success-hint",children:[w&&e.jsxs("div",{className:"about-autoupdate-newversion",children:["v",w]}),e.jsx("div",{children:s("config:about.autoUpdateRestartHint")})]}),o==="failed"&&n&&e.jsx("div",{className:"about-update-error",children:n}),(o==="success"||o==="failed")&&e.jsx("div",{className:"about-autoupdate-stream-actions",children:e.jsx("button",{className:"about-update-btn changelog",onClick:h,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:t.packageManager})}),t.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:t.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 ma(){const{t:s}=Y(["config"]),{updateAvailable:t,updateInfo:a,recentReleases:o,isChecking:r,error:d,currentVersion:c,isAndroid:n,checkForUpdate:u,downloadAndInstall:w,openReleasePage:x}=Us(),b=f=>f?`${(f/(1024*1024)).toFixed(1)} MB`:"",p=f=>new Date(f).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($,{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}),t&&a?e.jsx("span",{className:"about-version-update-badge",onClick:x,title:`Update available: ${a.version}`,children:a.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(ha,{}),e.jsxs("div",{className:"about-update",children:[t&&a?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:a.version})]}),a.apkSize&&e.jsxs("div",{className:"about-update-size",children:[s("config:about.sizeLabel"),": ",b(a.apkSize)]}),d&&e.jsx("div",{className:"about-update-error",children:d}),e.jsxs("div",{className:"about-update-actions",children:[e.jsx("button",{className:"about-update-btn changelog",onClick:x,children:s("config:about.changelog")}),n&&a.apkUrl?e.jsx("button",{className:"about-update-btn download",onClick:w,children:s("config:about.downloadAPK")}):e.jsx("button",{className:"about-update-btn download",onClick:x,children:s("config:about.viewRelease")})]})]}):e.jsxs("div",{className:"about-update-check",children:[e.jsx("span",{className:"about-update-status",children:s(r?"config:about.checkingUpdates":"config:about.upToDate")}),e.jsx("button",{className:"about-update-btn check",onClick:()=>u(!0),disabled:r,children:r?"...":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(f=>e.jsxs("a",{href:f.releaseUrl,target:"_blank",rel:"noopener noreferrer",className:`about-release-item ${f.version===`v${c}`||f.version===c?"current":""}`,children:[e.jsx("span",{className:"about-release-version",children:f.version}),e.jsx("span",{className:"about-release-date",children:p(f.publishedAt)})]},f.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($,{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")})]})]})]})}const ga={gmail:"✉️",slack:"💬",jira:"📋","google-calendar":"📅",docx:"📄",whatsapp:"📱"};function fa({onOpenModal:s}){const[t,a]=l.useState([]),[o,r]=l.useState(!0),d=l.useCallback(async()=>{try{const c=await we(me("/api/integrations"));if(!c.ok)return;const n=await c.json();a(n)}catch{}finally{r(!1)}},[]);return l.useEffect(()=>{d()},[d]),o?e.jsx("div",{style:{color:"var(--text-secondary, #a6adc8)",fontSize:12,padding:"4px 0"},children:"Loading..."}):t.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:[t.map(c=>{const n=ga[c.id]||"🔌",u=!!c.status.error,w=c.status.connected,x=u?"#f38ba8":w?"#a6e3a1":"#fab387",b=u?"Error":w?"Connected":"Setup Required",p=u?"✗":w?"✓":"⚠";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:n}),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:x,fontSize:10,fontWeight:500,whiteSpace:"nowrap"},title:b,children:p}),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:f=>{f.target.style.color="var(--text-primary, #cdd6f4)"},onMouseLeave:f=>{f.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"})]})}function xa({isOpen:s,onClose:t}){const{t:a}=Y(["config"]),[o,r]=l.useState(""),[d,c]=l.useState(""),[n,u]=l.useState(!0),[w,x]=l.useState(null),[b,p]=l.useState(null),[f,m]=l.useState(!1),[y,j]=l.useState(!1),[h,_]=l.useState(!1);l.useEffect(()=>{s&&D()},[s]);const D=async()=>{try{u(!0),x(null),p(null);const S=await Zs();r(S),c(S),m(!1)}catch(S){x(S instanceof Error?S.message:"Failed to load system prompt")}finally{u(!1)}},P=S=>{const H=S.target.value;r(H),m(H!==d),x(null),p(null)},C=async()=>{try{x(null),p(null),await Xs(o),c(o),m(!1),p(a("config:systemPrompt.saved"))}catch(S){x(S instanceof Error?S.message:"Failed to save system prompt")}},A=()=>{j(!0)},V=async()=>{try{x(null),p(null),await Qs(),r(""),c(""),m(!1),p(a("config:systemPrompt.cleared"))}catch(S){x(S instanceof Error?S.message:"Failed to clear system prompt")}},M=()=>{r(d),m(!1),x(null),p(null)},K=()=>{if(f){_(!0);return}t()},N=S=>{S.key==="Escape"&&(S.preventDefault(),K())};return s?e.jsxs(Ce,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:K,children:e.jsxs("div",{className:"system-prompt-modal",onClick:S=>S.stopPropagation(),onKeyDown:N,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:a("config:systemPrompt.title")}),e.jsx("button",{className:"modal-close",onClick:K,"aria-label":"Close",children:e.jsx($,{name:"close",size:16})})]}),e.jsx("div",{className:"modal-body",children:n?e.jsxs("div",{className:"loading-state",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:"Loading system prompt..."})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"modal-description",children:a("config:systemPrompt.description")}),w&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx($,{name:"warn",size:14})}),w]}),b&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx($,{name:"check",size:14})}),b]}),e.jsxs("div",{className:"editor-wrapper",children:[e.jsxs("div",{className:"editor-header",children:[e.jsx("label",{htmlFor:"prompt-input",className:"editor-label",children:a("config:systemPrompt.editPrompt")}),e.jsxs("span",{className:"char-count",children:[o.length," ",a("config:systemPrompt.characters")]})]}),e.jsx("textarea",{id:"prompt-input",className:"prompt-editor",value:o,onChange:P,placeholder:a("config:systemPrompt.placeholder"),rows:18,autoFocus:!0}),e.jsx("div",{className:"editor-hint",children:a("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:A,disabled:!o||n,children:a("config:systemPrompt.clear")})}),e.jsxs("div",{className:"footer-buttons-right",children:[e.jsx("button",{className:"btn btn-secondary",onClick:K,children:"Close"}),e.jsx("button",{className:"btn btn-secondary",onClick:M,disabled:!f||n,children:a("config:systemPrompt.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:C,disabled:!f||n,children:a("config:systemPrompt.save")})]})]})]})}),e.jsx(ge,{isOpen:y,title:a("config:systemPrompt.clear"),message:a("config:systemPrompt.confirmClear"),confirmLabel:a("config:systemPrompt.clear"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{V()},onClose:()=>j(!1)}),e.jsx(ge,{isOpen:h,title:"Unsaved Changes",message:"You have unsaved changes. Close anyway?",confirmLabel:"Close anyway",cancelLabel:"Keep editing",variant:"danger",onConfirm:t,onClose:()=>_(!1)})]}):null}const Xe={enabled:!1,baseUrl:"",defaultSessionId:"",webhookVerifyToken:"",showIncomingToasts:!0},ba=2500,ja=12e4;function Qe(s){return{enabled:s.enabled??!1,baseUrl:s.baseUrl??"",defaultSessionId:s.defaultSessionId??"",webhookVerifyToken:s.webhookVerifyToken??"",showIncomingToasts:s.showIncomingToasts??!0}}function wa(s,t){return s.enabled===t.enabled&&s.baseUrl===t.baseUrl&&s.defaultSessionId===t.defaultSessionId&&s.webhookVerifyToken===t.webhookVerifyToken&&s.showIncomingToasts===t.showIncomingToasts}function ya({isOpen:s,onClose:t}){const{t:a}=Y(["config"]),[o,r]=l.useState(Xe),[d,c]=l.useState(Xe),[n,u]=l.useState(!1),[w,x]=l.useState([]),[b,p]=l.useState(!0),[f,m]=l.useState(null),[y,j]=l.useState(null),[h,_]=l.useState(""),[D,P]=l.useState(!1),[C,A]=l.useState(""),[V,M]=l.useState(null),[K,N]=l.useState(null),[S,H]=l.useState(null),Z=l.useRef(null),ce=l.useRef(0),[k,O]=l.useState(""),[B,v]=l.useState(""),[F,R]=l.useState(null),[Q,ae]=l.useState(!1),[ee,T]=l.useState(!1),[q,ne]=l.useState(!1),[re,te]=l.useState(!1),[pe,ye]=l.useState(null),ve=!wa(o,d),ie=l.useCallback(()=>{Z.current&&(clearTimeout(Z.current),Z.current=null)},[]),L=l.useCallback(async()=>{try{p(!0),m(null),j(null);const[g,z]=await Promise.all([os(),ys()]),oe=Qe(g);if(r(oe),c(oe),u(!!z.configured),z.configured)try{const fe=await Be();x(Array.isArray(fe)?fe:[])}catch{x([])}else x([])}catch(g){m(g instanceof Error?g.message:a("config:whatsapp.errors.loadFailed"))}finally{p(!1)}},[a]),he=l.useCallback(async()=>{try{const g=await Be();x(Array.isArray(g)?g:[])}catch{}},[]);l.useEffect(()=>(s?L():(ie(),M(null),N(null),H(null),_(""),P(!1),R(null)),()=>{ie()}),[s,L,ie]);const se=(g,z)=>{r(oe=>({...oe,[g]:z})),m(null),j(null)},Le=async()=>{try{m(null),j(null);const g=await Ss({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 z=Qe(g);r(z),c(z),j(a("config:whatsapp.saved"))}catch(g){m(g instanceof Error?g.message:a("config:whatsapp.errors.saveFailed"))}},Se=()=>{r(d),m(null),j(null)},be=()=>{if(ve){T(!0);return}t()},De=g=>{g.key==="Escape"&&(g.preventDefault(),be())},Te=async()=>{const g=h.trim();if(g)try{m(null),j(null),await Ns(g),_(""),P(!1),u(!0),j(a("config:whatsapp.apiKeySaved"))}catch(z){m(z instanceof Error?z.message:a("config:whatsapp.errors.apiKeySaveFailed"))}},Fe=()=>{ne(!0)},Ae=async()=>{try{m(null),j(null),await Ts(),u(!1),j(a("config:whatsapp.apiKeyCleared"))}catch(g){m(g instanceof Error?g.message:a("config:whatsapp.errors.apiKeyClearFailed"))}},_e=l.useCallback(async g=>{if(Date.now()>ce.current){H(a("config:whatsapp.pairingTimeout")),M(null),N(null),ie(),he();return}try{const z=await vs(g);if(z.status&&["connected","paired","open","ready"].includes(z.status.toLowerCase())){H(a("config:whatsapp.pairingSuccess")),M(null),N(null),ie(),he();return}const fe=z.qrUrl??z.qr??null;fe&&N(fe)}catch(z){H(z instanceof Error?z.message:a("config:whatsapp.errors.qrFetchFailed"))}Z.current=setTimeout(()=>{_e(g)},ba)},[he,ie,a]),Ee=async()=>{const g=C.trim();if(g)try{m(null),j(null),H(null),N(null),ie(),await ks(g),A(""),M(g),ce.current=Date.now()+ja,_e(g),he()}catch(z){m(z instanceof Error?z.message:a("config:whatsapp.errors.sessionCreateFailed"))}},Ne=()=>{ie(),M(null),N(null),H(null)},Oe=g=>{ye(g),te(!0)},Ie=async()=>{if(pe)try{m(null),j(null),await As(pe),V===pe&&Ne(),he(),j(a("config:whatsapp.sessionDeleted"))}catch(g){m(g instanceof Error?g.message:a("config:whatsapp.errors.sessionDeleteFailed"))}finally{ye(null)}},ue=async()=>{const g=k.trim(),z=B.trim();if(!(!g||!z))try{ae(!0),R(null);const oe=o.defaultSessionId.trim()||void 0;await Cs(g,z,oe),R({kind:"success",text:a("config:whatsapp.testSent")})}catch(oe){R({kind:"error",text:oe instanceof Error?oe.message:a("config:whatsapp.errors.testSendFailed")})}finally{ae(!1)}};return s?e.jsxs(Ce,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:be,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:a("config:whatsapp.title")}),e.jsx("button",{className:"modal-close",onClick:be,"aria-label":"Close",children:e.jsx($,{name:"close",size:16})})]}),e.jsx("div",{className:"modal-body",children:b?e.jsxs("div",{className:"loading-state",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:a("config:whatsapp.loading")})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"modal-description",children:a("config:whatsapp.description")}),f&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx($,{name:"warn",size:14})}),f]}),y&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx($,{name:"check",size:14})}),y]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:a("config:whatsapp.sections.general")}),e.jsxs("div",{className:"wa-field wa-field-row",children:[e.jsx("label",{htmlFor:"wa-enabled",className:"wa-label",children:a("config:whatsapp.enabled")}),e.jsxs("label",{className:"wa-toggle",children:[e.jsx("input",{id:"wa-enabled",type:"checkbox",checked:o.enabled,onChange:g=>se("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:a("config:whatsapp.showIncomingToasts")}),e.jsxs("label",{className:"wa-toggle",children:[e.jsx("input",{id:"wa-show-toasts",type:"checkbox",checked:o.showIncomingToasts,onChange:g=>se("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:a("config:whatsapp.showIncomingToastsHelp")}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-base-url",className:"wa-label",children:a("config:whatsapp.baseUrl")}),e.jsx("input",{id:"wa-base-url",type:"text",className:"wa-input",placeholder:"http://localhost:3007",value:o.baseUrl,onChange:g=>se("baseUrl",g.target.value)})]}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-default-session",className:"wa-label",children:a("config:whatsapp.defaultSessionId")}),e.jsx("input",{id:"wa-default-session",type:"text",className:"wa-input",placeholder:a("config:whatsapp.defaultSessionIdPlaceholder"),value:o.defaultSessionId,onChange:g=>se("defaultSessionId",g.target.value)})]}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-webhook-token",className:"wa-label",children:a("config:whatsapp.webhookVerifyToken")}),e.jsx("input",{id:"wa-webhook-token",type:"text",className:"wa-input",placeholder:a("config:whatsapp.webhookVerifyTokenPlaceholder"),value:o.webhookVerifyToken,onChange:g=>se("webhookVerifyToken",g.target.value)})]})]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:a("config:whatsapp.sections.apiKey")}),e.jsx("div",{className:"wa-key-status",children:n?e.jsxs("span",{className:"wa-status wa-status-ok",children:[e.jsx($,{name:"check",size:12})," ",a("config:whatsapp.configured")]}):e.jsxs("span",{className:"wa-status wa-status-warn",children:[e.jsx($,{name:"warn",size:12})," ",a("config:whatsapp.notConfigured")]})}),e.jsxs("div",{className:"wa-field wa-field-inline",children:[e.jsx("input",{type:D?"text":"password",className:"wa-input",placeholder:a("config:whatsapp.apiKeyPlaceholder"),value:h,onChange:g=>_(g.target.value)}),e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>P(g=>!g),title:a(D?"config:whatsapp.hideKey":"config:whatsapp.showKey"),children:e.jsx($,{name:D?"eye-closed":"eye",size:14})}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:Te,disabled:!h.trim(),children:a("config:whatsapp.saveKey")}),e.jsx("button",{type:"button",className:"btn btn-danger",onClick:Fe,disabled:!n,children:a("config:whatsapp.clearKey")})]}),e.jsx("span",{className:"wa-hint",children:a("config:whatsapp.apiKeyHint")})]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:a("config:whatsapp.sections.sessions")}),e.jsx("div",{className:"wa-sessions-list",children:!Array.isArray(w)||w.length===0?e.jsx("div",{className:"wa-empty",children:a("config:whatsapp.noSessions")}):w.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:()=>Oe(g.id),children:a("config:whatsapp.deleteSession")})]},g.id))}),e.jsxs("div",{className:"wa-field wa-field-inline",children:[e.jsx("input",{type:"text",className:"wa-input",placeholder:a("config:whatsapp.addSessionPlaceholder"),value:C,onChange:g=>A(g.target.value),onKeyDown:g=>{g.key==="Enter"&&Ee()}}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:Ee,disabled:!C.trim()||V!==null,children:a("config:whatsapp.addSession")})]}),V&&e.jsxs("div",{className:"wa-qr-panel",children:[e.jsxs("div",{className:"wa-qr-header",children:[e.jsx("span",{children:a("config:whatsapp.qrPrompt",{id:V})}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ne,children:a("config:whatsapp.cancelPairing")})]}),K?e.jsx("div",{className:"wa-qr-image",children:e.jsx("img",{src:K,alt:"WhatsApp pairing QR code"})}):e.jsxs("div",{className:"wa-qr-loading",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:a("config:whatsapp.waitingForQr")})]})]}),S&&!V&&e.jsx("div",{className:"wa-pairing-message",children:S})]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:a("config:whatsapp.sections.testMessage")}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-test-to",className:"wa-label",children:a("config:whatsapp.testTo")}),e.jsx("input",{id:"wa-test-to",type:"text",className:"wa-input",placeholder:a("config:whatsapp.testToPlaceholder"),value:k,onChange:g=>O(g.target.value)})]}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-test-message",className:"wa-label",children:a("config:whatsapp.testMessageBody")}),e.jsx("textarea",{id:"wa-test-message",className:"wa-textarea",rows:4,placeholder:a("config:whatsapp.testMessageBodyPlaceholder"),value:B,onChange:g=>v(g.target.value)})]}),e.jsx("div",{className:"wa-field-inline wa-field-end",children:e.jsx("button",{type:"button",className:"btn btn-primary",onClick:ue,disabled:!k.trim()||!B.trim()||Q,children:a(Q?"config:whatsapp.sending":"config:whatsapp.sendTest")})}),F&&e.jsxs("div",{className:`alert ${F.kind==="success"?"alert-success":"alert-error"}`,children:[e.jsx("span",{className:"alert-icon",children:e.jsx($,{name:F.kind==="success"?"check":"warn",size:14})}),F.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:be,children:a("config:whatsapp.close")}),e.jsx("button",{className:"btn btn-secondary",onClick:Se,disabled:!ve||b,children:a("config:whatsapp.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:Le,disabled:!ve||b,children:a("config:whatsapp.save")})]})]})]})}),e.jsx(ge,{isOpen:ee,title:a("config:whatsapp.unsavedTitle"),message:a("config:whatsapp.unsavedMessage"),confirmLabel:a("config:whatsapp.closeAnyway"),cancelLabel:a("config:whatsapp.keepEditing"),variant:"danger",onConfirm:()=>{T(!1),t()},onClose:()=>T(!1)}),e.jsx(ge,{isOpen:q,title:a("config:whatsapp.clearKey"),message:a("config:whatsapp.confirmClearKey"),confirmLabel:a("config:whatsapp.clearKey"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{Ae()},onClose:()=>ne(!1)}),e.jsx(ge,{isOpen:re,title:a("config:whatsapp.deleteSession"),message:a("config:whatsapp.confirmDeleteSession",{id:pe??""}),confirmLabel:a("config:whatsapp.deleteSession"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{Ie()},onClose:()=>{te(!1),ye(null)}})]}):null}const cs=["messages","statusChanges","taskComplete","errors","planReady","agentSpawned","agentStopped"];function He(s=!1){const t=X(),a={};return t&&(a.Authorization=`Bearer ${t}`),s&&(a["Content-Type"]="application/json"),a}async function We(s,t){try{const a=await s.json();if(a&&typeof a.error=="string")return a.error;if(a&&typeof a.message=="string")return a.message}catch{}return`${t}: ${s.statusText}`}async function va(){const s=await fetch(`${J()}/api/whatsapp/notification-config`,{headers:He()});if(!s.ok)throw new Error(await We(s,"Failed to fetch WhatsApp notification config"));return s.json()}async function Na(s){const t=await fetch(`${J()}/api/whatsapp/notification-config`,{method:"PATCH",headers:He(!0),body:JSON.stringify(s)});if(!t.ok)throw new Error(await We(t,"Failed to update WhatsApp notification config"));return t.json()}async function ka(){const s=await fetch(`${J()}/api/whatsapp/notification-config`,{method:"DELETE",headers:He()});if(!s.ok)throw new Error(await We(s,"Failed to reset WhatsApp notification config"));return s.json()}const $e={messages:!0,statusChanges:!0,taskComplete:!0,errors:!0,planReady:!0,agentSpawned:!0,agentStopped:!0},es={filter:{...$e},recipient:""};function Ca(s,t){if(s.recipient!==t.recipient)return!1;for(const a of cs)if(s.filter[a]!==t.filter[a])return!1;return!0}function Sa({isOpen:s,onClose:t}){const{t:a}=Y(["config"]),[o,r]=l.useState(es),[d,c]=l.useState(es),[n,u]=l.useState(!0),[w,x]=l.useState(null),[b,p]=l.useState(null),[f,m]=l.useState(!1),[y,j]=l.useState(!1),h=!Ca(o,d),_=l.useCallback(async()=>{try{u(!0),x(null),p(null);const N=await va(),S={filter:{...$e,...N.filter},recipient:N.recipient??""};r(S),c(S)}catch(N){x(N instanceof Error?N.message:a("config:whatsappNotifications.errors.loadFailed"))}finally{u(!1)}},[a]);l.useEffect(()=>{s&&_()},[s,_]);const D=(N,S)=>{r(H=>({...H,filter:{...H.filter,[N]:S}})),x(null),p(null)},P=N=>{r(S=>({...S,recipient:N})),x(null),p(null)},C=async()=>{try{x(null),p(null);const N=await Na({filter:o.filter,recipient:o.recipient.trim()}),S={filter:{...$e,...N.filter},recipient:N.recipient??""};r(S),c(S),p(a("config:whatsappNotifications.saved"))}catch(N){x(N instanceof Error?N.message:a("config:whatsappNotifications.errors.saveFailed"))}},A=()=>{r(d),x(null),p(null)},V=async()=>{try{x(null),p(null);const N=await ka(),S={filter:{...$e,...N.filter},recipient:N.recipient??""};r(S),c(S),p(a("config:whatsappNotifications.resetDone"))}catch(N){x(N instanceof Error?N.message:a("config:whatsappNotifications.errors.resetFailed"))}},M=()=>{if(h){m(!0);return}t()},K=N=>{N.key==="Escape"&&(N.preventDefault(),M())};return s?e.jsxs(Ce,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:M,children:e.jsxs("div",{className:"whatsapp-notifications-modal",onClick:N=>N.stopPropagation(),onKeyDown:K,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:a("config:whatsappNotifications.title")}),e.jsx("button",{className:"modal-close",onClick:M,"aria-label":"Close",children:e.jsx($,{name:"close",size:16})})]}),e.jsx("div",{className:"modal-body",children:n?e.jsxs("div",{className:"loading-state",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:a("config:whatsappNotifications.loading")})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"modal-description",children:a("config:whatsappNotifications.description")}),w&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx($,{name:"warn",size:14})}),w]}),b&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx($,{name:"check",size:14})}),b]}),e.jsxs("section",{className:"wan-section",children:[e.jsx("h3",{className:"wan-section-title",children:a("config:whatsappNotifications.sections.recipient")}),e.jsxs("div",{className:"wan-field",children:[e.jsx("label",{htmlFor:"wan-recipient",className:"wan-label",children:a("config:whatsappNotifications.recipientLabel")}),e.jsx("input",{id:"wan-recipient",type:"text",className:"wan-input",placeholder:a("config:whatsappNotifications.recipientPlaceholder"),value:o.recipient,onChange:N=>P(N.target.value)}),e.jsx("span",{className:"wan-hint",children:a("config:whatsappNotifications.recipientHint")})]})]}),e.jsxs("section",{className:"wan-section",children:[e.jsx("h3",{className:"wan-section-title",children:a("config:whatsappNotifications.sections.events")}),e.jsx("p",{className:"wan-section-hint",children:a("config:whatsappNotifications.eventsHint")}),cs.map(N=>e.jsxs("div",{className:"wan-toggle-row",children:[e.jsxs("div",{className:"wan-toggle-info",children:[e.jsx("span",{className:"wan-toggle-title",children:a(`config:whatsappNotifications.events.${N}.title`)}),e.jsx("span",{className:"wan-toggle-help",children:a(`config:whatsappNotifications.events.${N}.help`)})]}),e.jsxs("label",{className:"wan-toggle",children:[e.jsx("input",{type:"checkbox",checked:o.filter[N],onChange:S=>D(N,S.target.checked)}),e.jsx("span",{className:"wan-toggle-track",children:e.jsx("span",{className:"wan-toggle-thumb"})})]})]},N))]})]})}),e.jsxs("div",{className:"modal-footer",children:[e.jsx("div",{className:"footer-buttons-left",children:e.jsx("button",{className:"btn btn-danger",onClick:()=>j(!0),disabled:n,children:a("config:whatsappNotifications.resetToDefaults")})}),e.jsxs("div",{className:"footer-buttons-right",children:[e.jsx("button",{className:"btn btn-secondary",onClick:M,children:a("config:whatsappNotifications.close")}),e.jsx("button",{className:"btn btn-secondary",onClick:A,disabled:!h||n,children:a("config:whatsappNotifications.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:C,disabled:!h||n,children:a("config:whatsappNotifications.save")})]})]})]})}),e.jsx(ge,{isOpen:f,title:a("config:whatsappNotifications.unsavedTitle"),message:a("config:whatsappNotifications.unsavedMessage"),confirmLabel:a("config:whatsappNotifications.closeAnyway"),cancelLabel:a("config:whatsappNotifications.keepEditing"),variant:"danger",onConfirm:()=>{m(!1),t()},onClose:()=>m(!1)}),e.jsx(ge,{isOpen:y,title:a("config:whatsappNotifications.resetToDefaults"),message:a("config:whatsappNotifications.confirmReset"),confirmLabel:a("config:whatsappNotifications.resetToDefaults"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{V(),j(!1)},onClose:()=>j(!1)})]}):null}function rs(s){const t=s.replace(/@.*$/,"");return/^\d{10,15}$/.test(t)?t.startsWith("521")&&t.length===13?`+52 1 ${t.slice(3,5)} ${t.slice(5,9)} ${t.slice(9)}`:t.startsWith("52")&&t.length===12?`+52 ${t.slice(2,4)} ${t.slice(4,8)} ${t.slice(8)}`:t.startsWith("1")&&t.length===11?`+1 ${t.slice(1,4)} ${t.slice(4,7)} ${t.slice(7)}`:`+${t}`:s}function Ta(s,t=Date.now()){const a=s*1e3,o=t-a;if(o<0)return ss(a);const r=Math.floor(o/6e4);if(r<1)return"now";if(r<60)return`${r}m`;const d=Math.floor(r/60);if(d<24)return`${d}h`;const c=Math.floor(d/24);return c===1?"yesterday":c<7?`${c}d`:ss(a)}function ss(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Aa(s){const t=s*1e3;return new Date(t).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}function ds(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 _a(s,t){return s.length<=t?s:s.slice(0,Math.max(0,t-1)).trimEnd()+"…"}function Ea({chats:s,selectedChatId:t,loading:a,error:o,onSelect:r,onRefresh:d,now:c}){const{t:n}=Y(["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:n("config:whatsappHistory.chats")}),e.jsx("button",{type:"button",className:"whatsapp-history-chatlist__refresh",onClick:d,disabled:a,"aria-label":n("config:whatsappHistory.refresh"),title:n("config:whatsappHistory.refresh"),children:"⟳"})]}),o&&e.jsx("div",{className:"whatsapp-history-chatlist__error",children:o}),a&&s.length===0&&e.jsxs("div",{className:"whatsapp-history-chatlist__loading",children:[e.jsx("span",{className:"spinner"}),e.jsx("span",{children:n("config:whatsappHistory.loadingChats")})]}),!a&&!o&&s.length===0&&e.jsx("div",{className:"whatsapp-history-chatlist__empty",children:n("config:whatsappHistory.emptyChats")}),e.jsx("ul",{className:"whatsapp-history-chatlist__items",children:s.map(u=>{const w=ds(u.lastMessageType),x=u.lastMessagePreview||`[${u.lastMessageType}]`,b=u.chatId===t;return e.jsx("li",{className:`whatsapp-history-chatlist__item ${b?"is-selected":""}`,children:e.jsxs("button",{type:"button",className:"whatsapp-history-chatlist__button",onClick:()=>r(u.chatId),children:[e.jsxs("div",{className:"whatsapp-history-chatlist__row",children:[e.jsx("span",{className:"whatsapp-history-chatlist__name",children:rs(u.chatId)}),e.jsx("span",{className:"whatsapp-history-chatlist__time",children:Ta(u.lastTimestamp,c)})]}),e.jsxs("div",{className:"whatsapp-history-chatlist__row whatsapp-history-chatlist__row--secondary",children:[e.jsxs("span",{className:"whatsapp-history-chatlist__preview",children:[u.lastDirection==="outbound"&&e.jsx("span",{className:"whatsapp-history-chatlist__direction",children:"↗ "}),w&&e.jsxs("span",{className:"whatsapp-history-chatlist__preview-icon",children:[w," "]}),_a(x,40)]}),u.unreadCount>0&&e.jsx("span",{className:"whatsapp-history-chatlist__unread",children:u.unreadCount})]})]})},u.chatId)})})]})}function Ia({message:s}){const t=s.direction==="outbound"?"outbound":"inbound",a=ds(s.messageType),o=(s.body??"").trim(),r=o.length>0,d=r?null:`[${s.messageType}]`;return e.jsx("div",{className:`whatsapp-history-bubble whatsapp-history-bubble--${t}`,children:e.jsxs("div",{className:"whatsapp-history-bubble__inner",children:[a&&e.jsx("span",{className:"whatsapp-history-bubble__type-icon",title:s.messageType,children:a}),r?e.jsx("span",{className:"whatsapp-history-bubble__body",children:o}):e.jsx("span",{className:"whatsapp-history-bubble__placeholder",children:d}),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:Aa(s.timestamp)})]})})}const Pa=["all","inbound","outbound"],$a=["all","text","image","audio","video","document","sticker","location","contact","reaction","unknown"];function La({direction:s,type:t,onDirectionChange:a,onTypeChange:o,disabled:r}){const{t:d}=Y(["config"]);return e.jsxs("div",{className:"whatsapp-history-filters",children:[e.jsxs("label",{className:"whatsapp-history-filters__field",children:[e.jsx("span",{children:d("config:whatsappHistory.direction")}),e.jsx("select",{value:s,onChange:c=>a(c.target.value),disabled:r,children:Pa.map(c=>e.jsx("option",{value:c,children:d(`config:whatsappHistory.directionValues.${c}`)},c))})]}),e.jsxs("label",{className:"whatsapp-history-filters__field",children:[e.jsx("span",{children:d("config:whatsappHistory.type")}),e.jsx("select",{value:t,onChange:c=>o(c.target.value),disabled:r,children:$a.map(c=>e.jsx("option",{value:c,children:d(`config:whatsappHistory.typeValues.${c}`)},c))})]})]})}function Da({chatId:s,messages:t,loading:a,loadingMore:o,error:r,hasMore:d,direction:c,type:n,onDirectionChange:u,onTypeChange:w,onLoadMore:x}){const{t:b}=Y(["config"]),p=l.useRef(null),f=l.useRef(null);return l.useEffect(()=>{p.current&&f.current!==s&&(f.current=s,p.current.scrollTop=p.current.scrollHeight)},[s,t.length]),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:rs(s)}),e.jsx(La,{direction:c,type:n,onDirectionChange:u,onTypeChange:w,disabled:a})]}),e.jsxs("div",{className:"whatsapp-history-messages__scroll",ref:p,children:[d&&e.jsx("div",{className:"whatsapp-history-messages__load-more-row",children:e.jsx("button",{type:"button",className:"whatsapp-history-messages__load-more",onClick:x,disabled:o||a,children:b(o?"config:whatsappHistory.loadingOlder":"config:whatsappHistory.loadOlder")})}),r&&e.jsx("div",{className:"whatsapp-history-messages__error",children:r}),a&&t.length===0&&e.jsxs("div",{className:"whatsapp-history-messages__loading",children:[e.jsx("span",{className:"spinner"}),e.jsx("span",{children:b("config:whatsappHistory.loadingMessages")})]}),!a&&!r&&t.length===0&&e.jsx("div",{className:"whatsapp-history-messages__empty",children:b("config:whatsappHistory.emptyMessages")}),t.map(m=>e.jsx(Ia,{message:m},Fa(m)))]})]}):e.jsx("div",{className:"whatsapp-history-messages whatsapp-history-messages--empty",children:e.jsx("div",{className:"whatsapp-history-messages__placeholder",children:b("config:whatsappHistory.selectChat")})})}function Fa(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 us(){const s=X(),t={};return s&&(t.Authorization=`Bearer ${s}`),t}async function ps(s,t){try{const a=await s.json();if(a&&typeof a.error=="string")return a.error;if(a&&typeof a.message=="string")return a.message}catch{}return`${t}: ${s.statusText}`}async function Oa(s){const t=`${J()}/api/whatsapp/chats/${encodeURIComponent(s)}`,a=await fetch(t,{headers:us()});if(!a.ok)throw new Error(await ps(a,"Failed to fetch WhatsApp chats"));return a.json()}async function as(s,t,a={}){const o=new URLSearchParams;a.cursor&&o.set("cursor",a.cursor),typeof a.limit=="number"&&o.set("limit",String(a.limit)),a.direction&&o.set("direction",a.direction),a.type&&o.set("type",a.type);const r=o.toString(),d=`${J()}/api/whatsapp/chats/${encodeURIComponent(s)}/${encodeURIComponent(t)}/messages${r?`?${r}`:""}`,c=await fetch(d,{headers:us()});if(!c.ok)throw new Error(await ps(c,"Failed to fetch WhatsApp messages"));return c.json()}const Ra=50;function Ua({isOpen:s,onClose:t}){const{t:a}=Y(["config"]),[o,r]=l.useState([]),[d,c]=l.useState(null),[n,u]=l.useState(null),[w,x]=l.useState([]),[b,p]=l.useState(!1),[f,m]=l.useState(null),[y,j]=l.useState(null),[h,_]=l.useState([]),[D,P]=l.useState(!1),[C,A]=l.useState(!1),[V,M]=l.useState(null),[K,N]=l.useState(null),[S,H]=l.useState("all"),[Z,ce]=l.useState("all"),[k,O]=l.useState(()=>Date.now()),B=l.useRef(0);l.useEffect(()=>{if(!s)return;const T=window.setInterval(()=>O(Date.now()),6e4);return()=>window.clearInterval(T)},[s]),l.useEffect(()=>{if(!s)return;let T=!1;return(async()=>{var q;try{u(null);const[ne,re]=await Promise.all([Be().catch(()=>[]),os().catch(()=>null)]);if(T)return;r(ne);const te=(re==null?void 0:re.defaultSessionId)||((q=ne[0])==null?void 0:q.id)||null;c(pe=>pe??te)}catch(ne){if(T)return;u(ne instanceof Error?ne.message:String(ne))}})(),()=>{T=!0}},[s]);const v=l.useCallback(async T=>{p(!0),m(null);try{const q=await Oa(T);x(q.chats)}catch(q){m(q instanceof Error?q.message:String(q))}finally{p(!1)}},[]);l.useEffect(()=>{!s||!d||(j(null),_([]),N(null),v(d))},[s,d,v]);const F=l.useMemo(()=>{const T={limit:Ra};return S!=="all"&&(T.direction=S),Z!=="all"&&(T.type=Z),T},[S,Z]),R=l.useCallback(async(T,q,ne)=>{const re=++B.current;P(!0),M(null),_([]),N(null);try{const te=await as(T,q,ne);if(re!==B.current)return;_([...te.messages].reverse()),N(te.nextCursor)}catch(te){if(re!==B.current)return;M(te instanceof Error?te.message:String(te))}finally{re===B.current&&P(!1)}},[]);l.useEffect(()=>{!s||!d||!y||R(d,y,F)},[s,d,y,F,R]);const Q=l.useCallback(async()=>{if(!(!d||!y||!K)){A(!0),M(null);try{const T=await as(d,y,{...F,cursor:K});_(q=>[...[...T.messages].reverse(),...q]),N(T.nextCursor)}catch(T){M(T instanceof Error?T.message:String(T))}finally{A(!1)}}},[d,y,K,F]),ae=l.useCallback(()=>{d&&v(d)},[d,v]),ee=l.useCallback(T=>{T.key==="Escape"&&(T.preventDefault(),t())},[t]);return s?e.jsx(Ce,{children:e.jsx("div",{className:"modal-overlay visible",onClick:t,children:e.jsxs("div",{className:"whatsapp-history-modal",onClick:T=>T.stopPropagation(),onKeyDown:ee,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:a("config:whatsappHistory.title")}),e.jsx("div",{className:"whatsapp-history-modal__session",children:e.jsxs("label",{children:[e.jsx("span",{children:a("config:whatsappHistory.session")}),e.jsxs("select",{value:d??"",onChange:T=>c(T.target.value||null),disabled:o.length===0,children:[o.length===0&&e.jsx("option",{value:"",children:a("config:whatsappHistory.noSessions")}),o.map(T=>e.jsxs("option",{value:T.id,children:[T.id,T.pairedNumber?` (${T.pairedNumber})`:""]},T.id))]})]})}),e.jsx("button",{className:"modal-close",onClick:t,"aria-label":"Close",children:e.jsx($,{name:"close",size:16})})]}),n&&e.jsx("div",{className:"whatsapp-history-modal__alert",children:n}),e.jsxs("div",{className:"whatsapp-history-modal__body",children:[e.jsx(Ea,{chats:w,selectedChatId:y,loading:b,error:f,onSelect:j,onRefresh:ae,now:k}),e.jsx(Da,{chatId:y,messages:h,loading:D,loadingMore:C,error:V,hasMore:K!==null,direction:S,type:Z,onDirectionChange:H,onTypeChange:ce,onLoadMore:Q})]})]})})}):null}function za({isOpen:s,onClose:t,onOpenConfig:a,onOpenNotifications:o,onOpenHistory:r}){const{t:d}=Y(["config"]);if(l.useEffect(()=>{if(!s)return;const n=u=>{u.key==="Escape"&&(u.preventDefault(),t())};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[s,t]),!s)return null;const c=n=>{t(),n()};return e.jsx(Ce,{children:e.jsx("div",{className:"modal-overlay visible",onClick:t,children:e.jsxs("div",{className:"whatsapp-hub-modal",onClick:n=>n.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("h2",{children:[e.jsx("span",{className:"whatsapp-hub-modal__icon",children:"📱"}),d("config:whatsappHub.title",{defaultValue:"WhatsApp"})]}),e.jsx("button",{className:"modal-close",onClick:t,"aria-label":"Close",children:e.jsx($,{name:"close",size:16})})]}),e.jsxs("div",{className:"modal-body",children:[e.jsx("p",{className:"whatsapp-hub-modal__intro",children:d("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(a),children:[e.jsx("span",{className:"whatsapp-hub-modal__option-icon",children:e.jsx($,{name:"gear",size:18})}),e.jsxs("span",{className:"whatsapp-hub-modal__option-text",children:[e.jsx("span",{className:"whatsapp-hub-modal__option-title",children:d("config:whatsappHub.config",{defaultValue:"Integration config"})}),e.jsx("span",{className:"whatsapp-hub-modal__option-desc",children:d("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($,{name:"bell",size:18})}),e.jsxs("span",{className:"whatsapp-hub-modal__option-text",children:[e.jsx("span",{className:"whatsapp-hub-modal__option-title",children:d("config:whatsappHub.notifications",{defaultValue:"Notifications"})}),e.jsx("span",{className:"whatsapp-hub-modal__option-desc",children:d("config:whatsappHub.notificationsDesc",{defaultValue:"Which agent events get forwarded and to whom."})})]})]}),e.jsxs("button",{type:"button",className:"whatsapp-hub-modal__option",onClick:()=>c(r),children:[e.jsx("span",{className:"whatsapp-hub-modal__option-icon",children:e.jsx($,{name:"hourglass",size:18})}),e.jsxs("span",{className:"whatsapp-hub-modal__option-text",children:[e.jsx("span",{className:"whatsapp-hub-modal__option-title",children:d("config:whatsappHub.history",{defaultValue:"History"})}),e.jsx("span",{className:"whatsapp-hub-modal__option-desc",children:d("config:whatsappHub.historyDesc",{defaultValue:"Browse persisted chats and messages."})})]})]})]})]})]})})})}const Ma=[{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:"🌙"}],Ba=[{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:"🔴"}],Va=[{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:"👎"}],Ka=[{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:"💜"}],Ha=[{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"}],Wa=[{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"}],qa={showTrees:"trees",showBushes:"bushes",showHouse:"house",showLamps:"lamps",showGrass:"grass",showClouds:"clouds"},Ga={none:"grass","pokemon-stadium":"pokemon"},Ya={"emote-yes":"yes","emote-no":"no"},Ja={"":"auto","#4a90d9":"dayBlue","#0a1a2a":"night","#ff6b35":"sunset","#1a0a2e":"purple","#2d5a27":"matrix","#8b0000":"blood","#000000":"void"};function le({checked:s,onChange:t}){return e.jsxs("label",{className:"config-toggle",children:[e.jsx("input",{type:"checkbox",className:"config-toggle-input",checked:s,onChange:a=>t(a.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})}function je({options:s,value:t,onChange:a,iconOnly:o=!1}){return e.jsx("div",{className:"chip-selector",children:s.map(r=>e.jsxs("button",{className:`chip ${t===r.value?"active":""}`,onClick:()=>a(r.value),title:r.label,children:[e.jsx("span",{className:"chip-icon",children:r.icon}),!o&&e.jsx("span",{className:"chip-label",children:r.label})]},r.value))})}function I({text:s,query:t}){if(!t.trim())return e.jsx(e.Fragment,{children:s});const a=s.toLowerCase(),o=t.toLowerCase(),r=a.indexOf(o);if(r===-1)return e.jsx(e.Fragment,{children:s});const d=s.slice(0,r),c=s.slice(r,r+t.length),n=s.slice(r+t.length);return e.jsxs(e.Fragment,{children:[d,e.jsx("mark",{className:"search-highlight",children:c}),n]})}const Za=[{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"]},{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:"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"]}],Me=[{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 Xa({config:s,onChange:t,searchQuery:a="",onOpenIntegrationsModal:o,onOpenMonitoringModal:r,onOpenWorkflowEditor:d,onOpenTriggerManager:c}){var qe;const{t:n}=Y(["config","common"]),u=Ve(),w=_s(),[x,b]=l.useState(()=>Es(ke.DEFAULT_AGENT_CLASS)||"scout"),[p,f]=l.useState(u.settings.historyLimit),[m,y]=l.useState(()=>Is()),[j,h]=l.useState(!1),[_,D]=l.useState(""),[P,C]=l.useState(()=>X()),[A,V]=l.useState(!1),[M,K]=l.useState(!1),[N,S]=l.useState(""),[H,Z]=l.useState(!1),[ce,k]=l.useState(!1),[O,B]=l.useState(!1),[v,F]=l.useState(!1),[R,Q]=l.useState(!1),[ae,ee]=l.useState(""),[T,q]=l.useState(!1);l.useEffect(()=>{aa().then(ee).catch(()=>{})},[]),l.useEffect(()=>{ea().then(i=>{i!==u.settings.experimentalEchoPrompt&&E.updateSettings({experimentalEchoPrompt:i})}).catch(()=>{})},[]),l.useEffect(()=>{na().then(i=>{i!==u.settings.tmuxMode&&E.updateSettings({tmuxMode:i})}).catch(()=>{})},[]),l.useEffect(()=>Ps(i=>{y(i),h(!1)}),[]);const ne=Ma.map(i=>({...i,label:n(`config:time.${i.value}`)})),re=Ba.map(i=>({...i,label:n(`config:floor.${Ga[i.value]||i.value}`)})),te=Va.map(i=>({...i,label:n(`config:animation.${Ya[i.value]||i.value}`)})),pe=Ka.map(i=>({...i,label:n(`config:colorMode.${i.value}`)})),ye=Ha.map(i=>({...i,label:n(`config:terrain.${qa[i.key]}`)})),ve=Wa.map(i=>({...i,label:n(`config:sky.${Ja[i.value??""]}`)})),ie=a.trim()?Za.filter(i=>{const U=a.toLowerCase();return i.title.toLowerCase().includes(U)||i.keywords.some(de=>de.toLowerCase().includes(U))}).map(i=>i.id):null,L=i=>ie?ie.includes(i):!0,he=L("integrations"),se=u.settings.customAgentNames||[],Le=se.length>0?se:$s,Se=()=>{const i=N.trim();i&&!se.includes(i)&&(E.updateSettings({customAgentNames:[...se,i]}),S(""))},be=i=>{E.updateSettings({customAgentNames:se.filter(U=>U!==i)})},De=()=>{E.updateSettings({customAgentNames:[]})},Te=()=>{const i=_.trim();if(i){if(m.includes(i)){D("");return}y([...m,i]),h(!0),D("")}},Fe=i=>{y(m.filter((U,de)=>de!==i)),h(!0)},Ae=(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]],y(xe),h(!0)},_e=()=>{Ds(m),h(!1),ze()},Ee=i=>{C(i),V(!0)},Ne=()=>{Pe(ke.AUTH_TOKEN,P),V(!1),ze()},Oe=i=>{ee(i),q(!0)},Ie=()=>{ta(ae).catch(()=>{}),q(!1)},ue=i=>{t({...s,terrain:{...s.terrain,...i}})},g=i=>{t({...s,modelStyle:{...s.modelStyle,...i}})},z=i=>{t({...s,animations:{...s.animations,...i}})},oe=i=>{f(i),E.updateSettings({historyLimit:i})},fe=i=>{const U=s.terrain[i];typeof U=="boolean"&&ue({[i]:!U})},G=a.trim().length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"config-section",children:[ie&&ie.length===0&&e.jsx("div",{className:"config-no-results",children:n("config:noResults",{query:a})}),L("general")&&e.jsxs(W,{title:n("config:sections.general"),storageKey:"general",defaultOpen:!0,forceOpen:G&&L("general"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:general.history"),query:a})}),e.jsx("input",{type:"number",className:"config-input config-input-sm",value:p,onChange:i=>oe(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(I,{text:n("config:general.hideCosts"),query:a})}),e.jsx(le,{checked:u.settings.hideCost,onChange:i=>E.updateSettings({hideCost:i})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:general.grid"),query:a})}),e.jsx(le,{checked:s.gridVisible,onChange:i=>t({...s,gridVisible:i})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:general.showFPS"),query:a})}),e.jsx(le,{checked:u.settings.showFPS,onChange:i=>E.updateSettings({showFPS:i})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:general.fpsLimit"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"120",step:"10",value:s.fpsLimit,onChange:i=>t({...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(I,{text:n("config:general.powerSaving"),query:a})," ",e.jsx($,{name:"bolt",size:12})]}),e.jsx(le,{checked:u.settings.powerSaving,onChange:i=>E.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(I,{text:n("config:general.tmuxMode"),query:a})}),e.jsx(le,{checked:u.settings.tmuxMode,onChange:async i=>{E.updateSettings({tmuxMode:i});try{await ia(i)}catch(U){console.error("Failed to sync tmux mode setting to server:",U)}}})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:general.vibrationIntensity"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"5",step:"1",value:u.settings.vibrationIntensity,onChange:i=>E.updateSettings({vibrationIntensity:parseInt(i.target.value)})}),e.jsx("span",{className:"config-value",children:u.settings.vibrationIntensity===0?n("config:vibrationValues.off"):u.settings.vibrationIntensity===1?n("config:vibrationValues.ultraLight"):u.settings.vibrationIntensity===2?n("config:vibrationValues.veryLight"):u.settings.vibrationIntensity===3?n("config:vibrationValues.light"):u.settings.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(I,{text:n("config:general.externalEditor"),query:a})}),e.jsx("input",{type:"text",className:"config-input",placeholder:n("config:general.externalEditorPlaceholder"),value:u.settings.externalEditorCommand||"",onChange:i=>E.updateSettings({externalEditorCommand:i.target.value})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:general.tabTitle"),query:a})}),e.jsx("input",{type:"text",className:"config-input",placeholder:n("config:general.tabTitlePlaceholder"),value:u.settings.tabTitle||"",onChange:i=>E.updateSettings({tabTitle:i.target.value})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:general.language"),query:a})}),e.jsx(je,{options:Me,value:localStorage.getItem("tide-commander-language-mode")==="manual"?((qe=Me.find(i=>i.value!=="auto"&&Ue.language.startsWith(i.value.split("-")[0])))==null?void 0:qe.value)||"en":"auto",onChange:i=>{var U;if(i==="auto"){localStorage.setItem("tide-commander-language-mode","auto");const de=navigator.language,xe=((U=Me.find(Ge=>Ge.value!=="auto"&&de.startsWith(Ge.value.split("-")[0])))==null?void 0:U.value)||"en";Ue.changeLanguage(xe)}else localStorage.setItem("tide-commander-language-mode","manual"),Ue.changeLanguage(i)}})]})]}),L("agentNames")&&e.jsx(W,{title:n("config:sections.agentNames"),storageKey:"agentNames",defaultOpen:!1,forceOpen:G&&L("agentNames"),children:e.jsxs("div",{className:"agent-names-section",children:[e.jsx("span",{className:"config-hint",children:se.length>0?n("config:agentNames.customConfigured",{count:se.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:N,onChange:i=>S(i.target.value),onKeyDown:i=>{i.key==="Enter"&&Se()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:Se,disabled:!N.trim(),title:n("config:agentNames.addName"),children:"+"})]}),e.jsx("div",{className:"agent-names-list",children:Le.map((i,U)=>e.jsxs("div",{className:"agent-name-chip",children:[e.jsx("span",{className:"agent-name-text",children:i}),se.length>0&&e.jsx("button",{className:"agent-name-remove",onClick:()=>be(i),title:n("common:buttons.remove"),children:"x"})]},`${i}-${U}`))}),se.length>0&&e.jsx("button",{className:"config-btn config-btn-link",onClick:De,children:n("common:buttons.resetToDefaults")})]})}),L("defaultClass")&&e.jsx(W,{title:"Default Spawn Class",storageKey:"defaultClass",defaultOpen:!1,forceOpen:G&&L("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${x==="random"?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{b("random"),Pe(ke.DEFAULT_AGENT_CLASS,"random")},children:e.jsx("span",{className:"agent-name-text",children:"🎲 Random"})}),Object.entries(Ls).map(([i,U])=>e.jsx("div",{className:`agent-name-chip${x===i?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{b(i),Pe(ke.DEFAULT_AGENT_CLASS,i)},children:e.jsxs("span",{className:"agent-name-text",children:[U.icon," ",i.charAt(0).toUpperCase()+i.slice(1)]})},i)),w.map(i=>e.jsx("div",{className:`agent-name-chip${x===i.id?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{b(i.id),Pe(ke.DEFAULT_AGENT_CLASS,i.id)},children:e.jsxs("span",{className:"agent-name-text",children:[i.icon," ",i.name]})},i.id))]})]})}),L("appearance")&&e.jsx(W,{title:n("config:sections.appearance"),storageKey:"appearance",defaultOpen:!1,forceOpen:G&&L("appearance"),children:e.jsx(pa,{})}),L("connection")&&e.jsxs(W,{title:n("config:sections.connection"),storageKey:"connection",defaultOpen:!1,forceOpen:G&&L("connection"),children:[e.jsxs("div",{className:"config-row config-row-stacked",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:connection.backendUrl"),query:a})}),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:()=>Ae(U,-1),disabled:U===0,title:n("config:connection.moveUp",{defaultValue:"Move up"}),children:"↑"}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>Ae(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:()=>Fe(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:_,onChange:i=>D(i.target.value),placeholder:n("config:connection.addUrlPlaceholder",{defaultValue:"http://host:port"}),onKeyDown:i=>{i.key==="Enter"&&Te()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:Te,disabled:!_.trim(),title:n("config:connection.addUrl",{defaultValue:"Add URL"}),children:"+"}),j&&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.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(I,{text:n("config:connection.authToken"),query:a})}),e.jsxs("div",{className:"config-input-group",children:[e.jsx("input",{type:M?"text":"password",className:"config-input config-input-full",value:P,onChange:i=>Ee(i.target.value),placeholder:n("config:connection.tokenPlaceholder"),onKeyDown:i=>{i.key==="Enter"&&A&&Ne()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>K(!M),title:n(M?"config:connection.hideToken":"config:connection.showToken"),children:e.jsx($,{name:M?"eye-closed":"eye",size:14})}),A&&e.jsx("button",{className:"config-btn config-btn-sm",onClick:Ne,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(I,{text:n("config:connection.codexBinaryPath"),query:a})}),e.jsxs("div",{className:"config-input-group",children:[e.jsx("input",{type:"text",className:"config-input config-input-full",value:ae,onChange:i=>Oe(i.target.value),placeholder:n("config:connection.codexBinaryPathPlaceholder"),onKeyDown:i=>{i.key==="Enter"&&T&&Ie()}}),T&&e.jsx("button",{className:"config-btn config-btn-sm",onClick:Ie,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(I,{text:n("common:buttons.reconnect"),query:a})}),e.jsx("button",{className:"config-btn",onClick:()=>ze(),title:"Force reconnect to server",children:n("common:buttons.reconnect")})]})]}),L("scene")&&e.jsxs(W,{title:n("config:sections.scene"),storageKey:"scene",defaultOpen:!1,forceOpen:G&&L("scene"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:scene.characterSize"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.3",max:"3.0",step:"0.1",value:s.characterScale,onChange:i=>t({...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(I,{text:n("config:scene.scale2d",{defaultValue:"2D Scale"}),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.3",max:"2.0",step:"0.1",value:s.scale2d,onChange:i=>t({...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(I,{text:n("config:scene.scale3d",{defaultValue:"3D Scale"}),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.3",max:"2.0",step:"0.1",value:s.scale3d,onChange:i=>t({...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(I,{text:n("config:scene.show2DTaskLabels",{defaultValue:"Show 2D task labels"}),query:a})}),e.jsx(le,{checked:s.show2DTaskLabels,onChange:i=>t({...s,show2DTaskLabels:i})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:scene.time"),query:a})}),e.jsx(je,{options:ne,value:s.timeMode,onChange:i=>t({...s,timeMode:i}),iconOnly:!0})]})]}),L("terrain")&&e.jsxs(W,{title:n("config:sections.terrain"),storageKey:"terrain",defaultOpen:!1,forceOpen:G&&L("terrain"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:terrainSettings.simpleMode",{defaultValue:"Simple Mode"}),query:a})}),e.jsx(le,{checked:s.terrain.simpleMode??!1,onChange:i=>ue({simpleMode:i})})]}),e.jsx("div",{className:"terrain-icons",style:{opacity:s.terrain.simpleMode?.4:1,pointerEvents:s.terrain.simpleMode?"none":"auto"},children:ye.map(i=>e.jsx("button",{className:`terrain-icon-btn ${s.terrain[i.key]?"active":""}`,onClick:()=>fe(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(I,{text:n("config:terrainSettings.fog"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"2",step:"0.1",value:s.terrain.fogDensity,onChange:i=>ue({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(I,{text:n("config:terrainSettings.brightness"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.2",max:"2",step:"0.1",value:s.terrain.brightness,onChange:i=>ue({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(I,{text:n("config:terrainSettings.floor"),query:a})}),e.jsx(je,{options:re,value:s.terrain.floorStyle,onChange:i=>ue({floorStyle:i}),iconOnly:!0})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:terrainSettings.sky"),query:a})}),e.jsx("div",{className:"sky-color-selector",children:ve.map(i=>e.jsx("button",{className:`sky-color-btn ${s.terrain.skyColor===i.value?"active":""}`,onClick:()=>ue({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(I,{text:n("config:terrainSettings.battlefieldSize"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"30",max:"200",step:"10",value:s.terrain.battlefieldSize,onChange:i=>ue({battlefieldSize:parseInt(i.target.value)})}),e.jsx("span",{className:"config-value",children:s.terrain.battlefieldSize})]})]}),L("modelStyle")&&e.jsxs(W,{title:n("config:sections.modelStyle"),storageKey:"modelStyle",defaultOpen:!1,forceOpen:G&&L("modelStyle"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:modelStyleSettings.saturation"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"2",step:"0.1",value:s.modelStyle.saturation,onChange:i=>g({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(I,{text:n("config:modelStyleSettings.roughness"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"-1",max:"1",step:"0.1",value:s.modelStyle.roughness,onChange:i=>g({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(I,{text:n("config:modelStyleSettings.metalness"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"-1",max:"1",step:"0.1",value:s.modelStyle.metalness,onChange:i=>g({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(I,{text:n("config:modelStyleSettings.glow"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"1",step:"0.05",value:s.modelStyle.emissiveBoost,onChange:i=>g({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(I,{text:n("config:modelStyleSettings.reflections"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"-1",max:"2",step:"0.1",value:s.modelStyle.envMapIntensity,onChange:i=>g({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(I,{text:n("config:modelStyleSettings.wireframe"),query:a})}),e.jsx(le,{checked:s.modelStyle.wireframe,onChange:i=>g({wireframe:i})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:modelStyleSettings.colorMode"),query:a})}),e.jsx(je,{options:pe,value:s.modelStyle.colorMode,onChange:i=>g({colorMode:i}),iconOnly:!0})]})]}),L("animations")&&e.jsxs(W,{title:n("config:sections.animations"),storageKey:"animations",defaultOpen:!1,forceOpen:G&&L("animations"),children:[e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:animationSettings.idle"),query:a})}),e.jsx(je,{options:te,value:s.animations.idleAnimation,onChange:i=>z({idleAnimation:i}),iconOnly:!0})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:animationSettings.working"),query:a})}),e.jsx(je,{options:te,value:s.animations.workingAnimation,onChange:i=>z({workingAnimation:i}),iconOnly:!0})]})]}),L("secrets")&&e.jsx(W,{title:n("config:sections.secrets"),storageKey:"secrets",defaultOpen:!1,forceOpen:G&&L("secrets"),children:e.jsx(Js,{})}),L("systemPrompt")&&e.jsx(W,{title:n("config:sections.systemPrompt"),storageKey:"systemPrompt",defaultOpen:!1,forceOpen:G&&L("systemPrompt"),children:e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:n("config:systemPrompt.title"),query:a})}),e.jsx("button",{className:"config-button",onClick:()=>Z(!0),children:n("config:systemPrompt.editPrompt")})]})}),L("data")&&e.jsx(W,{title:n("config:sections.data"),storageKey:"data",defaultOpen:!1,forceOpen:G&&L("data"),children:e.jsx(ra,{})}),he&&e.jsx(W,{title:n("config:sections.integrations"),storageKey:"integrations",defaultOpen:!1,forceOpen:G&&he,children:e.jsx(fa,{onOpenModal:i=>{i==="whatsapp"?Q(!0):o==null||o(i)}})}),L("workflows")&&e.jsxs(W,{title:"Workflows",storageKey:"workflows",defaultOpen:!1,forceOpen:G&&L("workflows"),children:[e.jsx("div",{className:"config-row",children:e.jsx("span",{className:"config-label",children:e.jsx(I,{text:"Create and manage automated workflow pipelines with visual state machine editor",query:a})})}),e.jsx("div",{className:"config-row",children:e.jsx("button",{className:"config-button",onClick:()=>d==null?void 0:d(),children:"Open Workflow Editor"})})]}),L("triggers")&&e.jsxs(W,{title:"Triggers",storageKey:"triggers",defaultOpen:!1,forceOpen:G&&L("triggers"),children:[e.jsx("div",{className:"config-row",children:e.jsx("span",{className:"config-label",children:e.jsx(I,{text:"Create and manage event-driven triggers that fire agents with templates",query:a})})}),e.jsx("div",{className:"config-row",children:e.jsx("button",{className:"config-button",onClick:()=>c==null?void 0:c(),children:"Open Trigger Manager"})})]}),L("monitoring")&&e.jsxs(W,{title:"Monitoring",storageKey:"monitoring",defaultOpen:!1,forceOpen:G&&L("monitoring"),children:[e.jsx("div",{className:"config-row",children:e.jsx("span",{className:"config-label",children:e.jsx(I,{text:"View event logs, trigger history, workflow traces, and system stats",query:a})})}),e.jsx("div",{className:"config-row",children:e.jsx("button",{className:"config-button",onClick:()=>r==null?void 0:r(),children:"Open Monitoring & Logs"})})]}),L("experimental")&&e.jsxs(W,{title:n("config:sections.experimental"),storageKey:"experimental",defaultOpen:!1,forceOpen:G&&L("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(I,{text:n("config:experimental.2dView"),query:a})," ",e.jsx($,{name:"map",size:12})]}),e.jsx(le,{checked:u.settings.experimental2DView,onChange:i=>E.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(I,{text:n("config:experimental.voiceAssistant"),query:a})," ",e.jsx($,{name:"microphone",size:12})]}),e.jsx(le,{checked:u.settings.experimentalVoiceAssistant,onChange:i=>E.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(I,{text:n("config:experimental.tts"),query:a})," ",e.jsx($,{name:"speaker-on",size:12})]}),e.jsx(le,{checked:u.settings.experimentalTTS,onChange:i=>E.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(I,{text:n("config:experimental.echoPrompt"),query:a})}),e.jsx(le,{checked:u.settings.experimentalEchoPrompt,onChange:async i=>{E.updateSettings({experimentalEchoPrompt:i});try{await sa(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")})]}),L("about")&&e.jsx(W,{title:n("config:sections.about"),storageKey:"about",defaultOpen:!1,forceOpen:G&&L("about"),children:e.jsx(ma,{})})]}),e.jsx(xa,{isOpen:H,onClose:()=>Z(!1)}),e.jsx(ya,{isOpen:ce,onClose:()=>k(!1)}),e.jsx(Sa,{isOpen:O,onClose:()=>B(!1)}),e.jsx(Ua,{isOpen:v,onClose:()=>F(!1)}),e.jsx(za,{isOpen:R,onClose:()=>Q(!1),onOpenConfig:()=>k(!0),onOpenNotifications:()=>B(!0),onOpenHistory:()=>F(!0)})]})}function at({onConfigChange:s,onToolChange:t,config:a,isOpen:o,onClose:r,onOpenBuildingModal:d,onOpenAreaExplorer:c,onOpenIntegrationsModal:n,onOpenMonitoringModal:u,onOpenWorkflowEditor:w,onOpenTriggerManager:x}){const{t:b}=Y(["config","common"]),p=Ve(),f=Array.from(p.areas.values()),m=Array.from(p.buildings.values()),[y,j]=l.useState(""),h=l.useRef(null);if(l.useEffect(()=>{const C=A=>{A.key==="Escape"&&o&&r()};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[o,r]),l.useEffect(()=>{if(o&&h.current){if(typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches)return;const A=setTimeout(()=>{var V;(V=h.current)==null||V.focus()},50);return()=>clearTimeout(A)}},[o]),!o)return null;const _=C=>{const A=p.activeTool===C?null:C;t(A)},D=C=>{E.selectArea(p.selectedAreaId===C?null:C),t("select")},P=(C,A)=>{C.stopPropagation(),E.deleteArea(A)};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"toolbox-backdrop",onClick:r}),e.jsxs("aside",{className:"toolbox",children:[e.jsxs("div",{className:"toolbox-header",children:[e.jsx("span",{children:b("config:title")}),e.jsx("button",{className:"toolbox-close-btn",onClick:r,title:b("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:h,type:"text",placeholder:b("config:searchPlaceholder"),value:y,onChange:C=>j(C.target.value),className:"toolbox-search-input"}),y&&e.jsx("button",{className:"toolbox-search-clear",onClick:()=>j(""),children:"×"})]}),e.jsxs("div",{className:"toolbox-content",children:[e.jsx("div",{className:"toolbox-section toolbox-section-collapsible",children:e.jsxs(W,{title:b("config:areas.title",{count:f.length}),storageKey:"areas",children:[e.jsxs("div",{className:"tool-buttons",children:[e.jsx("button",{className:`tool-btn ${p.activeTool==="select"?"active":""}`,onClick:()=>_("select"),title:b("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.activeTool==="rectangle"?"active":""}`,onClick:()=>_("rectangle"),title:b("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.activeTool==="circle"?"active":""}`,onClick:()=>_("circle"),title:b("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:f.length===0?e.jsx("div",{className:"areas-empty",children:b("config:areas.drawToCreate")}):f.map(C=>e.jsx(Bs,{area:C,isSelected:p.selectedAreaId===C.id,onClick:()=>D(C.id),onDelete:A=>P(A,C.id)},C.id))})]})}),p.selectedAreaId&&e.jsx(Ys,{area:p.areas.get(p.selectedAreaId),onClose:()=>E.selectArea(null),onOpenFolder:c}),e.jsx("div",{className:"toolbox-section toolbox-section-collapsible",children:e.jsx(W,{title:b("config:buildings.title",{count:m.length}),storageKey:"buildings",headerExtra:e.jsx("button",{className:"add-building-btn",onClick:C=>{C.stopPropagation(),d==null||d()},title:b("config:buildings.addBuilding"),children:"+"}),children:e.jsx("div",{className:"buildings-list",children:m.length===0?e.jsx("div",{className:"buildings-empty",children:b("config:buildings.clickToAdd")}):m.map(C=>e.jsx(Vs,{building:C,isSelected:p.selectedBuildingIds.has(C.id),onClick:()=>{E.selectBuilding(p.selectedBuildingIds.has(C.id)?null:C.id)},onEdit:()=>d==null?void 0:d(C.id)},C.id))})})}),p.selectedBuildingIds.size===1&&(()=>{const C=Array.from(p.selectedBuildingIds)[0],A=p.buildings.get(C);return A?e.jsx(Ks,{building:A,onClose:()=>E.selectBuilding(null),onOpenModal:()=>d==null?void 0:d(C)}):null})(),e.jsx(Xa,{config:a,onChange:s,searchQuery:y,onOpenIntegrationsModal:n,onOpenMonitoringModal:u,onOpenWorkflowEditor:w,onOpenTriggerManager:x})]})]})]})}export{at as Toolbox};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{bo as Oe,r as t,s as I,l as ye,bp as Ee,aJ as _e,j as e,I as z,u as fe,bq as ze,br as Te,bs as Ue,bt as Be,m as Ke,bu as We,bv as De,bw as Ve,a6 as qe,a7 as Ge,bx as Je,aS as Ye,J as Me,S as oe,aM as Xe,aI as Qe,_ as Ze,K as Ie,ah as et,U as tt,by as st,n as X,bz as nt}from"./main-
|
|
1
|
+
import{bo as Oe,r as t,s as I,l as ye,bp as Ee,aJ as _e,j as e,I as z,u as fe,bq as ze,br as Te,bs as Ue,bt as Be,m as Ke,bu as We,bv as De,bw as Ve,a6 as qe,a7 as Ge,bx as Je,aS as Ye,J as Me,S as oe,aM as Xe,aI as Qe,_ as Ze,K as Ie,ah as et,U as tt,by as st,n as X,bz as nt}from"./main-CBiZdw6w.js";import{FileExplorerPanel as at}from"./index-D1nrHGW6.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const Ne={status:"all",activity:"all",sort:"activity"},lt={"1h":3600*1e3,"6h":360*60*1e3,"24h":1440*60*1e3},Ae=20,me=3,ot={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a"},ct=12e4;function rt(s){return s.trim().replace(/\r\n/g,`
|
|
2
2
|
`)}function $e(s,a){return`${s}:${rt(a)}`}function it(s,a,l,f){if(s.uuid&&a.has(s.uuid))return!1;if(s.uuid)return!0;const p=s.isUserPrompt?"user":"assistant",d=$e(p,s.text),M=s.timestamp||0,A=l.get(d);return A!==void 0&&Math.abs(M-A)<=ct?!1:M>f}function dt({isOpen:s,agents:a}){const l=Oe(),[f,p]=t.useState(new Map),d=t.useRef(new Set);t.useRef(a);const M=t.useMemo(()=>Array.from(a.keys()).sort().join(","),[a]),A=t.useMemo(()=>Array.from(a.values()).map(j=>`${j.id}:${j.sessionId||""}`).sort().join(","),[a]);t.useEffect(()=>{s||(d.current.clear(),p(new Map))},[s]),t.useEffect(()=>{if(!s)return;const j=new Set(Array.from(a.keys()));for(const i of d.current)j.has(i)||d.current.delete(i);let h=null;l>0&&(h=I.preserveOutputs(),d.current.clear());const v=async(i,C,F=0)=>{if(d.current.add(i.id),F>0&&await new Promise(x=>setTimeout(x,F)),p(x=>{const k=new Map(x);return k.set(i.id,{agentId:i.id,messages:[],loading:!0,hasMore:!1,totalCount:0}),k}),!i.sessionId){C&&C.length>0&&I.mergeOutputsWithHistory(i.id,[],C),p(x=>{const k=new Map(x);return k.set(i.id,{agentId:i.id,messages:[],loading:!1,hasMore:!1,totalCount:0}),k});return}try{const k=await(await _e(ye(`/api/agents/${i.id}/history?limit=${Ee}&offset=0`))).json(),P=k.messages||[],W=P.length>0?Math.max(...P.map(w=>w.timestamp?new Date(w.timestamp).getTime():0)):0,J=new Set(P.map(w=>w.uuid).filter(w=>!!w)),V=new Map;for(const w of P){if(w.type!=="user"&&w.type!=="assistant")continue;const c=$e(w.type,w.content),L=w.timestamp?new Date(w.timestamp).getTime():0,K=V.get(c)??0;L>K&&V.set(c,L)}const q=I.getOutputs(i.id),B=(C&&C.length>0?[...C,...q]:q).filter(w=>it(w,J,V,W));I.clearOutputs(i.id);for(const w of B)I.addOutput(i.id,w);p(w=>{const c=new Map(w);return c.set(i.id,{agentId:i.id,messages:P,loading:!1,hasMore:k.hasMore||!1,totalCount:k.totalCount||0}),c})}catch(x){if(console.error(`Failed to load history for ${i.name}:`,x),C&&C.length>0){I.clearOutputs(i.id);for(const k of C)I.addOutput(i.id,k)}p(k=>{const P=new Map(k);return P.set(i.id,{agentId:i.id,messages:[],loading:!1,hasMore:!1,totalCount:0}),P})}},u=l>0?500:0,D=Array.from(a.values());for(const i of D)if(!d.current.has(i.id)){const C=h==null?void 0:h.get(i.id);v(i,C,u)}},[s,M,A,l]);const R=t.useRef(a),N=t.useRef(f);R.current=a,N.current=f;const b=t.useCallback(async j=>{const h=R.current.get(j),v=N.current.get(j);if(!(h!=null&&h.sessionId)||!v||!v.hasMore)return;const u=v.messages.length;try{const i=await(await fetch(ye(`/api/agents/${j}/history?limit=${Ee}&offset=${u}`))).json();i.messages&&i.messages.length>0&&p(C=>{const F=new Map(C),x=C.get(j);return x&&F.set(j,{...x,messages:[...i.messages,...x.messages],hasMore:i.hasMore||!1}),F})}catch(D){console.error(`Failed to load more history for agent ${j}:`,D)}},[]),E=t.useCallback(j=>{d.current.delete(j),p(h=>{const v=new Map(h),u=h.get(j);return u&&v.set(j,{...u,messages:[],hasMore:!1,totalCount:0,loading:!1}),v})},[]);return{histories:f,loadMoreHistory:b,clearAgentHistory:E}}function ut({command:s,onCommandChange:a,useTextarea:l,forceTextarea:f,onForceTextarea:p,onSend:d,canSend:M,attachedFiles:A,onAddFile:R,onRemoveFile:N,uploadFile:b,onAddPastedText:E,placeholder:j="Message...",className:h="",compact:v=!1,inputRef:u}){const D=t.useRef(null),i=t.useRef(null),C=t.useRef(l);t.useEffect(()=>{if(l&&!C.current&&i.current){const c=i.current;c.focus(),c.selectionStart=c.selectionEnd=c.value.length}C.current=l},[l]),t.useEffect(()=>{const c=i.current;if(!c||!l)return;c.style.height="auto";const L=v?120:180,K=Math.min(c.scrollHeight,L);c.style.height=`${K}px`},[s,l,v]);const F=t.useCallback(async c=>{const L=c.clipboardData.items;for(const _ of L)if(_.type.startsWith("image/")){c.preventDefault();const $=_.getAsFile();if($){const H=await b($);H&&R(H)}return}const K=c.clipboardData.files;if(K.length>0){c.preventDefault();for(const _ of K){const $=await b(_);$&&R($)}return}const U=c.clipboardData.getData("text"),te=(U.match(/\n/g)||[]).length+1;if(te>5){c.preventDefault();const $=`[Pasted text #${E(U)} +${te} lines]`,H=c.target,se=H.selectionStart||0,ae=H.selectionEnd||0,ne=s.slice(0,se)+$+s.slice(ae);a(ne),l||p(!0)}},[s,a,l,p,b,R,E]),x=t.useCallback(async c=>{const L=c.target.files;if(L){for(const K of L){const U=await b(K);U&&R(U)}D.current&&(D.current.value="")}},[b,R]),k=t.useCallback(c=>{if(c.key==="Enter"&&c.shiftKey){l||(c.preventDefault(),p(!0));return}c.key==="Enter"&&(c.preventDefault(),d())},[l,p,d]),P=t.useCallback(c=>{},[]),W=t.useCallback(c=>{c.button===1&&(c.preventDefault(),c.stopPropagation())},[]),J=t.useCallback(c=>{i.current=c,u==null||u(c)},[u]),V=v?"agent-panel-input":"guake-input",q=v?"agent-panel-input-container":"guake-input-container",Q=v?"agent-panel-attach-btn":"guake-attach-btn",B=v?"agent-panel-send-btn":"",w=l?v?"agent-panel-input-expanded":"guake-input-expanded":"";return e.jsxs(e.Fragment,{children:[A.length>0&&e.jsx("div",{className:v?"agent-panel-attachments":"guake-attachments",children:A.map(c=>e.jsxs("div",{className:`${v?"agent-panel-attachment":"guake-attachment"} ${c.isImage?"is-image":""}`,children:[e.jsx("span",{className:v?"agent-panel-attachment-icon":"guake-attachment-icon",children:e.jsx(z,{name:c.isImage?"file":"paperclip",size:12})}),e.jsx("span",{className:v?"agent-panel-attachment-name":"guake-attachment-name",title:c.path,children:c.name}),!v&&e.jsxs("span",{className:"guake-attachment-size",children:["(",Math.round(c.size/1024),"KB)"]}),e.jsx("button",{className:v?"agent-panel-attachment-remove":"guake-attachment-remove",onClick:()=>N(c.id),title:"Remove",children:"×"})]},c.id))}),e.jsxs("div",{className:`${V} ${w} ${h}`,children:[e.jsx("input",{ref:D,type:"file",multiple:!0,onChange:x,style:{display:"none"},accept:"*"}),e.jsxs("div",{className:q,onAuxClick:W,children:[e.jsx("button",{className:Q,onClick:()=>{var c;return(c=D.current)==null?void 0:c.click()},title:"Attach file (or paste image)",children:e.jsx(z,{name:"paperclip",size:14})}),l?e.jsx("textarea",{ref:J,placeholder:j,value:s,onChange:c=>a(c.target.value),onKeyDown:k,onPaste:F,onMouseDown:P}):e.jsx("input",{ref:u,type:"text",placeholder:j,value:s,onChange:c=>a(c.target.value),onKeyDown:k,onPaste:F,onMouseDown:P}),e.jsx("button",{className:B,onClick:d,disabled:!M,title:"Send",children:e.jsx(z,{name:"send",size:14})})]})]})]})}function mt(s){const a=Math.floor(s/1e3),l=Math.floor(a/60),f=a%60;return`${l}:${f.toString().padStart(2,"0")}`}const ft=t.memo(function({agentId:a,isWorking:l,timestamp:f}){const{t:p}=fe(["terminal"]),[d,M]=t.useState(0);return t.useEffect(()=>{if(!l||!f){M(0);return}M(Date.now()-f);const A=setInterval(()=>{M(Date.now()-f)},1e3);return()=>clearInterval(A)},[l,f]),l?e.jsxs("div",{className:"guake-stop-bar",children:[e.jsx("span",{className:"guake-elapsed-timer",children:mt(d)}),e.jsxs("button",{className:"guake-stop-btn",onClick:()=>I.stopAgent(a),title:p("terminal:input.stopOperation"),children:[e.jsx("span",{className:"stop-icon",children:e.jsx(z,{name:"stop",size:12,weight:"fill"})}),e.jsx("span",{className:"stop-label",children:p("terminal:input.stop")})]})]}):null});function pt({agent:s,history:a,outputs:l,isExpanded:f,isFocused:p,advancedView:d,onExpand:M,onFocus:A,inputRef:R,onLoadMore:N,onClearHistory:b}){const{t:E}=fe(["terminal","common"]),j=ze(s.id),h=t.useRef(null),[v,u]=t.useState(!1),D=t.useRef(0),i=t.useRef(!1),[C,F]=t.useState(!0),[x,k]=t.useState(!1),[P,W]=t.useState(null),[J,V]=t.useState(null),[q,Q]=t.useState(null);Te(`commander-image-modal-${s.id}`,P!==null,()=>W(null));const{command:B,setCommand:w,forceTextarea:c,setForceTextarea:L,useTextarea:K,setPastedTexts:U,incrementPastedCount:te,resetPastedCount:_,attachedFiles:$,setAttachedFiles:H,removeAttachedFile:se,uploadFile:ae,expandPastedTexts:ne}=Ue({selectedAgentId:s.id}),le=B.trim().length>0||$.length>0,n=Be({outputs:l,viewMode:d?"advanced":"simple"}),o=t.useMemo(()=>{const S=Ke(s);return{usedPercent:S.usedPercent,freePercent:S.freePercent,hasData:!!s.contextStats,totalTokens:S.totalTokens,contextWindow:S.contextWindow}},[s.contextStats,s.contextUsed,s.contextLimit]),g=t.useCallback(()=>{!v&&(a!=null&&a.hasMore)&&N&&(u(!0),D.current=h.current?h.current.scrollHeight-h.current.scrollTop:0,N())},[v,a==null?void 0:a.hasMore,N]);t.useEffect(()=>{v&&a&&!a.loading&&u(!1)},[a,v]);const m=t.useCallback(()=>{i.current=!0,F(!1)},[]),T=t.useRef(f),Z=t.useRef(p);t.useEffect(()=>{(f&&!T.current||p&&!Z.current)&&(i.current=!1,F(!0),k(!0)),T.current=f,Z.current=p},[f,p]);const ee=t.useRef(a==null?void 0:a.loading);t.useEffect(()=>{ee.current&&!(a!=null&&a.loading)&&(i.current=!1,F(!0),k(!0)),ee.current=a==null?void 0:a.loading},[a==null?void 0:a.loading]),t.useEffect(()=>{if(!x)return;const S=h.current;if(!S)return;const y=performance.now();let O=0,ue=-1,ke;const Re=()=>{const{scrollTop:Fe,scrollHeight:Se,clientHeight:Le}=S,He=Se-Fe-Le<=2;if(Math.abs(Se-ue)<=1&&He?O+=1:O=0,ue=Se,O>=3){k(!1);return}if(performance.now()-y>5e3){k(!1);return}ke=requestAnimationFrame(Re)};return ke=requestAnimationFrame(Re),()=>cancelAnimationFrame(ke)},[x]),t.useEffect(()=>{i.current||F(!0)},[n.length]);const G=t.useCallback(()=>!1,[]),ie=t.useCallback(S=>{const y=te();return U(O=>new Map(O).set(y,S)),y},[te,U]),he=t.useCallback(S=>{H(y=>[...y,S])},[H]),xe=t.useCallback(()=>{if(!le)return;if(B.trim()==="/clear"&&$.length===0){I.clearContext(s.id),b(),w(""),L(!1),U(new Map),H([]),_();return}let S=ne(B.trim());if($.length>0){const y=$.map(O=>O.isImage?`[Image: ${O.path}]`:`[File: ${O.path}]`).join(`
|
|
3
3
|
`);S=S?`${S}
|
|
4
4
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{u as J,a as Z,r,s as h,j as e,D as de,I as H,C as oe,b as me,c as be,d as ue,g as he,e as _e,Q as pe,R as xe}from"./main-XbhAPjbi.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const fe=({building:a,connections:x,activeConnectionId:l,activeDatabase:c,collapsed:y,onToggleCollapse:f,onConnectionChange:Q,onDatabaseChange:S,onInsertTable:A,onSelectTableQuery:M})=>{const{t:m}=J(["terminal"]),w=Z(a.id),[P,R]=r.useState(new Set),[k,n]=r.useState(""),[d,g]=r.useState(""),[$,q]=r.useState(!1),[U,F]=r.useState(null),K=r.useRef(null),C=r.useRef(null),O=r.useRef(null),N=l?w.databases.get(l)??[]:[],I=l&&c?`${l}:${c}`:"",j=I?w.tables.get(I)??[]:[],p=l?w.connectionStatus.get(l):void 0,D=r.useMemo(()=>{if(!k.trim())return N;const t=k.toLowerCase();return N.filter(o=>o.toLowerCase().includes(t))},[N,k]),b=r.useMemo(()=>{if(!d.trim())return j;const t=d.toLowerCase();return j.filter(o=>o.name.toLowerCase().includes(t))},[j,d]);r.useEffect(()=>{const t=o=>{C.current&&!C.current.contains(o.target)&&q(!1)};return $&&document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[$]),r.useEffect(()=>{l&&!p&&h.testDatabaseConnection(a.id,l)},[a.id,l,p]),r.useEffect(()=>{l&&(p!=null&&p.connected)&&N.length===0&&h.listDatabases(a.id,l)},[a.id,l,p==null?void 0:p.connected,N.length]),r.useEffect(()=>{l&&c&&j.length===0&&h.listTables(a.id,l,c)},[a.id,l,c,j.length]),r.useEffect(()=>{F(null),g("")},[l,c]);const _=r.useCallback(t=>{R(o=>{const T=new Set(o);if(T.has(t))T.delete(t);else if(T.add(t),l&&c){const v=`${l}:${c}:${t}`;w.tableSchemas.has(v)||h.getTableSchema(a.id,l,c,t)}return T})},[a.id,l,c,w.tableSchemas]),z=t=>{if(!l||!c)return null;const o=`${l}:${c}:${t}`;return w.tableSchemas.get(o)};return y?e.jsx("div",{className:"database-sidebar database-sidebar--collapsed",children:e.jsx("button",{className:"database-sidebar__toggle",onClick:f,title:m("terminal:database.expandSidebar"),children:"»"})}):e.jsxs("div",{className:"database-sidebar",children:[e.jsxs("div",{className:"database-sidebar__header",children:[e.jsx("span",{children:m("terminal:database.explorer")}),e.jsx("button",{className:"database-sidebar__toggle",onClick:f,title:m("terminal:database.collapseSidebar"),children:"«"})]}),e.jsxs("div",{className:"database-sidebar__section",children:[e.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.connection")}),e.jsx("select",{className:"database-sidebar__select",value:l||"",onChange:t=>Q(t.target.value),children:x.length===0?e.jsx("option",{value:"",children:m("terminal:database.noConnections")}):x.map(t=>{var o;return e.jsxs("option",{value:t.id,children:[((o=de[t.engine])==null?void 0:o.icon)??"🗄️"," ",t.name]},t.id)})}),p&&e.jsx("div",{className:`database-sidebar__status ${p.connected?"database-sidebar__status--connected":"database-sidebar__status--error"}`,children:p.connected?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"database-sidebar__status-icon",children:"✓"}),m("terminal:database.connected"),p.serverVersion&&e.jsxs("span",{className:"database-sidebar__version",children:["(",p.serverVersion,")"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"database-sidebar__status-icon",children:"✗"}),p.error||m("terminal:database.disconnected")]})})]}),N.length>0&&e.jsxs("div",{className:"database-sidebar__section",children:[e.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.databaseTitle")}),e.jsxs("div",{className:"database-sidebar__searchable-select",ref:C,children:[e.jsx("input",{ref:K,className:"database-sidebar__search-input",type:"text",value:$?k:c||"",placeholder:m("terminal:database.selectDatabase"),onChange:t=>{n(t.target.value),$||q(!0)},onFocus:()=>{q(!0),n("")},onKeyDown:t=>{var o,T;t.key==="Escape"?(q(!1),n(""),(o=K.current)==null||o.blur()):t.key==="Enter"&&D.length===1&&(S(D[0]),q(!1),n(""),(T=K.current)==null||T.blur())}}),$&&e.jsx("div",{className:"database-sidebar__dropdown",children:D.length===0?e.jsx("div",{className:"database-sidebar__dropdown-empty",children:"No matches"}):D.map(t=>e.jsx("div",{className:`database-sidebar__dropdown-item ${t===c?"database-sidebar__dropdown-item--active":""}`,onMouseDown:o=>{o.preventDefault(),S(t),q(!1),n("")},children:t},t))})]})]}),j.length>0&&e.jsxs("div",{className:"database-sidebar__section database-sidebar__section--tables",children:[e.jsx("div",{className:"database-sidebar__section-title",children:d.trim()?m("terminal:database.tablesCount",{count:b.length})+` / ${j.length}`:m("terminal:database.tablesCount",{count:j.length})}),e.jsxs("div",{className:"database-sidebar__table-filter",children:[e.jsx("input",{ref:O,className:"database-sidebar__table-filter-input",type:"text",value:d,placeholder:m("terminal:database.filterTables"),onChange:t=>g(t.target.value),onKeyDown:t=>{var o;t.key==="Escape"&&(d?g(""):(o=O.current)==null||o.blur(),t.stopPropagation())}}),d&&e.jsx("button",{className:"database-sidebar__table-filter-clear",onClick:()=>{var t;g(""),(t=O.current)==null||t.focus()},title:"Clear filter",children:"×"})]}),e.jsxs("div",{className:"database-sidebar__tables",children:[d.trim()&&b.length===0&&e.jsx("div",{className:"database-sidebar__tables-empty",children:m("terminal:database.noTablesMatch")}),b.map(t=>{const o=P.has(t.name),T=o?z(t.name):null;return e.jsxs("div",{className:"database-sidebar__table",children:[e.jsxs("div",{className:"database-sidebar__table-header",children:[e.jsx("button",{className:"database-sidebar__table-expand",onClick:()=>_(t.name),title:o?"Collapse table schema":"Expand table schema",children:e.jsx(H,{name:o?"caret-down":"caret-right",size:10})}),e.jsx("span",{className:"database-sidebar__table-icon",children:e.jsx(H,{name:t.type==="view"?"eye":"clipboard",size:12})}),e.jsx("span",{className:`database-sidebar__table-name ${U===t.name?"database-sidebar__table-name--selected":""}`,onClick:()=>F(t.name),onDoubleClick:()=>{F(t.name),M(t.name)},children:t.name}),e.jsx("button",{className:"database-sidebar__table-insert",onClick:v=>{v.stopPropagation(),A(t.name)},title:m("terminal:database.insertTableName"),children:"+"})]}),o&&T&&e.jsx("div",{className:"database-sidebar__table-columns",children:T.columns.map(v=>e.jsxs("div",{className:"database-sidebar__column",onClick:()=>A(v.name),title:`${v.type}${v.nullable?" NULL":" NOT NULL"}${v.primaryKey?" PK":""}`,children:[e.jsx("span",{className:"database-sidebar__column-icon",children:v.primaryKey?e.jsx(H,{name:"key",size:11}):null}),e.jsx("span",{className:"database-sidebar__column-name",children:v.name}),e.jsx("span",{className:"database-sidebar__column-type",children:v.type})]},v.name))})]},t.name)})]})]})]})},je=({buildingId:a,history:x,onLoadQuery:l})=>{const{t:c}=J(["terminal","common"]),[y,f]=r.useState(""),[Q,S]=r.useState(!1),[A,M]=r.useState(!1),m=r.useMemo(()=>{let n=x;if(Q&&(n=n.filter(d=>d.favorite)),y.trim()){const d=y.toLowerCase();n=n.filter(g=>g.query.toLowerCase().includes(d)||g.database.toLowerCase().includes(d))}return n},[x,Q,y]),w=n=>{const d=new Date(n),$=new Date().getTime()-d.getTime();return $<1440*60*1e3?d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):$<10080*60*1e3?d.toLocaleDateString([],{weekday:"short"})+" "+d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):d.toLocaleDateString([],{month:"short",day:"numeric"})},P=r.useCallback((n,d)=>{d.stopPropagation(),h.toggleQueryFavorite(a,n)},[a]),R=r.useCallback((n,d)=>{d.stopPropagation(),h.deleteQueryFromHistory(a,n)},[a]),k=r.useCallback(()=>{M(!0)},[]);return x.length===0?e.jsxs("div",{className:"query-history query-history--empty",children:[e.jsx("p",{children:c("terminal:database.noHistory")}),e.jsx("p",{children:c("terminal:database.queriesAppearHere")})]}):e.jsxs("div",{className:"query-history",children:[e.jsxs("div",{className:"query-history__toolbar",children:[e.jsx("input",{type:"text",className:"query-history__search",placeholder:c("terminal:database.searchQueries"),value:y,onChange:n=>f(n.target.value)}),e.jsxs("label",{className:"query-history__filter",children:[e.jsx("input",{type:"checkbox",checked:Q,onChange:n=>S(n.target.checked)}),c("terminal:database.favoritesOnly")]}),e.jsx("button",{className:"query-history__clear",onClick:k,title:c("terminal:database.clearAll"),children:c("terminal:database.clearAll")})]}),e.jsxs("div",{className:"query-history__list",children:[m.map(n=>e.jsxs("div",{className:`query-history__item ${n.status==="error"?"query-history__item--error":""}`,onClick:()=>l(n.query),children:[e.jsxs("div",{className:"query-history__item-header",children:[e.jsx("span",{className:`query-history__status ${n.status==="success"?"query-history__status--success":"query-history__status--error"}`,children:e.jsx(H,{name:n.status==="success"?"check":"cross",size:12})}),e.jsx("span",{className:"query-history__database",children:n.database}),e.jsx("span",{className:"query-history__date",children:w(n.executedAt)}),e.jsxs("span",{className:"query-history__duration",children:[n.duration,"ms"]}),n.rowCount!==void 0&&e.jsx("span",{className:"query-history__row-count",children:c("terminal:database.rowCount",{count:n.rowCount})})]}),e.jsx("div",{className:"query-history__query",children:e.jsx("code",{children:n.query.length>200?n.query.substring(0,200)+"...":n.query})}),n.error&&e.jsx("div",{className:"query-history__error",children:n.error}),e.jsxs("div",{className:"query-history__actions",children:[e.jsx("button",{className:`query-history__favorite ${n.favorite?"query-history__favorite--active":""}`,onClick:d=>P(n.id,d),title:n.favorite?c("terminal:database.removeFromFavorites"):c("terminal:database.addToFavorites"),children:e.jsx(H,{name:"star",size:12,weight:n.favorite?"fill":"regular",color:n.favorite?"#facc15":void 0})}),e.jsx("button",{className:"query-history__delete",onClick:d=>R(n.id,d),title:c("terminal:database.deleteFromHistory"),children:e.jsx(H,{name:"trash",size:12})})]})]},n.id)),m.length===0&&e.jsx("div",{className:"query-history__no-results",children:c("terminal:database.noQueriesMatch")})]}),e.jsx(oe,{isOpen:A,title:c("terminal:database.clearAll"),message:c("terminal:database.confirmClearHistory"),confirmLabel:c("terminal:database.clearAll"),cancelLabel:c("common:buttons.cancel"),variant:"danger",onConfirm:()=>h.clearQueryHistory(a),onClose:()=>M(!1)})]})},ye=({tabs:a,activeTabId:x,onTabClick:l,onTabClose:c})=>{const{t:y}=J(["terminal"]);return e.jsx("div",{className:"database-tabs",children:a.map(f=>e.jsxs("div",{className:`database-tabs__tab ${x===f.id?"database-tabs__tab--active":""}`,children:[e.jsxs("button",{className:"database-tabs__tab-label",onClick:()=>l(f),title:`${f.connectionName} / ${f.database}`,children:[f.database,e.jsx("span",{className:"database-tabs__tab-connection",children:f.connectionName})]}),e.jsx("button",{className:"database-tabs__tab-close",onClick:()=>c(f.id),title:y("terminal:database.closeTab"),"aria-label":`Close ${f.database} tab`,children:"×"})]},f.id))})},ee=a=>`db-panel-${a}`;function Ne(a){try{const x=localStorage.getItem(ee(a));return x?JSON.parse(x):{}}catch{return{}}}function ve(a,x){try{localStorage.setItem(ee(a),JSON.stringify(x))}catch{}}const ge=({building:a,onClose:x})=>{var B,Y,W,X;const{t:l}=J(["terminal","common"]),c=Z(a.id),y=me(a.id),f=be(a.id),Q=ue(a.id),S=r.useRef(Ne(a.id)),A=r.useRef(null),M=r.useRef(0),m=((B=a.database)==null?void 0:B.connections)??[],w=(s,i)=>`${s}:${i}`,P=s=>s?(S.current.queries??{})[s]??"":S.current.generalQuery??"",[R,k]=r.useState("results"),[n,d]=r.useState(0),[g,$]=r.useState(!1),[q,U]=r.useState(!1),[F,K]=r.useState(()=>(S.current.openTabs??[]).map(i=>{var u;return{id:`${i.connectionId}:${i.database}`,connectionId:i.connectionId,connectionName:((u=m.find(L=>L.id===i.connectionId))==null?void 0:u.name)??i.connectionId,database:i.database}})),[C,O]=r.useState(S.current.activeTabId??null),[N,I]=r.useState(()=>{const s=S.current.queries??{};return S.current.generalQuery,s}),[j,p]=r.useState(P(C)),D=r.useCallback(s=>{p(i=>{const u=typeof s=="function"?s(i):s;return I(L=>{const E={...L};return C&&(E[C]=u),E}),u})},[C]),b=c.activeConnectionId??S.current.connectionId??((Y=a.database)==null?void 0:Y.activeConnectionId)??((W=m[0])==null?void 0:W.id),_=c.activeDatabase??S.current.database??((X=a.database)==null?void 0:X.activeDatabase),z=m.find(s=>s.id===b),t=b&&_?`${b}:${_}`:"",o=t?c.tables.get(t)??[]:[],T=r.useMemo(()=>{const s=new Map;return!b||!_||o.forEach(i=>{const u=c.tableSchemas.get(`${b}:${_}:${i.name}`);u&&s.set(i.name,{columns:u.columns})}),s},[b,_,o,c.tableSchemas]),v=r.useCallback((s,i)=>{var E;const u=w(s,i),L=((E=m.find(G=>G.id===s))==null?void 0:E.name)??s;K(G=>{if(G.some(ie=>ie.id===u))return G;const ce={id:u,connectionId:s,connectionName:L,database:i};return[...G,ce]}),O(u),p(N[u]??""),h.setActiveConnection(a.id,s),h.setActiveDatabase(a.id,i)},[a.id,m,N]),ae=r.useCallback(s=>{K(i=>i.filter(u=>u.id!==s)),C===s&&K(i=>{if(i.length>0){const u=i[0];O(u.id),p(N[u.id]??""),h.setActiveConnection(a.id,u.connectionId),h.setActiveDatabase(a.id,u.database)}else O(null),p("");return i})},[C,a.id,N]),se=r.useCallback(s=>{O(s.id),p(N[s.id]??""),h.setActiveConnection(a.id,s.connectionId),h.setActiveDatabase(a.id,s.database)},[a.id,N]);r.useEffect(()=>{if(!q&&m.length>0){const s=S.current;s.connectionId&&m.some(i=>i.id===s.connectionId)&&(h.setActiveConnection(a.id,s.connectionId),h.listDatabases(a.id,s.connectionId),s.database&&(h.setActiveDatabase(a.id,s.database),h.listTables(a.id,s.connectionId,s.database))),U(!0)}},[a.id,m,q]),r.useEffect(()=>{h.requestQueryHistory(a.id)},[a.id]),r.useEffect(()=>{const s=i=>{i.key==="Escape"&&(i.preventDefault(),i.stopPropagation(),x())};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[x]),r.useEffect(()=>{q&&b&&ve(a.id,{connectionId:b,database:_,lastQuery:j,queries:N,generalQuery:"",openTabs:F.map(s=>({connectionId:s.connectionId,database:s.database})),activeTabId:C??void 0})},[a.id,b,_,j,q,F,C,N]);const te=r.useCallback(s=>{var i;if(!(!b||!_||!j.trim()||Q))if(s==="cursor"){const u=(i=A.current)==null?void 0:i.querySelector(".query-editor__textarea"),L=(u==null?void 0:u.selectionStart)??M.current,E=he(j,L);E&&h.executeQuery(a.id,b,_,E)}else{const u=_e(j);u.length<=1?h.executeQuery(a.id,b,_,j.trim()):u.forEach((L,E)=>{setTimeout(()=>{h.executeQuery(a.id,b,_,L.sql)},E*150)})}},[a.id,b,_,j,Q]),ne=r.useCallback(s=>{D(s),k("results")},[]),re=r.useCallback(s=>{h.setActiveConnection(a.id,s),h.listDatabases(a.id,s)},[a.id]),le=r.useCallback(s=>{b&&(v(b,s),h.listTables(a.id,b,s))},[a.id,b,v]),V=y[n];return m.length===0?e.jsxs("div",{className:"database-panel",ref:A,children:[e.jsxs("div",{className:"database-panel__header",children:[e.jsxs("div",{className:"database-panel__title",children:[e.jsx("span",{className:"database-panel__icon",children:e.jsx(H,{name:"database",size:16})}),e.jsx("span",{className:"database-panel__name",children:a.name})]}),e.jsx("button",{className:"database-panel__close",onClick:x,children:"×"})]}),e.jsx("div",{className:"database-panel__body",children:e.jsxs("div",{className:"database-panel__no-connections",children:[e.jsx("div",{className:"database-panel__no-connections-icon",children:e.jsx(H,{name:"plug",size:32})}),e.jsx("h3",{children:l("terminal:database.noConnections")}),e.jsx("p",{children:l("terminal:database.noConnectionsDesc")}),e.jsx("p",{children:l("terminal:database.toGetStarted")}),e.jsxs("ol",{children:[e.jsx("li",{children:l("terminal:database.step1Close")}),e.jsx("li",{children:l("terminal:database.step2Settings")}),e.jsx("li",{children:l("terminal:database.step3AddConnection")}),e.jsx("li",{children:l("terminal:database.step4Reopen")})]})]})})]}):e.jsxs("div",{className:"database-panel",ref:A,children:[e.jsxs("div",{className:"database-panel__header",children:[e.jsxs("div",{className:"database-panel__title",children:[e.jsx("span",{className:"database-panel__icon",children:(z==null?void 0:z.engine)==="mysql"?"🐬":"🐘"}),e.jsx("span",{className:"database-panel__name",children:a.name}),z&&e.jsxs("span",{className:"database-panel__connection-info",children:[z.name," / ",_||l("terminal:database.noDatabaseSelected")]})]}),e.jsx("button",{className:"database-panel__close",onClick:x,children:"×"})]}),e.jsxs("div",{className:"database-panel__body",children:[e.jsx(fe,{building:a,connections:m,activeConnectionId:b,activeDatabase:_,collapsed:g,onToggleCollapse:()=>$(!g),onConnectionChange:re,onDatabaseChange:le,onInsertTable:s=>D(i=>i+` ${s}`),onSelectTableQuery:s=>{const i=`SELECT * FROM ${s}`;D(i),b&&_&&h.executeQuery(a.id,b,_,i)}}),e.jsxs("div",{className:"database-panel__main",children:[F.length>0&&e.jsx(ye,{tabs:F,activeTabId:C,onTabClick:se,onTabClose:ae}),e.jsx(pe,{query:j,onChange:D,onExecute:te,isExecuting:Q,disabled:!b||!_,tables:o,tableSchemas:T,onRequestTableSchema:s=>{b&&_&&h.getTableSchema(a.id,b,_,s)}}),e.jsxs("div",{className:"database-panel__tabs",children:[e.jsxs("button",{className:`database-panel__tab ${R==="results"?"database-panel__tab--active":""}`,onClick:()=>k("results"),children:[l("terminal:database.results"),y.length>0&&e.jsx("span",{className:"database-panel__tab-badge",children:y.length})]}),e.jsxs("button",{className:`database-panel__tab ${R==="history"?"database-panel__tab--active":""}`,onClick:()=>k("history"),children:[l("terminal:database.history"),f.length>0&&e.jsx("span",{className:"database-panel__tab-badge",children:f.length})]}),R==="results"&&y.length>1&&e.jsxs("div",{className:"database-panel__result-nav",children:[e.jsxs("button",{disabled:n>=y.length-1,onClick:()=>d(s=>s+1),children:["← ",l("terminal:database.older")]}),e.jsxs("span",{children:[n+1," / ",y.length]}),e.jsxs("button",{disabled:n<=0,onClick:()=>d(s=>s-1),children:[l("terminal:database.newer")," →"]})]})]}),e.jsx("div",{className:"database-panel__tab-content",children:R==="results"?V?e.jsx(xe,{result:V,buildingId:a.id,building:a}):e.jsxs("div",{className:"database-panel__empty",children:[e.jsx("p",{children:l("terminal:database.noResultsYet")}),e.jsx("p",{children:l("terminal:database.selectDbAndRun")})]}):e.jsx(je,{buildingId:a.id,history:f,onLoadQuery:ne})})]})]})]})};export{ge as DatabasePanel,fe as DatabaseSidebar,ye as DatabaseTabs,pe as QueryEditor,je as QueryHistoryPanel,xe as ResultsTable};
|
|
1
|
+
import{u as J,a as Z,r,s as h,j as e,D as de,I as H,C as oe,b as me,c as be,d as ue,g as he,e as _e,Q as pe,R as xe}from"./main-CBiZdw6w.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const fe=({building:a,connections:x,activeConnectionId:l,activeDatabase:c,collapsed:y,onToggleCollapse:f,onConnectionChange:Q,onDatabaseChange:S,onInsertTable:A,onSelectTableQuery:M})=>{const{t:m}=J(["terminal"]),w=Z(a.id),[P,R]=r.useState(new Set),[k,n]=r.useState(""),[d,g]=r.useState(""),[$,q]=r.useState(!1),[U,F]=r.useState(null),K=r.useRef(null),C=r.useRef(null),O=r.useRef(null),N=l?w.databases.get(l)??[]:[],I=l&&c?`${l}:${c}`:"",j=I?w.tables.get(I)??[]:[],p=l?w.connectionStatus.get(l):void 0,D=r.useMemo(()=>{if(!k.trim())return N;const t=k.toLowerCase();return N.filter(o=>o.toLowerCase().includes(t))},[N,k]),b=r.useMemo(()=>{if(!d.trim())return j;const t=d.toLowerCase();return j.filter(o=>o.name.toLowerCase().includes(t))},[j,d]);r.useEffect(()=>{const t=o=>{C.current&&!C.current.contains(o.target)&&q(!1)};return $&&document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[$]),r.useEffect(()=>{l&&!p&&h.testDatabaseConnection(a.id,l)},[a.id,l,p]),r.useEffect(()=>{l&&(p!=null&&p.connected)&&N.length===0&&h.listDatabases(a.id,l)},[a.id,l,p==null?void 0:p.connected,N.length]),r.useEffect(()=>{l&&c&&j.length===0&&h.listTables(a.id,l,c)},[a.id,l,c,j.length]),r.useEffect(()=>{F(null),g("")},[l,c]);const _=r.useCallback(t=>{R(o=>{const T=new Set(o);if(T.has(t))T.delete(t);else if(T.add(t),l&&c){const v=`${l}:${c}:${t}`;w.tableSchemas.has(v)||h.getTableSchema(a.id,l,c,t)}return T})},[a.id,l,c,w.tableSchemas]),z=t=>{if(!l||!c)return null;const o=`${l}:${c}:${t}`;return w.tableSchemas.get(o)};return y?e.jsx("div",{className:"database-sidebar database-sidebar--collapsed",children:e.jsx("button",{className:"database-sidebar__toggle",onClick:f,title:m("terminal:database.expandSidebar"),children:"»"})}):e.jsxs("div",{className:"database-sidebar",children:[e.jsxs("div",{className:"database-sidebar__header",children:[e.jsx("span",{children:m("terminal:database.explorer")}),e.jsx("button",{className:"database-sidebar__toggle",onClick:f,title:m("terminal:database.collapseSidebar"),children:"«"})]}),e.jsxs("div",{className:"database-sidebar__section",children:[e.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.connection")}),e.jsx("select",{className:"database-sidebar__select",value:l||"",onChange:t=>Q(t.target.value),children:x.length===0?e.jsx("option",{value:"",children:m("terminal:database.noConnections")}):x.map(t=>{var o;return e.jsxs("option",{value:t.id,children:[((o=de[t.engine])==null?void 0:o.icon)??"🗄️"," ",t.name]},t.id)})}),p&&e.jsx("div",{className:`database-sidebar__status ${p.connected?"database-sidebar__status--connected":"database-sidebar__status--error"}`,children:p.connected?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"database-sidebar__status-icon",children:"✓"}),m("terminal:database.connected"),p.serverVersion&&e.jsxs("span",{className:"database-sidebar__version",children:["(",p.serverVersion,")"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"database-sidebar__status-icon",children:"✗"}),p.error||m("terminal:database.disconnected")]})})]}),N.length>0&&e.jsxs("div",{className:"database-sidebar__section",children:[e.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.databaseTitle")}),e.jsxs("div",{className:"database-sidebar__searchable-select",ref:C,children:[e.jsx("input",{ref:K,className:"database-sidebar__search-input",type:"text",value:$?k:c||"",placeholder:m("terminal:database.selectDatabase"),onChange:t=>{n(t.target.value),$||q(!0)},onFocus:()=>{q(!0),n("")},onKeyDown:t=>{var o,T;t.key==="Escape"?(q(!1),n(""),(o=K.current)==null||o.blur()):t.key==="Enter"&&D.length===1&&(S(D[0]),q(!1),n(""),(T=K.current)==null||T.blur())}}),$&&e.jsx("div",{className:"database-sidebar__dropdown",children:D.length===0?e.jsx("div",{className:"database-sidebar__dropdown-empty",children:"No matches"}):D.map(t=>e.jsx("div",{className:`database-sidebar__dropdown-item ${t===c?"database-sidebar__dropdown-item--active":""}`,onMouseDown:o=>{o.preventDefault(),S(t),q(!1),n("")},children:t},t))})]})]}),j.length>0&&e.jsxs("div",{className:"database-sidebar__section database-sidebar__section--tables",children:[e.jsx("div",{className:"database-sidebar__section-title",children:d.trim()?m("terminal:database.tablesCount",{count:b.length})+` / ${j.length}`:m("terminal:database.tablesCount",{count:j.length})}),e.jsxs("div",{className:"database-sidebar__table-filter",children:[e.jsx("input",{ref:O,className:"database-sidebar__table-filter-input",type:"text",value:d,placeholder:m("terminal:database.filterTables"),onChange:t=>g(t.target.value),onKeyDown:t=>{var o;t.key==="Escape"&&(d?g(""):(o=O.current)==null||o.blur(),t.stopPropagation())}}),d&&e.jsx("button",{className:"database-sidebar__table-filter-clear",onClick:()=>{var t;g(""),(t=O.current)==null||t.focus()},title:"Clear filter",children:"×"})]}),e.jsxs("div",{className:"database-sidebar__tables",children:[d.trim()&&b.length===0&&e.jsx("div",{className:"database-sidebar__tables-empty",children:m("terminal:database.noTablesMatch")}),b.map(t=>{const o=P.has(t.name),T=o?z(t.name):null;return e.jsxs("div",{className:"database-sidebar__table",children:[e.jsxs("div",{className:"database-sidebar__table-header",children:[e.jsx("button",{className:"database-sidebar__table-expand",onClick:()=>_(t.name),title:o?"Collapse table schema":"Expand table schema",children:e.jsx(H,{name:o?"caret-down":"caret-right",size:10})}),e.jsx("span",{className:"database-sidebar__table-icon",children:e.jsx(H,{name:t.type==="view"?"eye":"clipboard",size:12})}),e.jsx("span",{className:`database-sidebar__table-name ${U===t.name?"database-sidebar__table-name--selected":""}`,onClick:()=>F(t.name),onDoubleClick:()=>{F(t.name),M(t.name)},children:t.name}),e.jsx("button",{className:"database-sidebar__table-insert",onClick:v=>{v.stopPropagation(),A(t.name)},title:m("terminal:database.insertTableName"),children:"+"})]}),o&&T&&e.jsx("div",{className:"database-sidebar__table-columns",children:T.columns.map(v=>e.jsxs("div",{className:"database-sidebar__column",onClick:()=>A(v.name),title:`${v.type}${v.nullable?" NULL":" NOT NULL"}${v.primaryKey?" PK":""}`,children:[e.jsx("span",{className:"database-sidebar__column-icon",children:v.primaryKey?e.jsx(H,{name:"key",size:11}):null}),e.jsx("span",{className:"database-sidebar__column-name",children:v.name}),e.jsx("span",{className:"database-sidebar__column-type",children:v.type})]},v.name))})]},t.name)})]})]})]})},je=({buildingId:a,history:x,onLoadQuery:l})=>{const{t:c}=J(["terminal","common"]),[y,f]=r.useState(""),[Q,S]=r.useState(!1),[A,M]=r.useState(!1),m=r.useMemo(()=>{let n=x;if(Q&&(n=n.filter(d=>d.favorite)),y.trim()){const d=y.toLowerCase();n=n.filter(g=>g.query.toLowerCase().includes(d)||g.database.toLowerCase().includes(d))}return n},[x,Q,y]),w=n=>{const d=new Date(n),$=new Date().getTime()-d.getTime();return $<1440*60*1e3?d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):$<10080*60*1e3?d.toLocaleDateString([],{weekday:"short"})+" "+d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):d.toLocaleDateString([],{month:"short",day:"numeric"})},P=r.useCallback((n,d)=>{d.stopPropagation(),h.toggleQueryFavorite(a,n)},[a]),R=r.useCallback((n,d)=>{d.stopPropagation(),h.deleteQueryFromHistory(a,n)},[a]),k=r.useCallback(()=>{M(!0)},[]);return x.length===0?e.jsxs("div",{className:"query-history query-history--empty",children:[e.jsx("p",{children:c("terminal:database.noHistory")}),e.jsx("p",{children:c("terminal:database.queriesAppearHere")})]}):e.jsxs("div",{className:"query-history",children:[e.jsxs("div",{className:"query-history__toolbar",children:[e.jsx("input",{type:"text",className:"query-history__search",placeholder:c("terminal:database.searchQueries"),value:y,onChange:n=>f(n.target.value)}),e.jsxs("label",{className:"query-history__filter",children:[e.jsx("input",{type:"checkbox",checked:Q,onChange:n=>S(n.target.checked)}),c("terminal:database.favoritesOnly")]}),e.jsx("button",{className:"query-history__clear",onClick:k,title:c("terminal:database.clearAll"),children:c("terminal:database.clearAll")})]}),e.jsxs("div",{className:"query-history__list",children:[m.map(n=>e.jsxs("div",{className:`query-history__item ${n.status==="error"?"query-history__item--error":""}`,onClick:()=>l(n.query),children:[e.jsxs("div",{className:"query-history__item-header",children:[e.jsx("span",{className:`query-history__status ${n.status==="success"?"query-history__status--success":"query-history__status--error"}`,children:e.jsx(H,{name:n.status==="success"?"check":"cross",size:12})}),e.jsx("span",{className:"query-history__database",children:n.database}),e.jsx("span",{className:"query-history__date",children:w(n.executedAt)}),e.jsxs("span",{className:"query-history__duration",children:[n.duration,"ms"]}),n.rowCount!==void 0&&e.jsx("span",{className:"query-history__row-count",children:c("terminal:database.rowCount",{count:n.rowCount})})]}),e.jsx("div",{className:"query-history__query",children:e.jsx("code",{children:n.query.length>200?n.query.substring(0,200)+"...":n.query})}),n.error&&e.jsx("div",{className:"query-history__error",children:n.error}),e.jsxs("div",{className:"query-history__actions",children:[e.jsx("button",{className:`query-history__favorite ${n.favorite?"query-history__favorite--active":""}`,onClick:d=>P(n.id,d),title:n.favorite?c("terminal:database.removeFromFavorites"):c("terminal:database.addToFavorites"),children:e.jsx(H,{name:"star",size:12,weight:n.favorite?"fill":"regular",color:n.favorite?"#facc15":void 0})}),e.jsx("button",{className:"query-history__delete",onClick:d=>R(n.id,d),title:c("terminal:database.deleteFromHistory"),children:e.jsx(H,{name:"trash",size:12})})]})]},n.id)),m.length===0&&e.jsx("div",{className:"query-history__no-results",children:c("terminal:database.noQueriesMatch")})]}),e.jsx(oe,{isOpen:A,title:c("terminal:database.clearAll"),message:c("terminal:database.confirmClearHistory"),confirmLabel:c("terminal:database.clearAll"),cancelLabel:c("common:buttons.cancel"),variant:"danger",onConfirm:()=>h.clearQueryHistory(a),onClose:()=>M(!1)})]})},ye=({tabs:a,activeTabId:x,onTabClick:l,onTabClose:c})=>{const{t:y}=J(["terminal"]);return e.jsx("div",{className:"database-tabs",children:a.map(f=>e.jsxs("div",{className:`database-tabs__tab ${x===f.id?"database-tabs__tab--active":""}`,children:[e.jsxs("button",{className:"database-tabs__tab-label",onClick:()=>l(f),title:`${f.connectionName} / ${f.database}`,children:[f.database,e.jsx("span",{className:"database-tabs__tab-connection",children:f.connectionName})]}),e.jsx("button",{className:"database-tabs__tab-close",onClick:()=>c(f.id),title:y("terminal:database.closeTab"),"aria-label":`Close ${f.database} tab`,children:"×"})]},f.id))})},ee=a=>`db-panel-${a}`;function Ne(a){try{const x=localStorage.getItem(ee(a));return x?JSON.parse(x):{}}catch{return{}}}function ve(a,x){try{localStorage.setItem(ee(a),JSON.stringify(x))}catch{}}const ge=({building:a,onClose:x})=>{var B,Y,W,X;const{t:l}=J(["terminal","common"]),c=Z(a.id),y=me(a.id),f=be(a.id),Q=ue(a.id),S=r.useRef(Ne(a.id)),A=r.useRef(null),M=r.useRef(0),m=((B=a.database)==null?void 0:B.connections)??[],w=(s,i)=>`${s}:${i}`,P=s=>s?(S.current.queries??{})[s]??"":S.current.generalQuery??"",[R,k]=r.useState("results"),[n,d]=r.useState(0),[g,$]=r.useState(!1),[q,U]=r.useState(!1),[F,K]=r.useState(()=>(S.current.openTabs??[]).map(i=>{var u;return{id:`${i.connectionId}:${i.database}`,connectionId:i.connectionId,connectionName:((u=m.find(L=>L.id===i.connectionId))==null?void 0:u.name)??i.connectionId,database:i.database}})),[C,O]=r.useState(S.current.activeTabId??null),[N,I]=r.useState(()=>{const s=S.current.queries??{};return S.current.generalQuery,s}),[j,p]=r.useState(P(C)),D=r.useCallback(s=>{p(i=>{const u=typeof s=="function"?s(i):s;return I(L=>{const E={...L};return C&&(E[C]=u),E}),u})},[C]),b=c.activeConnectionId??S.current.connectionId??((Y=a.database)==null?void 0:Y.activeConnectionId)??((W=m[0])==null?void 0:W.id),_=c.activeDatabase??S.current.database??((X=a.database)==null?void 0:X.activeDatabase),z=m.find(s=>s.id===b),t=b&&_?`${b}:${_}`:"",o=t?c.tables.get(t)??[]:[],T=r.useMemo(()=>{const s=new Map;return!b||!_||o.forEach(i=>{const u=c.tableSchemas.get(`${b}:${_}:${i.name}`);u&&s.set(i.name,{columns:u.columns})}),s},[b,_,o,c.tableSchemas]),v=r.useCallback((s,i)=>{var E;const u=w(s,i),L=((E=m.find(G=>G.id===s))==null?void 0:E.name)??s;K(G=>{if(G.some(ie=>ie.id===u))return G;const ce={id:u,connectionId:s,connectionName:L,database:i};return[...G,ce]}),O(u),p(N[u]??""),h.setActiveConnection(a.id,s),h.setActiveDatabase(a.id,i)},[a.id,m,N]),ae=r.useCallback(s=>{K(i=>i.filter(u=>u.id!==s)),C===s&&K(i=>{if(i.length>0){const u=i[0];O(u.id),p(N[u.id]??""),h.setActiveConnection(a.id,u.connectionId),h.setActiveDatabase(a.id,u.database)}else O(null),p("");return i})},[C,a.id,N]),se=r.useCallback(s=>{O(s.id),p(N[s.id]??""),h.setActiveConnection(a.id,s.connectionId),h.setActiveDatabase(a.id,s.database)},[a.id,N]);r.useEffect(()=>{if(!q&&m.length>0){const s=S.current;s.connectionId&&m.some(i=>i.id===s.connectionId)&&(h.setActiveConnection(a.id,s.connectionId),h.listDatabases(a.id,s.connectionId),s.database&&(h.setActiveDatabase(a.id,s.database),h.listTables(a.id,s.connectionId,s.database))),U(!0)}},[a.id,m,q]),r.useEffect(()=>{h.requestQueryHistory(a.id)},[a.id]),r.useEffect(()=>{const s=i=>{i.key==="Escape"&&(i.preventDefault(),i.stopPropagation(),x())};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[x]),r.useEffect(()=>{q&&b&&ve(a.id,{connectionId:b,database:_,lastQuery:j,queries:N,generalQuery:"",openTabs:F.map(s=>({connectionId:s.connectionId,database:s.database})),activeTabId:C??void 0})},[a.id,b,_,j,q,F,C,N]);const te=r.useCallback(s=>{var i;if(!(!b||!_||!j.trim()||Q))if(s==="cursor"){const u=(i=A.current)==null?void 0:i.querySelector(".query-editor__textarea"),L=(u==null?void 0:u.selectionStart)??M.current,E=he(j,L);E&&h.executeQuery(a.id,b,_,E)}else{const u=_e(j);u.length<=1?h.executeQuery(a.id,b,_,j.trim()):u.forEach((L,E)=>{setTimeout(()=>{h.executeQuery(a.id,b,_,L.sql)},E*150)})}},[a.id,b,_,j,Q]),ne=r.useCallback(s=>{D(s),k("results")},[]),re=r.useCallback(s=>{h.setActiveConnection(a.id,s),h.listDatabases(a.id,s)},[a.id]),le=r.useCallback(s=>{b&&(v(b,s),h.listTables(a.id,b,s))},[a.id,b,v]),V=y[n];return m.length===0?e.jsxs("div",{className:"database-panel",ref:A,children:[e.jsxs("div",{className:"database-panel__header",children:[e.jsxs("div",{className:"database-panel__title",children:[e.jsx("span",{className:"database-panel__icon",children:e.jsx(H,{name:"database",size:16})}),e.jsx("span",{className:"database-panel__name",children:a.name})]}),e.jsx("button",{className:"database-panel__close",onClick:x,children:"×"})]}),e.jsx("div",{className:"database-panel__body",children:e.jsxs("div",{className:"database-panel__no-connections",children:[e.jsx("div",{className:"database-panel__no-connections-icon",children:e.jsx(H,{name:"plug",size:32})}),e.jsx("h3",{children:l("terminal:database.noConnections")}),e.jsx("p",{children:l("terminal:database.noConnectionsDesc")}),e.jsx("p",{children:l("terminal:database.toGetStarted")}),e.jsxs("ol",{children:[e.jsx("li",{children:l("terminal:database.step1Close")}),e.jsx("li",{children:l("terminal:database.step2Settings")}),e.jsx("li",{children:l("terminal:database.step3AddConnection")}),e.jsx("li",{children:l("terminal:database.step4Reopen")})]})]})})]}):e.jsxs("div",{className:"database-panel",ref:A,children:[e.jsxs("div",{className:"database-panel__header",children:[e.jsxs("div",{className:"database-panel__title",children:[e.jsx("span",{className:"database-panel__icon",children:(z==null?void 0:z.engine)==="mysql"?"🐬":"🐘"}),e.jsx("span",{className:"database-panel__name",children:a.name}),z&&e.jsxs("span",{className:"database-panel__connection-info",children:[z.name," / ",_||l("terminal:database.noDatabaseSelected")]})]}),e.jsx("button",{className:"database-panel__close",onClick:x,children:"×"})]}),e.jsxs("div",{className:"database-panel__body",children:[e.jsx(fe,{building:a,connections:m,activeConnectionId:b,activeDatabase:_,collapsed:g,onToggleCollapse:()=>$(!g),onConnectionChange:re,onDatabaseChange:le,onInsertTable:s=>D(i=>i+` ${s}`),onSelectTableQuery:s=>{const i=`SELECT * FROM ${s}`;D(i),b&&_&&h.executeQuery(a.id,b,_,i)}}),e.jsxs("div",{className:"database-panel__main",children:[F.length>0&&e.jsx(ye,{tabs:F,activeTabId:C,onTabClick:se,onTabClose:ae}),e.jsx(pe,{query:j,onChange:D,onExecute:te,isExecuting:Q,disabled:!b||!_,tables:o,tableSchemas:T,onRequestTableSchema:s=>{b&&_&&h.getTableSchema(a.id,b,_,s)}}),e.jsxs("div",{className:"database-panel__tabs",children:[e.jsxs("button",{className:`database-panel__tab ${R==="results"?"database-panel__tab--active":""}`,onClick:()=>k("results"),children:[l("terminal:database.results"),y.length>0&&e.jsx("span",{className:"database-panel__tab-badge",children:y.length})]}),e.jsxs("button",{className:`database-panel__tab ${R==="history"?"database-panel__tab--active":""}`,onClick:()=>k("history"),children:[l("terminal:database.history"),f.length>0&&e.jsx("span",{className:"database-panel__tab-badge",children:f.length})]}),R==="results"&&y.length>1&&e.jsxs("div",{className:"database-panel__result-nav",children:[e.jsxs("button",{disabled:n>=y.length-1,onClick:()=>d(s=>s+1),children:["← ",l("terminal:database.older")]}),e.jsxs("span",{children:[n+1," / ",y.length]}),e.jsxs("button",{disabled:n<=0,onClick:()=>d(s=>s-1),children:[l("terminal:database.newer")," →"]})]})]}),e.jsx("div",{className:"database-panel__tab-content",children:R==="results"?V?e.jsx(xe,{result:V,buildingId:a.id,building:a}):e.jsxs("div",{className:"database-panel__empty",children:[e.jsx("p",{children:l("terminal:database.noResultsYet")}),e.jsx("p",{children:l("terminal:database.selectDbAndRun")})]}):e.jsx(je,{buildingId:a.id,history:f,onLoadQuery:ne})})]})]})]})};export{ge as DatabasePanel,fe as DatabaseSidebar,ye as DatabaseTabs,pe as QueryEditor,je as QueryHistoryPanel,xe as ResultsTable};
|