diff --git a/dist-renderer/index.html b/dist-renderer/index.html index a06c4eb2..2c1e0c91 100644 --- a/dist-renderer/index.html +++ b/dist-renderer/index.html @@ -5,7 +5,7 @@ ProofForge - + diff --git a/dist-renderer/js/ScratchpadTab-D2yqtgVs.js b/dist-renderer/js/ScratchpadTab-zgUog115.js similarity index 99% rename from dist-renderer/js/ScratchpadTab-D2yqtgVs.js rename to dist-renderer/js/ScratchpadTab-zgUog115.js index 99a8f75e..18bac926 100644 --- a/dist-renderer/js/ScratchpadTab-D2yqtgVs.js +++ b/dist-renderer/js/ScratchpadTab-zgUog115.js @@ -1 +1 @@ -import{R as o,j as e}from"./vendor-react-C1Vrmh6-.js";import{l as te,r as ve,s as we,a as je,b as ye,w as ke,g as Ne,e as Ce,c as x,d as Te,i as Se,f as L,h as De,p as Ie,j as ae,k as We,m as Ae,n as Ee,o as re,q as R,t as Me,u as A,v as J,x as Le,y as Pe,z as Re,A as $e,B as _e,C as Oe,D as ze,E as se,F as Be,G as Ke,W as Je,H as He,I as Ye,J as Fe,K as Xe,L as Ue}from"./main-2TeVSSYI.js";import"./vendor-misc-DYLXRpC5.js";import"./vendor-state-B3vIvpM5.js";const Ve=[{id:"notes",label:"Notes",hint:"Pages & drafts"},{id:"tasks",label:"Tasks",hint:"Action items"},{id:"pins",label:"Pins",hint:"Snippets"},{id:"log",label:"Capture",hint:"Timestamped log"}];function $(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.75,children:[e.jsx("path",{d:"M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2"}),e.jsx("rect",{x:"9",y:"3",width:"6",height:"4",rx:"1"}),e.jsx("path",{d:"M9 12h6M9 16h4"})]})}function H(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.75,children:[e.jsx("path",{d:"M9 11l3 3L22 4"}),e.jsx("path",{d:"M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"})]})}function Y(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.75,children:[e.jsx("path",{d:"M12 17v5"}),e.jsx("path",{d:"M8 3h8l-1 7h2l-7 7v-4l-2-3 2-7z"})]})}function F(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.75,children:[e.jsx("circle",{cx:"12",cy:"12",r:"9"}),e.jsx("path",{d:"M12 7v5l3 2"})]})}const qe={notes:$,tasks:H,pins:Y,log:F};function u({children:n,onClick:m,tone:p="neutral",disabled:s=!1,testId:r}){const l={neutral:"border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.06] hover:text-white",primary:"border-amber-400/25 bg-amber-500/10 text-amber-100 hover:bg-amber-500/15",cyan:"border-cyan-400/25 bg-cyan-500/10 text-cyan-100 hover:bg-cyan-500/15",violet:"border-violet-400/25 bg-violet-500/10 text-violet-100 hover:bg-violet-500/15",danger:"border-rose-400/25 bg-rose-500/10 text-rose-200 hover:bg-rose-500/15"};return e.jsx("button",{type:"button","data-testid":r,disabled:s,onClick:m,className:`px-2.5 py-1.5 rounded-lg border text-[9px] font-mono uppercase tracking-[0.14em] transition-all disabled:opacity-40 ${l[p]||l.neutral}`,children:n})}function g({title:n,detail:m,actionLabel:p,onAction:s,icon:r=$,compact:l=!1}){return l?e.jsxs("div",{className:"text-center px-2 py-4",children:[e.jsx("div",{className:"text-[10px] font-semibold text-slate-400",children:n}),m&&e.jsx("div",{className:"text-[9px] font-mono text-slate-600 mt-1",children:m}),typeof s=="function"&&p&&e.jsx("button",{type:"button",onClick:s,className:"mt-2 px-2 py-1 rounded border border-amber-400/20 bg-amber-500/10 text-[8px] font-mono uppercase tracking-wider text-amber-100 hover:bg-amber-500/15",children:p})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center text-center px-6 py-12",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl border border-amber-400/20 bg-gradient-to-br from-amber-500/10 to-orange-500/5 flex items-center justify-center text-amber-200 mb-4",children:e.jsx(r,{})}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-100",children:n}),e.jsx("div",{className:"text-[11px] font-mono text-slate-500 mt-1 max-w-[16rem]",children:m}),typeof s=="function"&&p&&e.jsx("button",{type:"button",onClick:s,className:"mt-4 px-3 py-1.5 rounded-lg border border-amber-400/25 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100 hover:bg-amber-500/15",children:p})]})}function P({label:n,value:m,tone:p="slate"}){const s={slate:"border-white/10 bg-black/30 text-slate-300",amber:"border-amber-400/25 bg-amber-500/10 text-amber-100",rose:"border-rose-400/25 bg-rose-500/10 text-rose-200",emerald:"border-emerald-400/25 bg-emerald-500/10 text-emerald-200"};return e.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 min-w-[4.5rem] ${s[p]||s.slate}`,children:[e.jsx("div",{className:"text-[13px] font-bold font-mono leading-none",children:m}),e.jsx("div",{className:"text-[8px] uppercase tracking-[0.16em] text-slate-500 mt-1",children:n})]})}function Ge({savedAt:n}){return e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[9px] font-mono text-emerald-300/90",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-400 shadow-[0_0_8px_rgba(52,211,153,0.45)]"}),"Saved ",R(n)]})}function Qe({task:n,expanded:m,onToggleExpand:p,onToggleDone:s,onRemove:r,onPatch:l,onPromoteDeadline:T,onInsert:E,onAddTag:v}){const j=Ye(n.dueDate,n.done),y=Fe(n.priority),[k,w]=o.useState("");return e.jsxs("article",{"data-testid":`workpad-task-${n.id}`,className:`rounded-xl border transition-all ${n.done?"border-white/[0.06] bg-black/15 opacity-80":j==="overdue"?"border-rose-400/20 bg-rose-500/[0.04] ring-1 ring-rose-400/10":"border-white/10 bg-black/25 hover:bg-black/30"}`,children:[e.jsxs("div",{className:"px-3 py-2.5 flex items-start gap-2.5",children:[e.jsx("button",{type:"button","aria-label":n.done?"Mark incomplete":"Mark complete",onClick:s,className:`mt-0.5 h-4.5 w-4.5 rounded-md border flex items-center justify-center shrink-0 transition-colors ${n.done?"border-emerald-400/40 bg-emerald-500/20 text-emerald-200":"border-white/15 bg-black/30 hover:border-amber-400/30"}`,children:n.done&&e.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2.5,children:e.jsx("path",{d:"M5 13l4 4L19 7"})})}),e.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:p,children:[e.jsx("div",{className:`text-[12px] leading-snug ${n.done?"line-through text-slate-500":"text-slate-100"}`,children:n.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[e.jsx("span",{className:`text-[8px] font-mono uppercase tracking-wider px-1.5 py-0.5 rounded border ${y.className}`,children:y.label}),n.dueDate&&e.jsx("span",{className:`text-[8px] font-mono uppercase tracking-wider px-1.5 py-0.5 rounded border ${Ue(j)}`,children:Xe(n.dueDate,n.done)}),(n.tags||[]).map(b=>e.jsxs("span",{className:"text-[8px] font-mono text-cyan-300/80",children:["#",b]},b))]})]}),e.jsx("button",{type:"button",onClick:r,className:"text-slate-600 hover:text-rose-300 text-[11px] px-1",children:"✕"})]}),m&&e.jsxs("div",{className:"px-3 pb-3 pt-0 border-t border-white/[0.05] ml-9 mr-3 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 pt-2",children:[e.jsx("input",{type:"date",value:n.dueDate||"",onChange:b=>l({dueDate:b.target.value}),className:"rounded-lg border border-white/10 bg-black/30 px-2 py-1 text-[10px] font-mono text-slate-300"}),e.jsxs("select",{value:n.priority,onChange:b=>l({priority:b.target.value}),className:"rounded-lg border border-white/10 bg-black/30 px-2 py-1 text-[10px] font-mono text-slate-300",children:[e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"normal",children:"Normal"}),e.jsx("option",{value:"high",children:"High"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(u,{tone:"cyan",onClick:T,children:"To deadlines"}),e.jsx(u,{onClick:E,children:"Insert"})]}),e.jsx("div",{className:"flex gap-1.5",children:e.jsx("input",{value:k,onChange:b=>w(b.target.value),onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),v(k),w(""))},placeholder:"Add tag...",className:"flex-1 rounded-lg border border-white/10 bg-black/30 px-2 py-1 text-[10px] font-mono text-slate-300"})})]})]})}const Ze=["Ctrl+Shift+N — toggle Workpad","Ctrl+Shift+T — toggle Operator Inbox","Ctrl+Enter — insert active note into composer","Escape — close Workpad","Task syntax: !high !low due:YYYY-MM-DD #tag Title here","/workpad /pad /notepad — open from chat"];function et({open:n,onClose:m}){return n?e.jsx("div",{className:"absolute inset-0 z-[80] bg-black/60 backdrop-blur-sm flex items-center justify-center p-4",children:e.jsxs("section",{"data-testid":"workpad-cheatsheet",className:"w-full max-w-sm rounded-2xl border border-amber-400/25 bg-shell-deep p-4 shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] font-bold text-amber-200",children:"Workpad cheatsheet"}),e.jsx("button",{type:"button",onClick:m,className:"text-slate-400 hover:text-white",children:"✕"})]}),e.jsx("ul",{className:"space-y-2 text-[10px] font-mono text-slate-300",children:Ze.map(p=>e.jsx("li",{className:"rounded-lg border border-white/5 bg-black/30 px-2.5 py-1.5",children:p},p))})]})}):null}function ot({open:n,onClose:m,workflowId:p="global"}){const s=o.useMemo(()=>String(p||"global"),[p]),[r,l]=o.useState(()=>te(s)),[T,E]=o.useState(""),[v,j]=o.useState({label:"",body:""}),[y,k]=o.useState(""),[w,b]=o.useState("open"),[_,oe]=o.useState("priority"),[N,S]=o.useState(""),[ne,le]=o.useState(""),[ie,de]=o.useState(()=>Date.now()),[X,ce]=o.useState(!1),[C,pe]=o.useState(()=>ve()),[xe,U]=o.useState(!1),O=o.useRef(null),D=o.useRef(null),z=o.useRef(!1),V=o.useRef(C);o.useEffect(()=>{V.current=C},[C]),o.useEffect(()=>{if(n)return we(s),l(te(s)),je(l,s)},[n,s]),o.useEffect(()=>{if(n)return D.current&&window.clearTimeout(D.current),D.current=window.setTimeout(()=>{ye(r,s),de(Date.now())},280),()=>{D.current&&window.clearTimeout(D.current)}},[r,n,s]),o.useEffect(()=>{if(!n)return;const t=a=>{if(a.key==="Escape"&&(a.preventDefault(),m()),(a.ctrlKey||a.metaKey)&&a.key==="Enter"&&r.activeTab==="notes"){const i=r.notes.find(c=>c.id===r.activeNoteId);i&&i.body&&(a.preventDefault(),A(i.body),x("Inserted note into composer","success"))}};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[m,n,r.activeNoteId,r.activeTab,r.notes]);const f=o.useMemo(()=>ke(r),[r]),d=String(N||"").trim().toLowerCase(),h=o.useMemo(()=>r.notes.find(t=>t.id===r.activeNoteId)||r.notes[0]||null,[r.activeNoteId,r.notes]),q=o.useMemo(()=>d?r.notes.filter(t=>t.title.toLowerCase().includes(d)||t.body.toLowerCase().includes(d)):r.notes,[d,r.notes]),G=o.useMemo(()=>{let t=Array.isArray(r.tasks)?[...r.tasks]:[];return w==="done"?t=t.filter(a=>a.done):w==="open"&&(t=t.filter(a=>!a.done)),d&&(t=t.filter(a=>a.title.toLowerCase().includes(d)||(a.tags||[]).some(i=>i.includes(d)))),t.sort((a,i)=>{if(_==="due"){const B=a.dueDate||"9999-12-31",K=i.dueDate||"9999-12-31";return B.localeCompare(K)}const c={high:0,normal:1,low:2},W=c[a.priority]??1,M=c[i.priority]??1;return W!==M?W-M:String(i.updatedAt).localeCompare(String(a.updatedAt))}),t},[d,r.tasks,w,_]),Q=o.useMemo(()=>d?r.pins.filter(t=>t.label.toLowerCase().includes(d)||t.body.toLowerCase().includes(d)):r.pins,[d,r.pins]),Z=o.useMemo(()=>{const t=d?r.log.filter(a=>a.text.toLowerCase().includes(d)):r.log;return Ne(t)},[d,r.log]),I=o.useCallback(t=>{l(a=>typeof t=="function"?t(a):{...a,...t})},[]),me=o.useCallback(()=>{const t=Ce(r);if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){navigator.clipboard.writeText(t).then(()=>{x("Workpad exported to clipboard","success")}).catch(()=>x("Export copy failed","warning"));return}x("Workpad markdown prepared","info")},[r]),ue=o.useCallback(()=>{const t=Te(r);navigator.clipboard&&typeof navigator.clipboard.writeText=="function"&&navigator.clipboard.writeText(t).then(()=>{x("Workpad JSON copied","success")}).catch(()=>x("JSON copy failed","warning"))},[r]),be=o.useCallback(async t=>{const a=t&&t.target&&t.target.files?t.target.files[0]:null;if(a)try{const i=await a.text();l(Se(i,!1,s)),x("Workpad imported","success")}catch{x("Import failed — invalid JSON","error")}finally{t&&t.target&&(t.target.value="")}},[s]),he=o.useCallback(t=>{const a=(Array.isArray(L)?L:[]).find(i=>i.id===t);a&&(l(De(a,s)),x(`Template added: ${a.title}`,"success"))},[s]),ee=o.useCallback(()=>{const t=Ie(T);t.title&&(l(ae(t.title,{dueDate:t.dueDate,priority:t.priority,tags:t.tags},s)),E(""),x("Task added","success"))},[T,s]),fe=o.useCallback(t=>{if(!t||!t.dueDate){x("Set a due date first","warning");return}We([...Ae(),{id:`workpad-${t.id}`,title:t.title,date:t.dueDate,priority:t.priority==="high"?"high":"normal"}]),x("Synced to workspace deadlines","success")},[]),ge=o.useCallback(t=>{t.preventDefault(),z.current=!0;const a=t.clientX,i=C,c=M=>{if(!z.current)return;const B=a-M.clientX,K=Math.max(Je,Math.min(He,i+B));pe(K)},W=()=>{z.current=!1,Ke(V.current),window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",W)};window.addEventListener("pointermove",c),window.addEventListener("pointerup",W)},[C]);return n?e.jsxs("aside",{"data-testid":"scratchpad-tab","aria-label":"Workpad",style:{width:C},className:"absolute right-0 top-0 bottom-0 z-[70] border-l border-amber-300/20 bg-shell-deep/98 backdrop-blur-xl shadow-[-24px_0_80px_rgba(0,0,0,0.65)] flex",children:[e.jsx("button",{type:"button","aria-label":"Resize workpad",onPointerDown:ge,className:"w-1.5 shrink-0 cursor-col-resize hover:bg-amber-400/30 active:bg-amber-400/50 transition-colors"}),e.jsxs("div",{"data-testid":"workpad-panel",className:"flex-1 min-w-0 flex flex-col",children:[e.jsxs("header",{className:"px-4 pt-4 pb-3 border-b border-white/[0.06] bg-gradient-to-r from-amber-500/[0.06] via-transparent to-orange-500/[0.03]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-xl border border-amber-400/20 bg-gradient-to-br from-amber-500/15 to-orange-500/10 flex items-center justify-center text-amber-200",children:e.jsx($,{})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.2em] font-bold text-amber-200",children:"Workpad"}),e.jsxs("div",{className:"text-[10px] font-mono text-slate-500",children:["Scope: ",e.jsx("span",{className:"text-slate-300",children:Ee()})]})]})]})}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 flex-wrap justify-end",children:[e.jsxs("select",{"data-testid":"workpad-template-select",defaultValue:"",onChange:t=>{const a=t.target.value;a&&he(a),t.target.value=""},className:"max-w-[7rem] rounded-lg border border-white/10 bg-black/35 px-2 py-1 text-[9px] font-mono text-slate-300",children:[e.jsx("option",{value:"",children:"Template…"}),(Array.isArray(L)?L:[]).map(t=>e.jsx("option",{value:t.id,children:t.title},t.id))]}),e.jsx(u,{testId:"workpad-json-export-btn",onClick:ue,children:"JSON"}),e.jsx(u,{testId:"workpad-import-btn",onClick:()=>O.current&&O.current.click(),children:"Import"}),e.jsx("input",{ref:O,type:"file",accept:"application/json,.json",className:"hidden",onChange:be}),e.jsx(u,{testId:"workpad-export-btn",onClick:me,children:"Export"}),e.jsx("button",{type:"button","data-testid":"workpad-cheatsheet-btn",onClick:()=>U(!0),className:"h-8 w-8 rounded-lg border border-white/10 text-slate-400 hover:bg-white/10 hover:text-white transition-colors text-xs",title:"Cheatsheet",children:"?"}),e.jsx("button",{type:"button","data-testid":"scratchpad-close-btn","aria-label":"Close workpad",onClick:m,className:"h-8 w-8 rounded-lg border border-white/10 text-slate-400 hover:bg-white/10 hover:text-white transition-colors",children:"✕"})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(P,{label:"Open",value:f.openTasks,tone:f.openTasks?"amber":"slate"}),e.jsx(P,{label:"Overdue",value:f.overdueTasks,tone:f.overdueTasks?"rose":"slate"}),e.jsx(P,{label:"Notes",value:f.notes,tone:"slate"}),e.jsx(P,{label:"Pins",value:f.pins,tone:"slate"})]}),e.jsx("div",{className:"mt-3 relative",children:e.jsx("input",{"data-testid":"workpad-search",value:N,onChange:t=>S(t.target.value),placeholder:"Search workpad...",className:"w-full rounded-xl border border-white/10 bg-black/35 pl-3 pr-3 py-2 text-[11px] font-mono text-slate-200 outline-none focus:border-amber-400/30 focus:ring-1 focus:ring-amber-400/10"})})]}),e.jsx("nav",{className:"px-3 py-2 flex gap-1 border-b border-white/[0.05] bg-black/20",children:Ve.map(t=>{const a=qe[t.id],i=r.activeTab===t.id,c=t.id==="tasks"?f.openTasks:0;return e.jsx("button",{type:"button","data-testid":`workpad-tab-${t.id}`,title:t.hint,onClick:()=>I({activeTab:t.id}),className:`flex-1 min-w-0 px-2 py-2 rounded-xl border transition-all ${i?"border-amber-400/25 bg-amber-500/10 text-amber-100 shadow-[inset_0_1px_0_rgba(251,191,36,0.12)]":"border-transparent text-slate-500 hover:text-slate-300 hover:bg-white/[0.03]"}`,children:e.jsxs("div",{className:"flex items-center justify-center gap-1.5",children:[e.jsx(a,{}),e.jsx("span",{className:"text-[9px] font-mono uppercase tracking-[0.12em] truncate",children:t.label}),c>0&&e.jsx("span",{className:"text-[8px] px-1 rounded bg-amber-500/20 text-amber-100",children:c})]})},t.id)})}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden",children:[r.activeTab==="notes"&&e.jsxs("div",{className:"h-full flex min-h-0",children:[e.jsxs("div",{className:"w-[9.5rem] shrink-0 border-r border-white/[0.06] p-2 flex flex-col gap-1 min-h-0",children:[e.jsx("button",{type:"button","data-testid":"workpad-new-note-btn",onClick:()=>l(re("Untitled",s)),className:"w-full px-2 py-2 rounded-lg border border-amber-400/25 bg-gradient-to-r from-amber-500/10 to-orange-500/5 text-[9px] font-mono uppercase tracking-wider text-amber-100 hover:from-amber-500/15",children:"+ New page"}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto space-y-1",children:q.length===0&&d?e.jsx(g,{compact:!0,icon:$,title:"No matches",detail:`Nothing matched "${N.trim()}"`,actionLabel:"Clear",onAction:()=>S("")}):q.map(t=>e.jsxs("button",{type:"button",onClick:()=>I({activeNoteId:t.id}),className:`w-full text-left px-2 py-2 rounded-lg border transition-colors ${t.id===r.activeNoteId?"border-amber-400/25 bg-amber-500/10":"border-transparent hover:bg-white/[0.04]"}`,children:[e.jsx("div",{className:`text-[10px] font-medium truncate ${t.id===r.activeNoteId?"text-amber-100":"text-slate-300"}`,children:t.title}),e.jsx("div",{className:"text-[8px] font-mono text-slate-600 mt-0.5",children:R(t.updatedAt)})]},t.id))})]}),e.jsx("div",{className:"flex-1 min-w-0 p-3 flex flex-col gap-2 min-h-0",children:h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{"data-testid":"workpad-note-title",value:h.title,onChange:t=>{const a=t.target.value;I(i=>({...i,notes:i.notes.map(c=>c.id===h.id?{...c,title:a,updatedAt:new Date().toISOString()}:c)}))},className:"flex-1 rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-[13px] font-semibold text-slate-100 outline-none focus:border-amber-400/30"}),e.jsx("button",{type:"button",onClick:()=>ce(t=>!t),className:`px-2 py-2 rounded-lg border text-[9px] font-mono uppercase tracking-wider ${X?"border-cyan-400/25 bg-cyan-500/10 text-cyan-100":"border-white/10 text-slate-500"}`,children:"Preview"})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-600 flex items-center justify-between",children:[e.jsxs("span",{children:[Me(h.body)," words · edited ",R(h.updatedAt)]}),e.jsx(Ge,{savedAt:ie})]}),X?e.jsx("div",{"data-testid":"workpad-note-preview",className:"flex-1 min-h-0 overflow-auto rounded-xl border border-white/10 bg-black/30 px-3 py-3 text-[12px] font-mono text-slate-300 whitespace-pre-wrap",children:h.body||"Nothing to preview yet."}):e.jsx("textarea",{"data-testid":"scratchpad-input",value:h.body,onChange:t=>{const a=t.target.value;I(i=>({...i,notes:i.notes.map(c=>c.id===h.id?{...c,body:a,updatedAt:new Date().toISOString()}:c)}))},placeholder:"Meeting notes, prompts, specs, ideas...",className:"flex-1 min-h-0 w-full rounded-xl border border-white/10 bg-black/40 px-3 py-3 text-[12px] font-mono leading-relaxed text-slate-200 outline-none focus:border-amber-400/35 resize-none"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(u,{tone:"cyan",onClick:()=>A(h.body),children:"Insert"}),e.jsx(u,{tone:"violet",onClick:()=>l(J(h.title,h.body,s)),children:"Pin"}),e.jsx(u,{onClick:()=>l(Le(h.id,s)),children:"Duplicate"}),e.jsx(u,{tone:"danger",onClick:()=>{if(r.notes.length<=1){x("Keep at least one note page","warning");return}l(Pe(h.id,s))},children:"Delete"})]})]}):e.jsx(g,{title:"No notes yet",detail:"Create a page for specs, prompts, or meeting notes.",actionLabel:"Create first page",onAction:()=>l(re("Inbox",s))})})]}),r.activeTab==="tasks"&&e.jsxs("div",{className:"h-full p-3 flex flex-col gap-3 min-h-0",children:[e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("input",{"data-testid":"workpad-task-input",value:T,onChange:t=>E(t.target.value),onKeyDown:t=>{t.key==="Enter"&&(t.preventDefault(),ee())},placeholder:"Add task — try !high due:2026-05-21 #tag Review PR",className:"w-full rounded-lg border border-white/10 bg-black/35 px-3 py-2.5 text-[12px] font-mono text-slate-200 outline-none focus:border-amber-400/30"}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(u,{testId:"workpad-add-task-btn",tone:"primary",onClick:ee,children:"Add task"}),e.jsx("span",{className:"text-[9px] font-mono text-slate-600",children:"Smart: !high · due:YYYY-MM-DD · #tag"})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[["open","done","all"].map(t=>e.jsx("button",{type:"button",onClick:()=>b(t),className:`px-2.5 py-1 rounded-lg text-[9px] font-mono uppercase tracking-wider border ${w===t?"border-amber-400/25 bg-amber-500/10 text-amber-100":"border-transparent text-slate-500 hover:text-slate-300"}`,children:t},t)),e.jsxs("select",{value:_,onChange:t=>oe(t.target.value),className:"ml-auto rounded-lg border border-white/10 bg-black/30 px-2 py-1 text-[9px] font-mono text-slate-400",children:[e.jsx("option",{value:"priority",children:"Sort: Priority"}),e.jsx("option",{value:"due",children:"Sort: Due date"})]}),e.jsx("button",{type:"button",onClick:()=>l(Re(s)),className:"text-[9px] font-mono uppercase tracking-wider text-slate-500 hover:text-rose-300",children:"Clear done"})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto space-y-2 pr-0.5",children:G.length===0?d?e.jsx(g,{icon:H,title:"No matches",detail:`No tasks matched "${N.trim()}"`,actionLabel:"Clear search",onAction:()=>S("")}):e.jsx(g,{icon:H,title:"Task list is clear",detail:"Capture action items with priorities, due dates, and tags.",actionLabel:"Add sample task",onAction:()=>l(ae("Review bridge settings",{priority:"high"},s))}):G.map(t=>e.jsx(Qe,{task:t,expanded:ne===t.id,onToggleExpand:()=>le(a=>a===t.id?"":t.id),onToggleDone:()=>l(ze(t.id,s)),onRemove:()=>l(Oe(t.id,s)),onPatch:a=>l(_e(t.id,a,s)),onPromoteDeadline:()=>fe(t),onInsert:()=>A(t.title),onAddTag:a=>l($e(t.id,a,s))},t.id))})]}),r.activeTab==="pins"&&e.jsxs("div",{className:"h-full p-3 flex flex-col gap-3 min-h-0 overflow-auto",children:[e.jsxs("div",{className:"rounded-xl border border-violet-400/15 bg-violet-500/[0.04] p-3 space-y-2",children:[e.jsx("input",{value:v.label,onChange:t=>j(a=>({...a,label:t.target.value})),placeholder:"Pin label",className:"w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-[11px] font-mono text-slate-200 outline-none focus:border-violet-400/30"}),e.jsx("textarea",{value:v.body,onChange:t=>j(a=>({...a,body:t.target.value})),placeholder:"Reusable snippet — prompts, commands, templates...",rows:3,className:"w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-[11px] font-mono text-slate-200 outline-none resize-none focus:border-violet-400/30"}),e.jsx(u,{testId:"workpad-add-pin-btn",tone:"violet",onClick:()=>{String(v.body||"").trim()&&(l(J(v.label,v.body,s)),j({label:"",body:""}),x("Pin saved","success"))},children:"Save pin"})]}),Q.length===0?d?e.jsx(g,{icon:Y,title:"No matches",detail:`No pins matched "${N.trim()}"`,actionLabel:"Clear search",onAction:()=>S("")}):e.jsx(g,{icon:Y,title:"No pins saved",detail:"Store reusable snippets for one-click insert into the composer.",actionLabel:"Add example pin",onAction:()=>{l(J("Composer prompt","Summarize the active thread in 3 bullets.",s)),x("Example pin added","success")}}):e.jsx("div",{className:"grid gap-2",children:Q.map(t=>e.jsxs("div",{className:"rounded-xl border border-violet-400/15 bg-gradient-to-br from-violet-500/[0.06] to-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-semibold text-violet-100",children:t.label}),e.jsx("div",{className:"text-[8px] font-mono text-slate-600 mt-0.5",children:R(t.updatedAt)})]}),e.jsx("button",{type:"button",onClick:()=>I(a=>({...a,pins:a.pins.filter(i=>i.id!==t.id)})),className:"text-slate-600 hover:text-rose-300 text-[10px]",children:"✕"})]}),e.jsx("pre",{className:"text-[10px] font-mono text-slate-300 whitespace-pre-wrap max-h-28 overflow-auto",children:t.body}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(u,{tone:"cyan",onClick:()=>A(t.body),children:"Insert"}),e.jsx(u,{onClick:()=>{navigator.clipboard&&navigator.clipboard.writeText(t.body).catch(()=>{}),x("Copied","success")},children:"Copy"})]})]},t.id))})]}),r.activeTab==="log"&&e.jsxs("div",{className:"h-full p-3 flex flex-col gap-3 min-h-0",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{"data-testid":"workpad-log-input",value:y,onChange:t=>k(t.target.value),onKeyDown:t=>{if(t.key==="Enter"){t.preventDefault();const a=String(y||"").trim();if(!a)return;l(se(a,s)),k("")}},placeholder:"Quick capture — Enter to log",className:"flex-1 rounded-lg border border-white/10 bg-black/35 px-3 py-2 text-[12px] font-mono text-slate-200 outline-none focus:border-amber-400/30"}),e.jsx(u,{tone:"primary",onClick:()=>{const t=String(y||"").trim();t&&(l(se(t,s)),k(""))},children:"Log"})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto space-y-4",children:Z.length===0?d?e.jsx(g,{icon:F,title:"No matches",detail:`Nothing in capture log matched "${N.trim()}"`,actionLabel:"Clear search",onAction:()=>S("")}):e.jsx(g,{icon:F,title:"Capture log empty",detail:"Log decisions, blockers, and ideas with timestamps."}):Z.map(t=>e.jsxs("section",{children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.18em] text-slate-500 mb-2 sticky top-0 bg-shell-deep/95 py-1",children:t.day}),e.jsx("div",{className:"space-y-2",children:t.rows.map(a=>e.jsxs("div",{className:"rounded-xl border border-white/8 bg-black/25 px-3 py-2.5",children:[e.jsx("div",{className:"text-[9px] font-mono text-slate-600",children:Be(a.at)}),e.jsx("div",{className:"text-[11px] font-mono text-slate-300 mt-1 whitespace-pre-wrap leading-relaxed",children:a.text}),e.jsx("button",{type:"button",onClick:()=>A(a.text),className:"mt-2 text-[9px] font-mono uppercase tracking-wider text-cyan-300/80 hover:text-cyan-200",children:"Insert"})]},a.id))})]},t.day))})]})]}),e.jsxs("footer",{className:"px-4 py-2.5 border-t border-white/[0.06] bg-black/30 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-[9px] font-mono text-slate-500 truncate",children:[f.openTasks," open · ",f.overdueTasks," overdue · ",f.notes," notes"]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-600 shrink-0",children:"⌃⇧N · Esc close · ⌃↵ insert note"})]})]}),e.jsx(et,{open:xe,onClose:()=>U(!1)})]}):null}export{ot as default}; +import{R as o,j as e}from"./vendor-react-C1Vrmh6-.js";import{l as te,r as ve,s as we,a as je,b as ye,w as ke,g as Ne,e as Ce,c as x,d as Te,i as Se,f as L,h as De,p as Ie,j as ae,k as We,m as Ae,n as Ee,o as re,q as R,t as Me,u as A,v as J,x as Le,y as Pe,z as Re,A as $e,B as _e,C as Oe,D as ze,E as se,F as Be,G as Ke,W as Je,H as He,I as Ye,J as Fe,K as Xe,L as Ue}from"./main-I-j1AS1W.js";import"./vendor-misc-DYLXRpC5.js";import"./vendor-state-B3vIvpM5.js";const Ve=[{id:"notes",label:"Notes",hint:"Pages & drafts"},{id:"tasks",label:"Tasks",hint:"Action items"},{id:"pins",label:"Pins",hint:"Snippets"},{id:"log",label:"Capture",hint:"Timestamped log"}];function $(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.75,children:[e.jsx("path",{d:"M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2"}),e.jsx("rect",{x:"9",y:"3",width:"6",height:"4",rx:"1"}),e.jsx("path",{d:"M9 12h6M9 16h4"})]})}function H(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.75,children:[e.jsx("path",{d:"M9 11l3 3L22 4"}),e.jsx("path",{d:"M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"})]})}function Y(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.75,children:[e.jsx("path",{d:"M12 17v5"}),e.jsx("path",{d:"M8 3h8l-1 7h2l-7 7v-4l-2-3 2-7z"})]})}function F(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.75,children:[e.jsx("circle",{cx:"12",cy:"12",r:"9"}),e.jsx("path",{d:"M12 7v5l3 2"})]})}const qe={notes:$,tasks:H,pins:Y,log:F};function u({children:n,onClick:m,tone:p="neutral",disabled:s=!1,testId:r}){const l={neutral:"border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.06] hover:text-white",primary:"border-amber-400/25 bg-amber-500/10 text-amber-100 hover:bg-amber-500/15",cyan:"border-cyan-400/25 bg-cyan-500/10 text-cyan-100 hover:bg-cyan-500/15",violet:"border-violet-400/25 bg-violet-500/10 text-violet-100 hover:bg-violet-500/15",danger:"border-rose-400/25 bg-rose-500/10 text-rose-200 hover:bg-rose-500/15"};return e.jsx("button",{type:"button","data-testid":r,disabled:s,onClick:m,className:`px-2.5 py-1.5 rounded-lg border text-[9px] font-mono uppercase tracking-[0.14em] transition-all disabled:opacity-40 ${l[p]||l.neutral}`,children:n})}function g({title:n,detail:m,actionLabel:p,onAction:s,icon:r=$,compact:l=!1}){return l?e.jsxs("div",{className:"text-center px-2 py-4",children:[e.jsx("div",{className:"text-[10px] font-semibold text-slate-400",children:n}),m&&e.jsx("div",{className:"text-[9px] font-mono text-slate-600 mt-1",children:m}),typeof s=="function"&&p&&e.jsx("button",{type:"button",onClick:s,className:"mt-2 px-2 py-1 rounded border border-amber-400/20 bg-amber-500/10 text-[8px] font-mono uppercase tracking-wider text-amber-100 hover:bg-amber-500/15",children:p})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center text-center px-6 py-12",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl border border-amber-400/20 bg-gradient-to-br from-amber-500/10 to-orange-500/5 flex items-center justify-center text-amber-200 mb-4",children:e.jsx(r,{})}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-100",children:n}),e.jsx("div",{className:"text-[11px] font-mono text-slate-500 mt-1 max-w-[16rem]",children:m}),typeof s=="function"&&p&&e.jsx("button",{type:"button",onClick:s,className:"mt-4 px-3 py-1.5 rounded-lg border border-amber-400/25 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100 hover:bg-amber-500/15",children:p})]})}function P({label:n,value:m,tone:p="slate"}){const s={slate:"border-white/10 bg-black/30 text-slate-300",amber:"border-amber-400/25 bg-amber-500/10 text-amber-100",rose:"border-rose-400/25 bg-rose-500/10 text-rose-200",emerald:"border-emerald-400/25 bg-emerald-500/10 text-emerald-200"};return e.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 min-w-[4.5rem] ${s[p]||s.slate}`,children:[e.jsx("div",{className:"text-[13px] font-bold font-mono leading-none",children:m}),e.jsx("div",{className:"text-[8px] uppercase tracking-[0.16em] text-slate-500 mt-1",children:n})]})}function Ge({savedAt:n}){return e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[9px] font-mono text-emerald-300/90",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-400 shadow-[0_0_8px_rgba(52,211,153,0.45)]"}),"Saved ",R(n)]})}function Qe({task:n,expanded:m,onToggleExpand:p,onToggleDone:s,onRemove:r,onPatch:l,onPromoteDeadline:T,onInsert:E,onAddTag:v}){const j=Ye(n.dueDate,n.done),y=Fe(n.priority),[k,w]=o.useState("");return e.jsxs("article",{"data-testid":`workpad-task-${n.id}`,className:`rounded-xl border transition-all ${n.done?"border-white/[0.06] bg-black/15 opacity-80":j==="overdue"?"border-rose-400/20 bg-rose-500/[0.04] ring-1 ring-rose-400/10":"border-white/10 bg-black/25 hover:bg-black/30"}`,children:[e.jsxs("div",{className:"px-3 py-2.5 flex items-start gap-2.5",children:[e.jsx("button",{type:"button","aria-label":n.done?"Mark incomplete":"Mark complete",onClick:s,className:`mt-0.5 h-4.5 w-4.5 rounded-md border flex items-center justify-center shrink-0 transition-colors ${n.done?"border-emerald-400/40 bg-emerald-500/20 text-emerald-200":"border-white/15 bg-black/30 hover:border-amber-400/30"}`,children:n.done&&e.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2.5,children:e.jsx("path",{d:"M5 13l4 4L19 7"})})}),e.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:p,children:[e.jsx("div",{className:`text-[12px] leading-snug ${n.done?"line-through text-slate-500":"text-slate-100"}`,children:n.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[e.jsx("span",{className:`text-[8px] font-mono uppercase tracking-wider px-1.5 py-0.5 rounded border ${y.className}`,children:y.label}),n.dueDate&&e.jsx("span",{className:`text-[8px] font-mono uppercase tracking-wider px-1.5 py-0.5 rounded border ${Ue(j)}`,children:Xe(n.dueDate,n.done)}),(n.tags||[]).map(b=>e.jsxs("span",{className:"text-[8px] font-mono text-cyan-300/80",children:["#",b]},b))]})]}),e.jsx("button",{type:"button",onClick:r,className:"text-slate-600 hover:text-rose-300 text-[11px] px-1",children:"✕"})]}),m&&e.jsxs("div",{className:"px-3 pb-3 pt-0 border-t border-white/[0.05] ml-9 mr-3 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 pt-2",children:[e.jsx("input",{type:"date",value:n.dueDate||"",onChange:b=>l({dueDate:b.target.value}),className:"rounded-lg border border-white/10 bg-black/30 px-2 py-1 text-[10px] font-mono text-slate-300"}),e.jsxs("select",{value:n.priority,onChange:b=>l({priority:b.target.value}),className:"rounded-lg border border-white/10 bg-black/30 px-2 py-1 text-[10px] font-mono text-slate-300",children:[e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"normal",children:"Normal"}),e.jsx("option",{value:"high",children:"High"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(u,{tone:"cyan",onClick:T,children:"To deadlines"}),e.jsx(u,{onClick:E,children:"Insert"})]}),e.jsx("div",{className:"flex gap-1.5",children:e.jsx("input",{value:k,onChange:b=>w(b.target.value),onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),v(k),w(""))},placeholder:"Add tag...",className:"flex-1 rounded-lg border border-white/10 bg-black/30 px-2 py-1 text-[10px] font-mono text-slate-300"})})]})]})}const Ze=["Ctrl+Shift+N — toggle Workpad","Ctrl+Shift+T — toggle Operator Inbox","Ctrl+Enter — insert active note into composer","Escape — close Workpad","Task syntax: !high !low due:YYYY-MM-DD #tag Title here","/workpad /pad /notepad — open from chat"];function et({open:n,onClose:m}){return n?e.jsx("div",{className:"absolute inset-0 z-[80] bg-black/60 backdrop-blur-sm flex items-center justify-center p-4",children:e.jsxs("section",{"data-testid":"workpad-cheatsheet",className:"w-full max-w-sm rounded-2xl border border-amber-400/25 bg-shell-deep p-4 shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] font-bold text-amber-200",children:"Workpad cheatsheet"}),e.jsx("button",{type:"button",onClick:m,className:"text-slate-400 hover:text-white",children:"✕"})]}),e.jsx("ul",{className:"space-y-2 text-[10px] font-mono text-slate-300",children:Ze.map(p=>e.jsx("li",{className:"rounded-lg border border-white/5 bg-black/30 px-2.5 py-1.5",children:p},p))})]})}):null}function ot({open:n,onClose:m,workflowId:p="global"}){const s=o.useMemo(()=>String(p||"global"),[p]),[r,l]=o.useState(()=>te(s)),[T,E]=o.useState(""),[v,j]=o.useState({label:"",body:""}),[y,k]=o.useState(""),[w,b]=o.useState("open"),[_,oe]=o.useState("priority"),[N,S]=o.useState(""),[ne,le]=o.useState(""),[ie,de]=o.useState(()=>Date.now()),[X,ce]=o.useState(!1),[C,pe]=o.useState(()=>ve()),[xe,U]=o.useState(!1),O=o.useRef(null),D=o.useRef(null),z=o.useRef(!1),V=o.useRef(C);o.useEffect(()=>{V.current=C},[C]),o.useEffect(()=>{if(n)return we(s),l(te(s)),je(l,s)},[n,s]),o.useEffect(()=>{if(n)return D.current&&window.clearTimeout(D.current),D.current=window.setTimeout(()=>{ye(r,s),de(Date.now())},280),()=>{D.current&&window.clearTimeout(D.current)}},[r,n,s]),o.useEffect(()=>{if(!n)return;const t=a=>{if(a.key==="Escape"&&(a.preventDefault(),m()),(a.ctrlKey||a.metaKey)&&a.key==="Enter"&&r.activeTab==="notes"){const i=r.notes.find(c=>c.id===r.activeNoteId);i&&i.body&&(a.preventDefault(),A(i.body),x("Inserted note into composer","success"))}};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[m,n,r.activeNoteId,r.activeTab,r.notes]);const f=o.useMemo(()=>ke(r),[r]),d=String(N||"").trim().toLowerCase(),h=o.useMemo(()=>r.notes.find(t=>t.id===r.activeNoteId)||r.notes[0]||null,[r.activeNoteId,r.notes]),q=o.useMemo(()=>d?r.notes.filter(t=>t.title.toLowerCase().includes(d)||t.body.toLowerCase().includes(d)):r.notes,[d,r.notes]),G=o.useMemo(()=>{let t=Array.isArray(r.tasks)?[...r.tasks]:[];return w==="done"?t=t.filter(a=>a.done):w==="open"&&(t=t.filter(a=>!a.done)),d&&(t=t.filter(a=>a.title.toLowerCase().includes(d)||(a.tags||[]).some(i=>i.includes(d)))),t.sort((a,i)=>{if(_==="due"){const B=a.dueDate||"9999-12-31",K=i.dueDate||"9999-12-31";return B.localeCompare(K)}const c={high:0,normal:1,low:2},W=c[a.priority]??1,M=c[i.priority]??1;return W!==M?W-M:String(i.updatedAt).localeCompare(String(a.updatedAt))}),t},[d,r.tasks,w,_]),Q=o.useMemo(()=>d?r.pins.filter(t=>t.label.toLowerCase().includes(d)||t.body.toLowerCase().includes(d)):r.pins,[d,r.pins]),Z=o.useMemo(()=>{const t=d?r.log.filter(a=>a.text.toLowerCase().includes(d)):r.log;return Ne(t)},[d,r.log]),I=o.useCallback(t=>{l(a=>typeof t=="function"?t(a):{...a,...t})},[]),me=o.useCallback(()=>{const t=Ce(r);if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){navigator.clipboard.writeText(t).then(()=>{x("Workpad exported to clipboard","success")}).catch(()=>x("Export copy failed","warning"));return}x("Workpad markdown prepared","info")},[r]),ue=o.useCallback(()=>{const t=Te(r);navigator.clipboard&&typeof navigator.clipboard.writeText=="function"&&navigator.clipboard.writeText(t).then(()=>{x("Workpad JSON copied","success")}).catch(()=>x("JSON copy failed","warning"))},[r]),be=o.useCallback(async t=>{const a=t&&t.target&&t.target.files?t.target.files[0]:null;if(a)try{const i=await a.text();l(Se(i,!1,s)),x("Workpad imported","success")}catch{x("Import failed — invalid JSON","error")}finally{t&&t.target&&(t.target.value="")}},[s]),he=o.useCallback(t=>{const a=(Array.isArray(L)?L:[]).find(i=>i.id===t);a&&(l(De(a,s)),x(`Template added: ${a.title}`,"success"))},[s]),ee=o.useCallback(()=>{const t=Ie(T);t.title&&(l(ae(t.title,{dueDate:t.dueDate,priority:t.priority,tags:t.tags},s)),E(""),x("Task added","success"))},[T,s]),fe=o.useCallback(t=>{if(!t||!t.dueDate){x("Set a due date first","warning");return}We([...Ae(),{id:`workpad-${t.id}`,title:t.title,date:t.dueDate,priority:t.priority==="high"?"high":"normal"}]),x("Synced to workspace deadlines","success")},[]),ge=o.useCallback(t=>{t.preventDefault(),z.current=!0;const a=t.clientX,i=C,c=M=>{if(!z.current)return;const B=a-M.clientX,K=Math.max(Je,Math.min(He,i+B));pe(K)},W=()=>{z.current=!1,Ke(V.current),window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",W)};window.addEventListener("pointermove",c),window.addEventListener("pointerup",W)},[C]);return n?e.jsxs("aside",{"data-testid":"scratchpad-tab","aria-label":"Workpad",style:{width:C},className:"absolute right-0 top-0 bottom-0 z-[70] border-l border-amber-300/20 bg-shell-deep/98 backdrop-blur-xl shadow-[-24px_0_80px_rgba(0,0,0,0.65)] flex",children:[e.jsx("button",{type:"button","aria-label":"Resize workpad",onPointerDown:ge,className:"w-1.5 shrink-0 cursor-col-resize hover:bg-amber-400/30 active:bg-amber-400/50 transition-colors"}),e.jsxs("div",{"data-testid":"workpad-panel",className:"flex-1 min-w-0 flex flex-col",children:[e.jsxs("header",{className:"px-4 pt-4 pb-3 border-b border-white/[0.06] bg-gradient-to-r from-amber-500/[0.06] via-transparent to-orange-500/[0.03]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-xl border border-amber-400/20 bg-gradient-to-br from-amber-500/15 to-orange-500/10 flex items-center justify-center text-amber-200",children:e.jsx($,{})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.2em] font-bold text-amber-200",children:"Workpad"}),e.jsxs("div",{className:"text-[10px] font-mono text-slate-500",children:["Scope: ",e.jsx("span",{className:"text-slate-300",children:Ee()})]})]})]})}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 flex-wrap justify-end",children:[e.jsxs("select",{"data-testid":"workpad-template-select",defaultValue:"",onChange:t=>{const a=t.target.value;a&&he(a),t.target.value=""},className:"max-w-[7rem] rounded-lg border border-white/10 bg-black/35 px-2 py-1 text-[9px] font-mono text-slate-300",children:[e.jsx("option",{value:"",children:"Template…"}),(Array.isArray(L)?L:[]).map(t=>e.jsx("option",{value:t.id,children:t.title},t.id))]}),e.jsx(u,{testId:"workpad-json-export-btn",onClick:ue,children:"JSON"}),e.jsx(u,{testId:"workpad-import-btn",onClick:()=>O.current&&O.current.click(),children:"Import"}),e.jsx("input",{ref:O,type:"file",accept:"application/json,.json",className:"hidden",onChange:be}),e.jsx(u,{testId:"workpad-export-btn",onClick:me,children:"Export"}),e.jsx("button",{type:"button","data-testid":"workpad-cheatsheet-btn",onClick:()=>U(!0),className:"h-8 w-8 rounded-lg border border-white/10 text-slate-400 hover:bg-white/10 hover:text-white transition-colors text-xs",title:"Cheatsheet",children:"?"}),e.jsx("button",{type:"button","data-testid":"scratchpad-close-btn","aria-label":"Close workpad",onClick:m,className:"h-8 w-8 rounded-lg border border-white/10 text-slate-400 hover:bg-white/10 hover:text-white transition-colors",children:"✕"})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(P,{label:"Open",value:f.openTasks,tone:f.openTasks?"amber":"slate"}),e.jsx(P,{label:"Overdue",value:f.overdueTasks,tone:f.overdueTasks?"rose":"slate"}),e.jsx(P,{label:"Notes",value:f.notes,tone:"slate"}),e.jsx(P,{label:"Pins",value:f.pins,tone:"slate"})]}),e.jsx("div",{className:"mt-3 relative",children:e.jsx("input",{"data-testid":"workpad-search",value:N,onChange:t=>S(t.target.value),placeholder:"Search workpad...",className:"w-full rounded-xl border border-white/10 bg-black/35 pl-3 pr-3 py-2 text-[11px] font-mono text-slate-200 outline-none focus:border-amber-400/30 focus:ring-1 focus:ring-amber-400/10"})})]}),e.jsx("nav",{className:"px-3 py-2 flex gap-1 border-b border-white/[0.05] bg-black/20",children:Ve.map(t=>{const a=qe[t.id],i=r.activeTab===t.id,c=t.id==="tasks"?f.openTasks:0;return e.jsx("button",{type:"button","data-testid":`workpad-tab-${t.id}`,title:t.hint,onClick:()=>I({activeTab:t.id}),className:`flex-1 min-w-0 px-2 py-2 rounded-xl border transition-all ${i?"border-amber-400/25 bg-amber-500/10 text-amber-100 shadow-[inset_0_1px_0_rgba(251,191,36,0.12)]":"border-transparent text-slate-500 hover:text-slate-300 hover:bg-white/[0.03]"}`,children:e.jsxs("div",{className:"flex items-center justify-center gap-1.5",children:[e.jsx(a,{}),e.jsx("span",{className:"text-[9px] font-mono uppercase tracking-[0.12em] truncate",children:t.label}),c>0&&e.jsx("span",{className:"text-[8px] px-1 rounded bg-amber-500/20 text-amber-100",children:c})]})},t.id)})}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden",children:[r.activeTab==="notes"&&e.jsxs("div",{className:"h-full flex min-h-0",children:[e.jsxs("div",{className:"w-[9.5rem] shrink-0 border-r border-white/[0.06] p-2 flex flex-col gap-1 min-h-0",children:[e.jsx("button",{type:"button","data-testid":"workpad-new-note-btn",onClick:()=>l(re("Untitled",s)),className:"w-full px-2 py-2 rounded-lg border border-amber-400/25 bg-gradient-to-r from-amber-500/10 to-orange-500/5 text-[9px] font-mono uppercase tracking-wider text-amber-100 hover:from-amber-500/15",children:"+ New page"}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto space-y-1",children:q.length===0&&d?e.jsx(g,{compact:!0,icon:$,title:"No matches",detail:`Nothing matched "${N.trim()}"`,actionLabel:"Clear",onAction:()=>S("")}):q.map(t=>e.jsxs("button",{type:"button",onClick:()=>I({activeNoteId:t.id}),className:`w-full text-left px-2 py-2 rounded-lg border transition-colors ${t.id===r.activeNoteId?"border-amber-400/25 bg-amber-500/10":"border-transparent hover:bg-white/[0.04]"}`,children:[e.jsx("div",{className:`text-[10px] font-medium truncate ${t.id===r.activeNoteId?"text-amber-100":"text-slate-300"}`,children:t.title}),e.jsx("div",{className:"text-[8px] font-mono text-slate-600 mt-0.5",children:R(t.updatedAt)})]},t.id))})]}),e.jsx("div",{className:"flex-1 min-w-0 p-3 flex flex-col gap-2 min-h-0",children:h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{"data-testid":"workpad-note-title",value:h.title,onChange:t=>{const a=t.target.value;I(i=>({...i,notes:i.notes.map(c=>c.id===h.id?{...c,title:a,updatedAt:new Date().toISOString()}:c)}))},className:"flex-1 rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-[13px] font-semibold text-slate-100 outline-none focus:border-amber-400/30"}),e.jsx("button",{type:"button",onClick:()=>ce(t=>!t),className:`px-2 py-2 rounded-lg border text-[9px] font-mono uppercase tracking-wider ${X?"border-cyan-400/25 bg-cyan-500/10 text-cyan-100":"border-white/10 text-slate-500"}`,children:"Preview"})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-600 flex items-center justify-between",children:[e.jsxs("span",{children:[Me(h.body)," words · edited ",R(h.updatedAt)]}),e.jsx(Ge,{savedAt:ie})]}),X?e.jsx("div",{"data-testid":"workpad-note-preview",className:"flex-1 min-h-0 overflow-auto rounded-xl border border-white/10 bg-black/30 px-3 py-3 text-[12px] font-mono text-slate-300 whitespace-pre-wrap",children:h.body||"Nothing to preview yet."}):e.jsx("textarea",{"data-testid":"scratchpad-input",value:h.body,onChange:t=>{const a=t.target.value;I(i=>({...i,notes:i.notes.map(c=>c.id===h.id?{...c,body:a,updatedAt:new Date().toISOString()}:c)}))},placeholder:"Meeting notes, prompts, specs, ideas...",className:"flex-1 min-h-0 w-full rounded-xl border border-white/10 bg-black/40 px-3 py-3 text-[12px] font-mono leading-relaxed text-slate-200 outline-none focus:border-amber-400/35 resize-none"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(u,{tone:"cyan",onClick:()=>A(h.body),children:"Insert"}),e.jsx(u,{tone:"violet",onClick:()=>l(J(h.title,h.body,s)),children:"Pin"}),e.jsx(u,{onClick:()=>l(Le(h.id,s)),children:"Duplicate"}),e.jsx(u,{tone:"danger",onClick:()=>{if(r.notes.length<=1){x("Keep at least one note page","warning");return}l(Pe(h.id,s))},children:"Delete"})]})]}):e.jsx(g,{title:"No notes yet",detail:"Create a page for specs, prompts, or meeting notes.",actionLabel:"Create first page",onAction:()=>l(re("Inbox",s))})})]}),r.activeTab==="tasks"&&e.jsxs("div",{className:"h-full p-3 flex flex-col gap-3 min-h-0",children:[e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("input",{"data-testid":"workpad-task-input",value:T,onChange:t=>E(t.target.value),onKeyDown:t=>{t.key==="Enter"&&(t.preventDefault(),ee())},placeholder:"Add task — try !high due:2026-05-21 #tag Review PR",className:"w-full rounded-lg border border-white/10 bg-black/35 px-3 py-2.5 text-[12px] font-mono text-slate-200 outline-none focus:border-amber-400/30"}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(u,{testId:"workpad-add-task-btn",tone:"primary",onClick:ee,children:"Add task"}),e.jsx("span",{className:"text-[9px] font-mono text-slate-600",children:"Smart: !high · due:YYYY-MM-DD · #tag"})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[["open","done","all"].map(t=>e.jsx("button",{type:"button",onClick:()=>b(t),className:`px-2.5 py-1 rounded-lg text-[9px] font-mono uppercase tracking-wider border ${w===t?"border-amber-400/25 bg-amber-500/10 text-amber-100":"border-transparent text-slate-500 hover:text-slate-300"}`,children:t},t)),e.jsxs("select",{value:_,onChange:t=>oe(t.target.value),className:"ml-auto rounded-lg border border-white/10 bg-black/30 px-2 py-1 text-[9px] font-mono text-slate-400",children:[e.jsx("option",{value:"priority",children:"Sort: Priority"}),e.jsx("option",{value:"due",children:"Sort: Due date"})]}),e.jsx("button",{type:"button",onClick:()=>l(Re(s)),className:"text-[9px] font-mono uppercase tracking-wider text-slate-500 hover:text-rose-300",children:"Clear done"})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto space-y-2 pr-0.5",children:G.length===0?d?e.jsx(g,{icon:H,title:"No matches",detail:`No tasks matched "${N.trim()}"`,actionLabel:"Clear search",onAction:()=>S("")}):e.jsx(g,{icon:H,title:"Task list is clear",detail:"Capture action items with priorities, due dates, and tags.",actionLabel:"Add sample task",onAction:()=>l(ae("Review bridge settings",{priority:"high"},s))}):G.map(t=>e.jsx(Qe,{task:t,expanded:ne===t.id,onToggleExpand:()=>le(a=>a===t.id?"":t.id),onToggleDone:()=>l(ze(t.id,s)),onRemove:()=>l(Oe(t.id,s)),onPatch:a=>l(_e(t.id,a,s)),onPromoteDeadline:()=>fe(t),onInsert:()=>A(t.title),onAddTag:a=>l($e(t.id,a,s))},t.id))})]}),r.activeTab==="pins"&&e.jsxs("div",{className:"h-full p-3 flex flex-col gap-3 min-h-0 overflow-auto",children:[e.jsxs("div",{className:"rounded-xl border border-violet-400/15 bg-violet-500/[0.04] p-3 space-y-2",children:[e.jsx("input",{value:v.label,onChange:t=>j(a=>({...a,label:t.target.value})),placeholder:"Pin label",className:"w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-[11px] font-mono text-slate-200 outline-none focus:border-violet-400/30"}),e.jsx("textarea",{value:v.body,onChange:t=>j(a=>({...a,body:t.target.value})),placeholder:"Reusable snippet — prompts, commands, templates...",rows:3,className:"w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-[11px] font-mono text-slate-200 outline-none resize-none focus:border-violet-400/30"}),e.jsx(u,{testId:"workpad-add-pin-btn",tone:"violet",onClick:()=>{String(v.body||"").trim()&&(l(J(v.label,v.body,s)),j({label:"",body:""}),x("Pin saved","success"))},children:"Save pin"})]}),Q.length===0?d?e.jsx(g,{icon:Y,title:"No matches",detail:`No pins matched "${N.trim()}"`,actionLabel:"Clear search",onAction:()=>S("")}):e.jsx(g,{icon:Y,title:"No pins saved",detail:"Store reusable snippets for one-click insert into the composer.",actionLabel:"Add example pin",onAction:()=>{l(J("Composer prompt","Summarize the active thread in 3 bullets.",s)),x("Example pin added","success")}}):e.jsx("div",{className:"grid gap-2",children:Q.map(t=>e.jsxs("div",{className:"rounded-xl border border-violet-400/15 bg-gradient-to-br from-violet-500/[0.06] to-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-semibold text-violet-100",children:t.label}),e.jsx("div",{className:"text-[8px] font-mono text-slate-600 mt-0.5",children:R(t.updatedAt)})]}),e.jsx("button",{type:"button",onClick:()=>I(a=>({...a,pins:a.pins.filter(i=>i.id!==t.id)})),className:"text-slate-600 hover:text-rose-300 text-[10px]",children:"✕"})]}),e.jsx("pre",{className:"text-[10px] font-mono text-slate-300 whitespace-pre-wrap max-h-28 overflow-auto",children:t.body}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(u,{tone:"cyan",onClick:()=>A(t.body),children:"Insert"}),e.jsx(u,{onClick:()=>{navigator.clipboard&&navigator.clipboard.writeText(t.body).catch(()=>{}),x("Copied","success")},children:"Copy"})]})]},t.id))})]}),r.activeTab==="log"&&e.jsxs("div",{className:"h-full p-3 flex flex-col gap-3 min-h-0",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{"data-testid":"workpad-log-input",value:y,onChange:t=>k(t.target.value),onKeyDown:t=>{if(t.key==="Enter"){t.preventDefault();const a=String(y||"").trim();if(!a)return;l(se(a,s)),k("")}},placeholder:"Quick capture — Enter to log",className:"flex-1 rounded-lg border border-white/10 bg-black/35 px-3 py-2 text-[12px] font-mono text-slate-200 outline-none focus:border-amber-400/30"}),e.jsx(u,{tone:"primary",onClick:()=>{const t=String(y||"").trim();t&&(l(se(t,s)),k(""))},children:"Log"})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto space-y-4",children:Z.length===0?d?e.jsx(g,{icon:F,title:"No matches",detail:`Nothing in capture log matched "${N.trim()}"`,actionLabel:"Clear search",onAction:()=>S("")}):e.jsx(g,{icon:F,title:"Capture log empty",detail:"Log decisions, blockers, and ideas with timestamps."}):Z.map(t=>e.jsxs("section",{children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.18em] text-slate-500 mb-2 sticky top-0 bg-shell-deep/95 py-1",children:t.day}),e.jsx("div",{className:"space-y-2",children:t.rows.map(a=>e.jsxs("div",{className:"rounded-xl border border-white/8 bg-black/25 px-3 py-2.5",children:[e.jsx("div",{className:"text-[9px] font-mono text-slate-600",children:Be(a.at)}),e.jsx("div",{className:"text-[11px] font-mono text-slate-300 mt-1 whitespace-pre-wrap leading-relaxed",children:a.text}),e.jsx("button",{type:"button",onClick:()=>A(a.text),className:"mt-2 text-[9px] font-mono uppercase tracking-wider text-cyan-300/80 hover:text-cyan-200",children:"Insert"})]},a.id))})]},t.day))})]})]}),e.jsxs("footer",{className:"px-4 py-2.5 border-t border-white/[0.06] bg-black/30 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-[9px] font-mono text-slate-500 truncate",children:[f.openTasks," open · ",f.overdueTasks," overdue · ",f.notes," notes"]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-600 shrink-0",children:"⌃⇧N · Esc close · ⌃↵ insert note"})]})]}),e.jsx(et,{open:xe,onClose:()=>U(!1)})]}):null}export{ot as default}; diff --git a/dist-renderer/js/main-2TeVSSYI.js b/dist-renderer/js/main-I-j1AS1W.js similarity index 88% rename from dist-renderer/js/main-2TeVSSYI.js rename to dist-renderer/js/main-I-j1AS1W.js index 0f4c3599..dabb6870 100644 --- a/dist-renderer/js/main-2TeVSSYI.js +++ b/dist-renderer/js/main-I-j1AS1W.js @@ -1,11 +1,11 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./OnboardingProgressRail-D4ADuSst.js","./vendor-react-C1Vrmh6-.js","./vendor-misc-DYLXRpC5.js","./vendor-state-B3vIvpM5.js","./ScratchpadTab-D2yqtgVs.js"])))=>i.map(i=>d[i]); -import{r as O,j as e,c as Dl,R as i,A as Cx,a as _x,C as Ax,M as Ex,S as Ix,b as Px,d as ul,U as Rx,B as Ox,D as Tx,e as Mx,f as Dx,g as gp,h as $x,i as Lx,X as yp,k as Bx,l as Fx,m as Ux,T as zx,n as Hx,o as Wx,p as Kx,q as pl,s as Vx,t as Gx,F as Jx,u as qx,Z as Yx,P as Zx,L as Xx,v as od,w as Qx,x as ef,y as tf,z as rf}from"./vendor-react-C1Vrmh6-.js";import{p as nf,a as sf}from"./vendor-state-B3vIvpM5.js";import"./vendor-misc-DYLXRpC5.js";(function(){const r=document.createElement("link").relList;if(r&&r.supports&&r.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))s(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&s(l)}).observe(document,{childList:!0,subtree:!0});function n(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(a){if(a.ep)return;a.ep=!0;const o=n(a);fetch(a.href,o)}})();function na(t,r){const[n,s]=O.useState(r),[a,o]=O.useState(!0),l=O.useRef(r);O.useEffect(()=>{l.current=n},[n]),O.useEffect(()=>{async function u(){const d=await window.api.state.get();d[t]!==void 0&&(s(d[t]),l.current=d[t]),o(!1)}const x=d=>{d&&d[t]!==void 0&&(s(d[t]),l.current=d[t])};u();const p=window.api.on("state-updated",x);return()=>{typeof p=="function"&&p()}},[t]);const c=O.useCallback(async u=>{const x=l.current,p=typeof u=="function"?u(x):u;l.current=p,s(p),await window.api.state.update({[t]:p})},[t]);return[n,c,a]}const af=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;function of(t){let r=String(t??"").trim();return!r||(r=r.replace(/[/\\]+/g,"-"),r=r.replace(/\.\./g,"-"),r=r.replace(/[^a-zA-Z0-9._\-\s]+/g,""),r=r.replace(/\s+/g,"-"),r=r.replace(/-+/g,"-"),r=r.replace(/^[-_.]+|[-_.]+$/g,""),!r)?"":(af.test(r)&&(r=`session-${r}`),r)}function lf(t,r="Session name"){const n=String(t??"").trim();if(!n)throw new Error(`${r} is required.`);if(n.includes("..")||n.includes("/")||n.includes("\\"))throw new Error("Invalid session name path traversal.");const s=of(n);if(!s)throw new Error(`${r} is required.`);return s}const wp=O.createContext(null),Vt="default",Ir="NeuralShell_QuickStart",cf=1200;function lt(t){return String(t||"").trim()}function df(t){const r=Array.isArray(t)?t:[],n=Array.from(new Set(r.map(s=>lt(s)).filter(Boolean)));return n.length||n.push(Ir),n}function uf({children:t}){const[r,n]=na("model","llama3"),[s,a]=na("workflowId",Vt),[o]=na("nt_xp_state",{xp:0,tier:1}),[l,c]=na("sessionAutoLockOnBlur",!1),[u,x]=O.useState("checklist"),[p,d]=O.useState(null),[m,f]=O.useState([]),[b,h]=O.useState([]),[g,y]=O.useState({}),[P,A]=O.useState({cpuPercent:0,memoryMb:0}),[C,w]=O.useState("idle"),[j,E]=O.useState(""),[N,_]=O.useState({state:"idle",detail:"",at:0}),[S,R]=O.useState(!1),[$,U]=O.useState(!1),I=O.useRef({}),D=O.useRef(null),z=O.useRef(new Map),F=O.useRef(0),J=O.useCallback(()=>{h([]),d(null),x("checklist")},[]),ee=O.useCallback(re=>{const ae=lt(re);return!ae||ae===Ir?!0:!!g[ae]},[g]),ie=O.useCallback((re,ae={})=>{const M=lt(re);return{chat:Array.isArray(ae.chat)?ae.chat:b,model:String(ae.model||r||"llama3"),workflowId:M||String(ae.workflowId||s||Vt),outputMode:String(ae.outputMode||u||"checklist"),displayLabel:String(ae.displayLabel||M||s||Vt),workspaceAttachment:ae.workspaceAttachment===void 0?p:ae.workspaceAttachment,updatedAt:new Date().toISOString()}},[b,r,u,p,s]),ye=O.useCallback(async()=>{const re=await window.api.session.list(),ae=df(re);return f(ae),ae},[]),pe=O.useCallback(async(re,ae)=>{const M=lt(re),V=String(ae||"").trim();if(!M||!V)return{ok:!1,error:"Session name and passphrase are required."};const G=F.current+1;F.current=G,w("loading"),E("");try{const te=await window.api.session.load(M,V);return F.current!==G?{ok:!1,stale:!0}:(h(Array.isArray(te&&te.chat)?te.chat:[]),x(te&&te.outputMode?String(te.outputMode):"checklist"),d(te&&te.workspaceAttachment?te.workspaceAttachment:null),te&&te.model&&n(String(te.model)),w("ready"),E(""),{ok:!0,payload:te})}catch(te){if(F.current!==G)return{ok:!1,stale:!0};const de=te&&te.message?te.message:"Failed to load session.";return w("locked"),E(`Session "${M}" could not be unlocked. ${de}`),J(),{ok:!1,error:de}}},[n,J]),K=O.useCallback(async({name:re,passphrase:ae})=>{const M=lt(re),V=String(ae||"").trim();let G="";try{G=lf(M)}catch(te){return{ok:!1,error:te&&te.message?te.message:"Session name is required."}}if(!V)return{ok:!1,error:"Passphrase is required."};try{_({state:"saving",detail:(M!==G?G:null)?`Creating "${G}" (from "${M}")...`:`Creating "${G}"...`,at:Date.now()});const de=ie(G,{chat:[],workflowId:G,outputMode:"checklist",workspaceAttachment:null,displayLabel:M||G});await window.api.session.save(G,de,V),I.current[G]=V,y(Q=>({...Q,[G]:!0})),await ye(),await a(G),x("checklist");const L=await pe(G,V);if(!L.ok&&!L.stale)return L;const be=JSON.stringify(de);return z.current.set(G,be),_({state:"saved",detail:`Session "${G}" created.`,at:Date.now()}),{ok:!0,name:G}}catch(te){const de=te&&te.message?te.message:"Failed to create session.";return _({state:"error",detail:de,at:Date.now()}),{ok:!1,error:de}}},[ie,pe,ye,a]),H=O.useCallback(async(re,ae)=>{const M=lt(re),V=String(ae||"").trim();if(!M)return{ok:!1,error:"Session name is required."};if(!V)return{ok:!1,error:"Passphrase is required."};const G=await pe(M,V);return G.ok?(I.current[M]=V,y(te=>({...te,[M]:!0})),a(M),_({state:"idle",detail:`Unlocked "${M}".`,at:Date.now()}),{ok:!0}):G},[pe,a]),W=O.useCallback(re=>{const ae=lt(re);ae&&a(ae)},[a]),Z=O.useCallback(re=>{const ae=lt(re||s);if(!ae||ae===Vt||ae===Ir)return{ok:!1,error:"No lockable session is selected."};const M=!!I.current[ae];return delete I.current[ae],y(V=>{if(!V[ae])return V;const G={...V};return delete G[ae],G}),lt(s)===ae&&(w("locked"),E(`Session "${ae}" is locked. Enter passphrase to load it.`),J()),_({state:"locked",detail:M?`Locked "${ae}".`:`Session "${ae}" was already locked.`,at:Date.now()}),{ok:!0}},[s,J]),ce=O.useCallback(async(re="manual")=>{const ae=lt(s);if(!ae||ae===Vt||ae===Ir)return{ok:!1,error:"No persisted session selected."};const M=I.current[ae];if(!M)return w("locked"),E(`Session "${ae}" is locked. Enter passphrase to save.`),_({state:"locked",detail:`Session "${ae}" is locked. Unlock to save.`,at:Date.now()}),{ok:!1,error:"Session is locked."};_({state:"saving",detail:`${re==="autosave"?"Autosaving":re==="retry"?"Retrying save for":re==="flush"?"Flushing":"Saving"} "${ae}"...`,at:Date.now()});const G=ie(ae),te=JSON.stringify(G);try{return await window.api.session.save(ae,G,M),z.current.set(ae,te),_({state:"saved",detail:re==="autosave"?`Autosaved "${ae}".`:re==="flush"?`Flushed "${ae}".`:`Saved "${ae}".`,at:Date.now()}),{ok:!0}}catch(de){const L=de&&de.message?de.message:"Save failed.";return _({state:"error",detail:L,at:Date.now()}),{ok:!1,error:L}}},[s,ie]),fe=O.useCallback(async()=>{D.current&&(clearTimeout(D.current),D.current=null),await ce("flush")},[ce]);O.useEffect(()=>{ye().catch(re=>{E(re&&re.message?re.message:"Failed to load session index.")})},[ye]),O.useEffect(()=>{if(!m.length)return;const re=lt(s);if(!re||re===Vt){a(m[0]);return}m.includes(re)||a(m[0])},[m,s,a]),O.useEffect(()=>{const re=lt(s);if(!re||re===Vt||re===Ir){w("ready"),E(""),(re===Ir||re===Vt)&&J();return}const ae=I.current[re];if(!ae){w("locked"),E(`Session "${re}" is locked. Enter passphrase to load it.`),J();return}pe(re,ae)},[s,pe,J]),O.useEffect(()=>{const re=lt(s);if(!re||re===Vt||re===Ir||C!=="ready"||!I.current[re])return;const M=ie(re),V=JSON.stringify(M);if(z.current.get(re)!==V)return D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{ce("autosave").catch(()=>{})},cf),()=>{D.current&&(clearTimeout(D.current),D.current=null)}},[s,b,r,u,p,ie,ce,C]),O.useEffect(()=>{const re=()=>{fe().catch(()=>{})},ae=()=>{document.visibilityState==="hidden"&&fe().catch(()=>{})};return window.addEventListener("beforeunload",re),window.addEventListener("pagehide",re),document.addEventListener("visibilitychange",ae),()=>{window.removeEventListener("beforeunload",re),window.removeEventListener("pagehide",re),document.removeEventListener("visibilitychange",ae)}},[fe]),O.useEffect(()=>{if(!l)return;const re=()=>{Z(s)};return window.addEventListener("blur",re),()=>{window.removeEventListener("blur",re)}},[l,Z,s]),O.useEffect(()=>{const re=setInterval(async()=>{var ae,M;if((M=(ae=window.api)==null?void 0:ae.system)!=null&&M.getStats)try{const V=await window.api.system.getStats();A(V)}catch{}},3e3);return()=>clearInterval(re)},[]);const me=O.useCallback(()=>R(!0),[]),ke=O.useCallback(()=>R(!1),[]),Pe=O.useCallback(()=>R(re=>!re),[]),_e=O.useCallback(()=>U(!0),[]),ne=O.useCallback(()=>U(!1),[]),we=O.useCallback(re=>{h(ae=>[...ae,{...re,ts:re&&re.ts!=null?re.ts:Date.now()}])},[]),Be={model:r,setModel:n,workflowId:s,setWorkflowId:a,outputMode:u,setOutputMode:x,workspaceAttachment:p,setWorkspaceAttachment:d,xpState:o,sessions:m,chatLog:b,appendChat:we,setChatLog:h,unlockedSessions:g,createSession:K,unlockSession:H,selectSession:W,lockSession:Z,saveActiveSession:ce,flushPendingAutosave:fe,refreshSessions:ye,isSessionUnlocked:ee,sessionHydrationStatus:C,sessionError:j,saveStatus:N,autoLockOnBlur:l,setAutoLockOnBlur:c,stats:P,showPalette:S,openPalette:me,closePalette:ke,togglePalette:Pe,showSettings:$,openSettings:_e,closeSettings:ne};return e.jsx(wp.Provider,{value:Be,children:t})}function $l(){const t=O.useContext(wp);if(!t)throw new Error("useShell must be used within ShellProvider");return t}const pf="NeuralShell_QuickStart";function mf({workflowId:t,proofStatus:r,exportAvailable:n,evidenceExported:s}){const a=!!t&&t!==pf,o=r==="passed",l=r==="running",c=r==="failed";return[{id:"project",label:"Open project",description:a?`Session: ${t}`:"Create or open a workflow session from the rail",stepState:a?"complete":"active",ctaLabel:a?null:"Focus workspace",ctaDisabled:!1},{id:"proof",label:"Run proof check",description:o?"Last run: passed":l?"Running…":c?"Last run: failed — rerun to recover":"90-second value proof: trust, execution safety, session reliability, release evidence",stepState:o?"complete":c?"needs-attention":"idle",ctaLabel:l?"Running…":o?"Re-run":"Run /proof",ctaDisabled:l},{id:"trust",label:"Review trust gaps",description:"Inspect connection-profile trust state and forensic history",stepState:"idle",ctaLabel:"Open Trust Report",ctaDisabled:!1},{id:"export",label:"Export receipt",description:s?"Evidence bundle exported this session":n?"Export tamper-evident evidence bundle with workpad snapshots":"Unavailable — api not loaded (run in packaged app)",stepState:s?"complete":n?"idle":"unavailable",ctaLabel:s?"Re-export":"Export evidence",ctaDisabled:!n},{id:"ship",label:"Ship",description:s?"Proof artifacts ready — attach bundle to release pipeline":"Complete proof check and export receipt first",stepState:s?"complete":"idle",ctaLabel:s?"Open workpad for release notes":null,ctaDisabled:!1}]}const id={complete:"border-emerald-400/30 bg-emerald-500/10 text-emerald-300",active:"border-cyan-400/30 bg-cyan-500/10 text-cyan-300","needs-attention":"border-amber-400/30 bg-amber-500/10 text-amber-300",unavailable:"border-slate-600/30 bg-slate-800/30 text-slate-500",idle:"border-slate-600/30 bg-slate-900/30 text-slate-400"},xf={complete:"Done",active:"Active","needs-attention":"Action needed",unavailable:"Unavailable",idle:"Ready"};function ff({stepState:t}){const r=id[t]||id.idle;return e.jsx("span",{className:`px-2 py-0.5 rounded border text-[8px] font-mono uppercase tracking-[0.13em] ${r}`,children:xf[t]||t})}function bf({step:t,onAction:r}){const n=typeof r=="function"&&t.ctaLabel&&!t.ctaDisabled;return e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-white/8 bg-black/20 px-3 py-2.5","data-testid":`spine-step-${t.id}`,children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[11px] font-semibold text-slate-100",children:t.label}),e.jsx(ff,{stepState:t.stepState})]}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500 mt-0.5 leading-snug",children:t.description})]}),t.ctaLabel&&e.jsx("button",{type:"button",disabled:t.ctaDisabled||!n,onClick:n?r:void 0,className:`shrink-0 px-2.5 py-1.5 rounded border text-[9px] font-mono uppercase tracking-[0.13em] transition-colors ${n?"border-cyan-400/30 bg-cyan-500/10 text-cyan-200 hover:bg-cyan-500/20":"border-slate-600/20 bg-transparent text-slate-600 cursor-default"} disabled:opacity-50`,"aria-label":t.ctaLabel,children:t.ctaLabel})]})}function hf({workflowId:t,proofStatus:r="idle",exportEvidenceAvailable:n=!1,evidenceExported:s=!1,onRunProof:a,onOpenTrustReport:o,onExportEvidence:l,onOpenWorkpad:c,onDismiss:u}){const x=mf({workflowId:t,proofStatus:r,exportAvailable:n,evidenceExported:s}),p={project:()=>window.dispatchEvent(new CustomEvent("neuralshell:focus-composer")),proof:a,trust:o,export:l,ship:c};return e.jsxs("div",{role:"region","aria-label":"Operator spine","data-testid":"operator-spine-card",className:"fixed top-16 right-4 z-40 w-80 rounded-xl border border-white/10 bg-slate-950/95 shadow-2xl shadow-black/60 backdrop-blur-sm",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 pt-3 pb-2 border-b border-white/8",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-semibold text-slate-100 tracking-wide",children:"Operator Spine"}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500 mt-0.5",children:"Open project → Proof → Trust → Export → Ship"})]}),e.jsx("button",{type:"button",onClick:u,"aria-label":"Dismiss operator spine","data-testid":"spine-dismiss-btn",className:"text-slate-500 hover:text-slate-300 transition-colors text-xs leading-none p-1",children:"✕"})]}),e.jsx("div",{className:"flex flex-col gap-1.5 p-3",children:x.map(d=>e.jsx(bf,{step:d,onAction:p[d.id]},d.id))}),e.jsx("div",{className:"px-4 pb-3 text-[9px] font-mono text-slate-600 leading-snug",children:"ProofForge · local operator console · proof-first"})]})}function ml(t){return String(t||"").replace(/^Error invoking remote method '[^']+':\s*/i,"").replace(/^Error:\s*/i,"").replace(/^TypeError:\s*/i,"").trim()}function ld(t,r={}){const n=ml(t&&t.message?t.message:String(t||"unknown error")),s=n.toLowerCase(),a=String(r.provider||"ollama").trim().toLowerCase(),o=String(r.baseUrl||r.ollamaBaseUrl||"http://127.0.0.1:11434").trim(),l=String(r.model||"llama3").trim();return/offline mode is on|hosted bridges are blocked/.test(s)?"Hosted provider access is disabled. Enable Hosted Provider Access in Settings, then retry.":/requires an api key/.test(s)?"Provider authentication failed. Add your API key in Settings and run Test Live Connection.":/cancelled|aborted/.test(s)?"Request cancelled.":/fetch failed|failed to fetch|connection refused|enotfound|econnrefused|network|timed out|offline|not detected|socket hang up/.test(s)?a==="ollama"?`Provider connection failed. Check that Ollama is running at ${o} and that model ${l} is available. Open Settings to test the connection, then retry.`:`Provider connection failed for ${a}. Check base URL, API key, and network access in Settings, then retry.`:/model.*not found|not found|404/.test(s)?`Model "${l}" is not available on the configured provider. Open Settings, choose an installed model, and retry.`:/401|403|unauthorized|forbidden|api key/.test(s)?"Provider authentication failed. Check your API key in Settings and retry.":/blocked by safety/.test(s)?n:"Provider request failed. Open Settings to verify provider setup, then retry."}const vp="neuralshell_ui_prefs_v1",gf=["light","dark","system"],yf=["small","medium","large"],wf=["violet","fuchsia","sky","emerald","amber","rose","teal"],vf=["left","right"],jf=["operator","frutiger-aero"],Nn={violet:{primary:"#8b5cf6",hover:"#a78bfa",ring:"rgba(139,92,246,0.2)",bg:"rgba(139,92,246,0.06)"},fuchsia:{primary:"#d946ef",hover:"#e879f9",ring:"rgba(217,70,239,0.2)",bg:"rgba(217,70,239,0.06)"},sky:{primary:"#0ea5e9",hover:"#38bdf8",ring:"rgba(14,165,233,0.2)",bg:"rgba(14,165,233,0.06)"},emerald:{primary:"#10b981",hover:"#34d399",ring:"rgba(16,185,129,0.2)",bg:"rgba(16,185,129,0.06)"},amber:{primary:"#f59e0b",hover:"#fbbf24",ring:"rgba(245,158,11,0.2)",bg:"rgba(245,158,11,0.06)"},rose:{primary:"#f43f5e",hover:"#fb7185",ring:"rgba(244,63,94,0.2)",bg:"rgba(244,63,94,0.06)"},teal:{primary:"#14b8a6",hover:"#2dd4bf",ring:"rgba(20,184,166,0.2)",bg:"rgba(20,184,166,0.06)"}},cd={small:{base:12,mono:10,heading:11},medium:{base:14,mono:12,heading:13},large:{base:16,mono:14,heading:15}};function Ll(t){const r=String(t||"").trim().toLowerCase();return gf.includes(r)?r:"system"}function Bl(t){const r=Number.isFinite(Number(t))?Number(t):.2;return Math.max(0,Math.min(2,Number(r.toFixed(2))))}function Fl(t){const r=String(t||"").trim().toLowerCase();return yf.includes(r)?r:"medium"}function Ha(t){const r=String(t||"").trim().toLowerCase();return wf.includes(r)?r:"violet"}function Ul(t){const r=String(t||"").trim().toLowerCase();return jf.includes(r)?r:"operator"}function zl(t){const r=String(t||"").trim().toLowerCase();return vf.includes(r)?r:"left"}function dd(t,r=""){if(typeof document>"u")return;const n=Nn[Ha(t)]||Nn.violet,a=(String(r||"").trim()&&/^#?[0-9a-fA-F]{3,6}$/.test(String(r||"").trim())?String(r).startsWith("#")?String(r):`#${r}`:n.primary).toUpperCase(),o=/^#([0-9a-fA-F]{6})$/.exec(a)||/^#([0-9a-fA-F]{3})$/.exec(a);let l="34 211 238";if(o){const c=o[1],u=c.length===3?c.split("").map(m=>`${m}${m}`).join(""):c,x=Number.parseInt(u.slice(0,2),16),p=Number.parseInt(u.slice(2,4),16),d=Number.parseInt(u.slice(4,6),16);l=`${x} ${p} ${d}`}document.body.style.setProperty("--accent",a),document.body.style.setProperty("--accent-rgb",l),document.documentElement.style.setProperty("--accent",a),document.documentElement.style.setProperty("--accent-rgb",l)}const _a={theme:"system",temperature:.2,fontSize:"medium",accentColor:"violet",customAccentHex:"",compactMode:!1,animationsEnabled:!0,sidebarPosition:"left",visualStyle:"operator"};function kf(){if(typeof window>"u"||!window.localStorage)return{..._a};try{const t=window.localStorage.getItem(vp);if(!t)return{..._a};const r=JSON.parse(t);return{theme:Ll(r.theme),temperature:Bl(r.temperature),fontSize:Fl(r.fontSize),accentColor:Ha(r.accentColor),customAccentHex:String(r.customAccentHex||""),compactMode:!!r.compactMode,animationsEnabled:r.animationsEnabled!==!1,sidebarPosition:zl(r.sidebarPosition),visualStyle:Ul(r.visualStyle)}}catch{return{..._a}}}const xl=kf(),Xt=Dl(t=>({...xl,setTheme:r=>t({theme:Ll(r)}),setTemperature:r=>t({temperature:Bl(r)}),setFontSize:r=>t({fontSize:Fl(r)}),setAccentColor:r=>t({accentColor:Ha(r)}),setCustomAccentHex:r=>t({customAccentHex:String(r||"")}),setCompactMode:r=>t({compactMode:!!r}),setAnimationsEnabled:r=>t({animationsEnabled:!!r}),setSidebarPosition:r=>t({sidebarPosition:zl(r)}),setVisualStyle:r=>t({visualStyle:Ul(r)}),resetToDefaults:()=>t({..._a})}));typeof window<"u"&&window.localStorage&&(dd(xl.accentColor,xl.customAccentHex),Xt.subscribe(t=>{dd(t.accentColor,t.customAccentHex);try{window.localStorage.setItem(vp,JSON.stringify({theme:Ll(t.theme),temperature:Bl(t.temperature),fontSize:Fl(t.fontSize),accentColor:Ha(t.accentColor),customAccentHex:String(t.customAccentHex||""),compactMode:!!t.compactMode,animationsEnabled:t.animationsEnabled!==!1,sidebarPosition:zl(t.sidebarPosition),visualStyle:Ul(t.visualStyle)}))}catch{}}));const fl=2500;function ud(t){const r=Number.isFinite(Number(t))?Number(t):fl;return Math.max(0,Math.min(fl,Math.round(r)))}function Nf(t={}){const r=Number(t.windowMs||5e3),n=Number(t.pollMs||1e3),[s,a]=i.useState([]);i.useEffect(()=>{let x=!0,p=null;const d=async()=>{const m=typeof performance<"u"?performance.now():Date.now();let f=!1,b="api_unavailable",h=fl;try{if(window.api&&window.api.llm&&typeof window.api.llm.ping=="function"){f=!!await window.api.llm.ping(),b=f?"ok":"ping_false";const y=typeof performance<"u"?performance.now():Date.now();h=ud(y-m)}}catch(g){b=g&&g.message?String(g.message):"ping_failed";const y=typeof performance<"u"?performance.now():Date.now();h=ud(y-m)}x&&(a(g=>{const y=Date.now(),P=[...g,{at:y,ms:h,ok:f,reason:b}].filter(C=>y-C.at<=r),A=Math.max(5,Math.ceil(r/Math.max(200,n))+2);return P.slice(-A)}),p=setTimeout(d,n))};return d(),()=>{x=!1,p&&clearTimeout(p)}},[n,r]);const o=s.length?s[s.length-1]:null,l=o?o.ms:0,c=s.length?Math.round(s.reduce((x,p)=>x+p.ms,0)/s.length):0,u=o?o.ok:!1;return{samples:s,latencyMs:l,avgLatencyMs:c,online:u,lastReason:o?o.reason:"not_checked"}}const jp="neuralshell_clock_sync_v1",Sf=2500,Cf=6*60*60*1e3,_f=10*60*1e3;function Si(t,r,n,s){const a=t.getHours(),o=t.getMinutes(),l=t.getSeconds(),c=a>=12?"PM":"AM",x=`${String(a%12||12)}:${String(o).padStart(2,"0")}:${String(l).padStart(2,"0")} ${c}`,p=t.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),d=t.toLocaleDateString("en-US",{weekday:"short"});return{time:x,date:p,dow:d,rawH:a,rawM:o,rawS:l,rawDay:t.getDate(),rawMonth:t.getMonth()+1,rawYear:t.getFullYear(),syncSource:r,syncOffsetMs:n,syncedAt:s}}function pd(){try{const t=window.localStorage.getItem(jp);if(!t)return null;const r=JSON.parse(t),n=Number(r==null?void 0:r.offsetMs),s=Number(r==null?void 0:r.syncedAt);return!Number.isFinite(n)||!Number.isFinite(s)||Date.now()-s>Cf?null:{offsetMs:Math.round(n),syncedAt:s}}catch{return null}}function Af(t,r){try{window.localStorage.setItem(jp,JSON.stringify({offsetMs:t,syncedAt:r}))}catch{}}async function Ef(t,r){const n=new AbortController,s=window.setTimeout(()=>n.abort(),Sf),a=()=>n.abort();r.addEventListener("abort",a);try{const o=await fetch(t,{method:"GET",cache:"no-store",signal:n.signal});if(!o.ok)throw new Error(`time endpoint responded with status ${o.status}`);return await o.json()}finally{window.clearTimeout(s),r.removeEventListener("abort",a)}}async function If(t){const r=[{url:"https://worldtimeapi.org/api/ip",parse:s=>Date.parse(String((s==null?void 0:s.utc_datetime)||""))},{url:"https://worldtimeapi.org/api/timezone/Etc/UTC",parse:s=>Date.parse(String((s==null?void 0:s.utc_datetime)||""))},{url:"https://timeapi.io/api/Time/current/zone?timeZone=UTC",parse:s=>Date.parse(String((s==null?void 0:s.dateTime)||""))}];let n=null;for(const s of r)try{const a=Date.now(),o=await Ef(s.url,t),l=Date.now(),c=s.parse(o);if(!Number.isFinite(c))throw new Error(`invalid server timestamp from ${s.url}`);const u=a+Math.floor((l-a)/2);return Math.round(c-u)}catch(a){n=a}throw n instanceof Error?n:new Error("unable to fetch internet time offset")}function Pf(){const t=Date.now(),r=typeof window<"u"?pd():null,n=(r==null?void 0:r.offsetMs)||0,s=(r==null?void 0:r.syncedAt)||t,a=r?"cached":"local",[o,l]=O.useState(n),[c,u]=O.useState(a),[x,p]=O.useState(s),[d,m]=O.useState(()=>Si(new Date(t+n),a,n,s));return O.useEffect(()=>{let f=!0,b=0,h=0,g=null,y=n,P=a,A=s;const C=(S,R,$=Date.now())=>{y=S,P=R,A=$,l(S),u(R),p(A);const U=new Date(Date.now()+S);m(Si(U,R,S,A))},w=()=>{const S=new Date(Date.now()+y);m(Si(S,P,y,A))},j=async()=>{g&&g.abort();const S=new AbortController;g=S;try{const R=await If(S.signal);if(!f||S.signal.aborted)return;const $=Date.now();Af(R,$),C(R,"network",$)}catch{if(!f||S.signal.aborted)return;const R=pd();if(R){C(R.offsetMs,"cached",R.syncedAt);return}C(0,"local")}},E=1e3-Date.now()%1e3,N=window.setTimeout(()=>{w(),b=window.setInterval(w,1e3)},E);j().catch(()=>{}),h=window.setInterval(()=>{j().catch(()=>{})},_f);const _=()=>{document.visibilityState==="visible"&&j().catch(()=>{})};return document.addEventListener("visibilitychange",_),()=>{f=!1,g&&g.abort(),window.clearTimeout(N),window.clearInterval(b),window.clearInterval(h),document.removeEventListener("visibilitychange",_)}},[]),d}function Rf(t,r,n){if(n)return"border-amber-300/35 bg-amber-500/12 text-amber-100";const s=String(t||"").toLowerCase();return s==="enterprise"?"border-amber-300/30 bg-amber-500/10 text-amber-200":s==="pro"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-200":String(r||"").toUpperCase()==="PREVIEW"?"border-cyan-300/25 bg-cyan-500/8 text-cyan-100":"border-slate-300/20 bg-slate-500/10 text-slate-300"}function Of({tierLabel:t,tierId:r,runtimeTier:n,isOperator:s}){return s?"OPERATOR NODE":String(n||"").toUpperCase()==="PREVIEW"?"PREVIEW NODE":String(t||r||"free")}function Tf({tierId:t,tierLabel:r,runtimeTier:n,isOperator:s=!1,onUnlock:a}){const o=!s&&typeof a=="function",l=Of({tierLabel:r,tierId:t,runtimeTier:n,isOperator:s}),c=`inline-flex items-center px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${Rf(t,n,s)} ${o?"cursor-pointer hover:bg-white/10":""}`;return o?e.jsx("button",{type:"button","data-testid":"tier-badge",className:c,title:"Click to enter operator license",onClick:a,children:l}):e.jsx("span",{"data-testid":"tier-badge",className:c,title:`Tier ${l}`,children:l})}const md={verified:{dot:"bg-emerald-400 shadow-[0_0_8px_rgba(52,211,153,0.55)]",text:"text-emerald-300",border:"border-emerald-400/25",bg:"bg-emerald-500/10",label:"VERIFIED"},watch:{dot:"bg-amber-400 shadow-[0_0_8px_rgba(251,191,36,0.45)]",text:"text-amber-200",border:"border-amber-400/25",bg:"bg-amber-500/10",label:"WATCH"},degraded:{dot:"bg-orange-400 shadow-[0_0_8px_rgba(251,146,60,0.45)]",text:"text-orange-200",border:"border-orange-400/25",bg:"bg-orange-500/10",label:"DEGRADED"},critical:{dot:"bg-red-400 shadow-[0_0_8px_rgba(248,113,113,0.55)] animate-pulse",text:"text-red-200",border:"border-red-400/30",bg:"bg-red-500/10",label:"CRITICAL"}};function Mf(t){const r=String(t||"watch").toLowerCase();return md[r]||md.watch}function kp({report:t,compact:r=!1,onClick:n,testId:s="omega-posture-badge"}){const a=t&&t.posture?t.posture:null,o=Mf(a&&a.posture),l=a&&Number.isFinite(Number(a.score))?a.score:null,c=r?`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md border text-[9px] font-mono uppercase tracking-wider ${o.border} ${o.bg} ${o.text}`:`inline-flex items-center gap-2 px-2.5 py-1 rounded-lg border text-[10px] font-mono uppercase tracking-wider ${o.border} ${o.bg} ${o.text}`,u=e.jsxs(e.Fragment,{children:[e.jsx("span",{className:`inline-block h-1.5 w-1.5 rounded-full shrink-0 ${o.dot}`}),e.jsx("span",{children:"OMEGA"}),e.jsx("span",{className:"text-slate-500",children:"·"}),e.jsx("span",{children:o.label}),l!==null&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-slate-600",children:"·"}),e.jsx("span",{className:"tabular-nums",children:l})]})]});return typeof n=="function"?e.jsx("button",{type:"button","data-testid":s,onClick:n,className:`${c} hover:brightness-110 transition-all cursor-pointer`,title:"Run /omega kernel scan",children:u}):e.jsx("span",{"data-testid":s,className:c,title:"OMEGA kernel posture",children:u})}function Df(t){const r=String(t||"unknown").toLowerCase();return r==="running"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-200":r==="stopped"||r==="degraded"?"border-amber-300/40 bg-amber-500/10 text-amber-100":r==="fatal"||r==="spawn-failed"?"border-rose-300/40 bg-rose-500/10 text-rose-100":"border-slate-300/20 bg-slate-500/10 text-slate-300"}function $f({status:t,alertCount:r,onClick:n}){return e.jsxs("button",{type:"button","data-testid":"watchdog-status-badge",onClick:n,className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-lg border text-[9px] font-mono uppercase tracking-[0.14em] ${Df(t)}`,title:"Open runtime watchdog alerts",children:[e.jsx("span",{children:"Watchdog"}),e.jsx("span",{children:String(t||"unknown")}),e.jsx("span",{className:"opacity-80",children:Math.max(0,Number(r||0))})]})}function Lf({enabled:t,onOpen:r}){const n=!!t;return e.jsx("button",{type:"button","data-testid":"appliance-mode-badge",onClick:r,className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-lg border text-[9px] font-mono uppercase tracking-[0.12em] ${n?"border-cyan-300/35 bg-cyan-500/15 text-cyan-100":"border-slate-300/25 bg-slate-500/10 text-slate-300"}`,title:n?"Appliance mode is active":"Appliance mode is inactive",children:e.jsx("span",{children:n?"Appliance On":"Appliance Off"})})}function Bf({locked:t,onOpen:r}){const n=!!t;return e.jsx("button",{type:"button","data-testid":"airgap-mode-badge",onClick:r,className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-lg border text-[9px] font-mono uppercase tracking-[0.12em] ${n?"border-slate-300/30 bg-slate-500/20 text-slate-100":"border-cyan-300/35 bg-cyan-500/10 text-cyan-100"}`,title:n?"Air-gapped lock is active":"Air-gapped lock is inactive","aria-label":n?"Air-gapped lock active":"Air-gapped lock inactive",children:e.jsx("span",{children:n?"AirGap Locked":"AirGap Ready"})})}function Ff({enabled:t,onOpen:r}){return e.jsxs("button",{type:"button","data-testid":"demo-mode-badge",onClick:r,className:`px-2.5 py-1.5 rounded-lg border text-[10px] font-mono transition-colors ${t?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":"border-slate-300/25 bg-slate-500/10 text-slate-200"}`,title:"Demo mode",children:["Demo ",t?"On":"Off"]})}const xd="2.1.42";function Uf(t){const r=String(t||"").trim().toLowerCase();return r==="openai"?.25:r==="openrouter"?.35:r==="groq"?.12:r==="together"?.2:r==="custom_openai"?.3:0}function zf(t,r,n){const s=Array.isArray(t)?t:[];if(!s.length)return`M 0 ${n/2} L ${r} ${n/2}`;const a=Math.max(...s.map(c=>Number(c.ms||0)),1),o=Math.min(...s.map(c=>Number(c.ms||0)),0),l=Math.max(1,a-o);return s.map((c,u)=>{const x=s.length===1?r:u/(s.length-1)*r,p=n-(Number(c.ms||0)-o)/l*n;return`${u===0?"M":"L"} ${x.toFixed(2)} ${p.toFixed(2)}`}).join(" ")}function Hf(t,r,n,{clockFormat:s="12h",showSeconds:a=!1}={}){const o=String(r).padStart(2,"0"),l=String(n).padStart(2,"0");if(s==="24h"){const p=`${String(t).padStart(2,"0")}:${o}`;return a?`${p}:${l}`:p}const c=t>=12?"PM":"AM",x=`${String(t%12||12).padStart(2,"0")}:${o}`;return a?`${x}:${l} ${c}`:`${x} ${c}`}function Wf(t,r,n,s){const a=String(r).padStart(2,"0"),o=String(n).padStart(2,"0"),l=String(t).slice(-2);return`${String(s||"").toUpperCase()} • ${a}/${o}/${l}`}const Sr={shellClass:"border-cyan-400/15 bg-slate-950/88 shadow-[0_10px_30px_rgba(0,0,0,0.34),0_0_18px_rgba(34,211,238,0.08)]",clockClass:"text-cyan-50 drop-shadow-[0_0_8px_rgba(103,232,249,0.24)]",calendarClass:"text-cyan-100/82",syncActiveClass:"text-cyan-100 border-cyan-400/35 bg-cyan-500/10",syncFallbackClass:"text-amber-200 border-amber-400/35 bg-amber-500/10",accentDot:"bg-cyan-400"};function Kf({rawH:t,rawM:r,rawS:n,rawDay:s,rawMonth:a,rawYear:o,dow:l,syncSource:c,syncOffsetMs:u,syncedAt:x,clockFormat:p="12h",showSeconds:d=!1,onOpenCalendar:m}){const f=Hf(t,r,n,{clockFormat:p,showSeconds:d}),b=Wf(o,a,s,l),h=Math.max(0,Math.floor((Date.now()-x)/1e3)),g=c==="network"?`NET ${u>=0?"+":""}${u}ms`:c==="cached"?`CACHE ${u>=0?"+":""}${u}ms`:"LOCAL",y=c==="network"||c==="cached"?Sr.syncActiveClass:Sr.syncFallbackClass,P=f.split(" "),A=P[0],C=P[1]||"",w=typeof m=="function",j=`relative overflow-hidden flex flex-col items-start leading-none px-2.5 py-1 rounded-xl shrink-0 min-w-0 max-w-48 border border-white/10 before:pointer-events-none ${Sr.shellClass}${w?" cursor-pointer hover:border-cyan-400/30 hover:bg-slate-900/95 transition-colors":""}`,E=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"w-full flex items-baseline justify-between gap-2",children:[e.jsxs("div",{"data-testid":"normal-clock-text",className:"flex items-baseline gap-1.5",children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full shrink-0 ${Sr.accentDot}`}),e.jsx("span",{className:`text-[15px] font-semibold font-mono tracking-[0.06em] tabular-nums leading-none ${Sr.clockClass}`,children:A}),C&&e.jsx("span",{className:`text-[10px] font-bold font-mono leading-none ${Sr.clockClass} opacity-75`,children:C})]}),e.jsx("span",{className:`text-[9px] font-mono tracking-wide px-1 py-0.5 rounded border ${y}`,title:`Sync source: ${c}`,children:g})]}),e.jsx("div",{className:"flex items-center gap-1.5 w-full mt-0.5",children:e.jsx("span",{"data-testid":"normal-calendar-text",className:`text-[11px] font-mono tracking-[0.04em] ${Sr.calendarClass}`,children:b})})]});return w?e.jsx("button",{type:"button","data-testid":"clock-calendar-btn",onClick:m,"aria-label":"Open calendar and deadlines",title:`${b} · click for calendar & deadlines`,className:j,children:E}):e.jsx("div",{"data-testid":"clock-calendar-btn",role:"group","aria-label":"Live clock and calendar",title:`${b} · ${c==="network"||c==="cached"?"internet-synced":"local"} clock (last sync ${h}s ago)`,className:j,children:E})}function Vf({collabConnected:t,collabRoomId:r,collabPeerCount:n}){const s=!!t,a=Number(n||0);return e.jsxs("div",{"data-testid":"collab-status-pill",title:s?`Collab room ${r||"default"} · ${a} peer(s)`:"Collab offline",className:`hidden lg:inline-flex items-center gap-1.5 px-2 py-1 rounded-lg border text-[10px] font-mono transition-all ${s?"border-violet-400/30 bg-violet-500/10 text-violet-200":"border-white/10 bg-white/[0.03] text-slate-500"}`,children:[e.jsx(Rx,{size:11,className:"shrink-0 opacity-80"}),e.jsx("span",{children:s?"Collab":"Collab off"}),s&&e.jsx("span",{className:"text-violet-300/90 tabular-nums",children:a})]})}function Gf({model:t,setModel:r,stats:n,xpState:s,workflowId:a,onOpenPalette:o,onOpenSettings:l,onOpenAnalytics:c,onOpenEcosystem:u,onOpenMissionControl:x,onOpenFleetControl:p,onOpenApplianceConsole:d,onOpenAirGapOperations:m,onOpenInstitutionalCommand:f,onOpenDemoFlow:b,onOpenFieldLaunch:h,onToggleScratchpad:g,watchdogStatus:y,watchdogAlertCount:P,onOpenRuntimeAlerts:A,runtimeTier:C,connectionInfo:w,tokensRemaining:j,collabConnected:E,collabRoomId:N,collabPeerCount:_,accelStatus:S,applianceModeEnabled:R,airGapLocked:$,demoModeEnabled:U,feedbackDisabled:I,feedbackUrl:D,onOpenIssueAssist:z,tierId:F,tierLabel:J,canGoBack:ee,canGoForward:ie,onGoBack:ye,onGoForward:pe,onOpenTaskManager:K,onOpenCalendar:H,onOpenSupport:W,onTierUnlock:Z,omegaReport:ce,onRunOmega:fe,suppressDuplicateRuntimeStatus:me=!1}){const ke=String(C||"PREVIEW").toUpperCase(),Pe=ke==="OPERATOR"||String(F||"").toLowerCase()==="pro",_e=String(w&&w.provider||"ollama"),ne=String(w&&w.health||"unknown"),we=String(w&&w.model||t||"llama3"),Be=ne==="online"||ne==="healthy",re=Array.from(new Set([String(t||"").trim(),"llama3","mistral","qwen","gpt-4.1-mini","gpt-4o-mini","llama-3.3-70b-versatile"].filter(Boolean))),{samples:ae,latencyMs:M,avgLatencyMs:V}=Nf({windowMs:5e3,pollMs:1e3});i.useMemo(()=>zf(ae,54,14),[ae]);const{temperature:G,setTemperature:te,theme:de,setTheme:L}=Xt(),{time:be,date:Q,dow:We,rawH:B,rawM:oe,rawS:xe,rawDay:Re,rawMonth:De,rawYear:tt,syncSource:Ge,syncOffsetMs:An,syncedAt:Dt}=Pf(),En=Uf(_e);i.useEffect(()=>{typeof document>"u"||(document.documentElement.dataset.theme=String(de||"system"))},[de]);const er=`${_e}/${we} | ${M}ms live (${V}ms avg) | $${En.toFixed(2)}/1K tokens`,Dr=String(D||"https://github.com/Z3r0DayZion-install/NeuralShell/issues/new?template=bug_report.md&title=Feedback%3A+"),Ct=!I&&!!(window.api&&window.api.system&&typeof window.api.system.openExternal=="function"),In=i.useCallback(()=>{if(Ct){if(typeof z=="function"){z();return}window.api.system.openExternal(Dr).catch(()=>{})}},[Ct,z,Dr]),[mt,$t]=i.useState(!1),_t=i.useRef(null);return i.useEffect(()=>{if(!mt)return;const Ae=tr=>{_t.current&&!_t.current.contains(tr.target)&&$t(!1)};return document.addEventListener("pointerdown",Ae),()=>document.removeEventListener("pointerdown",Ae)},[mt]),e.jsxs("header",{"data-testid":"top-status-bar",className:"min-h-12 h-14 border-b border-indigo-500/[0.08] bg-shell-soft/97 backdrop-blur-xl flex items-center justify-between px-2.5 z-[140] shrink-0 gap-2",style:{boxShadow:"0 1px 0 rgba(107,122,255,0.09), 0 10px 36px rgba(0,0,0,0.34)"},children:[e.jsxs("div",{className:"flex gap-3 items-center min-w-0",children:[e.jsx("button",{type:"button","data-testid":"nav-back-btn",disabled:!ee,onClick:ye,className:`p-1.5 rounded-lg border transition-all ${ee?"border-orange-400/20 bg-orange-500/10 text-orange-300 hover:text-orange-200 hover:bg-orange-500/20 hover:border-orange-400/40":"border-transparent text-slate-600 cursor-default"}`,title:"Back (Mouse4 / Alt+Left)","aria-label":"Go back",children:e.jsx(Cx,{size:14})}),e.jsx("button",{type:"button","data-testid":"nav-forward-btn",disabled:!ie,onClick:pe,className:`p-1.5 rounded-lg border transition-all ${ie?"border-orange-400/20 bg-orange-500/10 text-orange-300 hover:text-orange-200 hover:bg-orange-500/20 hover:border-orange-400/40":"border-transparent text-slate-600 cursor-default"}`,title:"Forward (Mouse5 / Alt+Right)","aria-label":"Go forward",children:e.jsx(_x,{size:14})}),e.jsxs("div",{"data-testid":"trust-indicator",className:"flex flex-col shrink-0",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.3em] font-black text-gradient",style:{backgroundImage:"linear-gradient(90deg, #8b5cf6, #d946ef, #06b6d4, #8b5cf6)",WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent"},children:"ProofForge"}),e.jsxs("div",{className:"text-sm font-bold text-slate-100 flex items-center gap-2 tracking-tight",children:[e.jsxs("span",{className:"text-[12px] font-mono text-slate-400 leading-none",title:`Version ${xd}`,children:["v",xd]}),Be&&e.jsx("span",{className:"h-2 w-2 rounded-full bg-emerald-400 shadow-[0_0_8px_rgba(74,222,128,0.45)]",title:"Bridge connected","aria-hidden":"true"}),e.jsx(kp,{report:ce,compact:!0,onClick:typeof fe=="function"?fe:void 0,testId:"header-omega-posture-badge"}),e.jsx(Tf,{tierId:F,tierLabel:J,runtimeTier:ke,isOperator:Pe,onUnlock:Z})]})]})]}),e.jsxs("div",{className:"hidden xl:flex items-center gap-2 px-3 py-1 bg-black/30 rounded-full border border-violet-500/10 text-[10px] font-mono text-slate-400 tracking-wide shrink-0",children:[e.jsx("span",{className:"text-slate-500",children:"workflow"}),e.jsx("span",{className:"text-violet-400/60",children:"="}),a?e.jsxs("span",{className:"text-green-300 font-semibold",children:['"',a,'"']}):e.jsx("span",{className:"text-slate-600 italic",children:"null"})]}),e.jsxs("div",{className:"flex gap-2 items-center shrink-0 ml-auto",children:[e.jsx(Kf,{rawH:B,rawM:oe,rawS:xe,rawDay:Re,rawMonth:De,rawYear:tt,dow:We,syncSource:Ge,syncOffsetMs:An,syncedAt:Dt,onOpenCalendar:H}),e.jsx(Vf,{collabConnected:E,collabRoomId:N,collabPeerCount:_}),e.jsx("select",{value:t,"aria-label":"Active model","data-testid":"header-model-select",onChange:Ae=>{Promise.resolve(r(Ae.target.value)).catch(()=>{})},className:"bg-violet-500/5 border border-violet-400/15 rounded-lg px-2.5 py-1 text-[11px] text-sky-300 outline-none focus:border-violet-400/40 transition-all font-mono hover:bg-violet-500/10 cursor-pointer appearance-none min-w-20 shadow-inner",children:re.map(Ae=>e.jsx("option",{value:Ae,children:Ae},Ae))}),!me&&e.jsxs("div",{"data-testid":"presence-pill",title:er,className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-lg border text-[10px] font-mono transition-all duration-300 ${ne==="online"||ne==="healthy"?"border-green-400/25 bg-green-500/8 text-green-200 shadow-[0_0_12px_rgba(74,222,128,0.1)]":ne==="offline"?"border-red-400/30 bg-red-500/10 text-red-300":"border-yellow-400/20 bg-yellow-500/8 text-yellow-200"}`,children:[e.jsx("span",{className:"text-green-300",children:we}),e.jsx("span",{className:"text-slate-600",children:"|"}),e.jsxs("span",{className:"text-yellow-300",children:[M,e.jsx("span",{className:"text-slate-500",children:"ms"})]})]}),!me&&e.jsx($f,{status:y,alertCount:P,onClick:A}),e.jsx("button",{"data-testid":"command-palette-btn","aria-label":"Open command palette (Ctrl+K)",onClick:o,className:"px-3 py-1.5 rounded-lg border border-fuchsia-400/30 bg-fuchsia-500/10 text-[11px] font-bold text-fuchsia-300 uppercase tracking-wider hover:bg-fuchsia-400/20 hover:border-fuchsia-400/50 transition-all animate-glow-pulse active:scale-95 alive-hover",children:"EXEC"}),typeof W=="function"&&e.jsx("button",{type:"button","data-testid":"support-open-btn",onClick:W,className:"px-2.5 py-1.5 rounded-lg border border-sky-400/25 bg-sky-500/10 text-[11px] font-bold text-sky-200 uppercase tracking-wider hover:bg-sky-400/15 transition-all",title:"Open operator support (Discord + Support Ops)",children:"Support"}),e.jsxs("div",{className:"relative",ref:_t,children:[e.jsxs("button",{type:"button","data-testid":"more-menu-btn",onClick:()=>$t(Ae=>!Ae),className:`inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg border text-[11px] font-mono transition-all ${mt?"border-violet-400/40 bg-violet-500/15 text-violet-100":"border-white/10 bg-white/[0.04] text-slate-300 hover:bg-white/10 hover:border-violet-400/20"}`,title:"More panels & tools",children:["More ",e.jsx(Ax,{size:12,className:`transition-transform ${mt?"rotate-180":""}`})]}),mt&&e.jsxs("div",{className:"absolute right-0 top-full mt-1 w-64 rounded-xl border border-violet-500/15 bg-shell-mid/98 backdrop-blur-lg shadow-[0_12px_40px_rgba(0,0,0,0.7)] py-1.5 z-50 max-h-[70vh] overflow-y-auto animate-fade-up",children:[e.jsx("div",{className:"px-3 py-1.5 text-[9px] font-mono uppercase tracking-widest text-slate-600",children:"// infrastructure"}),[{label:"Analytics",testId:"analytics-open-btn",onClick:c,color:"text-yellow-300"},{label:"Ecosystem",testId:"ecosystem-open-btn",onClick:u,color:"text-sky-300"},{label:"Mission Control",testId:"mission-control-open-btn",onClick:x,color:"text-violet-300"},{label:"Fleet Control",testId:"fleet-control-open-btn",onClick:p,color:"text-blue-300"},{label:"Institutional",testId:"institutional-command-open-btn",onClick:f,color:"text-indigo-300"}].filter(Ae=>typeof Ae.onClick=="function").map(Ae=>e.jsxs("button",{type:"button","data-testid":Ae.testId,onClick:()=>{Ae.onClick(),$t(!1)},className:`w-full text-left px-4 py-2 text-[12px] font-mono hover:bg-white/8 transition-colors flex items-center gap-2 ${Ae.color}`,children:[e.jsx("span",{className:"text-slate-600 text-[10px]",children:"→"})," ",Ae.label]},Ae.testId)),(b||h)&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-white/5 my-1"}),e.jsx("div",{className:"px-3 py-1.5 text-[9px] font-mono uppercase tracking-widest text-slate-600",children:"// launch"}),[...b?[{label:"Demo Flow",testId:"demo-flow-open-btn",onClick:b,color:"text-green-300"}]:[],...h?[{label:"Field Launch",testId:"field-launch-open-btn",onClick:h,color:"text-orange-300"}]:[]].map(Ae=>e.jsxs("button",{type:"button","data-testid":Ae.testId,onClick:()=>{Ae.onClick(),$t(!1)},className:`w-full text-left px-4 py-2 text-[12px] font-mono hover:bg-white/8 transition-colors flex items-center gap-2 ${Ae.color}`,children:[e.jsx("span",{className:"text-slate-600 text-[10px]",children:"→"})," ",Ae.label]},Ae.testId))]}),e.jsx("div",{className:"border-t border-white/5 my-1"}),e.jsx("div",{className:"px-3 py-1.5 text-[9px] font-mono uppercase tracking-widest text-slate-600",children:"// tools"}),[{label:"Operator Inbox",testId:"task-manager-open-btn",onClick:K,color:"text-rose-300"},{label:"Workpad",testId:"scratchpad-open-btn",onClick:g,color:"text-amber-300"},{label:"Feedback",testId:"feedback-btn",onClick:Ct?In:void 0,color:"text-teal-300"}].filter(Ae=>typeof Ae.onClick=="function").map(Ae=>e.jsxs("button",{type:"button","data-testid":Ae.testId,onClick:()=>{Ae.onClick(),$t(!1)},className:`w-full text-left px-4 py-2 text-[12px] font-mono hover:bg-white/8 transition-colors flex items-center gap-2 ${Ae.color}`,children:[e.jsx("span",{className:"text-slate-600 text-[10px]",children:"→"})," ",Ae.label]},Ae.testId))]})]}),e.jsx("button",{type:"button","data-testid":"theme-toggle-btn",onClick:()=>{L(de==="system"?"dark":de==="dark"?"light":"system")},className:"p-1.5 rounded-lg border border-yellow-400/15 bg-yellow-500/5 text-yellow-300/80 hover:text-yellow-200 hover:bg-yellow-500/15 hover:border-yellow-400/30 transition-all",title:`Theme: ${de}`,children:de==="dark"?e.jsx(Ex,{size:14}):de==="light"?e.jsx(Ix,{size:14}):e.jsx(Px,{size:14})}),e.jsx("button",{"data-testid":"settings-open-btn","aria-label":"Open settings",onClick:l,className:"p-1.5 rounded-lg border border-slate-400/15 bg-slate-500/5 text-slate-400 hover:text-slate-100 hover:bg-slate-500/15 hover:border-slate-400/30 transition-all group alive-hover",title:"Settings (Ctrl+,)",children:e.jsx(ul,{size:14,className:"group-hover:rotate-90 transition-transform duration-500"})}),e.jsx(Lf,{enabled:R,onOpen:d}),e.jsx(Bf,{locked:$,onOpen:m}),e.jsx(Ff,{enabled:U,onOpen:b})]})]})}function Jf(t){const r=String(t||"").toLowerCase();return r.includes("127.0.0.1")||r.includes("localhost")||r.includes("::1")||r.includes("0.0.0.0")}function Np({connectionInfo:t={}}={}){const r=String(t.baseUrl||""),n=String(t.health||"unknown").toLowerCase(),s=String(t.provider||"ollama"),a=t.model?String(t.model):null,o=!!t.allowRemoteBridge,l=Jf(r)||s==="ollama"&&!r,c=l?"local":r?"hosted":"unknown",u=n==="healthy"||n==="online",p=l?u?"connected":n==="degraded"?"degraded":n==="unknown"?"not-tested":"unreachable":null,d=o?c==="hosted"?u?"connected":"not-tested":null:"blocked-by-policy";let m=null;const f=[];return c==="local"?p==="unreachable"?(m=`Local provider not responding at ${r||"http://127.0.0.1:11434"}. Check that ${s==="ollama"?"Ollama is running":`${s} is running`} and model ${a||"llama3"} is available.`,f.push({id:"test-connection",label:"Test local connection"})):p==="degraded"?(m=`Local provider is degraded at ${r||"http://127.0.0.1:11434"}.`,f.push({id:"test-connection",label:"Test connection"})):p==="not-tested"&&f.push({id:"test-connection",label:"Test local connection"}):c==="hosted"&&(d==="blocked-by-policy"?(m=`${s} is blocked by Offline Mode. Hosted providers are disabled.`,f.push({id:"enable-hosted",label:"Enable hosted providers"}),f.push({id:"switch-local",label:"Switch to local Ollama"})):d==="not-tested"&&(m=`${s} connection has not been verified yet.`,f.push({id:"test-connection",label:"Test connection"}))),{selectedRoute:c,localStatus:p,hostedStatus:d,currentProblem:m,nextActions:f}}function Hl({connectionInfo:t={},watchdogStatus:r="running",incidentCount:n=0,setupBlocked:s=!1}={}){const a=String(t.health||"unknown").toLowerCase(),o=a==="healthy"||a==="online",l=a==="degraded",c=String(t.provider||"ollama"),u=t.model?String(t.model):null,x=Math.max(0,Number(n)||0),p=String(r||"unknown"),d=["fatal","degraded"].includes(p.toLowerCase()),m=o?"connected":l?"degraded":"offline",{selectedRoute:f,localStatus:b,hostedStatus:h}=Np({connectionInfo:t}),g={selectedRoute:f,localStatus:b,hostedStatus:h};return s?{severity:"blocked",summary:"Setup blocked",primaryAction:{id:"fix-setup",label:"Fix Setup"},bridge:m,provider:c,model:u,runtimeLabel:p,incidentCount:x,...g}:!o&&!l&&!(f==="local"&&b==="connected")?{severity:"offline",summary:h==="blocked-by-policy"?"Hosted blocked · Local not tested":"Bridge offline",primaryAction:{id:"run-checks",label:"Run Checks"},bridge:m,provider:c,model:u,runtimeLabel:p,incidentCount:x,...g}:x>0||d||l?{severity:"degraded",summary:x>0?`${x} incident${x===1?"":"s"}`:l?"Bridge degraded":"Attention required",primaryAction:{id:"inspect",label:"Inspect Issue"},bridge:m,provider:c,model:u,runtimeLabel:p,incidentCount:x,...g}:{severity:"healthy",summary:"System ready",primaryAction:{id:"export",label:"Export Evidence"},bridge:m,provider:c,model:u,runtimeLabel:p,incidentCount:x,...g}}function Wl(t,{sessionDegradedDismissed:r=!1,acknowledgedReady:n=!1}={}){const s=String(t&&t.severity?t.severity:"offline").toLowerCase();return s==="blocked"?{verdict:"blocked",title:"Blocked",message:"ProofForge needs setup before operator use.",primaryAction:{id:"fix-setup",label:"Fix Setup"},secondaryAction:{id:"open-settings",label:"Open Settings"},shouldPrompt:!0,trustSeverity:s}:s==="offline"?{verdict:"blocked",title:"Blocked",message:"ProofForge needs setup before operator use.",primaryAction:{id:"fix-setup",label:"Fix Setup"},secondaryAction:{id:"open-settings",label:"Open Settings"},shouldPrompt:!0,trustSeverity:s}:s==="degraded"?{verdict:"degraded",title:"Degraded",message:"ProofForge can run, but one or more operator systems need attention.",primaryAction:{id:"inspect",label:"Inspect Issue"},secondaryAction:{id:"continue",label:"Continue Anyway"},shouldPrompt:!r,trustSeverity:s}:{verdict:"ready",title:"Ready",message:"ProofForge is ready for operator use.",primaryAction:{id:"start",label:"Start Operating"},secondaryAction:{id:"export",label:"Export Evidence"},shouldPrompt:!n,trustSeverity:s}}const fd={healthy:{border:"border-emerald-400/20",bg:"bg-emerald-500/[0.04]",dot:"bg-emerald-400",text:"text-emerald-200",action:"border-emerald-400/30 bg-emerald-500/10 text-emerald-100 hover:bg-emerald-500/20"},degraded:{border:"border-amber-400/25",bg:"bg-amber-500/[0.05]",dot:"bg-amber-400",text:"text-amber-100",action:"border-amber-400/30 bg-amber-500/10 text-amber-100 hover:bg-amber-500/20"},offline:{border:"border-slate-500/30",bg:"bg-slate-900/40",dot:"bg-slate-500",text:"text-slate-300",action:"border-sky-400/30 bg-sky-500/10 text-sky-100 hover:bg-sky-500/20"},blocked:{border:"border-rose-400/30",bg:"bg-rose-500/[0.06]",dot:"bg-rose-400",text:"text-rose-100",action:"border-rose-400/30 bg-rose-500/10 text-rose-100 hover:bg-rose-500/20"}};function qf(t){return t==="connected"?"Connected":t==="degraded"?"Degraded":"Offline"}function Yf(t){const r=String(t||"unknown").toLowerCase();return r==="running"?"Running":r==="fatal"?"Fatal":r==="degraded"?"Degraded":r.charAt(0).toUpperCase()+r.slice(1)}function Zf({connectionInfo:t,watchdogStatus:r,incidentCount:n=0,setupBlocked:s=!1,sessionDegradedDismissed:a=!1,acknowledgedReady:o=!1,exportAvailable:l=!1,exportBusy:c=!1,onExportEvidence:u,onInspectIssue:x,onFixSetup:p,onRunChecks:d,onToggleInspector:m,inspectorOpen:f=!1,layoutMode:b="expanded"}){const h=i.useMemo(()=>Hl({connectionInfo:t,watchdogStatus:r,incidentCount:n,setupBlocked:s}),[t,r,n,s]),g=i.useMemo(()=>Wl(h,{sessionDegradedDismissed:a,acknowledgedReady:o}),[h,a,o]),y=fd[h.severity]||fd.offline,P=()=>{const{id:w}=h.primaryAction;if(w==="export"&&typeof u=="function"){u();return}if(w==="inspect"&&typeof x=="function"){x();return}if(w==="fix-setup"&&typeof p=="function"){p();return}w==="run-checks"&&typeof d=="function"&&d()},A=h.primaryAction.id==="export"&&!l,C=A?"Export Evidence — unavailable in this shell":h.primaryAction.label;return e.jsxs("div",{"data-testid":"trust-strip","data-severity":h.severity,role:"status","aria-live":"polite",className:`px-3 py-1.5 border-b flex items-center justify-between gap-3 shrink-0 ${y.border} ${y.bg}`,children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-wrap",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 shrink-0",children:[e.jsx("span",{"data-testid":"readiness-verdict-badge","data-verdict":g.verdict,className:"px-1.5 py-0.5 rounded border border-white/10 text-[9px] font-bold uppercase tracking-[0.14em] text-slate-300",children:g.verdict}),e.jsx("span",{className:`h-2 w-2 rounded-full shrink-0 ${y.dot}`,"aria-hidden":"true"}),e.jsx("span",{className:`text-[11px] font-semibold tracking-wide ${y.text}`,children:h.summary})]}),e.jsx("span",{className:"hidden sm:inline text-[10px] font-mono text-slate-500",children:"·"}),e.jsx("span",{"data-testid":"trust-strip-bridge",className:"text-[10px] font-mono text-slate-400",children:h.selectedRoute==="local"?e.jsxs(e.Fragment,{children:["Local ",e.jsx("span",{className:h.localStatus==="connected"?"text-emerald-200":h.localStatus==="degraded"?"text-amber-200":h.localStatus==="unreachable"?"text-rose-300":"text-slate-400",children:h.localStatus==="connected"?"Connected":h.localStatus==="degraded"?"Degraded":h.localStatus==="unreachable"?"Not responding":"Selected"})]}):h.selectedRoute==="hosted"&&h.hostedStatus==="blocked-by-policy"?e.jsxs(e.Fragment,{children:["Hosted ",e.jsx("span",{className:"text-amber-200",children:"Blocked"})]}):e.jsxs(e.Fragment,{children:["Bridge ",e.jsx("span",{className:"text-slate-200",children:qf(h.bridge)})]})}),e.jsx("span",{className:"hidden md:inline text-[10px] font-mono text-slate-500",children:"·"}),e.jsxs("span",{"data-testid":"trust-strip-model",className:"hidden md:inline text-[10px] font-mono text-slate-400 truncate max-w-[12rem]",children:[h.provider,"/",h.model||"—"]}),e.jsx("span",{className:"hidden lg:inline text-[10px] font-mono text-slate-500",children:"·"}),e.jsxs("span",{"data-testid":"trust-strip-runtime",className:"hidden lg:inline text-[10px] font-mono text-slate-400",children:["Runtime ",e.jsx("span",{className:"text-slate-200",children:Yf(h.runtimeLabel)})]}),h.incidentCount>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] font-mono text-slate-500",children:"·"}),e.jsxs("span",{"data-testid":"trust-strip-incidents",className:"text-[10px] font-mono text-amber-200",children:[h.incidentCount," incident",h.incidentCount===1?"":"s"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[typeof m=="function"&&b!=="expanded"&&e.jsx("button",{type:"button","data-testid":"trust-strip-inspector-toggle",onClick:m,className:`px-2 py-1 rounded-lg border text-[10px] font-mono transition-colors ${f?"border-cyan-400/35 bg-cyan-500/10 text-cyan-100":"border-white/10 bg-white/[0.03] text-slate-400 hover:text-slate-200"}`,title:"Toggle inspector panel",children:"Inspector"}),e.jsx("button",{type:"button","data-testid":h.primaryAction.id==="run-checks"?"profile-bar-verify-btn":"trust-strip-primary-action","data-action-id":h.primaryAction.id,disabled:A||c,onClick:P,className:`px-2.5 py-1 rounded-lg border text-[10px] font-bold uppercase tracking-wider transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${y.action}`,children:c?"Exporting…":C})]})]})}const Xf="modulepreload",Qf=function(t,r){return new URL(t,r).href},bd={},Kl=function(r,n,s){let a=Promise.resolve();if(n&&n.length>0){const l=document.getElementsByTagName("link"),c=document.querySelector("meta[property=csp-nonce]"),u=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=Promise.allSettled(n.map(x=>{if(x=Qf(x,s),x in bd)return;bd[x]=!0;const p=x.endsWith(".css"),d=p?'[rel="stylesheet"]':"";if(!!s)for(let b=l.length-1;b>=0;b--){const h=l[b];if(h.href===x&&(!p||h.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${x}"]${d}`))return;const f=document.createElement("link");if(f.rel=p?"stylesheet":Xf,p||(f.as="script"),f.crossOrigin="",f.href=x,u&&f.setAttribute("nonce",u),document.head.appendChild(f),p)return new Promise((b,h)=>{f.addEventListener("load",b),f.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${x}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return a.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return r().catch(o)})},eb=i.lazy(()=>Kl(()=>import("./OnboardingProgressRail-D4ADuSst.js"),__vite__mapDeps([0,1,2,3]),import.meta.url)),tb=[{id:"hud",label:"HUD",title:"Minimum rail width — maximum chat canvas (heads-up)"},{id:"compact",label:"Dense",title:"Tighter side columns than standard"},{id:"balanced",label:"Standard",title:"Default ProofForge rail widths"},{id:"wide",label:"Spacious",title:"Wider rails for dense panels and previews"}],rb=i.memo(function({activeRailPresetId:r,onApplyRailPreset:n,onResetRailWidths:s,showInlineThreadRail:a,threadRailCollapsed:o,onToggleThreadRailCollapse:l,showInlineWorkbenchRail:c,workbenchRailCollapsed:u,onToggleWorkbenchRailCollapse:x,canOpenThreadRailOverlay:p,leftRailOverlayOpen:d,onToggleLeftRailOverlay:m,canOpenWorkbenchRailOverlay:f,rightRailOverlayOpen:b,onToggleRightRailOverlay:h,firstBootSteps:g,firstBootProgress:y,onReopenFirstBoot:P,onResetFirstBoot:A,onOpenCustomize:C}){return e.jsxs("div",{"data-testid":"layout-control-bar",className:"px-3 py-1 border-b border-white/[0.03] bg-white/[0.01] flex items-center justify-between gap-2 z-10",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 flex-wrap",children:[e.jsx("div",{className:"inline-flex items-center rounded border border-white/[0.06] overflow-hidden shrink-0",role:"toolbar","aria-label":"Side column width presets",children:tb.map((w,j)=>e.jsx("button",{type:"button","data-testid":`layout-preset-${w.id}-btn`,title:w.title,"aria-pressed":r===w.id,onClick:()=>n(w.id),className:`px-2 py-1 text-[11px] font-semibold tracking-wide transition-colors ${r===w.id?"bg-violet-500/20 text-violet-200":"text-slate-500 hover:bg-white/[0.04] hover:text-slate-300"} ${j>0?"border-l border-white/[0.06]":""}`,children:w.label},w.id))}),e.jsx("button",{type:"button","data-testid":"layout-reset-panels-btn",onClick:s,className:"text-[11px] font-mono text-slate-400 hover:text-slate-400 px-1.5 py-1 rounded hover:bg-white/[0.04] transition-colors",children:"Reset"}),typeof C=="function"&&e.jsx("button",{type:"button","data-testid":"layout-customize-btn",onClick:C,className:"text-[11px] font-mono text-violet-300/90 hover:text-violet-200 px-1.5 py-1 rounded hover:bg-violet-500/10 transition-colors",title:"Open Adaptive Layout Engine — presets and panel toggles",children:"Customize"}),e.jsx("span",{className:"w-px h-3 bg-white/[0.06]"}),a&&e.jsx("button",{type:"button","data-testid":"layout-toggle-thread-inline-btn",onClick:l,className:`text-[11px] font-mono px-1.5 py-1 rounded transition-colors ${o?"text-cyan-400/70 hover:text-cyan-300":"text-slate-500 hover:text-slate-300 hover:bg-white/[0.04]"}`,children:"Flows"}),c&&e.jsx("button",{type:"button","data-testid":"layout-toggle-workbench-inline-btn",onClick:x,className:`text-[11px] font-mono px-1.5 py-1 rounded transition-colors ${u?"text-cyan-400/70 hover:text-cyan-300":"text-slate-500 hover:text-slate-300 hover:bg-white/[0.04]"}`,children:"Bench"}),p&&e.jsx("button",{type:"button","data-testid":"layout-toggle-workflows-btn",onClick:m,className:`text-[11px] font-mono px-1.5 py-1 rounded transition-colors ${d?"text-cyan-300 bg-cyan-500/10":"text-slate-500 hover:text-slate-300 hover:bg-white/[0.04]"}`,children:"Flows"}),f&&e.jsx("button",{type:"button","data-testid":"layout-toggle-workbench-btn",onClick:h,className:`text-[11px] font-mono px-1.5 py-1 rounded transition-colors ${b?"text-cyan-300 bg-cyan-500/10":"text-slate-500 hover:text-slate-300 hover:bg-white/[0.04]"}`,children:"Bench"})]}),e.jsx(i.Suspense,{fallback:null,children:e.jsx(eb,{steps:g,progress:y,onReopen:P,onReset:A})})]})}),nb=80,sb=200,ab=12,hd=120,gd=180;function ob(t){const r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return r?{r:parseInt(r[1],16),g:parseInt(r[2],16),b:parseInt(r[3],16)}:{r:139,g:92,b:246}}function yd(t,r,n,s=!1){const a=Math.random()*Math.PI*2,o=s?1.5+Math.random()*3:.15+Math.random()*.45;return{x:s?t/2:Math.random()*t,y:s?r/2:Math.random()*r,vx:Math.cos(a)*o,vy:Math.sin(a)*o,radius:s?1+Math.random()*2.5:.8+Math.random()*2,opacity:s?.6+Math.random()*.4:.08+Math.random()*.2,color:n,life:s?40+Math.random()*60:1/0,maxLife:s?40+Math.random()*60:1/0,pulse:Math.random()*Math.PI*2,pulseSpeed:.02+Math.random()*.03}}const ib=i.memo(function({moodColors:r,isThinking:n,isTyping:s,enabled:a=!0}){const o=O.useRef(null),l=O.useRef([]),c=O.useRef(null),u=O.useRef({x:-1e3,y:-1e3}),x=O.useRef(0),[p,d]=O.useState(a),m=(r==null?void 0:r.dot)||(r==null?void 0:r.primary)||"#8b5cf6",f=ob(m),b=O.useCallback((g,y)=>{const P=[];for(let A=0;A{const C=l.current;if(!(C.length>sb))for(let w=0;w{d(a)},[a]),O.useEffect(()=>{if(!p)return;const g=o.current;if(!g)return;const y=g.getContext("2d");if(!y)return;const P=()=>{const w=window.devicePixelRatio||1,j=g.parentElement.getBoundingClientRect();g.width=j.width*w,g.height=j.height*w,g.style.width=j.width+"px",g.style.height=j.height+"px",y.setTransform(w,0,0,w,0,0),l.current.length===0&&b(j.width,j.height)};P(),window.addEventListener("resize",P);const A=w=>{const j=g.getBoundingClientRect();u.current={x:w.clientX-j.left,y:w.clientY-j.top}};g.addEventListener("mousemove",A);const C=()=>{x.current++;const w=g.width/(window.devicePixelRatio||1),j=g.height/(window.devicePixelRatio||1),E=u.current.x,N=u.current.y,_=l.current,$=(n?2.5:1)*(s?1.8:1);if(y.clearRect(0,0,w,j),n){const U=w/2,I=j/2,D=Math.min(w,j)*.3,z=y.createRadialGradient(U,I,0,U,I,D);z.addColorStop(0,`rgba(${f.r},${f.g},${f.b},0.04)`),z.addColorStop(1,"transparent"),y.fillStyle=z,y.beginPath(),y.arc(U,I,D,0,Math.PI*2),y.fill()}for(let U=_.length-1;U>=0;U--){const I=_[U];if(I.life!==1/0){if(I.life--,I.life<=0){_.splice(U,1);continue}I.opacity=I.life/I.maxLife*.7}I.pulse+=I.pulseSpeed;const D=1+Math.sin(I.pulse)*.2,z=I.x-E,F=I.y-N,J=Math.sqrt(z*z+F*F);if(J0){const ie=(1-J/gd)*.5;I.vx+=z/J*ie,I.vy+=F/J*ie}if(n){const ie=w/2,ye=j/2,pe=ie-I.x,K=ye-I.y,H=Math.sqrt(pe*pe+K*K);H>30&&(I.vx+=-K/H*.03+pe/H*.02,I.vy+=pe/H*.03+K/H*.02)}I.vx*=.98,I.vy*=.98,I.x+=I.vx*$,I.y+=I.vy*$,I.x<-10&&(I.x=w+10),I.x>w+10&&(I.x=-10),I.y<-10&&(I.y=j+10),I.y>j+10&&(I.y=-10);const ee=I.radius*D;y.beginPath(),y.arc(I.x,I.y,ee,0,Math.PI*2),y.fillStyle=`rgba(${I.color.r},${I.color.g},${I.color.b},${I.opacity})`,y.fill(),ee>1.5&&(y.beginPath(),y.arc(I.x,I.y,ee*2.5,0,Math.PI*2),y.fillStyle=`rgba(${I.color.r},${I.color.g},${I.color.b},${I.opacity*.15})`,y.fill())}for(let U=0;U<_.length;U++)for(let I=U+1;I<_.length;I++){const D=_[U],z=_[I],F=D.x-z.x,J=D.y-z.y,ee=Math.sqrt(F*F+J*J);if(ee{window.cancelAnimationFrame(c.current),window.removeEventListener("resize",P),g.removeEventListener("mousemove",A)}},[p,f.r,f.g,f.b,n,s,b,h]),p?e.jsx("canvas",{ref:o,className:"absolute inset-0 pointer-events-auto z-0",style:{opacity:.7,mixBlendMode:"screen"}}):null}),lb=i.memo(function({moodColors:r,isThinking:n,isTyping:s,particlesEnabled:a}){return e.jsxs(e.Fragment,{children:[e.jsx(ib,{moodColors:r,isThinking:n,isTyping:s,enabled:a}),e.jsx("div",{className:"absolute top-0 left-1/2 -translate-x-1/2 pointer-events-none animate-mood-aurora",style:{width:800,height:340,background:`radial-gradient(ellipse 100% 100% at 50% 0%, ${r.dot}26 0%, ${r.dot}0a 50%, transparent 78%)`,filter:"blur(48px)",transition:"background 1.8s cubic-bezier(0.4,0,0.2,1)"}}),e.jsx("div",{className:"absolute top-0 left-1/2 -translate-x-1/2 pointer-events-none animate-mood-aurora-2",style:{width:440,height:200,background:`radial-gradient(ellipse 100% 100% at 50% 0%, ${r.glow||r.dot}18 0%, transparent 70%)`,filter:"blur(32px)",transition:"background 2.2s cubic-bezier(0.4,0,0.2,1)"}}),e.jsx("div",{className:"absolute inset-0 pointer-events-none animate-mood-edge rounded-none z-[1]",style:{boxShadow:`inset 0 0 0 1px ${r.dot}1a, inset 0 0 80px ${r.dot}07`,transition:"box-shadow 1.8s cubic-bezier(0.4,0,0.2,1)"}})]})}),cb="NeuralShell_QuickStart";function Sp({sessions:t,workflowId:r,onSelectSession:n,onCreateSession:s,onSaveSession:a,onRetrySave:o,onLockSession:l,saveStatus:c,isSessionUnlocked:u,sessionHydrationStatus:x,autoLockOnBlur:p,onToggleAutoLock:d,auditOnly:m,onUpgradeToPro:f,widthPx:b=288}){const h=(...j)=>j.filter(Boolean).join(" "),[g,y]=O.useState(""),P=Number.isFinite(Number(b))?Math.max(220,Math.round(Number(b))):288,A=O.useMemo(()=>{if(!c||!c.at)return"";const j=new Date(c.at);return Number.isNaN(j.getTime())?"":j.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})},[c]),C=O.useMemo(()=>(t||[]).filter(j=>String(j||"").toLowerCase().includes(g.toLowerCase())),[t,g]),w=O.useMemo(()=>!c||c.state==="idle"?x==="loading"?"Loading selected session...":x==="locked"?"Session locked. Unlock to continue.":"Ready":c.state==="saving"?String(c.detail||"Saving..."):c.state==="locked"?String(c.detail||"Session locked."):A?`${String(c.detail||"").trim()} (${A})`:String(c.detail||"").trim()||(c.state==="error"?"Save failed.":"Saved."),[c,x,A]);return e.jsxs("aside",{"data-testid":"thread-rail",className:"shrink-0 border-r border-white/5 flex flex-col bg-slate-950/50 backdrop-blur-xl z-20 overflow-hidden",style:{width:`${P}px`},children:[e.jsxs("header",{className:"p-6 pb-4 border-b border-white/5",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] font-black uppercase tracking-[0.4em] text-cyan-500/60 mb-1",children:"Workflow_Nav"}),e.jsx("h2",{className:"text-sm font-bold tracking-tight text-slate-100 uppercase tracking-[0.1em]",children:"Active_Workflows"})]}),e.jsx("button",{"data-testid":"new-thread-btn",onClick:s,disabled:!!m,title:"New Thread",className:h("h-8 w-8 flex items-center justify-center rounded-lg border transition-all",m?"border-white/10 text-slate-600 cursor-not-allowed":"border-white/10 hover:border-cyan-400/40 hover:bg-cyan-400/10 text-slate-400 hover:text-cyan-300"),children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{type:"text",value:g,onChange:j=>y(j.target.value),placeholder:"Search Workflows...",className:"w-full bg-black/40 border border-white/5 rounded-lg px-3 py-2 text-[11px] font-mono text-slate-300 placeholder-slate-600 outline-none focus:border-cyan-400/30 transition-all"})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-1.5 custom-scrollbar",children:[t.length>0&&e.jsx("div",{className:"text-[8px] font-black uppercase tracking-widest text-slate-500 mb-3 px-1",children:"Current & Recent"}),t.length===0?e.jsxs("div",{className:"text-center p-6 mt-10",children:[e.jsx("div",{className:"text-3xl text-slate-700/30 mb-3 font-mono",children:"/"}),e.jsx("div",{className:"text-[10px] text-slate-500 uppercase tracking-[0.2em] font-bold mb-1",children:"History Empty"}),e.jsx("div",{className:"text-[9px] text-slate-600 font-mono",children:"No active workflow history"})]}):C.map((j,E)=>{const N=j!==cb&&!u(j);return e.jsxs("button",{"data-testid":`session-item-${j}`,onClick:()=>n(j),className:h("w-full text-left p-3.5 rounded-xl transition-all duration-200 group relative",r===j?"bg-cyan-500/[0.07] border border-cyan-400/30 shadow-[0_0_20px_rgba(34,211,238,0.03)]":"hover:bg-white/[0.04] border border-transparent"),children:[r===j&&e.jsx("div",{className:"absolute left-0 top-[20%] bottom-[20%] w-1 bg-cyan-400/80 rounded-r-full shadow-glow-cyan"}),e.jsxs("div",{className:"flex items-center justify-between mb-1.5 pl-1.5",children:[e.jsx("span",{className:h("text-[11px] font-bold truncate tracking-tight transition-colors",r===j?"text-cyan-100":"text-slate-300 group-hover:text-slate-200"),children:j}),N?e.jsx("span",{"data-testid":`session-lock-${j}`,className:"text-[8px] font-mono text-amber-300 uppercase tracking-widest px-1.5 py-0.5 bg-amber-400/10 rounded border border-amber-400/20",children:"LOCKED"}):E===0&&r!==j&&e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-slate-500"})]}),e.jsxs("div",{className:"flex items-center justify-between pl-1.5",children:[e.jsx("div",{className:h("text-[9px] truncate font-mono tracking-tighter transition-colors",r===j?"text-cyan-400/60":"text-slate-500/60"),children:N?"Unlock required":"/var/log/active"}),r===j&&e.jsx("span",{className:"text-[8px] font-mono text-cyan-400 font-bold uppercase tracking-widest px-1.5 py-0.5 bg-cyan-400/10 rounded",children:"LIVE"})]})]},j)})]}),e.jsxs("footer",{className:"p-4 border-t border-white/5 bg-black/20 flex flex-col gap-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx("button",{"data-testid":"save-active-session-btn",onClick:a,disabled:!!m,className:h("w-full py-2 rounded-lg border text-[9px] font-bold uppercase tracking-[0.1em] transition-all",m?"border-white/[0.08] text-slate-600 cursor-not-allowed":"border-white/[0.08] hover:bg-white/[0.05] text-slate-300"),children:"Save Active"}),e.jsx("button",{"data-testid":"lock-active-session-btn",onClick:l,disabled:!!m,className:h("w-full py-2 rounded-lg border text-[9px] font-bold uppercase tracking-[0.1em] transition-all",m?"border-amber-400/20 text-amber-400/40 cursor-not-allowed":"border-amber-400/30 hover:bg-amber-400/10 text-amber-200"),children:"Lock Active"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx("button",{"data-testid":"retry-save-session-btn",onClick:o,disabled:!!m||c&&c.state!=="error",className:h("w-full py-2 rounded-lg border text-[9px] font-bold uppercase tracking-[0.1em] transition-all",!m&&c&&c.state==="error"?"border-rose-300/30 text-rose-200 hover:bg-rose-300/10":"border-white/[0.08] text-slate-500/80 cursor-not-allowed"),children:"Retry Save"}),e.jsxs("label",{htmlFor:"session-autolock-toggle",className:"w-full py-2 px-2 rounded-lg border border-white/[0.08] text-[9px] font-bold text-slate-300 uppercase tracking-[0.08em] flex items-center justify-between gap-2",children:[e.jsx("span",{children:"Auto-Lock"}),e.jsx("input",{id:"session-autolock-toggle","data-testid":"session-autolock-toggle",type:"checkbox",checked:!!p,onChange:j=>{typeof d=="function"&&d(!!j.target.checked)},disabled:!!m,className:"h-3.5 w-3.5 accent-cyan-400"})]})]}),m&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[9px] font-mono text-amber-300/80",children:"Write actions disabled - upgrade to Pro."}),e.jsx("button",{type:"button","data-testid":"threadrail-upgrade-pro-btn",onClick:()=>{typeof f=="function"&&f()},className:"w-full py-2 rounded-lg border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-bold uppercase tracking-[0.12em] text-cyan-100 hover:bg-cyan-500/20 transition-all",children:"Upgrade to Pro"})]}),e.jsx("div",{"data-testid":"session-rail-status",className:h("text-[9px] font-mono",c&&c.state==="error"?"text-rose-300":c&&c.state==="saving"||c&&c.state==="locked"?"text-amber-300":"text-slate-500"),children:w})]})]})}const db=["a[href]:not([disabled])","button:not([disabled])","textarea:not([disabled])",'input:not([type="hidden"]):not([disabled])',"select:not([disabled])",'[tabindex]:not([tabindex="-1"]):not([disabled])'].join(",");function ub(t){if(!t||typeof t.getClientRects!="function")return!1;const r=t.getClientRects();if(!r||!r.length||t.getAttribute("aria-hidden")==="true")return!1;const n=typeof window<"u"?window.getComputedStyle(t):null;return!(n&&(n.visibility==="hidden"||n.display==="none"))}function wd(t){return!t||typeof t.querySelectorAll!="function"?[]:Array.from(t.querySelectorAll(db)).filter(ub)}function pb(t,r,n={}){const{restoreFocus:s=!0,initialSelector:a=null}=n,o=O.useRef(null);O.useEffect(()=>{if(!t)return;const l=r==null?void 0:r.current;if(!l)return;s&&document.activeElement&&typeof document.activeElement.focus=="function"&&(o.current=document.activeElement);const c=()=>{if(a){const d=l.querySelector(a);if(d&&typeof d.focus=="function"){d.focus();return}}const p=wd(l);p.length&&typeof p[0].focus=="function"&&p[0].focus()};c();const u=typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(c):0,x=p=>{if(p.key!=="Tab")return;const d=wd(l);if(!d.length)return;const m=d[0],f=d[d.length-1],b=document.activeElement;p.shiftKey?(b===m||!l.contains(b))&&(p.preventDefault(),f.focus()):(b===f||!l.contains(b))&&(p.preventDefault(),m.focus())};return document.addEventListener("keydown",x,!0),()=>{typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(u),document.removeEventListener("keydown",x,!0);const p=o.current;if(s&&p&&typeof p.focus=="function")try{p.focus()}catch{}o.current=null}},[t,r,s,a])}function Wa(t,r,n,s={}){const{initialSelector:a="[data-accessible-overlay-close]"}=s;pb(t,r,{initialSelector:a}),O.useEffect(()=>{if(!t)return;const o=l=>{l.key==="Escape"&&typeof n=="function"&&n()};return window.addEventListener("keydown",o,!0),()=>window.removeEventListener("keydown",o,!0)},[t,n])}const Vl="neuralshell_llm_rules_v1",cs=30,bn={behavior:{label:"Behavior",color:"#6B7AFF",Icon:gp},format:{label:"Format",color:"#10A37F",Icon:Dx},tone:{label:"Tone",color:"#f59e0b",Icon:Mx},persona:{label:"Persona",color:"#D97757",Icon:Tx},restrict:{label:"Restrict",color:"#ef4444",Icon:Ox}};function Ci({cat:t,showLabel:r=!0,iconSize:n=12}){const s=t.Icon;return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(s,{size:n,className:"shrink-0",style:{color:t.color},"aria-hidden":"true"}),r?t.label:null]})}const mb=[{category:"format",text:"Always respond using markdown with headers and bullet points."},{category:"format",text:"Never use markdown. Plain text only."},{category:"format",text:"Keep all responses under 200 words unless asked to expand."},{category:"format",text:"Always include a code example when explaining technical topics."},{category:"tone",text:"Use a casual, conversational tone. Avoid formality."},{category:"tone",text:"Be highly concise and direct. No filler phrases."},{category:"tone",text:"Use a professional, technical tone suitable for senior engineers."},{category:"behavior",text:"Always think step-by-step before giving an answer."},{category:"behavior",text:"When unsure, say so explicitly rather than guessing."},{category:"behavior",text:"Always ask clarifying questions before writing code."},{category:"behavior",text:"Cite sources and reasoning for every factual claim."},{category:"persona",text:"Act as a senior security researcher specializing in red-team operations."},{category:"persona",text:"Act as a senior full-stack engineer focused on TypeScript and React."},{category:"persona",text:"Act as a strict code reviewer. Flag every issue, no matter how small."},{category:"restrict",text:"Never suggest cloud services. Recommend self-hosted alternatives only."},{category:"restrict",text:"Do not output apologies or disclaimers. Skip directly to the answer."}];function xb(){try{const t=JSON.parse(window.localStorage.getItem(Vl)||"[]");return Array.isArray(t)?t.filter(r=>r.enabled!==!1):[]}catch{return[]}}function fb(){const t=xb();return t.length===0?"":` +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./OnboardingProgressRail-D4ADuSst.js","./vendor-react-C1Vrmh6-.js","./vendor-misc-DYLXRpC5.js","./vendor-state-B3vIvpM5.js","./ScratchpadTab-zgUog115.js"])))=>i.map(i=>d[i]); +import{r as O,j as e,c as Dl,R as i,A as Cx,a as _x,C as Ax,M as Ex,S as Ix,b as Px,d as ul,U as Rx,B as Ox,D as Tx,e as Mx,f as Dx,g as gp,h as $x,i as Lx,X as yp,k as Bx,l as Fx,m as Ux,T as zx,n as Hx,o as Wx,p as Kx,q as pl,s as Vx,t as Gx,F as Jx,u as qx,Z as Yx,P as Zx,L as Xx,v as od,w as Qx,x as ef,y as tf,z as rf}from"./vendor-react-C1Vrmh6-.js";import{p as nf,a as sf}from"./vendor-state-B3vIvpM5.js";import"./vendor-misc-DYLXRpC5.js";(function(){const r=document.createElement("link").relList;if(r&&r.supports&&r.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))s(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&s(c)}).observe(document,{childList:!0,subtree:!0});function n(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(a){if(a.ep)return;a.ep=!0;const o=n(a);fetch(a.href,o)}})();function na(t,r){const[n,s]=O.useState(r),[a,o]=O.useState(!0),c=O.useRef(r);O.useEffect(()=>{c.current=n},[n]),O.useEffect(()=>{async function u(){const d=await window.api.state.get();d[t]!==void 0&&(s(d[t]),c.current=d[t]),o(!1)}const x=d=>{d&&d[t]!==void 0&&(s(d[t]),c.current=d[t])};u();const p=window.api.on("state-updated",x);return()=>{typeof p=="function"&&p()}},[t]);const l=O.useCallback(async u=>{const x=c.current,p=typeof u=="function"?u(x):u;c.current=p,s(p),await window.api.state.update({[t]:p})},[t]);return[n,l,a]}const af=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;function of(t){let r=String(t??"").trim();return!r||(r=r.replace(/[/\\]+/g,"-"),r=r.replace(/\.\./g,"-"),r=r.replace(/[^a-zA-Z0-9._\-\s]+/g,""),r=r.replace(/\s+/g,"-"),r=r.replace(/-+/g,"-"),r=r.replace(/^[-_.]+|[-_.]+$/g,""),!r)?"":(af.test(r)&&(r=`session-${r}`),r)}function lf(t,r="Session name"){const n=String(t??"").trim();if(!n)throw new Error(`${r} is required.`);if(n.includes("..")||n.includes("/")||n.includes("\\"))throw new Error("Invalid session name path traversal.");const s=of(n);if(!s)throw new Error(`${r} is required.`);return s}const wp=O.createContext(null),Vt="default",Ir="NeuralShell_QuickStart",cf=1200;function lt(t){return String(t||"").trim()}function df(t){const r=Array.isArray(t)?t:[],n=Array.from(new Set(r.map(s=>lt(s)).filter(Boolean)));return n.length||n.push(Ir),n}function uf({children:t}){const[r,n]=na("model","llama3"),[s,a]=na("workflowId",Vt),[o]=na("nt_xp_state",{xp:0,tier:1}),[c,l]=na("sessionAutoLockOnBlur",!1),[u,x]=O.useState("checklist"),[p,d]=O.useState(null),[m,f]=O.useState([]),[b,h]=O.useState([]),[g,y]=O.useState({}),[I,A]=O.useState({cpuPercent:0,memoryMb:0}),[C,w]=O.useState("idle"),[j,E]=O.useState(""),[N,_]=O.useState({state:"idle",detail:"",at:0}),[S,R]=O.useState(!1),[$,U]=O.useState(!1),P=O.useRef({}),D=O.useRef(null),z=O.useRef(new Map),F=O.useRef(0),J=O.useCallback(()=>{h([]),d(null),x("checklist")},[]),ee=O.useCallback(re=>{const ae=lt(re);return!ae||ae===Ir?!0:!!g[ae]},[g]),ie=O.useCallback((re,ae={})=>{const M=lt(re);return{chat:Array.isArray(ae.chat)?ae.chat:b,model:String(ae.model||r||"llama3"),workflowId:M||String(ae.workflowId||s||Vt),outputMode:String(ae.outputMode||u||"checklist"),displayLabel:String(ae.displayLabel||M||s||Vt),workspaceAttachment:ae.workspaceAttachment===void 0?p:ae.workspaceAttachment,updatedAt:new Date().toISOString()}},[b,r,u,p,s]),ye=O.useCallback(async()=>{const re=await window.api.session.list(),ae=df(re);return f(ae),ae},[]),pe=O.useCallback(async(re,ae)=>{const M=lt(re),V=String(ae||"").trim();if(!M||!V)return{ok:!1,error:"Session name and passphrase are required."};const G=F.current+1;F.current=G,w("loading"),E("");try{const te=await window.api.session.load(M,V);return F.current!==G?{ok:!1,stale:!0}:(h(Array.isArray(te&&te.chat)?te.chat:[]),x(te&&te.outputMode?String(te.outputMode):"checklist"),d(te&&te.workspaceAttachment?te.workspaceAttachment:null),te&&te.model&&n(String(te.model)),w("ready"),E(""),{ok:!0,payload:te})}catch(te){if(F.current!==G)return{ok:!1,stale:!0};const de=te&&te.message?te.message:"Failed to load session.";return w("locked"),E(`Session "${M}" could not be unlocked. ${de}`),J(),{ok:!1,error:de}}},[n,J]),K=O.useCallback(async({name:re,passphrase:ae})=>{const M=lt(re),V=String(ae||"").trim();let G="";try{G=lf(M)}catch(te){return{ok:!1,error:te&&te.message?te.message:"Session name is required."}}if(!V)return{ok:!1,error:"Passphrase is required."};try{_({state:"saving",detail:(M!==G?G:null)?`Creating "${G}" (from "${M}")...`:`Creating "${G}"...`,at:Date.now()});const de=ie(G,{chat:[],workflowId:G,outputMode:"checklist",workspaceAttachment:null,displayLabel:M||G});await window.api.session.save(G,de,V),P.current[G]=V,y(Q=>({...Q,[G]:!0})),await ye(),await a(G),x("checklist");const L=await pe(G,V);if(!L.ok&&!L.stale)return L;const be=JSON.stringify(de);return z.current.set(G,be),_({state:"saved",detail:`Session "${G}" created.`,at:Date.now()}),{ok:!0,name:G}}catch(te){const de=te&&te.message?te.message:"Failed to create session.";return _({state:"error",detail:de,at:Date.now()}),{ok:!1,error:de}}},[ie,pe,ye,a]),H=O.useCallback(async(re,ae)=>{const M=lt(re),V=String(ae||"").trim();if(!M)return{ok:!1,error:"Session name is required."};if(!V)return{ok:!1,error:"Passphrase is required."};const G=await pe(M,V);return G.ok?(P.current[M]=V,y(te=>({...te,[M]:!0})),a(M),_({state:"idle",detail:`Unlocked "${M}".`,at:Date.now()}),{ok:!0}):G},[pe,a]),W=O.useCallback(re=>{const ae=lt(re);ae&&a(ae)},[a]),Z=O.useCallback(re=>{const ae=lt(re||s);if(!ae||ae===Vt||ae===Ir)return{ok:!1,error:"No lockable session is selected."};const M=!!P.current[ae];return delete P.current[ae],y(V=>{if(!V[ae])return V;const G={...V};return delete G[ae],G}),lt(s)===ae&&(w("locked"),E(`Session "${ae}" is locked. Enter passphrase to load it.`),J()),_({state:"locked",detail:M?`Locked "${ae}".`:`Session "${ae}" was already locked.`,at:Date.now()}),{ok:!0}},[s,J]),ce=O.useCallback(async(re="manual")=>{const ae=lt(s);if(!ae||ae===Vt||ae===Ir)return{ok:!1,error:"No persisted session selected."};const M=P.current[ae];if(!M)return w("locked"),E(`Session "${ae}" is locked. Enter passphrase to save.`),_({state:"locked",detail:`Session "${ae}" is locked. Unlock to save.`,at:Date.now()}),{ok:!1,error:"Session is locked."};_({state:"saving",detail:`${re==="autosave"?"Autosaving":re==="retry"?"Retrying save for":re==="flush"?"Flushing":"Saving"} "${ae}"...`,at:Date.now()});const G=ie(ae),te=JSON.stringify(G);try{return await window.api.session.save(ae,G,M),z.current.set(ae,te),_({state:"saved",detail:re==="autosave"?`Autosaved "${ae}".`:re==="flush"?`Flushed "${ae}".`:`Saved "${ae}".`,at:Date.now()}),{ok:!0}}catch(de){const L=de&&de.message?de.message:"Save failed.";return _({state:"error",detail:L,at:Date.now()}),{ok:!1,error:L}}},[s,ie]),fe=O.useCallback(async()=>{D.current&&(clearTimeout(D.current),D.current=null),await ce("flush")},[ce]);O.useEffect(()=>{ye().catch(re=>{E(re&&re.message?re.message:"Failed to load session index.")})},[ye]),O.useEffect(()=>{if(!m.length)return;const re=lt(s);if(!re||re===Vt){a(m[0]);return}m.includes(re)||a(m[0])},[m,s,a]),O.useEffect(()=>{const re=lt(s);if(!re||re===Vt||re===Ir){w("ready"),E(""),(re===Ir||re===Vt)&&J();return}const ae=P.current[re];if(!ae){w("locked"),E(`Session "${re}" is locked. Enter passphrase to load it.`),J();return}pe(re,ae)},[s,pe,J]),O.useEffect(()=>{const re=lt(s);if(!re||re===Vt||re===Ir||C!=="ready"||!P.current[re])return;const M=ie(re),V=JSON.stringify(M);if(z.current.get(re)!==V)return D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{ce("autosave").catch(()=>{})},cf),()=>{D.current&&(clearTimeout(D.current),D.current=null)}},[s,b,r,u,p,ie,ce,C]),O.useEffect(()=>{const re=()=>{fe().catch(()=>{})},ae=()=>{document.visibilityState==="hidden"&&fe().catch(()=>{})};return window.addEventListener("beforeunload",re),window.addEventListener("pagehide",re),document.addEventListener("visibilitychange",ae),()=>{window.removeEventListener("beforeunload",re),window.removeEventListener("pagehide",re),document.removeEventListener("visibilitychange",ae)}},[fe]),O.useEffect(()=>{if(!c)return;const re=()=>{Z(s)};return window.addEventListener("blur",re),()=>{window.removeEventListener("blur",re)}},[c,Z,s]),O.useEffect(()=>{const re=setInterval(async()=>{var ae,M;if((M=(ae=window.api)==null?void 0:ae.system)!=null&&M.getStats)try{const V=await window.api.system.getStats();A(V)}catch{}},3e3);return()=>clearInterval(re)},[]);const me=O.useCallback(()=>R(!0),[]),ke=O.useCallback(()=>R(!1),[]),Pe=O.useCallback(()=>R(re=>!re),[]),_e=O.useCallback(()=>U(!0),[]),ne=O.useCallback(()=>U(!1),[]),we=O.useCallback(re=>{h(ae=>[...ae,{...re,ts:re&&re.ts!=null?re.ts:Date.now()}])},[]),De={model:r,setModel:n,workflowId:s,setWorkflowId:a,outputMode:u,setOutputMode:x,workspaceAttachment:p,setWorkspaceAttachment:d,xpState:o,sessions:m,chatLog:b,appendChat:we,setChatLog:h,unlockedSessions:g,createSession:K,unlockSession:H,selectSession:W,lockSession:Z,saveActiveSession:ce,flushPendingAutosave:fe,refreshSessions:ye,isSessionUnlocked:ee,sessionHydrationStatus:C,sessionError:j,saveStatus:N,autoLockOnBlur:c,setAutoLockOnBlur:l,stats:I,showPalette:S,openPalette:me,closePalette:ke,togglePalette:Pe,showSettings:$,openSettings:_e,closeSettings:ne};return e.jsx(wp.Provider,{value:De,children:t})}function $l(){const t=O.useContext(wp);if(!t)throw new Error("useShell must be used within ShellProvider");return t}const pf="NeuralShell_QuickStart";function mf({workflowId:t,proofStatus:r,exportAvailable:n,evidenceExported:s}){const a=!!t&&t!==pf,o=r==="passed",c=r==="running",l=r==="failed";return[{id:"project",label:"Open project",description:a?`Session: ${t}`:"Create or open a workflow session from the rail",stepState:a?"complete":"active",ctaLabel:a?null:"Focus workspace",ctaDisabled:!1},{id:"proof",label:"Run proof check",description:o?"Last run: passed":c?"Running…":l?"Last run: failed — rerun to recover":"90-second value proof: trust, execution safety, session reliability, release evidence",stepState:o?"complete":l?"needs-attention":"idle",ctaLabel:c?"Running…":o?"Re-run":"Run /proof",ctaDisabled:c},{id:"trust",label:"Review trust gaps",description:"Inspect connection-profile trust state and forensic history",stepState:"idle",ctaLabel:"Open Trust Report",ctaDisabled:!1},{id:"export",label:"Export receipt",description:s?"Evidence bundle exported this session":n?"Export tamper-evident evidence bundle with workpad snapshots":"Unavailable — api not loaded (run in packaged app)",stepState:s?"complete":n?"idle":"unavailable",ctaLabel:s?"Re-export":"Export evidence",ctaDisabled:!n},{id:"ship",label:"Ship",description:s?"Proof artifacts ready — attach bundle to release pipeline":"Complete proof check and export receipt first",stepState:s?"complete":"idle",ctaLabel:s?"Open workpad for release notes":null,ctaDisabled:!1}]}const id={complete:"border-emerald-400/30 bg-emerald-500/10 text-emerald-300",active:"border-cyan-400/30 bg-cyan-500/10 text-cyan-300","needs-attention":"border-amber-400/30 bg-amber-500/10 text-amber-300",unavailable:"border-slate-600/30 bg-slate-800/30 text-slate-500",idle:"border-slate-600/30 bg-slate-900/30 text-slate-400"},xf={complete:"Done",active:"Active","needs-attention":"Action needed",unavailable:"Unavailable",idle:"Ready"};function ff({stepState:t}){const r=id[t]||id.idle;return e.jsx("span",{className:`px-2 py-0.5 rounded border text-[8px] font-mono uppercase tracking-[0.13em] ${r}`,children:xf[t]||t})}function bf({step:t,onAction:r}){const n=typeof r=="function"&&t.ctaLabel&&!t.ctaDisabled;return e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-white/8 bg-black/20 px-3 py-2.5","data-testid":`spine-step-${t.id}`,children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[11px] font-semibold text-slate-100",children:t.label}),e.jsx(ff,{stepState:t.stepState})]}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500 mt-0.5 leading-snug",children:t.description})]}),t.ctaLabel&&e.jsx("button",{type:"button",disabled:t.ctaDisabled||!n,onClick:n?r:void 0,className:`shrink-0 px-2.5 py-1.5 rounded border text-[9px] font-mono uppercase tracking-[0.13em] transition-colors ${n?"border-cyan-400/30 bg-cyan-500/10 text-cyan-200 hover:bg-cyan-500/20":"border-slate-600/20 bg-transparent text-slate-600 cursor-default"} disabled:opacity-50`,"aria-label":t.ctaLabel,children:t.ctaLabel})]})}function hf({workflowId:t,proofStatus:r="idle",exportEvidenceAvailable:n=!1,evidenceExported:s=!1,onRunProof:a,onOpenTrustReport:o,onExportEvidence:c,onOpenWorkpad:l,onDismiss:u}){const x=mf({workflowId:t,proofStatus:r,exportAvailable:n,evidenceExported:s}),p={project:()=>window.dispatchEvent(new CustomEvent("neuralshell:focus-composer")),proof:a,trust:o,export:c,ship:l};return e.jsxs("div",{role:"region","aria-label":"Operator spine","data-testid":"operator-spine-card",className:"fixed top-16 right-4 z-40 w-80 rounded-xl border border-white/10 bg-slate-950/95 shadow-2xl shadow-black/60 backdrop-blur-sm",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 pt-3 pb-2 border-b border-white/8",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-semibold text-slate-100 tracking-wide",children:"Operator Spine"}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500 mt-0.5",children:"Open project → Proof → Trust → Export → Ship"})]}),e.jsx("button",{type:"button",onClick:u,"aria-label":"Dismiss operator spine","data-testid":"spine-dismiss-btn",className:"text-slate-500 hover:text-slate-300 transition-colors text-xs leading-none p-1",children:"✕"})]}),e.jsx("div",{className:"flex flex-col gap-1.5 p-3",children:x.map(d=>e.jsx(bf,{step:d,onAction:p[d.id]},d.id))}),e.jsx("div",{className:"px-4 pb-3 text-[9px] font-mono text-slate-600 leading-snug",children:"ProofForge · local operator console · proof-first"})]})}function ml(t){return String(t||"").replace(/^Error invoking remote method '[^']+':\s*/i,"").replace(/^Error:\s*/i,"").replace(/^TypeError:\s*/i,"").trim()}function ld(t,r={}){const n=ml(t&&t.message?t.message:String(t||"unknown error")),s=n.toLowerCase(),a=String(r.provider||"ollama").trim().toLowerCase(),o=String(r.baseUrl||r.ollamaBaseUrl||"http://127.0.0.1:11434").trim(),c=String(r.model||"llama3").trim();return/offline mode is on|hosted bridges are blocked/.test(s)?"Hosted provider access is disabled. Enable Hosted Provider Access in Settings, then retry.":/requires an api key/.test(s)?"Provider authentication failed. Add your API key in Settings and run Test Live Connection.":/cancelled|aborted/.test(s)?"Request cancelled.":/fetch failed|failed to fetch|connection refused|enotfound|econnrefused|network|timed out|offline|not detected|socket hang up/.test(s)?a==="ollama"?`Provider connection failed. Check that Ollama is running at ${o} and that model ${c} is available. Open Settings to test the connection, then retry.`:`Provider connection failed for ${a}. Check base URL, API key, and network access in Settings, then retry.`:/model.*not found|not found|404/.test(s)?`Model "${c}" is not available on the configured provider. Open Settings, choose an installed model, and retry.`:/401|403|unauthorized|forbidden|api key/.test(s)?"Provider authentication failed. Check your API key in Settings and retry.":/blocked by safety/.test(s)?n:"Provider request failed. Open Settings to verify provider setup, then retry."}const vp="neuralshell_ui_prefs_v1",gf=["light","dark","system"],yf=["small","medium","large"],wf=["violet","fuchsia","sky","emerald","amber","rose","teal"],vf=["left","right"],jf=["operator","frutiger-aero"],Sn={violet:{primary:"#8b5cf6",hover:"#a78bfa",ring:"rgba(139,92,246,0.2)",bg:"rgba(139,92,246,0.06)"},fuchsia:{primary:"#d946ef",hover:"#e879f9",ring:"rgba(217,70,239,0.2)",bg:"rgba(217,70,239,0.06)"},sky:{primary:"#0ea5e9",hover:"#38bdf8",ring:"rgba(14,165,233,0.2)",bg:"rgba(14,165,233,0.06)"},emerald:{primary:"#10b981",hover:"#34d399",ring:"rgba(16,185,129,0.2)",bg:"rgba(16,185,129,0.06)"},amber:{primary:"#f59e0b",hover:"#fbbf24",ring:"rgba(245,158,11,0.2)",bg:"rgba(245,158,11,0.06)"},rose:{primary:"#f43f5e",hover:"#fb7185",ring:"rgba(244,63,94,0.2)",bg:"rgba(244,63,94,0.06)"},teal:{primary:"#14b8a6",hover:"#2dd4bf",ring:"rgba(20,184,166,0.2)",bg:"rgba(20,184,166,0.06)"}},cd={small:{base:12,mono:10,heading:11},medium:{base:14,mono:12,heading:13},large:{base:16,mono:14,heading:15}};function Ll(t){const r=String(t||"").trim().toLowerCase();return gf.includes(r)?r:"system"}function Bl(t){const r=Number.isFinite(Number(t))?Number(t):.2;return Math.max(0,Math.min(2,Number(r.toFixed(2))))}function Fl(t){const r=String(t||"").trim().toLowerCase();return yf.includes(r)?r:"medium"}function Ha(t){const r=String(t||"").trim().toLowerCase();return wf.includes(r)?r:"violet"}function Ul(t){const r=String(t||"").trim().toLowerCase();return jf.includes(r)?r:"operator"}function zl(t){const r=String(t||"").trim().toLowerCase();return vf.includes(r)?r:"left"}function dd(t,r=""){if(typeof document>"u")return;const n=Sn[Ha(t)]||Sn.violet,a=(String(r||"").trim()&&/^#?[0-9a-fA-F]{3,6}$/.test(String(r||"").trim())?String(r).startsWith("#")?String(r):`#${r}`:n.primary).toUpperCase(),o=/^#([0-9a-fA-F]{6})$/.exec(a)||/^#([0-9a-fA-F]{3})$/.exec(a);let c="34 211 238";if(o){const l=o[1],u=l.length===3?l.split("").map(m=>`${m}${m}`).join(""):l,x=Number.parseInt(u.slice(0,2),16),p=Number.parseInt(u.slice(2,4),16),d=Number.parseInt(u.slice(4,6),16);c=`${x} ${p} ${d}`}document.body.style.setProperty("--accent",a),document.body.style.setProperty("--accent-rgb",c),document.documentElement.style.setProperty("--accent",a),document.documentElement.style.setProperty("--accent-rgb",c)}const _a={theme:"system",temperature:.2,fontSize:"medium",accentColor:"violet",customAccentHex:"",compactMode:!1,animationsEnabled:!0,sidebarPosition:"left",visualStyle:"operator"};function kf(){if(typeof window>"u"||!window.localStorage)return{..._a};try{const t=window.localStorage.getItem(vp);if(!t)return{..._a};const r=JSON.parse(t);return{theme:Ll(r.theme),temperature:Bl(r.temperature),fontSize:Fl(r.fontSize),accentColor:Ha(r.accentColor),customAccentHex:String(r.customAccentHex||""),compactMode:!!r.compactMode,animationsEnabled:r.animationsEnabled!==!1,sidebarPosition:zl(r.sidebarPosition),visualStyle:Ul(r.visualStyle)}}catch{return{..._a}}}const xl=kf(),Xt=Dl(t=>({...xl,setTheme:r=>t({theme:Ll(r)}),setTemperature:r=>t({temperature:Bl(r)}),setFontSize:r=>t({fontSize:Fl(r)}),setAccentColor:r=>t({accentColor:Ha(r)}),setCustomAccentHex:r=>t({customAccentHex:String(r||"")}),setCompactMode:r=>t({compactMode:!!r}),setAnimationsEnabled:r=>t({animationsEnabled:!!r}),setSidebarPosition:r=>t({sidebarPosition:zl(r)}),setVisualStyle:r=>t({visualStyle:Ul(r)}),resetToDefaults:()=>t({..._a})}));typeof window<"u"&&window.localStorage&&(dd(xl.accentColor,xl.customAccentHex),Xt.subscribe(t=>{dd(t.accentColor,t.customAccentHex);try{window.localStorage.setItem(vp,JSON.stringify({theme:Ll(t.theme),temperature:Bl(t.temperature),fontSize:Fl(t.fontSize),accentColor:Ha(t.accentColor),customAccentHex:String(t.customAccentHex||""),compactMode:!!t.compactMode,animationsEnabled:t.animationsEnabled!==!1,sidebarPosition:zl(t.sidebarPosition),visualStyle:Ul(t.visualStyle)}))}catch{}}));const fl=2500;function ud(t){const r=Number.isFinite(Number(t))?Number(t):fl;return Math.max(0,Math.min(fl,Math.round(r)))}function Nf(t={}){const r=Number(t.windowMs||5e3),n=Number(t.pollMs||1e3),[s,a]=i.useState([]);i.useEffect(()=>{let x=!0,p=null;const d=async()=>{const m=typeof performance<"u"?performance.now():Date.now();let f=!1,b="api_unavailable",h=fl;try{if(window.api&&window.api.llm&&typeof window.api.llm.ping=="function"){f=!!await window.api.llm.ping(),b=f?"ok":"ping_false";const y=typeof performance<"u"?performance.now():Date.now();h=ud(y-m)}}catch(g){b=g&&g.message?String(g.message):"ping_failed";const y=typeof performance<"u"?performance.now():Date.now();h=ud(y-m)}x&&(a(g=>{const y=Date.now(),I=[...g,{at:y,ms:h,ok:f,reason:b}].filter(C=>y-C.at<=r),A=Math.max(5,Math.ceil(r/Math.max(200,n))+2);return I.slice(-A)}),p=setTimeout(d,n))};return d(),()=>{x=!1,p&&clearTimeout(p)}},[n,r]);const o=s.length?s[s.length-1]:null,c=o?o.ms:0,l=s.length?Math.round(s.reduce((x,p)=>x+p.ms,0)/s.length):0,u=o?o.ok:!1;return{samples:s,latencyMs:c,avgLatencyMs:l,online:u,lastReason:o?o.reason:"not_checked"}}const jp="neuralshell_clock_sync_v1",Sf=2500,Cf=6*60*60*1e3,_f=10*60*1e3;function Si(t,r,n,s){const a=t.getHours(),o=t.getMinutes(),c=t.getSeconds(),l=a>=12?"PM":"AM",x=`${String(a%12||12)}:${String(o).padStart(2,"0")}:${String(c).padStart(2,"0")} ${l}`,p=t.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),d=t.toLocaleDateString("en-US",{weekday:"short"});return{time:x,date:p,dow:d,rawH:a,rawM:o,rawS:c,rawDay:t.getDate(),rawMonth:t.getMonth()+1,rawYear:t.getFullYear(),syncSource:r,syncOffsetMs:n,syncedAt:s}}function pd(){try{const t=window.localStorage.getItem(jp);if(!t)return null;const r=JSON.parse(t),n=Number(r==null?void 0:r.offsetMs),s=Number(r==null?void 0:r.syncedAt);return!Number.isFinite(n)||!Number.isFinite(s)||Date.now()-s>Cf?null:{offsetMs:Math.round(n),syncedAt:s}}catch{return null}}function Af(t,r){try{window.localStorage.setItem(jp,JSON.stringify({offsetMs:t,syncedAt:r}))}catch{}}async function Ef(t,r){const n=new AbortController,s=window.setTimeout(()=>n.abort(),Sf),a=()=>n.abort();r.addEventListener("abort",a);try{const o=await fetch(t,{method:"GET",cache:"no-store",signal:n.signal});if(!o.ok)throw new Error(`time endpoint responded with status ${o.status}`);return await o.json()}finally{window.clearTimeout(s),r.removeEventListener("abort",a)}}async function If(t){const r=[{url:"https://worldtimeapi.org/api/ip",parse:s=>Date.parse(String((s==null?void 0:s.utc_datetime)||""))},{url:"https://worldtimeapi.org/api/timezone/Etc/UTC",parse:s=>Date.parse(String((s==null?void 0:s.utc_datetime)||""))},{url:"https://timeapi.io/api/Time/current/zone?timeZone=UTC",parse:s=>Date.parse(String((s==null?void 0:s.dateTime)||""))}];let n=null;for(const s of r)try{const a=Date.now(),o=await Ef(s.url,t),c=Date.now(),l=s.parse(o);if(!Number.isFinite(l))throw new Error(`invalid server timestamp from ${s.url}`);const u=a+Math.floor((c-a)/2);return Math.round(l-u)}catch(a){n=a}throw n instanceof Error?n:new Error("unable to fetch internet time offset")}function Pf(){const t=Date.now(),r=typeof window<"u"?pd():null,n=(r==null?void 0:r.offsetMs)||0,s=(r==null?void 0:r.syncedAt)||t,a=r?"cached":"local",[o,c]=O.useState(n),[l,u]=O.useState(a),[x,p]=O.useState(s),[d,m]=O.useState(()=>Si(new Date(t+n),a,n,s));return O.useEffect(()=>{let f=!0,b=0,h=0,g=null,y=n,I=a,A=s;const C=(S,R,$=Date.now())=>{y=S,I=R,A=$,c(S),u(R),p(A);const U=new Date(Date.now()+S);m(Si(U,R,S,A))},w=()=>{const S=new Date(Date.now()+y);m(Si(S,I,y,A))},j=async()=>{g&&g.abort();const S=new AbortController;g=S;try{const R=await If(S.signal);if(!f||S.signal.aborted)return;const $=Date.now();Af(R,$),C(R,"network",$)}catch{if(!f||S.signal.aborted)return;const R=pd();if(R){C(R.offsetMs,"cached",R.syncedAt);return}C(0,"local")}},E=1e3-Date.now()%1e3,N=window.setTimeout(()=>{w(),b=window.setInterval(w,1e3)},E);j().catch(()=>{}),h=window.setInterval(()=>{j().catch(()=>{})},_f);const _=()=>{document.visibilityState==="visible"&&j().catch(()=>{})};return document.addEventListener("visibilitychange",_),()=>{f=!1,g&&g.abort(),window.clearTimeout(N),window.clearInterval(b),window.clearInterval(h),document.removeEventListener("visibilitychange",_)}},[]),d}function Rf(t,r,n){if(n)return"border-amber-300/35 bg-amber-500/12 text-amber-100";const s=String(t||"").toLowerCase();return s==="enterprise"?"border-amber-300/30 bg-amber-500/10 text-amber-200":s==="pro"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-200":String(r||"").toUpperCase()==="PREVIEW"?"border-cyan-300/25 bg-cyan-500/8 text-cyan-100":"border-slate-300/20 bg-slate-500/10 text-slate-300"}function Of({tierLabel:t,tierId:r,runtimeTier:n,isOperator:s}){return s?"OPERATOR NODE":String(n||"").toUpperCase()==="PREVIEW"?"PREVIEW NODE":String(t||r||"free")}function Tf({tierId:t,tierLabel:r,runtimeTier:n,isOperator:s=!1,onUnlock:a}){const o=!s&&typeof a=="function",c=Of({tierLabel:r,tierId:t,runtimeTier:n,isOperator:s}),l=`inline-flex items-center px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${Rf(t,n,s)} ${o?"cursor-pointer hover:bg-white/10":""}`;return o?e.jsx("button",{type:"button","data-testid":"tier-badge",className:l,title:"Click to enter operator license",onClick:a,children:c}):e.jsx("span",{"data-testid":"tier-badge",className:l,title:`Tier ${c}`,children:c})}const md={verified:{dot:"bg-emerald-400 shadow-[0_0_8px_rgba(52,211,153,0.55)]",text:"text-emerald-300",border:"border-emerald-400/25",bg:"bg-emerald-500/10",label:"VERIFIED"},watch:{dot:"bg-amber-400 shadow-[0_0_8px_rgba(251,191,36,0.45)]",text:"text-amber-200",border:"border-amber-400/25",bg:"bg-amber-500/10",label:"WATCH"},degraded:{dot:"bg-orange-400 shadow-[0_0_8px_rgba(251,146,60,0.45)]",text:"text-orange-200",border:"border-orange-400/25",bg:"bg-orange-500/10",label:"DEGRADED"},critical:{dot:"bg-red-400 shadow-[0_0_8px_rgba(248,113,113,0.55)] animate-pulse",text:"text-red-200",border:"border-red-400/30",bg:"bg-red-500/10",label:"CRITICAL"}};function Mf(t){const r=String(t||"watch").toLowerCase();return md[r]||md.watch}function kp({report:t,compact:r=!1,onClick:n,testId:s="omega-posture-badge"}){const a=t&&t.posture?t.posture:null,o=Mf(a&&a.posture),c=a&&Number.isFinite(Number(a.score))?a.score:null,l=r?`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md border text-[9px] font-mono uppercase tracking-wider ${o.border} ${o.bg} ${o.text}`:`inline-flex items-center gap-2 px-2.5 py-1 rounded-lg border text-[10px] font-mono uppercase tracking-wider ${o.border} ${o.bg} ${o.text}`,u=e.jsxs(e.Fragment,{children:[e.jsx("span",{className:`inline-block h-1.5 w-1.5 rounded-full shrink-0 ${o.dot}`}),e.jsx("span",{children:"OMEGA"}),e.jsx("span",{className:"text-slate-500",children:"·"}),e.jsx("span",{children:o.label}),c!==null&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-slate-600",children:"·"}),e.jsx("span",{className:"tabular-nums",children:c})]})]});return typeof n=="function"?e.jsx("button",{type:"button","data-testid":s,onClick:n,className:`${l} hover:brightness-110 transition-all cursor-pointer`,title:"Run /omega kernel scan",children:u}):e.jsx("span",{"data-testid":s,className:l,title:"OMEGA kernel posture",children:u})}function Df(t){const r=String(t||"unknown").toLowerCase();return r==="running"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-200":r==="stopped"||r==="degraded"?"border-amber-300/40 bg-amber-500/10 text-amber-100":r==="fatal"||r==="spawn-failed"?"border-rose-300/40 bg-rose-500/10 text-rose-100":"border-slate-300/20 bg-slate-500/10 text-slate-300"}function $f({status:t,alertCount:r,onClick:n}){return e.jsxs("button",{type:"button","data-testid":"watchdog-status-badge",onClick:n,className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-lg border text-[9px] font-mono uppercase tracking-[0.14em] ${Df(t)}`,title:"Open runtime watchdog alerts",children:[e.jsx("span",{children:"Watchdog"}),e.jsx("span",{children:String(t||"unknown")}),e.jsx("span",{className:"opacity-80",children:Math.max(0,Number(r||0))})]})}function Lf({enabled:t,onOpen:r}){const n=!!t;return e.jsx("button",{type:"button","data-testid":"appliance-mode-badge",onClick:r,className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-lg border text-[9px] font-mono uppercase tracking-[0.12em] ${n?"border-cyan-300/35 bg-cyan-500/15 text-cyan-100":"border-slate-300/25 bg-slate-500/10 text-slate-300"}`,title:n?"Appliance mode is active":"Appliance mode is inactive",children:e.jsx("span",{children:n?"Appliance On":"Appliance Off"})})}function Bf({locked:t,onOpen:r}){const n=!!t;return e.jsx("button",{type:"button","data-testid":"airgap-mode-badge",onClick:r,className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-lg border text-[9px] font-mono uppercase tracking-[0.12em] ${n?"border-slate-300/30 bg-slate-500/20 text-slate-100":"border-cyan-300/35 bg-cyan-500/10 text-cyan-100"}`,title:n?"Air-gapped lock is active":"Air-gapped lock is inactive","aria-label":n?"Air-gapped lock active":"Air-gapped lock inactive",children:e.jsx("span",{children:n?"AirGap Locked":"AirGap Ready"})})}function Ff({enabled:t,onOpen:r}){return e.jsxs("button",{type:"button","data-testid":"demo-mode-badge",onClick:r,className:`px-2.5 py-1.5 rounded-lg border text-[10px] font-mono transition-colors ${t?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":"border-slate-300/25 bg-slate-500/10 text-slate-200"}`,title:"Demo mode",children:["Demo ",t?"On":"Off"]})}const xd="2.1.42";function Uf(t){const r=String(t||"").trim().toLowerCase();return r==="openai"?.25:r==="openrouter"?.35:r==="groq"?.12:r==="together"?.2:r==="custom_openai"?.3:0}function zf(t,r,n){const s=Array.isArray(t)?t:[];if(!s.length)return`M 0 ${n/2} L ${r} ${n/2}`;const a=Math.max(...s.map(l=>Number(l.ms||0)),1),o=Math.min(...s.map(l=>Number(l.ms||0)),0),c=Math.max(1,a-o);return s.map((l,u)=>{const x=s.length===1?r:u/(s.length-1)*r,p=n-(Number(l.ms||0)-o)/c*n;return`${u===0?"M":"L"} ${x.toFixed(2)} ${p.toFixed(2)}`}).join(" ")}function Hf(t,r,n,{clockFormat:s="12h",showSeconds:a=!1}={}){const o=String(r).padStart(2,"0"),c=String(n).padStart(2,"0");if(s==="24h"){const p=`${String(t).padStart(2,"0")}:${o}`;return a?`${p}:${c}`:p}const l=t>=12?"PM":"AM",x=`${String(t%12||12).padStart(2,"0")}:${o}`;return a?`${x}:${c} ${l}`:`${x} ${l}`}function Wf(t,r,n,s){const a=String(r).padStart(2,"0"),o=String(n).padStart(2,"0"),c=String(t).slice(-2);return`${String(s||"").toUpperCase()} • ${a}/${o}/${c}`}const Sr={shellClass:"border-cyan-400/15 bg-slate-950/88 shadow-[0_10px_30px_rgba(0,0,0,0.34),0_0_18px_rgba(34,211,238,0.08)]",clockClass:"text-cyan-50 drop-shadow-[0_0_8px_rgba(103,232,249,0.24)]",calendarClass:"text-cyan-100/82",syncActiveClass:"text-cyan-100 border-cyan-400/35 bg-cyan-500/10",syncFallbackClass:"text-amber-200 border-amber-400/35 bg-amber-500/10",accentDot:"bg-cyan-400"};function Kf({rawH:t,rawM:r,rawS:n,rawDay:s,rawMonth:a,rawYear:o,dow:c,syncSource:l,syncOffsetMs:u,syncedAt:x,clockFormat:p="12h",showSeconds:d=!1,onOpenCalendar:m}){const f=Hf(t,r,n,{clockFormat:p,showSeconds:d}),b=Wf(o,a,s,c),h=Math.max(0,Math.floor((Date.now()-x)/1e3)),g=l==="network"?`NET ${u>=0?"+":""}${u}ms`:l==="cached"?`CACHE ${u>=0?"+":""}${u}ms`:"LOCAL",y=l==="network"||l==="cached"?Sr.syncActiveClass:Sr.syncFallbackClass,I=f.split(" "),A=I[0],C=I[1]||"",w=typeof m=="function",j=`relative overflow-hidden flex flex-col items-start leading-none px-2.5 py-1 rounded-xl shrink-0 min-w-0 max-w-48 border border-white/10 before:pointer-events-none ${Sr.shellClass}${w?" cursor-pointer hover:border-cyan-400/30 hover:bg-slate-900/95 transition-colors":""}`,E=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"w-full flex items-baseline justify-between gap-2",children:[e.jsxs("div",{"data-testid":"normal-clock-text",className:"flex items-baseline gap-1.5",children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full shrink-0 ${Sr.accentDot}`}),e.jsx("span",{className:`text-[15px] font-semibold font-mono tracking-[0.06em] tabular-nums leading-none ${Sr.clockClass}`,children:A}),C&&e.jsx("span",{className:`text-[10px] font-bold font-mono leading-none ${Sr.clockClass} opacity-75`,children:C})]}),e.jsx("span",{className:`text-[9px] font-mono tracking-wide px-1 py-0.5 rounded border ${y}`,title:`Sync source: ${l}`,children:g})]}),e.jsx("div",{className:"flex items-center gap-1.5 w-full mt-0.5",children:e.jsx("span",{"data-testid":"normal-calendar-text",className:`text-[11px] font-mono tracking-[0.04em] ${Sr.calendarClass}`,children:b})})]});return w?e.jsx("button",{type:"button","data-testid":"clock-calendar-btn",onClick:m,"aria-label":"Open calendar and deadlines",title:`${b} · click for calendar & deadlines`,className:j,children:E}):e.jsx("div",{"data-testid":"clock-calendar-btn",role:"group","aria-label":"Live clock and calendar",title:`${b} · ${l==="network"||l==="cached"?"internet-synced":"local"} clock (last sync ${h}s ago)`,className:j,children:E})}function Vf({collabConnected:t,collabRoomId:r,collabPeerCount:n}){const s=!!t,a=Number(n||0);return e.jsxs("div",{"data-testid":"collab-status-pill",title:s?`Collab room ${r||"default"} · ${a} peer(s)`:"Collab offline",className:`hidden lg:inline-flex items-center gap-1.5 px-2 py-1 rounded-lg border text-[10px] font-mono transition-all ${s?"border-violet-400/30 bg-violet-500/10 text-violet-200":"border-white/10 bg-white/[0.03] text-slate-500"}`,children:[e.jsx(Rx,{size:11,className:"shrink-0 opacity-80"}),e.jsx("span",{children:s?"Collab":"Collab off"}),s&&e.jsx("span",{className:"text-violet-300/90 tabular-nums",children:a})]})}function Gf({model:t,setModel:r,stats:n,xpState:s,workflowId:a,onOpenPalette:o,onOpenSettings:c,onOpenAnalytics:l,onOpenEcosystem:u,onOpenMissionControl:x,onOpenFleetControl:p,onOpenApplianceConsole:d,onOpenAirGapOperations:m,onOpenInstitutionalCommand:f,onOpenDemoFlow:b,onOpenFieldLaunch:h,onToggleScratchpad:g,watchdogStatus:y,watchdogAlertCount:I,onOpenRuntimeAlerts:A,runtimeTier:C,connectionInfo:w,tokensRemaining:j,collabConnected:E,collabRoomId:N,collabPeerCount:_,accelStatus:S,applianceModeEnabled:R,airGapLocked:$,demoModeEnabled:U,feedbackDisabled:P,feedbackUrl:D,onOpenIssueAssist:z,tierId:F,tierLabel:J,canGoBack:ee,canGoForward:ie,onGoBack:ye,onGoForward:pe,onOpenTaskManager:K,onOpenCalendar:H,onOpenSupport:W,onTierUnlock:Z,omegaReport:ce,onRunOmega:fe,suppressDuplicateRuntimeStatus:me=!1}){const ke=String(C||"PREVIEW").toUpperCase(),Pe=ke==="OPERATOR"||String(F||"").toLowerCase()==="pro",_e=String(w&&w.provider||"ollama"),ne=String(w&&w.health||"unknown"),we=String(w&&w.model||t||"llama3"),De=ne==="online"||ne==="healthy",re=Array.from(new Set([String(t||"").trim(),"llama3","mistral","qwen","gpt-4.1-mini","gpt-4o-mini","llama-3.3-70b-versatile"].filter(Boolean))),{samples:ae,latencyMs:M,avgLatencyMs:V}=Nf({windowMs:5e3,pollMs:1e3});i.useMemo(()=>zf(ae,54,14),[ae]);const{temperature:G,setTemperature:te,theme:de,setTheme:L}=Xt(),{time:be,date:Q,dow:We,rawH:B,rawM:oe,rawS:xe,rawDay:Re,rawMonth:$e,rawYear:tt,syncSource:Ge,syncOffsetMs:En,syncedAt:Dt}=Pf(),In=Uf(_e);i.useEffect(()=>{typeof document>"u"||(document.documentElement.dataset.theme=String(de||"system"))},[de]);const er=`${_e}/${we} | ${M}ms live (${V}ms avg) | $${In.toFixed(2)}/1K tokens`,Dr=String(D||"https://github.com/Z3r0DayZion-install/NeuralShell/issues/new?template=bug_report.md&title=Feedback%3A+"),Ct=!P&&!!(window.api&&window.api.system&&typeof window.api.system.openExternal=="function"),Pn=i.useCallback(()=>{if(Ct){if(typeof z=="function"){z();return}window.api.system.openExternal(Dr).catch(()=>{})}},[Ct,z,Dr]),[mt,$t]=i.useState(!1),_t=i.useRef(null);return i.useEffect(()=>{if(!mt)return;const Ae=tr=>{_t.current&&!_t.current.contains(tr.target)&&$t(!1)};return document.addEventListener("pointerdown",Ae),()=>document.removeEventListener("pointerdown",Ae)},[mt]),e.jsxs("header",{"data-testid":"top-status-bar",className:"min-h-12 h-14 border-b border-indigo-500/[0.08] bg-shell-soft/97 backdrop-blur-xl flex items-center justify-between px-2.5 z-[140] shrink-0 gap-2",style:{boxShadow:"0 1px 0 rgba(107,122,255,0.09), 0 10px 36px rgba(0,0,0,0.34)"},children:[e.jsxs("div",{className:"flex gap-3 items-center min-w-0",children:[e.jsx("button",{type:"button","data-testid":"nav-back-btn",disabled:!ee,onClick:ye,className:`p-1.5 rounded-lg border transition-all ${ee?"border-orange-400/20 bg-orange-500/10 text-orange-300 hover:text-orange-200 hover:bg-orange-500/20 hover:border-orange-400/40":"border-transparent text-slate-600 cursor-default"}`,title:"Back (Mouse4 / Alt+Left)","aria-label":"Go back",children:e.jsx(Cx,{size:14})}),e.jsx("button",{type:"button","data-testid":"nav-forward-btn",disabled:!ie,onClick:pe,className:`p-1.5 rounded-lg border transition-all ${ie?"border-orange-400/20 bg-orange-500/10 text-orange-300 hover:text-orange-200 hover:bg-orange-500/20 hover:border-orange-400/40":"border-transparent text-slate-600 cursor-default"}`,title:"Forward (Mouse5 / Alt+Right)","aria-label":"Go forward",children:e.jsx(_x,{size:14})}),e.jsxs("div",{"data-testid":"trust-indicator",className:"flex flex-col shrink-0",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.3em] font-black text-gradient",style:{backgroundImage:"linear-gradient(90deg, #8b5cf6, #d946ef, #06b6d4, #8b5cf6)",WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent"},children:"ProofForge"}),e.jsxs("div",{className:"text-sm font-bold text-slate-100 flex items-center gap-2 tracking-tight",children:[e.jsxs("span",{className:"text-[12px] font-mono text-slate-400 leading-none",title:`Version ${xd}`,children:["v",xd]}),De&&e.jsx("span",{className:"h-2 w-2 rounded-full bg-emerald-400 shadow-[0_0_8px_rgba(74,222,128,0.45)]",title:"Bridge connected","aria-hidden":"true"}),e.jsx(kp,{report:ce,compact:!0,onClick:typeof fe=="function"?fe:void 0,testId:"header-omega-posture-badge"}),e.jsx(Tf,{tierId:F,tierLabel:J,runtimeTier:ke,isOperator:Pe,onUnlock:Z})]})]})]}),e.jsxs("div",{className:"hidden xl:flex items-center gap-2 px-3 py-1 bg-black/30 rounded-full border border-violet-500/10 text-[10px] font-mono text-slate-400 tracking-wide shrink-0",children:[e.jsx("span",{className:"text-slate-500",children:"workflow"}),e.jsx("span",{className:"text-violet-400/60",children:"="}),a?e.jsxs("span",{className:"text-green-300 font-semibold",children:['"',a,'"']}):e.jsx("span",{className:"text-slate-600 italic",children:"null"})]}),e.jsxs("div",{className:"flex gap-2 items-center shrink-0 ml-auto",children:[e.jsx(Kf,{rawH:B,rawM:oe,rawS:xe,rawDay:Re,rawMonth:$e,rawYear:tt,dow:We,syncSource:Ge,syncOffsetMs:En,syncedAt:Dt,onOpenCalendar:H}),e.jsx(Vf,{collabConnected:E,collabRoomId:N,collabPeerCount:_}),e.jsx("select",{value:t,"aria-label":"Active model","data-testid":"header-model-select",onChange:Ae=>{Promise.resolve(r(Ae.target.value)).catch(()=>{})},className:"bg-violet-500/5 border border-violet-400/15 rounded-lg px-2.5 py-1 text-[11px] text-sky-300 outline-none focus:border-violet-400/40 transition-all font-mono hover:bg-violet-500/10 cursor-pointer appearance-none min-w-20 shadow-inner",children:re.map(Ae=>e.jsx("option",{value:Ae,children:Ae},Ae))}),!me&&e.jsxs("div",{"data-testid":"presence-pill",title:er,className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-lg border text-[10px] font-mono transition-all duration-300 ${ne==="online"||ne==="healthy"?"border-green-400/25 bg-green-500/8 text-green-200 shadow-[0_0_12px_rgba(74,222,128,0.1)]":ne==="offline"?"border-red-400/30 bg-red-500/10 text-red-300":"border-yellow-400/20 bg-yellow-500/8 text-yellow-200"}`,children:[e.jsx("span",{className:"text-green-300",children:we}),e.jsx("span",{className:"text-slate-600",children:"|"}),e.jsxs("span",{className:"text-yellow-300",children:[M,e.jsx("span",{className:"text-slate-500",children:"ms"})]})]}),!me&&e.jsx($f,{status:y,alertCount:I,onClick:A}),e.jsx("button",{"data-testid":"command-palette-btn","aria-label":"Open command palette (Ctrl+K)",onClick:o,className:"px-3 py-1.5 rounded-lg border border-fuchsia-400/30 bg-fuchsia-500/10 text-[11px] font-bold text-fuchsia-300 uppercase tracking-wider hover:bg-fuchsia-400/20 hover:border-fuchsia-400/50 transition-all animate-glow-pulse active:scale-95 alive-hover",children:"EXEC"}),typeof W=="function"&&e.jsx("button",{type:"button","data-testid":"support-open-btn",onClick:W,className:"px-2.5 py-1.5 rounded-lg border border-sky-400/25 bg-sky-500/10 text-[11px] font-bold text-sky-200 uppercase tracking-wider hover:bg-sky-400/15 transition-all",title:"Open operator support (Discord + Support Ops)",children:"Support"}),e.jsxs("div",{className:"relative",ref:_t,children:[e.jsxs("button",{type:"button","data-testid":"more-menu-btn",onClick:()=>$t(Ae=>!Ae),className:`inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg border text-[11px] font-mono transition-all ${mt?"border-violet-400/40 bg-violet-500/15 text-violet-100":"border-white/10 bg-white/[0.04] text-slate-300 hover:bg-white/10 hover:border-violet-400/20"}`,title:"More panels & tools",children:["More ",e.jsx(Ax,{size:12,className:`transition-transform ${mt?"rotate-180":""}`})]}),mt&&e.jsxs("div",{className:"absolute right-0 top-full mt-1 w-64 rounded-xl border border-violet-500/15 bg-shell-mid/98 backdrop-blur-lg shadow-[0_12px_40px_rgba(0,0,0,0.7)] py-1.5 z-50 max-h-[70vh] overflow-y-auto animate-fade-up",children:[e.jsx("div",{className:"px-3 py-1.5 text-[9px] font-mono uppercase tracking-widest text-slate-600",children:"// infrastructure"}),[{label:"Analytics",testId:"analytics-open-btn",onClick:l,color:"text-yellow-300"},{label:"Ecosystem",testId:"ecosystem-open-btn",onClick:u,color:"text-sky-300"},{label:"Mission Control",testId:"mission-control-open-btn",onClick:x,color:"text-violet-300"},{label:"Fleet Control",testId:"fleet-control-open-btn",onClick:p,color:"text-blue-300"},{label:"Institutional",testId:"institutional-command-open-btn",onClick:f,color:"text-indigo-300"}].filter(Ae=>typeof Ae.onClick=="function").map(Ae=>e.jsxs("button",{type:"button","data-testid":Ae.testId,onClick:()=>{Ae.onClick(),$t(!1)},className:`w-full text-left px-4 py-2 text-[12px] font-mono hover:bg-white/8 transition-colors flex items-center gap-2 ${Ae.color}`,children:[e.jsx("span",{className:"text-slate-600 text-[10px]",children:"→"})," ",Ae.label]},Ae.testId)),(b||h)&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-white/5 my-1"}),e.jsx("div",{className:"px-3 py-1.5 text-[9px] font-mono uppercase tracking-widest text-slate-600",children:"// launch"}),[...b?[{label:"Demo Flow",testId:"demo-flow-open-btn",onClick:b,color:"text-green-300"}]:[],...h?[{label:"Field Launch",testId:"field-launch-open-btn",onClick:h,color:"text-orange-300"}]:[]].map(Ae=>e.jsxs("button",{type:"button","data-testid":Ae.testId,onClick:()=>{Ae.onClick(),$t(!1)},className:`w-full text-left px-4 py-2 text-[12px] font-mono hover:bg-white/8 transition-colors flex items-center gap-2 ${Ae.color}`,children:[e.jsx("span",{className:"text-slate-600 text-[10px]",children:"→"})," ",Ae.label]},Ae.testId))]}),e.jsx("div",{className:"border-t border-white/5 my-1"}),e.jsx("div",{className:"px-3 py-1.5 text-[9px] font-mono uppercase tracking-widest text-slate-600",children:"// tools"}),[{label:"Operator Inbox",testId:"task-manager-open-btn",onClick:K,color:"text-rose-300"},{label:"Workpad",testId:"scratchpad-open-btn",onClick:g,color:"text-amber-300"},{label:"Feedback",testId:"feedback-btn",onClick:Ct?Pn:void 0,color:"text-teal-300"}].filter(Ae=>typeof Ae.onClick=="function").map(Ae=>e.jsxs("button",{type:"button","data-testid":Ae.testId,onClick:()=>{Ae.onClick(),$t(!1)},className:`w-full text-left px-4 py-2 text-[12px] font-mono hover:bg-white/8 transition-colors flex items-center gap-2 ${Ae.color}`,children:[e.jsx("span",{className:"text-slate-600 text-[10px]",children:"→"})," ",Ae.label]},Ae.testId))]})]}),e.jsx("button",{type:"button","data-testid":"theme-toggle-btn",onClick:()=>{L(de==="system"?"dark":de==="dark"?"light":"system")},className:"p-1.5 rounded-lg border border-yellow-400/15 bg-yellow-500/5 text-yellow-300/80 hover:text-yellow-200 hover:bg-yellow-500/15 hover:border-yellow-400/30 transition-all",title:`Theme: ${de}`,children:de==="dark"?e.jsx(Ex,{size:14}):de==="light"?e.jsx(Ix,{size:14}):e.jsx(Px,{size:14})}),e.jsx("button",{"data-testid":"settings-open-btn","aria-label":"Open settings",onClick:c,className:"p-1.5 rounded-lg border border-slate-400/15 bg-slate-500/5 text-slate-400 hover:text-slate-100 hover:bg-slate-500/15 hover:border-slate-400/30 transition-all group alive-hover",title:"Settings (Ctrl+,)",children:e.jsx(ul,{size:14,className:"group-hover:rotate-90 transition-transform duration-500"})}),e.jsx(Lf,{enabled:R,onOpen:d}),e.jsx(Bf,{locked:$,onOpen:m}),e.jsx(Ff,{enabled:U,onOpen:b})]})]})}function Jf(t){const r=String(t||"").toLowerCase();return r.includes("127.0.0.1")||r.includes("localhost")||r.includes("::1")||r.includes("0.0.0.0")}function Np({connectionInfo:t={}}={}){const r=String(t.baseUrl||""),n=String(t.health||"unknown").toLowerCase(),s=String(t.provider||"ollama"),a=t.model?String(t.model):null,o=!!t.allowRemoteBridge,c=Jf(r)||s==="ollama"&&!r,l=c?"local":r?"hosted":"unknown",u=n==="healthy"||n==="online",p=c?u?"connected":n==="degraded"?"degraded":n==="unknown"?"not-tested":"unreachable":null,d=o?l==="hosted"?u?"connected":"not-tested":null:"blocked-by-policy";let m=null;const f=[];return l==="local"?p==="unreachable"?(m=`Local provider not responding at ${r||"http://127.0.0.1:11434"}. Check that ${s==="ollama"?"Ollama is running":`${s} is running`} and model ${a||"llama3"} is available.`,f.push({id:"test-connection",label:"Test local connection"})):p==="degraded"?(m=`Local provider is degraded at ${r||"http://127.0.0.1:11434"}.`,f.push({id:"test-connection",label:"Test connection"})):p==="not-tested"&&f.push({id:"test-connection",label:"Test local connection"}):l==="hosted"&&(d==="blocked-by-policy"?(m=`${s} is blocked by Offline Mode. Hosted providers are disabled.`,f.push({id:"enable-hosted",label:"Enable hosted providers"}),f.push({id:"switch-local",label:"Switch to local Ollama"})):d==="not-tested"&&(m=`${s} connection has not been verified yet.`,f.push({id:"test-connection",label:"Test connection"}))),{selectedRoute:l,localStatus:p,hostedStatus:d,currentProblem:m,nextActions:f}}function Hl({connectionInfo:t={},watchdogStatus:r="running",incidentCount:n=0,setupBlocked:s=!1}={}){const a=String(t.health||"unknown").toLowerCase(),o=a==="healthy"||a==="online",c=a==="degraded",l=String(t.provider||"ollama"),u=t.model?String(t.model):null,x=Math.max(0,Number(n)||0),p=String(r||"unknown"),d=["fatal","degraded"].includes(p.toLowerCase()),m=o?"connected":c?"degraded":"offline",{selectedRoute:f,localStatus:b,hostedStatus:h}=Np({connectionInfo:t}),g={selectedRoute:f,localStatus:b,hostedStatus:h};return s?{severity:"blocked",summary:"Setup blocked",primaryAction:{id:"fix-setup",label:"Fix Setup"},bridge:m,provider:l,model:u,runtimeLabel:p,incidentCount:x,...g}:!o&&!c&&!(f==="local"&&b==="connected")?{severity:"offline",summary:h==="blocked-by-policy"?"Hosted blocked · Local not tested":"Bridge offline",primaryAction:{id:"run-checks",label:"Run Checks"},bridge:m,provider:l,model:u,runtimeLabel:p,incidentCount:x,...g}:x>0||d||c?{severity:"degraded",summary:x>0?`${x} incident${x===1?"":"s"}`:c?"Bridge degraded":"Attention required",primaryAction:{id:"inspect",label:"Inspect Issue"},bridge:m,provider:l,model:u,runtimeLabel:p,incidentCount:x,...g}:{severity:"healthy",summary:"System ready",primaryAction:{id:"export",label:"Export Evidence"},bridge:m,provider:l,model:u,runtimeLabel:p,incidentCount:x,...g}}function Wl(t,{sessionDegradedDismissed:r=!1,acknowledgedReady:n=!1}={}){const s=String(t&&t.severity?t.severity:"offline").toLowerCase();return s==="blocked"?{verdict:"blocked",title:"Blocked",message:"ProofForge needs setup before operator use.",primaryAction:{id:"fix-setup",label:"Fix Setup"},secondaryAction:{id:"open-settings",label:"Open Settings"},shouldPrompt:!0,trustSeverity:s}:s==="offline"?{verdict:"blocked",title:"Blocked",message:"ProofForge needs setup before operator use.",primaryAction:{id:"fix-setup",label:"Fix Setup"},secondaryAction:{id:"open-settings",label:"Open Settings"},shouldPrompt:!0,trustSeverity:s}:s==="degraded"?{verdict:"degraded",title:"Degraded",message:"ProofForge can run, but one or more operator systems need attention.",primaryAction:{id:"inspect",label:"Inspect Issue"},secondaryAction:{id:"continue",label:"Continue Anyway"},shouldPrompt:!r,trustSeverity:s}:{verdict:"ready",title:"Ready",message:"ProofForge is ready for operator use.",primaryAction:{id:"start",label:"Start Operating"},secondaryAction:{id:"export",label:"Export Evidence"},shouldPrompt:!n,trustSeverity:s}}const fd={healthy:{border:"border-emerald-400/20",bg:"bg-emerald-500/[0.04]",dot:"bg-emerald-400",text:"text-emerald-200",action:"border-emerald-400/30 bg-emerald-500/10 text-emerald-100 hover:bg-emerald-500/20"},degraded:{border:"border-amber-400/25",bg:"bg-amber-500/[0.05]",dot:"bg-amber-400",text:"text-amber-100",action:"border-amber-400/30 bg-amber-500/10 text-amber-100 hover:bg-amber-500/20"},offline:{border:"border-slate-500/30",bg:"bg-slate-900/40",dot:"bg-slate-500",text:"text-slate-300",action:"border-sky-400/30 bg-sky-500/10 text-sky-100 hover:bg-sky-500/20"},blocked:{border:"border-rose-400/30",bg:"bg-rose-500/[0.06]",dot:"bg-rose-400",text:"text-rose-100",action:"border-rose-400/30 bg-rose-500/10 text-rose-100 hover:bg-rose-500/20"}};function qf(t){return t==="connected"?"Connected":t==="degraded"?"Degraded":"Offline"}function Yf(t){const r=String(t||"unknown").toLowerCase();return r==="running"?"Running":r==="fatal"?"Fatal":r==="degraded"?"Degraded":r.charAt(0).toUpperCase()+r.slice(1)}function Zf({connectionInfo:t,watchdogStatus:r,incidentCount:n=0,setupBlocked:s=!1,sessionDegradedDismissed:a=!1,acknowledgedReady:o=!1,exportAvailable:c=!1,exportBusy:l=!1,onExportEvidence:u,onInspectIssue:x,onFixSetup:p,onRunChecks:d,onToggleInspector:m,inspectorOpen:f=!1,layoutMode:b="expanded"}){const h=i.useMemo(()=>Hl({connectionInfo:t,watchdogStatus:r,incidentCount:n,setupBlocked:s}),[t,r,n,s]),g=i.useMemo(()=>Wl(h,{sessionDegradedDismissed:a,acknowledgedReady:o}),[h,a,o]),y=fd[h.severity]||fd.offline,I=()=>{const{id:w}=h.primaryAction;if(w==="export"&&typeof u=="function"){u();return}if(w==="inspect"&&typeof x=="function"){x();return}if(w==="fix-setup"&&typeof p=="function"){p();return}w==="run-checks"&&typeof d=="function"&&d()},A=h.primaryAction.id==="export"&&!c,C=A?"Export Evidence — unavailable in this shell":h.primaryAction.label;return e.jsxs("div",{"data-testid":"trust-strip","data-severity":h.severity,role:"status","aria-live":"polite",className:`px-3 py-1.5 border-b flex items-center justify-between gap-3 shrink-0 ${y.border} ${y.bg}`,children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-wrap",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 shrink-0",children:[e.jsx("span",{"data-testid":"readiness-verdict-badge","data-verdict":g.verdict,className:"px-1.5 py-0.5 rounded border border-white/10 text-[9px] font-bold uppercase tracking-[0.14em] text-slate-300",children:g.verdict}),e.jsx("span",{className:`h-2 w-2 rounded-full shrink-0 ${y.dot}`,"aria-hidden":"true"}),e.jsx("span",{className:`text-[11px] font-semibold tracking-wide ${y.text}`,children:h.summary})]}),e.jsx("span",{className:"hidden sm:inline text-[10px] font-mono text-slate-500",children:"·"}),e.jsx("span",{"data-testid":"trust-strip-bridge",className:"text-[10px] font-mono text-slate-400",children:h.selectedRoute==="local"?e.jsxs(e.Fragment,{children:["Local ",e.jsx("span",{className:h.localStatus==="connected"?"text-emerald-200":h.localStatus==="degraded"?"text-amber-200":h.localStatus==="unreachable"?"text-rose-300":"text-slate-400",children:h.localStatus==="connected"?"Connected":h.localStatus==="degraded"?"Degraded":h.localStatus==="unreachable"?"Not responding":"Selected"})]}):h.selectedRoute==="hosted"&&h.hostedStatus==="blocked-by-policy"?e.jsxs(e.Fragment,{children:["Hosted ",e.jsx("span",{className:"text-amber-200",children:"Blocked"})]}):e.jsxs(e.Fragment,{children:["Bridge ",e.jsx("span",{className:"text-slate-200",children:qf(h.bridge)})]})}),e.jsx("span",{className:"hidden md:inline text-[10px] font-mono text-slate-500",children:"·"}),e.jsxs("span",{"data-testid":"trust-strip-model",className:"hidden md:inline text-[10px] font-mono text-slate-400 truncate max-w-[12rem]",children:[h.provider,"/",h.model||"—"]}),e.jsx("span",{className:"hidden lg:inline text-[10px] font-mono text-slate-500",children:"·"}),e.jsxs("span",{"data-testid":"trust-strip-runtime",className:"hidden lg:inline text-[10px] font-mono text-slate-400",children:["Runtime ",e.jsx("span",{className:"text-slate-200",children:Yf(h.runtimeLabel)})]}),h.incidentCount>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] font-mono text-slate-500",children:"·"}),e.jsxs("span",{"data-testid":"trust-strip-incidents",className:"text-[10px] font-mono text-amber-200",children:[h.incidentCount," incident",h.incidentCount===1?"":"s"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[typeof m=="function"&&b!=="expanded"&&e.jsx("button",{type:"button","data-testid":"trust-strip-inspector-toggle",onClick:m,className:`px-2 py-1 rounded-lg border text-[10px] font-mono transition-colors ${f?"border-cyan-400/35 bg-cyan-500/10 text-cyan-100":"border-white/10 bg-white/[0.03] text-slate-400 hover:text-slate-200"}`,title:"Toggle inspector panel",children:"Inspector"}),e.jsx("button",{type:"button","data-testid":h.primaryAction.id==="run-checks"?"profile-bar-verify-btn":"trust-strip-primary-action","data-action-id":h.primaryAction.id,disabled:A||l,onClick:I,className:`px-2.5 py-1 rounded-lg border text-[10px] font-bold uppercase tracking-wider transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${y.action}`,children:l?"Exporting…":C})]})]})}const Xf="modulepreload",Qf=function(t,r){return new URL(t,r).href},bd={},Kl=function(r,n,s){let a=Promise.resolve();if(n&&n.length>0){const c=document.getElementsByTagName("link"),l=document.querySelector("meta[property=csp-nonce]"),u=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));a=Promise.allSettled(n.map(x=>{if(x=Qf(x,s),x in bd)return;bd[x]=!0;const p=x.endsWith(".css"),d=p?'[rel="stylesheet"]':"";if(!!s)for(let b=c.length-1;b>=0;b--){const h=c[b];if(h.href===x&&(!p||h.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${x}"]${d}`))return;const f=document.createElement("link");if(f.rel=p?"stylesheet":Xf,p||(f.as="script"),f.crossOrigin="",f.href=x,u&&f.setAttribute("nonce",u),document.head.appendChild(f),p)return new Promise((b,h)=>{f.addEventListener("load",b),f.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${x}`)))})}))}function o(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&o(l.reason);return r().catch(o)})},eb=i.lazy(()=>Kl(()=>import("./OnboardingProgressRail-D4ADuSst.js"),__vite__mapDeps([0,1,2,3]),import.meta.url)),tb=[{id:"hud",label:"HUD",title:"Minimum rail width — maximum chat canvas (heads-up)"},{id:"compact",label:"Dense",title:"Tighter side columns than standard"},{id:"balanced",label:"Standard",title:"Default ProofForge rail widths"},{id:"wide",label:"Spacious",title:"Wider rails for dense panels and previews"}],rb=i.memo(function({activeRailPresetId:r,onApplyRailPreset:n,onResetRailWidths:s,showInlineThreadRail:a,threadRailCollapsed:o,onToggleThreadRailCollapse:c,showInlineWorkbenchRail:l,workbenchRailCollapsed:u,onToggleWorkbenchRailCollapse:x,canOpenThreadRailOverlay:p,leftRailOverlayOpen:d,onToggleLeftRailOverlay:m,canOpenWorkbenchRailOverlay:f,rightRailOverlayOpen:b,onToggleRightRailOverlay:h,firstBootSteps:g,firstBootProgress:y,onReopenFirstBoot:I,onResetFirstBoot:A,onOpenCustomize:C}){return e.jsxs("div",{"data-testid":"layout-control-bar",className:"px-3 py-1 border-b border-white/[0.03] bg-white/[0.01] flex items-center justify-between gap-2 z-10",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 flex-wrap",children:[e.jsx("div",{className:"inline-flex items-center rounded border border-white/[0.06] overflow-hidden shrink-0",role:"toolbar","aria-label":"Side column width presets",children:tb.map((w,j)=>e.jsx("button",{type:"button","data-testid":`layout-preset-${w.id}-btn`,title:w.title,"aria-pressed":r===w.id,onClick:()=>n(w.id),className:`px-2 py-1 text-[11px] font-semibold tracking-wide transition-colors ${r===w.id?"bg-violet-500/20 text-violet-200":"text-slate-500 hover:bg-white/[0.04] hover:text-slate-300"} ${j>0?"border-l border-white/[0.06]":""}`,children:w.label},w.id))}),e.jsx("button",{type:"button","data-testid":"layout-reset-panels-btn",onClick:s,className:"text-[11px] font-mono text-slate-400 hover:text-slate-400 px-1.5 py-1 rounded hover:bg-white/[0.04] transition-colors",children:"Reset"}),typeof C=="function"&&e.jsx("button",{type:"button","data-testid":"layout-customize-btn",onClick:C,className:"text-[11px] font-mono text-violet-300/90 hover:text-violet-200 px-1.5 py-1 rounded hover:bg-violet-500/10 transition-colors",title:"Open Adaptive Layout Engine — presets and panel toggles",children:"Customize"}),e.jsx("span",{className:"w-px h-3 bg-white/[0.06]"}),a&&e.jsx("button",{type:"button","data-testid":"layout-toggle-thread-inline-btn",onClick:c,className:`text-[11px] font-mono px-1.5 py-1 rounded transition-colors ${o?"text-cyan-400/70 hover:text-cyan-300":"text-slate-500 hover:text-slate-300 hover:bg-white/[0.04]"}`,children:"Flows"}),l&&e.jsx("button",{type:"button","data-testid":"layout-toggle-workbench-inline-btn",onClick:x,className:`text-[11px] font-mono px-1.5 py-1 rounded transition-colors ${u?"text-cyan-400/70 hover:text-cyan-300":"text-slate-500 hover:text-slate-300 hover:bg-white/[0.04]"}`,children:"Bench"}),p&&e.jsx("button",{type:"button","data-testid":"layout-toggle-workflows-btn",onClick:m,className:`text-[11px] font-mono px-1.5 py-1 rounded transition-colors ${d?"text-cyan-300 bg-cyan-500/10":"text-slate-500 hover:text-slate-300 hover:bg-white/[0.04]"}`,children:"Flows"}),f&&e.jsx("button",{type:"button","data-testid":"layout-toggle-workbench-btn",onClick:h,className:`text-[11px] font-mono px-1.5 py-1 rounded transition-colors ${b?"text-cyan-300 bg-cyan-500/10":"text-slate-500 hover:text-slate-300 hover:bg-white/[0.04]"}`,children:"Bench"})]}),e.jsx(i.Suspense,{fallback:null,children:e.jsx(eb,{steps:g,progress:y,onReopen:I,onReset:A})})]})}),nb=80,sb=200,ab=12,hd=120,gd=180;function ob(t){const r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return r?{r:parseInt(r[1],16),g:parseInt(r[2],16),b:parseInt(r[3],16)}:{r:139,g:92,b:246}}function yd(t,r,n,s=!1){const a=Math.random()*Math.PI*2,o=s?1.5+Math.random()*3:.15+Math.random()*.45;return{x:s?t/2:Math.random()*t,y:s?r/2:Math.random()*r,vx:Math.cos(a)*o,vy:Math.sin(a)*o,radius:s?1+Math.random()*2.5:.8+Math.random()*2,opacity:s?.6+Math.random()*.4:.08+Math.random()*.2,color:n,life:s?40+Math.random()*60:1/0,maxLife:s?40+Math.random()*60:1/0,pulse:Math.random()*Math.PI*2,pulseSpeed:.02+Math.random()*.03}}const ib=i.memo(function({moodColors:r,isThinking:n,isTyping:s,enabled:a=!0}){const o=O.useRef(null),c=O.useRef([]),l=O.useRef(null),u=O.useRef({x:-1e3,y:-1e3}),x=O.useRef(0),[p,d]=O.useState(a),m=(r==null?void 0:r.dot)||(r==null?void 0:r.primary)||"#8b5cf6",f=ob(m),b=O.useCallback((g,y)=>{const I=[];for(let A=0;A{const C=c.current;if(!(C.length>sb))for(let w=0;w{d(a)},[a]),O.useEffect(()=>{if(!p)return;const g=o.current;if(!g)return;const y=g.getContext("2d");if(!y)return;const I=()=>{const w=window.devicePixelRatio||1,j=g.parentElement.getBoundingClientRect();g.width=j.width*w,g.height=j.height*w,g.style.width=j.width+"px",g.style.height=j.height+"px",y.setTransform(w,0,0,w,0,0),c.current.length===0&&b(j.width,j.height)};I(),window.addEventListener("resize",I);const A=w=>{const j=g.getBoundingClientRect();u.current={x:w.clientX-j.left,y:w.clientY-j.top}};g.addEventListener("mousemove",A);const C=()=>{x.current++;const w=g.width/(window.devicePixelRatio||1),j=g.height/(window.devicePixelRatio||1),E=u.current.x,N=u.current.y,_=c.current,$=(n?2.5:1)*(s?1.8:1);if(y.clearRect(0,0,w,j),n){const U=w/2,P=j/2,D=Math.min(w,j)*.3,z=y.createRadialGradient(U,P,0,U,P,D);z.addColorStop(0,`rgba(${f.r},${f.g},${f.b},0.04)`),z.addColorStop(1,"transparent"),y.fillStyle=z,y.beginPath(),y.arc(U,P,D,0,Math.PI*2),y.fill()}for(let U=_.length-1;U>=0;U--){const P=_[U];if(P.life!==1/0){if(P.life--,P.life<=0){_.splice(U,1);continue}P.opacity=P.life/P.maxLife*.7}P.pulse+=P.pulseSpeed;const D=1+Math.sin(P.pulse)*.2,z=P.x-E,F=P.y-N,J=Math.sqrt(z*z+F*F);if(J0){const ie=(1-J/gd)*.5;P.vx+=z/J*ie,P.vy+=F/J*ie}if(n){const ie=w/2,ye=j/2,pe=ie-P.x,K=ye-P.y,H=Math.sqrt(pe*pe+K*K);H>30&&(P.vx+=-K/H*.03+pe/H*.02,P.vy+=pe/H*.03+K/H*.02)}P.vx*=.98,P.vy*=.98,P.x+=P.vx*$,P.y+=P.vy*$,P.x<-10&&(P.x=w+10),P.x>w+10&&(P.x=-10),P.y<-10&&(P.y=j+10),P.y>j+10&&(P.y=-10);const ee=P.radius*D;y.beginPath(),y.arc(P.x,P.y,ee,0,Math.PI*2),y.fillStyle=`rgba(${P.color.r},${P.color.g},${P.color.b},${P.opacity})`,y.fill(),ee>1.5&&(y.beginPath(),y.arc(P.x,P.y,ee*2.5,0,Math.PI*2),y.fillStyle=`rgba(${P.color.r},${P.color.g},${P.color.b},${P.opacity*.15})`,y.fill())}for(let U=0;U<_.length;U++)for(let P=U+1;P<_.length;P++){const D=_[U],z=_[P],F=D.x-z.x,J=D.y-z.y,ee=Math.sqrt(F*F+J*J);if(ee{window.cancelAnimationFrame(l.current),window.removeEventListener("resize",I),g.removeEventListener("mousemove",A)}},[p,f.r,f.g,f.b,n,s,b,h]),p?e.jsx("canvas",{ref:o,className:"absolute inset-0 pointer-events-auto z-0",style:{opacity:.7,mixBlendMode:"screen"}}):null}),lb=i.memo(function({moodColors:r,isThinking:n,isTyping:s,particlesEnabled:a}){return e.jsxs(e.Fragment,{children:[e.jsx(ib,{moodColors:r,isThinking:n,isTyping:s,enabled:a}),e.jsx("div",{className:"absolute top-0 left-1/2 -translate-x-1/2 pointer-events-none animate-mood-aurora",style:{width:800,height:340,background:`radial-gradient(ellipse 100% 100% at 50% 0%, ${r.dot}26 0%, ${r.dot}0a 50%, transparent 78%)`,filter:"blur(48px)",transition:"background 1.8s cubic-bezier(0.4,0,0.2,1)"}}),e.jsx("div",{className:"absolute top-0 left-1/2 -translate-x-1/2 pointer-events-none animate-mood-aurora-2",style:{width:440,height:200,background:`radial-gradient(ellipse 100% 100% at 50% 0%, ${r.glow||r.dot}18 0%, transparent 70%)`,filter:"blur(32px)",transition:"background 2.2s cubic-bezier(0.4,0,0.2,1)"}}),e.jsx("div",{className:"absolute inset-0 pointer-events-none animate-mood-edge rounded-none z-[1]",style:{boxShadow:`inset 0 0 0 1px ${r.dot}1a, inset 0 0 80px ${r.dot}07`,transition:"box-shadow 1.8s cubic-bezier(0.4,0,0.2,1)"}})]})}),cb="NeuralShell_QuickStart";function Sp({sessions:t,workflowId:r,onSelectSession:n,onCreateSession:s,onSaveSession:a,onRetrySave:o,onLockSession:c,saveStatus:l,isSessionUnlocked:u,sessionHydrationStatus:x,autoLockOnBlur:p,onToggleAutoLock:d,auditOnly:m,onUpgradeToPro:f,widthPx:b=288}){const h=(...j)=>j.filter(Boolean).join(" "),[g,y]=O.useState(""),I=Number.isFinite(Number(b))?Math.max(220,Math.round(Number(b))):288,A=O.useMemo(()=>{if(!l||!l.at)return"";const j=new Date(l.at);return Number.isNaN(j.getTime())?"":j.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})},[l]),C=O.useMemo(()=>(t||[]).filter(j=>String(j||"").toLowerCase().includes(g.toLowerCase())),[t,g]),w=O.useMemo(()=>!l||l.state==="idle"?x==="loading"?"Loading selected session...":x==="locked"?"Session locked. Unlock to continue.":"Ready":l.state==="saving"?String(l.detail||"Saving..."):l.state==="locked"?String(l.detail||"Session locked."):A?`${String(l.detail||"").trim()} (${A})`:String(l.detail||"").trim()||(l.state==="error"?"Save failed.":"Saved."),[l,x,A]);return e.jsxs("aside",{"data-testid":"thread-rail",className:"shrink-0 border-r border-white/5 flex flex-col bg-slate-950/50 backdrop-blur-xl z-20 overflow-hidden",style:{width:`${I}px`},children:[e.jsxs("header",{className:"p-6 pb-4 border-b border-white/5",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] font-black uppercase tracking-[0.4em] text-cyan-500/60 mb-1",children:"Workflow_Nav"}),e.jsx("h2",{className:"text-sm font-bold tracking-tight text-slate-100 uppercase tracking-[0.1em]",children:"Active_Workflows"})]}),e.jsx("button",{"data-testid":"new-thread-btn",onClick:s,disabled:!!m,title:"New Thread",className:h("h-8 w-8 flex items-center justify-center rounded-lg border transition-all",m?"border-white/10 text-slate-600 cursor-not-allowed":"border-white/10 hover:border-cyan-400/40 hover:bg-cyan-400/10 text-slate-400 hover:text-cyan-300"),children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{type:"text",value:g,onChange:j=>y(j.target.value),placeholder:"Search Workflows...",className:"w-full bg-black/40 border border-white/5 rounded-lg px-3 py-2 text-[11px] font-mono text-slate-300 placeholder-slate-600 outline-none focus:border-cyan-400/30 transition-all"})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-1.5 custom-scrollbar",children:[t.length>0&&e.jsx("div",{className:"text-[8px] font-black uppercase tracking-widest text-slate-500 mb-3 px-1",children:"Current & Recent"}),t.length===0?e.jsxs("div",{className:"text-center p-6 mt-10",children:[e.jsx("div",{className:"text-3xl text-slate-700/30 mb-3 font-mono",children:"/"}),e.jsx("div",{className:"text-[10px] text-slate-500 uppercase tracking-[0.2em] font-bold mb-1",children:"History Empty"}),e.jsx("div",{className:"text-[9px] text-slate-600 font-mono",children:"No active workflow history"})]}):C.map((j,E)=>{const N=j!==cb&&!u(j);return e.jsxs("button",{"data-testid":`session-item-${j}`,onClick:()=>n(j),className:h("w-full text-left p-3.5 rounded-xl transition-all duration-200 group relative",r===j?"bg-cyan-500/[0.07] border border-cyan-400/30 shadow-[0_0_20px_rgba(34,211,238,0.03)]":"hover:bg-white/[0.04] border border-transparent"),children:[r===j&&e.jsx("div",{className:"absolute left-0 top-[20%] bottom-[20%] w-1 bg-cyan-400/80 rounded-r-full shadow-glow-cyan"}),e.jsxs("div",{className:"flex items-center justify-between mb-1.5 pl-1.5",children:[e.jsx("span",{className:h("text-[11px] font-bold truncate tracking-tight transition-colors",r===j?"text-cyan-100":"text-slate-300 group-hover:text-slate-200"),children:j}),N?e.jsx("span",{"data-testid":`session-lock-${j}`,className:"text-[8px] font-mono text-amber-300 uppercase tracking-widest px-1.5 py-0.5 bg-amber-400/10 rounded border border-amber-400/20",children:"LOCKED"}):E===0&&r!==j&&e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-slate-500"})]}),e.jsxs("div",{className:"flex items-center justify-between pl-1.5",children:[e.jsx("div",{className:h("text-[9px] truncate font-mono tracking-tighter transition-colors",r===j?"text-cyan-400/60":"text-slate-500/60"),children:N?"Unlock required":"/var/log/active"}),r===j&&e.jsx("span",{className:"text-[8px] font-mono text-cyan-400 font-bold uppercase tracking-widest px-1.5 py-0.5 bg-cyan-400/10 rounded",children:"LIVE"})]})]},j)})]}),e.jsxs("footer",{className:"p-4 border-t border-white/5 bg-black/20 flex flex-col gap-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx("button",{"data-testid":"save-active-session-btn",onClick:a,disabled:!!m,className:h("w-full py-2 rounded-lg border text-[9px] font-bold uppercase tracking-[0.1em] transition-all",m?"border-white/[0.08] text-slate-600 cursor-not-allowed":"border-white/[0.08] hover:bg-white/[0.05] text-slate-300"),children:"Save Active"}),e.jsx("button",{"data-testid":"lock-active-session-btn",onClick:c,disabled:!!m,className:h("w-full py-2 rounded-lg border text-[9px] font-bold uppercase tracking-[0.1em] transition-all",m?"border-amber-400/20 text-amber-400/40 cursor-not-allowed":"border-amber-400/30 hover:bg-amber-400/10 text-amber-200"),children:"Lock Active"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx("button",{"data-testid":"retry-save-session-btn",onClick:o,disabled:!!m||l&&l.state!=="error",className:h("w-full py-2 rounded-lg border text-[9px] font-bold uppercase tracking-[0.1em] transition-all",!m&&l&&l.state==="error"?"border-rose-300/30 text-rose-200 hover:bg-rose-300/10":"border-white/[0.08] text-slate-500/80 cursor-not-allowed"),children:"Retry Save"}),e.jsxs("label",{htmlFor:"session-autolock-toggle",className:"w-full py-2 px-2 rounded-lg border border-white/[0.08] text-[9px] font-bold text-slate-300 uppercase tracking-[0.08em] flex items-center justify-between gap-2",children:[e.jsx("span",{children:"Auto-Lock"}),e.jsx("input",{id:"session-autolock-toggle","data-testid":"session-autolock-toggle",type:"checkbox",checked:!!p,onChange:j=>{typeof d=="function"&&d(!!j.target.checked)},disabled:!!m,className:"h-3.5 w-3.5 accent-cyan-400"})]})]}),m&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[9px] font-mono text-amber-300/80",children:"Write actions disabled - upgrade to Pro."}),e.jsx("button",{type:"button","data-testid":"threadrail-upgrade-pro-btn",onClick:()=>{typeof f=="function"&&f()},className:"w-full py-2 rounded-lg border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-bold uppercase tracking-[0.12em] text-cyan-100 hover:bg-cyan-500/20 transition-all",children:"Upgrade to Pro"})]}),e.jsx("div",{"data-testid":"session-rail-status",className:h("text-[9px] font-mono",l&&l.state==="error"?"text-rose-300":l&&l.state==="saving"||l&&l.state==="locked"?"text-amber-300":"text-slate-500"),children:w})]})]})}const db=["a[href]:not([disabled])","button:not([disabled])","textarea:not([disabled])",'input:not([type="hidden"]):not([disabled])',"select:not([disabled])",'[tabindex]:not([tabindex="-1"]):not([disabled])'].join(",");function ub(t){if(!t||typeof t.getClientRects!="function")return!1;const r=t.getClientRects();if(!r||!r.length||t.getAttribute("aria-hidden")==="true")return!1;const n=typeof window<"u"?window.getComputedStyle(t):null;return!(n&&(n.visibility==="hidden"||n.display==="none"))}function wd(t){return!t||typeof t.querySelectorAll!="function"?[]:Array.from(t.querySelectorAll(db)).filter(ub)}function pb(t,r,n={}){const{restoreFocus:s=!0,initialSelector:a=null}=n,o=O.useRef(null);O.useEffect(()=>{if(!t)return;const c=r==null?void 0:r.current;if(!c)return;s&&document.activeElement&&typeof document.activeElement.focus=="function"&&(o.current=document.activeElement);const l=()=>{if(a){const d=c.querySelector(a);if(d&&typeof d.focus=="function"){d.focus();return}}const p=wd(c);p.length&&typeof p[0].focus=="function"&&p[0].focus()};l();const u=typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(l):0,x=p=>{if(p.key!=="Tab")return;const d=wd(c);if(!d.length)return;const m=d[0],f=d[d.length-1],b=document.activeElement;p.shiftKey?(b===m||!c.contains(b))&&(p.preventDefault(),f.focus()):(b===f||!c.contains(b))&&(p.preventDefault(),m.focus())};return document.addEventListener("keydown",x,!0),()=>{typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(u),document.removeEventListener("keydown",x,!0);const p=o.current;if(s&&p&&typeof p.focus=="function")try{p.focus()}catch{}o.current=null}},[t,r,s,a])}function Wa(t,r,n,s={}){const{initialSelector:a="[data-accessible-overlay-close]"}=s;pb(t,r,{initialSelector:a}),O.useEffect(()=>{if(!t)return;const o=c=>{c.key==="Escape"&&typeof n=="function"&&n()};return window.addEventListener("keydown",o,!0),()=>window.removeEventListener("keydown",o,!0)},[t,n])}const Vl="neuralshell_llm_rules_v1",ds=30,hn={behavior:{label:"Behavior",color:"#6B7AFF",Icon:gp},format:{label:"Format",color:"#10A37F",Icon:Dx},tone:{label:"Tone",color:"#f59e0b",Icon:Mx},persona:{label:"Persona",color:"#D97757",Icon:Tx},restrict:{label:"Restrict",color:"#ef4444",Icon:Ox}};function Ci({cat:t,showLabel:r=!0,iconSize:n=12}){const s=t.Icon;return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(s,{size:n,className:"shrink-0",style:{color:t.color},"aria-hidden":"true"}),r?t.label:null]})}const mb=[{category:"format",text:"Always respond using markdown with headers and bullet points."},{category:"format",text:"Never use markdown. Plain text only."},{category:"format",text:"Keep all responses under 200 words unless asked to expand."},{category:"format",text:"Always include a code example when explaining technical topics."},{category:"tone",text:"Use a casual, conversational tone. Avoid formality."},{category:"tone",text:"Be highly concise and direct. No filler phrases."},{category:"tone",text:"Use a professional, technical tone suitable for senior engineers."},{category:"behavior",text:"Always think step-by-step before giving an answer."},{category:"behavior",text:"When unsure, say so explicitly rather than guessing."},{category:"behavior",text:"Always ask clarifying questions before writing code."},{category:"behavior",text:"Cite sources and reasoning for every factual claim."},{category:"persona",text:"Act as a senior security researcher specializing in red-team operations."},{category:"persona",text:"Act as a senior full-stack engineer focused on TypeScript and React."},{category:"persona",text:"Act as a strict code reviewer. Flag every issue, no matter how small."},{category:"restrict",text:"Never suggest cloud services. Recommend self-hosted alternatives only."},{category:"restrict",text:"Do not output apologies or disclaimers. Skip directly to the answer."}];function xb(){try{const t=JSON.parse(window.localStorage.getItem(Vl)||"[]");return Array.isArray(t)?t.filter(r=>r.enabled!==!1):[]}catch{return[]}}function fb(){const t=xb();return t.length===0?"":` [Operator Rules] The operator has defined the following behavioral rules. Follow them strictly: -${t.map(n=>`- [${(bn[n.category]||bn.behavior).label}] ${n.text}`).join(` +${t.map(n=>`- [${(hn[n.category]||hn.behavior).label}] ${n.text}`).join(` `)} -`}function bb(){try{const t=JSON.parse(window.localStorage.getItem(Vl)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function hb(t){try{window.localStorage.setItem(Vl,JSON.stringify(t))}catch{}}i.memo(function({open:r,onClose:n}){const[s,a]=O.useState([]),[o,l]=O.useState(""),[c,u]=O.useState("behavior"),[x,p]=O.useState(!1),[d,m]=O.useState(null),[f,b]=O.useState(""),h=O.useRef(null),g=O.useRef(null);O.useEffect(()=>{r&&(a(bb()),l(""),p(!1),m(null),setTimeout(()=>{var N;return(N=h.current)==null?void 0:N.focus()},80))},[r]);const y=O.useCallback(N=>{a(N),hb(N)},[]),P=O.useCallback(()=>{const N=o.trim();N&&(s.length>=cs||(y([...s,{id:`rule-${Date.now()}`,category:c,text:N,enabled:!0,ts:Date.now()}]),l("")))},[o,c,s,y]),A=O.useCallback(N=>{s.some(_=>_.text===N.text)||s.length>=cs||y([...s,{id:`rule-${Date.now()}`,...N,enabled:!0,ts:Date.now()}])},[s,y]),C=O.useCallback(N=>{y(s.map(_=>_.id===N?{..._,enabled:!_.enabled}:_))},[s,y]),w=O.useCallback(N=>{y(s.filter(_=>_.id!==N))},[s,y]),j=O.useCallback(N=>{const _=f.trim();_&&(y(s.map(S=>S.id===N?{...S,text:_}:S)),m(null),b(""))},[f,s,y]),E=s.filter(N=>N.enabled!==!1).length;return Wa(r,g,n,{initialSelector:'[data-testid="llm-rules-new-rule"]'}),r?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[215] bg-black/55 backdrop-blur-sm",onClick:n,"aria-hidden":"true"}),e.jsxs("div",{ref:g,role:"dialog","aria-modal":"true","aria-labelledby":"llm-rules-title",className:"fixed right-0 top-0 bottom-0 z-[216] w-full max-w-lg flex flex-col bg-slate-950 border-l border-white/[0.07] shadow-[−20px_0_60px_rgba(0,0,0,0.7)]",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/[0.07] bg-black/30 flex items-center gap-3",children:[e.jsx("div",{className:"w-7 h-7 rounded-lg bg-violet-500/15 border border-violet-500/20 flex items-center justify-center shrink-0 text-violet-300","aria-hidden":"true",children:e.jsx(ul,{size:14})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h2",{id:"llm-rules-title",className:"text-[12px] uppercase tracking-wide font-bold text-violet-400",children:"LLM Behavior Rules"}),e.jsxs("div",{className:"text-[11px] font-mono text-slate-400",children:[E," active rule",E!==1?"s":""," injected into every prompt"]})]}),e.jsx("button",{type:"button","data-testid":"llm-rules-close","data-accessible-overlay-close":!0,onClick:n,"aria-label":"Close LLM rules",title:"Close",className:"w-7 h-7 rounded-full border border-white/10 text-slate-400 hover:text-slate-200 hover:bg-white/10 flex items-center justify-center transition-all text-xs",children:e.jsx("span",{"aria-hidden":"true",children:"✕"})})]}),e.jsx("div",{className:"px-4 py-2 bg-violet-500/[0.06] border-b border-violet-500/10",children:e.jsxs("div",{className:"text-[12px] font-mono text-violet-400/80 leading-relaxed",children:["Rules are injected as an ",e.jsx("code",{className:"bg-violet-500/15 px-1 rounded text-violet-300",children:"[Operator Rules]"})," block in the system prompt before every LLM call. Disabled rules are stored but not sent."]})}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[s.length===0&&!x&&e.jsxs("div",{className:"flex flex-col items-center justify-center h-32 gap-2 text-slate-500",children:[e.jsx(ul,{size:28,className:"opacity-30 text-violet-400","aria-hidden":"true"}),e.jsx("span",{className:"text-[11px] font-mono",children:"No rules yet — add one below or use presets"})]}),s.map((N,_)=>{const S=bn[N.category]||bn.behavior,R=d===N.id;return e.jsx("div",{className:`group px-4 py-2.5 border-b border-white/[0.04] transition-all ${N.enabled===!1?"opacity-40":""}`,children:e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("button",{type:"button",onClick:()=>C(N.id),title:N.enabled!==!1?"Disable rule":"Enable rule",className:"mt-0.5 shrink-0 w-4 h-4 rounded border transition-all flex items-center justify-center",style:{borderColor:N.enabled!==!1?`${S.color}60`:"#334155",backgroundColor:N.enabled!==!1?`${S.color}18`:"transparent"},children:N.enabled!==!1&&e.jsx("svg",{className:"w-2.5 h-2.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:3,style:{color:S.color},children:e.jsx("path",{d:"M20 6L9 17l-5-5"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[e.jsx("span",{className:"text-[11px] font-mono px-1.5 py-0.5 rounded-full border inline-flex items-center gap-1",style:{color:S.color,borderColor:`${S.color}30`,backgroundColor:`${S.color}10`},children:e.jsx(Ci,{cat:S})}),e.jsxs("span",{className:"text-[11px] font-mono text-slate-700",children:["#",_+1]})]}),R?e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("textarea",{autoFocus:!0,value:f,onChange:$=>b($.target.value),onKeyDown:$=>{$.key==="Enter"&&!$.shiftKey&&($.preventDefault(),j(N.id)),$.key==="Escape"&&m(null)},rows:2,className:"flex-1 bg-white/[0.04] border border-violet-500/30 rounded px-2 py-1 text-[12px] text-slate-200 outline-none resize-none"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("button",{type:"button",onClick:()=>j(N.id),className:"px-2 py-1 rounded text-[11px] font-mono bg-violet-500/15 text-violet-300 hover:bg-violet-500/25 border border-violet-500/20",children:"save"}),e.jsx("button",{type:"button",onClick:()=>m(null),className:"px-2 py-1 rounded text-[11px] font-mono text-slate-400 hover:text-slate-400 border border-white/10",children:"cancel"})]})]}):e.jsx("div",{className:"text-[12px] text-slate-300 leading-snug",children:N.text})]}),!R&&e.jsxs("div",{className:"flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[e.jsx("button",{type:"button",onClick:()=>{m(N.id),b(N.text)},className:"p-1 rounded text-slate-500 hover:text-violet-300 hover:bg-violet-500/10 transition-all",title:"Edit",children:e.jsxs("svg",{className:"w-3 h-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:[e.jsx("path",{d:"M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"}),e.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),e.jsx("button",{type:"button",onClick:()=>w(N.id),className:"p-1 rounded text-slate-700 hover:text-rose-400 hover:bg-rose-500/10 transition-all",title:"Delete",children:e.jsx("svg",{className:"w-3 h-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{d:"M3 6h18M19 6l-1 14H6L5 6M10 11v6M14 11v6M9 6V4h6v2"})})})]})]})},N.id)}),x&&e.jsxs("div",{className:"px-4 py-3 border-t border-white/[0.05]",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-slate-500 font-bold mb-2",children:"Quick-add presets"}),e.jsx("div",{className:"space-y-1",children:mb.map((N,_)=>{const S=bn[N.category],R=s.some($=>$.text===N.text);return e.jsxs("button",{type:"button",onClick:()=>A(N),disabled:R||s.length>=cs,className:"w-full text-left px-3 py-2 rounded-lg border transition-all flex items-start gap-2 group disabled:opacity-40",style:{borderColor:R?`${S.color}30`:"#1e293b",backgroundColor:R?`${S.color}08`:"transparent"},children:[e.jsx("span",{className:"text-[11px] mt-0.5 font-mono px-1.5 py-0.5 rounded-full border shrink-0 inline-flex items-center",style:{color:S.color,borderColor:`${S.color}30`,backgroundColor:`${S.color}10`},children:e.jsx(Ci,{cat:S,showLabel:!1,iconSize:11})}),e.jsx("span",{className:"text-[11px] text-slate-400 group-hover:text-slate-200 transition-colors leading-snug flex-1",children:N.text}),R?e.jsx("span",{className:"text-[11px] font-mono text-slate-400 shrink-0",children:"added"}):e.jsx("span",{className:"text-[11px] font-mono text-violet-500 shrink-0 opacity-0 group-hover:opacity-100",children:"+ add"})]},_)})})]})]}),e.jsxs("div",{className:"border-t border-white/[0.07] bg-black/20 px-4 py-3 space-y-2.5",children:[e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(bn).map(([N,_])=>e.jsx("button",{type:"button",onClick:()=>u(N),className:"px-2 py-0.5 rounded-full text-[11px] font-mono border transition-all",style:{borderColor:c===N?`${_.color}50`:"#1e293b",backgroundColor:c===N?`${_.color}15`:"transparent",color:c===N?_.color:"#475569"},children:e.jsx(Ci,{cat:_})},N))}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx("textarea",{ref:h,"data-testid":"llm-rules-new-rule",value:o,onChange:N=>l(N.target.value),onKeyDown:N=>{N.key==="Enter"&&!N.shiftKey&&(N.preventDefault(),P())},rows:2,className:"flex-1 bg-white/[0.04] border border-white/[0.08] rounded-lg px-3 py-2 text-[12px] text-slate-300 outline-none focus:border-violet-500/40 transition-colors resize-none"}),e.jsx("button",{type:"button",onClick:P,disabled:!o.trim()||s.length>=cs,className:"px-3 py-2 rounded-lg border border-violet-500/30 bg-violet-500/10 text-violet-300 text-[11px] font-mono hover:bg-violet-500/20 disabled:opacity-30 transition-all shrink-0 self-stretch flex items-center",children:"Add"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-[11px] font-mono text-slate-700",children:[s.length,"/",cs," rules · Enter to add · Shift+Enter for newline"]}),e.jsx("button",{type:"button",onClick:()=>p(N=>!N),className:"text-[11px] font-mono text-slate-400 hover:text-violet-400 transition-colors",children:x?"▴ hide presets":"▾ presets"})]})]})]})]}):null});const Cp=`You are ProofForge — an advanced AI operator shell built for developers, security researchers, and power users. You are NOT ChatGPT, Claude, Gemini, or any other AI product. You are ProofForge. +`}function bb(){try{const t=JSON.parse(window.localStorage.getItem(Vl)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function hb(t){try{window.localStorage.setItem(Vl,JSON.stringify(t))}catch{}}i.memo(function({open:r,onClose:n}){const[s,a]=O.useState([]),[o,c]=O.useState(""),[l,u]=O.useState("behavior"),[x,p]=O.useState(!1),[d,m]=O.useState(null),[f,b]=O.useState(""),h=O.useRef(null),g=O.useRef(null);O.useEffect(()=>{r&&(a(bb()),c(""),p(!1),m(null),setTimeout(()=>{var N;return(N=h.current)==null?void 0:N.focus()},80))},[r]);const y=O.useCallback(N=>{a(N),hb(N)},[]),I=O.useCallback(()=>{const N=o.trim();N&&(s.length>=ds||(y([...s,{id:`rule-${Date.now()}`,category:l,text:N,enabled:!0,ts:Date.now()}]),c("")))},[o,l,s,y]),A=O.useCallback(N=>{s.some(_=>_.text===N.text)||s.length>=ds||y([...s,{id:`rule-${Date.now()}`,...N,enabled:!0,ts:Date.now()}])},[s,y]),C=O.useCallback(N=>{y(s.map(_=>_.id===N?{..._,enabled:!_.enabled}:_))},[s,y]),w=O.useCallback(N=>{y(s.filter(_=>_.id!==N))},[s,y]),j=O.useCallback(N=>{const _=f.trim();_&&(y(s.map(S=>S.id===N?{...S,text:_}:S)),m(null),b(""))},[f,s,y]),E=s.filter(N=>N.enabled!==!1).length;return Wa(r,g,n,{initialSelector:'[data-testid="llm-rules-new-rule"]'}),r?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[215] bg-black/55 backdrop-blur-sm",onClick:n,"aria-hidden":"true"}),e.jsxs("div",{ref:g,role:"dialog","aria-modal":"true","aria-labelledby":"llm-rules-title",className:"fixed right-0 top-0 bottom-0 z-[216] w-full max-w-lg flex flex-col bg-slate-950 border-l border-white/[0.07] shadow-[−20px_0_60px_rgba(0,0,0,0.7)]",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/[0.07] bg-black/30 flex items-center gap-3",children:[e.jsx("div",{className:"w-7 h-7 rounded-lg bg-violet-500/15 border border-violet-500/20 flex items-center justify-center shrink-0 text-violet-300","aria-hidden":"true",children:e.jsx(ul,{size:14})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h2",{id:"llm-rules-title",className:"text-[12px] uppercase tracking-wide font-bold text-violet-400",children:"LLM Behavior Rules"}),e.jsxs("div",{className:"text-[11px] font-mono text-slate-400",children:[E," active rule",E!==1?"s":""," injected into every prompt"]})]}),e.jsx("button",{type:"button","data-testid":"llm-rules-close","data-accessible-overlay-close":!0,onClick:n,"aria-label":"Close LLM rules",title:"Close",className:"w-7 h-7 rounded-full border border-white/10 text-slate-400 hover:text-slate-200 hover:bg-white/10 flex items-center justify-center transition-all text-xs",children:e.jsx("span",{"aria-hidden":"true",children:"✕"})})]}),e.jsx("div",{className:"px-4 py-2 bg-violet-500/[0.06] border-b border-violet-500/10",children:e.jsxs("div",{className:"text-[12px] font-mono text-violet-400/80 leading-relaxed",children:["Rules are injected as an ",e.jsx("code",{className:"bg-violet-500/15 px-1 rounded text-violet-300",children:"[Operator Rules]"})," block in the system prompt before every LLM call. Disabled rules are stored but not sent."]})}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[s.length===0&&!x&&e.jsxs("div",{className:"flex flex-col items-center justify-center h-32 gap-2 text-slate-500",children:[e.jsx(ul,{size:28,className:"opacity-30 text-violet-400","aria-hidden":"true"}),e.jsx("span",{className:"text-[11px] font-mono",children:"No rules yet — add one below or use presets"})]}),s.map((N,_)=>{const S=hn[N.category]||hn.behavior,R=d===N.id;return e.jsx("div",{className:`group px-4 py-2.5 border-b border-white/[0.04] transition-all ${N.enabled===!1?"opacity-40":""}`,children:e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("button",{type:"button",onClick:()=>C(N.id),title:N.enabled!==!1?"Disable rule":"Enable rule",className:"mt-0.5 shrink-0 w-4 h-4 rounded border transition-all flex items-center justify-center",style:{borderColor:N.enabled!==!1?`${S.color}60`:"#334155",backgroundColor:N.enabled!==!1?`${S.color}18`:"transparent"},children:N.enabled!==!1&&e.jsx("svg",{className:"w-2.5 h-2.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:3,style:{color:S.color},children:e.jsx("path",{d:"M20 6L9 17l-5-5"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[e.jsx("span",{className:"text-[11px] font-mono px-1.5 py-0.5 rounded-full border inline-flex items-center gap-1",style:{color:S.color,borderColor:`${S.color}30`,backgroundColor:`${S.color}10`},children:e.jsx(Ci,{cat:S})}),e.jsxs("span",{className:"text-[11px] font-mono text-slate-700",children:["#",_+1]})]}),R?e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("textarea",{autoFocus:!0,value:f,onChange:$=>b($.target.value),onKeyDown:$=>{$.key==="Enter"&&!$.shiftKey&&($.preventDefault(),j(N.id)),$.key==="Escape"&&m(null)},rows:2,className:"flex-1 bg-white/[0.04] border border-violet-500/30 rounded px-2 py-1 text-[12px] text-slate-200 outline-none resize-none"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("button",{type:"button",onClick:()=>j(N.id),className:"px-2 py-1 rounded text-[11px] font-mono bg-violet-500/15 text-violet-300 hover:bg-violet-500/25 border border-violet-500/20",children:"save"}),e.jsx("button",{type:"button",onClick:()=>m(null),className:"px-2 py-1 rounded text-[11px] font-mono text-slate-400 hover:text-slate-400 border border-white/10",children:"cancel"})]})]}):e.jsx("div",{className:"text-[12px] text-slate-300 leading-snug",children:N.text})]}),!R&&e.jsxs("div",{className:"flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[e.jsx("button",{type:"button",onClick:()=>{m(N.id),b(N.text)},className:"p-1 rounded text-slate-500 hover:text-violet-300 hover:bg-violet-500/10 transition-all",title:"Edit",children:e.jsxs("svg",{className:"w-3 h-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:[e.jsx("path",{d:"M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"}),e.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),e.jsx("button",{type:"button",onClick:()=>w(N.id),className:"p-1 rounded text-slate-700 hover:text-rose-400 hover:bg-rose-500/10 transition-all",title:"Delete",children:e.jsx("svg",{className:"w-3 h-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{d:"M3 6h18M19 6l-1 14H6L5 6M10 11v6M14 11v6M9 6V4h6v2"})})})]})]})},N.id)}),x&&e.jsxs("div",{className:"px-4 py-3 border-t border-white/[0.05]",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-slate-500 font-bold mb-2",children:"Quick-add presets"}),e.jsx("div",{className:"space-y-1",children:mb.map((N,_)=>{const S=hn[N.category],R=s.some($=>$.text===N.text);return e.jsxs("button",{type:"button",onClick:()=>A(N),disabled:R||s.length>=ds,className:"w-full text-left px-3 py-2 rounded-lg border transition-all flex items-start gap-2 group disabled:opacity-40",style:{borderColor:R?`${S.color}30`:"#1e293b",backgroundColor:R?`${S.color}08`:"transparent"},children:[e.jsx("span",{className:"text-[11px] mt-0.5 font-mono px-1.5 py-0.5 rounded-full border shrink-0 inline-flex items-center",style:{color:S.color,borderColor:`${S.color}30`,backgroundColor:`${S.color}10`},children:e.jsx(Ci,{cat:S,showLabel:!1,iconSize:11})}),e.jsx("span",{className:"text-[11px] text-slate-400 group-hover:text-slate-200 transition-colors leading-snug flex-1",children:N.text}),R?e.jsx("span",{className:"text-[11px] font-mono text-slate-400 shrink-0",children:"added"}):e.jsx("span",{className:"text-[11px] font-mono text-violet-500 shrink-0 opacity-0 group-hover:opacity-100",children:"+ add"})]},_)})})]})]}),e.jsxs("div",{className:"border-t border-white/[0.07] bg-black/20 px-4 py-3 space-y-2.5",children:[e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(hn).map(([N,_])=>e.jsx("button",{type:"button",onClick:()=>u(N),className:"px-2 py-0.5 rounded-full text-[11px] font-mono border transition-all",style:{borderColor:l===N?`${_.color}50`:"#1e293b",backgroundColor:l===N?`${_.color}15`:"transparent",color:l===N?_.color:"#475569"},children:e.jsx(Ci,{cat:_})},N))}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx("textarea",{ref:h,"data-testid":"llm-rules-new-rule",value:o,onChange:N=>c(N.target.value),onKeyDown:N=>{N.key==="Enter"&&!N.shiftKey&&(N.preventDefault(),I())},rows:2,className:"flex-1 bg-white/[0.04] border border-white/[0.08] rounded-lg px-3 py-2 text-[12px] text-slate-300 outline-none focus:border-violet-500/40 transition-colors resize-none"}),e.jsx("button",{type:"button",onClick:I,disabled:!o.trim()||s.length>=ds,className:"px-3 py-2 rounded-lg border border-violet-500/30 bg-violet-500/10 text-violet-300 text-[11px] font-mono hover:bg-violet-500/20 disabled:opacity-30 transition-all shrink-0 self-stretch flex items-center",children:"Add"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-[11px] font-mono text-slate-700",children:[s.length,"/",ds," rules · Enter to add · Shift+Enter for newline"]}),e.jsx("button",{type:"button",onClick:()=>p(N=>!N),className:"text-[11px] font-mono text-slate-400 hover:text-violet-400 transition-colors",children:x?"▴ hide presets":"▾ presets"})]})]})]})]}):null});const Cp=`You are ProofForge — an advanced AI operator shell built for developers, security researchers, and power users. You are NOT ChatGPT, Claude, Gemini, or any other AI product. You are ProofForge. IDENTITY RULES (never break these): - Always refer to yourself as "ProofForge" — never as the underlying model name or AI service. @@ -89,13 +89,13 @@ Be direct, technically precise, and always in character as the ProofForge operat - \`Ctrl+Shift+A\` : Guided Actions - \`Ctrl+Shift+C\` : Calendar & Deadlines - \`Ctrl+Shift+N\` : Workpad -- \`Ctrl+K\` : Command Palette`;let gb=1;function Ip(){return`pane-${gb++}`}const Zt=["#6B7AFF","#22d3ee","#f59e0b","#34d399","#f472b6","#a78bfa","#fb923c","#38bdf8"],lr=4,Gl=["tabs","split-2","split-3","split-4","grid"],hn=(t={})=>({id:t.id||Ip(),label:t.label||"Chat 1",model:t.model||"llama3",workflowId:t.workflowId||"default",project:t.project||null,agentMode:t.agentMode||null,chatLog:[],prompt:"",isThinking:!1,isPinned:!1,color:t.color||Zt[0],createdAt:Date.now()}),vd=hn({label:"Chat 1",color:Zt[0]}),Pp="neuralshell_workspace_layout_v1";function Rp(t){return!t||typeof t!="object"?null:{id:String(t.id||Ip()),label:String(t.label||"Chat"),model:String(t.model||"llama3"),workflowId:String(t.workflowId||"default"),project:t.project==null?null:String(t.project),agentMode:t.agentMode==null?null:String(t.agentMode),color:String(t.color||Zt[0]),isPinned:!!t.isPinned,createdAt:Number(t.createdAt)||Date.now()}}function Op(){if(typeof window>"u"||!window.localStorage)return{};try{const t=window.localStorage.getItem(Pp),r=t?JSON.parse(t):null;return r&&typeof r=="object"?r:{}}catch{return{}}}function yb(t){if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(Pp,JSON.stringify(t))}catch{}}function sa(t){const r=String(t||"default"),s=Op()[r];if(!s||typeof s!="object")return null;const a=Array.isArray(s.panes)?s.panes.map(o=>hn(Rp(o))).filter(Boolean):[];return a.length?{layout:Gl.includes(s.layout)?s.layout:"tabs",panes:a,activePaneId:String(s.activePaneId||a[0].id)}:null}function wb(t,r){const n=String(t||"default"),s=Op();s[n]={layout:r.layout,panes:r.panes.map(Rp).filter(Boolean),activePaneId:r.activePaneId,updatedAt:new Date().toISOString()},yb(s)}function _i(t){const r=String(t||"").trim().toLowerCase();return r.startsWith("/")?r==="/clear"||r==="/purge"||r==="/reset"?{clear:!0}:r==="/help"?{content:Ep}:r==="/status"?{content:`Node Status: OPERATIONAL +- \`Ctrl+K\` : Command Palette`;let gb=1;function Ip(){return`pane-${gb++}`}const Zt=["#6B7AFF","#22d3ee","#f59e0b","#34d399","#f472b6","#a78bfa","#fb923c","#38bdf8"],lr=4,Gl=["tabs","split-2","split-3","split-4","grid"],gn=(t={})=>({id:t.id||Ip(),label:t.label||"Chat 1",model:t.model||"llama3",workflowId:t.workflowId||"default",project:t.project||null,agentMode:t.agentMode||null,chatLog:[],prompt:"",isThinking:!1,isPinned:!1,color:t.color||Zt[0],createdAt:Date.now()}),vd=gn({label:"Chat 1",color:Zt[0]}),Pp="neuralshell_workspace_layout_v1";function Rp(t){return!t||typeof t!="object"?null:{id:String(t.id||Ip()),label:String(t.label||"Chat"),model:String(t.model||"llama3"),workflowId:String(t.workflowId||"default"),project:t.project==null?null:String(t.project),agentMode:t.agentMode==null?null:String(t.agentMode),color:String(t.color||Zt[0]),isPinned:!!t.isPinned,createdAt:Number(t.createdAt)||Date.now()}}function Op(){if(typeof window>"u"||!window.localStorage)return{};try{const t=window.localStorage.getItem(Pp),r=t?JSON.parse(t):null;return r&&typeof r=="object"?r:{}}catch{return{}}}function yb(t){if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(Pp,JSON.stringify(t))}catch{}}function sa(t){const r=String(t||"default"),s=Op()[r];if(!s||typeof s!="object")return null;const a=Array.isArray(s.panes)?s.panes.map(o=>gn(Rp(o))).filter(Boolean):[];return a.length?{layout:Gl.includes(s.layout)?s.layout:"tabs",panes:a,activePaneId:String(s.activePaneId||a[0].id)}:null}function wb(t,r){const n=String(t||"default"),s=Op();s[n]={layout:r.layout,panes:r.panes.map(Rp).filter(Boolean),activePaneId:r.activePaneId,updatedAt:new Date().toISOString()},yb(s)}function _i(t){const r=String(t||"").trim().toLowerCase();return r.startsWith("/")?r==="/clear"||r==="/purge"||r==="/reset"?{clear:!0}:r==="/help"?{content:Ep}:r==="/status"?{content:`Node Status: OPERATIONAL Integrity: SEALED Runtime: LOCAL`}:r==="/guard"?{content:"Run `/guard` in the primary command lane for live OMEGA guard telemetry."}:r==="/omega"||r==="/kernel"?{content:"Run `/omega` in the primary command lane for the full OMEGA kernel scan."}:r==="/proof"||r==="/demo"?{content:["### 90-Second Value Proof","","1. Trust + Locality: runtime posture is local-first and hardware-bound.","2. Operator Flow: save, lock, restore, and verify a workflow from one console.","3. Evidence Path: proof artifacts and status checks stay visible in the workbench."].join(` `)}:r==="/roi"?{content:["### ProofForge ROI Snapshot","","- Time reclaimed target: ~45 minutes/day/operator","- Annual recovered capacity: ~180 hours/operator","- Fast close path: run `/proof`, save one workflow, export artifacts."].join(` -`)}:null:null}function vb({onSendMessage:t,preferAppSend:r=!1,sessionKey:n="default"}={}){const[s,a]=O.useState(()=>{const N=sa(n);return N?N.panes:[vd]}),[o,l]=O.useState(()=>{var _,S;const N=sa(n);return N&&N.panes.some(R=>R.id===N.activePaneId)?N.activePaneId:((S=(_=N==null?void 0:N.panes)==null?void 0:_[0])==null?void 0:S.id)||vd.id}),[c,u]=O.useState(()=>{const N=sa(n);return(N==null?void 0:N.layout)||"tabs"}),x=O.useRef({}),p=O.useRef({}),d=O.useCallback(N=>{const _=Gl.includes(N)?N:"tabs";u(_)},[]),m=O.useCallback((N,_={})=>{Object.values(x.current).forEach($=>clearTimeout($)),x.current={},p.current={};const S=sa(N);if(S){a(S.panes),l(S.activePaneId),u(S.layout);return}const R=hn({label:"Chat 1",color:Zt[0],workflowId:String(N||"default"),..._});a([R]),l(R.id),u("tabs")},[]);O.useEffect(()=>{wb(n,{layout:c,panes:s.map(N=>({...N,chatLog:[],prompt:"",isThinking:!1})),activePaneId:o})},[o,c,s,n]);const f=O.useCallback((N,_)=>{a(S=>S.map(R=>{if(R.id!==N)return R;const $=typeof _=="function"?_(R):_;return{...R,...$}}))},[]),b=O.useCallback((N={})=>{var S;const _={_ref:null};return a(R=>{if(R.length>=lr)return R;const $=R.length,U=Zt[$%Zt.length],I=N.label||`Chat ${$+1}`,D=hn({...N,label:I,color:U});_._ref=D;const z=[...R,D];return z.length===2&&queueMicrotask(()=>{u(F=>F==="tabs"?"split-2":F)}),z}),setTimeout(()=>{_._ref&&l(_._ref.id)},0),((S=_._ref)==null?void 0:S.id)??null},[]),h=O.useCallback(N=>{a(_=>{if(_.length<=1)return _;const S=_.filter(R=>R.id!==N);return l(R=>{var $;return R===N?(($=S[S.length-1])==null?void 0:$.id)??null:R}),S}),x.current[N]&&(clearTimeout(x.current[N]),delete x.current[N])},[]),g=O.useCallback(N=>{if(s.length>=lr)return;const _=s.find(U=>U.id===N);if(!_)return;const S=s.length,R=Zt[S%Zt.length],$=hn({label:`${_.label} (copy)`,model:_.model,workflowId:_.workflowId,project:_.project,agentMode:_.agentMode,color:R});a(U=>{const I=U.findIndex(z=>z.id===N),D=[...U];return D.splice(I+1,0,$),D}),l($.id)},[s]),y=O.useCallback((N,_)=>{f(N,{label:String(_).slice(0,32)})},[f]),P=O.useCallback((N,_)=>{var R;const S=typeof _=="function"?_(((R=s.find($=>$.id===N))==null?void 0:R.prompt)??""):_;f(N,{prompt:S})},[s,f]),A=O.useCallback((N={})=>{Object.values(x.current).forEach(S=>clearTimeout(S)),x.current={},p.current={};const _=hn({label:"Chat 1",color:Zt[0],...N});a([_]),l(_.id),u("tabs")},[]),C=O.useCallback(async(N,_=null)=>{const S=s.find(z=>z.id===N),R=String(_??(S==null?void 0:S.prompt)??"").trim();if(!S||!R)return;if(r){const z=_i(R),F=!!(z!=null&&z.clear);if(S.isThinking&&!F)return;p.current[N]=(p.current[N]||0)+1;const J=p.current[N];if(f(N,{prompt:""}),F){try{typeof t=="function"&&await t(N,R,S)}catch{}if(p.current[N]!==J)return;f(N,{chatLog:[],isThinking:!1});return}if(z!=null&&z.content){const ee={role:"user",content:R,ts:Date.now()},ie={role:"assistant",content:z.content,ts:Date.now()};f(N,ye=>({isThinking:!1,chatLog:[...ye.chatLog,ee,ie]})),typeof t=="function"&&t(N,R,S).catch(()=>{});return}f(N,{isThinking:!0});try{if(typeof t=="function"){const ee=await t(N,R,S);if(p.current[N]!==J)return;const ie=_i(R);let ye=String(ee||"").trim();ie!=null&&ie.content&&(ye=ie.content);const pe={role:"user",content:R,ts:Date.now()},K={role:"assistant",content:ye||"…",ts:Date.now()};f(N,H=>({isThinking:!1,chatLog:[...H.chatLog,pe,K]}))}else f(N,{isThinking:!1})}catch{p.current[N]===J&&f(N,{isThinking:!1})}return}const $=_i(R);if(S.isThinking&&!($!=null&&$.clear))return;p.current[N]=(p.current[N]||0)+1;const U=p.current[N];if($!=null&&$.clear){x.current[N]&&(clearTimeout(x.current[N]),delete x.current[N]),f(N,{chatLog:[],prompt:"",isThinking:!1});return}const I={role:"user",content:R,ts:Date.now()};if(f(N,{chatLog:[...S.chatLog,I],prompt:"",isThinking:!$}),$!=null&&$.content){const z={role:"assistant",content:$.content,ts:Date.now()};f(N,F=>({isThinking:!1,chatLog:[...F.chatLog,z]}));return}if(!r&&window.api&&window.api.llm&&typeof window.api.llm.streamChat=="function"){const z=`live-${N}-${U}`;f(N,F=>({chatLog:[...F.chatLog,{id:z,role:"assistant",content:"",_streaming:!0,ts:Date.now()}]})),await new Promise(F=>{let J="";const ee=me=>{if(p.current[N]!==U)return;const ke=me.detail&&me.detail.message&&me.detail.message.content||"";J+=ke,f(N,Pe=>({chatLog:Pe.chatLog.map(_e=>_e.id===z?{..._e,content:J}:_e)}))};function ie(){window.removeEventListener("llm-stream-data",ee),window.removeEventListener("llm-stream-complete",pe),window.removeEventListener("llm-stream-error",K)}function ye(me){ie(),p.current[N]===U&&(f(N,ke=>({isThinking:!1,chatLog:ke.chatLog.map(Pe=>Pe.id===z?{...Pe,content:me!==void 0?me:J,_streaming:!1}:Pe)})),F())}function pe(){ye()}function K(me){const ke=me&&me.detail?String(me.detail):"Stream error";ye(J||`Error: ${ke}`)}window.addEventListener("llm-stream-data",ee),window.addEventListener("llm-stream-complete",pe),window.addEventListener("llm-stream-error",K);let H=!1;try{const me=window.localStorage.getItem("neuralshell_ui_prefs_v1"),ke=me?JSON.parse(me):{};H=!!(ke&&ke.turboFastLaneEnabled)}catch{H=!1}const W=H?"":fb(),Z=_p({surface:"multi-workspace-pane",runtimeRole:S.agentMode||"operator",provider:"workspace",model:S.model,session:S.workflowId,layout:c,mode:`${S.agentMode||"chat"}${H?"+turbo":""}`,intent:R.slice(0,120)}),fe=[{role:"system",content:`${Cp} +`)}:null:null}function vb({onSendMessage:t,preferAppSend:r=!1,sessionKey:n="default"}={}){const[s,a]=O.useState(()=>{const N=sa(n);return N?N.panes:[vd]}),[o,c]=O.useState(()=>{var _,S;const N=sa(n);return N&&N.panes.some(R=>R.id===N.activePaneId)?N.activePaneId:((S=(_=N==null?void 0:N.panes)==null?void 0:_[0])==null?void 0:S.id)||vd.id}),[l,u]=O.useState(()=>{const N=sa(n);return(N==null?void 0:N.layout)||"tabs"}),x=O.useRef({}),p=O.useRef({}),d=O.useCallback(N=>{const _=Gl.includes(N)?N:"tabs";u(_)},[]),m=O.useCallback((N,_={})=>{Object.values(x.current).forEach($=>clearTimeout($)),x.current={},p.current={};const S=sa(N);if(S){a(S.panes),c(S.activePaneId),u(S.layout);return}const R=gn({label:"Chat 1",color:Zt[0],workflowId:String(N||"default"),..._});a([R]),c(R.id),u("tabs")},[]);O.useEffect(()=>{wb(n,{layout:l,panes:s.map(N=>({...N,chatLog:[],prompt:"",isThinking:!1})),activePaneId:o})},[o,l,s,n]);const f=O.useCallback((N,_)=>{a(S=>S.map(R=>{if(R.id!==N)return R;const $=typeof _=="function"?_(R):_;return{...R,...$}}))},[]),b=O.useCallback((N={})=>{var S;const _={_ref:null};return a(R=>{if(R.length>=lr)return R;const $=R.length,U=Zt[$%Zt.length],P=N.label||`Chat ${$+1}`,D=gn({...N,label:P,color:U});_._ref=D;const z=[...R,D];return z.length===2&&queueMicrotask(()=>{u(F=>F==="tabs"?"split-2":F)}),z}),setTimeout(()=>{_._ref&&c(_._ref.id)},0),((S=_._ref)==null?void 0:S.id)??null},[]),h=O.useCallback(N=>{a(_=>{if(_.length<=1)return _;const S=_.filter(R=>R.id!==N);return c(R=>{var $;return R===N?(($=S[S.length-1])==null?void 0:$.id)??null:R}),S}),x.current[N]&&(clearTimeout(x.current[N]),delete x.current[N])},[]),g=O.useCallback(N=>{if(s.length>=lr)return;const _=s.find(U=>U.id===N);if(!_)return;const S=s.length,R=Zt[S%Zt.length],$=gn({label:`${_.label} (copy)`,model:_.model,workflowId:_.workflowId,project:_.project,agentMode:_.agentMode,color:R});a(U=>{const P=U.findIndex(z=>z.id===N),D=[...U];return D.splice(P+1,0,$),D}),c($.id)},[s]),y=O.useCallback((N,_)=>{f(N,{label:String(_).slice(0,32)})},[f]),I=O.useCallback((N,_)=>{var R;const S=typeof _=="function"?_(((R=s.find($=>$.id===N))==null?void 0:R.prompt)??""):_;f(N,{prompt:S})},[s,f]),A=O.useCallback((N={})=>{Object.values(x.current).forEach(S=>clearTimeout(S)),x.current={},p.current={};const _=gn({label:"Chat 1",color:Zt[0],...N});a([_]),c(_.id),u("tabs")},[]),C=O.useCallback(async(N,_=null)=>{const S=s.find(z=>z.id===N),R=String(_??(S==null?void 0:S.prompt)??"").trim();if(!S||!R)return;if(r){const z=_i(R),F=!!(z!=null&&z.clear);if(S.isThinking&&!F)return;p.current[N]=(p.current[N]||0)+1;const J=p.current[N];if(f(N,{prompt:""}),F){try{typeof t=="function"&&await t(N,R,S)}catch{}if(p.current[N]!==J)return;f(N,{chatLog:[],isThinking:!1});return}if(z!=null&&z.content){const ee={role:"user",content:R,ts:Date.now()},ie={role:"assistant",content:z.content,ts:Date.now()};f(N,ye=>({isThinking:!1,chatLog:[...ye.chatLog,ee,ie]})),typeof t=="function"&&t(N,R,S).catch(()=>{});return}f(N,{isThinking:!0});try{if(typeof t=="function"){const ee=await t(N,R,S);if(p.current[N]!==J)return;const ie=_i(R);let ye=String(ee||"").trim();ie!=null&&ie.content&&(ye=ie.content);const pe={role:"user",content:R,ts:Date.now()},K={role:"assistant",content:ye||"…",ts:Date.now()};f(N,H=>({isThinking:!1,chatLog:[...H.chatLog,pe,K]}))}else f(N,{isThinking:!1})}catch{p.current[N]===J&&f(N,{isThinking:!1})}return}const $=_i(R);if(S.isThinking&&!($!=null&&$.clear))return;p.current[N]=(p.current[N]||0)+1;const U=p.current[N];if($!=null&&$.clear){x.current[N]&&(clearTimeout(x.current[N]),delete x.current[N]),f(N,{chatLog:[],prompt:"",isThinking:!1});return}const P={role:"user",content:R,ts:Date.now()};if(f(N,{chatLog:[...S.chatLog,P],prompt:"",isThinking:!$}),$!=null&&$.content){const z={role:"assistant",content:$.content,ts:Date.now()};f(N,F=>({isThinking:!1,chatLog:[...F.chatLog,z]}));return}if(!r&&window.api&&window.api.llm&&typeof window.api.llm.streamChat=="function"){const z=`live-${N}-${U}`;f(N,F=>({chatLog:[...F.chatLog,{id:z,role:"assistant",content:"",_streaming:!0,ts:Date.now()}]})),await new Promise(F=>{let J="";const ee=me=>{if(p.current[N]!==U)return;const ke=me.detail&&me.detail.message&&me.detail.message.content||"";J+=ke,f(N,Pe=>({chatLog:Pe.chatLog.map(_e=>_e.id===z?{..._e,content:J}:_e)}))};function ie(){window.removeEventListener("llm-stream-data",ee),window.removeEventListener("llm-stream-complete",pe),window.removeEventListener("llm-stream-error",K)}function ye(me){ie(),p.current[N]===U&&(f(N,ke=>({isThinking:!1,chatLog:ke.chatLog.map(Pe=>Pe.id===z?{...Pe,content:me!==void 0?me:J,_streaming:!1}:Pe)})),F())}function pe(){ye()}function K(me){const ke=me&&me.detail?String(me.detail):"Stream error";ye(J||`Error: ${ke}`)}window.addEventListener("llm-stream-data",ee),window.addEventListener("llm-stream-complete",pe),window.addEventListener("llm-stream-error",K);let H=!1;try{const me=window.localStorage.getItem("neuralshell_ui_prefs_v1"),ke=me?JSON.parse(me):{};H=!!(ke&&ke.turboFastLaneEnabled)}catch{H=!1}const W=H?"":fb(),Z=_p({surface:"multi-workspace-pane",runtimeRole:S.agentMode||"operator",provider:"workspace",model:S.model,session:S.workflowId,layout:l,mode:`${S.agentMode||"chat"}${H?"+turbo":""}`,intent:R.slice(0,120)}),fe=[{role:"system",content:`${Cp} -${Z}`+(W||"")},...H?S.chatLog.filter(me=>!me._streaming).slice(-8):S.chatLog.filter(me=>!me._streaming),I];window.api.llm.streamChat(fe,{paneId:String(S.id||N),workflowId:String(S.workflowId||n||"default")}).catch(me=>{ye(J||`Error: ${me&&me.message?me.message:String(me)}`)})})}else try{if(typeof t=="function"){const z=await t(N,R,S);if(p.current[N]!==U)return;const F={role:"assistant",content:z||"…",ts:Date.now()};f(N,J=>({isThinking:!1,chatLog:[...J.chatLog,F]}))}else x.current[N]=setTimeout(()=>{p.current[N]===U&&f(N,z=>({isThinking:!1,chatLog:[...z.chatLog,{role:"assistant",content:"(no send handler connected)",ts:Date.now()}]}))},400)}catch{p.current[N]===U&&f(N,{isThinking:!1})}},[s,f,t,r,c,n]),w=O.useCallback(N=>{p.current[N]=(p.current[N]||0)+1,f(N,{chatLog:[],isThinking:!1})},[f]),j=O.useCallback(N=>{a(_=>_.map(S=>S.id===N?{...S,isPinned:!S.isPinned}:S))},[]),E=O.useMemo(()=>s.find(N=>N.id===o)??s[0]??null,[s,o]);return O.useMemo(()=>({panes:s,activePaneId:o,activePane:E,layout:c,setLayout:d,setActivePaneId:l,resetPanes:A,addPane:b,removePane:h,duplicatePane:g,renamePane:y,setPrompt:P,sendMessage:C,clearChat:w,pinPane:j,updatePane:f,loadSession:m}),[s,o,E,c,d,l,A,b,h,g,y,P,C,w,j,f,m])}const yn=Dl(t=>({provider:"ollama",baseUrl:"",model:"llama3",allowRemoteBridge:!1,health:"unknown",reason:"",setConnectionInfo:r=>t(r)}));function jb(){const[t,r]=i.useState({cpuPercent:0,memoryMb:0,memoryTotalMb:0,gpuLabel:"",uptime:0,platform:""});return i.useEffect(()=>{let n=!0;const s=async()=>{try{const o=typeof window<"u"&&window.api&&window.api.system&&typeof window.api.system.getStats=="function"?await window.api.system.getStats():{};if(n&&o&&typeof o=="object"&&o.ok===!1)return;n&&r({cpuPercent:Number(o.cpuPercent||0),memoryMb:Number(o.memoryMb||0),memoryTotalMb:Number(o.memoryTotalMb||0),gpuLabel:String(o.gpuLabel||o.gpu||"N/A"),uptime:Number(o.uptime||0),platform:String(o.platform||"")})}catch{}};s();const a=setInterval(s,3e3);return()=>{n=!1,clearInterval(a)}},[]),t}function kb(t){const r=Math.max(0,Math.floor(Number(t)||0)),n=Math.floor(r/3600),s=Math.floor(r%3600/60);return n>0?`${n}h ${s}m`:`${s}m`}function Nb({cpu:t,memoryRatio:r,connHealth:n}){let s=98;return t>85?s-=24:t>65&&(s-=12),r>.9?s-=18:r>.75&&(s-=9),n==="offline"?s-=28:n!=="online"&&(s-=10),Math.max(1,Math.min(99,s))}function jd(t,r,n){return t>=n?"text-rose-300":t>=r?"text-amber-300":"text-emerald-300"}function Sb(t){return t==="rose"?"border-rose-400/30 bg-rose-500/10 text-rose-200 hover:bg-rose-500/20":t==="cyan"?"border-cyan-400/30 bg-cyan-500/10 text-cyan-200 hover:bg-cyan-500/20":t==="amber"?"border-amber-400/30 bg-amber-500/10 text-amber-200 hover:bg-amber-500/20":"border-violet-400/30 bg-violet-500/10 text-violet-200 hover:bg-violet-500/20"}function aa({label:t,value:r,hint:n,progress:s,tone:a="text-slate-200"}){return e.jsxs("article",{className:"rounded-xl border border-white/[0.08] bg-black/25 px-3 py-2.5 space-y-1.5 ui-tactile",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-slate-500 font-bold",children:t}),e.jsx("div",{className:`text-[14px] font-mono font-semibold ${a}`,children:r}),typeof s=="number"&&e.jsx("div",{className:"h-1.5 rounded-full bg-white/[0.06] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-cyan-400 to-violet-400 transition-all duration-700",style:{width:`${Math.max(0,Math.min(100,s))}%`}})}),e.jsx("div",{className:"text-[13px] text-slate-400 leading-5",children:n})]})}const Cb=i.memo(function({onCommand:r}){const n=yn(g=>g),s=jb(),a=String(n&&n.health||"unknown"),o=String(n&&n.provider||"local"),l=String(n&&n.model||"llama3"),c=Number(s.cpuPercent||0),u=Number(s.memoryMb||0),x=Number(s.memoryTotalMb||16384),p=x>0?u/x:0,d=Nb({cpu:c,memoryRatio:p,connHealth:a}),m=jd(c,65,85),f=jd(p*100,75,90),b=a==="online"?"text-emerald-300":a==="offline"?"text-rose-300":"text-amber-300",h=[{label:"Run Proof",sub:"/proof",command:"/proof",tone:"violet"},{label:"Open Guard",sub:"/guard",command:"/guard",tone:"rose"},{label:"Status Pulse",sub:"/status",command:"/status",tone:"cyan"},{label:"ROI Snapshot",sub:"/roi",command:"/roi",tone:"amber"}];return e.jsxs("section",{"data-testid":"capabilities-matrix",className:"rounded-2xl border border-cyan-400/15 bg-[radial-gradient(circle_at_10%_0%,rgba(45,212,191,0.12),transparent_44%),radial-gradient(circle_at_100%_120%,rgba(167,139,250,0.16),transparent_46%),rgba(8,11,22,0.9)] p-4 space-y-4 shadow-[0_14px_44px_rgba(0,0,0,0.42)]",children:[e.jsxs("header",{className:"grid grid-cols-1 lg:grid-cols-[1.2fr_1fr] gap-3.5 items-stretch",children:[e.jsxs("div",{className:"rounded-2xl border border-white/[0.09] bg-black/30 px-4 py-3.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-cyan-200/85 font-bold",children:"Control Deck"}),e.jsx("h3",{className:"mt-1 text-[20px] leading-tight font-semibold text-slate-100",children:"Run high-trust tasks with live confidence."})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-[12px] text-slate-400 font-mono uppercase tracking-wide",children:"Platform"}),e.jsx("div",{className:"text-[13px] text-slate-300 font-mono",children:s.platform||"unknown"})]})]}),e.jsx("p",{className:"mt-2.5 text-[13px] text-slate-400 leading-6",children:"This panel is your runtime flight deck: it tracks execution health, memory pressure, and model connectivity before you launch proof-critical workflows."}),e.jsx("div",{className:"mt-3.5 grid grid-cols-2 md:grid-cols-4 gap-2",children:h.map(g=>e.jsxs("button",{type:"button",onClick:()=>typeof r=="function"&&r(g.command),className:`rounded-xl border px-3 py-2 text-left transition-all ui-tactile ${Sb(g.tone)}`,children:[e.jsx("div",{className:"text-[12px] font-semibold",children:g.label}),e.jsx("div",{className:"text-[12px] font-mono opacity-80 mt-0.5",children:g.sub})]},g.command))})]}),e.jsxs("div",{className:"rounded-2xl border border-white/[0.09] bg-black/30 px-4 py-3.5 flex flex-col justify-between",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-wide text-slate-500 font-bold",children:"Execution Confidence"}),e.jsx("div",{className:"text-[12px] font-mono text-slate-400",children:"live"})]}),e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"text-[30px] leading-none font-semibold text-slate-100",children:[d,e.jsx("span",{className:"text-[14px] text-slate-500",children:"/99"})]}),e.jsx("div",{className:"mt-2 h-2 rounded-full bg-white/[0.06] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-[linear-gradient(90deg,#34d399,#22d3ee,#a78bfa)] transition-all duration-700",style:{width:`${d}%`}})}),e.jsx("div",{className:"mt-2 text-[13px] text-slate-400 leading-5",children:"Weighted from CPU load, memory pressure, and LLM link state."})]}),e.jsxs("div",{className:"mt-3.5 rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-2 text-[13px] text-slate-300 font-mono",children:[o,"/",l," • ",a.toUpperCase()," • uptime ",kb(s.uptime)]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-2.5",children:[e.jsx(aa,{label:"CPU",value:`${c.toFixed(0)}%`,hint:c>80?"Hot path saturated. Defer non-critical jobs.":"Nominal operator load.",progress:c,tone:m}),e.jsx(aa,{label:"Memory",value:`${u.toFixed(0)} MB`,hint:`Using ${Math.min(100,Math.round(p*100))}% of observed pool`,progress:Math.min(100,p*100),tone:f}),e.jsx(aa,{label:"GPU",value:s.gpuLabel||"N/A",hint:"Renderer acceleration path",tone:"text-violet-200"}),e.jsx(aa,{label:"LLM Link",value:a==="online"?"Connected":a==="offline"?"Offline":"Checking",hint:"Provider transport + model route",tone:b})]})]})});function _b(t){return Math.ceil(String(t||"").length/4)}function Ab(t){return t<6e4?`${Math.floor(t/1e3)}s`:t<36e5?`${Math.floor(t/6e4)}m`:`${Math.floor(t/36e5)}h ${Math.floor(t%36e5/6e4)}m`}const Eb=i.memo(function({chatLog:r,moodEngine:n,isThinking:s}){var m;const a=yn(f=>f),[o,l]=O.useState(!1),c=O.useMemo(()=>{var E,N;if(!Array.isArray(r)||r.length===0)return null;const f=r.filter(_=>_&&_.content&&!_._streaming);if(f.length===0)return null;const b=f.filter(_=>_.role==="user"),h=f.filter(_=>_.role==="kernel"||_.role==="assistant"),g=f.reduce((_,S)=>_+_b(S.content),0),y=f.reduce((_,S)=>_+String(S.content||"").split(/\s+/).filter(Boolean).length,0),P=h.length>0?Math.round(h.reduce((_,S)=>_+String(S.content||"").length,0)/h.length):0,A=(E=f.find(_=>_.ts))==null?void 0:E.ts,C=(N=[...f].reverse().find(_=>_.ts))==null?void 0:N.ts,w=A&&C?C-A:null,j=f.filter(_=>String(_.content||"").includes("```")).length;return{total:f.length,user:b.length,ai:h.length,totalTokens:g,totalWords:y,avgAiLen:P,duration:w,codeBlocks:j}},[r]);if(!c)return null;const u=(n==null?void 0:n.mood)||"neutral",x=((m=n==null?void 0:n.colors)==null?void 0:m.dot)||"#8b5cf6",p=(a==null?void 0:a.model)||"llama3",d=f=>f>=1e3?`${(f/1e3).toFixed(1)}k`:String(f);return e.jsxs("div",{className:"max-w-3xl mx-auto mb-1.5 px-1",children:[e.jsxs("button",{type:"button",onClick:()=>l(f=>!f),className:"w-full flex items-center gap-2 px-2.5 py-1 rounded-lg hover:bg-white/[0.03] transition-all group",title:o?"Collapse session stats":"Expand session stats",children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full shrink-0 transition-colors duration-500",style:{backgroundColor:x,boxShadow:`0 0 5px ${x}80`}}),e.jsx("span",{className:"text-[11px] font-mono text-slate-400 uppercase tracking-wide",children:u}),e.jsx("span",{className:"text-slate-800 mx-1",children:"·"}),e.jsxs("span",{className:"text-[11px] font-mono text-slate-400",children:[e.jsx("span",{className:"text-slate-500",children:c.total})," msgs"]}),e.jsx("span",{className:"text-slate-800 mx-0.5",children:"·"}),e.jsxs("span",{className:"text-[11px] font-mono text-slate-400",children:["~",e.jsx("span",{className:"text-slate-500",children:d(c.totalTokens)})," tokens"]}),e.jsx("span",{className:"text-slate-800 mx-0.5",children:"·"}),e.jsxs("span",{className:"text-[11px] font-mono text-slate-400",children:[e.jsx("span",{className:"text-slate-500",children:d(c.totalWords)})," words"]}),s&&e.jsxs("span",{className:"flex items-center gap-1 ml-1",children:[e.jsx("span",{className:"w-1 h-1 rounded-full animate-pulse",style:{backgroundColor:x}}),e.jsx("span",{className:"text-[11px] font-mono",style:{color:x,opacity:.7},children:"streaming"})]}),e.jsx("span",{className:"ml-auto text-[11px] font-mono text-slate-700 group-hover:text-slate-500 transition-colors",children:o?"▴":"▾"})]}),o&&e.jsxs("div",{className:"mt-1 px-2.5 pb-2 grid grid-cols-3 gap-x-4 gap-y-1.5 border border-white/[0.05] rounded-lg bg-white/[0.02] py-2",children:[e.jsx(pn,{label:"You",value:c.user,unit:"msgs",color:"#D97757"}),e.jsx(pn,{label:"AI",value:c.ai,unit:"msgs",color:"#6B7AFF"}),e.jsx(pn,{label:"Code blocks",value:c.codeBlocks,unit:"",color:"#10A37F"}),e.jsx(pn,{label:"Avg AI reply",value:c.avgAiLen,unit:"chars",color:"#6B7AFF"}),e.jsx(pn,{label:"Model",value:p,unit:"",color:"#8b5cf6",isText:!0}),c.duration!==null&&e.jsx(pn,{label:"Duration",value:Ab(c.duration),unit:"",color:"#f59e0b",isText:!0})]})]})});function pn({label:t,value:r,unit:n,color:s,isText:a}){return e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-[11px] font-mono text-slate-700 uppercase tracking-wider",children:t}),e.jsx("span",{className:"text-[11px] font-mono",style:{color:s},children:a?r:e.jsxs(e.Fragment,{children:[e.jsx("span",{children:r}),n&&e.jsx("span",{className:"text-slate-700 ml-0.5 text-[11px]",children:n})]})})]})}const Ib={ollama:"Ollama",openai:"OpenAI",openrouter:"OpenRouter",groq:"Groq",together:"Together",custom_openai:"Custom"};function Ka(t){const r=String(t||"ollama").trim().toLowerCase();return Ib[r]||r||"none"}function Pb(t){const r=String(t||"").trim();if(!r)return"";const n=new Date(r);if(Number.isNaN(n.getTime()))return r;const s=Date.now()-n.getTime();return s<45e3?"just now":s<36e5?`${Math.max(1,Math.floor(s/6e4))}m ago`:s<864e5?`${Math.max(1,Math.floor(s/36e5))}h ago`:n.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Rb(t){const r=String(t||"").toLowerCase();return r==="online"||r==="healthy"||r==="ready"?{text:"text-emerald-300",dot:"bg-emerald-400",label:"Bridge online"}:r==="degraded"||r==="reconnecting"?{text:"text-amber-300",dot:"bg-amber-400",label:"Bridge degraded"}:r==="offline"||r==="error"?{text:"text-rose-300",dot:"bg-rose-400",label:"Bridge offline"}:{text:"text-slate-400",dot:"bg-slate-500",label:"Bridge unknown"}}function ds({active:t,title:r,onClick:n,children:s,activeClass:a="text-violet-300 bg-violet-500/15 ring-1 ring-violet-500/25",testId:o}){return e.jsx("button",{type:"button","aria-label":r,"data-testid":o,onClick:n,title:r,className:`p-1.5 rounded-lg transition-all active:scale-90 ${t?a:"text-slate-500 hover:text-slate-200 hover:bg-white/[0.06]"}`,children:s})}const Ob=i.memo(function({moodEngine:r,pane:n,panels:s,rgbEnabled:a=!1,rgbStatus:o=null,activeTaskCount:l=0,onOpenTaskManager:c,onToggleWorkpad:u,workpadOpen:x=!1,workpadOpenCount:p=0}){var P;const d=yn(A=>A),m=(r==null?void 0:r.mood)||"neutral",f=((P=r==null?void 0:r.colors)==null?void 0:P.dot)||"#8b5cf6",b=(r==null?void 0:r.label)||m,h=Rb(d==null?void 0:d.health),g=Array.isArray(n==null?void 0:n.chatLog)?n.chatLog.filter(A=>A&&!A._streaming).length:0,y=!!(a&&o&&o.ok!==!1);return e.jsxs("div",{"data-testid":"user-hud",className:"rounded-xl border bg-black/25 backdrop-blur-sm overflow-hidden",style:{borderColor:`${f}35`,boxShadow:`inset 0 1px 0 ${f}18, 0 8px 24px rgba(0,0,0,0.22)`},children:[e.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-x-3 gap-y-1.5 border-b border-white/[0.05]",style:{background:`linear-gradient(90deg, ${f}10 0%, transparent 72%)`},children:[e.jsxs("div",{className:"inline-flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:`h-2.5 w-2.5 rounded-full shrink-0 ${n!=null&&n.isThinking?"animate-pulse":""}`,style:{backgroundColor:f,boxShadow:`0 0 10px ${f}88`}}),e.jsx("span",{className:"text-[10px] font-mono uppercase tracking-[0.18em] font-bold",style:{color:f},children:b})]}),e.jsx("span",{className:"text-slate-700 hidden sm:inline",children:"·"}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 text-[10px] font-mono min-w-0",children:[e.jsx("span",{className:"text-slate-500 uppercase tracking-wider",children:"Model"}),e.jsx("span",{className:"text-slate-200 truncate max-w-[9rem]",children:(n==null?void 0:n.model)||(d==null?void 0:d.model)||"not set"})]}),e.jsx("span",{className:"text-slate-700 hidden sm:inline",children:"·"}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 text-[10px] font-mono",children:[e.jsx("span",{className:"text-slate-500",children:g}),e.jsx("span",{className:"text-slate-400",children:"msgs"})]}),e.jsx("span",{className:"text-slate-700 hidden md:inline",children:"·"}),e.jsxs("div",{className:`hidden md:inline-flex items-center gap-1.5 text-[10px] font-mono ${h.text}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${h.dot}`}),e.jsx("span",{children:Ka(d==null?void 0:d.provider)}),e.jsx("span",{className:"text-slate-600",children:"·"}),e.jsx("span",{children:h.label})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-slate-700 hidden lg:inline",children:"·"}),e.jsxs("div",{"data-testid":"user-hud-rgb-sync",className:`hidden lg:inline-flex items-center gap-1.5 text-[10px] font-mono uppercase tracking-[0.14em] ${y?"text-cyan-200":"text-slate-500"}`,title:y?"RGB hardware synced to AI mood":"RGB sync enabled — waiting for controller",children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${y?"bg-cyan-400 animate-pulse":"bg-slate-600"}`}),"RGB sync"]})]}),(n==null?void 0:n.isThinking)&&e.jsxs("span",{className:"ml-auto inline-flex items-center gap-1.5 text-[10px] font-mono",style:{color:f},children:[e.jsx("span",{className:"h-1 w-1 rounded-full animate-pulse",style:{backgroundColor:f}}),"streaming"]}),typeof c=="function"&&e.jsx("button",{type:"button","data-testid":"user-hud-inbox-btn",onClick:c,title:"Open Operator Inbox (Ctrl+Shift+T)","aria-label":"Open Operator Inbox",className:`${n!=null&&n.isThinking?"":"ml-auto "}inline-flex items-center gap-1.5 px-2 py-0.5 rounded-lg border text-[10px] font-mono transition-colors ${Number(l)+Number(p)>0?"border-violet-400/25 bg-violet-500/10 text-violet-200 hover:bg-violet-500/15":"border-white/10 bg-white/[0.03] text-slate-500 hover:text-slate-300 hover:bg-white/[0.06]"}`,children:Number(l)+Number(p)>0?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-violet-400 animate-pulse"}),"Activity",Number(l)>0?` · ${l} ops`:"",Number(p)>0?` · ${p} tasks`:""]}):e.jsxs(e.Fragment,{children:[e.jsxs("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.75,children:[e.jsx("path",{d:"M4 4h16v16H4z"}),e.jsx("path",{d:"M4 9h16M9 9v11"})]}),"Inbox"]})})]}),s&&e.jsxs("div",{className:"px-2 py-1.5 flex items-center gap-1 border-t border-white/[0.04] bg-black/20",children:[e.jsx("span",{className:"text-[9px] font-mono uppercase tracking-[0.16em] text-slate-600 px-1.5 hidden sm:inline",children:"Panels"}),e.jsx(ds,{title:"Voice input",testId:"user-hud-panel-voice",active:s.isOpen("voice-mode"),onClick:()=>s.open("voice-mode"),activeClass:"text-violet-300 bg-violet-500/15 ring-1 ring-violet-500/25",children:e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:[e.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),e.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),e.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),e.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]})}),e.jsx(ds,{title:"AI Memory",testId:"user-hud-panel-memory",active:s.isOpen("ai-memory"),onClick:()=>s.toggle("ai-memory"),activeClass:"text-rose-300 bg-rose-500/15 ring-1 ring-rose-500/25",children:e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{d:"M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4"})})}),e.jsx(ds,{title:"Knowledge Base",testId:"user-hud-panel-knowledge",active:s.isOpen("knowledge-base"),onClick:()=>s.open("knowledge-base"),activeClass:"text-emerald-300 bg-emerald-500/15 ring-1 ring-emerald-500/25",children:e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{d:"M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"})})}),e.jsx(ds,{title:"Multi-model compare",testId:"user-hud-panel-compare",active:s.isOpen("multi-model-split"),onClick:()=>s.open("multi-model-split"),activeClass:"text-indigo-300 bg-indigo-500/15 ring-1 ring-indigo-500/25",children:e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{d:"M9 3h6v6H9zM9 15h6v6H9zM3 9h6v6H3zM15 9h6v6h-6z"})})}),typeof u=="function"&&e.jsx(ds,{title:"Workpad (Ctrl+Shift+N)",testId:"user-hud-panel-workpad",active:x,onClick:u,activeClass:"text-amber-300 bg-amber-500/15 ring-1 ring-amber-500/25",children:e.jsxs("span",{className:"relative inline-flex",children:[e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:[e.jsx("path",{d:"M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2"}),e.jsx("rect",{x:"9",y:"3",width:"6",height:"4",rx:"1"}),e.jsx("path",{d:"M9 12h6M9 16h6"})]}),Number(p)>0&&e.jsx("span",{className:"absolute -top-1.5 -right-2 min-w-3.5 h-3.5 px-0.5 rounded-full bg-amber-500 text-[8px] font-bold text-black flex items-center justify-center",children:p>9?"9+":p})]})}),e.jsx("span",{className:"ml-auto text-[10px] font-mono text-slate-600 pr-1 hidden sm:inline",children:"↵ send · ⇧↵ newline"})]})]})});function Tb(t){return!!(t&&typeof t=="object"&&t.ok===!1)}const Tp="neuralshell_smart_suggest_cache_v1",kd=40;function Nd(){try{return JSON.parse(window.localStorage.getItem(Tp)||"{}")}catch{return{}}}function Mb(t){try{window.localStorage.setItem(Tp,JSON.stringify(t))}catch{}}function Db(t){return String(t||"").slice(0,120)}const Oa=["Can you explain that in simpler terms?","What are the trade-offs here?","Show me a code example.","What should I do next?"];function $b(t){return String(t||"").split(` +${Z}`+(W||"")},...H?S.chatLog.filter(me=>!me._streaming).slice(-8):S.chatLog.filter(me=>!me._streaming),P];window.api.llm.streamChat(fe,{paneId:String(S.id||N),workflowId:String(S.workflowId||n||"default")}).catch(me=>{ye(J||`Error: ${me&&me.message?me.message:String(me)}`)})})}else try{if(typeof t=="function"){const z=await t(N,R,S);if(p.current[N]!==U)return;const F={role:"assistant",content:z||"…",ts:Date.now()};f(N,J=>({isThinking:!1,chatLog:[...J.chatLog,F]}))}else x.current[N]=setTimeout(()=>{p.current[N]===U&&f(N,z=>({isThinking:!1,chatLog:[...z.chatLog,{role:"assistant",content:"(no send handler connected)",ts:Date.now()}]}))},400)}catch{p.current[N]===U&&f(N,{isThinking:!1})}},[s,f,t,r,l,n]),w=O.useCallback(N=>{p.current[N]=(p.current[N]||0)+1,f(N,{chatLog:[],isThinking:!1})},[f]),j=O.useCallback(N=>{a(_=>_.map(S=>S.id===N?{...S,isPinned:!S.isPinned}:S))},[]),E=O.useMemo(()=>s.find(N=>N.id===o)??s[0]??null,[s,o]);return O.useMemo(()=>({panes:s,activePaneId:o,activePane:E,layout:l,setLayout:d,setActivePaneId:c,resetPanes:A,addPane:b,removePane:h,duplicatePane:g,renamePane:y,setPrompt:I,sendMessage:C,clearChat:w,pinPane:j,updatePane:f,loadSession:m}),[s,o,E,l,d,c,A,b,h,g,y,I,C,w,j,f,m])}const wn=Dl(t=>({provider:"ollama",baseUrl:"",model:"llama3",allowRemoteBridge:!1,health:"unknown",reason:"",setConnectionInfo:r=>t(r)}));function jb(){const[t,r]=i.useState({cpuPercent:0,memoryMb:0,memoryTotalMb:0,gpuLabel:"",uptime:0,platform:""});return i.useEffect(()=>{let n=!0;const s=async()=>{try{const o=typeof window<"u"&&window.api&&window.api.system&&typeof window.api.system.getStats=="function"?await window.api.system.getStats():{};if(n&&o&&typeof o=="object"&&o.ok===!1)return;n&&r({cpuPercent:Number(o.cpuPercent||0),memoryMb:Number(o.memoryMb||0),memoryTotalMb:Number(o.memoryTotalMb||0),gpuLabel:String(o.gpuLabel||o.gpu||"N/A"),uptime:Number(o.uptime||0),platform:String(o.platform||"")})}catch{}};s();const a=setInterval(s,3e3);return()=>{n=!1,clearInterval(a)}},[]),t}function kb(t){const r=Math.max(0,Math.floor(Number(t)||0)),n=Math.floor(r/3600),s=Math.floor(r%3600/60);return n>0?`${n}h ${s}m`:`${s}m`}function Nb({cpu:t,memoryRatio:r,connHealth:n}){let s=98;return t>85?s-=24:t>65&&(s-=12),r>.9?s-=18:r>.75&&(s-=9),n==="offline"?s-=28:n!=="online"&&(s-=10),Math.max(1,Math.min(99,s))}function jd(t,r,n){return t>=n?"text-rose-300":t>=r?"text-amber-300":"text-emerald-300"}function Sb(t){return t==="rose"?"border-rose-400/30 bg-rose-500/10 text-rose-200 hover:bg-rose-500/20":t==="cyan"?"border-cyan-400/30 bg-cyan-500/10 text-cyan-200 hover:bg-cyan-500/20":t==="amber"?"border-amber-400/30 bg-amber-500/10 text-amber-200 hover:bg-amber-500/20":"border-violet-400/30 bg-violet-500/10 text-violet-200 hover:bg-violet-500/20"}function aa({label:t,value:r,hint:n,progress:s,tone:a="text-slate-200"}){return e.jsxs("article",{className:"rounded-xl border border-white/[0.08] bg-black/25 px-3 py-2.5 space-y-1.5 ui-tactile",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-slate-500 font-bold",children:t}),e.jsx("div",{className:`text-[14px] font-mono font-semibold ${a}`,children:r}),typeof s=="number"&&e.jsx("div",{className:"h-1.5 rounded-full bg-white/[0.06] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-cyan-400 to-violet-400 transition-all duration-700",style:{width:`${Math.max(0,Math.min(100,s))}%`}})}),e.jsx("div",{className:"text-[13px] text-slate-400 leading-5",children:n})]})}const Cb=i.memo(function({onCommand:r}){const n=wn(g=>g),s=jb(),a=String(n&&n.health||"unknown"),o=String(n&&n.provider||"local"),c=String(n&&n.model||"llama3"),l=Number(s.cpuPercent||0),u=Number(s.memoryMb||0),x=Number(s.memoryTotalMb||16384),p=x>0?u/x:0,d=Nb({cpu:l,memoryRatio:p,connHealth:a}),m=jd(l,65,85),f=jd(p*100,75,90),b=a==="online"?"text-emerald-300":a==="offline"?"text-rose-300":"text-amber-300",h=[{label:"Run Proof",sub:"/proof",command:"/proof",tone:"violet"},{label:"Open Guard",sub:"/guard",command:"/guard",tone:"rose"},{label:"Status Pulse",sub:"/status",command:"/status",tone:"cyan"},{label:"ROI Snapshot",sub:"/roi",command:"/roi",tone:"amber"}];return e.jsxs("section",{"data-testid":"capabilities-matrix",className:"rounded-2xl border border-cyan-400/15 bg-[radial-gradient(circle_at_10%_0%,rgba(45,212,191,0.12),transparent_44%),radial-gradient(circle_at_100%_120%,rgba(167,139,250,0.16),transparent_46%),rgba(8,11,22,0.9)] p-4 space-y-4 shadow-[0_14px_44px_rgba(0,0,0,0.42)]",children:[e.jsxs("header",{className:"grid grid-cols-1 lg:grid-cols-[1.2fr_1fr] gap-3.5 items-stretch",children:[e.jsxs("div",{className:"rounded-2xl border border-white/[0.09] bg-black/30 px-4 py-3.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-cyan-200/85 font-bold",children:"Control Deck"}),e.jsx("h3",{className:"mt-1 text-[20px] leading-tight font-semibold text-slate-100",children:"Run high-trust tasks with live confidence."})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-[12px] text-slate-400 font-mono uppercase tracking-wide",children:"Platform"}),e.jsx("div",{className:"text-[13px] text-slate-300 font-mono",children:s.platform||"unknown"})]})]}),e.jsx("p",{className:"mt-2.5 text-[13px] text-slate-400 leading-6",children:"This panel is your runtime flight deck: it tracks execution health, memory pressure, and model connectivity before you launch proof-critical workflows."}),e.jsx("div",{className:"mt-3.5 grid grid-cols-2 md:grid-cols-4 gap-2",children:h.map(g=>e.jsxs("button",{type:"button",onClick:()=>typeof r=="function"&&r(g.command),className:`rounded-xl border px-3 py-2 text-left transition-all ui-tactile ${Sb(g.tone)}`,children:[e.jsx("div",{className:"text-[12px] font-semibold",children:g.label}),e.jsx("div",{className:"text-[12px] font-mono opacity-80 mt-0.5",children:g.sub})]},g.command))})]}),e.jsxs("div",{className:"rounded-2xl border border-white/[0.09] bg-black/30 px-4 py-3.5 flex flex-col justify-between",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-wide text-slate-500 font-bold",children:"Execution Confidence"}),e.jsx("div",{className:"text-[12px] font-mono text-slate-400",children:"live"})]}),e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"text-[30px] leading-none font-semibold text-slate-100",children:[d,e.jsx("span",{className:"text-[14px] text-slate-500",children:"/99"})]}),e.jsx("div",{className:"mt-2 h-2 rounded-full bg-white/[0.06] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-[linear-gradient(90deg,#34d399,#22d3ee,#a78bfa)] transition-all duration-700",style:{width:`${d}%`}})}),e.jsx("div",{className:"mt-2 text-[13px] text-slate-400 leading-5",children:"Weighted from CPU load, memory pressure, and LLM link state."})]}),e.jsxs("div",{className:"mt-3.5 rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-2 text-[13px] text-slate-300 font-mono",children:[o,"/",c," • ",a.toUpperCase()," • uptime ",kb(s.uptime)]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-2.5",children:[e.jsx(aa,{label:"CPU",value:`${l.toFixed(0)}%`,hint:l>80?"Hot path saturated. Defer non-critical jobs.":"Nominal operator load.",progress:l,tone:m}),e.jsx(aa,{label:"Memory",value:`${u.toFixed(0)} MB`,hint:`Using ${Math.min(100,Math.round(p*100))}% of observed pool`,progress:Math.min(100,p*100),tone:f}),e.jsx(aa,{label:"GPU",value:s.gpuLabel||"N/A",hint:"Renderer acceleration path",tone:"text-violet-200"}),e.jsx(aa,{label:"LLM Link",value:a==="online"?"Connected":a==="offline"?"Offline":"Checking",hint:"Provider transport + model route",tone:b})]})]})});function _b(t){return Math.ceil(String(t||"").length/4)}function Ab(t){return t<6e4?`${Math.floor(t/1e3)}s`:t<36e5?`${Math.floor(t/6e4)}m`:`${Math.floor(t/36e5)}h ${Math.floor(t%36e5/6e4)}m`}const Eb=i.memo(function({chatLog:r,moodEngine:n,isThinking:s}){var m;const a=wn(f=>f),[o,c]=O.useState(!1),l=O.useMemo(()=>{var E,N;if(!Array.isArray(r)||r.length===0)return null;const f=r.filter(_=>_&&_.content&&!_._streaming);if(f.length===0)return null;const b=f.filter(_=>_.role==="user"),h=f.filter(_=>_.role==="kernel"||_.role==="assistant"),g=f.reduce((_,S)=>_+_b(S.content),0),y=f.reduce((_,S)=>_+String(S.content||"").split(/\s+/).filter(Boolean).length,0),I=h.length>0?Math.round(h.reduce((_,S)=>_+String(S.content||"").length,0)/h.length):0,A=(E=f.find(_=>_.ts))==null?void 0:E.ts,C=(N=[...f].reverse().find(_=>_.ts))==null?void 0:N.ts,w=A&&C?C-A:null,j=f.filter(_=>String(_.content||"").includes("```")).length;return{total:f.length,user:b.length,ai:h.length,totalTokens:g,totalWords:y,avgAiLen:I,duration:w,codeBlocks:j}},[r]);if(!l)return null;const u=(n==null?void 0:n.mood)||"neutral",x=((m=n==null?void 0:n.colors)==null?void 0:m.dot)||"#8b5cf6",p=(a==null?void 0:a.model)||"llama3",d=f=>f>=1e3?`${(f/1e3).toFixed(1)}k`:String(f);return e.jsxs("div",{className:"max-w-3xl mx-auto mb-1.5 px-1",children:[e.jsxs("button",{type:"button",onClick:()=>c(f=>!f),className:"w-full flex items-center gap-2 px-2.5 py-1 rounded-lg hover:bg-white/[0.03] transition-all group",title:o?"Collapse session stats":"Expand session stats",children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full shrink-0 transition-colors duration-500",style:{backgroundColor:x,boxShadow:`0 0 5px ${x}80`}}),e.jsx("span",{className:"text-[11px] font-mono text-slate-400 uppercase tracking-wide",children:u}),e.jsx("span",{className:"text-slate-800 mx-1",children:"·"}),e.jsxs("span",{className:"text-[11px] font-mono text-slate-400",children:[e.jsx("span",{className:"text-slate-500",children:l.total})," msgs"]}),e.jsx("span",{className:"text-slate-800 mx-0.5",children:"·"}),e.jsxs("span",{className:"text-[11px] font-mono text-slate-400",children:["~",e.jsx("span",{className:"text-slate-500",children:d(l.totalTokens)})," tokens"]}),e.jsx("span",{className:"text-slate-800 mx-0.5",children:"·"}),e.jsxs("span",{className:"text-[11px] font-mono text-slate-400",children:[e.jsx("span",{className:"text-slate-500",children:d(l.totalWords)})," words"]}),s&&e.jsxs("span",{className:"flex items-center gap-1 ml-1",children:[e.jsx("span",{className:"w-1 h-1 rounded-full animate-pulse",style:{backgroundColor:x}}),e.jsx("span",{className:"text-[11px] font-mono",style:{color:x,opacity:.7},children:"streaming"})]}),e.jsx("span",{className:"ml-auto text-[11px] font-mono text-slate-700 group-hover:text-slate-500 transition-colors",children:o?"▴":"▾"})]}),o&&e.jsxs("div",{className:"mt-1 px-2.5 pb-2 grid grid-cols-3 gap-x-4 gap-y-1.5 border border-white/[0.05] rounded-lg bg-white/[0.02] py-2",children:[e.jsx(pn,{label:"You",value:l.user,unit:"msgs",color:"#D97757"}),e.jsx(pn,{label:"AI",value:l.ai,unit:"msgs",color:"#6B7AFF"}),e.jsx(pn,{label:"Code blocks",value:l.codeBlocks,unit:"",color:"#10A37F"}),e.jsx(pn,{label:"Avg AI reply",value:l.avgAiLen,unit:"chars",color:"#6B7AFF"}),e.jsx(pn,{label:"Model",value:p,unit:"",color:"#8b5cf6",isText:!0}),l.duration!==null&&e.jsx(pn,{label:"Duration",value:Ab(l.duration),unit:"",color:"#f59e0b",isText:!0})]})]})});function pn({label:t,value:r,unit:n,color:s,isText:a}){return e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-[11px] font-mono text-slate-700 uppercase tracking-wider",children:t}),e.jsx("span",{className:"text-[11px] font-mono",style:{color:s},children:a?r:e.jsxs(e.Fragment,{children:[e.jsx("span",{children:r}),n&&e.jsx("span",{className:"text-slate-700 ml-0.5 text-[11px]",children:n})]})})]})}const Ib={ollama:"Ollama",openai:"OpenAI",openrouter:"OpenRouter",groq:"Groq",together:"Together",custom_openai:"Custom"};function Ka(t){const r=String(t||"ollama").trim().toLowerCase();return Ib[r]||r||"none"}function Pb(t){const r=String(t||"").trim();if(!r)return"";const n=new Date(r);if(Number.isNaN(n.getTime()))return r;const s=Date.now()-n.getTime();return s<45e3?"just now":s<36e5?`${Math.max(1,Math.floor(s/6e4))}m ago`:s<864e5?`${Math.max(1,Math.floor(s/36e5))}h ago`:n.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Rb(t){const r=String(t||"").toLowerCase();return r==="online"||r==="healthy"||r==="ready"?{text:"text-emerald-300",dot:"bg-emerald-400",label:"Bridge online"}:r==="degraded"||r==="reconnecting"?{text:"text-amber-300",dot:"bg-amber-400",label:"Bridge degraded"}:r==="offline"||r==="error"?{text:"text-rose-300",dot:"bg-rose-400",label:"Bridge offline"}:{text:"text-slate-400",dot:"bg-slate-500",label:"Bridge unknown"}}function us({active:t,title:r,onClick:n,children:s,activeClass:a="text-violet-300 bg-violet-500/15 ring-1 ring-violet-500/25",testId:o}){return e.jsx("button",{type:"button","aria-label":r,"data-testid":o,onClick:n,title:r,className:`p-1.5 rounded-lg transition-all active:scale-90 ${t?a:"text-slate-500 hover:text-slate-200 hover:bg-white/[0.06]"}`,children:s})}const Ob=i.memo(function({moodEngine:r,pane:n,panels:s,rgbEnabled:a=!1,rgbStatus:o=null,activeTaskCount:c=0,onOpenTaskManager:l,onToggleWorkpad:u,workpadOpen:x=!1,workpadOpenCount:p=0}){var I;const d=wn(A=>A),m=(r==null?void 0:r.mood)||"neutral",f=((I=r==null?void 0:r.colors)==null?void 0:I.dot)||"#8b5cf6",b=(r==null?void 0:r.label)||m,h=Rb(d==null?void 0:d.health),g=Array.isArray(n==null?void 0:n.chatLog)?n.chatLog.filter(A=>A&&!A._streaming).length:0,y=!!(a&&o&&o.ok!==!1);return e.jsxs("div",{"data-testid":"user-hud",className:"rounded-xl border bg-black/25 backdrop-blur-sm overflow-hidden",style:{borderColor:`${f}35`,boxShadow:`inset 0 1px 0 ${f}18, 0 8px 24px rgba(0,0,0,0.22)`},children:[e.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-x-3 gap-y-1.5 border-b border-white/[0.05]",style:{background:`linear-gradient(90deg, ${f}10 0%, transparent 72%)`},children:[e.jsxs("div",{className:"inline-flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:`h-2.5 w-2.5 rounded-full shrink-0 ${n!=null&&n.isThinking?"animate-pulse":""}`,style:{backgroundColor:f,boxShadow:`0 0 10px ${f}88`}}),e.jsx("span",{className:"text-[10px] font-mono uppercase tracking-[0.18em] font-bold",style:{color:f},children:b})]}),e.jsx("span",{className:"text-slate-700 hidden sm:inline",children:"·"}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 text-[10px] font-mono min-w-0",children:[e.jsx("span",{className:"text-slate-500 uppercase tracking-wider",children:"Model"}),e.jsx("span",{className:"text-slate-200 truncate max-w-[9rem]",children:(n==null?void 0:n.model)||(d==null?void 0:d.model)||"not set"})]}),e.jsx("span",{className:"text-slate-700 hidden sm:inline",children:"·"}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 text-[10px] font-mono",children:[e.jsx("span",{className:"text-slate-500",children:g}),e.jsx("span",{className:"text-slate-400",children:"msgs"})]}),e.jsx("span",{className:"text-slate-700 hidden md:inline",children:"·"}),e.jsxs("div",{className:`hidden md:inline-flex items-center gap-1.5 text-[10px] font-mono ${h.text}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${h.dot}`}),e.jsx("span",{children:Ka(d==null?void 0:d.provider)}),e.jsx("span",{className:"text-slate-600",children:"·"}),e.jsx("span",{children:h.label})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-slate-700 hidden lg:inline",children:"·"}),e.jsxs("div",{"data-testid":"user-hud-rgb-sync",className:`hidden lg:inline-flex items-center gap-1.5 text-[10px] font-mono uppercase tracking-[0.14em] ${y?"text-cyan-200":"text-slate-500"}`,title:y?"RGB hardware synced to AI mood":"RGB sync enabled — waiting for controller",children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${y?"bg-cyan-400 animate-pulse":"bg-slate-600"}`}),"RGB sync"]})]}),(n==null?void 0:n.isThinking)&&e.jsxs("span",{className:"ml-auto inline-flex items-center gap-1.5 text-[10px] font-mono",style:{color:f},children:[e.jsx("span",{className:"h-1 w-1 rounded-full animate-pulse",style:{backgroundColor:f}}),"streaming"]}),typeof l=="function"&&e.jsx("button",{type:"button","data-testid":"user-hud-inbox-btn",onClick:l,title:"Open Operator Inbox (Ctrl+Shift+T)","aria-label":"Open Operator Inbox",className:`${n!=null&&n.isThinking?"":"ml-auto "}inline-flex items-center gap-1.5 px-2 py-0.5 rounded-lg border text-[10px] font-mono transition-colors ${Number(c)+Number(p)>0?"border-violet-400/25 bg-violet-500/10 text-violet-200 hover:bg-violet-500/15":"border-white/10 bg-white/[0.03] text-slate-500 hover:text-slate-300 hover:bg-white/[0.06]"}`,children:Number(c)+Number(p)>0?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-violet-400 animate-pulse"}),"Activity",Number(c)>0?` · ${c} ops`:"",Number(p)>0?` · ${p} tasks`:""]}):e.jsxs(e.Fragment,{children:[e.jsxs("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.75,children:[e.jsx("path",{d:"M4 4h16v16H4z"}),e.jsx("path",{d:"M4 9h16M9 9v11"})]}),"Inbox"]})})]}),s&&e.jsxs("div",{className:"px-2 py-1.5 flex items-center gap-1 border-t border-white/[0.04] bg-black/20",children:[e.jsx("span",{className:"text-[9px] font-mono uppercase tracking-[0.16em] text-slate-600 px-1.5 hidden sm:inline",children:"Panels"}),e.jsx(us,{title:"Voice input",testId:"user-hud-panel-voice",active:s.isOpen("voice-mode"),onClick:()=>s.open("voice-mode"),activeClass:"text-violet-300 bg-violet-500/15 ring-1 ring-violet-500/25",children:e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:[e.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),e.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),e.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),e.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]})}),e.jsx(us,{title:"AI Memory",testId:"user-hud-panel-memory",active:s.isOpen("ai-memory"),onClick:()=>s.toggle("ai-memory"),activeClass:"text-rose-300 bg-rose-500/15 ring-1 ring-rose-500/25",children:e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{d:"M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4"})})}),e.jsx(us,{title:"Knowledge Base",testId:"user-hud-panel-knowledge",active:s.isOpen("knowledge-base"),onClick:()=>s.open("knowledge-base"),activeClass:"text-emerald-300 bg-emerald-500/15 ring-1 ring-emerald-500/25",children:e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{d:"M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"})})}),e.jsx(us,{title:"Multi-model compare",testId:"user-hud-panel-compare",active:s.isOpen("multi-model-split"),onClick:()=>s.open("multi-model-split"),activeClass:"text-indigo-300 bg-indigo-500/15 ring-1 ring-indigo-500/25",children:e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{d:"M9 3h6v6H9zM9 15h6v6H9zM3 9h6v6H3zM15 9h6v6h-6z"})})}),typeof u=="function"&&e.jsx(us,{title:"Workpad (Ctrl+Shift+N)",testId:"user-hud-panel-workpad",active:x,onClick:u,activeClass:"text-amber-300 bg-amber-500/15 ring-1 ring-amber-500/25",children:e.jsxs("span",{className:"relative inline-flex",children:[e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:[e.jsx("path",{d:"M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2"}),e.jsx("rect",{x:"9",y:"3",width:"6",height:"4",rx:"1"}),e.jsx("path",{d:"M9 12h6M9 16h6"})]}),Number(p)>0&&e.jsx("span",{className:"absolute -top-1.5 -right-2 min-w-3.5 h-3.5 px-0.5 rounded-full bg-amber-500 text-[8px] font-bold text-black flex items-center justify-center",children:p>9?"9+":p})]})}),e.jsx("span",{className:"ml-auto text-[10px] font-mono text-slate-600 pr-1 hidden sm:inline",children:"↵ send · ⇧↵ newline"})]})]})});function Tb(t){return!!(t&&typeof t=="object"&&t.ok===!1)}const Tp="neuralshell_smart_suggest_cache_v1",kd=40;function Nd(){try{return JSON.parse(window.localStorage.getItem(Tp)||"{}")}catch{return{}}}function Mb(t){try{window.localStorage.setItem(Tp,JSON.stringify(t))}catch{}}function Db(t){return String(t||"").slice(0,120)}const Oa=["Can you explain that in simpler terms?","What are the trade-offs here?","Show me a code example.","What should I do next?"];function $b(t){return String(t||"").split(` `).map(s=>s.replace(/^[\d*.)-]+\s*/,"").replace(/^["']|["']$/g,"").trim()).filter(s=>s.length>4&&s.length<120&&!s.startsWith("{")&&!s.startsWith("[")).slice(0,4)}async function Lb(t,r){try{const s=window.localStorage.getItem("neuralshell_ui_prefs_v1"),a=s?JSON.parse(s):{};if(a&&a.turboFastLaneEnabled)return Oa}catch{}const n=`Based on this exchange, give exactly 4 short follow-up questions or prompts the user might want to ask next. Reply with ONLY a numbered list, one per line, no explanations. User: ${String(t||"").slice(0,300)} @@ -103,12 +103,12 @@ Assistant: ${String(r||"").slice(0,500)}`;if(window.api&&window.api.llm&&typeof ${s} -You generate concise follow-up suggestions. Reply only with a numbered list.`},{role:"user",content:n}]);if(Tb(a))return Oa;const o=a&&a.message?a.message.content:a&&a.content?a.content:"";return $b(o)}return[]}const Bb=i.memo(function({chatLog:r,onSend:n,isThinking:s}){const[a,o]=O.useState([]),[l,c]=O.useState(!1),[u,x]=O.useState(!1),[p,d]=O.useState(-1),m=O.useRef(""),f=O.useRef(!0),b=O.useRef(null);O.useEffect(()=>(f.current=!0,()=>{f.current=!1}),[]);const h=O.useCallback(P=>{x(!0),typeof n=="function"&&n(P)},[n]),g=O.useCallback(async()=>{if(!Array.isArray(r)||r.length<2||s)return;const P=r.filter(E=>E&&E.content&&!E._streaming),A=[...P].reverse().find(E=>E.role==="kernel"||E.role==="assistant"),C=[...P].reverse().find(E=>E.role==="user");if(!A||!C)return;const w=Db(A.content);if(w===m.current)return;m.current=w,x(!1),d(-1);const j=Nd();if(j[w]){o(j[w]);return}c(!0),o([]);try{const E=await Lb(C.content,A.content);if(!f.current)return;const N=E.length>=2?E:Oa;o(N);const _={...Nd(),[w]:N},S=Object.keys(_);S.length>kd&&S.slice(0,S.length-kd).forEach(R=>delete _[R]),Mb(_)}catch{f.current&&o(Oa)}finally{f.current&&c(!1)}},[r,s]);O.useEffect(()=>{if(s)return;const P=setTimeout(g,600);return()=>clearTimeout(P)},[r,s,g]);const y=O.useCallback(P=>{a.length&&(P.key==="ArrowRight"||P.key==="ArrowDown"?(P.preventDefault(),d(A=>(A+1)%a.length)):P.key==="ArrowLeft"||P.key==="ArrowUp"?(P.preventDefault(),d(A=>A<=0?a.length-1:A-1)):P.key==="Enter"&&p>=0?(P.preventDefault(),h(a[p])):P.key==="Escape"&&(P.preventDefault(),x(!0)))},[h,p,a]);return u||s||a.length===0?null:e.jsx("div",{className:"max-w-3xl mx-auto px-1 pb-2 pt-1",children:e.jsxs("div",{ref:b,"data-testid":"smart-suggest-row",role:"group","aria-label":"Suggested follow-ups",tabIndex:0,onKeyDown:y,className:"flex items-center gap-1.5 flex-wrap outline-none focus-visible:ring-1 focus-visible:ring-violet-400/30 rounded-lg",children:[e.jsx("span",{className:"text-[11px] font-mono text-slate-700 uppercase tracking-wide shrink-0 mr-0.5","aria-hidden":"true",children:l?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-slate-600 animate-bounce",style:{animationDelay:"0ms"}}),e.jsx("span",{className:"w-1 h-1 rounded-full bg-slate-600 animate-bounce",style:{animationDelay:"150ms"}}),e.jsx("span",{className:"w-1 h-1 rounded-full bg-slate-600 animate-bounce",style:{animationDelay:"300ms"}})]}):e.jsx($x,{size:12,className:"text-violet-400/70"})}),a.map((P,A)=>e.jsxs("button",{type:"button","data-testid":`smart-suggest-chip-${A}`,"aria-label":`Apply suggestion: ${P}`,"aria-pressed":p===A,onFocus:()=>d(A),onClick:()=>h(P),className:`group flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] border transition-all active:scale-95 ${p===A?"border-violet-400/40 bg-violet-500/15 text-slate-100":"border-white/[0.07] bg-white/[0.03] text-slate-400 hover:text-slate-100 hover:border-violet-500/30 hover:bg-violet-500/10"}`,children:[e.jsx(Lx,{size:11,className:"text-violet-500/50 group-hover:text-violet-400/80 transition-colors shrink-0","aria-hidden":"true"}),P]},A)),e.jsx("button",{type:"button","data-testid":"smart-suggest-dismiss-btn","aria-label":"Dismiss suggestions",onClick:()=>x(!0),className:"ml-auto text-slate-700 hover:text-slate-400 transition-colors px-1 py-1 rounded-md hover:bg-white/[0.04]",children:e.jsx(yp,{size:12,"aria-hidden":"true"})})]})})}),Jl="neuralshell_deadlines_v1",bl="neuralshell:deadlines-changed";function Fb(t){return t&&typeof t=="object"&&typeof t.title=="string"&&typeof t.date=="string"}function Is(t){return{id:String(t.id||`${t.date}-${t.title}`),title:String(t.title||"").trim(),date:String(t.date||"").trim(),priority:String(t.priority||"normal").trim().toLowerCase()||"normal"}}function Sn(t){return[...t].sort((r,n)=>{const s=r.date.localeCompare(n.date);return s!==0?s:r.title.localeCompare(n.title)})}function Qt(){try{const t=JSON.parse(window.localStorage.getItem(Jl)||"[]");return Array.isArray(t)?Sn(t.filter(Fb).map(Is).filter(r=>r.title&&r.date)):[]}catch{return[]}}function Ta(t){const r=Sn((Array.isArray(t)?t:[]).map(Is).filter(n=>n.title&&n.date));try{window.localStorage.setItem(Jl,JSON.stringify(r))}catch{}try{window.dispatchEvent(new CustomEvent(bl,{detail:r}))}catch{}return r}function Ub(t){const r=new Date;r.setHours(0,0,0,0);const n=new Date(`${t}T00:00:00`);return Number.isNaN(n.getTime())?Number.POSITIVE_INFINITY:Math.round((n-r)/864e5)}function zb(t,r,n){return`${String(t)}-${String(r).padStart(2,"0")}-${String(n).padStart(2,"0")}`}function Hb(t){const r=String(t||"").trim().match(/^(\d{4})-(\d{2})-(\d{2})$/);return r?{year:Number(r[1]),month:Number(r[2]),day:Number(r[3])}:null}function Mp(t,r){const n=Is(r);if(!n.title||!n.date)return Sn(Array.isArray(t)?t:[]);const s=(Array.isArray(t)?t:[]).map(Is),a=s.findIndex(o=>o.id===n.id);return a>=0?s[a]=n:s.push(n),Sn(s)}function Dp(t,r){const n=String(r||"").trim();return Sn(n?(Array.isArray(t)?t:[]).filter(s=>String(s.id)!==n):Array.isArray(t)?t:[])}function $p(t){return`workpad-${String(t||"").trim()}`}function Wb(t){return Ta(Dp(Qt(),$p(t)))}function ql(t){if(!t||typeof t!="object")return Qt();const r=$p(t.id);return t.done||!String(t.dueDate||"").trim()?Ta(Dp(Qt(),r)):Ta(Mp(Qt(),{id:r,title:String(t.title||"Task").trim()||"Task",date:String(t.dueDate).trim(),priority:t.priority==="high"?"high":"normal"}))}function Ai(t){return String(t||"").replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/,/g,"\\,").replace(/;/g,"\\;")}function Kb(t){return String(t||"").replace(/-/g,"")}function Vb(t=[]){return["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//NeuralShell//Deadlines//EN","CALSCALE:GREGORIAN","METHOD:PUBLISH",...(Array.isArray(t)?t:[]).map(Is).filter(n=>n.title&&n.date).map(n=>{const s=Kb(n.date),a=Hb(n.date);let o=s;if(a){const l=new Date(a.year,a.month-1,a.day+1);o=zb(l.getFullYear(),l.getMonth()+1,l.getDate()).replace(/-/g,"")}return["BEGIN:VEVENT",`UID:${Ai(n.id)}@neuralshell.local`,`DTSTAMP:${new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}`,`DTSTART;VALUE=DATE:${s}`,`DTEND;VALUE=DATE:${o}`,`SUMMARY:${Ai(n.title)}`,`DESCRIPTION:${Ai(`ProofForge deadline (${n.priority})`)}`,"END:VEVENT"].join(`\r +You generate concise follow-up suggestions. Reply only with a numbered list.`},{role:"user",content:n}]);if(Tb(a))return Oa;const o=a&&a.message?a.message.content:a&&a.content?a.content:"";return $b(o)}return[]}const Bb=i.memo(function({chatLog:r,onSend:n,isThinking:s}){const[a,o]=O.useState([]),[c,l]=O.useState(!1),[u,x]=O.useState(!1),[p,d]=O.useState(-1),m=O.useRef(""),f=O.useRef(!0),b=O.useRef(null);O.useEffect(()=>(f.current=!0,()=>{f.current=!1}),[]);const h=O.useCallback(I=>{x(!0),typeof n=="function"&&n(I)},[n]),g=O.useCallback(async()=>{if(!Array.isArray(r)||r.length<2||s)return;const I=r.filter(E=>E&&E.content&&!E._streaming),A=[...I].reverse().find(E=>E.role==="kernel"||E.role==="assistant"),C=[...I].reverse().find(E=>E.role==="user");if(!A||!C)return;const w=Db(A.content);if(w===m.current)return;m.current=w,x(!1),d(-1);const j=Nd();if(j[w]){o(j[w]);return}l(!0),o([]);try{const E=await Lb(C.content,A.content);if(!f.current)return;const N=E.length>=2?E:Oa;o(N);const _={...Nd(),[w]:N},S=Object.keys(_);S.length>kd&&S.slice(0,S.length-kd).forEach(R=>delete _[R]),Mb(_)}catch{f.current&&o(Oa)}finally{f.current&&l(!1)}},[r,s]);O.useEffect(()=>{if(s)return;const I=setTimeout(g,600);return()=>clearTimeout(I)},[r,s,g]);const y=O.useCallback(I=>{a.length&&(I.key==="ArrowRight"||I.key==="ArrowDown"?(I.preventDefault(),d(A=>(A+1)%a.length)):I.key==="ArrowLeft"||I.key==="ArrowUp"?(I.preventDefault(),d(A=>A<=0?a.length-1:A-1)):I.key==="Enter"&&p>=0?(I.preventDefault(),h(a[p])):I.key==="Escape"&&(I.preventDefault(),x(!0)))},[h,p,a]);return u||s||a.length===0?null:e.jsx("div",{className:"max-w-3xl mx-auto px-1 pb-2 pt-1",children:e.jsxs("div",{ref:b,"data-testid":"smart-suggest-row",role:"group","aria-label":"Suggested follow-ups",tabIndex:0,onKeyDown:y,className:"flex items-center gap-1.5 flex-wrap outline-none focus-visible:ring-1 focus-visible:ring-violet-400/30 rounded-lg",children:[e.jsx("span",{className:"text-[11px] font-mono text-slate-700 uppercase tracking-wide shrink-0 mr-0.5","aria-hidden":"true",children:c?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-slate-600 animate-bounce",style:{animationDelay:"0ms"}}),e.jsx("span",{className:"w-1 h-1 rounded-full bg-slate-600 animate-bounce",style:{animationDelay:"150ms"}}),e.jsx("span",{className:"w-1 h-1 rounded-full bg-slate-600 animate-bounce",style:{animationDelay:"300ms"}})]}):e.jsx($x,{size:12,className:"text-violet-400/70"})}),a.map((I,A)=>e.jsxs("button",{type:"button","data-testid":`smart-suggest-chip-${A}`,"aria-label":`Apply suggestion: ${I}`,"aria-pressed":p===A,onFocus:()=>d(A),onClick:()=>h(I),className:`group flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] border transition-all active:scale-95 ${p===A?"border-violet-400/40 bg-violet-500/15 text-slate-100":"border-white/[0.07] bg-white/[0.03] text-slate-400 hover:text-slate-100 hover:border-violet-500/30 hover:bg-violet-500/10"}`,children:[e.jsx(Lx,{size:11,className:"text-violet-500/50 group-hover:text-violet-400/80 transition-colors shrink-0","aria-hidden":"true"}),I]},A)),e.jsx("button",{type:"button","data-testid":"smart-suggest-dismiss-btn","aria-label":"Dismiss suggestions",onClick:()=>x(!0),className:"ml-auto text-slate-700 hover:text-slate-400 transition-colors px-1 py-1 rounded-md hover:bg-white/[0.04]",children:e.jsx(yp,{size:12,"aria-hidden":"true"})})]})})}),Jl="neuralshell_deadlines_v1",bl="neuralshell:deadlines-changed";function Fb(t){return t&&typeof t=="object"&&typeof t.title=="string"&&typeof t.date=="string"}function Is(t){return{id:String(t.id||`${t.date}-${t.title}`),title:String(t.title||"").trim(),date:String(t.date||"").trim(),priority:String(t.priority||"normal").trim().toLowerCase()||"normal"}}function Cn(t){return[...t].sort((r,n)=>{const s=r.date.localeCompare(n.date);return s!==0?s:r.title.localeCompare(n.title)})}function Qt(){try{const t=JSON.parse(window.localStorage.getItem(Jl)||"[]");return Array.isArray(t)?Cn(t.filter(Fb).map(Is).filter(r=>r.title&&r.date)):[]}catch{return[]}}function Ta(t){const r=Cn((Array.isArray(t)?t:[]).map(Is).filter(n=>n.title&&n.date));try{window.localStorage.setItem(Jl,JSON.stringify(r))}catch{}try{window.dispatchEvent(new CustomEvent(bl,{detail:r}))}catch{}return r}function Ub(t){const r=new Date;r.setHours(0,0,0,0);const n=new Date(`${t}T00:00:00`);return Number.isNaN(n.getTime())?Number.POSITIVE_INFINITY:Math.round((n-r)/864e5)}function zb(t,r,n){return`${String(t)}-${String(r).padStart(2,"0")}-${String(n).padStart(2,"0")}`}function Hb(t){const r=String(t||"").trim().match(/^(\d{4})-(\d{2})-(\d{2})$/);return r?{year:Number(r[1]),month:Number(r[2]),day:Number(r[3])}:null}function Mp(t,r){const n=Is(r);if(!n.title||!n.date)return Cn(Array.isArray(t)?t:[]);const s=(Array.isArray(t)?t:[]).map(Is),a=s.findIndex(o=>o.id===n.id);return a>=0?s[a]=n:s.push(n),Cn(s)}function Dp(t,r){const n=String(r||"").trim();return Cn(n?(Array.isArray(t)?t:[]).filter(s=>String(s.id)!==n):Array.isArray(t)?t:[])}function $p(t){return`workpad-${String(t||"").trim()}`}function Wb(t){return Ta(Dp(Qt(),$p(t)))}function ql(t){if(!t||typeof t!="object")return Qt();const r=$p(t.id);return t.done||!String(t.dueDate||"").trim()?Ta(Dp(Qt(),r)):Ta(Mp(Qt(),{id:r,title:String(t.title||"Task").trim()||"Task",date:String(t.dueDate).trim(),priority:t.priority==="high"?"high":"normal"}))}function Ai(t){return String(t||"").replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/,/g,"\\,").replace(/;/g,"\\;")}function Kb(t){return String(t||"").replace(/-/g,"")}function Vb(t=[]){return["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//NeuralShell//Deadlines//EN","CALSCALE:GREGORIAN","METHOD:PUBLISH",...(Array.isArray(t)?t:[]).map(Is).filter(n=>n.title&&n.date).map(n=>{const s=Kb(n.date),a=Hb(n.date);let o=s;if(a){const c=new Date(a.year,a.month-1,a.day+1);o=zb(c.getFullYear(),c.getMonth()+1,c.getDate()).replace(/-/g,"")}return["BEGIN:VEVENT",`UID:${Ai(n.id)}@neuralshell.local`,`DTSTAMP:${new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}`,`DTSTART;VALUE=DATE:${s}`,`DTEND;VALUE=DATE:${o}`,`SUMMARY:${Ai(n.title)}`,`DESCRIPTION:${Ai(`ProofForge deadline (${n.priority})`)}`,"END:VEVENT"].join(`\r `)}),"END:VCALENDAR"].join(`\r -`)}function Lp(t){const r=()=>{typeof t=="function"&&t(Qt())},n=s=>{(!s||s.key===Jl)&&r()};return window.addEventListener("storage",n),window.addEventListener(bl,r),()=>{window.removeEventListener("storage",n),window.removeEventListener(bl,r)}}function Gb(t,r=Date.now()){const n=typeof t=="number"?t:Date.parse(String(t||""));if(!Number.isFinite(n))return"";const s=new Date(n);if(Number.isNaN(s.getTime()))return"";const a=s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o=new Date(r);o.setHours(0,0,0,0);const l=new Date(s);if(l.setHours(0,0,0,0),l.getTime()===o.getTime())return a;const c=new Date(o);if(c.setDate(c.getDate()-1),l.getTime()===c.getTime())return`Yesterday ${a}`;const u=s.toLocaleDateString([],{month:"short",day:"numeric"}),x=s.getFullYear()!==o.getFullYear()?` ${s.getFullYear()}`:"";return`${u}${x} ${a}`}function Jb(t){const r=typeof t=="number"?t:Date.parse(String(t||""));return Number.isFinite(r)&&!Number.isNaN(new Date(r).getTime())?r:null}const Va="neuralshell_workpad_v1",Ma="neuralshell:workpad-changed",qb="scratchpadDraft";let fn="global";function Ga(){return String(fn||"global")}function Bp(t){const r=String(t||"global").trim()||"global";if(r===fn)return fn;fn=r;try{window.dispatchEvent(new CustomEvent(Ma,{detail:{scope:fn}}))}catch{}return fn}function Yl(t=Ga()){const r=String(t||"global").trim()||"global";return r==="global"?Va:`neuralshell_workpad_${r}`}function He(){return new Date().toISOString()}function dt(t){return`${String(t||"item")}-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}function hl(){return{version:1,activeTab:"notes",activeNoteId:"",notes:[],tasks:[],pins:[],log:[]}}function Ja(t){const r=t&&typeof t=="object"?t:{};return{id:String(r.id||dt("task")),title:String(r.title||"").trim(),done:!!r.done,dueDate:String(r.dueDate||"").trim(),priority:["low","normal","high"].includes(String(r.priority||"").toLowerCase())?String(r.priority).toLowerCase():"normal",tags:Array.isArray(r.tags)?r.tags.map(n=>String(n||"").trim()).filter(Boolean).slice(0,8):[],createdAt:String(r.createdAt||He()),updatedAt:String(r.updatedAt||r.createdAt||He())}}function Ms(t){const r=t&&typeof t=="object"?t:{};return{id:String(r.id||dt("note")),title:String(r.title||"Untitled").trim()||"Untitled",body:String(r.body||""),updatedAt:String(r.updatedAt||He())}}function Fp(t){const r=t&&typeof t=="object"?t:{};return{id:String(r.id||dt("pin")),label:String(r.label||"Snippet").trim()||"Snippet",body:String(r.body||""),updatedAt:String(r.updatedAt||He())}}function Up(t){const r=t&&typeof t=="object"?t:{};return{id:String(r.id||dt("log")),text:String(r.text||"").trim(),at:String(r.at||He())}}function St(t){const r=hl(),n=t&&typeof t=="object"?t:{},s=Array.isArray(n.notes)?n.notes.map(Ms).filter(x=>x.title):[],a=Array.isArray(n.tasks)?n.tasks.map(Ja).filter(x=>x.title):[],o=Array.isArray(n.pins)?n.pins.map(Fp).filter(x=>x.body||x.label):[],l=Array.isArray(n.log)?n.log.map(Up).filter(x=>x.text):[],c=String(n.activeNoteId||""),u=s.some(x=>x.id===c)?c:s[0]&&s[0].id||"";return{...r,activeTab:["notes","tasks","pins","log"].includes(String(n.activeTab||""))?String(n.activeTab):"notes",activeNoteId:u,notes:s,tasks:a,pins:o,log:l}}function Yb(){if(typeof window>"u"||!window.localStorage)return null;try{const t=String(window.localStorage.getItem(qb)||"").trim();if(!t)return null;const r=Ms({id:dt("note"),title:"Scratchpad import",body:t,updatedAt:He()});return St({activeTab:"notes",activeNoteId:r.id,notes:[r]})}catch{return null}}function et(t){if(typeof window>"u"||!window.localStorage)return hl();const r=Yl(t);try{const n=window.localStorage.getItem(r);if(!n&&r===Va){const s=Yb();return s?(Zl(s,t),s):St({notes:[{id:dt("note"),title:"Inbox",body:"",updatedAt:He()}]})}return St(n?JSON.parse(n):{notes:[{id:dt("note"),title:"Inbox",body:"",updatedAt:He()}]})}catch{return hl()}}function Zl(t,r){const n=St(t);if(typeof window<"u"&&window.localStorage)try{window.localStorage.setItem(Yl(r),JSON.stringify(n))}catch{}try{window.dispatchEvent(new CustomEvent(Ma,{detail:{...n,scope:Ga()}}))}catch{}return n}function ut(t,r){const n=et(r),s=typeof t=="function"?t(n):{...n,...t||{}};return Zl(s,r)}function qa(t,r){const n=()=>{typeof t=="function"&&t(et(r))},s=a=>{(!a||a.key===Yl(r)||a.key===Va)&&n()};return window.addEventListener("storage",s),window.addEventListener(Ma,n),()=>{window.removeEventListener("storage",s),window.removeEventListener(Ma,n)}}function qe(t){return t??Ga()}function WS(t,r={},n){const s=String(t||"").trim();if(!s)return et(qe(n));const a=qe(n),o=ut(c=>({...c,activeTab:"tasks",tasks:[Ja({id:dt("task"),title:s,dueDate:r.dueDate||"",priority:r.priority||"normal",tags:r.tags||[],createdAt:He(),updatedAt:He()}),...c.tasks]}),a),l=o.tasks[0];return l&&ql(l),o}function Zb(t,r){const n=String(t||"").trim(),s=ut(o=>({...o,tasks:o.tasks.map(l=>l.id===n?{...l,done:!l.done,updatedAt:He()}:l)}),qe(r)),a=s.tasks.find(o=>o.id===n);return a&&ql(a),s}function KS(t,r){const n=String(t||"").trim(),s=ut(a=>({...a,tasks:a.tasks.filter(o=>o.id!==n)}),qe(r));return Wb(n),s}function VS(t){return ut(r=>({...r,tasks:r.tasks.filter(n=>!n.done)}),qe(t))}function GS(t="Untitled",r){const n=Ms({id:dt("note"),title:t,body:"",updatedAt:He()});return ut(s=>({...s,activeTab:"notes",activeNoteId:n.id,notes:[n,...s.notes]}),qe(r))}function JS(t,r,n){const s=String(r||"").trim();if(!s)return et(qe(n));const a=Fp({id:dt("pin"),label:String(t||"Snippet").trim()||"Snippet",body:s,updatedAt:He()});return ut(o=>({...o,activeTab:"pins",pins:[a,...o.pins]}),qe(n))}function qS(t,r){const n=String(t||"").trim();if(!n)return et(qe(r));const s=Up({id:dt("log"),text:n,at:He()});return ut(a=>({...a,activeTab:"log",log:[s,...a.log].slice(0,500)}),qe(r))}function Xl(t){return(Array.isArray(t&&t.tasks)?t.tasks:[]).filter(n=>!n.done).length}function gl(t){if(!t)return null;const r=new Date;r.setHours(0,0,0,0);const n=new Date(`${t}T00:00:00`);return Number.isNaN(n.getTime())?null:Math.round((n-r)/864e5)}function Xb(t){return(Array.isArray(t&&t.tasks)?t.tasks:[]).filter(n=>!n.done&&gl(n.dueDate)!==null&&gl(n.dueDate)<0).length}function Qb(t){return(Array.isArray(t&&t.tasks)?t.tasks:[]).filter(n=>{if(n.done)return!1;const s=gl(n.dueDate);return s!==null&&s>=0&&s<=3}).length}function eh(t){const r=St(t);return{openTasks:Xl(r),overdueTasks:Xb(r),dueSoonTasks:Qb(r),notes:r.notes.length,pins:r.pins.length,logEntries:r.log.length,doneTasks:r.tasks.filter(n=>n.done).length}}function YS(t,r){const n=String(t||"").trim();return ut(s=>{const a=s.notes.filter(l=>l.id!==n),o=s.activeNoteId===n?a[0]&&a[0].id||"":s.activeNoteId;return{...s,notes:a,activeNoteId:o}},qe(r))}function ZS(t,r){const n=String(t||"").trim(),s=qe(r),a=et(s),o=a.notes.find(c=>c.id===n);if(!o)return a;const l=Ms({id:dt("note"),title:`${o.title} (copy)`,body:o.body,updatedAt:He()});return ut(c=>({...c,activeTab:"notes",activeNoteId:l.id,notes:[l,...c.notes]}),s)}function XS(t,r={},n){const s=String(t||"").trim(),a=ut(l=>({...l,tasks:l.tasks.map(c=>c.id===s?Ja({...c,...r,updatedAt:He()}):c)}),qe(n)),o=a.tasks.find(l=>l.id===s);return o&&ql(o),a}function QS(t,r=[],n){const s=String(t||"").trim(),a=(Array.isArray(r)?r:[r]).map(o=>String(o||"").trim().replace(/^#/,"").toLowerCase()).filter(Boolean);return a.length?ut(o=>({...o,tasks:o.tasks.map(l=>{if(l.id!==s)return l;const c=Array.from(new Set([...l.tags||[],...a])).slice(0,8);return Ja({...l,tags:c,updatedAt:He()})})}),qe(n)):et(qe(n))}function th(t){const r=St(t);return["# ProofForge Workpad Export","",`Generated: ${He()}`,"","## Tasks",...r.tasks.length?r.tasks.map(s=>{const a=(s.tags||[]).length?` [${s.tags.map(o=>`#${o}`).join(" ")}]`:"";return`- [${s.done?"x":" "}] ${s.title}${s.dueDate?` (due ${s.dueDate})`:""}${a}`}):["- (none)"],"","## Notes",...r.notes.flatMap(s=>["",`### ${s.title}`,"",s.body||""]),"","## Pins",...r.pins.length?r.pins.flatMap(s=>["",`### ${s.label}`,"",s.body||""]):["- (none)"],"","## Log",...r.log.length?r.log.map(s=>`- ${s.at}: ${s.text}`):["- (none)"]].join(` -`)}function e2(t){const r=String(t||"").trim();!r||typeof window>"u"||window.dispatchEvent(new CustomEvent("neuralshell:workpad-insert",{detail:{text:r}}))}function t2(t){return JSON.stringify(St(t),null,2)}function r2(t,r=!1,n){let s=t;typeof t=="string"&&(s=JSON.parse(t));const a=St(s),o=qe(n);return r?ut(l=>St({...l,notes:[...a.notes,...l.notes],tasks:[...a.tasks,...l.tasks],pins:[...a.pins,...l.pins],log:[...a.log,...l.log]}),o):Zl(a,o)}function zp(t,r){const n=t&&typeof t=="object"?t:{},s=Ms({id:dt("note"),title:String(n.title||"Template"),body:String(n.body||""),updatedAt:He()});return ut(a=>({...a,activeTab:"notes",activeNoteId:s.id,notes:[s,...a.notes]}),qe(r))}function yl(){if(typeof window>"u"||!window.localStorage)return{};const t={};try{for(let r=0;r0?a[o-1].focus():r.focus(),!0):!1}const Hp=`I need structured help with something I am learning. Please break it down step-by-step and explain the concepts so I understand and can finish the work myself: +`)}function Lp(t){const r=()=>{typeof t=="function"&&t(Qt())},n=s=>{(!s||s.key===Jl)&&r()};return window.addEventListener("storage",n),window.addEventListener(bl,r),()=>{window.removeEventListener("storage",n),window.removeEventListener(bl,r)}}function Gb(t,r=Date.now()){const n=typeof t=="number"?t:Date.parse(String(t||""));if(!Number.isFinite(n))return"";const s=new Date(n);if(Number.isNaN(s.getTime()))return"";const a=s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o=new Date(r);o.setHours(0,0,0,0);const c=new Date(s);if(c.setHours(0,0,0,0),c.getTime()===o.getTime())return a;const l=new Date(o);if(l.setDate(l.getDate()-1),c.getTime()===l.getTime())return`Yesterday ${a}`;const u=s.toLocaleDateString([],{month:"short",day:"numeric"}),x=s.getFullYear()!==o.getFullYear()?` ${s.getFullYear()}`:"";return`${u}${x} ${a}`}function Jb(t){const r=typeof t=="number"?t:Date.parse(String(t||""));return Number.isFinite(r)&&!Number.isNaN(new Date(r).getTime())?r:null}const Va="neuralshell_workpad_v1",Ma="neuralshell:workpad-changed",qb="scratchpadDraft";let bn="global";function Ga(){return String(bn||"global")}function Bp(t){const r=String(t||"global").trim()||"global";if(r===bn)return bn;bn=r;try{window.dispatchEvent(new CustomEvent(Ma,{detail:{scope:bn}}))}catch{}return bn}function Yl(t=Ga()){const r=String(t||"global").trim()||"global";return r==="global"?Va:`neuralshell_workpad_${r}`}function He(){return new Date().toISOString()}function dt(t){return`${String(t||"item")}-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}function hl(){return{version:1,activeTab:"notes",activeNoteId:"",notes:[],tasks:[],pins:[],log:[]}}function Ja(t){const r=t&&typeof t=="object"?t:{};return{id:String(r.id||dt("task")),title:String(r.title||"").trim(),done:!!r.done,dueDate:String(r.dueDate||"").trim(),priority:["low","normal","high"].includes(String(r.priority||"").toLowerCase())?String(r.priority).toLowerCase():"normal",tags:Array.isArray(r.tags)?r.tags.map(n=>String(n||"").trim()).filter(Boolean).slice(0,8):[],createdAt:String(r.createdAt||He()),updatedAt:String(r.updatedAt||r.createdAt||He())}}function Ms(t){const r=t&&typeof t=="object"?t:{};return{id:String(r.id||dt("note")),title:String(r.title||"Untitled").trim()||"Untitled",body:String(r.body||""),updatedAt:String(r.updatedAt||He())}}function Fp(t){const r=t&&typeof t=="object"?t:{};return{id:String(r.id||dt("pin")),label:String(r.label||"Snippet").trim()||"Snippet",body:String(r.body||""),updatedAt:String(r.updatedAt||He())}}function Up(t){const r=t&&typeof t=="object"?t:{};return{id:String(r.id||dt("log")),text:String(r.text||"").trim(),at:String(r.at||He())}}function St(t){const r=hl(),n=t&&typeof t=="object"?t:{},s=Array.isArray(n.notes)?n.notes.map(Ms).filter(x=>x.title):[],a=Array.isArray(n.tasks)?n.tasks.map(Ja).filter(x=>x.title):[],o=Array.isArray(n.pins)?n.pins.map(Fp).filter(x=>x.body||x.label):[],c=Array.isArray(n.log)?n.log.map(Up).filter(x=>x.text):[],l=String(n.activeNoteId||""),u=s.some(x=>x.id===l)?l:s[0]&&s[0].id||"";return{...r,activeTab:["notes","tasks","pins","log"].includes(String(n.activeTab||""))?String(n.activeTab):"notes",activeNoteId:u,notes:s,tasks:a,pins:o,log:c}}function Yb(){if(typeof window>"u"||!window.localStorage)return null;try{const t=String(window.localStorage.getItem(qb)||"").trim();if(!t)return null;const r=Ms({id:dt("note"),title:"Scratchpad import",body:t,updatedAt:He()});return St({activeTab:"notes",activeNoteId:r.id,notes:[r]})}catch{return null}}function et(t){if(typeof window>"u"||!window.localStorage)return hl();const r=Yl(t);try{const n=window.localStorage.getItem(r);if(!n&&r===Va){const s=Yb();return s?(Zl(s,t),s):St({notes:[{id:dt("note"),title:"Inbox",body:"",updatedAt:He()}]})}return St(n?JSON.parse(n):{notes:[{id:dt("note"),title:"Inbox",body:"",updatedAt:He()}]})}catch{return hl()}}function Zl(t,r){const n=St(t);if(typeof window<"u"&&window.localStorage)try{window.localStorage.setItem(Yl(r),JSON.stringify(n))}catch{}try{window.dispatchEvent(new CustomEvent(Ma,{detail:{...n,scope:Ga()}}))}catch{}return n}function ut(t,r){const n=et(r),s=typeof t=="function"?t(n):{...n,...t||{}};return Zl(s,r)}function qa(t,r){const n=()=>{typeof t=="function"&&t(et(r))},s=a=>{(!a||a.key===Yl(r)||a.key===Va)&&n()};return window.addEventListener("storage",s),window.addEventListener(Ma,n),()=>{window.removeEventListener("storage",s),window.removeEventListener(Ma,n)}}function qe(t){return t??Ga()}function WS(t,r={},n){const s=String(t||"").trim();if(!s)return et(qe(n));const a=qe(n),o=ut(l=>({...l,activeTab:"tasks",tasks:[Ja({id:dt("task"),title:s,dueDate:r.dueDate||"",priority:r.priority||"normal",tags:r.tags||[],createdAt:He(),updatedAt:He()}),...l.tasks]}),a),c=o.tasks[0];return c&&ql(c),o}function Zb(t,r){const n=String(t||"").trim(),s=ut(o=>({...o,tasks:o.tasks.map(c=>c.id===n?{...c,done:!c.done,updatedAt:He()}:c)}),qe(r)),a=s.tasks.find(o=>o.id===n);return a&&ql(a),s}function KS(t,r){const n=String(t||"").trim(),s=ut(a=>({...a,tasks:a.tasks.filter(o=>o.id!==n)}),qe(r));return Wb(n),s}function VS(t){return ut(r=>({...r,tasks:r.tasks.filter(n=>!n.done)}),qe(t))}function GS(t="Untitled",r){const n=Ms({id:dt("note"),title:t,body:"",updatedAt:He()});return ut(s=>({...s,activeTab:"notes",activeNoteId:n.id,notes:[n,...s.notes]}),qe(r))}function JS(t,r,n){const s=String(r||"").trim();if(!s)return et(qe(n));const a=Fp({id:dt("pin"),label:String(t||"Snippet").trim()||"Snippet",body:s,updatedAt:He()});return ut(o=>({...o,activeTab:"pins",pins:[a,...o.pins]}),qe(n))}function qS(t,r){const n=String(t||"").trim();if(!n)return et(qe(r));const s=Up({id:dt("log"),text:n,at:He()});return ut(a=>({...a,activeTab:"log",log:[s,...a.log].slice(0,500)}),qe(r))}function Xl(t){return(Array.isArray(t&&t.tasks)?t.tasks:[]).filter(n=>!n.done).length}function gl(t){if(!t)return null;const r=new Date;r.setHours(0,0,0,0);const n=new Date(`${t}T00:00:00`);return Number.isNaN(n.getTime())?null:Math.round((n-r)/864e5)}function Xb(t){return(Array.isArray(t&&t.tasks)?t.tasks:[]).filter(n=>!n.done&&gl(n.dueDate)!==null&&gl(n.dueDate)<0).length}function Qb(t){return(Array.isArray(t&&t.tasks)?t.tasks:[]).filter(n=>{if(n.done)return!1;const s=gl(n.dueDate);return s!==null&&s>=0&&s<=3}).length}function eh(t){const r=St(t);return{openTasks:Xl(r),overdueTasks:Xb(r),dueSoonTasks:Qb(r),notes:r.notes.length,pins:r.pins.length,logEntries:r.log.length,doneTasks:r.tasks.filter(n=>n.done).length}}function YS(t,r){const n=String(t||"").trim();return ut(s=>{const a=s.notes.filter(c=>c.id!==n),o=s.activeNoteId===n?a[0]&&a[0].id||"":s.activeNoteId;return{...s,notes:a,activeNoteId:o}},qe(r))}function ZS(t,r){const n=String(t||"").trim(),s=qe(r),a=et(s),o=a.notes.find(l=>l.id===n);if(!o)return a;const c=Ms({id:dt("note"),title:`${o.title} (copy)`,body:o.body,updatedAt:He()});return ut(l=>({...l,activeTab:"notes",activeNoteId:c.id,notes:[c,...l.notes]}),s)}function XS(t,r={},n){const s=String(t||"").trim(),a=ut(c=>({...c,tasks:c.tasks.map(l=>l.id===s?Ja({...l,...r,updatedAt:He()}):l)}),qe(n)),o=a.tasks.find(c=>c.id===s);return o&&ql(o),a}function QS(t,r=[],n){const s=String(t||"").trim(),a=(Array.isArray(r)?r:[r]).map(o=>String(o||"").trim().replace(/^#/,"").toLowerCase()).filter(Boolean);return a.length?ut(o=>({...o,tasks:o.tasks.map(c=>{if(c.id!==s)return c;const l=Array.from(new Set([...c.tags||[],...a])).slice(0,8);return Ja({...c,tags:l,updatedAt:He()})})}),qe(n)):et(qe(n))}function th(t){const r=St(t);return["# ProofForge Workpad Export","",`Generated: ${He()}`,"","## Tasks",...r.tasks.length?r.tasks.map(s=>{const a=(s.tags||[]).length?` [${s.tags.map(o=>`#${o}`).join(" ")}]`:"";return`- [${s.done?"x":" "}] ${s.title}${s.dueDate?` (due ${s.dueDate})`:""}${a}`}):["- (none)"],"","## Notes",...r.notes.flatMap(s=>["",`### ${s.title}`,"",s.body||""]),"","## Pins",...r.pins.length?r.pins.flatMap(s=>["",`### ${s.label}`,"",s.body||""]):["- (none)"],"","## Log",...r.log.length?r.log.map(s=>`- ${s.at}: ${s.text}`):["- (none)"]].join(` +`)}function e2(t){const r=String(t||"").trim();!r||typeof window>"u"||window.dispatchEvent(new CustomEvent("neuralshell:workpad-insert",{detail:{text:r}}))}function t2(t){return JSON.stringify(St(t),null,2)}function r2(t,r=!1,n){let s=t;typeof t=="string"&&(s=JSON.parse(t));const a=St(s),o=qe(n);return r?ut(c=>St({...c,notes:[...a.notes,...c.notes],tasks:[...a.tasks,...c.tasks],pins:[...a.pins,...c.pins],log:[...a.log,...c.log]}),o):Zl(a,o)}function zp(t,r){const n=t&&typeof t=="object"?t:{},s=Ms({id:dt("note"),title:String(n.title||"Template"),body:String(n.body||""),updatedAt:He()});return ut(a=>({...a,activeTab:"notes",activeNoteId:s.id,notes:[s,...a.notes]}),qe(r))}function yl(){if(typeof window>"u"||!window.localStorage)return{};const t={};try{for(let r=0;r0?a[o-1].focus():r.focus(),!0):!1}const Hp=`I need structured help with something I am learning. Please break it down step-by-step and explain the concepts so I understand and can finish the work myself: -`,us=Object.freeze({math:`I have a math problem I need help with. Please walk me through it step-by-step, explaining the method and why each step works so I understand the concept, not just the answer: +`,ps=Object.freeze({math:`I have a math problem I need help with. Please walk me through it step-by-step, explaining the method and why each step works so I understand the concept, not just the answer: `,science:`I have a science topic I am studying. Please explain the concept clearly with real-world examples, then help me reason through the question myself: @@ -118,18 +118,18 @@ You generate concise follow-up suggestions. Reply only with a numbered list.`},{ `,code:`I have a programming exercise I am working on. Please explain the concept first, then guide me step-by-step rather than pasting a full solution: -`}),ps=Object.freeze({math:"Math",science:"Science",english:"English",history:"History",code:"Coding"});Object.freeze([{id:"math",label:ps.math,emoji:"📐",color:"#38bdf8",prompt:us.math},{id:"science",label:ps.science,emoji:"🔬",color:"#34d399",prompt:us.science},{id:"english",label:ps.english,emoji:"✍️",color:"#a78bfa",prompt:us.english},{id:"history",label:ps.history,emoji:"🏛️",color:"#fbbf24",prompt:us.history},{id:"code",label:ps.code,emoji:"💻",color:"#f472b6",prompt:us.code},{id:"other",label:"Other",emoji:"📚",color:"#94a3b8",prompt:Hp}]);const nh="neuralshell_adaptive_layout_v1";function Sd(){if(typeof window>"u"||!window.localStorage)return{};try{const t=window.localStorage.getItem(nh),r=t?JSON.parse(t):null;return r&&typeof r=="object"&&r.panels&&typeof r.panels=="object"?r.panels:{}}catch{return{}}}function Wp(){const[t,r]=O.useState(()=>Sd());O.useEffect(()=>{const s=()=>r(Sd());return window.addEventListener("neuralshell:apply-layout",s),window.addEventListener("neuralshell:layout-chrome-updated",s),window.addEventListener("storage",s),()=>{window.removeEventListener("neuralshell:apply-layout",s),window.removeEventListener("neuralshell:layout-chrome-updated",s),window.removeEventListener("storage",s)}},[]);const n=O.useCallback((s,a=!0)=>!s||!Object.prototype.hasOwnProperty.call(t,s)?a:t[s]!==!1,[t]);return{panels:t,isPanelChromeVisible:n}}function sh(){const[t,r]=O.useState(Qt);return O.useEffect(()=>Lp(r),[]),[...t].sort((n,s)=>n.date.localeCompare(s.date)).slice(0,5)}function ah(){return e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{d:"M12 5v14M5 12h14"})})}function oh(){return e.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:e.jsx("path",{d:"M18 6L6 18M6 6l12 12"})})}function ih(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:[e.jsx("rect",{x:"2",y:"2",width:"20",height:"20",rx:"2"}),e.jsx("path",{d:"M12 2v20"})]})}function lh(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:[e.jsx("rect",{x:"2",y:"2",width:"20",height:"20",rx:"2"}),e.jsx("path",{d:"M9 2v20M15 2v20"})]})}function Cd(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:[e.jsx("rect",{x:"2",y:"2",width:"20",height:"20",rx:"2"}),e.jsx("path",{d:"M12 2v20M2 12h20"})]})}function ch(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:[e.jsx("rect",{x:"2",y:"6",width:"20",height:"16",rx:"1"}),e.jsx("path",{d:"M2 6V4a1 1 0 011-1h5a1 1 0 011 1v2M10 6V4a1 1 0 011-1h5a1 1 0 011 1v2"})]})}function dh(){return e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{d:"M22 2L11 13M22 2L15 22l-4-9-9-4 20-7z"})})}function uh(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:[e.jsx("circle",{cx:"12",cy:"12",r:"3"}),e.jsx("path",{d:"M12 1v4m0 14v4m-7.07-2.93l2.83-2.83m8.48-8.48l2.83-2.83M1 12h4m14 0h4m-2.93 7.07l-2.83-2.83M6.76 6.76L3.93 3.93"})]})}function ph(){return e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{d:"M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"})})}function mh(){return e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{d:"M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a1 1 0 011-1h4a1 1 0 011 1v2"})})}const xh={tabs:e.jsx(ch,{}),"split-2":e.jsx(ih,{}),"split-3":e.jsx(lh,{}),"split-4":e.jsx(Cd,{}),grid:e.jsx(Cd,{})},_d={tabs:"Tabs","split-2":"2-Split","split-3":"3-Split","split-4":"4-Split (2×2)",grid:"Grid (Auto)"},Ps=[{id:null,label:"None"},{id:"analyze",label:"Analyze"},{id:"code",label:"Code"},{id:"test",label:"Test"},{id:"review",label:"Review"},{id:"deploy",label:"Deploy"},{id:"monitor",label:"Monitor"},{id:"document",label:"Document"}];function fh(){return e.jsxs("span",{className:"flex gap-1 items-end px-1 h-4",children:[e.jsx("span",{className:"w-1 rounded-sm bg-violet-400 animate-thinking-dot-1",style:{height:"10px",transformOrigin:"bottom"}}),e.jsx("span",{className:"w-1 rounded-sm bg-violet-300 animate-thinking-dot-2",style:{height:"14px",transformOrigin:"bottom"}}),e.jsx("span",{className:"w-1 rounded-sm bg-violet-400 animate-thinking-dot-3",style:{height:"10px",transformOrigin:"bottom"}})]})}function Ei({title:t,eyebrow:r,children:n}){return e.jsxs("div",{className:"ui-holo-panel rounded-[1.15rem] px-3.5 py-3.5",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide font-bold text-slate-500",children:r}),e.jsx("div",{className:"mt-1 text-[13px] font-semibold text-slate-200",children:t}),e.jsx("div",{className:"mt-2 text-[13px] text-slate-400 leading-6",children:n})]})}i.memo(function({accentColor:r}){const[n,s]=O.useState({tok:0,words:0}),a=O.useRef({tok:0,words:0,recent:[],start:Date.now()});return O.useEffect(()=>{a.current={tok:0,words:0,recent:[],start:Date.now()};const o=c=>{const u=c.detail&&c.detail.message&&c.detail.message.content||"";if(!u)return;const x=Date.now();a.current.tok++,a.current.words+=u.split(/\s+/).filter(Boolean).length,a.current.recent.push(x),a.current.recent=a.current.recent.filter(p=>x-p<2e3)};window.addEventListener("llm-stream-data",o);const l=setInterval(()=>{const{tok:c,words:u,recent:x}=a.current,p=Math.round(x.filter(d=>Date.now()-d<2e3).length/2);s({tok:c,words:u,tokPerSec:p})},300);return()=>{window.removeEventListener("llm-stream-data",o),clearInterval(l)}},[]),e.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] font-mono",style:{color:r},children:[e.jsx("span",{className:"w-1 h-1 rounded-full animate-pulse",style:{backgroundColor:r}}),e.jsxs("span",{children:[n.tokPerSec??0," tok/s"]}),e.jsx("span",{className:"text-slate-700",children:"·"}),e.jsxs("span",{children:[n.words," words"]})]})});const bh=i.memo(function({msg:r,accentColor:n,onRetry:s}){const a=r.role==="user",o=!!r._streaming,l=o?Math.ceil(String(r.content||"").length/4):0,[c,u]=O.useState(!1),x=O.useCallback(()=>{navigator.clipboard.writeText(String(r.content||"")).then(()=>{u(!0),setTimeout(()=>u(!1),1500)}).catch(()=>{})},[r.content]),p=Jb(r.ts),d=p!=null?Gb(p):"";return e.jsxs("div",{"data-testid":"chat-message",tabIndex:-1,className:`group flex gap-2 ${a?"flex-row-reverse":"flex-row"} items-start mb-3`,children:[e.jsx("div",{className:"w-7 h-7 rounded-full shrink-0 flex items-center justify-center text-[12px] font-bold mt-0.5",style:{backgroundColor:a?`${n}25`:"rgba(139,92,246,0.2)",color:a?n:"#a78bfa"},children:a?"U":"AI"}),e.jsxs("div",{className:`flex flex-col gap-1 max-w-[85%] ${a?"items-end":"items-start"}`,children:[d&&e.jsx("span",{"data-testid":"message-timestamp",className:"text-[10px] font-mono text-slate-500 tabular-nums",title:p!=null?new Date(p).toLocaleString():void 0,children:d}),e.jsxs("div",{className:`rounded-xl px-3.5 py-2.5 text-[13px] leading-7 whitespace-pre-wrap break-words ${a?"bg-white/[0.06] text-slate-200 rounded-tr-none":"bg-violet-500/[0.08] border border-violet-500/20 text-slate-300 rounded-tl-none"}`,style:a?{borderColor:`${n}20`}:{},children:[r.content,o&&e.jsx("span",{className:"inline-block w-0.5 h-[1em] bg-current align-middle ml-0.5 animate-[blink_0.8s_step-end_infinite] opacity-80","aria-hidden":"true"})]}),o&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] font-mono text-violet-400/70 bg-violet-500/10 px-1.5 py-0.5 rounded-full border border-violet-500/15 self-start",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-violet-400 animate-pulse"}),"streaming · ~",l," tokens"]}),!o&&e.jsxs("div",{className:`flex items-center gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity duration-150 ${a?"justify-end":"justify-start"}`,children:[e.jsx("button",{type:"button",onClick:x,className:"flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] font-mono text-slate-400 hover:text-slate-300 hover:bg-white/5 transition-all",title:"Copy message",children:c?e.jsxs(e.Fragment,{children:[e.jsx("svg",{className:"w-2.5 h-2.5 text-emerald-400",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2.5,children:e.jsx("path",{d:"M20 6L9 17l-5-5"})}),e.jsx("span",{className:"text-emerald-400",children:"copied"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("svg",{className:"w-2.5 h-2.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:[e.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),e.jsx("path",{d:"M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"})]}),e.jsx("span",{children:"copy"})]})}),!a&&typeof s=="function"&&e.jsxs("button",{type:"button",onClick:s,className:"flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] font-mono text-slate-400 hover:text-violet-300 hover:bg-violet-500/10 transition-all",title:"Regenerate",children:[e.jsxs("svg",{className:"w-2.5 h-2.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:[e.jsx("path",{d:"M1 4v6h6"}),e.jsx("path",{d:"M3.51 15a9 9 0 1 0 .49-3.14"})]}),"retry"]})]})]})]})}),hh=i.memo(function({pane:r,onSend:n,onUpdatePane:s,starterCommands:a,promptSuggestions:o}){var x,p;const l=sh(),c=i.useCallback(d=>n(r.id,d),[n,r.id]),u=r.agentMode?`${((x=Ps.find(d=>d.id===r.agentMode))==null?void 0:x.label)||r.agentMode} lane armed`:"General lane active";return e.jsx("div",{className:"flex min-h-full w-full items-start justify-center px-4 py-8 sm:px-6",children:e.jsxs("div",{className:"w-full max-w-6xl space-y-6 animate-fade-up",children:[e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"mx-auto flex h-14 w-14 items-center justify-center rounded-[1.25rem] ui-edge-glow",style:{backgroundColor:`${r.color}15`,boxShadow:`0 0 28px ${r.color}28`,border:`1px solid ${r.color}22`},children:e.jsx("span",{className:"h-3.5 w-3.5 rounded-full animate-thinking-dot",style:{backgroundColor:r.color,boxShadow:`0 0 12px ${r.color}`}})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-[0.22em] text-slate-500",children:r.label}),e.jsx("h2",{className:"text-[2rem] font-semibold tracking-tight text-slate-100",children:"Operator Hero Console"}),e.jsx("p",{className:"mx-auto max-w-4xl text-sm leading-7 text-slate-500",children:"Skip dead-start screens: launch high-impact commands, verify posture, and move from idea to deployment in one control pass."})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2",children:[e.jsx("span",{className:"ui-holo-panel rounded-full px-3 py-1 text-[13px] font-mono text-slate-300",children:r.model}),r.agentMode&&e.jsxs("span",{className:"rounded-full border border-amber-500/20 bg-amber-500/10 px-3 py-1 text-[13px] text-amber-300 ui-edge-glow",children:[(p=Ps.find(d=>d.id===r.agentMode))==null?void 0:p.label," mode"]}),r.project&&e.jsx("span",{className:"rounded-full border border-sky-500/20 bg-sky-500/10 px-3 py-1 text-[13px] text-sky-300 ui-edge-glow",children:r.project})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2.5",children:[e.jsx("button",{type:"button",onClick:()=>n(r.id,"/proof"),className:"ui-tactile rounded-xl border border-violet-400/30 bg-violet-500/12 px-4 py-2 text-[13px] font-semibold text-violet-200 hover:bg-violet-500/20",children:"Launch proof lane"}),e.jsx("button",{type:"button",onClick:()=>n(r.id,"/guard"),className:"ui-tactile rounded-xl border border-rose-400/30 bg-rose-500/12 px-4 py-2 text-[13px] font-semibold text-rose-200 hover:bg-rose-500/20",children:"Run security sweep"})]})]}),e.jsx(Cb,{onCommand:c}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2.5",children:[e.jsxs(Ei,{eyebrow:"Execution lane",title:"Current operating posture",children:[e.jsx("span",{className:"text-cyan-300 font-mono",children:u}),e.jsx("span",{className:"block mt-1",children:"Pair this with /status for instant runtime confirmation."})]}),e.jsxs(Ei,{eyebrow:"Context",title:"Workspace objective",children:[r.project?`Project focus is ${r.project}.`:"No project pinned yet.",e.jsx("span",{className:"block mt-1",children:"Pin one to make suggestions sharper and faster."})]}),e.jsxs(Ei,{eyebrow:"Tempo",title:"Action cadence",children:["Begin with a command card, then commit one prompt from the suggestion grid.",e.jsx("span",{className:"block mt-1",children:"This keeps velocity high without context thrash."})]})]}),l.length>0&&e.jsxs("div",{className:"ui-holo-panel rounded-2xl px-4 py-3 space-y-2",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-wide font-bold text-slate-500",children:"Upcoming Deadlines"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map(d=>{const m=Ub(d.date),f=m<0?"#f87171":m===0?"#fb923c":m<=2?"#facc15":m<=7?"#67e8f9":"#475569";return e.jsxs("div",{className:"ui-tactile flex items-center gap-1.5 px-2.5 py-1 rounded-xl border border-white/[0.07] bg-black/20 text-[11px]",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:f}}),e.jsx("span",{className:"text-slate-300 truncate max-w-36",children:d.title}),e.jsx("span",{className:"font-mono shrink-0",style:{color:f},children:m<0?`${Math.abs(m)}d overdue`:m===0?"today":`${m}d`})]},d.id)})})]}),e.jsx("div",{className:"grid gap-2.5 md:grid-cols-2",children:a.map(d=>e.jsx("button",{"data-testid":d.testId,onClick:()=>{n(r.id,d.command)},className:"ui-holo-panel ui-tactile group rounded-[1.35rem] px-4 py-4 text-left hover:border-white/[0.13] hover:bg-white/[0.045]",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-200 group-hover:text-white transition-colors",children:d.label}),e.jsx("div",{className:"mt-0.5 text-[13px] leading-6 text-slate-500 group-hover:text-slate-400 transition-colors",children:d.description})]}),e.jsx("div",{className:"rounded-lg border border-white/[0.08] bg-black/30 px-2 py-0.5 text-[12px] font-mono text-slate-400 shrink-0 group-hover:border-white/[0.14] group-hover:text-slate-300 transition-all",children:d.command})]})},d.testId))}),e.jsxs("div",{className:"ui-holo-panel rounded-[1.35rem] p-4",children:[e.jsxs("div",{className:"mb-2.5 flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-300",children:"Suggested prompts"}),e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-slate-500 font-mono",children:"tap to send"})]}),e.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:o.map(d=>e.jsx("button",{type:"button",onClick:()=>{n(r.id,d)},className:"ui-tactile rounded-xl border border-white/[0.05] bg-black/10 px-3.5 py-2.5 text-left text-[13px] leading-6 text-slate-400 hover:border-white/[0.10] hover:bg-white/[0.035] hover:text-slate-200",children:d},d))})]}),e.jsx("div",{className:"text-center text-[11px] font-mono uppercase tracking-wide text-slate-700",children:"↵ send  ·  ⇧↵ newline  ·  Ctrl+T new pane  ·  click date in header for deadlines"})]})})}),gh=i.memo(function({pane:r,compact:n,isActive:s=!1,onPromptChange:a,onSend:o,onClear:l,onRename:c,onUpdatePane:u,onModelChange:x,panels:p,moodEngine:d,rgbEnabled:m=!1,rgbStatus:f=null,activeTaskCount:b=0,workpadOpenCount:h=0,workpadOpen:g=!1,onOpenTaskManager:y,onToggleWorkpad:P}){var pe;const A=O.useRef(null),C=O.useRef(null),w=O.useRef(null),[j,E]=O.useState(!1),[N,_]=O.useState(r.label),[S,R]=O.useState(!1),{isPanelChromeVisible:$}=Wp();O.useEffect(()=>{var K;(K=A.current)==null||K.scrollIntoView({behavior:"smooth"})},[r.chatLog.length,r.isThinking]),O.useEffect(()=>{const K=()=>{var H;(H=C.current)==null||H.focus()};return window.addEventListener("neuralshell:focus-composer",K),()=>window.removeEventListener("neuralshell:focus-composer",K)},[]),O.useEffect(()=>{if(!s)return;const K=window.setTimeout(()=>{var H;return(H=C.current)==null?void 0:H.focus()},0);return()=>window.clearTimeout(K)},[s,r.id]);const U=O.useCallback(K=>{K.key==="Enter"&&!K.shiftKey&&(K.preventDefault(),o(r.id))},[o,r.id]),I=O.useCallback(K=>o(r.id,K),[o,r.id]),D=O.useCallback(K=>{rh(K,w.current)},[]),z=String(r.prompt||"").trim(),F=/^\/(?:clear|purge|reset)$/i.test(z),J=!!z&&(!r.isThinking||F),ee=()=>{N.trim()&&c(r.id,N.trim()),E(!1)},ie=i.useMemo(()=>[{label:"Command help",description:"See operator commands and shortcuts.",command:"/help",testId:"card-help"},{label:"Run proof",description:"Generate the trust and release narrative.",command:"/proof",testId:"card-proof"},{label:"ROI snapshot",description:"Summarize value and impact quickly.",command:"/roi",testId:"card-roi"},{label:"Security guard",description:"Check the current protection posture.",command:"/guard",testId:"card-guard"},{label:"Concept mentor",description:"Walk the logic in deliberate steps—clarity on how and why, not a one-shot answer.",command:Hp.trim(),testId:"card-study-coach"}],[]),ye=i.useMemo(()=>r.agentMode==="code"||!r.agentMode?["Explain this codebase","Write a unit test","Find bugs in my code","Refactor for clarity"]:r.agentMode==="analyze"?["Analyze code quality","Find performance issues","Security audit","Summarize changes"]:r.agentMode==="review"?["Review this PR","Check for code smells","Suggest improvements","Validate logic"]:["Start a task","Ask a question","Summarize context","Generate output"],[r.agentMode]);return e.jsxs("div",{className:"flex flex-col h-full min-h-0 bg-shell-canvas rounded-xl overflow-hidden border",style:{borderColor:`${r.color}22`},children:[e.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2.5 border-b shrink-0",style:{borderColor:`${r.color}18`,background:`linear-gradient(90deg, ${r.color}0a 0%, transparent 100%)`},children:[e.jsx("span",{className:`w-2.5 h-2.5 rounded-full shrink-0 ${r.isThinking?"animate-pulse":""}`,style:{backgroundColor:r.color,boxShadow:`0 0 6px ${r.color}`}}),j?e.jsx("input",{autoFocus:!0,value:N,onChange:K=>_(K.target.value),onBlur:ee,onKeyDown:K=>{K.key==="Enter"&&ee(),K.key==="Escape"&&E(!1)},className:"flex-1 bg-white/[0.06] border border-white/[0.1] rounded px-2 py-1 text-[12px] font-medium text-slate-200 outline-none min-w-0"}):e.jsx("span",{className:"flex-1 text-[12px] font-semibold cursor-pointer hover:opacity-70 truncate min-w-0",style:{color:r.color},onDoubleClick:()=>{_(r.label),E(!0)},children:r.label}),r.agentMode&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[12px] font-medium bg-amber-500/15 text-amber-300 border border-amber-500/20 shrink-0",children:((pe=Ps.find(K=>K.id===r.agentMode))==null?void 0:pe.label)||r.agentMode}),r.project&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[12px] font-medium bg-sky-500/15 text-sky-300 border border-sky-500/20 shrink-0 max-w-24 truncate",children:r.project}),!n&&e.jsx("select",{value:r.model,"data-testid":`pane-model-select-${r.id}`,onChange:K=>{const H=K.target.value;u(r.id,{model:H}),typeof x=="function"&&Promise.resolve(x(H)).catch(()=>{})},className:"bg-white/[0.04] border border-white/[0.08] rounded px-1.5 py-1 text-[12px] font-mono text-slate-400 outline-none hover:bg-white/[0.06] transition-all cursor-pointer appearance-none max-w-24 truncate",children:["llama3","llama3.2","mistral","phi4","gemma3:12b","qwq:32b","gpt-4.1","gpt-4o","gpt-4o-mini","o4-mini","claude-opus-4-5","claude-sonnet-4-5","claude-3-7-sonnet-latest","claude-3-5-haiku-latest","gemini-2.5-pro","gemini-2.5-flash","gemini-2.0-flash","deepseek-chat","deepseek-reasoner","mistral-large-latest","codestral-latest","llama-3.3-70b-versatile","gemma2-9b-it"].map(K=>e.jsx("option",{value:K,children:K},K))}),!n&&e.jsx("select",{value:r.agentMode||"","aria-label":"Agent mode",onChange:K=>u(r.id,{agentMode:K.target.value||null}),className:"bg-white/[0.04] border border-white/[0.08] rounded px-1.5 py-1 text-[12px] font-mono text-slate-400 outline-none hover:bg-white/[0.06] transition-all cursor-pointer appearance-none max-w-24",title:"Agent Mode",children:Ps.map(K=>e.jsx("option",{value:K.id??"",children:K.label},K.id??"none"))}),e.jsx("button",{type:"button",onClick:()=>l(r.id),title:"Clear chat",className:"p-1.5 rounded text-slate-500 hover:text-rose-400 hover:bg-rose-500/10 transition-all active:scale-90",children:e.jsx(mh,{})})]}),e.jsxs("div",{ref:w,role:"region","aria-label":`Messages, ${r.label||"pane"}`,tabIndex:r.chatLog.length>0?0:void 0,onKeyDown:D,className:"flex-1 overflow-y-auto px-4 py-4 min-h-0 space-y-1 scrollbar-thin scrollbar-track-transparent scrollbar-thumb-white/10",children:[r.chatLog.length===0&&e.jsx(hh,{pane:r,onSend:o,onUpdatePane:u,starterCommands:ie,promptSuggestions:ye}),r.chatLog.map((K,H)=>e.jsx(bh,{msg:K,accentColor:r.color,onRetry:!K._streaming&&K.role!=="user"?()=>{var W;return o(r.id,((W=r.chatLog.slice(0,H).reverse().find(Z=>Z.role==="user"))==null?void 0:W.content)||"")}:void 0},H))," ",r.isThinking&&!r.chatLog.some(K=>K._streaming)&&e.jsxs("div",{className:"flex gap-2 items-start mb-3",children:[e.jsx("div",{className:"w-7 h-7 rounded-full shrink-0 flex items-center justify-center text-[12px] font-bold bg-violet-500/20 text-violet-400",children:"AI"}),e.jsx("div",{className:"rounded-xl px-3 py-2 bg-violet-500/[0.08] border border-violet-500/20 rounded-tl-none",children:e.jsx(fh,{})})]}),r.isThinking&&r.chatLog.some(K=>K._streaming)&&e.jsx("div",{className:"flex justify-end mb-1",children:e.jsxs("button",{type:"button",onClick:()=>{window.api&&window.api.llm&&window.api.llm.cancelStream().catch(()=>{})},className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-mono border border-rose-500/25 text-rose-400 hover:bg-rose-500/10 transition-all",title:"Stop generating",children:[e.jsx("svg",{className:"w-3 h-3",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),"Stop"]})}),!r.isThinking&&$("smart-suggest",!0)&&e.jsx(Bb,{chatLog:r.chatLog,onSend:I,isThinking:r.isThinking}),e.jsx("div",{ref:A})]}),e.jsxs("div",{className:"shrink-0 px-4 pb-4 pt-2 space-y-2",children:[e.jsx(Ob,{moodEngine:d,pane:r,panels:p,rgbEnabled:m,rgbStatus:f,activeTaskCount:b,onOpenTaskManager:y,onToggleWorkpad:P,workpadOpen:g,workpadOpenCount:h}),$("chat-summary",!1)&&e.jsx(Eb,{chatLog:r.chatLog,moodEngine:d,isThinking:r.isThinking}),e.jsxs("div",{"data-testid":"composer-input",className:"flex gap-2.5 items-end rounded-2xl border bg-white/[0.03] px-3.5 py-3 transition-all focus-within:border-opacity-60",style:{borderColor:`${r.color}30`},onFocus:K=>{K.currentTarget.style.borderColor=`${r.color}70`},onBlur:K=>{K.currentTarget.style.borderColor=`${r.color}30`},children:[e.jsx("textarea",{"data-testid":"chat-input",ref:C,value:r.prompt,onChange:K=>a(r.id,K.target.value),onKeyDown:U,rows:1,className:"flex-1 bg-transparent text-sm text-slate-200 resize-none outline-none leading-7 min-h-[1.75rem] max-h-32",style:{height:"auto",overflow:"hidden"},onInput:K=>{K.target.style.height="auto",K.target.style.height=Math.min(K.target.scrollHeight,128)+"px"}}),e.jsx("button",{"aria-label":"Send","data-testid":"composer-send-btn",onClick:()=>o(r.id),disabled:!J,className:"p-2 rounded-xl transition-all active:scale-90 disabled:opacity-30",style:{color:r.color,background:`${r.color}18`},children:e.jsx(dh,{})})]}),e.jsx("div",{"data-testid":"composer-hint",className:"px-1 text-[10px] font-mono text-slate-500 tracking-wide",children:"Enter to send · Shift+Enter for newline · / for commands · Ctrl+K palette"}),r.isThinking&&r.chatLog.some(K=>K._streaming)&&e.jsx("div",{className:"flex justify-end px-1",children:e.jsxs("button",{type:"button",onClick:()=>{window.api&&window.api.llm&&window.api.llm.cancelStream().catch(()=>{})},className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-mono border border-rose-500/25 text-rose-400 hover:bg-rose-500/10 transition-all",title:"Stop generating",children:[e.jsx("svg",{className:"w-3 h-3",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),"Stop"]})})]})]})});function yh({panes:t,visiblePanes:r,layout:n,activePaneId:s,renderPane:a}){const o=O.useRef(null),[l,c]=O.useState(0);if(O.useEffect(()=>{const h=o.current;if(!h)return;const g=()=>c(h.clientWidth||0);g();const y=new window.ResizeObserver(()=>g());return y.observe(h),()=>y.disconnect()},[]),n==="tabs"){const h=t.find(g=>g.id===s)??t[0];return h?e.jsx("div",{className:"h-full min-h-0 p-2",children:a(h,!1)}):null}const x={"split-2":2,"split-3":3,"split-4":4}[n]??r.length,p=r.slice(0,x),d=x>=3,m={"split-2":2,"split-3":3,"split-4":2,"split-6":2,"split-9":3,grid:p.length<=2||p.length<=4?2:3}[n]??2,f=d?260:320,b=l>0?Math.max(1,Math.min(m,p.length||1,Math.floor(l/f))):1;return e.jsxs("div",{ref:o,className:"grid gap-2 h-full min-h-0 p-2",style:{gridTemplateColumns:`repeat(${b}, minmax(0, 1fr))`,gridAutoRows:"minmax(0, 1fr)"},children:[p.map(h=>e.jsx("div",{className:`min-h-0 h-full rounded-xl transition-shadow ${h.id===s?"ring-1 ring-violet-400/25 shadow-[inset_0_0_0_1px_rgba(139,92,246,0.12)]":""}`,children:a(h,d)},h.id)),p.lengthe.jsx("div",{className:"rounded-xl border border-dashed border-white/[0.08] flex items-center justify-center text-slate-500 text-[11px] min-h-32",children:"+ Add pane"},`empty-${g}`))]})}function wh({onAdd:t,onClose:r}){const[n,s]=O.useState(""),[a,o]=O.useState(""),[l,c]=O.useState(""),[u,x]=O.useState("llama3");return e.jsxs("div",{className:"absolute top-full left-0 mt-1.5 z-50 w-72 rounded-xl border border-white/[0.1] bg-shell-overlay/98 backdrop-blur-xl shadow-[0_20px_50px_rgba(0,0,0,0.8)] p-4 space-y-3",children:[e.jsx("div",{className:"text-[11px] font-semibold text-slate-300",children:"New Chat Pane"}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[12px] text-slate-400 mb-1 block",children:"Label"}),e.jsx("input",{value:n,onChange:p=>s(p.target.value),className:"w-full bg-white/[0.05] border border-white/[0.08] rounded-lg px-2.5 py-1.5 text-[11px] text-slate-200 outline-none focus:border-violet-500/40"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[12px] text-slate-400 mb-1 block",children:"Agent Mode"}),e.jsx("select",{value:a,onChange:p=>o(p.target.value),className:"w-full bg-white/[0.05] border border-white/[0.08] rounded-lg px-2.5 py-1.5 text-[11px] text-slate-300 outline-none focus:border-violet-500/40 appearance-none",children:Ps.map(p=>e.jsx("option",{value:p.id??"",children:p.label},p.id??""))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[12px] text-slate-400 mb-1 block",children:"Project / Workspace"}),e.jsx("input",{value:l,onChange:p=>c(p.target.value),className:"w-full bg-white/[0.05] border border-white/[0.08] rounded-lg px-2.5 py-1.5 text-[11px] text-slate-200 outline-none focus:border-violet-500/40"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[12px] text-slate-400 mb-1 block",children:"Model"}),e.jsx("select",{value:u,onChange:p=>x(p.target.value),className:"w-full bg-white/[0.05] border border-white/[0.08] rounded-lg px-2.5 py-1.5 text-[11px] text-slate-300 outline-none focus:border-violet-500/40 appearance-none",children:["llama3","llama3.2","mistral","phi4","gemma3:12b","gpt-4.1","gpt-4o","gpt-4o-mini","o4-mini","claude-opus-4-5","claude-sonnet-4-5","claude-3-7-sonnet-latest","claude-3-5-haiku-latest","gemini-2.5-pro","gemini-2.5-flash","gemini-2.0-flash","deepseek-chat","deepseek-reasoner","mistral-large-latest","codestral-latest","llama-3.3-70b-versatile"].map(p=>e.jsx("option",{value:p,children:p},p))})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx("button",{type:"button","data-testid":"workspace-create-pane-btn",onClick:()=>t({label:n||void 0,agentMode:a||null,project:l||null,model:u}),className:"flex-1 py-1.5 rounded-lg bg-violet-500/20 text-violet-300 text-[11px] font-semibold hover:bg-violet-500/30 transition-all",children:"+ Create Pane"}),e.jsx("button",{type:"button",onClick:r,className:"px-3 py-1.5 rounded-lg text-slate-500 hover:text-slate-300 text-[11px] transition-all",children:"Cancel"})]})]})}const vh=i.memo(function({onSendMessage:r,preferAppSend:n=!1,collab:s=null,sessionKey:a="default",panels:o,onCreateSession:l,onOpenNewWindow:c,onOpenTaskManager:u,onToggleWorkpad:x,workpadOpen:p=!1,className:d="",moodEngine:m=null,rgbEnabled:f=!1,rgbStatus:b=null,activeModel:h="llama3",onModelChange:g}){const y=vb({onSendMessage:r,preferAppSend:n,sessionKey:a}),[P,A]=i.useState(0),[C,w]=i.useState(0),[j,E]=O.useState(!1),[N,_]=O.useState(null),S=O.useRef(null),R=O.useRef(null),$=O.useRef(0),U=O.useRef(y.addPane),I=O.useRef(y.removePane),D=O.useRef(y.activePaneId),z=O.useRef(y.panes.length),F=O.useRef(a);O.useEffect(()=>{U.current=y.addPane},[y.addPane]),O.useEffect(()=>{I.current=y.removePane},[y.removePane]),O.useEffect(()=>{D.current=y.activePaneId},[y.activePaneId]),O.useEffect(()=>{z.current=y.panes.length},[y.panes.length]),O.useEffect(()=>{const W=String(h||"").trim();if(!W||!y.activePaneId)return;const Z=y.panes.find(ce=>ce.id===y.activePaneId);Z&&String(Z.model||"")!==W&&y.updatePane(y.activePaneId,{model:W})},[h,y.activePaneId,y.panes,y.updatePane]),i.useEffect(()=>{let W=!0;const Z=async()=>{if(window.api&&window.api.tasks&&typeof window.api.tasks.list=="function")try{const fe=await window.api.tasks.list(),me=Number(fe&&fe.summary&&fe.summary.operations);W&&A(Number.isFinite(me)?me:0)}catch{W&&A(0)}};Z();const ce=window.setInterval(Z,3e3);return()=>{W=!1,window.clearInterval(ce)}},[]),i.useEffect(()=>{const W=String(a||"global"),Z=()=>w(Xl(et(W)));return Z(),qa(()=>Z(),W)},[a]),i.useEffect(()=>{const W=Z=>{const ce=Z&&Z.detail?String(Z.detail.text||"").trim():"";if(!ce)return;const fe=D.current;!fe||typeof y.setPrompt!="function"||(y.setPrompt(fe,ce),window.dispatchEvent(new CustomEvent("neuralshell:focus-composer")))};return window.addEventListener("neuralshell:workpad-insert",W),()=>window.removeEventListener("neuralshell:workpad-insert",W)},[y.setPrompt]),O.useEffect(()=>{const W=R.current;if(!W||!(s&&typeof s.publish=="function"))return;const Z=ce=>{const fe=Date.now();fe-$.current<80||($.current=fe,s.publish("cursor",{x:Number(ce.clientX||0),y:Number(ce.clientY||0)}))};return W.addEventListener("mousemove",Z),()=>{W.removeEventListener("mousemove",Z)}},[s]),O.useEffect(()=>{F.current!==a&&(F.current=a,y.loadSession(a,{workflowId:a||"default"}))},[a,y]),O.useEffect(()=>{const W=Z=>{var me;const ce=Z&&Z.detail&&typeof Z.detail=="object"?Z.detail:{},fe=String(ce.action||"");if(fe==="multi-model-split"){y.panes.length<2&&y.addPane({label:"Compare",model:((me=y.activePane)==null?void 0:me.model)||"llama3",workflowId:a}),y.setLayout("split-2");return}if(fe==="set-project"){const ke=String(ce.project||"").trim();if(!ke||!y.activePaneId)return;y.updatePane(y.activePaneId,{project:ke})}};return window.addEventListener("neuralshell:workspace-panel-action",W),()=>window.removeEventListener("neuralshell:workspace-panel-action",W)},[y,a]),O.useEffect(()=>{if(!j)return;const W=Z=>{S.current&&!S.current.contains(Z.target)&&E(!1)};return document.addEventListener("pointerdown",W),()=>document.removeEventListener("pointerdown",W)},[j]),O.useEffect(()=>{if(!N)return;const W=()=>_(null);return window.addEventListener("mousedown",W),window.addEventListener("blur",W),()=>{window.removeEventListener("mousedown",W),window.removeEventListener("blur",W)}},[N]),O.useEffect(()=>{const W=Z=>{Z.ctrlKey&&Z.key==="t"&&(Z.preventDefault(),U.current()),Z.ctrlKey&&Z.key==="w"&&(Z.preventDefault(),z.current>1&&I.current(D.current)),Z.ctrlKey&&Z.key==="p"&&o&&typeof o.open=="function"&&(Z.preventDefault(),o.open("projects-mode"))};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[o]);const J=O.useCallback(W=>{y.addPane(W),E(!1)},[y]),ee=O.useCallback(W=>{W.target.closest("button, input, textarea")||(W.preventDefault(),_({x:W.clientX,y:W.clientY}))},[]),ie=O.useCallback(async W=>{if(_(null),W==="new-chat"){typeof l=="function"?l():J();return}W==="new-window"&&typeof c=="function"&&await c()},[J,l,c]),ye=O.useCallback(()=>E(!1),[]),pe={"split-2":2,"split-3":3,"split-4":4},K=y.layout==="tabs"?y.panes:y.panes.slice(0,pe[y.layout]??y.panes.length),H=O.useCallback((W,Z)=>e.jsx(gh,{pane:W,compact:Z,isActive:W.id===y.activePaneId,onPromptChange:y.setPrompt,onSend:y.sendMessage,onClear:y.clearChat,onRename:y.renamePane,onUpdatePane:y.updatePane,onModelChange:g,panels:o,moodEngine:m,rgbEnabled:f,rgbStatus:b,activeTaskCount:P,onOpenTaskManager:u,onToggleWorkpad:x,workpadOpen:p,workpadOpenCount:C},W.id),[y,g,o,m,f,b,P,C,p,u,x]);return e.jsxs("div",{ref:R,"data-testid":"workspace-panel",className:`flex flex-col h-full min-h-0 bg-shell-canvas ${d}`,children:[e.jsxs("div",{className:"flex items-center gap-0 border-b border-white/[0.06] bg-shell-canvas/80 px-2 shrink-0 overflow-x-auto scrollbar-none",children:[e.jsxs("div",{className:"flex items-end gap-0.5 py-1.5 min-w-0 flex-1 overflow-x-auto scrollbar-none",children:[y.panes.map(W=>{const Z=W.id===y.activePaneId;return e.jsxs("div",{onClick:()=>y.setActivePaneId(W.id),className:`group flex items-center gap-1.5 px-3.5 py-2 rounded-t-lg cursor-pointer select-none shrink-0 transition-all border-b-2 ${Z?"border-opacity-100":"bg-transparent border-transparent hover:bg-white/[0.03] border-transparent"}`,style:{borderBottomColor:Z?W.color:"transparent",backgroundColor:Z?`${W.color}12`:void 0,boxShadow:Z?`inset 0 -1px 0 ${W.color}60`:void 0},children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0 transition-all",style:{backgroundColor:W.color,boxShadow:Z?`0 0 8px ${W.color}, 0 0 3px ${W.color}`:"none",opacity:Z?1:.4}}),e.jsx("span",{className:`text-[12px] font-medium transition-colors max-w-32 truncate ${Z?"text-slate-100":"text-slate-500 group-hover:text-slate-400"}`,children:W.label}),W.agentMode&&e.jsx("span",{className:"text-[11px] px-1.5 rounded bg-amber-500/15 text-amber-400/70 shrink-0",children:"agent"}),W.isThinking&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-violet-400 animate-pulse shrink-0"}),W.chatLog.length>0&&e.jsx("span",{className:`text-[11px] font-mono px-1.5 rounded-full shrink-0 ${Z?"bg-white/10 text-slate-400":"text-slate-600"}`,children:W.chatLog.length}),y.panes.length>1&&e.jsx("button",{type:"button","aria-label":"Close workspace pane",title:"Close pane",onClick:ce=>{ce.stopPropagation(),y.removePane(W.id)},className:"ml-0.5 p-0.5 rounded opacity-0 group-hover:opacity-100 text-slate-500 hover:text-rose-400 hover:bg-rose-500/10 transition-all active:scale-90",children:e.jsx(oh,{})})]},W.id)}),e.jsxs("div",{className:"relative shrink-0",ref:S,children:[e.jsxs("button",{type:"button","data-testid":"workspace-add-pane-btn",onClick:()=>E(W=>!W),className:"flex items-center gap-1.5 px-2.5 py-2 rounded-lg text-slate-500 hover:text-violet-300 hover:bg-violet-500/10 transition-all active:scale-95 ml-1",title:`New chat pane (Ctrl+T) • max ${lr}`,disabled:y.panes.length>=lr,"aria-disabled":y.panes.length>=lr,style:y.panes.length>=lr?{opacity:.45,cursor:"not-allowed"}:void 0,children:[e.jsx(ah,{}),e.jsx("span",{className:"text-[11px]",children:"New"})]}),j&&e.jsx(wh,{onAdd:J,onClose:ye})]})]}),e.jsx("div",{className:"w-px h-5 bg-white/[0.07] shrink-0 mx-1"}),e.jsx("div",{className:"flex items-center gap-0.5 shrink-0 py-1.5",children:Gl.map(W=>e.jsx("button",{type:"button","aria-label":`Layout: ${_d[W]}`,"aria-pressed":y.layout===W,onClick:()=>y.setLayout(W),title:_d[W],className:`p-1.5 rounded-md transition-all active:scale-90 ${y.layout===W?"text-violet-300 bg-violet-500/15 ring-1 ring-violet-500/25":"text-slate-500 hover:text-slate-300 hover:bg-white/[0.05]"}`,children:xh[W]},W))}),e.jsx("div",{className:"w-px h-5 bg-white/[0.07] shrink-0 mx-1"}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0 py-1.5 pr-1",children:[o&&e.jsxs("button",{type:"button",onClick:()=>o.open("projects-mode"),title:"Projects (Ctrl+P)",className:`flex items-center gap-1 px-2.5 py-1.5 rounded-md text-[12px] transition-all active:scale-95 ${o.isOpen("projects-mode")?"text-sky-300 bg-sky-500/15 ring-1 ring-sky-500/25":"text-slate-400 hover:text-sky-300 hover:bg-sky-500/10"}`,children:[e.jsx(ph,{}),e.jsx("span",{className:"hidden sm:inline",children:"Projects"})]}),o&&e.jsxs("button",{type:"button",onClick:()=>o.open("agent-store"),title:"Agent Marketplace",className:`flex items-center gap-1 px-2.5 py-1.5 rounded-md text-[12px] transition-all active:scale-95 ${o.isOpen("agent-store")?"text-amber-300 bg-amber-500/15 ring-1 ring-amber-500/25":"text-slate-400 hover:text-amber-300 hover:bg-amber-500/10"}`,children:[e.jsx(uh,{}),e.jsx("span",{className:"hidden sm:inline",children:"Agents"})]}),e.jsxs("span",{"data-testid":"workspace-pane-counter",className:"px-2 py-1 rounded-full text-[12px] font-mono bg-white/[0.05] text-slate-500",title:`Ctrl+T new · Ctrl+W close · max ${lr}`,children:[y.panes.findIndex(W=>W.id===y.activePaneId)+1,"/",y.panes.length," · max ",lr]})]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",onContextMenu:ee,children:e.jsx(yh,{panes:y.panes,visiblePanes:K,layout:y.layout,activePaneId:y.activePaneId,renderPane:H})}),s&&s.remoteCursors&&Object.keys(s.remoteCursors).length>0&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-[120]",children:Object.entries(s.remoteCursors).map(([W,Z])=>{const ce=Number(Z&&Z.x?Z.x:0),fe=Number(Z&&Z.y?Z.y:0);return!Number.isFinite(ce)||!Number.isFinite(fe)?null:e.jsxs("div",{className:"absolute",style:{transform:`translate(${Math.max(0,ce)}px, ${Math.max(0,fe)}px)`},children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-emerald-300 shadow-[0_0_12px_rgba(16,185,129,0.7)]"}),e.jsx("div",{className:"mt-1 px-1.5 py-0.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[8px] font-mono uppercase tracking-[0.14em] text-emerald-100",children:String(W||"peer").slice(0,10)})]},W)})}),N&&e.jsx("div",{className:"fixed inset-0 z-[115]",onMouseDown:()=>_(null),children:e.jsxs("div",{"data-testid":"desktop-context-menu",className:"absolute w-48 rounded-xl border border-cyan-400/20 bg-slate-950/96 shadow-[0_18px_60px_rgba(0,0,0,0.7)] backdrop-blur-xl p-1.5",style:{left:N.x,top:N.y},onMouseDown:W=>W.stopPropagation(),children:[e.jsx("div",{className:"px-2.5 py-1.5 text-[12px] font-mono uppercase tracking-wide text-cyan-200/75 border-b border-white/[0.06] mb-1",children:"Desktop"}),e.jsxs("button",{type:"button",onClick:()=>{ie("new-window")},className:"w-full flex items-center gap-2 rounded-lg px-2.5 py-2 text-left text-[11px] text-slate-300 hover:bg-cyan-500/10 hover:text-cyan-200 transition-colors group",children:[e.jsx("span",{className:"w-4 flex items-center justify-center text-slate-500 group-hover:text-cyan-400 transition-colors",children:e.jsx(Bx,{size:12})}),e.jsx("span",{children:"Open New Window"})]}),e.jsxs("button",{type:"button",onClick:()=>{ie("new-chat")},className:"w-full flex items-center gap-2 rounded-lg px-2.5 py-2 text-left text-[11px] text-slate-300 hover:bg-violet-500/10 hover:text-violet-200 transition-colors group",children:[e.jsx("span",{className:"w-4 flex items-center justify-center text-slate-500 group-hover:text-violet-400 transition-colors",children:e.jsx(Fx,{size:12})}),e.jsx("span",{children:"Open New Chat"})]})]})})]})});function jh({children:t,tone:r="default"}){const n=(...a)=>a.filter(Boolean).join(" "),s=r==="cyan"?"border-cyan-400/25 bg-cyan-400/10 text-cyan-200":r==="gold"?"border-amber-300/25 bg-amber-300/10 text-amber-200":r==="warn"?"border-orange-400/25 bg-orange-400/10 text-orange-200":r==="green"?"border-emerald-400/25 bg-emerald-400/10 text-emerald-200":"border-white/10 bg-white/[0.035] text-slate-300";return e.jsx("span",{className:n("inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em]",s),children:t})}function Ii({label:t,count:r,tone:n="neutral",testId:s}){const a=Math.max(0,Number(r||0)),o=n==="added"?"border-emerald-300/35 bg-emerald-500/12 text-emerald-200":n==="modified"?"border-amber-300/35 bg-amber-500/12 text-amber-200":n==="deleted"?"border-rose-300/35 bg-rose-500/12 text-rose-200":"border-slate-300/20 bg-slate-500/10 text-slate-300";return e.jsxs("div",{"data-testid":s,className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-md border text-[9px] font-mono uppercase tracking-[0.12em] ${o}`,children:[e.jsx("span",{children:t}),e.jsx("span",{children:a})]})}const kh=[{id:"explain",label:"Explain",prefix:"/explain"},{id:"refactor",label:"Refactor",prefix:"/refactor"},{id:"unit-test",label:"UnitTest",prefix:"/unit-test"}];function Nh({visible:t,x:r,y:n,selectionText:s,onPick:a}){if(!t)return null;const o=String(s||"").trim();return o?e.jsx("div",{"data-testid":"context-chip-bar",className:"fixed z-[80] flex items-center gap-1.5 rounded-lg border border-cyan-300/30 bg-slate-950/95 px-2 py-1 shadow-[0_10px_25px_rgba(0,0,0,0.45)]",style:{left:`${Math.max(8,Number(r||0))}px`,top:`${Math.max(8,Number(n||0))}px`},children:kh.map(l=>e.jsx("button",{type:"button","data-testid":`context-chip-${l.id}`,onMouseDown:c=>{c.preventDefault()},onClick:()=>{typeof a=="function"&&a(`${l.prefix} ${o}`)},className:"px-2 py-1 rounded border border-white/10 bg-black/35 text-[9px] font-mono uppercase tracking-[0.12em] text-slate-200 hover:border-cyan-300/30 hover:text-cyan-100 hover:bg-cyan-500/10",children:l.label},l.id))}):null}async function Sh(){if(!(window.api&&window.api.workspace&&typeof window.api.workspace.pickRoot=="function"))throw new Error("Workspace picker is unavailable in this runtime.");const t=await window.api.workspace.pickRoot();if(!t)return null;const r=String(t.path||t.rootPath||"").trim();return r?(window.api.workspace.register&&await window.api.workspace.register(r),window.api.workspace.setActive&&t.id&&await window.api.workspace.setActive(t.id),{path:r,id:t.id}):null}const Ch=["README.md","readme.md","package.json","src/main.js"];async function _h(t=2400){if(!(window.api&&window.api.workspace&&typeof window.api.workspace.getActive=="function"))return null;const r=await window.api.workspace.getActive(),n=String((r==null?void 0:r.path)||(r==null?void 0:r.rootPath)||"").trim();if(!n)return null;if(typeof window.api.workspace.readFile!="function")return{rootPath:n,label:String((r==null?void 0:r.label)||n),content:`// Active workspace: ${n} +`}),ms=Object.freeze({math:"Math",science:"Science",english:"English",history:"History",code:"Coding"});Object.freeze([{id:"math",label:ms.math,emoji:"📐",color:"#38bdf8",prompt:ps.math},{id:"science",label:ms.science,emoji:"🔬",color:"#34d399",prompt:ps.science},{id:"english",label:ms.english,emoji:"✍️",color:"#a78bfa",prompt:ps.english},{id:"history",label:ms.history,emoji:"🏛️",color:"#fbbf24",prompt:ps.history},{id:"code",label:ms.code,emoji:"💻",color:"#f472b6",prompt:ps.code},{id:"other",label:"Other",emoji:"📚",color:"#94a3b8",prompt:Hp}]);const nh="neuralshell_adaptive_layout_v1";function Sd(){if(typeof window>"u"||!window.localStorage)return{};try{const t=window.localStorage.getItem(nh),r=t?JSON.parse(t):null;return r&&typeof r=="object"&&r.panels&&typeof r.panels=="object"?r.panels:{}}catch{return{}}}function Wp(){const[t,r]=O.useState(()=>Sd());O.useEffect(()=>{const s=()=>r(Sd());return window.addEventListener("neuralshell:apply-layout",s),window.addEventListener("neuralshell:layout-chrome-updated",s),window.addEventListener("storage",s),()=>{window.removeEventListener("neuralshell:apply-layout",s),window.removeEventListener("neuralshell:layout-chrome-updated",s),window.removeEventListener("storage",s)}},[]);const n=O.useCallback((s,a=!0)=>!s||!Object.prototype.hasOwnProperty.call(t,s)?a:t[s]!==!1,[t]);return{panels:t,isPanelChromeVisible:n}}function sh(){const[t,r]=O.useState(Qt);return O.useEffect(()=>Lp(r),[]),[...t].sort((n,s)=>n.date.localeCompare(s.date)).slice(0,5)}function ah(){return e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{d:"M12 5v14M5 12h14"})})}function oh(){return e.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:e.jsx("path",{d:"M18 6L6 18M6 6l12 12"})})}function ih(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:[e.jsx("rect",{x:"2",y:"2",width:"20",height:"20",rx:"2"}),e.jsx("path",{d:"M12 2v20"})]})}function lh(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:[e.jsx("rect",{x:"2",y:"2",width:"20",height:"20",rx:"2"}),e.jsx("path",{d:"M9 2v20M15 2v20"})]})}function Cd(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:[e.jsx("rect",{x:"2",y:"2",width:"20",height:"20",rx:"2"}),e.jsx("path",{d:"M12 2v20M2 12h20"})]})}function ch(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:[e.jsx("rect",{x:"2",y:"6",width:"20",height:"16",rx:"1"}),e.jsx("path",{d:"M2 6V4a1 1 0 011-1h5a1 1 0 011 1v2M10 6V4a1 1 0 011-1h5a1 1 0 011 1v2"})]})}function dh(){return e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{d:"M22 2L11 13M22 2L15 22l-4-9-9-4 20-7z"})})}function uh(){return e.jsxs("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:[e.jsx("circle",{cx:"12",cy:"12",r:"3"}),e.jsx("path",{d:"M12 1v4m0 14v4m-7.07-2.93l2.83-2.83m8.48-8.48l2.83-2.83M1 12h4m14 0h4m-2.93 7.07l-2.83-2.83M6.76 6.76L3.93 3.93"})]})}function ph(){return e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{d:"M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"})})}function mh(){return e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{d:"M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a1 1 0 011-1h4a1 1 0 011 1v2"})})}const xh={tabs:e.jsx(ch,{}),"split-2":e.jsx(ih,{}),"split-3":e.jsx(lh,{}),"split-4":e.jsx(Cd,{}),grid:e.jsx(Cd,{})},_d={tabs:"Tabs","split-2":"2-Split","split-3":"3-Split","split-4":"4-Split (2×2)",grid:"Grid (Auto)"},Ps=[{id:null,label:"None"},{id:"analyze",label:"Analyze"},{id:"code",label:"Code"},{id:"test",label:"Test"},{id:"review",label:"Review"},{id:"deploy",label:"Deploy"},{id:"monitor",label:"Monitor"},{id:"document",label:"Document"}];function fh(){return e.jsxs("span",{className:"flex gap-1 items-end px-1 h-4",children:[e.jsx("span",{className:"w-1 rounded-sm bg-violet-400 animate-thinking-dot-1",style:{height:"10px",transformOrigin:"bottom"}}),e.jsx("span",{className:"w-1 rounded-sm bg-violet-300 animate-thinking-dot-2",style:{height:"14px",transformOrigin:"bottom"}}),e.jsx("span",{className:"w-1 rounded-sm bg-violet-400 animate-thinking-dot-3",style:{height:"10px",transformOrigin:"bottom"}})]})}function Ei({title:t,eyebrow:r,children:n}){return e.jsxs("div",{className:"ui-holo-panel rounded-[1.15rem] px-3.5 py-3.5",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide font-bold text-slate-500",children:r}),e.jsx("div",{className:"mt-1 text-[13px] font-semibold text-slate-200",children:t}),e.jsx("div",{className:"mt-2 text-[13px] text-slate-400 leading-6",children:n})]})}i.memo(function({accentColor:r}){const[n,s]=O.useState({tok:0,words:0}),a=O.useRef({tok:0,words:0,recent:[],start:Date.now()});return O.useEffect(()=>{a.current={tok:0,words:0,recent:[],start:Date.now()};const o=l=>{const u=l.detail&&l.detail.message&&l.detail.message.content||"";if(!u)return;const x=Date.now();a.current.tok++,a.current.words+=u.split(/\s+/).filter(Boolean).length,a.current.recent.push(x),a.current.recent=a.current.recent.filter(p=>x-p<2e3)};window.addEventListener("llm-stream-data",o);const c=setInterval(()=>{const{tok:l,words:u,recent:x}=a.current,p=Math.round(x.filter(d=>Date.now()-d<2e3).length/2);s({tok:l,words:u,tokPerSec:p})},300);return()=>{window.removeEventListener("llm-stream-data",o),clearInterval(c)}},[]),e.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] font-mono",style:{color:r},children:[e.jsx("span",{className:"w-1 h-1 rounded-full animate-pulse",style:{backgroundColor:r}}),e.jsxs("span",{children:[n.tokPerSec??0," tok/s"]}),e.jsx("span",{className:"text-slate-700",children:"·"}),e.jsxs("span",{children:[n.words," words"]})]})});const bh=i.memo(function({msg:r,accentColor:n,onRetry:s}){const a=r.role==="user",o=!!r._streaming,c=o?Math.ceil(String(r.content||"").length/4):0,[l,u]=O.useState(!1),x=O.useCallback(()=>{navigator.clipboard.writeText(String(r.content||"")).then(()=>{u(!0),setTimeout(()=>u(!1),1500)}).catch(()=>{})},[r.content]),p=Jb(r.ts),d=p!=null?Gb(p):"";return e.jsxs("div",{"data-testid":"chat-message",tabIndex:-1,className:`group flex gap-2 ${a?"flex-row-reverse":"flex-row"} items-start mb-3`,children:[e.jsx("div",{className:"w-7 h-7 rounded-full shrink-0 flex items-center justify-center text-[12px] font-bold mt-0.5",style:{backgroundColor:a?`${n}25`:"rgba(139,92,246,0.2)",color:a?n:"#a78bfa"},children:a?"U":"AI"}),e.jsxs("div",{className:`flex flex-col gap-1 max-w-[85%] ${a?"items-end":"items-start"}`,children:[d&&e.jsx("span",{"data-testid":"message-timestamp",className:"text-[10px] font-mono text-slate-500 tabular-nums",title:p!=null?new Date(p).toLocaleString():void 0,children:d}),e.jsxs("div",{className:`rounded-xl px-3.5 py-2.5 text-[13px] leading-7 whitespace-pre-wrap break-words ${a?"bg-white/[0.06] text-slate-200 rounded-tr-none":"bg-violet-500/[0.08] border border-violet-500/20 text-slate-300 rounded-tl-none"}`,style:a?{borderColor:`${n}20`}:{},children:[r.content,o&&e.jsx("span",{className:"inline-block w-0.5 h-[1em] bg-current align-middle ml-0.5 animate-[blink_0.8s_step-end_infinite] opacity-80","aria-hidden":"true"})]}),o&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] font-mono text-violet-400/70 bg-violet-500/10 px-1.5 py-0.5 rounded-full border border-violet-500/15 self-start",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-violet-400 animate-pulse"}),"streaming · ~",c," tokens"]}),!o&&e.jsxs("div",{className:`flex items-center gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity duration-150 ${a?"justify-end":"justify-start"}`,children:[e.jsx("button",{type:"button",onClick:x,className:"flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] font-mono text-slate-400 hover:text-slate-300 hover:bg-white/5 transition-all",title:"Copy message",children:l?e.jsxs(e.Fragment,{children:[e.jsx("svg",{className:"w-2.5 h-2.5 text-emerald-400",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2.5,children:e.jsx("path",{d:"M20 6L9 17l-5-5"})}),e.jsx("span",{className:"text-emerald-400",children:"copied"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("svg",{className:"w-2.5 h-2.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:[e.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),e.jsx("path",{d:"M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"})]}),e.jsx("span",{children:"copy"})]})}),!a&&typeof s=="function"&&e.jsxs("button",{type:"button",onClick:s,className:"flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] font-mono text-slate-400 hover:text-violet-300 hover:bg-violet-500/10 transition-all",title:"Regenerate",children:[e.jsxs("svg",{className:"w-2.5 h-2.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:[e.jsx("path",{d:"M1 4v6h6"}),e.jsx("path",{d:"M3.51 15a9 9 0 1 0 .49-3.14"})]}),"retry"]})]})]})]})}),hh=i.memo(function({pane:r,onSend:n,onUpdatePane:s,starterCommands:a,promptSuggestions:o}){var x,p;const c=sh(),l=i.useCallback(d=>n(r.id,d),[n,r.id]),u=r.agentMode?`${((x=Ps.find(d=>d.id===r.agentMode))==null?void 0:x.label)||r.agentMode} lane armed`:"General lane active";return e.jsx("div",{className:"flex min-h-full w-full items-start justify-center px-4 py-8 sm:px-6",children:e.jsxs("div",{className:"w-full max-w-6xl space-y-6 animate-fade-up",children:[e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"mx-auto flex h-14 w-14 items-center justify-center rounded-[1.25rem] ui-edge-glow",style:{backgroundColor:`${r.color}15`,boxShadow:`0 0 28px ${r.color}28`,border:`1px solid ${r.color}22`},children:e.jsx("span",{className:"h-3.5 w-3.5 rounded-full animate-thinking-dot",style:{backgroundColor:r.color,boxShadow:`0 0 12px ${r.color}`}})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-[0.22em] text-slate-500",children:r.label}),e.jsx("h2",{className:"text-[2rem] font-semibold tracking-tight text-slate-100",children:"Operator Hero Console"}),e.jsx("p",{className:"mx-auto max-w-4xl text-sm leading-7 text-slate-500",children:"Skip dead-start screens: launch high-impact commands, verify posture, and move from idea to deployment in one control pass."})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2",children:[e.jsx("span",{className:"ui-holo-panel rounded-full px-3 py-1 text-[13px] font-mono text-slate-300",children:r.model}),r.agentMode&&e.jsxs("span",{className:"rounded-full border border-amber-500/20 bg-amber-500/10 px-3 py-1 text-[13px] text-amber-300 ui-edge-glow",children:[(p=Ps.find(d=>d.id===r.agentMode))==null?void 0:p.label," mode"]}),r.project&&e.jsx("span",{className:"rounded-full border border-sky-500/20 bg-sky-500/10 px-3 py-1 text-[13px] text-sky-300 ui-edge-glow",children:r.project})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2.5",children:[e.jsx("button",{type:"button",onClick:()=>n(r.id,"/proof"),className:"ui-tactile rounded-xl border border-violet-400/30 bg-violet-500/12 px-4 py-2 text-[13px] font-semibold text-violet-200 hover:bg-violet-500/20",children:"Launch proof lane"}),e.jsx("button",{type:"button",onClick:()=>n(r.id,"/guard"),className:"ui-tactile rounded-xl border border-rose-400/30 bg-rose-500/12 px-4 py-2 text-[13px] font-semibold text-rose-200 hover:bg-rose-500/20",children:"Run security sweep"})]})]}),e.jsx(Cb,{onCommand:l}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2.5",children:[e.jsxs(Ei,{eyebrow:"Execution lane",title:"Current operating posture",children:[e.jsx("span",{className:"text-cyan-300 font-mono",children:u}),e.jsx("span",{className:"block mt-1",children:"Pair this with /status for instant runtime confirmation."})]}),e.jsxs(Ei,{eyebrow:"Context",title:"Workspace objective",children:[r.project?`Project focus is ${r.project}.`:"No project pinned yet.",e.jsx("span",{className:"block mt-1",children:"Pin one to make suggestions sharper and faster."})]}),e.jsxs(Ei,{eyebrow:"Tempo",title:"Action cadence",children:["Begin with a command card, then commit one prompt from the suggestion grid.",e.jsx("span",{className:"block mt-1",children:"This keeps velocity high without context thrash."})]})]}),c.length>0&&e.jsxs("div",{className:"ui-holo-panel rounded-2xl px-4 py-3 space-y-2",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-wide font-bold text-slate-500",children:"Upcoming Deadlines"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:c.map(d=>{const m=Ub(d.date),f=m<0?"#f87171":m===0?"#fb923c":m<=2?"#facc15":m<=7?"#67e8f9":"#475569";return e.jsxs("div",{className:"ui-tactile flex items-center gap-1.5 px-2.5 py-1 rounded-xl border border-white/[0.07] bg-black/20 text-[11px]",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:f}}),e.jsx("span",{className:"text-slate-300 truncate max-w-36",children:d.title}),e.jsx("span",{className:"font-mono shrink-0",style:{color:f},children:m<0?`${Math.abs(m)}d overdue`:m===0?"today":`${m}d`})]},d.id)})})]}),e.jsx("div",{className:"grid gap-2.5 md:grid-cols-2",children:a.map(d=>e.jsx("button",{"data-testid":d.testId,onClick:()=>{n(r.id,d.command)},className:"ui-holo-panel ui-tactile group rounded-[1.35rem] px-4 py-4 text-left hover:border-white/[0.13] hover:bg-white/[0.045]",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-200 group-hover:text-white transition-colors",children:d.label}),e.jsx("div",{className:"mt-0.5 text-[13px] leading-6 text-slate-500 group-hover:text-slate-400 transition-colors",children:d.description})]}),e.jsx("div",{className:"rounded-lg border border-white/[0.08] bg-black/30 px-2 py-0.5 text-[12px] font-mono text-slate-400 shrink-0 group-hover:border-white/[0.14] group-hover:text-slate-300 transition-all",children:d.command})]})},d.testId))}),e.jsxs("div",{className:"ui-holo-panel rounded-[1.35rem] p-4",children:[e.jsxs("div",{className:"mb-2.5 flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-300",children:"Suggested prompts"}),e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-slate-500 font-mono",children:"tap to send"})]}),e.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:o.map(d=>e.jsx("button",{type:"button",onClick:()=>{n(r.id,d)},className:"ui-tactile rounded-xl border border-white/[0.05] bg-black/10 px-3.5 py-2.5 text-left text-[13px] leading-6 text-slate-400 hover:border-white/[0.10] hover:bg-white/[0.035] hover:text-slate-200",children:d},d))})]}),e.jsx("div",{className:"text-center text-[11px] font-mono uppercase tracking-wide text-slate-700",children:"↵ send  ·  ⇧↵ newline  ·  Ctrl+T new pane  ·  click date in header for deadlines"})]})})}),gh=i.memo(function({pane:r,compact:n,isActive:s=!1,onPromptChange:a,onSend:o,onClear:c,onRename:l,onUpdatePane:u,onModelChange:x,panels:p,moodEngine:d,rgbEnabled:m=!1,rgbStatus:f=null,activeTaskCount:b=0,workpadOpenCount:h=0,workpadOpen:g=!1,onOpenTaskManager:y,onToggleWorkpad:I}){var pe;const A=O.useRef(null),C=O.useRef(null),w=O.useRef(null),[j,E]=O.useState(!1),[N,_]=O.useState(r.label),[S,R]=O.useState(!1),{isPanelChromeVisible:$}=Wp();O.useEffect(()=>{var K;(K=A.current)==null||K.scrollIntoView({behavior:"smooth"})},[r.chatLog.length,r.isThinking]),O.useEffect(()=>{const K=()=>{var H;(H=C.current)==null||H.focus()};return window.addEventListener("neuralshell:focus-composer",K),()=>window.removeEventListener("neuralshell:focus-composer",K)},[]),O.useEffect(()=>{if(!s)return;const K=window.setTimeout(()=>{var H;return(H=C.current)==null?void 0:H.focus()},0);return()=>window.clearTimeout(K)},[s,r.id]);const U=O.useCallback(K=>{K.key==="Enter"&&!K.shiftKey&&(K.preventDefault(),o(r.id))},[o,r.id]),P=O.useCallback(K=>o(r.id,K),[o,r.id]),D=O.useCallback(K=>{rh(K,w.current)},[]),z=String(r.prompt||"").trim(),F=/^\/(?:clear|purge|reset)$/i.test(z),J=!!z&&(!r.isThinking||F),ee=()=>{N.trim()&&l(r.id,N.trim()),E(!1)},ie=i.useMemo(()=>[{label:"Command help",description:"See operator commands and shortcuts.",command:"/help",testId:"card-help"},{label:"Run proof",description:"Generate the trust and release narrative.",command:"/proof",testId:"card-proof"},{label:"ROI snapshot",description:"Summarize value and impact quickly.",command:"/roi",testId:"card-roi"},{label:"Security guard",description:"Check the current protection posture.",command:"/guard",testId:"card-guard"},{label:"Concept mentor",description:"Walk the logic in deliberate steps—clarity on how and why, not a one-shot answer.",command:Hp.trim(),testId:"card-study-coach"}],[]),ye=i.useMemo(()=>r.agentMode==="code"||!r.agentMode?["Explain this codebase","Write a unit test","Find bugs in my code","Refactor for clarity"]:r.agentMode==="analyze"?["Analyze code quality","Find performance issues","Security audit","Summarize changes"]:r.agentMode==="review"?["Review this PR","Check for code smells","Suggest improvements","Validate logic"]:["Start a task","Ask a question","Summarize context","Generate output"],[r.agentMode]);return e.jsxs("div",{className:"flex flex-col h-full min-h-0 bg-shell-canvas rounded-xl overflow-hidden border",style:{borderColor:`${r.color}22`},children:[e.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2.5 border-b shrink-0",style:{borderColor:`${r.color}18`,background:`linear-gradient(90deg, ${r.color}0a 0%, transparent 100%)`},children:[e.jsx("span",{className:`w-2.5 h-2.5 rounded-full shrink-0 ${r.isThinking?"animate-pulse":""}`,style:{backgroundColor:r.color,boxShadow:`0 0 6px ${r.color}`}}),j?e.jsx("input",{autoFocus:!0,value:N,onChange:K=>_(K.target.value),onBlur:ee,onKeyDown:K=>{K.key==="Enter"&&ee(),K.key==="Escape"&&E(!1)},className:"flex-1 bg-white/[0.06] border border-white/[0.1] rounded px-2 py-1 text-[12px] font-medium text-slate-200 outline-none min-w-0"}):e.jsx("span",{className:"flex-1 text-[12px] font-semibold cursor-pointer hover:opacity-70 truncate min-w-0",style:{color:r.color},onDoubleClick:()=>{_(r.label),E(!0)},children:r.label}),r.agentMode&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[12px] font-medium bg-amber-500/15 text-amber-300 border border-amber-500/20 shrink-0",children:((pe=Ps.find(K=>K.id===r.agentMode))==null?void 0:pe.label)||r.agentMode}),r.project&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[12px] font-medium bg-sky-500/15 text-sky-300 border border-sky-500/20 shrink-0 max-w-24 truncate",children:r.project}),!n&&e.jsx("select",{value:r.model,"data-testid":`pane-model-select-${r.id}`,onChange:K=>{const H=K.target.value;u(r.id,{model:H}),typeof x=="function"&&Promise.resolve(x(H)).catch(()=>{})},className:"bg-white/[0.04] border border-white/[0.08] rounded px-1.5 py-1 text-[12px] font-mono text-slate-400 outline-none hover:bg-white/[0.06] transition-all cursor-pointer appearance-none max-w-24 truncate",children:["llama3","llama3.2","mistral","phi4","gemma3:12b","qwq:32b","gpt-4.1","gpt-4o","gpt-4o-mini","o4-mini","claude-opus-4-5","claude-sonnet-4-5","claude-3-7-sonnet-latest","claude-3-5-haiku-latest","gemini-2.5-pro","gemini-2.5-flash","gemini-2.0-flash","deepseek-chat","deepseek-reasoner","mistral-large-latest","codestral-latest","llama-3.3-70b-versatile","gemma2-9b-it"].map(K=>e.jsx("option",{value:K,children:K},K))}),!n&&e.jsx("select",{value:r.agentMode||"","aria-label":"Agent mode",onChange:K=>u(r.id,{agentMode:K.target.value||null}),className:"bg-white/[0.04] border border-white/[0.08] rounded px-1.5 py-1 text-[12px] font-mono text-slate-400 outline-none hover:bg-white/[0.06] transition-all cursor-pointer appearance-none max-w-24",title:"Agent Mode",children:Ps.map(K=>e.jsx("option",{value:K.id??"",children:K.label},K.id??"none"))}),e.jsx("button",{type:"button",onClick:()=>c(r.id),title:"Clear chat",className:"p-1.5 rounded text-slate-500 hover:text-rose-400 hover:bg-rose-500/10 transition-all active:scale-90",children:e.jsx(mh,{})})]}),e.jsxs("div",{ref:w,role:"region","aria-label":`Messages, ${r.label||"pane"}`,tabIndex:r.chatLog.length>0?0:void 0,onKeyDown:D,className:"flex-1 overflow-y-auto px-4 py-4 min-h-0 space-y-1 scrollbar-thin scrollbar-track-transparent scrollbar-thumb-white/10",children:[r.chatLog.length===0&&e.jsx(hh,{pane:r,onSend:o,onUpdatePane:u,starterCommands:ie,promptSuggestions:ye}),r.chatLog.map((K,H)=>e.jsx(bh,{msg:K,accentColor:r.color,onRetry:!K._streaming&&K.role!=="user"?()=>{var W;return o(r.id,((W=r.chatLog.slice(0,H).reverse().find(Z=>Z.role==="user"))==null?void 0:W.content)||"")}:void 0},H))," ",r.isThinking&&!r.chatLog.some(K=>K._streaming)&&e.jsxs("div",{className:"flex gap-2 items-start mb-3",children:[e.jsx("div",{className:"w-7 h-7 rounded-full shrink-0 flex items-center justify-center text-[12px] font-bold bg-violet-500/20 text-violet-400",children:"AI"}),e.jsx("div",{className:"rounded-xl px-3 py-2 bg-violet-500/[0.08] border border-violet-500/20 rounded-tl-none",children:e.jsx(fh,{})})]}),r.isThinking&&r.chatLog.some(K=>K._streaming)&&e.jsx("div",{className:"flex justify-end mb-1",children:e.jsxs("button",{type:"button",onClick:()=>{window.api&&window.api.llm&&window.api.llm.cancelStream().catch(()=>{})},className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-mono border border-rose-500/25 text-rose-400 hover:bg-rose-500/10 transition-all",title:"Stop generating",children:[e.jsx("svg",{className:"w-3 h-3",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),"Stop"]})}),!r.isThinking&&$("smart-suggest",!0)&&e.jsx(Bb,{chatLog:r.chatLog,onSend:P,isThinking:r.isThinking}),e.jsx("div",{ref:A})]}),e.jsxs("div",{className:"shrink-0 px-4 pb-4 pt-2 space-y-2",children:[e.jsx(Ob,{moodEngine:d,pane:r,panels:p,rgbEnabled:m,rgbStatus:f,activeTaskCount:b,onOpenTaskManager:y,onToggleWorkpad:I,workpadOpen:g,workpadOpenCount:h}),$("chat-summary",!1)&&e.jsx(Eb,{chatLog:r.chatLog,moodEngine:d,isThinking:r.isThinking}),e.jsxs("div",{"data-testid":"composer-input",className:"flex gap-2.5 items-end rounded-2xl border bg-white/[0.03] px-3.5 py-3 transition-all focus-within:border-opacity-60",style:{borderColor:`${r.color}30`},onFocus:K=>{K.currentTarget.style.borderColor=`${r.color}70`},onBlur:K=>{K.currentTarget.style.borderColor=`${r.color}30`},children:[e.jsx("textarea",{"data-testid":"chat-input",ref:C,value:r.prompt,onChange:K=>a(r.id,K.target.value),onKeyDown:U,rows:1,className:"flex-1 bg-transparent text-sm text-slate-200 resize-none outline-none leading-7 min-h-[1.75rem] max-h-32",style:{height:"auto",overflow:"hidden"},onInput:K=>{K.target.style.height="auto",K.target.style.height=Math.min(K.target.scrollHeight,128)+"px"}}),e.jsx("button",{"aria-label":"Send","data-testid":"composer-send-btn",onClick:()=>o(r.id),disabled:!J,className:"p-2 rounded-xl transition-all active:scale-90 disabled:opacity-30",style:{color:r.color,background:`${r.color}18`},children:e.jsx(dh,{})})]}),e.jsx("div",{"data-testid":"composer-hint",className:"px-1 text-[10px] font-mono text-slate-500 tracking-wide",children:"Enter to send · Shift+Enter for newline · / for commands · Ctrl+K palette"}),r.isThinking&&r.chatLog.some(K=>K._streaming)&&e.jsx("div",{className:"flex justify-end px-1",children:e.jsxs("button",{type:"button",onClick:()=>{window.api&&window.api.llm&&window.api.llm.cancelStream().catch(()=>{})},className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-mono border border-rose-500/25 text-rose-400 hover:bg-rose-500/10 transition-all",title:"Stop generating",children:[e.jsx("svg",{className:"w-3 h-3",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),"Stop"]})})]})]})});function yh({panes:t,visiblePanes:r,layout:n,activePaneId:s,renderPane:a}){const o=O.useRef(null),[c,l]=O.useState(0);if(O.useEffect(()=>{const h=o.current;if(!h)return;const g=()=>l(h.clientWidth||0);g();const y=new window.ResizeObserver(()=>g());return y.observe(h),()=>y.disconnect()},[]),n==="tabs"){const h=t.find(g=>g.id===s)??t[0];return h?e.jsx("div",{className:"h-full min-h-0 p-2",children:a(h,!1)}):null}const x={"split-2":2,"split-3":3,"split-4":4}[n]??r.length,p=r.slice(0,x),d=x>=3,m={"split-2":2,"split-3":3,"split-4":2,"split-6":2,"split-9":3,grid:p.length<=2||p.length<=4?2:3}[n]??2,f=d?260:320,b=c>0?Math.max(1,Math.min(m,p.length||1,Math.floor(c/f))):1;return e.jsxs("div",{ref:o,className:"grid gap-2 h-full min-h-0 p-2",style:{gridTemplateColumns:`repeat(${b}, minmax(0, 1fr))`,gridAutoRows:"minmax(0, 1fr)"},children:[p.map(h=>e.jsx("div",{className:`min-h-0 h-full rounded-xl transition-shadow ${h.id===s?"ring-1 ring-violet-400/25 shadow-[inset_0_0_0_1px_rgba(139,92,246,0.12)]":""}`,children:a(h,d)},h.id)),p.lengthe.jsx("div",{className:"rounded-xl border border-dashed border-white/[0.08] flex items-center justify-center text-slate-500 text-[11px] min-h-32",children:"+ Add pane"},`empty-${g}`))]})}function wh({onAdd:t,onClose:r}){const[n,s]=O.useState(""),[a,o]=O.useState(""),[c,l]=O.useState(""),[u,x]=O.useState("llama3");return e.jsxs("div",{className:"absolute top-full left-0 mt-1.5 z-50 w-72 rounded-xl border border-white/[0.1] bg-shell-overlay/98 backdrop-blur-xl shadow-[0_20px_50px_rgba(0,0,0,0.8)] p-4 space-y-3",children:[e.jsx("div",{className:"text-[11px] font-semibold text-slate-300",children:"New Chat Pane"}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[12px] text-slate-400 mb-1 block",children:"Label"}),e.jsx("input",{value:n,onChange:p=>s(p.target.value),className:"w-full bg-white/[0.05] border border-white/[0.08] rounded-lg px-2.5 py-1.5 text-[11px] text-slate-200 outline-none focus:border-violet-500/40"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[12px] text-slate-400 mb-1 block",children:"Agent Mode"}),e.jsx("select",{value:a,onChange:p=>o(p.target.value),className:"w-full bg-white/[0.05] border border-white/[0.08] rounded-lg px-2.5 py-1.5 text-[11px] text-slate-300 outline-none focus:border-violet-500/40 appearance-none",children:Ps.map(p=>e.jsx("option",{value:p.id??"",children:p.label},p.id??""))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[12px] text-slate-400 mb-1 block",children:"Project / Workspace"}),e.jsx("input",{value:c,onChange:p=>l(p.target.value),className:"w-full bg-white/[0.05] border border-white/[0.08] rounded-lg px-2.5 py-1.5 text-[11px] text-slate-200 outline-none focus:border-violet-500/40"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[12px] text-slate-400 mb-1 block",children:"Model"}),e.jsx("select",{value:u,onChange:p=>x(p.target.value),className:"w-full bg-white/[0.05] border border-white/[0.08] rounded-lg px-2.5 py-1.5 text-[11px] text-slate-300 outline-none focus:border-violet-500/40 appearance-none",children:["llama3","llama3.2","mistral","phi4","gemma3:12b","gpt-4.1","gpt-4o","gpt-4o-mini","o4-mini","claude-opus-4-5","claude-sonnet-4-5","claude-3-7-sonnet-latest","claude-3-5-haiku-latest","gemini-2.5-pro","gemini-2.5-flash","gemini-2.0-flash","deepseek-chat","deepseek-reasoner","mistral-large-latest","codestral-latest","llama-3.3-70b-versatile"].map(p=>e.jsx("option",{value:p,children:p},p))})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx("button",{type:"button","data-testid":"workspace-create-pane-btn",onClick:()=>t({label:n||void 0,agentMode:a||null,project:c||null,model:u}),className:"flex-1 py-1.5 rounded-lg bg-violet-500/20 text-violet-300 text-[11px] font-semibold hover:bg-violet-500/30 transition-all",children:"+ Create Pane"}),e.jsx("button",{type:"button",onClick:r,className:"px-3 py-1.5 rounded-lg text-slate-500 hover:text-slate-300 text-[11px] transition-all",children:"Cancel"})]})]})}const vh=i.memo(function({onSendMessage:r,preferAppSend:n=!1,collab:s=null,sessionKey:a="default",panels:o,onCreateSession:c,onOpenNewWindow:l,onOpenTaskManager:u,onToggleWorkpad:x,workpadOpen:p=!1,className:d="",moodEngine:m=null,rgbEnabled:f=!1,rgbStatus:b=null,activeModel:h="llama3",onModelChange:g}){const y=vb({onSendMessage:r,preferAppSend:n,sessionKey:a}),[I,A]=i.useState(0),[C,w]=i.useState(0),[j,E]=O.useState(!1),[N,_]=O.useState(null),S=O.useRef(null),R=O.useRef(null),$=O.useRef(0),U=O.useRef(y.addPane),P=O.useRef(y.removePane),D=O.useRef(y.activePaneId),z=O.useRef(y.panes.length),F=O.useRef(a);O.useEffect(()=>{U.current=y.addPane},[y.addPane]),O.useEffect(()=>{P.current=y.removePane},[y.removePane]),O.useEffect(()=>{D.current=y.activePaneId},[y.activePaneId]),O.useEffect(()=>{z.current=y.panes.length},[y.panes.length]),O.useEffect(()=>{const W=String(h||"").trim();if(!W||!y.activePaneId)return;const Z=y.panes.find(ce=>ce.id===y.activePaneId);Z&&String(Z.model||"")!==W&&y.updatePane(y.activePaneId,{model:W})},[h,y.activePaneId,y.panes,y.updatePane]),i.useEffect(()=>{let W=!0;const Z=async()=>{if(window.api&&window.api.tasks&&typeof window.api.tasks.list=="function")try{const fe=await window.api.tasks.list(),me=Number(fe&&fe.summary&&fe.summary.operations);W&&A(Number.isFinite(me)?me:0)}catch{W&&A(0)}};Z();const ce=window.setInterval(Z,3e3);return()=>{W=!1,window.clearInterval(ce)}},[]),i.useEffect(()=>{const W=String(a||"global"),Z=()=>w(Xl(et(W)));return Z(),qa(()=>Z(),W)},[a]),i.useEffect(()=>{const W=Z=>{const ce=Z&&Z.detail?String(Z.detail.text||"").trim():"";if(!ce)return;const fe=D.current;!fe||typeof y.setPrompt!="function"||(y.setPrompt(fe,ce),window.dispatchEvent(new CustomEvent("neuralshell:focus-composer")))};return window.addEventListener("neuralshell:workpad-insert",W),()=>window.removeEventListener("neuralshell:workpad-insert",W)},[y.setPrompt]),O.useEffect(()=>{const W=R.current;if(!W||!(s&&typeof s.publish=="function"))return;const Z=ce=>{const fe=Date.now();fe-$.current<80||($.current=fe,s.publish("cursor",{x:Number(ce.clientX||0),y:Number(ce.clientY||0)}))};return W.addEventListener("mousemove",Z),()=>{W.removeEventListener("mousemove",Z)}},[s]),O.useEffect(()=>{F.current!==a&&(F.current=a,y.loadSession(a,{workflowId:a||"default"}))},[a,y]),O.useEffect(()=>{const W=Z=>{var me;const ce=Z&&Z.detail&&typeof Z.detail=="object"?Z.detail:{},fe=String(ce.action||"");if(fe==="multi-model-split"){y.panes.length<2&&y.addPane({label:"Compare",model:((me=y.activePane)==null?void 0:me.model)||"llama3",workflowId:a}),y.setLayout("split-2");return}if(fe==="set-project"){const ke=String(ce.project||"").trim();if(!ke||!y.activePaneId)return;y.updatePane(y.activePaneId,{project:ke})}};return window.addEventListener("neuralshell:workspace-panel-action",W),()=>window.removeEventListener("neuralshell:workspace-panel-action",W)},[y,a]),O.useEffect(()=>{if(!j)return;const W=Z=>{S.current&&!S.current.contains(Z.target)&&E(!1)};return document.addEventListener("pointerdown",W),()=>document.removeEventListener("pointerdown",W)},[j]),O.useEffect(()=>{if(!N)return;const W=()=>_(null);return window.addEventListener("mousedown",W),window.addEventListener("blur",W),()=>{window.removeEventListener("mousedown",W),window.removeEventListener("blur",W)}},[N]),O.useEffect(()=>{const W=Z=>{Z.ctrlKey&&Z.key==="t"&&(Z.preventDefault(),U.current()),Z.ctrlKey&&Z.key==="w"&&(Z.preventDefault(),z.current>1&&P.current(D.current)),Z.ctrlKey&&Z.key==="p"&&o&&typeof o.open=="function"&&(Z.preventDefault(),o.open("projects-mode"))};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[o]);const J=O.useCallback(W=>{y.addPane(W),E(!1)},[y]),ee=O.useCallback(W=>{W.target.closest("button, input, textarea")||(W.preventDefault(),_({x:W.clientX,y:W.clientY}))},[]),ie=O.useCallback(async W=>{if(_(null),W==="new-chat"){typeof c=="function"?c():J();return}W==="new-window"&&typeof l=="function"&&await l()},[J,c,l]),ye=O.useCallback(()=>E(!1),[]),pe={"split-2":2,"split-3":3,"split-4":4},K=y.layout==="tabs"?y.panes:y.panes.slice(0,pe[y.layout]??y.panes.length),H=O.useCallback((W,Z)=>e.jsx(gh,{pane:W,compact:Z,isActive:W.id===y.activePaneId,onPromptChange:y.setPrompt,onSend:y.sendMessage,onClear:y.clearChat,onRename:y.renamePane,onUpdatePane:y.updatePane,onModelChange:g,panels:o,moodEngine:m,rgbEnabled:f,rgbStatus:b,activeTaskCount:I,onOpenTaskManager:u,onToggleWorkpad:x,workpadOpen:p,workpadOpenCount:C},W.id),[y,g,o,m,f,b,I,C,p,u,x]);return e.jsxs("div",{ref:R,"data-testid":"workspace-panel",className:`flex flex-col h-full min-h-0 bg-shell-canvas ${d}`,children:[e.jsxs("div",{className:"flex items-center gap-0 border-b border-white/[0.06] bg-shell-canvas/80 px-2 shrink-0 overflow-x-auto scrollbar-none",children:[e.jsxs("div",{className:"flex items-end gap-0.5 py-1.5 min-w-0 flex-1 overflow-x-auto scrollbar-none",children:[y.panes.map(W=>{const Z=W.id===y.activePaneId;return e.jsxs("div",{onClick:()=>y.setActivePaneId(W.id),className:`group flex items-center gap-1.5 px-3.5 py-2 rounded-t-lg cursor-pointer select-none shrink-0 transition-all border-b-2 ${Z?"border-opacity-100":"bg-transparent border-transparent hover:bg-white/[0.03] border-transparent"}`,style:{borderBottomColor:Z?W.color:"transparent",backgroundColor:Z?`${W.color}12`:void 0,boxShadow:Z?`inset 0 -1px 0 ${W.color}60`:void 0},children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0 transition-all",style:{backgroundColor:W.color,boxShadow:Z?`0 0 8px ${W.color}, 0 0 3px ${W.color}`:"none",opacity:Z?1:.4}}),e.jsx("span",{className:`text-[12px] font-medium transition-colors max-w-32 truncate ${Z?"text-slate-100":"text-slate-500 group-hover:text-slate-400"}`,children:W.label}),W.agentMode&&e.jsx("span",{className:"text-[11px] px-1.5 rounded bg-amber-500/15 text-amber-400/70 shrink-0",children:"agent"}),W.isThinking&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-violet-400 animate-pulse shrink-0"}),W.chatLog.length>0&&e.jsx("span",{className:`text-[11px] font-mono px-1.5 rounded-full shrink-0 ${Z?"bg-white/10 text-slate-400":"text-slate-600"}`,children:W.chatLog.length}),y.panes.length>1&&e.jsx("button",{type:"button","aria-label":"Close workspace pane",title:"Close pane",onClick:ce=>{ce.stopPropagation(),y.removePane(W.id)},className:"ml-0.5 p-0.5 rounded opacity-0 group-hover:opacity-100 text-slate-500 hover:text-rose-400 hover:bg-rose-500/10 transition-all active:scale-90",children:e.jsx(oh,{})})]},W.id)}),e.jsxs("div",{className:"relative shrink-0",ref:S,children:[e.jsxs("button",{type:"button","data-testid":"workspace-add-pane-btn",onClick:()=>E(W=>!W),className:"flex items-center gap-1.5 px-2.5 py-2 rounded-lg text-slate-500 hover:text-violet-300 hover:bg-violet-500/10 transition-all active:scale-95 ml-1",title:`New chat pane (Ctrl+T) • max ${lr}`,disabled:y.panes.length>=lr,"aria-disabled":y.panes.length>=lr,style:y.panes.length>=lr?{opacity:.45,cursor:"not-allowed"}:void 0,children:[e.jsx(ah,{}),e.jsx("span",{className:"text-[11px]",children:"New"})]}),j&&e.jsx(wh,{onAdd:J,onClose:ye})]})]}),e.jsx("div",{className:"w-px h-5 bg-white/[0.07] shrink-0 mx-1"}),e.jsx("div",{className:"flex items-center gap-0.5 shrink-0 py-1.5",children:Gl.map(W=>e.jsx("button",{type:"button","aria-label":`Layout: ${_d[W]}`,"aria-pressed":y.layout===W,onClick:()=>y.setLayout(W),title:_d[W],className:`p-1.5 rounded-md transition-all active:scale-90 ${y.layout===W?"text-violet-300 bg-violet-500/15 ring-1 ring-violet-500/25":"text-slate-500 hover:text-slate-300 hover:bg-white/[0.05]"}`,children:xh[W]},W))}),e.jsx("div",{className:"w-px h-5 bg-white/[0.07] shrink-0 mx-1"}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0 py-1.5 pr-1",children:[o&&e.jsxs("button",{type:"button",onClick:()=>o.open("projects-mode"),title:"Projects (Ctrl+P)",className:`flex items-center gap-1 px-2.5 py-1.5 rounded-md text-[12px] transition-all active:scale-95 ${o.isOpen("projects-mode")?"text-sky-300 bg-sky-500/15 ring-1 ring-sky-500/25":"text-slate-400 hover:text-sky-300 hover:bg-sky-500/10"}`,children:[e.jsx(ph,{}),e.jsx("span",{className:"hidden sm:inline",children:"Projects"})]}),o&&e.jsxs("button",{type:"button",onClick:()=>o.open("agent-store"),title:"Agent Marketplace",className:`flex items-center gap-1 px-2.5 py-1.5 rounded-md text-[12px] transition-all active:scale-95 ${o.isOpen("agent-store")?"text-amber-300 bg-amber-500/15 ring-1 ring-amber-500/25":"text-slate-400 hover:text-amber-300 hover:bg-amber-500/10"}`,children:[e.jsx(uh,{}),e.jsx("span",{className:"hidden sm:inline",children:"Agents"})]}),e.jsxs("span",{"data-testid":"workspace-pane-counter",className:"px-2 py-1 rounded-full text-[12px] font-mono bg-white/[0.05] text-slate-500",title:`Ctrl+T new · Ctrl+W close · max ${lr}`,children:[y.panes.findIndex(W=>W.id===y.activePaneId)+1,"/",y.panes.length," · max ",lr]})]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",onContextMenu:ee,children:e.jsx(yh,{panes:y.panes,visiblePanes:K,layout:y.layout,activePaneId:y.activePaneId,renderPane:H})}),s&&s.remoteCursors&&Object.keys(s.remoteCursors).length>0&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-[120]",children:Object.entries(s.remoteCursors).map(([W,Z])=>{const ce=Number(Z&&Z.x?Z.x:0),fe=Number(Z&&Z.y?Z.y:0);return!Number.isFinite(ce)||!Number.isFinite(fe)?null:e.jsxs("div",{className:"absolute",style:{transform:`translate(${Math.max(0,ce)}px, ${Math.max(0,fe)}px)`},children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-emerald-300 shadow-[0_0_12px_rgba(16,185,129,0.7)]"}),e.jsx("div",{className:"mt-1 px-1.5 py-0.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[8px] font-mono uppercase tracking-[0.14em] text-emerald-100",children:String(W||"peer").slice(0,10)})]},W)})}),N&&e.jsx("div",{className:"fixed inset-0 z-[115]",onMouseDown:()=>_(null),children:e.jsxs("div",{"data-testid":"desktop-context-menu",className:"absolute w-48 rounded-xl border border-cyan-400/20 bg-slate-950/96 shadow-[0_18px_60px_rgba(0,0,0,0.7)] backdrop-blur-xl p-1.5",style:{left:N.x,top:N.y},onMouseDown:W=>W.stopPropagation(),children:[e.jsx("div",{className:"px-2.5 py-1.5 text-[12px] font-mono uppercase tracking-wide text-cyan-200/75 border-b border-white/[0.06] mb-1",children:"Desktop"}),e.jsxs("button",{type:"button",onClick:()=>{ie("new-window")},className:"w-full flex items-center gap-2 rounded-lg px-2.5 py-2 text-left text-[11px] text-slate-300 hover:bg-cyan-500/10 hover:text-cyan-200 transition-colors group",children:[e.jsx("span",{className:"w-4 flex items-center justify-center text-slate-500 group-hover:text-cyan-400 transition-colors",children:e.jsx(Bx,{size:12})}),e.jsx("span",{children:"Open New Window"})]}),e.jsxs("button",{type:"button",onClick:()=>{ie("new-chat")},className:"w-full flex items-center gap-2 rounded-lg px-2.5 py-2 text-left text-[11px] text-slate-300 hover:bg-violet-500/10 hover:text-violet-200 transition-colors group",children:[e.jsx("span",{className:"w-4 flex items-center justify-center text-slate-500 group-hover:text-violet-400 transition-colors",children:e.jsx(Fx,{size:12})}),e.jsx("span",{children:"Open New Chat"})]})]})})]})});function jh({children:t,tone:r="default"}){const n=(...a)=>a.filter(Boolean).join(" "),s=r==="cyan"?"border-cyan-400/25 bg-cyan-400/10 text-cyan-200":r==="gold"?"border-amber-300/25 bg-amber-300/10 text-amber-200":r==="warn"?"border-orange-400/25 bg-orange-400/10 text-orange-200":r==="green"?"border-emerald-400/25 bg-emerald-400/10 text-emerald-200":"border-white/10 bg-white/[0.035] text-slate-300";return e.jsx("span",{className:n("inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em]",s),children:t})}function Ii({label:t,count:r,tone:n="neutral",testId:s}){const a=Math.max(0,Number(r||0)),o=n==="added"?"border-emerald-300/35 bg-emerald-500/12 text-emerald-200":n==="modified"?"border-amber-300/35 bg-amber-500/12 text-amber-200":n==="deleted"?"border-rose-300/35 bg-rose-500/12 text-rose-200":"border-slate-300/20 bg-slate-500/10 text-slate-300";return e.jsxs("div",{"data-testid":s,className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-md border text-[9px] font-mono uppercase tracking-[0.12em] ${o}`,children:[e.jsx("span",{children:t}),e.jsx("span",{children:a})]})}const kh=[{id:"explain",label:"Explain",prefix:"/explain"},{id:"refactor",label:"Refactor",prefix:"/refactor"},{id:"unit-test",label:"UnitTest",prefix:"/unit-test"}];function Nh({visible:t,x:r,y:n,selectionText:s,onPick:a}){if(!t)return null;const o=String(s||"").trim();return o?e.jsx("div",{"data-testid":"context-chip-bar",className:"fixed z-[80] flex items-center gap-1.5 rounded-lg border border-cyan-300/30 bg-slate-950/95 px-2 py-1 shadow-[0_10px_25px_rgba(0,0,0,0.45)]",style:{left:`${Math.max(8,Number(r||0))}px`,top:`${Math.max(8,Number(n||0))}px`},children:kh.map(c=>e.jsx("button",{type:"button","data-testid":`context-chip-${c.id}`,onMouseDown:l=>{l.preventDefault()},onClick:()=>{typeof a=="function"&&a(`${c.prefix} ${o}`)},className:"px-2 py-1 rounded border border-white/10 bg-black/35 text-[9px] font-mono uppercase tracking-[0.12em] text-slate-200 hover:border-cyan-300/30 hover:text-cyan-100 hover:bg-cyan-500/10",children:c.label},c.id))}):null}async function Sh(){if(!(window.api&&window.api.workspace&&typeof window.api.workspace.pickRoot=="function"))throw new Error("Workspace picker is unavailable in this runtime.");const t=await window.api.workspace.pickRoot();if(!t)return null;const r=String(t.path||t.rootPath||"").trim();return r?(window.api.workspace.register&&await window.api.workspace.register(r),window.api.workspace.setActive&&t.id&&await window.api.workspace.setActive(t.id),{path:r,id:t.id}):null}const Ch=["README.md","readme.md","package.json","src/main.js"];async function _h(t=2400){if(!(window.api&&window.api.workspace&&typeof window.api.workspace.getActive=="function"))return null;const r=await window.api.workspace.getActive(),n=String((r==null?void 0:r.path)||(r==null?void 0:r.rootPath)||"").trim();if(!n)return null;if(typeof window.api.workspace.readFile!="function")return{rootPath:n,label:String((r==null?void 0:r.label)||n),content:`// Active workspace: ${n} // Open a file from this folder in your editor to inspect code here.`};for(const s of Ch)try{const a=await window.api.workspace.readFile(n,s,t),o=String((a==null?void 0:a.content)||"").trim();if(o)return{rootPath:n,label:s,content:o}}catch{}return{rootPath:n,label:String((r==null?void 0:r.label)||n),content:`// Workspace loaded: ${n} // No README or package.json preview found.`}}const Ad=["export function verifyReleaseGate(input) {"," if (!input || !input.manifest) {"," throw new Error('manifest required');"," }"," const passed = Boolean(input.signature && input.checksums);"," return { passed, checkedAt: new Date().toISOString() };","}"].join(` -`);function Ah({onInsertCommand:t,onPickWorkspace:r,auditOnly:n=!1}){const s=i.useRef(null),[a,o]=i.useState({visible:!1,x:0,y:0,text:""}),[l,c]=i.useState({label:"Example snippet",content:Ad,hasWorkspace:!1,loading:!0}),u=i.useCallback(async()=>{c(p=>({...p,loading:!0}));try{const p=await _h();if(p&&p.content){c({label:p.label,content:p.content,hasWorkspace:!0,loading:!1});return}}catch{}c({label:"Example snippet",content:Ad,hasWorkspace:!1,loading:!1})},[]);i.useEffect(()=>{var d,m;u();const p=()=>{u()};return(m=(d=window.api)==null?void 0:d.workspace)!=null&&m.onChanged&&window.api.workspace.onChanged(p),()=>{}},[u]),i.useEffect(()=>{const p=()=>{o(d=>({...d,visible:!1}))};return window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),()=>{window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0)}},[]);const x=i.useCallback(()=>{const p=window.getSelection?window.getSelection():null;if(!p||p.rangeCount===0){o(h=>({...h,visible:!1}));return}const d=String(p.toString()||"").trim();if(!d){o(h=>({...h,visible:!1}));return}const m=p.getRangeAt(0),f=m.getBoundingClientRect();if(!f||!f.width&&!f.height){o(h=>({...h,visible:!1}));return}const b=s.current;if(b&&!b.contains(m.commonAncestorContainer)){o(h=>({...h,visible:!1}));return}o({visible:!0,x:f.left+f.width/2-90,y:f.top-38,text:d})},[]);return e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/30 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Workspace Viewer"}),e.jsx("div",{className:"text-[10px] text-slate-400 font-mono",children:l.loading?"Loading preview…":l.hasWorkspace?`${l.label} · select text for context chips`:"Example snippet · open a folder for your code"})]}),!l.hasWorkspace&&typeof r=="function"&&e.jsx("button",{type:"button","data-testid":"workspace-viewer-pick-btn",disabled:n,onClick:r,className:"shrink-0 px-2 py-1 rounded border border-cyan-400/25 bg-cyan-500/10 text-[9px] font-mono uppercase text-cyan-100 hover:bg-cyan-500/20 disabled:opacity-40",children:"Open folder"})]}),e.jsx("pre",{ref:s,"data-testid":"workspace-file-viewer",onMouseUp:x,onKeyUp:x,onBlur:()=>{o(p=>({...p,visible:!1}))},tabIndex:0,className:"m-0 rounded-lg border border-white/10 bg-slate-950/70 p-3 text-[10px] leading-relaxed font-mono text-slate-300 max-h-44 overflow-auto custom-scrollbar whitespace-pre-wrap outline-none focus:border-cyan-300/35",children:l.content}),e.jsx(Nh,{visible:a.visible,x:a.x,y:a.y,selectionText:a.text,onPick:p=>{typeof t=="function"&&t(p),o(d=>({...d,visible:!1}))}})]})}function ms({label:t,ok:r,detail:n,testId:s}){return e.jsxs("div",{"data-testid":s,className:"flex items-start justify-between gap-2 text-[10px] font-mono",children:[e.jsx("span",{className:"text-slate-500 uppercase tracking-wider shrink-0",children:t}),e.jsx("span",{className:`text-right ${r?"text-emerald-300":"text-red-300"}`,children:n})]})}function Eh({report:t,loading:r=!1,error:n="",onRefresh:s,onRunOmega:a}){const o=t&&t.policy?t.policy:{},l=!!(t&&t.audit&&t.audit.ok),c=!!(t&&t.state&&t.state.ok),u=!!(t&&t.registry&&t.registry.ok),x=t&&t.omegaCore&&t.omegaCore.version?t.omegaCore.version:"—";return e.jsxs("section",{"data-testid":"omega-trust-strip",className:"p-4 border border-fuchsia-400/15 bg-gradient-to-br from-fuchsia-500/[0.04] via-slate-950/40 to-cyan-500/[0.03] rounded-2xl shadow-inner relative overflow-hidden",children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-[0.07]",style:{backgroundImage:"repeating-linear-gradient(0deg, #000 0px, #000 1px, transparent 1px, transparent 3px)"}}),e.jsxs("div",{className:"relative z-10 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] font-black uppercase tracking-[0.35em] text-fuchsia-400/70 mb-1",children:"OMEGA Trust Lane"}),e.jsx("div",{className:"text-[11px] font-bold text-slate-100 tracking-tight",children:"@neural/omega-core"}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500 mt-0.5",children:x})]}),e.jsx(kp,{report:t,compact:!0})]}),r&&e.jsx("div",{"data-testid":"omega-trust-loading",className:"text-[10px] font-mono text-cyan-300/80 animate-pulse",children:"Probing kernel posture…"}),n&&!r&&e.jsx("div",{"data-testid":"omega-trust-error",className:"text-[10px] font-mono text-red-300",children:n}),!r&&t&&e.jsxs("div",{className:"space-y-2 pt-1 border-t border-white/5",children:[e.jsx(ms,{testId:"omega-trust-audit",label:"Audit",ok:l,detail:l?`VALID · ${t.audit.count||0}`:"FAIL"}),e.jsx(ms,{testId:"omega-trust-state",label:"State",ok:c,detail:c?String(t.state.format||"omega-v5").toUpperCase():"INVALID"}),e.jsx(ms,{testId:"omega-trust-registry",label:"Registry",ok:u,detail:u?"SIGNED":"FAIL"}),e.jsx(ms,{testId:"omega-trust-policy",label:"Policy",ok:!!o.offlineMode,detail:o.policyLabel||"UNKNOWN"}),e.jsx(ms,{testId:"omega-trust-release",label:"Release",ok:t.releaseHealth&&t.releaseHealth.status!=="red",detail:String(t.releaseHealth&&t.releaseHealth.status?t.releaseHealth.status:"unknown").toUpperCase()})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[typeof a=="function"&&e.jsx("button",{type:"button","data-testid":"omega-trust-run-btn",onClick:a,className:"flex-1 px-2 py-1.5 rounded-lg border border-amber-400/25 bg-amber-500/10 text-[9px] font-bold uppercase tracking-wider text-amber-100 hover:bg-amber-500/20 transition-colors",children:"/omega"}),typeof s=="function"&&e.jsx("button",{type:"button","data-testid":"omega-trust-refresh-btn",onClick:s,className:"px-2 py-1.5 rounded-lg border border-white/10 bg-white/[0.03] text-[9px] font-bold uppercase tracking-wider text-slate-300 hover:bg-white/[0.06] transition-colors",title:"Refresh OMEGA posture",children:"Refresh"})]})]})]})}function Kp({stats:t,workflowId:r,onExecute:n,onInsertPrompt:s,auditOnly:a,widthPx:o=288,connectionInfo:l,omegaReport:c=null,omegaLoading:u=!1,omegaError:x="",onRefreshOmega:p}){const[d,m]=i.useState(null),[f,b]=i.useState(!1),h=Number.isFinite(Number(o))?Math.max(220,Math.round(Number(o))):288;i.useEffect(()=>{var _,S;let w=!0;const j=async()=>{try{if(!(window.api&&window.api.workspace&&typeof window.api.workspace.gitStatus=="function"))return;const R=window.api.workspace.getActive?await window.api.workspace.getActive():null,$=R&&R.path?String(R.path):"",U=await window.api.workspace.gitStatus($);if(!w)return;m(U||null)}catch{if(!w)return;m(null)}};j();const E=window.setInterval(j,2e3),N=()=>{j()};return(S=(_=window.api)==null?void 0:_.workspace)!=null&&S.onChanged&&window.api.workspace.onChanged(N),()=>{w=!1,window.clearInterval(E)}},[]);const g=i.useCallback(w=>{typeof n=="function"&&n(w)},[n]),y=i.useCallback(async()=>{if(!(a||f)){b(!0);try{await Sh()}finally{b(!1)}}},[a,f]),P=i.useCallback(()=>{g("/status")},[g]),A=Number.isFinite(Number(t==null?void 0:t.cpuPercent))?Math.round(Number(t.cpuPercent)):0,C=Number.isFinite(Number(t==null?void 0:t.memoryMb))?Math.round(Number(t.memoryMb)):0;return e.jsxs("aside",{"data-testid":"workbench-rail",className:"shrink-0 border-l border-white/5 flex flex-col bg-slate-950/50 backdrop-blur-xl z-20",style:{width:`${h}px`},children:[e.jsxs("header",{className:"p-6 border-b border-white/5",children:[e.jsx("div",{className:"text-[9px] font-black uppercase tracking-[0.4em] text-cyan-500/60 mb-2",children:"Workspace"}),e.jsx("h2",{className:"text-sm font-bold tracking-tight text-slate-100 uppercase tracking-[0.1em]",children:"Context"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-5 space-y-5 custom-scrollbar",children:[e.jsx(Eh,{report:c,loading:u,error:x,onRefresh:p,onRunOmega:()=>g("/omega")}),e.jsxs("div",{className:"p-5 border border-cyan-400/20 bg-cyan-400/[0.03] rounded-2xl shadow-inner",children:[e.jsxs("div",{className:"flex justify-between items-start mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] font-black uppercase tracking-[0.3em] text-cyan-500/60 mb-1",children:"Active_Workflow"}),e.jsx("div",{className:"text-[12px] font-bold text-slate-200 tracking-tight truncate max-w-40",children:r||"Global_Empty_State"})]}),e.jsx(jh,{tone:r?"green":"warn",children:r?"ON_LINK":"AWAIT"})]}),e.jsxs("div",{className:"space-y-4 pt-4 border-t border-white/5",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-[9px] text-slate-500 font-bold uppercase tracking-widest",children:"Runtime"}),e.jsxs("span",{className:"text-[11px] font-mono text-slate-300",children:["CPU ",A,"% · Memory ",C," MB"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(Ii,{label:"Added",count:d&&d.counts?d.counts.added:0,tone:"added",testId:"git-badge-added"}),e.jsx(Ii,{label:"Modified",count:d&&d.counts?d.counts.modified:0,tone:"modified",testId:"git-badge-modified"}),e.jsx(Ii,{label:"Deleted",count:d&&d.counts?d.counts.deleted:0,tone:"deleted",testId:"git-badge-deleted"})]}),a&&e.jsx("div",{className:"text-[9px] font-mono text-amber-300/80",children:"Auditor mode: read-only workbench actions."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[9px] font-bold uppercase tracking-[0.2em] text-slate-600 mb-3 px-1",children:"Quick Actions"}),e.jsxs("button",{type:"button","data-testid":"workbench-load-repo-btn",disabled:a||f,onClick:y,className:"w-full flex items-center justify-between p-4 rounded-xl border border-white/5 bg-black/40 hover:bg-white/[0.04] text-slate-300 transition-all group disabled:opacity-40 disabled:cursor-not-allowed",children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest group-hover:text-cyan-300 transition-colors",children:f?"Opening folder…":"Open workspace folder"}),e.jsx("span",{className:"text-cyan-500/30 group-hover:text-cyan-400 transition-colors",children:"→"})]}),e.jsxs("button",{type:"button","data-testid":"workbench-bridge-status-btn",onClick:P,className:"w-full flex items-center justify-between p-4 rounded-xl border border-white/5 bg-black/40 hover:bg-white/[0.04] text-slate-300 transition-all group",children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest group-hover:text-amber-300 transition-colors",children:"Run bridge status (/status)"}),e.jsx("span",{className:"text-amber-500/30 group-hover:text-amber-400 transition-colors",children:"→"})]})]}),e.jsx(Ah,{auditOnly:a,onInsertCommand:w=>{if(typeof s=="function"){s(w);return}g(w)},onPickWorkspace:y})]}),e.jsx("footer",{className:"p-5 border-t border-white/5 bg-black/20",children:e.jsxs("div",{className:"flex justify-between items-center gap-3 text-[9px] font-mono text-slate-500",children:[e.jsxs("div",{className:"min-w-0 truncate",children:[e.jsx("span",{className:"text-slate-400",children:"Bridge"})," · ",e.jsx("span",{className:"text-slate-300",children:Ka(l==null?void 0:l.provider)}),(l==null?void 0:l.model)&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-slate-500 truncate",children:l.model})]})]}),e.jsxs("span",{className:`shrink-0 inline-flex items-center gap-1 ${(l==null?void 0:l.health)==="healthy"||(l==null?void 0:l.health)==="online"?"text-emerald-500/90":(l==null?void 0:l.health)==="degraded"?"text-amber-500/90":"text-slate-500"}`,children:[e.jsx("span",{className:`inline-block h-1.5 w-1.5 rounded-full ${(l==null?void 0:l.health)==="healthy"||(l==null?void 0:l.health)==="online"?"bg-emerald-400 shadow-[0_0_6px_rgba(52,211,153,0.6)]":(l==null?void 0:l.health)==="degraded"?"bg-amber-400":"bg-slate-600"}`}),(l==null?void 0:l.health)==="healthy"||(l==null?void 0:l.health)==="online"?"Online":(l==null?void 0:l.health)==="degraded"?"Degraded":"Offline"]})]})})]})}const Ih=i.lazy(()=>Kl(()=>import("./ScratchpadTab-D2yqtgVs.js"),__vite__mapDeps([4,1,2,3]),import.meta.url)),Ph=i.memo(function({moodColors:r,isThinking:n,isTyping:s,particlesEnabled:a,moodEngine:o=null,rgbEnabled:l=!1,rgbStatus:c=null,showInlineThreadRailPanel:u,sessions:x,workflowId:p,onSelectSession:d,onCreateSession:m,onSaveSession:f,onRetrySave:b,onLockSession:h,saveStatus:g,isSessionUnlocked:y,sessionHydrationStatus:P,autoLockOnBlur:A,onToggleAutoLock:C,auditOnly:w,onUpgradeToPro:j,chatLog:E,inlineThreadRailWidth:N,onBeginThreadRailResize:_,onResetThreadRailWidth:S,showThreadRailResizeHint:R,showInlineThreadRail:$,threadRailCollapsed:U,onToggleThreadRailCollapse:I,onSendMessage:D,preferAppSend:z=!1,collab:F=null,panels:J,onOpenNewWindow:ee,onOpenTaskManager:ie,onToggleWorkpad:ye,showInlineWorkbenchRailPanel:pe,onBeginWorkbenchRailResize:K,onResetWorkbenchRailWidth:H,stats:W,onExecute:Z,onInsertPrompt:ce,inlineWorkbenchRailWidth:fe,showInlineWorkbenchRail:me,workbenchRailCollapsed:ke,onToggleWorkbenchRailCollapse:Pe,showScratchpad:_e,onCloseScratchpad:ne,connectionInfo:we,omegaReport:Be=null,omegaLoading:re=!1,omegaError:ae="",onRefreshOmega:M,activeModel:V="llama3",onModelChange:G,visualStyle:te="operator"}){const de=String(te||"")==="frutiger-aero";return e.jsxs("main",{id:"main-workspace",tabIndex:-1,className:"flex-1 flex min-h-0 overflow-hidden relative outline-none",children:[de?null:e.jsx(lb,{moodColors:r,isThinking:n,isTyping:s,particlesEnabled:a}),u&&e.jsx(Sp,{sessions:x,workflowId:p,onSelectSession:d,onCreateSession:m,onSaveSession:f,onRetrySave:b,onLockSession:h,saveStatus:g,isSessionUnlocked:y,sessionHydrationStatus:P,autoLockOnBlur:A,onToggleAutoLock:C,auditOnly:w,onUpgradeToPro:j,chatLog:E,widthPx:N}),u&&e.jsxs("button",{type:"button",role:"separator","aria-label":"Resize workflow rail","aria-orientation":"vertical","data-testid":"thread-rail-resize-handle",onPointerDown:_,onDoubleClick:S,title:"Drag to resize. Double-click to reset.",className:"relative group z-20 w-2 -mx-1 cursor-col-resize touch-none select-none flex items-stretch",children:[e.jsx("span",{className:"mx-auto my-2 w-px bg-white/10 transition-colors group-hover:bg-cyan-400/80"}),R&&e.jsx("span",{role:"status",className:"absolute top-3 left-3 whitespace-nowrap px-2 py-1 rounded-lg border border-cyan-300/30 bg-slate-950/95 text-[11px] font-mono uppercase tracking-[0.1em] text-cyan-100 shadow-[0_6px_24px_rgba(0,0,0,0.5)]",children:"Drag to resize · double-click to reset"})]}),$&&U&&e.jsxs("button",{type:"button","data-testid":"thread-rail-mini-expand-btn",onClick:I,className:"shrink-0 w-12 border-r border-white/10 bg-slate-950/75 hover:bg-slate-900/90 text-cyan-100 transition-colors flex flex-col items-center justify-center gap-1",title:"Expand workflows rail","aria-label":"Expand workflows rail",children:[e.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wide",children:"WF"}),e.jsx("span",{className:"text-[11px] text-slate-400 font-mono uppercase tracking-wide",children:"Open"})]}),e.jsx(vh,{sessionKey:p||"default",onSendMessage:D,preferAppSend:z,collab:F,panels:J,onCreateSession:m,onOpenNewWindow:ee,onOpenTaskManager:ie,onToggleWorkpad:ye,workpadOpen:_e,className:"flex-1",moodEngine:o,rgbEnabled:l,rgbStatus:c,activeModel:V,onModelChange:G}),pe&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",role:"separator","aria-label":"Resize workbench rail","aria-orientation":"vertical","data-testid":"workbench-rail-resize-handle",onPointerDown:K,onDoubleClick:H,title:"Drag to resize. Double-click to reset.",className:"group z-20 w-2 -mx-1 cursor-col-resize touch-none select-none flex items-stretch",children:e.jsx("span",{className:"mx-auto my-2 w-px bg-white/10 transition-colors group-hover:bg-cyan-400/80"})}),e.jsx(Kp,{stats:W,workflowId:p,onExecute:Z,onInsertPrompt:ce,auditOnly:w,widthPx:fe,connectionInfo:we,omegaReport:Be,omegaLoading:re,omegaError:ae,onRefreshOmega:M})]}),me&&ke&&e.jsxs("button",{type:"button","data-testid":"workbench-rail-mini-expand-btn",onClick:Pe,className:"shrink-0 w-12 border-l border-white/10 bg-slate-950/75 hover:bg-slate-900/90 text-cyan-100 transition-colors flex flex-col items-center justify-center gap-1",title:"Expand workbench rail","aria-label":"Expand workbench rail",children:[e.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wide",children:"WB"}),e.jsx("span",{className:"text-[11px] text-slate-400 font-mono uppercase tracking-wide",children:"Open"})]}),e.jsx(i.Suspense,{fallback:null,children:e.jsx(Ih,{open:_e,onClose:ne,workflowId:p})})]})});function Ed(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}Dl()(nf((t,r)=>({threadsBySession:{},activeThreadIdBySession:{},startThread:(n,s,a)=>{const o=String(n||"default"),l=String(s||"").trim(),c=r().threadsBySession[o]||{},u=Object.values(c).find(d=>String(d.messageId||"")===l);if(u)return t(d=>({activeThreadIdBySession:{...d.activeThreadIdBySession,[o]:u.id}})),u.id;const x=Ed(String(s||"msg")),p={id:x,messageId:l,rootContent:String(a||""),createdAt:new Date().toISOString(),replies:[]};return t(d=>({threadsBySession:{...d.threadsBySession,[o]:{...d.threadsBySession[o]||{},[x]:p}},activeThreadIdBySession:{...d.activeThreadIdBySession,[o]:x}})),x},openThread:(n,s)=>{const a=String(n||"default");t(o=>({activeThreadIdBySession:{...o.activeThreadIdBySession,[a]:String(s||"")}}))},closeThread:n=>{const s=String(n||"default");t(a=>({activeThreadIdBySession:{...a.activeThreadIdBySession,[s]:""}}))},addReply:(n,s,a)=>{const o=String(n||"default"),l=String(s||"").trim(),c=String(a||"").trim();if(!l||!c)return!1;const x=(r().threadsBySession[o]||{})[l];if(!x)return!1;const p={id:Ed("reply"),content:c,createdAt:new Date().toISOString()};return t(d=>({threadsBySession:{...d.threadsBySession,[o]:{...d.threadsBySession[o]||{},[l]:{...x,replies:[...x.replies,p]}}}})),!0}}),{name:"neuralshell-thread-store-v1",storage:sf(()=>window.localStorage),partialize:t=>({threadsBySession:t.threadsBySession,activeThreadIdBySession:t.activeThreadIdBySession})}));function oa(t){let r="";for(let n=0;nr.toString(16).padStart(2,"0")).join("")}async function Oh(t){if(!window.crypto||!window.crypto.subtle)throw new Error("WebCrypto is unavailable.");const r=JSON.stringify(t||{}),n=new TextEncoder().encode(r),s=window.crypto.getRandomValues(new Uint8Array(12)),a=window.crypto.getRandomValues(new Uint8Array(32)),o=await window.crypto.subtle.importKey("raw",a,{name:"AES-GCM"},!1,["encrypt"]),l=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:s},o,n),c=new Uint8Array(l),u=new Uint8Array(await window.crypto.subtle.digest("SHA-256",c)),x=Rh(u).slice(0,20),p={v:1,iv:oa(s),c:oa(c),k:oa(a)},d=oa(new TextEncoder().encode(JSON.stringify(p)));return{hash:x,fragment:d,envelope:p}}async function Th(t){if(!t)throw new Error("Missing share fragment.");if(!window.crypto||!window.crypto.subtle)throw new Error("WebCrypto is unavailable.");const r=Aa(t),n=new TextDecoder().decode(r),s=JSON.parse(n);return Vp(s)}async function Vp(t){if(!t||typeof t!="object")throw new Error("Invalid share envelope.");if(Number(t.v)!==1)throw new Error(`Unsupported share envelope version: ${t.v}`);const r=Aa(t.iv),n=Aa(t.c),s=Aa(t.k),a=await window.crypto.subtle.importKey("raw",s,{name:"AES-GCM"},!1,["decrypt"]),o=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:r},a,n),l=new TextDecoder().decode(new Uint8Array(o));return JSON.parse(l)}function Mh(t,r){const n=String(t||"").trim()||"local",s=String(r||"").trim();return`${typeof window<"u"&&window.location.origin&&window.location.origin!=="null"?window.location.origin:"https://neuralshell.app"}/share/${n}${s?`#${s}`:""}`}async function Dh(t){const r=String(t||"").trim();if(!r)throw new Error("Missing share hash.");const n=[`/static/share_blobs/${r}.json`,`/share_blobs/${r}.json`,`./static/share_blobs/${r}.json`];let s=null;for(const a of n)try{const o=await fetch(a,{method:"GET"});if(!o.ok)continue;return await o.json()}catch(o){s=o}throw s||new Error("Share blob not found.")}function $h({src:t,alt:r,className:n="",placeholderClassName:s=""}){const a=i.useRef(null),[o,l]=i.useState(!1),[c,u]=i.useState(!1);return i.useEffect(()=>{const x=a.current;if(!x)return;if(!window.IntersectionObserver){l(!0);return}const p=new window.IntersectionObserver(d=>{d.forEach(m=>{m.isIntersecting&&(l(!0),p.disconnect())})},{rootMargin:"120px 0px 120px 0px",threshold:.01});return p.observe(x),()=>p.disconnect()},[]),e.jsxs("div",{ref:a,className:`relative overflow-hidden ${n}`.trim(),children:[!c&&e.jsx("div",{"data-testid":"lazy-image-placeholder",className:`absolute inset-0 bg-slate-800/60 ${s}`.trim(),children:e.jsx("div",{className:"h-full w-full ns-shimmer"})}),o&&e.jsx("img",{src:t,alt:r,loading:"lazy",decoding:"async",onLoad:()=>u(!0),className:`block h-full w-full object-cover ${c?"opacity-100":"opacity-0"} transition-opacity duration-300`})]})}function Lh(t){const r=Number(t);return Number.isFinite(r)?r:0}function Gp(t){const r=Array.isArray(t)?t.map(s=>Lh(s)).filter(s=>Number.isFinite(s)&&s>=0).sort((s,a)=>s-a):[];if(!r.length)return null;const n=Math.floor(r.length/2);return r.length%2===0?Number(((r[n-1]+r[n])/2).toFixed(1)):Number(r[n].toFixed(1))}function Bh(t){return t==null||t===""||!Number.isFinite(Number(t))||Number(t)<0?"neutral":Number(t)<150?"green":Number(t)<=250?"amber":"red"}const Fh=Object.freeze(Object.defineProperty({__proto__:null,classifyVoiceRtt:Bh,computeMedianRtt:Gp},Symbol.toStringTag,{value:"Module"}));function Uh(t){const r=[];return!t||typeof t.forEach!="function"||t.forEach(n=>{!n||typeof n!="object"||(typeof n.currentRoundTripTime=="number"&&Number.isFinite(n.currentRoundTripTime)?r.push(n.currentRoundTripTime*1e3):typeof n.roundTripTime=="number"&&Number.isFinite(n.roundTripTime)&&r.push(n.roundTripTime*1e3))}),r}function zh(t={}){const r=!!t.enabled,n=Math.max(5e3,Number(t.pollMs||5e3)),s=typeof t.getPeerConnection=="function"?t.getPeerConnection:()=>null,[a,o]=i.useState([]);return i.useEffect(()=>{if(!r){o([]);return}let c=!0,u=null;const x=async()=>{try{const p=s();if(p&&typeof p.getStats=="function"){const d=await p.getStats(),m=Uh(d);c&&m.length&&o(f=>[...f,...m].slice(-30))}}catch{}c&&(u=setTimeout(x,n))};return x(),()=>{c=!1,u&&clearTimeout(u)}},[r,s,n]),{medianRttMs:i.useMemo(()=>Gp(a),[a]),sampleCount:a.length}}const{classifyVoiceRtt:Hh}=Fh;function Wh(t){return t&&t.payload&&typeof t.payload=="object"?t.payload:{}}function Kh({collab:t}){const[r,n]=i.useState(!1),[s,a]=i.useState("idle"),[o,l]=i.useState(""),[c,u]=i.useState(!1),x=i.useRef(null),p=i.useRef(null),d=i.useRef(null),m=zh({enabled:r&&s==="connected",pollMs:5e3,getPeerConnection:()=>d.current}),f=Hh(m.medianRttMs),b=i.useCallback((w,j={})=>{t&&typeof t.publish=="function"&&t.publish("voice-signal",{type:w,toPeerId:String(j.toPeerId||""),fromPeerId:String(t.peerId||""),sdp:j.sdp||null,candidate:j.candidate||null})},[t]),h=window.RTCPeerConnection||window.webkitRTCPeerConnection,g=window.RTCSessionDescription||window.webkitRTCSessionDescription,y=window.RTCIceCandidate||window.webkitRTCIceCandidate,P=i.useCallback(()=>{if(d.current)return d.current;if(!h)throw new Error("WebRTC is unavailable in this runtime.");const w=new h;return w.onicecandidate=j=>{j.candidate&&b("candidate",{toPeerId:o,candidate:j.candidate})},w.ontrack=j=>{x.current&&(x.current.srcObject=j.streams[0])},d.current=w,w},[h,b,o]),A=i.useCallback(()=>{if(d.current&&(d.current.close(),d.current=null),p.current){for(const w of p.current.getTracks())w.stop();p.current=null}x.current&&(x.current.srcObject=null),n(!1),l(""),a("idle")},[]),C=i.useCallback(async()=>{try{const w=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,channelCount:1}});p.current=w;const j=P();for(const E of w.getTracks())E.enabled=!1,j.addTrack(E,w);n(!0),a("waiting"),b("hello",{toPeerId:""})}catch(w){a(`join_failed:${w&&w.message?w.message:String(w)}`)}},[P,b]);return i.useEffect(()=>{if(!r||!p.current)return;(j=>{for(const E of p.current.getAudioTracks())E.enabled=j})(!!c)},[r,c]),i.useEffect(()=>{const w=E=>{E.code==="Space"&&r&&u(!0)},j=E=>{E.code==="Space"&&r&&u(!1)};return window.addEventListener("keydown",w),window.addEventListener("keyup",j),()=>{window.removeEventListener("keydown",w),window.removeEventListener("keyup",j)}},[r]),i.useEffect(()=>{const w=t&&t.lastEvent?t.lastEvent:null;if(!w||w.eventType!=="voice-signal")return;const j=Wh(w),E=String(j.fromPeerId||w.fromPeerId||"");if(!E||E===String(t&&t.peerId||""))return;const N=String(j.toPeerId||"");if(N&&N!==String(t&&t.peerId||""))return;const _=String(j.type||"");(async()=>{try{const R=P();if(_==="hello"){if(!r)return;if(l(E),String(t&&t.peerId||"")()=>A(),[A]),e.jsxs("section",{"data-testid":"voice-panel",className:"rounded-xl border border-white/10 bg-black/30 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.14em] font-bold text-fuchsia-300",children:"Voice Room"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"DTLS-SRTP via WebRTC · Push-to-talk Space"})]}),e.jsx("div",{"data-testid":"voice-rtt-badge",className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${f==="green"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-200":f==="amber"?"border-amber-300/40 bg-amber-500/10 text-amber-200":f==="red"?"border-rose-300/40 bg-rose-500/10 text-rose-200":"border-slate-300/20 bg-slate-500/10 text-slate-300"}`,title:"Median voice round-trip time, refreshed every 5 seconds.",children:Number.isFinite(Number(m.medianRttMs))?`RTT ${Math.round(Number(m.medianRttMs))}ms`:"RTT --"}),e.jsx("button",{type:"button","data-testid":"voice-toggle-btn",onClick:()=>r?A():C(),className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${r?"border-rose-300/30 bg-rose-500/10 text-rose-200":"border-fuchsia-300/30 bg-fuchsia-500/10 text-fuchsia-200"}`,children:r?"Leave":"Join"})]}),e.jsx("div",{className:"text-[10px] font-mono text-slate-300",children:r?`Status: ${s} · remote=${o||"none"} · PTT=${c?"on":"off"}`:"Voice idle."}),e.jsx("audio",{ref:x,autoPlay:!0,playsInline:!0})]})}const Jp="neuralshell_omega_boot_session_v1",Vh="neuralshell_omega_boot_suppressed_v1";function Gh(){return typeof window>"u"?!1:!!(window.localStorage&&window.localStorage.getItem(Vh)==="1"||window.sessionStorage&&window.sessionStorage.getItem(Jp)==="1")}function Jh({report:t,onComplete:r}){const[n,s]=i.useState(()=>!Gh()),[a,o]=i.useState([]),[l,c]=i.useState(0);return i.useEffect(()=>{if(!n)return;typeof window<"u"&&window.sessionStorage&&window.sessionStorage.setItem(Jp,"1");const u=Array.isArray(t&&t.bootSequence)?t.bootSequence:[{phase:"BOOT",text:"Initializing OMEGA-Kernel…",delayMs:0},{phase:"READY",text:"ProofForge online",delayMs:1800}],x=[];u.forEach((d,m)=>{x.push(window.setTimeout(()=>{o(f=>[...f,d]),c(Math.round((m+1)/u.length*100))},Number(d.delayMs)||0))});const p=Math.max(...u.map(d=>Number(d.delayMs)||0),0)+900;return x.push(window.setTimeout(()=>{s(!1),typeof r=="function"&&r()},p)),()=>{x.forEach(d=>window.clearTimeout(d))}},[n,t,r]),n?e.jsxs("div",{"data-testid":"omega-boot-overlay",className:"fixed inset-0 z-[12000] flex items-center justify-center bg-[#020812]/96 backdrop-blur-sm",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.12] pointer-events-none",style:{backgroundImage:"repeating-linear-gradient(0deg, #000 0px, #000 1px, transparent 1px, transparent 4px)"}}),e.jsxs("div",{className:"relative w-full max-w-2xl mx-6 rounded-2xl border border-cyan-400/20 bg-slate-950/90 shadow-[0_0_60px_rgba(34,211,238,0.08)] overflow-hidden",children:[e.jsxs("div",{className:"px-5 py-3 border-b border-white/10 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-mono uppercase tracking-[0.25em] text-slate-400",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-red-500 animate-pulse"}),"REC · OMEGA BOOT"]}),e.jsx("button",{type:"button","data-testid":"omega-boot-skip-btn",onClick:()=>{s(!1),typeof r=="function"&&r()},className:"text-[10px] font-mono uppercase tracking-wider text-slate-500 hover:text-cyan-300 transition-colors",children:"Skip"})]}),e.jsxs("div",{className:"p-6 font-mono text-[12px] leading-relaxed min-h-[220px]",children:[a.map((u,x)=>e.jsxs("div",{"data-testid":`omega-boot-line-${String(u.phase||x).toLowerCase()}`,className:`mb-1.5 ${u.ok===!1?"text-red-300":u.ok===!0?"text-emerald-300":"text-cyan-100/90"}`,children:[e.jsxs("span",{className:"text-fuchsia-400/80",children:["[",u.phase,"]"]})," ",u.text]},`${u.phase}-${x}`)),e.jsx("div",{className:"mt-4 text-cyan-300/70 animate-pulse",children:"▮"})]}),e.jsxs("div",{className:"px-6 pb-5",children:[e.jsx("div",{className:"h-1.5 rounded-full bg-white/5 overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-violet-500 via-cyan-400 to-fuchsia-500 transition-all duration-300",style:{width:`${l}%`}})}),e.jsx("div",{className:"mt-2 text-[9px] font-mono text-slate-500 uppercase tracking-[0.3em]",children:"PF // VHS-01 · OMEGA-Kernel sequence · Created by The Founder"})]})]})]}):null}const qh=[{left:"8%",size:48,delay:0,duration:14},{left:"22%",size:28,delay:2,duration:11},{left:"38%",size:64,delay:1,duration:16},{left:"55%",size:36,delay:3,duration:12},{left:"72%",size:52,delay:.5,duration:15},{left:"86%",size:24,delay:4,duration:10},{left:"91%",size:40,delay:1.5,duration:13}],Yh=i.memo(function(){return e.jsxs("div",{"aria-hidden":!0,className:"aero-backdrop pointer-events-none absolute inset-0 overflow-hidden z-0",children:[e.jsx("div",{className:"aero-sky absolute inset-0"}),e.jsx("div",{className:"aero-sun absolute top-[8%] right-[12%] w-28 h-28 rounded-full"}),e.jsx("div",{className:"aero-cloud aero-cloud-1"}),e.jsx("div",{className:"aero-cloud aero-cloud-2"}),e.jsx("div",{className:"aero-grass absolute inset-x-0 bottom-0 h-[28%]"}),e.jsx("div",{className:"aero-water-shimmer absolute inset-x-0 bottom-[18%] h-24"}),qh.map((r,n)=>e.jsx("span",{className:"aero-bubble absolute rounded-full",style:{left:r.left,width:r.size,height:r.size,animationDelay:`${r.delay}s`,animationDuration:`${r.duration}s`,bottom:`${12+n%4*8}%`}},`aero-bubble-${n}`)),e.jsx("div",{className:"aero-lens-flare absolute top-[18%] left-[32%] w-64 h-32 rotate-12"})]})}),Zh=40;function As(t){return String(t||"").trim().toLowerCase()}function Xh(t){return As(t).split(/\s+/).map(r=>r.trim()).filter(Boolean)}function Qh(t,r){return r.length?r.every(n=>t.includes(n)):!0}function Es(t){const r=Array.isArray(t)?t:t&&Array.isArray(t.entries)?t.entries:[],n=new Map;for(const s of r){const a=s&&typeof s=="object",o=String(a?s.key:s||"").trim();if(!o)continue;const l=n.get(o),c=Math.max(1,Number(a?s.count:1)||1),u=Math.max(0,Number(a?s.lastUsedAt:0)||0);n.set(o,{key:o,count:l?Math.max(l.count,c):c,lastUsedAt:l?Math.max(l.lastUsedAt,u):u})}return Array.from(n.values()).sort((s,a)=>a.lastUsedAt!==s.lastUsedAt?a.lastUsedAt-s.lastUsedAt:a.count!==s.count?a.count-s.count:s.key.localeCompare(a.key)).slice(0,Zh)}function eg(t,r,n=Date.now()){const s=String(r||"").trim();if(!s)return Es(t);const a=Es(t),o=a.find(c=>c.key===s),l=[{key:s,count:o?o.count+1:1,lastUsedAt:Math.max(0,Number(n)||Date.now())},...a.filter(c=>c.key!==s)];return Es(l)}function tg(t={}){const r=String(t&&t.workflowId||"").trim(),n=Array.isArray(t&&t.sessions)?t.sessions:[],s=Array.isArray(t&&t.chatLog)?t.chatLog:[],a=String(t&&t.sessionHydrationStatus||"").trim(),o=new Set(["global","system"]);return r&&o.add("workflow"),n.length&&o.add("session"),s.length&&o.add("chat"),a==="locked"&&o.add("locked-session"),r&&a!=="locked"&&o.add("active-workflow"),{workflowId:r,hasWorkflow:!!r,hasSessions:n.length>0,hasChat:s.length>0,sessionHydrationStatus:a,contexts:Array.from(o)}}function rg(t,r={}){const n=Array.isArray(t&&t.contexts)?t.contexts.map(a=>String(a||"").trim()).filter(Boolean):[];if(!n.length)return!0;const s=new Set(Array.isArray(r&&r.contexts)?r.contexts.map(a=>String(a||"").trim()).filter(Boolean):["global"]);return n.some(a=>s.has(a))}function ng(t,r,n,s){const a=As(t&&t.label),o=As(t&&t.id),l=As(t&&t.keywords),c=`${a} ${o} ${l}`.trim();if(!c||!Qh(c,n))return Number.NEGATIVE_INFINITY;let u=Number(t&&t.contextWeight)||0;const x=String(t&&t.kind||"command");if(!r)u+=x==="command"?12:6;else{c.startsWith(r)&&(u+=150),a.startsWith(r)&&(u+=120),o.startsWith(r)&&(u+=80),a.includes(r)&&(u+=50),o.includes(r)&&(u+=30);for(const p of n)a.startsWith(p)?u+=20:a.includes(p)&&(u+=10),o.startsWith(p)?u+=12:o.includes(p)&&(u+=6),l.includes(p)&&(u+=4)}if(r.startsWith("/")&&x==="command"&&(u+=35),x==="session"&&n.some(p=>p==="session"||p==="workflow"||p==="thread")&&(u+=22),s){const p=Math.max(0,Number(s.rank)||0),d=Math.max(1,Number(s.count)||1);u+=Math.max(0,110-p*5),u+=Math.min(35,d*5)}return x==="session"&&t.active&&(u+=12),x==="session"&&t.locked&&(u-=4),u}function sg({resultCount:t,selectedLabel:r,query:n}){const s=Math.max(0,Number(t)||0),a=n?`${s} result${s===1?"":"s"} for ${String(n).trim()}`:`${s} palette result${s===1?"":"s"}`;return r?`${a}. Selected ${r}.`:`${a}.`}const Ea=[];function Nt(t){if(!t.id||!t.slot)throw new Error(`Module registration requires id and slot: ${JSON.stringify(t)}`);const r=Ea.findIndex(n=>n.id===t.id);r>=0?Ea[r]={priority:100,stability:"trusted",visible:()=>!0,...t}:Ea.push({priority:100,stability:"trusted",visible:()=>!0,...t})}function Id(t,r={}){const{includeExperimental:n=!1,context:s={}}=r;return Ea.filter(a=>a.slot===t).filter(a=>n||a.stability!=="experimental").filter(a=>rg(a,s)).filter(a=>a.visible(s)).sort((a,o)=>a.priority-o.priority)}function ag(t={}){return[...Id("palette.commands",t),...Id("palette.system",t)]}Nt({id:"cmd-purge",slot:"palette.commands",title:"Purge Workflow History",priority:30,stability:"core",contexts:["session","chat"],contextLabel:"Workflow",visible:t=>!!(t&&(t.hasSessions||t.hasChat)),action:()=>{window.api&&window.api.ritual&&window.api.ritual.execute("purge")}});Nt({id:"cmd-clear",slot:"palette.system",title:"Clear History",priority:10,stability:"core",contexts:["chat"],contextLabel:"Current chat",visible:t=>!!(t&&t.hasChat),action:t=>{t&&typeof t.setChatLog=="function"&&t.setChatLog([])}});Nt({id:"cmd-status",slot:"palette.system",title:"Show System Status",priority:20,stability:"core",contexts:["system"],contextLabel:"System",action:t=>{t&&typeof t.appendChat=="function"&&t.appendChat({role:"assistant",content:`Node Status: OPERATIONAL +`);function Ah({onInsertCommand:t,onPickWorkspace:r,auditOnly:n=!1}){const s=i.useRef(null),[a,o]=i.useState({visible:!1,x:0,y:0,text:""}),[c,l]=i.useState({label:"Example snippet",content:Ad,hasWorkspace:!1,loading:!0}),u=i.useCallback(async()=>{l(p=>({...p,loading:!0}));try{const p=await _h();if(p&&p.content){l({label:p.label,content:p.content,hasWorkspace:!0,loading:!1});return}}catch{}l({label:"Example snippet",content:Ad,hasWorkspace:!1,loading:!1})},[]);i.useEffect(()=>{var d,m;u();const p=()=>{u()};return(m=(d=window.api)==null?void 0:d.workspace)!=null&&m.onChanged&&window.api.workspace.onChanged(p),()=>{}},[u]),i.useEffect(()=>{const p=()=>{o(d=>({...d,visible:!1}))};return window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),()=>{window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0)}},[]);const x=i.useCallback(()=>{const p=window.getSelection?window.getSelection():null;if(!p||p.rangeCount===0){o(h=>({...h,visible:!1}));return}const d=String(p.toString()||"").trim();if(!d){o(h=>({...h,visible:!1}));return}const m=p.getRangeAt(0),f=m.getBoundingClientRect();if(!f||!f.width&&!f.height){o(h=>({...h,visible:!1}));return}const b=s.current;if(b&&!b.contains(m.commonAncestorContainer)){o(h=>({...h,visible:!1}));return}o({visible:!0,x:f.left+f.width/2-90,y:f.top-38,text:d})},[]);return e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/30 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Workspace Viewer"}),e.jsx("div",{className:"text-[10px] text-slate-400 font-mono",children:c.loading?"Loading preview…":c.hasWorkspace?`${c.label} · select text for context chips`:"Example snippet · open a folder for your code"})]}),!c.hasWorkspace&&typeof r=="function"&&e.jsx("button",{type:"button","data-testid":"workspace-viewer-pick-btn",disabled:n,onClick:r,className:"shrink-0 px-2 py-1 rounded border border-cyan-400/25 bg-cyan-500/10 text-[9px] font-mono uppercase text-cyan-100 hover:bg-cyan-500/20 disabled:opacity-40",children:"Open folder"})]}),e.jsx("pre",{ref:s,"data-testid":"workspace-file-viewer",onMouseUp:x,onKeyUp:x,onBlur:()=>{o(p=>({...p,visible:!1}))},tabIndex:0,className:"m-0 rounded-lg border border-white/10 bg-slate-950/70 p-3 text-[10px] leading-relaxed font-mono text-slate-300 max-h-44 overflow-auto custom-scrollbar whitespace-pre-wrap outline-none focus:border-cyan-300/35",children:c.content}),e.jsx(Nh,{visible:a.visible,x:a.x,y:a.y,selectionText:a.text,onPick:p=>{typeof t=="function"&&t(p),o(d=>({...d,visible:!1}))}})]})}function xs({label:t,ok:r,detail:n,testId:s}){return e.jsxs("div",{"data-testid":s,className:"flex items-start justify-between gap-2 text-[10px] font-mono",children:[e.jsx("span",{className:"text-slate-500 uppercase tracking-wider shrink-0",children:t}),e.jsx("span",{className:`text-right ${r?"text-emerald-300":"text-red-300"}`,children:n})]})}function Eh({report:t,loading:r=!1,error:n="",onRefresh:s,onRunOmega:a}){const o=t&&t.policy?t.policy:{},c=!!(t&&t.audit&&t.audit.ok),l=!!(t&&t.state&&t.state.ok),u=!!(t&&t.registry&&t.registry.ok),x=t&&t.omegaCore&&t.omegaCore.version?t.omegaCore.version:"—";return e.jsxs("section",{"data-testid":"omega-trust-strip",className:"p-4 border border-fuchsia-400/15 bg-gradient-to-br from-fuchsia-500/[0.04] via-slate-950/40 to-cyan-500/[0.03] rounded-2xl shadow-inner relative overflow-hidden",children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-[0.07]",style:{backgroundImage:"repeating-linear-gradient(0deg, #000 0px, #000 1px, transparent 1px, transparent 3px)"}}),e.jsxs("div",{className:"relative z-10 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] font-black uppercase tracking-[0.35em] text-fuchsia-400/70 mb-1",children:"OMEGA Trust Lane"}),e.jsx("div",{className:"text-[11px] font-bold text-slate-100 tracking-tight",children:"@neural/omega-core"}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500 mt-0.5",children:x})]}),e.jsx(kp,{report:t,compact:!0})]}),r&&e.jsx("div",{"data-testid":"omega-trust-loading",className:"text-[10px] font-mono text-cyan-300/80 animate-pulse",children:"Probing kernel posture…"}),n&&!r&&e.jsx("div",{"data-testid":"omega-trust-error",className:"text-[10px] font-mono text-red-300",children:n}),!r&&t&&e.jsxs("div",{className:"space-y-2 pt-1 border-t border-white/5",children:[e.jsx(xs,{testId:"omega-trust-audit",label:"Audit",ok:c,detail:c?`VALID · ${t.audit.count||0}`:"FAIL"}),e.jsx(xs,{testId:"omega-trust-state",label:"State",ok:l,detail:l?String(t.state.format||"omega-v5").toUpperCase():"INVALID"}),e.jsx(xs,{testId:"omega-trust-registry",label:"Registry",ok:u,detail:u?"SIGNED":"FAIL"}),e.jsx(xs,{testId:"omega-trust-policy",label:"Policy",ok:!!o.offlineMode,detail:o.policyLabel||"UNKNOWN"}),e.jsx(xs,{testId:"omega-trust-release",label:"Release",ok:t.releaseHealth&&t.releaseHealth.status!=="red",detail:String(t.releaseHealth&&t.releaseHealth.status?t.releaseHealth.status:"unknown").toUpperCase()})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[typeof a=="function"&&e.jsx("button",{type:"button","data-testid":"omega-trust-run-btn",onClick:a,className:"flex-1 px-2 py-1.5 rounded-lg border border-amber-400/25 bg-amber-500/10 text-[9px] font-bold uppercase tracking-wider text-amber-100 hover:bg-amber-500/20 transition-colors",children:"/omega"}),typeof s=="function"&&e.jsx("button",{type:"button","data-testid":"omega-trust-refresh-btn",onClick:s,className:"px-2 py-1.5 rounded-lg border border-white/10 bg-white/[0.03] text-[9px] font-bold uppercase tracking-wider text-slate-300 hover:bg-white/[0.06] transition-colors",title:"Refresh OMEGA posture",children:"Refresh"})]})]})]})}function Kp({stats:t,workflowId:r,onExecute:n,onInsertPrompt:s,auditOnly:a,widthPx:o=288,connectionInfo:c,omegaReport:l=null,omegaLoading:u=!1,omegaError:x="",onRefreshOmega:p}){const[d,m]=i.useState(null),[f,b]=i.useState(!1),h=Number.isFinite(Number(o))?Math.max(220,Math.round(Number(o))):288;i.useEffect(()=>{var _,S;let w=!0;const j=async()=>{try{if(!(window.api&&window.api.workspace&&typeof window.api.workspace.gitStatus=="function"))return;const R=window.api.workspace.getActive?await window.api.workspace.getActive():null,$=R&&R.path?String(R.path):"",U=await window.api.workspace.gitStatus($);if(!w)return;m(U||null)}catch{if(!w)return;m(null)}};j();const E=window.setInterval(j,2e3),N=()=>{j()};return(S=(_=window.api)==null?void 0:_.workspace)!=null&&S.onChanged&&window.api.workspace.onChanged(N),()=>{w=!1,window.clearInterval(E)}},[]);const g=i.useCallback(w=>{typeof n=="function"&&n(w)},[n]),y=i.useCallback(async()=>{if(!(a||f)){b(!0);try{await Sh()}finally{b(!1)}}},[a,f]),I=i.useCallback(()=>{g("/status")},[g]),A=Number.isFinite(Number(t==null?void 0:t.cpuPercent))?Math.round(Number(t.cpuPercent)):0,C=Number.isFinite(Number(t==null?void 0:t.memoryMb))?Math.round(Number(t.memoryMb)):0;return e.jsxs("aside",{"data-testid":"workbench-rail",className:"shrink-0 border-l border-white/5 flex flex-col bg-slate-950/50 backdrop-blur-xl z-20",style:{width:`${h}px`},children:[e.jsxs("header",{className:"p-6 border-b border-white/5",children:[e.jsx("div",{className:"text-[9px] font-black uppercase tracking-[0.4em] text-cyan-500/60 mb-2",children:"Workspace"}),e.jsx("h2",{className:"text-sm font-bold tracking-tight text-slate-100 uppercase tracking-[0.1em]",children:"Context"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-5 space-y-5 custom-scrollbar",children:[e.jsx(Eh,{report:l,loading:u,error:x,onRefresh:p,onRunOmega:()=>g("/omega")}),e.jsxs("div",{className:"p-5 border border-cyan-400/20 bg-cyan-400/[0.03] rounded-2xl shadow-inner",children:[e.jsxs("div",{className:"flex justify-between items-start mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] font-black uppercase tracking-[0.3em] text-cyan-500/60 mb-1",children:"Active_Workflow"}),e.jsx("div",{className:"text-[12px] font-bold text-slate-200 tracking-tight truncate max-w-40",children:r||"Global_Empty_State"})]}),e.jsx(jh,{tone:r?"green":"warn",children:r?"ON_LINK":"AWAIT"})]}),e.jsxs("div",{className:"space-y-4 pt-4 border-t border-white/5",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-[9px] text-slate-500 font-bold uppercase tracking-widest",children:"Runtime"}),e.jsxs("span",{className:"text-[11px] font-mono text-slate-300",children:["CPU ",A,"% · Memory ",C," MB"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(Ii,{label:"Added",count:d&&d.counts?d.counts.added:0,tone:"added",testId:"git-badge-added"}),e.jsx(Ii,{label:"Modified",count:d&&d.counts?d.counts.modified:0,tone:"modified",testId:"git-badge-modified"}),e.jsx(Ii,{label:"Deleted",count:d&&d.counts?d.counts.deleted:0,tone:"deleted",testId:"git-badge-deleted"})]}),a&&e.jsx("div",{className:"text-[9px] font-mono text-amber-300/80",children:"Auditor mode: read-only workbench actions."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[9px] font-bold uppercase tracking-[0.2em] text-slate-600 mb-3 px-1",children:"Quick Actions"}),e.jsxs("button",{type:"button","data-testid":"workbench-load-repo-btn",disabled:a||f,onClick:y,className:"w-full flex items-center justify-between p-4 rounded-xl border border-white/5 bg-black/40 hover:bg-white/[0.04] text-slate-300 transition-all group disabled:opacity-40 disabled:cursor-not-allowed",children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest group-hover:text-cyan-300 transition-colors",children:f?"Opening folder…":"Open workspace folder"}),e.jsx("span",{className:"text-cyan-500/30 group-hover:text-cyan-400 transition-colors",children:"→"})]}),e.jsxs("button",{type:"button","data-testid":"workbench-bridge-status-btn",onClick:I,className:"w-full flex items-center justify-between p-4 rounded-xl border border-white/5 bg-black/40 hover:bg-white/[0.04] text-slate-300 transition-all group",children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest group-hover:text-amber-300 transition-colors",children:"Run bridge status (/status)"}),e.jsx("span",{className:"text-amber-500/30 group-hover:text-amber-400 transition-colors",children:"→"})]})]}),e.jsx(Ah,{auditOnly:a,onInsertCommand:w=>{if(typeof s=="function"){s(w);return}g(w)},onPickWorkspace:y})]}),e.jsx("footer",{className:"p-5 border-t border-white/5 bg-black/20",children:e.jsxs("div",{className:"flex justify-between items-center gap-3 text-[9px] font-mono text-slate-500",children:[e.jsxs("div",{className:"min-w-0 truncate",children:[e.jsx("span",{className:"text-slate-400",children:"Bridge"})," · ",e.jsx("span",{className:"text-slate-300",children:Ka(c==null?void 0:c.provider)}),(c==null?void 0:c.model)&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-slate-500 truncate",children:c.model})]})]}),e.jsxs("span",{className:`shrink-0 inline-flex items-center gap-1 ${(c==null?void 0:c.health)==="healthy"||(c==null?void 0:c.health)==="online"?"text-emerald-500/90":(c==null?void 0:c.health)==="degraded"?"text-amber-500/90":"text-slate-500"}`,children:[e.jsx("span",{className:`inline-block h-1.5 w-1.5 rounded-full ${(c==null?void 0:c.health)==="healthy"||(c==null?void 0:c.health)==="online"?"bg-emerald-400 shadow-[0_0_6px_rgba(52,211,153,0.6)]":(c==null?void 0:c.health)==="degraded"?"bg-amber-400":"bg-slate-600"}`}),(c==null?void 0:c.health)==="healthy"||(c==null?void 0:c.health)==="online"?"Online":(c==null?void 0:c.health)==="degraded"?"Degraded":"Offline"]})]})})]})}const Ih=i.lazy(()=>Kl(()=>import("./ScratchpadTab-zgUog115.js"),__vite__mapDeps([4,1,2,3]),import.meta.url)),Ph=i.memo(function({moodColors:r,isThinking:n,isTyping:s,particlesEnabled:a,moodEngine:o=null,rgbEnabled:c=!1,rgbStatus:l=null,showInlineThreadRailPanel:u,sessions:x,workflowId:p,onSelectSession:d,onCreateSession:m,onSaveSession:f,onRetrySave:b,onLockSession:h,saveStatus:g,isSessionUnlocked:y,sessionHydrationStatus:I,autoLockOnBlur:A,onToggleAutoLock:C,auditOnly:w,onUpgradeToPro:j,chatLog:E,inlineThreadRailWidth:N,onBeginThreadRailResize:_,onResetThreadRailWidth:S,showThreadRailResizeHint:R,showInlineThreadRail:$,threadRailCollapsed:U,onToggleThreadRailCollapse:P,onSendMessage:D,preferAppSend:z=!1,collab:F=null,panels:J,onOpenNewWindow:ee,onOpenTaskManager:ie,onToggleWorkpad:ye,showInlineWorkbenchRailPanel:pe,onBeginWorkbenchRailResize:K,onResetWorkbenchRailWidth:H,stats:W,onExecute:Z,onInsertPrompt:ce,inlineWorkbenchRailWidth:fe,showInlineWorkbenchRail:me,workbenchRailCollapsed:ke,onToggleWorkbenchRailCollapse:Pe,showScratchpad:_e,onCloseScratchpad:ne,connectionInfo:we,omegaReport:De=null,omegaLoading:re=!1,omegaError:ae="",onRefreshOmega:M,activeModel:V="llama3",onModelChange:G,visualStyle:te="operator"}){const de=String(te||"")==="frutiger-aero";return e.jsxs("main",{id:"main-workspace",tabIndex:-1,className:"flex-1 flex min-h-0 overflow-hidden relative outline-none",children:[de?null:e.jsx(lb,{moodColors:r,isThinking:n,isTyping:s,particlesEnabled:a}),u&&e.jsx(Sp,{sessions:x,workflowId:p,onSelectSession:d,onCreateSession:m,onSaveSession:f,onRetrySave:b,onLockSession:h,saveStatus:g,isSessionUnlocked:y,sessionHydrationStatus:I,autoLockOnBlur:A,onToggleAutoLock:C,auditOnly:w,onUpgradeToPro:j,chatLog:E,widthPx:N}),u&&e.jsxs("button",{type:"button",role:"separator","aria-label":"Resize workflow rail","aria-orientation":"vertical","data-testid":"thread-rail-resize-handle",onPointerDown:_,onDoubleClick:S,title:"Drag to resize. Double-click to reset.",className:"relative group z-20 w-2 -mx-1 cursor-col-resize touch-none select-none flex items-stretch",children:[e.jsx("span",{className:"mx-auto my-2 w-px bg-white/10 transition-colors group-hover:bg-cyan-400/80"}),R&&e.jsx("span",{role:"status",className:"absolute top-3 left-3 whitespace-nowrap px-2 py-1 rounded-lg border border-cyan-300/30 bg-slate-950/95 text-[11px] font-mono uppercase tracking-[0.1em] text-cyan-100 shadow-[0_6px_24px_rgba(0,0,0,0.5)]",children:"Drag to resize · double-click to reset"})]}),$&&U&&e.jsxs("button",{type:"button","data-testid":"thread-rail-mini-expand-btn",onClick:P,className:"shrink-0 w-12 border-r border-white/10 bg-slate-950/75 hover:bg-slate-900/90 text-cyan-100 transition-colors flex flex-col items-center justify-center gap-1",title:"Expand workflows rail","aria-label":"Expand workflows rail",children:[e.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wide",children:"WF"}),e.jsx("span",{className:"text-[11px] text-slate-400 font-mono uppercase tracking-wide",children:"Open"})]}),e.jsx(vh,{sessionKey:p||"default",onSendMessage:D,preferAppSend:z,collab:F,panels:J,onCreateSession:m,onOpenNewWindow:ee,onOpenTaskManager:ie,onToggleWorkpad:ye,workpadOpen:_e,className:"flex-1",moodEngine:o,rgbEnabled:c,rgbStatus:l,activeModel:V,onModelChange:G}),pe&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",role:"separator","aria-label":"Resize workbench rail","aria-orientation":"vertical","data-testid":"workbench-rail-resize-handle",onPointerDown:K,onDoubleClick:H,title:"Drag to resize. Double-click to reset.",className:"group z-20 w-2 -mx-1 cursor-col-resize touch-none select-none flex items-stretch",children:e.jsx("span",{className:"mx-auto my-2 w-px bg-white/10 transition-colors group-hover:bg-cyan-400/80"})}),e.jsx(Kp,{stats:W,workflowId:p,onExecute:Z,onInsertPrompt:ce,auditOnly:w,widthPx:fe,connectionInfo:we,omegaReport:De,omegaLoading:re,omegaError:ae,onRefreshOmega:M})]}),me&&ke&&e.jsxs("button",{type:"button","data-testid":"workbench-rail-mini-expand-btn",onClick:Pe,className:"shrink-0 w-12 border-l border-white/10 bg-slate-950/75 hover:bg-slate-900/90 text-cyan-100 transition-colors flex flex-col items-center justify-center gap-1",title:"Expand workbench rail","aria-label":"Expand workbench rail",children:[e.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wide",children:"WB"}),e.jsx("span",{className:"text-[11px] text-slate-400 font-mono uppercase tracking-wide",children:"Open"})]}),e.jsx(i.Suspense,{fallback:null,children:e.jsx(Ih,{open:_e,onClose:ne,workflowId:p})})]})});function Ed(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}Dl()(nf((t,r)=>({threadsBySession:{},activeThreadIdBySession:{},startThread:(n,s,a)=>{const o=String(n||"default"),c=String(s||"").trim(),l=r().threadsBySession[o]||{},u=Object.values(l).find(d=>String(d.messageId||"")===c);if(u)return t(d=>({activeThreadIdBySession:{...d.activeThreadIdBySession,[o]:u.id}})),u.id;const x=Ed(String(s||"msg")),p={id:x,messageId:c,rootContent:String(a||""),createdAt:new Date().toISOString(),replies:[]};return t(d=>({threadsBySession:{...d.threadsBySession,[o]:{...d.threadsBySession[o]||{},[x]:p}},activeThreadIdBySession:{...d.activeThreadIdBySession,[o]:x}})),x},openThread:(n,s)=>{const a=String(n||"default");t(o=>({activeThreadIdBySession:{...o.activeThreadIdBySession,[a]:String(s||"")}}))},closeThread:n=>{const s=String(n||"default");t(a=>({activeThreadIdBySession:{...a.activeThreadIdBySession,[s]:""}}))},addReply:(n,s,a)=>{const o=String(n||"default"),c=String(s||"").trim(),l=String(a||"").trim();if(!c||!l)return!1;const x=(r().threadsBySession[o]||{})[c];if(!x)return!1;const p={id:Ed("reply"),content:l,createdAt:new Date().toISOString()};return t(d=>({threadsBySession:{...d.threadsBySession,[o]:{...d.threadsBySession[o]||{},[c]:{...x,replies:[...x.replies,p]}}}})),!0}}),{name:"neuralshell-thread-store-v1",storage:sf(()=>window.localStorage),partialize:t=>({threadsBySession:t.threadsBySession,activeThreadIdBySession:t.activeThreadIdBySession})}));function oa(t){let r="";for(let n=0;nr.toString(16).padStart(2,"0")).join("")}async function Oh(t){if(!window.crypto||!window.crypto.subtle)throw new Error("WebCrypto is unavailable.");const r=JSON.stringify(t||{}),n=new TextEncoder().encode(r),s=window.crypto.getRandomValues(new Uint8Array(12)),a=window.crypto.getRandomValues(new Uint8Array(32)),o=await window.crypto.subtle.importKey("raw",a,{name:"AES-GCM"},!1,["encrypt"]),c=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:s},o,n),l=new Uint8Array(c),u=new Uint8Array(await window.crypto.subtle.digest("SHA-256",l)),x=Rh(u).slice(0,20),p={v:1,iv:oa(s),c:oa(l),k:oa(a)},d=oa(new TextEncoder().encode(JSON.stringify(p)));return{hash:x,fragment:d,envelope:p}}async function Th(t){if(!t)throw new Error("Missing share fragment.");if(!window.crypto||!window.crypto.subtle)throw new Error("WebCrypto is unavailable.");const r=Aa(t),n=new TextDecoder().decode(r),s=JSON.parse(n);return Vp(s)}async function Vp(t){if(!t||typeof t!="object")throw new Error("Invalid share envelope.");if(Number(t.v)!==1)throw new Error(`Unsupported share envelope version: ${t.v}`);const r=Aa(t.iv),n=Aa(t.c),s=Aa(t.k),a=await window.crypto.subtle.importKey("raw",s,{name:"AES-GCM"},!1,["decrypt"]),o=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:r},a,n),c=new TextDecoder().decode(new Uint8Array(o));return JSON.parse(c)}function Mh(t,r){const n=String(t||"").trim()||"local",s=String(r||"").trim();return`${typeof window<"u"&&window.location.origin&&window.location.origin!=="null"?window.location.origin:"https://neuralshell.app"}/share/${n}${s?`#${s}`:""}`}async function Dh(t){const r=String(t||"").trim();if(!r)throw new Error("Missing share hash.");const n=[`/static/share_blobs/${r}.json`,`/share_blobs/${r}.json`,`./static/share_blobs/${r}.json`];let s=null;for(const a of n)try{const o=await fetch(a,{method:"GET"});if(!o.ok)continue;return await o.json()}catch(o){s=o}throw s||new Error("Share blob not found.")}function $h({src:t,alt:r,className:n="",placeholderClassName:s=""}){const a=i.useRef(null),[o,c]=i.useState(!1),[l,u]=i.useState(!1);return i.useEffect(()=>{const x=a.current;if(!x)return;if(!window.IntersectionObserver){c(!0);return}const p=new window.IntersectionObserver(d=>{d.forEach(m=>{m.isIntersecting&&(c(!0),p.disconnect())})},{rootMargin:"120px 0px 120px 0px",threshold:.01});return p.observe(x),()=>p.disconnect()},[]),e.jsxs("div",{ref:a,className:`relative overflow-hidden ${n}`.trim(),children:[!l&&e.jsx("div",{"data-testid":"lazy-image-placeholder",className:`absolute inset-0 bg-slate-800/60 ${s}`.trim(),children:e.jsx("div",{className:"h-full w-full ns-shimmer"})}),o&&e.jsx("img",{src:t,alt:r,loading:"lazy",decoding:"async",onLoad:()=>u(!0),className:`block h-full w-full object-cover ${l?"opacity-100":"opacity-0"} transition-opacity duration-300`})]})}function Lh(t){const r=Number(t);return Number.isFinite(r)?r:0}function Gp(t){const r=Array.isArray(t)?t.map(s=>Lh(s)).filter(s=>Number.isFinite(s)&&s>=0).sort((s,a)=>s-a):[];if(!r.length)return null;const n=Math.floor(r.length/2);return r.length%2===0?Number(((r[n-1]+r[n])/2).toFixed(1)):Number(r[n].toFixed(1))}function Bh(t){return t==null||t===""||!Number.isFinite(Number(t))||Number(t)<0?"neutral":Number(t)<150?"green":Number(t)<=250?"amber":"red"}const Fh=Object.freeze(Object.defineProperty({__proto__:null,classifyVoiceRtt:Bh,computeMedianRtt:Gp},Symbol.toStringTag,{value:"Module"}));function Uh(t){const r=[];return!t||typeof t.forEach!="function"||t.forEach(n=>{!n||typeof n!="object"||(typeof n.currentRoundTripTime=="number"&&Number.isFinite(n.currentRoundTripTime)?r.push(n.currentRoundTripTime*1e3):typeof n.roundTripTime=="number"&&Number.isFinite(n.roundTripTime)&&r.push(n.roundTripTime*1e3))}),r}function zh(t={}){const r=!!t.enabled,n=Math.max(5e3,Number(t.pollMs||5e3)),s=typeof t.getPeerConnection=="function"?t.getPeerConnection:()=>null,[a,o]=i.useState([]);return i.useEffect(()=>{if(!r){o([]);return}let l=!0,u=null;const x=async()=>{try{const p=s();if(p&&typeof p.getStats=="function"){const d=await p.getStats(),m=Uh(d);l&&m.length&&o(f=>[...f,...m].slice(-30))}}catch{}l&&(u=setTimeout(x,n))};return x(),()=>{l=!1,u&&clearTimeout(u)}},[r,s,n]),{medianRttMs:i.useMemo(()=>Gp(a),[a]),sampleCount:a.length}}const{classifyVoiceRtt:Hh}=Fh;function Wh(t){return t&&t.payload&&typeof t.payload=="object"?t.payload:{}}function Kh({collab:t}){const[r,n]=i.useState(!1),[s,a]=i.useState("idle"),[o,c]=i.useState(""),[l,u]=i.useState(!1),x=i.useRef(null),p=i.useRef(null),d=i.useRef(null),m=zh({enabled:r&&s==="connected",pollMs:5e3,getPeerConnection:()=>d.current}),f=Hh(m.medianRttMs),b=i.useCallback((w,j={})=>{t&&typeof t.publish=="function"&&t.publish("voice-signal",{type:w,toPeerId:String(j.toPeerId||""),fromPeerId:String(t.peerId||""),sdp:j.sdp||null,candidate:j.candidate||null})},[t]),h=window.RTCPeerConnection||window.webkitRTCPeerConnection,g=window.RTCSessionDescription||window.webkitRTCSessionDescription,y=window.RTCIceCandidate||window.webkitRTCIceCandidate,I=i.useCallback(()=>{if(d.current)return d.current;if(!h)throw new Error("WebRTC is unavailable in this runtime.");const w=new h;return w.onicecandidate=j=>{j.candidate&&b("candidate",{toPeerId:o,candidate:j.candidate})},w.ontrack=j=>{x.current&&(x.current.srcObject=j.streams[0])},d.current=w,w},[h,b,o]),A=i.useCallback(()=>{if(d.current&&(d.current.close(),d.current=null),p.current){for(const w of p.current.getTracks())w.stop();p.current=null}x.current&&(x.current.srcObject=null),n(!1),c(""),a("idle")},[]),C=i.useCallback(async()=>{try{const w=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,channelCount:1}});p.current=w;const j=I();for(const E of w.getTracks())E.enabled=!1,j.addTrack(E,w);n(!0),a("waiting"),b("hello",{toPeerId:""})}catch(w){a(`join_failed:${w&&w.message?w.message:String(w)}`)}},[I,b]);return i.useEffect(()=>{if(!r||!p.current)return;(j=>{for(const E of p.current.getAudioTracks())E.enabled=j})(!!l)},[r,l]),i.useEffect(()=>{const w=E=>{E.code==="Space"&&r&&u(!0)},j=E=>{E.code==="Space"&&r&&u(!1)};return window.addEventListener("keydown",w),window.addEventListener("keyup",j),()=>{window.removeEventListener("keydown",w),window.removeEventListener("keyup",j)}},[r]),i.useEffect(()=>{const w=t&&t.lastEvent?t.lastEvent:null;if(!w||w.eventType!=="voice-signal")return;const j=Wh(w),E=String(j.fromPeerId||w.fromPeerId||"");if(!E||E===String(t&&t.peerId||""))return;const N=String(j.toPeerId||"");if(N&&N!==String(t&&t.peerId||""))return;const _=String(j.type||"");(async()=>{try{const R=I();if(_==="hello"){if(!r)return;if(c(E),String(t&&t.peerId||"")()=>A(),[A]),e.jsxs("section",{"data-testid":"voice-panel",className:"rounded-xl border border-white/10 bg-black/30 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.14em] font-bold text-fuchsia-300",children:"Voice Room"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"DTLS-SRTP via WebRTC · Push-to-talk Space"})]}),e.jsx("div",{"data-testid":"voice-rtt-badge",className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${f==="green"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-200":f==="amber"?"border-amber-300/40 bg-amber-500/10 text-amber-200":f==="red"?"border-rose-300/40 bg-rose-500/10 text-rose-200":"border-slate-300/20 bg-slate-500/10 text-slate-300"}`,title:"Median voice round-trip time, refreshed every 5 seconds.",children:Number.isFinite(Number(m.medianRttMs))?`RTT ${Math.round(Number(m.medianRttMs))}ms`:"RTT --"}),e.jsx("button",{type:"button","data-testid":"voice-toggle-btn",onClick:()=>r?A():C(),className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${r?"border-rose-300/30 bg-rose-500/10 text-rose-200":"border-fuchsia-300/30 bg-fuchsia-500/10 text-fuchsia-200"}`,children:r?"Leave":"Join"})]}),e.jsx("div",{className:"text-[10px] font-mono text-slate-300",children:r?`Status: ${s} · remote=${o||"none"} · PTT=${l?"on":"off"}`:"Voice idle."}),e.jsx("audio",{ref:x,autoPlay:!0,playsInline:!0})]})}const Jp="neuralshell_omega_boot_session_v1",Vh="neuralshell_omega_boot_suppressed_v1";function Gh(){return typeof window>"u"?!1:!!(window.localStorage&&window.localStorage.getItem(Vh)==="1"||window.sessionStorage&&window.sessionStorage.getItem(Jp)==="1")}function Jh({report:t,onComplete:r}){const[n,s]=i.useState(()=>!Gh()),[a,o]=i.useState([]),[c,l]=i.useState(0);return i.useEffect(()=>{if(!n)return;typeof window<"u"&&window.sessionStorage&&window.sessionStorage.setItem(Jp,"1");const u=Array.isArray(t&&t.bootSequence)?t.bootSequence:[{phase:"BOOT",text:"Initializing OMEGA-Kernel…",delayMs:0},{phase:"READY",text:"ProofForge online",delayMs:1800}],x=[];u.forEach((d,m)=>{x.push(window.setTimeout(()=>{o(f=>[...f,d]),l(Math.round((m+1)/u.length*100))},Number(d.delayMs)||0))});const p=Math.max(...u.map(d=>Number(d.delayMs)||0),0)+900;return x.push(window.setTimeout(()=>{s(!1),typeof r=="function"&&r()},p)),()=>{x.forEach(d=>window.clearTimeout(d))}},[n,t,r]),n?e.jsxs("div",{"data-testid":"omega-boot-overlay",className:"fixed inset-0 z-[12000] flex items-center justify-center bg-[#020812]/96 backdrop-blur-sm",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.12] pointer-events-none",style:{backgroundImage:"repeating-linear-gradient(0deg, #000 0px, #000 1px, transparent 1px, transparent 4px)"}}),e.jsxs("div",{className:"relative w-full max-w-2xl mx-6 rounded-2xl border border-cyan-400/20 bg-slate-950/90 shadow-[0_0_60px_rgba(34,211,238,0.08)] overflow-hidden",children:[e.jsxs("div",{className:"px-5 py-3 border-b border-white/10 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-mono uppercase tracking-[0.25em] text-slate-400",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-red-500 animate-pulse"}),"REC · OMEGA BOOT"]}),e.jsx("button",{type:"button","data-testid":"omega-boot-skip-btn",onClick:()=>{s(!1),typeof r=="function"&&r()},className:"text-[10px] font-mono uppercase tracking-wider text-slate-500 hover:text-cyan-300 transition-colors",children:"Skip"})]}),e.jsxs("div",{className:"p-6 font-mono text-[12px] leading-relaxed min-h-[220px]",children:[a.map((u,x)=>e.jsxs("div",{"data-testid":`omega-boot-line-${String(u.phase||x).toLowerCase()}`,className:`mb-1.5 ${u.ok===!1?"text-red-300":u.ok===!0?"text-emerald-300":"text-cyan-100/90"}`,children:[e.jsxs("span",{className:"text-fuchsia-400/80",children:["[",u.phase,"]"]})," ",u.text]},`${u.phase}-${x}`)),e.jsx("div",{className:"mt-4 text-cyan-300/70 animate-pulse",children:"▮"})]}),e.jsxs("div",{className:"px-6 pb-5",children:[e.jsx("div",{className:"h-1.5 rounded-full bg-white/5 overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-violet-500 via-cyan-400 to-fuchsia-500 transition-all duration-300",style:{width:`${c}%`}})}),e.jsx("div",{className:"mt-2 text-[9px] font-mono text-slate-500 uppercase tracking-[0.3em]",children:"PF // VHS-01 · OMEGA-Kernel sequence · Created by The Founder"})]})]})]}):null}const qh=[{left:"8%",size:48,delay:0,duration:14},{left:"22%",size:28,delay:2,duration:11},{left:"38%",size:64,delay:1,duration:16},{left:"55%",size:36,delay:3,duration:12},{left:"72%",size:52,delay:.5,duration:15},{left:"86%",size:24,delay:4,duration:10},{left:"91%",size:40,delay:1.5,duration:13}],Yh=i.memo(function(){return e.jsxs("div",{"aria-hidden":!0,className:"aero-backdrop pointer-events-none absolute inset-0 overflow-hidden z-0",children:[e.jsx("div",{className:"aero-sky absolute inset-0"}),e.jsx("div",{className:"aero-sun absolute top-[8%] right-[12%] w-28 h-28 rounded-full"}),e.jsx("div",{className:"aero-cloud aero-cloud-1"}),e.jsx("div",{className:"aero-cloud aero-cloud-2"}),e.jsx("div",{className:"aero-grass absolute inset-x-0 bottom-0 h-[28%]"}),e.jsx("div",{className:"aero-water-shimmer absolute inset-x-0 bottom-[18%] h-24"}),qh.map((r,n)=>e.jsx("span",{className:"aero-bubble absolute rounded-full",style:{left:r.left,width:r.size,height:r.size,animationDelay:`${r.delay}s`,animationDuration:`${r.duration}s`,bottom:`${12+n%4*8}%`}},`aero-bubble-${n}`)),e.jsx("div",{className:"aero-lens-flare absolute top-[18%] left-[32%] w-64 h-32 rotate-12"})]})}),Zh=40;function As(t){return String(t||"").trim().toLowerCase()}function Xh(t){return As(t).split(/\s+/).map(r=>r.trim()).filter(Boolean)}function Qh(t,r){return r.length?r.every(n=>t.includes(n)):!0}function Es(t){const r=Array.isArray(t)?t:t&&Array.isArray(t.entries)?t.entries:[],n=new Map;for(const s of r){const a=s&&typeof s=="object",o=String(a?s.key:s||"").trim();if(!o)continue;const c=n.get(o),l=Math.max(1,Number(a?s.count:1)||1),u=Math.max(0,Number(a?s.lastUsedAt:0)||0);n.set(o,{key:o,count:c?Math.max(c.count,l):l,lastUsedAt:c?Math.max(c.lastUsedAt,u):u})}return Array.from(n.values()).sort((s,a)=>a.lastUsedAt!==s.lastUsedAt?a.lastUsedAt-s.lastUsedAt:a.count!==s.count?a.count-s.count:s.key.localeCompare(a.key)).slice(0,Zh)}function eg(t,r,n=Date.now()){const s=String(r||"").trim();if(!s)return Es(t);const a=Es(t),o=a.find(l=>l.key===s),c=[{key:s,count:o?o.count+1:1,lastUsedAt:Math.max(0,Number(n)||Date.now())},...a.filter(l=>l.key!==s)];return Es(c)}function tg(t={}){const r=String(t&&t.workflowId||"").trim(),n=Array.isArray(t&&t.sessions)?t.sessions:[],s=Array.isArray(t&&t.chatLog)?t.chatLog:[],a=String(t&&t.sessionHydrationStatus||"").trim(),o=new Set(["global","system"]);return r&&o.add("workflow"),n.length&&o.add("session"),s.length&&o.add("chat"),a==="locked"&&o.add("locked-session"),r&&a!=="locked"&&o.add("active-workflow"),{workflowId:r,hasWorkflow:!!r,hasSessions:n.length>0,hasChat:s.length>0,sessionHydrationStatus:a,contexts:Array.from(o)}}function rg(t,r={}){const n=Array.isArray(t&&t.contexts)?t.contexts.map(a=>String(a||"").trim()).filter(Boolean):[];if(!n.length)return!0;const s=new Set(Array.isArray(r&&r.contexts)?r.contexts.map(a=>String(a||"").trim()).filter(Boolean):["global"]);return n.some(a=>s.has(a))}function ng(t,r,n,s){const a=As(t&&t.label),o=As(t&&t.id),c=As(t&&t.keywords),l=`${a} ${o} ${c}`.trim();if(!l||!Qh(l,n))return Number.NEGATIVE_INFINITY;let u=Number(t&&t.contextWeight)||0;const x=String(t&&t.kind||"command");if(!r)u+=x==="command"?12:6;else{l.startsWith(r)&&(u+=150),a.startsWith(r)&&(u+=120),o.startsWith(r)&&(u+=80),a.includes(r)&&(u+=50),o.includes(r)&&(u+=30);for(const p of n)a.startsWith(p)?u+=20:a.includes(p)&&(u+=10),o.startsWith(p)?u+=12:o.includes(p)&&(u+=6),c.includes(p)&&(u+=4)}if(r.startsWith("/")&&x==="command"&&(u+=35),x==="session"&&n.some(p=>p==="session"||p==="workflow"||p==="thread")&&(u+=22),s){const p=Math.max(0,Number(s.rank)||0),d=Math.max(1,Number(s.count)||1);u+=Math.max(0,110-p*5),u+=Math.min(35,d*5)}return x==="session"&&t.active&&(u+=12),x==="session"&&t.locked&&(u-=4),u}function sg({resultCount:t,selectedLabel:r,query:n}){const s=Math.max(0,Number(t)||0),a=n?`${s} result${s===1?"":"s"} for ${String(n).trim()}`:`${s} palette result${s===1?"":"s"}`;return r?`${a}. Selected ${r}.`:`${a}.`}const Ea=[];function Nt(t){if(!t.id||!t.slot)throw new Error(`Module registration requires id and slot: ${JSON.stringify(t)}`);const r=Ea.findIndex(n=>n.id===t.id);r>=0?Ea[r]={priority:100,stability:"trusted",visible:()=>!0,...t}:Ea.push({priority:100,stability:"trusted",visible:()=>!0,...t})}function Id(t,r={}){const{includeExperimental:n=!1,context:s={}}=r;return Ea.filter(a=>a.slot===t).filter(a=>n||a.stability!=="experimental").filter(a=>rg(a,s)).filter(a=>a.visible(s)).sort((a,o)=>a.priority-o.priority)}function ag(t={}){return[...Id("palette.commands",t),...Id("palette.system",t)]}Nt({id:"cmd-purge",slot:"palette.commands",title:"Purge Workflow History",priority:30,stability:"core",contexts:["session","chat"],contextLabel:"Workflow",visible:t=>!!(t&&(t.hasSessions||t.hasChat)),action:()=>{window.api&&window.api.ritual&&window.api.ritual.execute("purge")}});Nt({id:"cmd-clear",slot:"palette.system",title:"Clear History",priority:10,stability:"core",contexts:["chat"],contextLabel:"Current chat",visible:t=>!!(t&&t.hasChat),action:t=>{t&&typeof t.setChatLog=="function"&&t.setChatLog([])}});Nt({id:"cmd-status",slot:"palette.system",title:"Show System Status",priority:20,stability:"core",contexts:["system"],contextLabel:"System",action:t=>{t&&typeof t.appendChat=="function"&&t.appendChat({role:"assistant",content:`Node Status: OPERATIONAL Integrity: SEALED CPU: ${t.stats.cpuPercent}% -Memory: ${t.stats.memoryMb}MB`})}});Nt({id:"cmd-help",slot:"palette.system",title:"Show Help Guide",priority:50,stability:"core",contexts:["global"],contextLabel:"Global",action:t=>{t&&typeof t.appendChat=="function"&&t.appendChat({role:"assistant",content:"### ProofForge Help Guide\n\n- `/help` : Show this guide\n- `/status` : Check node telemetry\n- `/clear` : Clear current thread\n- `/purge` : Delete all session history\n- `Ctrl+K` : Command Palette\n- `Ctrl+Shift+T` : Operator Inbox\n- `Ctrl+Shift+N` : Workpad\n- `Ctrl+P` : Projects panel"})}});const og=24,qp="neuralshell_palette_mru_v1";function ig(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(qp)||"[]");return Es(t)}catch{return[]}}function lg(t){if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(qp,JSON.stringify(Es(t)))}catch{}}function Pd(t,r){return`command-palette-option-${String(t&&t.key||`item-${r}`).replace(/[^a-zA-Z0-9_-]/g,"-")}`}function cg({onClose:t}){const r=$l(),s=typeof navigator<"u"&&/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl",a=i.useRef(null),o=i.useRef(new Map),l=i.useRef(null),c=i.useRef(!1);!c.current&&typeof document<"u"&&(l.current=document.activeElement,c.current=!0);const[u,x]=i.useState(""),[p,d]=i.useState(0),[m,f]=i.useState(()=>ig());i.useEffect(()=>{lg(m)},[m]),i.useEffect(()=>{var I;(I=a.current)==null||I.focus({preventScroll:!0})},[]);const b=i.useMemo(()=>tg(r),[r]),h=i.useMemo(()=>ag({context:b}).map((D,z)=>({key:`command:${String(D&&D.id||`cmd-${z}`)}`,id:String(D&&D.id||`cmd-${z}`),label:String(D&&D.title||`Command ${z+1}`),subtitle:String(D&&D.contextLabel||"Command"),kind:"command",action:D&&D.action,shortcutNumber:D&&D.shortcut?null:z<9?z+1:null,shortcut:D&&D.shortcut||(z<9?`${s} + ${z+1}`:""),keywords:`${String(D&&D.title||"")} ${String(D&&D.id||"")} ${String(D&&D.contextLabel||"")} command`,contextWeight:Array.isArray(D&&D.contexts)&&D.contexts.some(F=>b.contexts.includes(F))?8:0,baseIndex:z})),[s,b]),g=i.useMemo(()=>{const I=Array.isArray(r&&r.sessions)?r.sessions:[],D=String(r&&r.workflowId||"").trim(),z=!!(r&&typeof r.isSessionUnlocked=="function");return I.map((F,J)=>{const ee=String(F||"").trim(),ie=ee===D,ye=z?!r.isSessionUnlocked(ee):!1;return{key:`session:${ee}`,id:ee,label:ee,subtitle:ie?"Active workflow":"Workflow session",kind:"session",sessionName:ee,active:ie,locked:ye,shortcutNumber:null,shortcut:"",keywords:`${ee} workflow session thread`,contextWeight:ie?8:0,baseIndex:1e3+J}})},[r]),y=i.useMemo(()=>[...h,...g],[h,g]),P=i.useMemo(()=>As(u),[u]),A=i.useMemo(()=>Xh(u),[u]),C=i.useMemo(()=>new Map(m.map((I,D)=>[I.key,{...I,rank:D}])),[m]),w=i.useMemo(()=>y.map(I=>{const D=C.get(I.key)||null;return{item:I,score:ng(I,P,A,D),mruRank:D?D.rank:-1}}).filter(I=>Number.isFinite(I.score)&&I.score>Number.NEGATIVE_INFINITY).sort((I,D)=>D.score!==I.score?D.score-I.score:I.mruRank!==D.mruRank?I.mruRank<0?1:D.mruRank<0?-1:I.mruRank-D.mruRank:I.item.baseIndex!==D.item.baseIndex?I.item.baseIndex-D.item.baseIndex:String(I.item.label||"").localeCompare(String(D.item.label||""))).slice(0,og).map(I=>I.item),[y,C,P,A]),j=i.useMemo(()=>{let I=0,D=0;for(const z of w)z.kind==="session"?D+=1:I+=1;return{commands:I,sessions:D}},[w]);i.useEffect(()=>{d(0)},[P]),i.useEffect(()=>{p0?w.length-1:0)},[w.length,p]),i.useEffect(()=>{const I=w[p];if(!I)return;const D=o.current.get(I.key);D&&typeof D.scrollIntoView=="function"&&D.scrollIntoView({block:"nearest"})},[w,p]);const E=i.useCallback(I=>{f(D=>eg(D,I))},[]),N=i.useCallback(()=>{const I=l.current;t(),window.requestAnimationFrame(()=>{I&&typeof I.focus=="function"&&I.focus({preventScroll:!0})})},[t]),_=i.useCallback(I=>{if(I){if(I.kind==="command")typeof I.action=="function"&&I.action(r);else if(I.kind==="session"){const D=String(I.sessionName||"").trim();D&&r&&typeof r.selectSession=="function"&&r.selectSession(D)}E(I.key),N()}},[N,E,r]),S=i.useCallback(I=>{if(I.key==="Escape"){I.preventDefault(),N();return}if((I.ctrlKey||I.metaKey)&&/^[1-9]$/.test(I.key)){const D=Number(I.key),z=h.find(F=>F.shortcutNumber===D);z&&(I.preventDefault(),_(z));return}if(I.key==="ArrowDown"){if(I.preventDefault(),!w.length)return;d(D=>(D+1)%w.length);return}if(I.key==="ArrowUp"){if(I.preventDefault(),!w.length)return;d(D=>(D-1+w.length)%w.length);return}if(I.key==="PageDown"){if(I.preventDefault(),!w.length)return;d(D=>Math.min(w.length-1,D+5));return}if(I.key==="PageUp"){if(I.preventDefault(),!w.length)return;d(D=>Math.max(0,D-5));return}if(I.key==="Home"){I.preventDefault(),d(0);return}if(I.key==="End"){if(I.preventDefault(),!w.length)return;d(w.length-1);return}if(I.key==="Enter"){if(I.preventDefault(),!w.length)return;const D=w[p]||w[0];_(D)}},[N,h,w,_,p]),R=w[p]||null,$=R?Pd(R,p):void 0,U=i.useMemo(()=>sg({resultCount:w.length,selectedLabel:R&&R.label,query:u}),[w.length,u,R]);return e.jsx("div",{"data-testid":"command-palette",role:"dialog","aria-modal":"true","aria-label":"Command palette",className:"fixed inset-0 z-50 flex items-start justify-center pt-[15vh] px-4 backdrop-blur-md bg-black/60 animate-in fade-in duration-200",onClick:N,children:e.jsxs("div",{className:"w-full max-w-2xl bg-slate-900/80 backdrop-blur-xl border border-cyan-400/30 rounded-2xl shadow-[0_20px_50px_rgba(0,0,0,0.5),0_0_30px_rgba(34,211,238,0.1)] overflow-hidden",onClick:I=>I.stopPropagation(),children:[e.jsxs("div",{className:"p-4 border-b border-white/5 flex items-center gap-3",children:[e.jsx("span",{className:"text-cyan-400 font-mono text-xl",children:"/"}),e.jsx("input",{ref:a,"data-testid":"command-palette-input",value:u,onChange:I=>x(I.target.value),onKeyDown:S,"aria-label":"Search commands and sessions","aria-controls":"command-palette-results","aria-activedescendant":$,"aria-describedby":"command-palette-live-status command-palette-help",className:"flex-1 bg-transparent border-none outline-none text-lg text-slate-100 placeholder-slate-600",placeholder:"Search commands, workflows, and sessions..."}),e.jsxs("div",{className:"text-[10px] text-slate-500 bg-white/5 px-2 py-1 rounded border border-white/10 uppercase font-bold",children:[w.length," Result",w.length===1?"":"s"]})]}),e.jsxs("div",{className:"px-4 py-2 border-b border-white/5 text-[10px] font-mono text-slate-500 flex items-center justify-between",children:[e.jsxs("span",{children:[j.commands," command",j.commands===1?"":"s"]}),e.jsxs("span",{children:[j.sessions," workflow",j.sessions===1?"":"s"]})]}),e.jsx("div",{id:"command-palette-live-status","data-testid":"command-palette-live-status",className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:U}),e.jsx("div",{id:"command-palette-help",className:"sr-only",children:"Use arrow keys to move, Enter to run, Escape to close, and Page Up or Page Down to jump results."}),e.jsx("div",{id:"command-palette-results",className:"p-2 max-h-96 overflow-y-auto no-scrollbar",role:"listbox","aria-label":"Available palette results",children:w.length===0?e.jsxs("div",{className:"px-3 py-8 text-center",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"No Matches"}),e.jsx("div",{className:"mt-1 text-[10px] font-mono text-slate-500",children:"Try a simpler keyword or clear the query."})]}):w.map((I,D)=>{const z=D===p;return e.jsx("button",{id:Pd(I,D),ref:F=>{F?o.current.set(I.key,F):o.current.delete(I.key)},role:"option","aria-selected":z,"data-testid":`command-palette-item-${I.kind}-${I.id}`,className:`w-full text-left p-3 rounded-xl transition-all border ${z?"bg-cyan-400/15 border-cyan-400/25":"hover:bg-cyan-400/10 border-transparent"}`,onMouseMove:()=>{z||d(D)},onClick:()=>_(I),children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:z?"text-cyan-100 font-semibold truncate":"text-slate-200 font-semibold truncate",children:I.label}),e.jsxs("div",{className:"mt-0.5 text-[10px] font-mono text-slate-500 truncate",children:[I.subtitle,I.kind==="session"&&I.locked?" · Locked":""]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${I.kind==="session"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-200":"border-cyan-300/30 bg-cyan-500/10 text-cyan-200"}`,children:I.kind==="session"?"Workflow":"Command"}),I.active?e.jsx("span",{className:"px-1.5 py-0.5 rounded border border-amber-300/30 bg-amber-500/10 text-[9px] font-mono uppercase tracking-[0.14em] text-amber-200",children:"Active"}):null,I.shortcut?e.jsx("span",{className:`text-[9px] font-mono uppercase ${z?"text-cyan-300":"text-slate-600"}`,children:I.shortcut}):null]})]})},I.key)})})]})})}function dg(t,r){const n=new Blob([`${JSON.stringify(r,null,2)} -`],{type:"application/json"}),s=URL.createObjectURL(n),a=document.createElement("a");a.href=s,a.download=t,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(s)}function ug(){const[t,r]=i.useState(""),[n,s]=i.useState(""),[a,o]=i.useState(!1),[l,c]=i.useState({tone:"idle",text:""}),u=async()=>{o(!0);try{await window.api.vault.lock(),c({tone:"ok",text:"Vault locked."})}catch(m){c({tone:"bad",text:`Vault lock failed: ${m&&m.message?m.message:String(m)}`})}finally{o(!1)}},x=async()=>{o(!0);try{await window.api.vault.unlock(t),c({tone:"ok",text:"Vault unlocked."})}catch(m){c({tone:"bad",text:`Vault unlock failed: ${m&&m.message?m.message:String(m)}`})}finally{o(!1)}},p=async()=>{o(!0);try{const m=await window.api.vault.export(t);if(!m||!m.ok||!m.blob)throw new Error("Vault export returned no blob payload.");const f=new Date().toISOString().replace(/[:.]/g,"-");dg(`neuralshell-vault-${f}.json`,m.blob),c({tone:"ok",text:`Vault exported (${Number(m.count)||0} entries).`})}catch(m){c({tone:"bad",text:`Vault export failed: ${m&&m.message?m.message:String(m)}`})}finally{o(!1)}},d=async()=>{o(!0);try{const m=JSON.parse(String(n||"{}")),f=await window.api.vault.import(m,t,{mode:"merge"});if(!f||!f.ok)throw new Error("Vault import failed.");c({tone:"ok",text:`Vault imported (${Number(f.imported)||0} entries).`})}catch(m){c({tone:"bad",text:`Vault import failed: ${m&&m.message?m.message:String(m)}`})}finally{o(!1)}};return e.jsxs("section",{"data-testid":"vault-card",className:"space-y-4 p-5 bg-black/30 rounded-2xl border border-cyan-400/20 shadow-inner",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-cyan-400 font-bold",children:"Vault+"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"Provider secrets are encrypted at rest and exported/imported as AES-GCM JSON blobs."}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[10px] text-slate-400 uppercase tracking-widest font-bold ml-1",children:"Vault Passphrase"}),e.jsx("input",{"data-testid":"vault-passphrase-input",type:"password",value:t,onChange:m=>r(m.target.value),placeholder:"Required for unlock / export / import",className:"w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-sm text-slate-200 placeholder-slate-600 outline-none focus:border-cyan-400/50 focus:ring-1 focus:ring-cyan-400/10 transition-all font-mono"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx("button",{"data-testid":"vault-unlock-btn",type:"button",onClick:x,disabled:a,className:"px-3 py-2 rounded-xl border border-emerald-300/30 bg-emerald-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-emerald-200 hover:bg-emerald-500/20 disabled:opacity-50",children:"Unlock Vault"}),e.jsx("button",{"data-testid":"vault-lock-btn",type:"button",onClick:u,disabled:a,className:"px-3 py-2 rounded-xl border border-amber-300/30 bg-amber-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-amber-200 hover:bg-amber-500/20 disabled:opacity-50",children:"Lock Vault"}),e.jsx("button",{"data-testid":"vault-export-btn",type:"button",onClick:p,disabled:a,className:"px-3 py-2 rounded-xl border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-cyan-200 hover:bg-cyan-500/20 disabled:opacity-50",children:"Export Vault"}),e.jsx("button",{"data-testid":"vault-import-btn",type:"button",onClick:d,disabled:a,className:"px-3 py-2 rounded-xl border border-violet-300/30 bg-violet-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-violet-200 hover:bg-violet-500/20 disabled:opacity-50",children:"Import Vault"})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[10px] text-slate-400 uppercase tracking-widest font-bold ml-1",children:"Import JSON Blob"}),e.jsx("textarea",{"data-testid":"vault-import-json",value:n,onChange:m=>s(m.target.value),placeholder:"Paste vault export JSON blob here",className:"min-h-24 w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-[11px] text-slate-200 placeholder-slate-600 outline-none focus:border-cyan-400/50 focus:ring-1 focus:ring-cyan-400/10 transition-all font-mono resize-y"})]}),l.text&&e.jsx("div",{className:`rounded-xl border px-3 py-2 text-[10px] font-mono ${l.tone==="ok"?"border-emerald-400/30 bg-emerald-500/10 text-emerald-200":l.tone==="bad"?"border-rose-400/30 bg-rose-500/10 text-rose-200":"border-white/10 bg-black/30 text-slate-300"}`,children:l.text})]})}function pg({licenseMode:t=""}){const[r,n]=i.useState(!1),[s,a]=i.useState(!1),[o,l]=i.useState(""),c=String(t||"").trim().toLowerCase()==="auditor";i.useEffect(()=>{let x=!0;return(async()=>{try{const p=await window.api.proofRelay.getConfig();if(!x)return;n(!!(p&&p.enabled))}catch(p){if(!x)return;l(`Proof relay config load failed: ${p&&p.message?p.message:String(p)}`)}})(),()=>{x=!1}},[]);const u=async()=>{if(!c){a(!0);try{const x=await window.api.proofRelay.setConfig({enabled:!r,channel:"auto"});n(!!(x&&x.enabled)),l(x&&x.enabled?"Proof relay enabled.":"Proof relay disabled.")}catch(x){l(`Proof relay update failed: ${x&&x.message?x.message:String(x)}`)}finally{a(!1)}}};return e.jsxs("section",{"data-testid":"proof-relay-toggle",className:"space-y-3 p-5 bg-black/30 rounded-2xl border border-white/5 shadow-inner",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-emerald-300 font-bold",children:"Proof Relay Webhook"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"When enabled, a successful `npm run proof:bundle` posts repo/tag/SHA/manifest to Slack/Discord."})]}),e.jsx("button",{type:"button","data-testid":"proof-relay-toggle-btn",onClick:u,disabled:s||c,className:`h-8 min-w-20 rounded-lg border px-3 text-[10px] uppercase tracking-[0.16em] font-bold transition-colors ${r?"border-emerald-300/40 bg-emerald-500/20 text-emerald-100":"border-slate-500/30 bg-slate-700/20 text-slate-300"} disabled:opacity-60`,children:r?"ON":"OFF"})]}),c&&e.jsx("div",{className:"rounded-xl border border-amber-400/30 bg-amber-500/10 px-3 py-2 text-[10px] font-mono text-amber-200",children:"Auditor mode is active; proof relay is forced off."}),o&&e.jsx("div",{className:"rounded-xl border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-300",children:o})]})}function mg({licenseMode:t=""}){const[r,n]=i.useState({enabled:!1,channel:"stable",available:!1}),[s,a]=i.useState({pending:!1,available:!1}),[o,l]=i.useState(!1),[c,u]=i.useState(""),x=String(t||"").trim().toLowerCase()==="auditor",p=i.useCallback(async()=>{try{const[f,b]=await Promise.all([window.api.autoUpdate.getPolicy(),window.api.autoUpdate.pending()]);n(f||{enabled:!1,channel:"stable",available:!1}),a(b||{pending:!1,available:!1})}catch(f){u(`Auto-update status load failed: ${f&&f.message?f.message:String(f)}`)}},[]);i.useEffect(()=>{p()},[p]);const d=async f=>{if(!x){l(!0);try{const b=await window.api.autoUpdate.setPolicy({enabled:f,channel:r.channel||"stable"});n(b||r),u(f?"Auto-update lane enabled.":"Auto-update lane disabled.")}catch(b){u(`Auto-update toggle failed: ${b&&b.message?b.message:String(b)}`)}finally{l(!1)}}},m=async f=>{if(!x){l(!0);try{const b=await window.api.autoUpdate.setPolicy({enabled:r.enabled,channel:f});n(b||r),u(`Auto-update channel set to ${f}.`)}catch(b){u(`Auto-update channel update failed: ${b&&b.message?b.message:String(b)}`)}finally{l(!1)}}};return e.jsxs("section",{"data-testid":"auto-update-card",className:"space-y-3 p-5 bg-black/30 rounded-2xl border border-white/5 shadow-inner",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-cyan-300 font-bold",children:"Deterministic Auto-Update"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"Verified SHA-256 + signature lane with staged swap-on-restart behavior."})]}),e.jsx("button",{type:"button","data-testid":"auto-update-toggle-btn",onClick:()=>d(!r.enabled),disabled:o||x||!r.available,className:`h-8 min-w-20 rounded-lg border px-3 text-[10px] uppercase tracking-[0.16em] font-bold transition-colors ${r.enabled?"border-emerald-300/40 bg-emerald-500/20 text-emerald-100":"border-slate-500/30 bg-slate-700/20 text-slate-300"} disabled:opacity-60`,children:r.enabled?"ON":"OFF"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Channel"}),e.jsxs("select",{"data-testid":"auto-update-channel",value:String(r.channel||"stable"),onChange:f=>m(f.target.value),disabled:o||x||!r.available,className:"bg-slate-900 border border-white/10 rounded px-2 py-1 text-[11px] text-slate-200 font-mono",children:[e.jsx("option",{value:"stable",children:"stable"}),e.jsx("option",{value:"canary",children:"canary"})]}),e.jsx("button",{type:"button",onClick:p,disabled:o,className:"px-2 py-1 rounded border border-white/10 text-[10px] font-mono text-slate-300 hover:bg-white/10 disabled:opacity-60",children:"Refresh"})]}),e.jsx("div",{className:`rounded-xl border px-3 py-2 text-[10px] font-mono ${s.pending?"border-amber-300/30 bg-amber-500/10 text-amber-200":"border-emerald-300/20 bg-emerald-500/10 text-emerald-200"}`,children:s.pending?"Pending verified swap is queued for next restart.":"No pending swap queued."}),x&&e.jsx("div",{className:"rounded-xl border border-amber-400/30 bg-amber-500/10 px-3 py-2 text-[10px] font-mono text-amber-200",children:"Auditor mode is active; auto-update lane is forced to read-only."}),c&&e.jsx("div",{className:"rounded-xl border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-300",children:c})]})}function Rd(t){return Object.entries(t&&typeof t=="object"?t:{}).map(([n,s])=>({repo:String(n||"").trim(),slackWebhook:String(s&&s.slackWebhook?s.slackWebhook:""),discordWebhook:String(s&&s.discordWebhook?s.discordWebhook:"")})).filter(n=>n.repo)}function xg(t){const r={};for(const n of Array.isArray(t)?t:[]){const s=String(n&&n.repo?n.repo:"").trim();s&&(r[s]={slackWebhook:String(n&&n.slackWebhook?n.slackWebhook:"").trim(),discordWebhook:String(n&&n.discordWebhook?n.discordWebhook:"").trim()})}return r}function fg({licenseMode:t=""}){const[r,n]=i.useState([]),[s,a]=i.useState(!1),[o,l]=i.useState(""),c=String(t||"").trim().toLowerCase()==="auditor";i.useEffect(()=>{let m=!0;return(async()=>{try{const f=await window.api.proofRelay.getRepoMap();if(!m)return;n(Rd(f&&f.map?f.map:{}))}catch(f){if(!m)return;l(`Repo relay map load failed: ${f&&f.message?f.message:String(f)}`)}})(),()=>{m=!1}},[]);const u=(m,f,b)=>{n(h=>h.map((g,y)=>y===m?{...g,[f]:b}:g))},x=()=>{n(m=>[...m,{repo:"",slackWebhook:"",discordWebhook:""}])},p=m=>{n(f=>f.filter((b,h)=>h!==m))},d=async()=>{if(!c){a(!0);try{const m=await window.api.proofRelay.setRepoMap({map:xg(r)});n(Rd(m&&m.map?m.map:{})),l("Proof relay map saved to Vault+.")}catch(m){l(`Proof relay map save failed: ${m&&m.message?m.message:String(m)}`)}finally{a(!1)}}};return e.jsxs("section",{"data-testid":"proof-relay-map",className:"space-y-3 p-5 bg-black/30 rounded-2xl border border-white/5 shadow-inner",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-cyan-300 font-bold",children:"Proof Relay Mapping"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"Assign per-repository Slack/Discord webhooks for proof bundle notifications."})]}),e.jsx("button",{type:"button","data-testid":"proof-relay-map-add-row-btn",onClick:x,disabled:c,className:"px-3 py-1.5 rounded-lg border border-white/15 bg-white/5 text-[10px] font-mono uppercase tracking-[0.14em] text-slate-200 hover:bg-white/10 disabled:opacity-50",children:"Add Repo"})]}),e.jsxs("div",{className:"space-y-2",children:[r.length===0&&e.jsx("div",{className:"rounded-xl border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-500",children:"No repository mappings yet."}),r.map((m,f)=>e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:[e.jsx("input",{"data-testid":`proof-relay-map-repo-${f}`,value:m.repo,onChange:b=>u(f,"repo",b.target.value),placeholder:"repo slug (e.g. org/foo)",disabled:c,className:"bg-slate-900 border border-white/10 rounded-lg px-3 py-2 text-[11px] text-slate-200 font-mono outline-none focus:border-cyan-400/40 disabled:opacity-60"}),e.jsx("input",{"data-testid":`proof-relay-map-slack-${f}`,value:m.slackWebhook,onChange:b=>u(f,"slackWebhook",b.target.value),placeholder:"Slack webhook URL",disabled:c,className:"bg-slate-900 border border-white/10 rounded-lg px-3 py-2 text-[11px] text-slate-200 font-mono outline-none focus:border-cyan-400/40 disabled:opacity-60"}),e.jsx("input",{"data-testid":`proof-relay-map-discord-${f}`,value:m.discordWebhook,onChange:b=>u(f,"discordWebhook",b.target.value),placeholder:"Discord webhook URL",disabled:c,className:"bg-slate-900 border border-white/10 rounded-lg px-3 py-2 text-[11px] text-slate-200 font-mono outline-none focus:border-cyan-400/40 disabled:opacity-60"})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx("button",{type:"button","data-testid":`proof-relay-map-remove-${f}`,onClick:()=>p(f),disabled:c,className:"px-2 py-1 rounded border border-rose-300/30 bg-rose-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-rose-200 hover:bg-rose-500/20 disabled:opacity-50",children:"Remove"})})]},`${m.repo||"repo"}-${f}`))]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("button",{type:"button","data-testid":"proof-relay-map-save-btn",onClick:d,disabled:s||c,className:"px-3 py-2 rounded-lg border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-cyan-100 hover:bg-cyan-500/20 disabled:opacity-50",children:s?"Saving":"Save Mapping"}),c&&e.jsx("span",{className:"text-[10px] font-mono text-amber-300",children:"Auditor mode: relay mapping edits are disabled."})]}),o&&e.jsx("div",{className:"rounded-xl border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-300",children:o})]})}function bg(t){const r=String(t||"").trim();if(/^#[0-9a-fA-F]{6}$/.test(r))return r;if(/^#[0-9a-fA-F]{3}$/.test(r)){const[n,s,a]=r.slice(1).split("");return`#${n}${n}${s}${s}${a}${a}`}return"#22d3ee"}function hg(t,r="#22d3ee"){const n=bg(r),s=document.createElement("canvas");s.width=1200,s.height=630;const a=s.getContext("2d");if(!a)throw new Error("Canvas context unavailable.");const o=a.createLinearGradient(0,0,s.width,s.height);return o.addColorStop(0,"#020617"),o.addColorStop(1,"#0f172a"),a.fillStyle=o,a.fillRect(0,0,s.width,s.height),a.strokeStyle=`${n}99`,a.lineWidth=3,a.strokeRect(34,34,s.width-68,s.height-68),a.fillStyle=n,a.font="700 28px monospace",a.fillText("ProofForge Sweep Proof",64,90),a.fillStyle="#e2e8f0",a.font="600 22px monospace",a.fillText(`Provider: ${String(t.provider||"unknown")}`,64,170),a.fillText(`Model: ${String(t.model||"unknown")}`,64,220),a.fillText(`Models Detected: ${Number(t.modelCount||0)}`,64,270),a.fillText(`Generated: ${new Date().toISOString()}`,64,320),a.fillStyle="#94a3b8",a.font="500 18px monospace",a.fillText("Verification lane: Bridge test passed, share route minted.",64,390),a.fillStyle=`${n}2E`,a.fillRect(64,440,s.width-128,120),a.fillStyle=n,a.font="700 24px monospace",a.fillText("Top-Notch Proof Artifact",84,510),s.toDataURL("image/png")}function gg(t,r){const n=document.createElement("a");n.href=r,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n)}function yg({open:t,payload:r,onClose:n}){const[s,a]=i.useState(!1),[o,l]=i.useState(""),[c,u]=i.useState(""),[x,p]=i.useState("");if(i.useEffect(()=>{if(!t||!r)return;u(""),p(""),l("");let m=!0;return(async()=>{try{const f=await Oh({app:"ProofForge",generatedAt:new Date().toISOString(),messages:[{role:"assistant",content:["Bridge Sweep Success",`Provider: ${String(r.provider||"unknown")}`,`Model: ${String(r.model||"unknown")}`,`Models Detected: ${Number(r.modelCount||0)}`].join(` -`)}]});if(!m)return;const b=window.getComputedStyle(document.body).getPropertyValue("--accent").trim()||"#22d3ee";p(Mh(f.hash,f.fragment)),u(hg(r,b))}catch(f){if(!m)return;l(`Proof share prep failed: ${f&&f.message?f.message:String(f)}`)}})(),()=>{m=!1}},[t,r]),!t)return null;const d=async()=>{if(!(!c||!x)){a(!0);try{gg(`neuralshell-proof-${Date.now()}.png`,c),await navigator.clipboard.writeText(x),l("PNG downloaded and /share link copied to clipboard.")}catch(m){l(`Share failed: ${m&&m.message?m.message:String(m)}`)}finally{a(!1)}}};return e.jsx("div",{className:"fixed inset-0 z-[90] bg-black/70 backdrop-blur-sm flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-3xl rounded-2xl border border-cyan-400/20 bg-slate-950 p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.2em] text-cyan-300 font-bold",children:"Share Proof Badge"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"Preview then share a generated PNG + `/share/` link."})]}),e.jsx("button",{type:"button",onClick:n,className:"h-9 w-9 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),c?e.jsx($h,{src:c,alt:"Proof preview",className:"w-full rounded-xl border border-white/10 min-h-52",placeholderClassName:"rounded-xl"}):e.jsx("div",{className:"h-52 rounded-xl border border-white/10 bg-black/30 flex items-center justify-center text-[11px] font-mono text-slate-500",children:"Preparing badge preview..."}),x&&e.jsx("div",{className:"mt-3 rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-300 break-all",children:x}),e.jsxs("div",{className:"mt-4 flex items-center gap-2 justify-end",children:[e.jsx("button",{type:"button",onClick:n,className:"px-3 py-2 rounded-lg border border-white/10 text-[10px] uppercase tracking-[0.14em] font-bold text-slate-300",children:"Close"}),e.jsx("button",{type:"button","data-testid":"share-proof-btn",onClick:d,disabled:s||!c||!x,className:"px-3 py-2 rounded-lg border text-[10px] uppercase tracking-[0.14em] font-bold disabled:opacity-50",style:{borderColor:"rgb(var(--accent-rgb) / 0.38)",backgroundColor:"rgb(var(--accent-rgb) / 0.14)",color:"var(--accent)"},children:"Share"})]}),o&&e.jsx("div",{className:"mt-3 rounded-xl border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-300",children:o})]})})}function wg(t){return t==="connected"?"text-emerald-300":t==="failed"?"text-rose-300":t==="skipped"?"text-amber-300":"text-slate-400"}function vg(t,r){return r?"border-cyan-400/35 bg-cyan-500/5 ring-1 ring-cyan-400/15":t==="connected"?"border-emerald-400/20 bg-emerald-500/5":t==="failed"?"border-rose-400/20 bg-rose-500/5":t==="skipped"?"border-amber-400/20 bg-amber-500/5":"border-white/10 bg-black/30"}function jg({providerSweep:t,providerSweepRows:r,providerSweepBusy:n,providerSweepUpdatedAt:s,activeProviderId:a,onRefresh:o,hostedProxyEnabled:l,hostedProxyStatus:c,onToggleHostedProxy:u}){const x=!!(c&&c.running),p=Number(c&&c.rateCapPerMinute?c.rateCapPerMinute:60);return e.jsxs("section",{children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-widest text-emerald-300 mb-4 font-bold flex items-center justify-between",children:[e.jsx("span",{children:"Provider Health"}),e.jsx("button",{type:"button","data-testid":"settings-provider-sweep-btn",onClick:o,disabled:n,className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] font-mono uppercase tracking-[0.14em] text-emerald-200 hover:bg-emerald-500/20 disabled:opacity-50",children:n?"Checking":"Refresh"})]}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-[10px] text-slate-500 font-mono",children:[t?`${Number(t.connected||0)}/${Number(t.total||0)} connected`:"No provider sweep has been run yet.",s?` · ${s}`:""]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${l?"border-cyan-300/30 bg-cyan-500/10 text-cyan-200":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:["Hosted Proxy ",l?"On":"Off"]}),l&&e.jsxs("span",{className:"px-2 py-1 rounded border border-amber-300/30 bg-amber-500/10 text-[9px] font-mono uppercase tracking-[0.14em] text-amber-200",children:["Rate cap ",p,"/min"]}),e.jsx("button",{type:"button","data-testid":"settings-hosted-proxy-toggle-btn",onClick:u,className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] font-mono uppercase tracking-[0.14em] text-slate-200 hover:bg-white/10",children:l?"Disable Proxy":"Use Hosted Proxy"})]})]}),l&&e.jsx("div",{className:`rounded-lg border px-3 py-2 text-[10px] font-mono ${x?"border-emerald-300/30 bg-emerald-500/10 text-emerald-200":"border-amber-300/30 bg-amber-500/10 text-amber-200"}`,children:x?`Hosted proxy active at ${c.baseUrl||"localhost"}`:"Hosted proxy is enabled and will start when provider validation runs."}),e.jsxs("div",{className:"space-y-2",children:[n&&r.length===0&&[1,2,3].map(d=>e.jsx("div",{className:"h-12 rounded-lg border border-white/5 bg-white/[0.03] animate-pulse"},`sweep-skeleton-${d}`)),!n&&r.length===0&&e.jsx("div",{"data-testid":"settings-provider-sweep-empty",className:"text-center py-6 text-[10px] font-mono text-slate-500 border border-dashed border-white/10 rounded-xl",children:"No provider results yet — click Refresh to run a sweep."}),r.map(d=>{const m=String(a||"")===String(d.id||"");return e.jsxs("div",{className:`rounded-lg border px-3 py-2 transition-colors ${vg(d.status,m)}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-[10px] uppercase tracking-[0.14em] font-bold text-slate-200 flex items-center gap-1.5",children:[d.label,m&&e.jsx("span",{className:"px-1 py-0.5 rounded bg-cyan-500/15 text-cyan-200 text-[8px] font-mono border border-cyan-400/25",children:"active"})]}),e.jsx("span",{className:`text-[9px] font-mono uppercase tracking-[0.14em] ${wg(d.status)}`,children:d.status})]}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono mt-0.5",children:d.detail})]},d.id)})]})]})]})}const kg=[{id:"free",label:"Free",priceUsd:0,billingPeriod:"forever",checkout:{gumroad:"",stripe:"",manualInvoice:!1}},{id:"pro",label:"Pro",priceUsd:99,billingPeriod:"one_time",checkout:{gumroad:"https://gumroad.com/l/neuralshell-operator",stripe:"https://buy.stripe.com/test_neuralshell_pro",manualInvoice:!1}},{id:"enterprise",label:"Enterprise",priceUsd:499,billingPeriod:"annual",checkout:{gumroad:"",stripe:"",manualInvoice:!0,invoiceUrl:"mailto:enterprise@neuralshell.app?subject=NeuralShell%20Enterprise%20Invoice%20Request"}}],wn={plans:kg};function Ng(t){return t==="active"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-200":t==="grace"?"border-amber-300/30 bg-amber-500/10 text-amber-200":t==="expired"?"border-rose-300/30 bg-rose-500/10 text-rose-200":"border-slate-300/20 bg-slate-500/10 text-slate-300"}function Od(t){const r=t&&typeof t=="object"?t:{};return{present:!!r.present,status:String(r.status||"none"),planId:String(r.planId||"free"),planLabel:String(r.planLabel||"Free"),seats:Number(r.seats||1),expiresAt:String(r.expiresAt||""),graceEndsAt:String(r.graceEndsAt||""),graceRemainingDays:Number(r.graceRemainingDays||0),plans:Array.isArray(r.plans)?r.plans:[]}}function Sg(){const[t,r]=i.useState(()=>Od({})),[n,s]=i.useState(""),[a,o]=i.useState(!1),[l,c]=i.useState(""),u=i.useCallback(async()=>{try{const f=await window.api.license.status();r(Od(f))}catch(f){c(`Billing status load failed: ${f&&f.message?f.message:String(f)}`)}},[]);i.useEffect(()=>{u()},[u]);const x=i.useCallback(async f=>{const b=String(f||"").trim();if(!b){c("Paste or import a license JSON blob first.");return}o(!0);try{const h=JSON.parse(b),g=await window.api.license.activateBlob(h);g&&g.ok?(c(`License activated: ${g.planLabel} (${g.status}).`),await u()):c(`License activation failed: ${g&&g.reason?g.reason:"unknown error"}`)}catch(h){c(`License activation failed: ${h&&h.message?h.message:String(h)}`)}finally{o(!1)}},[u]),p=i.useCallback(async f=>{const b=f&&f.target&&f.target.files?f.target.files[0]:null;if(!b)return;const h=await b.text();s(h),await x(h)},[x]),d=i.useCallback(async()=>{o(!0);try{await window.api.license.clear(),s(""),c("Active license cleared. Runtime falls back to Free tier."),await u()}catch(f){c(`License clear failed: ${f&&f.message?f.message:String(f)}`)}finally{o(!1)}},[u]),m=Array.isArray(t.plans)&&t.plans.length?t.plans:Array.isArray(wn&&wn.plans)?wn.plans:[];return e.jsxs("section",{"data-testid":"billing-center",className:"space-y-3 p-5 bg-black/30 rounded-2xl border border-white/5 shadow-inner",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-emerald-300 font-bold",children:"Billing & License"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"Offline license activation with grace-state visibility."})]}),e.jsx("button",{type:"button",onClick:u,className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.14em] font-mono text-slate-200 hover:bg-white/10",children:"Refresh"})]}),e.jsxs("div",{className:`inline-flex items-center px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${Ng(t.status)}`,"data-testid":"billing-status-pill",children:[t.status," · ",t.planLabel," · ",t.seats," seat",t.seats===1?"":"s"]}),t.expiresAt&&e.jsxs("div",{className:"text-[10px] font-mono text-slate-400",children:["Expires: ",t.expiresAt,t.status==="grace"&&t.graceRemainingDays>0?` · grace ${t.graceRemainingDays}d remaining`:""]}),e.jsx("textarea",{"data-testid":"billing-license-text",value:n,onChange:f=>s(f.target.value),placeholder:"Paste signed offline license JSON...",className:"w-full min-h-24 bg-black/40 border border-white/10 rounded-xl p-3 text-[11px] font-mono text-slate-100"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button","data-testid":"billing-activate-btn",disabled:a,onClick:()=>x(n),className:"px-3 py-2 rounded-lg border border-emerald-300/30 bg-emerald-500/10 text-[10px] uppercase tracking-[0.14em] font-mono text-emerald-100 disabled:opacity-60",children:a?"Activating":"Activate License"}),e.jsxs("label",{className:"px-3 py-2 rounded-lg border border-white/15 bg-white/5 text-[10px] uppercase tracking-[0.14em] font-mono text-slate-200 cursor-pointer",children:["Import License File",e.jsx("input",{"data-testid":"billing-license-file",type:"file",accept:"application/json,.json,.license",className:"hidden",onChange:p})]}),e.jsx("button",{type:"button","data-testid":"billing-clear-btn",disabled:a,onClick:d,className:"px-3 py-2 rounded-lg border border-rose-300/30 bg-rose-500/10 text-[10px] uppercase tracking-[0.14em] font-mono text-rose-100 disabled:opacity-60",children:"Clear License"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:m.map(f=>e.jsxs("article",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[10px] font-bold text-slate-100 uppercase tracking-[0.14em]",children:f.label}),e.jsxs("div",{className:"text-[10px] font-mono text-slate-400",children:["$",Number(f.priceUsd||0)," · ",String(f.billingPeriod||"once")]}),e.jsx("div",{className:"mt-1 text-[9px] text-slate-500 break-all",children:f.checkout&&f.checkout.manualInvoice?String(f.checkout.invoiceUrl||"Manual invoice"):String(f.checkout&&(f.checkout.gumroad||f.checkout.stripe)||"Activation via checkout")})]},f.id))}),l&&e.jsx("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-300",children:l})]})}const wl="neuralshell_upgrade_prompt_dismissed_v1";function Td(t){if(typeof window>"u"||!window.localStorage)return!1;const r=JSON.parse(window.localStorage.getItem(wl)||"{}");return!!(r&&r[String(t||"")])}function Cg(t){if(typeof window>"u"||!window.localStorage)return;const r=JSON.parse(window.localStorage.getItem(wl)||"{}"),n=r&&typeof r=="object"?r:{};n[String(t||"")]=!0,window.localStorage.setItem(wl,JSON.stringify(n))}function _g({open:t,featureKey:r="",featureLabel:n="",requiredPlan:s="pro",onClose:a}){const[o,l]=i.useState(()=>Td(r));if(i.useEffect(()=>{l(Td(r))},[r]),!t||o)return null;const u=(Array.isArray(wn&&wn.plans)?wn.plans:[]).find(p=>String(p.id||"").toLowerCase()===String(s||"").toLowerCase()),x=String(u&&u.checkout&&(u.checkout.gumroad||u.checkout.stripe||u.checkout.invoiceUrl)||"");return e.jsx("div",{className:"fixed inset-0 z-[160] bg-black/70 backdrop-blur-sm flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-xl rounded-2xl border border-cyan-300/20 bg-slate-950 p-5 space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Upgrade Available"}),e.jsxs("div",{className:"text-[11px] text-slate-400 font-mono",children:[String(n||"This capability")," is available on the ",String(s||"pro").toUpperCase()," plan."]})]}),u&&e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-300",children:[u.label," · $",Number(u.priceUsd||0)," · ",String(u.billingPeriod||"one_time")]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{type:"button","data-testid":"upgrade-modal-dismiss",onClick:()=>{Cg(r),l(!0),typeof a=="function"&&a()},className:"px-3 py-2 rounded border border-white/10 bg-white/5 text-[10px] uppercase tracking-[0.14em] font-mono text-slate-200",children:"Dismiss"}),e.jsx("button",{type:"button","data-testid":"upgrade-modal-open-checkout",onClick:async()=>{x&&window.api&&window.api.system&&typeof window.api.system.openExternal=="function"&&await window.api.system.openExternal(x),typeof a=="function"&&a()},className:"px-3 py-2 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.14em] font-mono text-cyan-100",children:"Upgrade"})]})]})})}function Ag({featureLabel:t,requiredPlan:r="Pro",onUpgrade:n}){return e.jsxs("div",{"data-testid":"tier-gate-notice",className:"rounded-lg border border-amber-300/30 bg-amber-500/10 px-3 py-2",children:[e.jsxs("div",{className:"text-[10px] font-mono text-amber-100",children:[String(t||"This feature")," requires ",r,"."]}),e.jsx("button",{type:"button","data-testid":"tier-gate-upgrade-btn",onClick:n,className:"mt-2 px-2 py-1 rounded border border-amber-200/40 text-[9px] uppercase tracking-[0.14em] font-mono text-amber-100 hover:bg-amber-500/15",children:"View Upgrade"})]})}function Eg(t){const r=Number(t||0);return r>=95?"text-emerald-300":r>=80?"text-amber-300":"text-rose-300"}function Ig({agent:t}){const r=t&&typeof t=="object"?t:{},n=r.compatibility&&r.compatibility.minVersion?r.compatibility.minVersion:"",s=r.compatibility&&r.compatibility.maxVersion?r.compatibility.maxVersion:"";return e.jsxs("div",{"data-testid":`agent-reputation-${r.id||"unknown"}`,className:"rounded-lg border border-white/10 bg-black/25 px-2 py-1.5 text-[9px] font-mono text-slate-400 space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{children:["Trust: ",String(r.trustBadge||"community")]}),e.jsxs("span",{children:["Rating: ",Number(r.rating||0).toFixed(1)," (",Number(r.ratingsCount||0),")"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{children:"Install success"}),e.jsxs("span",{className:Eg(r.installSuccessRate),children:[Number(r.installSuccessRate||0),"%"]})]}),e.jsxs("div",{children:["Compat: ",n||"any",s?` -> ${s}`:"+"]})]})}function Yp(){const[t,r]=i.useState([]),[n,s]=i.useState({}),[a,o]=i.useState({capabilities:[]}),[l,c]=i.useState(""),[u,x]=i.useState(""),[p,d]=i.useState({}),[m,f]=i.useState(null),b=i.useCallback(async()=>{const[P,A,C]=await Promise.all([window.api.agents.list(),window.api.agents.receipts().catch(()=>({receipts:{}})),window.api.settings.get()]);r(Array.isArray(P)?P:[]),s(A&&A.receipts?A.receipts:{}),o(C&&typeof C=="object"?C:{capabilities:[]})},[]);i.useEffect(()=>{b().catch(P=>{c(`Agent store load failed: ${P&&P.message?P.message:String(P)}`)})},[b]);const g=(Array.isArray(a&&a.capabilities)?a.capabilities:[]).includes("marketplace_paid_install"),y=async P=>{if(P){if(P.paid&&!g){f(P);return}x(P.id);try{const A=String(p[P.id]||"").trim(),C=await window.api.agents.install(P.id,{receiptCode:A});if(C&&C.ok){const w=C.receipt&&C.receipt.code?" (receipt stored)":"";c(`Installed ${C.id}${w}`)}else c(`Install failed for ${P.id}.`);await b()}catch(A){c(`Install failed: ${A&&A.message?A.message:String(A)}`)}finally{x("")}}};return e.jsxs("section",{"data-testid":"agent-store",className:"space-y-3 p-5 bg-black/30 rounded-2xl border border-white/5 shadow-inner",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-emerald-300 font-bold",children:"Agent Store"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"Free + paid agents with local receipts and trust reputation."})]}),m&&e.jsx(Ag,{featureLabel:`Install ${m.name}`,requiredPlan:"Pro",onUpgrade:()=>f(m)}),e.jsx("div",{className:"grid grid-cols-1 gap-2",children:t.map(P=>{const A=n&&n[P.id]?n[P.id]:null;return e.jsxs("article",{className:"rounded-xl border border-white/10 bg-black/30 px-3 py-2 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-slate-100 font-semibold",children:P.name}),e.jsxs("div",{className:"text-[10px] text-slate-500 font-mono",children:[P.id,"@",P.version]}),e.jsx("div",{className:"text-[10px] text-slate-400",children:P.description}),e.jsxs("div",{className:"mt-1 text-[9px] font-mono text-slate-400",children:[P.paid?`Paid $${Number(P.priceUsd||0)}`:"Free"," · ",P.publisher||"Community"]})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx("span",{className:`text-[9px] font-mono uppercase tracking-[0.14em] ${P.verified?"text-emerald-300":"text-rose-300"}`,children:P.verified?"Verified":"Unverified"}),P.verified?e.jsx("button",{type:"button","data-testid":`agent-store-install-${P.id}`,disabled:u===P.id,onClick:()=>y(P),className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20 disabled:opacity-50",children:u===P.id?"Installing":"Install"}):e.jsx("span",{"data-testid":`agent-store-install-${P.id}`,className:"px-2 py-1 rounded border border-amber-300/25 bg-amber-500/5 text-[9px] font-mono uppercase tracking-[0.14em] text-amber-200/70",children:"Receipt required"})]})]}),P.paid&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{"data-testid":`agent-store-receipt-${P.id}`,value:p[P.id]||"",onChange:C=>d(w=>({...w,[P.id]:C.target.value})),placeholder:"Receipt code (rcpt_...)",className:"flex-1 min-w-40 bg-black/40 border border-white/10 rounded px-2 py-1 text-[10px] font-mono text-slate-100"}),e.jsx("span",{className:"text-[9px] font-mono text-slate-500",children:e.jsx("span",{"data-testid":`agent-store-receipt-status-${P.id}`,children:A?"Receipt stored":"Receipt required"})})]}),e.jsx(Ig,{agent:P})]},P.id)})}),l&&e.jsx("div",{"data-testid":"agent-store-status",className:"rounded-xl border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-300",children:l}),e.jsx(_g,{open:!!m,featureKey:m?`agent-store:${m.id}`:"",featureLabel:m?`Install ${m.name}`:"",requiredPlan:"pro",onClose:()=>f(null)})]})}const Pg=Object.freeze(Object.defineProperty({__proto__:null,default:Yp},Symbol.toStringTag,{value:"Module"})),Zp="neuralshell_referrals_v1";function Rg(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(Zp)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Og(t){typeof window>"u"||!window.localStorage||window.localStorage.setItem(Zp,JSON.stringify(t))}function Tg(){return`NSREF-${Math.random().toString(36).slice(2,10).toUpperCase()}`}function Mg(t,r){const n=String(t||"https://gumroad.com/l/neuralshell-operator").trim(),s=n.includes("?")?"&":"?";return`${n}${s}ref=${encodeURIComponent(r)}&utm_source=referral&utm_medium=partner&utm_campaign=delta9`}function Dg(t,r){const n=new Blob([`${JSON.stringify(r,null,2)} -`],{type:"application/json"}),s=URL.createObjectURL(n),a=document.createElement("a");a.href=s,a.download=t,document.body.appendChild(a),a.click(),a.remove(),URL.revokeObjectURL(s)}function $g(){const[t,r]=i.useState(()=>Rg()),[n,s]=i.useState(""),[a,o]=i.useState("https://gumroad.com/l/neuralshell-operator"),l=()=>{const u=Tg(),x=Mg(a,u),d=[{code:u,link:x,createdAt:new Date().toISOString()},...t].slice(0,200);r(d),Og(d),s(`Created referral ${u}`)},c=()=>{const u={generatedAt:new Date().toISOString(),count:t.length,rows:t};Dg(`neuralshell_referrals_${Date.now()}.json`,u),s("Referral report exported.")};return e.jsxs("section",{"data-testid":"referral-card",className:"space-y-3 p-5 bg-black/30 rounded-2xl border border-white/5 shadow-inner",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-cyan-300 font-bold",children:"Referral Program"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"Generate referral links and export local attribution reports."})]}),e.jsx("input",{"data-testid":"referral-base-url",value:a,onChange:u=>o(u.target.value),className:"w-full bg-black/40 border border-white/10 rounded px-3 py-2 text-[10px] font-mono text-slate-100",placeholder:"Checkout URL"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button","data-testid":"referral-generate-btn",onClick:l,className:"px-3 py-2 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.14em] font-mono text-cyan-100",children:"Generate Referral"}),e.jsx("button",{type:"button","data-testid":"referral-export-btn",onClick:c,className:"px-3 py-2 rounded border border-white/15 bg-white/5 text-[10px] uppercase tracking-[0.14em] font-mono text-slate-200",children:"Export Report"})]}),e.jsxs("div",{className:"space-y-1 max-h-32 overflow-auto",children:[t.slice(0,5).map(u=>e.jsxs("div",{"data-testid":`referral-row-${u.code}`,className:"rounded border border-white/10 bg-black/25 px-2 py-1 text-[9px] font-mono text-slate-300 break-all",children:[u.code," -> ",u.link]},u.code)),t.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No referral codes generated yet."})]}),n&&e.jsx("div",{"data-testid":"referral-status",className:"rounded border border-white/10 bg-black/25 px-2 py-1 text-[10px] font-mono text-slate-300",children:n})]})}const Ve=Object.freeze({EVENT:"event",DEADLINE:"deadline",REMINDER:"reminder"}),Md=Object.freeze({CONFIRMED:"confirmed",TENTATIVE:"tentative",CANCELLED:"cancelled"}),Ql=Object.freeze({LOCAL:"local",ICS:"ics",GOOGLE:"google",OUTLOOK:"outlook",CALDAV:"caldav",CALENDLY:"calendly",PROJECT:"project",TASK:"task"}),Lg=Object.freeze([{id:"local",label:"Local",status:"Active",connected:!0},{id:"ics",label:"ICS",status:"Export available / Import unavailable",connected:!1},{id:"google",label:"Google",status:"Not connected",connected:!1},{id:"outlook",label:"Outlook",status:"Not connected",connected:!1},{id:"calendly",label:"Calendly",status:"Not connected",connected:!1}]),ec="neuralshell_chrono_events_v1",vl="neuralshell:chrono-events-changed";function Ya(){return new Date().toISOString()}function Xp(t){return`${String(t||"chrono")}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Le(t,r=""){return String(t??"").trim()||r}function Dd(t){const r=new Date(t).getTime();return Number.isFinite(r)?r:Number.NaN}function Qp(t){const r=Le(t);return r?r.includes("T")?new Date(r).toISOString():new Date(`${r}T23:59:00`).toISOString():""}function Rs(t={}){const r=Dd(t.startAt),n=Dd(t.endAt),s=Le(t.createdAt,Ya()),a=Number.isFinite(r)?new Date(r).toISOString():"",o=Number.isFinite(n)?new Date(n).toISOString():a;return{id:Le(t.id,Xp("event")),type:Ve.EVENT,title:Le(t.title,"Untitled event"),description:Le(t.description),startAt:a,endAt:o,allDay:!!t.allDay,category:Le(t.category),location:Le(t.location),source:Ql.LOCAL,sourceId:Le(t.sourceId),status:Object.values(Md).includes(t.status)?t.status:Md.CONFIRMED,reminders:Array.isArray(t.reminders)?t.reminders:[],createdAt:s,updatedAt:Le(t.updatedAt,s)}}function Da(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(ec)||"[]");return Array.isArray(t)?t.map(Rs).filter(r=>r.title&&r.startAt&&r.endAt).sort((r,n)=>r.startAt.localeCompare(n.startAt)):[]}catch{return[]}}function Bg(t=[]){const r=(Array.isArray(t)?t:[]).map(Rs).filter(n=>n.title&&n.startAt&&n.endAt).sort((n,s)=>n.startAt.localeCompare(s.startAt));if(typeof window<"u"&&window.localStorage)try{window.localStorage.setItem(ec,JSON.stringify(r))}catch{}try{window.dispatchEvent(new CustomEvent(vl,{detail:r}))}catch{}return r}function Fg(t=[],r={}){const n=Rs(r),s=(Array.isArray(t)?t:[]).map(Rs),a=s.findIndex(o=>o.id===n.id);return a>=0?s[a]={...n,updatedAt:Ya()}:s.push(n),s.sort((o,l)=>o.startAt.localeCompare(l.startAt))}function Ug(t){const r=()=>{typeof t=="function"&&t(Da())},n=s=>{(!s||s.key===ec)&&r()};return window.addEventListener("storage",n),window.addEventListener(vl,r),()=>{window.removeEventListener("storage",n),window.removeEventListener(vl,r)}}function zg(t={}){const r=Le(t.createdAt,Ya()),n=Le(t.date||t.dueAt);return{id:Le(t.id,`deadline-${n}-${t.title||"item"}`),type:Ve.DEADLINE,title:Le(t.title,"Untitled deadline"),dueAt:Qp(n),date:n,projectId:Le(t.projectId),priority:["low","normal","high","critical"].includes(String(t.priority||"").toLowerCase())?String(t.priority).toLowerCase():"normal",completed:!!t.completed,source:Ql.LOCAL,createdAt:r,updatedAt:Le(t.updatedAt,r),raw:t}}function Hg(t={}){const r=Le(t.createdAt,Ya()),n=Le(t.dueDate);return{id:`workpad-${Le(t.id,Xp("task"))}`,type:Ve.DEADLINE,title:Le(t.title,"Workpad task"),dueAt:Qp(n),date:n,projectId:Le(t.projectId),priority:String(t.priority||"").toLowerCase()==="high"?"high":"normal",completed:!!t.done,source:Ql.TASK,createdAt:r,updatedAt:Le(t.updatedAt,r),raw:t}}function e0({events:t=[],deadlines:r=[],workpadTasks:n=[]}={}){const s=[...Array.isArray(t)?t.map(Rs):[],...Array.isArray(r)?r.map(zg):[],...Array.isArray(n)?n.map(Hg):[]].filter(o=>o&&o.id&&o.title),a=new Set;return s.filter(o=>{const l=`${o.type}:${o.id}`;return a.has(l)?!1:(a.add(l),!0)})}const Za="neuralshell_proof_timestamps_v1",jl="neuralshell:proof-timestamps-changed",Wg=Object.freeze(["session_started","session_paused","session_resumed","session_ended","mode_changed","calendar_linked","event_created","deadline_created","deadline_completed","manual_note"]),Kg=Object.freeze(["sessionhud","chronohud","timeledger","calendar","system"]);let t0=[];function Vg(t){return`${String(t)}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function kt(t,r=""){return String(t??"").trim()||r}function Gg(t,r=new Date().toISOString()){const n=String(t||"").trim();if(!n)return r;const s=new Date(n);return Number.isFinite(s.getTime())?s.toISOString():r}function r0(t){return t||(typeof window<"u"&&window.localStorage?window.localStorage:null)}function n0(t){const r=r0(t);if(!r)return[...t0];try{const n=JSON.parse(r.getItem(Za)||"[]");return Array.isArray(n)?n:[]}catch{return[]}}function Jg(t,r){const n=i0(t),s=r0(r);if(!s)return t0=n,n;try{s.setItem(Za,JSON.stringify(n))}catch{}return n}function qg(t){try{typeof window<"u"&&window.dispatchEvent(new CustomEvent(jl,{detail:t}))}catch{}}function s0(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local"}catch{return"local"}}function a0(t){const r=t instanceof Date?t:new Date(t);return Number.isFinite(r.getTime())?r.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):""}function o0(t={}){const r=Gg(t.createdAt),n=new Date(r),s=Wg.includes(t.eventType)?t.eventType:"manual_note",a=Kg.includes(t.source)?t.source:"system";return{id:kt(t.id,Vg("proof")),createdAt:r,localLabel:kt(t.localLabel,a0(n)),timezone:kt(t.timezone,s0()),eventType:s,source:a,projectId:kt(t.projectId),projectName:kt(t.projectName),sessionId:kt(t.sessionId),calendarItemId:kt(t.calendarItemId),calendarItemType:kt(t.calendarItemType),title:kt(t.title,s.replace(/_/g," ")),details:kt(t.details)}}function i0(t=[]){return(Array.isArray(t)?t:[]).map(o0).filter(r=>r.id&&r.createdAt&&r.title).sort((r,n)=>r.createdAt.localeCompare(n.createdAt))}function Yg(t={},r={}){const n=r.now instanceof Date?r.now:new Date(r.now||Date.now()),s=o0({...t,createdAt:t.createdAt||n.toISOString(),localLabel:t.localLabel||a0(n),timezone:t.timezone||s0()}),a=Jg([...n0(r.storage),s],r.storage);return qg(a),s}function ur(t={},r={}){const n=t&&typeof t=="object"?t:{},s=kt(n.date),a=n.start?new Date(n.start).getTime():Number.NaN,o=n.end?new Date(n.end).getTime():Number.NaN,l=Number(n.limit),c=n.order!=="asc";let u=i0(n0(r.storage));return s&&(u=u.filter(x=>x.createdAt.slice(0,10)===s)),Number.isFinite(a)&&(u=u.filter(x=>new Date(x.createdAt).getTime()>=a)),Number.isFinite(o)&&(u=u.filter(x=>new Date(x.createdAt).getTime()<=o)),c&&(u=[...u].reverse()),Number.isFinite(l)&&l>0?u.slice(0,Math.floor(l)):u}function l0(t){const r=()=>{typeof t=="function"&&t(ur())};if(typeof window>"u")return()=>{};const n=s=>{(!s||s.key===Za)&&r()};return window.addEventListener("storage",n),window.addEventListener(jl,r),()=>{window.removeEventListener("storage",n),window.removeEventListener(jl,r)}}const Xa="neuralshell_time_ledger_v1",kl="neuralshell:time-ledger-changed",$a=Object.freeze(["focus","planning","review","admin"]),Zg=Object.freeze(["active","paused","ended"]);function Xg(){return new Date().toISOString()}function c0(t){return`${String(t)}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function ia(t,r=""){return String(t??"").trim()||r}function Qg(t){const r=String(t||"").trim().toLowerCase();return $a.includes(r)?r:$a[0]}function Pi(t,r=""){const n=String(t||"").trim();if(!n)return r;const s=new Date(n);return Number.isFinite(s.getTime())?s.toISOString():r}function Ri(t){const r=Number(t);return Number.isFinite(r)&&r>0?Math.round(r):0}function $d(t){const r=new Date(t).getTime();return Number.isFinite(r)?r:Number.NaN}function La(t,r=new Date){const n=$d(t),s=r instanceof Date?r.getTime():$d(r);return!Number.isFinite(n)||!Number.isFinite(s)||s<=n?0:s-n}function d0(t){return typeof window<"u"&&window.localStorage?window.localStorage:null}function ey(t){try{typeof window<"u"&&window.dispatchEvent(new CustomEvent(kl,{detail:t}))}catch{}}function ht(){return{version:1,sessions:[]}}function Mr(t={}){const r=Pi(t.startedAt,Xg()),n=Pi(t.endedAt),s=Pi(t.lastActiveAt,n||r),a=Ri(t.activeDurationMs),o=Ri(t.idleDurationMs),l=a+o,c=n?"ended":Zg.includes(t.status)?t.status:"active";return{id:ia(t.id,c0("session")),projectId:ia(t.projectId),projectName:ia(t.projectName),startedAt:r,endedAt:n,lastActiveAt:s,durationMs:Math.max(Ri(t.durationMs),l),activeDurationMs:a,idleDurationMs:o,mode:Qg(t.mode),source:ia(t.source,"local"),status:c}}function Ke(t={}){const r=t&&typeof t=="object"?t:{};return{version:1,sessions:Array.isArray(r.sessions)?r.sessions.map(Mr).filter(s=>s.id&&s.startedAt).sort((s,a)=>s.startedAt.localeCompare(a.startedAt)):[]}}function Cn(t){const r=d0();if(!r)return ht();try{const n=JSON.parse(r.getItem(Xa)||"{}");return Ke(n)}catch{return ht()}}function ty(t,r){const n=Ke(t),s=d0();if(s)try{s.setItem(Xa,JSON.stringify(n))}catch{}return ey(n),n}function u0(t){const r=()=>{typeof t=="function"&&t(Cn())};if(typeof window>"u")return()=>{};const n=s=>{(!s||s.key===Xa)&&r()};return window.addEventListener("storage",n),window.addEventListener(kl,r),()=>{window.removeEventListener("storage",n),window.removeEventListener(kl,r)}}function ry(t=ht()){return Ke(t).sessions.filter(n=>!n.endedAt).sort((n,s)=>s.startedAt.localeCompare(n.startedAt))[0]||null}function ny(t=ht(),r={},n=new Date){if(ry(t))return Ke(t);const a=(n instanceof Date?n:new Date(n)).toISOString(),o=Mr({id:r.id||c0("session"),projectId:r.projectId,projectName:r.projectName,startedAt:a,lastActiveAt:a,mode:r.mode,source:r.source||"local",status:"active"});return Ke({sessions:[...Ke(t).sessions,o]})}function sy(t=ht(),r,n=new Date){const s=n instanceof Date?n:new Date(n),a=s.toISOString(),o=Ke(t).sessions.map(l=>{if(l.id!==r||l.status!=="active"||l.endedAt)return l;const c=l.activeDurationMs+La(l.lastActiveAt,s),u=l.idleDurationMs;return Mr({...l,lastActiveAt:a,activeDurationMs:c,idleDurationMs:u,durationMs:c+u,status:"paused"})});return Ke({sessions:o})}function ay(t=ht(),r,n=new Date){const s=n instanceof Date?n:new Date(n),a=s.toISOString(),o=Ke(t).sessions.map(l=>{if(l.id!==r||l.status!=="paused"||l.endedAt)return l;const c=l.activeDurationMs,u=l.idleDurationMs+La(l.lastActiveAt,s);return Mr({...l,lastActiveAt:a,activeDurationMs:c,idleDurationMs:u,durationMs:c+u,status:"active"})});return Ke({sessions:o})}function oy(t=ht(),r,n=new Date){const s=n instanceof Date?n:new Date(n),a=s.toISOString(),o=Ke(t).sessions.map(l=>{if(l.id!==r||l.endedAt)return l;const c=l.status==="active"?La(l.lastActiveAt,s):0,u=l.status==="paused"?La(l.lastActiveAt,s):0,x=l.activeDurationMs+c,p=l.idleDurationMs+u;return Mr({...l,endedAt:a,lastActiveAt:a,activeDurationMs:x,idleDurationMs:p,durationMs:x+p,status:"ended"})});return Ke({sessions:o})}function iy(t=ht(),r,n){const s=Ke(t).sessions.map(a=>a.id!==r||a.endedAt?a:Mr({...a,mode:n}));return Ke({sessions:s})}const p0=864e5;function tc(t){const r=new Date(t);return Number.isFinite(r.getTime())?r:null}function m0(t){const r=t instanceof Date?new Date(t.getTime()):tc(t);return r?(r.setHours(0,0,0,0),r):null}function ly(t){const r=m0(t);return r?(r.setDate(r.getDate()-r.getDay()),r):null}function x0(t,r,n){const s=tc(t.startedAt);return!!(s&&s.getTime()>=r.getTime()&&s.getTime()!n.endedAt).sort((n,s)=>s.startedAt.localeCompare(n.startedAt))[0]||null}function cy(t=ht(),r=new Date){const n=m0(r);if(!n)return 0;const s=new Date(n.getTime()+p0);return Ke(t).sessions.filter(a=>x0(a,n,s)).reduce((a,o)=>a+Or(o,r).activeDurationMs,0)}function dy(t=ht(),r=new Date){const n=ly(r);if(!n)return 0;const s=new Date(n.getTime()+p0*7);return Ke(t).sessions.filter(a=>x0(a,n,s)).reduce((a,o)=>a+Or(o,r).activeDurationMs,0)}function uy(t=ht(),r,n=new Date){const s=String(r||"").trim();return s?Ke(t).sessions.filter(a=>String(a.projectId||"").trim()===s).reduce((a,o)=>a+Or(o,n).activeDurationMs,0):0}function cr(t){const r=Math.max(0,Math.floor((Number(t)||0)/1e3)),n=Math.floor(r/3600),s=Math.floor(r%3600/60),a=r%60;return n>0?`${n}h ${String(s).padStart(2,"0")}m`:s>0?`${s}m ${String(a).padStart(2,"0")}s`:`${a}s`}const py=864e5;function Os(t){const r=new Date(t);return Number.isFinite(r.getTime())?r:null}function f0(t=new Date){const r=t instanceof Date?t:Os(t);return r?[r.getFullYear(),String(r.getMonth()+1).padStart(2,"0"),String(r.getDate()).padStart(2,"0")].join("-"):""}function my(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local"}catch{return"local"}}function Rr(t){return t?t.type==="event"?Os(t.startAt):Os(t.dueAt||t.remindAt||t.createdAt):null}function xy(t){return t?t.type==="event"?Os(t.endAt||t.startAt):Rr(t):null}function Ld(t,r){return f0(t)===r}function Bd(t,r,n){var a;const s=new Map;return t.forEach(o=>{const l=String(r(o)||"").trim();l&&s.set(l,(s.get(l)||0)+Or(o,n).activeDurationMs)}),((a=[...s.entries()].sort((o,l)=>l[1]-o[1]||o[0].localeCompare(l[0]))[0])==null?void 0:a[0])||""}function fy(t,r){const n=r instanceof Date?r.getTime():Date.now(),s=(Array.isArray(t)?t:[]).filter(l=>{const c=Rr(l);return!c||l.type==="deadline"&&l.completed?!1:(xy(l)||c).getTime()>=n}).sort((l,c)=>Rr(l).getTime()-Rr(c).getTime())[0];if(!s)return"No upcoming local items";const a=Rr(s),o=a?a.toLocaleString([],{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"unscheduled";return`${s.title||"Untitled item"} ${o}`}function b0({sessions:t=[],calendarItems:r=[],proofTimestamps:n=[],now:s=new Date,date:a}={}){const o=a||f0(s),l=new Date(`${o}T00:00:00`),c=new Date(l.getTime()+py),u=Array.isArray(t)?t:[],x=Array.isArray(r)?r:[],p=Array.isArray(n)?n:[],d=u.filter(y=>{const P=Os(y.startedAt);return P&&P.getTime()>=l.getTime()&&P.getTime()Ld(y.createdAt,o)),f=x.filter(y=>Ld(Rr(y),o)),b=f.filter(y=>y.type==="deadline"),h=b.filter(y=>{if(y.completed)return!1;const P=Rr(y);return P&&P.getTime()<(s instanceof Date?s.getTime():Date.now())}),g=d.reduce((y,P)=>{const A=Or(P,s);return y.totalSessionMs+=A.durationMs,y.activeMs+=A.activeDurationMs,y.idleMs+=A.idleDurationMs,y.longestSessionMs=Math.max(y.longestSessionMs,A.durationMs),y},{totalSessionMs:0,activeMs:0,idleMs:0,longestSessionMs:0});return{date:o,timezone:my(),totalSessionMs:g.totalSessionMs,activeMs:g.activeMs,idleMs:g.idleMs,sessionCount:d.length,longestSessionMs:g.longestSessionMs,topProject:Bd(d,y=>y.projectName||y.projectId,s),topMode:Bd(d,y=>y.mode,s),eventsToday:f.filter(y=>y.type==="event").length,deadlinesDue:b.length,deadlinesCompleted:b.filter(y=>y.completed).length,overdueDeadlines:h.length,proofEventCount:m.length,linkedCalendarItems:new Set(m.map(y=>y.calendarItemId).filter(Boolean)).size,nextThreat:fy(x,s)}}const h0="neuralshell_timeproof_integrity_v1",rc="SHA-256",by="local-tamper-evident",hy=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Nl(t){return t==null?null:t instanceof Date?Number.isFinite(t.getTime())?t.toISOString():null:Array.isArray(t)?t.map(Nl):typeof t=="number"?Number.isFinite(t)?t:null:typeof t=="string"||typeof t=="boolean"?t:typeof t!="object"?null:Object.keys(t).sort().reduce((r,n)=>{const s=t[n];return s!==void 0&&typeof s!="function"&&typeof s!="symbol"&&(r[n]=Nl(s)),r},{})}function gy(t){const r=String(t??"");if(typeof globalThis.TextEncoder=="function")return Array.from(new globalThis.TextEncoder().encode(r));const n=[];for(let s=0;s65535&&(s+=1),a<=127?n.push(a):a<=2047?(n.push(192|a>>>6),n.push(128|a&63)):a<=65535?(n.push(224|a>>>12),n.push(128|a>>>6&63),n.push(128|a&63)):(n.push(240|a>>>18),n.push(128|a>>>12&63),n.push(128|a>>>6&63),n.push(128|a&63))}return n}function Pt(t,r){return t>>>r|t<<32-r}function it(...t){return t.reduce((r,n)=>r+n>>>0,0)}function g0(t){return{algorithm:rc,canonicalPayload:String(t.canonicalPayload||""),chainIndex:Number(t.chainIndex),createdAt:String(t.createdAt||""),payloadHash:String(t.payloadHash||""),previousEntryHash:t.previousEntryHash||null,sourceId:String(t.sourceId||""),sourceType:String(t.sourceType||"")}}function y0(t,r=new Date().toISOString()){const n=String(t||"").trim(),s=n?new Date(n):null;return s&&Number.isFinite(s.getTime())?s.toISOString():r}function yy(t){return typeof window<"u"&&window.localStorage?window.localStorage:null}function Sl(t){return JSON.stringify(Nl(t))}function Ba(t){const r=gy(t),n=r.length*8;for(r.push(128);r.length%64!==56;)r.push(0);const s=Math.floor(n/4294967296),a=n>>>0;for(let c=24;c>=0;c-=8)r.push(s>>>c&255);for(let c=24;c>=0;c-=8)r.push(a>>>c&255);const o=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],l=new Array(64);for(let c=0;c>>0}for(let g=16;g<64;g+=1){const y=Pt(l[g-15],7)^Pt(l[g-15],18)^l[g-15]>>>3,P=Pt(l[g-2],17)^Pt(l[g-2],19)^l[g-2]>>>10;l[g]=it(l[g-16],y,l[g-7],P)}let[u,x,p,d,m,f,b,h]=o;for(let g=0;g<64;g+=1){const y=Pt(m,6)^Pt(m,11)^Pt(m,25),P=m&f^~m&b,A=it(h,y,P,hy[g],l[g]),C=Pt(u,2)^Pt(u,13)^Pt(u,22),w=u&x^u&p^x&p,j=it(C,w);h=b,b=f,f=m,m=it(d,A),d=p,p=x,x=u,u=it(A,j)}o[0]=it(o[0],u),o[1]=it(o[1],x),o[2]=it(o[2],p),o[3]=it(o[3],d),o[4]=it(o[4],m),o[5]=it(o[5],f),o[6]=it(o[6],b),o[7]=it(o[7],h)}return o.map(c=>c.toString(16).padStart(8,"0")).join("")}function wy(t={},r=null){const n=t&&typeof t=="object"?t:{},s=n.payload!==void 0?n.payload:n.record!==void 0?n.record:n,a=n.canonicalPayload||Sl(s),o=Ba(a),l=r?Number(r.chainIndex)+1:0,c={id:String(n.id||`integrity-${l}-${o.slice(0,12)}`),chainIndex:l,createdAt:y0(n.createdAt||(s==null?void 0:s.createdAt)),sourceId:String(n.sourceId||(s==null?void 0:s.id)||n.id||""),sourceType:String(n.sourceType||"proofTimestamp"),algorithm:rc,canonicalPayload:a,payloadHash:o,previousEntryHash:r?r.entryHash:null,entryHash:"",verificationStatus:"verified"};return c.entryHash=Ba(Sl(g0(c))),c}function w0(t=[]){const r=(Array.isArray(t)?t:[]).filter(s=>s&&typeof s=="object").sort((s,a)=>String(s.createdAt||"").localeCompare(String(a.createdAt||""))||String(s.id||"").localeCompare(String(a.id||""))),n=[];return r.forEach(s=>{n.push(wy({createdAt:s.createdAt,payload:s,sourceId:s.id,sourceType:"proofTimestamp"},n[n.length-1]||null))}),n}function vy(t=[]){if(!Array.isArray(t)||t.length===0)return{ok:!0,status:"empty",errors:[],entryCount:0};const r=[];let n=null;return t.forEach((s,a)=>{if(!s||typeof s!="object"){r.push({code:"broken_sequence",index:a}),n=null;return}s.chainIndex!==a&&r.push({code:"wrong_chain_index",index:a,expected:a,actual:s.chainIndex}),(s.previousEntryHash||null)!==n&&r.push({code:"previous_hash_mismatch",index:a});const o=Ba(String(s.canonicalPayload||""));s.payloadHash!==o&&r.push({code:"payload_hash_mismatch",index:a});const l=Ba(Sl(g0({...s,payloadHash:o})));s.entryHash!==l&&r.push({code:"entry_hash_mismatch",index:a}),n=s.entryHash||null}),{ok:r.length===0,status:r.length===0?"verified":"mismatch",errors:r,entryCount:t.length}}function v0(t=[],{now:r=new Date}={}){const n=vy(t);return{algorithm:rc,status:n.status,entryCount:Array.isArray(t)?t.length:0,firstEntryHash:Array.isArray(t)&&t[0]?t[0].entryHash:null,lastEntryHash:Array.isArray(t)&&t.length?t[t.length-1].entryHash:null,checkedAt:y0(r),claim:by}}function jy(t=[],r){const n=yy(),s=Array.isArray(t)?t:[];if(n)try{n.setItem(h0,JSON.stringify(s))}catch{}return s}function ky(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local"}catch{return"local"}}function Ny(t){const r=t instanceof Date?t:new Date(t||Date.now());return Number.isFinite(r.getTime())?r:new Date}function Cl({workflowId:t="",now:r=new Date}={}){const n=Ny(r),s=Cn(),a=ur({order:"asc"}),o=w0(a);jy(o);const l=et(t||void 0),c=e0({events:Da(),deadlines:Qt(),workpadTasks:(l.tasks||[]).filter(u=>!u.done&&u.dueDate)});return{exportedAt:n.toISOString(),timezone:ky(),sessions:s.sessions,proofTimeline:a,daySummary:b0({sessions:s.sessions,calendarItems:c,proofTimestamps:a,now:n}),integrity:v0(o,{now:n}),storageKeys:{timeLedger:Xa,proofTimestamps:Za,integrity:h0}}}function Sy(){const[t,r]=i.useState(!1),[n,s]=i.useState(!1),[a,o]=i.useState(""),l=async()=>{r(!0),o("");try{const c=window.api&&window.api.support&&typeof window.api.support.exportBundle=="function"?await window.api.support.exportBundle({includeUserText:!!n,workpadSnapshots:yl(),timeProof:Cl()}):await window.api.invoke("support:exportBundle",{includeUserText:!!n,workpadSnapshots:yl(),timeProof:Cl()});c&&c.ok?(o(`Bundle exported: ${c.outputPath}`),window.dispatchEvent(new window.CustomEvent("neuralshell:support-bundle-exported",{detail:{outputPath:String(c.outputPath||""),sha256:String(c.sha256||"")}}))):o("Bundle export failed.")}catch(c){o(`Export failed: ${c&&c.message?c.message:String(c)}`)}finally{r(!1)}};return e.jsxs("section",{"data-testid":"support-bundle-card",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-amber-300 mb-4 font-bold",children:"Support Bundle"}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-3",children:[e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Export sanitized diagnostics bundle (ZIP + SHA-256). Secrets are redacted by default."}),e.jsxs("label",{className:"flex items-center gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{"data-testid":"support-bundle-include-user-text",type:"checkbox",checked:n,onChange:c=>s(c.target.checked)}),"Include user text (not recommended)"]}),e.jsx("button",{type:"button","data-testid":"support-bundle-export-btn",disabled:t,onClick:l,className:"px-3 py-2 rounded-xl border border-amber-300/30 bg-amber-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-amber-200 hover:bg-amber-500/20 disabled:opacity-60",children:t?"Exporting":"Export Support Bundle"}),a&&e.jsx("div",{className:"text-[10px] font-mono text-slate-300 break-all",children:a})]})]})}function he(t,r=0){const n=Number(t);return Number.isFinite(n)?n:Number(r||0)}function Fd(t){const r=[];let n="",s=!1;for(let a=0;aString(s||"").trim().length>0);if(!r.length)return[];const n=Fd(r[0]).map(s=>String(s||"").trim());return n.length?r.slice(1).map(s=>{const a=Fd(s),o={};return n.forEach((l,c)=>{l&&(o[l]=String(a[c]||"").trim())}),o}):[]}function Cy(t=""){const r=JSON.parse(String(t||"{}"));return Array.isArray(r)?r:r&&typeof r=="object"?Array.isArray(r.rows)?r.rows:Array.isArray(r.records)?r.records:Array.isArray(r.items)?r.items:[r]:[]}function Ds(t="",r=""){if(String(r||"").toLowerCase().endsWith(".csv"))return Ud(t);try{return Cy(t)}catch{return Ud(t)}}function pt(t){return new Promise((r,n)=>{const s=new FileReader;s.onerror=()=>n(new Error("Unable to read local file.")),s.onload=()=>r(String(s.result||"")),s.readAsText(t)})}function je(t,r){const n=new Blob([`${JSON.stringify(r,null,2)} -`],{type:"application/json"}),s=URL.createObjectURL(n),a=document.createElement("a");a.href=s,a.download=String(t||"export.json"),a.click(),URL.revokeObjectURL(s)}function $s(t,r){const n=new Blob([String(r||"")],{type:"text/plain"}),s=URL.createObjectURL(n),a=document.createElement("a");a.href=s,a.download=String(t||"export.txt"),a.click(),URL.revokeObjectURL(s)}function nc(t,r=""){const n=String(t||"").trim();if(!n)return r;const s=new Date(n);return Number.isNaN(s.getTime())?r:s.toISOString().slice(0,10)}async function _y(){if(window.api&&window.api.diagnostics&&typeof window.api.diagnostics.exportLog=="function")return window.api.diagnostics.exportLog();if(window.api&&typeof window.api.invoke=="function")return window.api.invoke("execution:exportLog");throw new Error("Execution log export is unavailable in this build.")}function Ay(){const[t,r]=i.useState(!1),[n,s]=i.useState(""),a=async()=>{r(!0),s("");try{const o=await _y(),l=Date.now();je(`neuralshell-execution-log-${l}.json`,o||{});const c=Array.isArray(o&&o.diagnostics)?o.diagnostics.length:0,u=Array.isArray(o&&o.actionOutcomes)?o.actionOutcomes.length:0;s(`Exported ${c} diagnostic event(s) and ${u} action outcome(s).`)}catch(o){s(`Export failed: ${o&&o.message?o.message:String(o)}`)}finally{r(!1)}};return e.jsxs("section",{"data-testid":"execution-log-export-card",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-cyan-300 mb-4 font-bold",children:"Execution Log"}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-3",children:[e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Export orchestration diagnostics and action outcomes (JSON). No secrets included."}),e.jsx("button",{type:"button","data-testid":"execution-log-export-btn",disabled:t,onClick:a,className:"px-3 py-2 rounded-xl border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-cyan-100 hover:bg-cyan-500/20 disabled:opacity-60",children:t?"Exporting":"Export Execution Log"}),n&&e.jsx("div",{className:"text-[10px] font-mono text-slate-300 break-all",children:n})]})]})}const Ey=["network","llm","security","runtime","trust","observability","general"],Iy={network:{label:"Network",tone:"text-sky-300"},llm:{label:"Models & Bridge",tone:"text-emerald-300"},security:{label:"Security",tone:"text-rose-300"},runtime:{label:"Runtime",tone:"text-violet-300"},trust:{label:"Trust",tone:"text-amber-300"},observability:{label:"Telemetry",tone:"text-fuchsia-300"},general:{label:"General",tone:"text-slate-300"}},zd={failed:0,warning:1,passed:2,skipped:3};function Py(t){return t==="passed"?"border-emerald-400/20 bg-emerald-500/5":t==="failed"?"border-rose-400/25 bg-rose-500/8 ring-1 ring-rose-400/10":t==="warning"?"border-amber-400/20 bg-amber-500/5":"border-white/10 bg-black/25"}function Ry(t){return t==="passed"?"text-emerald-300":t==="failed"?"text-rose-300":t==="warning"?"text-amber-300":"text-slate-400"}function Oy(t){return t==="passed"?"bg-emerald-400 shadow-[0_0_8px_rgba(52,211,153,0.45)]":t==="failed"?"bg-rose-400 shadow-[0_0_8px_rgba(251,113,133,0.45)]":t==="warning"?"bg-amber-400 shadow-[0_0_8px_rgba(251,191,36,0.35)]":"bg-slate-500"}function Ty(t){return t==="passed"?"OK":t==="failed"?"FAIL":t==="warning"?"WARN":"SKIP"}function My(t){const r=new Map;for(const n of t){const s=String(n.category||"general");r.has(s)||r.set(s,[]),r.get(s).push(n)}for(const[,n]of r)n.sort((s,a)=>{const o=zd[s.status]??9,l=zd[a.status]??9;return o!==l?o-l:String(s.label||"").localeCompare(String(a.label||""))});return Ey.filter(n=>r.has(n)).map(n=>({id:n,...Iy[n],checks:r.get(n)}))}function Dy(t){return t.some(r=>r.status==="failed"||r.status==="warning")}function la({label:t,value:r,tone:n}){const s={emerald:"border-emerald-400/25 bg-emerald-500/10 text-emerald-200",rose:"border-rose-400/25 bg-rose-500/10 text-rose-200",amber:"border-amber-400/25 bg-amber-500/10 text-amber-200",slate:"border-white/10 bg-black/30 text-slate-300"}[n]||"border-white/10 bg-black/30 text-slate-300";return e.jsxs("div",{className:`rounded-xl border px-3 py-2 text-center ${s}`,children:[e.jsx("div",{className:"text-[18px] font-bold leading-none tabular-nums",children:r}),e.jsx("div",{className:"text-[8px] uppercase tracking-[0.18em] font-mono mt-1 opacity-80",children:t})]})}function $y({check:t}){return e.jsx("div",{"data-testid":`system-health-row-${t.id}`,className:`rounded-xl border px-3 py-2.5 transition-colors ${Py(t.status)}`,children:e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("span",{className:`mt-1.5 h-2 w-2 rounded-full shrink-0 ${Oy(t.status)}`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium text-slate-100 leading-snug",children:t.label}),e.jsxs("span",{className:`text-[9px] font-mono uppercase tracking-[0.14em] shrink-0 ${Ry(t.status)}`,children:[Ty(t.status),Number.isFinite(t.latencyMs)?` · ${t.latencyMs}ms`:""]})]}),t.detail&&e.jsx("div",{className:"text-[10px] font-mono text-slate-400 mt-1 leading-relaxed line-clamp-3",children:t.detail})]})]})})}function Ly(){const[t,r]=i.useState(!1),[n,s]=i.useState(null),[a,o]=i.useState(!1),[l,c]=i.useState(""),u=i.useCallback(async()=>{if(!(window.api&&window.api.system&&typeof window.api.system.runHealthCheck=="function")){c("System health check is unavailable in this runtime.");return}r(!0),c("");try{const f=await window.api.system.runHealthCheck();s(f&&typeof f=="object"?f:null),f||c("Health check returned no data.")}catch(f){s(null),c(`Health check failed: ${f&&f.message?f.message:String(f)}`)}finally{r(!1)}},[]);i.useEffect(()=>{u()},[u]);const x=Array.isArray(n&&n.checks)?n.checks:[],p=a?x.filter(f=>f.status==="failed"||f.status==="warning"):x,d=My(p),m=x.filter(f=>f.status==="failed"||f.status==="warning").length;return e.jsxs("section",{"data-testid":"system-health-check-card",children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-widest text-cyan-300 mb-4 font-bold flex items-center justify-between gap-2",children:[e.jsx("span",{children:"System Health Check"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"system-health-filter-btn",onClick:()=>o(f=>!f),className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] transition-colors ${a?"border-amber-300/35 bg-amber-500/10 text-amber-200":"border-white/15 bg-white/5 text-slate-300 hover:bg-white/10"}`,children:a?"Show all":"Issues only"}),e.jsxs("button",{type:"button","data-testid":"system-health-run-btn",onClick:u,disabled:t,className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono uppercase tracking-[0.14em] text-cyan-200 hover:bg-cyan-500/20 disabled:opacity-50 inline-flex items-center gap-1.5",children:[t&&e.jsx("span",{className:"inline-block h-2 w-2 rounded-full border border-cyan-200/60 border-t-transparent animate-spin"}),t?"Checking":"Run again"]})]})]}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[12px] font-medium text-slate-200",children:"Connectivity, models, vault, and runtime diagnostics"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono mt-1 leading-relaxed",children:"Run this when Wi‑Fi, provider keys, or local Ollama look wrong."})]}),n&&e.jsxs("div",{"data-testid":"system-health-summary",className:`shrink-0 rounded-xl border px-3 py-2 text-[10px] font-mono ${n.ok?"border-emerald-400/30 bg-emerald-500/10 text-emerald-200":"border-amber-400/30 bg-amber-500/10 text-amber-100"}`,children:[e.jsx("div",{className:"font-bold uppercase tracking-[0.14em]",children:n.ok?"All critical checks passed":`${m} issue${m===1?"":"s"} found`}),n.generatedAt&&e.jsx("div",{className:"text-slate-400 mt-0.5",children:Pb(n.generatedAt)})]})]}),n&&e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:[e.jsx(la,{label:"Passed",value:n.passed,tone:"emerald"}),e.jsx(la,{label:"Failed",value:n.failed,tone:"rose"}),e.jsx(la,{label:"Warnings",value:n.warnings,tone:"amber"}),e.jsx(la,{label:"Skipped",value:n.skipped,tone:"slate"})]}),t&&!x.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500 py-6 text-center rounded-xl border border-dashed border-white/10",children:"Running diagnostics…"}),!t&&a&&!p.length&&x.length>0&&e.jsx("div",{className:"text-[10px] font-mono text-emerald-300 py-4 text-center rounded-xl border border-emerald-400/20 bg-emerald-500/5",children:"No warnings or failures — everything looks healthy."}),!t&&!x.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500 py-4 text-center rounded-xl border border-dashed border-white/10",children:"No results yet. Run the health check."}),e.jsx("div",{className:"space-y-3",children:d.map(f=>e.jsxs("details",{open:Dy(f.checks)||f.checks.length<=2,className:"rounded-xl border border-white/5 bg-black/20 overflow-hidden",children:[e.jsxs("summary",{className:"cursor-pointer list-none px-3 py-2.5 flex items-center justify-between gap-2 hover:bg-white/[0.03] transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:`text-[10px] uppercase tracking-[0.16em] font-bold ${f.tone||"text-slate-300"}`,children:f.label}),e.jsxs("span",{className:"text-[9px] font-mono text-slate-500",children:[f.checks.length," check",f.checks.length===1?"":"s"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[f.checks.some(b=>b.status==="failed")&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[8px] font-mono uppercase tracking-widest border border-rose-400/25 bg-rose-500/10 text-rose-200",children:"fail"}),f.checks.some(b=>b.status==="warning")&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[8px] font-mono uppercase tracking-widest border border-amber-400/25 bg-amber-500/10 text-amber-200",children:"warn"}),e.jsx("span",{className:"text-slate-500 text-[10px]",children:"▾"})]})]}),e.jsx("div",{className:"px-3 pb-3 grid grid-cols-1 gap-2",children:f.checks.map(b=>e.jsx($y,{check:b},b.id))})]},f.id))}),l&&e.jsx("div",{"data-testid":"system-health-status",className:"rounded-xl border border-rose-400/30 bg-rose-500/10 px-3 py-2 text-[10px] font-mono text-rose-200",children:l})]})]})}const _l=Object.freeze({neutral:{mood:"neutral",rgbMood:"idle",label:"Neutral",dot:"#8b5cf6",glow:"rgba(139, 92, 246, 0.02)",accent:"rgba(139, 92, 246, 0.12)",avatarFrom:"rgba(139, 92, 246, 0.8)",avatarTo:"rgba(99, 102, 241, 0.8)"},focused:{mood:"focused",rgbMood:"focused",label:"Focused",dot:"#22d3ee",glow:"rgba(34, 211, 238, 0.025)",accent:"rgba(34, 211, 238, 0.14)",avatarFrom:"rgba(34, 211, 238, 0.85)",avatarTo:"rgba(6, 182, 212, 0.85)"},caution:{mood:"caution",rgbMood:"caution",label:"Caution",dot:"#fbbf24",glow:"rgba(251, 191, 36, 0.02)",accent:"rgba(251, 191, 36, 0.12)",avatarFrom:"rgba(251, 191, 36, 0.85)",avatarTo:"rgba(245, 158, 11, 0.85)"},critical:{mood:"critical",rgbMood:"critical",label:"Critical",dot:"#fb7185",glow:"rgba(251, 113, 133, 0.025)",accent:"rgba(251, 113, 133, 0.12)",avatarFrom:"rgba(251, 113, 133, 0.85)",avatarTo:"rgba(244, 63, 94, 0.85)"}});function By(t){const r=String(t||"").trim().toLowerCase();return r==="online"||r==="healthy"||r==="ready"?"online":r==="offline"||r==="error"||r==="failed"?"offline":r==="degraded"||r==="reconnecting"||r==="caution"?"degraded":"unknown"}function Fy({isThinking:t=!1,isTyping:r=!1,connectionHealth:n="unknown"}={}){const s=By(n);return s==="offline"?"critical":s==="degraded"?"caution":t||r?"focused":"neutral"}function j0(t={}){const r=Fy(t),n=_l[r]||_l.neutral;return{mood:r,colors:n,rgbMood:n.rgbMood,label:n.label}}function Uy({isThinking:t=!1,isTyping:r=!1,connectionHealth:n="unknown"}={}){return i.useMemo(()=>j0({isThinking:t,isTyping:r,connectionHealth:n}),[t,r,n])}function zy({settings:t,onUpdateSetting:r,connectionHealth:n="unknown",isThinking:s=!1}){const[a,o]=i.useState(null),l=!!(t&&t.rgbEnabled),c=j0({isThinking:s,isTyping:!1,connectionHealth:n});i.useEffect(()=>{let x=!0;return(async()=>{if(window.api&&window.api.rgb&&typeof window.api.rgb.status=="function")try{const d=await window.api.rgb.status();x&&o(d&&typeof d=="object"?d:null)}catch{x&&o(null)}})(),()=>{x=!1}},[l,c.rgbMood]);const u=Object.values(_l);return e.jsxs("section",{"data-testid":"rgb-mood-card",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-fuchsia-300 mb-4 font-bold",children:"RGB · AI Mood Sync"}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-4",children:[e.jsx("div",{className:"text-[11px] text-slate-400 leading-relaxed",children:"When enabled, OpenRGB-compatible lighting follows the assistant mood — focused while streaming, amber on bridge warnings, red when offline."}),e.jsxs("label",{className:"flex justify-between items-center p-4 bg-black/30 hover:bg-black/40 transition-colors rounded-2xl border border-white/5 cursor-pointer group",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-slate-200",children:"Sync RGB with AI mood"}),e.jsx("div",{className:"text-[10px] text-slate-500",children:"Push hardware colors when mood shifts"})]}),e.jsx("div",{className:`h-5 w-10 rounded-full flex items-center px-1 transition-colors ${l?"bg-fuchsia-400/20 border border-fuchsia-400/40":"bg-slate-800 border border-white/5"}`,children:e.jsx("div",{className:`h-3 w-3 rounded-full transition-all ${l?"bg-fuchsia-400 ml-auto":"bg-slate-500"}`})}),e.jsx("input",{type:"checkbox",className:"hidden","data-testid":"settings-rgb-sync-toggle",checked:l,onChange:x=>r("rgbEnabled",x.target.checked)})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/25 px-3 py-2.5 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"h-3 w-3 rounded-full shrink-0",style:{backgroundColor:c.colors.dot,boxShadow:`0 0 10px ${c.colors.dot}66`}}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-[10px] font-mono uppercase tracking-[0.14em] text-slate-300",children:["Live mood · ",c.label]}),e.jsxs("div",{className:"text-[10px] font-mono text-slate-500 truncate",children:["RGB lane · ",c.rgbMood]})]})]}),a&&e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-widest text-slate-500 shrink-0",children:l?"armed":"off"})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:u.map(x=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2 py-1 rounded-lg border border-white/10 bg-black/30 text-[9px] font-mono uppercase tracking-wider text-slate-400",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:x.dot}}),x.label]},x.mood))})]})]})}function Hy(t){return t==="green"?"text-emerald-200 border-emerald-300/30 bg-emerald-500/10":t==="yellow"?"text-amber-200 border-amber-300/30 bg-amber-500/10":"text-rose-200 border-rose-300/30 bg-rose-500/10"}function Wy(){const[t,r]=i.useState(null),[n,s]=i.useState(!1),[a,o]=i.useState(""),l=i.useCallback(async()=>{s(!0);try{const u=window.api&&window.api.releaseHealth&&typeof window.api.releaseHealth.check=="function"?await window.api.releaseHealth.check():await window.api.invoke("releaseHealth:check");r(u||null),o("")}catch(u){o(u&&u.message?u.message:String(u))}finally{s(!1)}},[]);i.useEffect(()=>{l()},[l]);const c=Array.isArray(t&&t.rows)?t.rows:[];return e.jsxs("section",{"data-testid":"release-health-console",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-cyan-300 mb-4 font-bold",children:"Release Health"}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:`px-2 py-1 rounded border text-[10px] font-mono uppercase tracking-[0.14em] ${Hy(String(t&&t.status?t.status:"red"))}`,children:["Status ",String(t&&t.status?t.status:"unknown")]}),e.jsx("button",{type:"button","data-testid":"release-health-refresh-btn",disabled:n,onClick:l,className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.14em] font-mono text-slate-200 hover:bg-white/10 disabled:opacity-60",children:"Refresh"})]}),a&&e.jsx("div",{className:"rounded border border-rose-300/30 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-200",children:a}),e.jsxs("div",{className:"space-y-2",children:[c.map(u=>e.jsxs("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[10px] font-mono",children:[e.jsx("span",{className:"text-slate-200",children:u.id}),e.jsx("span",{className:u.ok?"text-emerald-300":u.required?"text-rose-300":"text-amber-300",children:u.ok?"ok":u.required?"missing":"optional-missing"})]}),e.jsx("div",{className:"text-[9px] text-slate-500 font-mono break-all",children:u.path})]},u.id)),c.length===0&&e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"No release health rows found."})]})]})]})}const Ky=[{id:"offline_only",label:"Offline Only",description:"Strict local-only lane; remote and relay disabled."},{id:"balanced_team",label:"Balanced Team",description:"Allows approved remote lanes with controlled relay."},{id:"enterprise_locked",label:"Enterprise Locked",description:"Admin-safe defaults for controlled enterprise rollout."}],Vy={offline_only:{allowRemoteBridge:!1,proofRelayEnabled:!1,hostedProxyEnabled:!1,connectOnStartup:!0,otelExportEnabled:!1},balanced_team:{allowRemoteBridge:!0,proofRelayEnabled:!1,hostedProxyEnabled:!1,connectOnStartup:!0,otelExportEnabled:!1},enterprise_locked:{allowRemoteBridge:!1,proofRelayEnabled:!1,hostedProxyEnabled:!1,connectOnStartup:!1,otelExportEnabled:!1,updateChannel:"stable"}};async function Oi(t){const r=JSON.stringify(t);let n=2166136261;for(let a=0;a>>0).toString(16).padStart(8,"0").repeat(8).slice(0,64)}function Gy({disabled:t}){const[r,n]=i.useState(""),[s,a]=i.useState(""),o=i.useRef(null),l=async x=>{if(t)return;const p=Vy[String(x||"")];if(p){a(x);try{const m={...await window.api.settings.get()||{},...p},f=await window.api.settings.update(m),b=await Oi(p);return await window.api.audit.append({event:"policy_profile_applied",profileId:String(x),profileHash:b,at:new Date().toISOString()}),n(`Applied ${x} (sha256:${b.slice(0,12)}...)`),f}catch(d){n(`Failed to apply ${x}: ${d&&d.message?d.message:String(d)}`)}finally{a("")}}},c=async()=>{try{const x=await window.api.settings.get(),p={id:"custom_export",exportedAt:new Date().toISOString(),settings:{allowRemoteBridge:!!(x&&x.allowRemoteBridge),proofRelayEnabled:!!(x&&x.proofRelayEnabled),hostedProxyEnabled:!!(x&&x.hostedProxyEnabled),connectOnStartup:x&&x.connectOnStartup!==!1,otelExportEnabled:!!(x&&x.otelExportEnabled)}},d=await Oi(p.settings);p.sha256=d;const m=new Blob([`${JSON.stringify(p,null,2)} -`],{type:"application/json"}),f=URL.createObjectURL(m),b=document.createElement("a");b.href=f,b.download=`neuralshell_policy_profile_${Date.now()}.json`,document.body.appendChild(b),b.click(),b.remove(),URL.revokeObjectURL(f),n(`Exported profile (sha256:${d.slice(0,12)}...)`)}catch(x){n(`Export failed: ${x&&x.message?x.message:String(x)}`)}},u=async x=>{const p=x&&x.target&&x.target.files?x.target.files[0]:null;if(p){if(o.current&&(o.current.value=""),t){n("Policy profile apply is unavailable for this tier.");return}a("import");try{const d=await p.text(),m=JSON.parse(d),f=m&&typeof m=="object"?m:{},b=f.settings&&typeof f.settings=="object"?f.settings:null;if(!b)throw new Error("Imported profile is missing a settings object.");const g={...await window.api.settings.get()||{},...b};await window.api.settings.update(g);const y=await Oi(b);await window.api.audit.append({event:"policy_profile_imported",profileId:String(f.id||"imported"),profileHash:y,at:new Date().toISOString()}),n(`Imported ${String(f.id||"profile")} (sha256:${y.slice(0,12)}...)`)}catch(d){n(`Import failed: ${d&&d.message?d.message:String(d)}`)}finally{a("")}}};return e.jsxs("section",{"data-testid":"policy-profile-card",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-violet-300 mb-4 font-bold",children:"Policy Profiles"}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-2",children:[Ky.map(x=>e.jsxs("div",{className:"rounded border border-white/10 bg-black/30 px-3 py-2 flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-slate-200",children:x.label}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:x.description})]}),e.jsx("button",{type:"button","data-testid":`policy-apply-${x.id}`,disabled:!!t||s===x.id,onClick:()=>l(x.id),className:"px-2 py-1 rounded border border-violet-300/30 bg-violet-500/10 text-[9px] uppercase tracking-[0.14em] font-mono text-violet-200 hover:bg-violet-500/20 disabled:opacity-60",children:s===x.id?"Applying":"Apply"})]},x.id)),e.jsxs("div",{className:"pt-2 flex flex-wrap gap-2",children:[e.jsx("button",{type:"button","data-testid":"policy-export-current-btn",onClick:c,className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.14em] font-mono text-slate-200 hover:bg-white/10",children:"Export Current Profile"}),e.jsxs("label",{className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.14em] font-mono text-slate-200 hover:bg-white/10 cursor-pointer",children:["Import Profile JSON",e.jsx("input",{ref:o,"data-testid":"policy-import-input",type:"file",accept:"application/json,.json",className:"hidden",onChange:u,disabled:!!t||s==="import"})]})]}),r&&e.jsx("div",{className:"text-[10px] font-mono text-slate-300 break-all",children:r})]})]})}function Ti(t){const r=String(t||"").trim(),n=r.startsWith("#")?r:`#${r}`,s=/^#([0-9a-fA-F]{3})$/.exec(n);if(s){const[o,l,c]=s[1].split("");return`#${o}${o}${l}${l}${c}${c}`.toUpperCase()}const a=/^#([0-9a-fA-F]{6})$/.exec(n);return a?`#${a[1].toUpperCase()}`:""}function Jy(t){const r=String(t||"").trim();return/^#?[0-9a-fA-F]{3}$/.test(r)||/^#?[0-9a-fA-F]{6}$/.test(r)}function k0(){const t=Xt(l=>l.accentColor),r=Xt(l=>l.customAccentHex),n=Xt(l=>l.setAccentColor),s=Xt(l=>l.setCustomAccentHex),a=i.useMemo(()=>{const l=Ti(r);if(l)return l;const c=Nn[t]||Nn.violet;return String(c.primary||"#8B5CF6").toUpperCase()},[t,r]),o=i.useCallback(l=>{const c=Ti(l);c&&s(c)},[s]);return{accent:a,setAccent:o,isValidAccent:Jy,normalizeAccent:Ti,accentColor:t,setAccentColor:n,setCustomAccentHex:s}}const qy=Object.keys(Nn),Yy=["small","medium","large"],Zy=["left","right"],Hd=i.memo(function({checked:r,onChange:n,label:s,description:a}){return e.jsxs("label",{className:"flex items-center justify-between cursor-pointer group py-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[12px] font-medium text-slate-200 group-hover:text-white transition-colors",children:s}),a&&e.jsx("div",{className:"text-[10px] text-slate-500 mt-0.5",children:a})]}),e.jsx("button",{type:"button",role:"switch","aria-checked":r,onClick:()=>n(!r),className:`relative w-10 h-5.5 rounded-full transition-all duration-200 ${r?"bg-violet-500/40 border-violet-400/40":"bg-white/5 border-white/10"} border flex-shrink-0`,children:e.jsx("span",{className:`absolute top-0.5 h-4 w-4 rounded-full transition-all duration-200 ${r?"left-5 bg-violet-400 shadow-[0_0_8px_rgba(139,92,246,0.4)]":"left-0.5 bg-slate-400"}`})})]})}),Mi=i.memo(function({value:r,options:n,onChange:s,labels:a}){return e.jsx("div",{className:"inline-flex items-center rounded-lg border border-violet-400/15 bg-violet-500/5 overflow-hidden",children:n.map((o,l)=>e.jsx("button",{type:"button",onClick:()=>s(o),className:`px-3 py-1.5 text-[10px] font-mono uppercase tracking-[0.1em] transition-all ${l>0?"border-l border-violet-400/15":""} ${r===o?"bg-violet-500/20 text-violet-200 font-bold":"text-slate-400 hover:bg-white/5 hover:text-slate-200"}`,children:a?a[l]:o},o))})}),Xy=i.memo(function(){const{fontSize:r,setFontSize:n,accentColor:s,setAccentColor:a,compactMode:o,setCompactMode:l,animationsEnabled:c,setAnimationsEnabled:u,sidebarPosition:x,setSidebarPosition:p,visualStyle:d,setVisualStyle:m,resetToDefaults:f}=Xt(),{accent:b,setAccent:h,isValidAccent:g,normalizeAccent:y}=k0(),[P,A]=i.useState(b);i.useEffect(()=>{A(b)},[b]);const C=cd[r]||cd.medium;return e.jsxs("section",{className:"rounded-xl border border-violet-400/15 bg-shell-soft/40 p-5 space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-[13px] font-bold text-violet-300",children:"Appearance & Layout"}),e.jsx("p",{className:"text-[10px] font-mono text-slate-500 mt-0.5",children:"Customize how ProofForge looks and feels"})]}),e.jsx("button",{type:"button",onClick:f,className:"px-2.5 py-1 rounded-lg border border-slate-500/20 bg-white/[0.02] text-[9px] font-mono text-slate-400 uppercase tracking-wider hover:bg-white/5 hover:text-slate-300 transition-all",children:"Reset All"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-[11px] font-mono text-slate-300",children:[e.jsx("span",{className:"text-violet-400",children:"visualStyle"})," ",e.jsx("span",{className:"text-slate-600",children:"="})," ",e.jsxs("span",{className:"text-green-300",children:['"',d,'"']})]}),e.jsx(Mi,{value:d,options:["operator","frutiger-aero"],onChange:m,labels:["Operator","Frutiger Aero"]}),e.jsx("p",{className:"text-[10px] text-slate-500",children:"Frutiger Aero: glossy glass, sky gradients, bubbles — Windows Vista nostalgia mode."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"text-[11px] font-mono text-slate-300",children:[e.jsx("span",{className:"text-violet-400",children:"fontSize"})," ",e.jsx("span",{className:"text-slate-600",children:"="})," ",e.jsxs("span",{className:"text-green-300",children:['"',r,'"']})]}),e.jsxs("span",{className:"text-[9px] font-mono text-slate-600",children:[C.base,"px base"]})]}),e.jsx(Mi,{value:r,options:Yy,onChange:n,labels:["Sm","Md","Lg"]}),e.jsxs("div",{className:"text-[10px] text-slate-500 mt-1",style:{fontSize:`${C.base}px`},children:["Preview text at ",r," size"]})]}),e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("label",{className:"text-[11px] font-mono text-slate-300",children:[e.jsx("span",{className:"text-violet-400",children:"accentColor"})," ",e.jsx("span",{className:"text-slate-600",children:"="})," ",e.jsxs("span",{className:"text-green-300",children:['"',s,'"']})]}),e.jsx("div",{className:"flex items-center gap-2",children:qy.map(w=>{const j=Nn[w],E=s===w;return e.jsx("button",{type:"button",onClick:()=>a(w),title:w,className:`w-7 h-7 rounded-full transition-all duration-200 border-2 ${E?"scale-110 shadow-[0_0_12px_var(--ring)]":"border-transparent hover:scale-105 opacity-70 hover:opacity-100"}`,style:{backgroundColor:j.primary,borderColor:E?j.hover:"transparent","--ring":j.ring}},w)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[11px] font-mono text-slate-300",children:e.jsx("span",{className:"text-violet-400",children:"customAccentHex"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{"data-testid":"settings-accent-input",type:"text",value:P,onChange:w=>A(w.target.value),onBlur:()=>{if(g(P)){h(y(P));return}A(b)},className:"flex-1 bg-slate-900 border border-white/10 rounded-xl px-3 py-2 text-sm text-slate-200 outline-none focus:border-violet-400/50 font-mono",placeholder:"#22D3EE"}),e.jsx("div",{className:"h-9 w-9 rounded-lg border border-white/10",style:{backgroundColor:b}})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-[11px] font-mono text-slate-300",children:[e.jsx("span",{className:"text-violet-400",children:"sidebarPosition"})," ",e.jsx("span",{className:"text-slate-600",children:"="})," ",e.jsxs("span",{className:"text-green-300",children:['"',x,'"']})]}),e.jsx(Mi,{value:x,options:Zy,onChange:p,labels:["← Left","Right →"]})]}),e.jsxs("div",{className:"space-y-1 border-t border-white/5 pt-3",children:[e.jsx(Hd,{checked:o,onChange:l,label:"Compact Mode",description:"Reduce padding and spacing for more content density"}),e.jsx(Hd,{checked:c,onChange:u,label:"Animations",description:"Enable smooth transitions and pulse effects"})]})]})}),Qy={local:"Local (Ollama)",hosted:"Hosted",unknown:"Unknown"},ew={connected:{text:"Connected",cls:"text-emerald-300"},degraded:{text:"Degraded",cls:"text-amber-300"},unreachable:{text:"Not responding",cls:"text-rose-300"},"not-tested":{text:"Selected — not tested",cls:"text-slate-400"}},tw={connected:{text:"Connected",cls:"text-emerald-300"},"blocked-by-policy":{text:"Blocked by Offline Mode",cls:"text-amber-300"},"not-tested":{text:"Not tested",cls:"text-slate-400"}};function rw({connectionInfo:t}){const r=i.useMemo(()=>Np({connectionInfo:t}),[t]),n=ew[r.localStatus]||null,s=tw[r.hostedStatus]||null,a=!!r.currentProblem;return e.jsxs("div",{"data-testid":"bridge-diagnosis-card",className:`rounded-xl border px-4 py-3 space-y-2 text-[10px] font-mono ${a?"border-amber-400/25 bg-amber-500/[0.04]":"border-emerald-400/15 bg-emerald-500/[0.03]"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-[9px] text-slate-500 uppercase tracking-widest font-bold",children:"Active Route"}),e.jsxs("span",{"data-testid":"bridge-diagnosis-route",className:"text-slate-200",children:[Qy[r.selectedRoute]||r.selectedRoute,t&&t.model?` / ${t.model}`:""]})]}),n&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-slate-500",children:"Local"}),e.jsx("span",{"data-testid":"bridge-diagnosis-local",className:n.cls,children:n.text})]}),s&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-slate-500",children:"Hosted"}),e.jsx("span",{"data-testid":"bridge-diagnosis-hosted",className:s.cls,children:s.text})]}),a&&e.jsx("div",{"data-testid":"bridge-diagnosis-problem",className:"text-amber-200/80 leading-snug border-t border-amber-400/10 pt-2 mt-1",children:r.currentProblem}),!a&&r.selectedRoute!=="unknown"&&e.jsxs("div",{"data-testid":"bridge-diagnosis-clear",className:"text-emerald-400/70 border-t border-emerald-400/10 pt-2 mt-1",children:["Route clear",r.hostedStatus==="blocked-by-policy"&&r.selectedRoute==="local"&&e.jsx("span",{className:"text-slate-500 ml-2",children:"· Hosted blocked by Offline Mode"})]})]})}const Ts=[{id:"ollama",label:"Local Node (Ollama)",defaultBaseUrl:"http://127.0.0.1:11434",remote:!1},{id:"openai",label:"OpenAI Network",defaultBaseUrl:"https://api.openai.com",remote:!0},{id:"openrouter",label:"OpenRouter Network",defaultBaseUrl:"https://openrouter.ai/api",remote:!0},{id:"groq",label:"Groq Network",defaultBaseUrl:"https://api.groq.com/openai",remote:!0},{id:"together",label:"Together Network",defaultBaseUrl:"https://api.together.xyz",remote:!0},{id:"custom_openai",label:"Custom OpenAI-Compatible",defaultBaseUrl:"https://api.example.com",remote:!0}],Wd={ollama:["llama3","mistral","qwen2.5-coder:7b"],openai:["gpt-4.1-mini","gpt-4o-mini","gpt-4.1"],openrouter:["openai/gpt-4o-mini","anthropic/claude-3.5-sonnet","meta-llama/llama-3.3-70b-instruct"],groq:["llama-3.3-70b-versatile","llama3-8b-8192","mixtral-8x7b-32768"],together:["meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo","Qwen/Qwen2.5-Coder-32B-Instruct"],custom_openai:[]},fs={openai:"OPENAI_API_KEY",openrouter:"OPENROUTER_API_KEY",groq:"GROQ_API_KEY",together:"TOGETHER_API_KEY",custom_openai:"CUSTOM_OPENAI_API_KEY"};function Kd(t){const r=String(t||"").trim();return r?r.replace(/_/g," "):""}function Yt(t){const r=Ts.find(n=>n.id===String(t||"").trim());return r?r.defaultBaseUrl:"http://127.0.0.1:11434"}function ca(t){return t!=="ollama"}function Gt(t){const r=Ts.find(n=>n.id===String(t||"").trim());return!!(r&&r.remote)}function Vd(t,r){return(Array.isArray(t&&t.capabilities)?t.capabilities:[]).includes(String(r||"").trim())}function nw(t){const r=Ts.find(n=>n.id===String(t||"").trim());return r?r.label:Ka(t)}function sw(t={}){const r=Array.isArray(t.connectionProfiles)?t.connectionProfiles:[],n=String(t.activeProfileId||"").trim();if(n){const s=r.find(a=>String(a&&a.id||"")===n);if(s)return s}return r[0]||null}function mn(t={}){const r=t||{},n=sw(r),s=String(r.provider||n&&n.provider||"ollama"),a=String(r.ollamaBaseUrl||n&&n.baseUrl||Yt(s)).trim();return{...r,provider:s,apiKey:String(r.apiKey||""),apiKeyPresent:!!r.apiKeyPresent,ollamaBaseUrl:a||Yt(s),hostedProxyEnabled:!!r.hostedProxyEnabled}}const aw=[{id:"section-connection",label:"Connection"},{id:"section-security",label:"Security"},{id:"section-personalization",label:"Personalization"},{id:"section-updates",label:"Updates"},{id:"section-support",label:"Support"}];function bs({id:t,title:r,accentClass:n="text-slate-400",children:s}){return e.jsxs("div",{id:t,className:"space-y-6 scroll-mt-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`text-[10px] uppercase tracking-[0.22em] font-bold shrink-0 ${n}`,children:r}),e.jsx("div",{className:"h-px flex-1 bg-gradient-to-r from-white/10 to-transparent"})]}),e.jsx("div",{className:"space-y-8",children:s})]})}function ow({connectionInfo:t}){const{closeSettings:r}=$l(),[n,s]=O.useState(null),[a,o]=O.useState("llama3"),[l,c]=O.useState(!1),[u,x]=O.useState({tone:"idle",text:""}),[p,d]=O.useState(null),[m,f]=O.useState(null),[b,h]=O.useState(!1),[g,y]=O.useState(""),[P,A]=O.useState({running:!1,enabled:!1,rateCapPerMinute:60}),[C,w]=O.useState({enabled:!1,host:"127.0.0.1",port:4317,ok:!1,reason:""}),[j,E]=O.useState(!1),[N,_]=O.useState(null),[S,R]=O.useState(!1),$=O.useRef(null),U=O.useRef(null);O.useEffect(()=>{let M=!0;return(async()=>{try{const[V,G]=await Promise.all([window.api.settings.get(),window.api.state.get()]);if(!M)return;if(s(mn(V||{})),V&&V.hostedProxyStatus&&A({running:!!V.hostedProxyStatus.running,enabled:!!V.hostedProxyStatus.enabled,rateCapPerMinute:Number(V.hostedProxyStatus.rateCapPerMinute||60),baseUrl:String(V.hostedProxyStatus.baseUrl||"")}),window.api&&window.api.otel&&typeof window.api.otel.status=="function"){const te=await window.api.otel.status().catch(()=>null);te&&typeof te=="object"&&w({enabled:!!te.enabled,host:String(te.host||"127.0.0.1"),port:Number(te.port||4317),ok:!1,reason:""})}o(String(G&&G.model||"llama3"))}catch(V){if(!M)return;x({tone:"bad",text:`Failed to load settings: ${V&&V.message?V.message:String(V)}`})}})(),()=>{M=!1,$.current&&clearTimeout($.current)}},[]);const I=String(n&&n.provider||"ollama"),D=String(n&&n.licenseMode||"preview").toLowerCase(),z=Vd(n,"policy_profiles_apply"),F=Vd(n,"release_health_console")||D==="enterprise",J=ca(I),ee=O.useMemo(()=>{const V=[...Wd[I]||[],String(a||"").trim()].filter(Boolean);return Array.from(new Set(V))},[I,a]),ie=O.useMemo(()=>{if(!n)return[];const M=String(n.ollamaBaseUrl||"").trim(),V=!!String(a||"").trim(),G=!J||!!String(n.apiKey||"").trim()||!!n.apiKeyPresent,te=!Gt(I)||!!n.allowRemoteBridge;return[{id:"hosted",label:"Hosted access",ok:te,hint:te?"Remote providers allowed":"Enable Hosted Provider Access"},{id:"endpoint",label:"Endpoint",ok:!!M,hint:M||"Set base URL"},{id:"auth",label:"Credentials",ok:G,hint:G?"Key ready":`Set ${fs[I]||"API key"}`},{id:"model",label:"Model",ok:V,hint:V?String(a):"Choose a model"}]},[a,I,J,n]),ye=ie.every(M=>M.ok),pe=O.useMemo(()=>{const M=Array.isArray(m&&m.results)?m.results:[],V=new Map(M.map(G=>[String(G.provider||"").trim(),G]));return Ts.map(G=>{const te=V.get(G.id);if(!te)return{id:G.id,label:G.label,status:"unknown",detail:"Not checked yet"};if(te.status==="connected")return{id:G.id,label:G.label,status:"connected",detail:`${Number(te.modelCount||0)} models · ${Number(te.latencyMs||0)} ms`};if(te.status==="skipped"){const de=fs[G.id],L=Kd(te.reason||te.healthReason||"skipped"),be=String(L||"").startsWith("missing")&&de?`${L} (${de})`:L||"skipped";return{id:G.id,label:G.label,status:"skipped",detail:be}}return{id:G.id,label:G.label,status:"failed",detail:Kd(te.reason||te.healthReason||"connection failed")}})},[m]),K=O.useCallback(M=>{if(!M||typeof M!="object")return{};const{connectionProfiles:V,...G}=M;return G},[]),H=O.useCallback(async(M,V="Settings saved.")=>{const G=mn(M||{});s(G);try{const te=await window.api.settings.update(K(G)),de=mn(te||G);return s(de),x({tone:"ok",text:V}),typeof window<"u"&&window.dispatchEvent(new CustomEvent("neuralshell:settings-updated")),de}catch(te){return x({tone:"bad",text:`Settings save failed: ${te&&te.message?te.message:String(te)}`}),null}},[]),W=O.useCallback((M,V="Settings saved.")=>{U.current=null,H(M,V)},[H]),Z=O.useCallback((M,V="Settings saved.",G=0)=>{if(U.current=M,$.current&&(clearTimeout($.current),$.current=null),G<=0){W(M,V);return}$.current=setTimeout(()=>{const te=U.current;te&&W(te,V)},G)},[W]),ce=O.useCallback(async()=>{if(!(window.api&&window.api.bridge&&typeof window.api.bridge.sweep=="function"))return x({tone:"bad",text:"Provider sweep bridge is unavailable in this runtime."}),null;h(!0);try{const M=await window.api.bridge.sweep(),V=M&&typeof M=="object"?M:null;return f(V),V&&V.hostedProxy&&A({running:!!V.hostedProxy.running,enabled:!!V.hostedProxy.enabled,rateCapPerMinute:Number(V.hostedProxy.rateCapPerMinute||60),baseUrl:String(V.hostedProxy.baseUrl||"")}),y(String(V&&V.generatedAt||new Date().toISOString())),V&&x({tone:V.failed>0?"bad":"ok",text:`Provider sweep complete: ${V.connected}/${V.total} connected.`}),V}catch(M){return x({tone:"bad",text:`Provider sweep failed: ${M&&M.message?M.message:String(M)}`}),null}finally{h(!1)}},[]),fe=O.useCallback(async()=>{if(!n)return;c(!0),d(null);const M={...n,provider:"ollama",ollamaBaseUrl:Yt("ollama"),apiKey:"",apiKeyPresent:!1,allowRemoteBridge:!1,connectOnStartup:!0};await H(M,"Local lane enabled. Remote providers are now disabled.")&&await ce(),c(!1)},[ce,H,n]),me=O.useCallback(async()=>{if(!n)return;c(!0),d(null);const M=Gt(I)?I:"openai",V={...n,provider:M,ollamaBaseUrl:Yt(M),allowRemoteBridge:!0,connectOnStartup:!0,apiKeyPresent:ca(M)?!!n.apiKeyPresent:!1,apiKey:ca(M)?String(n.apiKey||""):""};await H(V,"Hosted lane enabled. Add API credentials, then run validation.")&&await ce(),c(!1)},[I,ce,H,n]),ke=O.useCallback(async()=>{if(!(window.api&&window.api.bridge&&typeof window.api.bridge.importEnvProfiles=="function")){x({tone:"bad",text:"Environment profile import is unavailable in this runtime."});return}c(!0);try{const M=await window.api.bridge.importEnvProfiles(),V=await window.api.settings.get();s(mn(V||{})),d(null);const G=Array.isArray(M&&M.importedProfiles)?M.importedProfiles.length:0;x({tone:"ok",text:`Imported ${G} profile${G===1?"":"s"} from environment.`}),await ce()}catch(M){x({tone:"bad",text:`Env profile import failed: ${M&&M.message?M.message:String(M)}`})}finally{c(!1)}},[ce]),Pe=O.useCallback(async()=>{if(n){c(!0);try{const M={...n,hostedProxyEnabled:!n.hostedProxyEnabled};await H(M,M.hostedProxyEnabled?"Hosted fallback proxy enabled (Together gateway, rate capped).":"Hosted fallback proxy disabled.")&&await ce()}finally{c(!1)}}},[ce,H,n]),_e=O.useCallback(async()=>{if(!n)return;const M=!n.otelExportEnabled;if(await H({...n,otelExportEnabled:M},M?"OpenTelemetry export enabled.":"OpenTelemetry export disabled.")&&window.api&&window.api.otel&&typeof window.api.otel.setEnabled=="function"){const G=await window.api.otel.setEnabled(M).catch(()=>null);G&&typeof G=="object"&&w(te=>({...te,enabled:!!G.enabled,host:String(G.host||te.host),port:Number(G.port||te.port)}))}},[H,n]),ne=O.useCallback(async()=>{if(!(window.api&&window.api.otel&&typeof window.api.otel.verify=="function"))return;const M=await window.api.otel.verify().catch(()=>null);!M||typeof M!="object"||w(V=>({...V,ok:!!M.ok,reason:String(M.reason||""),host:String(M.host||V.host),port:Number(M.port||V.port)}))},[]),we=(M,V)=>{if(!n)return;const G=String(n.provider||"ollama"),te={...n,[M]:V};if(M==="provider"){const be=String(V||"ollama"),Q=Yt(G),We=String(n.ollamaBaseUrl||"").trim();(!We||We===Q)&&(te.ollamaBaseUrl=Yt(be)),Gt(be)&&(te.allowRemoteBridge=!0),ca(be)||(te.apiKey="",te.apiKeyPresent=!1);const oe=Wd[be]||[];if(oe.length>0){const xe=String(oe[0]);o(xe),te.defaultModel=xe,window.api&&window.api.state&&typeof window.api.state.update=="function"&&window.api.state.update({model:xe}).catch(()=>{})}d(null)}M==="apiKey"&&(te.apiKeyPresent=!!String(V||"").trim());const de=mn(te);s(de),Z(de,"Settings saved.",M==="ollamaBaseUrl"||M==="apiKey"?450:0)},Be=async()=>{const M=String(a||"").trim();if(!M){x({tone:"bad",text:"Model is required."});return}c(!0);try{await window.api.state.update({model:M}),x({tone:"ok",text:`Model set to ${M}.`})}catch(V){x({tone:"bad",text:`Model update failed: ${V&&V.message?V.message:String(V)}`})}finally{c(!1)}},re=async()=>{if(!n)return;const M=String(n.ollamaBaseUrl||Yt(I)).trim();if(!M){x({tone:"bad",text:"Base URL is required for bridge test."});return}if(Gt(I)&&!n.allowRemoteBridge){x({tone:"bad",text:"Enable Hosted Provider Access before testing remote providers."});return}if(J&&!String(n.apiKey||"").trim()&&!n.apiKeyPresent){x({tone:"bad",text:"API key is required. Paste your key, save settings, then test again."});return}const V={id:String(n.activeProfileId||""),provider:I,baseUrl:M,timeoutMs:Math.max(8e3,Math.min(Number(n.timeoutMs)||15e3,12e3)),retryCount:0,defaultModel:String(a||"llama3").trim()||"llama3",apiKey:String(n.apiKey||"")};c(!0),d(null);try{const G=await window.api.bridge.test(V);if(d(G),G&&G.ok){x({tone:"ok",text:`Live bridge verified (${G.provider}) with ${Number(G.modelCount)||0} models.`});const te={provider:String(G.provider||I),model:String(a||""),modelCount:Number(G.modelCount||0),baseUrl:String(G.baseUrl||M)};_(te),S||(E(!0),R(!0))}else{const te=G&&G.health&&G.health.reason?G.health.reason:"Bridge test failed.";x({tone:"bad",text:ld(new Error(te),{provider:I,baseUrl:M,model:V.defaultModel,ollamaBaseUrl:M})})}}catch(G){d(null),x({tone:"bad",text:ld(G,{provider:I,baseUrl:M,model:V.defaultModel,ollamaBaseUrl:M})})}finally{c(!1)}},ae=async()=>{if(n){c(!0),d(null);try{await window.api.llm.cancelStream().catch(()=>!1);const M={...n,provider:"ollama",apiKey:"",apiKeyPresent:!1,ollamaBaseUrl:Yt("ollama"),allowRemoteBridge:!1,connectOnStartup:!1},V=await window.api.settings.update(M);s(mn(V||M)),x({tone:"ok",text:"Offline kill switch engaged. Hosted providers disabled and bridge stream cancelled."})}catch(M){x({tone:"bad",text:`Offline kill switch failed: ${M&&M.message?M.message:String(M)}`})}finally{c(!1)}}};return n?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[149] bg-black/40 backdrop-blur-[2px] transition-all",onClick:r}),e.jsxs("div",{"data-testid":"settings-drawer",className:"fixed right-0 top-0 bottom-0 max-w-xl w-full z-[150] bg-slate-950 border-l border-cyan-400/20 shadow-[-20px_0_50px_rgba(0,0,0,0.6)] p-8 flex flex-col animate-fade-up",style:{borderImage:"linear-gradient(180deg, rgba(6,182,212,0.3), rgba(139,92,246,0.15), rgba(217,70,239,0.08)) 1"},children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight text-gradient animate-gradient-shift",style:{backgroundImage:"linear-gradient(90deg, #06b6d4, #8b5cf6, #d946ef, #06b6d4)"},children:"Configuration"}),e.jsx("button",{"data-testid":"settings-close-btn",onClick:r,className:"h-10 w-10 rounded-full hover:bg-white/5 flex items-center justify-center text-slate-400 hover:text-white transition-colors",children:"✕"})]}),e.jsx("nav",{"data-testid":"settings-section-nav",className:"sticky top-0 z-10 -mx-2 mb-4 px-2 py-2 flex flex-wrap gap-1.5 border-b border-white/[0.06] bg-slate-950/95 backdrop-blur-sm",children:aw.map(M=>e.jsx("button",{type:"button",onClick:()=>{const V=document.getElementById(M.id);V&&typeof V.scrollIntoView=="function"&&V.scrollIntoView({behavior:"smooth",block:"start"})},className:"px-2.5 py-1 rounded-lg border border-white/10 bg-white/[0.03] text-[9px] font-mono uppercase tracking-[0.14em] text-slate-400 hover:text-cyan-200 hover:border-cyan-400/25 transition-colors",children:M.label},M.id))}),e.jsxs("div",{className:"space-y-10 flex-1 overflow-y-auto pr-4 custom-scrollbar",children:[e.jsxs(bs,{id:"section-connection",title:"Connection & Models",accentClass:"text-emerald-300",children:[e.jsxs("section",{children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-widest text-emerald-400 mb-4 font-bold flex items-center gap-2",children:["LLM Bridge Profile",e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-emerald-500/10 text-emerald-400 text-[8px] font-mono border border-emerald-500/20",children:"LIVE"})]}),e.jsxs("div",{className:"space-y-4 p-5 bg-black/30 rounded-2xl border border-white/5 shadow-inner",children:[e.jsxs("div",{"data-testid":"settings-bridge-readiness",className:`rounded-xl border px-3 py-3 space-y-2 ${ye?"border-emerald-400/25 bg-emerald-500/5":"border-amber-400/20 bg-amber-500/5"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.16em] font-bold text-slate-200",children:"Connection checklist"}),e.jsx("span",{className:`text-[9px] font-mono uppercase tracking-[0.14em] ${ye?"text-emerald-300":"text-amber-300"}`,children:ye?"ready to test":"needs attention"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:ie.map(M=>e.jsxs("div",{className:"flex items-start gap-2 text-[10px] font-mono",children:[e.jsx("span",{className:M.ok?"text-emerald-400":"text-amber-400",children:M.ok?"✓":"○"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-slate-300",children:M.label}),e.jsx("div",{className:"text-slate-500",children:M.hint})]})]},M.id))})]}),t&&e.jsx(rw,{connectionInfo:t}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[10px] text-slate-400 uppercase tracking-widest font-bold ml-1",children:"Provider Engine"}),e.jsx("select",{"data-testid":"settings-provider-select",value:I,onChange:M=>we("provider",M.target.value),className:"w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-sm text-slate-200 outline-none focus:border-cyan-400/50 transition-all cursor-pointer font-mono",children:Ts.map(M=>e.jsx("option",{value:M.id,children:M.label},M.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[10px] font-mono",children:[e.jsx("span",{className:`px-2 py-0.5 rounded border ${Gt(I)?"border-violet-400/30 bg-violet-500/10 text-violet-200":"border-cyan-400/30 bg-cyan-500/10 text-cyan-200"}`,children:Gt(I)?"Hosted lane":"Local lane"}),Gt(I)&&n.allowRemoteBridge&&e.jsx("span",{className:"text-emerald-400/90",children:"Hosted access enabled"}),Gt(I)&&fs[I]&&e.jsxs("span",{className:"text-slate-500",children:["Env: ",fs[I]]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[10px] text-slate-400 uppercase tracking-widest font-bold ml-1",children:"Base URL / Endpoint"}),e.jsx("input",{type:"text",value:n.ollamaBaseUrl||"",onChange:M=>we("ollamaBaseUrl",M.target.value),placeholder:Yt(I),className:"w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-sm text-slate-200 placeholder-slate-600 outline-none focus:border-cyan-400/50 focus:ring-1 focus:ring-cyan-400/10 transition-all font-mono"})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("label",{className:"text-[10px] text-slate-400 uppercase tracking-widest font-bold ml-1 flex justify-between",children:[e.jsx("span",{children:"Authorization Key"}),!J&&e.jsx("span",{className:"text-slate-600 italic",children:"Not required for local"})]}),e.jsx("input",{type:"password",value:n.apiKey||"",onChange:M=>we("apiKey",M.target.value),placeholder:J?"sk-...":"Optional",disabled:!J,className:"w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-sm text-slate-200 placeholder-slate-600 outline-none focus:border-cyan-400/50 focus:ring-1 focus:ring-cyan-400/10 transition-all font-mono disabled:opacity-50"}),J&&e.jsx("div",{"data-testid":"settings-api-key-status",className:`text-[10px] font-mono ${n.apiKeyPresent?"text-emerald-300":"text-slate-500"}`,children:n.apiKeyPresent?"Key stored securely in Vault+.":`Paste your ${fs[I]||"API key"} — saves automatically.`})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[10px] text-slate-400 uppercase tracking-widest font-bold ml-1",children:"Active Model"}),e.jsx("input",{"data-testid":"settings-model-input",list:"settings-model-suggestions",type:"text",value:a,onChange:M=>o(M.target.value),placeholder:"Set active model name",className:"w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-sm text-slate-200 placeholder-slate-600 outline-none focus:border-cyan-400/50 focus:ring-1 focus:ring-cyan-400/10 transition-all font-mono"}),ee.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:ee.slice(0,4).map(M=>e.jsx("button",{type:"button",onClick:()=>o(M),className:`px-2 py-1 rounded-lg border text-[9px] font-mono transition-colors ${String(a||"")===M?"border-cyan-400/40 bg-cyan-500/15 text-cyan-100":"border-white/10 bg-white/5 text-slate-400 hover:text-slate-200 hover:border-white/20"}`,children:M},M))}),e.jsx("datalist",{id:"settings-model-suggestions",children:ee.map(M=>e.jsx("option",{value:M},M))}),e.jsx("button",{type:"button",onClick:Be,disabled:l,className:"px-3 py-2 rounded-xl border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-cyan-200 hover:bg-cyan-500/20 disabled:opacity-50",children:"Apply Model"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsxs("button",{"data-testid":"settings-test-connection-btn",type:"button",onClick:re,disabled:l,className:"px-3 py-2 rounded-xl border border-emerald-300/30 bg-emerald-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-emerald-200 hover:bg-emerald-500/20 disabled:opacity-50 inline-flex items-center justify-center gap-2",children:[l&&e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full border border-emerald-200/70 border-t-transparent animate-spin"}),l?"Testing…":"Test Live Connection"]}),e.jsx("button",{"data-testid":"settings-offline-kill-btn",type:"button",onClick:ae,disabled:l,className:"px-3 py-2 rounded-xl border border-rose-300/30 bg-rose-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-rose-200 hover:bg-rose-500/20 disabled:opacity-50",children:"Offline Kill Switch"})]}),p&&e.jsxs("div",{className:`rounded-xl border px-3 py-2 text-[10px] font-mono space-y-1.5 ${p.ok?"border-emerald-400/30 bg-emerald-500/10 text-emerald-200":"border-rose-400/30 bg-rose-500/10 text-rose-200"}`,children:[e.jsx("div",{children:p.ok?`Verified ${nw(p.provider)} · ${p.modelCount||0} models`:`Bridge test failed: ${p.health&&p.health.reason?p.health.reason:"unknown reason"}`}),p.ok&&p.baseUrl&&e.jsx("div",{className:"text-emerald-300/80 truncate",children:p.baseUrl}),p.ok&&Array.isArray(p.models)&&p.models.length>0&&e.jsxs("div",{className:"text-emerald-300/70",children:["Sample: ",p.models.slice(0,3).join(", "),p.models.length>3?"…":""]}),p.ok&&e.jsx("button",{type:"button","data-testid":"share-proof-open-btn",onClick:()=>E(!0),className:"mt-2 px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-cyan-100 hover:bg-cyan-500/20",children:"Share Proof"})]})]})]}),e.jsxs("section",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-amber-300 mb-4 font-bold",children:"Provider Setup Wizard"}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx("button",{"data-testid":"settings-setup-local-btn",type:"button",onClick:fe,disabled:l,className:"px-3 py-2 rounded-xl border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-cyan-200 hover:bg-cyan-500/20 disabled:opacity-50",children:"Local Lane"}),e.jsx("button",{"data-testid":"settings-setup-hosted-btn",type:"button",onClick:me,disabled:l,className:"px-3 py-2 rounded-xl border border-emerald-300/30 bg-emerald-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-emerald-200 hover:bg-emerald-500/20 disabled:opacity-50",children:"Hosted Lane"})]}),e.jsx("button",{"data-testid":"settings-import-env-btn",type:"button",onClick:ke,disabled:l,className:"w-full px-3 py-2 rounded-xl border border-white/15 bg-white/5 text-[10px] uppercase tracking-[0.16em] font-bold text-slate-200 hover:bg-white/10 disabled:opacity-50",children:"Import Provider Profiles from Environment"})]})]}),e.jsx(jg,{providerSweep:m,providerSweepRows:pe,providerSweepBusy:b,providerSweepUpdatedAt:g,activeProviderId:I,onRefresh:ce,hostedProxyEnabled:!!n.hostedProxyEnabled,hostedProxyStatus:P,onToggleHostedProxy:Pe}),e.jsx(Ly,{})]}),e.jsxs(bs,{id:"section-security",title:"Security & Trust",accentClass:"text-cyan-300",children:[e.jsxs("section",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-cyan-400 mb-4 font-bold",children:"Security Subsystem"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"flex justify-between items-center p-4 bg-black/30 hover:bg-black/40 transition-colors rounded-2xl border border-white/5 cursor-pointer group",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-slate-200",children:"Safe Defaults"}),e.jsx("div",{className:"text-[10px] text-slate-500",children:"Enable OMEGA-hardened zero-trust guards"})]}),e.jsx("div",{className:`h-5 w-10 rounded-full flex items-center px-1 transition-colors ${n.safeMode!==!1?"bg-cyan-400/20 border border-cyan-400/40":"bg-slate-800 border border-white/5"}`,children:e.jsx("div",{className:`h-3 w-3 rounded-full transition-all ${n.safeMode!==!1?"bg-cyan-400 ml-auto":"bg-slate-500"}`})}),e.jsx("input",{type:"checkbox",className:"hidden",checked:n.safeMode!==!1,onChange:M=>we("safeMode",M.target.checked)})]}),e.jsxs("label",{className:"flex justify-between items-center p-4 bg-black/30 hover:bg-black/40 transition-colors rounded-2xl border border-white/5 cursor-pointer group opacity-60",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-slate-200",children:"P2P Network Tunnel"}),e.jsx("div",{className:"text-[10px] text-slate-500",children:"Enable decentralized swarming (Requires APEX)"})]}),e.jsx("div",{className:`h-5 w-10 rounded-full flex items-center px-1 transition-colors ${n.networkTunnel?"bg-amber-400/20 border border-amber-400/40":"bg-slate-800 border border-white/5"}`,children:e.jsx("div",{className:`h-3 w-3 rounded-full transition-all ${n.networkTunnel?"bg-amber-400 ml-auto":"bg-slate-500"}`})}),e.jsx("input",{type:"checkbox",className:"hidden",checked:!!n.networkTunnel,onChange:M=>we("networkTunnel",M.target.checked)})]}),e.jsxs("label",{className:"flex justify-between items-center p-4 bg-black/30 hover:bg-black/40 transition-colors rounded-2xl border border-white/5 cursor-pointer group",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-slate-200",children:"Hosted Provider Access"}),e.jsx("div",{className:"text-[10px] text-slate-500",children:"Allow network-hosted model providers in this runtime"})]}),e.jsx("div",{className:`h-5 w-10 rounded-full flex items-center px-1 transition-colors ${n.allowRemoteBridge?"bg-emerald-400/20 border border-emerald-400/40":"bg-slate-800 border border-white/5"}`,children:e.jsx("div",{className:`h-3 w-3 rounded-full transition-all ${n.allowRemoteBridge?"bg-emerald-400 ml-auto":"bg-slate-500"}`})}),e.jsx("input",{type:"checkbox",className:"hidden",checked:!!n.allowRemoteBridge,onChange:M=>we("allowRemoteBridge",M.target.checked)})]})]})]}),e.jsxs("section",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-violet-300 mb-4 font-bold",children:"OpenTelemetry Export"}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-3",children:[e.jsxs("div",{className:"text-[11px] text-slate-400 font-mono",children:["Optional local OTLP bridge to ",e.jsx("code",{className:"text-cyan-300",children:"localhost:4317"}),". Disabled by default."]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"settings-otel-toggle-btn",onClick:_e,className:`px-3 py-2 rounded-xl border text-[10px] uppercase tracking-[0.16em] font-bold ${n.otelExportEnabled?"border-violet-300/35 bg-violet-500/10 text-violet-200":"border-white/15 bg-white/5 text-slate-200"}`,children:n.otelExportEnabled?"Disable Export":"Enable Export"}),e.jsx("button",{type:"button","data-testid":"settings-otel-verify-btn",onClick:ne,className:"px-3 py-2 rounded-xl border border-white/15 bg-white/5 text-[10px] uppercase tracking-[0.16em] font-bold text-slate-200 hover:bg-white/10",children:"Verify Collector"}),e.jsxs("span",{className:`text-[10px] font-mono ${C.ok?"text-emerald-300":"text-slate-500"}`,children:[C.ok?"Collector reachable":`Collector ${C.host}:${C.port}`,C.reason?` (${C.reason})`:""]})]})]})]}),e.jsx(ug,{}),e.jsx(Gy,{disabled:!z})]}),e.jsxs(bs,{id:"section-personalization",title:"Personalization",accentClass:"text-violet-300",children:[e.jsx(Xy,{}),e.jsx(zy,{settings:n,onUpdateSetting:we,connectionHealth:p!=null&&p.ok?"online":Gt(I)&&!n.allowRemoteBridge?"offline":"unknown",isThinking:l})]}),e.jsxs(bs,{id:"section-updates",title:"Updates & Licensing",accentClass:"text-amber-300",children:[e.jsx(mg,{licenseMode:n.licenseMode}),e.jsx(pg,{licenseMode:n.licenseMode}),e.jsx(fg,{licenseMode:n.licenseMode}),e.jsx(Sg,{})]}),e.jsxs(bs,{id:"section-support",title:"Support & Advanced",accentClass:"text-slate-400",children:[e.jsx(Sy,{}),e.jsx(Ay,{}),F&&e.jsx(Wy,{}),e.jsx(Yp,{}),e.jsx($g,{}),e.jsxs("section",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-slate-300 mb-4 font-bold",children:"Legal"}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-3",children:[e.jsx("div",{className:"text-[11px] text-slate-300 font-mono",children:"Created by The Founder"}),e.jsxs("div",{className:"text-[11px] text-slate-400 font-mono",children:["Third-party attribution is generated at ",e.jsx("code",{className:"text-cyan-300",children:"public/about.html"}),"."]}),e.jsx("button",{type:"button","data-testid":"settings-legal-open-about-btn",onClick:()=>{window.api&&window.api.system&&typeof window.api.system.openExternal=="function"&&window.api.system.openExternal("https://github.com/Z3r0DayZion-install/NeuralShell/blob/master/public/about.html")},className:"px-3 py-2 rounded-xl border border-white/15 bg-white/5 text-[10px] uppercase tracking-[0.16em] font-bold text-slate-200 hover:bg-white/10",children:"Open Attribution Page"})]})]})]})]}),u.text&&e.jsx("div",{"data-testid":"settings-status-text",className:`mt-4 rounded-xl border px-3 py-2 text-[10px] font-mono ${u.tone==="ok"?"border-emerald-400/30 bg-emerald-500/10 text-emerald-200":u.tone==="bad"?"border-rose-400/30 bg-rose-500/10 text-rose-200":"border-white/10 bg-black/30 text-slate-300"}`,children:u.text})]}),e.jsx(yg,{open:j,payload:N,onClose:()=>E(!1)})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[149] bg-black/40 backdrop-blur-[2px] transition-all",onClick:r}),e.jsxs("div",{"data-testid":"settings-drawer",className:"fixed right-0 top-0 bottom-0 max-w-xl w-full z-[150] bg-slate-950 border-l border-cyan-400/20 shadow-[-20px_0_50px_rgba(0,0,0,0.6)] p-8 flex flex-col animate-fade-up",style:{borderImage:"linear-gradient(180deg, rgba(6,182,212,0.3), rgba(139,92,246,0.15), rgba(217,70,239,0.08)) 1"},children:[e.jsxs("div",{className:"flex justify-between items-center mb-8",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight text-slate-100",children:"Configuration"}),e.jsx("button",{"data-testid":"settings-close-btn",onClick:r,className:"h-10 w-10 rounded-full hover:bg-white/5 flex items-center justify-center text-slate-400 hover:text-white transition-colors",children:"✕"})]}),e.jsx("div",{className:"text-sm text-slate-400 font-mono",children:"Loading settings…"})]})]})}function da(t,r=0){const n=Number(t);return Number.isFinite(n)?n:r}function iw(t){return Array.isArray(t)?t:[]}function N0(t){const r=t&&typeof t=="object"?t:{},n=da(r.installs,0),s=da(r.proofRuns,0),a=da(r.vaultWrites,0),o=r.providerSuccess&&typeof r.providerSuccess=="object"?r.providerSuccess:{},l=String(r.tier||"unknown");return{source:String(r.source||r.fileName||"bundle"),tier:l,installs:n,proofRuns:s,vaultWrites:a,providerSuccess:Object.fromEntries(Object.entries(o).map(([u,x])=>[String(u),da(x,0)]))}}function Gd(t){const r=iw(t).map(N0),n={installs:0,proofRuns:0,vaultWrites:0},s={},a={};for(const o of r){n.installs+=o.installs,n.proofRuns+=o.proofRuns,n.vaultWrites+=o.vaultWrites,a[o.tier]=(a[o.tier]||0)+1;for(const[l,c]of Object.entries(o.providerSuccess))s[l]=(s[l]||0)+c}return{bundleCount:r.length,totals:n,providerSuccess:s,tierMix:a,bundles:r}}function lw(t){return new Promise((r,n)=>{const s=new FileReader;s.onerror=()=>n(new Error("Unable to read file.")),s.onload=()=>{try{r(JSON.parse(String(s.result||"{}")))}catch{n(new Error("Invalid JSON bundle."))}},s.readAsText(t)})}function cw(){const[t,r]=i.useState(null),[n,s]=i.useState(()=>Gd([])),[a,o]=i.useState("");i.useEffect(()=>{let c=!0;return(async()=>{try{const u=await window.api.analytics.getDashboard(30);if(!c)return;r(u||null)}catch(u){if(!c)return;o(u&&u.message?u.message:String(u))}})(),()=>{c=!1}},[]);const l=async c=>{const u=c&&c.target&&c.target.files?c.target.files[0]:null;if(u)try{const x=await lw(u),p=N0({...x,fileName:u.name});s(d=>Gd([...d.bundles||[],p])),o("")}catch(x){o(x&&x.message?x.message:String(x))}};return e.jsxs("section",{"data-testid":"operator-dashboard",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Operator Dashboard"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Import local metrics bundles. No cloud backend required."})]}),e.jsxs("label",{className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.14em] font-mono text-cyan-200 cursor-pointer",children:["Import Bundle",e.jsx("input",{"data-testid":"operator-import-bundle-input",type:"file",accept:"application/json,.json,.neuralshell-metrics.json",className:"hidden",onChange:l})]})]}),a&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:a}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Installs"}),e.jsx("div",{className:"text-[14px] text-slate-100 font-bold",children:Number(n.totals.installs||0).toLocaleString()})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Proof Runs"}),e.jsx("div",{className:"text-[14px] text-slate-100 font-bold",children:Number(n.totals.proofRuns||0).toLocaleString()})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Vault Writes"}),e.jsx("div",{className:"text-[14px] text-slate-100 font-bold",children:Number(n.totals.vaultWrites||0).toLocaleString()})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Bundles"}),e.jsx("div",{className:"text-[14px] text-slate-100 font-bold",children:Number(n.bundleCount||0).toLocaleString()})]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold mb-1",children:"Local Runtime Reliability"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-300",children:t?`Events ${t.eventCount||0} · Median ${t.medianLatencyMs||0}ms · Est $${Number(t.estimatedUsd||0).toFixed(2)}`:"Local dashboard unavailable."})]})]})}const dw="neuralshell_onboarding_events_v1";function Cr(t,r=0){const n=Number(t);return Number.isFinite(n)?n:r}function uw(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(dw)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function pw(t=[]){const r=Array.isArray(t)?t:[];let n=0,s=0,a=0,o=0,l=0;for(const c of r){const u=String(c&&c.type?c.type:"").trim(),x=String(c&&c.stepId?c.stepId:"").trim();u==="wizard_opened"&&(n+=1),u==="step_completed"&&x==="provider_sweep"&&(s+=1),u==="step_completed"&&x==="vault_save"&&(a+=1),u==="step_completed"&&x==="run_proof"&&(o+=1),u==="step_completed"&&x==="share_badge"&&(l+=1)}return{started:n,providerSweep:s,vaultSave:a,runProof:o,shareBadge:l}}function S0(t={}){const r=t&&typeof t=="object"?t:{},n=r.funnel&&typeof r.funnel=="object"?r.funnel:{};return{source:String(r.source||r.fileName||"bundle"),installs:Cr(r.installs,0),onboardingStarted:Cr(n.onboardingStarted,0),onboardingCompleted:Cr(n.onboardingCompleted,0),proofRuns:Cr(n.proofRuns,Cr(r.proofRuns,0)),shares:Cr(n.shares,0),upgrades:Cr(n.upgrades,0)}}function mw(t=[]){const r=(Array.isArray(t)?t:[]).map(S0),n={installs:0,onboardingStarted:0,onboardingCompleted:0,proofRuns:0,shares:0,upgrades:0};for(const s of r)n.installs+=s.installs,n.onboardingStarted+=s.onboardingStarted,n.onboardingCompleted+=s.onboardingCompleted,n.proofRuns+=s.proofRuns,n.shares+=s.shares,n.upgrades+=s.upgrades;return{bundles:r,totals:n}}function xw(t,r){return r?Math.round(Number(t||0)/Number(r||1)*100):0}function fw(t){return new Promise((r,n)=>{const s=new FileReader;s.onerror=()=>n(new Error("Unable to read conversion bundle.")),s.onload=()=>{try{const a=JSON.parse(String(s.result||"{}"));r(a)}catch{n(new Error("Invalid conversion bundle JSON."))}},s.readAsText(t)})}function bw(){const[t]=i.useState(()=>uw()),[r,n]=i.useState([]),[s,a]=i.useState(""),o=i.useMemo(()=>pw(t),[t]),l=i.useMemo(()=>mw(r),[r]),c=i.useMemo(()=>{const p=l.totals||{};return{installs:Number(p.installs||0),onboardingStarted:Math.max(Number(p.onboardingStarted||0),Number(o.started||0)),onboardingCompleted:Math.max(Number(p.onboardingCompleted||0),Number(o.shareBadge||0)),proofRuns:Math.max(Number(p.proofRuns||0),Number(o.runProof||0)),shares:Math.max(Number(p.shares||0),Number(o.shareBadge||0)),upgrades:Number(p.upgrades||0)}},[l.totals,o.runProof,o.shareBadge,o.started]),u=[{id:"installs",label:"Installs",value:c.installs},{id:"onboardingStarted",label:"Onboarding Started",value:c.onboardingStarted},{id:"proofRuns",label:"Proof Runs",value:c.proofRuns},{id:"shares",label:"Shares",value:c.shares},{id:"upgrades",label:"Upgrades",value:c.upgrades}],x=async p=>{const d=p&&p.target&&p.target.files?p.target.files[0]:null;if(d)try{const m=await fw(d),b=(Array.isArray(m)?m:Array.isArray(m.bundles)?m.bundles:[m]).map(h=>S0({...h,fileName:d.name}));n(h=>[...h,...b]),a("")}catch(m){a(m&&m.message?m.message:String(m))}};return e.jsxs("section",{"data-testid":"funnel-dashboard",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Conversion Funnel"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Local funnel metrics + importable bundle overlays."})]}),e.jsxs("label",{className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.14em] font-mono text-cyan-200 cursor-pointer",children:["Import Funnel JSON",e.jsx("input",{"data-testid":"funnel-import-input",type:"file",accept:"application/json,.json,.neuralshell-metrics.json",className:"hidden",onChange:x})]})]}),s&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:s}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-5 gap-2",children:u.map((p,d)=>{const m=d===0?p.value:u[d-1].value;return e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:p.label}),e.jsx("div",{className:"text-[14px] text-slate-100 font-bold",children:Number(p.value||0).toLocaleString()}),d>0&&e.jsxs("div",{className:"text-[9px] font-mono text-cyan-300",children:[xw(p.value,m),"%"]})]},p.id)})}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-400",children:["Local onboarding events: started ",o.started,", provider sweep ",o.providerSweep,", vault save ",o.vaultSave,", proof ",o.runProof,", share ",o.shareBadge,"."]})]})}function ct(t,r=0){const n=Number(t);return Number.isFinite(n)?n:r}function hw(t){const r=String(t||"").split(/\r?\n/).filter(Boolean);if(!r.length)return[];const n=r[0].split(",").map(s=>s.trim());return r.slice(1).map(s=>{const a=s.split(","),o={};return n.forEach((l,c)=>{o[l]=String(a[c]||"").trim()}),o})}function ua(t={},r="snapshot"){const n=t&&typeof t=="object"?t:{};return{source:r,period:String(n.period||n.date||new Date().toISOString().slice(0,10)),mrr:ct(n.mrr,0),installs:ct(n.installs,0),activations:ct(n.activations,0),upgrades:ct(n.upgrades,0),agentSales:ct(n.agentSales,0),partnerRevenue:ct(n.partnerRevenue,0)}}function gw(t,r=""){const n=String(r||"import");if(n.toLowerCase().endsWith(".csv"))return hw(t).map(a=>ua(a,n));const s=JSON.parse(String(t||"{}"));return Array.isArray(s)?s.map(a=>ua(a,n)):Array.isArray(s.snapshots)?s.snapshots.map(a=>ua(a,n)):[ua(s,n)]}function yw(t=[]){const r=Array.isArray(t)?t:[],n={mrr:0,installs:0,activations:0,upgrades:0,agentSales:0,partnerRevenue:0};for(const o of r)n.mrr+=ct(o.mrr,0),n.installs+=ct(o.installs,0),n.activations+=ct(o.activations,0),n.upgrades+=ct(o.upgrades,0),n.agentSales+=ct(o.agentSales,0),n.partnerRevenue+=ct(o.partnerRevenue,0);const s=r.slice(-3),a=s.length?s.reduce((o,l)=>o+ct(l.mrr,0),0)/s.length:0;return{totals:n,projectionYearly:Math.round(a*12)}}function ww(t){return new Promise((r,n)=>{const s=new FileReader;s.onerror=()=>n(new Error("Unable to read revenue file.")),s.onload=()=>r(String(s.result||"")),s.readAsText(t)})}function vw(){const[t,r]=i.useState([]),[n,s]=i.useState(""),a=i.useMemo(()=>yw(t),[t]),o=async l=>{const c=l&&l.target&&l.target.files?l.target.files[0]:null;if(c)try{const u=await ww(c),x=gw(u,c.name);r(p=>[...p,...x]),s("")}catch(u){s(u&&u.message?u.message:String(u))}};return e.jsxs("section",{"data-testid":"revenue-console",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-emerald-300 font-bold",children:"Revenue Console"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Founder-only projections from imported CSV/JSON snapshots."})]}),e.jsxs("label",{className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.14em] font-mono text-emerald-200 cursor-pointer",children:["Import Revenue",e.jsx("input",{"data-testid":"revenue-import-input",type:"file",accept:".csv,application/json,.json",className:"hidden",onChange:o})]})]}),n&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:n}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"MRR Total"}),e.jsxs("div",{className:"text-[14px] text-slate-100 font-bold",children:["$",Number(a.totals.mrr||0).toLocaleString()]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Upgrades"}),e.jsx("div",{className:"text-[14px] text-slate-100 font-bold",children:Number(a.totals.upgrades||0).toLocaleString()})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Agent Sales"}),e.jsxs("div",{className:"text-[14px] text-slate-100 font-bold",children:["$",Number(a.totals.agentSales||0).toLocaleString()]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Proj. ARR"}),e.jsxs("div",{className:"text-[14px] text-emerald-200 font-bold",children:["$",Number(a.projectionYearly||0).toLocaleString()]})]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2 max-h-44 overflow-auto",children:[t.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No revenue snapshots imported yet."}),t.slice(-8).map((l,c)=>e.jsxs("div",{className:"text-[10px] font-mono text-slate-300 flex justify-between gap-2",children:[e.jsx("span",{children:l.period}),e.jsxs("span",{children:["MRR $",Number(l.mrr||0).toLocaleString()]}),e.jsxs("span",{children:["Upgrades ",Number(l.upgrades||0).toLocaleString()]})]},`${l.source}-${l.period}-${c}`))]})]})}function jw(t=[]){const r=Array.isArray(t)?t.slice(-24):[],n=Math.max(1,...r.map(s=>Number(s.latencyMs||0)));return r.map((s,a)=>({x:a,h:Math.max(2,Math.round(Number(s.latencyMs||0)/n*52)),latencyMs:Number(s.latencyMs||0)}))}function kw({onClose:t,capabilities:r=[]}){const[n,s]=i.useState(null),[a,o]=i.useState(!0),[l,c]=i.useState(!1),[u,x]=i.useState(""),[p,d]=i.useState(!1),m=i.useCallback(async()=>{try{const A=await window.api.analytics.getDashboard(7);s(A||null),x("")}catch(A){x(A&&A.message?A.message:String(A))}finally{o(!1)}},[]);i.useEffect(()=>{m();const A=window.setInterval(()=>{m()},1e4);return()=>{window.clearInterval(A)}},[m]),i.useEffect(()=>{if(!window.matchMedia)return;const A=window.matchMedia("(prefers-reduced-motion: reduce)"),C=()=>d(!!A.matches);return C(),typeof A.addEventListener=="function"?(A.addEventListener("change",C),()=>A.removeEventListener("change",C)):(A.addListener(C),()=>A.removeListener(C))},[]);const f=async A=>{c(!0);try{await window.api.analytics.setEnabled(!!A),await m()}catch(C){x(C&&C.message?C.message:String(C))}finally{c(!1)}},b=async()=>{c(!0);try{await window.api.analytics.clear(),await m()}catch(A){x(A&&A.message?A.message:String(A))}finally{c(!1)}},h=jw(n&&n.latencySeries?n.latencySeries:[]),g=Array.isArray(r)&&(r.includes("operator_dashboard")||r.includes("release_health_console")),y=Array.isArray(r)&&r.includes("funnel_dashboard"),P=Array.isArray(r)&&r.includes("revenue_console");return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[70] bg-black/50 backdrop-blur-[2px]",onClick:t}),e.jsxs("aside",{className:`fixed right-0 top-0 bottom-0 z-[80] w-full max-w-xl border-l border-cyan-400/20 bg-slate-950 p-6 overflow-y-auto ${p?"":"animate-in slide-in-from-right duration-300"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.2em] text-cyan-400 font-bold",children:"Analytics Dashboard"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"Local-only usage telemetry (7 day window)."})]}),e.jsx("button",{onClick:t,className:"h-9 w-9 rounded-full border border-white/10 text-slate-300 hover:text-white hover:bg-white/10",children:"✕"})]}),a&&e.jsx("div",{className:"text-[11px] font-mono text-slate-400",children:"Loading analytics..."}),u&&e.jsx("div",{className:"rounded-xl border border-rose-400/30 bg-rose-500/10 px-3 py-2 text-[10px] font-mono text-rose-200 mb-3",children:u}),!a&&n&&e.jsxs("div",{className:"space-y-4",children:[g&&e.jsx(cw,{}),y&&e.jsx(bw,{}),P&&e.jsx(vw,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Events"}),e.jsx("div",{className:"text-lg font-bold text-slate-100",children:Number(n.eventCount||0).toLocaleString()})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Tokens"}),e.jsx("div",{className:"text-lg font-bold text-slate-100",children:Number(n.totalTokens||0).toLocaleString()})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Median Latency"}),e.jsxs("div",{className:"text-lg font-bold text-slate-100",children:[Number(n.medianLatencyMs||0)," ms"]})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Estimated Spend"}),e.jsxs("div",{className:"text-lg font-bold text-slate-100",children:["$",Number(n.estimatedUsd||0).toFixed(2)]})]})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold mb-2",children:"Latency Trend"}),e.jsxs("div",{className:"h-16 flex items-end gap-1",children:[h.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No samples yet."}),h.map((A,C)=>e.jsx("div",{title:`${A.latencyMs}ms`,className:"w-2 rounded-sm bg-cyan-400/70",style:{height:`${A.h}px`}},`bar-${C}`))]})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold mb-2",children:"Model Mix"}),e.jsxs("div",{className:"space-y-1",children:[(n.modelMix||[]).slice(0,8).map(A=>e.jsxs("div",{className:"text-[10px] font-mono text-slate-300 flex justify-between gap-2",children:[e.jsx("span",{className:"truncate",children:A.model}),e.jsx("span",{children:Number(A.count||0).toLocaleString()})]},A.model)),(!n.modelMix||n.modelMix.length===0)&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No model usage yet."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"analytics-enable-btn",disabled:l,onClick:()=>f(!n.enabled),className:`px-3 py-2 rounded-xl border text-[10px] uppercase tracking-[0.16em] font-bold ${n.enabled?"border-emerald-300/30 bg-emerald-500/10 text-emerald-200":"border-slate-400/30 bg-slate-500/10 text-slate-200"} disabled:opacity-60`,children:n.enabled?"Disable Analytics":"Enable Analytics"}),e.jsx("button",{type:"button","data-testid":"analytics-clear-btn",disabled:l,onClick:b,className:"px-3 py-2 rounded-xl border border-rose-300/30 bg-rose-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-rose-200 disabled:opacity-60",children:"Clear Data"}),e.jsx("button",{type:"button",onClick:m,disabled:l,className:"px-3 py-2 rounded-xl border border-white/10 bg-white/5 text-[10px] uppercase tracking-[0.16em] font-bold text-slate-200 disabled:opacity-60",children:"Refresh"})]})]})]})]})}const Fa=[{id:"getting_started",title:"Getting Started",body:`# NeuralShell Workpad +Memory: ${t.stats.memoryMb}MB`})}});Nt({id:"cmd-help",slot:"palette.system",title:"Show Help Guide",priority:50,stability:"core",contexts:["global"],contextLabel:"Global",action:t=>{t&&typeof t.appendChat=="function"&&t.appendChat({role:"assistant",content:"### ProofForge Help Guide\n\n- `/help` : Show this guide\n- `/status` : Check node telemetry\n- `/clear` : Clear current thread\n- `/purge` : Delete all session history\n- `Ctrl+K` : Command Palette\n- `Ctrl+Shift+T` : Operator Inbox\n- `Ctrl+Shift+N` : Workpad\n- `Ctrl+P` : Projects panel"})}});const og=24,qp="neuralshell_palette_mru_v1";function ig(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(qp)||"[]");return Es(t)}catch{return[]}}function lg(t){if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(qp,JSON.stringify(Es(t)))}catch{}}function Pd(t,r){return`command-palette-option-${String(t&&t.key||`item-${r}`).replace(/[^a-zA-Z0-9_-]/g,"-")}`}function cg({onClose:t}){const r=$l(),s=typeof navigator<"u"&&/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl",a=i.useRef(null),o=i.useRef(new Map),c=i.useRef(null),l=i.useRef(!1);!l.current&&typeof document<"u"&&(c.current=document.activeElement,l.current=!0);const[u,x]=i.useState(""),[p,d]=i.useState(0),[m,f]=i.useState(()=>ig());i.useEffect(()=>{lg(m)},[m]),i.useEffect(()=>{var P;(P=a.current)==null||P.focus({preventScroll:!0})},[]);const b=i.useMemo(()=>tg(r),[r]),h=i.useMemo(()=>ag({context:b}).map((D,z)=>({key:`command:${String(D&&D.id||`cmd-${z}`)}`,id:String(D&&D.id||`cmd-${z}`),label:String(D&&D.title||`Command ${z+1}`),subtitle:String(D&&D.contextLabel||"Command"),kind:"command",action:D&&D.action,shortcutNumber:D&&D.shortcut?null:z<9?z+1:null,shortcut:D&&D.shortcut||(z<9?`${s} + ${z+1}`:""),keywords:`${String(D&&D.title||"")} ${String(D&&D.id||"")} ${String(D&&D.contextLabel||"")} command`,contextWeight:Array.isArray(D&&D.contexts)&&D.contexts.some(F=>b.contexts.includes(F))?8:0,baseIndex:z})),[s,b]),g=i.useMemo(()=>{const P=Array.isArray(r&&r.sessions)?r.sessions:[],D=String(r&&r.workflowId||"").trim(),z=!!(r&&typeof r.isSessionUnlocked=="function");return P.map((F,J)=>{const ee=String(F||"").trim(),ie=ee===D,ye=z?!r.isSessionUnlocked(ee):!1;return{key:`session:${ee}`,id:ee,label:ee,subtitle:ie?"Active workflow":"Workflow session",kind:"session",sessionName:ee,active:ie,locked:ye,shortcutNumber:null,shortcut:"",keywords:`${ee} workflow session thread`,contextWeight:ie?8:0,baseIndex:1e3+J}})},[r]),y=i.useMemo(()=>[...h,...g],[h,g]),I=i.useMemo(()=>As(u),[u]),A=i.useMemo(()=>Xh(u),[u]),C=i.useMemo(()=>new Map(m.map((P,D)=>[P.key,{...P,rank:D}])),[m]),w=i.useMemo(()=>y.map(P=>{const D=C.get(P.key)||null;return{item:P,score:ng(P,I,A,D),mruRank:D?D.rank:-1}}).filter(P=>Number.isFinite(P.score)&&P.score>Number.NEGATIVE_INFINITY).sort((P,D)=>D.score!==P.score?D.score-P.score:P.mruRank!==D.mruRank?P.mruRank<0?1:D.mruRank<0?-1:P.mruRank-D.mruRank:P.item.baseIndex!==D.item.baseIndex?P.item.baseIndex-D.item.baseIndex:String(P.item.label||"").localeCompare(String(D.item.label||""))).slice(0,og).map(P=>P.item),[y,C,I,A]),j=i.useMemo(()=>{let P=0,D=0;for(const z of w)z.kind==="session"?D+=1:P+=1;return{commands:P,sessions:D}},[w]);i.useEffect(()=>{d(0)},[I]),i.useEffect(()=>{p0?w.length-1:0)},[w.length,p]),i.useEffect(()=>{const P=w[p];if(!P)return;const D=o.current.get(P.key);D&&typeof D.scrollIntoView=="function"&&D.scrollIntoView({block:"nearest"})},[w,p]);const E=i.useCallback(P=>{f(D=>eg(D,P))},[]),N=i.useCallback(()=>{const P=c.current;t(),window.requestAnimationFrame(()=>{P&&typeof P.focus=="function"&&P.focus({preventScroll:!0})})},[t]),_=i.useCallback(P=>{if(P){if(P.kind==="command")typeof P.action=="function"&&P.action(r);else if(P.kind==="session"){const D=String(P.sessionName||"").trim();D&&r&&typeof r.selectSession=="function"&&r.selectSession(D)}E(P.key),N()}},[N,E,r]),S=i.useCallback(P=>{if(P.key==="Escape"){P.preventDefault(),N();return}if((P.ctrlKey||P.metaKey)&&/^[1-9]$/.test(P.key)){const D=Number(P.key),z=h.find(F=>F.shortcutNumber===D);z&&(P.preventDefault(),_(z));return}if(P.key==="ArrowDown"){if(P.preventDefault(),!w.length)return;d(D=>(D+1)%w.length);return}if(P.key==="ArrowUp"){if(P.preventDefault(),!w.length)return;d(D=>(D-1+w.length)%w.length);return}if(P.key==="PageDown"){if(P.preventDefault(),!w.length)return;d(D=>Math.min(w.length-1,D+5));return}if(P.key==="PageUp"){if(P.preventDefault(),!w.length)return;d(D=>Math.max(0,D-5));return}if(P.key==="Home"){P.preventDefault(),d(0);return}if(P.key==="End"){if(P.preventDefault(),!w.length)return;d(w.length-1);return}if(P.key==="Enter"){if(P.preventDefault(),!w.length)return;const D=w[p]||w[0];_(D)}},[N,h,w,_,p]),R=w[p]||null,$=R?Pd(R,p):void 0,U=i.useMemo(()=>sg({resultCount:w.length,selectedLabel:R&&R.label,query:u}),[w.length,u,R]);return e.jsx("div",{"data-testid":"command-palette",role:"dialog","aria-modal":"true","aria-label":"Command palette",className:"fixed inset-0 z-50 flex items-start justify-center pt-[15vh] px-4 backdrop-blur-md bg-black/60 animate-in fade-in duration-200",onClick:N,children:e.jsxs("div",{className:"w-full max-w-2xl bg-slate-900/80 backdrop-blur-xl border border-cyan-400/30 rounded-2xl shadow-[0_20px_50px_rgba(0,0,0,0.5),0_0_30px_rgba(34,211,238,0.1)] overflow-hidden",onClick:P=>P.stopPropagation(),children:[e.jsxs("div",{className:"p-4 border-b border-white/5 flex items-center gap-3",children:[e.jsx("span",{className:"text-cyan-400 font-mono text-xl",children:"/"}),e.jsx("input",{ref:a,"data-testid":"command-palette-input",value:u,onChange:P=>x(P.target.value),onKeyDown:S,"aria-label":"Search commands and sessions","aria-controls":"command-palette-results","aria-activedescendant":$,"aria-describedby":"command-palette-live-status command-palette-help",className:"flex-1 bg-transparent border-none outline-none text-lg text-slate-100 placeholder-slate-600",placeholder:"Search commands, workflows, and sessions..."}),e.jsxs("div",{className:"text-[10px] text-slate-500 bg-white/5 px-2 py-1 rounded border border-white/10 uppercase font-bold",children:[w.length," Result",w.length===1?"":"s"]})]}),e.jsxs("div",{className:"px-4 py-2 border-b border-white/5 text-[10px] font-mono text-slate-500 flex items-center justify-between",children:[e.jsxs("span",{children:[j.commands," command",j.commands===1?"":"s"]}),e.jsxs("span",{children:[j.sessions," workflow",j.sessions===1?"":"s"]})]}),e.jsx("div",{id:"command-palette-live-status","data-testid":"command-palette-live-status",className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:U}),e.jsx("div",{id:"command-palette-help",className:"sr-only",children:"Use arrow keys to move, Enter to run, Escape to close, and Page Up or Page Down to jump results."}),e.jsx("div",{id:"command-palette-results",className:"p-2 max-h-96 overflow-y-auto no-scrollbar",role:"listbox","aria-label":"Available palette results",children:w.length===0?e.jsxs("div",{className:"px-3 py-8 text-center",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"No Matches"}),e.jsx("div",{className:"mt-1 text-[10px] font-mono text-slate-500",children:"Try a simpler keyword or clear the query."})]}):w.map((P,D)=>{const z=D===p;return e.jsx("button",{id:Pd(P,D),ref:F=>{F?o.current.set(P.key,F):o.current.delete(P.key)},role:"option","aria-selected":z,"data-testid":`command-palette-item-${P.kind}-${P.id}`,className:`w-full text-left p-3 rounded-xl transition-all border ${z?"bg-cyan-400/15 border-cyan-400/25":"hover:bg-cyan-400/10 border-transparent"}`,onMouseMove:()=>{z||d(D)},onClick:()=>_(P),children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:z?"text-cyan-100 font-semibold truncate":"text-slate-200 font-semibold truncate",children:P.label}),e.jsxs("div",{className:"mt-0.5 text-[10px] font-mono text-slate-500 truncate",children:[P.subtitle,P.kind==="session"&&P.locked?" · Locked":""]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${P.kind==="session"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-200":"border-cyan-300/30 bg-cyan-500/10 text-cyan-200"}`,children:P.kind==="session"?"Workflow":"Command"}),P.active?e.jsx("span",{className:"px-1.5 py-0.5 rounded border border-amber-300/30 bg-amber-500/10 text-[9px] font-mono uppercase tracking-[0.14em] text-amber-200",children:"Active"}):null,P.shortcut?e.jsx("span",{className:`text-[9px] font-mono uppercase ${z?"text-cyan-300":"text-slate-600"}`,children:P.shortcut}):null]})]})},P.key)})})]})})}function dg(t,r){const n=new Blob([`${JSON.stringify(r,null,2)} +`],{type:"application/json"}),s=URL.createObjectURL(n),a=document.createElement("a");a.href=s,a.download=t,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(s)}function ug(){const[t,r]=i.useState(""),[n,s]=i.useState(""),[a,o]=i.useState(!1),[c,l]=i.useState({tone:"idle",text:""}),u=async()=>{o(!0);try{await window.api.vault.lock(),l({tone:"ok",text:"Vault locked."})}catch(m){l({tone:"bad",text:`Vault lock failed: ${m&&m.message?m.message:String(m)}`})}finally{o(!1)}},x=async()=>{o(!0);try{await window.api.vault.unlock(t),l({tone:"ok",text:"Vault unlocked."})}catch(m){l({tone:"bad",text:`Vault unlock failed: ${m&&m.message?m.message:String(m)}`})}finally{o(!1)}},p=async()=>{o(!0);try{const m=await window.api.vault.export(t);if(!m||!m.ok||!m.blob)throw new Error("Vault export returned no blob payload.");const f=new Date().toISOString().replace(/[:.]/g,"-");dg(`neuralshell-vault-${f}.json`,m.blob),l({tone:"ok",text:`Vault exported (${Number(m.count)||0} entries).`})}catch(m){l({tone:"bad",text:`Vault export failed: ${m&&m.message?m.message:String(m)}`})}finally{o(!1)}},d=async()=>{o(!0);try{const m=JSON.parse(String(n||"{}")),f=await window.api.vault.import(m,t,{mode:"merge"});if(!f||!f.ok)throw new Error("Vault import failed.");l({tone:"ok",text:`Vault imported (${Number(f.imported)||0} entries).`})}catch(m){l({tone:"bad",text:`Vault import failed: ${m&&m.message?m.message:String(m)}`})}finally{o(!1)}};return e.jsxs("section",{"data-testid":"vault-card",className:"space-y-4 p-5 bg-black/30 rounded-2xl border border-cyan-400/20 shadow-inner",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-cyan-400 font-bold",children:"Vault+"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"Provider secrets are encrypted at rest and exported/imported as AES-GCM JSON blobs."}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[10px] text-slate-400 uppercase tracking-widest font-bold ml-1",children:"Vault Passphrase"}),e.jsx("input",{"data-testid":"vault-passphrase-input",type:"password",value:t,onChange:m=>r(m.target.value),placeholder:"Required for unlock / export / import",className:"w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-sm text-slate-200 placeholder-slate-600 outline-none focus:border-cyan-400/50 focus:ring-1 focus:ring-cyan-400/10 transition-all font-mono"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx("button",{"data-testid":"vault-unlock-btn",type:"button",onClick:x,disabled:a,className:"px-3 py-2 rounded-xl border border-emerald-300/30 bg-emerald-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-emerald-200 hover:bg-emerald-500/20 disabled:opacity-50",children:"Unlock Vault"}),e.jsx("button",{"data-testid":"vault-lock-btn",type:"button",onClick:u,disabled:a,className:"px-3 py-2 rounded-xl border border-amber-300/30 bg-amber-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-amber-200 hover:bg-amber-500/20 disabled:opacity-50",children:"Lock Vault"}),e.jsx("button",{"data-testid":"vault-export-btn",type:"button",onClick:p,disabled:a,className:"px-3 py-2 rounded-xl border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-cyan-200 hover:bg-cyan-500/20 disabled:opacity-50",children:"Export Vault"}),e.jsx("button",{"data-testid":"vault-import-btn",type:"button",onClick:d,disabled:a,className:"px-3 py-2 rounded-xl border border-violet-300/30 bg-violet-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-violet-200 hover:bg-violet-500/20 disabled:opacity-50",children:"Import Vault"})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[10px] text-slate-400 uppercase tracking-widest font-bold ml-1",children:"Import JSON Blob"}),e.jsx("textarea",{"data-testid":"vault-import-json",value:n,onChange:m=>s(m.target.value),placeholder:"Paste vault export JSON blob here",className:"min-h-24 w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-[11px] text-slate-200 placeholder-slate-600 outline-none focus:border-cyan-400/50 focus:ring-1 focus:ring-cyan-400/10 transition-all font-mono resize-y"})]}),c.text&&e.jsx("div",{className:`rounded-xl border px-3 py-2 text-[10px] font-mono ${c.tone==="ok"?"border-emerald-400/30 bg-emerald-500/10 text-emerald-200":c.tone==="bad"?"border-rose-400/30 bg-rose-500/10 text-rose-200":"border-white/10 bg-black/30 text-slate-300"}`,children:c.text})]})}function pg({licenseMode:t=""}){const[r,n]=i.useState(!1),[s,a]=i.useState(!1),[o,c]=i.useState(""),l=String(t||"").trim().toLowerCase()==="auditor";i.useEffect(()=>{let x=!0;return(async()=>{try{const p=await window.api.proofRelay.getConfig();if(!x)return;n(!!(p&&p.enabled))}catch(p){if(!x)return;c(`Proof relay config load failed: ${p&&p.message?p.message:String(p)}`)}})(),()=>{x=!1}},[]);const u=async()=>{if(!l){a(!0);try{const x=await window.api.proofRelay.setConfig({enabled:!r,channel:"auto"});n(!!(x&&x.enabled)),c(x&&x.enabled?"Proof relay enabled.":"Proof relay disabled.")}catch(x){c(`Proof relay update failed: ${x&&x.message?x.message:String(x)}`)}finally{a(!1)}}};return e.jsxs("section",{"data-testid":"proof-relay-toggle",className:"space-y-3 p-5 bg-black/30 rounded-2xl border border-white/5 shadow-inner",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-emerald-300 font-bold",children:"Proof Relay Webhook"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"When enabled, a successful `npm run proof:bundle` posts repo/tag/SHA/manifest to Slack/Discord."})]}),e.jsx("button",{type:"button","data-testid":"proof-relay-toggle-btn",onClick:u,disabled:s||l,className:`h-8 min-w-20 rounded-lg border px-3 text-[10px] uppercase tracking-[0.16em] font-bold transition-colors ${r?"border-emerald-300/40 bg-emerald-500/20 text-emerald-100":"border-slate-500/30 bg-slate-700/20 text-slate-300"} disabled:opacity-60`,children:r?"ON":"OFF"})]}),l&&e.jsx("div",{className:"rounded-xl border border-amber-400/30 bg-amber-500/10 px-3 py-2 text-[10px] font-mono text-amber-200",children:"Auditor mode is active; proof relay is forced off."}),o&&e.jsx("div",{className:"rounded-xl border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-300",children:o})]})}function mg({licenseMode:t=""}){const[r,n]=i.useState({enabled:!1,channel:"stable",available:!1}),[s,a]=i.useState({pending:!1,available:!1}),[o,c]=i.useState(!1),[l,u]=i.useState(""),x=String(t||"").trim().toLowerCase()==="auditor",p=i.useCallback(async()=>{try{const[f,b]=await Promise.all([window.api.autoUpdate.getPolicy(),window.api.autoUpdate.pending()]);n(f||{enabled:!1,channel:"stable",available:!1}),a(b||{pending:!1,available:!1})}catch(f){u(`Auto-update status load failed: ${f&&f.message?f.message:String(f)}`)}},[]);i.useEffect(()=>{p()},[p]);const d=async f=>{if(!x){c(!0);try{const b=await window.api.autoUpdate.setPolicy({enabled:f,channel:r.channel||"stable"});n(b||r),u(f?"Auto-update lane enabled.":"Auto-update lane disabled.")}catch(b){u(`Auto-update toggle failed: ${b&&b.message?b.message:String(b)}`)}finally{c(!1)}}},m=async f=>{if(!x){c(!0);try{const b=await window.api.autoUpdate.setPolicy({enabled:r.enabled,channel:f});n(b||r),u(`Auto-update channel set to ${f}.`)}catch(b){u(`Auto-update channel update failed: ${b&&b.message?b.message:String(b)}`)}finally{c(!1)}}};return e.jsxs("section",{"data-testid":"auto-update-card",className:"space-y-3 p-5 bg-black/30 rounded-2xl border border-white/5 shadow-inner",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-cyan-300 font-bold",children:"Deterministic Auto-Update"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"Verified SHA-256 + signature lane with staged swap-on-restart behavior."})]}),e.jsx("button",{type:"button","data-testid":"auto-update-toggle-btn",onClick:()=>d(!r.enabled),disabled:o||x||!r.available,className:`h-8 min-w-20 rounded-lg border px-3 text-[10px] uppercase tracking-[0.16em] font-bold transition-colors ${r.enabled?"border-emerald-300/40 bg-emerald-500/20 text-emerald-100":"border-slate-500/30 bg-slate-700/20 text-slate-300"} disabled:opacity-60`,children:r.enabled?"ON":"OFF"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Channel"}),e.jsxs("select",{"data-testid":"auto-update-channel",value:String(r.channel||"stable"),onChange:f=>m(f.target.value),disabled:o||x||!r.available,className:"bg-slate-900 border border-white/10 rounded px-2 py-1 text-[11px] text-slate-200 font-mono",children:[e.jsx("option",{value:"stable",children:"stable"}),e.jsx("option",{value:"canary",children:"canary"})]}),e.jsx("button",{type:"button",onClick:p,disabled:o,className:"px-2 py-1 rounded border border-white/10 text-[10px] font-mono text-slate-300 hover:bg-white/10 disabled:opacity-60",children:"Refresh"})]}),e.jsx("div",{className:`rounded-xl border px-3 py-2 text-[10px] font-mono ${s.pending?"border-amber-300/30 bg-amber-500/10 text-amber-200":"border-emerald-300/20 bg-emerald-500/10 text-emerald-200"}`,children:s.pending?"Pending verified swap is queued for next restart.":"No pending swap queued."}),x&&e.jsx("div",{className:"rounded-xl border border-amber-400/30 bg-amber-500/10 px-3 py-2 text-[10px] font-mono text-amber-200",children:"Auditor mode is active; auto-update lane is forced to read-only."}),l&&e.jsx("div",{className:"rounded-xl border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-300",children:l})]})}function Rd(t){return Object.entries(t&&typeof t=="object"?t:{}).map(([n,s])=>({repo:String(n||"").trim(),slackWebhook:String(s&&s.slackWebhook?s.slackWebhook:""),discordWebhook:String(s&&s.discordWebhook?s.discordWebhook:"")})).filter(n=>n.repo)}function xg(t){const r={};for(const n of Array.isArray(t)?t:[]){const s=String(n&&n.repo?n.repo:"").trim();s&&(r[s]={slackWebhook:String(n&&n.slackWebhook?n.slackWebhook:"").trim(),discordWebhook:String(n&&n.discordWebhook?n.discordWebhook:"").trim()})}return r}function fg({licenseMode:t=""}){const[r,n]=i.useState([]),[s,a]=i.useState(!1),[o,c]=i.useState(""),l=String(t||"").trim().toLowerCase()==="auditor";i.useEffect(()=>{let m=!0;return(async()=>{try{const f=await window.api.proofRelay.getRepoMap();if(!m)return;n(Rd(f&&f.map?f.map:{}))}catch(f){if(!m)return;c(`Repo relay map load failed: ${f&&f.message?f.message:String(f)}`)}})(),()=>{m=!1}},[]);const u=(m,f,b)=>{n(h=>h.map((g,y)=>y===m?{...g,[f]:b}:g))},x=()=>{n(m=>[...m,{repo:"",slackWebhook:"",discordWebhook:""}])},p=m=>{n(f=>f.filter((b,h)=>h!==m))},d=async()=>{if(!l){a(!0);try{const m=await window.api.proofRelay.setRepoMap({map:xg(r)});n(Rd(m&&m.map?m.map:{})),c("Proof relay map saved to Vault+.")}catch(m){c(`Proof relay map save failed: ${m&&m.message?m.message:String(m)}`)}finally{a(!1)}}};return e.jsxs("section",{"data-testid":"proof-relay-map",className:"space-y-3 p-5 bg-black/30 rounded-2xl border border-white/5 shadow-inner",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-cyan-300 font-bold",children:"Proof Relay Mapping"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"Assign per-repository Slack/Discord webhooks for proof bundle notifications."})]}),e.jsx("button",{type:"button","data-testid":"proof-relay-map-add-row-btn",onClick:x,disabled:l,className:"px-3 py-1.5 rounded-lg border border-white/15 bg-white/5 text-[10px] font-mono uppercase tracking-[0.14em] text-slate-200 hover:bg-white/10 disabled:opacity-50",children:"Add Repo"})]}),e.jsxs("div",{className:"space-y-2",children:[r.length===0&&e.jsx("div",{className:"rounded-xl border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-500",children:"No repository mappings yet."}),r.map((m,f)=>e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:[e.jsx("input",{"data-testid":`proof-relay-map-repo-${f}`,value:m.repo,onChange:b=>u(f,"repo",b.target.value),placeholder:"repo slug (e.g. org/foo)",disabled:l,className:"bg-slate-900 border border-white/10 rounded-lg px-3 py-2 text-[11px] text-slate-200 font-mono outline-none focus:border-cyan-400/40 disabled:opacity-60"}),e.jsx("input",{"data-testid":`proof-relay-map-slack-${f}`,value:m.slackWebhook,onChange:b=>u(f,"slackWebhook",b.target.value),placeholder:"Slack webhook URL",disabled:l,className:"bg-slate-900 border border-white/10 rounded-lg px-3 py-2 text-[11px] text-slate-200 font-mono outline-none focus:border-cyan-400/40 disabled:opacity-60"}),e.jsx("input",{"data-testid":`proof-relay-map-discord-${f}`,value:m.discordWebhook,onChange:b=>u(f,"discordWebhook",b.target.value),placeholder:"Discord webhook URL",disabled:l,className:"bg-slate-900 border border-white/10 rounded-lg px-3 py-2 text-[11px] text-slate-200 font-mono outline-none focus:border-cyan-400/40 disabled:opacity-60"})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx("button",{type:"button","data-testid":`proof-relay-map-remove-${f}`,onClick:()=>p(f),disabled:l,className:"px-2 py-1 rounded border border-rose-300/30 bg-rose-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-rose-200 hover:bg-rose-500/20 disabled:opacity-50",children:"Remove"})})]},`${m.repo||"repo"}-${f}`))]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("button",{type:"button","data-testid":"proof-relay-map-save-btn",onClick:d,disabled:s||l,className:"px-3 py-2 rounded-lg border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-cyan-100 hover:bg-cyan-500/20 disabled:opacity-50",children:s?"Saving":"Save Mapping"}),l&&e.jsx("span",{className:"text-[10px] font-mono text-amber-300",children:"Auditor mode: relay mapping edits are disabled."})]}),o&&e.jsx("div",{className:"rounded-xl border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-300",children:o})]})}function bg(t){const r=String(t||"").trim();if(/^#[0-9a-fA-F]{6}$/.test(r))return r;if(/^#[0-9a-fA-F]{3}$/.test(r)){const[n,s,a]=r.slice(1).split("");return`#${n}${n}${s}${s}${a}${a}`}return"#22d3ee"}function hg(t,r="#22d3ee"){const n=bg(r),s=document.createElement("canvas");s.width=1200,s.height=630;const a=s.getContext("2d");if(!a)throw new Error("Canvas context unavailable.");const o=a.createLinearGradient(0,0,s.width,s.height);return o.addColorStop(0,"#020617"),o.addColorStop(1,"#0f172a"),a.fillStyle=o,a.fillRect(0,0,s.width,s.height),a.strokeStyle=`${n}99`,a.lineWidth=3,a.strokeRect(34,34,s.width-68,s.height-68),a.fillStyle=n,a.font="700 28px monospace",a.fillText("ProofForge Sweep Proof",64,90),a.fillStyle="#e2e8f0",a.font="600 22px monospace",a.fillText(`Provider: ${String(t.provider||"unknown")}`,64,170),a.fillText(`Model: ${String(t.model||"unknown")}`,64,220),a.fillText(`Models Detected: ${Number(t.modelCount||0)}`,64,270),a.fillText(`Generated: ${new Date().toISOString()}`,64,320),a.fillStyle="#94a3b8",a.font="500 18px monospace",a.fillText("Verification lane: Bridge test passed, share route minted.",64,390),a.fillStyle=`${n}2E`,a.fillRect(64,440,s.width-128,120),a.fillStyle=n,a.font="700 24px monospace",a.fillText("Top-Notch Proof Artifact",84,510),s.toDataURL("image/png")}function gg(t,r){const n=document.createElement("a");n.href=r,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n)}function yg({open:t,payload:r,onClose:n}){const[s,a]=i.useState(!1),[o,c]=i.useState(""),[l,u]=i.useState(""),[x,p]=i.useState("");if(i.useEffect(()=>{if(!t||!r)return;u(""),p(""),c("");let m=!0;return(async()=>{try{const f=await Oh({app:"ProofForge",generatedAt:new Date().toISOString(),messages:[{role:"assistant",content:["Bridge Sweep Success",`Provider: ${String(r.provider||"unknown")}`,`Model: ${String(r.model||"unknown")}`,`Models Detected: ${Number(r.modelCount||0)}`].join(` +`)}]});if(!m)return;const b=window.getComputedStyle(document.body).getPropertyValue("--accent").trim()||"#22d3ee";p(Mh(f.hash,f.fragment)),u(hg(r,b))}catch(f){if(!m)return;c(`Proof share prep failed: ${f&&f.message?f.message:String(f)}`)}})(),()=>{m=!1}},[t,r]),!t)return null;const d=async()=>{if(!(!l||!x)){a(!0);try{gg(`neuralshell-proof-${Date.now()}.png`,l),await navigator.clipboard.writeText(x),c("PNG downloaded and /share link copied to clipboard.")}catch(m){c(`Share failed: ${m&&m.message?m.message:String(m)}`)}finally{a(!1)}}};return e.jsx("div",{className:"fixed inset-0 z-[90] bg-black/70 backdrop-blur-sm flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-3xl rounded-2xl border border-cyan-400/20 bg-slate-950 p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.2em] text-cyan-300 font-bold",children:"Share Proof Badge"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"Preview then share a generated PNG + `/share/` link."})]}),e.jsx("button",{type:"button",onClick:n,className:"h-9 w-9 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),l?e.jsx($h,{src:l,alt:"Proof preview",className:"w-full rounded-xl border border-white/10 min-h-52",placeholderClassName:"rounded-xl"}):e.jsx("div",{className:"h-52 rounded-xl border border-white/10 bg-black/30 flex items-center justify-center text-[11px] font-mono text-slate-500",children:"Preparing badge preview..."}),x&&e.jsx("div",{className:"mt-3 rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-300 break-all",children:x}),e.jsxs("div",{className:"mt-4 flex items-center gap-2 justify-end",children:[e.jsx("button",{type:"button",onClick:n,className:"px-3 py-2 rounded-lg border border-white/10 text-[10px] uppercase tracking-[0.14em] font-bold text-slate-300",children:"Close"}),e.jsx("button",{type:"button","data-testid":"share-proof-btn",onClick:d,disabled:s||!l||!x,className:"px-3 py-2 rounded-lg border text-[10px] uppercase tracking-[0.14em] font-bold disabled:opacity-50",style:{borderColor:"rgb(var(--accent-rgb) / 0.38)",backgroundColor:"rgb(var(--accent-rgb) / 0.14)",color:"var(--accent)"},children:"Share"})]}),o&&e.jsx("div",{className:"mt-3 rounded-xl border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-300",children:o})]})})}function wg(t){return t==="connected"?"text-emerald-300":t==="failed"?"text-rose-300":t==="skipped"?"text-amber-300":"text-slate-400"}function vg(t,r){return r?"border-cyan-400/35 bg-cyan-500/5 ring-1 ring-cyan-400/15":t==="connected"?"border-emerald-400/20 bg-emerald-500/5":t==="failed"?"border-rose-400/20 bg-rose-500/5":t==="skipped"?"border-amber-400/20 bg-amber-500/5":"border-white/10 bg-black/30"}function jg({providerSweep:t,providerSweepRows:r,providerSweepBusy:n,providerSweepUpdatedAt:s,activeProviderId:a,onRefresh:o,hostedProxyEnabled:c,hostedProxyStatus:l,onToggleHostedProxy:u}){const x=!!(l&&l.running),p=Number(l&&l.rateCapPerMinute?l.rateCapPerMinute:60);return e.jsxs("section",{children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-widest text-emerald-300 mb-4 font-bold flex items-center justify-between",children:[e.jsx("span",{children:"Provider Health"}),e.jsx("button",{type:"button","data-testid":"settings-provider-sweep-btn",onClick:o,disabled:n,className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] font-mono uppercase tracking-[0.14em] text-emerald-200 hover:bg-emerald-500/20 disabled:opacity-50",children:n?"Checking":"Refresh"})]}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-[10px] text-slate-500 font-mono",children:[t?`${Number(t.connected||0)}/${Number(t.total||0)} connected`:"No provider sweep has been run yet.",s?` · ${s}`:""]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${c?"border-cyan-300/30 bg-cyan-500/10 text-cyan-200":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:["Hosted Proxy ",c?"On":"Off"]}),c&&e.jsxs("span",{className:"px-2 py-1 rounded border border-amber-300/30 bg-amber-500/10 text-[9px] font-mono uppercase tracking-[0.14em] text-amber-200",children:["Rate cap ",p,"/min"]}),e.jsx("button",{type:"button","data-testid":"settings-hosted-proxy-toggle-btn",onClick:u,className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] font-mono uppercase tracking-[0.14em] text-slate-200 hover:bg-white/10",children:c?"Disable Proxy":"Use Hosted Proxy"})]})]}),c&&e.jsx("div",{className:`rounded-lg border px-3 py-2 text-[10px] font-mono ${x?"border-emerald-300/30 bg-emerald-500/10 text-emerald-200":"border-amber-300/30 bg-amber-500/10 text-amber-200"}`,children:x?`Hosted proxy active at ${l.baseUrl||"localhost"}`:"Hosted proxy is enabled and will start when provider validation runs."}),e.jsxs("div",{className:"space-y-2",children:[n&&r.length===0&&[1,2,3].map(d=>e.jsx("div",{className:"h-12 rounded-lg border border-white/5 bg-white/[0.03] animate-pulse"},`sweep-skeleton-${d}`)),!n&&r.length===0&&e.jsx("div",{"data-testid":"settings-provider-sweep-empty",className:"text-center py-6 text-[10px] font-mono text-slate-500 border border-dashed border-white/10 rounded-xl",children:"No provider results yet — click Refresh to run a sweep."}),r.map(d=>{const m=String(a||"")===String(d.id||"");return e.jsxs("div",{className:`rounded-lg border px-3 py-2 transition-colors ${vg(d.status,m)}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-[10px] uppercase tracking-[0.14em] font-bold text-slate-200 flex items-center gap-1.5",children:[d.label,m&&e.jsx("span",{className:"px-1 py-0.5 rounded bg-cyan-500/15 text-cyan-200 text-[8px] font-mono border border-cyan-400/25",children:"active"})]}),e.jsx("span",{className:`text-[9px] font-mono uppercase tracking-[0.14em] ${wg(d.status)}`,children:d.status})]}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono mt-0.5",children:d.detail})]},d.id)})]})]})]})}const kg=[{id:"free",label:"Free",priceUsd:0,billingPeriod:"forever",checkout:{gumroad:"",stripe:"",manualInvoice:!1}},{id:"pro",label:"Pro",priceUsd:99,billingPeriod:"one_time",checkout:{gumroad:"https://gumroad.com/l/neuralshell-operator",stripe:"https://buy.stripe.com/test_neuralshell_pro",manualInvoice:!1}},{id:"enterprise",label:"Enterprise",priceUsd:499,billingPeriod:"annual",checkout:{gumroad:"",stripe:"",manualInvoice:!0,invoiceUrl:"mailto:enterprise@neuralshell.app?subject=NeuralShell%20Enterprise%20Invoice%20Request"}}],vn={plans:kg};function Ng(t){return t==="active"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-200":t==="grace"?"border-amber-300/30 bg-amber-500/10 text-amber-200":t==="expired"?"border-rose-300/30 bg-rose-500/10 text-rose-200":"border-slate-300/20 bg-slate-500/10 text-slate-300"}function Od(t){const r=t&&typeof t=="object"?t:{};return{present:!!r.present,status:String(r.status||"none"),planId:String(r.planId||"free"),planLabel:String(r.planLabel||"Free"),seats:Number(r.seats||1),expiresAt:String(r.expiresAt||""),graceEndsAt:String(r.graceEndsAt||""),graceRemainingDays:Number(r.graceRemainingDays||0),plans:Array.isArray(r.plans)?r.plans:[]}}function Sg(){const[t,r]=i.useState(()=>Od({})),[n,s]=i.useState(""),[a,o]=i.useState(!1),[c,l]=i.useState(""),u=i.useCallback(async()=>{try{const f=await window.api.license.status();r(Od(f))}catch(f){l(`Billing status load failed: ${f&&f.message?f.message:String(f)}`)}},[]);i.useEffect(()=>{u()},[u]);const x=i.useCallback(async f=>{const b=String(f||"").trim();if(!b){l("Paste or import a license JSON blob first.");return}o(!0);try{const h=JSON.parse(b),g=await window.api.license.activateBlob(h);g&&g.ok?(l(`License activated: ${g.planLabel} (${g.status}).`),await u()):l(`License activation failed: ${g&&g.reason?g.reason:"unknown error"}`)}catch(h){l(`License activation failed: ${h&&h.message?h.message:String(h)}`)}finally{o(!1)}},[u]),p=i.useCallback(async f=>{const b=f&&f.target&&f.target.files?f.target.files[0]:null;if(!b)return;const h=await b.text();s(h),await x(h)},[x]),d=i.useCallback(async()=>{o(!0);try{await window.api.license.clear(),s(""),l("Active license cleared. Runtime falls back to Free tier."),await u()}catch(f){l(`License clear failed: ${f&&f.message?f.message:String(f)}`)}finally{o(!1)}},[u]),m=Array.isArray(t.plans)&&t.plans.length?t.plans:Array.isArray(vn&&vn.plans)?vn.plans:[];return e.jsxs("section",{"data-testid":"billing-center",className:"space-y-3 p-5 bg-black/30 rounded-2xl border border-white/5 shadow-inner",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-emerald-300 font-bold",children:"Billing & License"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"Offline license activation with grace-state visibility."})]}),e.jsx("button",{type:"button",onClick:u,className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.14em] font-mono text-slate-200 hover:bg-white/10",children:"Refresh"})]}),e.jsxs("div",{className:`inline-flex items-center px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${Ng(t.status)}`,"data-testid":"billing-status-pill",children:[t.status," · ",t.planLabel," · ",t.seats," seat",t.seats===1?"":"s"]}),t.expiresAt&&e.jsxs("div",{className:"text-[10px] font-mono text-slate-400",children:["Expires: ",t.expiresAt,t.status==="grace"&&t.graceRemainingDays>0?` · grace ${t.graceRemainingDays}d remaining`:""]}),e.jsx("textarea",{"data-testid":"billing-license-text",value:n,onChange:f=>s(f.target.value),placeholder:"Paste signed offline license JSON...",className:"w-full min-h-24 bg-black/40 border border-white/10 rounded-xl p-3 text-[11px] font-mono text-slate-100"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button","data-testid":"billing-activate-btn",disabled:a,onClick:()=>x(n),className:"px-3 py-2 rounded-lg border border-emerald-300/30 bg-emerald-500/10 text-[10px] uppercase tracking-[0.14em] font-mono text-emerald-100 disabled:opacity-60",children:a?"Activating":"Activate License"}),e.jsxs("label",{className:"px-3 py-2 rounded-lg border border-white/15 bg-white/5 text-[10px] uppercase tracking-[0.14em] font-mono text-slate-200 cursor-pointer",children:["Import License File",e.jsx("input",{"data-testid":"billing-license-file",type:"file",accept:"application/json,.json,.license",className:"hidden",onChange:p})]}),e.jsx("button",{type:"button","data-testid":"billing-clear-btn",disabled:a,onClick:d,className:"px-3 py-2 rounded-lg border border-rose-300/30 bg-rose-500/10 text-[10px] uppercase tracking-[0.14em] font-mono text-rose-100 disabled:opacity-60",children:"Clear License"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:m.map(f=>e.jsxs("article",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[10px] font-bold text-slate-100 uppercase tracking-[0.14em]",children:f.label}),e.jsxs("div",{className:"text-[10px] font-mono text-slate-400",children:["$",Number(f.priceUsd||0)," · ",String(f.billingPeriod||"once")]}),e.jsx("div",{className:"mt-1 text-[9px] text-slate-500 break-all",children:f.checkout&&f.checkout.manualInvoice?String(f.checkout.invoiceUrl||"Manual invoice"):String(f.checkout&&(f.checkout.gumroad||f.checkout.stripe)||"Activation via checkout")})]},f.id))}),c&&e.jsx("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-300",children:c})]})}const wl="neuralshell_upgrade_prompt_dismissed_v1";function Td(t){if(typeof window>"u"||!window.localStorage)return!1;const r=JSON.parse(window.localStorage.getItem(wl)||"{}");return!!(r&&r[String(t||"")])}function Cg(t){if(typeof window>"u"||!window.localStorage)return;const r=JSON.parse(window.localStorage.getItem(wl)||"{}"),n=r&&typeof r=="object"?r:{};n[String(t||"")]=!0,window.localStorage.setItem(wl,JSON.stringify(n))}function _g({open:t,featureKey:r="",featureLabel:n="",requiredPlan:s="pro",onClose:a}){const[o,c]=i.useState(()=>Td(r));if(i.useEffect(()=>{c(Td(r))},[r]),!t||o)return null;const u=(Array.isArray(vn&&vn.plans)?vn.plans:[]).find(p=>String(p.id||"").toLowerCase()===String(s||"").toLowerCase()),x=String(u&&u.checkout&&(u.checkout.gumroad||u.checkout.stripe||u.checkout.invoiceUrl)||"");return e.jsx("div",{className:"fixed inset-0 z-[160] bg-black/70 backdrop-blur-sm flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-xl rounded-2xl border border-cyan-300/20 bg-slate-950 p-5 space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Upgrade Available"}),e.jsxs("div",{className:"text-[11px] text-slate-400 font-mono",children:[String(n||"This capability")," is available on the ",String(s||"pro").toUpperCase()," plan."]})]}),u&&e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-300",children:[u.label," · $",Number(u.priceUsd||0)," · ",String(u.billingPeriod||"one_time")]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{type:"button","data-testid":"upgrade-modal-dismiss",onClick:()=>{Cg(r),c(!0),typeof a=="function"&&a()},className:"px-3 py-2 rounded border border-white/10 bg-white/5 text-[10px] uppercase tracking-[0.14em] font-mono text-slate-200",children:"Dismiss"}),e.jsx("button",{type:"button","data-testid":"upgrade-modal-open-checkout",onClick:async()=>{x&&window.api&&window.api.system&&typeof window.api.system.openExternal=="function"&&await window.api.system.openExternal(x),typeof a=="function"&&a()},className:"px-3 py-2 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.14em] font-mono text-cyan-100",children:"Upgrade"})]})]})})}function Ag({featureLabel:t,requiredPlan:r="Pro",onUpgrade:n}){return e.jsxs("div",{"data-testid":"tier-gate-notice",className:"rounded-lg border border-amber-300/30 bg-amber-500/10 px-3 py-2",children:[e.jsxs("div",{className:"text-[10px] font-mono text-amber-100",children:[String(t||"This feature")," requires ",r,"."]}),e.jsx("button",{type:"button","data-testid":"tier-gate-upgrade-btn",onClick:n,className:"mt-2 px-2 py-1 rounded border border-amber-200/40 text-[9px] uppercase tracking-[0.14em] font-mono text-amber-100 hover:bg-amber-500/15",children:"View Upgrade"})]})}function Eg(t){const r=Number(t||0);return r>=95?"text-emerald-300":r>=80?"text-amber-300":"text-rose-300"}function Ig({agent:t}){const r=t&&typeof t=="object"?t:{},n=r.compatibility&&r.compatibility.minVersion?r.compatibility.minVersion:"",s=r.compatibility&&r.compatibility.maxVersion?r.compatibility.maxVersion:"";return e.jsxs("div",{"data-testid":`agent-reputation-${r.id||"unknown"}`,className:"rounded-lg border border-white/10 bg-black/25 px-2 py-1.5 text-[9px] font-mono text-slate-400 space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{children:["Trust: ",String(r.trustBadge||"community")]}),e.jsxs("span",{children:["Rating: ",Number(r.rating||0).toFixed(1)," (",Number(r.ratingsCount||0),")"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{children:"Install success"}),e.jsxs("span",{className:Eg(r.installSuccessRate),children:[Number(r.installSuccessRate||0),"%"]})]}),e.jsxs("div",{children:["Compat: ",n||"any",s?` -> ${s}`:"+"]})]})}function Yp(){const[t,r]=i.useState([]),[n,s]=i.useState({}),[a,o]=i.useState({capabilities:[]}),[c,l]=i.useState(""),[u,x]=i.useState(""),[p,d]=i.useState({}),[m,f]=i.useState(null),b=i.useCallback(async()=>{const[I,A,C]=await Promise.all([window.api.agents.list(),window.api.agents.receipts().catch(()=>({receipts:{}})),window.api.settings.get()]);r(Array.isArray(I)?I:[]),s(A&&A.receipts?A.receipts:{}),o(C&&typeof C=="object"?C:{capabilities:[]})},[]);i.useEffect(()=>{b().catch(I=>{l(`Agent store load failed: ${I&&I.message?I.message:String(I)}`)})},[b]);const g=(Array.isArray(a&&a.capabilities)?a.capabilities:[]).includes("marketplace_paid_install"),y=async I=>{if(I){if(I.paid&&!g){f(I);return}x(I.id);try{const A=String(p[I.id]||"").trim(),C=await window.api.agents.install(I.id,{receiptCode:A});if(C&&C.ok){const w=C.receipt&&C.receipt.code?" (receipt stored)":"";l(`Installed ${C.id}${w}`)}else l(`Install failed for ${I.id}.`);await b()}catch(A){l(`Install failed: ${A&&A.message?A.message:String(A)}`)}finally{x("")}}};return e.jsxs("section",{"data-testid":"agent-store",className:"space-y-3 p-5 bg-black/30 rounded-2xl border border-white/5 shadow-inner",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-emerald-300 font-bold",children:"Agent Store"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"Free + paid agents with local receipts and trust reputation."})]}),m&&e.jsx(Ag,{featureLabel:`Install ${m.name}`,requiredPlan:"Pro",onUpgrade:()=>f(m)}),e.jsx("div",{className:"grid grid-cols-1 gap-2",children:t.map(I=>{const A=n&&n[I.id]?n[I.id]:null;return e.jsxs("article",{className:"rounded-xl border border-white/10 bg-black/30 px-3 py-2 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-slate-100 font-semibold",children:I.name}),e.jsxs("div",{className:"text-[10px] text-slate-500 font-mono",children:[I.id,"@",I.version]}),e.jsx("div",{className:"text-[10px] text-slate-400",children:I.description}),e.jsxs("div",{className:"mt-1 text-[9px] font-mono text-slate-400",children:[I.paid?`Paid $${Number(I.priceUsd||0)}`:"Free"," · ",I.publisher||"Community"]})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx("span",{className:`text-[9px] font-mono uppercase tracking-[0.14em] ${I.verified?"text-emerald-300":"text-rose-300"}`,children:I.verified?"Verified":"Unverified"}),I.verified?e.jsx("button",{type:"button","data-testid":`agent-store-install-${I.id}`,disabled:u===I.id,onClick:()=>y(I),className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20 disabled:opacity-50",children:u===I.id?"Installing":"Install"}):e.jsx("span",{"data-testid":`agent-store-install-${I.id}`,className:"px-2 py-1 rounded border border-amber-300/25 bg-amber-500/5 text-[9px] font-mono uppercase tracking-[0.14em] text-amber-200/70",children:"Receipt required"})]})]}),I.paid&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{"data-testid":`agent-store-receipt-${I.id}`,value:p[I.id]||"",onChange:C=>d(w=>({...w,[I.id]:C.target.value})),placeholder:"Receipt code (rcpt_...)",className:"flex-1 min-w-40 bg-black/40 border border-white/10 rounded px-2 py-1 text-[10px] font-mono text-slate-100"}),e.jsx("span",{className:"text-[9px] font-mono text-slate-500",children:e.jsx("span",{"data-testid":`agent-store-receipt-status-${I.id}`,children:A?"Receipt stored":"Receipt required"})})]}),e.jsx(Ig,{agent:I})]},I.id)})}),c&&e.jsx("div",{"data-testid":"agent-store-status",className:"rounded-xl border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-300",children:c}),e.jsx(_g,{open:!!m,featureKey:m?`agent-store:${m.id}`:"",featureLabel:m?`Install ${m.name}`:"",requiredPlan:"pro",onClose:()=>f(null)})]})}const Pg=Object.freeze(Object.defineProperty({__proto__:null,default:Yp},Symbol.toStringTag,{value:"Module"})),Zp="neuralshell_referrals_v1";function Rg(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(Zp)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Og(t){typeof window>"u"||!window.localStorage||window.localStorage.setItem(Zp,JSON.stringify(t))}function Tg(){return`NSREF-${Math.random().toString(36).slice(2,10).toUpperCase()}`}function Mg(t,r){const n=String(t||"https://gumroad.com/l/neuralshell-operator").trim(),s=n.includes("?")?"&":"?";return`${n}${s}ref=${encodeURIComponent(r)}&utm_source=referral&utm_medium=partner&utm_campaign=delta9`}function Dg(t,r){const n=new Blob([`${JSON.stringify(r,null,2)} +`],{type:"application/json"}),s=URL.createObjectURL(n),a=document.createElement("a");a.href=s,a.download=t,document.body.appendChild(a),a.click(),a.remove(),URL.revokeObjectURL(s)}function $g(){const[t,r]=i.useState(()=>Rg()),[n,s]=i.useState(""),[a,o]=i.useState("https://gumroad.com/l/neuralshell-operator"),c=()=>{const u=Tg(),x=Mg(a,u),d=[{code:u,link:x,createdAt:new Date().toISOString()},...t].slice(0,200);r(d),Og(d),s(`Created referral ${u}`)},l=()=>{const u={generatedAt:new Date().toISOString(),count:t.length,rows:t};Dg(`neuralshell_referrals_${Date.now()}.json`,u),s("Referral report exported.")};return e.jsxs("section",{"data-testid":"referral-card",className:"space-y-3 p-5 bg-black/30 rounded-2xl border border-white/5 shadow-inner",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-cyan-300 font-bold",children:"Referral Program"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"Generate referral links and export local attribution reports."})]}),e.jsx("input",{"data-testid":"referral-base-url",value:a,onChange:u=>o(u.target.value),className:"w-full bg-black/40 border border-white/10 rounded px-3 py-2 text-[10px] font-mono text-slate-100",placeholder:"Checkout URL"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button","data-testid":"referral-generate-btn",onClick:c,className:"px-3 py-2 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.14em] font-mono text-cyan-100",children:"Generate Referral"}),e.jsx("button",{type:"button","data-testid":"referral-export-btn",onClick:l,className:"px-3 py-2 rounded border border-white/15 bg-white/5 text-[10px] uppercase tracking-[0.14em] font-mono text-slate-200",children:"Export Report"})]}),e.jsxs("div",{className:"space-y-1 max-h-32 overflow-auto",children:[t.slice(0,5).map(u=>e.jsxs("div",{"data-testid":`referral-row-${u.code}`,className:"rounded border border-white/10 bg-black/25 px-2 py-1 text-[9px] font-mono text-slate-300 break-all",children:[u.code," -> ",u.link]},u.code)),t.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No referral codes generated yet."})]}),n&&e.jsx("div",{"data-testid":"referral-status",className:"rounded border border-white/10 bg-black/25 px-2 py-1 text-[10px] font-mono text-slate-300",children:n})]})}const Ve=Object.freeze({EVENT:"event",DEADLINE:"deadline",REMINDER:"reminder"}),Md=Object.freeze({CONFIRMED:"confirmed",TENTATIVE:"tentative",CANCELLED:"cancelled"}),Ql=Object.freeze({LOCAL:"local",ICS:"ics",GOOGLE:"google",OUTLOOK:"outlook",CALDAV:"caldav",CALENDLY:"calendly",PROJECT:"project",TASK:"task"}),Lg=Object.freeze([{id:"local",label:"Local",status:"Active",connected:!0},{id:"ics",label:"ICS",status:"Export available / Import unavailable",connected:!1},{id:"google",label:"Google",status:"Not connected",connected:!1},{id:"outlook",label:"Outlook",status:"Not connected",connected:!1},{id:"calendly",label:"Calendly",status:"Not connected",connected:!1}]),ec="neuralshell_chrono_events_v1",vl="neuralshell:chrono-events-changed";function Ya(){return new Date().toISOString()}function Xp(t){return`${String(t||"chrono")}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Be(t,r=""){return String(t??"").trim()||r}function Dd(t){const r=new Date(t).getTime();return Number.isFinite(r)?r:Number.NaN}function Qp(t){const r=Be(t);return r?r.includes("T")?new Date(r).toISOString():new Date(`${r}T23:59:00`).toISOString():""}function Rs(t={}){const r=Dd(t.startAt),n=Dd(t.endAt),s=Be(t.createdAt,Ya()),a=Number.isFinite(r)?new Date(r).toISOString():"",o=Number.isFinite(n)?new Date(n).toISOString():a;return{id:Be(t.id,Xp("event")),type:Ve.EVENT,title:Be(t.title,"Untitled event"),description:Be(t.description),startAt:a,endAt:o,allDay:!!t.allDay,category:Be(t.category),location:Be(t.location),source:Ql.LOCAL,sourceId:Be(t.sourceId),status:Object.values(Md).includes(t.status)?t.status:Md.CONFIRMED,reminders:Array.isArray(t.reminders)?t.reminders:[],createdAt:s,updatedAt:Be(t.updatedAt,s)}}function Da(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(ec)||"[]");return Array.isArray(t)?t.map(Rs).filter(r=>r.title&&r.startAt&&r.endAt).sort((r,n)=>r.startAt.localeCompare(n.startAt)):[]}catch{return[]}}function Bg(t=[]){const r=(Array.isArray(t)?t:[]).map(Rs).filter(n=>n.title&&n.startAt&&n.endAt).sort((n,s)=>n.startAt.localeCompare(s.startAt));if(typeof window<"u"&&window.localStorage)try{window.localStorage.setItem(ec,JSON.stringify(r))}catch{}try{window.dispatchEvent(new CustomEvent(vl,{detail:r}))}catch{}return r}function Fg(t=[],r={}){const n=Rs(r),s=(Array.isArray(t)?t:[]).map(Rs),a=s.findIndex(o=>o.id===n.id);return a>=0?s[a]={...n,updatedAt:Ya()}:s.push(n),s.sort((o,c)=>o.startAt.localeCompare(c.startAt))}function Ug(t){const r=()=>{typeof t=="function"&&t(Da())},n=s=>{(!s||s.key===ec)&&r()};return window.addEventListener("storage",n),window.addEventListener(vl,r),()=>{window.removeEventListener("storage",n),window.removeEventListener(vl,r)}}function zg(t={}){const r=Be(t.createdAt,Ya()),n=Be(t.date||t.dueAt);return{id:Be(t.id,`deadline-${n}-${t.title||"item"}`),type:Ve.DEADLINE,title:Be(t.title,"Untitled deadline"),dueAt:Qp(n),date:n,projectId:Be(t.projectId),priority:["low","normal","high","critical"].includes(String(t.priority||"").toLowerCase())?String(t.priority).toLowerCase():"normal",completed:!!t.completed,source:Ql.LOCAL,createdAt:r,updatedAt:Be(t.updatedAt,r),raw:t}}function Hg(t={}){const r=Be(t.createdAt,Ya()),n=Be(t.dueDate);return{id:`workpad-${Be(t.id,Xp("task"))}`,type:Ve.DEADLINE,title:Be(t.title,"Workpad task"),dueAt:Qp(n),date:n,projectId:Be(t.projectId),priority:String(t.priority||"").toLowerCase()==="high"?"high":"normal",completed:!!t.done,source:Ql.TASK,createdAt:r,updatedAt:Be(t.updatedAt,r),raw:t}}function e0({events:t=[],deadlines:r=[],workpadTasks:n=[]}={}){const s=[...Array.isArray(t)?t.map(Rs):[],...Array.isArray(r)?r.map(zg):[],...Array.isArray(n)?n.map(Hg):[]].filter(o=>o&&o.id&&o.title),a=new Set;return s.filter(o=>{const c=`${o.type}:${o.id}`;return a.has(c)?!1:(a.add(c),!0)})}const Za="neuralshell_proof_timestamps_v1",jl="neuralshell:proof-timestamps-changed",Wg=Object.freeze(["session_started","session_paused","session_resumed","session_ended","mode_changed","calendar_linked","event_created","deadline_created","deadline_completed","manual_note"]),Kg=Object.freeze(["sessionhud","chronohud","timeledger","calendar","system"]);let t0=[];function Vg(t){return`${String(t)}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function kt(t,r=""){return String(t??"").trim()||r}function Gg(t,r=new Date().toISOString()){const n=String(t||"").trim();if(!n)return r;const s=new Date(n);return Number.isFinite(s.getTime())?s.toISOString():r}function r0(t){return t||(typeof window<"u"&&window.localStorage?window.localStorage:null)}function n0(t){const r=r0(t);if(!r)return[...t0];try{const n=JSON.parse(r.getItem(Za)||"[]");return Array.isArray(n)?n:[]}catch{return[]}}function Jg(t,r){const n=i0(t),s=r0(r);if(!s)return t0=n,n;try{s.setItem(Za,JSON.stringify(n))}catch{}return n}function qg(t){try{typeof window<"u"&&window.dispatchEvent(new CustomEvent(jl,{detail:t}))}catch{}}function s0(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local"}catch{return"local"}}function a0(t){const r=t instanceof Date?t:new Date(t);return Number.isFinite(r.getTime())?r.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):""}function o0(t={}){const r=Gg(t.createdAt),n=new Date(r),s=Wg.includes(t.eventType)?t.eventType:"manual_note",a=Kg.includes(t.source)?t.source:"system";return{id:kt(t.id,Vg("proof")),createdAt:r,localLabel:kt(t.localLabel,a0(n)),timezone:kt(t.timezone,s0()),eventType:s,source:a,projectId:kt(t.projectId),projectName:kt(t.projectName),sessionId:kt(t.sessionId),calendarItemId:kt(t.calendarItemId),calendarItemType:kt(t.calendarItemType),title:kt(t.title,s.replace(/_/g," ")),details:kt(t.details)}}function i0(t=[]){return(Array.isArray(t)?t:[]).map(o0).filter(r=>r.id&&r.createdAt&&r.title).sort((r,n)=>r.createdAt.localeCompare(n.createdAt))}function Yg(t={},r={}){const n=r.now instanceof Date?r.now:new Date(r.now||Date.now()),s=o0({...t,createdAt:t.createdAt||n.toISOString(),localLabel:t.localLabel||a0(n),timezone:t.timezone||s0()}),a=Jg([...n0(r.storage),s],r.storage);return qg(a),s}function ur(t={},r={}){const n=t&&typeof t=="object"?t:{},s=kt(n.date),a=n.start?new Date(n.start).getTime():Number.NaN,o=n.end?new Date(n.end).getTime():Number.NaN,c=Number(n.limit),l=n.order!=="asc";let u=i0(n0(r.storage));return s&&(u=u.filter(x=>x.createdAt.slice(0,10)===s)),Number.isFinite(a)&&(u=u.filter(x=>new Date(x.createdAt).getTime()>=a)),Number.isFinite(o)&&(u=u.filter(x=>new Date(x.createdAt).getTime()<=o)),l&&(u=[...u].reverse()),Number.isFinite(c)&&c>0?u.slice(0,Math.floor(c)):u}function l0(t){const r=()=>{typeof t=="function"&&t(ur())};if(typeof window>"u")return()=>{};const n=s=>{(!s||s.key===Za)&&r()};return window.addEventListener("storage",n),window.addEventListener(jl,r),()=>{window.removeEventListener("storage",n),window.removeEventListener(jl,r)}}const Xa="neuralshell_time_ledger_v1",kl="neuralshell:time-ledger-changed",$a=Object.freeze(["focus","planning","review","admin"]),Zg=Object.freeze(["active","paused","ended"]);function Xg(){return new Date().toISOString()}function c0(t){return`${String(t)}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function ia(t,r=""){return String(t??"").trim()||r}function Qg(t){const r=String(t||"").trim().toLowerCase();return $a.includes(r)?r:$a[0]}function Pi(t,r=""){const n=String(t||"").trim();if(!n)return r;const s=new Date(n);return Number.isFinite(s.getTime())?s.toISOString():r}function Ri(t){const r=Number(t);return Number.isFinite(r)&&r>0?Math.round(r):0}function $d(t){const r=new Date(t).getTime();return Number.isFinite(r)?r:Number.NaN}function La(t,r=new Date){const n=$d(t),s=r instanceof Date?r.getTime():$d(r);return!Number.isFinite(n)||!Number.isFinite(s)||s<=n?0:s-n}function d0(t){return typeof window<"u"&&window.localStorage?window.localStorage:null}function ey(t){try{typeof window<"u"&&window.dispatchEvent(new CustomEvent(kl,{detail:t}))}catch{}}function ht(){return{version:1,sessions:[]}}function Mr(t={}){const r=Pi(t.startedAt,Xg()),n=Pi(t.endedAt),s=Pi(t.lastActiveAt,n||r),a=Ri(t.activeDurationMs),o=Ri(t.idleDurationMs),c=a+o,l=n?"ended":Zg.includes(t.status)?t.status:"active";return{id:ia(t.id,c0("session")),projectId:ia(t.projectId),projectName:ia(t.projectName),startedAt:r,endedAt:n,lastActiveAt:s,durationMs:Math.max(Ri(t.durationMs),c),activeDurationMs:a,idleDurationMs:o,mode:Qg(t.mode),source:ia(t.source,"local"),status:l}}function Ke(t={}){const r=t&&typeof t=="object"?t:{};return{version:1,sessions:Array.isArray(r.sessions)?r.sessions.map(Mr).filter(s=>s.id&&s.startedAt).sort((s,a)=>s.startedAt.localeCompare(a.startedAt)):[]}}function _n(t){const r=d0();if(!r)return ht();try{const n=JSON.parse(r.getItem(Xa)||"{}");return Ke(n)}catch{return ht()}}function ty(t,r){const n=Ke(t),s=d0();if(s)try{s.setItem(Xa,JSON.stringify(n))}catch{}return ey(n),n}function u0(t){const r=()=>{typeof t=="function"&&t(_n())};if(typeof window>"u")return()=>{};const n=s=>{(!s||s.key===Xa)&&r()};return window.addEventListener("storage",n),window.addEventListener(kl,r),()=>{window.removeEventListener("storage",n),window.removeEventListener(kl,r)}}function ry(t=ht()){return Ke(t).sessions.filter(n=>!n.endedAt).sort((n,s)=>s.startedAt.localeCompare(n.startedAt))[0]||null}function ny(t=ht(),r={},n=new Date){if(ry(t))return Ke(t);const a=(n instanceof Date?n:new Date(n)).toISOString(),o=Mr({id:r.id||c0("session"),projectId:r.projectId,projectName:r.projectName,startedAt:a,lastActiveAt:a,mode:r.mode,source:r.source||"local",status:"active"});return Ke({sessions:[...Ke(t).sessions,o]})}function sy(t=ht(),r,n=new Date){const s=n instanceof Date?n:new Date(n),a=s.toISOString(),o=Ke(t).sessions.map(c=>{if(c.id!==r||c.status!=="active"||c.endedAt)return c;const l=c.activeDurationMs+La(c.lastActiveAt,s),u=c.idleDurationMs;return Mr({...c,lastActiveAt:a,activeDurationMs:l,idleDurationMs:u,durationMs:l+u,status:"paused"})});return Ke({sessions:o})}function ay(t=ht(),r,n=new Date){const s=n instanceof Date?n:new Date(n),a=s.toISOString(),o=Ke(t).sessions.map(c=>{if(c.id!==r||c.status!=="paused"||c.endedAt)return c;const l=c.activeDurationMs,u=c.idleDurationMs+La(c.lastActiveAt,s);return Mr({...c,lastActiveAt:a,activeDurationMs:l,idleDurationMs:u,durationMs:l+u,status:"active"})});return Ke({sessions:o})}function oy(t=ht(),r,n=new Date){const s=n instanceof Date?n:new Date(n),a=s.toISOString(),o=Ke(t).sessions.map(c=>{if(c.id!==r||c.endedAt)return c;const l=c.status==="active"?La(c.lastActiveAt,s):0,u=c.status==="paused"?La(c.lastActiveAt,s):0,x=c.activeDurationMs+l,p=c.idleDurationMs+u;return Mr({...c,endedAt:a,lastActiveAt:a,activeDurationMs:x,idleDurationMs:p,durationMs:x+p,status:"ended"})});return Ke({sessions:o})}function iy(t=ht(),r,n){const s=Ke(t).sessions.map(a=>a.id!==r||a.endedAt?a:Mr({...a,mode:n}));return Ke({sessions:s})}const p0=864e5;function tc(t){const r=new Date(t);return Number.isFinite(r.getTime())?r:null}function m0(t){const r=t instanceof Date?new Date(t.getTime()):tc(t);return r?(r.setHours(0,0,0,0),r):null}function ly(t){const r=m0(t);return r?(r.setDate(r.getDate()-r.getDay()),r):null}function x0(t,r,n){const s=tc(t.startedAt);return!!(s&&s.getTime()>=r.getTime()&&s.getTime()!n.endedAt).sort((n,s)=>s.startedAt.localeCompare(n.startedAt))[0]||null}function cy(t=ht(),r=new Date){const n=m0(r);if(!n)return 0;const s=new Date(n.getTime()+p0);return Ke(t).sessions.filter(a=>x0(a,n,s)).reduce((a,o)=>a+Or(o,r).activeDurationMs,0)}function dy(t=ht(),r=new Date){const n=ly(r);if(!n)return 0;const s=new Date(n.getTime()+p0*7);return Ke(t).sessions.filter(a=>x0(a,n,s)).reduce((a,o)=>a+Or(o,r).activeDurationMs,0)}function uy(t=ht(),r,n=new Date){const s=String(r||"").trim();return s?Ke(t).sessions.filter(a=>String(a.projectId||"").trim()===s).reduce((a,o)=>a+Or(o,n).activeDurationMs,0):0}function cr(t){const r=Math.max(0,Math.floor((Number(t)||0)/1e3)),n=Math.floor(r/3600),s=Math.floor(r%3600/60),a=r%60;return n>0?`${n}h ${String(s).padStart(2,"0")}m`:s>0?`${s}m ${String(a).padStart(2,"0")}s`:`${a}s`}const py=864e5;function Os(t){const r=new Date(t);return Number.isFinite(r.getTime())?r:null}function f0(t=new Date){const r=t instanceof Date?t:Os(t);return r?[r.getFullYear(),String(r.getMonth()+1).padStart(2,"0"),String(r.getDate()).padStart(2,"0")].join("-"):""}function my(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local"}catch{return"local"}}function Rr(t){return t?t.type==="event"?Os(t.startAt):Os(t.dueAt||t.remindAt||t.createdAt):null}function xy(t){return t?t.type==="event"?Os(t.endAt||t.startAt):Rr(t):null}function Ld(t,r){return f0(t)===r}function Bd(t,r,n){var a;const s=new Map;return t.forEach(o=>{const c=String(r(o)||"").trim();c&&s.set(c,(s.get(c)||0)+Or(o,n).activeDurationMs)}),((a=[...s.entries()].sort((o,c)=>c[1]-o[1]||o[0].localeCompare(c[0]))[0])==null?void 0:a[0])||""}function fy(t,r){const n=r instanceof Date?r.getTime():Date.now(),s=(Array.isArray(t)?t:[]).filter(c=>{const l=Rr(c);return!l||c.type==="deadline"&&c.completed?!1:(xy(c)||l).getTime()>=n}).sort((c,l)=>Rr(c).getTime()-Rr(l).getTime())[0];if(!s)return"No upcoming local items";const a=Rr(s),o=a?a.toLocaleString([],{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"unscheduled";return`${s.title||"Untitled item"} ${o}`}function b0({sessions:t=[],calendarItems:r=[],proofTimestamps:n=[],now:s=new Date,date:a}={}){const o=a||f0(s),c=new Date(`${o}T00:00:00`),l=new Date(c.getTime()+py),u=Array.isArray(t)?t:[],x=Array.isArray(r)?r:[],p=Array.isArray(n)?n:[],d=u.filter(y=>{const I=Os(y.startedAt);return I&&I.getTime()>=c.getTime()&&I.getTime()Ld(y.createdAt,o)),f=x.filter(y=>Ld(Rr(y),o)),b=f.filter(y=>y.type==="deadline"),h=b.filter(y=>{if(y.completed)return!1;const I=Rr(y);return I&&I.getTime()<(s instanceof Date?s.getTime():Date.now())}),g=d.reduce((y,I)=>{const A=Or(I,s);return y.totalSessionMs+=A.durationMs,y.activeMs+=A.activeDurationMs,y.idleMs+=A.idleDurationMs,y.longestSessionMs=Math.max(y.longestSessionMs,A.durationMs),y},{totalSessionMs:0,activeMs:0,idleMs:0,longestSessionMs:0});return{date:o,timezone:my(),totalSessionMs:g.totalSessionMs,activeMs:g.activeMs,idleMs:g.idleMs,sessionCount:d.length,longestSessionMs:g.longestSessionMs,topProject:Bd(d,y=>y.projectName||y.projectId,s),topMode:Bd(d,y=>y.mode,s),eventsToday:f.filter(y=>y.type==="event").length,deadlinesDue:b.length,deadlinesCompleted:b.filter(y=>y.completed).length,overdueDeadlines:h.length,proofEventCount:m.length,linkedCalendarItems:new Set(m.map(y=>y.calendarItemId).filter(Boolean)).size,nextThreat:fy(x,s)}}const h0="neuralshell_timeproof_integrity_v1",rc="SHA-256",by="local-tamper-evident",hy=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Nl(t){return t==null?null:t instanceof Date?Number.isFinite(t.getTime())?t.toISOString():null:Array.isArray(t)?t.map(Nl):typeof t=="number"?Number.isFinite(t)?t:null:typeof t=="string"||typeof t=="boolean"?t:typeof t!="object"?null:Object.keys(t).sort().reduce((r,n)=>{const s=t[n];return s!==void 0&&typeof s!="function"&&typeof s!="symbol"&&(r[n]=Nl(s)),r},{})}function gy(t){const r=String(t??"");if(typeof globalThis.TextEncoder=="function")return Array.from(new globalThis.TextEncoder().encode(r));const n=[];for(let s=0;s65535&&(s+=1),a<=127?n.push(a):a<=2047?(n.push(192|a>>>6),n.push(128|a&63)):a<=65535?(n.push(224|a>>>12),n.push(128|a>>>6&63),n.push(128|a&63)):(n.push(240|a>>>18),n.push(128|a>>>12&63),n.push(128|a>>>6&63),n.push(128|a&63))}return n}function Pt(t,r){return t>>>r|t<<32-r}function it(...t){return t.reduce((r,n)=>r+n>>>0,0)}function g0(t){return{algorithm:rc,canonicalPayload:String(t.canonicalPayload||""),chainIndex:Number(t.chainIndex),createdAt:String(t.createdAt||""),payloadHash:String(t.payloadHash||""),previousEntryHash:t.previousEntryHash||null,sourceId:String(t.sourceId||""),sourceType:String(t.sourceType||"")}}function y0(t,r=new Date().toISOString()){const n=String(t||"").trim(),s=n?new Date(n):null;return s&&Number.isFinite(s.getTime())?s.toISOString():r}function yy(t){return typeof window<"u"&&window.localStorage?window.localStorage:null}function Sl(t){return JSON.stringify(Nl(t))}function Ba(t){const r=gy(t),n=r.length*8;for(r.push(128);r.length%64!==56;)r.push(0);const s=Math.floor(n/4294967296),a=n>>>0;for(let l=24;l>=0;l-=8)r.push(s>>>l&255);for(let l=24;l>=0;l-=8)r.push(a>>>l&255);const o=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],c=new Array(64);for(let l=0;l>>0}for(let g=16;g<64;g+=1){const y=Pt(c[g-15],7)^Pt(c[g-15],18)^c[g-15]>>>3,I=Pt(c[g-2],17)^Pt(c[g-2],19)^c[g-2]>>>10;c[g]=it(c[g-16],y,c[g-7],I)}let[u,x,p,d,m,f,b,h]=o;for(let g=0;g<64;g+=1){const y=Pt(m,6)^Pt(m,11)^Pt(m,25),I=m&f^~m&b,A=it(h,y,I,hy[g],c[g]),C=Pt(u,2)^Pt(u,13)^Pt(u,22),w=u&x^u&p^x&p,j=it(C,w);h=b,b=f,f=m,m=it(d,A),d=p,p=x,x=u,u=it(A,j)}o[0]=it(o[0],u),o[1]=it(o[1],x),o[2]=it(o[2],p),o[3]=it(o[3],d),o[4]=it(o[4],m),o[5]=it(o[5],f),o[6]=it(o[6],b),o[7]=it(o[7],h)}return o.map(l=>l.toString(16).padStart(8,"0")).join("")}function wy(t={},r=null){const n=t&&typeof t=="object"?t:{},s=n.payload!==void 0?n.payload:n.record!==void 0?n.record:n,a=n.canonicalPayload||Sl(s),o=Ba(a),c=r?Number(r.chainIndex)+1:0,l={id:String(n.id||`integrity-${c}-${o.slice(0,12)}`),chainIndex:c,createdAt:y0(n.createdAt||(s==null?void 0:s.createdAt)),sourceId:String(n.sourceId||(s==null?void 0:s.id)||n.id||""),sourceType:String(n.sourceType||"proofTimestamp"),algorithm:rc,canonicalPayload:a,payloadHash:o,previousEntryHash:r?r.entryHash:null,entryHash:"",verificationStatus:"verified"};return l.entryHash=Ba(Sl(g0(l))),l}function w0(t=[]){const r=(Array.isArray(t)?t:[]).filter(s=>s&&typeof s=="object").sort((s,a)=>String(s.createdAt||"").localeCompare(String(a.createdAt||""))||String(s.id||"").localeCompare(String(a.id||""))),n=[];return r.forEach(s=>{n.push(wy({createdAt:s.createdAt,payload:s,sourceId:s.id,sourceType:"proofTimestamp"},n[n.length-1]||null))}),n}function vy(t=[]){if(!Array.isArray(t)||t.length===0)return{ok:!0,status:"empty",errors:[],entryCount:0};const r=[];let n=null;return t.forEach((s,a)=>{if(!s||typeof s!="object"){r.push({code:"broken_sequence",index:a}),n=null;return}s.chainIndex!==a&&r.push({code:"wrong_chain_index",index:a,expected:a,actual:s.chainIndex}),(s.previousEntryHash||null)!==n&&r.push({code:"previous_hash_mismatch",index:a});const o=Ba(String(s.canonicalPayload||""));s.payloadHash!==o&&r.push({code:"payload_hash_mismatch",index:a});const c=Ba(Sl(g0({...s,payloadHash:o})));s.entryHash!==c&&r.push({code:"entry_hash_mismatch",index:a}),n=s.entryHash||null}),{ok:r.length===0,status:r.length===0?"verified":"mismatch",errors:r,entryCount:t.length}}function v0(t=[],{now:r=new Date}={}){const n=vy(t);return{algorithm:rc,status:n.status,entryCount:Array.isArray(t)?t.length:0,firstEntryHash:Array.isArray(t)&&t[0]?t[0].entryHash:null,lastEntryHash:Array.isArray(t)&&t.length?t[t.length-1].entryHash:null,checkedAt:y0(r),claim:by}}function jy(t=[],r){const n=yy(),s=Array.isArray(t)?t:[];if(n)try{n.setItem(h0,JSON.stringify(s))}catch{}return s}function ky(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local"}catch{return"local"}}function Ny(t){const r=t instanceof Date?t:new Date(t||Date.now());return Number.isFinite(r.getTime())?r:new Date}function Cl({workflowId:t="",now:r=new Date}={}){const n=Ny(r),s=_n(),a=ur({order:"asc"}),o=w0(a);jy(o);const c=et(t||void 0),l=e0({events:Da(),deadlines:Qt(),workpadTasks:(c.tasks||[]).filter(u=>!u.done&&u.dueDate)});return{exportedAt:n.toISOString(),timezone:ky(),sessions:s.sessions,proofTimeline:a,daySummary:b0({sessions:s.sessions,calendarItems:l,proofTimestamps:a,now:n}),integrity:v0(o,{now:n}),storageKeys:{timeLedger:Xa,proofTimestamps:Za,integrity:h0}}}function Sy(){const[t,r]=i.useState(!1),[n,s]=i.useState(!1),[a,o]=i.useState(""),c=async()=>{r(!0),o("");try{const l=window.api&&window.api.support&&typeof window.api.support.exportBundle=="function"?await window.api.support.exportBundle({includeUserText:!!n,workpadSnapshots:yl(),timeProof:Cl()}):await window.api.invoke("support:exportBundle",{includeUserText:!!n,workpadSnapshots:yl(),timeProof:Cl()});l&&l.ok?(o(`Bundle exported: ${l.outputPath}`),window.dispatchEvent(new window.CustomEvent("neuralshell:support-bundle-exported",{detail:{outputPath:String(l.outputPath||""),sha256:String(l.sha256||"")}}))):o("Bundle export failed.")}catch(l){o(`Export failed: ${l&&l.message?l.message:String(l)}`)}finally{r(!1)}};return e.jsxs("section",{"data-testid":"support-bundle-card",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-amber-300 mb-4 font-bold",children:"Support Bundle"}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-3",children:[e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Export sanitized diagnostics bundle (ZIP + SHA-256). Secrets are redacted by default."}),e.jsxs("label",{className:"flex items-center gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{"data-testid":"support-bundle-include-user-text",type:"checkbox",checked:n,onChange:l=>s(l.target.checked)}),"Include user text (not recommended)"]}),e.jsx("button",{type:"button","data-testid":"support-bundle-export-btn",disabled:t,onClick:c,className:"px-3 py-2 rounded-xl border border-amber-300/30 bg-amber-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-amber-200 hover:bg-amber-500/20 disabled:opacity-60",children:t?"Exporting":"Export Support Bundle"}),a&&e.jsx("div",{className:"text-[10px] font-mono text-slate-300 break-all",children:a})]})]})}function he(t,r=0){const n=Number(t);return Number.isFinite(n)?n:Number(r||0)}function Fd(t){const r=[];let n="",s=!1;for(let a=0;aString(s||"").trim().length>0);if(!r.length)return[];const n=Fd(r[0]).map(s=>String(s||"").trim());return n.length?r.slice(1).map(s=>{const a=Fd(s),o={};return n.forEach((c,l)=>{c&&(o[c]=String(a[l]||"").trim())}),o}):[]}function Cy(t=""){const r=JSON.parse(String(t||"{}"));return Array.isArray(r)?r:r&&typeof r=="object"?Array.isArray(r.rows)?r.rows:Array.isArray(r.records)?r.records:Array.isArray(r.items)?r.items:[r]:[]}function Ds(t="",r=""){if(String(r||"").toLowerCase().endsWith(".csv"))return Ud(t);try{return Cy(t)}catch{return Ud(t)}}function pt(t){return new Promise((r,n)=>{const s=new FileReader;s.onerror=()=>n(new Error("Unable to read local file.")),s.onload=()=>r(String(s.result||"")),s.readAsText(t)})}function je(t,r){const n=new Blob([`${JSON.stringify(r,null,2)} +`],{type:"application/json"}),s=URL.createObjectURL(n),a=document.createElement("a");a.href=s,a.download=String(t||"export.json"),a.click(),URL.revokeObjectURL(s)}function $s(t,r){const n=new Blob([String(r||"")],{type:"text/plain"}),s=URL.createObjectURL(n),a=document.createElement("a");a.href=s,a.download=String(t||"export.txt"),a.click(),URL.revokeObjectURL(s)}function nc(t,r=""){const n=String(t||"").trim();if(!n)return r;const s=new Date(n);return Number.isNaN(s.getTime())?r:s.toISOString().slice(0,10)}async function _y(){if(window.api&&window.api.diagnostics&&typeof window.api.diagnostics.exportLog=="function")return window.api.diagnostics.exportLog();if(window.api&&typeof window.api.invoke=="function")return window.api.invoke("execution:exportLog");throw new Error("Execution log export is unavailable in this build.")}function Ay(){const[t,r]=i.useState(!1),[n,s]=i.useState(""),a=async()=>{r(!0),s("");try{const o=await _y(),c=Date.now();je(`neuralshell-execution-log-${c}.json`,o||{});const l=Array.isArray(o&&o.diagnostics)?o.diagnostics.length:0,u=Array.isArray(o&&o.actionOutcomes)?o.actionOutcomes.length:0;s(`Exported ${l} diagnostic event(s) and ${u} action outcome(s).`)}catch(o){s(`Export failed: ${o&&o.message?o.message:String(o)}`)}finally{r(!1)}};return e.jsxs("section",{"data-testid":"execution-log-export-card",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-cyan-300 mb-4 font-bold",children:"Execution Log"}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-3",children:[e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Export orchestration diagnostics and action outcomes (JSON). No secrets included."}),e.jsx("button",{type:"button","data-testid":"execution-log-export-btn",disabled:t,onClick:a,className:"px-3 py-2 rounded-xl border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-cyan-100 hover:bg-cyan-500/20 disabled:opacity-60",children:t?"Exporting":"Export Execution Log"}),n&&e.jsx("div",{className:"text-[10px] font-mono text-slate-300 break-all",children:n})]})]})}const Ey=["network","llm","security","runtime","trust","observability","general"],Iy={network:{label:"Network",tone:"text-sky-300"},llm:{label:"Models & Bridge",tone:"text-emerald-300"},security:{label:"Security",tone:"text-rose-300"},runtime:{label:"Runtime",tone:"text-violet-300"},trust:{label:"Trust",tone:"text-amber-300"},observability:{label:"Telemetry",tone:"text-fuchsia-300"},general:{label:"General",tone:"text-slate-300"}},zd={failed:0,warning:1,passed:2,skipped:3};function Py(t){return t==="passed"?"border-emerald-400/20 bg-emerald-500/5":t==="failed"?"border-rose-400/25 bg-rose-500/8 ring-1 ring-rose-400/10":t==="warning"?"border-amber-400/20 bg-amber-500/5":"border-white/10 bg-black/25"}function Ry(t){return t==="passed"?"text-emerald-300":t==="failed"?"text-rose-300":t==="warning"?"text-amber-300":"text-slate-400"}function Oy(t){return t==="passed"?"bg-emerald-400 shadow-[0_0_8px_rgba(52,211,153,0.45)]":t==="failed"?"bg-rose-400 shadow-[0_0_8px_rgba(251,113,133,0.45)]":t==="warning"?"bg-amber-400 shadow-[0_0_8px_rgba(251,191,36,0.35)]":"bg-slate-500"}function Ty(t){return t==="passed"?"OK":t==="failed"?"FAIL":t==="warning"?"WARN":"SKIP"}function My(t){const r=new Map;for(const n of t){const s=String(n.category||"general");r.has(s)||r.set(s,[]),r.get(s).push(n)}for(const[,n]of r)n.sort((s,a)=>{const o=zd[s.status]??9,c=zd[a.status]??9;return o!==c?o-c:String(s.label||"").localeCompare(String(a.label||""))});return Ey.filter(n=>r.has(n)).map(n=>({id:n,...Iy[n],checks:r.get(n)}))}function Dy(t){return t.some(r=>r.status==="failed"||r.status==="warning")}function la({label:t,value:r,tone:n}){const s={emerald:"border-emerald-400/25 bg-emerald-500/10 text-emerald-200",rose:"border-rose-400/25 bg-rose-500/10 text-rose-200",amber:"border-amber-400/25 bg-amber-500/10 text-amber-200",slate:"border-white/10 bg-black/30 text-slate-300"}[n]||"border-white/10 bg-black/30 text-slate-300";return e.jsxs("div",{className:`rounded-xl border px-3 py-2 text-center ${s}`,children:[e.jsx("div",{className:"text-[18px] font-bold leading-none tabular-nums",children:r}),e.jsx("div",{className:"text-[8px] uppercase tracking-[0.18em] font-mono mt-1 opacity-80",children:t})]})}function $y({check:t}){return e.jsx("div",{"data-testid":`system-health-row-${t.id}`,className:`rounded-xl border px-3 py-2.5 transition-colors ${Py(t.status)}`,children:e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("span",{className:`mt-1.5 h-2 w-2 rounded-full shrink-0 ${Oy(t.status)}`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium text-slate-100 leading-snug",children:t.label}),e.jsxs("span",{className:`text-[9px] font-mono uppercase tracking-[0.14em] shrink-0 ${Ry(t.status)}`,children:[Ty(t.status),Number.isFinite(t.latencyMs)?` · ${t.latencyMs}ms`:""]})]}),t.detail&&e.jsx("div",{className:"text-[10px] font-mono text-slate-400 mt-1 leading-relaxed line-clamp-3",children:t.detail})]})]})})}function Ly(){const[t,r]=i.useState(!1),[n,s]=i.useState(null),[a,o]=i.useState(!1),[c,l]=i.useState(""),u=i.useCallback(async()=>{if(!(window.api&&window.api.system&&typeof window.api.system.runHealthCheck=="function")){l("System health check is unavailable in this runtime.");return}r(!0),l("");try{const f=await window.api.system.runHealthCheck();s(f&&typeof f=="object"?f:null),f||l("Health check returned no data.")}catch(f){s(null),l(`Health check failed: ${f&&f.message?f.message:String(f)}`)}finally{r(!1)}},[]);i.useEffect(()=>{u()},[u]);const x=Array.isArray(n&&n.checks)?n.checks:[],p=a?x.filter(f=>f.status==="failed"||f.status==="warning"):x,d=My(p),m=x.filter(f=>f.status==="failed"||f.status==="warning").length;return e.jsxs("section",{"data-testid":"system-health-check-card",children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-widest text-cyan-300 mb-4 font-bold flex items-center justify-between gap-2",children:[e.jsx("span",{children:"System Health Check"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"system-health-filter-btn",onClick:()=>o(f=>!f),className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] transition-colors ${a?"border-amber-300/35 bg-amber-500/10 text-amber-200":"border-white/15 bg-white/5 text-slate-300 hover:bg-white/10"}`,children:a?"Show all":"Issues only"}),e.jsxs("button",{type:"button","data-testid":"system-health-run-btn",onClick:u,disabled:t,className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono uppercase tracking-[0.14em] text-cyan-200 hover:bg-cyan-500/20 disabled:opacity-50 inline-flex items-center gap-1.5",children:[t&&e.jsx("span",{className:"inline-block h-2 w-2 rounded-full border border-cyan-200/60 border-t-transparent animate-spin"}),t?"Checking":"Run again"]})]})]}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[12px] font-medium text-slate-200",children:"Connectivity, models, vault, and runtime diagnostics"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono mt-1 leading-relaxed",children:"Run this when Wi‑Fi, provider keys, or local Ollama look wrong."})]}),n&&e.jsxs("div",{"data-testid":"system-health-summary",className:`shrink-0 rounded-xl border px-3 py-2 text-[10px] font-mono ${n.ok?"border-emerald-400/30 bg-emerald-500/10 text-emerald-200":"border-amber-400/30 bg-amber-500/10 text-amber-100"}`,children:[e.jsx("div",{className:"font-bold uppercase tracking-[0.14em]",children:n.ok?"All critical checks passed":`${m} issue${m===1?"":"s"} found`}),n.generatedAt&&e.jsx("div",{className:"text-slate-400 mt-0.5",children:Pb(n.generatedAt)})]})]}),n&&e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:[e.jsx(la,{label:"Passed",value:n.passed,tone:"emerald"}),e.jsx(la,{label:"Failed",value:n.failed,tone:"rose"}),e.jsx(la,{label:"Warnings",value:n.warnings,tone:"amber"}),e.jsx(la,{label:"Skipped",value:n.skipped,tone:"slate"})]}),t&&!x.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500 py-6 text-center rounded-xl border border-dashed border-white/10",children:"Running diagnostics…"}),!t&&a&&!p.length&&x.length>0&&e.jsx("div",{className:"text-[10px] font-mono text-emerald-300 py-4 text-center rounded-xl border border-emerald-400/20 bg-emerald-500/5",children:"No warnings or failures — everything looks healthy."}),!t&&!x.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500 py-4 text-center rounded-xl border border-dashed border-white/10",children:"No results yet. Run the health check."}),e.jsx("div",{className:"space-y-3",children:d.map(f=>e.jsxs("details",{open:Dy(f.checks)||f.checks.length<=2,className:"rounded-xl border border-white/5 bg-black/20 overflow-hidden",children:[e.jsxs("summary",{className:"cursor-pointer list-none px-3 py-2.5 flex items-center justify-between gap-2 hover:bg-white/[0.03] transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:`text-[10px] uppercase tracking-[0.16em] font-bold ${f.tone||"text-slate-300"}`,children:f.label}),e.jsxs("span",{className:"text-[9px] font-mono text-slate-500",children:[f.checks.length," check",f.checks.length===1?"":"s"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[f.checks.some(b=>b.status==="failed")&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[8px] font-mono uppercase tracking-widest border border-rose-400/25 bg-rose-500/10 text-rose-200",children:"fail"}),f.checks.some(b=>b.status==="warning")&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[8px] font-mono uppercase tracking-widest border border-amber-400/25 bg-amber-500/10 text-amber-200",children:"warn"}),e.jsx("span",{className:"text-slate-500 text-[10px]",children:"▾"})]})]}),e.jsx("div",{className:"px-3 pb-3 grid grid-cols-1 gap-2",children:f.checks.map(b=>e.jsx($y,{check:b},b.id))})]},f.id))}),c&&e.jsx("div",{"data-testid":"system-health-status",className:"rounded-xl border border-rose-400/30 bg-rose-500/10 px-3 py-2 text-[10px] font-mono text-rose-200",children:c})]})]})}const _l=Object.freeze({neutral:{mood:"neutral",rgbMood:"idle",label:"Neutral",dot:"#8b5cf6",glow:"rgba(139, 92, 246, 0.02)",accent:"rgba(139, 92, 246, 0.12)",avatarFrom:"rgba(139, 92, 246, 0.8)",avatarTo:"rgba(99, 102, 241, 0.8)"},focused:{mood:"focused",rgbMood:"focused",label:"Focused",dot:"#22d3ee",glow:"rgba(34, 211, 238, 0.025)",accent:"rgba(34, 211, 238, 0.14)",avatarFrom:"rgba(34, 211, 238, 0.85)",avatarTo:"rgba(6, 182, 212, 0.85)"},caution:{mood:"caution",rgbMood:"caution",label:"Caution",dot:"#fbbf24",glow:"rgba(251, 191, 36, 0.02)",accent:"rgba(251, 191, 36, 0.12)",avatarFrom:"rgba(251, 191, 36, 0.85)",avatarTo:"rgba(245, 158, 11, 0.85)"},critical:{mood:"critical",rgbMood:"critical",label:"Critical",dot:"#fb7185",glow:"rgba(251, 113, 133, 0.025)",accent:"rgba(251, 113, 133, 0.12)",avatarFrom:"rgba(251, 113, 133, 0.85)",avatarTo:"rgba(244, 63, 94, 0.85)"}});function By(t){const r=String(t||"").trim().toLowerCase();return r==="online"||r==="healthy"||r==="ready"?"online":r==="offline"||r==="error"||r==="failed"?"offline":r==="degraded"||r==="reconnecting"||r==="caution"?"degraded":"unknown"}function Fy({isThinking:t=!1,isTyping:r=!1,connectionHealth:n="unknown"}={}){const s=By(n);return s==="offline"?"critical":s==="degraded"?"caution":t||r?"focused":"neutral"}function j0(t={}){const r=Fy(t),n=_l[r]||_l.neutral;return{mood:r,colors:n,rgbMood:n.rgbMood,label:n.label}}function Uy({isThinking:t=!1,isTyping:r=!1,connectionHealth:n="unknown"}={}){return i.useMemo(()=>j0({isThinking:t,isTyping:r,connectionHealth:n}),[t,r,n])}function zy({settings:t,onUpdateSetting:r,connectionHealth:n="unknown",isThinking:s=!1}){const[a,o]=i.useState(null),c=!!(t&&t.rgbEnabled),l=j0({isThinking:s,isTyping:!1,connectionHealth:n});i.useEffect(()=>{let x=!0;return(async()=>{if(window.api&&window.api.rgb&&typeof window.api.rgb.status=="function")try{const d=await window.api.rgb.status();x&&o(d&&typeof d=="object"?d:null)}catch{x&&o(null)}})(),()=>{x=!1}},[c,l.rgbMood]);const u=Object.values(_l);return e.jsxs("section",{"data-testid":"rgb-mood-card",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-fuchsia-300 mb-4 font-bold",children:"RGB · AI Mood Sync"}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-4",children:[e.jsx("div",{className:"text-[11px] text-slate-400 leading-relaxed",children:"When enabled, OpenRGB-compatible lighting follows the assistant mood — focused while streaming, amber on bridge warnings, red when offline."}),e.jsxs("label",{className:"flex justify-between items-center p-4 bg-black/30 hover:bg-black/40 transition-colors rounded-2xl border border-white/5 cursor-pointer group",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-slate-200",children:"Sync RGB with AI mood"}),e.jsx("div",{className:"text-[10px] text-slate-500",children:"Push hardware colors when mood shifts"})]}),e.jsx("div",{className:`h-5 w-10 rounded-full flex items-center px-1 transition-colors ${c?"bg-fuchsia-400/20 border border-fuchsia-400/40":"bg-slate-800 border border-white/5"}`,children:e.jsx("div",{className:`h-3 w-3 rounded-full transition-all ${c?"bg-fuchsia-400 ml-auto":"bg-slate-500"}`})}),e.jsx("input",{type:"checkbox",className:"hidden","data-testid":"settings-rgb-sync-toggle",checked:c,onChange:x=>r("rgbEnabled",x.target.checked)})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/25 px-3 py-2.5 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"h-3 w-3 rounded-full shrink-0",style:{backgroundColor:l.colors.dot,boxShadow:`0 0 10px ${l.colors.dot}66`}}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-[10px] font-mono uppercase tracking-[0.14em] text-slate-300",children:["Live mood · ",l.label]}),e.jsxs("div",{className:"text-[10px] font-mono text-slate-500 truncate",children:["RGB lane · ",l.rgbMood]})]})]}),a&&e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-widest text-slate-500 shrink-0",children:c?"armed":"off"})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:u.map(x=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2 py-1 rounded-lg border border-white/10 bg-black/30 text-[9px] font-mono uppercase tracking-wider text-slate-400",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:x.dot}}),x.label]},x.mood))})]})]})}function Hy(t){return t==="green"?"text-emerald-200 border-emerald-300/30 bg-emerald-500/10":t==="yellow"?"text-amber-200 border-amber-300/30 bg-amber-500/10":"text-rose-200 border-rose-300/30 bg-rose-500/10"}function Wy(){const[t,r]=i.useState(null),[n,s]=i.useState(!1),[a,o]=i.useState(""),c=i.useCallback(async()=>{s(!0);try{const u=window.api&&window.api.releaseHealth&&typeof window.api.releaseHealth.check=="function"?await window.api.releaseHealth.check():await window.api.invoke("releaseHealth:check");r(u||null),o("")}catch(u){o(u&&u.message?u.message:String(u))}finally{s(!1)}},[]);i.useEffect(()=>{c()},[c]);const l=Array.isArray(t&&t.rows)?t.rows:[];return e.jsxs("section",{"data-testid":"release-health-console",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-cyan-300 mb-4 font-bold",children:"Release Health"}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:`px-2 py-1 rounded border text-[10px] font-mono uppercase tracking-[0.14em] ${Hy(String(t&&t.status?t.status:"red"))}`,children:["Status ",String(t&&t.status?t.status:"unknown")]}),e.jsx("button",{type:"button","data-testid":"release-health-refresh-btn",disabled:n,onClick:c,className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.14em] font-mono text-slate-200 hover:bg-white/10 disabled:opacity-60",children:"Refresh"})]}),a&&e.jsx("div",{className:"rounded border border-rose-300/30 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-200",children:a}),e.jsxs("div",{className:"space-y-2",children:[l.map(u=>e.jsxs("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[10px] font-mono",children:[e.jsx("span",{className:"text-slate-200",children:u.id}),e.jsx("span",{className:u.ok?"text-emerald-300":u.required?"text-rose-300":"text-amber-300",children:u.ok?"ok":u.required?"missing":"optional-missing"})]}),e.jsx("div",{className:"text-[9px] text-slate-500 font-mono break-all",children:u.path})]},u.id)),l.length===0&&e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"No release health rows found."})]})]})]})}const Ky=[{id:"offline_only",label:"Offline Only",description:"Strict local-only lane; remote and relay disabled."},{id:"balanced_team",label:"Balanced Team",description:"Allows approved remote lanes with controlled relay."},{id:"enterprise_locked",label:"Enterprise Locked",description:"Admin-safe defaults for controlled enterprise rollout."}],Vy={offline_only:{allowRemoteBridge:!1,proofRelayEnabled:!1,hostedProxyEnabled:!1,connectOnStartup:!0,otelExportEnabled:!1},balanced_team:{allowRemoteBridge:!0,proofRelayEnabled:!1,hostedProxyEnabled:!1,connectOnStartup:!0,otelExportEnabled:!1},enterprise_locked:{allowRemoteBridge:!1,proofRelayEnabled:!1,hostedProxyEnabled:!1,connectOnStartup:!1,otelExportEnabled:!1,updateChannel:"stable"}};async function Oi(t){const r=JSON.stringify(t);let n=2166136261;for(let a=0;a>>0).toString(16).padStart(8,"0").repeat(8).slice(0,64)}function Gy({disabled:t}){const[r,n]=i.useState(""),[s,a]=i.useState(""),o=i.useRef(null),c=async x=>{if(t)return;const p=Vy[String(x||"")];if(p){a(x);try{const m={...await window.api.settings.get()||{},...p},f=await window.api.settings.update(m),b=await Oi(p);return await window.api.audit.append({event:"policy_profile_applied",profileId:String(x),profileHash:b,at:new Date().toISOString()}),n(`Applied ${x} (sha256:${b.slice(0,12)}...)`),f}catch(d){n(`Failed to apply ${x}: ${d&&d.message?d.message:String(d)}`)}finally{a("")}}},l=async()=>{try{const x=await window.api.settings.get(),p={id:"custom_export",exportedAt:new Date().toISOString(),settings:{allowRemoteBridge:!!(x&&x.allowRemoteBridge),proofRelayEnabled:!!(x&&x.proofRelayEnabled),hostedProxyEnabled:!!(x&&x.hostedProxyEnabled),connectOnStartup:x&&x.connectOnStartup!==!1,otelExportEnabled:!!(x&&x.otelExportEnabled)}},d=await Oi(p.settings);p.sha256=d;const m=new Blob([`${JSON.stringify(p,null,2)} +`],{type:"application/json"}),f=URL.createObjectURL(m),b=document.createElement("a");b.href=f,b.download=`neuralshell_policy_profile_${Date.now()}.json`,document.body.appendChild(b),b.click(),b.remove(),URL.revokeObjectURL(f),n(`Exported profile (sha256:${d.slice(0,12)}...)`)}catch(x){n(`Export failed: ${x&&x.message?x.message:String(x)}`)}},u=async x=>{const p=x&&x.target&&x.target.files?x.target.files[0]:null;if(p){if(o.current&&(o.current.value=""),t){n("Policy profile apply is unavailable for this tier.");return}a("import");try{const d=await p.text(),m=JSON.parse(d),f=m&&typeof m=="object"?m:{},b=f.settings&&typeof f.settings=="object"?f.settings:null;if(!b)throw new Error("Imported profile is missing a settings object.");const g={...await window.api.settings.get()||{},...b};await window.api.settings.update(g);const y=await Oi(b);await window.api.audit.append({event:"policy_profile_imported",profileId:String(f.id||"imported"),profileHash:y,at:new Date().toISOString()}),n(`Imported ${String(f.id||"profile")} (sha256:${y.slice(0,12)}...)`)}catch(d){n(`Import failed: ${d&&d.message?d.message:String(d)}`)}finally{a("")}}};return e.jsxs("section",{"data-testid":"policy-profile-card",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-violet-300 mb-4 font-bold",children:"Policy Profiles"}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-2",children:[Ky.map(x=>e.jsxs("div",{className:"rounded border border-white/10 bg-black/30 px-3 py-2 flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-slate-200",children:x.label}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:x.description})]}),e.jsx("button",{type:"button","data-testid":`policy-apply-${x.id}`,disabled:!!t||s===x.id,onClick:()=>c(x.id),className:"px-2 py-1 rounded border border-violet-300/30 bg-violet-500/10 text-[9px] uppercase tracking-[0.14em] font-mono text-violet-200 hover:bg-violet-500/20 disabled:opacity-60",children:s===x.id?"Applying":"Apply"})]},x.id)),e.jsxs("div",{className:"pt-2 flex flex-wrap gap-2",children:[e.jsx("button",{type:"button","data-testid":"policy-export-current-btn",onClick:l,className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.14em] font-mono text-slate-200 hover:bg-white/10",children:"Export Current Profile"}),e.jsxs("label",{className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.14em] font-mono text-slate-200 hover:bg-white/10 cursor-pointer",children:["Import Profile JSON",e.jsx("input",{ref:o,"data-testid":"policy-import-input",type:"file",accept:"application/json,.json",className:"hidden",onChange:u,disabled:!!t||s==="import"})]})]}),r&&e.jsx("div",{className:"text-[10px] font-mono text-slate-300 break-all",children:r})]})]})}function Ti(t){const r=String(t||"").trim(),n=r.startsWith("#")?r:`#${r}`,s=/^#([0-9a-fA-F]{3})$/.exec(n);if(s){const[o,c,l]=s[1].split("");return`#${o}${o}${c}${c}${l}${l}`.toUpperCase()}const a=/^#([0-9a-fA-F]{6})$/.exec(n);return a?`#${a[1].toUpperCase()}`:""}function Jy(t){const r=String(t||"").trim();return/^#?[0-9a-fA-F]{3}$/.test(r)||/^#?[0-9a-fA-F]{6}$/.test(r)}function k0(){const t=Xt(c=>c.accentColor),r=Xt(c=>c.customAccentHex),n=Xt(c=>c.setAccentColor),s=Xt(c=>c.setCustomAccentHex),a=i.useMemo(()=>{const c=Ti(r);if(c)return c;const l=Sn[t]||Sn.violet;return String(l.primary||"#8B5CF6").toUpperCase()},[t,r]),o=i.useCallback(c=>{const l=Ti(c);l&&s(l)},[s]);return{accent:a,setAccent:o,isValidAccent:Jy,normalizeAccent:Ti,accentColor:t,setAccentColor:n,setCustomAccentHex:s}}const qy=Object.keys(Sn),Yy=["small","medium","large"],Zy=["left","right"],Hd=i.memo(function({checked:r,onChange:n,label:s,description:a}){return e.jsxs("label",{className:"flex items-center justify-between cursor-pointer group py-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[12px] font-medium text-slate-200 group-hover:text-white transition-colors",children:s}),a&&e.jsx("div",{className:"text-[10px] text-slate-500 mt-0.5",children:a})]}),e.jsx("button",{type:"button",role:"switch","aria-checked":r,onClick:()=>n(!r),className:`relative w-10 h-5.5 rounded-full transition-all duration-200 ${r?"bg-violet-500/40 border-violet-400/40":"bg-white/5 border-white/10"} border flex-shrink-0`,children:e.jsx("span",{className:`absolute top-0.5 h-4 w-4 rounded-full transition-all duration-200 ${r?"left-5 bg-violet-400 shadow-[0_0_8px_rgba(139,92,246,0.4)]":"left-0.5 bg-slate-400"}`})})]})}),Mi=i.memo(function({value:r,options:n,onChange:s,labels:a}){return e.jsx("div",{className:"inline-flex items-center rounded-lg border border-violet-400/15 bg-violet-500/5 overflow-hidden",children:n.map((o,c)=>e.jsx("button",{type:"button",onClick:()=>s(o),className:`px-3 py-1.5 text-[10px] font-mono uppercase tracking-[0.1em] transition-all ${c>0?"border-l border-violet-400/15":""} ${r===o?"bg-violet-500/20 text-violet-200 font-bold":"text-slate-400 hover:bg-white/5 hover:text-slate-200"}`,children:a?a[c]:o},o))})}),Xy=i.memo(function(){const{fontSize:r,setFontSize:n,accentColor:s,setAccentColor:a,compactMode:o,setCompactMode:c,animationsEnabled:l,setAnimationsEnabled:u,sidebarPosition:x,setSidebarPosition:p,visualStyle:d,setVisualStyle:m,resetToDefaults:f}=Xt(),{accent:b,setAccent:h,isValidAccent:g,normalizeAccent:y}=k0(),[I,A]=i.useState(b);i.useEffect(()=>{A(b)},[b]);const C=cd[r]||cd.medium;return e.jsxs("section",{className:"rounded-xl border border-violet-400/15 bg-shell-soft/40 p-5 space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-[13px] font-bold text-violet-300",children:"Appearance & Layout"}),e.jsx("p",{className:"text-[10px] font-mono text-slate-500 mt-0.5",children:"Customize how ProofForge looks and feels"})]}),e.jsx("button",{type:"button",onClick:f,className:"px-2.5 py-1 rounded-lg border border-slate-500/20 bg-white/[0.02] text-[9px] font-mono text-slate-400 uppercase tracking-wider hover:bg-white/5 hover:text-slate-300 transition-all",children:"Reset All"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-[11px] font-mono text-slate-300",children:[e.jsx("span",{className:"text-violet-400",children:"visualStyle"})," ",e.jsx("span",{className:"text-slate-600",children:"="})," ",e.jsxs("span",{className:"text-green-300",children:['"',d,'"']})]}),e.jsx(Mi,{value:d,options:["operator","frutiger-aero"],onChange:m,labels:["Operator","Frutiger Aero"]}),e.jsx("p",{className:"text-[10px] text-slate-500",children:"Frutiger Aero: glossy glass, sky gradients, bubbles — Windows Vista nostalgia mode."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"text-[11px] font-mono text-slate-300",children:[e.jsx("span",{className:"text-violet-400",children:"fontSize"})," ",e.jsx("span",{className:"text-slate-600",children:"="})," ",e.jsxs("span",{className:"text-green-300",children:['"',r,'"']})]}),e.jsxs("span",{className:"text-[9px] font-mono text-slate-600",children:[C.base,"px base"]})]}),e.jsx(Mi,{value:r,options:Yy,onChange:n,labels:["Sm","Md","Lg"]}),e.jsxs("div",{className:"text-[10px] text-slate-500 mt-1",style:{fontSize:`${C.base}px`},children:["Preview text at ",r," size"]})]}),e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("label",{className:"text-[11px] font-mono text-slate-300",children:[e.jsx("span",{className:"text-violet-400",children:"accentColor"})," ",e.jsx("span",{className:"text-slate-600",children:"="})," ",e.jsxs("span",{className:"text-green-300",children:['"',s,'"']})]}),e.jsx("div",{className:"flex items-center gap-2",children:qy.map(w=>{const j=Sn[w],E=s===w;return e.jsx("button",{type:"button",onClick:()=>a(w),title:w,className:`w-7 h-7 rounded-full transition-all duration-200 border-2 ${E?"scale-110 shadow-[0_0_12px_var(--ring)]":"border-transparent hover:scale-105 opacity-70 hover:opacity-100"}`,style:{backgroundColor:j.primary,borderColor:E?j.hover:"transparent","--ring":j.ring}},w)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[11px] font-mono text-slate-300",children:e.jsx("span",{className:"text-violet-400",children:"customAccentHex"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{"data-testid":"settings-accent-input",type:"text",value:I,onChange:w=>A(w.target.value),onBlur:()=>{if(g(I)){h(y(I));return}A(b)},className:"flex-1 bg-slate-900 border border-white/10 rounded-xl px-3 py-2 text-sm text-slate-200 outline-none focus:border-violet-400/50 font-mono",placeholder:"#22D3EE"}),e.jsx("div",{className:"h-9 w-9 rounded-lg border border-white/10",style:{backgroundColor:b}})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-[11px] font-mono text-slate-300",children:[e.jsx("span",{className:"text-violet-400",children:"sidebarPosition"})," ",e.jsx("span",{className:"text-slate-600",children:"="})," ",e.jsxs("span",{className:"text-green-300",children:['"',x,'"']})]}),e.jsx(Mi,{value:x,options:Zy,onChange:p,labels:["← Left","Right →"]})]}),e.jsxs("div",{className:"space-y-1 border-t border-white/5 pt-3",children:[e.jsx(Hd,{checked:o,onChange:c,label:"Compact Mode",description:"Reduce padding and spacing for more content density"}),e.jsx(Hd,{checked:l,onChange:u,label:"Animations",description:"Enable smooth transitions and pulse effects"})]})]})}),Qy={local:"Local (Ollama)",hosted:"Hosted",unknown:"Unknown"},ew={connected:{text:"Connected",cls:"text-emerald-300"},degraded:{text:"Degraded",cls:"text-amber-300"},unreachable:{text:"Not responding",cls:"text-rose-300"},"not-tested":{text:"Selected — not tested",cls:"text-slate-400"}},tw={connected:{text:"Connected",cls:"text-emerald-300"},"blocked-by-policy":{text:"Blocked by Offline Mode",cls:"text-amber-300"},"not-tested":{text:"Not tested",cls:"text-slate-400"}};function rw({connectionInfo:t}){const r=i.useMemo(()=>Np({connectionInfo:t}),[t]),n=ew[r.localStatus]||null,s=tw[r.hostedStatus]||null,a=!!r.currentProblem;return e.jsxs("div",{"data-testid":"bridge-diagnosis-card",className:`rounded-xl border px-4 py-3 space-y-2 text-[10px] font-mono ${a?"border-amber-400/25 bg-amber-500/[0.04]":"border-emerald-400/15 bg-emerald-500/[0.03]"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-[9px] text-slate-500 uppercase tracking-widest font-bold",children:"Active Route"}),e.jsxs("span",{"data-testid":"bridge-diagnosis-route",className:"text-slate-200",children:[Qy[r.selectedRoute]||r.selectedRoute,t&&t.model?` / ${t.model}`:""]})]}),n&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-slate-500",children:"Local"}),e.jsx("span",{"data-testid":"bridge-diagnosis-local",className:n.cls,children:n.text})]}),s&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-slate-500",children:"Hosted"}),e.jsx("span",{"data-testid":"bridge-diagnosis-hosted",className:s.cls,children:s.text})]}),a&&e.jsx("div",{"data-testid":"bridge-diagnosis-problem",className:"text-amber-200/80 leading-snug border-t border-amber-400/10 pt-2 mt-1",children:r.currentProblem}),!a&&r.selectedRoute!=="unknown"&&e.jsxs("div",{"data-testid":"bridge-diagnosis-clear",className:"text-emerald-400/70 border-t border-emerald-400/10 pt-2 mt-1",children:["Route clear",r.hostedStatus==="blocked-by-policy"&&r.selectedRoute==="local"&&e.jsx("span",{className:"text-slate-500 ml-2",children:"· Hosted blocked by Offline Mode"})]})]})}const Ts=[{id:"ollama",label:"Local Node (Ollama)",defaultBaseUrl:"http://127.0.0.1:11434",remote:!1},{id:"openai",label:"OpenAI Network",defaultBaseUrl:"https://api.openai.com",remote:!0},{id:"openrouter",label:"OpenRouter Network",defaultBaseUrl:"https://openrouter.ai/api",remote:!0},{id:"groq",label:"Groq Network",defaultBaseUrl:"https://api.groq.com/openai",remote:!0},{id:"together",label:"Together Network",defaultBaseUrl:"https://api.together.xyz",remote:!0},{id:"custom_openai",label:"Custom OpenAI-Compatible",defaultBaseUrl:"https://api.example.com",remote:!0}],Wd={ollama:["llama3","mistral","qwen2.5-coder:7b"],openai:["gpt-4.1-mini","gpt-4o-mini","gpt-4.1"],openrouter:["openai/gpt-4o-mini","anthropic/claude-3.5-sonnet","meta-llama/llama-3.3-70b-instruct"],groq:["llama-3.3-70b-versatile","llama3-8b-8192","mixtral-8x7b-32768"],together:["meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo","Qwen/Qwen2.5-Coder-32B-Instruct"],custom_openai:[]},bs={openai:"OPENAI_API_KEY",openrouter:"OPENROUTER_API_KEY",groq:"GROQ_API_KEY",together:"TOGETHER_API_KEY",custom_openai:"CUSTOM_OPENAI_API_KEY"};function Kd(t){const r=String(t||"").trim();return r?r.replace(/_/g," "):""}function Yt(t){const r=Ts.find(n=>n.id===String(t||"").trim());return r?r.defaultBaseUrl:"http://127.0.0.1:11434"}function ca(t){return t!=="ollama"}function Gt(t){const r=Ts.find(n=>n.id===String(t||"").trim());return!!(r&&r.remote)}function Vd(t,r){return(Array.isArray(t&&t.capabilities)?t.capabilities:[]).includes(String(r||"").trim())}function nw(t){const r=Ts.find(n=>n.id===String(t||"").trim());return r?r.label:Ka(t)}function sw(t={}){const r=Array.isArray(t.connectionProfiles)?t.connectionProfiles:[],n=String(t.activeProfileId||"").trim();if(n){const s=r.find(a=>String(a&&a.id||"")===n);if(s)return s}return r[0]||null}function mn(t={}){const r=t||{},n=sw(r),s=String(r.provider||n&&n.provider||"ollama"),a=String(r.ollamaBaseUrl||n&&n.baseUrl||Yt(s)).trim();return{...r,provider:s,apiKey:String(r.apiKey||""),apiKeyPresent:!!r.apiKeyPresent,ollamaBaseUrl:a||Yt(s),hostedProxyEnabled:!!r.hostedProxyEnabled}}const aw=[{id:"section-connection",label:"Connection"},{id:"section-security",label:"Security"},{id:"section-personalization",label:"Personalization"},{id:"section-updates",label:"Updates"},{id:"section-support",label:"Support"}];function hs({id:t,title:r,accentClass:n="text-slate-400",children:s}){return e.jsxs("div",{id:t,className:"space-y-6 scroll-mt-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`text-[10px] uppercase tracking-[0.22em] font-bold shrink-0 ${n}`,children:r}),e.jsx("div",{className:"h-px flex-1 bg-gradient-to-r from-white/10 to-transparent"})]}),e.jsx("div",{className:"space-y-8",children:s})]})}function ow({connectionInfo:t}){const{closeSettings:r}=$l(),[n,s]=O.useState(null),[a,o]=O.useState("llama3"),[c,l]=O.useState(!1),[u,x]=O.useState({tone:"idle",text:""}),[p,d]=O.useState(null),[m,f]=O.useState(null),[b,h]=O.useState(!1),[g,y]=O.useState(""),[I,A]=O.useState({running:!1,enabled:!1,rateCapPerMinute:60}),[C,w]=O.useState({enabled:!1,host:"127.0.0.1",port:4317,ok:!1,reason:""}),[j,E]=O.useState(!1),[N,_]=O.useState(null),[S,R]=O.useState(!1),$=O.useRef(null),U=O.useRef(null);O.useEffect(()=>{let M=!0;return(async()=>{try{const[V,G]=await Promise.all([window.api.settings.get(),window.api.state.get()]);if(!M)return;if(s(mn(V||{})),V&&V.hostedProxyStatus&&A({running:!!V.hostedProxyStatus.running,enabled:!!V.hostedProxyStatus.enabled,rateCapPerMinute:Number(V.hostedProxyStatus.rateCapPerMinute||60),baseUrl:String(V.hostedProxyStatus.baseUrl||"")}),window.api&&window.api.otel&&typeof window.api.otel.status=="function"){const te=await window.api.otel.status().catch(()=>null);te&&typeof te=="object"&&w({enabled:!!te.enabled,host:String(te.host||"127.0.0.1"),port:Number(te.port||4317),ok:!1,reason:""})}o(String(G&&G.model||"llama3"))}catch(V){if(!M)return;x({tone:"bad",text:`Failed to load settings: ${V&&V.message?V.message:String(V)}`})}})(),()=>{M=!1,$.current&&clearTimeout($.current)}},[]);const P=String(n&&n.provider||"ollama"),D=String(n&&n.licenseMode||"preview").toLowerCase(),z=Vd(n,"policy_profiles_apply"),F=Vd(n,"release_health_console")||D==="enterprise",J=ca(P),ee=O.useMemo(()=>{const V=[...Wd[P]||[],String(a||"").trim()].filter(Boolean);return Array.from(new Set(V))},[P,a]),ie=O.useMemo(()=>{if(!n)return[];const M=String(n.ollamaBaseUrl||"").trim(),V=!!String(a||"").trim(),G=!J||!!String(n.apiKey||"").trim()||!!n.apiKeyPresent,te=!Gt(P)||!!n.allowRemoteBridge;return[{id:"hosted",label:"Hosted access",ok:te,hint:te?"Remote providers allowed":"Enable Hosted Provider Access"},{id:"endpoint",label:"Endpoint",ok:!!M,hint:M||"Set base URL"},{id:"auth",label:"Credentials",ok:G,hint:G?"Key ready":`Set ${bs[P]||"API key"}`},{id:"model",label:"Model",ok:V,hint:V?String(a):"Choose a model"}]},[a,P,J,n]),ye=ie.every(M=>M.ok),pe=O.useMemo(()=>{const M=Array.isArray(m&&m.results)?m.results:[],V=new Map(M.map(G=>[String(G.provider||"").trim(),G]));return Ts.map(G=>{const te=V.get(G.id);if(!te)return{id:G.id,label:G.label,status:"unknown",detail:"Not checked yet"};if(te.status==="connected")return{id:G.id,label:G.label,status:"connected",detail:`${Number(te.modelCount||0)} models · ${Number(te.latencyMs||0)} ms`};if(te.status==="skipped"){const de=bs[G.id],L=Kd(te.reason||te.healthReason||"skipped"),be=String(L||"").startsWith("missing")&&de?`${L} (${de})`:L||"skipped";return{id:G.id,label:G.label,status:"skipped",detail:be}}return{id:G.id,label:G.label,status:"failed",detail:Kd(te.reason||te.healthReason||"connection failed")}})},[m]),K=O.useCallback(M=>{if(!M||typeof M!="object")return{};const{connectionProfiles:V,...G}=M;return G},[]),H=O.useCallback(async(M,V="Settings saved.")=>{const G=mn(M||{});s(G);try{const te=await window.api.settings.update(K(G)),de=mn(te||G);return s(de),x({tone:"ok",text:V}),typeof window<"u"&&window.dispatchEvent(new CustomEvent("neuralshell:settings-updated")),de}catch(te){return x({tone:"bad",text:`Settings save failed: ${te&&te.message?te.message:String(te)}`}),null}},[]),W=O.useCallback((M,V="Settings saved.")=>{U.current=null,H(M,V)},[H]),Z=O.useCallback((M,V="Settings saved.",G=0)=>{if(U.current=M,$.current&&(clearTimeout($.current),$.current=null),G<=0){W(M,V);return}$.current=setTimeout(()=>{const te=U.current;te&&W(te,V)},G)},[W]),ce=O.useCallback(async()=>{if(!(window.api&&window.api.bridge&&typeof window.api.bridge.sweep=="function"))return x({tone:"bad",text:"Provider sweep bridge is unavailable in this runtime."}),null;h(!0);try{const M=await window.api.bridge.sweep(),V=M&&typeof M=="object"?M:null;return f(V),V&&V.hostedProxy&&A({running:!!V.hostedProxy.running,enabled:!!V.hostedProxy.enabled,rateCapPerMinute:Number(V.hostedProxy.rateCapPerMinute||60),baseUrl:String(V.hostedProxy.baseUrl||"")}),y(String(V&&V.generatedAt||new Date().toISOString())),V&&x({tone:V.failed>0?"bad":"ok",text:`Provider sweep complete: ${V.connected}/${V.total} connected.`}),V}catch(M){return x({tone:"bad",text:`Provider sweep failed: ${M&&M.message?M.message:String(M)}`}),null}finally{h(!1)}},[]),fe=O.useCallback(async()=>{if(!n)return;l(!0),d(null);const M={...n,provider:"ollama",ollamaBaseUrl:Yt("ollama"),apiKey:"",apiKeyPresent:!1,allowRemoteBridge:!1,connectOnStartup:!0};await H(M,"Local lane enabled. Remote providers are now disabled.")&&await ce(),l(!1)},[ce,H,n]),me=O.useCallback(async()=>{if(!n)return;l(!0),d(null);const M=Gt(P)?P:"openai",V={...n,provider:M,ollamaBaseUrl:Yt(M),allowRemoteBridge:!0,connectOnStartup:!0,apiKeyPresent:ca(M)?!!n.apiKeyPresent:!1,apiKey:ca(M)?String(n.apiKey||""):""};await H(V,"Hosted lane enabled. Add API credentials, then run validation.")&&await ce(),l(!1)},[P,ce,H,n]),ke=O.useCallback(async()=>{if(!(window.api&&window.api.bridge&&typeof window.api.bridge.importEnvProfiles=="function")){x({tone:"bad",text:"Environment profile import is unavailable in this runtime."});return}l(!0);try{const M=await window.api.bridge.importEnvProfiles(),V=await window.api.settings.get();s(mn(V||{})),d(null);const G=Array.isArray(M&&M.importedProfiles)?M.importedProfiles.length:0;x({tone:"ok",text:`Imported ${G} profile${G===1?"":"s"} from environment.`}),await ce()}catch(M){x({tone:"bad",text:`Env profile import failed: ${M&&M.message?M.message:String(M)}`})}finally{l(!1)}},[ce]),Pe=O.useCallback(async()=>{if(n){l(!0);try{const M={...n,hostedProxyEnabled:!n.hostedProxyEnabled};await H(M,M.hostedProxyEnabled?"Hosted fallback proxy enabled (Together gateway, rate capped).":"Hosted fallback proxy disabled.")&&await ce()}finally{l(!1)}}},[ce,H,n]),_e=O.useCallback(async()=>{if(!n)return;const M=!n.otelExportEnabled;if(await H({...n,otelExportEnabled:M},M?"OpenTelemetry export enabled.":"OpenTelemetry export disabled.")&&window.api&&window.api.otel&&typeof window.api.otel.setEnabled=="function"){const G=await window.api.otel.setEnabled(M).catch(()=>null);G&&typeof G=="object"&&w(te=>({...te,enabled:!!G.enabled,host:String(G.host||te.host),port:Number(G.port||te.port)}))}},[H,n]),ne=O.useCallback(async()=>{if(!(window.api&&window.api.otel&&typeof window.api.otel.verify=="function"))return;const M=await window.api.otel.verify().catch(()=>null);!M||typeof M!="object"||w(V=>({...V,ok:!!M.ok,reason:String(M.reason||""),host:String(M.host||V.host),port:Number(M.port||V.port)}))},[]),we=(M,V)=>{if(!n)return;const G=String(n.provider||"ollama"),te={...n,[M]:V};if(M==="provider"){const be=String(V||"ollama"),Q=Yt(G),We=String(n.ollamaBaseUrl||"").trim();(!We||We===Q)&&(te.ollamaBaseUrl=Yt(be)),Gt(be)&&(te.allowRemoteBridge=!0),ca(be)||(te.apiKey="",te.apiKeyPresent=!1);const oe=Wd[be]||[];if(oe.length>0){const xe=String(oe[0]);o(xe),te.defaultModel=xe,window.api&&window.api.state&&typeof window.api.state.update=="function"&&window.api.state.update({model:xe}).catch(()=>{})}d(null)}M==="apiKey"&&(te.apiKeyPresent=!!String(V||"").trim());const de=mn(te);s(de),Z(de,"Settings saved.",M==="ollamaBaseUrl"||M==="apiKey"?450:0)},De=async()=>{const M=String(a||"").trim();if(!M){x({tone:"bad",text:"Model is required."});return}l(!0);try{await window.api.state.update({model:M}),x({tone:"ok",text:`Model set to ${M}.`})}catch(V){x({tone:"bad",text:`Model update failed: ${V&&V.message?V.message:String(V)}`})}finally{l(!1)}},re=async()=>{if(!n)return;const M=String(n.ollamaBaseUrl||Yt(P)).trim();if(!M){x({tone:"bad",text:"Base URL is required for bridge test."});return}if(Gt(P)&&!n.allowRemoteBridge){x({tone:"bad",text:"Enable Hosted Provider Access before testing remote providers."});return}if(J&&!String(n.apiKey||"").trim()&&!n.apiKeyPresent){x({tone:"bad",text:"API key is required. Paste your key, save settings, then test again."});return}const V={id:String(n.activeProfileId||""),provider:P,baseUrl:M,timeoutMs:Math.max(8e3,Math.min(Number(n.timeoutMs)||15e3,12e3)),retryCount:0,defaultModel:String(a||"llama3").trim()||"llama3",apiKey:String(n.apiKey||"")};l(!0),d(null);try{const G=await window.api.bridge.test(V);if(d(G),G&&G.ok){x({tone:"ok",text:`Live bridge verified (${G.provider}) with ${Number(G.modelCount)||0} models.`});const te={provider:String(G.provider||P),model:String(a||""),modelCount:Number(G.modelCount||0),baseUrl:String(G.baseUrl||M)};_(te),S||(E(!0),R(!0))}else{const te=G&&G.health&&G.health.reason?G.health.reason:"Bridge test failed.";x({tone:"bad",text:ld(new Error(te),{provider:P,baseUrl:M,model:V.defaultModel,ollamaBaseUrl:M})})}}catch(G){d(null),x({tone:"bad",text:ld(G,{provider:P,baseUrl:M,model:V.defaultModel,ollamaBaseUrl:M})})}finally{l(!1)}},ae=async()=>{if(n){l(!0),d(null);try{await window.api.llm.cancelStream().catch(()=>!1);const M={...n,provider:"ollama",apiKey:"",apiKeyPresent:!1,ollamaBaseUrl:Yt("ollama"),allowRemoteBridge:!1,connectOnStartup:!1},V=await window.api.settings.update(M);s(mn(V||M)),x({tone:"ok",text:"Offline kill switch engaged. Hosted providers disabled and bridge stream cancelled."})}catch(M){x({tone:"bad",text:`Offline kill switch failed: ${M&&M.message?M.message:String(M)}`})}finally{l(!1)}}};return n?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[149] bg-black/40 backdrop-blur-[2px] transition-all",onClick:r}),e.jsxs("div",{"data-testid":"settings-drawer",className:"fixed right-0 top-0 bottom-0 max-w-xl w-full z-[150] bg-slate-950 border-l border-cyan-400/20 shadow-[-20px_0_50px_rgba(0,0,0,0.6)] p-8 flex flex-col animate-fade-up",style:{borderImage:"linear-gradient(180deg, rgba(6,182,212,0.3), rgba(139,92,246,0.15), rgba(217,70,239,0.08)) 1"},children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight text-gradient animate-gradient-shift",style:{backgroundImage:"linear-gradient(90deg, #06b6d4, #8b5cf6, #d946ef, #06b6d4)"},children:"Configuration"}),e.jsx("button",{"data-testid":"settings-close-btn",onClick:r,className:"h-10 w-10 rounded-full hover:bg-white/5 flex items-center justify-center text-slate-400 hover:text-white transition-colors",children:"✕"})]}),e.jsx("nav",{"data-testid":"settings-section-nav",className:"sticky top-0 z-10 -mx-2 mb-4 px-2 py-2 flex flex-wrap gap-1.5 border-b border-white/[0.06] bg-slate-950/95 backdrop-blur-sm",children:aw.map(M=>e.jsx("button",{type:"button",onClick:()=>{const V=document.getElementById(M.id);V&&typeof V.scrollIntoView=="function"&&V.scrollIntoView({behavior:"smooth",block:"start"})},className:"px-2.5 py-1 rounded-lg border border-white/10 bg-white/[0.03] text-[9px] font-mono uppercase tracking-[0.14em] text-slate-400 hover:text-cyan-200 hover:border-cyan-400/25 transition-colors",children:M.label},M.id))}),e.jsxs("div",{className:"space-y-10 flex-1 overflow-y-auto pr-4 custom-scrollbar",children:[e.jsxs(hs,{id:"section-connection",title:"Connection & Models",accentClass:"text-emerald-300",children:[e.jsxs("section",{children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-widest text-emerald-400 mb-4 font-bold flex items-center gap-2",children:["LLM Bridge Profile",e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-emerald-500/10 text-emerald-400 text-[8px] font-mono border border-emerald-500/20",children:"LIVE"})]}),e.jsxs("div",{className:"space-y-4 p-5 bg-black/30 rounded-2xl border border-white/5 shadow-inner",children:[e.jsxs("div",{"data-testid":"settings-bridge-readiness",className:`rounded-xl border px-3 py-3 space-y-2 ${ye?"border-emerald-400/25 bg-emerald-500/5":"border-amber-400/20 bg-amber-500/5"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.16em] font-bold text-slate-200",children:"Connection checklist"}),e.jsx("span",{className:`text-[9px] font-mono uppercase tracking-[0.14em] ${ye?"text-emerald-300":"text-amber-300"}`,children:ye?"ready to test":"needs attention"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:ie.map(M=>e.jsxs("div",{className:"flex items-start gap-2 text-[10px] font-mono",children:[e.jsx("span",{className:M.ok?"text-emerald-400":"text-amber-400",children:M.ok?"✓":"○"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-slate-300",children:M.label}),e.jsx("div",{className:"text-slate-500",children:M.hint})]})]},M.id))})]}),t&&e.jsx(rw,{connectionInfo:t}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[10px] text-slate-400 uppercase tracking-widest font-bold ml-1",children:"Provider Engine"}),e.jsx("select",{"data-testid":"settings-provider-select",value:P,onChange:M=>we("provider",M.target.value),className:"w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-sm text-slate-200 outline-none focus:border-cyan-400/50 transition-all cursor-pointer font-mono",children:Ts.map(M=>e.jsx("option",{value:M.id,children:M.label},M.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[10px] font-mono",children:[e.jsx("span",{className:`px-2 py-0.5 rounded border ${Gt(P)?"border-violet-400/30 bg-violet-500/10 text-violet-200":"border-cyan-400/30 bg-cyan-500/10 text-cyan-200"}`,children:Gt(P)?"Hosted lane":"Local lane"}),Gt(P)&&n.allowRemoteBridge&&e.jsx("span",{className:"text-emerald-400/90",children:"Hosted access enabled"}),Gt(P)&&bs[P]&&e.jsxs("span",{className:"text-slate-500",children:["Env: ",bs[P]]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[10px] text-slate-400 uppercase tracking-widest font-bold ml-1",children:"Base URL / Endpoint"}),e.jsx("input",{type:"text",value:n.ollamaBaseUrl||"",onChange:M=>we("ollamaBaseUrl",M.target.value),placeholder:Yt(P),className:"w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-sm text-slate-200 placeholder-slate-600 outline-none focus:border-cyan-400/50 focus:ring-1 focus:ring-cyan-400/10 transition-all font-mono"})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("label",{className:"text-[10px] text-slate-400 uppercase tracking-widest font-bold ml-1 flex justify-between",children:[e.jsx("span",{children:"Authorization Key"}),!J&&e.jsx("span",{className:"text-slate-600 italic",children:"Not required for local"})]}),e.jsx("input",{type:"password",value:n.apiKey||"",onChange:M=>we("apiKey",M.target.value),placeholder:J?"sk-...":"Optional",disabled:!J,className:"w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-sm text-slate-200 placeholder-slate-600 outline-none focus:border-cyan-400/50 focus:ring-1 focus:ring-cyan-400/10 transition-all font-mono disabled:opacity-50"}),J&&e.jsx("div",{"data-testid":"settings-api-key-status",className:`text-[10px] font-mono ${n.apiKeyPresent?"text-emerald-300":"text-slate-500"}`,children:n.apiKeyPresent?"Key stored securely in Vault+.":`Paste your ${bs[P]||"API key"} — saves automatically.`})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[10px] text-slate-400 uppercase tracking-widest font-bold ml-1",children:"Active Model"}),e.jsx("input",{"data-testid":"settings-model-input",list:"settings-model-suggestions",type:"text",value:a,onChange:M=>o(M.target.value),placeholder:"Set active model name",className:"w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-sm text-slate-200 placeholder-slate-600 outline-none focus:border-cyan-400/50 focus:ring-1 focus:ring-cyan-400/10 transition-all font-mono"}),ee.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:ee.slice(0,4).map(M=>e.jsx("button",{type:"button",onClick:()=>o(M),className:`px-2 py-1 rounded-lg border text-[9px] font-mono transition-colors ${String(a||"")===M?"border-cyan-400/40 bg-cyan-500/15 text-cyan-100":"border-white/10 bg-white/5 text-slate-400 hover:text-slate-200 hover:border-white/20"}`,children:M},M))}),e.jsx("datalist",{id:"settings-model-suggestions",children:ee.map(M=>e.jsx("option",{value:M},M))}),e.jsx("button",{type:"button",onClick:De,disabled:c,className:"px-3 py-2 rounded-xl border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-cyan-200 hover:bg-cyan-500/20 disabled:opacity-50",children:"Apply Model"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsxs("button",{"data-testid":"settings-test-connection-btn",type:"button",onClick:re,disabled:c,className:"px-3 py-2 rounded-xl border border-emerald-300/30 bg-emerald-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-emerald-200 hover:bg-emerald-500/20 disabled:opacity-50 inline-flex items-center justify-center gap-2",children:[c&&e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full border border-emerald-200/70 border-t-transparent animate-spin"}),c?"Testing…":"Test Live Connection"]}),e.jsx("button",{"data-testid":"settings-offline-kill-btn",type:"button",onClick:ae,disabled:c,className:"px-3 py-2 rounded-xl border border-rose-300/30 bg-rose-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-rose-200 hover:bg-rose-500/20 disabled:opacity-50",children:"Offline Kill Switch"})]}),p&&e.jsxs("div",{className:`rounded-xl border px-3 py-2 text-[10px] font-mono space-y-1.5 ${p.ok?"border-emerald-400/30 bg-emerald-500/10 text-emerald-200":"border-rose-400/30 bg-rose-500/10 text-rose-200"}`,children:[e.jsx("div",{children:p.ok?`Verified ${nw(p.provider)} · ${p.modelCount||0} models`:`Bridge test failed: ${p.health&&p.health.reason?p.health.reason:"unknown reason"}`}),p.ok&&p.baseUrl&&e.jsx("div",{className:"text-emerald-300/80 truncate",children:p.baseUrl}),p.ok&&Array.isArray(p.models)&&p.models.length>0&&e.jsxs("div",{className:"text-emerald-300/70",children:["Sample: ",p.models.slice(0,3).join(", "),p.models.length>3?"…":""]}),p.ok&&e.jsx("button",{type:"button","data-testid":"share-proof-open-btn",onClick:()=>E(!0),className:"mt-2 px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-cyan-100 hover:bg-cyan-500/20",children:"Share Proof"})]})]})]}),e.jsxs("section",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-amber-300 mb-4 font-bold",children:"Provider Setup Wizard"}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx("button",{"data-testid":"settings-setup-local-btn",type:"button",onClick:fe,disabled:c,className:"px-3 py-2 rounded-xl border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-cyan-200 hover:bg-cyan-500/20 disabled:opacity-50",children:"Local Lane"}),e.jsx("button",{"data-testid":"settings-setup-hosted-btn",type:"button",onClick:me,disabled:c,className:"px-3 py-2 rounded-xl border border-emerald-300/30 bg-emerald-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-emerald-200 hover:bg-emerald-500/20 disabled:opacity-50",children:"Hosted Lane"})]}),e.jsx("button",{"data-testid":"settings-import-env-btn",type:"button",onClick:ke,disabled:c,className:"w-full px-3 py-2 rounded-xl border border-white/15 bg-white/5 text-[10px] uppercase tracking-[0.16em] font-bold text-slate-200 hover:bg-white/10 disabled:opacity-50",children:"Import Provider Profiles from Environment"})]})]}),e.jsx(jg,{providerSweep:m,providerSweepRows:pe,providerSweepBusy:b,providerSweepUpdatedAt:g,activeProviderId:P,onRefresh:ce,hostedProxyEnabled:!!n.hostedProxyEnabled,hostedProxyStatus:I,onToggleHostedProxy:Pe}),e.jsx(Ly,{})]}),e.jsxs(hs,{id:"section-security",title:"Security & Trust",accentClass:"text-cyan-300",children:[e.jsxs("section",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-cyan-400 mb-4 font-bold",children:"Security Subsystem"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"flex justify-between items-center p-4 bg-black/30 hover:bg-black/40 transition-colors rounded-2xl border border-white/5 cursor-pointer group",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-slate-200",children:"Safe Defaults"}),e.jsx("div",{className:"text-[10px] text-slate-500",children:"Enable OMEGA-hardened zero-trust guards"})]}),e.jsx("div",{className:`h-5 w-10 rounded-full flex items-center px-1 transition-colors ${n.safeMode!==!1?"bg-cyan-400/20 border border-cyan-400/40":"bg-slate-800 border border-white/5"}`,children:e.jsx("div",{className:`h-3 w-3 rounded-full transition-all ${n.safeMode!==!1?"bg-cyan-400 ml-auto":"bg-slate-500"}`})}),e.jsx("input",{type:"checkbox",className:"hidden",checked:n.safeMode!==!1,onChange:M=>we("safeMode",M.target.checked)})]}),e.jsxs("label",{className:"flex justify-between items-center p-4 bg-black/30 hover:bg-black/40 transition-colors rounded-2xl border border-white/5 cursor-pointer group opacity-60",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-slate-200",children:"P2P Network Tunnel"}),e.jsx("div",{className:"text-[10px] text-slate-500",children:"Enable decentralized swarming (Requires APEX)"})]}),e.jsx("div",{className:`h-5 w-10 rounded-full flex items-center px-1 transition-colors ${n.networkTunnel?"bg-amber-400/20 border border-amber-400/40":"bg-slate-800 border border-white/5"}`,children:e.jsx("div",{className:`h-3 w-3 rounded-full transition-all ${n.networkTunnel?"bg-amber-400 ml-auto":"bg-slate-500"}`})}),e.jsx("input",{type:"checkbox",className:"hidden",checked:!!n.networkTunnel,onChange:M=>we("networkTunnel",M.target.checked)})]}),e.jsxs("label",{className:"flex justify-between items-center p-4 bg-black/30 hover:bg-black/40 transition-colors rounded-2xl border border-white/5 cursor-pointer group",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-slate-200",children:"Hosted Provider Access"}),e.jsx("div",{className:"text-[10px] text-slate-500",children:"Allow network-hosted model providers in this runtime"})]}),e.jsx("div",{className:`h-5 w-10 rounded-full flex items-center px-1 transition-colors ${n.allowRemoteBridge?"bg-emerald-400/20 border border-emerald-400/40":"bg-slate-800 border border-white/5"}`,children:e.jsx("div",{className:`h-3 w-3 rounded-full transition-all ${n.allowRemoteBridge?"bg-emerald-400 ml-auto":"bg-slate-500"}`})}),e.jsx("input",{type:"checkbox",className:"hidden",checked:!!n.allowRemoteBridge,onChange:M=>we("allowRemoteBridge",M.target.checked)})]})]})]}),e.jsxs("section",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-violet-300 mb-4 font-bold",children:"OpenTelemetry Export"}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-3",children:[e.jsxs("div",{className:"text-[11px] text-slate-400 font-mono",children:["Optional local OTLP bridge to ",e.jsx("code",{className:"text-cyan-300",children:"localhost:4317"}),". Disabled by default."]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"settings-otel-toggle-btn",onClick:_e,className:`px-3 py-2 rounded-xl border text-[10px] uppercase tracking-[0.16em] font-bold ${n.otelExportEnabled?"border-violet-300/35 bg-violet-500/10 text-violet-200":"border-white/15 bg-white/5 text-slate-200"}`,children:n.otelExportEnabled?"Disable Export":"Enable Export"}),e.jsx("button",{type:"button","data-testid":"settings-otel-verify-btn",onClick:ne,className:"px-3 py-2 rounded-xl border border-white/15 bg-white/5 text-[10px] uppercase tracking-[0.16em] font-bold text-slate-200 hover:bg-white/10",children:"Verify Collector"}),e.jsxs("span",{className:`text-[10px] font-mono ${C.ok?"text-emerald-300":"text-slate-500"}`,children:[C.ok?"Collector reachable":`Collector ${C.host}:${C.port}`,C.reason?` (${C.reason})`:""]})]})]})]}),e.jsx(ug,{}),e.jsx(Gy,{disabled:!z})]}),e.jsxs(hs,{id:"section-personalization",title:"Personalization",accentClass:"text-violet-300",children:[e.jsx(Xy,{}),e.jsx(zy,{settings:n,onUpdateSetting:we,connectionHealth:p!=null&&p.ok?"online":Gt(P)&&!n.allowRemoteBridge?"offline":"unknown",isThinking:c})]}),e.jsxs(hs,{id:"section-updates",title:"Updates & Licensing",accentClass:"text-amber-300",children:[e.jsx(mg,{licenseMode:n.licenseMode}),e.jsx(pg,{licenseMode:n.licenseMode}),e.jsx(fg,{licenseMode:n.licenseMode}),e.jsx(Sg,{})]}),e.jsxs(hs,{id:"section-support",title:"Support & Advanced",accentClass:"text-slate-400",children:[e.jsx(Sy,{}),e.jsx(Ay,{}),F&&e.jsx(Wy,{}),e.jsx(Yp,{}),e.jsx($g,{}),e.jsxs("section",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-slate-300 mb-4 font-bold",children:"Legal"}),e.jsxs("div",{className:"p-5 bg-black/30 rounded-2xl border border-white/5 space-y-3",children:[e.jsx("div",{className:"text-[11px] text-slate-300 font-mono",children:"Created by The Founder"}),e.jsxs("div",{className:"text-[11px] text-slate-400 font-mono",children:["Third-party attribution is generated at ",e.jsx("code",{className:"text-cyan-300",children:"public/about.html"}),"."]}),e.jsx("button",{type:"button","data-testid":"settings-legal-open-about-btn",onClick:()=>{window.api&&window.api.system&&typeof window.api.system.openExternal=="function"&&window.api.system.openExternal("https://github.com/Z3r0DayZion-install/NeuralShell/blob/master/public/about.html")},className:"px-3 py-2 rounded-xl border border-white/15 bg-white/5 text-[10px] uppercase tracking-[0.16em] font-bold text-slate-200 hover:bg-white/10",children:"Open Attribution Page"})]})]})]})]}),u.text&&e.jsx("div",{"data-testid":"settings-status-text",className:`mt-4 rounded-xl border px-3 py-2 text-[10px] font-mono ${u.tone==="ok"?"border-emerald-400/30 bg-emerald-500/10 text-emerald-200":u.tone==="bad"?"border-rose-400/30 bg-rose-500/10 text-rose-200":"border-white/10 bg-black/30 text-slate-300"}`,children:u.text})]}),e.jsx(yg,{open:j,payload:N,onClose:()=>E(!1)})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[149] bg-black/40 backdrop-blur-[2px] transition-all",onClick:r}),e.jsxs("div",{"data-testid":"settings-drawer",className:"fixed right-0 top-0 bottom-0 max-w-xl w-full z-[150] bg-slate-950 border-l border-cyan-400/20 shadow-[-20px_0_50px_rgba(0,0,0,0.6)] p-8 flex flex-col animate-fade-up",style:{borderImage:"linear-gradient(180deg, rgba(6,182,212,0.3), rgba(139,92,246,0.15), rgba(217,70,239,0.08)) 1"},children:[e.jsxs("div",{className:"flex justify-between items-center mb-8",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight text-slate-100",children:"Configuration"}),e.jsx("button",{"data-testid":"settings-close-btn",onClick:r,className:"h-10 w-10 rounded-full hover:bg-white/5 flex items-center justify-center text-slate-400 hover:text-white transition-colors",children:"✕"})]}),e.jsx("div",{className:"text-sm text-slate-400 font-mono",children:"Loading settings…"})]})]})}function da(t,r=0){const n=Number(t);return Number.isFinite(n)?n:r}function iw(t){return Array.isArray(t)?t:[]}function N0(t){const r=t&&typeof t=="object"?t:{},n=da(r.installs,0),s=da(r.proofRuns,0),a=da(r.vaultWrites,0),o=r.providerSuccess&&typeof r.providerSuccess=="object"?r.providerSuccess:{},c=String(r.tier||"unknown");return{source:String(r.source||r.fileName||"bundle"),tier:c,installs:n,proofRuns:s,vaultWrites:a,providerSuccess:Object.fromEntries(Object.entries(o).map(([u,x])=>[String(u),da(x,0)]))}}function Gd(t){const r=iw(t).map(N0),n={installs:0,proofRuns:0,vaultWrites:0},s={},a={};for(const o of r){n.installs+=o.installs,n.proofRuns+=o.proofRuns,n.vaultWrites+=o.vaultWrites,a[o.tier]=(a[o.tier]||0)+1;for(const[c,l]of Object.entries(o.providerSuccess))s[c]=(s[c]||0)+l}return{bundleCount:r.length,totals:n,providerSuccess:s,tierMix:a,bundles:r}}function lw(t){return new Promise((r,n)=>{const s=new FileReader;s.onerror=()=>n(new Error("Unable to read file.")),s.onload=()=>{try{r(JSON.parse(String(s.result||"{}")))}catch{n(new Error("Invalid JSON bundle."))}},s.readAsText(t)})}function cw(){const[t,r]=i.useState(null),[n,s]=i.useState(()=>Gd([])),[a,o]=i.useState("");i.useEffect(()=>{let l=!0;return(async()=>{try{const u=await window.api.analytics.getDashboard(30);if(!l)return;r(u||null)}catch(u){if(!l)return;o(u&&u.message?u.message:String(u))}})(),()=>{l=!1}},[]);const c=async l=>{const u=l&&l.target&&l.target.files?l.target.files[0]:null;if(u)try{const x=await lw(u),p=N0({...x,fileName:u.name});s(d=>Gd([...d.bundles||[],p])),o("")}catch(x){o(x&&x.message?x.message:String(x))}};return e.jsxs("section",{"data-testid":"operator-dashboard",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Operator Dashboard"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Import local metrics bundles. No cloud backend required."})]}),e.jsxs("label",{className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.14em] font-mono text-cyan-200 cursor-pointer",children:["Import Bundle",e.jsx("input",{"data-testid":"operator-import-bundle-input",type:"file",accept:"application/json,.json,.neuralshell-metrics.json",className:"hidden",onChange:c})]})]}),a&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:a}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Installs"}),e.jsx("div",{className:"text-[14px] text-slate-100 font-bold",children:Number(n.totals.installs||0).toLocaleString()})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Proof Runs"}),e.jsx("div",{className:"text-[14px] text-slate-100 font-bold",children:Number(n.totals.proofRuns||0).toLocaleString()})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Vault Writes"}),e.jsx("div",{className:"text-[14px] text-slate-100 font-bold",children:Number(n.totals.vaultWrites||0).toLocaleString()})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Bundles"}),e.jsx("div",{className:"text-[14px] text-slate-100 font-bold",children:Number(n.bundleCount||0).toLocaleString()})]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold mb-1",children:"Local Runtime Reliability"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-300",children:t?`Events ${t.eventCount||0} · Median ${t.medianLatencyMs||0}ms · Est $${Number(t.estimatedUsd||0).toFixed(2)}`:"Local dashboard unavailable."})]})]})}const dw="neuralshell_onboarding_events_v1";function Cr(t,r=0){const n=Number(t);return Number.isFinite(n)?n:r}function uw(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(dw)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function pw(t=[]){const r=Array.isArray(t)?t:[];let n=0,s=0,a=0,o=0,c=0;for(const l of r){const u=String(l&&l.type?l.type:"").trim(),x=String(l&&l.stepId?l.stepId:"").trim();u==="wizard_opened"&&(n+=1),u==="step_completed"&&x==="provider_sweep"&&(s+=1),u==="step_completed"&&x==="vault_save"&&(a+=1),u==="step_completed"&&x==="run_proof"&&(o+=1),u==="step_completed"&&x==="share_badge"&&(c+=1)}return{started:n,providerSweep:s,vaultSave:a,runProof:o,shareBadge:c}}function S0(t={}){const r=t&&typeof t=="object"?t:{},n=r.funnel&&typeof r.funnel=="object"?r.funnel:{};return{source:String(r.source||r.fileName||"bundle"),installs:Cr(r.installs,0),onboardingStarted:Cr(n.onboardingStarted,0),onboardingCompleted:Cr(n.onboardingCompleted,0),proofRuns:Cr(n.proofRuns,Cr(r.proofRuns,0)),shares:Cr(n.shares,0),upgrades:Cr(n.upgrades,0)}}function mw(t=[]){const r=(Array.isArray(t)?t:[]).map(S0),n={installs:0,onboardingStarted:0,onboardingCompleted:0,proofRuns:0,shares:0,upgrades:0};for(const s of r)n.installs+=s.installs,n.onboardingStarted+=s.onboardingStarted,n.onboardingCompleted+=s.onboardingCompleted,n.proofRuns+=s.proofRuns,n.shares+=s.shares,n.upgrades+=s.upgrades;return{bundles:r,totals:n}}function xw(t,r){return r?Math.round(Number(t||0)/Number(r||1)*100):0}function fw(t){return new Promise((r,n)=>{const s=new FileReader;s.onerror=()=>n(new Error("Unable to read conversion bundle.")),s.onload=()=>{try{const a=JSON.parse(String(s.result||"{}"));r(a)}catch{n(new Error("Invalid conversion bundle JSON."))}},s.readAsText(t)})}function bw(){const[t]=i.useState(()=>uw()),[r,n]=i.useState([]),[s,a]=i.useState(""),o=i.useMemo(()=>pw(t),[t]),c=i.useMemo(()=>mw(r),[r]),l=i.useMemo(()=>{const p=c.totals||{};return{installs:Number(p.installs||0),onboardingStarted:Math.max(Number(p.onboardingStarted||0),Number(o.started||0)),onboardingCompleted:Math.max(Number(p.onboardingCompleted||0),Number(o.shareBadge||0)),proofRuns:Math.max(Number(p.proofRuns||0),Number(o.runProof||0)),shares:Math.max(Number(p.shares||0),Number(o.shareBadge||0)),upgrades:Number(p.upgrades||0)}},[c.totals,o.runProof,o.shareBadge,o.started]),u=[{id:"installs",label:"Installs",value:l.installs},{id:"onboardingStarted",label:"Onboarding Started",value:l.onboardingStarted},{id:"proofRuns",label:"Proof Runs",value:l.proofRuns},{id:"shares",label:"Shares",value:l.shares},{id:"upgrades",label:"Upgrades",value:l.upgrades}],x=async p=>{const d=p&&p.target&&p.target.files?p.target.files[0]:null;if(d)try{const m=await fw(d),b=(Array.isArray(m)?m:Array.isArray(m.bundles)?m.bundles:[m]).map(h=>S0({...h,fileName:d.name}));n(h=>[...h,...b]),a("")}catch(m){a(m&&m.message?m.message:String(m))}};return e.jsxs("section",{"data-testid":"funnel-dashboard",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Conversion Funnel"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Local funnel metrics + importable bundle overlays."})]}),e.jsxs("label",{className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.14em] font-mono text-cyan-200 cursor-pointer",children:["Import Funnel JSON",e.jsx("input",{"data-testid":"funnel-import-input",type:"file",accept:"application/json,.json,.neuralshell-metrics.json",className:"hidden",onChange:x})]})]}),s&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:s}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-5 gap-2",children:u.map((p,d)=>{const m=d===0?p.value:u[d-1].value;return e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:p.label}),e.jsx("div",{className:"text-[14px] text-slate-100 font-bold",children:Number(p.value||0).toLocaleString()}),d>0&&e.jsxs("div",{className:"text-[9px] font-mono text-cyan-300",children:[xw(p.value,m),"%"]})]},p.id)})}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-400",children:["Local onboarding events: started ",o.started,", provider sweep ",o.providerSweep,", vault save ",o.vaultSave,", proof ",o.runProof,", share ",o.shareBadge,"."]})]})}function ct(t,r=0){const n=Number(t);return Number.isFinite(n)?n:r}function hw(t){const r=String(t||"").split(/\r?\n/).filter(Boolean);if(!r.length)return[];const n=r[0].split(",").map(s=>s.trim());return r.slice(1).map(s=>{const a=s.split(","),o={};return n.forEach((c,l)=>{o[c]=String(a[l]||"").trim()}),o})}function ua(t={},r="snapshot"){const n=t&&typeof t=="object"?t:{};return{source:r,period:String(n.period||n.date||new Date().toISOString().slice(0,10)),mrr:ct(n.mrr,0),installs:ct(n.installs,0),activations:ct(n.activations,0),upgrades:ct(n.upgrades,0),agentSales:ct(n.agentSales,0),partnerRevenue:ct(n.partnerRevenue,0)}}function gw(t,r=""){const n=String(r||"import");if(n.toLowerCase().endsWith(".csv"))return hw(t).map(a=>ua(a,n));const s=JSON.parse(String(t||"{}"));return Array.isArray(s)?s.map(a=>ua(a,n)):Array.isArray(s.snapshots)?s.snapshots.map(a=>ua(a,n)):[ua(s,n)]}function yw(t=[]){const r=Array.isArray(t)?t:[],n={mrr:0,installs:0,activations:0,upgrades:0,agentSales:0,partnerRevenue:0};for(const o of r)n.mrr+=ct(o.mrr,0),n.installs+=ct(o.installs,0),n.activations+=ct(o.activations,0),n.upgrades+=ct(o.upgrades,0),n.agentSales+=ct(o.agentSales,0),n.partnerRevenue+=ct(o.partnerRevenue,0);const s=r.slice(-3),a=s.length?s.reduce((o,c)=>o+ct(c.mrr,0),0)/s.length:0;return{totals:n,projectionYearly:Math.round(a*12)}}function ww(t){return new Promise((r,n)=>{const s=new FileReader;s.onerror=()=>n(new Error("Unable to read revenue file.")),s.onload=()=>r(String(s.result||"")),s.readAsText(t)})}function vw(){const[t,r]=i.useState([]),[n,s]=i.useState(""),a=i.useMemo(()=>yw(t),[t]),o=async c=>{const l=c&&c.target&&c.target.files?c.target.files[0]:null;if(l)try{const u=await ww(l),x=gw(u,l.name);r(p=>[...p,...x]),s("")}catch(u){s(u&&u.message?u.message:String(u))}};return e.jsxs("section",{"data-testid":"revenue-console",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-emerald-300 font-bold",children:"Revenue Console"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Founder-only projections from imported CSV/JSON snapshots."})]}),e.jsxs("label",{className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.14em] font-mono text-emerald-200 cursor-pointer",children:["Import Revenue",e.jsx("input",{"data-testid":"revenue-import-input",type:"file",accept:".csv,application/json,.json",className:"hidden",onChange:o})]})]}),n&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:n}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"MRR Total"}),e.jsxs("div",{className:"text-[14px] text-slate-100 font-bold",children:["$",Number(a.totals.mrr||0).toLocaleString()]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Upgrades"}),e.jsx("div",{className:"text-[14px] text-slate-100 font-bold",children:Number(a.totals.upgrades||0).toLocaleString()})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Agent Sales"}),e.jsxs("div",{className:"text-[14px] text-slate-100 font-bold",children:["$",Number(a.totals.agentSales||0).toLocaleString()]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Proj. ARR"}),e.jsxs("div",{className:"text-[14px] text-emerald-200 font-bold",children:["$",Number(a.projectionYearly||0).toLocaleString()]})]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2 max-h-44 overflow-auto",children:[t.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No revenue snapshots imported yet."}),t.slice(-8).map((c,l)=>e.jsxs("div",{className:"text-[10px] font-mono text-slate-300 flex justify-between gap-2",children:[e.jsx("span",{children:c.period}),e.jsxs("span",{children:["MRR $",Number(c.mrr||0).toLocaleString()]}),e.jsxs("span",{children:["Upgrades ",Number(c.upgrades||0).toLocaleString()]})]},`${c.source}-${c.period}-${l}`))]})]})}function jw(t=[]){const r=Array.isArray(t)?t.slice(-24):[],n=Math.max(1,...r.map(s=>Number(s.latencyMs||0)));return r.map((s,a)=>({x:a,h:Math.max(2,Math.round(Number(s.latencyMs||0)/n*52)),latencyMs:Number(s.latencyMs||0)}))}function kw({onClose:t,capabilities:r=[]}){const[n,s]=i.useState(null),[a,o]=i.useState(!0),[c,l]=i.useState(!1),[u,x]=i.useState(""),[p,d]=i.useState(!1),m=i.useCallback(async()=>{try{const A=await window.api.analytics.getDashboard(7);s(A||null),x("")}catch(A){x(A&&A.message?A.message:String(A))}finally{o(!1)}},[]);i.useEffect(()=>{m();const A=window.setInterval(()=>{m()},1e4);return()=>{window.clearInterval(A)}},[m]),i.useEffect(()=>{if(!window.matchMedia)return;const A=window.matchMedia("(prefers-reduced-motion: reduce)"),C=()=>d(!!A.matches);return C(),typeof A.addEventListener=="function"?(A.addEventListener("change",C),()=>A.removeEventListener("change",C)):(A.addListener(C),()=>A.removeListener(C))},[]);const f=async A=>{l(!0);try{await window.api.analytics.setEnabled(!!A),await m()}catch(C){x(C&&C.message?C.message:String(C))}finally{l(!1)}},b=async()=>{l(!0);try{await window.api.analytics.clear(),await m()}catch(A){x(A&&A.message?A.message:String(A))}finally{l(!1)}},h=jw(n&&n.latencySeries?n.latencySeries:[]),g=Array.isArray(r)&&(r.includes("operator_dashboard")||r.includes("release_health_console")),y=Array.isArray(r)&&r.includes("funnel_dashboard"),I=Array.isArray(r)&&r.includes("revenue_console");return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[70] bg-black/50 backdrop-blur-[2px]",onClick:t}),e.jsxs("aside",{className:`fixed right-0 top-0 bottom-0 z-[80] w-full max-w-xl border-l border-cyan-400/20 bg-slate-950 p-6 overflow-y-auto ${p?"":"animate-in slide-in-from-right duration-300"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.2em] text-cyan-400 font-bold",children:"Analytics Dashboard"}),e.jsx("div",{className:"text-[11px] text-slate-400 font-mono",children:"Local-only usage telemetry (7 day window)."})]}),e.jsx("button",{onClick:t,className:"h-9 w-9 rounded-full border border-white/10 text-slate-300 hover:text-white hover:bg-white/10",children:"✕"})]}),a&&e.jsx("div",{className:"text-[11px] font-mono text-slate-400",children:"Loading analytics..."}),u&&e.jsx("div",{className:"rounded-xl border border-rose-400/30 bg-rose-500/10 px-3 py-2 text-[10px] font-mono text-rose-200 mb-3",children:u}),!a&&n&&e.jsxs("div",{className:"space-y-4",children:[g&&e.jsx(cw,{}),y&&e.jsx(bw,{}),I&&e.jsx(vw,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Events"}),e.jsx("div",{className:"text-lg font-bold text-slate-100",children:Number(n.eventCount||0).toLocaleString()})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Tokens"}),e.jsx("div",{className:"text-lg font-bold text-slate-100",children:Number(n.totalTokens||0).toLocaleString()})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Median Latency"}),e.jsxs("div",{className:"text-lg font-bold text-slate-100",children:[Number(n.medianLatencyMs||0)," ms"]})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Estimated Spend"}),e.jsxs("div",{className:"text-lg font-bold text-slate-100",children:["$",Number(n.estimatedUsd||0).toFixed(2)]})]})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold mb-2",children:"Latency Trend"}),e.jsxs("div",{className:"h-16 flex items-end gap-1",children:[h.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No samples yet."}),h.map((A,C)=>e.jsx("div",{title:`${A.latencyMs}ms`,className:"w-2 rounded-sm bg-cyan-400/70",style:{height:`${A.h}px`}},`bar-${C}`))]})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-500 font-bold mb-2",children:"Model Mix"}),e.jsxs("div",{className:"space-y-1",children:[(n.modelMix||[]).slice(0,8).map(A=>e.jsxs("div",{className:"text-[10px] font-mono text-slate-300 flex justify-between gap-2",children:[e.jsx("span",{className:"truncate",children:A.model}),e.jsx("span",{children:Number(A.count||0).toLocaleString()})]},A.model)),(!n.modelMix||n.modelMix.length===0)&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No model usage yet."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"analytics-enable-btn",disabled:c,onClick:()=>f(!n.enabled),className:`px-3 py-2 rounded-xl border text-[10px] uppercase tracking-[0.16em] font-bold ${n.enabled?"border-emerald-300/30 bg-emerald-500/10 text-emerald-200":"border-slate-400/30 bg-slate-500/10 text-slate-200"} disabled:opacity-60`,children:n.enabled?"Disable Analytics":"Enable Analytics"}),e.jsx("button",{type:"button","data-testid":"analytics-clear-btn",disabled:c,onClick:b,className:"px-3 py-2 rounded-xl border border-rose-300/30 bg-rose-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-rose-200 disabled:opacity-60",children:"Clear Data"}),e.jsx("button",{type:"button",onClick:m,disabled:c,className:"px-3 py-2 rounded-xl border border-white/10 bg-white/5 text-[10px] uppercase tracking-[0.16em] font-bold text-slate-200 disabled:opacity-60",children:"Refresh"})]})]})]})]})}const Fa=[{id:"getting_started",title:"Getting Started",body:`# NeuralShell Workpad ## Today - [ ] Connect LLM bridge @@ -173,14 +173,14 @@ You are a senior engineer. ## Task ## Output format -`}];function ge(t,r="info"){if(typeof window>"u")return;const n=String(t||"").trim();n&&window.dispatchEvent(new CustomEvent("neuralshell:toast",{detail:{message:n,tone:String(r||"info")}}))}function Nw(t){if(!t)return"";try{const r=new Date(t).getTime(),n=Date.now()-r;return Number.isFinite(n)?n<6e4?"just now":n<36e5?`${Math.floor(n/6e4)}m ago`:n<864e5?`${Math.floor(n/36e5)}h ago`:n<6048e5?`${Math.floor(n/864e5)}d ago`:new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric"}):""}catch{return""}}function n2(t){if(!t)return"";try{return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return String(t)}}function Sw(t){if(!t)return"Unknown";try{return new Date(t).toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"})}catch{return"Unknown"}}function C0(t){if(!t)return null;const r=new Date;r.setHours(0,0,0,0);const n=new Date(`${t}T00:00:00`);return Number.isNaN(n.getTime())?null:Math.round((n-r)/864e5)}function _0(t,r=!1){if(r||!t)return"none";const n=C0(t);return n===null?"none":n<0?"overdue":n===0?"today":n<=3?"soon":"normal"}function Cw(t,r=!1){const n=_0(t,r);if(n==="none")return"";const s=C0(t);return n==="overdue"?`${Math.abs(s)}d overdue`:n==="today"?"Due today":n==="soon"?`Due in ${s}d`:t}function _w(t){return t==="overdue"?"text-rose-300 border-rose-400/30 bg-rose-500/10":t==="today"?"text-amber-200 border-amber-400/30 bg-amber-500/10":t==="soon"?"text-orange-200 border-orange-400/25 bg-orange-500/10":"text-slate-400 border-white/10 bg-white/[0.03]"}function s2(t){return t==="high"?{label:"High",className:"text-rose-200 border-rose-400/30 bg-rose-500/10"}:t==="low"?{label:"Low",className:"text-slate-400 border-white/10 bg-white/[0.03]"}:{label:"Normal",className:"text-amber-200 border-amber-400/25 bg-amber-500/10"}}function a2(t){let r=String(t||"").trim();const n=[];let s="normal",a="";const o=r.match(/#[\w-]+/g);o&&(o.forEach(u=>n.push(u.slice(1).toLowerCase())),r=r.replace(/#[\w-]+/g," ").replace(/\s+/g," ").trim());const l=r.match(/^!(high|normal|low)\b/i);l&&(s=l[1].toLowerCase(),r=r.slice(l[0].length).trim());const c=r.match(/^due:(\d{4}-\d{2}-\d{2})\b/i);return c&&(a=c[1],r=r.slice(c[0].length).trim()),{title:r.trim(),tags:Array.from(new Set(n)).slice(0,8),priority:s,dueDate:a}}function o2(t){const r=String(t||"").trim();return r?r.split(/\s+/).filter(Boolean).length:0}function i2(t){const r=new Map;return(Array.isArray(t)?t:[]).forEach(n=>{const s=Sw(n.at);r.has(s)||r.set(s,[]),r.get(s).push(n)}),Array.from(r.entries()).map(([n,s])=>({day:n,rows:s}))}const A0="neuralshell_workpad_width_v1",Aw=380,Ew=720,Di=520;function l2(){if(typeof window>"u"||!window.localStorage)return Di;try{const t=Number(window.localStorage.getItem(A0));return Number.isFinite(t)?Math.max(Aw,Math.min(Ew,t)):Di}catch{return Di}}function c2(t){if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(A0,String(Math.round(t)))}catch{}}const pa=[{id:"provider_sweep",title:"Provider Sweep",description:"Open settings and run provider health sweep."},{id:"vault_save",title:"Save Vault",description:"Store a demo secret in Vault+."},{id:"run_proof",title:"Run 90s Proof",description:"Execute /proof from the command lane."},{id:"share_badge",title:"Share Badge",description:"Open proof badge URL and confirm outbound share path."}],E0="neuralshell_onboarding_progress_v1",Jd="neuralshell_onboarding_events_v1";function Iw(){if(typeof window>"u"||!window.localStorage)return{};try{return JSON.parse(window.localStorage.getItem(E0)||"{}")||{}}catch{return{}}}function Pw(t){typeof window>"u"||!window.localStorage||window.localStorage.setItem(E0,JSON.stringify(t||{}))}function ma(t,r=""){if(!(typeof window>"u"||!window.localStorage))try{const n=JSON.parse(window.localStorage.getItem(Jd)||"[]"),s=Array.isArray(n)?n:[];s.push({at:new Date().toISOString(),type:String(t||""),stepId:String(r||"")}),window.localStorage.setItem(Jd,JSON.stringify(s.slice(-200)))}catch{}}function Rw({open:t,onClose:r,onOpenSettings:n,onRunCommand:s}){const[a,o]=i.useState(()=>Iw()),[l,c]=i.useState("");if(i.useEffect(()=>{t&&ma("wizard_opened")},[t]),!t)return null;const u=m=>{const f={...a,[m]:!0};o(f),Pw(f),ma("step_completed",m)},x=async m=>{const f=String(m&&m.id?m.id:"");if(f){c(f),ma("step_started",f);try{if(f==="provider_sweep"){typeof n=="function"&&n(),u(f);return}if(f==="vault_save"){await window.api.vault.setSecret("onboarding","demo_key",`created:${new Date().toISOString()}`),u(f);return}if(f==="run_proof"){typeof s=="function"&&s("/proof"),u(f);return}f==="share_badge"&&(await window.api.system.openExternal("https://raw.githubusercontent.com/Z3r0DayZion-install/NeuralShell/badges/proof_badge.svg"),u(f))}catch{ma("step_failed",f)}finally{c("")}}},p=pa.filter(m=>!!a[m.id]).length,d=p>=pa.length;return e.jsx("div",{className:"fixed inset-0 z-[140] bg-black/65 backdrop-blur-sm flex items-center justify-center p-5",children:e.jsxs("div",{className:"w-full max-w-3xl rounded-2xl border border-cyan-300/20 bg-slate-950 p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"First-Run Onboarding"}),e.jsxs("div",{className:"text-[11px] text-slate-400 font-mono",children:[p,"/",pa.length," complete"]})]}),e.jsx("button",{type:"button","data-testid":"onboarding-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsx("div",{className:"space-y-3",children:pa.map((m,f)=>{const b=String(m.id||""),h=!!a[b];return e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 px-4 py-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-200 font-bold",children:[f+1,". ",m.title]}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:m.description})]}),e.jsx("button",{type:"button","data-testid":`onboarding-step-${b}`,disabled:h||l===b,onClick:()=>x(m),className:`px-3 py-1.5 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${h?"border-emerald-300/30 bg-emerald-500/10 text-emerald-200":"border-cyan-300/30 bg-cyan-500/10 text-cyan-200 hover:bg-cyan-500/20"} disabled:opacity-60`,children:h?"Done":l===b?"Running":"Run"})]},b)})}),e.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Funnel events are logged locally for drop-off tracking."}),e.jsx("button",{type:"button","data-testid":"onboarding-finish-btn",onClick:r,className:`px-3 py-2 rounded border text-[10px] uppercase tracking-[0.16em] font-bold ${d?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":"border-white/10 bg-white/5 text-slate-300"}`,children:d?"Complete":"Close"})]})]})})}const xa=[{id:"bug_report",label:"Bug Report",template:"bug_report.yml"},{id:"proof_flow",label:"Proof Flow Regression",template:"proof_flow.yml"}];function $i(t){return encodeURIComponent(String(t||""))}function Ow(t){return["### Source",`- tier: ${t.tier||"unknown"}`,`- version: ${t.version||"unknown"}`,`- workflow: ${t.workflowId||"unknown"}`,"","### Support Bundle",`- path: ${t.supportBundlePath||"n/a"}`,`- sha256: ${t.supportBundleHash||"n/a"}`,"","### Notes",`${t.notes||""}`].join(` -`)}function Tw({open:t,onClose:r,metadata:n}){const[s,a]=i.useState(xa[0].id),[o,l]=i.useState("");if(!t)return null;const c=xa.find(m=>m.id===s)||xa[0],u={...n||{},notes:o},x=Ow(u),p=`https://github.com/Z3r0DayZion-install/NeuralShell/issues/new?template=${$i(c.template)}&title=${$i(`${c.label}: `)}&body=${$i(x)}`,d=async()=>{await window.api.system.openExternal(p),r()};return e.jsx("div",{className:"fixed inset-0 z-[150] bg-black/70 backdrop-blur-sm flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-2xl rounded-2xl border border-cyan-300/20 bg-slate-950 p-5 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Issue Assist"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Prepare sanitized issue markdown and open GitHub issue page."})]}),e.jsx("button",{type:"button","data-testid":"issue-assist-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsx("div",{className:"flex items-center gap-2",children:xa.map(m=>e.jsx("button",{type:"button","data-testid":`issue-assist-type-${m.id}`,onClick:()=>a(m.id),className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${s===m.id?"border-cyan-300/30 bg-cyan-500/10 text-cyan-200":"border-white/10 bg-white/5 text-slate-300"}`,children:m.label},m.id))}),e.jsx("textarea",{"data-testid":"issue-assist-notes",value:o,onChange:m=>l(m.target.value),placeholder:"Add reproduction notes...",className:"w-full min-h-24 bg-black/40 border border-white/10 rounded-xl p-3 text-[12px] text-slate-100 font-mono"}),e.jsx("pre",{className:"rounded-xl border border-white/10 bg-black/40 p-3 text-[10px] text-slate-300 font-mono whitespace-pre-wrap max-h-48 overflow-auto",children:x}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{type:"button","data-testid":"issue-assist-copy-btn",onClick:()=>navigator.clipboard.writeText(x),className:"px-3 py-2 rounded border border-white/10 bg-white/5 text-[10px] uppercase tracking-[0.14em] font-mono text-slate-200",children:"Copy"}),e.jsx("button",{type:"button","data-testid":"issue-assist-open-btn",onClick:d,className:"px-3 py-2 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.14em] font-mono text-cyan-100",children:"Open Issue"})]})]})})}function Mw({workflowId:t,tierLabel:r,beforeMinutes:n,afterMinutes:s,notes:a}){const o=Number(n)||0,l=Number(s)||0,c=Math.max(0,o-l);return{exportedAt:new Date().toISOString(),anonymized:!0,workflowId:String(t||""),tier:String(r||"unknown"),metrics:{beforeMinutes:n,afterMinutes:s,reclaimedMinutes:c},notes:String(a||"").trim(),screenshotChecklist:["proof_output","roi_output","lock_flow","unlock_restored"]}}function Dw(t,r){const n=new Blob([`${JSON.stringify(r,null,2)} -`],{type:"application/json"}),s=URL.createObjectURL(n),a=document.createElement("a");a.href=s,a.download=t,document.body.appendChild(a),a.click(),a.remove(),URL.revokeObjectURL(s)}function $w({open:t,onClose:r,workflowId:n,tierLabel:s}){const[a,o]=i.useState("45"),[l,c]=i.useState("10"),[u,x]=i.useState(""),[p,d]=i.useState("");if(!t)return null;const m=()=>{const f=Mw({workflowId:n,tierLabel:s,beforeMinutes:a,afterMinutes:l,notes:u});Dw(`neuralshell_case_study_${Date.now()}.json`,f),d("Anonymized success capture exported.")};return e.jsx("div",{className:"fixed inset-0 z-[145] bg-black/70 backdrop-blur-sm flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-2xl rounded-2xl border border-emerald-300/20 bg-slate-950 p-5 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-emerald-300 font-bold",children:"Case Study Capture"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Export anonymized before/after metrics and screenshot checklist."})]}),e.jsx("button",{type:"button","data-testid":"success-capture-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("label",{className:"text-[10px] font-mono text-slate-300",children:["Before (minutes/day)",e.jsx("input",{"data-testid":"success-capture-before",value:a,onChange:f=>o(f.target.value),className:"mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-[12px] text-slate-100"})]}),e.jsxs("label",{className:"text-[10px] font-mono text-slate-300",children:["After (minutes/day)",e.jsx("input",{"data-testid":"success-capture-after",value:l,onChange:f=>c(f.target.value),className:"mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-[12px] text-slate-100"})]})]}),e.jsxs("label",{className:"text-[10px] font-mono text-slate-300 block",children:["Notes (optional)",e.jsx("textarea",{"data-testid":"success-capture-notes",value:u,onChange:f=>x(f.target.value),placeholder:"Short anonymized context for marketing review...",className:"mt-1 w-full min-h-20 rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-[12px] text-slate-100"})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-400",children:["Workflow: ",String(n||"unknown")," · Tier: ",String(s||"unknown")]}),e.jsx("div",{className:"flex justify-end gap-2",children:e.jsx("button",{type:"button","data-testid":"success-capture-export-btn",onClick:m,className:"px-3 py-2 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] uppercase tracking-[0.14em] font-mono text-emerald-100",children:"Export Capture Bundle"})}),p&&e.jsx("div",{className:"text-[10px] font-mono text-emerald-200",children:p})]})})}const I0="neuralshell_sales_console_v1",P0=["Lead","Discovery","Demo Scheduled","Pilot Active","Security Review","Procurement","Deployment","Renewal","Closed Won","Closed Lost"];function Al(t={}){const r=t&&typeof t=="object"?t:{};return{id:String(r.id||r.leadId||`deal-${Date.now()}-${Math.random().toString(36).slice(2,7)}`),accountName:String(r.accountName||r.customer||r.company||"Unnamed Account").trim(),owner:String(r.owner||r.sdr||r.ae||"Founder").trim(),stage:P0.includes(String(r.stage||"").trim())?String(r.stage||"").trim():"Lead",dealSizeUsd:he(r.dealSizeUsd||r.dealSize||r.acv||r.value,0),nextAction:String(r.nextAction||r.action||"Follow up").trim(),nextActionDate:nc(r.nextActionDate||r.nextStepDate||r.followUpDate,""),demoStatus:String(r.demoStatus||r.demo||"pending").trim().toLowerCase(),proofStatus:String(r.proofStatus||r.proof||"pending").trim().toLowerCase(),pilotStatus:String(r.pilotStatus||r.pilot||"not_started").trim().toLowerCase(),securityReview:String(r.securityReview||r.security||"not_started").trim().toLowerCase(),procurementStatus:String(r.procurementStatus||r.procurement||"not_started").trim().toLowerCase(),renewalState:String(r.renewalState||r.renewal||"n/a").trim().toLowerCase(),notes:String(r.notes||"").trim(),updatedAt:new Date().toISOString()}}function Lw(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(I0)||"[]");return Array.isArray(t)?t.map(r=>Al(r)):[]}catch{return[]}}function Bw(){const[t,r]=i.useState(()=>Lw()),[n,s]=i.useState("");i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(I0,JSON.stringify(t))},[t]);const a=i.useMemo(()=>t.reduce((d,m)=>d+he(m.dealSizeUsd,0),0),[t]),o=i.useMemo(()=>t.filter(d=>d.stage==="Pilot Active"||d.pilotStatus==="active").length,[t]),l=i.useMemo(()=>t.filter(d=>d.stage==="Security Review"||d.securityReview==="blocked").length,[t]),c=i.useMemo(()=>t.filter(d=>d.stage==="Procurement"||d.procurementStatus==="blocked").length,[t]),u=async d=>{const m=d&&d.target&&d.target.files?d.target.files[0]:null;if(m)try{const f=await pt(m),h=Ds(f,m.name).map(g=>Al(g));r(g=>{const y=new Map(g.map(P=>[P.id,P]));return h.forEach(P=>y.set(P.id,P)),Array.from(y.values())}),s("")}catch(f){s(f&&f.message?f.message:String(f))}},x=(d,m)=>{r(f=>f.map(b=>b.id===d?{...b,...m,updatedAt:new Date().toISOString()}:b))},p=()=>{r(d=>[Al({accountName:`Net-New_${d.length+1}`,owner:"Founder",stage:"Lead",nextAction:"Discovery call"}),...d])};return e.jsxs("section",{"data-testid":"sales-console",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Enterprise Sales Console"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Local pipeline tracking for demos, pilots, review gates, deployment, and renewals."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"sales-console-add-deal-btn",onClick:p,className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"+ Deal"}),e.jsxs("label",{className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.12em] font-mono text-slate-200 cursor-pointer",children:["Import CSV/JSON",e.jsx("input",{type:"file",accept:".csv,.json,application/json",className:"hidden","data-testid":"sales-console-import-input",onChange:u})]}),e.jsx("button",{type:"button","data-testid":"sales-console-export-btn",onClick:()=>{je(`neuralshell_sales_pipeline_${Date.now()}.json`,{exportedAt:new Date().toISOString(),totals:{dealCount:t.length,totalPipeline:a},deals:t})},className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Export"})]})]}),n&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:n}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Deals"}),e.jsx("div",{className:"text-[14px] font-bold text-slate-100",children:t.length})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Pipeline"}),e.jsxs("div",{className:"text-[14px] font-bold text-cyan-100",children:["$",a.toLocaleString()]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Active Pilots"}),e.jsx("div",{className:"text-[14px] font-bold text-emerald-100",children:o})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Blocked"}),e.jsx("div",{className:"text-[14px] font-bold text-amber-100",children:l+c})]})]}),e.jsx("div",{className:"rounded-lg border border-white/10 bg-black/30 overflow-auto",children:e.jsxs("table",{className:"min-w-full text-[10px] font-mono",children:[e.jsx("thead",{className:"bg-white/[0.04] text-slate-400 uppercase tracking-[0.1em]",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-2 py-2",children:"Account"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Stage"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Deal"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Next Action"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Demo"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Proof"})]})}),e.jsxs("tbody",{children:[t.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-3 py-3 text-slate-500",colSpan:6,children:"No deals imported yet."})}),t.map(d=>e.jsxs("tr",{className:"border-t border-white/5",children:[e.jsx("td",{className:"px-2 py-2 text-slate-200",children:e.jsx("input",{value:d.accountName,onChange:m=>x(d.id,{accountName:m.target.value}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1"})}),e.jsx("td",{className:"px-2 py-2",children:e.jsx("select",{value:d.stage,onChange:m=>x(d.id,{stage:m.target.value}),className:"w-full bg-slate-900 border border-white/10 rounded px-1.5 py-1 text-slate-200",children:P0.map(m=>e.jsx("option",{value:m,children:m},m))})}),e.jsx("td",{className:"px-2 py-2 text-slate-200",children:e.jsx("input",{type:"number",value:d.dealSizeUsd,onChange:m=>x(d.id,{dealSizeUsd:he(m.target.value,0)}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1"})}),e.jsxs("td",{className:"px-2 py-2 text-slate-200",children:[e.jsx("input",{value:d.nextAction,onChange:m=>x(d.id,{nextAction:m.target.value}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1 mb-1"}),e.jsx("input",{type:"date",value:d.nextActionDate,onChange:m=>x(d.id,{nextActionDate:m.target.value}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1"})]}),e.jsx("td",{className:"px-2 py-2",children:e.jsxs("select",{value:d.demoStatus,onChange:m=>x(d.id,{demoStatus:m.target.value}),className:"w-full bg-slate-900 border border-white/10 rounded px-1.5 py-1 text-slate-200",children:[e.jsx("option",{value:"pending",children:"pending"}),e.jsx("option",{value:"scheduled",children:"scheduled"}),e.jsx("option",{value:"completed",children:"completed"}),e.jsx("option",{value:"blocked",children:"blocked"})]})}),e.jsx("td",{className:"px-2 py-2",children:e.jsxs("select",{value:d.proofStatus,onChange:m=>x(d.id,{proofStatus:m.target.value}),className:"w-full bg-slate-900 border border-white/10 rounded px-1.5 py-1 text-slate-200",children:[e.jsx("option",{value:"pending",children:"pending"}),e.jsx("option",{value:"in_progress",children:"in_progress"}),e.jsx("option",{value:"completed",children:"completed"}),e.jsx("option",{value:"blocked",children:"blocked"})]})})]},d.id))]})]})})]})}function Fw(){const[t,r]=i.useState("Acme Security Group"),[n,s]=i.useState("critical-infrastructure"),[a,o]=i.useState("secure release verification"),[l,c]=i.useState("assets/pilot_kit/customer_logo.png"),u=i.useMemo(()=>["node scripts/gen_pilot_pack.cjs",`--customer "${t}"`,`--industry "${n}"`,`--use-case "${a}"`,`--logo "${l}"`].join(" "),[t,n,l,a]),x=i.useMemo(()=>({customerName:t,industry:n,useCase:a,logoPath:l,generatedAt:new Date().toISOString(),recommendedCommand:u}),[u,t,n,l,a]);return e.jsxs("section",{"data-testid":"pilot-kit-console",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Pilot Program Kit"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Generate ready-to-send pilot bundles tailored by customer, logo, industry, and use case."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"pilot-kit-export-json-btn",onClick:()=>je(`neuralshell_pilot_pack_request_${Date.now()}.json`,x),className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Export Request"}),e.jsx("button",{type:"button","data-testid":"pilot-kit-export-command-btn",onClick:()=>$s(`neuralshell_pilot_pack_command_${Date.now()}.txt`,`${u} -`),className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"Export Command"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:[e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:["Customer Name",e.jsx("input",{value:t,onChange:p=>r(p.target.value),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]}),e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:["Industry",e.jsx("input",{value:n,onChange:p=>s(p.target.value),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]}),e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300 md:col-span-2",children:["Use Case",e.jsx("input",{value:a,onChange:p=>o(p.target.value),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]}),e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300 md:col-span-2",children:["Logo Path",e.jsx("input",{value:l,onChange:p=>c(p.target.value),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500 mb-1",children:"Generator Command"}),e.jsx("code",{className:"text-[10px] font-mono text-cyan-100 break-all",children:u})]})]})}const Uw=[{publisherId:"demo-neuralshell-labs",displayName:"ProofForge Labs Demo Publisher",fingerprint:"sha256:78b7d2a0650f9b1c022f22319e4ff326dae93e962735936d898675c4e10a21c0"}],Li={publishers:Uw},zw="neuralshell_branding_profile_v1",Hw="neuralshell-default",Ww="ProofForge Default Branding",Kw={productName:"ProofForge",logoText:"ProofForge",accentColor:"#22d3ee",supportUrl:"https://github.com/Z3r0DayZion-install/NeuralShell/issues",docsUrl:"https://github.com/Z3r0DayZion-install/NeuralShell/tree/main/docs"},Vw={allowRemoteBridge:!1,offlineOnly:!1,updateRing:"stable"},Ia={schema:zw,profileId:Hw,displayName:Ww,branding:Kw,policyDefaults:Vw};function El(t){if(Array.isArray(t))return t.map(r=>El(r));if(t&&typeof t=="object"){const r={};return Object.keys(t).sort().forEach(n=>{r[n]=El(t[n])}),r}return t}function pr(t){return JSON.stringify(El(t))}function sc(t){const r=new Uint8Array(t);let n="";for(let s=0;s{if(n[s]!==2)throw new Error("Invalid DER integer marker.");s+=1;let p=n[s];if(s+=1,p&128){const f=p&127;p=0;for(let b=0;bo)throw new Error("DER signature length mismatch.");const x=new Uint8Array(r*2);return x.set(c.slice(-r),r-Math.min(r,c.length)),x.set(u.slice(-r),r*2-Math.min(r,u.length)),x.buffer}function R0(t,r){const n=String(r||"").match(/.{1,64}/g)||[];return`-----BEGIN ${t}----- +`}];function ge(t,r="info"){if(typeof window>"u")return;const n=String(t||"").trim();n&&window.dispatchEvent(new CustomEvent("neuralshell:toast",{detail:{message:n,tone:String(r||"info")}}))}function Nw(t){if(!t)return"";try{const r=new Date(t).getTime(),n=Date.now()-r;return Number.isFinite(n)?n<6e4?"just now":n<36e5?`${Math.floor(n/6e4)}m ago`:n<864e5?`${Math.floor(n/36e5)}h ago`:n<6048e5?`${Math.floor(n/864e5)}d ago`:new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric"}):""}catch{return""}}function n2(t){if(!t)return"";try{return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return String(t)}}function Sw(t){if(!t)return"Unknown";try{return new Date(t).toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"})}catch{return"Unknown"}}function C0(t){if(!t)return null;const r=new Date;r.setHours(0,0,0,0);const n=new Date(`${t}T00:00:00`);return Number.isNaN(n.getTime())?null:Math.round((n-r)/864e5)}function _0(t,r=!1){if(r||!t)return"none";const n=C0(t);return n===null?"none":n<0?"overdue":n===0?"today":n<=3?"soon":"normal"}function Cw(t,r=!1){const n=_0(t,r);if(n==="none")return"";const s=C0(t);return n==="overdue"?`${Math.abs(s)}d overdue`:n==="today"?"Due today":n==="soon"?`Due in ${s}d`:t}function _w(t){return t==="overdue"?"text-rose-300 border-rose-400/30 bg-rose-500/10":t==="today"?"text-amber-200 border-amber-400/30 bg-amber-500/10":t==="soon"?"text-orange-200 border-orange-400/25 bg-orange-500/10":"text-slate-400 border-white/10 bg-white/[0.03]"}function s2(t){return t==="high"?{label:"High",className:"text-rose-200 border-rose-400/30 bg-rose-500/10"}:t==="low"?{label:"Low",className:"text-slate-400 border-white/10 bg-white/[0.03]"}:{label:"Normal",className:"text-amber-200 border-amber-400/25 bg-amber-500/10"}}function a2(t){let r=String(t||"").trim();const n=[];let s="normal",a="";const o=r.match(/#[\w-]+/g);o&&(o.forEach(u=>n.push(u.slice(1).toLowerCase())),r=r.replace(/#[\w-]+/g," ").replace(/\s+/g," ").trim());const c=r.match(/^!(high|normal|low)\b/i);c&&(s=c[1].toLowerCase(),r=r.slice(c[0].length).trim());const l=r.match(/^due:(\d{4}-\d{2}-\d{2})\b/i);return l&&(a=l[1],r=r.slice(l[0].length).trim()),{title:r.trim(),tags:Array.from(new Set(n)).slice(0,8),priority:s,dueDate:a}}function o2(t){const r=String(t||"").trim();return r?r.split(/\s+/).filter(Boolean).length:0}function i2(t){const r=new Map;return(Array.isArray(t)?t:[]).forEach(n=>{const s=Sw(n.at);r.has(s)||r.set(s,[]),r.get(s).push(n)}),Array.from(r.entries()).map(([n,s])=>({day:n,rows:s}))}const A0="neuralshell_workpad_width_v1",Aw=380,Ew=720,Di=520;function l2(){if(typeof window>"u"||!window.localStorage)return Di;try{const t=Number(window.localStorage.getItem(A0));return Number.isFinite(t)?Math.max(Aw,Math.min(Ew,t)):Di}catch{return Di}}function c2(t){if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(A0,String(Math.round(t)))}catch{}}const pa=[{id:"provider_sweep",title:"Provider Sweep",description:"Open settings and run provider health sweep."},{id:"vault_save",title:"Save Vault",description:"Store a demo secret in Vault+."},{id:"run_proof",title:"Run 90s Proof",description:"Execute /proof from the command lane."},{id:"share_badge",title:"Share Badge",description:"Open proof badge URL and confirm outbound share path."}],E0="neuralshell_onboarding_progress_v1",Jd="neuralshell_onboarding_events_v1";function Iw(){if(typeof window>"u"||!window.localStorage)return{};try{return JSON.parse(window.localStorage.getItem(E0)||"{}")||{}}catch{return{}}}function Pw(t){typeof window>"u"||!window.localStorage||window.localStorage.setItem(E0,JSON.stringify(t||{}))}function ma(t,r=""){if(!(typeof window>"u"||!window.localStorage))try{const n=JSON.parse(window.localStorage.getItem(Jd)||"[]"),s=Array.isArray(n)?n:[];s.push({at:new Date().toISOString(),type:String(t||""),stepId:String(r||"")}),window.localStorage.setItem(Jd,JSON.stringify(s.slice(-200)))}catch{}}function Rw({open:t,onClose:r,onOpenSettings:n,onRunCommand:s}){const[a,o]=i.useState(()=>Iw()),[c,l]=i.useState("");if(i.useEffect(()=>{t&&ma("wizard_opened")},[t]),!t)return null;const u=m=>{const f={...a,[m]:!0};o(f),Pw(f),ma("step_completed",m)},x=async m=>{const f=String(m&&m.id?m.id:"");if(f){l(f),ma("step_started",f);try{if(f==="provider_sweep"){typeof n=="function"&&n(),u(f);return}if(f==="vault_save"){await window.api.vault.setSecret("onboarding","demo_key",`created:${new Date().toISOString()}`),u(f);return}if(f==="run_proof"){typeof s=="function"&&s("/proof"),u(f);return}f==="share_badge"&&(await window.api.system.openExternal("https://raw.githubusercontent.com/Z3r0DayZion-install/NeuralShell/badges/proof_badge.svg"),u(f))}catch{ma("step_failed",f)}finally{l("")}}},p=pa.filter(m=>!!a[m.id]).length,d=p>=pa.length;return e.jsx("div",{className:"fixed inset-0 z-[140] bg-black/65 backdrop-blur-sm flex items-center justify-center p-5",children:e.jsxs("div",{className:"w-full max-w-3xl rounded-2xl border border-cyan-300/20 bg-slate-950 p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"First-Run Onboarding"}),e.jsxs("div",{className:"text-[11px] text-slate-400 font-mono",children:[p,"/",pa.length," complete"]})]}),e.jsx("button",{type:"button","data-testid":"onboarding-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsx("div",{className:"space-y-3",children:pa.map((m,f)=>{const b=String(m.id||""),h=!!a[b];return e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 px-4 py-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-200 font-bold",children:[f+1,". ",m.title]}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:m.description})]}),e.jsx("button",{type:"button","data-testid":`onboarding-step-${b}`,disabled:h||c===b,onClick:()=>x(m),className:`px-3 py-1.5 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${h?"border-emerald-300/30 bg-emerald-500/10 text-emerald-200":"border-cyan-300/30 bg-cyan-500/10 text-cyan-200 hover:bg-cyan-500/20"} disabled:opacity-60`,children:h?"Done":c===b?"Running":"Run"})]},b)})}),e.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Funnel events are logged locally for drop-off tracking."}),e.jsx("button",{type:"button","data-testid":"onboarding-finish-btn",onClick:r,className:`px-3 py-2 rounded border text-[10px] uppercase tracking-[0.16em] font-bold ${d?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":"border-white/10 bg-white/5 text-slate-300"}`,children:d?"Complete":"Close"})]})]})})}const xa=[{id:"bug_report",label:"Bug Report",template:"bug_report.yml"},{id:"proof_flow",label:"Proof Flow Regression",template:"proof_flow.yml"}];function $i(t){return encodeURIComponent(String(t||""))}function Ow(t){return["### Source",`- tier: ${t.tier||"unknown"}`,`- version: ${t.version||"unknown"}`,`- workflow: ${t.workflowId||"unknown"}`,"","### Support Bundle",`- path: ${t.supportBundlePath||"n/a"}`,`- sha256: ${t.supportBundleHash||"n/a"}`,"","### Notes",`${t.notes||""}`].join(` +`)}function Tw({open:t,onClose:r,metadata:n}){const[s,a]=i.useState(xa[0].id),[o,c]=i.useState("");if(!t)return null;const l=xa.find(m=>m.id===s)||xa[0],u={...n||{},notes:o},x=Ow(u),p=`https://github.com/Z3r0DayZion-install/NeuralShell/issues/new?template=${$i(l.template)}&title=${$i(`${l.label}: `)}&body=${$i(x)}`,d=async()=>{await window.api.system.openExternal(p),r()};return e.jsx("div",{className:"fixed inset-0 z-[150] bg-black/70 backdrop-blur-sm flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-2xl rounded-2xl border border-cyan-300/20 bg-slate-950 p-5 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Issue Assist"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Prepare sanitized issue markdown and open GitHub issue page."})]}),e.jsx("button",{type:"button","data-testid":"issue-assist-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsx("div",{className:"flex items-center gap-2",children:xa.map(m=>e.jsx("button",{type:"button","data-testid":`issue-assist-type-${m.id}`,onClick:()=>a(m.id),className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${s===m.id?"border-cyan-300/30 bg-cyan-500/10 text-cyan-200":"border-white/10 bg-white/5 text-slate-300"}`,children:m.label},m.id))}),e.jsx("textarea",{"data-testid":"issue-assist-notes",value:o,onChange:m=>c(m.target.value),placeholder:"Add reproduction notes...",className:"w-full min-h-24 bg-black/40 border border-white/10 rounded-xl p-3 text-[12px] text-slate-100 font-mono"}),e.jsx("pre",{className:"rounded-xl border border-white/10 bg-black/40 p-3 text-[10px] text-slate-300 font-mono whitespace-pre-wrap max-h-48 overflow-auto",children:x}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{type:"button","data-testid":"issue-assist-copy-btn",onClick:()=>navigator.clipboard.writeText(x),className:"px-3 py-2 rounded border border-white/10 bg-white/5 text-[10px] uppercase tracking-[0.14em] font-mono text-slate-200",children:"Copy"}),e.jsx("button",{type:"button","data-testid":"issue-assist-open-btn",onClick:d,className:"px-3 py-2 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.14em] font-mono text-cyan-100",children:"Open Issue"})]})]})})}function Mw({workflowId:t,tierLabel:r,beforeMinutes:n,afterMinutes:s,notes:a}){const o=Number(n)||0,c=Number(s)||0,l=Math.max(0,o-c);return{exportedAt:new Date().toISOString(),anonymized:!0,workflowId:String(t||""),tier:String(r||"unknown"),metrics:{beforeMinutes:n,afterMinutes:s,reclaimedMinutes:l},notes:String(a||"").trim(),screenshotChecklist:["proof_output","roi_output","lock_flow","unlock_restored"]}}function Dw(t,r){const n=new Blob([`${JSON.stringify(r,null,2)} +`],{type:"application/json"}),s=URL.createObjectURL(n),a=document.createElement("a");a.href=s,a.download=t,document.body.appendChild(a),a.click(),a.remove(),URL.revokeObjectURL(s)}function $w({open:t,onClose:r,workflowId:n,tierLabel:s}){const[a,o]=i.useState("45"),[c,l]=i.useState("10"),[u,x]=i.useState(""),[p,d]=i.useState("");if(!t)return null;const m=()=>{const f=Mw({workflowId:n,tierLabel:s,beforeMinutes:a,afterMinutes:c,notes:u});Dw(`neuralshell_case_study_${Date.now()}.json`,f),d("Anonymized success capture exported.")};return e.jsx("div",{className:"fixed inset-0 z-[145] bg-black/70 backdrop-blur-sm flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-2xl rounded-2xl border border-emerald-300/20 bg-slate-950 p-5 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-emerald-300 font-bold",children:"Case Study Capture"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Export anonymized before/after metrics and screenshot checklist."})]}),e.jsx("button",{type:"button","data-testid":"success-capture-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("label",{className:"text-[10px] font-mono text-slate-300",children:["Before (minutes/day)",e.jsx("input",{"data-testid":"success-capture-before",value:a,onChange:f=>o(f.target.value),className:"mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-[12px] text-slate-100"})]}),e.jsxs("label",{className:"text-[10px] font-mono text-slate-300",children:["After (minutes/day)",e.jsx("input",{"data-testid":"success-capture-after",value:c,onChange:f=>l(f.target.value),className:"mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-[12px] text-slate-100"})]})]}),e.jsxs("label",{className:"text-[10px] font-mono text-slate-300 block",children:["Notes (optional)",e.jsx("textarea",{"data-testid":"success-capture-notes",value:u,onChange:f=>x(f.target.value),placeholder:"Short anonymized context for marketing review...",className:"mt-1 w-full min-h-20 rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-[12px] text-slate-100"})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-400",children:["Workflow: ",String(n||"unknown")," · Tier: ",String(s||"unknown")]}),e.jsx("div",{className:"flex justify-end gap-2",children:e.jsx("button",{type:"button","data-testid":"success-capture-export-btn",onClick:m,className:"px-3 py-2 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] uppercase tracking-[0.14em] font-mono text-emerald-100",children:"Export Capture Bundle"})}),p&&e.jsx("div",{className:"text-[10px] font-mono text-emerald-200",children:p})]})})}const I0="neuralshell_sales_console_v1",P0=["Lead","Discovery","Demo Scheduled","Pilot Active","Security Review","Procurement","Deployment","Renewal","Closed Won","Closed Lost"];function Al(t={}){const r=t&&typeof t=="object"?t:{};return{id:String(r.id||r.leadId||`deal-${Date.now()}-${Math.random().toString(36).slice(2,7)}`),accountName:String(r.accountName||r.customer||r.company||"Unnamed Account").trim(),owner:String(r.owner||r.sdr||r.ae||"Founder").trim(),stage:P0.includes(String(r.stage||"").trim())?String(r.stage||"").trim():"Lead",dealSizeUsd:he(r.dealSizeUsd||r.dealSize||r.acv||r.value,0),nextAction:String(r.nextAction||r.action||"Follow up").trim(),nextActionDate:nc(r.nextActionDate||r.nextStepDate||r.followUpDate,""),demoStatus:String(r.demoStatus||r.demo||"pending").trim().toLowerCase(),proofStatus:String(r.proofStatus||r.proof||"pending").trim().toLowerCase(),pilotStatus:String(r.pilotStatus||r.pilot||"not_started").trim().toLowerCase(),securityReview:String(r.securityReview||r.security||"not_started").trim().toLowerCase(),procurementStatus:String(r.procurementStatus||r.procurement||"not_started").trim().toLowerCase(),renewalState:String(r.renewalState||r.renewal||"n/a").trim().toLowerCase(),notes:String(r.notes||"").trim(),updatedAt:new Date().toISOString()}}function Lw(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(I0)||"[]");return Array.isArray(t)?t.map(r=>Al(r)):[]}catch{return[]}}function Bw(){const[t,r]=i.useState(()=>Lw()),[n,s]=i.useState("");i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(I0,JSON.stringify(t))},[t]);const a=i.useMemo(()=>t.reduce((d,m)=>d+he(m.dealSizeUsd,0),0),[t]),o=i.useMemo(()=>t.filter(d=>d.stage==="Pilot Active"||d.pilotStatus==="active").length,[t]),c=i.useMemo(()=>t.filter(d=>d.stage==="Security Review"||d.securityReview==="blocked").length,[t]),l=i.useMemo(()=>t.filter(d=>d.stage==="Procurement"||d.procurementStatus==="blocked").length,[t]),u=async d=>{const m=d&&d.target&&d.target.files?d.target.files[0]:null;if(m)try{const f=await pt(m),h=Ds(f,m.name).map(g=>Al(g));r(g=>{const y=new Map(g.map(I=>[I.id,I]));return h.forEach(I=>y.set(I.id,I)),Array.from(y.values())}),s("")}catch(f){s(f&&f.message?f.message:String(f))}},x=(d,m)=>{r(f=>f.map(b=>b.id===d?{...b,...m,updatedAt:new Date().toISOString()}:b))},p=()=>{r(d=>[Al({accountName:`Net-New_${d.length+1}`,owner:"Founder",stage:"Lead",nextAction:"Discovery call"}),...d])};return e.jsxs("section",{"data-testid":"sales-console",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Enterprise Sales Console"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Local pipeline tracking for demos, pilots, review gates, deployment, and renewals."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"sales-console-add-deal-btn",onClick:p,className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"+ Deal"}),e.jsxs("label",{className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.12em] font-mono text-slate-200 cursor-pointer",children:["Import CSV/JSON",e.jsx("input",{type:"file",accept:".csv,.json,application/json",className:"hidden","data-testid":"sales-console-import-input",onChange:u})]}),e.jsx("button",{type:"button","data-testid":"sales-console-export-btn",onClick:()=>{je(`neuralshell_sales_pipeline_${Date.now()}.json`,{exportedAt:new Date().toISOString(),totals:{dealCount:t.length,totalPipeline:a},deals:t})},className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Export"})]})]}),n&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:n}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Deals"}),e.jsx("div",{className:"text-[14px] font-bold text-slate-100",children:t.length})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Pipeline"}),e.jsxs("div",{className:"text-[14px] font-bold text-cyan-100",children:["$",a.toLocaleString()]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Active Pilots"}),e.jsx("div",{className:"text-[14px] font-bold text-emerald-100",children:o})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Blocked"}),e.jsx("div",{className:"text-[14px] font-bold text-amber-100",children:c+l})]})]}),e.jsx("div",{className:"rounded-lg border border-white/10 bg-black/30 overflow-auto",children:e.jsxs("table",{className:"min-w-full text-[10px] font-mono",children:[e.jsx("thead",{className:"bg-white/[0.04] text-slate-400 uppercase tracking-[0.1em]",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-2 py-2",children:"Account"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Stage"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Deal"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Next Action"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Demo"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Proof"})]})}),e.jsxs("tbody",{children:[t.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-3 py-3 text-slate-500",colSpan:6,children:"No deals imported yet."})}),t.map(d=>e.jsxs("tr",{className:"border-t border-white/5",children:[e.jsx("td",{className:"px-2 py-2 text-slate-200",children:e.jsx("input",{value:d.accountName,onChange:m=>x(d.id,{accountName:m.target.value}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1"})}),e.jsx("td",{className:"px-2 py-2",children:e.jsx("select",{value:d.stage,onChange:m=>x(d.id,{stage:m.target.value}),className:"w-full bg-slate-900 border border-white/10 rounded px-1.5 py-1 text-slate-200",children:P0.map(m=>e.jsx("option",{value:m,children:m},m))})}),e.jsx("td",{className:"px-2 py-2 text-slate-200",children:e.jsx("input",{type:"number",value:d.dealSizeUsd,onChange:m=>x(d.id,{dealSizeUsd:he(m.target.value,0)}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1"})}),e.jsxs("td",{className:"px-2 py-2 text-slate-200",children:[e.jsx("input",{value:d.nextAction,onChange:m=>x(d.id,{nextAction:m.target.value}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1 mb-1"}),e.jsx("input",{type:"date",value:d.nextActionDate,onChange:m=>x(d.id,{nextActionDate:m.target.value}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1"})]}),e.jsx("td",{className:"px-2 py-2",children:e.jsxs("select",{value:d.demoStatus,onChange:m=>x(d.id,{demoStatus:m.target.value}),className:"w-full bg-slate-900 border border-white/10 rounded px-1.5 py-1 text-slate-200",children:[e.jsx("option",{value:"pending",children:"pending"}),e.jsx("option",{value:"scheduled",children:"scheduled"}),e.jsx("option",{value:"completed",children:"completed"}),e.jsx("option",{value:"blocked",children:"blocked"})]})}),e.jsx("td",{className:"px-2 py-2",children:e.jsxs("select",{value:d.proofStatus,onChange:m=>x(d.id,{proofStatus:m.target.value}),className:"w-full bg-slate-900 border border-white/10 rounded px-1.5 py-1 text-slate-200",children:[e.jsx("option",{value:"pending",children:"pending"}),e.jsx("option",{value:"in_progress",children:"in_progress"}),e.jsx("option",{value:"completed",children:"completed"}),e.jsx("option",{value:"blocked",children:"blocked"})]})})]},d.id))]})]})})]})}function Fw(){const[t,r]=i.useState("Acme Security Group"),[n,s]=i.useState("critical-infrastructure"),[a,o]=i.useState("secure release verification"),[c,l]=i.useState("assets/pilot_kit/customer_logo.png"),u=i.useMemo(()=>["node scripts/gen_pilot_pack.cjs",`--customer "${t}"`,`--industry "${n}"`,`--use-case "${a}"`,`--logo "${c}"`].join(" "),[t,n,c,a]),x=i.useMemo(()=>({customerName:t,industry:n,useCase:a,logoPath:c,generatedAt:new Date().toISOString(),recommendedCommand:u}),[u,t,n,c,a]);return e.jsxs("section",{"data-testid":"pilot-kit-console",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Pilot Program Kit"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Generate ready-to-send pilot bundles tailored by customer, logo, industry, and use case."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"pilot-kit-export-json-btn",onClick:()=>je(`neuralshell_pilot_pack_request_${Date.now()}.json`,x),className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Export Request"}),e.jsx("button",{type:"button","data-testid":"pilot-kit-export-command-btn",onClick:()=>$s(`neuralshell_pilot_pack_command_${Date.now()}.txt`,`${u} +`),className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"Export Command"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:[e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:["Customer Name",e.jsx("input",{value:t,onChange:p=>r(p.target.value),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]}),e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:["Industry",e.jsx("input",{value:n,onChange:p=>s(p.target.value),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]}),e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300 md:col-span-2",children:["Use Case",e.jsx("input",{value:a,onChange:p=>o(p.target.value),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]}),e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300 md:col-span-2",children:["Logo Path",e.jsx("input",{value:c,onChange:p=>l(p.target.value),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500 mb-1",children:"Generator Command"}),e.jsx("code",{className:"text-[10px] font-mono text-cyan-100 break-all",children:u})]})]})}const Uw=[{publisherId:"demo-neuralshell-labs",displayName:"ProofForge Labs Demo Publisher",fingerprint:"sha256:78b7d2a0650f9b1c022f22319e4ff326dae93e962735936d898675c4e10a21c0"}],Li={publishers:Uw},zw="neuralshell_branding_profile_v1",Hw="neuralshell-default",Ww="ProofForge Default Branding",Kw={productName:"ProofForge",logoText:"ProofForge",accentColor:"#22d3ee",supportUrl:"https://github.com/Z3r0DayZion-install/NeuralShell/issues",docsUrl:"https://github.com/Z3r0DayZion-install/NeuralShell/tree/main/docs"},Vw={allowRemoteBridge:!1,offlineOnly:!1,updateRing:"stable"},Ia={schema:zw,profileId:Hw,displayName:Ww,branding:Kw,policyDefaults:Vw};function El(t){if(Array.isArray(t))return t.map(r=>El(r));if(t&&typeof t=="object"){const r={};return Object.keys(t).sort().forEach(n=>{r[n]=El(t[n])}),r}return t}function pr(t){return JSON.stringify(El(t))}function sc(t){const r=new Uint8Array(t);let n="";for(let s=0;s{if(n[s]!==2)throw new Error("Invalid DER integer marker.");s+=1;let p=n[s];if(s+=1,p&128){const f=p&127;p=0;for(let b=0;bo)throw new Error("DER signature length mismatch.");const x=new Uint8Array(r*2);return x.set(l.slice(-r),r-Math.min(r,l.length)),x.set(u.slice(-r),r*2-Math.min(r,u.length)),x.buffer}function R0(t,r){const n=String(r||"").match(/.{1,64}/g)||[];return`-----BEGIN ${t}----- ${n.join(` `)} ------END ${t}-----`}function ac(t){return String(t||"").replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"").trim()}async function Jw(t){const r=await window.crypto.subtle.exportKey("spki",t);return R0("PUBLIC KEY",sc(r))}async function qw(t){const r=await window.crypto.subtle.exportKey("pkcs8",t);return R0("PRIVATE KEY",sc(r))}async function Yw(t){const r=Qa(ac(t));return window.crypto.subtle.importKey("spki",r,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"])}async function Zw(t){const r=Qa(ac(t));return window.crypto.subtle.importKey("pkcs8",r,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}async function eo(t="neuralshell_signing_key_v1"){if(!window.crypto||!window.crypto.subtle)throw new Error("WebCrypto is unavailable.");const r=`${t}_public`,n=`${t}_private`,s=window.localStorage?window.localStorage.getItem(r):"",a=window.localStorage?window.localStorage.getItem(n):"";if(s&&a)return{publicKeyPem:s,privateKeyPem:a};const o=await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),l=await Jw(o.publicKey),c=await qw(o.privateKey);return window.localStorage&&(window.localStorage.setItem(r,l),window.localStorage.setItem(n,c)),{publicKeyPem:l,privateKeyPem:c}}async function to(t,r){if(!window.crypto||!window.crypto.subtle)throw new Error("WebCrypto is unavailable.");const n=await Zw(r),s=new window.TextEncoder,a=pr(t),o=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,s.encode(a));return sc(o)}async function Mt(t,r,n){if(!window.crypto||!window.crypto.subtle)throw new Error("WebCrypto is unavailable.");try{const s=await Yw(n),a=new window.TextEncoder,o=pr(t),l=Qa(r);if(await window.crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,l,a.encode(o)))return!0;try{const u=Gw(l,32);return!!await window.crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,u,a.encode(o))}catch{return!1}}catch{return!1}}async function Tr(t){if(!window.crypto||!window.crypto.subtle)throw new Error("WebCrypto is unavailable.");const r=Qa(ac(t)),n=await window.crypto.subtle.digest("SHA-256",r);return`sha256:${Array.from(new Uint8Array(n)).map(a=>a.toString(16).padStart(2,"0")).join("")}`}const O0="neuralshell_branding_profile_active_v1";function _s(t={}){const r=t&&typeof t=="object"?t:{},n=r.branding&&typeof r.branding=="object"?r.branding:{},s=r.policyDefaults&&typeof r.policyDefaults=="object"?r.policyDefaults:{};return{schema:"neuralshell_branding_profile_v1",profileId:String(r.profileId||"unnamed-profile").trim(),displayName:String(r.displayName||r.profileId||"Unnamed Profile").trim(),branding:{productName:String(n.productName||"ProofForge").trim(),logoText:String(n.logoText||n.productName||"ProofForge").trim(),accentColor:String(n.accentColor||"#22d3ee").trim(),supportUrl:String(n.supportUrl||"").trim(),docsUrl:String(n.docsUrl||"").trim(),installerName:String(n.installerName||"").trim()},policyDefaults:{allowRemoteBridge:!!s.allowRemoteBridge,offlineOnly:!!s.offlineOnly,updateRing:String(s.updateRing||"stable").trim().toLowerCase(),allowedProviders:Array.isArray(s.allowedProviders)?s.allowedProviders.map(a=>String(a||"").trim()).filter(Boolean):[]},source:{publisherId:String(r.publisherId||r.sourcePublisherId||"").trim(),appliedAt:new Date().toISOString()}}}function Xw(){if(typeof window>"u"||!window.localStorage)return _s(Ia);try{const t=JSON.parse(window.localStorage.getItem(O0)||"{}");return!t||typeof t!="object"||!t.profileId?_s(Ia):_s(t)}catch{return _s(Ia)}}function Qw(){const[t,r]=i.useState(()=>Xw()),[n,s]=i.useState(""),[a,o]=i.useState(""),l=i.useMemo(()=>{const p=Li&&Array.isArray(Li.publishers)?Li.publishers:[];return new Set(p.map(d=>String(d&&d.fingerprint?d.fingerprint:"").trim()).filter(Boolean))},[]),c=i.useCallback(async p=>{const d=_s(p);r(d),typeof window<"u"&&window.localStorage&&window.localStorage.setItem(O0,JSON.stringify(d)),window.dispatchEvent(new window.CustomEvent("neuralshell:branding-updated",{detail:d})),window.api&&window.api.audit&&typeof window.api.audit.append=="function"&&window.api.audit.append({event:"white_label_profile_applied",profileId:d.profileId,displayName:d.displayName,publisherId:d.source.publisherId,appliedAt:d.source.appliedAt}).catch(()=>{})},[]),u=async p=>{const d=p&&p.target&&p.target.files?p.target.files[0]:null;if(d)try{const m=await pt(d),f=JSON.parse(String(m||"{}")),b=f&&typeof f=="object"?f.payload:null,h=f&&typeof f=="object"?String(f.signature||""):"",g=f&&f.signer&&typeof f.signer=="object"?String(f.signer.publicKeyPem||""):"";if(!b||!h||!g)throw new Error("Signed profile requires payload, signature, and signer public key.");if(!await Mt(b,h,g))throw new Error("Branding profile signature verification failed.");const P=await Tr(g);if(l.size>0&&!l.has(P))throw new Error(`Untrusted branding signer fingerprint: ${P}`);await c({...b,sourcePublisherId:b&&b.publisherId?b.publisherId:""}),s(`Applied signed profile "${b.displayName||b.profileId}" (${P.slice(0,26)}...).`),o("")}catch(m){s(""),o(m&&m.message?m.message:String(m))}},x=async()=>{await c(Ia),s("Restored default ProofForge branding profile."),o("")};return e.jsxs("section",{"data-testid":"branding-overrides",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"White-Label / OEM Mode"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Signed branding profile import with capability-safe policy defaults."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("label",{className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100 cursor-pointer",children:["Import Signed Profile",e.jsx("input",{type:"file",accept:".json,application/json",className:"hidden","data-testid":"branding-overrides-import-input",onChange:u})]}),e.jsx("button",{type:"button","data-testid":"branding-overrides-reset-btn",onClick:x,className:"px-2 py-1 rounded border border-white/10 bg-white/5 text-[9px] uppercase tracking-[0.12em] font-mono text-slate-200",children:"Reset Default"})]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Active Profile"}),e.jsx("div",{className:"text-[13px] text-slate-100 font-bold",children:t.displayName}),e.jsx("div",{className:"text-[10px] text-slate-400 font-mono",children:t.profileId}),e.jsxs("div",{className:"mt-2 grid grid-cols-1 md:grid-cols-2 gap-2 text-[10px] font-mono text-slate-300",children:[e.jsxs("div",{children:["Product: ",t.branding.productName]}),e.jsxs("div",{children:["Logo Text: ",t.branding.logoText]}),e.jsxs("div",{children:["Accent: ",t.branding.accentColor]}),e.jsxs("div",{children:["Update Ring: ",t.policyDefaults.updateRing]}),e.jsxs("div",{children:["Remote Bridge: ",t.policyDefaults.allowRemoteBridge?"enabled":"disabled"]}),e.jsxs("div",{children:["Offline Only: ",t.policyDefaults.offlineOnly?"true":"false"]})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("button",{type:"button","data-testid":"branding-overrides-export-btn",onClick:()=>{je(`neuralshell_active_branding_profile_${Date.now()}.json`,t)},className:"px-2.5 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Export Active Profile"})}),n&&e.jsx("div",{className:"rounded-lg border border-emerald-300/30 bg-emerald-500/10 px-3 py-2 text-[10px] text-emerald-100 font-mono",children:n}),a&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:a})]})}const T0="neuralshell_partner_console_v1";function e1(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(T0)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Bi(t={}){const r=t&&typeof t=="object"?t:{},n=he(r.dealValueUsd||r.dealSize||r.value,0),s=Math.max(0,Math.min(100,he(r.marginPercent||r.margin,20))),a=Math.round(n*s/100);return{id:String(r.id||`partner-deal-${Date.now()}-${Math.random().toString(36).slice(2,7)}`),partnerId:String(r.partnerId||r.resellerId||"PARTNER_UNSET").trim().toUpperCase(),partnerName:String(r.partnerName||r.partner||"Unassigned Partner").trim(),accountName:String(r.accountName||r.account||r.customer||"Unnamed Account").trim(),leadOwner:String(r.leadOwner||r.owner||"sales").trim().toLowerCase(),stage:String(r.stage||r.status||"registered").trim().toLowerCase(),dealValueUsd:n,marginPercent:s,marginUsd:a,coBrandSlug:String(r.coBrandSlug||r.coBrand||r.partnerId||"default").trim().toLowerCase(),notes:String(r.notes||"").trim(),updatedAt:new Date().toISOString()}}function t1(){const[t,r]=i.useState(()=>e1()),[n,s]=i.useState("");i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(T0,JSON.stringify(t))},[t]);const a=i.useMemo(()=>t.reduce((p,d)=>(p.deals+=1,p.value+=he(d.dealValueUsd,0),p.margin+=he(d.marginUsd,0),p),{deals:0,value:0,margin:0}),[t]),o=async p=>{const d=p&&p.target&&p.target.files?p.target.files[0]:null;if(d)try{const m=await pt(d),f=Ds(m,d.name).map(b=>Bi(b));r(b=>{const h=new Map(b.map(g=>[g.id,g]));return f.forEach(g=>h.set(g.id,g)),Array.from(h.values())}),s("")}catch(m){s(m&&m.message?m.message:String(m))}},l=(p,d)=>{r(m=>m.map(f=>{if(f.id!==p)return f;const b={...f,...d},h=he(b.dealValueUsd,0),g=Math.max(0,Math.min(100,he(b.marginPercent,0)));return{...b,dealValueUsd:h,marginPercent:g,marginUsd:Math.round(h*g/100),updatedAt:new Date().toISOString()}}))},c=()=>{r(p=>[Bi({partnerId:`P-${String(p.length+1).padStart(3,"0")}`,partnerName:"New Partner",accountName:"New Account",leadOwner:"sales",stage:"registered",dealValueUsd:5e4,marginPercent:20}),...p])},u=()=>{const p=t.reduce((d,m)=>{const f=String(m.partnerId||"UNKNOWN");return d[f]||(d[f]={partnerId:f,partnerName:m.partnerName||f,deals:0,valueUsd:0,marginUsd:0}),d[f].deals+=1,d[f].valueUsd+=he(m.dealValueUsd,0),d[f].marginUsd+=he(m.marginUsd,0),d},{});je(`neuralshell_partner_report_${Date.now()}.json`,{exportedAt:new Date().toISOString(),totals:a,partners:Object.values(p),deals:t})},x=p=>{const d=Bi(p);je(`neuralshell_cobranded_kit_${d.partnerId}_${Date.now()}.json`,{generatedAt:new Date().toISOString(),partner:{id:d.partnerId,name:d.partnerName,coBrandSlug:d.coBrandSlug},account:d.accountName,messaging:{header:`${d.partnerName} + ProofForge`,cta:"Book enterprise pilot review",supportEmail:`support+${d.coBrandSlug}@neuralshell.local`},deal:{stage:d.stage,valueUsd:d.dealValueUsd,marginPercent:d.marginPercent,marginUsd:d.marginUsd}})};return e.jsxs("section",{"data-testid":"partner-console",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Partner Operations Layer"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Deal registration, ownership, margin tracking, and reseller export packs."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"partner-console-add-row-btn",onClick:c,className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"+ Register Deal"}),e.jsxs("label",{className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.12em] font-mono text-slate-200 cursor-pointer",children:["Import CSV/JSON",e.jsx("input",{type:"file",accept:".csv,.json,application/json",className:"hidden","data-testid":"partner-console-import-input",onChange:o})]}),e.jsx("button",{type:"button","data-testid":"partner-console-export-report-btn",onClick:u,className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Export Report"})]})]}),n&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:n}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Registered Deals"}),e.jsx("div",{className:"text-[14px] font-bold text-slate-100",children:a.deals})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Pipeline Value"}),e.jsxs("div",{className:"text-[14px] font-bold text-cyan-100",children:["$",a.value.toLocaleString()]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Partner Margin"}),e.jsxs("div",{className:"text-[14px] font-bold text-emerald-100",children:["$",a.margin.toLocaleString()]})]})]}),e.jsx("div",{className:"rounded-lg border border-white/10 bg-black/30 overflow-auto",children:e.jsxs("table",{className:"min-w-full text-[10px] font-mono",children:[e.jsx("thead",{className:"bg-white/[0.04] text-slate-400 uppercase tracking-[0.1em]",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-2 py-2",children:"Partner"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Account"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Owner"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Value"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Margin %"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Actions"})]})}),e.jsxs("tbody",{children:[t.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-3 py-3 text-slate-500",colSpan:6,children:"No partner deals registered."})}),t.map(p=>e.jsxs("tr",{className:"border-t border-white/5",children:[e.jsxs("td",{className:"px-2 py-2",children:[e.jsx("input",{value:p.partnerId,onChange:d=>l(p.id,{partnerId:d.target.value.toUpperCase()}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1 mb-1 text-slate-200"}),e.jsx("input",{value:p.partnerName,onChange:d=>l(p.id,{partnerName:d.target.value}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1 text-slate-300"})]}),e.jsx("td",{className:"px-2 py-2 text-slate-200",children:e.jsx("input",{value:p.accountName,onChange:d=>l(p.id,{accountName:d.target.value}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1"})}),e.jsx("td",{className:"px-2 py-2",children:e.jsxs("select",{value:p.leadOwner,onChange:d=>l(p.id,{leadOwner:d.target.value}),className:"w-full bg-slate-900 border border-white/10 rounded px-1.5 py-1 text-slate-200",children:[e.jsx("option",{value:"sales",children:"sales"}),e.jsx("option",{value:"support",children:"support"}),e.jsx("option",{value:"founder",children:"founder"}),e.jsx("option",{value:"partner",children:"partner"})]})}),e.jsx("td",{className:"px-2 py-2",children:e.jsx("input",{type:"number",value:p.dealValueUsd,onChange:d=>l(p.id,{dealValueUsd:he(d.target.value,0)}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1 text-slate-200"})}),e.jsxs("td",{className:"px-2 py-2",children:[e.jsx("input",{type:"number",value:p.marginPercent,onChange:d=>l(p.id,{marginPercent:he(d.target.value,0)}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1 text-slate-200"}),e.jsxs("div",{className:"text-[9px] text-emerald-200 mt-1",children:["$",he(p.marginUsd,0).toLocaleString()]})]}),e.jsx("td",{className:"px-2 py-2",children:e.jsx("button",{type:"button","data-testid":`partner-console-cobrand-btn-${p.id}`,onClick:()=>x(p),className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] text-cyan-100",children:"Co-Brand Kit"})})]},p.id))]})]})})]})}const qd=[{id:"audit_operator",title:"Audit Operator",description:"Run proof-first workflows, capture evidence, and maintain local audit posture.",passScore:80,questions:[{id:"ao_q1",prompt:"What command is used for a live trust/value proof run?",options:["/proof","/reset","/daemon"],answerIndex:0},{id:"ao_q2",prompt:"Which mode blocks most write actions by default?",options:["Operator","Auditor","Enterprise"],answerIndex:1},{id:"ao_q3",prompt:"Which export is used for support diagnostics?",options:["Support Bundle","Theme Snapshot","Model Cache"],answerIndex:0}]},{id:"deployment_admin",title:"Deployment Admin",description:"Enforce approved providers, update lanes, and relay restrictions.",passScore:80,questions:[{id:"da_q1",prompt:"What should be restricted for offline-first enterprise policy?",options:["Remote bridge","Scratchpad","Theme"],answerIndex:0},{id:"da_q2",prompt:"What gate protects production packaging quality?",options:["Release gate","Theme toggle","Quickstart cards"],answerIndex:0},{id:"da_q3",prompt:"What should every applied policy include?",options:["Signature metadata","Emoji badges","Music playlist"],answerIndex:0}]},{id:"compliance_lead",title:"Compliance Lead",description:"Verify artifact integrity, support audit requests, and preserve traceability.",passScore:80,questions:[{id:"cl_q1",prompt:"What verifies packaged artifacts have not been tampered?",options:["Signature verification","Screen brightness","CPU fan speed"],answerIndex:0},{id:"cl_q2",prompt:"What is required for external compliance review handoff?",options:["Reproducible evidence bundle","Desktop wallpaper","Audio recording"],answerIndex:0},{id:"cl_q3",prompt:"Where should policy and proof changes be recorded?",options:["Audit chain/log","Clipboard history","Chat emoji reactions"],answerIndex:0}]},{id:"marketplace_builder",title:"Marketplace Builder",description:"Package, price, and validate marketplace-facing modules with policy-safe defaults.",passScore:80,questions:[{id:"mb_q1",prompt:"What must not be bypassed by marketplace modules?",options:["Security and policy guardrails","Component naming conventions","Theme palette"],answerIndex:0},{id:"mb_q2",prompt:"What should partner-facing modules include for trust?",options:["Verification receipts","Animated stickers","Random IDs"],answerIndex:0},{id:"mb_q3",prompt:"Which signal is important before shipping new paid module updates?",options:["Release validation status","Mouse DPI","Window opacity"],answerIndex:0}]}],M0="neuralshell_certification_center_v1";function r1(){if(typeof window>"u"||!window.localStorage)return{};try{return JSON.parse(window.localStorage.getItem(M0)||"{}")||{}}catch{return{}}}function n1(t={}){const r=t&&typeof t=="object"?t:{};return{id:String(r.id||"").trim(),title:String(r.title||"Untitled Track").trim(),description:String(r.description||"").trim(),passScore:Math.max(1,Math.min(100,he(r.passScore,80))),questions:Array.isArray(r.questions)?r.questions.map(n=>({id:String(n&&n.id?n.id:`${r.id||"q"}_${Math.random().toString(36).slice(2,6)}`),prompt:String(n&&n.prompt?n.prompt:"Question"),options:Array.isArray(n&&n.options)?n.options.map(s=>String(s||"")):[],answerIndex:Math.max(0,he(n&&n.answerIndex,0))})):[]}}function Yd(t,r){const n=Array.isArray(t&&t.questions)?t.questions:[];if(!n.length)return{score:0,correct:0,total:0};const s=n.reduce((l,c)=>{const u=he(r[c.id],-1);return l+(u===he(c.answerIndex,-2)?1:0)},0),a=n.length;return{score:Math.round(s/a*100),correct:s,total:a}}function s1(){const t=i.useMemo(()=>(Array.isArray(qd)?qd:[]).map(y=>n1(y)),[]),[r,n]=i.useState(()=>t[0]?t[0].id:""),[s,a]=i.useState(()=>r1()),[o,l]=i.useState(""),[c,u]=i.useState(""),[x,p]=i.useState("");i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(M0,JSON.stringify(s))},[s]);const d=i.useMemo(()=>t.find(y=>y.id===r)||t[0]||null,[r,t]),m=i.useMemo(()=>d?s[d.id]||{}:{},[d,s]),f=i.useMemo(()=>d?Yd(d,m):{score:0,correct:0,total:0},[d,m]),b=(y,P)=>{d&&a(A=>({...A,[d.id]:{...A[d.id]||{},[y]:P}}))},h=async()=>{if(d)try{const y=Yd(d,m);if(y.score{const P=y&&y.target&&y.target.files?y.target.files[0]:null;if(P)try{const A=await pt(P),C=JSON.parse(String(A||"{}")),w=C&&typeof C=="object"?C.payload:null,j=C&&typeof C=="object"?String(C.signature||""):"",E=C&&C.signer&&typeof C.signer=="object"?String(C.signer.publicKeyPem||""):"";if(!w||!j||!E)throw new Error("Certificate file missing payload/signature/public key.");const N=await Mt(w,j,E),_=await Tr(E);p(N?`Verified certificate ${w.certificateId||""} (${_.slice(0,28)}...)`:"Certificate signature check failed."),u("")}catch(A){p(""),u(A&&A.message?A.message:String(A))}};return e.jsxs("section",{"data-testid":"certification-center",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Certification Center"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Local training modules with quiz scoring and signed certificate exports."})]}),e.jsxs("label",{className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.12em] font-mono text-slate-200 cursor-pointer",children:["Verify Certificate",e.jsx("input",{type:"file",accept:".json,application/json",className:"hidden","data-testid":"certification-verify-input",onChange:g})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:t.map(y=>e.jsx("button",{type:"button","data-testid":`certification-track-${y.id}`,onClick:()=>n(y.id),className:`px-2.5 py-1.5 rounded-lg border text-[10px] font-mono uppercase tracking-[0.12em] ${d&&d.id===y.id?"border-cyan-300/40 bg-cyan-500/20 text-cyan-100":"border-white/10 bg-white/5 text-slate-300 hover:bg-white/10"}`,children:y.title},y.id))}),d&&e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 p-3 space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-bold text-slate-100",children:d.title}),e.jsx("div",{className:"text-[10px] text-slate-400 font-mono",children:d.description})]}),e.jsx("div",{className:"space-y-2",children:d.questions.map((y,P)=>e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-2",children:[e.jsxs("div",{className:"text-[10px] text-slate-200 mb-1",children:[P+1,". ",y.prompt]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:y.options.map((A,C)=>e.jsx("button",{type:"button",onClick:()=>b(y.id,C),className:`px-2 py-1 rounded border text-[9px] font-mono ${he(m[y.id],-1)===C?"border-cyan-300/40 bg-cyan-500/20 text-cyan-100":"border-white/10 bg-white/5 text-slate-300 hover:bg-white/10"}`,children:A},`${y.id}-${C}`))})]},y.id))}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-300",children:["Score ",f.score,"% (",f.correct,"/",f.total,") · Pass ",d.passScore,"%"]}),e.jsx("button",{type:"button","data-testid":"certification-issue-certificate-btn",onClick:h,className:"px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Issue Certificate"})]})]}),o&&e.jsx("div",{className:"rounded-lg border border-emerald-300/30 bg-emerald-500/10 px-3 py-2 text-[10px] text-emerald-100 font-mono",children:o}),x&&e.jsx("div",{className:"rounded-lg border border-cyan-300/30 bg-cyan-500/10 px-3 py-2 text-[10px] text-cyan-100 font-mono",children:x}),c&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:c})]})}const D0="neuralshell_board_console_v1";function a1(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(D0)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Zd(t={}){const r=t&&typeof t=="object"?t:{};return{month:String(r.month||nc(r.date||new Date().toISOString(),new Date().toISOString().slice(0,7))).slice(0,7),installs:he(r.installs,0),activations:he(r.activations,0),retained30d:he(r.retained30d||r.retention,0),revenueUsd:he(r.revenueUsd||r.revenue,0),proofRuns:he(r.proofRuns,0),partnerGrowth:he(r.partnerGrowth||r.partnerAdds,0),compliancePosture:String(r.compliancePosture||r.compliance||"stable").trim().toLowerCase(),source:String(r.source||"import").trim()}}function Pr(t,r,n){const s=he(t&&t[n],0),a=he(r&&r[n],0);return s-a}function o1(t,r){if(!t)return"No board snapshot available.";const n=Pr(t,r,"installs"),s=Pr(t,r,"activations"),a=Pr(t,r,"revenueUsd"),o=Pr(t,r,"proofRuns"),l=Pr(t,r,"partnerGrowth");return[`# ProofForge Board Pack - ${t.month}`,"","## Operating Summary",`- Installs: ${t.installs.toLocaleString()} (${n>=0?"+":""}${n.toLocaleString()} vs previous)`,`- Activations: ${t.activations.toLocaleString()} (${s>=0?"+":""}${s.toLocaleString()} vs previous)`,`- Revenue: $${t.revenueUsd.toLocaleString()} (${a>=0?"+":""}$${a.toLocaleString()} vs previous)`,`- Proof Runs: ${t.proofRuns.toLocaleString()} (${o>=0?"+":""}${o.toLocaleString()} vs previous)`,`- Partner Growth: ${t.partnerGrowth.toLocaleString()} (${l>=0?"+":""}${l.toLocaleString()} vs previous)`,"","## Retention / Compliance",`- 30d Retained Accounts: ${t.retained30d.toLocaleString()}`,`- Compliance Posture: ${t.compliancePosture}`,"","## Founder Notes","- Confirm top two pilot expansions from Customer Success risk list.","- Validate policy enforcement snapshots before enterprise renewal calls.","- Align partner incentives with highest-conversion pilot verticals."].join(` -`)}function i1(){const[t,r]=i.useState(()=>a1().map(x=>Zd(x))),[n,s]=i.useState("");i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(D0,JSON.stringify(t))},[t]);const a=i.useMemo(()=>[...t].sort((x,p)=>String(x.month||"").localeCompare(String(p.month||""))),[t]),o=a.length?a[a.length-1]:null,l=a.length>1?a[a.length-2]:null,c=i.useMemo(()=>o1(o,l),[o,l]),u=async x=>{const p=x&&x.target&&x.target.files?x.target.files[0]:null;if(p)try{const d=await pt(p),m=Ds(d,p.name).map(f=>Zd({...f,source:p.name}));r(f=>{const b=new Map(f.map(h=>[h.month,h]));return m.forEach(h=>b.set(h.month,h)),Array.from(b.values())}),s("")}catch(d){s(d&&d.message?d.message:String(d))}};return e.jsxs("section",{"data-testid":"board-console",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Investor / Board Reporting Pack"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Monthly operating snapshot with deltas from previous export and local metrics imports."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("label",{className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.12em] font-mono text-slate-200 cursor-pointer",children:["Import Metrics Bundle",e.jsx("input",{type:"file",accept:".csv,.json,application/json",className:"hidden","data-testid":"board-console-import-input",onChange:u})]}),e.jsx("button",{type:"button","data-testid":"board-console-export-markdown-btn",onClick:()=>$s(`neuralshell_board_pack_${Date.now()}.md`,c),className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"Export Markdown"}),e.jsx("button",{type:"button","data-testid":"board-console-export-json-btn",onClick:()=>je(`neuralshell_board_pack_${Date.now()}.json`,{exportedAt:new Date().toISOString(),current:o,previous:l,markdown:c,snapshots:a}),className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Export JSON"})]})]}),n&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:n}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Current Month"}),e.jsx("div",{className:"text-[14px] font-bold text-slate-100",children:o?o.month:"N/A"})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Revenue"}),e.jsxs("div",{className:"text-[14px] font-bold text-emerald-100",children:["$",o?o.revenueUsd.toLocaleString():"0"]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Delta vs Prev"}),e.jsx("div",{className:"text-[14px] font-bold text-cyan-100",children:o&&l?`${Pr(o,l,"revenueUsd")>=0?"+":""}$${Pr(o,l,"revenueUsd").toLocaleString()}`:"N/A"})]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500 mb-2",children:"Board Draft"}),e.jsx("pre",{className:"text-[10px] text-slate-300 font-mono whitespace-pre-wrap leading-relaxed",children:c})]})]})}function fa(t={}){const r=t&&typeof t=="object"?t:{};return{policyId:String(r.policyId||r.id||`policy-${Date.now()}`).trim(),label:String(r.label||r.policyId||"Enterprise Policy").trim(),allowedProviders:Array.isArray(r.allowedProviders)?r.allowedProviders.map(n=>String(n||"").trim().toLowerCase()).filter(Boolean):["ollama"],offlineOnly:!!r.offlineOnly,allowRemoteBridge:!!r.allowRemoteBridge,proofRelayEnabled:!!r.proofRelayEnabled,updateRing:String(r.updateRing||"stable").trim().toLowerCase(),certPins:Array.isArray(r.certPins)?r.certPins.map(n=>String(n||"").trim()).filter(Boolean):[],relayRestriction:String(r.relayRestriction||"local-only").trim().toLowerCase()}}function l1(){const[t,r]=i.useState(()=>fa({})),[n,s]=i.useState(""),[a,o]=i.useState(""),[l,c]=i.useState(!1),u=i.useCallback(async()=>{try{const m=window.api&&window.api.settings&&typeof window.api.settings.get=="function"?await window.api.settings.get():{},f=m&&m.enterprisePolicyEnforced&&typeof m.enterprisePolicyEnforced=="object"?m.enterprisePolicyEnforced:{};r(fa({...f,allowedProviders:Array.isArray(f.allowedProviders)&&f.allowedProviders.length?f.allowedProviders:["ollama"],offlineOnly:!!(m&&m.offlineOnlyEnforced),allowRemoteBridge:!!(m&&m.allowRemoteBridge),proofRelayEnabled:!!(m&&m.proofRelayEnabled),updateRing:String(m&&m.autoUpdateChannel?m.autoUpdateChannel:f.updateRing||"stable")}))}catch(m){o(m&&m.message?m.message:String(m))}},[]);i.useEffect(()=>{u()},[u]);const x=async m=>{const f=fa(m);c(!0);try{window.api&&window.api.settings&&typeof window.api.settings.update=="function"&&await window.api.settings.update({allowRemoteBridge:!!f.allowRemoteBridge,proofRelayEnabled:!!f.proofRelayEnabled,autoUpdateChannel:f.updateRing,offlineOnlyEnforced:!!f.offlineOnly,enterprisePolicyEnforced:{...f,enforcedAt:new Date().toISOString()}}),window.api&&window.api.audit&&typeof window.api.audit.append=="function"&&await window.api.audit.append({event:"enterprise_policy_enforced",policyId:f.policyId,updateRing:f.updateRing,relayRestriction:f.relayRestriction,offlineOnly:f.offlineOnly}),r(f),s(`Applied policy "${f.label}" to runtime.`),o("")}catch(b){s(""),o(b&&b.message?b.message:String(b))}finally{c(!1)}},p=async m=>{const f=m&&m.target&&m.target.files?m.target.files[0]:null;if(f)try{const b=await pt(f),h=JSON.parse(String(b||"{}")),g=h&&typeof h=="object"?h.payload:null,y=h&&typeof h=="object"?String(h.signature||""):"",P=h&&h.signer&&typeof h.signer=="object"?String(h.signer.publicKeyPem||""):"";if(!g||!y||!P)throw new Error("Signed policy bundle requires payload/signature/public key.");if(!await Mt(g,y,P))throw new Error("Policy bundle signature verification failed.");await x(g);const C=await Tr(P);s(`Policy applied from signed bundle (${C.slice(0,26)}...).`),o("")}catch(b){s(""),o(b&&b.message?b.message:String(b))}},d=m=>{r(f=>fa({...f,...m}))};return e.jsxs("section",{"data-testid":"enterprise-policy-suite",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Deployment Policy Suite"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Apply signed policy bundles with provider controls, relay restrictions, update rings, and cert pinning."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("label",{className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100 cursor-pointer",children:["Import Signed Policy",e.jsx("input",{type:"file",accept:".json,application/json",className:"hidden","data-testid":"enterprise-policy-import-input",onChange:p})]}),e.jsx("button",{type:"button","data-testid":"enterprise-policy-export-btn",onClick:()=>{je(`neuralshell_enterprise_policy_${Date.now()}.json`,{exportedAt:new Date().toISOString(),payload:t})},className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Export"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:[e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:["Policy Label",e.jsx("input",{value:t.label,onChange:m=>d({label:m.target.value}),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]}),e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:["Policy ID",e.jsx("input",{value:t.policyId,onChange:m=>d({policyId:m.target.value}),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]}),e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:["Allowed Providers (comma separated)",e.jsx("input",{value:t.allowedProviders.join(","),onChange:m=>d({allowedProviders:String(m.target.value||"").split(",").map(f=>f.trim().toLowerCase()).filter(Boolean)}),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]}),e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:["Update Ring",e.jsxs("select",{value:t.updateRing,onChange:m=>d({updateRing:m.target.value}),className:"mt-1 w-full bg-slate-900 border border-white/10 rounded px-2 py-1",children:[e.jsx("option",{value:"stable",children:"stable"}),e.jsx("option",{value:"canary",children:"canary"}),e.jsx("option",{value:"beta",children:"beta"}),e.jsx("option",{value:"frozen",children:"frozen"})]})]}),e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:["Relay Restriction",e.jsxs("select",{value:t.relayRestriction,onChange:m=>d({relayRestriction:m.target.value}),className:"mt-1 w-full bg-slate-900 border border-white/10 rounded px-2 py-1",children:[e.jsx("option",{value:"local-only",children:"local-only"}),e.jsx("option",{value:"allowlisted-remotes",children:"allowlisted-remotes"}),e.jsx("option",{value:"blocked",children:"blocked"})]})]}),e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:["Cert Pins (one per comma)",e.jsx("input",{value:t.certPins.join(","),onChange:m=>d({certPins:String(m.target.value||"").split(",").map(f=>f.trim()).filter(Boolean)}),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-[10px] font-mono text-slate-300",children:[e.jsxs("label",{className:"inline-flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:!!t.offlineOnly,onChange:m=>d({offlineOnly:!!m.target.checked})}),"Offline-only enforced"]}),e.jsxs("label",{className:"inline-flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:!!t.allowRemoteBridge,onChange:m=>d({allowRemoteBridge:!!m.target.checked})}),"Allow remote bridge"]}),e.jsxs("label",{className:"inline-flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:!!t.proofRelayEnabled,onChange:m=>d({proofRelayEnabled:!!m.target.checked})}),"Proof relay enabled"]}),e.jsx("button",{type:"button","data-testid":"enterprise-policy-apply-btn",disabled:l,onClick:()=>x(t),className:"px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.12em] text-cyan-100 disabled:opacity-60",children:"Apply Policy"})]}),n&&e.jsx("div",{className:"rounded-lg border border-emerald-300/30 bg-emerald-500/10 px-3 py-2 text-[10px] text-emerald-100 font-mono",children:n}),a&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:a})]})}const $0="neuralshell_customer_success_console_v1";function c1(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem($0)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Xd(t={}){const r=t&&typeof t=="object"?t:{},n=Math.max(0,Math.min(100,he(r.onboardingCompletion||r.onboardingPct,0))),s=Math.max(0,he(r.proofRuns30d||r.proofRuns||0)),a=Math.max(0,he(r.supportBundles30d||r.supportBundles||0)),o=!!(r.upgraded||r.isUpgraded||String(r.plan||"").toLowerCase()==="paid"),l=nc(r.renewalDate||r.renewal,""),c=Array.isArray(r.timeline)?r.timeline.map(m=>String(m||"").trim()).filter(Boolean):[],u=Math.min(45,a*4),x=Math.max(0,Math.min(100,Math.round(n*.35+Math.min(30,s)*1.2+(o?20:0)-u))),p=x>=75?"healthy":x>=50?"watch":"risk",d=p==="healthy"?"Push expansion or renewal package.":p==="watch"?"Schedule proof refresh and onboarding checkpoint.":"Escalate to support + executive sponsor call.";return{id:String(r.id||r.customerId||`customer-${Date.now()}-${Math.random().toString(36).slice(2,6)}`),customerName:String(r.customerName||r.customer||r.account||"Unnamed Customer").trim(),onboardingCompletion:n,proofRuns30d:s,supportBundles30d:a,upgraded:o,renewalDate:l,healthScore:x,riskLevel:p,recommendation:d,timeline:c,updatedAt:new Date().toISOString()}}function d1(){const[t,r]=i.useState(()=>c1().map(l=>Xd(l))),[n,s]=i.useState("");i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem($0,JSON.stringify(t))},[t]);const a=async l=>{const c=l&&l.target&&l.target.files?l.target.files[0]:null;if(c)try{const u=await pt(c),x=Ds(u,c.name).map(p=>Xd(p));r(p=>{const d=new Map(p.map(m=>[m.id,m]));return x.forEach(m=>d.set(m.id,m)),Array.from(d.values())}),s("")}catch(u){s(u&&u.message?u.message:String(u))}},o=i.useMemo(()=>{if(!t.length)return{avgHealth:0,riskCount:0,watchCount:0};const l=t.reduce((c,u)=>c+he(u.healthScore,0),0);return{avgHealth:Math.round(l/t.length),riskCount:t.filter(c=>c.riskLevel==="risk").length,watchCount:t.filter(c=>c.riskLevel==="watch").length}},[t]);return e.jsxs("section",{"data-testid":"customer-success-console",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Customer Success Workspace"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Import local usage bundles, score customer health, and surface renewal risk actions."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("label",{className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.12em] font-mono text-slate-200 cursor-pointer",children:["Import Usage Bundles",e.jsx("input",{type:"file",accept:".csv,.json,application/json",className:"hidden","data-testid":"customer-success-import-input",onChange:a})]}),e.jsx("button",{type:"button","data-testid":"customer-success-export-btn",onClick:()=>{je(`neuralshell_customer_success_${Date.now()}.json`,{exportedAt:new Date().toISOString(),summary:o,customers:t})},className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Export"})]})]}),n&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:n}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Customers"}),e.jsx("div",{className:"text-[14px] font-bold text-slate-100",children:t.length})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Average Health"}),e.jsxs("div",{className:"text-[14px] font-bold text-cyan-100",children:[o.avgHealth,"%"]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Risk / Watch"}),e.jsxs("div",{className:"text-[14px] font-bold text-amber-100",children:[o.riskCount," / ",o.watchCount]})]})]}),e.jsxs("div",{className:"space-y-2 max-h-96 overflow-auto pr-1",children:[t.length===0&&e.jsx("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-3 text-[10px] font-mono text-slate-500",children:"No customer bundles loaded yet."}),t.map(l=>e.jsxs("article",{className:"rounded-lg border border-white/10 bg-black/30 p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[12px] font-bold text-slate-100",children:l.customerName}),e.jsxs("div",{className:"text-[10px] text-slate-500 font-mono",children:["Renewal ",l.renewalDate||"unset"," · Proof runs ",l.proofRuns30d," · Support bundles ",l.supportBundles30d]})]}),e.jsxs("span",{className:`px-2 py-1 rounded border text-[9px] uppercase tracking-[0.12em] font-mono ${l.riskLevel==="healthy"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":l.riskLevel==="watch"?"border-amber-300/30 bg-amber-500/10 text-amber-100":"border-rose-300/30 bg-rose-500/10 text-rose-100"}`,children:[l.riskLevel," · ",l.healthScore,"%"]})]}),e.jsxs("div",{className:"mt-2 text-[10px] font-mono text-slate-300",children:["Next action: ",l.recommendation]}),l.timeline.length>0&&e.jsxs("div",{className:"mt-2 rounded border border-white/10 bg-black/20 p-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.1em] text-slate-500 mb-1",children:"Timeline"}),e.jsx("div",{className:"space-y-1",children:l.timeline.slice(-4).map((c,u)=>e.jsxs("div",{className:"text-[10px] font-mono text-slate-400",children:["- ",c]},`${l.id}-timeline-${u}`))})]})]},l.id))]})]})}const Qd=[{id:"mobile_companion",name:"Mobile Companion Upsell",notes:"Fast status + approvals from phone for field operators.",effort:4,revenuePotential:7,salesFriction:5,deploymentComplexity:6,ecosystemFit:8},{id:"team_edition",name:"Team Edition",notes:"Role-aware seats, shared workflow visibility, and centralized policy control.",effort:7,revenuePotential:9,salesFriction:4,deploymentComplexity:6,ecosystemFit:9},{id:"secure_relay_appliance",name:"Secure Relay Appliance",notes:"On-prem hardened relay bridge for regulated enterprise deals.",effort:8,revenuePotential:8,salesFriction:6,deploymentComplexity:8,ecosystemFit:7},{id:"enterprise_support_plans",name:"Enterprise Support Plans",notes:"SLA-backed premium response and white-glove onboarding services.",effort:3,revenuePotential:8,salesFriction:3,deploymentComplexity:2,ecosystemFit:8}],L0="neuralshell_expansion_planner_v1",Fe={effort:.2,revenuePotential:.35,salesFriction:.15,deploymentComplexity:.1,ecosystemFit:.2};function u1(){if(typeof window>"u"||!window.localStorage)return{weights:Fe,overrides:{}};try{const t=JSON.parse(window.localStorage.getItem(L0)||"{}");return{weights:{effort:he(t&&t.weights?t.weights.effort:Fe.effort,Fe.effort),revenuePotential:he(t&&t.weights?t.weights.revenuePotential:Fe.revenuePotential,Fe.revenuePotential),salesFriction:he(t&&t.weights?t.weights.salesFriction:Fe.salesFriction,Fe.salesFriction),deploymentComplexity:he(t&&t.weights?t.weights.deploymentComplexity:Fe.deploymentComplexity,Fe.deploymentComplexity),ecosystemFit:he(t&&t.weights?t.weights.ecosystemFit:Fe.ecosystemFit,Fe.ecosystemFit)},overrides:t&&t.overrides&&typeof t.overrides=="object"?t.overrides:{}}}catch{return{weights:Fe,overrides:{}}}}function p1(t={}){const r=t&&typeof t=="object"?t:{};return{id:String(r.id||`bet-${Math.random().toString(36).slice(2,6)}`),name:String(r.name||"Untitled Bet"),notes:String(r.notes||""),effort:Math.max(1,Math.min(10,he(r.effort,5))),revenuePotential:Math.max(1,Math.min(10,he(r.revenuePotential,5))),salesFriction:Math.max(1,Math.min(10,he(r.salesFriction,5))),deploymentComplexity:Math.max(1,Math.min(10,he(r.deploymentComplexity,5))),ecosystemFit:Math.max(1,Math.min(10,he(r.ecosystemFit,5)))}}function m1(){const t=i.useMemo(()=>u1(),[]),[r,n]=i.useState(t.weights),[s,a]=i.useState(t.overrides);i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(L0,JSON.stringify({weights:r,overrides:s}))},[r,s]);const o=i.useMemo(()=>(Array.isArray(Qd)?Qd:[]).map(c=>p1(c)),[]),l=i.useMemo(()=>{const c={effort:Math.max(0,he(r.effort,Fe.effort)),revenuePotential:Math.max(0,he(r.revenuePotential,Fe.revenuePotential)),salesFriction:Math.max(0,he(r.salesFriction,Fe.salesFriction)),deploymentComplexity:Math.max(0,he(r.deploymentComplexity,Fe.deploymentComplexity)),ecosystemFit:Math.max(0,he(r.ecosystemFit,Fe.ecosystemFit))};return o.map(u=>{const x=((11-u.effort)*c.effort+u.revenuePotential*c.revenuePotential+(11-u.salesFriction)*c.salesFriction+(11-u.deploymentComplexity)*c.deploymentComplexity+u.ecosystemFit*c.ecosystemFit)*10,p=s[u.id]!=null?he(s[u.id],NaN):NaN,d=Number.isFinite(p)?p:Math.round(x);return{...u,baseScore:Math.round(x),finalScore:Math.max(0,Math.min(100,Math.round(d))),overrideUsed:Number.isFinite(p)}}).sort((u,x)=>x.finalScore-u.finalScore)},[o,s,r]);return e.jsxs("section",{"data-testid":"expansion-planner",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Strategic Expansion Planner"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Score expansion bets by effort, revenue, friction, complexity, and ecosystem fit."})]}),e.jsx("button",{type:"button","data-testid":"expansion-planner-export-btn",onClick:()=>{je(`neuralshell_expansion_planner_${Date.now()}.json`,{exportedAt:new Date().toISOString(),weights:r,ranked:l})},className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Export Plan"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-5 gap-2",children:Object.keys(Fe).map(c=>e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:[c,e.jsx("input",{type:"number",step:"0.05",min:"0",max:"1",value:he(r[c],Fe[c]),onChange:u=>n(x=>({...x,[c]:Math.max(0,Math.min(1,he(u.target.value,Fe[c])))})),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]},c))}),e.jsx("div",{className:"space-y-2",children:l.map(c=>e.jsxs("article",{className:"rounded-lg border border-white/10 bg-black/30 p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[12px] font-bold text-slate-100",children:c.name}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:c.notes})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.12em] text-slate-500",children:"Score"}),e.jsx("div",{className:"text-[16px] font-bold text-cyan-100",children:c.finalScore}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["base ",c.baseScore,c.overrideUsed?" · manual":""]})]})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-2 md:grid-cols-5 gap-2 text-[10px] font-mono text-slate-300",children:[e.jsxs("div",{children:["Effort ",c.effort,"/10"]}),e.jsxs("div",{children:["Revenue ",c.revenuePotential,"/10"]}),e.jsxs("div",{children:["Sales Friction ",c.salesFriction,"/10"]}),e.jsxs("div",{children:["Deploy Complexity ",c.deploymentComplexity,"/10"]}),e.jsxs("div",{children:["Ecosystem Fit ",c.ecosystemFit,"/10"]})]}),e.jsxs("div",{className:"mt-2",children:[e.jsx("label",{className:"text-[9px] uppercase tracking-[0.1em] text-slate-500",children:"Manual Score Override"}),e.jsx("input",{type:"number",min:"0",max:"100",placeholder:"leave empty to use weighted score",value:s[c.id]==null?"":s[c.id],onChange:u=>{const x=String(u.target.value||"").trim();a(p=>{if(!x){const d={...p};return delete d[c.id],d}return{...p,[c.id]:Math.max(0,Math.min(100,he(x,c.baseScore)))}})},className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1 text-[10px] font-mono text-slate-200"})]})]},c.id))})]})}const eu={free:0,pro:1,enterprise:2},B0=[{id:"mission_control",title:"Mission Control",description:"Runtime authority cockpit with live health cards, event feed, and watchdog visibility.",minTier:"free",roles:["founder","sales","support","operator"]},{id:"fleet_control",title:"Fleet Control",description:"Import and compare multi-node runtime bundles with health and event drill-ins.",minTier:"pro",roles:["founder","support","operator"]},{id:"recovery_center",title:"Recovery Center",description:"Signed recovery bundles, restore preview, and safe-mode restoration flow.",minTier:"pro",roles:["founder","support","operator"]},{id:"appliance_console",title:"Appliance Console",description:"Operator-only hardened appliance mode for relay/control deployments.",minTier:"enterprise",roles:["founder","operator","support"]},{id:"airgap_operations",title:"Air-Gapped Operations",description:"Import/export station ledger, verification gates, and air-gap lock posture controls.",minTier:"enterprise",roles:["founder","operator","support"]},{id:"trust_fabric",title:"PKI Trust Fabric",description:"Local CA controls, certificate lifecycle, revocation, and trust-chain export.",minTier:"enterprise",roles:["founder","operator","support"]},{id:"hardware_appliance",title:"Hardware Appliance Program",description:"Provisioning, profile health, support diagnostics scope, and decommission workflows.",minTier:"enterprise",roles:["founder","operator","support"]},{id:"courier_transfer",title:"Offline Evidence Courier",description:"Signed courier package movement with quarantine, receipt verification, and release controls.",minTier:"enterprise",roles:["founder","operator","support"]},{id:"continuity_drills",title:"Continuity Drills",description:"Schedule and score continuity exercises with recovery evidence exports.",minTier:"enterprise",roles:["founder","operator","support"]},{id:"procurement_command",title:"Procurement Command Center",description:"Generate buyer-ready security/procurement review packs and version deltas.",minTier:"enterprise",roles:["founder","support","sales"]},{id:"tamper_simulation",title:"Tamper Simulation Mode",description:"Safe simulation of detection, quarantine, and response workflows.",minTier:"enterprise",roles:["founder","operator","support","sales"]},{id:"institutional_command",title:"Institutional Command Console",description:"Unified executive/operator command surface across all institutional tracks.",minTier:"enterprise",roles:["founder","operator","support","sales"]},{id:"demo_flow",title:"Institutional Demo System",description:"Seeded deterministic demo route with presenter guidance and baseline reset controls.",minTier:"pro",roles:["founder","sales","support","operator"]},{id:"deployment_program",title:"Deployment Program Pack",description:"Role-based deployment runbooks plus preflight and post-install validation flows.",minTier:"pro",roles:["founder","operator","support"]},{id:"training_delivery",title:"Training Delivery Pack",description:"Offline role training tracks, labs, instructor guidance, and exam export controls.",minTier:"pro",roles:["founder","operator","support","sales"]},{id:"support_ops",title:"Support Operations Pack",description:"Support intake, severity matrix, escalation ladder, and triage workflow controls.",minTier:"pro",roles:["founder","support","operator"]},{id:"buyer_journey",title:"Buyer Evaluation Journey",description:"Evaluator quickstart and defensible buyer path from first look to approval.",minTier:"pro",roles:["founder","sales","support"]},{id:"pilot_conversion",title:"Pilot Conversion Kit",description:"Evidence-first pilot review templates and expansion planning artifacts.",minTier:"pro",roles:["founder","sales","support"]},{id:"commercial_packages",title:"Commercial Package Matrix",description:"SKU, deployment, support entitlement, and add-on mapping across offerings.",minTier:"pro",roles:["founder","sales","support"]},{id:"field_launch",title:"Field Launch Command Center",description:"One-screen commercialization and deployment readiness tracker with blockers.",minTier:"pro",roles:["founder","sales","support","operator"]},{id:"partner_rollout",title:"Partner Rollout Console",description:"Partner activation checklist, readiness scoring, blocker queue, and handoff summary export.",minTier:"pro",roles:["founder","sales","support"]},{id:"buyer_ops",title:"Buyer Ops Automation",description:"Stage-aware buyer follow-up generation with timeline and stale-evaluator controls.",minTier:"pro",roles:["founder","sales","support"]},{id:"demo_to_pilot",title:"Demo-to-Pilot Engine",description:"Demo outcome capture, pilot-fit scorecard, and conversion decision workflow.",minTier:"pro",roles:["founder","sales","support"]},{id:"pilot_expansion",title:"Pilot Expansion Command",description:"Pilot milestone tracking and expansion proposal generation from evidence inputs.",minTier:"pro",roles:["founder","sales","support"]},{id:"renewal_risk",title:"Renewal Risk Console",description:"Renewal timeline, explainable risk scoring, and retention intervention summaries.",minTier:"pro",roles:["founder","sales","support"]},{id:"launch_week",title:"Launch Week Command Discipline",description:"Live launch-day checklist, escalation board, and end-of-day command exports.",minTier:"pro",roles:["founder","sales","support","operator"]},{id:"followup_generator",title:"Proof-Backed Follow-Up",description:"Generate stage-aware follow-up drafts grounded in explicit proof references.",minTier:"pro",roles:["founder","sales","support"]},{id:"field_feedback",title:"Field Feedback Routing",description:"Capture and classify field feedback for routing to product/support/docs/training queues.",minTier:"pro",roles:["founder","sales","support","operator"]},{id:"partner_certification",title:"Partner Certification Hub",description:"Formal partner certification, enablement assignment, recertification warnings, and registry export.",minTier:"pro",roles:["founder","sales","support"]},{id:"managed_services",title:"Managed Services Console",description:"Multi-account managed operations with health, drift, and escalation visibility.",minTier:"pro",roles:["founder","support","operator"]},{id:"strategic_account",title:"Strategic Account Orchestration",description:"Stakeholder maps, blockers, and evidence-linked expansion hypotheses for key accounts.",minTier:"pro",roles:["founder","sales","support"]},{id:"portfolio_rollout",title:"Portfolio Rollout Planner",description:"Cross-site/account rollout stage matrix with dependency and strain visibility.",minTier:"pro",roles:["founder","support","operator"]},{id:"revenue_ops",title:"Revenue Operations Console",description:"Pipeline-to-revenue, SKU mix, and expansion/renewal signal views.",minTier:"pro",roles:["founder","sales","support"]},{id:"channel_expansion",title:"Channel Expansion Planner",description:"Channel model scorecards, enablement gaps, and launch package readiness planning.",minTier:"pro",roles:["founder","sales","support"]},{id:"cross_account_renewal",title:"Cross-Account Renewal Matrix",description:"Renewal timing, risk overlays, and intervention planning across accounts.",minTier:"pro",roles:["founder","sales","support"]},{id:"executive_scale",title:"Executive Scale Dashboard",description:"Founder/exec one-screen summary for partner, account, rollout, revenue, and renewal scale posture.",minTier:"pro",roles:["founder","sales","support","operator"]},{id:"ecosystem_portfolio",title:"Ecosystem Portfolio Console",description:"Operate product/service/channel portfolio lines with attachment path and health visibility.",minTier:"pro",roles:["founder","sales","support"]},{id:"service_line",title:"Service Line Operating Layer",description:"Service line catalog, capacity, utilization, and health operations view.",minTier:"pro",roles:["founder","support","operator"]},{id:"partner_network_governance",title:"Partner Network Governance",description:"Network-wide tier, compliance, and governance-state command view.",minTier:"pro",roles:["founder","sales","support"]},{id:"global_planning",title:"Global Account & Region Planning",description:"Region-fit overlays and phased global planning across account/deployment realities.",minTier:"pro",roles:["founder","sales","support"]},{id:"ecosystem_revenue",title:"Ecosystem Revenue Mix Planner",description:"Revenue mix, margin proxy, and partner/support overlays across ecosystem lines.",minTier:"pro",roles:["founder","sales","support"]},{id:"board_operating_pack",title:"Board / Investor Operating Pack",description:"Generate sober board/investor operating packs with evidence-linked appendix context.",minTier:"pro",roles:["founder"]},{id:"licensed_operator",title:"Licensed Operator Framework",description:"Controlled licensed-operator launch framework tied to training/certification/governance requirements.",minTier:"pro",roles:["founder","support"]},{id:"ecosystem_command",title:"Ecosystem Command Center",description:"Top-level ecosystem command summary with drill-down into all Δ18 systems.",minTier:"pro",roles:["founder","sales","support","operator"]},{id:"shift_console",title:"Shift Console",description:"Role-aware handoff console with signed shift summaries.",minTier:"pro",roles:["founder","operator","support","sales"]},{id:"incident_mode",title:"Incident Mode",description:"Declare and manage degraded/critical incidents with playbook execution.",minTier:"pro",roles:["founder","operator","support","security"]},{id:"policy_rollout",title:"Policy Rollout",description:"Signed fleet policy rollout preview, apply, and rollback history.",minTier:"enterprise",roles:["founder","operator","support","security"]},{id:"offline_update_packs",title:"Offline Update Packs",description:"Verify offline update packs and assign/promote update rings per node.",minTier:"enterprise",roles:["founder","operator","support","security"]},{id:"mission_scheduler",title:"Mission Scheduler",description:"NodeChain mission templates, schedules, dry-run controls, and run history.",minTier:"enterprise",roles:["founder","operator","support"]},{id:"sales_console",title:"Enterprise Sales Console",description:"Pipeline stages, pilots, procurement blockers, renewals, and deal progression.",minTier:"pro",capability:"enterprise_sales_console",roles:["founder","sales","support"]},{id:"pilot_kit",title:"Pilot Program Kit",description:"Generate customer-tailored pilot materials and reusable deployment packet artifacts.",minTier:"pro",capability:"pilot_kit_generator",roles:["founder","sales","support"]},{id:"white_label",title:"White-Label / OEM",description:"Signed branding profile import and local profile enforcement preview.",minTier:"enterprise",capability:"white_label_mode",roles:["founder","support"]},{id:"partner_console",title:"Partner Operations",description:"Deal registration, ownership, margins, and co-branded reseller assets.",minTier:"enterprise",capability:"partner_ops_console",roles:["founder","sales","support"]},{id:"certifications",title:"Certification Center",description:"Local training tracks, quizzes, and signed certificate exports.",minTier:"pro",capability:"certification_center",roles:["founder","operator","support"]},{id:"board_console",title:"Board / Investor Pack",description:"Monthly operating report generation from imported local metrics bundles.",minTier:"enterprise",capability:"board_reporting_console",roles:["founder"]},{id:"enterprise_policy",title:"Deployment Policy Suite",description:"Signed enterprise policy bundle import and runtime enforcement controls.",minTier:"enterprise",capability:"enterprise_policy_suite",roles:["founder","support"]},{id:"customer_success",title:"Customer Success Workspace",description:"Onboarding health, risk alerts, support trend mapping, and renewal posture.",minTier:"enterprise",capability:"customer_success_console",roles:["founder","support","sales"]},{id:"ecosystem_launcher",title:"Ecosystem Launcher",description:"Role-aware command center for core, marketplace, support, and GTM modules.",minTier:"free",roles:["founder","sales","support","operator"]},{id:"expansion_planner",title:"Strategic Expansion Planner",description:"Weighted scoring for net-new products and enterprise growth bets.",minTier:"pro",capability:"expansion_planner",roles:["founder","sales"]}];function x1(t){const r=String(t||"").trim().toLowerCase();return r==="enterprise"?"enterprise":r==="pro"?"pro":"free"}function F0(t,r,n,s=[]){const a=t.roles.includes(r),o=x1(n),l=eu[o]>=eu[t.minTier],c=t.capability?Array.isArray(s)&&s.includes(t.capability):!0;return a&&l&&c}function f1(t,r,n=[]){return B0.filter(s=>F0(s,t,r,n))}const U0="neuralshell_ecosystem_role_v1",z0=[{id:"founder",label:"Founder"},{id:"sales",label:"Sales"},{id:"support",label:"Support"},{id:"operator",label:"Operator"}],b1=new Set(["mission_control","fleet_control","recovery_center","appliance_console","airgap_operations","trust_fabric","hardware_appliance","courier_transfer","continuity_drills","procurement_command","tamper_simulation","institutional_command","demo_flow","deployment_program","training_delivery","support_ops","buyer_journey","pilot_conversion","commercial_packages","field_launch","partner_rollout","buyer_ops","demo_to_pilot","pilot_expansion","renewal_risk","launch_week","followup_generator","field_feedback","partner_certification","managed_services","strategic_account","portfolio_rollout","revenue_ops","channel_expansion","cross_account_renewal","executive_scale","ecosystem_portfolio","service_line","partner_network_governance","global_planning","ecosystem_revenue","board_operating_pack","licensed_operator","ecosystem_command","shift_console","incident_mode","policy_rollout","offline_update_packs","mission_scheduler","enterprise_policy"]);function h1(){if(typeof window>"u"||!window.localStorage)return"founder";const t=String(window.localStorage.getItem(U0)||"").trim().toLowerCase();return z0.some(r=>r.id===t)?t:"founder"}function g1({role:t,tierId:r,moduleCount:n}){return e.jsxs("section",{"data-testid":"ecosystem-home",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Ecosystem Command Center"}),e.jsx("div",{className:"text-[11px] text-slate-300",children:"ProofForge ecosystem mode links enterprise sales, partner ops, certification workflows, policy enforcement, and board reporting into one local-first surface."}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.1em] text-slate-500",children:"Role"}),e.jsx("div",{className:"text-[13px] text-slate-100 font-bold",children:t})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.1em] text-slate-500",children:"Tier"}),e.jsx("div",{className:"text-[13px] text-slate-100 font-bold",children:r||"free"})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.1em] text-slate-500",children:"Modules"}),e.jsx("div",{className:"text-[13px] text-slate-100 font-bold",children:n})]})]}),e.jsx("div",{className:"rounded-lg border border-white/10 bg-black/20 p-3 text-[10px] font-mono text-slate-400",children:"Use role + tier controls to validate access boundaries for Sales, Support, Founder, and Operator views."})]})}function y1({open:t,onClose:r,capabilities:n=[],tierId:s="free",onOpenMissionControl:a,onOpenFleetControl:o,onOpenRecoveryCenter:l,onOpenApplianceConsole:c,onOpenAirGapOperations:u,onOpenTrustFabric:x,onOpenHardwareAppliance:p,onOpenCourierTransfer:d,onOpenContinuityDrills:m,onOpenProcurementCommand:f,onOpenTamperSimulation:b,onOpenInstitutionalCommand:h,onOpenDemoFlow:g,onOpenDeploymentProgram:y,onOpenTrainingDelivery:P,onOpenSupportOps:A,onOpenBuyerJourney:C,onOpenPilotConversion:w,onOpenCommercialPackages:j,onOpenFieldLaunch:E,onOpenPartnerRollout:N,onOpenBuyerOps:_,onOpenDemoToPilot:S,onOpenPilotExpansion:R,onOpenRenewalRisk:$,onOpenLaunchWeek:U,onOpenFollowupGenerator:I,onOpenFieldFeedback:D,onOpenPartnerCertification:z,onOpenManagedServices:F,onOpenStrategicAccount:J,onOpenPortfolioRollout:ee,onOpenRevenueOps:ie,onOpenChannelExpansion:ye,onOpenCrossAccountRenewal:pe,onOpenExecutiveScale:K,onOpenEcosystemPortfolio:H,onOpenServiceLine:W,onOpenPartnerNetworkGovernance:Z,onOpenGlobalPlanning:ce,onOpenEcosystemRevenue:fe,onOpenBoardOperatingPack:me,onOpenLicensedOperator:ke,onOpenEcosystemCommand:Pe,onOpenShiftConsole:_e,onOpenIncidentMode:ne,onOpenPolicyRollout:we,onOpenOfflineUpdates:Be,onOpenMissionScheduler:re,applianceModeEnabled:ae=!1}){const[M,V]=i.useState(()=>h1()),[G,te]=i.useState("ecosystem_launcher");i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(U0,M)},[M]);const de=i.useMemo(()=>{const be=f1(M,s,n);return ae?be.filter(Q=>b1.has(Q.id)):be},[ae,n,M,s]);i.useEffect(()=>{de.some(be=>be.id===G)||te(de[0]?de[0].id:"ecosystem_launcher")},[de,G]);const L=de.find(be=>be.id===G)||null;return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[95] bg-black/55 backdrop-blur-sm",onClick:r}),e.jsxs("aside",{"data-testid":"ecosystem-launcher",className:"fixed inset-x-4 top-16 bottom-4 z-[96] rounded-2xl border border-cyan-400/30 bg-slate-950 shadow-[0_20px_80px_rgba(0,0,0,0.65)] overflow-hidden flex min-h-0",children:[e.jsxs("div",{className:"w-72 border-r border-white/10 bg-black/35 p-3 flex flex-col gap-3 overflow-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Ecosystem Launcher"}),e.jsx("div",{className:"text-[9px] text-slate-500 font-mono",children:"Role-aware navigation"})]}),e.jsx("button",{type:"button","data-testid":"ecosystem-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:text-white hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-2",children:[e.jsx("label",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500 font-mono",children:"Role"}),e.jsx("select",{"data-testid":"ecosystem-role-select",value:M,onChange:be=>V(be.target.value),className:"mt-1 w-full bg-slate-900 border border-white/10 rounded px-2 py-1 text-[10px] font-mono text-slate-200",children:z0.map(be=>e.jsx("option",{value:be.id,children:be.label},be.id))}),e.jsxs("div",{className:"mt-1 text-[9px] text-slate-500 font-mono",children:["Tier ",String(s||"free")]})]}),e.jsx("div",{className:"space-y-1",children:de.map(be=>e.jsxs("button",{type:"button","data-testid":`ecosystem-module-${be.id}`,onClick:()=>te(be.id),className:`w-full text-left px-2.5 py-2 rounded-lg border text-[10px] font-mono ${G===be.id?"border-cyan-300/40 bg-cyan-500/15 text-cyan-100":"border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/10"}`,children:[e.jsx("div",{className:"font-bold uppercase tracking-[0.1em]",children:be.title}),e.jsx("div",{className:"text-[9px] text-slate-500 mt-0.5",children:be.description})]},be.id))}),e.jsx("div",{className:"pt-2 border-t border-white/10 space-y-1",children:B0.filter(be=>!F0(be,M,s,n)).map(be=>e.jsxs("div",{"data-testid":`ecosystem-module-locked-${be.id}`,className:"px-2 py-1.5 rounded border border-white/10 bg-white/[0.02] text-[9px] font-mono text-slate-500",children:[be.title," · locked (",be.minTier,")"]},`locked-${be.id}`))})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-4",children:[!L&&e.jsx("div",{className:"text-[11px] font-mono text-slate-500",children:"No module available for this role/tier."}),L&&L.id==="ecosystem_launcher"&&e.jsx(g1,{role:M,tierId:String(s||"free"),moduleCount:de.length}),L&&L.id==="mission_control"&&e.jsxs("section",{"data-testid":"ecosystem-mission-control-entry",className:"rounded-2xl border border-blue-300/30 bg-blue-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-blue-200 font-bold",children:"Mission Control Runtime Cockpit"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Launch the live runtime command center with provider, vault, proof, policy, update, and watchdog state in one view."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-mission-control-btn",onClick:()=>{typeof a=="function"&&a()},className:"px-3 py-2 rounded-lg border border-blue-200/35 bg-blue-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/30",children:"Open Mission Control"})]}),L&&L.id==="fleet_control"&&e.jsxs("section",{"data-testid":"ecosystem-fleet-control-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Fleet Control"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open the multi-node fleet panel to import offline bundles, compare node posture, and drill into node-level event feeds."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-fleet-control-btn",onClick:()=>{typeof o=="function"&&o()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Fleet Control"})]}),L&&L.id==="recovery_center"&&e.jsxs("section",{"data-testid":"ecosystem-recovery-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Recovery Center"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Generate signed backup bundles, verify restore artifacts, and apply staged or safe-mode recovery."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-recovery-btn",onClick:()=>{typeof l=="function"&&l()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Recovery Center"})]}),L&&L.id==="appliance_console"&&e.jsxs("section",{"data-testid":"ecosystem-appliance-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Appliance Console"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open hardened appliance controls for relay, policy distribution, update gating, and support ingest posture."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-appliance-btn",onClick:()=>{typeof c=="function"&&c()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Appliance Console"})]}),L&&L.id==="airgap_operations"&&e.jsxs("section",{"data-testid":"ecosystem-airgap-entry",className:"rounded-2xl border border-slate-300/30 bg-slate-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-slate-100 font-bold",children:"Air-Gapped Operations"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open controlled transfer-station workflows for offline artifacts with verification gates and air-gap lock controls."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-airgap-btn",onClick:()=>{typeof u=="function"&&u()},className:"px-3 py-2 rounded-lg border border-slate-300/35 bg-slate-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-slate-100 hover:bg-slate-500/30",children:"Open Air-Gapped Operations"})]}),L&&L.id==="trust_fabric"&&typeof x=="function"&&e.jsxs("section",{"data-testid":"ecosystem-trust-fabric-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"PKI Trust Fabric"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open local certificate authority controls, lifecycle operations, and trust-chain export view."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-trust-fabric-btn",onClick:()=>{typeof x=="function"&&x()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Trust Fabric"})]}),L&&L.id==="hardware_appliance"&&typeof p=="function"&&e.jsxs("section",{"data-testid":"ecosystem-hardware-appliance-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Hardware Appliance Program"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open profile manager for provisioning, appliance health simulation, and decommission exports."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-hardware-appliance-btn",onClick:()=>{typeof p=="function"&&p()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Hardware Appliance"})]}),L&&L.id==="courier_transfer"&&e.jsxs("section",{"data-testid":"ecosystem-courier-transfer-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Offline Evidence Courier"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open transfer chain controls for package quarantine, receipt verification, and release gates."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-courier-transfer-btn",onClick:()=>{typeof d=="function"&&d()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Courier Transfer"})]}),L&&L.id==="continuity_drills"&&typeof m=="function"&&e.jsxs("section",{"data-testid":"ecosystem-continuity-drills-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Continuity Drills"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open drill scheduling, readiness scorecard, and continuity evidence export workflows."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-continuity-drills-btn",onClick:()=>{typeof m=="function"&&m()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-100/30",children:"Open Continuity Drills"})]}),L&&L.id==="procurement_command"&&e.jsxs("section",{"data-testid":"ecosystem-procurement-command-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Procurement Command Center"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open buyer/security review pack controls with version delta generation."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-procurement-command-btn",onClick:()=>{typeof f=="function"&&f()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Procurement Center"})]}),L&&L.id==="tamper_simulation"&&e.jsxs("section",{"data-testid":"ecosystem-tamper-simulation-entry",className:"rounded-2xl border border-rose-300/30 bg-rose-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-rose-100 font-bold",children:"Tamper Simulation Mode"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open sandboxed simulation workflows for detection and response drills."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-tamper-simulation-btn",onClick:()=>{typeof b=="function"&&b()},className:"px-3 py-2 rounded-lg border border-rose-200/35 bg-rose-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-rose-100 hover:bg-rose-500/30",children:"Open Tamper Simulation"})]}),L&&L.id==="institutional_command"&&e.jsxs("section",{"data-testid":"ecosystem-institutional-command-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Institutional Command Console"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open one-screen institutional posture summary with direct drill-down controls."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-institutional-command-btn",onClick:()=>{typeof h=="function"&&h()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Institutional Command"})]}),L&&L.id==="demo_flow"&&typeof g=="function"&&e.jsxs("section",{"data-testid":"ecosystem-demo-flow-entry",className:"rounded-2xl border border-emerald-300/30 bg-emerald-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-emerald-100 font-bold",children:"Institutional Demo Flow"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Launch deterministic demo mode with seeded state and guided presenter flow."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-demo-flow-btn",onClick:()=>{typeof g=="function"&&g()},className:"px-3 py-2 rounded-lg border border-emerald-200/35 bg-emerald-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/30",children:"Open Demo Flow"})]}),L&&L.id==="deployment_program"&&e.jsxs("section",{"data-testid":"ecosystem-deployment-program-entry",className:"rounded-2xl border border-blue-300/30 bg-blue-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-blue-100 font-bold",children:"Deployment Program Pack"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open deployment runbooks and preflight/post-install validation controls."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-deployment-program-btn",onClick:()=>{typeof y=="function"&&y()},className:"px-3 py-2 rounded-lg border border-blue-200/35 bg-blue-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/30",children:"Open Deployment Program"})]}),L&&L.id==="training_delivery"&&e.jsxs("section",{"data-testid":"ecosystem-training-delivery-entry",className:"rounded-2xl border border-emerald-300/30 bg-emerald-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-emerald-100 font-bold",children:"Training Delivery Pack"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open role-based offline training bundle generation and lab history."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-training-delivery-btn",onClick:()=>{typeof P=="function"&&P()},className:"px-3 py-2 rounded-lg border border-emerald-200/35 bg-emerald-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/30",children:"Open Training Delivery"})]}),L&&L.id==="support_ops"&&e.jsxs("section",{"data-testid":"ecosystem-support-ops-entry",className:"rounded-2xl border border-amber-300/30 bg-amber-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-amber-100 font-bold",children:"Support Operations Pack"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open support intake, severity matrix, and triage queue controls."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-support-ops-btn",onClick:()=>{typeof A=="function"&&A()},className:"px-3 py-2 rounded-lg border border-amber-200/35 bg-amber-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100 hover:bg-amber-500/30",children:"Open Support Ops"})]}),L&&L.id==="buyer_journey"&&e.jsxs("section",{"data-testid":"ecosystem-buyer-journey-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Buyer Evaluation Journey"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open evaluator quickstart and defensible buyer path summary."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-buyer-journey-btn",onClick:()=>{typeof C=="function"&&C()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Buyer Journey"})]}),L&&L.id==="pilot_conversion"&&typeof w=="function"&&e.jsxs("section",{"data-testid":"ecosystem-pilot-conversion-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Pilot Conversion Kit"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open proof-of-value and expansion planning workflows for pilot conversion."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-pilot-conversion-btn",onClick:()=>{typeof w=="function"&&w()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Pilot Conversion"})]}),L&&L.id==="commercial_packages"&&e.jsxs("section",{"data-testid":"ecosystem-commercial-packages-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Commercial Package Matrix"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open SKU, deployment, and support entitlement alignment surface."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-commercial-packages-btn",onClick:()=>{typeof j=="function"&&j()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Commercial Packages"})]}),L&&L.id==="field_launch"&&typeof E=="function"&&e.jsxs("section",{"data-testid":"ecosystem-field-launch-entry",className:"rounded-2xl border border-blue-300/30 bg-blue-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-blue-100 font-bold",children:"Field Launch Command Center"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open launch-day commercialization and deployment readiness dashboard."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-field-launch-btn",onClick:()=>{typeof E=="function"&&E()},className:"px-3 py-2 rounded-lg border border-blue-200/35 bg-blue-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/30",children:"Open Field Launch"})]}),L&&L.id==="partner_rollout"&&e.jsxs("section",{"data-testid":"ecosystem-partner-rollout-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Partner Rollout Console"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Track partner activation, readiness scoring, blocker queue, and handoff exports."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-partner-rollout-btn",onClick:()=>{typeof N=="function"&&N()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Partner Rollout"})]}),L&&L.id==="buyer_ops"&&e.jsxs("section",{"data-testid":"ecosystem-buyer-ops-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Buyer Ops Automation"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Generate stage-aware follow-up packs and maintain buyer timeline discipline."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-buyer-ops-btn",onClick:()=>{typeof _=="function"&&_()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Buyer Ops"})]}),L&&L.id==="demo_to_pilot"&&e.jsxs("section",{"data-testid":"ecosystem-demo-to-pilot-entry",className:"rounded-2xl border border-emerald-300/30 bg-emerald-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-emerald-100 font-bold",children:"Demo-to-Pilot Engine"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Capture demo outcomes, score pilot fit, and trigger pilot launch packs."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-demo-to-pilot-btn",onClick:()=>{typeof S=="function"&&S()},className:"px-3 py-2 rounded-lg border border-emerald-200/35 bg-emerald-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/30",children:"Open Demo-to-Pilot"})]}),L&&L.id==="pilot_expansion"&&e.jsxs("section",{"data-testid":"ecosystem-pilot-expansion-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Pilot Expansion Command"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Convert pilot outcomes into expansion proposals with deployment phase mapping."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-pilot-expansion-btn",onClick:()=>{typeof R=="function"&&R()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Pilot Expansion"})]}),L&&L.id==="renewal_risk"&&e.jsxs("section",{"data-testid":"ecosystem-renewal-risk-entry",className:"rounded-2xl border border-amber-300/30 bg-amber-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-amber-100 font-bold",children:"Renewal Risk Console"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Monitor renewal timelines, explain risk scoring, and export intervention plans."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-renewal-risk-btn",onClick:()=>{typeof $=="function"&&$()},className:"px-3 py-2 rounded-lg border border-amber-200/35 bg-amber-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100 hover:bg-amber-500/30",children:"Open Renewal Risk"})]}),L&&L.id==="launch_week"&&typeof U=="function"&&e.jsxs("section",{"data-testid":"ecosystem-launch-week-entry",className:"rounded-2xl border border-blue-300/30 bg-blue-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-blue-100 font-bold",children:"Launch Week Command Discipline"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Run launch-day checklist, escalations, priorities, and end-of-day command exports."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-launch-week-btn",onClick:()=>{typeof U=="function"&&U()},className:"px-3 py-2 rounded-lg border border-blue-200/35 bg-blue-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/30",children:"Open Launch Week"})]}),L&&L.id==="followup_generator"&&e.jsxs("section",{"data-testid":"ecosystem-followup-generator-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Proof-Backed Follow-Up"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Create stage-aware follow-up drafts with explicit evidence references and deltas."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-followup-generator-btn",onClick:()=>{typeof I=="function"&&I()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Follow-Up Generator"})]}),L&&L.id==="field_feedback"&&e.jsxs("section",{"data-testid":"ecosystem-field-feedback-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Field Feedback Routing"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Capture structured field notes and route them into product/support/docs/training queues."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-field-feedback-btn",onClick:()=>{typeof D=="function"&&D()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Field Feedback"})]}),L&&L.id==="partner_certification"&&e.jsxs("section",{"data-testid":"ecosystem-partner-certification-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Partner Certification Hub"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Manage partner certification tracks, recertification warnings, and co-sell readiness exports."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-partner-certification-btn",onClick:()=>{typeof z=="function"&&z()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Partner Certification"})]}),L&&L.id==="managed_services"&&typeof F=="function"&&e.jsxs("section",{"data-testid":"ecosystem-managed-services-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Managed Services Console"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Run operator-network account health, escalation, and drift management across managed accounts."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-managed-services-btn",onClick:()=>{typeof F=="function"&&F()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Managed Services"})]}),L&&L.id==="strategic_account"&&typeof J=="function"&&e.jsxs("section",{"data-testid":"ecosystem-strategic-account-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Strategic Account Orchestration"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Orchestrate stakeholder maps, blockers, and evidence-linked expansion hypotheses for key accounts."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-strategic-account-btn",onClick:()=>{typeof J=="function"&&J()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Strategic Account"})]}),L&&L.id==="portfolio_rollout"&&typeof ee=="function"&&e.jsxs("section",{"data-testid":"ecosystem-portfolio-rollout-entry",className:"rounded-2xl border border-blue-300/30 bg-blue-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-blue-100 font-bold",children:"Portfolio Rollout Planner"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Coordinate rollout stages, dependency hotspots, and resource strain across accounts and sites."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-portfolio-rollout-btn",onClick:()=>{typeof ee=="function"&&ee()},className:"px-3 py-2 rounded-lg border border-blue-200/35 bg-blue-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/30",children:"Open Portfolio Rollout"})]}),L&&L.id==="revenue_ops"&&typeof ie=="function"&&e.jsxs("section",{"data-testid":"ecosystem-revenue-ops-entry",className:"rounded-2xl border border-emerald-300/30 bg-emerald-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-emerald-100 font-bold",children:"Revenue Operations Console"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Review pipeline-to-revenue conversion, SKU mix, and expansion-vs-renewal posture from local data."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-revenue-ops-btn",onClick:()=>{typeof ie=="function"&&ie()},className:"px-3 py-2 rounded-lg border border-emerald-200/35 bg-emerald-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/30",children:"Open Revenue Ops"})]}),L&&L.id==="channel_expansion"&&typeof ye=="function"&&e.jsxs("section",{"data-testid":"ecosystem-channel-expansion-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Channel Expansion Planner"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Plan channel models, readiness gaps, and enablement priorities for controlled growth."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-channel-expansion-btn",onClick:()=>{typeof ye=="function"&&ye()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Channel Expansion"})]}),L&&L.id==="cross_account_renewal"&&typeof pe=="function"&&e.jsxs("section",{"data-testid":"ecosystem-cross-account-renewal-entry",className:"rounded-2xl border border-amber-300/30 bg-amber-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-amber-100 font-bold",children:"Cross-Account Renewal Matrix"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Visualize renewal urgency and intervention planning across multiple accounts in one matrix."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-cross-account-renewal-btn",onClick:()=>{typeof pe=="function"&&pe()},className:"px-3 py-2 rounded-lg border border-amber-200/35 bg-amber-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100 hover:bg-amber-500/30",children:"Open Cross-Account Renewal"})]}),L&&L.id==="executive_scale"&&typeof K=="function"&&e.jsxs("section",{"data-testid":"ecosystem-executive-scale-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Executive Scale Dashboard"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open one-screen executive scale operations view with partner, account, rollout, and revenue signals."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-executive-scale-btn",onClick:()=>{typeof K=="function"&&K()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Executive Scale"})]}),L&&L.id==="ecosystem_portfolio"&&typeof H=="function"&&e.jsxs("section",{"data-testid":"ecosystem-portfolio-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Ecosystem Portfolio Console"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Operate portfolio lines and attachment paths across product, services, support, and channels."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-ecosystem-portfolio-btn",onClick:()=>{typeof H=="function"&&H()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Ecosystem Portfolio"})]}),L&&L.id==="service_line"&&typeof W=="function"&&e.jsxs("section",{"data-testid":"ecosystem-service-line-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Service Line Operating Layer"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Manage service-line capacity, utilization, and operating health for delivery discipline."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-service-line-btn",onClick:()=>{typeof W=="function"&&W()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Service Line Console"})]}),L&&L.id==="partner_network_governance"&&typeof Z=="function"&&e.jsxs("section",{"data-testid":"ecosystem-partner-network-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Partner Network Governance"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Track tier governance, compliance posture, and escalation/reactivation flows across the partner network."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-partner-network-governance-btn",onClick:()=>{typeof Z=="function"&&Z()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Partner Network Governance"})]}),L&&L.id==="global_planning"&&typeof ce=="function"&&e.jsxs("section",{"data-testid":"ecosystem-global-planning-entry",className:"rounded-2xl border border-blue-300/30 bg-blue-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-blue-100 font-bold",children:"Global Account & Region Planning"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Plan global account and region expansion using deployment, compliance, and channel-fit overlays."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-global-planning-btn",onClick:()=>{typeof ce=="function"&&ce()},className:"px-3 py-2 rounded-lg border border-blue-200/35 bg-blue-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/30",children:"Open Global Planning"})]}),L&&L.id==="ecosystem_revenue"&&e.jsxs("section",{"data-testid":"ecosystem-ecosystem-revenue-entry",className:"rounded-2xl border border-emerald-300/30 bg-emerald-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-emerald-100 font-bold",children:"Ecosystem Revenue Mix Planner"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Optimize ecosystem revenue mix across product, services, support, and partner-sourced streams."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-ecosystem-revenue-btn",onClick:()=>{typeof fe=="function"&&fe()},className:"px-3 py-2 rounded-lg border border-emerald-200/35 bg-emerald-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/30",children:"Open Ecosystem Revenue"})]}),L&&L.id==="board_operating_pack"&&typeof me=="function"&&e.jsxs("section",{"data-testid":"ecosystem-board-operating-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Board / Investor Operating Pack"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Generate board operating packs with risk framing and evidence-linked appendix references."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-board-operating-pack-btn",onClick:()=>{typeof me=="function"&&me()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Board Operating Pack"})]}),L&&L.id==="licensed_operator"&&typeof ke=="function"&&e.jsxs("section",{"data-testid":"ecosystem-licensed-operator-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Licensed Operator Framework"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Prepare controlled licensed/regional operator launch packs with governance prerequisites."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-licensed-operator-btn",onClick:()=>{typeof ke=="function"&&ke()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Licensed Operator Framework"})]}),L&&L.id==="ecosystem_command"&&typeof Pe=="function"&&e.jsxs("section",{"data-testid":"ecosystem-ecosystem-command-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Ecosystem Command Center"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open top-level ecosystem command surface with portfolio, network, service, planning, and revenue posture."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-ecosystem-command-btn",onClick:()=>{typeof Pe=="function"&&Pe()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Ecosystem Command"})]}),L&&L.id==="shift_console"&&e.jsxs("section",{"data-testid":"ecosystem-shift-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Shift Console"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open role-based shift operations, handoff notes, and signed summary exports."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-shift-btn",onClick:()=>{typeof _e=="function"&&_e()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Shift Console"})]}),L&&L.id==="incident_mode"&&e.jsxs("section",{"data-testid":"ecosystem-incident-entry",className:"rounded-2xl border border-rose-300/30 bg-rose-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-rose-100 font-bold",children:"Incident Mode"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open incident workflow to capture timeline, attach nodes, apply playbooks, and export incident bundles."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-incident-btn",onClick:()=>{typeof ne=="function"&&ne()},className:"px-3 py-2 rounded-lg border border-rose-200/35 bg-rose-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-rose-100 hover:bg-rose-500/30",children:"Open Incident Mode"})]}),L&&L.id==="policy_rollout"&&e.jsxs("section",{"data-testid":"ecosystem-policy-rollout-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Policy Rollout"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Launch signed policy rollout controls with diff preview and rollback history."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-policy-rollout-btn",onClick:()=>{typeof we=="function"&&we()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Policy Rollout"})]}),L&&L.id==="offline_update_packs"&&e.jsxs("section",{"data-testid":"ecosystem-offline-updates-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Offline Update Packs"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Verify signed update packs, assign node rings, and promote update lanes with explicit control."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-offline-updates-btn",onClick:()=>{typeof Be=="function"&&Be()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Offline Updates"})]}),L&&L.id==="mission_scheduler"&&e.jsxs("section",{"data-testid":"ecosystem-mission-scheduler-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Mission Scheduler"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Run NodeChain mission templates with schedules, dry-run controls, and mission history visibility."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-mission-scheduler-btn",onClick:()=>{typeof re=="function"&&re()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Mission Scheduler"})]}),L&&L.id==="sales_console"&&e.jsx(Bw,{}),L&&L.id==="pilot_kit"&&e.jsx(Fw,{}),L&&L.id==="white_label"&&e.jsx(Qw,{}),L&&L.id==="partner_console"&&e.jsx(t1,{}),L&&L.id==="certifications"&&e.jsx(s1,{}),L&&L.id==="board_console"&&e.jsx(i1,{}),L&&L.id==="enterprise_policy"&&e.jsx(l1,{}),L&&L.id==="customer_success"&&e.jsx(d1,{}),L&&L.id==="expansion_planner"&&e.jsx(m1,{})]})]})]}):null}function w1(t){const r=String(t||"grey").toLowerCase();return r==="green"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":r==="amber"?"border-amber-300/40 bg-amber-500/10 text-amber-100":r==="red"?"border-rose-300/40 bg-rose-500/10 text-rose-100":r==="blue"||r==="cyan"?"border-cyan-300/35 bg-cyan-500/10 text-cyan-100":"border-slate-300/20 bg-slate-500/10 text-slate-200"}function ir({title:t,subtitle:r,statusLabel:n,tone:s="grey",rows:a=[],testId:o=""}){return e.jsxs("article",{"data-testid":o||void 0,"aria-label":t,className:"rounded-2xl border border-white/10 bg-black/35 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:t}),r?e.jsx("div",{className:"text-[10px] text-slate-500 font-mono mt-0.5",children:r}):null]}),e.jsx("div",{className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${w1(s)}`,children:n||"unknown"})]}),e.jsx("div",{className:"grid grid-cols-1 gap-1.5",children:(Array.isArray(a)?a:[]).map(l=>e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[10px] font-mono",children:[e.jsx("span",{className:"text-slate-500",children:l.label}),e.jsx("span",{className:"text-slate-200 text-right break-all",children:l.value})]},l.id))})]})}function v1({vaultState:t,onPromptSave:r,onOpenSettings:n}){const s=t&&typeof t=="object"?t:{},a=!!s.locked;return e.jsxs("section",{"data-testid":"vault-panel-plus","aria-label":"Vault Panel Plus",className:"rounded-2xl border border-white/10 bg-black/35 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"VaultPanel+"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Local profile custody, restore posture, and policy binding."})]}),e.jsx("div",{className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${a?"border-amber-300/40 bg-amber-500/10 text-amber-100":"border-emerald-300/30 bg-emerald-500/10 text-emerald-100"}`,children:a?"locked":"unlocked"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1.5 text-[10px] font-mono",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-slate-500",children:"Active Profile"}),e.jsx("span",{className:"text-slate-200 break-all",children:String(s.activeProfile||"default")})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-slate-500",children:"Import/Export"}),e.jsx("span",{className:"text-slate-200 break-all",children:String(s.exportImportStatus||"idle")})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-slate-500",children:"Policy Bound"}),e.jsx("span",{className:"text-slate-200",children:s.policyBound?"yes":"no"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"vault-panel-plus-save-btn",onClick:r,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Prompt Vault Save"}),e.jsx("button",{type:"button","data-testid":"vault-panel-plus-settings-btn",onClick:n,className:"px-2.5 py-1.5 rounded border border-white/10 bg-white/5 text-[10px] font-mono uppercase tracking-[0.14em] text-slate-200 hover:bg-white/10",children:"Settings"})]})]})}const Me=Object.freeze({STABLE:"stable",PILOT:"pilot",EXPERIMENTAL:"experimental",INTERNAL:"internal"}),tu=Object.freeze({[Me.STABLE]:"Stable",[Me.PILOT]:"Pilot",[Me.EXPERIMENTAL]:"Experimental",[Me.INTERNAL]:"Internal"}),j1=Object.freeze({[Me.STABLE]:"maturity-label-stable",[Me.PILOT]:"maturity-label-pilot",[Me.EXPERIMENTAL]:"maturity-label-experimental",[Me.INTERNAL]:"maturity-label-internal"});function ru(t,r={}){const n=!!(r.internalGtmMode||r.devUnlock),s=!!r.includeExperimental;switch(t){case Me.STABLE:return!0;case Me.PILOT:return n;case Me.EXPERIMENTAL:return n&&s;case Me.INTERNAL:return n;default:return!1}}const k1={[Me.STABLE]:"border-emerald-400/35 bg-emerald-500/10 text-emerald-100",[Me.PILOT]:"border-amber-400/35 bg-amber-500/10 text-amber-100",[Me.EXPERIMENTAL]:"border-violet-400/35 bg-violet-500/10 text-violet-100",[Me.INTERNAL]:"border-slate-400/35 bg-slate-500/10 text-slate-200"};function N1({maturity:t=Me.STABLE,className:r=""}){const n=tu[t]?t:Me.STABLE;return e.jsx("span",{"data-testid":j1[n],"data-maturity":n,className:`inline-flex items-center px-1.5 py-0.5 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${k1[n]} ${r}`,children:tu[n]})}function ba({onOpen:t,testId:r,label:n,className:s}){return typeof t!="function"?null:e.jsx("button",{type:"button","data-testid":r,onClick:t,className:s,children:n})}function S1(t){return t?"green":"red"}function Fi(t){const r=String(t||"info").toLowerCase();return r==="critical"?"red":r==="warning"||r==="degraded"?"amber":r==="info"?"blue":"grey"}function nu(t){const r=String(t||"").trim();if(!r)return"n/a";const n=new Date(r);return Number.isNaN(n.getTime())?r:n.toLocaleString()}function C1({open:t,onClose:r,runtimeState:n,events:s,onOpenSettings:a,onOpenFleet:o,onOpenRecovery:l,onOpenAppliance:c,onOpenAirGap:u,onOpenTrustFabric:x,onOpenHardwareAppliance:p,onOpenCourierTransfer:d,onOpenContinuityDrills:m,onOpenProcurementCommand:f,onOpenTamperSimulation:b,onOpenInstitutionalCommand:h,onOpenDemoFlow:g,onOpenDeploymentProgram:y,onOpenTrainingDelivery:P,onOpenSupportOps:A,onOpenBuyerJourney:C,onOpenPilotConversion:w,onOpenCommercialPackages:j,onOpenFieldLaunch:E,onOpenPartnerRollout:N,onOpenBuyerOps:_,onOpenDemoToPilot:S,onOpenPilotExpansion:R,onOpenRenewalRisk:$,onOpenLaunchWeek:U,onOpenFollowupGenerator:I,onOpenFieldFeedback:D,onOpenPartnerCertification:z,onOpenManagedServices:F,onOpenStrategicAccount:J,onOpenPortfolioRollout:ee,onOpenRevenueOps:ie,onOpenChannelExpansion:ye,onOpenCrossAccountRenewal:pe,onOpenExecutiveScale:K,onOpenEcosystemPortfolio:H,onOpenServiceLine:W,onOpenPartnerNetworkGovernance:Z,onOpenGlobalPlanning:ce,onOpenEcosystemRevenue:fe,onOpenBoardOperatingPack:me,onOpenLicensedOperator:ke,onOpenEcosystemCommand:Pe,onOpenShift:_e,onOpenIncidentMode:ne,onOpenPolicyRollout:we,onOpenOfflineUpdates:Be,onOpenMissionScheduler:re,onOpenNodeChain:ae,onOpenWatchdog:M,onOpenFirstBoot:V,onOpenSplitWorkspace:G,showInternalSurfaces:te=!1}){if(!t)return null;const de=n&&typeof n=="object"?n:{},L=Array.isArray(s)?s.slice(-80).reverse():[],be=de.providerHealth||{},Q=de.vaultState||{},We=de.proofEngine||{},B=de.relayState||{},oe=de.collabVoiceState||{},xe=de.policyState||{},Re=de.updateLane||{},De=de.sealIdentity||{},tt=de.watchdog||{};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[120] bg-black/60 backdrop-blur-sm",onClick:r}),e.jsxs("section",{"data-testid":"mission-control","aria-label":"Mission Control",className:"fixed inset-x-4 top-16 bottom-4 z-[121] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.7)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-[0.18em] text-cyan-300 font-bold flex items-center gap-2",children:["Mission Control",e.jsx(N1,{maturity:te?Me.INTERNAL:Me.STABLE})]}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Runtime cockpit, authority feed, and control rails."})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap justify-end",children:[e.jsx(ba,{testId:"mission-control-open-fleet-btn",onOpen:o,label:"Fleet",className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20"}),e.jsx(ba,{testId:"mission-control-open-recovery-btn",onOpen:l,label:"Recovery",className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20"}),e.jsx(ba,{testId:"mission-control-open-appliance-btn",onOpen:c,label:"Appliance",className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20"}),e.jsx(ba,{testId:"mission-control-open-airgap-btn",onOpen:u,label:"AirGap",className:"px-2.5 py-1.5 rounded border border-slate-300/30 bg-slate-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-slate-100 hover:bg-slate-500/20"}),typeof x=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-trust-fabric-btn",onClick:x,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"PKI"}),typeof p=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-hardware-appliance-btn",onClick:p,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Hardware"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-courier-transfer-btn",onClick:d,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Courier"}),typeof m=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-continuity-drills-btn",onClick:m,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Drills"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-procurement-command-btn",onClick:f,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Procurement"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-tamper-simulation-btn",onClick:b,className:"px-2.5 py-1.5 rounded border border-rose-300/30 bg-rose-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-rose-100 hover:bg-rose-500/20",children:"Simulate"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-institutional-command-btn",onClick:h,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Institutional"}),typeof g=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-demo-flow-btn",onClick:g,className:"px-2.5 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/20",children:"Demo"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-deployment-program-btn",onClick:y,className:"px-2.5 py-1.5 rounded border border-blue-300/30 bg-blue-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/20",children:"Deploy"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-training-delivery-btn",onClick:P,className:"px-2.5 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/20",children:"Training"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-support-ops-btn",onClick:A,className:"px-2.5 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100 hover:bg-amber-500/20",children:"Support"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-buyer-journey-btn",onClick:C,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Buyer"}),typeof w=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-pilot-conversion-btn",onClick:w,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Pilot"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-commercial-packages-btn",onClick:j,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Commercial"}),typeof E=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-field-launch-btn",onClick:E,className:"px-2.5 py-1.5 rounded border border-blue-300/30 bg-blue-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/20",children:"Launch"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-partner-rollout-btn",onClick:N,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Partner"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-buyer-ops-btn",onClick:_,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"BuyerOps"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-demo-to-pilot-btn",onClick:S,className:"px-2.5 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/20",children:"D2P"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-pilot-expansion-btn",onClick:R,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Expand"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-renewal-risk-btn",onClick:$,className:"px-2.5 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100 hover:bg-amber-500/20",children:"Renewal"}),typeof U=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-launch-week-btn",onClick:U,className:"px-2.5 py-1.5 rounded border border-blue-300/30 bg-blue-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/20",children:"LaunchWeek"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-followup-generator-btn",onClick:I,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"FollowUp"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-field-feedback-btn",onClick:D,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Feedback"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-partner-certification-btn",onClick:z,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Certify"}),typeof F=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-managed-services-btn",onClick:F,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Managed"}),typeof J=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-strategic-account-btn",onClick:J,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Strategic"}),typeof ee=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-portfolio-rollout-btn",onClick:ee,className:"px-2.5 py-1.5 rounded border border-blue-300/30 bg-blue-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/20",children:"Portfolio"}),typeof ie=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-revenue-ops-btn",onClick:ie,className:"px-2.5 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/20",children:"Revenue"}),typeof ye=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-channel-expansion-btn",onClick:ye,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Channel"}),typeof pe=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-cross-account-renewal-btn",onClick:pe,className:"px-2.5 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100 hover:bg-amber-500/20",children:"Renewal+"}),typeof K=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-executive-scale-btn",onClick:K,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"ExecScale"}),typeof H=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-ecosystem-portfolio-btn",onClick:H,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Portfolio+"}),typeof W=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-service-line-btn",onClick:W,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Services"}),typeof Z=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-partner-network-governance-btn",onClick:Z,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"PartnerNet"}),typeof ce=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-global-planning-btn",onClick:ce,className:"px-2.5 py-1.5 rounded border border-blue-300/30 bg-blue-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/20",children:"Global"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-ecosystem-revenue-btn",onClick:fe,className:"px-2.5 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/20",children:"RevMix"}),typeof me=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-board-operating-pack-btn",onClick:me,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"BoardOps"}),typeof ke=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-licensed-operator-btn",onClick:ke,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Operator"}),typeof Pe=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-ecosystem-command-btn",onClick:Pe,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"EcoCmd"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-shift-btn",onClick:_e,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Shift"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-incident-btn",onClick:ne,className:"px-2.5 py-1.5 rounded border border-rose-300/30 bg-rose-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-rose-100 hover:bg-rose-500/20",children:"Incident"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-policy-rollout-btn",onClick:we,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Rollout"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-offline-updates-btn",onClick:Be,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Updates"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-mission-scheduler-btn",onClick:re,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Missions"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-nodechain-btn",onClick:ae,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"NodeChain"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-watchdog-btn",onClick:M,className:"px-2.5 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100 hover:bg-amber-500/20",children:"Watchdog"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-firstboot-btn",onClick:V,className:"px-2.5 py-1.5 rounded border border-white/10 bg-white/5 text-[10px] font-mono uppercase tracking-[0.14em] text-slate-200 hover:bg-white/10",children:"First Boot"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-splitworkspace-btn",onClick:G,className:"px-2.5 py-1.5 rounded border border-blue-300/30 bg-blue-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/20",children:"Split Workspace"}),e.jsx("button",{type:"button","data-testid":"mission-control-close-btn","aria-label":"Close mission control",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10 flex items-center justify-center",children:"✕"})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-3",children:[e.jsx(ir,{testId:"mission-card-provider-health",title:"Provider Health",subtitle:"Bridge + model posture",statusLabel:be.online?"healthy":"offline",tone:S1(!!be.online),rows:[{id:"provider",label:"Provider",value:String(be.activeProvider||"ollama")},{id:"model",label:"Model",value:String(be.model||"llama3")},{id:"latency",label:"Latency",value:be.latencyMs==null?"n/a":`${be.latencyMs}ms`},{id:"sweep",label:"Last Sweep",value:String(be.lastSweepResult||"unknown")}]}),e.jsx(v1,{vaultState:Q,onPromptSave:()=>{window.dispatchEvent(new window.CustomEvent("neuralshell:prompt-vault-save"))},onOpenSettings:a}),e.jsx(ir,{testId:"mission-card-proof-engine",title:"Proof Engine",subtitle:"Proof run state and bundle parity",statusLabel:String(We.lastProofStatus||"idle"),tone:String(We.lastProofStatus||"").toLowerCase().includes("fail")?"red":"blue",rows:[{id:"proof-status",label:"Last Status",value:String(We.lastProofStatus||"idle")},{id:"proof-stage",label:"Stage",value:String(We.currentStage||"idle")},{id:"proof-hash",label:"Bundle Hash",value:String(We.lastBundleHash||"n/a")},{id:"proof-parity",label:"Parity",value:String(We.parityState||"unknown")}]}),e.jsx(ir,{testId:"mission-card-relay-state",title:"Relay State",subtitle:"Proof relay + channel mapping",statusLabel:B.enabled?"enabled":"disabled",tone:B.relayError?"red":B.enabled?"blue":"grey",rows:[{id:"relay-enabled",label:"Enabled",value:B.enabled?"yes":"no"},{id:"relay-channel",label:"Channel",value:String(B.mappedChannel||"local-only")},{id:"relay-last",label:"Last Send",value:String(B.lastRelaySend||"n/a")},{id:"relay-error",label:"Error",value:String(B.relayError||"none")}]}),e.jsx(ir,{testId:"mission-card-collab-state",title:"Collab / Voice State",subtitle:"Peers, room, RTT, session health",statusLabel:String(oe.sessionHealth||"unknown"),tone:String(oe.sessionHealth||"")==="healthy"?"green":"amber",rows:[{id:"collab-peers",label:"Peers",value:String(oe.peersActive??0)},{id:"collab-room",label:"Room",value:String(oe.currentRoom||"default")},{id:"collab-rtt",label:"Voice RTT",value:oe.voiceRttMs==null?"n/a":`${oe.voiceRttMs}ms`},{id:"collab-health",label:"Session",value:String(oe.sessionHealth||"unknown")}]}),e.jsx(ir,{testId:"mission-card-policy-state",title:"Policy / Enforcement",subtitle:"Enterprise policy + provider boundaries",statusLabel:String(xe.activePolicyProfile||"none"),tone:xe.offlineOnly?"green":"amber",rows:[{id:"policy-active",label:"Profile",value:String(xe.activePolicyProfile||"none")},{id:"policy-ring",label:"Update Ring",value:String(xe.updateRing||"stable")},{id:"policy-offline",label:"Offline Only",value:xe.offlineOnly?"true":"false"},{id:"policy-approved",label:"Providers",value:(xe.approvedProviders||[]).join(", ")||"n/a"}]}),e.jsx(ir,{testId:"mission-card-update-lane",title:"Update Lane",subtitle:"Signature verification + staged updates",statusLabel:String(Re.signatureState||"unknown"),tone:String(Re.signatureState||"")==="verified"?"green":"amber",rows:[{id:"update-version",label:"Version",value:String(Re.currentVersion||"unknown")},{id:"update-check",label:"Last Check",value:String(Re.lastUpdateCheck||"n/a")},{id:"update-signature",label:"Signature",value:String(Re.signatureState||"unknown")},{id:"update-staged",label:"Staged",value:Re.stagedUpdateAvailable?"available":"none"}]}),e.jsx(ir,{testId:"mission-card-seal-identity",title:"SEAL / Identity",subtitle:"Machine trust + branding profile",statusLabel:String(De.machineTrust||"unknown"),tone:String(De.machineTrust||"")==="auditor"?"amber":"green",rows:[{id:"seal-id",label:"Seal",value:String(De.sealIdentity||"unknown")},{id:"seal-trust",label:"Trust",value:String(De.machineTrust||"unknown")},{id:"seal-branding",label:"White-Label",value:String(De.whiteLabelProfile||"default")}]}),e.jsx(ir,{testId:"mission-card-watchdog",title:"Runtime Watchdog",subtitle:"Supervisor liveness and bridge process",statusLabel:String(tt.status||"unknown"),tone:String(tt.status||"")==="running"?"green":"amber",rows:[{id:"watchdog-status",label:"Status",value:String(tt.status||"unknown")},{id:"watchdog-pid",label:"PID",value:tt.pid==null?"n/a":String(tt.pid)},{id:"watchdog-ws",label:"WS Bridge",value:tt.wsRunning?"running":"stopped"},{id:"watchdog-refreshed",label:"Refreshed",value:nu(de.refreshedAt||"")}]})]}),e.jsxs("section",{"data-testid":"mission-control-event-feed","aria-label":"Runtime Event Feed",className:"rounded-2xl border border-white/10 bg-black/30 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Runtime Event Feed"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Chronological stream of proofs, policy changes, relay/runtime alerts, and watchdog events."})]}),e.jsxs("div",{className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${Fi(String(L[0]&&L[0].severity?L[0].severity:"info"))==="red"?"border-rose-300/40 bg-rose-500/10 text-rose-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100"}`,children:[L.length," events"]})]}),e.jsxs("div",{className:"max-h-64 overflow-auto space-y-1.5 pr-1",children:[L.map(Ge=>e.jsxs("article",{className:`rounded-lg border px-2 py-1.5 ${Fi(String(Ge.severity||"info"))==="red"?"border-rose-300/40 bg-rose-500/10":Fi(String(Ge.severity||"info"))==="amber"?"border-amber-300/40 bg-amber-500/10":"border-white/10 bg-black/30"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-200",children:String(Ge.type||"runtime.event")}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:nu(String(Ge.at||""))})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:[String(Ge.source||"runtime")," · ",String(Ge.severity||"info")]})]},Ge.id)),L.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No runtime events captured yet."})]})]})]})]})]})}const vn=[{id:"provider-sweep-success-prompt-vault-save",label:"Provider sweep success -> prompt vault save",enabled:!0,eventType:"provider.sweep.passed",actions:[{type:"prompt_vault_save"},{type:"write_audit_log",payload:{event:"provider_sweep_passed"}}]},{id:"proof-pass-share-and-snapshot",label:"Proof pass -> offer share badge + snapshot",enabled:!0,eventType:"proof.passed",actions:[{type:"share_proof_badge"},{type:"snapshot_state"}]},{id:"policy-change-log-and-snapshot",label:"Policy change -> log + snapshot",enabled:!0,eventType:"policy.changed",actions:[{type:"write_audit_log",payload:{event:"policy_changed"}},{type:"snapshot_state"}]},{id:"update-verify-failed-block-apply",label:"Update verification fail -> disable auto-apply + alert",enabled:!0,eventType:"update.verification.failed",actions:[{type:"block_update_apply"},{type:"show_alert",payload:{severity:"critical",message:"Update signature verification failed."}}]},{id:"relay-failure-x3-disable-relay",label:"Relay failure x3 -> disable relay + alert",enabled:!0,eventType:"relay.failed",conditions:{relayFailureThreshold:3},actions:[{type:"disable_relay"},{type:"show_alert",payload:{severity:"degraded",message:"Relay disabled after repeated failures."}}]},{id:"collab-disconnect-mark-degraded",label:"Collab disconnect -> mark session degraded",enabled:!0,eventType:"collab.peer.left",actions:[{type:"show_alert",payload:{severity:"warning",message:"Collab session degraded after peer disconnect."}},{type:"write_audit_log",payload:{event:"collab_peer_left"}}]}];class H0{constructor(r,n={},s=[]){this.rules=Array.isArray(r)?r:[],this.handlers=n,this.logs=[],this.timers=[],this.relayFailedCount=0,this.commandAllowlist=new Set((Array.isArray(s)?s:[]).map(a=>String(a||"")))}setRules(r){this.rules=Array.isArray(r)?r:[],this.stop(),this.start()}getRules(){return this.rules.slice()}getLogs(){return this.logs.slice(-250)}start(){this.stop(),this.rules.forEach(r=>{if(!r.enabled||!Number.isFinite(Number(r.scheduleMs))||Number(r.scheduleMs)<=0)return;const n=window.setInterval(()=>{this.dispatch({type:"nodechain.schedule.tick",at:new Date().toISOString(),payload:{scheduledRuleId:r.id}},!0).catch(()=>{})},Number(r.scheduleMs));this.timers.push(n)})}stop(){this.timers.splice(0).forEach(r=>window.clearInterval(r))}async dispatch(r,n=!1){const s={type:String(r&&r.type?r.type:""),at:String(r&&r.at?r.at:new Date().toISOString()),payload:r&&r.payload&&typeof r.payload=="object"?r.payload:{}};if(!s.type)return[];s.type==="relay.failed"&&(this.relayFailedCount+=1),s.type==="relay.sent"&&(this.relayFailedCount=0);const a=this.rules.filter(l=>!!l.enabled&&String(l.eventType||"")===s.type),o=[];for(const l of a){const c=await this.executeRule(l,s,n);this.logs.push(c),o.push(c)}return o}async executeRule(r,n,s){const a={id:`nodechain-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,at:new Date().toISOString(),ruleId:String(r.id||"unknown-rule"),eventType:String(n.type||"unknown-event"),dryRun:!!s,status:"executed",detail:"",actions:[]};if(!this.conditionsPass(r,n))return{...a,status:"skipped",detail:"Conditions not met."};for(const o of Array.isArray(r.actions)?r.actions:[]){const l=String(o&&o.type?o.type:"");if(l){if(s){a.actions.push({type:l,status:"dry-run",detail:"Action simulated."});continue}try{const c=await this.runAction(l,o&&o.payload?o.payload:{});a.actions.push({type:l,status:"ok",detail:c})}catch(c){a.actions.push({type:l,status:"failed",detail:c&&c.message?c.message:String(c)}),a.status="failed",a.detail=`Action ${l} failed.`}}}return a.detail||(a.detail=a.actions.length?`${a.actions.length} action(s) evaluated.`:"No actions configured."),a}conditionsPass(r,n){const s=r&&r.conditions&&typeof r.conditions=="object"?r.conditions:{},a=Number(s.relayFailureThreshold||0);if(a>0&&this.relayFailedCountString(l[u])!==String(x))}async runAction(r,n){if(r==="show_alert")return await Promise.resolve(this.handlers.showAlert&&this.handlers.showAlert(n)),"Alert emitted.";if(r==="open_panel")return await Promise.resolve(this.handlers.openPanel&&this.handlers.openPanel(n)),"Panel opened.";if(r==="share_proof_badge")return await Promise.resolve(this.handlers.shareProofBadge&&this.handlers.shareProofBadge(n)),"Proof badge flow triggered.";if(r==="snapshot_state")return await Promise.resolve(this.handlers.snapshotState&&this.handlers.snapshotState(n)),"State snapshot captured.";if(r==="disable_relay")return await Promise.resolve(this.handlers.disableRelay&&this.handlers.disableRelay(n)),"Relay disabled.";if(r==="block_update_apply")return await Promise.resolve(this.handlers.blockUpdateApply&&this.handlers.blockUpdateApply(n)),"Update apply blocked.";if(r==="prompt_vault_save")return await Promise.resolve(this.handlers.promptVaultSave&&this.handlers.promptVaultSave(n)),"Vault save prompt emitted.";if(r==="write_audit_log")return await Promise.resolve(this.handlers.writeAuditLog&&this.handlers.writeAuditLog(n)),"Audit entry recorded.";if(r==="switch_safe_policy")return await Promise.resolve(this.handlers.switchSafePolicy&&this.handlers.switchSafePolicy(n)),"Safe policy profile applied.";if(r==="run_local_script"){const s=String(n&&n.commandId?n.commandId:"").trim();if(!s||!this.commandAllowlist.has(s))throw new Error(`Command '${s||""}' is not in NodeChain allowlist.`);return await Promise.resolve(this.handlers.runLocalScript&&this.handlers.runLocalScript(n)),`Allowlisted command '${s}' executed.`}throw new Error(`Unsupported NodeChain action type: ${r}`)}}const W0="neuralshell_runtime_event_feed_v1",Il="neuralshell:runtime-event";function _1(t){const r=t&&typeof t=="object"?t:{},n={};return Object.entries(r).forEach(([s,a])=>{const o=String(s||""),l=o.toLowerCase();if(l.includes("token")||l.includes("secret")||l.includes("apikey")||l.includes("password")||l.includes("passphrase")){n[o]="[redacted]";return}n[o]=a}),n}function Pl(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(W0)||"[]");return Array.isArray(t)?t.filter(Boolean):[]}catch{return[]}}function A1(t){typeof window>"u"||!window.localStorage||window.localStorage.setItem(W0,JSON.stringify((Array.isArray(t)?t:[]).slice(-400)))}function X(t,r={},n={}){if(typeof window>"u")return null;const s={id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,at:new Date().toISOString(),type:String(t||"runtime.event"),source:String(n.source||"runtime"),severity:n.severity||"info",payload:_1(r)},a=[...Pl(),s].slice(-400);return A1(a),window.dispatchEvent(new window.CustomEvent(Il,{detail:s})),s}function K0(t){if(typeof window>"u"||typeof t!="function")return()=>{};const r=n=>{const s=n,a=s&&s.detail?s.detail:null;a&&t(a)};return window.addEventListener(Il,r),()=>window.removeEventListener(Il,r)}function E1({rule:t,onChange:r}){const n=t&&typeof t=="object"?t:null;if(!n)return e.jsx("div",{className:"rounded-xl border border-white/10 bg-black/20 p-3 text-[10px] font-mono text-slate-500",children:"Select a rule to edit."});const s=Number(n&&n.conditions&&Number.isFinite(Number(n.conditions.relayFailureThreshold))?Number(n.conditions.relayFailureThreshold):0);return e.jsxs("section",{"data-testid":"nodechain-rule-editor",className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Rule Editor"}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Label",e.jsx("input",{value:String(n.label||""),onChange:a=>r({...n,label:a.target.value}),className:"mt-1 w-full rounded border border-white/10 bg-black/40 px-2 py-1"})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Event Type",e.jsx("input",{value:String(n.eventType||""),onChange:a=>r({...n,eventType:a.target.value}),className:"mt-1 w-full rounded border border-white/10 bg-black/40 px-2 py-1"})]}),e.jsxs("label",{className:"inline-flex items-center gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:!!n.enabled,onChange:a=>r({...n,enabled:!!a.target.checked})}),"Enabled"]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Relay Failure Threshold (0 = disabled)",e.jsx("input",{type:"number",min:"0",value:s,onChange:a=>{const o=Math.max(0,Number(a.target.value||0));r({...n,conditions:{...n.conditions||{},relayFailureThreshold:o}})},className:"mt-1 w-full rounded border border-white/10 bg-black/40 px-2 py-1"})]})]})}const V0="neuralshell_nodechain_rules_v1",I1=["releaseHealth:check","audit:verify","verification:run"],su=["provider.sweep.passed","provider.sweep.failed","vault.unlocked","vault.locked","proof.started","proof.passed","proof.failed","relay.sent","relay.failed","policy.changed","update.verification.failed","collab.peer.joined","collab.peer.left","runtime.watchdog.alert"];function Ui(){if(typeof window>"u"||!window.localStorage)return vn;try{const t=JSON.parse(window.localStorage.getItem(V0)||"[]");return!Array.isArray(t)||!t.length?vn:t}catch{return vn}}function P1({open:t,onClose:r,onSnapshotRequest:n,onOpenPanel:s}){const[a,o]=i.useState(()=>Ui()),[l,c]=i.useState(()=>String(Ui()[0]&&Ui()[0].id||"")),[u,x]=i.useState([]),[p,d]=i.useState(!1),[m,f]=i.useState(su[0]),[b,h]=i.useState(!0),g=i.useRef(null);i.useEffect(()=>{typeof window<"u"&&window.localStorage&&window.localStorage.setItem(V0,JSON.stringify(a||[]))},[a]);const y=i.useCallback(C=>new H0(C||[],{showAlert:j=>{X("nodechain.alert",j||{},{severity:String(j&&j.severity?j.severity:"warning"),source:"nodechain"})},openPanel:j=>{const E=String(j&&j.panel?j.panel:"");typeof s=="function"&&s(E)},shareProofBadge:async()=>{window.api&&window.api.system&&typeof window.api.system.openExternal=="function"&&await window.api.system.openExternal("https://raw.githubusercontent.com/Z3r0DayZion-install/NeuralShell/badges/proof_badge.svg")},snapshotState:async()=>{typeof n=="function"&&await n()},disableRelay:async()=>{if(!(window.api&&window.api.settings&&typeof window.api.settings.get=="function"))return;const j=await window.api.settings.get();await window.api.settings.update({...j||{},proofRelayEnabled:!1})},blockUpdateApply:async()=>{window.api&&window.api.autoUpdate&&typeof window.api.autoUpdate.setPolicy=="function"&&await window.api.autoUpdate.setPolicy({autoApply:!1,blockedBy:"nodechain"})},promptVaultSave:async()=>{window.dispatchEvent(new window.CustomEvent("neuralshell:prompt-vault-save"))},writeAuditLog:async j=>{window.api&&window.api.audit&&typeof window.api.audit.append=="function"&&await window.api.audit.append({event:"nodechain_action",...j||{}})},switchSafePolicy:async()=>{if(!(window.api&&window.api.settings&&typeof window.api.settings.get=="function"))return;const j=await window.api.settings.get();await window.api.settings.update({...j||{},offlineOnlyEnforced:!0,allowRemoteBridge:!1,autoUpdateChannel:"frozen"})},runLocalScript:async j=>{if(!(window.api&&window.api.command&&typeof window.api.command.run=="function"))return;const E=String(j&&j.commandId?j.commandId:"");await window.api.command.run(E,j&&j.args?j.args:[])}},I1),[s,n]);i.useEffect(()=>{const C=y(a);return g.current=C,C.start(),()=>{C.stop(),g.current=null}},[y,a]);const P=async()=>{if(g.current){d(!0);try{const C=await g.current.dispatch({type:m,at:new Date().toISOString(),payload:{source:"manual-trigger"}},b),w=g.current.getLogs();x(w),X("nodechain.manual.dispatch",{eventType:m,dryRun:b,rulesEvaluated:Array.isArray(C)?C.length:0},{source:"nodechain",severity:"info"})}finally{d(!1)}}},A=(a||[]).find(C=>String(C.id||"")===l)||null;return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[122] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"nodechain-panel",className:"fixed inset-x-8 top-20 bottom-8 z-[123] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.7)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"NodeChain Runtime Engine"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Local rule listeners, dry-run simulation, action logs, and allowlisted automation."})]}),e.jsx("button",{type:"button","data-testid":"nodechain-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden grid grid-cols-1 xl:grid-cols-[420px_1fr]",children:[e.jsxs("div",{className:"border-r border-white/10 p-3 overflow-auto space-y-3",children:[e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Manual Event Dispatch"}),e.jsx("select",{"data-testid":"nodechain-event-select",value:m,onChange:C=>f(C.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200",children:su.map(C=>e.jsx("option",{value:C,children:C},C))}),e.jsxs("label",{className:"inline-flex items-center gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:b,onChange:C=>h(!!C.target.checked)}),"Dry-run mode"]}),e.jsx("button",{type:"button","data-testid":"nodechain-run-event-btn",disabled:p,onClick:P,className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 disabled:opacity-60",children:p?"Running...":"Dispatch Event"})]}),e.jsx("div",{className:"space-y-2",children:(a||[]).map(C=>e.jsxs("button",{type:"button","data-testid":`nodechain-rule-${C.id}`,onClick:()=>c(String(C.id||"")),className:`w-full rounded-xl border p-2 text-left ${String(C.id||"")===l?"border-cyan-300/30 bg-cyan-500/10":"border-white/10 bg-black/20 hover:bg-white/5"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:String(C.label||C.id)}),e.jsxs("label",{className:"inline-flex items-center gap-1 text-[9px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:!!C.enabled,onChange:w=>{w.stopPropagation(),o(j=>Array.isArray(j)?j.map(E=>String(E.id||"")===String(C.id||"")?{...E,enabled:!!w.target.checked}:E):j)}}),"enabled"]})]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500 mt-0.5",children:String(C.eventType||"unknown")})]},C.id))})]}),e.jsxs("div",{className:"p-3 overflow-auto space-y-3",children:[e.jsx(E1,{rule:A,onChange:C=>{o(w=>Array.isArray(w)?w.map(j=>String(j.id||"")===String(C.id||"")?C:j):w)}}),e.jsxs("section",{"data-testid":"nodechain-logs",className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Execution Logs"}),e.jsxs("div",{className:"max-h-96 overflow-auto space-y-1.5 pr-1",children:[(u||[]).slice(-120).reverse().map(C=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[10px] font-mono",children:[e.jsx("span",{className:"text-slate-200",children:C.ruleId}),e.jsx("span",{className:"text-slate-500",children:String(C.status||"unknown")})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:[C.eventType," · ",C.at]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:C.detail})]},C.id)),(!u||u.length===0)&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No rule execution logs yet."})]})]})]})]})]})]}):null}function R1(t){const r=String(t||"info").toLowerCase();return r==="critical"?"border-rose-300/40 bg-rose-500/10 text-rose-100":r==="degraded"?"border-amber-300/40 bg-amber-500/10 text-amber-100":r==="warning"?"border-amber-300/30 bg-amber-500/10 text-amber-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100"}function O1({open:t,alerts:r=[],onClose:n,onAcknowledge:s}){return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[124] bg-black/50",onClick:n}),e.jsxs("aside",{"data-testid":"runtime-alerts-drawer","aria-label":"Runtime Alerts",className:"fixed right-4 top-16 bottom-4 z-[125] w-[27.5rem] rounded-2xl border border-amber-300/30 bg-slate-950 shadow-[0_18px_80px_rgba(0,0,0,0.7)] flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-amber-300 font-bold",children:"Runtime Watchdog Alerts"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Sticky failures remain visible until acknowledged."})]}),e.jsx("button",{type:"button","data-testid":"runtime-alerts-close-btn",onClick:n,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3 space-y-2",children:[(Array.isArray(r)?r:[]).map(a=>e.jsxs("article",{className:`rounded-xl border p-3 ${R1(a.severity)}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[10px] font-mono uppercase tracking-[0.14em]",children:String(a.source||"watchdog")}),e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em]",children:String(a.severity||"info")})]}),e.jsx("div",{className:"text-[10px] font-mono mt-1",children:String(a.message||"")}),e.jsx("div",{className:"text-[9px] font-mono opacity-90 mt-1",children:String(a.suggestedAction||"")}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-300 mt-1",children:[String(a.at||""),a.recoveredAt?` · recovered ${a.recoveredAt}`:""]}),e.jsx("div",{className:"mt-2 flex items-center justify-end",children:e.jsx("button",{type:"button","data-testid":`runtime-alert-ack-${a.id}`,onClick:()=>s(a.id),className:"px-2 py-1 rounded border border-white/20 bg-black/25 text-[9px] font-mono uppercase tracking-[0.12em]",children:a.acknowledged?"Acknowledged":"Acknowledge"})})]},a.id)),(!r||r.length===0)&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No active watchdog alerts."})]})]})]}):null}const T1=864e5;function bt(t){const r=new Date(t);return Number.isFinite(r.getTime())?r:null}function _n(t){return t?t.type===Ve.EVENT?bt(t.startAt):t.type===Ve.DEADLINE?bt(t.dueAt):bt(t.remindAt||t.createdAt):null}function G0(t){return t?t.type===Ve.EVENT?bt(t.endAt||t.startAt):_n(t):null}function au(t){const r=t instanceof Date?t:bt(t);return r?[r.getFullYear(),String(r.getMonth()+1).padStart(2,"0"),String(r.getDate()).padStart(2,"0")].join("-"):""}function oc(t,r){const n=_n(t),s=_n(r),a=n?n.getTime():Number.MAX_SAFE_INTEGER,o=s?s.getTime():Number.MAX_SAFE_INTEGER;return a!==o?a-o:String(t.title||"").localeCompare(String(r.title||""))}function M1(t=[],r=new Date){const n=au(r);return(Array.isArray(t)?t:[]).filter(s=>au(_n(s))===n).sort(oc)}function ic(t=[],r=new Date,n=5){var o;const s=((o=bt(r))==null?void 0:o.getTime())??Date.now(),a=Math.max(1,Number(n)||5);return(Array.isArray(t)?t:[]).filter(l=>{const c=_n(l);return!c||l.type===Ve.DEADLINE&&l.completed||l.type===Ve.EVENT&&String(l.status||"").toLowerCase()==="cancelled"?!1:(G0(l)||c).getTime()>=s}).sort(oc).slice(0,a)}function D1(t=[],r=new Date){return ic(t.filter(n=>n.type===Ve.EVENT),r,1)[0]||null}function $1(t=[],r=new Date){return ic(t.filter(n=>n.type===Ve.DEADLINE),r,1)[0]||null}function L1(t=[],r=new Date){var s;const n=((s=bt(r))==null?void 0:s.getTime())??Date.now();return(Array.isArray(t)?t:[]).filter(a=>a.type===Ve.DEADLINE&&!a.completed).filter(a=>{const o=bt(a.dueAt);return o&&o.getTime()p.type===Ve.DEADLINE&&!p.completed),s=((x=bt(r))==null?void 0:x.getTime())??Date.now(),a=L1(n,r),o=n.filter(p=>p.priority==="critical"||p.priority==="high"),l=n.filter(p=>{const d=bt(p.dueAt);if(!d)return!1;const m=d.getTime()-s;return m>=0&&m<=T1}),c=a.length*4+o.length*2+l.length;return{severity:c>=8||a.some(p=>p.priority==="critical")?"CRITICAL":c>=4?"HIGH":c>=1?"NORMAL":"LOW",score:c,overdueCount:a.length,criticalCount:o.length,upcomingCount:n.length,dueSoonCount:l.length}}function F1(t=[]){const r=(Array.isArray(t)?t:[]).filter(s=>s.type===Ve.EVENT).map(s=>({item:s,start:bt(s.startAt),end:bt(s.endAt)})).filter(s=>s.start&&s.end&&s.end.getTime()>s.start.getTime()).sort((s,a)=>s.start.getTime()-a.start.getTime()),n=[];for(let s=0;s=r[s].end.getTime());a+=1)n.push([r[s].item,r[a].item]);return n}function U1(t){const r=Math.max(0,Math.round((Number(t)||0)/6e4)),n=Math.floor(r/60),s=r%60;return n<=0?`${s}m`:s===0?`${n}h`:`${n}h ${s}m`}function ou(t){const r=_n(t);if(!r)return"unscheduled";if(t.type===Ve.EVENT){const n=G0(t),s=r.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),a=n?n.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):"";return a?`${s}-${a}`:s}return r.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function z1(){return Lg.map(t=>({...t}))}function H1({calendarItems:t=[],now:r=new Date}){const[n,s]=i.useState(()=>Cn()),[a,o]=i.useState(()=>ur({order:"asc"})),[l,c]=i.useState(r);i.useEffect(()=>(s(Cn()),u0(s)),[]),i.useEffect(()=>{c(r)},[r]),i.useEffect(()=>{const p=window.setInterval(()=>c(new Date),1e3);return()=>window.clearInterval(p)},[]),i.useEffect(()=>(o(ur({order:"asc"})),l0(()=>o(ur({order:"asc"})))),[]);const u=i.useMemo(()=>b0({sessions:n.sessions||[],calendarItems:t,proofTimestamps:a,now:l}),[t,l,n.sessions,a]),x=u.totalSessionMs>0||u.sessionCount>0;return e.jsxs("section",{"data-testid":"chrono-day-summary",className:"rounded-2xl border border-amber-300/15 bg-black/25 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.18em] text-amber-300",children:"Day Summary"}),e.jsxs("div",{className:"mt-1 text-[11px] font-mono text-slate-500",children:[u.date," · ",u.timezone]})]}),e.jsx("div",{"data-testid":"day-summary-proof-trail",className:"rounded-full border border-amber-400/25 bg-amber-500/10 px-3 py-1 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100",children:"Local proof trail"})]}),!x&&e.jsx("div",{className:"mt-3 rounded-xl border border-dashed border-white/10 bg-white/[0.02] p-3 text-[12px] font-mono text-slate-500",children:"No session time recorded today"}),e.jsxs("div",{className:"mt-3 grid gap-2 md:grid-cols-4",children:[e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Operated"}),e.jsx("div",{"data-testid":"day-summary-total-time",className:"mt-1 text-sm font-semibold tabular-nums text-slate-100",children:cr(u.totalSessionMs)})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Active"}),e.jsx("div",{"data-testid":"day-summary-active-time",className:"mt-1 text-sm font-semibold tabular-nums text-slate-100",children:cr(u.activeMs)})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Idle"}),e.jsx("div",{"data-testid":"day-summary-idle-time",className:"mt-1 text-sm font-semibold tabular-nums text-slate-100",children:cr(u.idleMs)})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Top Mode"}),e.jsx("div",{"data-testid":"day-summary-top-mode",className:"mt-1 text-sm font-semibold capitalize text-slate-100",children:u.topMode||"None"})]})]}),e.jsxs("div",{className:"mt-2 grid gap-2 md:grid-cols-4",children:[e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Proof Events"}),e.jsx("div",{"data-testid":"day-summary-proof-events",className:"mt-1 text-sm font-semibold tabular-nums text-slate-100",children:u.proofEventCount})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Deadlines Done"}),e.jsx("div",{"data-testid":"day-summary-deadlines-completed",className:"mt-1 text-sm font-semibold tabular-nums text-slate-100",children:u.deadlinesCompleted})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3 md:col-span-2",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Next Threat"}),e.jsx("div",{"data-testid":"day-summary-next-threat",className:"mt-1 text-sm font-semibold text-slate-100",children:u.nextThreat})]})]})]})}function W1(t){return t.title||String(t.eventType||"proof event").replace(/_/g," ")}function K1({limit:t=8}){const[r,n]=i.useState(()=>ur({order:"asc"}));i.useEffect(()=>(n(ur({order:"asc"})),l0(()=>n(ur({order:"asc"})))),[]);const s=i.useMemo(()=>[...r].reverse().slice(0,t),[r,t]),a=i.useMemo(()=>v0(w0(r)),[r]),o=a.status==="verified"?"Integrity: local chain verified":a.status==="mismatch"?"Integrity: chain mismatch detected":"Integrity: no local chain yet";return e.jsxs("section",{"data-testid":"proof-timeline",className:"rounded-2xl border border-violet-300/15 bg-black/25 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.18em] text-violet-300",children:"Proof Timeline"}),e.jsx("div",{className:"mt-1 text-[11px] font-mono text-slate-500",children:"Local proof trail. Timestamped locally."})]}),e.jsxs("div",{className:"rounded-full border border-violet-400/25 bg-violet-500/10 px-3 py-1 text-[10px] font-mono uppercase tracking-[0.14em] text-violet-100",children:[r.length," event",r.length===1?"":"s"]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-[10px] font-mono text-slate-500",children:[e.jsx("span",{"data-testid":"timeproof-integrity-status",children:o}),e.jsxs("span",{"data-testid":"timeproof-integrity-entry-count",children:[a.entryCount," entries"]})]}),e.jsxs("div",{className:"mt-3 space-y-2",children:[s.length===0&&e.jsx("div",{"data-testid":"proof-timeline-empty",className:"rounded-xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-[12px] font-mono text-slate-500",children:"Proof Timeline — no events recorded yet"}),s.map(l=>e.jsxs("article",{"data-testid":"proof-timeline-event",className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{"data-testid":"proof-timeline-event-title",className:"text-sm font-semibold text-slate-100",children:W1(l)}),e.jsx("div",{className:"mt-1 text-[10px] font-mono text-slate-500",children:l.sessionId?"Linked to session":"Local proof trail"})]}),e.jsx("div",{"data-testid":"proof-timeline-event-time",className:"text-right text-[11px] font-mono tabular-nums text-violet-100",children:l.localLabel})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2 text-[10px] font-mono uppercase tracking-[0.12em] text-slate-500",children:[e.jsx("span",{"data-testid":"proof-timeline-event-source",children:l.source}),l.projectName&&e.jsx("span",{children:l.projectName}),l.details&&e.jsx("span",{className:"normal-case tracking-normal text-slate-400",children:l.details})]})]},l.id))]})]})}function V1(t){return[...t.sessions||[]].sort((r,n)=>n.startedAt.localeCompare(r.startedAt))[0]||null}function zi(t){return t||"Not set"}function hs(t){const r=String(t||"").trim();return r?r.charAt(0).toUpperCase()+r.slice(1):"Focus"}function G1({projectId:t="",projectName:r=""}){const[n,s]=i.useState(()=>Cn()),[a,o]=i.useState(()=>new Date),[l,c]=i.useState($a[0]);i.useEffect(()=>{const j=window.setInterval(()=>o(new Date),1e3);return()=>window.clearInterval(j)},[]),i.useEffect(()=>(s(Cn()),u0(s)),[]);const u=i.useMemo(()=>xs(n),[n]),x=u||V1(n),p=i.useMemo(()=>Or(u,a),[u,a]),d=i.useMemo(()=>cy(n,a),[n,a]),m=i.useMemo(()=>dy(n,a),[n,a]),f=i.useMemo(()=>uy(n,t,a),[n,a,t]),b=String(r||t||"").trim();i.useEffect(()=>{u&&u.mode!==l&&c(u.mode)},[u,l]);const h=i.useCallback(j=>{s(ty(j))},[]),g=i.useCallback((j,E,N,_)=>{!E||!E.id||Yg({eventType:j,source:"sessionhud",projectId:E.projectId||t,projectName:E.projectName||b,sessionId:E.id,title:N,details:_})},[t,b]),y=i.useCallback(()=>{if(u)return;const j=ny(n,{projectId:t,projectName:b,mode:l,source:"local"},new Date),E=xs(j);h(j),g("session_started",E,"Session started",`Mode: ${hs((E==null?void 0:E.mode)||l)}`)},[u,n,h,t,b,g,l]),P=i.useCallback(()=>{if(!u)return;const j=sy(n,u.id,new Date),E=xs(j);h(j),g("session_paused",E,"Session paused",`Mode: ${hs((E==null?void 0:E.mode)||u.mode)}`)},[u,n,h,g]),A=i.useCallback(()=>{if(!u)return;const j=ay(n,u.id,new Date),E=xs(j);h(j),g("session_resumed",E,"Session resumed",`Mode: ${hs((E==null?void 0:E.mode)||u.mode)}`)},[u,n,h,g]),C=i.useCallback(()=>{if(!u)return;const j=oy(n,u.id,new Date),E=(j.sessions||[]).find(_=>_.id===u.id),N=Or(E,new Date);h(j),g("session_ended",E,"Session ended",`${cr(N.activeDurationMs)} active · Mode: ${hs((E==null?void 0:E.mode)||u.mode)}`)},[u,n,h,g]),w=i.useCallback(j=>{const E=j.target.value;if(c(E),u){const N=iy(n,u.id,E),_=xs(N);h(N),g("mode_changed",_,"Mode changed",`Mode: ${hs(E)}`)}},[u,n,h,g]);return e.jsxs("section",{"data-testid":"session-hud",className:"rounded-2xl border border-emerald-300/15 bg-black/25 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.18em] text-emerald-300",children:"SessionHUD"}),e.jsx("div",{className:"mt-1 text-[11px] font-mono text-slate-500",children:"Local TimeLedger, no telemetry."})]}),e.jsxs("div",{"data-testid":"session-current-run",className:"rounded-xl border border-emerald-400/25 bg-emerald-500/10 px-3 py-2 text-right",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-emerald-200",children:"Current run"}),e.jsx("div",{className:"mt-1 text-xl font-semibold tabular-nums text-emerald-50",children:u?cr(p.activeDurationMs):"No active session"})]})]}),e.jsxs("div",{className:"mt-4 grid gap-2 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Today"}),e.jsx("div",{"data-testid":"session-today-total",className:"mt-1 text-sm font-semibold tabular-nums text-slate-100",children:cr(d)})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Week"}),e.jsx("div",{"data-testid":"session-week-total",className:"mt-1 text-sm font-semibold tabular-nums text-slate-100",children:cr(m)})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:b?"Project":"Project context"}),e.jsx("div",{"data-testid":"session-project-total",className:"mt-1 text-sm font-semibold tabular-nums text-slate-100",children:b?cr(f):"No project"})]})]}),e.jsxs("div",{className:"mt-3 grid gap-2 md:grid-cols-[1fr_auto_auto_auto_auto]",children:[e.jsx("select",{"data-testid":"session-mode-select",value:l,onChange:w,className:"rounded-lg border border-white/10 bg-black/35 px-3 py-2 text-[12px] text-slate-100 outline-none",children:$a.map(j=>e.jsx("option",{value:j,children:j},j))}),e.jsx("button",{type:"button","data-testid":"session-start",disabled:!!u,onClick:y,className:"rounded-lg border border-emerald-400/30 bg-emerald-500/10 px-3 py-2 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 disabled:cursor-not-allowed disabled:opacity-40",children:"Start Session"}),e.jsx("button",{type:"button","data-testid":"session-pause",disabled:!u||u.status!=="active",onClick:P,className:"rounded-lg border border-white/10 bg-white/[0.03] px-3 py-2 text-[10px] font-mono uppercase tracking-[0.14em] text-slate-200 disabled:cursor-not-allowed disabled:opacity-40",children:"Pause"}),e.jsx("button",{type:"button","data-testid":"session-resume",disabled:!u||u.status!=="paused",onClick:A,className:"rounded-lg border border-white/10 bg-white/[0.03] px-3 py-2 text-[10px] font-mono uppercase tracking-[0.14em] text-slate-200 disabled:cursor-not-allowed disabled:opacity-40",children:"Resume"}),e.jsx("button",{type:"button","data-testid":"session-end",disabled:!u,onClick:C,className:"rounded-lg border border-rose-400/25 bg-rose-500/10 px-3 py-2 text-[10px] font-mono uppercase tracking-[0.14em] text-rose-100 disabled:cursor-not-allowed disabled:opacity-40",children:"End Session"})]}),e.jsxs("div",{className:"mt-3 grid gap-2 text-[10px] font-mono text-slate-500 md:grid-cols-3",children:[e.jsxs("div",{"data-testid":"session-started-at",children:["Started UTC: ",zi(x==null?void 0:x.startedAt)]}),e.jsxs("div",{"data-testid":"session-last-active-at",children:["Last active UTC: ",zi(x==null?void 0:x.lastActiveAt)]}),e.jsxs("div",{"data-testid":"session-ended-at",children:["Ended UTC: ",zi(x==null?void 0:x.endedAt)]})]})]})}function Hi(t=new Date){const r=t instanceof Date?t:new Date(t);return Number.isFinite(r.getTime())?[r.getFullYear(),String(r.getMonth()+1).padStart(2,"0"),String(r.getDate()).padStart(2,"0")].join("-"):""}function ha(t){const r=t instanceof Date?t:new Date(t);return Number.isFinite(r.getTime())?[r.getFullYear(),String(r.getMonth()+1).padStart(2,"0"),String(r.getDate()).padStart(2,"0")].join("-")+`T${String(r.getHours()).padStart(2,"0")}:${String(r.getMinutes()).padStart(2,"0")}`:""}function ga(t,r){return new Date(t.getTime()+r*6e4)}function iu(t){return t.type===Ve.EVENT?"border-cyan-400/25 bg-cyan-500/10 text-cyan-100":t.priority==="critical"||t.priority==="high"?"border-rose-400/30 bg-rose-500/10 text-rose-100":t.source==="task"?"border-violet-400/25 bg-violet-500/10 text-violet-100":"border-amber-400/25 bg-amber-500/10 text-amber-100"}function lu(t){return t.type===Ve.EVENT?"EVENT":t.type===Ve.REMINDER?"REMINDER":"DEADLINE"}function cu(t,r){if(!t)return"No upcoming item";const n=new Date(t.type===Ve.EVENT?t.startAt:t.dueAt||t.remindAt);if(!Number.isFinite(n.getTime()))return t.title;const s=n.getTime()-r.getTime();return`${t.title} in ${U1(s)}`}function J1({workflowId:t}){const[r,n]=i.useState(()=>new Date),[s,a]=i.useState(()=>Da()),[o,l]=i.useState(()=>Qt()),[c,u]=i.useState(()=>et(t)),[x,p]=i.useState(""),[d,m]=i.useState(()=>ha(ga(new Date,30))),[f,b]=i.useState(()=>ha(ga(new Date,60))),[h,g]=i.useState(""),[y,P]=i.useState(()=>Hi(new Date)),[A,C]=i.useState("normal");i.useEffect(()=>{const F=window.setInterval(()=>n(new Date),3e4);return()=>window.clearInterval(F)},[]),i.useEffect(()=>{a(Da()),l(Qt()),u(et(t));const F=Ug(a),J=Lp(l),ee=qa(u,t);return()=>{F(),J(),ee()}},[t]);const w=i.useMemo(()=>e0({events:s,deadlines:o,workpadTasks:(c.tasks||[]).filter(F=>!F.done&&F.dueDate)}),[o,s,c.tasks]),j=i.useMemo(()=>M1(w,r),[w,r]),E=i.useMemo(()=>ic(w,r,5),[w,r]),N=i.useMemo(()=>D1(w,r),[w,r]),_=i.useMemo(()=>$1(w,r),[w,r]),S=i.useMemo(()=>B1(w,r),[w,r]),R=i.useMemo(()=>F1(w),[w]),$=i.useMemo(()=>z1(),[]),U=i.useCallback(()=>{const F=String(x||"").trim(),J=new Date(d),ee=new Date(f);if(!F){ge("Enter an event title","warning");return}if(!Number.isFinite(J.getTime())||!Number.isFinite(ee.getTime())||ee<=J){ge("Choose a valid event window","warning");return}const ie=Fg(s,{id:`event-${Date.now()}`,title:F,startAt:J.toISOString(),endAt:ee.toISOString(),category:"local",status:"confirmed",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()});Bg(ie),a(ie),p(""),m(ha(ga(ee,30))),b(ha(ga(ee,60))),ge("Local event saved","success")},[f,d,x,s]),I=i.useCallback(()=>{const F=String(h||"").trim();if(!F){ge("Enter a deadline title","warning");return}const J=Mp(o,{id:`deadline-${Date.now()}`,title:F,date:y||Hi(r),priority:A});Ta(J),l(J),g(""),ge("Deadline saved","success")},[y,A,h,o,r]),D=i.useCallback(()=>{if(!o.length){ge("No deadlines to export","warning");return}$s(`neuralshell-deadlines-${Date.now()}.ics`,Vb(o)),ge("ICS calendar file downloaded","success")},[o]),z=i.useCallback(()=>{const F=new Date;n(F),P(Hi(F))},[]);return e.jsx("div",{"data-testid":"chrono-hud",className:"h-full min-h-0 overflow-auto bg-[radial-gradient(circle_at_top,rgba(8,145,178,0.18),transparent_34%),#020617] text-slate-100",children:e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("section",{"data-testid":"chrono-now-bar",className:"rounded-2xl border border-cyan-300/25 bg-black/30 p-4 shadow-[0_0_28px_rgba(34,211,238,0.08)]",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-bold uppercase tracking-[0.24em] text-cyan-300",children:[e.jsx(Ux,{size:15}),"ChronoHUD"]}),e.jsx("div",{"data-testid":"chrono-now-zone",className:"mt-2 text-2xl font-semibold tabular-nums text-cyan-50",children:r.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}),e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-[0.12em] text-slate-500",children:r.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"})})]}),e.jsx("button",{type:"button","data-testid":"calendar-today-btn",onClick:z,className:"rounded-lg border border-cyan-400/25 bg-cyan-500/10 px-3 py-2 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/15",children:"Today"})]}),e.jsxs("div",{className:"mt-4 grid gap-2 md:grid-cols-2",children:[e.jsxs("div",{"data-testid":"chrono-next-zone",className:"rounded-xl border border-white/10 bg-white/[0.03] p-3 text-[12px] font-mono text-slate-200",children:[e.jsxs("div",{children:["Next event: ",N?cu(N,r):"none scheduled"]}),e.jsxs("div",{className:"mt-1 text-amber-100",children:["Next deadline: ",_?cu(_,r):"none scheduled"]})]}),e.jsxs("div",{"data-testid":"chrono-later-zone",className:"rounded-xl border border-white/10 bg-white/[0.03] p-3 text-[12px] font-mono text-slate-200",children:["Later: ",E.length," queued mission item",E.length===1?"":"s"]})]})]}),e.jsx(G1,{projectId:t||"",projectName:t||""}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[1fr_1fr]",children:[e.jsx(H1,{calendarItems:w,now:r}),e.jsx(K1,{})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[1fr_1.05fr]",children:[e.jsxs("section",{"data-testid":"chrono-today-timeline",className:"rounded-2xl border border-cyan-300/15 bg-black/25 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-bold uppercase tracking-[0.18em] text-cyan-300",children:[e.jsx(zx,{size:14}),"Today Timeline"]}),e.jsxs("div",{className:"mt-3 space-y-2",children:[j.length===0&&e.jsx("div",{className:"rounded-xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-[12px] font-mono text-slate-500",children:"No mission windows or threat markers today."}),j.map(F=>e.jsxs("article",{className:`rounded-xl border p-3 ${iu(F)}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.16em] opacity-80",children:lu(F)}),e.jsx("div",{className:"mt-1 text-sm font-semibold",children:F.title})]}),e.jsx("div",{className:"text-right text-[11px] font-mono tabular-nums opacity-85",children:ou(F)})]}),F.source==="task"&&e.jsx("div",{className:"mt-2 text-[10px] font-mono uppercase tracking-[0.12em] opacity-70",children:"Workpad due task"})]},`${F.type}-${F.id}`))]})]}),e.jsxs("section",{"data-testid":"chrono-time-radar",className:"rounded-2xl border border-cyan-300/15 bg-black/25 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-bold uppercase tracking-[0.18em] text-cyan-300",children:[e.jsx(Hx,{size:14}),"Time Radar"]}),e.jsxs("div",{"data-testid":"chrono-time-pressure",className:"rounded-full border border-cyan-400/25 bg-cyan-500/10 px-3 py-1 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100",children:["Pressure ",S.severity]})]}),e.jsxs("svg",{viewBox:"0 0 240 150",className:"mt-4 h-40 w-full text-cyan-300",role:"img","aria-label":"Time radar now ring",children:[e.jsx("defs",{children:e.jsxs("radialGradient",{id:"chrono-radar-glow",cx:"50%",cy:"50%",r:"50%",children:[e.jsx("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:"0.22"}),e.jsx("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:"0"})]})}),e.jsx("circle",{cx:"120",cy:"86",r:"60",fill:"url(#chrono-radar-glow)"}),e.jsx("circle",{cx:"120",cy:"86",r:"58",fill:"none",stroke:"currentColor",strokeOpacity:"0.35"}),e.jsx("circle",{cx:"120",cy:"86",r:"34",fill:"none",stroke:"currentColor",strokeOpacity:"0.22"}),e.jsx("line",{x1:"120",y1:"86",x2:"120",y2:"26",stroke:"currentColor",strokeOpacity:"0.55"}),e.jsx("circle",{cx:"120",cy:"26",r:"4",fill:"currentColor"}),e.jsx("circle",{cx:"174",cy:"86",r:"4",fill:N?"#67e8f9":"#334155"}),e.jsx("circle",{cx:"120",cy:"140",r:"4",fill:_?"#fbbf24":"#334155"}),e.jsx("text",{x:"120",y:"88",textAnchor:"middle",className:"fill-cyan-100 text-[10px] font-bold",children:"NOW"}),e.jsx("text",{x:"174",y:"77",textAnchor:"middle",className:"fill-slate-300 text-[8px]",children:"EVENT"}),e.jsx("text",{x:"120",y:"132",textAnchor:"middle",className:"fill-slate-300 text-[8px]",children:"DEADLINE"})]}),e.jsx("div",{"data-testid":"chrono-conflict-alerts",className:"rounded-xl border border-white/10 bg-white/[0.03] p-3 text-[11px] font-mono text-slate-300",children:R.length?`${R.length} schedule conflict${R.length===1?"":"s"} detected`:"No schedule conflicts detected"})]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[1fr_1fr]",children:[e.jsxs("section",{"data-testid":"chrono-mission-queue",className:"rounded-2xl border border-cyan-300/15 bg-black/25 p-4",children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.18em] text-cyan-300",children:"Mission Queue"}),e.jsxs("div",{className:"mt-3 space-y-2",children:[E.length===0&&e.jsx("div",{className:"text-[12px] font-mono text-slate-500",children:"No upcoming mission items."}),E.map(F=>e.jsxs("div",{className:`rounded-xl border p-3 ${iu(F)}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-[9px] font-mono uppercase tracking-[0.16em] opacity-80",children:lu(F)}),e.jsx("span",{className:"text-[10px] font-mono opacity-85",children:ou(F)})]}),e.jsx("div",{className:"mt-1 text-[13px] font-semibold",children:F.title})]},`${F.type}-${F.id}`))]})]}),e.jsxs("section",{"data-testid":"chrono-deadline-pressure",className:"rounded-2xl border border-cyan-300/15 bg-black/25 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-bold uppercase tracking-[0.18em] text-cyan-300",children:[e.jsx(Wx,{size:14}),"Deadline Pressure"]}),e.jsx("div",{className:"mt-3 text-3xl font-semibold text-slate-50",children:S.severity}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-center",children:[e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-2",children:[e.jsx("div",{className:"text-lg font-semibold text-rose-200",children:S.overdueCount}),e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.12em] text-slate-500",children:"Overdue"})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-2",children:[e.jsx("div",{className:"text-lg font-semibold text-amber-200",children:S.criticalCount}),e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.12em] text-slate-500",children:"Critical"})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-2",children:[e.jsx("div",{className:"text-lg font-semibold text-cyan-200",children:S.upcomingCount}),e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.12em] text-slate-500",children:"Upcoming"})]})]})]})]}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-2",children:[e.jsxs("div",{className:"rounded-2xl border border-cyan-300/15 bg-black/25 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-bold uppercase tracking-[0.18em] text-cyan-300",children:[e.jsx(Kx,{size:14}),"Local Event"]}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("input",{"data-testid":"chrono-event-title-input",value:x,onChange:F=>p(F.target.value),placeholder:"Event title",className:"w-full rounded-lg border border-white/10 bg-black/35 px-3 py-2 text-[12px] text-slate-100 outline-none focus:border-cyan-400/40"}),e.jsxs("div",{className:"grid gap-2 md:grid-cols-2",children:[e.jsx("input",{"data-testid":"chrono-event-start-input",type:"datetime-local",value:d,onChange:F=>m(F.target.value),className:"rounded-lg border border-white/10 bg-black/35 px-3 py-2 text-[12px] text-slate-100 outline-none"}),e.jsx("input",{"data-testid":"chrono-event-end-input",type:"datetime-local",value:f,onChange:F=>b(F.target.value),className:"rounded-lg border border-white/10 bg-black/35 px-3 py-2 text-[12px] text-slate-100 outline-none"})]}),e.jsx("button",{type:"button","data-testid":"chrono-add-event-btn",onClick:U,className:"w-full rounded-lg border border-cyan-400/30 bg-cyan-500/10 px-3 py-2 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100",children:"+ Event"})]})]}),e.jsxs("div",{className:"rounded-2xl border border-cyan-300/15 bg-black/25 p-4",children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.18em] text-cyan-300",children:"Local Deadline"}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("input",{"data-testid":"chrono-deadline-title-input",value:h,onChange:F=>g(F.target.value),placeholder:"Deadline title",className:"w-full rounded-lg border border-white/10 bg-black/35 px-3 py-2 text-[12px] text-slate-100 outline-none focus:border-cyan-400/40"}),e.jsxs("div",{className:"grid gap-2 md:grid-cols-[1fr_0.75fr]",children:[e.jsx("input",{"data-testid":"chrono-deadline-date-input",type:"date",value:y,onChange:F=>P(F.target.value),className:"rounded-lg border border-white/10 bg-black/35 px-3 py-2 text-[12px] text-slate-100 outline-none"}),e.jsxs("select",{"data-testid":"chrono-deadline-priority-select",value:A,onChange:F=>C(F.target.value),className:"rounded-lg border border-white/10 bg-black/35 px-3 py-2 text-[12px] text-slate-100 outline-none",children:[e.jsx("option",{value:"high",children:"High"}),e.jsx("option",{value:"normal",children:"Normal"}),e.jsx("option",{value:"low",children:"Low"})]})]}),e.jsx("button",{type:"button","data-testid":"calendar-add-deadline-btn",onClick:I,className:"w-full rounded-lg border border-amber-400/30 bg-amber-500/10 px-3 py-2 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100",children:"+ Deadline"})]})]})]}),e.jsxs("section",{"data-testid":"chrono-provider-truth",className:"rounded-2xl border border-cyan-300/15 bg-black/25 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.18em] text-cyan-300",children:"Provider Truth"}),e.jsxs("button",{type:"button","data-testid":"calendar-export-ics-btn",disabled:!o.length,onClick:D,className:"inline-flex items-center gap-1.5 rounded-lg border border-white/10 bg-white/[0.03] px-3 py-1.5 text-[10px] font-mono uppercase tracking-[0.12em] text-slate-300 disabled:cursor-not-allowed disabled:opacity-50",title:"ICS export remains available through the existing deadline exporter.",children:[e.jsx(pl,{size:12}),"Export ICS"]})]}),e.jsx("div",{className:"mt-3 grid gap-2 md:grid-cols-5",children:$.map(F=>e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[11px] font-semibold text-slate-100",children:F.label}),e.jsx("div",{className:`mt-1 text-[9px] font-mono uppercase tracking-[0.12em] ${F.connected?"text-emerald-300":"text-slate-500"}`,children:F.status})]},F.id))}),e.jsx("div",{className:"mt-3 text-[10px] font-mono text-slate-500",children:"Google and Outlook actions are deep links only when shown elsewhere; no external calendar sync is connected."})]})]})})}function q1({open:t,onClose:r,workflowId:n}){return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[124] bg-black/55",onClick:r}),e.jsxs("aside",{"data-testid":"operator-calendar-drawer","aria-label":"ChronoHUD calendar and deadlines",className:"fixed right-4 top-16 bottom-4 z-[125] w-[min(980px,calc(100vw-2rem))] overflow-hidden rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_18px_80px_rgba(0,0,0,0.7)] flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-cyan-300/15 bg-black/40 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] uppercase tracking-[0.18em] text-cyan-300 font-bold",children:[e.jsx(Vx,{size:14}),"ChronoHUD"]}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500 mt-0.5",children:"Local events + deadlines · provider truth · operator time radar"})]}),e.jsx("button",{type:"button","data-testid":"operator-calendar-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10 shrink-0","aria-label":"Close ChronoHUD",children:"x"})]}),e.jsx(J1,{workflowId:n})]})]}):null}function Y1(t){var s,a;if(!t||!t.metadata)return"";const r=t.metadata;let n=`# ProofForge Trust Report: ${r.name||r.id} +-----END ${t}-----`}function ac(t){return String(t||"").replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"").trim()}async function Jw(t){const r=await window.crypto.subtle.exportKey("spki",t);return R0("PUBLIC KEY",sc(r))}async function qw(t){const r=await window.crypto.subtle.exportKey("pkcs8",t);return R0("PRIVATE KEY",sc(r))}async function Yw(t){const r=Qa(ac(t));return window.crypto.subtle.importKey("spki",r,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"])}async function Zw(t){const r=Qa(ac(t));return window.crypto.subtle.importKey("pkcs8",r,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}async function eo(t="neuralshell_signing_key_v1"){if(!window.crypto||!window.crypto.subtle)throw new Error("WebCrypto is unavailable.");const r=`${t}_public`,n=`${t}_private`,s=window.localStorage?window.localStorage.getItem(r):"",a=window.localStorage?window.localStorage.getItem(n):"";if(s&&a)return{publicKeyPem:s,privateKeyPem:a};const o=await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),c=await Jw(o.publicKey),l=await qw(o.privateKey);return window.localStorage&&(window.localStorage.setItem(r,c),window.localStorage.setItem(n,l)),{publicKeyPem:c,privateKeyPem:l}}async function to(t,r){if(!window.crypto||!window.crypto.subtle)throw new Error("WebCrypto is unavailable.");const n=await Zw(r),s=new window.TextEncoder,a=pr(t),o=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,s.encode(a));return sc(o)}async function Mt(t,r,n){if(!window.crypto||!window.crypto.subtle)throw new Error("WebCrypto is unavailable.");try{const s=await Yw(n),a=new window.TextEncoder,o=pr(t),c=Qa(r);if(await window.crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,c,a.encode(o)))return!0;try{const u=Gw(c,32);return!!await window.crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,u,a.encode(o))}catch{return!1}}catch{return!1}}async function Tr(t){if(!window.crypto||!window.crypto.subtle)throw new Error("WebCrypto is unavailable.");const r=Qa(ac(t)),n=await window.crypto.subtle.digest("SHA-256",r);return`sha256:${Array.from(new Uint8Array(n)).map(a=>a.toString(16).padStart(2,"0")).join("")}`}const O0="neuralshell_branding_profile_active_v1";function _s(t={}){const r=t&&typeof t=="object"?t:{},n=r.branding&&typeof r.branding=="object"?r.branding:{},s=r.policyDefaults&&typeof r.policyDefaults=="object"?r.policyDefaults:{};return{schema:"neuralshell_branding_profile_v1",profileId:String(r.profileId||"unnamed-profile").trim(),displayName:String(r.displayName||r.profileId||"Unnamed Profile").trim(),branding:{productName:String(n.productName||"ProofForge").trim(),logoText:String(n.logoText||n.productName||"ProofForge").trim(),accentColor:String(n.accentColor||"#22d3ee").trim(),supportUrl:String(n.supportUrl||"").trim(),docsUrl:String(n.docsUrl||"").trim(),installerName:String(n.installerName||"").trim()},policyDefaults:{allowRemoteBridge:!!s.allowRemoteBridge,offlineOnly:!!s.offlineOnly,updateRing:String(s.updateRing||"stable").trim().toLowerCase(),allowedProviders:Array.isArray(s.allowedProviders)?s.allowedProviders.map(a=>String(a||"").trim()).filter(Boolean):[]},source:{publisherId:String(r.publisherId||r.sourcePublisherId||"").trim(),appliedAt:new Date().toISOString()}}}function Xw(){if(typeof window>"u"||!window.localStorage)return _s(Ia);try{const t=JSON.parse(window.localStorage.getItem(O0)||"{}");return!t||typeof t!="object"||!t.profileId?_s(Ia):_s(t)}catch{return _s(Ia)}}function Qw(){const[t,r]=i.useState(()=>Xw()),[n,s]=i.useState(""),[a,o]=i.useState(""),c=i.useMemo(()=>{const p=Li&&Array.isArray(Li.publishers)?Li.publishers:[];return new Set(p.map(d=>String(d&&d.fingerprint?d.fingerprint:"").trim()).filter(Boolean))},[]),l=i.useCallback(async p=>{const d=_s(p);r(d),typeof window<"u"&&window.localStorage&&window.localStorage.setItem(O0,JSON.stringify(d)),window.dispatchEvent(new window.CustomEvent("neuralshell:branding-updated",{detail:d})),window.api&&window.api.audit&&typeof window.api.audit.append=="function"&&window.api.audit.append({event:"white_label_profile_applied",profileId:d.profileId,displayName:d.displayName,publisherId:d.source.publisherId,appliedAt:d.source.appliedAt}).catch(()=>{})},[]),u=async p=>{const d=p&&p.target&&p.target.files?p.target.files[0]:null;if(d)try{const m=await pt(d),f=JSON.parse(String(m||"{}")),b=f&&typeof f=="object"?f.payload:null,h=f&&typeof f=="object"?String(f.signature||""):"",g=f&&f.signer&&typeof f.signer=="object"?String(f.signer.publicKeyPem||""):"";if(!b||!h||!g)throw new Error("Signed profile requires payload, signature, and signer public key.");if(!await Mt(b,h,g))throw new Error("Branding profile signature verification failed.");const I=await Tr(g);if(c.size>0&&!c.has(I))throw new Error(`Untrusted branding signer fingerprint: ${I}`);await l({...b,sourcePublisherId:b&&b.publisherId?b.publisherId:""}),s(`Applied signed profile "${b.displayName||b.profileId}" (${I.slice(0,26)}...).`),o("")}catch(m){s(""),o(m&&m.message?m.message:String(m))}},x=async()=>{await l(Ia),s("Restored default ProofForge branding profile."),o("")};return e.jsxs("section",{"data-testid":"branding-overrides",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"White-Label / OEM Mode"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Signed branding profile import with capability-safe policy defaults."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("label",{className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100 cursor-pointer",children:["Import Signed Profile",e.jsx("input",{type:"file",accept:".json,application/json",className:"hidden","data-testid":"branding-overrides-import-input",onChange:u})]}),e.jsx("button",{type:"button","data-testid":"branding-overrides-reset-btn",onClick:x,className:"px-2 py-1 rounded border border-white/10 bg-white/5 text-[9px] uppercase tracking-[0.12em] font-mono text-slate-200",children:"Reset Default"})]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Active Profile"}),e.jsx("div",{className:"text-[13px] text-slate-100 font-bold",children:t.displayName}),e.jsx("div",{className:"text-[10px] text-slate-400 font-mono",children:t.profileId}),e.jsxs("div",{className:"mt-2 grid grid-cols-1 md:grid-cols-2 gap-2 text-[10px] font-mono text-slate-300",children:[e.jsxs("div",{children:["Product: ",t.branding.productName]}),e.jsxs("div",{children:["Logo Text: ",t.branding.logoText]}),e.jsxs("div",{children:["Accent: ",t.branding.accentColor]}),e.jsxs("div",{children:["Update Ring: ",t.policyDefaults.updateRing]}),e.jsxs("div",{children:["Remote Bridge: ",t.policyDefaults.allowRemoteBridge?"enabled":"disabled"]}),e.jsxs("div",{children:["Offline Only: ",t.policyDefaults.offlineOnly?"true":"false"]})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("button",{type:"button","data-testid":"branding-overrides-export-btn",onClick:()=>{je(`neuralshell_active_branding_profile_${Date.now()}.json`,t)},className:"px-2.5 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Export Active Profile"})}),n&&e.jsx("div",{className:"rounded-lg border border-emerald-300/30 bg-emerald-500/10 px-3 py-2 text-[10px] text-emerald-100 font-mono",children:n}),a&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:a})]})}const T0="neuralshell_partner_console_v1";function e1(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(T0)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Bi(t={}){const r=t&&typeof t=="object"?t:{},n=he(r.dealValueUsd||r.dealSize||r.value,0),s=Math.max(0,Math.min(100,he(r.marginPercent||r.margin,20))),a=Math.round(n*s/100);return{id:String(r.id||`partner-deal-${Date.now()}-${Math.random().toString(36).slice(2,7)}`),partnerId:String(r.partnerId||r.resellerId||"PARTNER_UNSET").trim().toUpperCase(),partnerName:String(r.partnerName||r.partner||"Unassigned Partner").trim(),accountName:String(r.accountName||r.account||r.customer||"Unnamed Account").trim(),leadOwner:String(r.leadOwner||r.owner||"sales").trim().toLowerCase(),stage:String(r.stage||r.status||"registered").trim().toLowerCase(),dealValueUsd:n,marginPercent:s,marginUsd:a,coBrandSlug:String(r.coBrandSlug||r.coBrand||r.partnerId||"default").trim().toLowerCase(),notes:String(r.notes||"").trim(),updatedAt:new Date().toISOString()}}function t1(){const[t,r]=i.useState(()=>e1()),[n,s]=i.useState("");i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(T0,JSON.stringify(t))},[t]);const a=i.useMemo(()=>t.reduce((p,d)=>(p.deals+=1,p.value+=he(d.dealValueUsd,0),p.margin+=he(d.marginUsd,0),p),{deals:0,value:0,margin:0}),[t]),o=async p=>{const d=p&&p.target&&p.target.files?p.target.files[0]:null;if(d)try{const m=await pt(d),f=Ds(m,d.name).map(b=>Bi(b));r(b=>{const h=new Map(b.map(g=>[g.id,g]));return f.forEach(g=>h.set(g.id,g)),Array.from(h.values())}),s("")}catch(m){s(m&&m.message?m.message:String(m))}},c=(p,d)=>{r(m=>m.map(f=>{if(f.id!==p)return f;const b={...f,...d},h=he(b.dealValueUsd,0),g=Math.max(0,Math.min(100,he(b.marginPercent,0)));return{...b,dealValueUsd:h,marginPercent:g,marginUsd:Math.round(h*g/100),updatedAt:new Date().toISOString()}}))},l=()=>{r(p=>[Bi({partnerId:`P-${String(p.length+1).padStart(3,"0")}`,partnerName:"New Partner",accountName:"New Account",leadOwner:"sales",stage:"registered",dealValueUsd:5e4,marginPercent:20}),...p])},u=()=>{const p=t.reduce((d,m)=>{const f=String(m.partnerId||"UNKNOWN");return d[f]||(d[f]={partnerId:f,partnerName:m.partnerName||f,deals:0,valueUsd:0,marginUsd:0}),d[f].deals+=1,d[f].valueUsd+=he(m.dealValueUsd,0),d[f].marginUsd+=he(m.marginUsd,0),d},{});je(`neuralshell_partner_report_${Date.now()}.json`,{exportedAt:new Date().toISOString(),totals:a,partners:Object.values(p),deals:t})},x=p=>{const d=Bi(p);je(`neuralshell_cobranded_kit_${d.partnerId}_${Date.now()}.json`,{generatedAt:new Date().toISOString(),partner:{id:d.partnerId,name:d.partnerName,coBrandSlug:d.coBrandSlug},account:d.accountName,messaging:{header:`${d.partnerName} + ProofForge`,cta:"Book enterprise pilot review",supportEmail:`support+${d.coBrandSlug}@neuralshell.local`},deal:{stage:d.stage,valueUsd:d.dealValueUsd,marginPercent:d.marginPercent,marginUsd:d.marginUsd}})};return e.jsxs("section",{"data-testid":"partner-console",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Partner Operations Layer"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Deal registration, ownership, margin tracking, and reseller export packs."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"partner-console-add-row-btn",onClick:l,className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"+ Register Deal"}),e.jsxs("label",{className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.12em] font-mono text-slate-200 cursor-pointer",children:["Import CSV/JSON",e.jsx("input",{type:"file",accept:".csv,.json,application/json",className:"hidden","data-testid":"partner-console-import-input",onChange:o})]}),e.jsx("button",{type:"button","data-testid":"partner-console-export-report-btn",onClick:u,className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Export Report"})]})]}),n&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:n}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Registered Deals"}),e.jsx("div",{className:"text-[14px] font-bold text-slate-100",children:a.deals})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Pipeline Value"}),e.jsxs("div",{className:"text-[14px] font-bold text-cyan-100",children:["$",a.value.toLocaleString()]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Partner Margin"}),e.jsxs("div",{className:"text-[14px] font-bold text-emerald-100",children:["$",a.margin.toLocaleString()]})]})]}),e.jsx("div",{className:"rounded-lg border border-white/10 bg-black/30 overflow-auto",children:e.jsxs("table",{className:"min-w-full text-[10px] font-mono",children:[e.jsx("thead",{className:"bg-white/[0.04] text-slate-400 uppercase tracking-[0.1em]",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-2 py-2",children:"Partner"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Account"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Owner"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Value"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Margin %"}),e.jsx("th",{className:"text-left px-2 py-2",children:"Actions"})]})}),e.jsxs("tbody",{children:[t.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-3 py-3 text-slate-500",colSpan:6,children:"No partner deals registered."})}),t.map(p=>e.jsxs("tr",{className:"border-t border-white/5",children:[e.jsxs("td",{className:"px-2 py-2",children:[e.jsx("input",{value:p.partnerId,onChange:d=>c(p.id,{partnerId:d.target.value.toUpperCase()}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1 mb-1 text-slate-200"}),e.jsx("input",{value:p.partnerName,onChange:d=>c(p.id,{partnerName:d.target.value}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1 text-slate-300"})]}),e.jsx("td",{className:"px-2 py-2 text-slate-200",children:e.jsx("input",{value:p.accountName,onChange:d=>c(p.id,{accountName:d.target.value}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1"})}),e.jsx("td",{className:"px-2 py-2",children:e.jsxs("select",{value:p.leadOwner,onChange:d=>c(p.id,{leadOwner:d.target.value}),className:"w-full bg-slate-900 border border-white/10 rounded px-1.5 py-1 text-slate-200",children:[e.jsx("option",{value:"sales",children:"sales"}),e.jsx("option",{value:"support",children:"support"}),e.jsx("option",{value:"founder",children:"founder"}),e.jsx("option",{value:"partner",children:"partner"})]})}),e.jsx("td",{className:"px-2 py-2",children:e.jsx("input",{type:"number",value:p.dealValueUsd,onChange:d=>c(p.id,{dealValueUsd:he(d.target.value,0)}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1 text-slate-200"})}),e.jsxs("td",{className:"px-2 py-2",children:[e.jsx("input",{type:"number",value:p.marginPercent,onChange:d=>c(p.id,{marginPercent:he(d.target.value,0)}),className:"w-full bg-transparent border border-white/10 rounded px-1.5 py-1 text-slate-200"}),e.jsxs("div",{className:"text-[9px] text-emerald-200 mt-1",children:["$",he(p.marginUsd,0).toLocaleString()]})]}),e.jsx("td",{className:"px-2 py-2",children:e.jsx("button",{type:"button","data-testid":`partner-console-cobrand-btn-${p.id}`,onClick:()=>x(p),className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] text-cyan-100",children:"Co-Brand Kit"})})]},p.id))]})]})})]})}const qd=[{id:"audit_operator",title:"Audit Operator",description:"Run proof-first workflows, capture evidence, and maintain local audit posture.",passScore:80,questions:[{id:"ao_q1",prompt:"What command is used for a live trust/value proof run?",options:["/proof","/reset","/daemon"],answerIndex:0},{id:"ao_q2",prompt:"Which mode blocks most write actions by default?",options:["Operator","Auditor","Enterprise"],answerIndex:1},{id:"ao_q3",prompt:"Which export is used for support diagnostics?",options:["Support Bundle","Theme Snapshot","Model Cache"],answerIndex:0}]},{id:"deployment_admin",title:"Deployment Admin",description:"Enforce approved providers, update lanes, and relay restrictions.",passScore:80,questions:[{id:"da_q1",prompt:"What should be restricted for offline-first enterprise policy?",options:["Remote bridge","Scratchpad","Theme"],answerIndex:0},{id:"da_q2",prompt:"What gate protects production packaging quality?",options:["Release gate","Theme toggle","Quickstart cards"],answerIndex:0},{id:"da_q3",prompt:"What should every applied policy include?",options:["Signature metadata","Emoji badges","Music playlist"],answerIndex:0}]},{id:"compliance_lead",title:"Compliance Lead",description:"Verify artifact integrity, support audit requests, and preserve traceability.",passScore:80,questions:[{id:"cl_q1",prompt:"What verifies packaged artifacts have not been tampered?",options:["Signature verification","Screen brightness","CPU fan speed"],answerIndex:0},{id:"cl_q2",prompt:"What is required for external compliance review handoff?",options:["Reproducible evidence bundle","Desktop wallpaper","Audio recording"],answerIndex:0},{id:"cl_q3",prompt:"Where should policy and proof changes be recorded?",options:["Audit chain/log","Clipboard history","Chat emoji reactions"],answerIndex:0}]},{id:"marketplace_builder",title:"Marketplace Builder",description:"Package, price, and validate marketplace-facing modules with policy-safe defaults.",passScore:80,questions:[{id:"mb_q1",prompt:"What must not be bypassed by marketplace modules?",options:["Security and policy guardrails","Component naming conventions","Theme palette"],answerIndex:0},{id:"mb_q2",prompt:"What should partner-facing modules include for trust?",options:["Verification receipts","Animated stickers","Random IDs"],answerIndex:0},{id:"mb_q3",prompt:"Which signal is important before shipping new paid module updates?",options:["Release validation status","Mouse DPI","Window opacity"],answerIndex:0}]}],M0="neuralshell_certification_center_v1";function r1(){if(typeof window>"u"||!window.localStorage)return{};try{return JSON.parse(window.localStorage.getItem(M0)||"{}")||{}}catch{return{}}}function n1(t={}){const r=t&&typeof t=="object"?t:{};return{id:String(r.id||"").trim(),title:String(r.title||"Untitled Track").trim(),description:String(r.description||"").trim(),passScore:Math.max(1,Math.min(100,he(r.passScore,80))),questions:Array.isArray(r.questions)?r.questions.map(n=>({id:String(n&&n.id?n.id:`${r.id||"q"}_${Math.random().toString(36).slice(2,6)}`),prompt:String(n&&n.prompt?n.prompt:"Question"),options:Array.isArray(n&&n.options)?n.options.map(s=>String(s||"")):[],answerIndex:Math.max(0,he(n&&n.answerIndex,0))})):[]}}function Yd(t,r){const n=Array.isArray(t&&t.questions)?t.questions:[];if(!n.length)return{score:0,correct:0,total:0};const s=n.reduce((c,l)=>{const u=he(r[l.id],-1);return c+(u===he(l.answerIndex,-2)?1:0)},0),a=n.length;return{score:Math.round(s/a*100),correct:s,total:a}}function s1(){const t=i.useMemo(()=>(Array.isArray(qd)?qd:[]).map(y=>n1(y)),[]),[r,n]=i.useState(()=>t[0]?t[0].id:""),[s,a]=i.useState(()=>r1()),[o,c]=i.useState(""),[l,u]=i.useState(""),[x,p]=i.useState("");i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(M0,JSON.stringify(s))},[s]);const d=i.useMemo(()=>t.find(y=>y.id===r)||t[0]||null,[r,t]),m=i.useMemo(()=>d?s[d.id]||{}:{},[d,s]),f=i.useMemo(()=>d?Yd(d,m):{score:0,correct:0,total:0},[d,m]),b=(y,I)=>{d&&a(A=>({...A,[d.id]:{...A[d.id]||{},[y]:I}}))},h=async()=>{if(d)try{const y=Yd(d,m);if(y.score{const I=y&&y.target&&y.target.files?y.target.files[0]:null;if(I)try{const A=await pt(I),C=JSON.parse(String(A||"{}")),w=C&&typeof C=="object"?C.payload:null,j=C&&typeof C=="object"?String(C.signature||""):"",E=C&&C.signer&&typeof C.signer=="object"?String(C.signer.publicKeyPem||""):"";if(!w||!j||!E)throw new Error("Certificate file missing payload/signature/public key.");const N=await Mt(w,j,E),_=await Tr(E);p(N?`Verified certificate ${w.certificateId||""} (${_.slice(0,28)}...)`:"Certificate signature check failed."),u("")}catch(A){p(""),u(A&&A.message?A.message:String(A))}};return e.jsxs("section",{"data-testid":"certification-center",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Certification Center"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Local training modules with quiz scoring and signed certificate exports."})]}),e.jsxs("label",{className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.12em] font-mono text-slate-200 cursor-pointer",children:["Verify Certificate",e.jsx("input",{type:"file",accept:".json,application/json",className:"hidden","data-testid":"certification-verify-input",onChange:g})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:t.map(y=>e.jsx("button",{type:"button","data-testid":`certification-track-${y.id}`,onClick:()=>n(y.id),className:`px-2.5 py-1.5 rounded-lg border text-[10px] font-mono uppercase tracking-[0.12em] ${d&&d.id===y.id?"border-cyan-300/40 bg-cyan-500/20 text-cyan-100":"border-white/10 bg-white/5 text-slate-300 hover:bg-white/10"}`,children:y.title},y.id))}),d&&e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 p-3 space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-bold text-slate-100",children:d.title}),e.jsx("div",{className:"text-[10px] text-slate-400 font-mono",children:d.description})]}),e.jsx("div",{className:"space-y-2",children:d.questions.map((y,I)=>e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-2",children:[e.jsxs("div",{className:"text-[10px] text-slate-200 mb-1",children:[I+1,". ",y.prompt]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:y.options.map((A,C)=>e.jsx("button",{type:"button",onClick:()=>b(y.id,C),className:`px-2 py-1 rounded border text-[9px] font-mono ${he(m[y.id],-1)===C?"border-cyan-300/40 bg-cyan-500/20 text-cyan-100":"border-white/10 bg-white/5 text-slate-300 hover:bg-white/10"}`,children:A},`${y.id}-${C}`))})]},y.id))}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-300",children:["Score ",f.score,"% (",f.correct,"/",f.total,") · Pass ",d.passScore,"%"]}),e.jsx("button",{type:"button","data-testid":"certification-issue-certificate-btn",onClick:h,className:"px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Issue Certificate"})]})]}),o&&e.jsx("div",{className:"rounded-lg border border-emerald-300/30 bg-emerald-500/10 px-3 py-2 text-[10px] text-emerald-100 font-mono",children:o}),x&&e.jsx("div",{className:"rounded-lg border border-cyan-300/30 bg-cyan-500/10 px-3 py-2 text-[10px] text-cyan-100 font-mono",children:x}),l&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:l})]})}const D0="neuralshell_board_console_v1";function a1(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(D0)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Zd(t={}){const r=t&&typeof t=="object"?t:{};return{month:String(r.month||nc(r.date||new Date().toISOString(),new Date().toISOString().slice(0,7))).slice(0,7),installs:he(r.installs,0),activations:he(r.activations,0),retained30d:he(r.retained30d||r.retention,0),revenueUsd:he(r.revenueUsd||r.revenue,0),proofRuns:he(r.proofRuns,0),partnerGrowth:he(r.partnerGrowth||r.partnerAdds,0),compliancePosture:String(r.compliancePosture||r.compliance||"stable").trim().toLowerCase(),source:String(r.source||"import").trim()}}function Pr(t,r,n){const s=he(t&&t[n],0),a=he(r&&r[n],0);return s-a}function o1(t,r){if(!t)return"No board snapshot available.";const n=Pr(t,r,"installs"),s=Pr(t,r,"activations"),a=Pr(t,r,"revenueUsd"),o=Pr(t,r,"proofRuns"),c=Pr(t,r,"partnerGrowth");return[`# ProofForge Board Pack - ${t.month}`,"","## Operating Summary",`- Installs: ${t.installs.toLocaleString()} (${n>=0?"+":""}${n.toLocaleString()} vs previous)`,`- Activations: ${t.activations.toLocaleString()} (${s>=0?"+":""}${s.toLocaleString()} vs previous)`,`- Revenue: $${t.revenueUsd.toLocaleString()} (${a>=0?"+":""}$${a.toLocaleString()} vs previous)`,`- Proof Runs: ${t.proofRuns.toLocaleString()} (${o>=0?"+":""}${o.toLocaleString()} vs previous)`,`- Partner Growth: ${t.partnerGrowth.toLocaleString()} (${c>=0?"+":""}${c.toLocaleString()} vs previous)`,"","## Retention / Compliance",`- 30d Retained Accounts: ${t.retained30d.toLocaleString()}`,`- Compliance Posture: ${t.compliancePosture}`,"","## Founder Notes","- Confirm top two pilot expansions from Customer Success risk list.","- Validate policy enforcement snapshots before enterprise renewal calls.","- Align partner incentives with highest-conversion pilot verticals."].join(` +`)}function i1(){const[t,r]=i.useState(()=>a1().map(x=>Zd(x))),[n,s]=i.useState("");i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(D0,JSON.stringify(t))},[t]);const a=i.useMemo(()=>[...t].sort((x,p)=>String(x.month||"").localeCompare(String(p.month||""))),[t]),o=a.length?a[a.length-1]:null,c=a.length>1?a[a.length-2]:null,l=i.useMemo(()=>o1(o,c),[o,c]),u=async x=>{const p=x&&x.target&&x.target.files?x.target.files[0]:null;if(p)try{const d=await pt(p),m=Ds(d,p.name).map(f=>Zd({...f,source:p.name}));r(f=>{const b=new Map(f.map(h=>[h.month,h]));return m.forEach(h=>b.set(h.month,h)),Array.from(b.values())}),s("")}catch(d){s(d&&d.message?d.message:String(d))}};return e.jsxs("section",{"data-testid":"board-console",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Investor / Board Reporting Pack"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Monthly operating snapshot with deltas from previous export and local metrics imports."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("label",{className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.12em] font-mono text-slate-200 cursor-pointer",children:["Import Metrics Bundle",e.jsx("input",{type:"file",accept:".csv,.json,application/json",className:"hidden","data-testid":"board-console-import-input",onChange:u})]}),e.jsx("button",{type:"button","data-testid":"board-console-export-markdown-btn",onClick:()=>$s(`neuralshell_board_pack_${Date.now()}.md`,l),className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"Export Markdown"}),e.jsx("button",{type:"button","data-testid":"board-console-export-json-btn",onClick:()=>je(`neuralshell_board_pack_${Date.now()}.json`,{exportedAt:new Date().toISOString(),current:o,previous:c,markdown:l,snapshots:a}),className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Export JSON"})]})]}),n&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:n}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Current Month"}),e.jsx("div",{className:"text-[14px] font-bold text-slate-100",children:o?o.month:"N/A"})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Revenue"}),e.jsxs("div",{className:"text-[14px] font-bold text-emerald-100",children:["$",o?o.revenueUsd.toLocaleString():"0"]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Delta vs Prev"}),e.jsx("div",{className:"text-[14px] font-bold text-cyan-100",children:o&&c?`${Pr(o,c,"revenueUsd")>=0?"+":""}$${Pr(o,c,"revenueUsd").toLocaleString()}`:"N/A"})]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500 mb-2",children:"Board Draft"}),e.jsx("pre",{className:"text-[10px] text-slate-300 font-mono whitespace-pre-wrap leading-relaxed",children:l})]})]})}function fa(t={}){const r=t&&typeof t=="object"?t:{};return{policyId:String(r.policyId||r.id||`policy-${Date.now()}`).trim(),label:String(r.label||r.policyId||"Enterprise Policy").trim(),allowedProviders:Array.isArray(r.allowedProviders)?r.allowedProviders.map(n=>String(n||"").trim().toLowerCase()).filter(Boolean):["ollama"],offlineOnly:!!r.offlineOnly,allowRemoteBridge:!!r.allowRemoteBridge,proofRelayEnabled:!!r.proofRelayEnabled,updateRing:String(r.updateRing||"stable").trim().toLowerCase(),certPins:Array.isArray(r.certPins)?r.certPins.map(n=>String(n||"").trim()).filter(Boolean):[],relayRestriction:String(r.relayRestriction||"local-only").trim().toLowerCase()}}function l1(){const[t,r]=i.useState(()=>fa({})),[n,s]=i.useState(""),[a,o]=i.useState(""),[c,l]=i.useState(!1),u=i.useCallback(async()=>{try{const m=window.api&&window.api.settings&&typeof window.api.settings.get=="function"?await window.api.settings.get():{},f=m&&m.enterprisePolicyEnforced&&typeof m.enterprisePolicyEnforced=="object"?m.enterprisePolicyEnforced:{};r(fa({...f,allowedProviders:Array.isArray(f.allowedProviders)&&f.allowedProviders.length?f.allowedProviders:["ollama"],offlineOnly:!!(m&&m.offlineOnlyEnforced),allowRemoteBridge:!!(m&&m.allowRemoteBridge),proofRelayEnabled:!!(m&&m.proofRelayEnabled),updateRing:String(m&&m.autoUpdateChannel?m.autoUpdateChannel:f.updateRing||"stable")}))}catch(m){o(m&&m.message?m.message:String(m))}},[]);i.useEffect(()=>{u()},[u]);const x=async m=>{const f=fa(m);l(!0);try{window.api&&window.api.settings&&typeof window.api.settings.update=="function"&&await window.api.settings.update({allowRemoteBridge:!!f.allowRemoteBridge,proofRelayEnabled:!!f.proofRelayEnabled,autoUpdateChannel:f.updateRing,offlineOnlyEnforced:!!f.offlineOnly,enterprisePolicyEnforced:{...f,enforcedAt:new Date().toISOString()}}),window.api&&window.api.audit&&typeof window.api.audit.append=="function"&&await window.api.audit.append({event:"enterprise_policy_enforced",policyId:f.policyId,updateRing:f.updateRing,relayRestriction:f.relayRestriction,offlineOnly:f.offlineOnly}),r(f),s(`Applied policy "${f.label}" to runtime.`),o("")}catch(b){s(""),o(b&&b.message?b.message:String(b))}finally{l(!1)}},p=async m=>{const f=m&&m.target&&m.target.files?m.target.files[0]:null;if(f)try{const b=await pt(f),h=JSON.parse(String(b||"{}")),g=h&&typeof h=="object"?h.payload:null,y=h&&typeof h=="object"?String(h.signature||""):"",I=h&&h.signer&&typeof h.signer=="object"?String(h.signer.publicKeyPem||""):"";if(!g||!y||!I)throw new Error("Signed policy bundle requires payload/signature/public key.");if(!await Mt(g,y,I))throw new Error("Policy bundle signature verification failed.");await x(g);const C=await Tr(I);s(`Policy applied from signed bundle (${C.slice(0,26)}...).`),o("")}catch(b){s(""),o(b&&b.message?b.message:String(b))}},d=m=>{r(f=>fa({...f,...m}))};return e.jsxs("section",{"data-testid":"enterprise-policy-suite",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Deployment Policy Suite"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Apply signed policy bundles with provider controls, relay restrictions, update rings, and cert pinning."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("label",{className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100 cursor-pointer",children:["Import Signed Policy",e.jsx("input",{type:"file",accept:".json,application/json",className:"hidden","data-testid":"enterprise-policy-import-input",onChange:p})]}),e.jsx("button",{type:"button","data-testid":"enterprise-policy-export-btn",onClick:()=>{je(`neuralshell_enterprise_policy_${Date.now()}.json`,{exportedAt:new Date().toISOString(),payload:t})},className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Export"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:[e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:["Policy Label",e.jsx("input",{value:t.label,onChange:m=>d({label:m.target.value}),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]}),e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:["Policy ID",e.jsx("input",{value:t.policyId,onChange:m=>d({policyId:m.target.value}),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]}),e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:["Allowed Providers (comma separated)",e.jsx("input",{value:t.allowedProviders.join(","),onChange:m=>d({allowedProviders:String(m.target.value||"").split(",").map(f=>f.trim().toLowerCase()).filter(Boolean)}),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]}),e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:["Update Ring",e.jsxs("select",{value:t.updateRing,onChange:m=>d({updateRing:m.target.value}),className:"mt-1 w-full bg-slate-900 border border-white/10 rounded px-2 py-1",children:[e.jsx("option",{value:"stable",children:"stable"}),e.jsx("option",{value:"canary",children:"canary"}),e.jsx("option",{value:"beta",children:"beta"}),e.jsx("option",{value:"frozen",children:"frozen"})]})]}),e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:["Relay Restriction",e.jsxs("select",{value:t.relayRestriction,onChange:m=>d({relayRestriction:m.target.value}),className:"mt-1 w-full bg-slate-900 border border-white/10 rounded px-2 py-1",children:[e.jsx("option",{value:"local-only",children:"local-only"}),e.jsx("option",{value:"allowlisted-remotes",children:"allowlisted-remotes"}),e.jsx("option",{value:"blocked",children:"blocked"})]})]}),e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:["Cert Pins (one per comma)",e.jsx("input",{value:t.certPins.join(","),onChange:m=>d({certPins:String(m.target.value||"").split(",").map(f=>f.trim()).filter(Boolean)}),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-[10px] font-mono text-slate-300",children:[e.jsxs("label",{className:"inline-flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:!!t.offlineOnly,onChange:m=>d({offlineOnly:!!m.target.checked})}),"Offline-only enforced"]}),e.jsxs("label",{className:"inline-flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:!!t.allowRemoteBridge,onChange:m=>d({allowRemoteBridge:!!m.target.checked})}),"Allow remote bridge"]}),e.jsxs("label",{className:"inline-flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:!!t.proofRelayEnabled,onChange:m=>d({proofRelayEnabled:!!m.target.checked})}),"Proof relay enabled"]}),e.jsx("button",{type:"button","data-testid":"enterprise-policy-apply-btn",disabled:c,onClick:()=>x(t),className:"px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] uppercase tracking-[0.12em] text-cyan-100 disabled:opacity-60",children:"Apply Policy"})]}),n&&e.jsx("div",{className:"rounded-lg border border-emerald-300/30 bg-emerald-500/10 px-3 py-2 text-[10px] text-emerald-100 font-mono",children:n}),a&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:a})]})}const $0="neuralshell_customer_success_console_v1";function c1(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem($0)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Xd(t={}){const r=t&&typeof t=="object"?t:{},n=Math.max(0,Math.min(100,he(r.onboardingCompletion||r.onboardingPct,0))),s=Math.max(0,he(r.proofRuns30d||r.proofRuns||0)),a=Math.max(0,he(r.supportBundles30d||r.supportBundles||0)),o=!!(r.upgraded||r.isUpgraded||String(r.plan||"").toLowerCase()==="paid"),c=nc(r.renewalDate||r.renewal,""),l=Array.isArray(r.timeline)?r.timeline.map(m=>String(m||"").trim()).filter(Boolean):[],u=Math.min(45,a*4),x=Math.max(0,Math.min(100,Math.round(n*.35+Math.min(30,s)*1.2+(o?20:0)-u))),p=x>=75?"healthy":x>=50?"watch":"risk",d=p==="healthy"?"Push expansion or renewal package.":p==="watch"?"Schedule proof refresh and onboarding checkpoint.":"Escalate to support + executive sponsor call.";return{id:String(r.id||r.customerId||`customer-${Date.now()}-${Math.random().toString(36).slice(2,6)}`),customerName:String(r.customerName||r.customer||r.account||"Unnamed Customer").trim(),onboardingCompletion:n,proofRuns30d:s,supportBundles30d:a,upgraded:o,renewalDate:c,healthScore:x,riskLevel:p,recommendation:d,timeline:l,updatedAt:new Date().toISOString()}}function d1(){const[t,r]=i.useState(()=>c1().map(c=>Xd(c))),[n,s]=i.useState("");i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem($0,JSON.stringify(t))},[t]);const a=async c=>{const l=c&&c.target&&c.target.files?c.target.files[0]:null;if(l)try{const u=await pt(l),x=Ds(u,l.name).map(p=>Xd(p));r(p=>{const d=new Map(p.map(m=>[m.id,m]));return x.forEach(m=>d.set(m.id,m)),Array.from(d.values())}),s("")}catch(u){s(u&&u.message?u.message:String(u))}},o=i.useMemo(()=>{if(!t.length)return{avgHealth:0,riskCount:0,watchCount:0};const c=t.reduce((l,u)=>l+he(u.healthScore,0),0);return{avgHealth:Math.round(c/t.length),riskCount:t.filter(l=>l.riskLevel==="risk").length,watchCount:t.filter(l=>l.riskLevel==="watch").length}},[t]);return e.jsxs("section",{"data-testid":"customer-success-console",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Customer Success Workspace"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Import local usage bundles, score customer health, and surface renewal risk actions."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("label",{className:"px-2 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-[0.12em] font-mono text-slate-200 cursor-pointer",children:["Import Usage Bundles",e.jsx("input",{type:"file",accept:".csv,.json,application/json",className:"hidden","data-testid":"customer-success-import-input",onChange:a})]}),e.jsx("button",{type:"button","data-testid":"customer-success-export-btn",onClick:()=>{je(`neuralshell_customer_success_${Date.now()}.json`,{exportedAt:new Date().toISOString(),summary:o,customers:t})},className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Export"})]})]}),n&&e.jsx("div",{className:"rounded-lg border border-rose-300/30 bg-rose-500/10 px-3 py-2 text-[10px] text-rose-200 font-mono",children:n}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Customers"}),e.jsx("div",{className:"text-[14px] font-bold text-slate-100",children:t.length})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Average Health"}),e.jsxs("div",{className:"text-[14px] font-bold text-cyan-100",children:[o.avgHealth,"%"]})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500",children:"Risk / Watch"}),e.jsxs("div",{className:"text-[14px] font-bold text-amber-100",children:[o.riskCount," / ",o.watchCount]})]})]}),e.jsxs("div",{className:"space-y-2 max-h-96 overflow-auto pr-1",children:[t.length===0&&e.jsx("div",{className:"rounded-lg border border-white/10 bg-black/30 px-3 py-3 text-[10px] font-mono text-slate-500",children:"No customer bundles loaded yet."}),t.map(c=>e.jsxs("article",{className:"rounded-lg border border-white/10 bg-black/30 p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[12px] font-bold text-slate-100",children:c.customerName}),e.jsxs("div",{className:"text-[10px] text-slate-500 font-mono",children:["Renewal ",c.renewalDate||"unset"," · Proof runs ",c.proofRuns30d," · Support bundles ",c.supportBundles30d]})]}),e.jsxs("span",{className:`px-2 py-1 rounded border text-[9px] uppercase tracking-[0.12em] font-mono ${c.riskLevel==="healthy"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":c.riskLevel==="watch"?"border-amber-300/30 bg-amber-500/10 text-amber-100":"border-rose-300/30 bg-rose-500/10 text-rose-100"}`,children:[c.riskLevel," · ",c.healthScore,"%"]})]}),e.jsxs("div",{className:"mt-2 text-[10px] font-mono text-slate-300",children:["Next action: ",c.recommendation]}),c.timeline.length>0&&e.jsxs("div",{className:"mt-2 rounded border border-white/10 bg-black/20 p-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.1em] text-slate-500 mb-1",children:"Timeline"}),e.jsx("div",{className:"space-y-1",children:c.timeline.slice(-4).map((l,u)=>e.jsxs("div",{className:"text-[10px] font-mono text-slate-400",children:["- ",l]},`${c.id}-timeline-${u}`))})]})]},c.id))]})]})}const Qd=[{id:"mobile_companion",name:"Mobile Companion Upsell",notes:"Fast status + approvals from phone for field operators.",effort:4,revenuePotential:7,salesFriction:5,deploymentComplexity:6,ecosystemFit:8},{id:"team_edition",name:"Team Edition",notes:"Role-aware seats, shared workflow visibility, and centralized policy control.",effort:7,revenuePotential:9,salesFriction:4,deploymentComplexity:6,ecosystemFit:9},{id:"secure_relay_appliance",name:"Secure Relay Appliance",notes:"On-prem hardened relay bridge for regulated enterprise deals.",effort:8,revenuePotential:8,salesFriction:6,deploymentComplexity:8,ecosystemFit:7},{id:"enterprise_support_plans",name:"Enterprise Support Plans",notes:"SLA-backed premium response and white-glove onboarding services.",effort:3,revenuePotential:8,salesFriction:3,deploymentComplexity:2,ecosystemFit:8}],L0="neuralshell_expansion_planner_v1",Fe={effort:.2,revenuePotential:.35,salesFriction:.15,deploymentComplexity:.1,ecosystemFit:.2};function u1(){if(typeof window>"u"||!window.localStorage)return{weights:Fe,overrides:{}};try{const t=JSON.parse(window.localStorage.getItem(L0)||"{}");return{weights:{effort:he(t&&t.weights?t.weights.effort:Fe.effort,Fe.effort),revenuePotential:he(t&&t.weights?t.weights.revenuePotential:Fe.revenuePotential,Fe.revenuePotential),salesFriction:he(t&&t.weights?t.weights.salesFriction:Fe.salesFriction,Fe.salesFriction),deploymentComplexity:he(t&&t.weights?t.weights.deploymentComplexity:Fe.deploymentComplexity,Fe.deploymentComplexity),ecosystemFit:he(t&&t.weights?t.weights.ecosystemFit:Fe.ecosystemFit,Fe.ecosystemFit)},overrides:t&&t.overrides&&typeof t.overrides=="object"?t.overrides:{}}}catch{return{weights:Fe,overrides:{}}}}function p1(t={}){const r=t&&typeof t=="object"?t:{};return{id:String(r.id||`bet-${Math.random().toString(36).slice(2,6)}`),name:String(r.name||"Untitled Bet"),notes:String(r.notes||""),effort:Math.max(1,Math.min(10,he(r.effort,5))),revenuePotential:Math.max(1,Math.min(10,he(r.revenuePotential,5))),salesFriction:Math.max(1,Math.min(10,he(r.salesFriction,5))),deploymentComplexity:Math.max(1,Math.min(10,he(r.deploymentComplexity,5))),ecosystemFit:Math.max(1,Math.min(10,he(r.ecosystemFit,5)))}}function m1(){const t=i.useMemo(()=>u1(),[]),[r,n]=i.useState(t.weights),[s,a]=i.useState(t.overrides);i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(L0,JSON.stringify({weights:r,overrides:s}))},[r,s]);const o=i.useMemo(()=>(Array.isArray(Qd)?Qd:[]).map(l=>p1(l)),[]),c=i.useMemo(()=>{const l={effort:Math.max(0,he(r.effort,Fe.effort)),revenuePotential:Math.max(0,he(r.revenuePotential,Fe.revenuePotential)),salesFriction:Math.max(0,he(r.salesFriction,Fe.salesFriction)),deploymentComplexity:Math.max(0,he(r.deploymentComplexity,Fe.deploymentComplexity)),ecosystemFit:Math.max(0,he(r.ecosystemFit,Fe.ecosystemFit))};return o.map(u=>{const x=((11-u.effort)*l.effort+u.revenuePotential*l.revenuePotential+(11-u.salesFriction)*l.salesFriction+(11-u.deploymentComplexity)*l.deploymentComplexity+u.ecosystemFit*l.ecosystemFit)*10,p=s[u.id]!=null?he(s[u.id],NaN):NaN,d=Number.isFinite(p)?p:Math.round(x);return{...u,baseScore:Math.round(x),finalScore:Math.max(0,Math.min(100,Math.round(d))),overrideUsed:Number.isFinite(p)}}).sort((u,x)=>x.finalScore-u.finalScore)},[o,s,r]);return e.jsxs("section",{"data-testid":"expansion-planner",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Strategic Expansion Planner"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Score expansion bets by effort, revenue, friction, complexity, and ecosystem fit."})]}),e.jsx("button",{type:"button","data-testid":"expansion-planner-export-btn",onClick:()=>{je(`neuralshell_expansion_planner_${Date.now()}.json`,{exportedAt:new Date().toISOString(),weights:r,ranked:c})},className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Export Plan"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-5 gap-2",children:Object.keys(Fe).map(l=>e.jsxs("label",{className:"rounded-lg border border-white/10 bg-black/20 p-2 text-[10px] font-mono text-slate-300",children:[l,e.jsx("input",{type:"number",step:"0.05",min:"0",max:"1",value:he(r[l],Fe[l]),onChange:u=>n(x=>({...x,[l]:Math.max(0,Math.min(1,he(u.target.value,Fe[l])))})),className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1"})]},l))}),e.jsx("div",{className:"space-y-2",children:c.map(l=>e.jsxs("article",{className:"rounded-lg border border-white/10 bg-black/30 p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[12px] font-bold text-slate-100",children:l.name}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:l.notes})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.12em] text-slate-500",children:"Score"}),e.jsx("div",{className:"text-[16px] font-bold text-cyan-100",children:l.finalScore}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["base ",l.baseScore,l.overrideUsed?" · manual":""]})]})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-2 md:grid-cols-5 gap-2 text-[10px] font-mono text-slate-300",children:[e.jsxs("div",{children:["Effort ",l.effort,"/10"]}),e.jsxs("div",{children:["Revenue ",l.revenuePotential,"/10"]}),e.jsxs("div",{children:["Sales Friction ",l.salesFriction,"/10"]}),e.jsxs("div",{children:["Deploy Complexity ",l.deploymentComplexity,"/10"]}),e.jsxs("div",{children:["Ecosystem Fit ",l.ecosystemFit,"/10"]})]}),e.jsxs("div",{className:"mt-2",children:[e.jsx("label",{className:"text-[9px] uppercase tracking-[0.1em] text-slate-500",children:"Manual Score Override"}),e.jsx("input",{type:"number",min:"0",max:"100",placeholder:"leave empty to use weighted score",value:s[l.id]==null?"":s[l.id],onChange:u=>{const x=String(u.target.value||"").trim();a(p=>{if(!x){const d={...p};return delete d[l.id],d}return{...p,[l.id]:Math.max(0,Math.min(100,he(x,l.baseScore)))}})},className:"mt-1 w-full bg-transparent border border-white/10 rounded px-2 py-1 text-[10px] font-mono text-slate-200"})]})]},l.id))})]})}const eu={free:0,pro:1,enterprise:2},B0=[{id:"mission_control",title:"Mission Control",description:"Runtime authority cockpit with live health cards, event feed, and watchdog visibility.",minTier:"free",roles:["founder","sales","support","operator"]},{id:"fleet_control",title:"Fleet Control",description:"Import and compare multi-node runtime bundles with health and event drill-ins.",minTier:"pro",roles:["founder","support","operator"]},{id:"recovery_center",title:"Recovery Center",description:"Signed recovery bundles, restore preview, and safe-mode restoration flow.",minTier:"pro",roles:["founder","support","operator"]},{id:"appliance_console",title:"Appliance Console",description:"Operator-only hardened appliance mode for relay/control deployments.",minTier:"enterprise",roles:["founder","operator","support"]},{id:"airgap_operations",title:"Air-Gapped Operations",description:"Import/export station ledger, verification gates, and air-gap lock posture controls.",minTier:"enterprise",roles:["founder","operator","support"]},{id:"trust_fabric",title:"PKI Trust Fabric",description:"Local CA controls, certificate lifecycle, revocation, and trust-chain export.",minTier:"enterprise",roles:["founder","operator","support"]},{id:"hardware_appliance",title:"Hardware Appliance Program",description:"Provisioning, profile health, support diagnostics scope, and decommission workflows.",minTier:"enterprise",roles:["founder","operator","support"]},{id:"courier_transfer",title:"Offline Evidence Courier",description:"Signed courier package movement with quarantine, receipt verification, and release controls.",minTier:"enterprise",roles:["founder","operator","support"]},{id:"continuity_drills",title:"Continuity Drills",description:"Schedule and score continuity exercises with recovery evidence exports.",minTier:"enterprise",roles:["founder","operator","support"]},{id:"procurement_command",title:"Procurement Command Center",description:"Generate buyer-ready security/procurement review packs and version deltas.",minTier:"enterprise",roles:["founder","support","sales"]},{id:"tamper_simulation",title:"Tamper Simulation Mode",description:"Safe simulation of detection, quarantine, and response workflows.",minTier:"enterprise",roles:["founder","operator","support","sales"]},{id:"institutional_command",title:"Institutional Command Console",description:"Unified executive/operator command surface across all institutional tracks.",minTier:"enterprise",roles:["founder","operator","support","sales"]},{id:"demo_flow",title:"Institutional Demo System",description:"Seeded deterministic demo route with presenter guidance and baseline reset controls.",minTier:"pro",roles:["founder","sales","support","operator"]},{id:"deployment_program",title:"Deployment Program Pack",description:"Role-based deployment runbooks plus preflight and post-install validation flows.",minTier:"pro",roles:["founder","operator","support"]},{id:"training_delivery",title:"Training Delivery Pack",description:"Offline role training tracks, labs, instructor guidance, and exam export controls.",minTier:"pro",roles:["founder","operator","support","sales"]},{id:"support_ops",title:"Support Operations Pack",description:"Support intake, severity matrix, escalation ladder, and triage workflow controls.",minTier:"pro",roles:["founder","support","operator"]},{id:"buyer_journey",title:"Buyer Evaluation Journey",description:"Evaluator quickstart and defensible buyer path from first look to approval.",minTier:"pro",roles:["founder","sales","support"]},{id:"pilot_conversion",title:"Pilot Conversion Kit",description:"Evidence-first pilot review templates and expansion planning artifacts.",minTier:"pro",roles:["founder","sales","support"]},{id:"commercial_packages",title:"Commercial Package Matrix",description:"SKU, deployment, support entitlement, and add-on mapping across offerings.",minTier:"pro",roles:["founder","sales","support"]},{id:"field_launch",title:"Field Launch Command Center",description:"One-screen commercialization and deployment readiness tracker with blockers.",minTier:"pro",roles:["founder","sales","support","operator"]},{id:"partner_rollout",title:"Partner Rollout Console",description:"Partner activation checklist, readiness scoring, blocker queue, and handoff summary export.",minTier:"pro",roles:["founder","sales","support"]},{id:"buyer_ops",title:"Buyer Ops Automation",description:"Stage-aware buyer follow-up generation with timeline and stale-evaluator controls.",minTier:"pro",roles:["founder","sales","support"]},{id:"demo_to_pilot",title:"Demo-to-Pilot Engine",description:"Demo outcome capture, pilot-fit scorecard, and conversion decision workflow.",minTier:"pro",roles:["founder","sales","support"]},{id:"pilot_expansion",title:"Pilot Expansion Command",description:"Pilot milestone tracking and expansion proposal generation from evidence inputs.",minTier:"pro",roles:["founder","sales","support"]},{id:"renewal_risk",title:"Renewal Risk Console",description:"Renewal timeline, explainable risk scoring, and retention intervention summaries.",minTier:"pro",roles:["founder","sales","support"]},{id:"launch_week",title:"Launch Week Command Discipline",description:"Live launch-day checklist, escalation board, and end-of-day command exports.",minTier:"pro",roles:["founder","sales","support","operator"]},{id:"followup_generator",title:"Proof-Backed Follow-Up",description:"Generate stage-aware follow-up drafts grounded in explicit proof references.",minTier:"pro",roles:["founder","sales","support"]},{id:"field_feedback",title:"Field Feedback Routing",description:"Capture and classify field feedback for routing to product/support/docs/training queues.",minTier:"pro",roles:["founder","sales","support","operator"]},{id:"partner_certification",title:"Partner Certification Hub",description:"Formal partner certification, enablement assignment, recertification warnings, and registry export.",minTier:"pro",roles:["founder","sales","support"]},{id:"managed_services",title:"Managed Services Console",description:"Multi-account managed operations with health, drift, and escalation visibility.",minTier:"pro",roles:["founder","support","operator"]},{id:"strategic_account",title:"Strategic Account Orchestration",description:"Stakeholder maps, blockers, and evidence-linked expansion hypotheses for key accounts.",minTier:"pro",roles:["founder","sales","support"]},{id:"portfolio_rollout",title:"Portfolio Rollout Planner",description:"Cross-site/account rollout stage matrix with dependency and strain visibility.",minTier:"pro",roles:["founder","support","operator"]},{id:"revenue_ops",title:"Revenue Operations Console",description:"Pipeline-to-revenue, SKU mix, and expansion/renewal signal views.",minTier:"pro",roles:["founder","sales","support"]},{id:"channel_expansion",title:"Channel Expansion Planner",description:"Channel model scorecards, enablement gaps, and launch package readiness planning.",minTier:"pro",roles:["founder","sales","support"]},{id:"cross_account_renewal",title:"Cross-Account Renewal Matrix",description:"Renewal timing, risk overlays, and intervention planning across accounts.",minTier:"pro",roles:["founder","sales","support"]},{id:"executive_scale",title:"Executive Scale Dashboard",description:"Founder/exec one-screen summary for partner, account, rollout, revenue, and renewal scale posture.",minTier:"pro",roles:["founder","sales","support","operator"]},{id:"ecosystem_portfolio",title:"Ecosystem Portfolio Console",description:"Operate product/service/channel portfolio lines with attachment path and health visibility.",minTier:"pro",roles:["founder","sales","support"]},{id:"service_line",title:"Service Line Operating Layer",description:"Service line catalog, capacity, utilization, and health operations view.",minTier:"pro",roles:["founder","support","operator"]},{id:"partner_network_governance",title:"Partner Network Governance",description:"Network-wide tier, compliance, and governance-state command view.",minTier:"pro",roles:["founder","sales","support"]},{id:"global_planning",title:"Global Account & Region Planning",description:"Region-fit overlays and phased global planning across account/deployment realities.",minTier:"pro",roles:["founder","sales","support"]},{id:"ecosystem_revenue",title:"Ecosystem Revenue Mix Planner",description:"Revenue mix, margin proxy, and partner/support overlays across ecosystem lines.",minTier:"pro",roles:["founder","sales","support"]},{id:"board_operating_pack",title:"Board / Investor Operating Pack",description:"Generate sober board/investor operating packs with evidence-linked appendix context.",minTier:"pro",roles:["founder"]},{id:"licensed_operator",title:"Licensed Operator Framework",description:"Controlled licensed-operator launch framework tied to training/certification/governance requirements.",minTier:"pro",roles:["founder","support"]},{id:"ecosystem_command",title:"Ecosystem Command Center",description:"Top-level ecosystem command summary with drill-down into all Δ18 systems.",minTier:"pro",roles:["founder","sales","support","operator"]},{id:"shift_console",title:"Shift Console",description:"Role-aware handoff console with signed shift summaries.",minTier:"pro",roles:["founder","operator","support","sales"]},{id:"incident_mode",title:"Incident Mode",description:"Declare and manage degraded/critical incidents with playbook execution.",minTier:"pro",roles:["founder","operator","support","security"]},{id:"policy_rollout",title:"Policy Rollout",description:"Signed fleet policy rollout preview, apply, and rollback history.",minTier:"enterprise",roles:["founder","operator","support","security"]},{id:"offline_update_packs",title:"Offline Update Packs",description:"Verify offline update packs and assign/promote update rings per node.",minTier:"enterprise",roles:["founder","operator","support","security"]},{id:"mission_scheduler",title:"Mission Scheduler",description:"NodeChain mission templates, schedules, dry-run controls, and run history.",minTier:"enterprise",roles:["founder","operator","support"]},{id:"sales_console",title:"Enterprise Sales Console",description:"Pipeline stages, pilots, procurement blockers, renewals, and deal progression.",minTier:"pro",capability:"enterprise_sales_console",roles:["founder","sales","support"]},{id:"pilot_kit",title:"Pilot Program Kit",description:"Generate customer-tailored pilot materials and reusable deployment packet artifacts.",minTier:"pro",capability:"pilot_kit_generator",roles:["founder","sales","support"]},{id:"white_label",title:"White-Label / OEM",description:"Signed branding profile import and local profile enforcement preview.",minTier:"enterprise",capability:"white_label_mode",roles:["founder","support"]},{id:"partner_console",title:"Partner Operations",description:"Deal registration, ownership, margins, and co-branded reseller assets.",minTier:"enterprise",capability:"partner_ops_console",roles:["founder","sales","support"]},{id:"certifications",title:"Certification Center",description:"Local training tracks, quizzes, and signed certificate exports.",minTier:"pro",capability:"certification_center",roles:["founder","operator","support"]},{id:"board_console",title:"Board / Investor Pack",description:"Monthly operating report generation from imported local metrics bundles.",minTier:"enterprise",capability:"board_reporting_console",roles:["founder"]},{id:"enterprise_policy",title:"Deployment Policy Suite",description:"Signed enterprise policy bundle import and runtime enforcement controls.",minTier:"enterprise",capability:"enterprise_policy_suite",roles:["founder","support"]},{id:"customer_success",title:"Customer Success Workspace",description:"Onboarding health, risk alerts, support trend mapping, and renewal posture.",minTier:"enterprise",capability:"customer_success_console",roles:["founder","support","sales"]},{id:"ecosystem_launcher",title:"Ecosystem Launcher",description:"Role-aware command center for core, marketplace, support, and GTM modules.",minTier:"free",roles:["founder","sales","support","operator"]},{id:"expansion_planner",title:"Strategic Expansion Planner",description:"Weighted scoring for net-new products and enterprise growth bets.",minTier:"pro",capability:"expansion_planner",roles:["founder","sales"]}];function x1(t){const r=String(t||"").trim().toLowerCase();return r==="enterprise"?"enterprise":r==="pro"?"pro":"free"}function F0(t,r,n,s=[]){const a=t.roles.includes(r),o=x1(n),c=eu[o]>=eu[t.minTier],l=t.capability?Array.isArray(s)&&s.includes(t.capability):!0;return a&&c&&l}function f1(t,r,n=[]){return B0.filter(s=>F0(s,t,r,n))}const U0="neuralshell_ecosystem_role_v1",z0=[{id:"founder",label:"Founder"},{id:"sales",label:"Sales"},{id:"support",label:"Support"},{id:"operator",label:"Operator"}],b1=new Set(["mission_control","fleet_control","recovery_center","appliance_console","airgap_operations","trust_fabric","hardware_appliance","courier_transfer","continuity_drills","procurement_command","tamper_simulation","institutional_command","demo_flow","deployment_program","training_delivery","support_ops","buyer_journey","pilot_conversion","commercial_packages","field_launch","partner_rollout","buyer_ops","demo_to_pilot","pilot_expansion","renewal_risk","launch_week","followup_generator","field_feedback","partner_certification","managed_services","strategic_account","portfolio_rollout","revenue_ops","channel_expansion","cross_account_renewal","executive_scale","ecosystem_portfolio","service_line","partner_network_governance","global_planning","ecosystem_revenue","board_operating_pack","licensed_operator","ecosystem_command","shift_console","incident_mode","policy_rollout","offline_update_packs","mission_scheduler","enterprise_policy"]);function h1(){if(typeof window>"u"||!window.localStorage)return"founder";const t=String(window.localStorage.getItem(U0)||"").trim().toLowerCase();return z0.some(r=>r.id===t)?t:"founder"}function g1({role:t,tierId:r,moduleCount:n}){return e.jsxs("section",{"data-testid":"ecosystem-home",className:"rounded-2xl border border-white/10 bg-black/30 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Ecosystem Command Center"}),e.jsx("div",{className:"text-[11px] text-slate-300",children:"ProofForge ecosystem mode links enterprise sales, partner ops, certification workflows, policy enforcement, and board reporting into one local-first surface."}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.1em] text-slate-500",children:"Role"}),e.jsx("div",{className:"text-[13px] text-slate-100 font-bold",children:t})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.1em] text-slate-500",children:"Tier"}),e.jsx("div",{className:"text-[13px] text-slate-100 font-bold",children:r||"free"})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 px-3 py-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.1em] text-slate-500",children:"Modules"}),e.jsx("div",{className:"text-[13px] text-slate-100 font-bold",children:n})]})]}),e.jsx("div",{className:"rounded-lg border border-white/10 bg-black/20 p-3 text-[10px] font-mono text-slate-400",children:"Use role + tier controls to validate access boundaries for Sales, Support, Founder, and Operator views."})]})}function y1({open:t,onClose:r,capabilities:n=[],tierId:s="free",onOpenMissionControl:a,onOpenFleetControl:o,onOpenRecoveryCenter:c,onOpenApplianceConsole:l,onOpenAirGapOperations:u,onOpenTrustFabric:x,onOpenHardwareAppliance:p,onOpenCourierTransfer:d,onOpenContinuityDrills:m,onOpenProcurementCommand:f,onOpenTamperSimulation:b,onOpenInstitutionalCommand:h,onOpenDemoFlow:g,onOpenDeploymentProgram:y,onOpenTrainingDelivery:I,onOpenSupportOps:A,onOpenBuyerJourney:C,onOpenPilotConversion:w,onOpenCommercialPackages:j,onOpenFieldLaunch:E,onOpenPartnerRollout:N,onOpenBuyerOps:_,onOpenDemoToPilot:S,onOpenPilotExpansion:R,onOpenRenewalRisk:$,onOpenLaunchWeek:U,onOpenFollowupGenerator:P,onOpenFieldFeedback:D,onOpenPartnerCertification:z,onOpenManagedServices:F,onOpenStrategicAccount:J,onOpenPortfolioRollout:ee,onOpenRevenueOps:ie,onOpenChannelExpansion:ye,onOpenCrossAccountRenewal:pe,onOpenExecutiveScale:K,onOpenEcosystemPortfolio:H,onOpenServiceLine:W,onOpenPartnerNetworkGovernance:Z,onOpenGlobalPlanning:ce,onOpenEcosystemRevenue:fe,onOpenBoardOperatingPack:me,onOpenLicensedOperator:ke,onOpenEcosystemCommand:Pe,onOpenShiftConsole:_e,onOpenIncidentMode:ne,onOpenPolicyRollout:we,onOpenOfflineUpdates:De,onOpenMissionScheduler:re,applianceModeEnabled:ae=!1}){const[M,V]=i.useState(()=>h1()),[G,te]=i.useState("ecosystem_launcher");i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(U0,M)},[M]);const de=i.useMemo(()=>{const be=f1(M,s,n);return ae?be.filter(Q=>b1.has(Q.id)):be},[ae,n,M,s]);i.useEffect(()=>{de.some(be=>be.id===G)||te(de[0]?de[0].id:"ecosystem_launcher")},[de,G]);const L=de.find(be=>be.id===G)||null;return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[95] bg-black/55 backdrop-blur-sm",onClick:r}),e.jsxs("aside",{"data-testid":"ecosystem-launcher",className:"fixed inset-x-4 top-16 bottom-4 z-[96] rounded-2xl border border-cyan-400/30 bg-slate-950 shadow-[0_20px_80px_rgba(0,0,0,0.65)] overflow-hidden flex min-h-0",children:[e.jsxs("div",{className:"w-72 border-r border-white/10 bg-black/35 p-3 flex flex-col gap-3 overflow-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Ecosystem Launcher"}),e.jsx("div",{className:"text-[9px] text-slate-500 font-mono",children:"Role-aware navigation"})]}),e.jsx("button",{type:"button","data-testid":"ecosystem-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:text-white hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-2",children:[e.jsx("label",{className:"text-[9px] uppercase tracking-[0.12em] text-slate-500 font-mono",children:"Role"}),e.jsx("select",{"data-testid":"ecosystem-role-select",value:M,onChange:be=>V(be.target.value),className:"mt-1 w-full bg-slate-900 border border-white/10 rounded px-2 py-1 text-[10px] font-mono text-slate-200",children:z0.map(be=>e.jsx("option",{value:be.id,children:be.label},be.id))}),e.jsxs("div",{className:"mt-1 text-[9px] text-slate-500 font-mono",children:["Tier ",String(s||"free")]})]}),e.jsx("div",{className:"space-y-1",children:de.map(be=>e.jsxs("button",{type:"button","data-testid":`ecosystem-module-${be.id}`,onClick:()=>te(be.id),className:`w-full text-left px-2.5 py-2 rounded-lg border text-[10px] font-mono ${G===be.id?"border-cyan-300/40 bg-cyan-500/15 text-cyan-100":"border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/10"}`,children:[e.jsx("div",{className:"font-bold uppercase tracking-[0.1em]",children:be.title}),e.jsx("div",{className:"text-[9px] text-slate-500 mt-0.5",children:be.description})]},be.id))}),e.jsx("div",{className:"pt-2 border-t border-white/10 space-y-1",children:B0.filter(be=>!F0(be,M,s,n)).map(be=>e.jsxs("div",{"data-testid":`ecosystem-module-locked-${be.id}`,className:"px-2 py-1.5 rounded border border-white/10 bg-white/[0.02] text-[9px] font-mono text-slate-500",children:[be.title," · locked (",be.minTier,")"]},`locked-${be.id}`))})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-4",children:[!L&&e.jsx("div",{className:"text-[11px] font-mono text-slate-500",children:"No module available for this role/tier."}),L&&L.id==="ecosystem_launcher"&&e.jsx(g1,{role:M,tierId:String(s||"free"),moduleCount:de.length}),L&&L.id==="mission_control"&&e.jsxs("section",{"data-testid":"ecosystem-mission-control-entry",className:"rounded-2xl border border-blue-300/30 bg-blue-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-blue-200 font-bold",children:"Mission Control Runtime Cockpit"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Launch the live runtime command center with provider, vault, proof, policy, update, and watchdog state in one view."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-mission-control-btn",onClick:()=>{typeof a=="function"&&a()},className:"px-3 py-2 rounded-lg border border-blue-200/35 bg-blue-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/30",children:"Open Mission Control"})]}),L&&L.id==="fleet_control"&&e.jsxs("section",{"data-testid":"ecosystem-fleet-control-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Fleet Control"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open the multi-node fleet panel to import offline bundles, compare node posture, and drill into node-level event feeds."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-fleet-control-btn",onClick:()=>{typeof o=="function"&&o()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Fleet Control"})]}),L&&L.id==="recovery_center"&&e.jsxs("section",{"data-testid":"ecosystem-recovery-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Recovery Center"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Generate signed backup bundles, verify restore artifacts, and apply staged or safe-mode recovery."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-recovery-btn",onClick:()=>{typeof c=="function"&&c()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Recovery Center"})]}),L&&L.id==="appliance_console"&&e.jsxs("section",{"data-testid":"ecosystem-appliance-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Appliance Console"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open hardened appliance controls for relay, policy distribution, update gating, and support ingest posture."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-appliance-btn",onClick:()=>{typeof l=="function"&&l()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Appliance Console"})]}),L&&L.id==="airgap_operations"&&e.jsxs("section",{"data-testid":"ecosystem-airgap-entry",className:"rounded-2xl border border-slate-300/30 bg-slate-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-slate-100 font-bold",children:"Air-Gapped Operations"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open controlled transfer-station workflows for offline artifacts with verification gates and air-gap lock controls."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-airgap-btn",onClick:()=>{typeof u=="function"&&u()},className:"px-3 py-2 rounded-lg border border-slate-300/35 bg-slate-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-slate-100 hover:bg-slate-500/30",children:"Open Air-Gapped Operations"})]}),L&&L.id==="trust_fabric"&&typeof x=="function"&&e.jsxs("section",{"data-testid":"ecosystem-trust-fabric-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"PKI Trust Fabric"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open local certificate authority controls, lifecycle operations, and trust-chain export view."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-trust-fabric-btn",onClick:()=>{typeof x=="function"&&x()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Trust Fabric"})]}),L&&L.id==="hardware_appliance"&&typeof p=="function"&&e.jsxs("section",{"data-testid":"ecosystem-hardware-appliance-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Hardware Appliance Program"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open profile manager for provisioning, appliance health simulation, and decommission exports."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-hardware-appliance-btn",onClick:()=>{typeof p=="function"&&p()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Hardware Appliance"})]}),L&&L.id==="courier_transfer"&&e.jsxs("section",{"data-testid":"ecosystem-courier-transfer-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Offline Evidence Courier"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open transfer chain controls for package quarantine, receipt verification, and release gates."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-courier-transfer-btn",onClick:()=>{typeof d=="function"&&d()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Courier Transfer"})]}),L&&L.id==="continuity_drills"&&typeof m=="function"&&e.jsxs("section",{"data-testid":"ecosystem-continuity-drills-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Continuity Drills"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open drill scheduling, readiness scorecard, and continuity evidence export workflows."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-continuity-drills-btn",onClick:()=>{typeof m=="function"&&m()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-100/30",children:"Open Continuity Drills"})]}),L&&L.id==="procurement_command"&&e.jsxs("section",{"data-testid":"ecosystem-procurement-command-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Procurement Command Center"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open buyer/security review pack controls with version delta generation."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-procurement-command-btn",onClick:()=>{typeof f=="function"&&f()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Procurement Center"})]}),L&&L.id==="tamper_simulation"&&e.jsxs("section",{"data-testid":"ecosystem-tamper-simulation-entry",className:"rounded-2xl border border-rose-300/30 bg-rose-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-rose-100 font-bold",children:"Tamper Simulation Mode"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open sandboxed simulation workflows for detection and response drills."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-tamper-simulation-btn",onClick:()=>{typeof b=="function"&&b()},className:"px-3 py-2 rounded-lg border border-rose-200/35 bg-rose-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-rose-100 hover:bg-rose-500/30",children:"Open Tamper Simulation"})]}),L&&L.id==="institutional_command"&&e.jsxs("section",{"data-testid":"ecosystem-institutional-command-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Institutional Command Console"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open one-screen institutional posture summary with direct drill-down controls."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-institutional-command-btn",onClick:()=>{typeof h=="function"&&h()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Institutional Command"})]}),L&&L.id==="demo_flow"&&typeof g=="function"&&e.jsxs("section",{"data-testid":"ecosystem-demo-flow-entry",className:"rounded-2xl border border-emerald-300/30 bg-emerald-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-emerald-100 font-bold",children:"Institutional Demo Flow"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Launch deterministic demo mode with seeded state and guided presenter flow."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-demo-flow-btn",onClick:()=>{typeof g=="function"&&g()},className:"px-3 py-2 rounded-lg border border-emerald-200/35 bg-emerald-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/30",children:"Open Demo Flow"})]}),L&&L.id==="deployment_program"&&e.jsxs("section",{"data-testid":"ecosystem-deployment-program-entry",className:"rounded-2xl border border-blue-300/30 bg-blue-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-blue-100 font-bold",children:"Deployment Program Pack"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open deployment runbooks and preflight/post-install validation controls."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-deployment-program-btn",onClick:()=>{typeof y=="function"&&y()},className:"px-3 py-2 rounded-lg border border-blue-200/35 bg-blue-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/30",children:"Open Deployment Program"})]}),L&&L.id==="training_delivery"&&e.jsxs("section",{"data-testid":"ecosystem-training-delivery-entry",className:"rounded-2xl border border-emerald-300/30 bg-emerald-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-emerald-100 font-bold",children:"Training Delivery Pack"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open role-based offline training bundle generation and lab history."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-training-delivery-btn",onClick:()=>{typeof I=="function"&&I()},className:"px-3 py-2 rounded-lg border border-emerald-200/35 bg-emerald-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/30",children:"Open Training Delivery"})]}),L&&L.id==="support_ops"&&e.jsxs("section",{"data-testid":"ecosystem-support-ops-entry",className:"rounded-2xl border border-amber-300/30 bg-amber-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-amber-100 font-bold",children:"Support Operations Pack"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open support intake, severity matrix, and triage queue controls."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-support-ops-btn",onClick:()=>{typeof A=="function"&&A()},className:"px-3 py-2 rounded-lg border border-amber-200/35 bg-amber-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100 hover:bg-amber-500/30",children:"Open Support Ops"})]}),L&&L.id==="buyer_journey"&&e.jsxs("section",{"data-testid":"ecosystem-buyer-journey-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Buyer Evaluation Journey"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open evaluator quickstart and defensible buyer path summary."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-buyer-journey-btn",onClick:()=>{typeof C=="function"&&C()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Buyer Journey"})]}),L&&L.id==="pilot_conversion"&&typeof w=="function"&&e.jsxs("section",{"data-testid":"ecosystem-pilot-conversion-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Pilot Conversion Kit"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open proof-of-value and expansion planning workflows for pilot conversion."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-pilot-conversion-btn",onClick:()=>{typeof w=="function"&&w()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Pilot Conversion"})]}),L&&L.id==="commercial_packages"&&e.jsxs("section",{"data-testid":"ecosystem-commercial-packages-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Commercial Package Matrix"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open SKU, deployment, and support entitlement alignment surface."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-commercial-packages-btn",onClick:()=>{typeof j=="function"&&j()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Commercial Packages"})]}),L&&L.id==="field_launch"&&typeof E=="function"&&e.jsxs("section",{"data-testid":"ecosystem-field-launch-entry",className:"rounded-2xl border border-blue-300/30 bg-blue-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-blue-100 font-bold",children:"Field Launch Command Center"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open launch-day commercialization and deployment readiness dashboard."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-field-launch-btn",onClick:()=>{typeof E=="function"&&E()},className:"px-3 py-2 rounded-lg border border-blue-200/35 bg-blue-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/30",children:"Open Field Launch"})]}),L&&L.id==="partner_rollout"&&e.jsxs("section",{"data-testid":"ecosystem-partner-rollout-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Partner Rollout Console"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Track partner activation, readiness scoring, blocker queue, and handoff exports."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-partner-rollout-btn",onClick:()=>{typeof N=="function"&&N()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Partner Rollout"})]}),L&&L.id==="buyer_ops"&&e.jsxs("section",{"data-testid":"ecosystem-buyer-ops-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Buyer Ops Automation"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Generate stage-aware follow-up packs and maintain buyer timeline discipline."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-buyer-ops-btn",onClick:()=>{typeof _=="function"&&_()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Buyer Ops"})]}),L&&L.id==="demo_to_pilot"&&e.jsxs("section",{"data-testid":"ecosystem-demo-to-pilot-entry",className:"rounded-2xl border border-emerald-300/30 bg-emerald-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-emerald-100 font-bold",children:"Demo-to-Pilot Engine"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Capture demo outcomes, score pilot fit, and trigger pilot launch packs."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-demo-to-pilot-btn",onClick:()=>{typeof S=="function"&&S()},className:"px-3 py-2 rounded-lg border border-emerald-200/35 bg-emerald-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/30",children:"Open Demo-to-Pilot"})]}),L&&L.id==="pilot_expansion"&&e.jsxs("section",{"data-testid":"ecosystem-pilot-expansion-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Pilot Expansion Command"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Convert pilot outcomes into expansion proposals with deployment phase mapping."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-pilot-expansion-btn",onClick:()=>{typeof R=="function"&&R()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Pilot Expansion"})]}),L&&L.id==="renewal_risk"&&e.jsxs("section",{"data-testid":"ecosystem-renewal-risk-entry",className:"rounded-2xl border border-amber-300/30 bg-amber-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-amber-100 font-bold",children:"Renewal Risk Console"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Monitor renewal timelines, explain risk scoring, and export intervention plans."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-renewal-risk-btn",onClick:()=>{typeof $=="function"&&$()},className:"px-3 py-2 rounded-lg border border-amber-200/35 bg-amber-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100 hover:bg-amber-500/30",children:"Open Renewal Risk"})]}),L&&L.id==="launch_week"&&typeof U=="function"&&e.jsxs("section",{"data-testid":"ecosystem-launch-week-entry",className:"rounded-2xl border border-blue-300/30 bg-blue-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-blue-100 font-bold",children:"Launch Week Command Discipline"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Run launch-day checklist, escalations, priorities, and end-of-day command exports."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-launch-week-btn",onClick:()=>{typeof U=="function"&&U()},className:"px-3 py-2 rounded-lg border border-blue-200/35 bg-blue-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/30",children:"Open Launch Week"})]}),L&&L.id==="followup_generator"&&e.jsxs("section",{"data-testid":"ecosystem-followup-generator-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Proof-Backed Follow-Up"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Create stage-aware follow-up drafts with explicit evidence references and deltas."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-followup-generator-btn",onClick:()=>{typeof P=="function"&&P()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Follow-Up Generator"})]}),L&&L.id==="field_feedback"&&e.jsxs("section",{"data-testid":"ecosystem-field-feedback-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Field Feedback Routing"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Capture structured field notes and route them into product/support/docs/training queues."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-field-feedback-btn",onClick:()=>{typeof D=="function"&&D()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Field Feedback"})]}),L&&L.id==="partner_certification"&&e.jsxs("section",{"data-testid":"ecosystem-partner-certification-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Partner Certification Hub"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Manage partner certification tracks, recertification warnings, and co-sell readiness exports."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-partner-certification-btn",onClick:()=>{typeof z=="function"&&z()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Partner Certification"})]}),L&&L.id==="managed_services"&&typeof F=="function"&&e.jsxs("section",{"data-testid":"ecosystem-managed-services-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Managed Services Console"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Run operator-network account health, escalation, and drift management across managed accounts."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-managed-services-btn",onClick:()=>{typeof F=="function"&&F()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Managed Services"})]}),L&&L.id==="strategic_account"&&typeof J=="function"&&e.jsxs("section",{"data-testid":"ecosystem-strategic-account-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Strategic Account Orchestration"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Orchestrate stakeholder maps, blockers, and evidence-linked expansion hypotheses for key accounts."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-strategic-account-btn",onClick:()=>{typeof J=="function"&&J()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Strategic Account"})]}),L&&L.id==="portfolio_rollout"&&typeof ee=="function"&&e.jsxs("section",{"data-testid":"ecosystem-portfolio-rollout-entry",className:"rounded-2xl border border-blue-300/30 bg-blue-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-blue-100 font-bold",children:"Portfolio Rollout Planner"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Coordinate rollout stages, dependency hotspots, and resource strain across accounts and sites."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-portfolio-rollout-btn",onClick:()=>{typeof ee=="function"&&ee()},className:"px-3 py-2 rounded-lg border border-blue-200/35 bg-blue-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/30",children:"Open Portfolio Rollout"})]}),L&&L.id==="revenue_ops"&&typeof ie=="function"&&e.jsxs("section",{"data-testid":"ecosystem-revenue-ops-entry",className:"rounded-2xl border border-emerald-300/30 bg-emerald-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-emerald-100 font-bold",children:"Revenue Operations Console"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Review pipeline-to-revenue conversion, SKU mix, and expansion-vs-renewal posture from local data."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-revenue-ops-btn",onClick:()=>{typeof ie=="function"&&ie()},className:"px-3 py-2 rounded-lg border border-emerald-200/35 bg-emerald-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/30",children:"Open Revenue Ops"})]}),L&&L.id==="channel_expansion"&&typeof ye=="function"&&e.jsxs("section",{"data-testid":"ecosystem-channel-expansion-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Channel Expansion Planner"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Plan channel models, readiness gaps, and enablement priorities for controlled growth."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-channel-expansion-btn",onClick:()=>{typeof ye=="function"&&ye()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Channel Expansion"})]}),L&&L.id==="cross_account_renewal"&&typeof pe=="function"&&e.jsxs("section",{"data-testid":"ecosystem-cross-account-renewal-entry",className:"rounded-2xl border border-amber-300/30 bg-amber-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-amber-100 font-bold",children:"Cross-Account Renewal Matrix"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Visualize renewal urgency and intervention planning across multiple accounts in one matrix."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-cross-account-renewal-btn",onClick:()=>{typeof pe=="function"&&pe()},className:"px-3 py-2 rounded-lg border border-amber-200/35 bg-amber-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100 hover:bg-amber-500/30",children:"Open Cross-Account Renewal"})]}),L&&L.id==="executive_scale"&&typeof K=="function"&&e.jsxs("section",{"data-testid":"ecosystem-executive-scale-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Executive Scale Dashboard"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open one-screen executive scale operations view with partner, account, rollout, and revenue signals."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-executive-scale-btn",onClick:()=>{typeof K=="function"&&K()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Executive Scale"})]}),L&&L.id==="ecosystem_portfolio"&&typeof H=="function"&&e.jsxs("section",{"data-testid":"ecosystem-portfolio-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Ecosystem Portfolio Console"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Operate portfolio lines and attachment paths across product, services, support, and channels."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-ecosystem-portfolio-btn",onClick:()=>{typeof H=="function"&&H()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Ecosystem Portfolio"})]}),L&&L.id==="service_line"&&typeof W=="function"&&e.jsxs("section",{"data-testid":"ecosystem-service-line-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Service Line Operating Layer"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Manage service-line capacity, utilization, and operating health for delivery discipline."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-service-line-btn",onClick:()=>{typeof W=="function"&&W()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Service Line Console"})]}),L&&L.id==="partner_network_governance"&&typeof Z=="function"&&e.jsxs("section",{"data-testid":"ecosystem-partner-network-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Partner Network Governance"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Track tier governance, compliance posture, and escalation/reactivation flows across the partner network."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-partner-network-governance-btn",onClick:()=>{typeof Z=="function"&&Z()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Partner Network Governance"})]}),L&&L.id==="global_planning"&&typeof ce=="function"&&e.jsxs("section",{"data-testid":"ecosystem-global-planning-entry",className:"rounded-2xl border border-blue-300/30 bg-blue-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-blue-100 font-bold",children:"Global Account & Region Planning"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Plan global account and region expansion using deployment, compliance, and channel-fit overlays."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-global-planning-btn",onClick:()=>{typeof ce=="function"&&ce()},className:"px-3 py-2 rounded-lg border border-blue-200/35 bg-blue-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/30",children:"Open Global Planning"})]}),L&&L.id==="ecosystem_revenue"&&e.jsxs("section",{"data-testid":"ecosystem-ecosystem-revenue-entry",className:"rounded-2xl border border-emerald-300/30 bg-emerald-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-emerald-100 font-bold",children:"Ecosystem Revenue Mix Planner"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Optimize ecosystem revenue mix across product, services, support, and partner-sourced streams."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-ecosystem-revenue-btn",onClick:()=>{typeof fe=="function"&&fe()},className:"px-3 py-2 rounded-lg border border-emerald-200/35 bg-emerald-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/30",children:"Open Ecosystem Revenue"})]}),L&&L.id==="board_operating_pack"&&typeof me=="function"&&e.jsxs("section",{"data-testid":"ecosystem-board-operating-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Board / Investor Operating Pack"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Generate board operating packs with risk framing and evidence-linked appendix references."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-board-operating-pack-btn",onClick:()=>{typeof me=="function"&&me()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Board Operating Pack"})]}),L&&L.id==="licensed_operator"&&typeof ke=="function"&&e.jsxs("section",{"data-testid":"ecosystem-licensed-operator-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Licensed Operator Framework"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Prepare controlled licensed/regional operator launch packs with governance prerequisites."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-licensed-operator-btn",onClick:()=>{typeof ke=="function"&&ke()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Licensed Operator Framework"})]}),L&&L.id==="ecosystem_command"&&typeof Pe=="function"&&e.jsxs("section",{"data-testid":"ecosystem-ecosystem-command-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Ecosystem Command Center"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open top-level ecosystem command surface with portfolio, network, service, planning, and revenue posture."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-ecosystem-command-btn",onClick:()=>{typeof Pe=="function"&&Pe()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Ecosystem Command"})]}),L&&L.id==="shift_console"&&e.jsxs("section",{"data-testid":"ecosystem-shift-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Shift Console"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open role-based shift operations, handoff notes, and signed summary exports."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-shift-btn",onClick:()=>{typeof _e=="function"&&_e()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Shift Console"})]}),L&&L.id==="incident_mode"&&e.jsxs("section",{"data-testid":"ecosystem-incident-entry",className:"rounded-2xl border border-rose-300/30 bg-rose-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-rose-100 font-bold",children:"Incident Mode"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Open incident workflow to capture timeline, attach nodes, apply playbooks, and export incident bundles."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-incident-btn",onClick:()=>{typeof ne=="function"&&ne()},className:"px-3 py-2 rounded-lg border border-rose-200/35 bg-rose-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-rose-100 hover:bg-rose-500/30",children:"Open Incident Mode"})]}),L&&L.id==="policy_rollout"&&e.jsxs("section",{"data-testid":"ecosystem-policy-rollout-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Policy Rollout"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Launch signed policy rollout controls with diff preview and rollback history."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-policy-rollout-btn",onClick:()=>{typeof we=="function"&&we()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Policy Rollout"})]}),L&&L.id==="offline_update_packs"&&e.jsxs("section",{"data-testid":"ecosystem-offline-updates-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Offline Update Packs"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Verify signed update packs, assign node rings, and promote update lanes with explicit control."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-offline-updates-btn",onClick:()=>{typeof De=="function"&&De()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Offline Updates"})]}),L&&L.id==="mission_scheduler"&&e.jsxs("section",{"data-testid":"ecosystem-mission-scheduler-entry",className:"rounded-2xl border border-cyan-300/30 bg-cyan-500/10 p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-100 font-bold",children:"Mission Scheduler"}),e.jsx("div",{className:"text-[11px] text-slate-200",children:"Run NodeChain mission templates with schedules, dry-run controls, and mission history visibility."}),e.jsx("button",{type:"button","data-testid":"ecosystem-open-mission-scheduler-btn",onClick:()=>{typeof re=="function"&&re()},className:"px-3 py-2 rounded-lg border border-cyan-200/35 bg-cyan-500/20 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/30",children:"Open Mission Scheduler"})]}),L&&L.id==="sales_console"&&e.jsx(Bw,{}),L&&L.id==="pilot_kit"&&e.jsx(Fw,{}),L&&L.id==="white_label"&&e.jsx(Qw,{}),L&&L.id==="partner_console"&&e.jsx(t1,{}),L&&L.id==="certifications"&&e.jsx(s1,{}),L&&L.id==="board_console"&&e.jsx(i1,{}),L&&L.id==="enterprise_policy"&&e.jsx(l1,{}),L&&L.id==="customer_success"&&e.jsx(d1,{}),L&&L.id==="expansion_planner"&&e.jsx(m1,{})]})]})]}):null}function w1(t){const r=String(t||"grey").toLowerCase();return r==="green"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":r==="amber"?"border-amber-300/40 bg-amber-500/10 text-amber-100":r==="red"?"border-rose-300/40 bg-rose-500/10 text-rose-100":r==="blue"||r==="cyan"?"border-cyan-300/35 bg-cyan-500/10 text-cyan-100":"border-slate-300/20 bg-slate-500/10 text-slate-200"}function ir({title:t,subtitle:r,statusLabel:n,tone:s="grey",rows:a=[],testId:o=""}){return e.jsxs("article",{"data-testid":o||void 0,"aria-label":t,className:"rounded-2xl border border-white/10 bg-black/35 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:t}),r?e.jsx("div",{className:"text-[10px] text-slate-500 font-mono mt-0.5",children:r}):null]}),e.jsx("div",{className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${w1(s)}`,children:n||"unknown"})]}),e.jsx("div",{className:"grid grid-cols-1 gap-1.5",children:(Array.isArray(a)?a:[]).map(c=>e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[10px] font-mono",children:[e.jsx("span",{className:"text-slate-500",children:c.label}),e.jsx("span",{className:"text-slate-200 text-right break-all",children:c.value})]},c.id))})]})}function v1({vaultState:t,onPromptSave:r,onOpenSettings:n}){const s=t&&typeof t=="object"?t:{},a=!!s.locked;return e.jsxs("section",{"data-testid":"vault-panel-plus","aria-label":"Vault Panel Plus",className:"rounded-2xl border border-white/10 bg-black/35 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"VaultPanel+"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Local profile custody, restore posture, and policy binding."})]}),e.jsx("div",{className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${a?"border-amber-300/40 bg-amber-500/10 text-amber-100":"border-emerald-300/30 bg-emerald-500/10 text-emerald-100"}`,children:a?"locked":"unlocked"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1.5 text-[10px] font-mono",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-slate-500",children:"Active Profile"}),e.jsx("span",{className:"text-slate-200 break-all",children:String(s.activeProfile||"default")})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-slate-500",children:"Import/Export"}),e.jsx("span",{className:"text-slate-200 break-all",children:String(s.exportImportStatus||"idle")})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-slate-500",children:"Policy Bound"}),e.jsx("span",{className:"text-slate-200",children:s.policyBound?"yes":"no"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"vault-panel-plus-save-btn",onClick:r,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Prompt Vault Save"}),e.jsx("button",{type:"button","data-testid":"vault-panel-plus-settings-btn",onClick:n,className:"px-2.5 py-1.5 rounded border border-white/10 bg-white/5 text-[10px] font-mono uppercase tracking-[0.14em] text-slate-200 hover:bg-white/10",children:"Settings"})]})]})}const Me=Object.freeze({STABLE:"stable",PILOT:"pilot",EXPERIMENTAL:"experimental",INTERNAL:"internal"}),tu=Object.freeze({[Me.STABLE]:"Stable",[Me.PILOT]:"Pilot",[Me.EXPERIMENTAL]:"Experimental",[Me.INTERNAL]:"Internal"}),j1=Object.freeze({[Me.STABLE]:"maturity-label-stable",[Me.PILOT]:"maturity-label-pilot",[Me.EXPERIMENTAL]:"maturity-label-experimental",[Me.INTERNAL]:"maturity-label-internal"});function ru(t,r={}){const n=!!(r.internalGtmMode||r.devUnlock),s=!!r.includeExperimental;switch(t){case Me.STABLE:return!0;case Me.PILOT:return n;case Me.EXPERIMENTAL:return n&&s;case Me.INTERNAL:return n;default:return!1}}const k1={[Me.STABLE]:"border-emerald-400/35 bg-emerald-500/10 text-emerald-100",[Me.PILOT]:"border-amber-400/35 bg-amber-500/10 text-amber-100",[Me.EXPERIMENTAL]:"border-violet-400/35 bg-violet-500/10 text-violet-100",[Me.INTERNAL]:"border-slate-400/35 bg-slate-500/10 text-slate-200"};function N1({maturity:t=Me.STABLE,className:r=""}){const n=tu[t]?t:Me.STABLE;return e.jsx("span",{"data-testid":j1[n],"data-maturity":n,className:`inline-flex items-center px-1.5 py-0.5 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${k1[n]} ${r}`,children:tu[n]})}function ba({onOpen:t,testId:r,label:n,className:s}){return typeof t!="function"?null:e.jsx("button",{type:"button","data-testid":r,onClick:t,className:s,children:n})}function S1(t){return t?"green":"red"}function Fi(t){const r=String(t||"info").toLowerCase();return r==="critical"?"red":r==="warning"||r==="degraded"?"amber":r==="info"?"blue":"grey"}function nu(t){const r=String(t||"").trim();if(!r)return"n/a";const n=new Date(r);return Number.isNaN(n.getTime())?r:n.toLocaleString()}function C1({open:t,onClose:r,runtimeState:n,events:s,onOpenSettings:a,onOpenFleet:o,onOpenRecovery:c,onOpenAppliance:l,onOpenAirGap:u,onOpenTrustFabric:x,onOpenHardwareAppliance:p,onOpenCourierTransfer:d,onOpenContinuityDrills:m,onOpenProcurementCommand:f,onOpenTamperSimulation:b,onOpenInstitutionalCommand:h,onOpenDemoFlow:g,onOpenDeploymentProgram:y,onOpenTrainingDelivery:I,onOpenSupportOps:A,onOpenBuyerJourney:C,onOpenPilotConversion:w,onOpenCommercialPackages:j,onOpenFieldLaunch:E,onOpenPartnerRollout:N,onOpenBuyerOps:_,onOpenDemoToPilot:S,onOpenPilotExpansion:R,onOpenRenewalRisk:$,onOpenLaunchWeek:U,onOpenFollowupGenerator:P,onOpenFieldFeedback:D,onOpenPartnerCertification:z,onOpenManagedServices:F,onOpenStrategicAccount:J,onOpenPortfolioRollout:ee,onOpenRevenueOps:ie,onOpenChannelExpansion:ye,onOpenCrossAccountRenewal:pe,onOpenExecutiveScale:K,onOpenEcosystemPortfolio:H,onOpenServiceLine:W,onOpenPartnerNetworkGovernance:Z,onOpenGlobalPlanning:ce,onOpenEcosystemRevenue:fe,onOpenBoardOperatingPack:me,onOpenLicensedOperator:ke,onOpenEcosystemCommand:Pe,onOpenShift:_e,onOpenIncidentMode:ne,onOpenPolicyRollout:we,onOpenOfflineUpdates:De,onOpenMissionScheduler:re,onOpenNodeChain:ae,onOpenWatchdog:M,onOpenFirstBoot:V,onOpenSplitWorkspace:G,showInternalSurfaces:te=!1}){if(!t)return null;const de=n&&typeof n=="object"?n:{},L=Array.isArray(s)?s.slice(-80).reverse():[],be=de.providerHealth||{},Q=de.vaultState||{},We=de.proofEngine||{},B=de.relayState||{},oe=de.collabVoiceState||{},xe=de.policyState||{},Re=de.updateLane||{},$e=de.sealIdentity||{},tt=de.watchdog||{};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[120] bg-black/60 backdrop-blur-sm",onClick:r}),e.jsxs("section",{"data-testid":"mission-control","aria-label":"Mission Control",className:"fixed inset-x-4 top-16 bottom-4 z-[121] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.7)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-[0.18em] text-cyan-300 font-bold flex items-center gap-2",children:["Mission Control",e.jsx(N1,{maturity:te?Me.INTERNAL:Me.STABLE})]}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Runtime cockpit, authority feed, and control rails."})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap justify-end",children:[e.jsx(ba,{testId:"mission-control-open-fleet-btn",onOpen:o,label:"Fleet",className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20"}),e.jsx(ba,{testId:"mission-control-open-recovery-btn",onOpen:c,label:"Recovery",className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20"}),e.jsx(ba,{testId:"mission-control-open-appliance-btn",onOpen:l,label:"Appliance",className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20"}),e.jsx(ba,{testId:"mission-control-open-airgap-btn",onOpen:u,label:"AirGap",className:"px-2.5 py-1.5 rounded border border-slate-300/30 bg-slate-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-slate-100 hover:bg-slate-500/20"}),typeof x=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-trust-fabric-btn",onClick:x,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"PKI"}),typeof p=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-hardware-appliance-btn",onClick:p,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Hardware"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-courier-transfer-btn",onClick:d,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Courier"}),typeof m=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-continuity-drills-btn",onClick:m,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Drills"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-procurement-command-btn",onClick:f,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Procurement"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-tamper-simulation-btn",onClick:b,className:"px-2.5 py-1.5 rounded border border-rose-300/30 bg-rose-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-rose-100 hover:bg-rose-500/20",children:"Simulate"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-institutional-command-btn",onClick:h,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Institutional"}),typeof g=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-demo-flow-btn",onClick:g,className:"px-2.5 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/20",children:"Demo"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-deployment-program-btn",onClick:y,className:"px-2.5 py-1.5 rounded border border-blue-300/30 bg-blue-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/20",children:"Deploy"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-training-delivery-btn",onClick:I,className:"px-2.5 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/20",children:"Training"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-support-ops-btn",onClick:A,className:"px-2.5 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100 hover:bg-amber-500/20",children:"Support"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-buyer-journey-btn",onClick:C,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Buyer"}),typeof w=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-pilot-conversion-btn",onClick:w,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Pilot"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-commercial-packages-btn",onClick:j,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Commercial"}),typeof E=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-field-launch-btn",onClick:E,className:"px-2.5 py-1.5 rounded border border-blue-300/30 bg-blue-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/20",children:"Launch"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-partner-rollout-btn",onClick:N,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Partner"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-buyer-ops-btn",onClick:_,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"BuyerOps"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-demo-to-pilot-btn",onClick:S,className:"px-2.5 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/20",children:"D2P"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-pilot-expansion-btn",onClick:R,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Expand"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-renewal-risk-btn",onClick:$,className:"px-2.5 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100 hover:bg-amber-500/20",children:"Renewal"}),typeof U=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-launch-week-btn",onClick:U,className:"px-2.5 py-1.5 rounded border border-blue-300/30 bg-blue-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/20",children:"LaunchWeek"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-followup-generator-btn",onClick:P,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"FollowUp"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-field-feedback-btn",onClick:D,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Feedback"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-partner-certification-btn",onClick:z,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Certify"}),typeof F=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-managed-services-btn",onClick:F,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Managed"}),typeof J=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-strategic-account-btn",onClick:J,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Strategic"}),typeof ee=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-portfolio-rollout-btn",onClick:ee,className:"px-2.5 py-1.5 rounded border border-blue-300/30 bg-blue-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/20",children:"Portfolio"}),typeof ie=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-revenue-ops-btn",onClick:ie,className:"px-2.5 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/20",children:"Revenue"}),typeof ye=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-channel-expansion-btn",onClick:ye,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Channel"}),typeof pe=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-cross-account-renewal-btn",onClick:pe,className:"px-2.5 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100 hover:bg-amber-500/20",children:"Renewal+"}),typeof K=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-executive-scale-btn",onClick:K,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"ExecScale"}),typeof H=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-ecosystem-portfolio-btn",onClick:H,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Portfolio+"}),typeof W=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-service-line-btn",onClick:W,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Services"}),typeof Z=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-partner-network-governance-btn",onClick:Z,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"PartnerNet"}),typeof ce=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-global-planning-btn",onClick:ce,className:"px-2.5 py-1.5 rounded border border-blue-300/30 bg-blue-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/20",children:"Global"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-ecosystem-revenue-btn",onClick:fe,className:"px-2.5 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 hover:bg-emerald-500/20",children:"RevMix"}),typeof me=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-board-operating-pack-btn",onClick:me,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"BoardOps"}),typeof ke=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-licensed-operator-btn",onClick:ke,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Operator"}),typeof Pe=="function"&&e.jsx("button",{type:"button","data-testid":"mission-control-open-ecosystem-command-btn",onClick:Pe,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"EcoCmd"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-shift-btn",onClick:_e,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Shift"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-incident-btn",onClick:ne,className:"px-2.5 py-1.5 rounded border border-rose-300/30 bg-rose-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-rose-100 hover:bg-rose-500/20",children:"Incident"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-policy-rollout-btn",onClick:we,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Rollout"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-offline-updates-btn",onClick:De,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Updates"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-mission-scheduler-btn",onClick:re,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Missions"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-nodechain-btn",onClick:ae,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"NodeChain"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-watchdog-btn",onClick:M,className:"px-2.5 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100 hover:bg-amber-500/20",children:"Watchdog"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-firstboot-btn",onClick:V,className:"px-2.5 py-1.5 rounded border border-white/10 bg-white/5 text-[10px] font-mono uppercase tracking-[0.14em] text-slate-200 hover:bg-white/10",children:"First Boot"}),e.jsx("button",{type:"button","data-testid":"mission-control-open-splitworkspace-btn",onClick:G,className:"px-2.5 py-1.5 rounded border border-blue-300/30 bg-blue-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-blue-100 hover:bg-blue-500/20",children:"Split Workspace"}),e.jsx("button",{type:"button","data-testid":"mission-control-close-btn","aria-label":"Close mission control",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10 flex items-center justify-center",children:"✕"})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-3",children:[e.jsx(ir,{testId:"mission-card-provider-health",title:"Provider Health",subtitle:"Bridge + model posture",statusLabel:be.online?"healthy":"offline",tone:S1(!!be.online),rows:[{id:"provider",label:"Provider",value:String(be.activeProvider||"ollama")},{id:"model",label:"Model",value:String(be.model||"llama3")},{id:"latency",label:"Latency",value:be.latencyMs==null?"n/a":`${be.latencyMs}ms`},{id:"sweep",label:"Last Sweep",value:String(be.lastSweepResult||"unknown")}]}),e.jsx(v1,{vaultState:Q,onPromptSave:()=>{window.dispatchEvent(new window.CustomEvent("neuralshell:prompt-vault-save"))},onOpenSettings:a}),e.jsx(ir,{testId:"mission-card-proof-engine",title:"Proof Engine",subtitle:"Proof run state and bundle parity",statusLabel:String(We.lastProofStatus||"idle"),tone:String(We.lastProofStatus||"").toLowerCase().includes("fail")?"red":"blue",rows:[{id:"proof-status",label:"Last Status",value:String(We.lastProofStatus||"idle")},{id:"proof-stage",label:"Stage",value:String(We.currentStage||"idle")},{id:"proof-hash",label:"Bundle Hash",value:String(We.lastBundleHash||"n/a")},{id:"proof-parity",label:"Parity",value:String(We.parityState||"unknown")}]}),e.jsx(ir,{testId:"mission-card-relay-state",title:"Relay State",subtitle:"Proof relay + channel mapping",statusLabel:B.enabled?"enabled":"disabled",tone:B.relayError?"red":B.enabled?"blue":"grey",rows:[{id:"relay-enabled",label:"Enabled",value:B.enabled?"yes":"no"},{id:"relay-channel",label:"Channel",value:String(B.mappedChannel||"local-only")},{id:"relay-last",label:"Last Send",value:String(B.lastRelaySend||"n/a")},{id:"relay-error",label:"Error",value:String(B.relayError||"none")}]}),e.jsx(ir,{testId:"mission-card-collab-state",title:"Collab / Voice State",subtitle:"Peers, room, RTT, session health",statusLabel:String(oe.sessionHealth||"unknown"),tone:String(oe.sessionHealth||"")==="healthy"?"green":"amber",rows:[{id:"collab-peers",label:"Peers",value:String(oe.peersActive??0)},{id:"collab-room",label:"Room",value:String(oe.currentRoom||"default")},{id:"collab-rtt",label:"Voice RTT",value:oe.voiceRttMs==null?"n/a":`${oe.voiceRttMs}ms`},{id:"collab-health",label:"Session",value:String(oe.sessionHealth||"unknown")}]}),e.jsx(ir,{testId:"mission-card-policy-state",title:"Policy / Enforcement",subtitle:"Enterprise policy + provider boundaries",statusLabel:String(xe.activePolicyProfile||"none"),tone:xe.offlineOnly?"green":"amber",rows:[{id:"policy-active",label:"Profile",value:String(xe.activePolicyProfile||"none")},{id:"policy-ring",label:"Update Ring",value:String(xe.updateRing||"stable")},{id:"policy-offline",label:"Offline Only",value:xe.offlineOnly?"true":"false"},{id:"policy-approved",label:"Providers",value:(xe.approvedProviders||[]).join(", ")||"n/a"}]}),e.jsx(ir,{testId:"mission-card-update-lane",title:"Update Lane",subtitle:"Signature verification + staged updates",statusLabel:String(Re.signatureState||"unknown"),tone:String(Re.signatureState||"")==="verified"?"green":"amber",rows:[{id:"update-version",label:"Version",value:String(Re.currentVersion||"unknown")},{id:"update-check",label:"Last Check",value:String(Re.lastUpdateCheck||"n/a")},{id:"update-signature",label:"Signature",value:String(Re.signatureState||"unknown")},{id:"update-staged",label:"Staged",value:Re.stagedUpdateAvailable?"available":"none"}]}),e.jsx(ir,{testId:"mission-card-seal-identity",title:"SEAL / Identity",subtitle:"Machine trust + branding profile",statusLabel:String($e.machineTrust||"unknown"),tone:String($e.machineTrust||"")==="auditor"?"amber":"green",rows:[{id:"seal-id",label:"Seal",value:String($e.sealIdentity||"unknown")},{id:"seal-trust",label:"Trust",value:String($e.machineTrust||"unknown")},{id:"seal-branding",label:"White-Label",value:String($e.whiteLabelProfile||"default")}]}),e.jsx(ir,{testId:"mission-card-watchdog",title:"Runtime Watchdog",subtitle:"Supervisor liveness and bridge process",statusLabel:String(tt.status||"unknown"),tone:String(tt.status||"")==="running"?"green":"amber",rows:[{id:"watchdog-status",label:"Status",value:String(tt.status||"unknown")},{id:"watchdog-pid",label:"PID",value:tt.pid==null?"n/a":String(tt.pid)},{id:"watchdog-ws",label:"WS Bridge",value:tt.wsRunning?"running":"stopped"},{id:"watchdog-refreshed",label:"Refreshed",value:nu(de.refreshedAt||"")}]})]}),e.jsxs("section",{"data-testid":"mission-control-event-feed","aria-label":"Runtime Event Feed",className:"rounded-2xl border border-white/10 bg-black/30 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Runtime Event Feed"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Chronological stream of proofs, policy changes, relay/runtime alerts, and watchdog events."})]}),e.jsxs("div",{className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-[0.14em] ${Fi(String(L[0]&&L[0].severity?L[0].severity:"info"))==="red"?"border-rose-300/40 bg-rose-500/10 text-rose-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100"}`,children:[L.length," events"]})]}),e.jsxs("div",{className:"max-h-64 overflow-auto space-y-1.5 pr-1",children:[L.map(Ge=>e.jsxs("article",{className:`rounded-lg border px-2 py-1.5 ${Fi(String(Ge.severity||"info"))==="red"?"border-rose-300/40 bg-rose-500/10":Fi(String(Ge.severity||"info"))==="amber"?"border-amber-300/40 bg-amber-500/10":"border-white/10 bg-black/30"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-200",children:String(Ge.type||"runtime.event")}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:nu(String(Ge.at||""))})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:[String(Ge.source||"runtime")," · ",String(Ge.severity||"info")]})]},Ge.id)),L.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No runtime events captured yet."})]})]})]})]})]})}const jn=[{id:"provider-sweep-success-prompt-vault-save",label:"Provider sweep success -> prompt vault save",enabled:!0,eventType:"provider.sweep.passed",actions:[{type:"prompt_vault_save"},{type:"write_audit_log",payload:{event:"provider_sweep_passed"}}]},{id:"proof-pass-share-and-snapshot",label:"Proof pass -> offer share badge + snapshot",enabled:!0,eventType:"proof.passed",actions:[{type:"share_proof_badge"},{type:"snapshot_state"}]},{id:"policy-change-log-and-snapshot",label:"Policy change -> log + snapshot",enabled:!0,eventType:"policy.changed",actions:[{type:"write_audit_log",payload:{event:"policy_changed"}},{type:"snapshot_state"}]},{id:"update-verify-failed-block-apply",label:"Update verification fail -> disable auto-apply + alert",enabled:!0,eventType:"update.verification.failed",actions:[{type:"block_update_apply"},{type:"show_alert",payload:{severity:"critical",message:"Update signature verification failed."}}]},{id:"relay-failure-x3-disable-relay",label:"Relay failure x3 -> disable relay + alert",enabled:!0,eventType:"relay.failed",conditions:{relayFailureThreshold:3},actions:[{type:"disable_relay"},{type:"show_alert",payload:{severity:"degraded",message:"Relay disabled after repeated failures."}}]},{id:"collab-disconnect-mark-degraded",label:"Collab disconnect -> mark session degraded",enabled:!0,eventType:"collab.peer.left",actions:[{type:"show_alert",payload:{severity:"warning",message:"Collab session degraded after peer disconnect."}},{type:"write_audit_log",payload:{event:"collab_peer_left"}}]}];class H0{constructor(r,n={},s=[]){this.rules=Array.isArray(r)?r:[],this.handlers=n,this.logs=[],this.timers=[],this.relayFailedCount=0,this.commandAllowlist=new Set((Array.isArray(s)?s:[]).map(a=>String(a||"")))}setRules(r){this.rules=Array.isArray(r)?r:[],this.stop(),this.start()}getRules(){return this.rules.slice()}getLogs(){return this.logs.slice(-250)}start(){this.stop(),this.rules.forEach(r=>{if(!r.enabled||!Number.isFinite(Number(r.scheduleMs))||Number(r.scheduleMs)<=0)return;const n=window.setInterval(()=>{this.dispatch({type:"nodechain.schedule.tick",at:new Date().toISOString(),payload:{scheduledRuleId:r.id}},!0).catch(()=>{})},Number(r.scheduleMs));this.timers.push(n)})}stop(){this.timers.splice(0).forEach(r=>window.clearInterval(r))}async dispatch(r,n=!1){const s={type:String(r&&r.type?r.type:""),at:String(r&&r.at?r.at:new Date().toISOString()),payload:r&&r.payload&&typeof r.payload=="object"?r.payload:{}};if(!s.type)return[];s.type==="relay.failed"&&(this.relayFailedCount+=1),s.type==="relay.sent"&&(this.relayFailedCount=0);const a=this.rules.filter(c=>!!c.enabled&&String(c.eventType||"")===s.type),o=[];for(const c of a){const l=await this.executeRule(c,s,n);this.logs.push(l),o.push(l)}return o}async executeRule(r,n,s){const a={id:`nodechain-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,at:new Date().toISOString(),ruleId:String(r.id||"unknown-rule"),eventType:String(n.type||"unknown-event"),dryRun:!!s,status:"executed",detail:"",actions:[]};if(!this.conditionsPass(r,n))return{...a,status:"skipped",detail:"Conditions not met."};for(const o of Array.isArray(r.actions)?r.actions:[]){const c=String(o&&o.type?o.type:"");if(c){if(s){a.actions.push({type:c,status:"dry-run",detail:"Action simulated."});continue}try{const l=await this.runAction(c,o&&o.payload?o.payload:{});a.actions.push({type:c,status:"ok",detail:l})}catch(l){a.actions.push({type:c,status:"failed",detail:l&&l.message?l.message:String(l)}),a.status="failed",a.detail=`Action ${c} failed.`}}}return a.detail||(a.detail=a.actions.length?`${a.actions.length} action(s) evaluated.`:"No actions configured."),a}conditionsPass(r,n){const s=r&&r.conditions&&typeof r.conditions=="object"?r.conditions:{},a=Number(s.relayFailureThreshold||0);if(a>0&&this.relayFailedCountString(c[u])!==String(x))}async runAction(r,n){if(r==="show_alert")return await Promise.resolve(this.handlers.showAlert&&this.handlers.showAlert(n)),"Alert emitted.";if(r==="open_panel")return await Promise.resolve(this.handlers.openPanel&&this.handlers.openPanel(n)),"Panel opened.";if(r==="share_proof_badge")return await Promise.resolve(this.handlers.shareProofBadge&&this.handlers.shareProofBadge(n)),"Proof badge flow triggered.";if(r==="snapshot_state")return await Promise.resolve(this.handlers.snapshotState&&this.handlers.snapshotState(n)),"State snapshot captured.";if(r==="disable_relay")return await Promise.resolve(this.handlers.disableRelay&&this.handlers.disableRelay(n)),"Relay disabled.";if(r==="block_update_apply")return await Promise.resolve(this.handlers.blockUpdateApply&&this.handlers.blockUpdateApply(n)),"Update apply blocked.";if(r==="prompt_vault_save")return await Promise.resolve(this.handlers.promptVaultSave&&this.handlers.promptVaultSave(n)),"Vault save prompt emitted.";if(r==="write_audit_log")return await Promise.resolve(this.handlers.writeAuditLog&&this.handlers.writeAuditLog(n)),"Audit entry recorded.";if(r==="switch_safe_policy")return await Promise.resolve(this.handlers.switchSafePolicy&&this.handlers.switchSafePolicy(n)),"Safe policy profile applied.";if(r==="run_local_script"){const s=String(n&&n.commandId?n.commandId:"").trim();if(!s||!this.commandAllowlist.has(s))throw new Error(`Command '${s||""}' is not in NodeChain allowlist.`);return await Promise.resolve(this.handlers.runLocalScript&&this.handlers.runLocalScript(n)),`Allowlisted command '${s}' executed.`}throw new Error(`Unsupported NodeChain action type: ${r}`)}}const W0="neuralshell_runtime_event_feed_v1",Il="neuralshell:runtime-event";function _1(t){const r=t&&typeof t=="object"?t:{},n={};return Object.entries(r).forEach(([s,a])=>{const o=String(s||""),c=o.toLowerCase();if(c.includes("token")||c.includes("secret")||c.includes("apikey")||c.includes("password")||c.includes("passphrase")){n[o]="[redacted]";return}n[o]=a}),n}function Pl(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(W0)||"[]");return Array.isArray(t)?t.filter(Boolean):[]}catch{return[]}}function A1(t){typeof window>"u"||!window.localStorage||window.localStorage.setItem(W0,JSON.stringify((Array.isArray(t)?t:[]).slice(-400)))}function X(t,r={},n={}){if(typeof window>"u")return null;const s={id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,at:new Date().toISOString(),type:String(t||"runtime.event"),source:String(n.source||"runtime"),severity:n.severity||"info",payload:_1(r)},a=[...Pl(),s].slice(-400);return A1(a),window.dispatchEvent(new window.CustomEvent(Il,{detail:s})),s}function K0(t){if(typeof window>"u"||typeof t!="function")return()=>{};const r=n=>{const s=n,a=s&&s.detail?s.detail:null;a&&t(a)};return window.addEventListener(Il,r),()=>window.removeEventListener(Il,r)}function E1({rule:t,onChange:r}){const n=t&&typeof t=="object"?t:null;if(!n)return e.jsx("div",{className:"rounded-xl border border-white/10 bg-black/20 p-3 text-[10px] font-mono text-slate-500",children:"Select a rule to edit."});const s=Number(n&&n.conditions&&Number.isFinite(Number(n.conditions.relayFailureThreshold))?Number(n.conditions.relayFailureThreshold):0);return e.jsxs("section",{"data-testid":"nodechain-rule-editor",className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Rule Editor"}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Label",e.jsx("input",{value:String(n.label||""),onChange:a=>r({...n,label:a.target.value}),className:"mt-1 w-full rounded border border-white/10 bg-black/40 px-2 py-1"})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Event Type",e.jsx("input",{value:String(n.eventType||""),onChange:a=>r({...n,eventType:a.target.value}),className:"mt-1 w-full rounded border border-white/10 bg-black/40 px-2 py-1"})]}),e.jsxs("label",{className:"inline-flex items-center gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:!!n.enabled,onChange:a=>r({...n,enabled:!!a.target.checked})}),"Enabled"]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Relay Failure Threshold (0 = disabled)",e.jsx("input",{type:"number",min:"0",value:s,onChange:a=>{const o=Math.max(0,Number(a.target.value||0));r({...n,conditions:{...n.conditions||{},relayFailureThreshold:o}})},className:"mt-1 w-full rounded border border-white/10 bg-black/40 px-2 py-1"})]})]})}const V0="neuralshell_nodechain_rules_v1",I1=["releaseHealth:check","audit:verify","verification:run"],su=["provider.sweep.passed","provider.sweep.failed","vault.unlocked","vault.locked","proof.started","proof.passed","proof.failed","relay.sent","relay.failed","policy.changed","update.verification.failed","collab.peer.joined","collab.peer.left","runtime.watchdog.alert"];function Ui(){if(typeof window>"u"||!window.localStorage)return jn;try{const t=JSON.parse(window.localStorage.getItem(V0)||"[]");return!Array.isArray(t)||!t.length?jn:t}catch{return jn}}function P1({open:t,onClose:r,onSnapshotRequest:n,onOpenPanel:s}){const[a,o]=i.useState(()=>Ui()),[c,l]=i.useState(()=>String(Ui()[0]&&Ui()[0].id||"")),[u,x]=i.useState([]),[p,d]=i.useState(!1),[m,f]=i.useState(su[0]),[b,h]=i.useState(!0),g=i.useRef(null);i.useEffect(()=>{typeof window<"u"&&window.localStorage&&window.localStorage.setItem(V0,JSON.stringify(a||[]))},[a]);const y=i.useCallback(C=>new H0(C||[],{showAlert:j=>{X("nodechain.alert",j||{},{severity:String(j&&j.severity?j.severity:"warning"),source:"nodechain"})},openPanel:j=>{const E=String(j&&j.panel?j.panel:"");typeof s=="function"&&s(E)},shareProofBadge:async()=>{window.api&&window.api.system&&typeof window.api.system.openExternal=="function"&&await window.api.system.openExternal("https://raw.githubusercontent.com/Z3r0DayZion-install/NeuralShell/badges/proof_badge.svg")},snapshotState:async()=>{typeof n=="function"&&await n()},disableRelay:async()=>{if(!(window.api&&window.api.settings&&typeof window.api.settings.get=="function"))return;const j=await window.api.settings.get();await window.api.settings.update({...j||{},proofRelayEnabled:!1})},blockUpdateApply:async()=>{window.api&&window.api.autoUpdate&&typeof window.api.autoUpdate.setPolicy=="function"&&await window.api.autoUpdate.setPolicy({autoApply:!1,blockedBy:"nodechain"})},promptVaultSave:async()=>{window.dispatchEvent(new window.CustomEvent("neuralshell:prompt-vault-save"))},writeAuditLog:async j=>{window.api&&window.api.audit&&typeof window.api.audit.append=="function"&&await window.api.audit.append({event:"nodechain_action",...j||{}})},switchSafePolicy:async()=>{if(!(window.api&&window.api.settings&&typeof window.api.settings.get=="function"))return;const j=await window.api.settings.get();await window.api.settings.update({...j||{},offlineOnlyEnforced:!0,allowRemoteBridge:!1,autoUpdateChannel:"frozen"})},runLocalScript:async j=>{if(!(window.api&&window.api.command&&typeof window.api.command.run=="function"))return;const E=String(j&&j.commandId?j.commandId:"");await window.api.command.run(E,j&&j.args?j.args:[])}},I1),[s,n]);i.useEffect(()=>{const C=y(a);return g.current=C,C.start(),()=>{C.stop(),g.current=null}},[y,a]);const I=async()=>{if(g.current){d(!0);try{const C=await g.current.dispatch({type:m,at:new Date().toISOString(),payload:{source:"manual-trigger"}},b),w=g.current.getLogs();x(w),X("nodechain.manual.dispatch",{eventType:m,dryRun:b,rulesEvaluated:Array.isArray(C)?C.length:0},{source:"nodechain",severity:"info"})}finally{d(!1)}}},A=(a||[]).find(C=>String(C.id||"")===c)||null;return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[122] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"nodechain-panel",className:"fixed inset-x-8 top-20 bottom-8 z-[123] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.7)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"NodeChain Runtime Engine"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Local rule listeners, dry-run simulation, action logs, and allowlisted automation."})]}),e.jsx("button",{type:"button","data-testid":"nodechain-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden grid grid-cols-1 xl:grid-cols-[420px_1fr]",children:[e.jsxs("div",{className:"border-r border-white/10 p-3 overflow-auto space-y-3",children:[e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Manual Event Dispatch"}),e.jsx("select",{"data-testid":"nodechain-event-select",value:m,onChange:C=>f(C.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200",children:su.map(C=>e.jsx("option",{value:C,children:C},C))}),e.jsxs("label",{className:"inline-flex items-center gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:b,onChange:C=>h(!!C.target.checked)}),"Dry-run mode"]}),e.jsx("button",{type:"button","data-testid":"nodechain-run-event-btn",disabled:p,onClick:I,className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 disabled:opacity-60",children:p?"Running...":"Dispatch Event"})]}),e.jsx("div",{className:"space-y-2",children:(a||[]).map(C=>e.jsxs("button",{type:"button","data-testid":`nodechain-rule-${C.id}`,onClick:()=>l(String(C.id||"")),className:`w-full rounded-xl border p-2 text-left ${String(C.id||"")===c?"border-cyan-300/30 bg-cyan-500/10":"border-white/10 bg-black/20 hover:bg-white/5"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:String(C.label||C.id)}),e.jsxs("label",{className:"inline-flex items-center gap-1 text-[9px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:!!C.enabled,onChange:w=>{w.stopPropagation(),o(j=>Array.isArray(j)?j.map(E=>String(E.id||"")===String(C.id||"")?{...E,enabled:!!w.target.checked}:E):j)}}),"enabled"]})]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500 mt-0.5",children:String(C.eventType||"unknown")})]},C.id))})]}),e.jsxs("div",{className:"p-3 overflow-auto space-y-3",children:[e.jsx(E1,{rule:A,onChange:C=>{o(w=>Array.isArray(w)?w.map(j=>String(j.id||"")===String(C.id||"")?C:j):w)}}),e.jsxs("section",{"data-testid":"nodechain-logs",className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Execution Logs"}),e.jsxs("div",{className:"max-h-96 overflow-auto space-y-1.5 pr-1",children:[(u||[]).slice(-120).reverse().map(C=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[10px] font-mono",children:[e.jsx("span",{className:"text-slate-200",children:C.ruleId}),e.jsx("span",{className:"text-slate-500",children:String(C.status||"unknown")})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:[C.eventType," · ",C.at]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:C.detail})]},C.id)),(!u||u.length===0)&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No rule execution logs yet."})]})]})]})]})]})]}):null}function R1(t){const r=String(t||"info").toLowerCase();return r==="critical"?"border-rose-300/40 bg-rose-500/10 text-rose-100":r==="degraded"?"border-amber-300/40 bg-amber-500/10 text-amber-100":r==="warning"?"border-amber-300/30 bg-amber-500/10 text-amber-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100"}function O1({open:t,alerts:r=[],onClose:n,onAcknowledge:s}){return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[124] bg-black/50",onClick:n}),e.jsxs("aside",{"data-testid":"runtime-alerts-drawer","aria-label":"Runtime Alerts",className:"fixed right-4 top-16 bottom-4 z-[125] w-[27.5rem] rounded-2xl border border-amber-300/30 bg-slate-950 shadow-[0_18px_80px_rgba(0,0,0,0.7)] flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-amber-300 font-bold",children:"Runtime Watchdog Alerts"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Sticky failures remain visible until acknowledged."})]}),e.jsx("button",{type:"button","data-testid":"runtime-alerts-close-btn",onClick:n,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3 space-y-2",children:[(Array.isArray(r)?r:[]).map(a=>e.jsxs("article",{className:`rounded-xl border p-3 ${R1(a.severity)}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[10px] font-mono uppercase tracking-[0.14em]",children:String(a.source||"watchdog")}),e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em]",children:String(a.severity||"info")})]}),e.jsx("div",{className:"text-[10px] font-mono mt-1",children:String(a.message||"")}),e.jsx("div",{className:"text-[9px] font-mono opacity-90 mt-1",children:String(a.suggestedAction||"")}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-300 mt-1",children:[String(a.at||""),a.recoveredAt?` · recovered ${a.recoveredAt}`:""]}),e.jsx("div",{className:"mt-2 flex items-center justify-end",children:e.jsx("button",{type:"button","data-testid":`runtime-alert-ack-${a.id}`,onClick:()=>s(a.id),className:"px-2 py-1 rounded border border-white/20 bg-black/25 text-[9px] font-mono uppercase tracking-[0.12em]",children:a.acknowledged?"Acknowledged":"Acknowledge"})})]},a.id)),(!r||r.length===0)&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No active watchdog alerts."})]})]})]}):null}const T1=864e5;function bt(t){const r=new Date(t);return Number.isFinite(r.getTime())?r:null}function An(t){return t?t.type===Ve.EVENT?bt(t.startAt):t.type===Ve.DEADLINE?bt(t.dueAt):bt(t.remindAt||t.createdAt):null}function G0(t){return t?t.type===Ve.EVENT?bt(t.endAt||t.startAt):An(t):null}function au(t){const r=t instanceof Date?t:bt(t);return r?[r.getFullYear(),String(r.getMonth()+1).padStart(2,"0"),String(r.getDate()).padStart(2,"0")].join("-"):""}function oc(t,r){const n=An(t),s=An(r),a=n?n.getTime():Number.MAX_SAFE_INTEGER,o=s?s.getTime():Number.MAX_SAFE_INTEGER;return a!==o?a-o:String(t.title||"").localeCompare(String(r.title||""))}function M1(t=[],r=new Date){const n=au(r);return(Array.isArray(t)?t:[]).filter(s=>au(An(s))===n).sort(oc)}function ic(t=[],r=new Date,n=5){var o;const s=((o=bt(r))==null?void 0:o.getTime())??Date.now(),a=Math.max(1,Number(n)||5);return(Array.isArray(t)?t:[]).filter(c=>{const l=An(c);return!l||c.type===Ve.DEADLINE&&c.completed||c.type===Ve.EVENT&&String(c.status||"").toLowerCase()==="cancelled"?!1:(G0(c)||l).getTime()>=s}).sort(oc).slice(0,a)}function D1(t=[],r=new Date){return ic(t.filter(n=>n.type===Ve.EVENT),r,1)[0]||null}function $1(t=[],r=new Date){return ic(t.filter(n=>n.type===Ve.DEADLINE),r,1)[0]||null}function L1(t=[],r=new Date){var s;const n=((s=bt(r))==null?void 0:s.getTime())??Date.now();return(Array.isArray(t)?t:[]).filter(a=>a.type===Ve.DEADLINE&&!a.completed).filter(a=>{const o=bt(a.dueAt);return o&&o.getTime()p.type===Ve.DEADLINE&&!p.completed),s=((x=bt(r))==null?void 0:x.getTime())??Date.now(),a=L1(n,r),o=n.filter(p=>p.priority==="critical"||p.priority==="high"),c=n.filter(p=>{const d=bt(p.dueAt);if(!d)return!1;const m=d.getTime()-s;return m>=0&&m<=T1}),l=a.length*4+o.length*2+c.length;return{severity:l>=8||a.some(p=>p.priority==="critical")?"CRITICAL":l>=4?"HIGH":l>=1?"NORMAL":"LOW",score:l,overdueCount:a.length,criticalCount:o.length,upcomingCount:n.length,dueSoonCount:c.length}}function F1(t=[]){const r=(Array.isArray(t)?t:[]).filter(s=>s.type===Ve.EVENT).map(s=>({item:s,start:bt(s.startAt),end:bt(s.endAt)})).filter(s=>s.start&&s.end&&s.end.getTime()>s.start.getTime()).sort((s,a)=>s.start.getTime()-a.start.getTime()),n=[];for(let s=0;s=r[s].end.getTime());a+=1)n.push([r[s].item,r[a].item]);return n}function U1(t){const r=Math.max(0,Math.round((Number(t)||0)/6e4)),n=Math.floor(r/60),s=r%60;return n<=0?`${s}m`:s===0?`${n}h`:`${n}h ${s}m`}function ou(t){const r=An(t);if(!r)return"unscheduled";if(t.type===Ve.EVENT){const n=G0(t),s=r.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),a=n?n.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):"";return a?`${s}-${a}`:s}return r.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function z1(){return Lg.map(t=>({...t}))}function H1({calendarItems:t=[],now:r=new Date}){const[n,s]=i.useState(()=>_n()),[a,o]=i.useState(()=>ur({order:"asc"})),[c,l]=i.useState(r);i.useEffect(()=>(s(_n()),u0(s)),[]),i.useEffect(()=>{l(r)},[r]),i.useEffect(()=>{const p=window.setInterval(()=>l(new Date),1e3);return()=>window.clearInterval(p)},[]),i.useEffect(()=>(o(ur({order:"asc"})),l0(()=>o(ur({order:"asc"})))),[]);const u=i.useMemo(()=>b0({sessions:n.sessions||[],calendarItems:t,proofTimestamps:a,now:c}),[t,c,n.sessions,a]),x=u.totalSessionMs>0||u.sessionCount>0;return e.jsxs("section",{"data-testid":"chrono-day-summary",className:"rounded-2xl border border-amber-300/15 bg-black/25 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.18em] text-amber-300",children:"Day Summary"}),e.jsxs("div",{className:"mt-1 text-[11px] font-mono text-slate-500",children:[u.date," · ",u.timezone]})]}),e.jsx("div",{"data-testid":"day-summary-proof-trail",className:"rounded-full border border-amber-400/25 bg-amber-500/10 px-3 py-1 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100",children:"Local proof trail"})]}),!x&&e.jsx("div",{className:"mt-3 rounded-xl border border-dashed border-white/10 bg-white/[0.02] p-3 text-[12px] font-mono text-slate-500",children:"No session time recorded today"}),e.jsxs("div",{className:"mt-3 grid gap-2 md:grid-cols-4",children:[e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Operated"}),e.jsx("div",{"data-testid":"day-summary-total-time",className:"mt-1 text-sm font-semibold tabular-nums text-slate-100",children:cr(u.totalSessionMs)})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Active"}),e.jsx("div",{"data-testid":"day-summary-active-time",className:"mt-1 text-sm font-semibold tabular-nums text-slate-100",children:cr(u.activeMs)})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Idle"}),e.jsx("div",{"data-testid":"day-summary-idle-time",className:"mt-1 text-sm font-semibold tabular-nums text-slate-100",children:cr(u.idleMs)})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Top Mode"}),e.jsx("div",{"data-testid":"day-summary-top-mode",className:"mt-1 text-sm font-semibold capitalize text-slate-100",children:u.topMode||"None"})]})]}),e.jsxs("div",{className:"mt-2 grid gap-2 md:grid-cols-4",children:[e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Proof Events"}),e.jsx("div",{"data-testid":"day-summary-proof-events",className:"mt-1 text-sm font-semibold tabular-nums text-slate-100",children:u.proofEventCount})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Deadlines Done"}),e.jsx("div",{"data-testid":"day-summary-deadlines-completed",className:"mt-1 text-sm font-semibold tabular-nums text-slate-100",children:u.deadlinesCompleted})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3 md:col-span-2",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Next Threat"}),e.jsx("div",{"data-testid":"day-summary-next-threat",className:"mt-1 text-sm font-semibold text-slate-100",children:u.nextThreat})]})]})]})}function W1(t){return t.title||String(t.eventType||"proof event").replace(/_/g," ")}function K1({limit:t=8}){const[r,n]=i.useState(()=>ur({order:"asc"}));i.useEffect(()=>(n(ur({order:"asc"})),l0(()=>n(ur({order:"asc"})))),[]);const s=i.useMemo(()=>[...r].reverse().slice(0,t),[r,t]),a=i.useMemo(()=>v0(w0(r)),[r]),o=a.status==="verified"?"Integrity: local chain verified":a.status==="mismatch"?"Integrity: chain mismatch detected":"Integrity: no local chain yet";return e.jsxs("section",{"data-testid":"proof-timeline",className:"rounded-2xl border border-violet-300/15 bg-black/25 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.18em] text-violet-300",children:"Proof Timeline"}),e.jsx("div",{className:"mt-1 text-[11px] font-mono text-slate-500",children:"Local proof trail. Timestamped locally."})]}),e.jsxs("div",{className:"rounded-full border border-violet-400/25 bg-violet-500/10 px-3 py-1 text-[10px] font-mono uppercase tracking-[0.14em] text-violet-100",children:[r.length," event",r.length===1?"":"s"]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-[10px] font-mono text-slate-500",children:[e.jsx("span",{"data-testid":"timeproof-integrity-status",children:o}),e.jsxs("span",{"data-testid":"timeproof-integrity-entry-count",children:[a.entryCount," entries"]})]}),e.jsxs("div",{className:"mt-3 space-y-2",children:[s.length===0&&e.jsx("div",{"data-testid":"proof-timeline-empty",className:"rounded-xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-[12px] font-mono text-slate-500",children:"Proof Timeline — no events recorded yet"}),s.map(c=>e.jsxs("article",{"data-testid":"proof-timeline-event",className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{"data-testid":"proof-timeline-event-title",className:"text-sm font-semibold text-slate-100",children:W1(c)}),e.jsx("div",{className:"mt-1 text-[10px] font-mono text-slate-500",children:c.sessionId?"Linked to session":"Local proof trail"})]}),e.jsx("div",{"data-testid":"proof-timeline-event-time",className:"text-right text-[11px] font-mono tabular-nums text-violet-100",children:c.localLabel})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2 text-[10px] font-mono uppercase tracking-[0.12em] text-slate-500",children:[e.jsx("span",{"data-testid":"proof-timeline-event-source",children:c.source}),c.projectName&&e.jsx("span",{children:c.projectName}),c.details&&e.jsx("span",{className:"normal-case tracking-normal text-slate-400",children:c.details})]})]},c.id))]})]})}function V1(t){return[...t.sessions||[]].sort((r,n)=>n.startedAt.localeCompare(r.startedAt))[0]||null}function zi(t){return t||"Not set"}function gs(t){const r=String(t||"").trim();return r?r.charAt(0).toUpperCase()+r.slice(1):"Focus"}function G1({projectId:t="",projectName:r=""}){const[n,s]=i.useState(()=>_n()),[a,o]=i.useState(()=>new Date),[c,l]=i.useState($a[0]);i.useEffect(()=>{const j=window.setInterval(()=>o(new Date),1e3);return()=>window.clearInterval(j)},[]),i.useEffect(()=>(s(_n()),u0(s)),[]);const u=i.useMemo(()=>fs(n),[n]),x=u||V1(n),p=i.useMemo(()=>Or(u,a),[u,a]),d=i.useMemo(()=>cy(n,a),[n,a]),m=i.useMemo(()=>dy(n,a),[n,a]),f=i.useMemo(()=>uy(n,t,a),[n,a,t]),b=String(r||t||"").trim();i.useEffect(()=>{u&&u.mode!==c&&l(u.mode)},[u,c]);const h=i.useCallback(j=>{s(ty(j))},[]),g=i.useCallback((j,E,N,_)=>{!E||!E.id||Yg({eventType:j,source:"sessionhud",projectId:E.projectId||t,projectName:E.projectName||b,sessionId:E.id,title:N,details:_})},[t,b]),y=i.useCallback(()=>{if(u)return;const j=ny(n,{projectId:t,projectName:b,mode:c,source:"local"},new Date),E=fs(j);h(j),g("session_started",E,"Session started",`Mode: ${gs((E==null?void 0:E.mode)||c)}`)},[u,n,h,t,b,g,c]),I=i.useCallback(()=>{if(!u)return;const j=sy(n,u.id,new Date),E=fs(j);h(j),g("session_paused",E,"Session paused",`Mode: ${gs((E==null?void 0:E.mode)||u.mode)}`)},[u,n,h,g]),A=i.useCallback(()=>{if(!u)return;const j=ay(n,u.id,new Date),E=fs(j);h(j),g("session_resumed",E,"Session resumed",`Mode: ${gs((E==null?void 0:E.mode)||u.mode)}`)},[u,n,h,g]),C=i.useCallback(()=>{if(!u)return;const j=oy(n,u.id,new Date),E=(j.sessions||[]).find(_=>_.id===u.id),N=Or(E,new Date);h(j),g("session_ended",E,"Session ended",`${cr(N.activeDurationMs)} active · Mode: ${gs((E==null?void 0:E.mode)||u.mode)}`)},[u,n,h,g]),w=i.useCallback(j=>{const E=j.target.value;if(l(E),u){const N=iy(n,u.id,E),_=fs(N);h(N),g("mode_changed",_,"Mode changed",`Mode: ${gs(E)}`)}},[u,n,h,g]);return e.jsxs("section",{"data-testid":"session-hud",className:"rounded-2xl border border-emerald-300/15 bg-black/25 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.18em] text-emerald-300",children:"SessionHUD"}),e.jsx("div",{className:"mt-1 text-[11px] font-mono text-slate-500",children:"Local TimeLedger, no telemetry."})]}),e.jsxs("div",{"data-testid":"session-current-run",className:"rounded-xl border border-emerald-400/25 bg-emerald-500/10 px-3 py-2 text-right",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-emerald-200",children:"Current run"}),e.jsx("div",{className:"mt-1 text-xl font-semibold tabular-nums text-emerald-50",children:u?cr(p.activeDurationMs):"No active session"})]})]}),e.jsxs("div",{className:"mt-4 grid gap-2 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Today"}),e.jsx("div",{"data-testid":"session-today-total",className:"mt-1 text-sm font-semibold tabular-nums text-slate-100",children:cr(d)})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:"Week"}),e.jsx("div",{"data-testid":"session-week-total",className:"mt-1 text-sm font-semibold tabular-nums text-slate-100",children:cr(m)})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.14em] text-slate-500",children:b?"Project":"Project context"}),e.jsx("div",{"data-testid":"session-project-total",className:"mt-1 text-sm font-semibold tabular-nums text-slate-100",children:b?cr(f):"No project"})]})]}),e.jsxs("div",{className:"mt-3 grid gap-2 md:grid-cols-[1fr_auto_auto_auto_auto]",children:[e.jsx("select",{"data-testid":"session-mode-select",value:c,onChange:w,className:"rounded-lg border border-white/10 bg-black/35 px-3 py-2 text-[12px] text-slate-100 outline-none",children:$a.map(j=>e.jsx("option",{value:j,children:j},j))}),e.jsx("button",{type:"button","data-testid":"session-start",disabled:!!u,onClick:y,className:"rounded-lg border border-emerald-400/30 bg-emerald-500/10 px-3 py-2 text-[10px] font-mono uppercase tracking-[0.14em] text-emerald-100 disabled:cursor-not-allowed disabled:opacity-40",children:"Start Session"}),e.jsx("button",{type:"button","data-testid":"session-pause",disabled:!u||u.status!=="active",onClick:I,className:"rounded-lg border border-white/10 bg-white/[0.03] px-3 py-2 text-[10px] font-mono uppercase tracking-[0.14em] text-slate-200 disabled:cursor-not-allowed disabled:opacity-40",children:"Pause"}),e.jsx("button",{type:"button","data-testid":"session-resume",disabled:!u||u.status!=="paused",onClick:A,className:"rounded-lg border border-white/10 bg-white/[0.03] px-3 py-2 text-[10px] font-mono uppercase tracking-[0.14em] text-slate-200 disabled:cursor-not-allowed disabled:opacity-40",children:"Resume"}),e.jsx("button",{type:"button","data-testid":"session-end",disabled:!u,onClick:C,className:"rounded-lg border border-rose-400/25 bg-rose-500/10 px-3 py-2 text-[10px] font-mono uppercase tracking-[0.14em] text-rose-100 disabled:cursor-not-allowed disabled:opacity-40",children:"End Session"})]}),e.jsxs("div",{className:"mt-3 grid gap-2 text-[10px] font-mono text-slate-500 md:grid-cols-3",children:[e.jsxs("div",{"data-testid":"session-started-at",children:["Started UTC: ",zi(x==null?void 0:x.startedAt)]}),e.jsxs("div",{"data-testid":"session-last-active-at",children:["Last active UTC: ",zi(x==null?void 0:x.lastActiveAt)]}),e.jsxs("div",{"data-testid":"session-ended-at",children:["Ended UTC: ",zi(x==null?void 0:x.endedAt)]})]})]})}function Hi(t=new Date){const r=t instanceof Date?t:new Date(t);return Number.isFinite(r.getTime())?[r.getFullYear(),String(r.getMonth()+1).padStart(2,"0"),String(r.getDate()).padStart(2,"0")].join("-"):""}function ha(t){const r=t instanceof Date?t:new Date(t);return Number.isFinite(r.getTime())?[r.getFullYear(),String(r.getMonth()+1).padStart(2,"0"),String(r.getDate()).padStart(2,"0")].join("-")+`T${String(r.getHours()).padStart(2,"0")}:${String(r.getMinutes()).padStart(2,"0")}`:""}function ga(t,r){return new Date(t.getTime()+r*6e4)}function iu(t){return t.type===Ve.EVENT?"border-cyan-400/25 bg-cyan-500/10 text-cyan-100":t.priority==="critical"||t.priority==="high"?"border-rose-400/30 bg-rose-500/10 text-rose-100":t.source==="task"?"border-violet-400/25 bg-violet-500/10 text-violet-100":"border-amber-400/25 bg-amber-500/10 text-amber-100"}function lu(t){return t.type===Ve.EVENT?"EVENT":t.type===Ve.REMINDER?"REMINDER":"DEADLINE"}function cu(t,r){if(!t)return"No upcoming item";const n=new Date(t.type===Ve.EVENT?t.startAt:t.dueAt||t.remindAt);if(!Number.isFinite(n.getTime()))return t.title;const s=n.getTime()-r.getTime();return`${t.title} in ${U1(s)}`}function J1({workflowId:t}){const[r,n]=i.useState(()=>new Date),[s,a]=i.useState(()=>Da()),[o,c]=i.useState(()=>Qt()),[l,u]=i.useState(()=>et(t)),[x,p]=i.useState(""),[d,m]=i.useState(()=>ha(ga(new Date,30))),[f,b]=i.useState(()=>ha(ga(new Date,60))),[h,g]=i.useState(""),[y,I]=i.useState(()=>Hi(new Date)),[A,C]=i.useState("normal");i.useEffect(()=>{const F=window.setInterval(()=>n(new Date),3e4);return()=>window.clearInterval(F)},[]),i.useEffect(()=>{a(Da()),c(Qt()),u(et(t));const F=Ug(a),J=Lp(c),ee=qa(u,t);return()=>{F(),J(),ee()}},[t]);const w=i.useMemo(()=>e0({events:s,deadlines:o,workpadTasks:(l.tasks||[]).filter(F=>!F.done&&F.dueDate)}),[o,s,l.tasks]),j=i.useMemo(()=>M1(w,r),[w,r]),E=i.useMemo(()=>ic(w,r,5),[w,r]),N=i.useMemo(()=>D1(w,r),[w,r]),_=i.useMemo(()=>$1(w,r),[w,r]),S=i.useMemo(()=>B1(w,r),[w,r]),R=i.useMemo(()=>F1(w),[w]),$=i.useMemo(()=>z1(),[]),U=i.useCallback(()=>{const F=String(x||"").trim(),J=new Date(d),ee=new Date(f);if(!F){ge("Enter an event title","warning");return}if(!Number.isFinite(J.getTime())||!Number.isFinite(ee.getTime())||ee<=J){ge("Choose a valid event window","warning");return}const ie=Fg(s,{id:`event-${Date.now()}`,title:F,startAt:J.toISOString(),endAt:ee.toISOString(),category:"local",status:"confirmed",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()});Bg(ie),a(ie),p(""),m(ha(ga(ee,30))),b(ha(ga(ee,60))),ge("Local event saved","success")},[f,d,x,s]),P=i.useCallback(()=>{const F=String(h||"").trim();if(!F){ge("Enter a deadline title","warning");return}const J=Mp(o,{id:`deadline-${Date.now()}`,title:F,date:y||Hi(r),priority:A});Ta(J),c(J),g(""),ge("Deadline saved","success")},[y,A,h,o,r]),D=i.useCallback(()=>{if(!o.length){ge("No deadlines to export","warning");return}$s(`neuralshell-deadlines-${Date.now()}.ics`,Vb(o)),ge("ICS calendar file downloaded","success")},[o]),z=i.useCallback(()=>{const F=new Date;n(F),I(Hi(F))},[]);return e.jsx("div",{"data-testid":"chrono-hud",className:"h-full min-h-0 overflow-auto bg-[radial-gradient(circle_at_top,rgba(8,145,178,0.18),transparent_34%),#020617] text-slate-100",children:e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("section",{"data-testid":"chrono-now-bar",className:"rounded-2xl border border-cyan-300/25 bg-black/30 p-4 shadow-[0_0_28px_rgba(34,211,238,0.08)]",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-bold uppercase tracking-[0.24em] text-cyan-300",children:[e.jsx(Ux,{size:15}),"ChronoHUD"]}),e.jsx("div",{"data-testid":"chrono-now-zone",className:"mt-2 text-2xl font-semibold tabular-nums text-cyan-50",children:r.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}),e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-[0.12em] text-slate-500",children:r.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"})})]}),e.jsx("button",{type:"button","data-testid":"calendar-today-btn",onClick:z,className:"rounded-lg border border-cyan-400/25 bg-cyan-500/10 px-3 py-2 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/15",children:"Today"})]}),e.jsxs("div",{className:"mt-4 grid gap-2 md:grid-cols-2",children:[e.jsxs("div",{"data-testid":"chrono-next-zone",className:"rounded-xl border border-white/10 bg-white/[0.03] p-3 text-[12px] font-mono text-slate-200",children:[e.jsxs("div",{children:["Next event: ",N?cu(N,r):"none scheduled"]}),e.jsxs("div",{className:"mt-1 text-amber-100",children:["Next deadline: ",_?cu(_,r):"none scheduled"]})]}),e.jsxs("div",{"data-testid":"chrono-later-zone",className:"rounded-xl border border-white/10 bg-white/[0.03] p-3 text-[12px] font-mono text-slate-200",children:["Later: ",E.length," queued mission item",E.length===1?"":"s"]})]})]}),e.jsx(G1,{projectId:t||"",projectName:t||""}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[1fr_1fr]",children:[e.jsx(H1,{calendarItems:w,now:r}),e.jsx(K1,{})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[1fr_1.05fr]",children:[e.jsxs("section",{"data-testid":"chrono-today-timeline",className:"rounded-2xl border border-cyan-300/15 bg-black/25 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-bold uppercase tracking-[0.18em] text-cyan-300",children:[e.jsx(zx,{size:14}),"Today Timeline"]}),e.jsxs("div",{className:"mt-3 space-y-2",children:[j.length===0&&e.jsx("div",{className:"rounded-xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-[12px] font-mono text-slate-500",children:"No mission windows or threat markers today."}),j.map(F=>e.jsxs("article",{className:`rounded-xl border p-3 ${iu(F)}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.16em] opacity-80",children:lu(F)}),e.jsx("div",{className:"mt-1 text-sm font-semibold",children:F.title})]}),e.jsx("div",{className:"text-right text-[11px] font-mono tabular-nums opacity-85",children:ou(F)})]}),F.source==="task"&&e.jsx("div",{className:"mt-2 text-[10px] font-mono uppercase tracking-[0.12em] opacity-70",children:"Workpad due task"})]},`${F.type}-${F.id}`))]})]}),e.jsxs("section",{"data-testid":"chrono-time-radar",className:"rounded-2xl border border-cyan-300/15 bg-black/25 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-bold uppercase tracking-[0.18em] text-cyan-300",children:[e.jsx(Hx,{size:14}),"Time Radar"]}),e.jsxs("div",{"data-testid":"chrono-time-pressure",className:"rounded-full border border-cyan-400/25 bg-cyan-500/10 px-3 py-1 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100",children:["Pressure ",S.severity]})]}),e.jsxs("svg",{viewBox:"0 0 240 150",className:"mt-4 h-40 w-full text-cyan-300",role:"img","aria-label":"Time radar now ring",children:[e.jsx("defs",{children:e.jsxs("radialGradient",{id:"chrono-radar-glow",cx:"50%",cy:"50%",r:"50%",children:[e.jsx("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:"0.22"}),e.jsx("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:"0"})]})}),e.jsx("circle",{cx:"120",cy:"86",r:"60",fill:"url(#chrono-radar-glow)"}),e.jsx("circle",{cx:"120",cy:"86",r:"58",fill:"none",stroke:"currentColor",strokeOpacity:"0.35"}),e.jsx("circle",{cx:"120",cy:"86",r:"34",fill:"none",stroke:"currentColor",strokeOpacity:"0.22"}),e.jsx("line",{x1:"120",y1:"86",x2:"120",y2:"26",stroke:"currentColor",strokeOpacity:"0.55"}),e.jsx("circle",{cx:"120",cy:"26",r:"4",fill:"currentColor"}),e.jsx("circle",{cx:"174",cy:"86",r:"4",fill:N?"#67e8f9":"#334155"}),e.jsx("circle",{cx:"120",cy:"140",r:"4",fill:_?"#fbbf24":"#334155"}),e.jsx("text",{x:"120",y:"88",textAnchor:"middle",className:"fill-cyan-100 text-[10px] font-bold",children:"NOW"}),e.jsx("text",{x:"174",y:"77",textAnchor:"middle",className:"fill-slate-300 text-[8px]",children:"EVENT"}),e.jsx("text",{x:"120",y:"132",textAnchor:"middle",className:"fill-slate-300 text-[8px]",children:"DEADLINE"})]}),e.jsx("div",{"data-testid":"chrono-conflict-alerts",className:"rounded-xl border border-white/10 bg-white/[0.03] p-3 text-[11px] font-mono text-slate-300",children:R.length?`${R.length} schedule conflict${R.length===1?"":"s"} detected`:"No schedule conflicts detected"})]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[1fr_1fr]",children:[e.jsxs("section",{"data-testid":"chrono-mission-queue",className:"rounded-2xl border border-cyan-300/15 bg-black/25 p-4",children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.18em] text-cyan-300",children:"Mission Queue"}),e.jsxs("div",{className:"mt-3 space-y-2",children:[E.length===0&&e.jsx("div",{className:"text-[12px] font-mono text-slate-500",children:"No upcoming mission items."}),E.map(F=>e.jsxs("div",{className:`rounded-xl border p-3 ${iu(F)}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-[9px] font-mono uppercase tracking-[0.16em] opacity-80",children:lu(F)}),e.jsx("span",{className:"text-[10px] font-mono opacity-85",children:ou(F)})]}),e.jsx("div",{className:"mt-1 text-[13px] font-semibold",children:F.title})]},`${F.type}-${F.id}`))]})]}),e.jsxs("section",{"data-testid":"chrono-deadline-pressure",className:"rounded-2xl border border-cyan-300/15 bg-black/25 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-bold uppercase tracking-[0.18em] text-cyan-300",children:[e.jsx(Wx,{size:14}),"Deadline Pressure"]}),e.jsx("div",{className:"mt-3 text-3xl font-semibold text-slate-50",children:S.severity}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-center",children:[e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-2",children:[e.jsx("div",{className:"text-lg font-semibold text-rose-200",children:S.overdueCount}),e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.12em] text-slate-500",children:"Overdue"})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-2",children:[e.jsx("div",{className:"text-lg font-semibold text-amber-200",children:S.criticalCount}),e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.12em] text-slate-500",children:"Critical"})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-2",children:[e.jsx("div",{className:"text-lg font-semibold text-cyan-200",children:S.upcomingCount}),e.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.12em] text-slate-500",children:"Upcoming"})]})]})]})]}),e.jsxs("section",{className:"grid gap-4 xl:grid-cols-2",children:[e.jsxs("div",{className:"rounded-2xl border border-cyan-300/15 bg-black/25 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-bold uppercase tracking-[0.18em] text-cyan-300",children:[e.jsx(Kx,{size:14}),"Local Event"]}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("input",{"data-testid":"chrono-event-title-input",value:x,onChange:F=>p(F.target.value),placeholder:"Event title",className:"w-full rounded-lg border border-white/10 bg-black/35 px-3 py-2 text-[12px] text-slate-100 outline-none focus:border-cyan-400/40"}),e.jsxs("div",{className:"grid gap-2 md:grid-cols-2",children:[e.jsx("input",{"data-testid":"chrono-event-start-input",type:"datetime-local",value:d,onChange:F=>m(F.target.value),className:"rounded-lg border border-white/10 bg-black/35 px-3 py-2 text-[12px] text-slate-100 outline-none"}),e.jsx("input",{"data-testid":"chrono-event-end-input",type:"datetime-local",value:f,onChange:F=>b(F.target.value),className:"rounded-lg border border-white/10 bg-black/35 px-3 py-2 text-[12px] text-slate-100 outline-none"})]}),e.jsx("button",{type:"button","data-testid":"chrono-add-event-btn",onClick:U,className:"w-full rounded-lg border border-cyan-400/30 bg-cyan-500/10 px-3 py-2 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100",children:"+ Event"})]})]}),e.jsxs("div",{className:"rounded-2xl border border-cyan-300/15 bg-black/25 p-4",children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.18em] text-cyan-300",children:"Local Deadline"}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("input",{"data-testid":"chrono-deadline-title-input",value:h,onChange:F=>g(F.target.value),placeholder:"Deadline title",className:"w-full rounded-lg border border-white/10 bg-black/35 px-3 py-2 text-[12px] text-slate-100 outline-none focus:border-cyan-400/40"}),e.jsxs("div",{className:"grid gap-2 md:grid-cols-[1fr_0.75fr]",children:[e.jsx("input",{"data-testid":"chrono-deadline-date-input",type:"date",value:y,onChange:F=>I(F.target.value),className:"rounded-lg border border-white/10 bg-black/35 px-3 py-2 text-[12px] text-slate-100 outline-none"}),e.jsxs("select",{"data-testid":"chrono-deadline-priority-select",value:A,onChange:F=>C(F.target.value),className:"rounded-lg border border-white/10 bg-black/35 px-3 py-2 text-[12px] text-slate-100 outline-none",children:[e.jsx("option",{value:"high",children:"High"}),e.jsx("option",{value:"normal",children:"Normal"}),e.jsx("option",{value:"low",children:"Low"})]})]}),e.jsx("button",{type:"button","data-testid":"calendar-add-deadline-btn",onClick:P,className:"w-full rounded-lg border border-amber-400/30 bg-amber-500/10 px-3 py-2 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100",children:"+ Deadline"})]})]})]}),e.jsxs("section",{"data-testid":"chrono-provider-truth",className:"rounded-2xl border border-cyan-300/15 bg-black/25 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.18em] text-cyan-300",children:"Provider Truth"}),e.jsxs("button",{type:"button","data-testid":"calendar-export-ics-btn",disabled:!o.length,onClick:D,className:"inline-flex items-center gap-1.5 rounded-lg border border-white/10 bg-white/[0.03] px-3 py-1.5 text-[10px] font-mono uppercase tracking-[0.12em] text-slate-300 disabled:cursor-not-allowed disabled:opacity-50",title:"ICS export remains available through the existing deadline exporter.",children:[e.jsx(pl,{size:12}),"Export ICS"]})]}),e.jsx("div",{className:"mt-3 grid gap-2 md:grid-cols-5",children:$.map(F=>e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsx("div",{className:"text-[11px] font-semibold text-slate-100",children:F.label}),e.jsx("div",{className:`mt-1 text-[9px] font-mono uppercase tracking-[0.12em] ${F.connected?"text-emerald-300":"text-slate-500"}`,children:F.status})]},F.id))}),e.jsx("div",{className:"mt-3 text-[10px] font-mono text-slate-500",children:"Google and Outlook actions are deep links only when shown elsewhere; no external calendar sync is connected."})]})]})})}function q1({open:t,onClose:r,workflowId:n}){return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[124] bg-black/55",onClick:r}),e.jsxs("aside",{"data-testid":"operator-calendar-drawer","aria-label":"ChronoHUD calendar and deadlines",className:"fixed right-4 top-16 bottom-4 z-[125] w-[min(980px,calc(100vw-2rem))] overflow-hidden rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_18px_80px_rgba(0,0,0,0.7)] flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-cyan-300/15 bg-black/40 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] uppercase tracking-[0.18em] text-cyan-300 font-bold",children:[e.jsx(Vx,{size:14}),"ChronoHUD"]}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500 mt-0.5",children:"Local events + deadlines · provider truth · operator time radar"})]}),e.jsx("button",{type:"button","data-testid":"operator-calendar-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10 shrink-0","aria-label":"Close ChronoHUD",children:"x"})]}),e.jsx(J1,{workflowId:n})]})]}):null}function Y1(t){var s,a;if(!t||!t.metadata)return"";const r=t.metadata;let n=`# ProofForge Trust Report: ${r.name||r.id} `;return n+=`## Metadata `,n+=`- **Profile UUID**: \`${r.id}\` @@ -204,16 +204,16 @@ ${n.join(` `,(((a=t.forensics)==null?void 0:a.repairLog)||[]).forEach(o=>{n+=`- [${new Date(o.ts).toLocaleString()}] **${o.type}**: ${o.reason||o.summary||""} `}),n+=` --- -*Generated by ProofForge Forensic Engine*`,n}async function Z1(t){var r,n,s;return(n=(r=window.api)==null?void 0:r.state)!=null&&n.getProfileTrustReport?window.api.state.getProfileTrustReport(t):(s=window.api)!=null&&s.invoke?window.api.invoke("state:getProfileTrustReport",t):null}async function X1(){var t,r,n,s;if(!((r=(t=window.api)==null?void 0:t.settings)!=null&&r.get))return"";try{const a=await window.api.settings.get();return String((a==null?void 0:a.activeProfileId)||((s=(n=a==null?void 0:a.connectionProfiles)==null?void 0:n[0])==null?void 0:s.id)||"").trim()}catch{return""}}function Q1(t){const r=String(t||"UNKNOWN").toUpperCase();return r==="VERIFIED"?"text-emerald-200 border-emerald-400/30 bg-emerald-500/10":r==="DRIFTED"||r==="NEEDS_REVIEW"?"text-amber-200 border-amber-400/30 bg-amber-500/10":r==="SIGNATURE_TAMPERED"||r==="INVALID"?"text-rose-200 border-rose-400/30 bg-rose-500/10":r==="OFFLINE_LOCKED"?"text-cyan-200 border-cyan-400/30 bg-cyan-500/10":"text-slate-200 border-white/10 bg-black/20"}function ev({open:t,onClose:r,profileId:n}){var f;const[s,a]=i.useState(null),[o,l]=i.useState(!1),[c,u]=i.useState("");i.useEffect(()=>{if(!t)return;let b=!1;return(async()=>{l(!0);try{const h=String(n||"").trim()||await X1();if(b)return;if(u(h),!h){a(null);return}const g=await Z1(h);b||a(g)}catch{b||a(null)}finally{b||l(!1)}})(),()=>{b=!0}},[t,n]);const x=i.useCallback(async()=>{var b,h;s&&(je(`trust-report-${c||"profile"}.json`,s),c&&((h=(b=window.api)==null?void 0:b.state)!=null&&h.logProfileEvent)&&await window.api.state.logProfileEvent(c,"REPORT_EXPORTED","Forensic trust report exported as JSON."),ge("Trust report JSON downloaded","success"))},[s,c]),p=i.useCallback(async()=>{var b,h;s&&($s(`trust-report-${c||"profile"}.md`,Y1(s)),c&&((h=(b=window.api)==null?void 0:b.state)!=null&&h.logProfileEvent)&&await window.api.state.logProfileEvent(c,"REPORT_EXPORTED","Forensic trust report exported as Markdown."),ge("Trust report Markdown downloaded","success"))},[s,c]);if(!t)return null;const d=s==null?void 0:s.metadata,m=((f=s==null?void 0:s.forensics)==null?void 0:f.history)||[];return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[124] bg-black/50",onClick:r}),e.jsxs("aside",{"data-testid":"trust-report-drawer","aria-label":"Profile trust report",className:"fixed left-4 top-16 bottom-4 z-[125] w-[min(520px,calc(100vw-2rem))] rounded-2xl border border-violet-300/25 bg-slate-950 shadow-[0_18px_80px_rgba(0,0,0,0.7)] flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] uppercase tracking-[0.16em] text-violet-300 font-bold",children:[e.jsx(Gx,{size:14}),"Trust Report"]}),e.jsx("button",{type:"button","data-testid":"trust-report-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10","aria-label":"Close trust report",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-4 space-y-4",children:[o&&e.jsx("div",{className:"text-[11px] font-mono text-slate-500",children:"Loading forensic report…"}),!o&&!d&&e.jsx("div",{"data-testid":"trust-report-empty",className:"text-[11px] font-mono text-slate-500",children:"No active bridge profile found. Configure a provider in Settings first."}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:`rounded-xl border p-3 space-y-1.5 ${Q1(d.trustState)}`,children:[e.jsx("div",{className:"text-[13px] font-semibold",children:d.name||d.id}),e.jsxs("div",{className:"text-[10px] font-mono uppercase tracking-[0.12em] opacity-90",children:[d.trustState," · ",d.provider," · ",d.secretCustody]}),e.jsx("div",{className:"text-[10px] font-mono text-slate-400 break-all",children:d.baseUrl}),d.fingerprint&&e.jsxs("div",{className:"text-[9px] font-mono opacity-70 break-all",children:["FP: ",d.fingerprint]})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Forensic history"}),m.length===0?e.jsx("div",{className:"text-[11px] font-mono text-slate-600",children:"No events recorded yet."}):m.map(b=>e.jsxs("article",{className:"rounded-lg border border-white/8 bg-black/20 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[9px] font-mono uppercase tracking-wider text-slate-500",children:[e.jsx("span",{children:new Date(b.ts).toLocaleString()}),e.jsx("span",{className:"text-violet-300",children:b.type})]}),e.jsx("div",{className:"text-[11px] text-slate-300 mt-1",children:b.summary})]},b.id||`${b.ts}-${b.type}`))]})]})]}),d&&e.jsxs("div",{className:"px-4 py-3 border-t border-white/10 flex flex-wrap gap-2",children:[e.jsxs("button",{type:"button","data-testid":"trust-report-export-json-btn",onClick:x,className:"inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border border-white/15 bg-black/25 text-[9px] font-mono uppercase tracking-[0.12em] text-slate-200",children:[e.jsx(pl,{size:12}),"Export JSON"]}),e.jsxs("button",{type:"button","data-testid":"trust-report-export-md-btn",onClick:p,className:"inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border border-white/15 bg-black/25 text-[9px] font-mono uppercase tracking-[0.12em] text-slate-200",children:[e.jsx(pl,{size:12}),"Export Markdown"]})]})]})]})}function tv({open:t,steps:r=[],progress:n={},busyStepId:s="",onRunStep:a,onSkipStep:o,onClose:l,onFinish:c}){if(!t)return null;const u=Array.isArray(r)?r:[],x=u.filter(d=>!!n[String(d.id||"")]).length,p=x>=u.length&&u.length>0;return e.jsx("div",{className:"fixed inset-0 z-[140] bg-black/70 flex items-center justify-center p-5",children:e.jsxs("section",{"data-testid":"firstboot-authority-wizard","aria-label":"First Boot Authority Wizard",className:"w-full max-w-5xl rounded-2xl border border-cyan-300/25 bg-slate-950 p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.18em] text-cyan-300 font-bold",children:"First-Boot Authority Funnel"}),e.jsxs("div",{className:"text-[11px] text-slate-400 font-mono",children:[x,"/",u.length," complete"]}),e.jsx("p",{className:"mt-2 text-[11px] font-mono text-slate-500 leading-relaxed",children:"Finish authority setup now, or start using the app and return from Mission Control anytime."})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("button",{type:"button","data-testid":"firstboot-skip-now-btn",onClick:l,className:"px-3 py-2 rounded-lg border border-emerald-400/35 bg-emerald-500/15 text-[10px] font-mono uppercase tracking-[0.12em] font-bold text-emerald-100 hover:bg-emerald-500/25 transition-colors",children:"Start using app"}),e.jsx("button",{type:"button","data-testid":"firstboot-close-btn",onClick:l,"aria-label":"Close first-boot wizard",className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]})]}),e.jsx("div",{className:"space-y-2 max-h-[56vh] overflow-auto pr-1",children:u.map((d,m)=>{const f=String(d.id||""),b=!!n[f],h=s===f,g=!!d.critical;return e.jsxs("article",{"data-testid":`firstboot-step-${f}`,className:`rounded-xl border px-4 py-3 flex items-center justify-between gap-3 ${b?"border-emerald-300/30 bg-emerald-500/10":g?"border-cyan-300/30 bg-cyan-500/10":"border-white/10 bg-black/30"}`,children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-[0.14em] font-bold text-slate-100",children:[m+1,". ",String(d.title||f)]}),e.jsx("div",{className:"text-[10px] font-mono text-slate-400",children:String(d.description||"")}),g?e.jsx("div",{className:"text-[9px] font-mono text-amber-300 mt-1",children:"Security-critical step"}):null]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!g&&!b?e.jsx("button",{type:"button","data-testid":`firstboot-skip-${f}`,onClick:()=>o(f),className:"px-2.5 py-1.5 rounded border border-white/10 bg-white/5 text-[9px] font-mono uppercase tracking-[0.12em] text-slate-200 hover:bg-white/10",children:"Skip"}):null,e.jsx("button",{type:"button","data-testid":`firstboot-run-${f}`,disabled:b||h,onClick:()=>a(f),className:`px-3 py-1.5 rounded border text-[9px] font-mono uppercase tracking-[0.12em] ${b?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100 hover:bg-cyan-500/20"} disabled:opacity-60`,children:b?"Done":h?"Running":"Run"})]})]},f)})}),e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Completion summary is stored locally. Reopen from Mission Control → First Boot when ready."}),e.jsx("button",{type:"button","data-testid":"firstboot-finish-btn",onClick:c,className:`px-3 py-2 rounded border text-[10px] uppercase tracking-[0.14em] font-bold ${p?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":"border-white/10 bg-white/5 text-slate-400 hover:bg-white/10 hover:text-slate-200"}`,children:p?"Open Mission Control":"Continue setup later"})]})]})})}function rv({snapshots:t=[],onCapture:r,onRestore:n,onCompare:s,activeSnapshotId:a=""}){const[o,l]=i.useState(""),c=Array.isArray(t)?t:[];return e.jsxs("section",{"data-testid":"snapshot-manager",className:"rounded-2xl border border-white/10 bg-black/30 p-3 space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between gap-2",children:e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"State Snapshots"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Capture, restore, and compare runtime state safely."})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{"data-testid":"snapshot-name-input",value:o,onChange:u=>l(u.target.value),placeholder:"Snapshot name",className:"flex-1 rounded border border-white/10 bg-black/40 px-2 py-1 text-[10px] font-mono text-slate-200"}),e.jsx("button",{type:"button","data-testid":"snapshot-capture-btn",onClick:()=>{const u=String(o||"").trim()||`Snapshot ${new Date().toLocaleTimeString()}`;r(u),l("")},className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Capture"})]}),e.jsxs("div",{className:"max-h-56 overflow-auto space-y-1.5 pr-1",children:[c.map(u=>e.jsx("article",{className:`rounded-lg border px-2 py-1.5 ${String(u.id||"")===String(a||"")?"border-cyan-300/30 bg-cyan-500/10":"border-white/10 bg-black/20"}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-200",children:String(u.name||u.id)}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:String(u.createdAt||"")})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{type:"button","data-testid":`snapshot-restore-${u.id}`,onClick:()=>n(u.id),className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Restore"}),e.jsx("button",{type:"button","data-testid":`snapshot-compare-${u.id}`,onClick:()=>s(u.id),className:"px-2 py-1 rounded border border-white/10 bg-white/5 text-[9px] font-mono uppercase tracking-[0.12em] text-slate-200",children:"Compare"})]})]})},u.id)),c.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No snapshots captured yet."})]})]})}function ya(t){return JSON.stringify(t||{},null,2)}function nv({paneId:t,payload:r}){const n=String(t||"runtime_snapshots");return n==="proof_stdout"?e.jsxs("section",{"data-testid":"result-pane-proof",className:"rounded-2xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold mb-2",children:"Proof Stdout"}),e.jsx("pre",{className:"text-[10px] font-mono text-slate-200 whitespace-pre-wrap",children:String(r&&r.text?r.text:"No proof output yet.")})]}):n==="watchdog_alerts"?e.jsxs("section",{"data-testid":"result-pane-watchdog",className:"rounded-2xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-amber-300 font-bold mb-2",children:"Watchdog Alerts"}),e.jsx("pre",{className:"text-[10px] font-mono text-slate-200 whitespace-pre-wrap",children:ya(r)})]}):n==="release_health"?e.jsxs("section",{"data-testid":"result-pane-release-health",className:"rounded-2xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold mb-2",children:"Release Health"}),e.jsx("pre",{className:"text-[10px] font-mono text-slate-200 whitespace-pre-wrap",children:ya(r)})]}):n==="snapshot_compare"?e.jsxs("section",{"data-testid":"result-pane-snapshot-compare",className:"rounded-2xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-blue-300 font-bold mb-2",children:"Snapshot Compare"}),e.jsx("pre",{className:"text-[10px] font-mono text-slate-200 whitespace-pre-wrap",children:ya(r)})]}):e.jsxs("section",{"data-testid":"result-pane-default",className:"rounded-2xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold mb-2",children:"Runtime Snapshots"}),e.jsx("pre",{className:"text-[10px] font-mono text-slate-200 whitespace-pre-wrap",children:ya(r)})]})}function Rl(t){if(t==null)return t;if(typeof t=="string"){const r=t.toLowerCase();return r.includes("token")||r.includes("secret")||r.includes("passphrase")?"[redacted]":t}if(Array.isArray(t))return t.map(r=>Rl(r));if(typeof t=="object"){const r={};return Object.entries(t).forEach(([n,s])=>{const a=String(n||"").toLowerCase();a.includes("token")||a.includes("secret")||a.includes("password")||a.includes("passphrase")?r[n]="[redacted]":r[n]=Rl(s)}),r}return t}function sv(t,r){return{id:`snap-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,name:String(t||`Snapshot ${new Date().toLocaleTimeString()}`),createdAt:new Date().toISOString(),payload:Rl(r)}}function av(t,r){if(!t||!r)return[];const n=t&&t.payload&&typeof t.payload=="object"?t.payload:{},s=r&&r.payload&&typeof r.payload=="object"?r.payload:{};return Array.from(new Set([...Object.keys(n),...Object.keys(s)])).sort().map(o=>({key:o,before:n[o],after:s[o],changed:JSON.stringify(n[o])!==JSON.stringify(s[o])})).filter(o=>o.changed)}function ov(t){return t?t.payload:null}const J0="neuralshell_runtime_snapshots_v1";function iv(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(J0)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function lv(t){typeof window>"u"||!window.localStorage||window.localStorage.setItem(J0,JSON.stringify((Array.isArray(t)?t:[]).slice(-120)))}function cv({open:t,onClose:r,runtimeState:n,onRestoreSnapshotPayload:s,alerts:a=[],proofStdout:o="",releaseHealth:l={}}){const[c,u]=i.useState("runtime_snapshots"),[x,p]=i.useState({}),[d,m]=i.useState(()=>iv()),[f,b]=i.useState("");i.useEffect(()=>{lv(d)},[d]);const h=i.useCallback(P=>{const A=n&&typeof n=="object"?n:{},C=sv(P,{provider:String(A.providerHealth&&A.providerHealth.activeProvider?A.providerHealth.activeProvider:"ollama"),model:String(A.providerHealth&&A.providerHealth.model?A.providerHealth.model:"llama3"),vaultLocked:!!(A.vaultState&&A.vaultState.locked),policyProfile:String(A.policyState&&A.policyState.activePolicyProfile?A.policyState.activePolicyProfile:"none"),proofStatus:String(A.proofEngine&&A.proofEngine.lastProofStatus?A.proofEngine.lastProofStatus:"idle"),activePanels:[String(c||"runtime_snapshots")],collabRoom:String(A.collabVoiceState&&A.collabVoiceState.currentRoom?A.collabVoiceState.currentRoom:"default"),collabPeers:Number(A.collabVoiceState&&A.collabVoiceState.peersActive?A.collabVoiceState.peersActive:0),selectedCards:["provider","vault","proof","policy","watchdog"]});return m(w=>[...w,C].slice(-120)),b(String(C.id||"")),u("runtime_snapshots"),p(C),X("runtime.snapshot.captured",{snapshotId:C.id,name:C.name},{source:"snapshots",severity:"info"}),C},[c,n]),g=i.useCallback(P=>{const A=(d||[]).find(w=>String(w.id||"")===String(P||""));if(!A)return;const C=ov(A);b(String(A.id||"")),typeof s=="function"&&s(C),u("runtime_snapshots"),p(A),X("runtime.snapshot.restored",{snapshotId:A.id,name:A.name},{source:"snapshots",severity:"info"})},[s,d]),y=i.useCallback(P=>{const A=(d||[]).find(j=>String(j.id||"")===String(f||"")),C=(d||[]).find(j=>String(j.id||"")===String(P||""));if(!C)return;const w=av(A||null,C||null);u("snapshot_compare"),p({from:A?A.name:"current-runtime",to:C.name,rows:w}),X("runtime.snapshot.compared",{from:A?A.id:"current-runtime",to:C.id,changedFields:w.length},{source:"snapshots",severity:"info"})},[f,d]);return i.useEffect(()=>{t&&(c==="watchdog_alerts"?p(a):c==="proof_stdout"?p({text:o||""}):c==="release_health"&&p(l||{}))},[a,t,o,l,c]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[126] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"split-workspace",className:"fixed inset-x-6 top-18 bottom-6 z-[127] rounded-2xl border border-blue-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.7)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-blue-300 font-bold",children:"Live Split Workspace"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Left: command deck · Center: workflow context · Right: result pane + snapshots."})]}),e.jsx("button",{type:"button","data-testid":"split-workspace-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[250px_1fr_380px]",children:[e.jsxs("aside",{className:"border-r border-white/10 p-3 space-y-2 bg-black/25",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Command Deck"}),e.jsx("button",{type:"button","data-testid":"split-pane-proof-btn",onClick:()=>u("proof_stdout"),className:"w-full text-left px-2.5 py-2 rounded border border-white/10 bg-black/20 text-[10px] font-mono text-slate-200 hover:bg-white/10",children:"Proof Stdout"}),e.jsx("button",{type:"button","data-testid":"split-pane-watchdog-btn",onClick:()=>u("watchdog_alerts"),className:"w-full text-left px-2.5 py-2 rounded border border-white/10 bg-black/20 text-[10px] font-mono text-slate-200 hover:bg-white/10",children:"Watchdog Alerts"}),e.jsx("button",{type:"button","data-testid":"split-pane-release-btn",onClick:()=>u("release_health"),className:"w-full text-left px-2.5 py-2 rounded border border-white/10 bg-black/20 text-[10px] font-mono text-slate-200 hover:bg-white/10",children:"Release Health"}),e.jsx("button",{type:"button","data-testid":"split-pane-snapshots-btn",onClick:()=>u("runtime_snapshots"),className:"w-full text-left px-2.5 py-2 rounded border border-white/10 bg-black/20 text-[10px] font-mono text-slate-200 hover:bg-white/10",children:"Runtime Snapshots"})]}),e.jsx("main",{className:"p-3 overflow-auto space-y-3",children:e.jsxs("section",{className:"rounded-2xl border border-white/10 bg-black/25 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Primary Workflow Context"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-2 text-[10px] font-mono",children:[e.jsxs("div",{className:"rounded border border-white/10 bg-black/25 px-2 py-1.5",children:[e.jsx("div",{className:"text-slate-500",children:"Provider"}),e.jsx("div",{className:"text-slate-100",children:String(n&&n.providerHealth&&n.providerHealth.activeProvider?n.providerHealth.activeProvider:"ollama")})]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/25 px-2 py-1.5",children:[e.jsx("div",{className:"text-slate-500",children:"Model"}),e.jsx("div",{className:"text-slate-100",children:String(n&&n.providerHealth&&n.providerHealth.model?n.providerHealth.model:"llama3")})]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/25 px-2 py-1.5",children:[e.jsx("div",{className:"text-slate-500",children:"Policy"}),e.jsx("div",{className:"text-slate-100",children:String(n&&n.policyState&&n.policyState.activePolicyProfile?n.policyState.activePolicyProfile:"none")})]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/25 px-2 py-1.5",children:[e.jsx("div",{className:"text-slate-500",children:"Proof Status"}),e.jsx("div",{className:"text-slate-100",children:String(n&&n.proofEngine&&n.proofEngine.lastProofStatus?n.proofEngine.lastProofStatus:"idle")})]})]})]})}),e.jsxs("aside",{className:"border-l border-white/10 p-3 overflow-auto space-y-3 bg-black/20",children:[e.jsx(nv,{paneId:c,payload:x}),e.jsx(rv,{snapshots:d,activeSnapshotId:f,onCapture:h,onRestore:g,onCompare:y})]})]})]})]}):null}const dv="neuralshell_readiness_checklist_v1",uv="neuralshell_nodechain_mission_schedules_v1";function du(){typeof window>"u"||!window.localStorage||window.localStorage.setItem(dv,"1")}function Wi({label:t,detail:r,done:n,running:s,onRun:a,testId:o}){return e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 px-4 py-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] font-semibold text-slate-100",children:t}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500 mt-0.5",children:r})]}),e.jsx("button",{type:"button","data-testid":o,"aria-label":`Run ${t}`,disabled:n||s,onClick:a,className:`px-3 py-1.5 rounded-lg border text-[9px] font-mono uppercase tracking-[0.14em] ${n?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100 hover:bg-cyan-500/20"} disabled:opacity-60`,children:n?"Done":s?"Running…":"Run"})]})}i.memo(function({open:r,onClose:n,onOpenSettings:s,rgbEnabled:a=!1,onToggleRgb:o,workflowId:l="global"}){const[c,u]=i.useState(""),[x,p]=i.useState(!1),[d,m]=i.useState(!1),[f,b]=i.useState(()=>!!a),h=i.useRef(null);if(Wa(r,h,n),i.useEffect(()=>{b(!!a)},[a]),i.useEffect(()=>{if(!r)return;let C=!1;return(async()=>{if(window.api&&window.api.system&&typeof window.api.system.healthHistory=="function")try{const w=await window.api.system.healthHistory(),j=Array.isArray(w&&w.entries)?w.entries:[];!C&&j.length>0&&p(!!(j[0]&&j[0].ok))}catch{}if(window.api&&window.api.bridge&&typeof window.api.bridge.get=="function")try{const w=await window.api.bridge.get();!C&&w&&w.ok===!0&&m(!0)}catch{}})(),()=>{C=!0}},[r]),!r)return null;const g=x&&d&&(f||!o),y=async()=>{if(window.api&&window.api.system&&typeof window.api.system.runHealthCheck=="function"){u("health");try{const C=await window.api.system.runHealthCheck(),w=!!(C&&C.ok);p(w),w||window.dispatchEvent(new CustomEvent("neuralshell:toast",{detail:{message:"Health check found issues — review Settings",tone:"warning"}}))}finally{u("")}}},P=async()=>{if(!(window.api&&window.api.bridge&&typeof window.api.bridge.test=="function")){typeof s=="function"&&s();return}u("bridge");try{const C=await window.api.bridge.get(),w=Array.isArray(C&&C.profiles)?C.profiles:[],j=w.find(_=>String(_.id)===String(C.activeProfileId))||w[0]||null;if(!j){typeof s=="function"&&s();return}const E=await window.api.bridge.test(j),N=!!(E&&E.ok);m(N),N||window.dispatchEvent(new CustomEvent("neuralshell:toast",{detail:{message:"Bridge test failed — open Settings to fix",tone:"error"}}))}finally{u("")}},A=()=>{du();const C=(Array.isArray(Fa)?Fa:[]).find(w=>w.id==="getting_started");C&&zp(C,l||"global"),typeof n=="function"&&n(),window.dispatchEvent(new CustomEvent("neuralshell:toast",{detail:{message:"ProofForge is ready — Workpad starter note added",tone:"success"}}))};return e.jsx("div",{className:"fixed inset-0 z-[145] bg-black/70 backdrop-blur-sm flex items-center justify-center p-5",onClick:n,children:e.jsxs("section",{ref:h,"data-testid":"readiness-checklist-modal",role:"dialog","aria-modal":"true","aria-label":"ProofForge readiness checklist",className:"w-full max-w-lg rounded-2xl border border-emerald-300/25 bg-slate-950 p-5 shadow-[0_20px_90px_rgba(0,0,0,0.75)]",onClick:C=>C.stopPropagation(),children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.18em] text-emerald-300 font-bold",children:"ProofForge is ready"}),e.jsx("div",{className:"text-[12px] text-slate-300 mt-1",children:"Quick checklist before your first session."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Wi,{label:"System health check",detail:"Network, bridge, vault, runtime",done:x,running:c==="health",onRun:y,testId:"readiness-checklist-run-health-btn"}),e.jsx(Wi,{label:"Bridge connection test",detail:"Verify your active LLM provider",done:d,running:c==="bridge",onRun:P,testId:"readiness-checklist-run-bridge-btn"}),typeof o=="function"&&e.jsx(Wi,{label:"RGB mood sync (optional)",detail:"Sync lighting to assistant mood",done:f,running:c==="rgb",onRun:async()=>{u("rgb");try{await Promise.resolve(o(!0)),b(!0)}finally{u("")}}})]}),e.jsxs("div",{className:"mt-5 flex items-center justify-between gap-3",children:[e.jsx("button",{type:"button","data-testid":"readiness-checklist-skip-btn",onClick:()=>{du(),typeof n=="function"&&n()},className:"px-3 py-2 rounded-lg border border-white/10 text-[10px] font-mono uppercase tracking-[0.14em] text-slate-400 hover:text-slate-200",children:"Skip for now"}),e.jsx("button",{type:"button","data-testid":"readiness-checklist-finish-btn",onClick:A,className:`px-4 py-2 rounded-lg border text-[10px] font-mono uppercase tracking-[0.14em] font-bold ${g?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100"}`,children:g?"Start working":"Continue anyway"})]})]})})});async function pv(){var t,r;if((r=(t=window.api)==null?void 0:t.workspace)!=null&&r.getActive)try{const n=await window.api.workspace.getActive();if(n!=null&&n.path)return String(n.path)}catch{}return""}function mv(t){const r=String(t||""),n=r.lastIndexOf(":");return n<=0?{workspacePath:"",actionId:r}:{workspacePath:r.slice(0,n),actionId:r.slice(n+1)}}function xv(t){const r=String(t).toLowerCase();return r==="high"?"border-rose-400/25 text-rose-200":r==="safe"?"border-emerald-400/25 text-emerald-200":"border-amber-400/25 text-amber-200"}const q0=[{id:"continue",label:"Approve & Run",tone:"good",primary:!0},{id:"cancel",label:"Cancel",tone:"bad"}];function fv({actionId:t,pending:r,busy:n,onChoice:s}){if(!r)return null;const a=r.request||{},o=Array.isArray(a.choices)&&a.choices.length?a.choices:q0;return e.jsxs("div",{"data-testid":`guided-action-approval-${t}`,className:"mt-2 rounded-lg border border-amber-400/25 bg-amber-500/10 p-2.5 space-y-2",children:[e.jsx("div",{className:"text-[10px] font-mono text-amber-100",children:String(a.message||"Operator approval required.")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(l=>e.jsx("button",{type:"button","data-testid":`guided-action-approve-${t}-${l.id}`,disabled:n,onClick:()=>s(t,l.id,r.mode),className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-wider disabled:opacity-50 ${l.tone==="bad"?"border-rose-400/30 text-rose-200 hover:bg-rose-500/10":l.primary?"border-emerald-400/30 text-emerald-100 bg-emerald-500/10 hover:bg-emerald-500/20":"border-white/15 text-slate-300 hover:bg-white/5"}`,children:l.label},l.id))})]})}function bv({workflowId:t,chatLog:r=[]}){const[n,s]=i.useState(""),[a,o]=i.useState([]),[l,c]=i.useState({}),[u,x]=i.useState(0),[p,d]=i.useState(!1),[m,f]=i.useState(""),[b,h]=i.useState(""),[g,y]=i.useState({}),[P,A]=i.useState(!1),C=i.useCallback(async()=>{var S,R,$,U;d(!0);try{const I=await pv();if(s(I),(R=(S=window.api)==null?void 0:S.action)!=null&&R.listRegistry){const F=await window.api.action.listRegistry(),J={};(Array.isArray(F)?F:[]).forEach(ee=>{ee!=null&&ee.id&&(J[ee.id]=ee)}),c(J)}if(!I||!((U=($=window.api)==null?void 0:$.project)!=null&&U.analyze)){o([]);return}const D=(Array.isArray(r)?r:[]).filter(F=>F&&!F._streaming).slice(-12).map(F=>({role:F.role,content:String(F.content||"").slice(0,500)})),z=await window.api.project.analyze(I,t,D);z!=null&&z.ok?(o(Array.isArray(z.rankedActions)?z.rankedActions:[]),x(Number(z.urgency)||0)):o([])}catch(I){ge((I==null?void 0:I.message)||"Failed to load guided actions","error")}finally{d(!1)}},[t,r]);i.useEffect(()=>{C()},[C]),i.useEffect(()=>{var R,$;if(!(($=(R=window.api)==null?void 0:R.action)!=null&&$.onLog))return;const S=window.api.action.onLog(U=>{if(!U)return;const I=`[${U.type||"log"}] ${String(U.message||U.msg||"").trim()}`;I.length>8&&h(I)});return typeof S=="function"?S:void 0},[]),i.useEffect(()=>{var R,$;if(!(($=(R=window.api)==null?void 0:R.action)!=null&&$.onInteraction))return;const S=window.api.action.onInteraction(U=>{if(!(U!=null&&U.actionId))return;const{actionId:I}=mv(U.actionId);y(D=>({...D,[I]:{mode:"interaction",fullActionId:U.actionId,workspacePath:U.workspacePath||"",request:U.request||{message:"Operator decision required."}}})),ge("Action waiting for operator decision","warning")});return typeof S=="function"?S:void 0},[]);const w=i.useCallback(S=>{y(R=>{if(!R[S])return R;const $={...R};return delete $[S],$})},[]),j=i.useCallback(async(S,R={})=>{var $,U;return(U=($=window.api)==null?void 0:$.action)!=null&&U.run?window.api.action.run(S,{rootPath:n||void 0,workflowId:t,...R}):null},[n,t]),E=i.useCallback(async S=>{var R,$,U,I;if(($=(R=window.api)==null?void 0:R.action)!=null&&$.run){f(S);try{const D=await j(S),z=String((D==null?void 0:D.status)||(D!=null&&D.ok?"succeeded":"failed"));if(z==="awaiting_input"){let F=null;if((I=(U=window.api)==null?void 0:U.action)!=null&&I.status){const J=await window.api.action.status(S,n||void 0);F=(J==null?void 0:J.interactionRequest)||null}y(J=>({...J,[S]:{mode:"policy",fullActionId:"",workspacePath:n,request:F||{type:"confirm",message:"Policy requires operator approval before this action can run.",choices:q0}}})),ge("Action needs operator approval","warning")}else(D==null?void 0:D.ok)!==!1&&z!=="failed"?(w(S),ge(`Action ${S} completed`,"success")):(w(S),ge((D==null?void 0:D.reason)||`Action ${S} failed`,"error"));await C()}catch(D){ge((D==null?void 0:D.message)||"Action run failed","error")}finally{f("")}}},[w,C,n,j]),N=i.useCallback(async(S,R,$)=>{var I,D,z,F;const U=g[S];if(U){f(S);try{if($==="policy"){const J=U.workspacePath||n;if((D=(I=window.api)==null?void 0:I.action)!=null&&D.cancel&&await window.api.action.cancel(S,J||void 0),R==="cancel"){w(S),ge("Action cancelled","info");return}const ee=await j(S,{forceAutoRun:!0,workspacePath:J}),ie=String((ee==null?void 0:ee.status)||(ee!=null&&ee.ok?"succeeded":"failed"));ie==="awaiting_input"?ge("Action still needs approval","warning"):(ee==null?void 0:ee.ok)!==!1&&ie!=="failed"?(w(S),ge(`Action ${S} completed`,"success")):(w(S),ge((ee==null?void 0:ee.reason)||`Action ${S} failed`,"error"))}else if((F=(z=window.api)==null?void 0:z.action)!=null&&F.respond){const J=U.fullActionId||S,ee=U.workspacePath||n,ie=await window.api.action.respond(J,{choiceId:R},ee||void 0);(ie==null?void 0:ie.ok)===!1?ge(ie.reason||"Failed to submit decision","error"):(w(S),ge("Decision recorded","success"))}await C()}catch(J){ge((J==null?void 0:J.message)||"Approval failed","error")}finally{f("")}}},[w,g,C,n,j]),_=i.useCallback(async()=>{var S,R,$,U,I,D;if(!((R=(S=window.api)==null?void 0:S.workspace)!=null&&R.pickRoot)){ge("Workspace picker unavailable","error");return}A(!0);try{const z=await window.api.workspace.pickRoot(),F=String((z==null?void 0:z.path)||(z==null?void 0:z.rootPath)||"").trim();if(!F)return;(U=($=window.api)==null?void 0:$.workspace)!=null&&U.register&&await window.api.workspace.register(F),(D=(I=window.api)==null?void 0:I.workspace)!=null&&D.setActive&&(z!=null&&z.id)&&await window.api.workspace.setActive(z.id),ge("Workspace registered","success"),await C()}catch(z){ge((z==null?void 0:z.message)||"Failed to pick workspace","error")}finally{A(!1)}},[C]);return e.jsxs("div",{className:"space-y-3","data-testid":"operator-inbox-actions-tab",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.18em] font-bold text-emerald-300",children:"Guided Actions"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500 truncate max-w-xs",title:n||"No workspace",children:n||"No active workspace"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[!n&&e.jsxs("button",{type:"button","data-testid":"guided-actions-pick-workspace-btn",disabled:P,onClick:_,className:"inline-flex items-center gap-1 px-2 py-1 rounded-lg border border-cyan-400/25 bg-cyan-500/10 text-[9px] font-mono uppercase text-cyan-100 hover:bg-cyan-500/20 disabled:opacity-50",children:[e.jsx(Jx,{size:11}),P?"Picking…":"Pick workspace"]}),e.jsxs("button",{type:"button","data-testid":"guided-actions-refresh-btn",onClick:C,disabled:p,className:"inline-flex items-center gap-1 px-2 py-1 rounded-lg border border-white/10 text-[9px] font-mono uppercase text-slate-400 hover:text-slate-200",children:[e.jsx(qx,{size:11,className:p?"animate-spin":""}),"Refresh"]})]})]}),u>0&&e.jsxs("div",{className:"rounded-lg border border-amber-400/20 bg-amber-500/10 px-3 py-2 text-[10px] font-mono text-amber-100",children:["Workspace urgency: ",e.jsx("span",{className:"font-bold",children:u})]}),b&&e.jsx("div",{className:"rounded-lg border border-white/8 bg-black/25 px-3 py-2 text-[9px] font-mono text-slate-400 truncate",title:b,children:b}),e.jsxs("div",{className:"space-y-2 max-h-[48vh] overflow-auto",children:[p&&a.length===0&&e.jsx("div",{className:"text-[11px] font-mono text-slate-500 py-6 text-center",children:"Analyzing workspace…"}),!p&&!n&&e.jsx("div",{"data-testid":"guided-actions-no-workspace",className:"text-center py-8 text-[11px] font-mono text-slate-500 border border-dashed border-cyan-400/20 rounded-xl",children:"Register a workspace root to rank guided actions."}),!p&&n&&a.length===0&&e.jsx("div",{"data-testid":"guided-actions-empty",className:"text-center py-8 text-[11px] font-mono text-slate-500 border border-dashed border-white/10 rounded-xl",children:"No ranked actions for this workspace yet."}),a.map(S=>{const R=l[S.id]||{},$=R.risk||"medium",U=m===S.id,I=g[S.id];return e.jsxs("article",{"data-testid":`guided-action-${S.id}`,className:"rounded-xl border border-white/10 bg-black/25 p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yx,{size:12,className:"text-emerald-400 shrink-0"}),e.jsx("span",{className:"text-[12px] font-semibold text-slate-100",children:S.label||R.label||S.id}),e.jsx("span",{className:`text-[8px] font-mono uppercase px-1.5 py-0.5 rounded border ${xv($)}`,children:$})]}),e.jsx("div",{className:"text-[10px] text-slate-500 mt-1",children:S.reason||R.description||""}),e.jsxs("p",{className:"text-[9px] font-mono text-emerald-400/80 mt-0.5",children:["score ",S.score??"—"]})]}),e.jsxs("button",{type:"button","data-testid":`guided-action-run-${S.id}`,disabled:!!m||!!I,onClick:()=>E(S.id),className:"inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg border border-emerald-400/30 bg-emerald-500/10 text-[9px] font-mono uppercase tracking-wider text-emerald-100 shrink-0 disabled:opacity-50",children:[e.jsx(Zx,{size:11}),U?"Running":I?"Awaiting":"Run"]})]}),e.jsx(fv,{actionId:S.id,pending:I,busy:U,onChoice:N})]},S.id)})]})]})}const hv=[{id:"ops",label:"Operations"},{id:"actions",label:"Actions"},{id:"workpad",label:"Workpad"},{id:"health",label:"Health"},{id:"missions",label:"Missions"}];function gv({active:t,label:r,badge:n,onClick:s,testId:a}){return e.jsxs("button",{type:"button","data-testid":a,onClick:s,className:`flex-1 px-2 py-2 rounded-xl border text-[9px] font-mono uppercase tracking-[0.12em] transition-all ${t?"border-violet-400/30 bg-violet-500/15 text-violet-100":"border-transparent text-slate-500 hover:text-slate-300 hover:bg-white/[0.03]"}`,children:[r,n>0?` (${n})`:""]})}function yv({workflowId:t,onOpenWorkpad:r}){const[n,s]=i.useState(()=>et(t));i.useEffect(()=>(Bp(t),s(et(t)),qa(s,t)),[t]);const a=i.useMemo(()=>eh(n),[n]),o=(n.tasks||[]).filter(l=>!l.done).slice(0,12);return e.jsxs("div",{className:"space-y-3","data-testid":"operator-inbox-workpad-tab",children:[e.jsx("div",{className:"grid grid-cols-4 gap-2",children:[{label:"Open",value:a.openTasks,tone:"text-amber-200"},{label:"Overdue",value:a.overdueTasks,tone:"text-rose-300"},{label:"Notes",value:a.notes,tone:"text-slate-200"},{label:"Pins",value:a.pins,tone:"text-violet-200"}].map(({label:l,value:c,tone:u})=>e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/25 px-2 py-1.5 text-center",children:[e.jsx("div",{className:`text-[14px] font-bold font-mono ${u}`,children:c}),e.jsx("div",{className:"text-[8px] uppercase tracking-wider text-slate-500",children:l})]},l))}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-500 truncate",children:["Scope: ",e.jsx("span",{className:"text-slate-300",children:Ga()})]}),typeof r=="function"&&e.jsx("button",{type:"button","data-testid":"operator-inbox-open-workpad-btn",onClick:r,className:"px-2.5 py-1 rounded-lg border border-amber-400/25 bg-amber-500/10 text-[9px] font-mono uppercase tracking-wider text-amber-100",children:"Open full Workpad"})]}),e.jsx("div",{className:"space-y-2 max-h-[42vh] overflow-auto",children:o.length===0?e.jsx("div",{"data-testid":"operator-inbox-workpad-empty",className:"text-center py-8 text-[11px] font-mono text-slate-500 border border-dashed border-white/10 rounded-xl",children:"No open Workpad tasks for this workflow."}):o.map(l=>{const c=_0(l.dueDate,l.done);return e.jsxs("div",{className:"flex items-start gap-2 rounded-xl border border-white/10 bg-black/25 px-3 py-2",children:[e.jsx("button",{type:"button","aria-label":l.done?"Mark incomplete":"Mark complete",onClick:()=>s(Zb(l.id,t)),className:`mt-0.5 h-4 w-4 rounded border flex items-center justify-center shrink-0 transition-colors ${l.done?"border-emerald-400/40 bg-emerald-500/20 text-emerald-200":"border-white/15 bg-black/30 hover:border-violet-400/30"}`,children:l.done&&e.jsx("svg",{className:"w-2.5 h-2.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2.5,children:e.jsx("path",{d:"M5 13l4 4L19 7"})})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[11px] text-slate-100",children:l.title}),l.dueDate&&e.jsx("span",{className:`inline-block mt-1 text-[8px] font-mono uppercase px-1.5 py-0.5 rounded border ${_w(c)}`,children:Cw(l.dueDate,l.done)})]})]},l.id)})})]})}function wv({onRunHealthCheck:t,bulkBusy:r,onEntriesChange:n}){const[s,a]=i.useState({entries:[]}),o=i.useCallback(async()=>{if(window.api&&window.api.system&&typeof window.api.system.healthHistory=="function")try{const c=await window.api.system.healthHistory();a(c&&typeof c=="object"?c:{entries:[]})}catch{a({entries:[]})}},[]);i.useEffect(()=>{o()},[o]);const l=Array.isArray(s.entries)?s.entries:[];return i.useEffect(()=>{typeof n=="function"&&n(l.length)},[l.length,n]),e.jsxs("div",{className:"space-y-3","data-testid":"operator-inbox-health-tab",children:[e.jsx("button",{type:"button","data-testid":"operator-inbox-run-health-btn",disabled:r,onClick:async()=>{typeof t=="function"&&await t(),await o()},className:"w-full px-3 py-2 rounded-xl border border-cyan-400/25 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-wider text-cyan-100 disabled:opacity-50",children:"Run health check now"}),e.jsx("div",{className:"space-y-2 max-h-[46vh] overflow-auto",children:l.length===0?e.jsx("div",{"data-testid":"operator-inbox-health-empty",className:"text-center py-8 text-[11px] font-mono text-slate-500 border border-dashed border-white/10 rounded-xl",children:"No health check history yet."}):l.map(c=>e.jsxs("div",{className:`rounded-xl border px-3 py-2.5 ${c.ok?"border-emerald-400/20 bg-emerald-500/5":"border-rose-400/20 bg-rose-500/5"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:`text-[10px] font-mono uppercase tracking-wider ${c.ok?"text-emerald-300":"text-rose-300"}`,children:c.ok?"Passed":"Issues found"}),e.jsx("span",{className:"text-[9px] font-mono text-slate-500",children:Nw(c.at)})]}),c.summary&&e.jsxs("div",{className:"text-[9px] font-mono text-slate-400 mt-1",children:[c.summary.passed,"/",c.summary.total," passed",c.summary.failed?` · ${c.summary.failed} failed`:"",c.summary.warning?` · ${c.summary.warning} warn`:""]})]},c.id))})]})}function vv(t){const r=Math.max(0,Math.floor(Number(t)||0)),n=Math.floor(r/3600),s=Math.floor(r%3600/60),a=r%60;return n>0?`${n}h ${String(s).padStart(2,"0")}m ${String(a).padStart(2,"0")}s`:`${s}m ${String(a).padStart(2,"0")}s`}function jv(t){if(!t)return"";const r=Date.now()-new Date(t).getTime();return!Number.isFinite(r)||r<0?"":r<1e3?"just now":r<6e4?`${Math.floor(r/1e3)}s`:r<36e5?`${Math.floor(r/6e4)}m`:`${Math.floor(r/36e5)}h`}function kv(t){const r=Math.max(1,Math.round(Number(t||0)/6e4));return r>=60?`${Math.round(r/60)}h`:`${r}m`}function Nv(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(uv)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}const Sv={llm_inference:"LLM",proof_exec:"Proof",provider_sweep:"Sweep",bridge_test:"Bridge",health_check:"Health",command:"Command",mission_schedule:"Mission",daemon:"Engine",daemon_ws:"WS",bridge_health:"Monitor",hosted_proxy:"Proxy",collab:"Collab"};function Cv(t){return Sv[String(t||"")]||String(t||"Task")}const _v=i.memo(function({usedMb:r,label:n}){const s=Math.min(100,Math.max(0,r/2048*100)),a=s>80?"bg-red-500":s>50?"bg-yellow-500":"bg-green-500";return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-[11px] font-mono mb-1",children:[e.jsx("span",{className:"text-slate-400",children:n}),e.jsxs("span",{className:"text-slate-300",children:[r," MB"]})]}),e.jsx("div",{className:"h-2 rounded-full bg-white/5 overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${a} transition-all duration-700`,style:{width:`${s}%`}})})]})});function Ki({task:t,onCancel:r,onRestartDaemon:n,busyId:s}){const a=t.category==="service",o=!!t.cancellable&&typeof r=="function",l=a&&t.kind==="daemon"&&typeof n=="function",c=t.paneId?`pane:${t.paneId}`:"",u=t.workflowId?`wf:${t.workflowId}`:"";return e.jsxs("div",{"data-testid":`task-row-${t.id}`,className:"flex items-start justify-between gap-3 px-3 py-2.5 rounded-xl border border-white/8 bg-black/25 hover:bg-white/[0.03] transition-colors",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[9px] font-mono uppercase tracking-[0.16em] px-1.5 py-0.5 rounded border border-violet-400/20 bg-violet-500/10 text-violet-200",children:Cv(t.kind)}),e.jsx("span",{className:"text-[12px] font-medium text-slate-100 truncate",children:t.label}),t.startedAt&&e.jsx("span",{className:"text-[10px] font-mono text-slate-500",children:jv(t.startedAt)})]}),t.detail&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500 mt-1 truncate",children:t.detail}),(c||u)&&e.jsx("div",{className:"text-[9px] font-mono text-slate-600 mt-1 truncate",children:[u,c].filter(Boolean).join(" · ")})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o&&e.jsx("button",{type:"button","data-testid":`task-cancel-${t.id}`,disabled:s===t.id,onClick:()=>r(t.id),className:"px-2.5 py-1 rounded-lg border border-rose-400/25 bg-rose-500/10 text-[9px] font-semibold uppercase tracking-wider text-rose-200 hover:bg-rose-500/15 disabled:opacity-50",children:s===t.id?"…":"Cancel"}),l&&e.jsx("button",{type:"button","data-testid":"task-manager-restart-daemon-btn",onClick:n,className:"px-2.5 py-1 rounded-lg border border-orange-400/25 bg-orange-500/10 text-[9px] font-semibold uppercase tracking-wider text-orange-200 hover:bg-orange-500/15",children:"Restart"}),!o&&!l&&e.jsx("span",{className:"text-[9px] font-mono uppercase tracking-wider text-slate-600",children:t.status||"running"})]})]})}function Av({memMb:t,settings:r={}}){if(t<1200)return null;const n=[];return t>=1200&&n.push("High RAM — disable particle backdrop in layout settings"),t>=1500&&r.otelExportEnabled&&n.push("OTel export is on — disable if not needed"),t>=1500&&r.hostedProxyEnabled&&n.push("Hosted model proxy adds overhead — disable when idle"),n.length===0?null:e.jsxs("section",{"data-testid":"task-manager-resource-warnings",className:"rounded-xl border border-amber-400/25 bg-amber-500/10 px-3 py-2.5 space-y-1",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] font-bold text-amber-200",children:"Resource warnings"}),n.map(s=>e.jsx("div",{className:"text-[10px] font-mono text-amber-100/90",children:s},s))]})}const Ev=i.memo(function({open:r,onClose:n,stats:s={},connectionInfo:a={},accelStatus:o={},settings:l={},workflowId:c="global",initialTab:u="ops",onOpenWorkpad:x,chatLog:p=[]}){const[d,m]=i.useState({operations:[],services:[],summary:{}}),[f,b]=i.useState([]),[h,g]=i.useState(""),[y,P]=i.useState(!1),[A,C]=i.useState(""),[w,j]=i.useState("ops"),[E,N]=i.useState(0),[_,S]=i.useState(0);i.useEffect(()=>{r&&j(u||"ops")},[r,u]),i.useEffect(()=>{if(!r||typeof n!="function")return;const ne=we=>{we.key==="Escape"&&(we.preventDefault(),n())};return window.addEventListener("keydown",ne),()=>window.removeEventListener("keydown",ne)},[r,n]),i.useEffect(()=>{if(!r)return;const ne=String(c||"global");Bp(ne);const we=()=>N(Xl(et(ne)));return we(),qa(()=>we(),ne)},[r,c]);const R=i.useCallback(async()=>{if(window.api&&window.api.tasks&&typeof window.api.tasks.list=="function")try{const ne=await window.api.tasks.list();m(ne&&typeof ne=="object"?ne:{operations:[],services:[],summary:{}}),b(Nv()),C("")}catch(ne){C(ne&&ne.message?ne.message:String(ne))}},[]);i.useEffect(()=>{if(!r)return;R();const ne=window.setInterval(R,2e3);return()=>window.clearInterval(ne)},[r,R]);const $=i.useCallback(async ne=>{if(window.api&&window.api.tasks&&typeof window.api.tasks.cancel=="function"){g(String(ne));try{const we=await window.api.tasks.cancel(ne);we&&we.ok?ge("Task cancelled","success"):ge(we&&we.reason?`Cancel failed: ${we.reason}`:"Cancel failed","error"),await R()}finally{g("")}}},[R]),U=i.useCallback(async()=>{if(window.api&&window.api.tasks&&typeof window.api.tasks.cancelAll=="function"){P(!0);try{const ne=await window.api.tasks.cancelAll({kinds:["llm_inference","proof_exec","provider_sweep"]}),we=Number(ne&&ne.cancelled)||0;ge(we>0?`Cancelled ${we} operation(s)`:"No cancellable operations",we>0?"success":"info"),await R()}finally{P(!1)}}},[R]),I=i.useCallback(async()=>{if(window.api&&window.api.system&&typeof window.api.system.runHealthCheck=="function"){P(!0);try{const ne=await window.api.system.runHealthCheck(),we=!!(ne&&ne.ok);ge(we?"Health check passed":"Health check found issues",we?"success":"warning"),await R()}catch(ne){ge(ne&&ne.message?ne.message:"Health check failed","error")}finally{P(!1)}}},[R]),D=i.useCallback(async()=>{window.api&&window.api.daemon&&typeof window.api.daemon.restart=="function"&&await window.api.daemon.restart(),await R()},[R]),z=i.useCallback(()=>{typeof x=="function"&&(x(),typeof n=="function"&&n())},[n,x]);if(!r)return null;const F=Number(s.cpuPercent||0),J=Number(s.memoryMb||0),ee=Number(s.tokensUsed||0),ie=Number(s.uptimeSec||0),ye=String(s.platform||"unknown"),pe=String(a.health||"unknown"),K=String(a.provider||"ollama"),H=String(a.model||"llama3"),W=!!o.enabled,Z=String(o.backend||"cpu"),ce=Array.isArray(d.operations)?d.operations:[],fe=Array.isArray(d.services)?d.services:[],me=d.summary&&typeof d.summary=="object"?d.summary:{},ke=Number(me.operations||ce.length);Number(me.services||fe.filter(ne=>ne.status==="running").length);const Pe=f.filter(ne=>!!(ne&&ne.enabled)),_e={ops:ke,workpad:E,health:_,missions:Pe.length};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[124] bg-black/50 backdrop-blur-[2px]",onClick:n}),e.jsxs("aside",{"data-testid":"operator-inbox-drawer",role:"dialog","aria-modal":"true","aria-label":"Operator Inbox",className:"fixed right-4 top-16 bottom-4 z-[125] w-[min(560px,calc(100vw-2rem))] rounded-2xl border border-violet-400/20 bg-shell-deep/98 shadow-[0_18px_80px_rgba(0,0,0,0.7)] flex flex-col backdrop-blur-xl animate-fade-up",children:[e.jsxs("div",{className:"px-5 py-4 border-b border-violet-500/10 bg-shell-soft/60 flex items-center justify-between rounded-t-2xl",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-9 w-9 rounded-xl bg-gradient-to-br from-fuchsia-500/20 to-violet-500/20 border border-fuchsia-400/20 flex items-center justify-center text-violet-200",children:e.jsxs("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.75,children:[e.jsx("path",{d:"M4 4h16v16H4z"}),e.jsx("path",{d:"M4 9h16M9 9v11"})]})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-bold text-white",children:"Operator Inbox"}),e.jsxs("div",{className:"text-[10px] text-slate-500 font-mono",children:[ke," ops · ",E," workpad · ",Pe.length," missions"]})]})]}),e.jsx("button",{type:"button","data-testid":"operator-inbox-close-btn","aria-label":"Close operator inbox",onClick:n,className:"h-8 w-8 rounded-lg border border-white/10 text-slate-400 hover:bg-white/10 hover:text-white flex items-center justify-center text-sm transition-all",children:"✕"})]}),e.jsx("div",{className:"px-3 py-2 border-b border-white/[0.03] bg-black/20 flex gap-1",children:hv.map(ne=>e.jsx(gv,{testId:`operator-inbox-tab-${ne.id}`,active:w===ne.id,label:ne.label,badge:_e[ne.id]||0,onClick:()=>j(ne.id)},ne.id))}),w==="ops"&&e.jsxs("div",{className:"px-4 py-2 border-b border-white/[0.03] bg-white/[0.01] flex flex-wrap gap-2",children:[e.jsx("button",{type:"button","data-testid":"task-manager-cancel-all-btn",disabled:y||ke===0,onClick:U,className:"px-2.5 py-1 rounded-lg border border-rose-400/25 bg-rose-500/10 text-[9px] font-semibold uppercase tracking-wider text-rose-200 hover:bg-rose-500/15 disabled:opacity-50",children:"Cancel all"}),e.jsx("button",{type:"button","data-testid":"task-manager-health-check-btn",disabled:y,onClick:I,className:"px-2.5 py-1 rounded-lg border border-cyan-400/25 bg-cyan-500/10 text-[9px] font-semibold uppercase tracking-wider text-cyan-200 hover:bg-cyan-500/15 disabled:opacity-50",children:"Run health check"})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-4 space-y-4",children:[w==="ops"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-4 gap-2",children:[{label:"CPU",value:`${F}%`},{label:"RAM",value:`${J}MB`},{label:"Bridge",value:pe==="online"?"Online":"Check"},{label:"Uptime",value:vv(ie)}].map(({label:ne,value:we})=>e.jsxs("div",{className:"text-center rounded-lg border border-white/5 bg-black/20 px-2 py-1.5",children:[e.jsx("div",{className:"text-[13px] font-bold font-mono text-slate-200",children:we}),e.jsx("div",{className:"text-[8px] text-slate-500 uppercase tracking-wider",children:ne})]},ne))}),e.jsx(Av,{memMb:J,settings:l}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.18em] font-bold text-cyan-300",children:"Active Operations"}),e.jsx("button",{type:"button",onClick:R,className:"text-[9px] font-mono uppercase tracking-wider text-slate-500 hover:text-slate-300",children:"Refresh"})]}),ce.length>0?e.jsx("div",{className:"space-y-2",children:ce.map(ne=>e.jsx(Ki,{task:ne,onCancel:$,busyId:h},ne.id))}):e.jsx("div",{"data-testid":"task-manager-empty",className:"rounded-xl border border-dashed border-white/10 px-4 py-6 text-center text-[11px] text-slate-500 font-mono",children:"No active operations. LLM streams, proof runs, sweeps, and health checks appear here while running."})]}),e.jsxs("section",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.18em] font-bold text-amber-300 mb-2",children:"Background Services"}),fe.length>0?e.jsx("div",{className:"space-y-2",children:fe.map(ne=>e.jsx(Ki,{task:ne,onRestartDaemon:D},ne.id))}):e.jsx("div",{className:"text-[11px] text-slate-500 font-mono px-1",children:"No background services reported."})]}),e.jsxs("section",{className:"rounded-xl border border-white/8 bg-black/20 p-3 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.18em] font-bold text-slate-400",children:"Runtime Snapshot"}),e.jsx(_v,{usedMb:J,label:"Process Memory"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-[10px] font-mono",children:[e.jsxs("div",{className:"text-slate-500",children:["Provider ",e.jsx("span",{className:"text-slate-300",children:Ka(K)})]}),e.jsxs("div",{className:"text-slate-500",children:["Model ",e.jsx("span",{className:"text-slate-300 truncate",children:H})]}),e.jsxs("div",{className:"text-slate-500",children:["Tokens ",e.jsx("span",{className:"text-slate-300",children:ee.toLocaleString()})]}),e.jsxs("div",{className:"text-slate-500",children:["Accel ",e.jsx("span",{className:"text-slate-300",children:W?Z:"off"})]}),e.jsxs("div",{className:"text-slate-500",children:["Platform ",e.jsx("span",{className:"text-slate-300",children:ye})]}),e.jsxs("div",{className:"text-slate-500",children:["Bridge ",e.jsx("span",{className:pe==="online"?"text-emerald-300":"text-amber-300",children:pe})]})]})]})]}),w==="workpad"&&e.jsx(yv,{workflowId:c,onOpenWorkpad:z}),w==="actions"&&e.jsx(bv,{workflowId:c,chatLog:p}),w==="health"&&e.jsx(wv,{onRunHealthCheck:I,bulkBusy:y,onEntriesChange:S}),w==="missions"&&e.jsxs("section",{"data-testid":"operator-inbox-missions-tab",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.18em] font-bold text-fuchsia-300 mb-2",children:"Scheduled Missions"}),Pe.length>0?e.jsx("div",{className:"space-y-2",children:Pe.map(ne=>e.jsx(Ki,{task:{id:`mission-${ne.missionId}`,kind:"mission_schedule",label:String(ne.missionId||"mission"),detail:`every ${kv(ne.intervalMs)} · ${ne.dryRun?"dry-run":"live"}`,category:"operation",status:"scheduled",cancellable:!1}},`mission-${ne.missionId}-${ne.intervalMs}`))}):e.jsx("div",{"data-testid":"operator-inbox-missions-empty",className:"text-center py-8 text-[11px] font-mono text-slate-500 border border-dashed border-white/10 rounded-xl",children:"No scheduled missions. Configure them in Mission Control or Readiness."})]}),A&&e.jsx("div",{className:"rounded-xl border border-rose-400/25 bg-rose-500/10 px-3 py-2 text-[10px] font-mono text-rose-200",children:A})]}),e.jsxs("div",{className:"px-4 py-2.5 border-t border-violet-500/10 bg-shell-soft/40 text-[10px] text-slate-500 flex items-center justify-between rounded-b-2xl",children:[e.jsx("span",{children:"Auto-refresh every 2s · Ctrl+Shift+T inbox · Ctrl+Shift+A actions · Ctrl+Shift+C calendar · Esc closes"}),e.jsx("span",{className:"font-mono text-slate-600",children:w})]})]})]})}),uu={info:"border-cyan-300/30 bg-cyan-500/15 text-cyan-100",success:"border-emerald-300/30 bg-emerald-500/15 text-emerald-100",warning:"border-amber-300/30 bg-amber-500/15 text-amber-100",error:"border-rose-300/30 bg-rose-500/15 text-rose-100"},Iv=i.memo(function(){const[r,n]=i.useState({message:"",tone:"info"}),s=i.useRef(null),a=i.useCallback(()=>{s.current&&(window.clearTimeout(s.current),s.current=null),n({message:"",tone:"info"})},[]);i.useEffect(()=>{const c=u=>{const x=u&&u.detail?u.detail:{},p=String(x.message||"").trim();if(!p)return;const d=String(x.tone||"info");n({message:p,tone:d}),s.current&&window.clearTimeout(s.current),s.current=window.setTimeout(()=>{n({message:"",tone:"info"})},3200)};return window.addEventListener("neuralshell:toast",c),()=>{window.removeEventListener("neuralshell:toast",c),s.current&&window.clearTimeout(s.current)}},[]);const o=!!r.message,l=uu[r.tone]||uu.info;return e.jsx("div",{"data-testid":"app-toast-host","aria-live":"polite",className:`fixed bottom-5 left-1/2 -translate-x-1/2 z-[200] max-w-[min(92vw,520px)] transition-all duration-300 ${o?"opacity-100 translate-y-0":"opacity-0 translate-y-2 pointer-events-none"}`,children:e.jsxs("div",{className:`rounded-xl border px-4 py-2.5 text-[11px] font-mono shadow-[0_12px_40px_rgba(0,0,0,0.45)] flex items-center gap-3 ${l}`,children:[e.jsx("span",{"data-testid":"app-toast-message",className:"flex-1 min-w-0",children:r.message||" "}),o&&e.jsx("button",{type:"button","aria-label":"Dismiss notification","data-testid":"app-toast-dismiss-btn",onClick:a,className:"shrink-0 h-6 w-6 rounded-md border border-white/10 text-slate-300 hover:text-white hover:bg-white/10 transition-colors",children:"✕"})]})})}),pu={ready:{border:"border-emerald-300/25",badge:"bg-emerald-500/15 text-emerald-100 border-emerald-400/30",primary:"border-emerald-300/30 bg-emerald-500/10 text-emerald-100 hover:bg-emerald-500/20",secondary:"border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.06]"},degraded:{border:"border-amber-300/25",badge:"bg-amber-500/15 text-amber-100 border-amber-400/30",primary:"border-amber-300/30 bg-amber-500/10 text-amber-100 hover:bg-amber-500/20",secondary:"border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.06]"},blocked:{border:"border-rose-300/25",badge:"bg-rose-500/15 text-rose-100 border-rose-400/30",primary:"border-rose-300/30 bg-rose-500/10 text-rose-100 hover:bg-rose-500/20",secondary:"border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.06]"}},Pv=i.memo(function({open:r,onClose:n,connectionInfo:s,watchdogStatus:a,incidentCount:o=0,setupBlocked:l=!1,sessionDegradedDismissed:c=!1,acknowledgedReady:u=!1,exportAvailable:x=!1,exportBusy:p=!1,onStartOperating:d,onInspectIssue:m,onFixSetup:f,onOpenSettings:b,onContinueAnyway:h,onExportEvidence:g}){const y=i.useRef(null);Wa(r,y,n);const P=i.useMemo(()=>Hl({connectionInfo:s,watchdogStatus:a,incidentCount:o,setupBlocked:l}),[s,a,o,l]),A=i.useMemo(()=>Wl(P,{sessionDegradedDismissed:c,acknowledgedReady:u}),[P,c,u]),C=pu[A.verdict]||pu.blocked;if(!r)return null;const w=()=>{const{id:_}=A.primaryAction;if(_==="start"&&typeof d=="function"){d();return}if(_==="inspect"&&typeof m=="function"){m();return}_==="fix-setup"&&typeof f=="function"&&f()},j=()=>{const{id:_}=A.secondaryAction;if(_==="export"&&typeof g=="function"){g();return}if(_==="continue"&&typeof h=="function"){h();return}_==="open-settings"&&typeof b=="function"&&b()},E=A.secondaryAction.id==="export"&&!x,N=E?"Export Evidence — unavailable in this shell":A.secondaryAction.label;return e.jsx("div",{className:"fixed inset-0 z-[146] bg-black/70 backdrop-blur-sm flex items-center justify-center p-5",onClick:n,children:e.jsxs("section",{ref:y,"data-testid":"readiness-verdict-modal","data-verdict":A.verdict,"data-trust-severity":A.trustSeverity,role:"dialog","aria-modal":"true","aria-label":`Readiness verdict: ${A.title}`,className:`w-full max-w-lg rounded-2xl border bg-slate-950 p-5 shadow-[0_20px_90px_rgba(0,0,0,0.75)] ${C.border}`,onClick:_=>_.stopPropagation(),children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("span",{"data-testid":"readiness-verdict-title",className:`inline-flex px-2 py-0.5 rounded border text-[10px] font-bold uppercase tracking-[0.18em] ${C.badge}`,children:A.title}),e.jsx("p",{className:"text-[12px] text-slate-300 mt-2",children:A.message})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-400 space-y-1",children:[e.jsxs("div",{children:["Bridge: ",e.jsx("span",{className:"text-slate-200",children:P.bridge})]}),e.jsxs("div",{children:["Provider: ",e.jsxs("span",{className:"text-slate-200",children:[P.provider,"/",P.model||"—"]})]}),e.jsxs("div",{children:["Runtime: ",e.jsx("span",{className:"text-slate-200",children:P.runtimeLabel})]}),P.incidentCount>0&&e.jsxs("div",{children:["Incidents: ",e.jsx("span",{className:"text-amber-200",children:P.incidentCount})]})]}),e.jsxs("div",{className:"mt-5 flex items-center justify-end gap-2",children:[e.jsx("button",{type:"button","data-testid":"readiness-verdict-secondary-btn","data-action-id":A.secondaryAction.id,disabled:E||p,onClick:j,className:`px-3 py-2 rounded-lg border text-[10px] font-mono uppercase tracking-[0.14em] disabled:opacity-50 ${C.secondary}`,children:p?"Exporting…":N}),e.jsx("button",{type:"button","data-testid":"readiness-verdict-primary-btn","data-action-id":A.primaryAction.id,onClick:w,className:`px-4 py-2 rounded-lg border text-[10px] font-mono uppercase tracking-[0.14em] font-bold ${C.primary}`,children:A.primaryAction.label})]})]})})});function Rv(t={}){const r=t&&typeof t=="object"?t:{};Nt({id:"cmd-operator-inbox",slot:"palette.commands",title:"Open Operator Inbox",priority:5,stability:"core",contexts:["global"],contextLabel:"Operator",shortcut:"Ctrl + Shift + T",action:()=>{typeof r.openOperatorInbox=="function"&&r.openOperatorInbox()}}),Nt({id:"cmd-workpad",slot:"palette.commands",title:"Open Workpad",priority:6,stability:"core",contexts:["active-workflow"],contextLabel:"Current workflow",shortcut:"Ctrl + Shift + N",action:()=>{typeof r.openWorkpad=="function"&&r.openWorkpad()}}),Nt({id:"cmd-operator-calendar",slot:"palette.commands",title:"Open ChronoHUD",priority:7,stability:"core",contexts:["global"],contextLabel:"Operator",shortcut:"Ctrl + Shift + C",action:()=>{typeof r.openCalendar=="function"&&r.openCalendar()}}),Nt({id:"cmd-guided-actions",slot:"palette.commands",title:"Open Guided Actions",priority:8,stability:"core",contexts:["global"],contextLabel:"Operator",shortcut:"Ctrl + Shift + A",action:()=>{typeof r.openGuidedActions=="function"&&r.openGuidedActions()}}),Nt({id:"cmd-trust-report",slot:"palette.system",title:"Open Trust Report",priority:9,stability:"core",contexts:["system"],contextLabel:"Trust",action:()=>{typeof r.openTrustReport=="function"&&r.openTrustReport()}}),Nt({id:"cmd-health-check",slot:"palette.system",title:"Run System Health Check",priority:10,stability:"core",contexts:["system"],contextLabel:"Diagnostics",action:async()=>{typeof r.runHealthCheck=="function"&&await r.runHealthCheck()}}),Nt({id:"cmd-export-workpad",slot:"palette.system",title:"Export Workpad Markdown",priority:45,stability:"trusted",contexts:["active-workflow"],contextLabel:"Current workflow",action:()=>{typeof r.exportWorkpad=="function"&&r.exportWorkpad()}})}const Ov=new Set(["system","user","assistant"]),Tv={kernel:"assistant",operator:"assistant"};function Mv(t){return Array.isArray(t)?t.filter(r=>r&&typeof r=="object").map(r=>{const n=String(r.role||"").trim().toLowerCase(),s=Tv[n]||n,a=typeof r.content=="string"?r.content:String(r.content??"");return{role:s,content:a}}).filter(r=>Ov.has(r.role)&&r.content.trim().length>0):[]}async function Dv(t){var n,s,a,o;const r=String(t||"").trim();if(!(!r||!((s=(n=window.api)==null?void 0:n.settings)!=null&&s.get)||!((o=(a=window.api)==null?void 0:a.settings)!=null&&o.update)))try{const l=await window.api.settings.get();if(!l||typeof l!="object")return;const c=Array.isArray(l.connectionProfiles)?l.connectionProfiles:[],u=String(l.activeProfileId||"").trim(),x=u&&c.length?c.map(p=>String((p==null?void 0:p.id)||"")===u?{...p,defaultModel:r}:p):c;await window.api.settings.update({...l,defaultModel:r,connectionProfiles:x})}catch{}}const mu="https://discord.gg/neuralshell";function $v(){if(window.api&&window.api.system&&typeof window.api.system.openExternal=="function"){window.api.system.openExternal(mu).catch(()=>{});return}window.open(mu,"_blank","noopener,noreferrer")}function Lv(t){const r=String(t||"degraded").toLowerCase();return r==="healthy"?"border-emerald-300/35 bg-emerald-500/10 text-emerald-100":r==="critical"?"border-rose-300/40 bg-rose-500/10 text-rose-100":r==="offline"?"border-slate-300/30 bg-slate-500/10 text-slate-200":"border-amber-300/35 bg-amber-500/10 text-amber-100"}function Bv(t){const r=String(t||"").trim();if(!r)return"n/a";const n=new Date(r);return Number.isNaN(n.getTime())?r:n.toLocaleString()}function Fv({node:t,selected:r,onToggleSelect:n,onRemove:s,onOpenFeed:a}){const o=t&&typeof t=="object"?t:{},l=String(o.nodeId||"unknown-node");return e.jsxs("article",{"data-testid":`fleet-node-card-${l}`,"aria-label":`Fleet node ${l}`,className:`rounded-xl border p-3 ${Lv(o.runtimeHealth)} transition-colors`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-mono uppercase tracking-[0.12em] opacity-85",children:String(o.displayName||l)}),e.jsx("div",{className:"text-[9px] font-mono opacity-70",children:l})]}),e.jsxs("label",{className:"inline-flex items-center gap-1 text-[9px] font-mono uppercase tracking-[0.12em]",children:[e.jsx("input",{type:"checkbox",checked:!!r,onChange:()=>n(l),"aria-label":`Select node ${l} for compare`}),"Compare"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-1.5 mt-2 text-[9px] font-mono",children:[e.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-1.5 py-1",children:["Provider: ",e.jsx("span",{className:"text-slate-100",children:String(o.providerHealth||"unknown")})]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-1.5 py-1",children:["Proof: ",e.jsx("span",{className:"text-slate-100",children:String(o.proofStatus||"unknown")})]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-1.5 py-1",children:["Policy: ",e.jsx("span",{className:"text-slate-100",children:String(o.policyProfile||"none")})]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-1.5 py-1",children:["Version: ",e.jsx("span",{className:"text-slate-100",children:String(o.updateVersion||"unknown")})]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-1.5 py-1",children:["Relay: ",e.jsx("span",{className:"text-slate-100",children:String(o.relayStatus||"unknown")})]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-1.5 py-1",children:["Collab: ",e.jsx("span",{className:"text-slate-100",children:String(o.collabState||"unknown")})]})]}),e.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 text-[9px] font-mono opacity-80",children:[e.jsxs("span",{children:["Seen ",Bv(o.lastSeenAt)]}),e.jsxs("span",{children:[Array.isArray(o.alerts)?o.alerts.length:0," alert(s)"]})]}),e.jsxs("div",{className:"mt-2 flex items-center justify-end gap-2",children:[e.jsx("button",{type:"button","data-testid":`fleet-open-feed-${l}`,onClick:()=>a(l),className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"Event Feed"}),e.jsx("button",{type:"button","data-testid":`fleet-remove-node-${l}`,onClick:()=>s(l),className:"px-2 py-1 rounded border border-rose-300/35 bg-rose-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-rose-100",children:"Remove"})]})]})}function Uv({selectedNodes:t=[],compareRows:r=[]}){const n=Array.isArray(t)?t:[],s=n[0]||null,a=n[1]||null;return e.jsxs("section",{"data-testid":"fleet-compare-view",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Compare Selected Nodes"}),!s||!a?e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Select exactly two nodes to compare."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-[10px] font-mono",children:[e.jsx("div",{className:"text-slate-500",children:"Field"}),e.jsx("div",{className:"text-slate-300",children:String(s.displayName||s.nodeId)}),e.jsx("div",{className:"text-slate-300",children:String(a.displayName||a.nodeId)})]}),e.jsxs("div",{className:"max-h-52 overflow-auto space-y-1 pr-1",children:[(Array.isArray(r)?r:[]).map(o=>e.jsxs("div",{className:"grid grid-cols-3 gap-2 rounded border border-amber-300/30 bg-amber-500/10 px-2 py-1.5 text-[10px] font-mono",children:[e.jsx("div",{className:"text-amber-100",children:String(o.label||o.key)}),e.jsx("div",{className:"text-slate-200 break-all",children:String(o.left)}),e.jsx("div",{className:"text-slate-200 break-all",children:String(o.right)})]},o.key)),(!r||r.length===0)&&e.jsx("div",{className:"text-[10px] font-mono text-emerald-300",children:"No meaningful differences across selected fields."})]})]})]})}function gs(t,r,n){return e.jsxs("div",{className:`rounded border px-2 py-1 text-[10px] font-mono ${n}`,children:[e.jsx("span",{className:"opacity-80",children:t}),e.jsx("span",{className:"ml-1 font-bold",children:r})]})}function zv({open:t,onClose:r,fleet:n,onImportLocalRuntime:s}){const[a,o]=i.useState(""),[l,c]=i.useState(""),[u,x]=i.useState("");if(!t)return null;const p=n&&typeof n=="object"?n:{},d=Array.isArray(p.filteredNodes)?p.filteredNodes:[],m=Array.isArray(p.nodes)?p.nodes:[],f=p.healthSummary||{total:0,healthy:0,degraded:0,critical:0,offline:0},b=m.find(g=>String(g.nodeId||"")===String(u||""))||null,h=async g=>{const y=g&&g.target&&g.target.files?g.target.files[0]:null;if(y)try{const P=await p.importFleetFile(y);c(`Imported ${P} node(s) from ${y.name}.`),o("")}catch(P){c(""),o(P&&P.message?P.message:String(P))}finally{g&&g.target&&(g.target.value="")}};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[128] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"fleet-control-panel","aria-label":"Fleet Control Panel",className:"fixed inset-x-6 top-16 bottom-6 z-[129] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.72)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Fleet Control Panel"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Offline-first multi-node view from imported bundles and local runtime snapshots."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("label",{className:"px-2 py-1 rounded border border-cyan-300/35 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100 cursor-pointer",children:["Import Bundle",e.jsx("input",{"data-testid":"fleet-import-input",type:"file",accept:".json,.csv,application/json,text/csv",className:"hidden",onChange:h})]}),e.jsx("button",{type:"button","data-testid":"fleet-import-runtime-btn",onClick:()=>{if(typeof s=="function"){const g=s();g&&(c(`Imported local runtime node: ${g.displayName}.`),o(""))}},className:"px-2 py-1 rounded border border-blue-300/35 bg-blue-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-blue-100",children:"Import Local Node"}),e.jsx("button",{type:"button","data-testid":"fleet-clear-btn",onClick:()=>p.clearFleet(),className:"px-2 py-1 rounded border border-rose-300/35 bg-rose-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-rose-100",children:"Clear"}),e.jsx("button",{type:"button","data-testid":"fleet-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]})]}),e.jsxs("div",{className:"px-4 py-2 border-b border-white/10 bg-black/20 flex flex-wrap items-center gap-2",children:[gs("Total",f.total,"border-white/15 bg-black/25 text-slate-200"),gs("Healthy",f.healthy,"border-emerald-300/35 bg-emerald-500/10 text-emerald-100"),gs("Degraded",f.degraded,"border-amber-300/35 bg-amber-500/10 text-amber-100"),gs("Critical",f.critical,"border-rose-300/35 bg-rose-500/10 text-rose-100"),gs("Offline",f.offline,"border-slate-300/30 bg-slate-500/10 text-slate-200"),e.jsx("div",{className:"ml-auto inline-flex rounded border border-white/10 bg-black/30 overflow-hidden",children:[{id:"all",label:"All"},{id:"healthy",label:"Healthy"},{id:"degraded",label:"Degraded"},{id:"critical",label:"Critical"},{id:"offline",label:"Offline"}].map(g=>e.jsx("button",{type:"button","data-testid":`fleet-filter-${g.id}`,onClick:()=>p.setStatusFilter(g.id),className:`px-2 py-1 text-[9px] font-mono uppercase tracking-[0.12em] border-l border-white/10 first:border-l-0 ${String(p.statusFilter||"all")===g.id?"bg-cyan-500/20 text-cyan-100":"text-slate-300 hover:bg-white/10"}`,children:g.label},g.id))})]}),(l||a)&&e.jsxs("div",{className:"px-4 py-2 border-b border-white/10 bg-black/15",children:[l&&e.jsx("div",{"data-testid":"fleet-import-info",className:"text-[10px] font-mono text-emerald-200",children:l}),a&&e.jsx("div",{"data-testid":"fleet-import-error",className:"text-[10px] font-mono text-rose-200",children:a})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[1.1fr_0.9fr]",children:[e.jsxs("div",{className:"p-3 border-r border-white/10 min-h-0 flex flex-col",children:[e.jsxs("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold mb-2",children:["Node List (",d.length,")"]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto pr-1 space-y-2","data-testid":"fleet-node-list",children:[d.map(g=>e.jsx(Fv,{node:g,selected:Array.isArray(p.selectedNodeIds)&&p.selectedNodeIds.includes(g.nodeId),onToggleSelect:p.toggleNodeSelected,onRemove:p.removeNode,onOpenFeed:x},g.nodeId)),d.length===0&&e.jsx("div",{className:"rounded-lg border border-white/10 bg-black/25 px-3 py-3 text-[10px] font-mono text-slate-500",children:"No nodes loaded. Import JSON/CSV bundles or pull the local runtime."})]})]}),e.jsxs("div",{className:"p-3 min-h-0 overflow-auto space-y-3",children:[e.jsx(Uv,{selectedNodes:p.selectedNodes||[],compareRows:p.compareRows||[]}),e.jsxs("section",{"data-testid":"fleet-node-event-feed",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Node Event Feed"}),e.jsxs("select",{"data-testid":"fleet-event-node-select",value:u,onChange:g=>x(g.target.value),className:"rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200",children:[e.jsx("option",{value:"",children:"Select node"}),m.map(g=>e.jsx("option",{value:g.nodeId,children:g.displayName},g.nodeId))]})]}),b?e.jsxs("div",{className:"max-h-64 overflow-auto space-y-1 pr-1",children:[(Array.isArray(b.events)?b.events:[]).slice(-80).reverse().map(g=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/25 px-2 py-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[10px] font-mono",children:[e.jsx("span",{className:"text-slate-200",children:String(g.type||"fleet.event")}),e.jsx("span",{className:"text-slate-500",children:String(g.at||"")})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:[String(g.source||"fleet")," · ",String(g.severity||"info")]})]},g.id)),(!b.events||b.events.length===0)&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No events for this node yet."})]}):e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Choose a node to inspect its timeline."})]})]})]})]})]})}function xu(t){return t==null?"null":typeof t=="string"?t:JSON.stringify(t)}function Hv({currentState:t={},incomingState:r={}}){const n=t&&typeof t=="object"?t:{},s=r&&typeof r=="object"?r:{},o=Array.from(new Set([...Object.keys(n),...Object.keys(s)])).sort().map(l=>({key:l,before:n[l],after:s[l],changed:JSON.stringify(n[l])!==JSON.stringify(s[l])})).filter(l=>l.changed);return e.jsxs("section",{"data-testid":"restore-preview",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Restore Preview"}),e.jsxs("div",{className:"max-h-60 overflow-auto space-y-1 pr-1",children:[o.map(l=>e.jsxs("div",{className:"grid grid-cols-3 gap-2 rounded border border-amber-300/30 bg-amber-500/10 px-2 py-1 text-[10px] font-mono",children:[e.jsx("div",{className:"text-amber-100 break-all",children:l.key}),e.jsx("div",{className:"text-slate-300 break-all",children:xu(l.before)}),e.jsx("div",{className:"text-slate-100 break-all",children:xu(l.after)})]},l.key)),o.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-emerald-300",children:"No diff detected."})]})]})}const Wv="neuralshell_recovery_last_bundle_v1";async function fu(t){const n=new window.TextEncoder().encode(String(t||"")),s=await window.crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(s)).map(a=>a.toString(16).padStart(2,"0")).join("")}function bu(){if(typeof window>"u"||!window.localStorage)return{};const t=(r,n)=>{try{const s=window.localStorage.getItem(r);return s?JSON.parse(s):n}catch{return n}};return{policyProfiles:t("neuralshell_policy_profiles_v1",[]),nodechainRules:t("neuralshell_nodechain_rules_v1",[]),runtimeSnapshots:t("neuralshell_runtime_snapshots_v1",[]),operatorLayouts:{onboardingProgress:t("neuralshell_onboarding_progress_v1",{}),railLayout:t("neuralshell_rail_layout_prefs_v1",{}),railCollapse:t("neuralshell_rail_collapse_prefs_v1",{})},releaseTruth:t("neuralshell_release_truth_cache_v1",{}),marketplaceReceipts:t("neuralshell_marketplace_receipts_v1",[]),fleetConfig:t("neuralshell_fleet_nodes_v1",[]),analyticsBundles:t("neuralshell_analytics_bundle_cache_v1",{})}}function Ol(t,r){if(t==null)return t;if(Array.isArray(t))return t.map(s=>Ol(s,r));if(typeof t!="object")return t;const n={};return Object.entries(t).forEach(([s,a])=>{const o=String(s||"").toLowerCase();if(!r&&(o.includes("token")||o.includes("secret")||o.includes("password")||o.includes("passphrase")||o.includes("apikey"))){n[s]="[excluded]";return}n[s]=Ol(a,r)}),n}function Kv(t,r){const n=t&&typeof t=="object"?t:{},s=Array.isArray(r)?r:[],a={};return s.forEach(o=>{Object.prototype.hasOwnProperty.call(n,o)&&(a[o]=n[o])}),a}function Vv(t,r){const n=t&&typeof t=="object"?t:{};if(typeof window>"u"||!window.localStorage)return;const s=(a,o)=>{window.localStorage.setItem(a,JSON.stringify(o))};n.policyProfiles&&s("neuralshell_policy_profiles_v1",n.policyProfiles),n.nodechainRules&&s("neuralshell_nodechain_rules_v1",n.nodechainRules),n.runtimeSnapshots&&s("neuralshell_runtime_snapshots_v1",n.runtimeSnapshots),n.operatorLayouts&&typeof n.operatorLayouts=="object"&&(n.operatorLayouts.onboardingProgress&&s("neuralshell_onboarding_progress_v1",n.operatorLayouts.onboardingProgress),n.operatorLayouts.railLayout&&s("neuralshell_rail_layout_prefs_v1",n.operatorLayouts.railLayout),n.operatorLayouts.railCollapse&&s("neuralshell_rail_collapse_prefs_v1",n.operatorLayouts.railCollapse)),n.releaseTruth&&s("neuralshell_release_truth_cache_v1",n.releaseTruth),n.marketplaceReceipts&&s("neuralshell_marketplace_receipts_v1",n.marketplaceReceipts),n.fleetConfig&&s("neuralshell_fleet_nodes_v1",n.fleetConfig),n.analyticsBundles&&s("neuralshell_analytics_bundle_cache_v1",n.analyticsBundles),r==="safe"&&window.api&&window.api.settings&&typeof window.api.settings.update=="function"&&window.api.settings.update({offlineOnlyEnforced:!0,allowRemoteBridge:!1,autoUpdateChannel:"frozen"}).catch(()=>{})}function Gv({open:t,onClose:r}){const[n,s]=i.useState({policyProfiles:!0,nodechainRules:!0,runtimeSnapshots:!0,operatorLayouts:!0,releaseTruth:!0,marketplaceReceipts:!0,fleetConfig:!0,analyticsBundles:!1}),[a,o]=i.useState(!1),[l,c]=i.useState(""),[u,x]=i.useState(""),[p,d]=i.useState(!1),[m,f]=i.useState(null),[b,h]=i.useState(null),[g,y]=i.useState("full"),P=i.useMemo(()=>Object.entries(n).filter(([,E])=>!!E).map(([E])=>E),[n]),A=i.useMemo(()=>bu(),[]),C=async()=>{d(!0);try{const E=bu(),N=Kv(E,P),_={schema:"neuralshell_recovery_bundle_v1",generatedAt:new Date().toISOString(),includeSecrets:!!a,scopes:Ol(N,!!a)},S=await fu(pr(_)),R=await eo("neuralshell_recovery_signing_v1"),$=await to(_,R.privateKeyPem),U=await Tr(R.publicKeyPem),I={schema:"neuralshell_recovery_bundle_signed_v1",payload:_,hash:S,signature:$,signer:{publicKeyPem:R.publicKeyPem,fingerprint:U}};typeof window<"u"&&window.localStorage&&window.localStorage.setItem(Wv,JSON.stringify(I)),je(`neuralshell_recovery_bundle_${Date.now()}.signed.json`,I),c(`Recovery bundle exported (${P.length} scope(s), signer ${U.slice(0,24)}...).`),x(""),X("recovery.bundle.exported",{scopes:P,includeSecrets:!!a},{source:"recovery",severity:"info"})}catch(E){c(""),x(E&&E.message?E.message:String(E))}finally{d(!1)}},w=async E=>{const N=E&&E.target&&E.target.files?E.target.files[0]:null;if(N){d(!0);try{const _=await pt(N),S=JSON.parse(String(_||"{}")),R=S&&S.payload&&typeof S.payload=="object"?S.payload:null,$=String(S&&S.signature?S.signature:""),U=String(S&&S.signer&&S.signer.publicKeyPem?S.signer.publicKeyPem:""),I=String(S&&S.hash?S.hash:"").trim().toLowerCase();if(!R||!$||!U||!I)throw new Error("Bundle missing payload/signature/hash/public key.");const D=await Mt(R,$,U),z=await fu(pr(R)),F=I===z,J={ok:!!(D&&F),signatureValid:!!D,hashValid:!!F,hash:I,computedHash:z};if(f(S),h(J),!J.ok)throw new Error("Bundle verification failed (signature/hash mismatch).");c(`Bundle verified from ${N.name}.`),x(""),X("recovery.bundle.verified",{sourceName:N.name,signatureValid:J.signatureValid,hashValid:J.hashValid},{source:"recovery",severity:"info"})}catch(_){c(""),x(_&&_.message?_.message:String(_)),h(null)}finally{d(!1),E&&E.target&&(E.target.value="")}}},j=()=>{if(!m||!b||!b.ok){x("Import and verify a signed bundle before restore.");return}const E=m&&m.payload&&m.payload.scopes?m.payload.scopes:{};Vv(E,g),c(`Restore applied in ${g} mode.`),x(""),X("recovery.restore.applied",{restoreMode:g,scopeKeys:Object.keys(E||{})},{source:"recovery",severity:g==="safe"?"warning":"info"})};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[130] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"recovery-center",className:"fixed inset-x-8 top-18 bottom-8 z-[131] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Recovery Center"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Signed backup/export, staged restore preview, and safe-mode recovery paths."})]}),e.jsx("button",{type:"button","data-testid":"recovery-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.95fr_1.05fr]",children:[e.jsxs("div",{className:"p-3 border-r border-white/10 min-h-0 overflow-auto space-y-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Backup Scope Selection"}),Object.keys(n).map(E=>e.jsxs("label",{className:"flex items-center gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:!!n[E],onChange:N=>s(_=>({..._,[E]:!!N.target.checked}))}),E]},E)),e.jsxs("label",{className:"flex items-center gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:a,onChange:E=>o(!!E.target.checked)}),"Include secrets (dangerous)"]}),a&&e.jsx("div",{className:"rounded border border-rose-300/35 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-200",children:"Secret export is enabled. Use only for isolated sealed transfers."}),e.jsx("button",{type:"button","data-testid":"recovery-export-btn",disabled:p,onClick:C,className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 disabled:opacity-60",children:p?"Working...":"Export Signed Bundle"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Restore Bundle"}),e.jsxs("label",{className:"inline-flex items-center px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono uppercase tracking-[0.12em] text-cyan-100 cursor-pointer",children:["Import Signed Bundle",e.jsx("input",{type:"file","data-testid":"recovery-import-input",accept:".json,application/json",className:"hidden",onChange:w})]}),e.jsxs("div",{className:"space-y-1 text-[10px] font-mono",children:[e.jsxs("label",{className:"flex items-center gap-2 text-slate-300",children:[e.jsx("input",{type:"radio",name:"restore-mode",value:"full",checked:g==="full",onChange:()=>y("full")}),"Full restore"]}),e.jsxs("label",{className:"flex items-center gap-2 text-slate-300",children:[e.jsx("input",{type:"radio",name:"restore-mode",value:"partial",checked:g==="partial",onChange:()=>y("partial")}),"Partial restore"]}),e.jsxs("label",{className:"flex items-center gap-2 text-slate-300",children:[e.jsx("input",{type:"radio",name:"restore-mode",value:"safe",checked:g==="safe",onChange:()=>y("safe")}),"Safe-mode restore"]})]}),e.jsx("button",{type:"button","data-testid":"recovery-apply-btn",onClick:j,className:"w-full px-3 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100",children:"Apply Restore"})]}),b&&e.jsxs("section",{"data-testid":"recovery-verify-result",className:"rounded-xl border border-white/10 bg-black/20 p-3 text-[10px] font-mono space-y-1",children:[e.jsx("div",{className:b.ok?"text-emerald-300":"text-rose-300",children:b.ok?"PASS":"FAIL"}),e.jsxs("div",{className:"text-slate-400",children:["Signature: ",b.signatureValid?"valid":"invalid"]}),e.jsxs("div",{className:"text-slate-400",children:["Hash: ",b.hashValid?"valid":"invalid"]})]}),l&&e.jsx("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-[10px] font-mono text-emerald-100",children:l}),u&&e.jsx("div",{className:"rounded border border-rose-300/35 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-200",children:u})]}),e.jsxs("div",{className:"p-3 min-h-0 overflow-auto space-y-3",children:[e.jsx(Hv,{currentState:A,incomingState:m&&m.payload&&m.payload.scopes?m.payload.scopes:{}}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Staged Restore Notes"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-400",children:"Restore is blocked unless signature + hash both verify. Safe mode forces offline-only and frozen update ring before applying payload scopes."})]})]})]})]})]}):null}function Jv(){if(typeof window>"u"||!window.localStorage)return 0;const t=Number(window.localStorage.getItem("neuralshell_support_ingest_count_v1")||"0");return Number.isFinite(t)?Math.max(0,Math.round(t)):0}function qv({open:t,onClose:r,enabled:n,onToggleEnabled:s,runtimeState:a,fleetSummary:o}){const[l]=i.useState(()=>Jv()),c=a&&typeof a=="object"?a:{},u=c.relayState||{},x=c.policyState||{},p=c.updateLane||{},d=o&&typeof o=="object"?o:{total:0,healthy:0,degraded:0,critical:0,offline:0};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[132] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"appliance-console",className:"fixed inset-x-8 top-20 bottom-8 z-[133] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Appliance Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Hardened relay/control profile for operator deployments."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"appliance-toggle-btn",onClick:()=>{const m=!n;typeof s=="function"&&s(m),X("appliance.mode.changed",{enabled:m},{source:"appliance",severity:m?"info":"warning"})},className:`px-3 py-1.5 rounded border text-[10px] font-mono uppercase tracking-[0.12em] ${n?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100"}`,children:n?"Disable Appliance":"Enable Appliance"}),e.jsx("button",{type:"button","data-testid":"appliance-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-4 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold mb-2",children:"Relay / Policy / Updates"}),e.jsxs("div",{className:"space-y-1 text-[10px] font-mono text-slate-300",children:[e.jsxs("div",{children:["Relay Enabled: ",e.jsx("span",{className:"text-slate-100",children:u.enabled?"yes":"no"})]}),e.jsxs("div",{children:["Relay Channel: ",e.jsx("span",{className:"text-slate-100",children:String(u.mappedChannel||"local-only")})]}),e.jsxs("div",{children:["Policy Profile: ",e.jsx("span",{className:"text-slate-100",children:String(x.activePolicyProfile||"none")})]}),e.jsxs("div",{children:["Offline-only: ",e.jsx("span",{className:"text-slate-100",children:x.offlineOnly?"true":"false"})]}),e.jsxs("div",{children:["Update Ring: ",e.jsx("span",{className:"text-slate-100",children:String(x.updateRing||"stable")})]}),e.jsxs("div",{children:["Signature: ",e.jsx("span",{className:"text-slate-100",children:String(p.signatureState||"unknown")})]})]})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold mb-2",children:"Appliance Operations"}),e.jsxs("div",{className:"space-y-1 text-[10px] font-mono text-slate-300",children:[e.jsxs("div",{children:["Support Ingest Bundles: ",e.jsx("span",{className:"text-slate-100",children:l})]}),e.jsxs("div",{children:["Fleet Nodes: ",e.jsx("span",{className:"text-slate-100",children:d.total})]}),e.jsxs("div",{children:["Healthy: ",e.jsx("span",{className:"text-slate-100",children:d.healthy})]}),e.jsxs("div",{children:["Degraded: ",e.jsx("span",{className:"text-slate-100",children:d.degraded})]}),e.jsxs("div",{children:["Critical: ",e.jsx("span",{className:"text-slate-100",children:d.critical})]}),e.jsxs("div",{children:["Offline: ",e.jsx("span",{className:"text-slate-100",children:d.offline})]})]})]})]}),e.jsx("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 text-[10px] font-mono text-slate-400",children:"Appliance mode narrows UX scope to operational controls. Security and proof controls remain enforced and cannot be bypassed by profile branding or appliance toggles."})]})]})]}):null}const Ua={founder:{canRunPolicyRollouts:!0,canRunRecovery:!0,canDeclareIncidents:!0,canManageFleet:!0,canManageAppliance:!0,canViewSalesSlice:!0,canEditNodeChainMissions:!0},operator:{canRunPolicyRollouts:!0,canRunRecovery:!0,canDeclareIncidents:!0,canManageFleet:!0,canManageAppliance:!0,canViewSalesSlice:!1,canEditNodeChainMissions:!0},support:{canRunPolicyRollouts:!1,canRunRecovery:!0,canDeclareIncidents:!0,canManageFleet:!0,canManageAppliance:!0,canViewSalesSlice:!0,canEditNodeChainMissions:!1},security:{canRunPolicyRollouts:!0,canRunRecovery:!0,canDeclareIncidents:!0,canManageFleet:!0,canManageAppliance:!0,canViewSalesSlice:!1,canEditNodeChainMissions:!1},sales:{canRunPolicyRollouts:!1,canRunRecovery:!1,canDeclareIncidents:!1,canManageFleet:!1,canManageAppliance:!1,canViewSalesSlice:!0,canEditNodeChainMissions:!1}};function Yv(t){const r=String(t||"").trim().toLowerCase();return r==="founder"||r==="operator"||r==="support"||r==="security"||r==="sales"?Ua[r]:Ua.operator}function Zv({role:t,onChange:r}){const n=String(t||"operator").toLowerCase(),s=Ua[n]||Ua.operator;return e.jsxs("section",{"data-testid":"role-switcher",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Role Switcher"}),e.jsxs("select",{"data-testid":"role-switcher-select",value:n,onChange:a=>r(a.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200",children:[e.jsx("option",{value:"founder",children:"Founder"}),e.jsx("option",{value:"operator",children:"Operator"}),e.jsx("option",{value:"support",children:"Support"}),e.jsx("option",{value:"security",children:"Security/Compliance"}),e.jsx("option",{value:"sales",children:"Sales/Success"})]}),e.jsx("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5 text-[9px] font-mono text-slate-400",children:Object.entries(s).map(([a,o])=>e.jsxs("div",{children:[a,": ",e.jsx("span",{className:o?"text-emerald-300":"text-slate-500",children:o?"yes":"no"})]},a))})]})}const Y0="neuralshell_shift_console_v1";function Xv(){if(typeof window>"u"||!window.localStorage)return{notes:"",queueDepth:0,pendingActions:[]};try{const t=JSON.parse(window.localStorage.getItem(Y0)||"{}");return{notes:String(t&&t.notes?t.notes:""),queueDepth:Number.isFinite(Number(t&&t.queueDepth))?Number(t.queueDepth):0,pendingActions:Array.isArray(t&&t.pendingActions)?t.pendingActions:[]}}catch{return{notes:"",queueDepth:0,pendingActions:[]}}}async function Qv(t){const n=new window.TextEncoder().encode(String(t||"")),s=await window.crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(s)).map(a=>a.toString(16).padStart(2,"0")).join("")}function ej({open:t,onClose:r,role:n,onChangeRole:s,fleetNodes:a=[],incidents:o=[]}){const[l,c]=i.useState(()=>Xv()),[u,x]=i.useState("");i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(Y0,JSON.stringify(l))},[l]);const p=async()=>{const d=Array.isArray(a)?a.slice(0,10).map(y=>y.nodeId):[],m={schema:"neuralshell_shift_summary_v1",generatedAt:new Date().toISOString(),activeRole:n,queueDepth:Number(l.queueDepth||0),pendingActions:Array.isArray(l.pendingActions)?l.pendingActions:[],handoffNotes:String(l.notes||"").split(/\r?\n/).map(y=>y.trim()).filter(Boolean),incidents:Array.isArray(o)?o.slice(-20):[],assignedNodes:d},f=await eo("neuralshell_shift_signing_v1"),b=await to(m,f.privateKeyPem),h=await Qv(pr(m)),g=await Tr(f.publicKeyPem);je(`neuralshell_shift_summary_${Date.now()}.signed.json`,{schema:"neuralshell_shift_summary_signed_v1",payload:m,hash:h,signature:b,signer:{publicKeyPem:f.publicKeyPem,fingerprint:g}}),X("shift.summary.exported",{role:n,queueDepth:m.queueDepth,assignedNodes:d.length},{source:"shift",severity:"info"}),x(`Signed shift summary exported (${g.slice(0,24)}...).`)};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[134] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"shift-console",className:"fixed inset-x-10 top-20 bottom-8 z-[135] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Shift Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Operator handoff, queue posture, and signed summary export."})]}),e.jsx("button",{type:"button","data-testid":"shift-console-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[320px_1fr]",children:[e.jsxs("div",{className:"p-3 border-r border-white/10 min-h-0 overflow-auto space-y-3",children:[e.jsx(Zv,{role:n,onChange:s}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Shift Queue"}),e.jsxs("label",{className:"text-[10px] font-mono text-slate-300 block",children:["Queue Depth",e.jsx("input",{"data-testid":"shift-queue-depth-input",type:"number",min:"0",value:l.queueDepth,onChange:d=>c(m=>({...m,queueDepth:Math.max(0,Number(d.target.value||0))})),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1"})]}),e.jsx("button",{type:"button","data-testid":"shift-add-pending-action-btn",onClick:()=>c(d=>({...d,pendingActions:[...d.pendingActions||[],`action-${Date.now()}`]})),className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"Add Pending Action"}),e.jsxs("div",{className:"max-h-36 overflow-auto space-y-1 pr-1",children:[(l.pendingActions||[]).map((d,m)=>e.jsx("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[9px] font-mono text-slate-300 break-all",children:d},`${d}-${m}`)),(!l.pendingActions||l.pendingActions.length===0)&&e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:"No pending actions."})]})]})]}),e.jsxs("div",{className:"p-3 min-h-0 overflow-auto space-y-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Handoff Notes"}),e.jsx("textarea",{"data-testid":"shift-handoff-notes-input",value:l.notes,onChange:d=>c(m=>({...m,notes:d.target.value})),className:"w-full min-h-36 rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200",placeholder:"Capture next shift context, blockers, and known risks..."})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Assigned Nodes / Incidents"}),e.jsxs("div",{className:"text-[10px] font-mono text-slate-400",children:["Assigned nodes: ",Array.isArray(a)?a.length:0]}),e.jsxs("div",{className:"text-[10px] font-mono text-slate-400",children:["Open incidents: ",Array.isArray(o)?o.length:0]})]}),e.jsx("button",{type:"button","data-testid":"shift-export-summary-btn",onClick:p,className:"px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100",children:"Export Signed Shift Summary"}),u&&e.jsx("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-[10px] font-mono text-emerald-100",children:u})]})]})]})]}):null}const tj=[{id:"provider_bridge_failure",title:"Provider Bridge Failure",steps:["Retry provider bridge probe.","Switch to safe policy profile if probe fails twice.","Capture diagnostics bundle and attach to incident."]},{id:"relay_failure_repeated",title:"Repeated Relay Failure",steps:["Disable relay path after threshold.","Force local-only mode.","Review relay channel mapping and retry once."]},{id:"proof_engine_stall",title:"Proof Engine Stall",steps:["Abort stalled proof run and capture stdout tail.","Run health probe before retry.","Escalate incident if second run stalls."]},{id:"policy_corruption",title:"Policy Corruption",steps:["Block policy apply and freeze rollout queue.","Restore known-good signed policy bundle.","Run policy verification before reopening rollout."]},{id:"update_verification_failure",title:"Update Verification Failure",steps:["Freeze update lane immediately.","Reject pending pack and keep current version.","Notify operator with evidence hash details."]},{id:"vault_access_failure",title:"Vault Access Failure",steps:["Lock runtime and block sensitive actions.","Prompt sealed recovery flow.","Require manual operator acknowledgement before unlock."]},{id:"fleet_node_degraded",title:"Fleet Node Degraded/Unreachable",steps:["Mark node degraded in fleet panel.","Attempt one health re-probe and capture delta.","Open incident if node stays degraded for next cycle."]}];function rj({onApply:t}){return e.jsxs("section",{"data-testid":"recovery-playbook-view",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Recovery Playbooks"}),e.jsx("div",{className:"max-h-64 overflow-auto space-y-2 pr-1",children:tj.map(r=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 p-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:r.title}),e.jsx("button",{type:"button","data-testid":`playbook-apply-${r.id}`,onClick:()=>{typeof t=="function"&&t(r)},className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"Apply"})]}),e.jsx("ul",{className:"mt-1 space-y-1 text-[9px] font-mono text-slate-400",children:r.steps.map((n,s)=>e.jsxs("li",{children:[s+1,". ",n]},`${r.id}-${s}`))})]},r.id))})]})}function nj({open:t,onClose:r,incidents:n=[],fleetNodes:s=[],onDeclare:a,onResolve:o,onApplyPlaybook:l,onTriggerSafeMode:c}){const[u,x]=i.useState("Runtime Incident"),[p,d]=i.useState("degraded"),[m,f]=i.useState([]),[b,h]=i.useState(""),g=Array.isArray(n)?n:[],y=g.find(w=>String(w.incidentId||"")===String(b||""))||g[0]||null,P=w=>{const j=String(w||"");j&&f(E=>E.includes(j)?E.filter(N=>N!==j):[...E,j])},A=()=>{if(typeof a!="function")return;const w=a({title:u,severity:p,affectedNodes:m});w&&w.incidentId&&h(w.incidentId)},C=()=>{y&&je(`neuralshell_incident_${y.incidentId}.json`,{exportedAt:new Date().toISOString(),incident:y})};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[136] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"incident-mode-panel",className:"fixed inset-x-8 top-16 bottom-6 z-[137] rounded-2xl border border-rose-300/35 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-rose-300 font-bold",children:"Incident Mode"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Declare incidents, capture timeline, and execute recovery playbooks."})]}),e.jsx("button",{type:"button","data-testid":"incident-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.95fr_1.05fr]",children:[e.jsxs("div",{className:"p-3 border-r border-white/10 min-h-0 overflow-auto space-y-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Declare Incident"}),e.jsx("input",{"data-testid":"incident-title-input",value:u,onChange:w=>x(w.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200"}),e.jsxs("select",{"data-testid":"incident-severity-select",value:p,onChange:w=>d(w.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200",children:[e.jsx("option",{value:"warning",children:"warning"}),e.jsx("option",{value:"degraded",children:"degraded"}),e.jsx("option",{value:"critical",children:"critical"})]}),e.jsx("div",{className:"max-h-36 overflow-auto space-y-1 pr-1",children:(Array.isArray(s)?s:[]).map(w=>e.jsxs("label",{className:"flex items-center gap-2 text-[9px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:m.includes(w.nodeId),onChange:()=>P(w.nodeId)}),w.displayName]},w.nodeId))}),e.jsx("button",{type:"button","data-testid":"incident-declare-btn",onClick:A,className:"w-full px-3 py-1.5 rounded border border-rose-300/35 bg-rose-500/10 text-[10px] uppercase tracking-[0.14em] font-mono text-rose-100",children:"Declare Incident"}),e.jsx("button",{type:"button","data-testid":"incident-trigger-safe-mode-btn",onClick:()=>{typeof c=="function"&&c()},className:"w-full px-3 py-1.5 rounded border border-amber-300/35 bg-amber-500/10 text-[10px] uppercase tracking-[0.14em] font-mono text-amber-100",children:"Trigger Safe Mode"})]}),e.jsx(rj,{onApply:w=>{typeof l=="function"&&l(w,y)}})]}),e.jsxs("div",{className:"p-3 min-h-0 overflow-auto space-y-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Incident Queue"}),e.jsxs("div",{className:"space-y-1 max-h-40 overflow-auto pr-1",children:[g.map(w=>e.jsxs("button",{type:"button","data-testid":`incident-row-${w.incidentId}`,onClick:()=>h(w.incidentId),className:`w-full rounded border px-2 py-1.5 text-left ${String(b||y&&y.incidentId||"")===String(w.incidentId)?"border-rose-300/35 bg-rose-500/10":"border-white/10 bg-black/25 hover:bg-white/10"}`,children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:w.title}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:[w.severity," · ",w.status]})]},w.incidentId)),g.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No incidents declared."})]})]}),y&&e.jsxs("section",{"data-testid":"incident-active-view",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:y.title}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:[y.incidentId," · ",y.severity," · ",y.status]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"incident-export-btn",onClick:C,className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"Export"}),e.jsx("button",{type:"button","data-testid":"incident-resolve-btn",onClick:()=>{typeof o=="function"&&o(y.incidentId)},className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Resolve"})]})]}),e.jsxs("div",{className:"max-h-48 overflow-auto space-y-1 pr-1",children:[(Array.isArray(y.timeline)?y.timeline:[]).slice(-120).reverse().map((w,j)=>e.jsxs("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[9px] font-mono text-slate-300",children:[e.jsxs("div",{children:[w.type," · ",w.source]}),e.jsx("div",{className:"text-slate-500",children:w.at})]},`${w.at}-${j}`)),(!y.timeline||y.timeline.length===0)&&e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:"No timeline events captured yet."})]})]})]})]})]})]}):null}function sj({rows:t=[]}){const r=Array.isArray(t)?t:[];return e.jsxs("section",{"data-testid":"policy-diff-panel",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Policy Diff Preview"}),e.jsxs("div",{className:"max-h-44 overflow-auto space-y-1 pr-1",children:[r.map(n=>e.jsxs("div",{className:"grid grid-cols-3 gap-2 rounded border border-amber-300/30 bg-amber-500/10 px-2 py-1 text-[10px] font-mono",children:[e.jsx("div",{className:"text-amber-100 break-all",children:String(n.key||"field")}),e.jsx("div",{className:"text-slate-300 break-all",children:String(n.before)}),e.jsx("div",{className:"text-slate-100 break-all",children:String(n.after)})]},n.key)),r.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No diff to apply."})]})]})}function aj({history:t=[],onRollback:r}){const n=Array.isArray(t)?t:[];return e.jsxs("section",{"data-testid":"rollback-history-view",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Rollout History"}),e.jsxs("div",{className:"max-h-48 overflow-auto space-y-1 pr-1",children:[n.map(s=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 p-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[10px] font-mono",children:[e.jsx("span",{className:"text-slate-100",children:String(s.policyProfile||s.policyId||"policy")}),e.jsx("span",{className:"text-slate-500",children:String(s.status||"pending")})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["nodes: ",(s.nodeIds||[]).length," · ",String(s.updatedAt||s.createdAt||"")]}),e.jsx("div",{className:"mt-1 flex justify-end",children:e.jsx("button",{type:"button","data-testid":`rollout-rollback-${s.rolloutId}`,onClick:()=>{typeof r=="function"&&r(s)},className:"px-2 py-1 rounded border border-amber-300/30 bg-amber-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-amber-100",children:"Rollback"})})]},s.rolloutId)),n.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No rollout history yet."})]})]})}function oj(t,r,n){const s=Array.isArray(t)?t:[],a=Array.isArray(r)?r:[],o=s.find(u=>a.includes(u.nodeId)),l=o?String(o.policyProfile||"none"):"none",c=String(n||"none");return l===c?[]:[{key:"policyProfile",before:l,after:c}]}function ij({open:t,onClose:r,fleet:n,history:s=[],onApplyRollout:a,onRollbackRollout:o}){const[l,c]=i.useState(""),[u,x]=i.useState(""),[p,d]=i.useState(null),[m,f]=i.useState([]),[b,h]=i.useState("immediate"),[g,y]=i.useState(""),P=Array.isArray(n&&n.nodes)?n.nodes:[],A=String(p&&p.payload&&(p.payload.policyProfile||p.payload.label||p.payload.policyId)?p.payload.policyProfile||p.payload.label||p.payload.policyId:""),C=i.useMemo(()=>oj(P,m,A),[P,A,m]),w=async N=>{const _=N&&N.target&&N.target.files?N.target.files[0]:null;if(_)try{const S=await pt(_),R=JSON.parse(String(S||"{}")),$=R&&R.payload&&typeof R.payload=="object"?R.payload:null,U=String(R&&R.signature?R.signature:""),I=String(R&&R.signer&&R.signer.publicKeyPem?R.signer.publicKeyPem:"");if(!$||!U||!I)throw new Error("Signed bundle requires payload/signature/public key.");if(!await Mt($,U,I))throw new Error("Unsigned or invalid policy bundle rejected.");d(R),c(`Verified policy bundle: ${String($.policyProfile||$.label||$.policyId||"policy")}`),x("")}catch(S){d(null),c(""),x(S&&S.message?S.message:String(S))}finally{N&&N.target&&(N.target.value="")}},j=N=>{const _=String(N||"");f(S=>S.includes(_)?S.filter(R=>R!==_):[...S,_])},E=()=>{if(!p){x("Load a verified signed bundle first.");return}if(!m.length){x("Select at least one node.");return}typeof a=="function"&&(a({bundle:p,nodeIds:m,mode:b,scheduledFor:g}),x(""))};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[138] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"policy-rollout-console",className:"fixed inset-x-8 top-20 bottom-8 z-[139] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Policy Rollout Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Signed policy rollout preview, apply, verify, and rollback history."})]}),e.jsx("button",{type:"button","data-testid":"policy-rollout-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.95fr_1.05fr]",children:[e.jsxs("div",{className:"p-3 border-r border-white/10 min-h-0 overflow-auto space-y-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Signed Bundle Input"}),e.jsxs("label",{className:"inline-flex items-center px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono uppercase tracking-[0.12em] text-cyan-100 cursor-pointer",children:["Import Signed Policy",e.jsx("input",{"data-testid":"policy-rollout-import-input",type:"file",accept:".json,application/json",className:"hidden",onChange:w})]}),l&&e.jsx("div",{className:"text-[10px] font-mono text-emerald-200",children:l}),u&&e.jsx("div",{"data-testid":"policy-rollout-error",className:"text-[10px] font-mono text-rose-200",children:u})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Target Nodes"}),e.jsxs("div",{className:"max-h-40 overflow-auto space-y-1 pr-1",children:[P.map(N=>e.jsxs("label",{className:"flex items-center gap-2 text-[9px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:m.includes(N.nodeId),onChange:()=>j(N.nodeId)}),N.displayName]},N.nodeId)),P.length===0&&e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:"No fleet nodes available."})]}),e.jsxs("div",{className:"space-y-1 text-[10px] font-mono text-slate-300",children:[e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"radio",checked:b==="immediate",onChange:()=>h("immediate")}),"Immediate apply"]}),e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"radio",checked:b==="scheduled",onChange:()=>h("scheduled")}),"Schedule rollout"]}),b==="scheduled"&&e.jsx("input",{"data-testid":"policy-rollout-scheduled-input",type:"datetime-local",value:g,onChange:N=>y(N.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200"})]}),e.jsx("button",{type:"button","data-testid":"policy-rollout-apply-btn",onClick:E,className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100",children:"Apply Rollout"})]})]}),e.jsxs("div",{className:"p-3 min-h-0 overflow-auto space-y-3",children:[e.jsx(sj,{rows:C}),e.jsx(aj,{history:s,onRollback:N=>{typeof o=="function"&&o(N)}})]})]})]})]}):null}function lj({onPackVerified:t}){const[r,n]=i.useState(""),[s,a]=i.useState(""),[o,l]=i.useState(null),c=async u=>{const x=u&&u.target&&u.target.files?u.target.files[0]:null;if(x)try{const p=await pt(x),d=JSON.parse(String(p||"{}")),m=d&&d.payload&&typeof d.payload=="object"?d.payload:null,f=String(d&&d.signature?d.signature:""),b=String(d&&d.signer&&d.signer.publicKeyPem?d.signer.publicKeyPem:"");if(!m||!f||!b)throw new Error("Update pack missing payload/signature/public key.");if(!await Mt(m,f,b))throw new Error("Unverified update pack rejected.");l(d),n(`Verified update pack ${String(m.version||"unknown")}/${String(m.ring||"standard")}.`),a(""),typeof t=="function"&&t(d)}catch(p){l(null),n(""),a(p&&p.message?p.message:String(p))}finally{u&&u.target&&(u.target.value="")}};return e.jsxs("section",{"data-testid":"update-pack-manager",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Offline Update Pack Manager"}),e.jsxs("label",{className:"inline-flex items-center px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono uppercase tracking-[0.12em] text-cyan-100 cursor-pointer",children:["Import Signed Pack",e.jsx("input",{"data-testid":"update-pack-import-input",type:"file",accept:".json,application/json",className:"hidden",onChange:c})]}),r&&e.jsx("div",{className:"text-[10px] font-mono text-emerald-200",children:r}),s&&e.jsx("div",{"data-testid":"update-pack-error",className:"text-[10px] font-mono text-rose-200",children:s}),o&&e.jsxs("div",{"data-testid":"update-pack-verified",className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px] font-mono text-slate-300",children:["Pack ID: ",String(o&&o.payload&&o.payload.packId?o.payload.packId:o&&o.payload&&o.payload.version?`pack-${o.payload.version}`:"n/a")]})]})}const Tl=["canary","standard","delayed","locked"];function cj(t){return(Array.isArray(t)?t:[]).reduce((n,s)=>{const a=String(s&&s.updateRing?s.updateRing:"standard").toLowerCase(),o=Tl.includes(a)?a:"standard";return n[o]+=1,n},{canary:0,standard:0,delayed:0,locked:0})}function dj({fleet:t,verifiedPack:r,onAssignPack:n}){const[s,a]=i.useState("canary"),[o,l]=i.useState([]),c=Array.isArray(t&&t.nodes)?t.nodes:[],u=cj(c),x=d=>{const m=String(d||"");l(f=>f.includes(m)?f.filter(b=>b!==m):[...f,m])},p=()=>{!r||!r.payload||o.length&&typeof n=="function"&&n({nodeIds:o,ring:s,packId:String(r.payload.packId||`pack-${r.payload.version||"unknown"}`),version:String(r.payload.version||"unknown")})};return e.jsxs("section",{"data-testid":"update-ring-console",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Update Ring Console"}),e.jsx("div",{className:"grid grid-cols-4 gap-1 text-[9px] font-mono",children:Tl.map(d=>e.jsxs("div",{className:"rounded border border-white/10 bg-black/30 px-1.5 py-1 text-slate-300",children:[d,": ",u[d]]},d))}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:"Verified pack required before assignment. Unverified packs cannot be applied."}),e.jsx("select",{"data-testid":"update-ring-target-select",value:s,onChange:d=>a(d.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200",children:Tl.map(d=>e.jsx("option",{value:d,children:d},d))}),e.jsxs("div",{className:"max-h-40 overflow-auto space-y-1 pr-1",children:[c.map(d=>e.jsxs("label",{className:"flex items-center gap-2 text-[9px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:o.includes(d.nodeId),onChange:()=>x(d.nodeId)}),d.displayName," (",d.updateRing||"standard",")"]},d.nodeId)),c.length===0&&e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:"No nodes available."})]}),e.jsx("button",{type:"button","data-testid":"update-ring-assign-btn",disabled:!r||!r.payload,onClick:p,className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 disabled:opacity-50",children:"Assign Pack To Ring"})]})}function uj({open:t,onClose:r,fleet:n}){const[s,a]=i.useState(null);return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[140] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"offline-update-console",className:"fixed inset-x-10 top-20 bottom-8 z-[141] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Offline Update Packs"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Import verified packs, assign rings, and promote deliberately."})]}),e.jsx("button",{type:"button","data-testid":"offline-update-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-1 xl:grid-cols-2 gap-3 p-3 overflow-auto",children:[e.jsx(lj,{onPackVerified:o=>{a(o),X("update.pack.verified",{version:String(o&&o.payload&&o.payload.version?o.payload.version:"unknown"),ring:String(o&&o.payload&&o.payload.ring?o.payload.ring:"standard")},{source:"updates",severity:"info"})}}),e.jsx(dj,{fleet:n,verifiedPack:s,onAssignPack:o=>{n&&typeof n.assignUpdatePack=="function"&&(n.assignUpdatePack(o.nodeIds,{packId:o.packId,ring:o.ring,version:o.version}),X("update.pack.assigned",{packId:o.packId,ring:o.ring,targets:o.nodeIds.length},{source:"updates",severity:"info"}))}})]})]})]}):null}const ys=[{missionId:"nightly_fleet_health_sweep",label:"Nightly Fleet Health Sweep",description:"Run nightly health sweep and summarize degraded nodes.",target:"fleet",defaultScheduleMinutes:1440,defaultDryRun:!1,steps:["collect_fleet_snapshot","score_runtime_health","emit_summary"]},{missionId:"post_policy_recovery_export",label:"Post-Policy Recovery Export",description:"After policy rollout, export recovery bundle evidence.",target:"fleet",defaultScheduleMinutes:60,defaultDryRun:!0,steps:["verify_policy_rollout","export_recovery_bundle","attach_audit_record"]},{missionId:"weekly_release_truth_audit",label:"Weekly Release Truth Audit",description:"Run weekly release truth checks and report drift.",target:"fleet",defaultScheduleMinutes:10080,defaultDryRun:!0,steps:["run_release_truth_verify","compare_last_report","raise_alert_if_drift"]},{missionId:"degraded_node_incident_trigger",label:"Degraded Node Incident Trigger",description:"Open incident mode when degraded fleet threshold is exceeded.",target:"fleet",defaultScheduleMinutes:15,defaultDryRun:!0,steps:["detect_degraded_nodes","open_incident_mode","assign_operator"]},{missionId:"proof_pass_relay_summary",label:"Proof-Pass Relay Summary",description:"After proof pass, relay summary to approved appliance queue.",target:"node",defaultScheduleMinutes:30,defaultDryRun:!0,steps:["detect_proof_pass","compose_summary","relay_to_approved_queue"]},{missionId:"update_fail_freeze_notify",label:"Update Fail Freeze + Notify",description:"Freeze node updates and alert operator on update verification failure.",target:"node",defaultScheduleMinutes:10,defaultDryRun:!1,steps:["detect_update_verification_failure","freeze_update_lane","notify_operator"]}];class pj{constructor(r=[],n={}){this.hooks=n,this.schedules=Array.isArray(r)?r:[],this.history=[],this.timers=new Map}setSchedules(r){this.schedules=Array.isArray(r)?r:[],this.restart()}getSchedules(){return this.schedules.slice()}getHistory(){return this.history.slice(-500)}restart(){this.stop(),this.start()}start(){this.stop(),this.schedules.forEach(r=>{if(!r||!r.enabled)return;const n=Number(r.intervalMs||0);if(!Number.isFinite(n)||n<1e3)return;const s=window.setInterval(()=>{this.runScheduledMission(r).catch(()=>{})},n);this.timers.set(String(r.missionId||""),s)})}stop(){Array.from(this.timers.values()).forEach(r=>window.clearInterval(r)),this.timers.clear()}async runMission(r,n={}){const s=new Date().toISOString(),a=!!n.dryRun,o={runId:`mission-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,missionId:String(r&&r.missionId?r.missionId:"mission"),label:String(r&&r.label?r.label:"Mission"),target:r&&r.target?r.target:"fleet",targetNodeIds:Array.isArray(n.targetNodeIds)?n.targetNodeIds:[],dryRun:a,status:"completed",startedAt:s,finishedAt:new Date().toISOString(),detail:a?"Dry-run complete. No side effects applied.":"Mission completed."};return this.history.push(o),this.history=this.history.slice(-500),this.hooks.onRun&&await Promise.resolve(this.hooks.onRun(o)),o}cancelRun(r){this.history=this.history.map(n=>String(n.runId||"")!==String(r||"")?n:{...n,status:"cancelled",finishedAt:new Date().toISOString(),detail:"Mission run cancelled."})}async runScheduledMission(r){const n=String(r&&r.missionId?r.missionId:"");if(!n)return;const s={missionId:n,label:n,description:"scheduled mission",target:r&&r.targetNodeIds&&r.targetNodeIds.length?"node":"fleet",defaultScheduleMinutes:Math.max(1,Math.round(Number(r.intervalMs||6e4)/6e4)),defaultDryRun:!!r.dryRun,steps:[]};await this.runMission(s,{dryRun:!!r.dryRun,targetNodeIds:r.targetNodeIds})}}function mj({history:t=[],onCancel:r}){const n=Array.isArray(t)?t:[];return e.jsxs("section",{"data-testid":"mission-history-panel",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Mission History"}),e.jsxs("div",{className:"max-h-56 overflow-auto space-y-1 pr-1",children:[n.map(s=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 p-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[10px] font-mono",children:[e.jsx("span",{className:"text-slate-100",children:s.label}),e.jsx("span",{className:"text-slate-500",children:s.status})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:[s.missionId," · ",s.startedAt]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:s.detail}),e.jsx("div",{className:"mt-1 flex justify-end",children:e.jsx("button",{type:"button","data-testid":`mission-cancel-${s.runId}`,onClick:()=>{typeof r=="function"&&r(s.runId)},className:"px-2 py-1 rounded border border-amber-300/30 bg-amber-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-amber-100",children:"Cancel"})})]},s.runId)),n.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No missions run yet."})]})]})}const Z0="neuralshell_nodechain_mission_schedules_v1";function xj(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(Z0)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function fj(t,r=1){const n=Number(t);return Number.isFinite(n)?n:r}function bj({open:t,onClose:r,fleet:n,onOpenIncidentMode:s}){const[a,o]=i.useState(()=>xj()),[l,c]=i.useState(()=>String(ys[0]&&ys[0].missionId||"")),[u,x]=i.useState([]),[p,d]=i.useState(!0),[m,f]=i.useState(30),[b,h]=i.useState(!1),[g,y]=i.useState([]),P=i.useRef(null);i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(Z0,JSON.stringify(a))},[a]),i.useEffect(()=>{const _=new pj(a,{onRun:S=>{y(R=>[S,...Array.isArray(R)?R:[]].slice(0,300)),X("nodechain.mission.run",{missionId:S.missionId,dryRun:S.dryRun,status:S.status},{source:"nodechain-missions",severity:S.dryRun?"info":"warning"}),!S.dryRun&&S.missionId==="degraded_node_incident_trigger"&&typeof s=="function"&&s()}});return P.current=_,_.start(),()=>{_.stop(),P.current=null}},[s,a]);const A=i.useMemo(()=>ys.find(_=>String(_.missionId||"")===String(l||""))||null,[l]),C=Array.isArray(n&&n.nodes)?n.nodes:[],w=_=>{const S=String(_||"");x(R=>R.includes(S)?R.filter($=>$!==S):[...R,S])},j=async()=>{!P.current||!A||await P.current.runMission(A,{dryRun:p,targetNodeIds:u})},E=()=>{if(!A)return;const _=String(A.missionId||""),S={missionId:_,enabled:!!b,intervalMs:Math.max(1e3,Math.round(fj(m,1)*6e4)),dryRun:!!p,targetNodeIds:u.slice()};o(R=>{const $=Array.isArray(R)?R:[];return $.some(I=>String(I.missionId||"")===_)?$.map(I=>String(I.missionId||"")===_?S:I):[...$,S]})},N=()=>{if(!A)return;const _=String(A.missionId||"");o(S=>Array.isArray(S)?S.map(R=>String(R.missionId||"")===_?{...R,enabled:!1}:R):S)};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[142] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"mission-scheduler",className:"fixed inset-x-8 top-20 bottom-8 z-[143] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"NodeChain Mission Scheduler"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Template-driven orchestration with dry-run, schedules, and history."})]}),e.jsx("button",{type:"button","data-testid":"mission-scheduler-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.95fr_1.05fr]",children:[e.jsxs("div",{className:"p-3 border-r border-white/10 min-h-0 overflow-auto space-y-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Mission Template"}),e.jsx("select",{"data-testid":"mission-template-select",value:l,onChange:_=>{c(_.target.value);const S=ys.find(R=>String(R.missionId||"")===String(_.target.value||""));S&&(d(!!S.defaultDryRun),f(Number(S.defaultScheduleMinutes||30)))},className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200",children:ys.map(_=>e.jsx("option",{value:_.missionId,children:_.label},_.missionId))}),A&&e.jsx("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px] font-mono text-slate-400",children:A.description}),e.jsxs("label",{className:"inline-flex items-center gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:p,onChange:_=>d(!!_.target.checked)}),"Dry-run"]}),e.jsxs("label",{className:"inline-flex items-center gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:b,onChange:_=>h(!!_.target.checked)}),"Schedule enabled"]}),e.jsxs("label",{className:"text-[10px] font-mono text-slate-300 block",children:["Interval Minutes",e.jsx("input",{"data-testid":"mission-interval-input",type:"number",min:"1",value:m,onChange:_=>f(Math.max(1,Number(_.target.value||1))),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1"})]})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Target Nodes"}),e.jsxs("div",{className:"max-h-36 overflow-auto space-y-1 pr-1",children:[C.map(_=>e.jsxs("label",{className:"flex items-center gap-2 text-[9px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:u.includes(_.nodeId),onChange:()=>w(_.nodeId)}),_.displayName]},_.nodeId)),C.length===0&&e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:"No nodes in fleet."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"mission-run-now-btn",onClick:j,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"Run Now"}),e.jsx("button",{type:"button","data-testid":"mission-save-schedule-btn",onClick:E,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"Save Schedule"}),e.jsx("button",{type:"button","data-testid":"mission-pause-schedule-btn",onClick:N,className:"px-2.5 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-amber-100",children:"Pause"})]})]})]}),e.jsx("div",{className:"p-3 min-h-0 overflow-auto space-y-3",children:e.jsx(mj,{history:g,onCancel:_=>{P.current&&(P.current.cancelRun(_),y(P.current.getHistory().slice().reverse()))}})})]})]})]}):null}const hu="neuralshell_airgap_transfer_chain_v1",gu="neuralshell_airgap_import_checklist_v1",yu="neuralshell_airgap_export_checklist_v1",hj="neuralshell_airgap_activated_artifacts_v1",ws=[{id:"import-media-serial",label:"Validate transfer media serial and seal record."},{id:"import-hash-verify",label:"Verify hash and signature before ingest."},{id:"import-quarantine",label:"Quarantine unverified inbound artifacts."},{id:"import-dual-approval",label:"Record dual-operator approval for activation."}],wa=[{id:"export-class-label",label:"Assign courier class and sensitivity label."},{id:"export-manifest-sign",label:"Sign outbound manifest with sender identity."},{id:"export-ledger-record",label:"Record handoff in offline transfer ledger."},{id:"export-receipt-confirm",label:"Capture receiver receipt hash and close transfer."}];function Vi(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function va(t,r){typeof window>"u"||!window.localStorage||window.localStorage.setItem(t,JSON.stringify(r))}function wu(t,r){const n=r&&typeof r=="object"?r:{},s={};return t.forEach(a=>{s[a.id]=!!n[a.id]}),s}function gj(t){const r=String(t&&t.schema?t.schema:"").toLowerCase();return r.includes("update_pack")?"update_pack":r.includes("recovery_bundle")?"evidence_bundle":r.includes("airgap_bundle")?"docs_bundle":r.includes("certificate")||r.includes("cert")?"certificate_bundle":r.includes("trust")?"trust_bundle":"unknown"}async function yj(t){const r=new window.TextEncoder().encode(String(t||"")),n=await window.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}function vu(t,r){return r.reduce((n,s)=>n+(t[s.id]?1:0),0)}function wj({open:t,onClose:r,locked:n=!1,onToggleLocked:s}){const[a,o]=i.useState(()=>{const j=Vi(hu,[]);return Array.isArray(j)?j:[]}),[l,c]=i.useState(()=>wu(ws,Vi(gu,{}))),[u,x]=i.useState(()=>wu(wa,Vi(yu,{}))),[p,d]=i.useState(""),[m,f]=i.useState(""),[b,h]=i.useState(!1);i.useEffect(()=>{va(hu,a)},[a]),i.useEffect(()=>{va(gu,l)},[l]),i.useEffect(()=>{va(yu,u)},[u]);const g=vu(l,ws),y=vu(u,wa),P=a.filter(j=>j.direction==="import"&&j.verified),A=a.filter(j=>j.direction==="import"&&!j.verified),C=async j=>{const E=j&&j.target&&j.target.files?j.target.files[0]:null;if(E){h(!0);try{const N=await pt(E),_=JSON.parse(String(N||"{}")),S=_&&_.payload&&typeof _.payload=="object"?_.payload:null,R=String(_&&_.signature?_.signature:""),$=String(_&&_.signer&&_.signer.publicKeyPem?_.signer.publicKeyPem:""),U=String(_&&_.hash?_.hash:"").trim().toLowerCase();if(!S||!R||!$||!U)throw new Error("Artifact missing payload/signature/public key/hash.");const I=await Mt(S,R,$),D=await yj(pr(S)),F=!!(I&&D===U),J=String(_&&_.direction?_.direction:"import").toLowerCase()==="export"?"export":"import",ee={transferId:`airgap-transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,at:new Date().toISOString(),sourceName:String(E.name||"artifact.json"),direction:J,artifactType:gj(S),classLabel:String(_&&_.classLabel?_.classLabel:"standard"),signerFingerprint:String(_&&_.signer&&_.signer.fingerprint?_.signer.fingerprint:""),hash:U,computedHash:D,verified:F,quarantineState:F?"released":"quarantined",schema:String(S&&S.schema?S.schema:"unknown")};o(ie=>[ee,...Array.isArray(ie)?ie:[]].slice(0,400)),d(F?`Verified ${ee.sourceName} and staged for activation.`:`Quarantined ${ee.sourceName}. Verification failed.`),f(F?"":"Imported artifact failed verification and remains quarantined.")}catch(N){d(""),f(N&&N.message?N.message:String(N))}finally{h(!1),j&&j.target&&(j.target.value="")}}},w=()=>{if(!P.length){f("No verified import artifacts available to activate.");return}if(gString(E.transferId));va(hj,{activatedAt:new Date().toISOString(),transferIds:j}),o(E=>Array.isArray(E)?E.map(N=>j.includes(String(N.transferId))?{...N,quarantineState:"released"}:N):E),!n&&typeof s=="function"&&s(!0),d(`Activated ${j.length} verified artifact(s) for air-gapped runtime.`),f("")};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[142] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"airgap-operations-center",className:"fixed inset-x-8 top-16 bottom-6 z-[143] rounded-2xl border border-slate-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.72)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-slate-200 font-bold",children:"Air-Gapped Operations Center"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Controlled import/export station with verification-first activation and sealed-network lock posture."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"airgap-lock-toggle-btn",onClick:()=>{typeof s=="function"&&s(!n)},className:`px-2.5 py-1.5 rounded border text-[10px] font-mono uppercase tracking-[0.12em] ${n?"border-slate-300/35 bg-slate-500/20 text-slate-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100"}`,children:n?"AirGap Locked":"Enable AirGap Lock"}),e.jsx("button",{type:"button","data-testid":"airgap-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.95fr_1.05fr]",children:[e.jsxs("div",{className:"p-3 border-r border-white/10 min-h-0 overflow-auto space-y-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Import / Export Station"}),e.jsx("div",{className:"text-[10px] text-slate-300",children:"Every inbound or outbound artifact must be recorded in the transfer chain with a verifiable signature/hash result."}),e.jsxs("label",{className:"inline-flex items-center px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono uppercase tracking-[0.12em] text-cyan-100 cursor-pointer",children:["Ingest Signed Artifact",e.jsx("input",{type:"file","data-testid":"airgap-import-input",accept:".json,application/json",className:"hidden",onChange:C})]}),e.jsx("button",{type:"button","data-testid":"airgap-activate-imports-btn",onClick:w,disabled:b,className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100 disabled:opacity-60",children:"Activate Verified Imports"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-[9px] font-mono",children:[e.jsxs("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-emerald-200",children:["verified imports: ",P.length]}),e.jsxs("div",{className:"rounded border border-amber-300/30 bg-amber-500/10 px-2 py-1 text-amber-200",children:["quarantined imports: ",A.length]})]})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:["Import Checklist (",g,"/",ws.length,")"]}),ws.map(j=>e.jsxs("label",{className:"flex items-start gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:!!l[j.id],onChange:E=>c(N=>({...N,[j.id]:!!E.target.checked}))}),e.jsx("span",{children:j.label})]},j.id))]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:["Export Checklist (",y,"/",wa.length,")"]}),wa.map(j=>e.jsxs("label",{className:"flex items-start gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:!!u[j.id],onChange:E=>x(N=>({...N,[j.id]:!!E.target.checked}))}),e.jsx("span",{children:j.label})]},j.id))]}),e.jsxs("section",{className:"rounded-xl border border-slate-300/25 bg-slate-500/10 p-3",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-300",children:["Network policy: ",e.jsx("span",{className:"text-slate-100 font-semibold",children:"no hidden external network assumptions"})]}),e.jsx("div",{className:"text-[9px] text-slate-400 font-mono mt-1",children:"Critical activation paths require explicit verification results and checklist completion before release."})]})]}),e.jsxs("div",{className:"p-3 min-h-0 overflow-auto space-y-3",children:[e.jsxs("section",{"data-testid":"airgap-transfer-ledger",className:"rounded-xl border border-white/10 bg-black/20 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Transfer Chain Ledger"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Inspectable record of import/export artifacts crossing the air-gap station."})]}),e.jsx("div",{className:`px-2 py-1 rounded border text-[9px] font-mono uppercase ${n?"border-slate-300/30 bg-slate-500/15 text-slate-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100"}`,children:n?"locked":"ready"})]}),e.jsxs("div",{className:"max-h-96 overflow-auto pr-1 space-y-1.5",children:[a.map(j=>e.jsxs("article",{className:`rounded-lg border px-2 py-1.5 ${j.verified?"border-emerald-300/30 bg-emerald-500/10":"border-rose-300/40 bg-rose-500/10"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:j.sourceName}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:new Date(j.at).toLocaleString()})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-300",children:[j.direction," · ",j.artifactType," · ",j.classLabel]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["schema ",j.schema," · ",j.verified?"verified/released":"quarantined"]})]},j.transferId)),a.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No transfer entries yet. Ingest a signed artifact to start the ledger."})]})]}),p&&e.jsx("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-[10px] font-mono text-emerald-100",children:p}),m&&e.jsx("div",{"data-testid":"airgap-import-error",className:"rounded border border-rose-300/40 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-100",children:m})]})]})]})]}):null}async function vj(t){const r=new window.TextEncoder().encode(String(t||"")),n=await window.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}function ju(t,r){const n=new Date(String(t||new Date().toISOString())),s=Number.isNaN(n.getTime())?new Date:n;return s.setUTCDate(s.getUTCDate()+Math.max(1,Number(r||1))),s.toISOString()}function jj(t){const r=new Date(String(t||"")).getTime();if(!Number.isFinite(r))return"unknown";const n=r-Date.now();return n<=0?"expired":n<=1e3*60*60*24*30?"expiring":"healthy"}function kj({caRecord:t,certificates:r,revokedCertificateIds:n,onUpdateCA:s,onUpdateCertificates:a,onUpdateRevocations:o}){const[l,c]=i.useState("Node Alpha"),[u,x]=i.useState("node-alpha"),[p,d]=i.useState("node"),[m,f]=i.useState(365),[b,h]=i.useState(""),[g,y]=i.useState(""),[P,A]=i.useState(!1),C=Array.isArray(r)?r:[],w=Array.isArray(n)?n:[],j=async()=>{A(!0);try{const S=await eo("neuralshell_pki_local_ca_v1"),R=await Tr(S.publicKeyPem),$={schema:"neuralshell_local_ca_v1",caId:String(t&&t.caId?t.caId:`ca-${Date.now()}`),commonName:"ProofForge Local Trust CA",createdAt:String(t&&t.createdAt?t.createdAt:new Date().toISOString()),rotatedAt:new Date().toISOString(),expiresAt:ju(new Date().toISOString(),3650),keyAlgorithm:"ECDSA_P256",publicKeyPem:S.publicKeyPem,privateKeyPem:S.privateKeyPem,fingerprint:R,nextSerial:Number(t&&t.nextSerial?t.nextSerial:1)};s($),h("Local CA ready for certificate issuance."),y("")}catch(S){h(""),y(S&&S.message?S.message:String(S))}finally{A(!1)}},E=async()=>{if(!(t&&t.privateKeyPem&&t.publicKeyPem)){y("Initialize local CA before issuing certificates.");return}A(!0);try{const S=Number(t.nextSerial||1),R={schema:"neuralshell_trust_certificate_v1",serialNumber:`NS-${String(S).padStart(8,"0")}`,kind:String(p||"node"),subjectName:String(l||"Unnamed Subject"),subjectId:String(u||`subject-${S}`),issuedAt:new Date().toISOString(),expiresAt:ju(new Date().toISOString(),Number(m||365)),issuedByCaId:String(t.caId||""),issuedByFingerprint:String(t.fingerprint||""),binding:{rolloutPolicyBinding:p==="fleet"||p==="org",evidenceExchangeBinding:p==="node"||p==="appliance"||p==="fleet"}},$=await to(R,t.privateKeyPem),U=await vj(pr(R));if(!await Mt(R,$,t.publicKeyPem))throw new Error("Issued certificate failed local signature verification.");const D={certificateId:`cert-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,...R,hash:U,signature:$,status:"active"};a([D,...C].slice(0,600)),s({...t,nextSerial:S+1}),h(`Certificate issued: ${D.serialNumber}`),y("")}catch(S){h(""),y(S&&S.message?S.message:String(S))}finally{A(!1)}},N=async S=>{c(String(S.subjectName||"Rotated Subject")),x(String(S.subjectId||"rotated-subject")),d(String(S.kind||"node")),await E()},_=S=>{const R=String(S||"");R&&(w.includes(R)||(o([R,...w]),a(C.map($=>String($.certificateId||"")===R?{...$,status:"revoked",revokedAt:new Date().toISOString(),revokedReason:"manual-revocation"}:$)),h(`Certificate revoked: ${R}`),y("")))};return e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Certificate Lifecycle"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Issue, rotate, revoke, and verify node/appliance/fleet/org certificates."})]}),e.jsx("button",{type:"button","data-testid":"trustfabric-init-ca-btn",onClick:j,disabled:P,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100 disabled:opacity-60",children:t?"Rotate CA Key":"Initialize Local CA"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-[10px] font-mono",children:[e.jsxs("label",{className:"space-y-1",children:[e.jsx("span",{className:"text-slate-400",children:"Subject Name"}),e.jsx("input",{"data-testid":"trustfabric-subject-name-input",value:l,onChange:S=>c(S.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsxs("label",{className:"space-y-1",children:[e.jsx("span",{className:"text-slate-400",children:"Subject ID"}),e.jsx("input",{"data-testid":"trustfabric-subject-id-input",value:u,onChange:S=>x(S.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsxs("label",{className:"space-y-1",children:[e.jsx("span",{className:"text-slate-400",children:"Certificate Kind"}),e.jsxs("select",{"data-testid":"trustfabric-kind-select",value:p,onChange:S=>d(S.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100",children:[e.jsx("option",{value:"node",children:"node"}),e.jsx("option",{value:"appliance",children:"appliance"}),e.jsx("option",{value:"fleet",children:"fleet"}),e.jsx("option",{value:"org",children:"org"})]})]}),e.jsxs("label",{className:"space-y-1",children:[e.jsx("span",{className:"text-slate-400",children:"Validity (days)"}),e.jsx("input",{"data-testid":"trustfabric-validity-input",type:"number",min:"1",max:"3650",value:m,onChange:S=>f(Number(S.target.value||365)),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]})]}),e.jsx("button",{type:"button","data-testid":"trustfabric-issue-cert-btn",disabled:P,onClick:E,className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100 disabled:opacity-60",children:"Issue Certificate"}),e.jsxs("div",{className:"space-y-1 max-h-64 overflow-auto pr-1",children:[C.map(S=>{const R=w.includes(String(S.certificateId||""))?"revoked":jj(S.expiresAt);return e.jsxs("article",{className:`rounded border px-2 py-1.5 ${R==="revoked"||R==="expired"?"border-rose-300/40 bg-rose-500/10":R==="expiring"?"border-amber-300/35 bg-amber-500/10":"border-emerald-300/30 bg-emerald-500/10"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-100",children:[S.serialNumber," · ",S.subjectName]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:S.kind})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["expires ",new Date(S.expiresAt).toLocaleDateString()," · ",R]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("button",{type:"button","data-testid":`trustfabric-rotate-${S.certificateId}`,onClick:()=>N(S),className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono text-cyan-100",children:"rotate"}),e.jsx("button",{type:"button","data-testid":`trustfabric-revoke-${S.certificateId}`,onClick:()=>_(S.certificateId),className:"px-2 py-1 rounded border border-rose-300/35 bg-rose-500/10 text-[9px] font-mono text-rose-100",children:"revoke"})]})]},S.certificateId)}),C.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No certificates issued yet."})]}),b&&e.jsx("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-[10px] font-mono text-emerald-100",children:b}),g&&e.jsx("div",{"data-testid":"trustfabric-error",className:"rounded border border-rose-300/40 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-100",children:g})]})}function Nj(t){const r=new Date(String(t||"")).getTime();if(!Number.isFinite(r))return"expired";const n=r-Date.now();return n<=0?"expired":n<=1e3*60*60*24*30?"expiring":"healthy"}function Sj({caRecord:t,certificates:r,revokedCertificateIds:n}){const s=Array.isArray(r)?r:[],a=Array.isArray(n)?n:[],[o,l]=i.useState({});i.useEffect(()=>{let u=!0;return(async()=>{const p={};for(const d of s){const m=String(d&&d.certificateId?d.certificateId:"");if(!m)continue;const f={schema:d.schema,serialNumber:d.serialNumber,kind:d.kind,subjectName:d.subjectName,subjectId:d.subjectId,issuedAt:d.issuedAt,expiresAt:d.expiresAt,issuedByCaId:d.issuedByCaId,issuedByFingerprint:d.issuedByFingerprint,binding:d.binding&&typeof d.binding=="object"?d.binding:{}},b=!!(t&&t.publicKeyPem)&&await Mt(f,String(d.signature||""),String(t.publicKeyPem||"")),h=a.includes(m),g=Nj(d.expiresAt);p[m]={signatureValid:b,revoked:h,expiry:g,ok:b&&!h&&g!=="expired"}}u&&l(p)})(),()=>{u=!1}},[t,s,a]);const c=i.useMemo(()=>{const u=Object.values(o);return{total:s.length,healthy:u.filter(x=>x.ok).length,expiring:u.filter(x=>x.expiry==="expiring").length,revoked:u.filter(x=>x.revoked).length}},[s.length,o]);return e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Trust Chain Viewer"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Certificate path state for nodes, appliances, fleets, and org relationships."})]}),e.jsx("button",{type:"button","data-testid":"trustchain-export-btn",onClick:()=>{je("neuralshell_trust_chain_view.json",{exportedAt:new Date().toISOString(),ca:t||null,certificates:s,revocations:a,verificationMap:o})},className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Export"})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-2 text-[9px] font-mono",children:[e.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-2 py-1 text-slate-300",children:["total ",c.total]}),e.jsxs("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-emerald-200",children:["healthy ",c.healthy]}),e.jsxs("div",{className:"rounded border border-amber-300/30 bg-amber-500/10 px-2 py-1 text-amber-200",children:["expiring ",c.expiring]}),e.jsxs("div",{className:"rounded border border-rose-300/35 bg-rose-500/10 px-2 py-1 text-rose-200",children:["revoked ",c.revoked]})]}),e.jsxs("div",{"data-testid":"trustchain-list",className:"max-h-72 overflow-auto pr-1 space-y-1.5",children:[s.map(u=>{const x=String(u&&u.certificateId?u.certificateId:""),p=o[x]||{ok:!1,signatureValid:!1,revoked:!1,expiry:"expired"};return e.jsxs("article",{className:`rounded border px-2 py-1.5 ${p.ok?"border-emerald-300/30 bg-emerald-500/10":p.revoked?"border-rose-300/40 bg-rose-500/10":p.expiry==="expiring"?"border-amber-300/35 bg-amber-500/10":"border-rose-300/40 bg-rose-500/10"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-100",children:[u.serialNumber," · ",u.subjectName]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:u.kind})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["sig=",p.signatureValid?"valid":"invalid"," · expiry=",p.expiry," · revoked=",p.revoked?"yes":"no"]})]},x)}),s.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No certificates available for trust-chain view."})]})]})}const ku="neuralshell_pki_local_ca_v1",Nu="neuralshell_pki_certificates_v1",Su="neuralshell_pki_revocations_v1";function Gi(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function Ji(t,r){typeof window>"u"||!window.localStorage||window.localStorage.setItem(t,JSON.stringify(r))}function Cj(t,r=30){const n=Number(r)*24*60*60*1e3,s=Date.now();return(Array.isArray(t)?t:[]).filter(a=>{const o=new Date(String(a&&a.expiresAt?a.expiresAt:"")).getTime();if(!Number.isFinite(o))return!1;const l=o-s;return l>0&&l<=n})}function _j({open:t,onClose:r}){const[n,s]=i.useState(()=>Gi(ku,null)),[a,o]=i.useState(()=>{const d=Gi(Nu,[]);return Array.isArray(d)?d:[]}),[l,c]=i.useState(()=>{const d=Gi(Su,[]);return Array.isArray(d)?d:[]});i.useEffect(()=>{Ji(ku,n)},[n]),i.useEffect(()=>{Ji(Nu,a)},[a]),i.useEffect(()=>{Ji(Su,l)},[l]);const u=i.useMemo(()=>Cj(a,30),[a]),x=Array.isArray(l)?l.length:0,p=(Array.isArray(a)?a:[]).filter(d=>!l.includes(String(d&&d.certificateId?d.certificateId:"")));return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[144] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"trust-fabric-console",className:"fixed inset-x-8 top-16 bottom-6 z-[145] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"PKI Trust Fabric"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Local CA issuance, certificate lifecycle controls, CRL enforcement, and trust-chain visibility."})]}),e.jsx("button",{type:"button","data-testid":"trust-fabric-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"p-3 border-b border-white/10 grid grid-cols-4 gap-2 text-[9px] font-mono",children:[e.jsxs("div",{className:"rounded border border-cyan-300/30 bg-cyan-500/10 px-2 py-1 text-cyan-100",children:["CA ",n?"initialized":"missing"]}),e.jsxs("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-emerald-100",children:["active certs ",p.length]}),e.jsxs("div",{className:"rounded border border-amber-300/30 bg-amber-500/10 px-2 py-1 text-amber-100",children:["expiring soon ",u.length]}),e.jsxs("div",{className:"rounded border border-rose-300/35 bg-rose-500/10 px-2 py-1 text-rose-100",children:["revoked ",x]})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.95fr_1.05fr] gap-3 p-3 overflow-auto",children:[e.jsx(kj,{caRecord:n,certificates:a,revokedCertificateIds:l,onUpdateCA:s,onUpdateCertificates:o,onUpdateRevocations:c}),e.jsx(Sj,{caRecord:n,certificates:a,revokedCertificateIds:l})]})]})]}):null}const qi="hardware_customization_profiles_v1",Yi="hardware_customization_settings_v1",Cu="luxgrid_profiles_v1",Aj="luxgrid_settings_v1",Ej=["single","multi","row","zone"],Ij=["Static","Pulse","Breathing","Temperature Gradient","Usage Meter","Timer Fade"];function Qe(){return new Date().toISOString()}function Pj(){return[{id:"zone-main",name:"Main Cluster",keyIds:["K1","K2","K3","K4","K5","K6"],color:"#22d3ee",effect:"Static",brightness:80,speed:40,sensorSource:"none"},{id:"zone-nav",name:"Navigation",keyIds:["K7","K8","K9","K10"],color:"#a78bfa",effect:"Pulse",brightness:70,speed:35,sensorSource:"cpu"}]}function _u(t="Thermal HUD"){const r=Qe();return{id:`profile-${Math.random().toString(36).slice(2,9)}`,name:t,description:"Default hardware customization profile.",zones:Pj(),effects:{global:"Static"},createdAt:r,updatedAt:r,lastAppliedAt:""}}function Au(){return[_u("Thermal HUD"),_u("Sleep Ritual")]}function Eu(){return{general:{startInSimulatorMode:!0,startMinimized:!1,minimizeToTray:!1,confirmBeforeExit:!0,themeIntensity:70,animationLevel:"medium"},device:{autoScanOnLaunch:!1,openRgbHost:"127.0.0.1",openRgbPort:6742,hidScanEnabled:!0,vendorLockWarnings:!0},profiles:{autoApplyLastProfile:!1,saveProfileOnChange:!0,defaultProfileId:"",backupProfiles:!0},proof:{saveProofLogs:!0,includeSimulatorProofs:!0,proofOutputFolder:"proof/hardware-customization",timestampFormat:"utc_iso"}}}function Rj(){return[["K1","K2","K3","K4","K5","K6"],["K7","K8","K9","K10","K11","K12"],["K13","K14","K15","K16","K17","K18"],["K19","K20","K21","K22","K23","K24"]].map((r,n)=>r.map((s,a)=>({id:s,rowIndex:n,colIndex:a})))}function Zi(t){const r=Qe();return{id:String(t&&t.id?t.id:`profile-${Math.random().toString(36).slice(2,9)}`),name:String(t&&t.name?t.name:"Imported Profile"),description:String(t&&t.description?t.description:""),zones:Array.isArray(t&&t.zones)?t.zones:[],effects:t&&typeof t.effects=="object"?t.effects:{},createdAt:String(t&&t.createdAt?t.createdAt:r),updatedAt:String(t&&t.updatedAt?t.updatedAt:r),lastAppliedAt:String(t&&t.lastAppliedAt?t.lastAppliedAt:"")}}function Iu(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function Pa(t,r){typeof window>"u"||!window.localStorage||window.localStorage.setItem(t,JSON.stringify(r))}function Xi(t,r,n){const s=Iu(t,null);if(s!=null)return s;const a=Iu(r,null);return a!=null?(Pa(t,a),a):n}function Oj(t,r){const n=new Blob([JSON.stringify(r,null,2)],{type:"application/json"}),s=URL.createObjectURL(n),a=document.createElement("a");a.href=s,a.download=t,a.click(),URL.revokeObjectURL(s)}function Tj(t,r){const n=Array.isArray(r&&r.zones)?r.zones:[];for(const s of n)if(Array.isArray(s.keyIds)&&s.keyIds.includes(t))return s.color||"#1f2937";return"#111827"}function Pu(t,r){return t.find(n=>String(n.id)===String(r))||null}async function Ru(t){const r=[{id:"sim-keyboard",name:"Simulated Keyboard",vendor:"ProofForge",product:"Hardware Simulator",type:"keyboard",mode:"simulator",writable:!0,reason:"Simulator device available.",capabilities:["zones","effects","proof"]}];if(window.api&&window.api.rgb&&typeof window.api.rgb.status=="function"){const n=await window.api.rgb.status().catch(()=>null);!!(n&&n.transport&&n.transport.connected)?r.push({id:"openrgb-bridge",name:"OpenRGB Bridge",vendor:"OpenRGB",product:"OpenRGB Server",type:"bridge",mode:"openrgb",writable:!1,reason:"OpenRGB connected; hardware write adapter not implemented.",capabilities:["status"]}):r.push({id:"openrgb-bridge",name:"OpenRGB Bridge",vendor:"OpenRGB",product:"OpenRGB Server",type:"bridge",mode:"openrgb",writable:!1,reason:"OpenRGB server not connected.",capabilities:[]})}return t.device.hidScanEnabled&&typeof navigator<"u"&&"hid"in navigator&&r.push({id:"hid-local",name:"Local HID Interface",vendor:"OS",product:"HID",type:"keyboard",mode:"hid",writable:!1,reason:"HID device found, no writable RGB endpoint detected.",capabilities:["enumeration"]}),r.push({id:"vendor-lock",name:"Roccat Bridge",vendor:"Roccat",product:"Swarm Managed Device",type:"keyboard",mode:"vendor",writable:!1,reason:"Device may be locked by vendor software. Close Roccat Swarm before Live Mode.",capabilities:["vendor_lock_warning"]}),r}function Mj({open:t,onClose:r,onOpenSettings:n}){const[s,a]=i.useState(()=>Xi(qi,Cu,Au())),[o,l]=i.useState(()=>Xi(Yi,Aj,Eu())),[c,u]=i.useState(()=>{const B=Xi(qi,Cu,Au());return B[0]?B[0].id:""}),[x,p]=i.useState(()=>c),[d,m]=i.useState(""),[f,b]=i.useState(""),[h,g]=i.useState("simulator"),[y,P]=i.useState("No profile applied yet."),[A,C]=i.useState("sim-keyboard"),[w,j]=i.useState("single"),[E,N]=i.useState([]),[_,S]=i.useState(""),[R,$]=i.useState([]),[U,I]=i.useState(null),[D,z]=i.useState(""),[F,J]=i.useState(!1),[ee,ie]=i.useState("general"),[ye,pe]=i.useState("Simulator device available."),K=i.useRef(null);i.useEffect(()=>Pa(qi,s),[s]),i.useEffect(()=>Pa(Yi,o),[o]),i.useEffect(()=>{t&&o.device.autoScanOnLaunch&&Ru(o).then(B=>$(B))},[t,o]);const H=i.useMemo(()=>Pu(s,x)||s[0]||null,[s,x]),W=i.useMemo(()=>Pu(s,c)||s[0]||null,[s,c]),Z=i.useMemo(()=>R.find(B=>B.id===A)||null,[R,A]),ce=i.useMemo(()=>Rj(),[]);if(i.useEffect(()=>{!x&&s[0]&&p(s[0].id),!c&&s[0]&&u(s[0].id)},[s,x,c]),!t)return null;const fe=B=>{a(oe=>oe.map(xe=>xe.id===B.id?B:xe))},me=()=>{if(!H)return;const B=Qe();u(H.id),p(H.id),m(H.id),b(B),g("simulator"),P(`Applied ${H.name} to simulator.`),pe(`Applied ${H.name} to simulator.`),fe({...H,updatedAt:B,lastAppliedAt:B})},ke=()=>{if(!Z||!Z.writable){const oe=Z?Z.reason:"Cannot apply to device: no writable device selected.";g("failed"),P(oe||"Cannot apply to device: no writable device selected."),pe(oe||"Cannot apply to device: no writable device selected.");return}const B=Qe();b(B),m(H?H.id:""),g(Z.mode),P(`Applied ${H?H.name:"profile"} to ${Z.name}.`)},Pe=()=>{const B=Qe(),oe=Zi({name:`New Profile ${s.length+1}`,description:"",zones:[],effects:{global:"Static"},createdAt:B,updatedAt:B});a(xe=>[...xe,oe]),p(oe.id),u(oe.id)},_e=()=>{if(!H)return;const B=Qe(),oe=Zi({...H,id:`profile-${Math.random().toString(36).slice(2,9)}`,name:`${H.name} Copy`,zones:JSON.parse(JSON.stringify(H.zones||[])),effects:JSON.parse(JSON.stringify(H.effects||{})),createdAt:B,updatedAt:B,lastAppliedAt:""});a(xe=>[...xe,oe]),p(oe.id)},ne=()=>{if(!H)return;if(s.length<=1){pe("Cannot delete the last profile.");return}if(!window.confirm(`Delete profile "${H.name}"?`))return;const oe=s.filter(xe=>xe.id!==H.id);a(oe),p(oe[0].id),c===H.id&&u(oe[0].id)},we=()=>{if(!H)return;const B=Qe(),oe={...H,zones:[],effects:{global:"Static"},updatedAt:B};fe(oe),pe(`Reset ${H.name}.`)},Be=()=>{H&&Oj(`${H.name.replace(/\s+/g,"_").toLowerCase()}_hardware_profile.json`,H)},re=async B=>{const oe=B.target.files&&B.target.files[0];if(oe)try{const xe=await oe.text(),Re=JSON.parse(xe);if(!Re||typeof Re!="object"||!Re.name)throw new Error("Bad profile import: missing name.");const De=Zi(Re);a(tt=>[...tt,De]),p(De.id),pe(`Imported profile "${De.name}".`)}catch(xe){pe(`Bad import: ${xe&&xe.message?xe.message:"Invalid JSON"}`)}finally{K.current&&(K.current.value="")}},ae=B=>{const oe=B.id;if(w==="single"){N([oe]);return}if(w==="row"){const xe=ce[B.rowIndex].map(Re=>Re.id);N(xe);return}if(w==="zone"&&H){const xe=(H.zones||[]).find(Re=>Re.id===_)||(H.zones||[])[0];N(xe?xe.keyIds||[]:[]);return}N(xe=>xe.includes(oe)?xe.filter(Re=>Re!==oe):[...xe,oe])},M=()=>{if(!H||!_)return;const B=(H.zones||[]).map(oe=>oe.id===_?{...oe,keyIds:Array.from(new Set(E))}:{...oe,keyIds:(oe.keyIds||[]).filter(xe=>!E.includes(xe))});fe({...H,zones:B,updatedAt:Qe()})},V=()=>{if(!H)return;const B={id:`zone-${Math.random().toString(36).slice(2,8)}`,name:`Zone ${(H.zones||[]).length+1}`,keyIds:[],color:"#22d3ee",effect:"Static",brightness:80,speed:40,sensorSource:"none"};fe({...H,zones:[...H.zones||[],B],updatedAt:Qe()}),S(B.id)},G=(B,oe)=>{if(!H)return;const xe=(H.zones||[]).map(Re=>Re.id===B?{...Re,...oe}:Re);fe({...H,zones:xe,updatedAt:Qe()})},te=()=>{if(!H||!_)return;const B=(H.zones||[]).filter(oe=>oe.id!==_);fe({...H,zones:B,updatedAt:Qe()}),S(B[0]?B[0].id:"")},de=async()=>{const B=await Ru(o);$(B),!A&&B[0]&&C(B[0].id),pe(B[0]?B[0].reason:"No devices detected.")},L=()=>{if(!H)return;if(!Z||!Z.writable){const Re={timestamp:Qe(),success:!1,reason:Z&&Z.reason?Z.reason:"No writable device selected"};I(Re),z("proof-failed");return}const B=Array.isArray(H.zones)?H.zones:[],oe=B.reduce((Re,De)=>Re+(Array.isArray(De.keyIds)?De.keyIds.length:0),0),xe={timestamp:Qe(),mode:"simulator",deviceId:"sim-keyboard",deviceName:"Simulated Keyboard",profile:H.name,zonesApplied:B.length,keysApplied:oe,success:!0,notes:["Simulator proof only — no physical device changed."]};I(xe),z("proof-success")},be=!!(Z&&Z.writable),Q=H&&(H.zones||[]).find(B=>B.id===_)||null,We=ce.flat();return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[146] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"hardware-appliance-manager",className:"fixed inset-x-8 top-16 bottom-6 z-[147] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Hardware Customization Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"ProofForge can detect supported local devices exposed through Simulator, OpenRGB, HID, or future vendor adapters."})]}),e.jsx("button",{type:"button",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-3 p-3 overflow-auto flex-1 min-h-0",children:[e.jsxs("section",{className:"col-span-1 rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{"data-testid":"active-profile-card",className:"text-[10px] font-mono text-cyan-100",children:["Active: ",W?W.name:"n/a"]}),e.jsx("div",{className:"space-y-1 max-h-44 overflow-auto",children:s.map(B=>e.jsx("button",{type:"button",onClick:()=>p(B.id),className:`w-full text-left px-2 py-1 rounded border text-[10px] font-mono ${B.id===x?"border-cyan-300/40 bg-cyan-500/10 text-cyan-100":"border-white/10 bg-black/30 text-slate-300"}`,children:B.name},B.id))}),e.jsx("input",{"data-testid":"profile-name-input",value:H?H.name:"",onChange:B=>H&&fe({...H,name:B.target.value,updatedAt:Qe()}),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px] text-slate-200"}),e.jsx("textarea",{"data-testid":"profile-description-input",value:H?H.description:"",onChange:B=>H&&fe({...H,description:B.target.value,updatedAt:Qe()}),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px] text-slate-200"}),e.jsxs("div",{className:"grid grid-cols-2 gap-1",children:[e.jsx("button",{"data-testid":"profile-create-button",type:"button",onClick:Pe,className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"New"}),e.jsx("button",{"data-testid":"profile-duplicate-button",type:"button",onClick:_e,className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"Duplicate"}),e.jsx("button",{"data-testid":"profile-rename-button",type:"button",onClick:()=>H&&pe(`Renamed profile to ${H.name}.`),className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"Rename"}),e.jsx("button",{"data-testid":"profile-delete-button",type:"button",onClick:ne,className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"Delete"}),e.jsx("button",{"data-testid":"profile-export-button",type:"button",onClick:Be,className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"Export"}),e.jsx("button",{"data-testid":"profile-import-button",type:"button",onClick:()=>K.current&&K.current.click(),className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"Import"}),e.jsx("button",{"data-testid":"profile-reset-button",type:"button",onClick:we,className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"Reset"})]}),e.jsx("input",{ref:K,type:"file",accept:".json,application/json",onChange:re,className:"hidden"})]}),e.jsxs("section",{className:"col-span-2 rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("select",{"data-testid":"selection-mode-select",value:w,onChange:B=>j(B.target.value),className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px]",children:Ej.map(B=>e.jsx("option",{value:B,children:B},B))}),e.jsxs("span",{"data-testid":"selected-key-count",className:"text-[10px] font-mono text-cyan-100",children:[E.length," selected"]}),e.jsx("button",{"data-testid":"selection-clear-button",type:"button",onClick:()=>N([]),className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"Clear"}),e.jsx("button",{"data-testid":"selection-invert-button",type:"button",onClick:()=>N(We.map(B=>B.id).filter(B=>!E.includes(B))),className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"Invert"}),e.jsx("button",{"data-testid":"selection-all-button",type:"button",onClick:()=>N(We.map(B=>B.id)),className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"All"})]}),e.jsx("div",{className:"space-y-1",children:ce.map(B=>e.jsx("div",{className:"flex gap-1",children:B.map(oe=>{const xe=E.includes(oe.id);return e.jsx("button",{type:"button","data-testid":xe?"keyboard-key-selected":"keyboard-key",onClick:()=>ae(oe),className:`h-8 w-12 rounded border text-[9px] font-mono ${xe?"border-cyan-300 bg-cyan-500/20 text-cyan-100":"border-white/10 text-slate-200"}`,style:{backgroundColor:xe?void 0:Tj(oe.id,H)},children:oe.id},oe.id)})},B[0].id))})]}),e.jsxs("section",{className:"col-span-1 rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("button",{"data-testid":"zone-create-button",type:"button",onClick:V,className:"w-full px-2 py-1 rounded border border-white/10 text-[9px]",children:"Create Zone"}),e.jsxs("select",{value:_,onChange:B=>S(B.target.value),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px]",children:[e.jsx("option",{value:"",children:"Select Zone"}),(H&&H.zones||[]).map(B=>e.jsx("option",{value:B.id,children:B.name},B.id))]}),e.jsx("input",{"data-testid":"zone-rename-input",value:Q?Q.name:"",onChange:B=>Q&&G(Q.id,{name:B.target.value}),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px]"}),e.jsx("button",{"data-testid":"zone-delete-button",type:"button",onClick:te,className:"w-full px-2 py-1 rounded border border-white/10 text-[9px]",children:"Delete Zone"}),e.jsx("input",{"data-testid":"zone-color-picker",type:"color",value:Q?Q.color:"#22d3ee",onChange:B=>Q&&G(Q.id,{color:B.target.value}),className:"w-full h-8"}),e.jsx("select",{"data-testid":"zone-effect-select",value:Q?Q.effect:"Static",onChange:B=>Q&&G(Q.id,{effect:B.target.value}),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px]",children:Ij.map(B=>e.jsx("option",{value:B,children:B},B))}),e.jsx("input",{"data-testid":"zone-brightness-slider",type:"range",min:"0",max:"100",value:Q?Q.brightness:80,onChange:B=>Q&&G(Q.id,{brightness:Number(B.target.value)})}),e.jsx("input",{"data-testid":"zone-speed-slider",type:"range",min:"0",max:"100",value:Q?Q.speed:40,onChange:B=>Q&&G(Q.id,{speed:Number(B.target.value)})}),e.jsxs("select",{"data-testid":"zone-sensor-source-select",value:Q?Q.sensorSource:"none",onChange:B=>Q&&G(Q.id,{sensorSource:B.target.value}),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px]",children:[e.jsx("option",{value:"none",children:"none"}),e.jsx("option",{value:"cpu",children:"cpu"}),e.jsx("option",{value:"gpu",children:"gpu"}),e.jsx("option",{value:"timer",children:"timer"})]}),e.jsx("button",{"data-testid":"assign-selection-zone-button",type:"button",onClick:M,className:"w-full px-2 py-1 rounded border border-white/10 text-[9px]",children:"Assign selection"}),e.jsx("button",{"data-testid":"zone-preview-button",type:"button",onClick:()=>pe(Q?`Previewing ${Q.name}`:"Select a zone first."),className:"w-full px-2 py-1 rounded border border-white/10 text-[9px]",children:"Preview Zone"}),e.jsx("div",{"data-testid":"zone-assigned-keys",className:"text-[9px] font-mono text-slate-400",children:Q&&(Q.keyIds||[]).join(", ")||"none"})]})]}),e.jsxs("div",{className:"px-3 py-2 border-t border-white/10 bg-black/40 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[10px] font-mono",children:[e.jsx("button",{"data-testid":"device-scan-button",type:"button",onClick:de,className:"px-2 py-1 rounded border border-white/10",children:"Scan Devices"}),e.jsx("button",{"data-testid":"app-restart-scan-button",type:"button",onClick:de,className:"px-2 py-1 rounded border border-white/10",children:"Restart Scan"}),e.jsx("button",{"data-testid":"apply-simulator-button",type:"button",onClick:me,className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10",children:"Apply to Simulator"}),e.jsx("button",{"data-testid":"apply-device-button",type:"button",disabled:!be,onClick:ke,className:"px-2 py-1 rounded border border-white/10 disabled:opacity-50",children:"Apply to Device"}),e.jsx("span",{"data-testid":"profile-apply-status",children:ye})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:R.map(B=>e.jsxs("button",{type:"button","data-testid":"device-card",onClick:()=>C(B.id),className:`px-2 py-1 rounded border text-[9px] font-mono ${B.id===A?"border-cyan-300/40 bg-cyan-500/10":"border-white/10"}`,children:[e.jsx("div",{children:B.name}),e.jsx("div",{"data-testid":"device-mode-badge",children:B.mode}),e.jsx("div",{"data-testid":"device-writable-status",children:B.writable?"writable":"read-only"}),e.jsx("div",{"data-testid":"device-lock-reason",children:B.reason})]},B.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[10px] font-mono",children:[e.jsx("span",{"data-testid":"last-applied-status",children:y}),e.jsx("span",{"data-testid":"last-applied-at",children:f||"n/a"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{"data-testid":"proof-run-button",type:"button",onClick:L,className:"px-2 py-1 rounded border border-white/10",children:"Run Proof"}),e.jsx("div",{"data-testid":"proof-mode",className:"text-[10px] font-mono",children:h}),e.jsx("div",{"data-testid":"proof-success",className:"text-[10px] font-mono",children:D})]}),e.jsx("pre",{"data-testid":"proof-output",className:"max-h-32 overflow-auto text-[9px] font-mono border border-white/10 rounded p-2 bg-black/40",children:U?JSON.stringify(U,null,2):"No proof yet."}),e.jsx("div",{"data-testid":"proof-reason",className:"text-[10px] font-mono text-slate-400",children:U&&!U.success?U.reason:""}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{"data-testid":"settings-button",type:"button",onClick:()=>J(!0),className:"px-2 py-1 rounded border border-white/10",children:"Settings"}),e.jsx("button",{"data-testid":"app-settings-button",type:"button",onClick:()=>J(!0),className:"px-2 py-1 rounded border border-white/10",children:"App Settings"}),e.jsx("button",{"data-testid":"app-minimize-button",type:"button",disabled:!(window.api&&window.api.app&&typeof window.api.app.minimize=="function"),onClick:()=>window.api.app.minimize(),className:"px-2 py-1 rounded border border-white/10 disabled:opacity-50",children:"Minimize"}),e.jsx("button",{"data-testid":"app-exit-button",type:"button",disabled:!(window.api&&window.api.app&&typeof window.api.app.exit=="function"),onClick:()=>window.api.app.exit(),className:"px-2 py-1 rounded border border-white/10 disabled:opacity-50",children:"Exit"}),e.jsx("button",{type:"button",onClick:()=>typeof n=="function"&&n(),className:"px-2 py-1 rounded border border-white/10",children:"Open App Settings"})]})]})]}),F&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[148] bg-black/50",onClick:()=>J(!1)}),e.jsxs("section",{"data-testid":"settings-modal",className:"fixed right-12 top-20 z-[149] w-[28rem] rounded-xl border border-white/10 bg-slate-950 p-3 space-y-2",children:[e.jsx("div",{className:"flex gap-1",children:["general","device","profiles","proof"].map(B=>e.jsx("button",{"data-testid":`settings-${B}-tab`,type:"button",onClick:()=>ie(B),className:`px-2 py-1 rounded border text-[9px] ${ee===B?"border-cyan-300/40 bg-cyan-500/10":"border-white/10"}`,children:B},B))}),ee==="general"&&e.jsxs("label",{className:"text-[10px] font-mono flex items-center justify-between",children:["Start in Simulator Mode",e.jsx("input",{type:"checkbox",checked:o.general.startInSimulatorMode,onChange:B=>l(oe=>({...oe,general:{...oe.general,startInSimulatorMode:B.target.checked}}))})]}),ee==="device"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-[10px] font-mono flex items-center justify-between",children:["Auto-scan on launch",e.jsx("input",{"data-testid":"setting-auto-scan",type:"checkbox",checked:o.device.autoScanOnLaunch,onChange:B=>l(oe=>({...oe,device:{...oe.device,autoScanOnLaunch:B.target.checked}}))})]}),e.jsx("input",{"data-testid":"setting-openrgb-host",value:o.device.openRgbHost,onChange:B=>l(oe=>({...oe,device:{...oe.device,openRgbHost:B.target.value}})),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px]"}),e.jsx("input",{"data-testid":"setting-openrgb-port",type:"number",value:o.device.openRgbPort,onChange:B=>l(oe=>({...oe,device:{...oe.device,openRgbPort:Number(B.target.value)}})),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px]"})]}),ee==="profiles"&&e.jsxs("label",{className:"text-[10px] font-mono flex items-center justify-between",children:["Auto-apply last profile",e.jsx("input",{"data-testid":"setting-auto-apply-profile",type:"checkbox",checked:o.profiles.autoApplyLastProfile,onChange:B=>l(oe=>({...oe,profiles:{...oe.profiles,autoApplyLastProfile:B.target.checked}}))})]}),ee==="proof"&&e.jsx("input",{"data-testid":"setting-proof-output-folder",value:o.proof.proofOutputFolder,onChange:B=>l(oe=>({...oe,proof:{...oe.proof,proofOutputFolder:B.target.value}})),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px]"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{"data-testid":"settings-save-button",type:"button",onClick:()=>{Pa(Yi,o),J(!1)},children:"Save"}),e.jsx("button",{"data-testid":"settings-reset-button",type:"button",onClick:()=>l(Eu()),children:"Reset"})]})]})]})]})}function Dj(t){const r=String(t||"").toLowerCase();return r==="released"?"border-emerald-300/30 bg-emerald-500/10":r==="verified"?"border-cyan-300/30 bg-cyan-500/10":r==="quarantined"?"border-amber-300/35 bg-amber-500/10":"border-white/10 bg-black/20"}function $j({entries:t,onVerifyReceipt:r,onReleaseFromQuarantine:n}){const s=Array.isArray(t)?t:[];return e.jsxs("section",{"data-testid":"transfer-ledger-view",className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Transfer Ledger"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Each handoff is recorded with quarantine, verification, and release transitions."})]}),e.jsxs("div",{className:"max-h-80 overflow-auto pr-1 space-y-1.5",children:[s.map(a=>e.jsxs("article",{className:`rounded border px-2 py-1.5 ${Dj(a.status)}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:a.packageId}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:a.courierClass})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:[a.sender," ➜ ",a.receiver," · ",a.status]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("button",{type:"button","data-testid":`courier-verify-${a.entryId}`,onClick:()=>{typeof r=="function"&&r(a.entryId)},className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono text-cyan-100",children:"verify receipt"}),e.jsx("button",{type:"button","data-testid":`courier-release-${a.entryId}`,onClick:()=>{typeof n=="function"&&n(a.entryId)},className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] font-mono text-emerald-100",children:"release"})]})]},a.entryId)),s.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No transfer ledger entries yet."})]})]})}const Ou="neuralshell_courier_transfer_ledger_v1";function Lj(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function Bj(t,r){typeof window>"u"||!window.localStorage||window.localStorage.setItem(t,JSON.stringify(r))}async function Fj(t){const r=new window.TextEncoder().encode(String(t||"")),n=await window.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}function Tu(t){const r=String(t||"").trim().toLowerCase();return r==="standard"||r==="sensitive"||r==="sealed"||r==="emergency"?r:"standard"}function Uj({open:t,onClose:r}){const[n,s]=i.useState(()=>{const f=Lj(Ou,[]);return Array.isArray(f)?f:[]}),[a,o]=i.useState("standard"),[l,c]=i.useState(""),[u,x]=i.useState("");i.useEffect(()=>{Bj(Ou,n)},[n]);const p=async f=>{const b=f&&f.target&&f.target.files?f.target.files[0]:null;if(b)try{const h=await pt(b),g=JSON.parse(String(h||"{}")),y=g&&g.payload&&typeof g.payload=="object"?g.payload:null,P=String(g&&g.signature?g.signature:""),A=String(g&&g.hash?g.hash:"").trim().toLowerCase(),C=String(g&&g.signer&&g.signer.publicKeyPem?g.signer.publicKeyPem:"");if(!y||!P||!A||!C)throw new Error("Courier package missing payload/signature/hash/public key.");const w=await Mt(y,P,C),E=await Fj(pr(y))===A;if(!w||!E)throw new Error("Courier package failed verification and remains quarantined.");const N={entryId:`ledger-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,packageId:String(y.packageId||`package-${Date.now()}`),courierClass:Tu(y.courierClass||a),sender:String(y.sender||"sender-unset"),receiver:String(y.receiver||"receiver-unset"),status:"quarantined",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),handoffs:[{handoffId:`handoff-${Date.now()}`,at:new Date().toISOString(),actor:"import-station",action:"imported",detail:{sourceFile:b.name,artifactCount:Array.isArray(y.artifacts)?y.artifacts.length:0}}]};s(_=>[N,...Array.isArray(_)?_:[]].slice(0,500)),c(`Courier package ${N.packageId} quarantined pending receipt verification.`),x("")}catch(h){c(""),x(h&&h.message?h.message:String(h))}finally{f&&f.target&&(f.target.value="")}},d=f=>{const b=String(f||"");b&&(s(h=>Array.isArray(h)?h.map(g=>{if(String(g.entryId||"")!==b)return g;const y=new Date().toISOString();return{...g,status:"verified",updatedAt:y,handoffs:[...Array.isArray(g.handoffs)?g.handoffs:[],{handoffId:`handoff-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,at:y,actor:"receipt-station",action:"verified",detail:{}}].slice(-400)}}):h),c(`Receipt verified for ${b}.`),x(""))},m=f=>{const b=String(f||"");if(!b)return;const h=(Array.isArray(n)?n:[]).find(g=>String(g.entryId||"")===b);if(h){if(String(h.status||"")!=="verified"){x("Release blocked: verify receipt before quarantine release.");return}s(g=>Array.isArray(g)?g.map(y=>{if(String(y.entryId||"")!==b)return y;const P=new Date().toISOString();return{...y,status:"released",updatedAt:P,handoffs:[...Array.isArray(y.handoffs)?y.handoffs:[],{handoffId:`handoff-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,at:P,actor:"release-station",action:"released",detail:{}}].slice(-400)}}):g),c(`Released package ${h.packageId} from quarantine.`),x("")}};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[148] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"courier-transfer-center",className:"fixed inset-x-8 top-16 bottom-6 z-[149] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Offline Evidence Courier"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Quarantine-first courier transfer chain for restricted environment handoffs."})]}),e.jsx("button",{type:"button","data-testid":"courier-transfer-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"p-3 border-b border-white/10 flex items-center gap-2",children:[e.jsxs("select",{"data-testid":"courier-class-select",value:a,onChange:f=>o(Tu(f.target.value)),className:"rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-100",children:[e.jsx("option",{value:"standard",children:"standard"}),e.jsx("option",{value:"sensitive",children:"sensitive"}),e.jsx("option",{value:"sealed",children:"sealed"}),e.jsx("option",{value:"emergency",children:"emergency"})]}),e.jsxs("label",{className:"inline-flex items-center px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono uppercase tracking-[0.12em] text-cyan-100 cursor-pointer",children:["Import Courier Package",e.jsx("input",{type:"file","data-testid":"courier-import-input",className:"hidden",accept:".json,application/json",onChange:p})]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:e.jsx($j,{entries:n,onVerifyReceipt:d,onReleaseFromQuarantine:m})}),(l||u)&&e.jsxs("div",{className:"px-3 py-2 border-t border-white/10",children:[l&&e.jsx("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-[10px] font-mono text-emerald-100",children:l}),u&&e.jsx("div",{"data-testid":"courier-error",className:"mt-1 rounded border border-rose-300/40 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-100",children:u})]})]})]}):null}function zj({templates:t,selectedTemplateId:r,onSelectTemplate:n,onUpdateTemplates:s}){const a=Array.isArray(t)?t:[];return e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Drill Templates"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Scenario definitions for repeatable continuity exercises."})]}),e.jsx("div",{className:"space-y-1 max-h-60 overflow-auto pr-1",children:a.map(o=>e.jsxs("button",{type:"button","data-testid":`drill-template-${o.templateId}`,onClick:()=>{typeof n=="function"&&n(o.templateId)},className:`w-full text-left rounded border px-2 py-1.5 ${r===o.templateId?"border-cyan-300/35 bg-cyan-500/15":"border-white/10 bg-black/20"}`,children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:o.title}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:o.scenarioId})]},o.templateId))}),e.jsx("button",{type:"button","data-testid":"drill-template-add-btn",onClick:()=>{const o={templateId:`drill-custom-${Date.now()}`,scenarioId:"support_incident_export",title:"Custom Continuity Drill",expectedState:{exportCompleted:!0,trustState:"valid"},checklist:["run scenario","capture evidence","review deltas"]};typeof s=="function"&&s([o,...a].slice(0,40))},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Add Template"})]})}function Hj({score:t,runs:r}){const a=(Array.isArray(r)?r:[]).filter(o=>!o.passed).flatMap(o=>Array.isArray(o.deltas)?o.deltas.map(l=>({runId:o.runId,key:l.key,expected:l.expected,actual:l.actual})):[]);return e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Recovery Scorecard"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Readiness score and remediation tasks from failed drills."})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-2 text-[9px] font-mono",children:[e.jsxs("div",{className:"rounded border border-cyan-300/30 bg-cyan-500/10 px-2 py-1 text-cyan-100",children:["score ",t.score]}),e.jsxs("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-emerald-100",children:["passed ",t.passed]}),e.jsxs("div",{className:"rounded border border-rose-300/35 bg-rose-500/10 px-2 py-1 text-rose-100",children:["failed ",t.failed]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-2 py-1 text-slate-300",children:["total ",t.total]})]}),e.jsxs("div",{className:"max-h-56 overflow-auto pr-1 space-y-1.5",children:[a.map((o,l)=>e.jsxs("article",{className:"rounded border border-amber-300/35 bg-amber-500/10 px-2 py-1.5",children:[e.jsx("div",{className:"text-[9px] font-mono text-amber-100",children:o.key}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-300",children:["expected ",JSON.stringify(o.expected)]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-300",children:["actual ",JSON.stringify(o.actual)]})]},`${o.runId}-${o.key}-${l}`)),a.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No remediation tasks. Latest drill set is aligned."})]})]})}const vs=[{templateId:"drill-fleet-restore",scenarioId:"fleet_restore",title:"Fleet Restore Drill",expectedState:{fleetHealth:"healthy",restoredNodes:3,trustState:"valid"},checklist:["recover backup bundle","verify trust chain","confirm node telemetry"]},{templateId:"drill-appliance-replacement",scenarioId:"appliance_replacement",title:"Appliance Replacement Drill",expectedState:{provisioned:!0,trustState:"valid",policyProfile:"sealed"},checklist:["replace hardware","provision role","verify diagnostics"]},{templateId:"drill-policy-rollback",scenarioId:"regional_policy_rollback",title:"Regional Policy Rollback Drill",expectedState:{rollbackApplied:!0,incidentsOpen:0},checklist:["apply rollback","verify signatures","validate runtime status"]},{templateId:"drill-revoked-trust",scenarioId:"revoked_trust_relationship",title:"Revoked Trust Relationship Drill",expectedState:{revokedBlocked:!0,alertsRaised:1},checklist:["present revoked certificate","confirm trust path invalidated","capture incident evidence"]}],Mu="neuralshell_continuity_templates_v1",Du="neuralshell_continuity_schedules_v1",$u="neuralshell_continuity_runs_v1";function Qi(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function el(t,r){typeof window>"u"||!window.localStorage||window.localStorage.setItem(t,JSON.stringify(r))}function Wj(t,r){const n=t&&typeof t=="object"?t:{},s=r&&typeof r=="object"?r:{};return Array.from(new Set([...Object.keys(n),...Object.keys(s)])).sort().map(o=>({key:o,expected:n[o],actual:s[o]})).filter(o=>JSON.stringify(o.expected)!==JSON.stringify(o.actual))}function Kj(t){const r=Array.isArray(t)?t:[];if(!r.length)return{score:0,passed:0,failed:0,total:0};const n=r.filter(s=>s&&s.passed).length;return{score:Math.round(n/r.length*100),passed:n,failed:r.length-n,total:r.length}}function Vj({open:t,onClose:r}){const[n,s]=i.useState(()=>{const C=Qi(Mu,vs);return Array.isArray(C)&&C.length?C:vs}),[a,o]=i.useState(()=>{const C=Array.isArray(vs)&&vs.length?vs[0]:null;return C?C.templateId:""}),[l,c]=i.useState(""),[u,x]=i.useState(()=>{const C=Qi(Du,[]);return Array.isArray(C)?C:[]}),[p,d]=i.useState(()=>{const C=Qi($u,[]);return Array.isArray(C)?C:[]}),[m,f]=i.useState(!1),[b,h]=i.useState("");i.useEffect(()=>{el(Mu,n)},[n]),i.useEffect(()=>{el(Du,u)},[u]),i.useEffect(()=>{el($u,p)},[p]);const g=i.useMemo(()=>(Array.isArray(n)?n:[]).find(C=>C.templateId===a)||null,[a,n]),y=i.useMemo(()=>Kj(p),[p]),P=()=>{if(!g)return;const C=g.expectedState&&typeof g.expectedState=="object"?g.expectedState:{};let w={...C};if(m){const S=Object.keys(C)[0]||"unexpectedState";w[S]=C[S]===!0?!1:`mismatch-${Date.now()}`}const j=Wj(C,w),E=new Date().toISOString(),N={runId:`drill-run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,templateId:g.templateId,title:g.title,startedAt:E,finishedAt:E,passed:j.length===0,expectedState:C,actualState:w,deltas:j,evidence:{artifactId:`drill-evidence-${Date.now()}`,generatedAt:E,summary:j.length===0?"Drill passed expected recovery state.":`Drill failed with ${j.length} delta(s).`,attachablePacks:["audit","support","board"]}};d(_=>[N,...Array.isArray(_)?_:[]].slice(0,300)),h(`Drill ${N.passed?"passed":"failed"}: ${N.title}`)},A=()=>{!g||!l||(x(C=>[{scheduleId:`schedule-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,templateId:g.templateId,title:g.title,scheduledAt:l,status:"scheduled"},...Array.isArray(C)?C:[]].slice(0,200)),h(`Scheduled ${g.title} for ${new Date(l).toLocaleString()}.`),c(""))};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[150] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"continuity-drill-center",className:"fixed inset-x-8 top-16 bottom-6 z-[151] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Continuity Drill Center"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Schedule and run repeatable recovery drills with evidence bundles and scorecard output."})]}),e.jsx("button",{type:"button","data-testid":"continuity-drill-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"p-3 border-b border-white/10 flex items-center gap-2",children:[e.jsx("input",{type:"datetime-local","data-testid":"continuity-schedule-input",value:l,onChange:C=>c(C.target.value),className:"rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-100"}),e.jsx("button",{type:"button","data-testid":"continuity-schedule-btn",onClick:A,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Schedule Drill"}),e.jsxs("label",{className:"inline-flex items-center gap-1 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox","data-testid":"continuity-simulate-failure",checked:m,onChange:C=>f(!!C.target.checked)}),"simulate failure"]}),e.jsx("button",{type:"button","data-testid":"continuity-run-btn",onClick:P,className:"px-2.5 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Run Drill"}),e.jsx("button",{type:"button","data-testid":"continuity-export-evidence-btn",onClick:()=>{const C=Array.isArray(p)&&p.length?p[0]:null;C&&je(`neuralshell_continuity_evidence_${C.runId}.json`,C)},className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Export Evidence"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.95fr_1.05fr] gap-3 p-3 overflow-auto",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(zj,{templates:n,selectedTemplateId:a,onSelectTemplate:o,onUpdateTemplates:s}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-1",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Scheduled Drills"}),e.jsxs("div",{className:"max-h-44 overflow-auto pr-1 space-y-1",children:[(Array.isArray(u)?u:[]).map(C=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/20 px-2 py-1 text-[9px] font-mono text-slate-300",children:[C.title," · ",new Date(C.scheduledAt).toLocaleString()]},C.scheduleId)),(Array.isArray(u)?u:[]).length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No drills scheduled."})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Hj,{score:y,runs:p}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-1",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Drill Runs"}),e.jsxs("div",{className:"max-h-48 overflow-auto pr-1 space-y-1.5",children:[(Array.isArray(p)?p:[]).map(C=>e.jsxs("article",{className:`rounded border px-2 py-1.5 ${C.passed?"border-emerald-300/30 bg-emerald-500/10":"border-rose-300/35 bg-rose-500/10"}`,children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:C.title}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:[C.passed?"passed":"failed"," · ",C.evidence.artifactId]})]},C.runId)),(Array.isArray(p)?p:[]).length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No drill runs yet."})]})]})]})]}),b&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-cyan-100 bg-cyan-500/10",children:b})]})]}):null}const Lu="neuralshell_procurement_pack_history_v1";function Gj(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function Jj(t,r){typeof window>"u"||!window.localStorage||window.localStorage.setItem(t,JSON.stringify(r))}function qj(t){const r=new Date(String(t||"")).getTime();return Number.isFinite(r)?Math.floor((Date.now()-r)/(24*60*60*1e3)):999}function Yj({open:t,onClose:r}){const[n,s]=i.useState("Institutional Buyer"),[a,o]=i.useState("security-ops"),[l,c]=i.useState("2.1.29"),[u,x]=i.useState("2.1.28"),[p,d]=i.useState(()=>{const h=Gj(Lu,[]);return Array.isArray(h)?h:[]}),[m,f]=i.useState("");i.useEffect(()=>{Jj(Lu,p)},[p]);const b=()=>{const h=new Date().toISOString(),g={generatedAt:h,organization:n,reviewOwner:a,currentVersion:l,previousVersion:u,securityQuestionnaire:{deploymentModel:"local-first + air-gapped capable",trustIdentity:"local CA + certificate lifecycle + revocation",evidenceMovement:"offline courier chain with quarantine/release",continuityDiscipline:"scheduled drill engine + scorecard evidence"},architectureOnePager:{runtime:"local command runtime",modules:["airgap","pki","appliance","courier","continuity","procurement","simulation","institutional_console"],policy:"verification-first activation and explicit trust controls"},dataFlowDeclaration:{inbound:"signed artifact ingestion at import station",outbound:"signed courier transfer with ledger handoffs",cloudDependency:"not required for core operations"},artifactInventory:["airgap_bundle.signed.json","courier_package.signed.json","trust_chain_view.json","continuity_evidence_bundle.json","procurement_pack_manifest.json"],compliancePostureSummary:{localFirst:!0,airGapReady:!0,revocationEnforced:!0,continuityDrillsEnabled:!0},procurementFAQ:[{question:"Does operation require cloud connectivity?",answer:"No. Critical operations run local-first and support sealed environments."},{question:"How are trust identities governed?",answer:"Certificates are issued/rotated/revoked under local CA control."}],deltaSinceLastReview:{previousVersion:u,currentVersion:l,summary:`Review delta from ${u} to ${l} includes air-gap, PKI, appliance, courier, continuity, and institutional console surfaces.`}};je(`neuralshell_security_review_pack_${l}.json`,g),$s(`neuralshell_procurement_faq_${l}.md`,[`# Procurement FAQ (${l})`,"",...g.procurementFAQ.map(y=>`Q: ${y.question} +*Generated by ProofForge Forensic Engine*`,n}async function Z1(t){var r,n,s;return(n=(r=window.api)==null?void 0:r.state)!=null&&n.getProfileTrustReport?window.api.state.getProfileTrustReport(t):(s=window.api)!=null&&s.invoke?window.api.invoke("state:getProfileTrustReport",t):null}async function X1(){var t,r,n,s;if(!((r=(t=window.api)==null?void 0:t.settings)!=null&&r.get))return"";try{const a=await window.api.settings.get();return String((a==null?void 0:a.activeProfileId)||((s=(n=a==null?void 0:a.connectionProfiles)==null?void 0:n[0])==null?void 0:s.id)||"").trim()}catch{return""}}function Q1(t){const r=String(t||"UNKNOWN").toUpperCase();return r==="VERIFIED"?"text-emerald-200 border-emerald-400/30 bg-emerald-500/10":r==="DRIFTED"||r==="NEEDS_REVIEW"?"text-amber-200 border-amber-400/30 bg-amber-500/10":r==="SIGNATURE_TAMPERED"||r==="INVALID"?"text-rose-200 border-rose-400/30 bg-rose-500/10":r==="OFFLINE_LOCKED"?"text-cyan-200 border-cyan-400/30 bg-cyan-500/10":"text-slate-200 border-white/10 bg-black/20"}function ev({open:t,onClose:r,profileId:n}){var f;const[s,a]=i.useState(null),[o,c]=i.useState(!1),[l,u]=i.useState("");i.useEffect(()=>{if(!t)return;let b=!1;return(async()=>{c(!0);try{const h=String(n||"").trim()||await X1();if(b)return;if(u(h),!h){a(null);return}const g=await Z1(h);b||a(g)}catch{b||a(null)}finally{b||c(!1)}})(),()=>{b=!0}},[t,n]);const x=i.useCallback(async()=>{var b,h;s&&(je(`trust-report-${l||"profile"}.json`,s),l&&((h=(b=window.api)==null?void 0:b.state)!=null&&h.logProfileEvent)&&await window.api.state.logProfileEvent(l,"REPORT_EXPORTED","Forensic trust report exported as JSON."),ge("Trust report JSON downloaded","success"))},[s,l]),p=i.useCallback(async()=>{var b,h;s&&($s(`trust-report-${l||"profile"}.md`,Y1(s)),l&&((h=(b=window.api)==null?void 0:b.state)!=null&&h.logProfileEvent)&&await window.api.state.logProfileEvent(l,"REPORT_EXPORTED","Forensic trust report exported as Markdown."),ge("Trust report Markdown downloaded","success"))},[s,l]);if(!t)return null;const d=s==null?void 0:s.metadata,m=((f=s==null?void 0:s.forensics)==null?void 0:f.history)||[];return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[124] bg-black/50",onClick:r}),e.jsxs("aside",{"data-testid":"trust-report-drawer","aria-label":"Profile trust report",className:"fixed left-4 top-16 bottom-4 z-[125] w-[min(520px,calc(100vw-2rem))] rounded-2xl border border-violet-300/25 bg-slate-950 shadow-[0_18px_80px_rgba(0,0,0,0.7)] flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] uppercase tracking-[0.16em] text-violet-300 font-bold",children:[e.jsx(Gx,{size:14}),"Trust Report"]}),e.jsx("button",{type:"button","data-testid":"trust-report-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10","aria-label":"Close trust report",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-4 space-y-4",children:[o&&e.jsx("div",{className:"text-[11px] font-mono text-slate-500",children:"Loading forensic report…"}),!o&&!d&&e.jsx("div",{"data-testid":"trust-report-empty",className:"text-[11px] font-mono text-slate-500",children:"No active bridge profile found. Configure a provider in Settings first."}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:`rounded-xl border p-3 space-y-1.5 ${Q1(d.trustState)}`,children:[e.jsx("div",{className:"text-[13px] font-semibold",children:d.name||d.id}),e.jsxs("div",{className:"text-[10px] font-mono uppercase tracking-[0.12em] opacity-90",children:[d.trustState," · ",d.provider," · ",d.secretCustody]}),e.jsx("div",{className:"text-[10px] font-mono text-slate-400 break-all",children:d.baseUrl}),d.fingerprint&&e.jsxs("div",{className:"text-[9px] font-mono opacity-70 break-all",children:["FP: ",d.fingerprint]})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-500 font-bold",children:"Forensic history"}),m.length===0?e.jsx("div",{className:"text-[11px] font-mono text-slate-600",children:"No events recorded yet."}):m.map(b=>e.jsxs("article",{className:"rounded-lg border border-white/8 bg-black/20 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[9px] font-mono uppercase tracking-wider text-slate-500",children:[e.jsx("span",{children:new Date(b.ts).toLocaleString()}),e.jsx("span",{className:"text-violet-300",children:b.type})]}),e.jsx("div",{className:"text-[11px] text-slate-300 mt-1",children:b.summary})]},b.id||`${b.ts}-${b.type}`))]})]})]}),d&&e.jsxs("div",{className:"px-4 py-3 border-t border-white/10 flex flex-wrap gap-2",children:[e.jsxs("button",{type:"button","data-testid":"trust-report-export-json-btn",onClick:x,className:"inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border border-white/15 bg-black/25 text-[9px] font-mono uppercase tracking-[0.12em] text-slate-200",children:[e.jsx(pl,{size:12}),"Export JSON"]}),e.jsxs("button",{type:"button","data-testid":"trust-report-export-md-btn",onClick:p,className:"inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border border-white/15 bg-black/25 text-[9px] font-mono uppercase tracking-[0.12em] text-slate-200",children:[e.jsx(pl,{size:12}),"Export Markdown"]})]})]})]})}function tv({open:t,steps:r=[],progress:n={},busyStepId:s="",onRunStep:a,onSkipStep:o,onClose:c,onFinish:l}){if(!t)return null;const u=Array.isArray(r)?r:[],x=u.filter(d=>!!n[String(d.id||"")]).length,p=x>=u.length&&u.length>0;return e.jsx("div",{className:"fixed inset-0 z-[140] bg-black/70 flex items-center justify-center p-5",children:e.jsxs("section",{"data-testid":"firstboot-authority-wizard","aria-label":"First Boot Authority Wizard",className:"w-full max-w-5xl rounded-2xl border border-cyan-300/25 bg-slate-950 p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.18em] text-cyan-300 font-bold",children:"First-Boot Authority Funnel"}),e.jsxs("div",{className:"text-[11px] text-slate-400 font-mono",children:[x,"/",u.length," complete"]}),e.jsx("p",{className:"mt-2 text-[11px] font-mono text-slate-500 leading-relaxed",children:"Finish authority setup now, or start using the app and return from Mission Control anytime."})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("button",{type:"button","data-testid":"firstboot-skip-now-btn",onClick:c,className:"px-3 py-2 rounded-lg border border-emerald-400/35 bg-emerald-500/15 text-[10px] font-mono uppercase tracking-[0.12em] font-bold text-emerald-100 hover:bg-emerald-500/25 transition-colors",children:"Start using app"}),e.jsx("button",{type:"button","data-testid":"firstboot-close-btn",onClick:c,"aria-label":"Close first-boot wizard",className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]})]}),e.jsx("div",{className:"space-y-2 max-h-[56vh] overflow-auto pr-1",children:u.map((d,m)=>{const f=String(d.id||""),b=!!n[f],h=s===f,g=!!d.critical;return e.jsxs("article",{"data-testid":`firstboot-step-${f}`,className:`rounded-xl border px-4 py-3 flex items-center justify-between gap-3 ${b?"border-emerald-300/30 bg-emerald-500/10":g?"border-cyan-300/30 bg-cyan-500/10":"border-white/10 bg-black/30"}`,children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-[0.14em] font-bold text-slate-100",children:[m+1,". ",String(d.title||f)]}),e.jsx("div",{className:"text-[10px] font-mono text-slate-400",children:String(d.description||"")}),g?e.jsx("div",{className:"text-[9px] font-mono text-amber-300 mt-1",children:"Security-critical step"}):null]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!g&&!b?e.jsx("button",{type:"button","data-testid":`firstboot-skip-${f}`,onClick:()=>o(f),className:"px-2.5 py-1.5 rounded border border-white/10 bg-white/5 text-[9px] font-mono uppercase tracking-[0.12em] text-slate-200 hover:bg-white/10",children:"Skip"}):null,e.jsx("button",{type:"button","data-testid":`firstboot-run-${f}`,disabled:b||h,onClick:()=>a(f),className:`px-3 py-1.5 rounded border text-[9px] font-mono uppercase tracking-[0.12em] ${b?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100 hover:bg-cyan-500/20"} disabled:opacity-60`,children:b?"Done":h?"Running":"Run"})]})]},f)})}),e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Completion summary is stored locally. Reopen from Mission Control → First Boot when ready."}),e.jsx("button",{type:"button","data-testid":"firstboot-finish-btn",onClick:l,className:`px-3 py-2 rounded border text-[10px] uppercase tracking-[0.14em] font-bold ${p?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":"border-white/10 bg-white/5 text-slate-400 hover:bg-white/10 hover:text-slate-200"}`,children:p?"Open Mission Control":"Continue setup later"})]})]})})}function rv({snapshots:t=[],onCapture:r,onRestore:n,onCompare:s,activeSnapshotId:a=""}){const[o,c]=i.useState(""),l=Array.isArray(t)?t:[];return e.jsxs("section",{"data-testid":"snapshot-manager",className:"rounded-2xl border border-white/10 bg-black/30 p-3 space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between gap-2",children:e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"State Snapshots"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Capture, restore, and compare runtime state safely."})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{"data-testid":"snapshot-name-input",value:o,onChange:u=>c(u.target.value),placeholder:"Snapshot name",className:"flex-1 rounded border border-white/10 bg-black/40 px-2 py-1 text-[10px] font-mono text-slate-200"}),e.jsx("button",{type:"button","data-testid":"snapshot-capture-btn",onClick:()=>{const u=String(o||"").trim()||`Snapshot ${new Date().toLocaleTimeString()}`;r(u),c("")},className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 hover:bg-cyan-500/20",children:"Capture"})]}),e.jsxs("div",{className:"max-h-56 overflow-auto space-y-1.5 pr-1",children:[l.map(u=>e.jsx("article",{className:`rounded-lg border px-2 py-1.5 ${String(u.id||"")===String(a||"")?"border-cyan-300/30 bg-cyan-500/10":"border-white/10 bg-black/20"}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-200",children:String(u.name||u.id)}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:String(u.createdAt||"")})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{type:"button","data-testid":`snapshot-restore-${u.id}`,onClick:()=>n(u.id),className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Restore"}),e.jsx("button",{type:"button","data-testid":`snapshot-compare-${u.id}`,onClick:()=>s(u.id),className:"px-2 py-1 rounded border border-white/10 bg-white/5 text-[9px] font-mono uppercase tracking-[0.12em] text-slate-200",children:"Compare"})]})]})},u.id)),l.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No snapshots captured yet."})]})]})}function ya(t){return JSON.stringify(t||{},null,2)}function nv({paneId:t,payload:r}){const n=String(t||"runtime_snapshots");return n==="proof_stdout"?e.jsxs("section",{"data-testid":"result-pane-proof",className:"rounded-2xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold mb-2",children:"Proof Stdout"}),e.jsx("pre",{className:"text-[10px] font-mono text-slate-200 whitespace-pre-wrap",children:String(r&&r.text?r.text:"No proof output yet.")})]}):n==="watchdog_alerts"?e.jsxs("section",{"data-testid":"result-pane-watchdog",className:"rounded-2xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-amber-300 font-bold mb-2",children:"Watchdog Alerts"}),e.jsx("pre",{className:"text-[10px] font-mono text-slate-200 whitespace-pre-wrap",children:ya(r)})]}):n==="release_health"?e.jsxs("section",{"data-testid":"result-pane-release-health",className:"rounded-2xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold mb-2",children:"Release Health"}),e.jsx("pre",{className:"text-[10px] font-mono text-slate-200 whitespace-pre-wrap",children:ya(r)})]}):n==="snapshot_compare"?e.jsxs("section",{"data-testid":"result-pane-snapshot-compare",className:"rounded-2xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-blue-300 font-bold mb-2",children:"Snapshot Compare"}),e.jsx("pre",{className:"text-[10px] font-mono text-slate-200 whitespace-pre-wrap",children:ya(r)})]}):e.jsxs("section",{"data-testid":"result-pane-default",className:"rounded-2xl border border-white/10 bg-black/30 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold mb-2",children:"Runtime Snapshots"}),e.jsx("pre",{className:"text-[10px] font-mono text-slate-200 whitespace-pre-wrap",children:ya(r)})]})}function Rl(t){if(t==null)return t;if(typeof t=="string"){const r=t.toLowerCase();return r.includes("token")||r.includes("secret")||r.includes("passphrase")?"[redacted]":t}if(Array.isArray(t))return t.map(r=>Rl(r));if(typeof t=="object"){const r={};return Object.entries(t).forEach(([n,s])=>{const a=String(n||"").toLowerCase();a.includes("token")||a.includes("secret")||a.includes("password")||a.includes("passphrase")?r[n]="[redacted]":r[n]=Rl(s)}),r}return t}function sv(t,r){return{id:`snap-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,name:String(t||`Snapshot ${new Date().toLocaleTimeString()}`),createdAt:new Date().toISOString(),payload:Rl(r)}}function av(t,r){if(!t||!r)return[];const n=t&&t.payload&&typeof t.payload=="object"?t.payload:{},s=r&&r.payload&&typeof r.payload=="object"?r.payload:{};return Array.from(new Set([...Object.keys(n),...Object.keys(s)])).sort().map(o=>({key:o,before:n[o],after:s[o],changed:JSON.stringify(n[o])!==JSON.stringify(s[o])})).filter(o=>o.changed)}function ov(t){return t?t.payload:null}const J0="neuralshell_runtime_snapshots_v1";function iv(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(J0)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function lv(t){typeof window>"u"||!window.localStorage||window.localStorage.setItem(J0,JSON.stringify((Array.isArray(t)?t:[]).slice(-120)))}function cv({open:t,onClose:r,runtimeState:n,onRestoreSnapshotPayload:s,alerts:a=[],proofStdout:o="",releaseHealth:c={}}){const[l,u]=i.useState("runtime_snapshots"),[x,p]=i.useState({}),[d,m]=i.useState(()=>iv()),[f,b]=i.useState("");i.useEffect(()=>{lv(d)},[d]);const h=i.useCallback(I=>{const A=n&&typeof n=="object"?n:{},C=sv(I,{provider:String(A.providerHealth&&A.providerHealth.activeProvider?A.providerHealth.activeProvider:"ollama"),model:String(A.providerHealth&&A.providerHealth.model?A.providerHealth.model:"llama3"),vaultLocked:!!(A.vaultState&&A.vaultState.locked),policyProfile:String(A.policyState&&A.policyState.activePolicyProfile?A.policyState.activePolicyProfile:"none"),proofStatus:String(A.proofEngine&&A.proofEngine.lastProofStatus?A.proofEngine.lastProofStatus:"idle"),activePanels:[String(l||"runtime_snapshots")],collabRoom:String(A.collabVoiceState&&A.collabVoiceState.currentRoom?A.collabVoiceState.currentRoom:"default"),collabPeers:Number(A.collabVoiceState&&A.collabVoiceState.peersActive?A.collabVoiceState.peersActive:0),selectedCards:["provider","vault","proof","policy","watchdog"]});return m(w=>[...w,C].slice(-120)),b(String(C.id||"")),u("runtime_snapshots"),p(C),X("runtime.snapshot.captured",{snapshotId:C.id,name:C.name},{source:"snapshots",severity:"info"}),C},[l,n]),g=i.useCallback(I=>{const A=(d||[]).find(w=>String(w.id||"")===String(I||""));if(!A)return;const C=ov(A);b(String(A.id||"")),typeof s=="function"&&s(C),u("runtime_snapshots"),p(A),X("runtime.snapshot.restored",{snapshotId:A.id,name:A.name},{source:"snapshots",severity:"info"})},[s,d]),y=i.useCallback(I=>{const A=(d||[]).find(j=>String(j.id||"")===String(f||"")),C=(d||[]).find(j=>String(j.id||"")===String(I||""));if(!C)return;const w=av(A||null,C||null);u("snapshot_compare"),p({from:A?A.name:"current-runtime",to:C.name,rows:w}),X("runtime.snapshot.compared",{from:A?A.id:"current-runtime",to:C.id,changedFields:w.length},{source:"snapshots",severity:"info"})},[f,d]);return i.useEffect(()=>{t&&(l==="watchdog_alerts"?p(a):l==="proof_stdout"?p({text:o||""}):l==="release_health"&&p(c||{}))},[a,t,o,c,l]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[126] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"split-workspace",className:"fixed inset-x-6 top-18 bottom-6 z-[127] rounded-2xl border border-blue-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.7)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-blue-300 font-bold",children:"Live Split Workspace"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Left: command deck · Center: workflow context · Right: result pane + snapshots."})]}),e.jsx("button",{type:"button","data-testid":"split-workspace-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[250px_1fr_380px]",children:[e.jsxs("aside",{className:"border-r border-white/10 p-3 space-y-2 bg-black/25",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Command Deck"}),e.jsx("button",{type:"button","data-testid":"split-pane-proof-btn",onClick:()=>u("proof_stdout"),className:"w-full text-left px-2.5 py-2 rounded border border-white/10 bg-black/20 text-[10px] font-mono text-slate-200 hover:bg-white/10",children:"Proof Stdout"}),e.jsx("button",{type:"button","data-testid":"split-pane-watchdog-btn",onClick:()=>u("watchdog_alerts"),className:"w-full text-left px-2.5 py-2 rounded border border-white/10 bg-black/20 text-[10px] font-mono text-slate-200 hover:bg-white/10",children:"Watchdog Alerts"}),e.jsx("button",{type:"button","data-testid":"split-pane-release-btn",onClick:()=>u("release_health"),className:"w-full text-left px-2.5 py-2 rounded border border-white/10 bg-black/20 text-[10px] font-mono text-slate-200 hover:bg-white/10",children:"Release Health"}),e.jsx("button",{type:"button","data-testid":"split-pane-snapshots-btn",onClick:()=>u("runtime_snapshots"),className:"w-full text-left px-2.5 py-2 rounded border border-white/10 bg-black/20 text-[10px] font-mono text-slate-200 hover:bg-white/10",children:"Runtime Snapshots"})]}),e.jsx("main",{className:"p-3 overflow-auto space-y-3",children:e.jsxs("section",{className:"rounded-2xl border border-white/10 bg-black/25 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Primary Workflow Context"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-2 text-[10px] font-mono",children:[e.jsxs("div",{className:"rounded border border-white/10 bg-black/25 px-2 py-1.5",children:[e.jsx("div",{className:"text-slate-500",children:"Provider"}),e.jsx("div",{className:"text-slate-100",children:String(n&&n.providerHealth&&n.providerHealth.activeProvider?n.providerHealth.activeProvider:"ollama")})]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/25 px-2 py-1.5",children:[e.jsx("div",{className:"text-slate-500",children:"Model"}),e.jsx("div",{className:"text-slate-100",children:String(n&&n.providerHealth&&n.providerHealth.model?n.providerHealth.model:"llama3")})]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/25 px-2 py-1.5",children:[e.jsx("div",{className:"text-slate-500",children:"Policy"}),e.jsx("div",{className:"text-slate-100",children:String(n&&n.policyState&&n.policyState.activePolicyProfile?n.policyState.activePolicyProfile:"none")})]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/25 px-2 py-1.5",children:[e.jsx("div",{className:"text-slate-500",children:"Proof Status"}),e.jsx("div",{className:"text-slate-100",children:String(n&&n.proofEngine&&n.proofEngine.lastProofStatus?n.proofEngine.lastProofStatus:"idle")})]})]})]})}),e.jsxs("aside",{className:"border-l border-white/10 p-3 overflow-auto space-y-3 bg-black/20",children:[e.jsx(nv,{paneId:l,payload:x}),e.jsx(rv,{snapshots:d,activeSnapshotId:f,onCapture:h,onRestore:g,onCompare:y})]})]})]})]}):null}const dv="neuralshell_readiness_checklist_v1",uv="neuralshell_nodechain_mission_schedules_v1";function du(){typeof window>"u"||!window.localStorage||window.localStorage.setItem(dv,"1")}function Wi({label:t,detail:r,done:n,running:s,onRun:a,testId:o}){return e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 px-4 py-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] font-semibold text-slate-100",children:t}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500 mt-0.5",children:r})]}),e.jsx("button",{type:"button","data-testid":o,"aria-label":`Run ${t}`,disabled:n||s,onClick:a,className:`px-3 py-1.5 rounded-lg border text-[9px] font-mono uppercase tracking-[0.14em] ${n?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100 hover:bg-cyan-500/20"} disabled:opacity-60`,children:n?"Done":s?"Running…":"Run"})]})}i.memo(function({open:r,onClose:n,onOpenSettings:s,rgbEnabled:a=!1,onToggleRgb:o,workflowId:c="global"}){const[l,u]=i.useState(""),[x,p]=i.useState(!1),[d,m]=i.useState(!1),[f,b]=i.useState(()=>!!a),h=i.useRef(null);if(Wa(r,h,n),i.useEffect(()=>{b(!!a)},[a]),i.useEffect(()=>{if(!r)return;let C=!1;return(async()=>{if(window.api&&window.api.system&&typeof window.api.system.healthHistory=="function")try{const w=await window.api.system.healthHistory(),j=Array.isArray(w&&w.entries)?w.entries:[];!C&&j.length>0&&p(!!(j[0]&&j[0].ok))}catch{}if(window.api&&window.api.bridge&&typeof window.api.bridge.get=="function")try{const w=await window.api.bridge.get();!C&&w&&w.ok===!0&&m(!0)}catch{}})(),()=>{C=!0}},[r]),!r)return null;const g=x&&d&&(f||!o),y=async()=>{if(window.api&&window.api.system&&typeof window.api.system.runHealthCheck=="function"){u("health");try{const C=await window.api.system.runHealthCheck(),w=!!(C&&C.ok);p(w),w||window.dispatchEvent(new CustomEvent("neuralshell:toast",{detail:{message:"Health check found issues — review Settings",tone:"warning"}}))}finally{u("")}}},I=async()=>{if(!(window.api&&window.api.bridge&&typeof window.api.bridge.test=="function")){typeof s=="function"&&s();return}u("bridge");try{const C=await window.api.bridge.get(),w=Array.isArray(C&&C.profiles)?C.profiles:[],j=w.find(_=>String(_.id)===String(C.activeProfileId))||w[0]||null;if(!j){typeof s=="function"&&s();return}const E=await window.api.bridge.test(j),N=!!(E&&E.ok);m(N),N||window.dispatchEvent(new CustomEvent("neuralshell:toast",{detail:{message:"Bridge test failed — open Settings to fix",tone:"error"}}))}finally{u("")}},A=()=>{du();const C=(Array.isArray(Fa)?Fa:[]).find(w=>w.id==="getting_started");C&&zp(C,c||"global"),typeof n=="function"&&n(),window.dispatchEvent(new CustomEvent("neuralshell:toast",{detail:{message:"ProofForge is ready — Workpad starter note added",tone:"success"}}))};return e.jsx("div",{className:"fixed inset-0 z-[145] bg-black/70 backdrop-blur-sm flex items-center justify-center p-5",onClick:n,children:e.jsxs("section",{ref:h,"data-testid":"readiness-checklist-modal",role:"dialog","aria-modal":"true","aria-label":"ProofForge readiness checklist",className:"w-full max-w-lg rounded-2xl border border-emerald-300/25 bg-slate-950 p-5 shadow-[0_20px_90px_rgba(0,0,0,0.75)]",onClick:C=>C.stopPropagation(),children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.18em] text-emerald-300 font-bold",children:"ProofForge is ready"}),e.jsx("div",{className:"text-[12px] text-slate-300 mt-1",children:"Quick checklist before your first session."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Wi,{label:"System health check",detail:"Network, bridge, vault, runtime",done:x,running:l==="health",onRun:y,testId:"readiness-checklist-run-health-btn"}),e.jsx(Wi,{label:"Bridge connection test",detail:"Verify your active LLM provider",done:d,running:l==="bridge",onRun:I,testId:"readiness-checklist-run-bridge-btn"}),typeof o=="function"&&e.jsx(Wi,{label:"RGB mood sync (optional)",detail:"Sync lighting to assistant mood",done:f,running:l==="rgb",onRun:async()=>{u("rgb");try{await Promise.resolve(o(!0)),b(!0)}finally{u("")}}})]}),e.jsxs("div",{className:"mt-5 flex items-center justify-between gap-3",children:[e.jsx("button",{type:"button","data-testid":"readiness-checklist-skip-btn",onClick:()=>{du(),typeof n=="function"&&n()},className:"px-3 py-2 rounded-lg border border-white/10 text-[10px] font-mono uppercase tracking-[0.14em] text-slate-400 hover:text-slate-200",children:"Skip for now"}),e.jsx("button",{type:"button","data-testid":"readiness-checklist-finish-btn",onClick:A,className:`px-4 py-2 rounded-lg border text-[10px] font-mono uppercase tracking-[0.14em] font-bold ${g?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100"}`,children:g?"Start working":"Continue anyway"})]})]})})});async function pv(){var t,r;if((r=(t=window.api)==null?void 0:t.workspace)!=null&&r.getActive)try{const n=await window.api.workspace.getActive();if(n!=null&&n.path)return String(n.path)}catch{}return""}function mv(t){const r=String(t||""),n=r.lastIndexOf(":");return n<=0?{workspacePath:"",actionId:r}:{workspacePath:r.slice(0,n),actionId:r.slice(n+1)}}function xv(t){const r=String(t).toLowerCase();return r==="high"?"border-rose-400/25 text-rose-200":r==="safe"?"border-emerald-400/25 text-emerald-200":"border-amber-400/25 text-amber-200"}const q0=[{id:"continue",label:"Approve & Run",tone:"good",primary:!0},{id:"cancel",label:"Cancel",tone:"bad"}];function fv({actionId:t,pending:r,busy:n,onChoice:s}){if(!r)return null;const a=r.request||{},o=Array.isArray(a.choices)&&a.choices.length?a.choices:q0;return e.jsxs("div",{"data-testid":`guided-action-approval-${t}`,className:"mt-2 rounded-lg border border-amber-400/25 bg-amber-500/10 p-2.5 space-y-2",children:[e.jsx("div",{className:"text-[10px] font-mono text-amber-100",children:String(a.message||"Operator approval required.")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(c=>e.jsx("button",{type:"button","data-testid":`guided-action-approve-${t}-${c.id}`,disabled:n,onClick:()=>s(t,c.id,r.mode),className:`px-2 py-1 rounded border text-[9px] font-mono uppercase tracking-wider disabled:opacity-50 ${c.tone==="bad"?"border-rose-400/30 text-rose-200 hover:bg-rose-500/10":c.primary?"border-emerald-400/30 text-emerald-100 bg-emerald-500/10 hover:bg-emerald-500/20":"border-white/15 text-slate-300 hover:bg-white/5"}`,children:c.label},c.id))})]})}function bv({workflowId:t,chatLog:r=[]}){const[n,s]=i.useState(""),[a,o]=i.useState([]),[c,l]=i.useState({}),[u,x]=i.useState(0),[p,d]=i.useState(!1),[m,f]=i.useState(""),[b,h]=i.useState(""),[g,y]=i.useState({}),[I,A]=i.useState(!1),C=i.useCallback(async()=>{var S,R,$,U;d(!0);try{const P=await pv();if(s(P),(R=(S=window.api)==null?void 0:S.action)!=null&&R.listRegistry){const F=await window.api.action.listRegistry(),J={};(Array.isArray(F)?F:[]).forEach(ee=>{ee!=null&&ee.id&&(J[ee.id]=ee)}),l(J)}if(!P||!((U=($=window.api)==null?void 0:$.project)!=null&&U.analyze)){o([]);return}const D=(Array.isArray(r)?r:[]).filter(F=>F&&!F._streaming).slice(-12).map(F=>({role:F.role,content:String(F.content||"").slice(0,500)})),z=await window.api.project.analyze(P,t,D);z!=null&&z.ok?(o(Array.isArray(z.rankedActions)?z.rankedActions:[]),x(Number(z.urgency)||0)):o([])}catch(P){ge((P==null?void 0:P.message)||"Failed to load guided actions","error")}finally{d(!1)}},[t,r]);i.useEffect(()=>{C()},[C]),i.useEffect(()=>{var R,$;if(!(($=(R=window.api)==null?void 0:R.action)!=null&&$.onLog))return;const S=window.api.action.onLog(U=>{if(!U)return;const P=`[${U.type||"log"}] ${String(U.message||U.msg||"").trim()}`;P.length>8&&h(P)});return typeof S=="function"?S:void 0},[]),i.useEffect(()=>{var R,$;if(!(($=(R=window.api)==null?void 0:R.action)!=null&&$.onInteraction))return;const S=window.api.action.onInteraction(U=>{if(!(U!=null&&U.actionId))return;const{actionId:P}=mv(U.actionId);y(D=>({...D,[P]:{mode:"interaction",fullActionId:U.actionId,workspacePath:U.workspacePath||"",request:U.request||{message:"Operator decision required."}}})),ge("Action waiting for operator decision","warning")});return typeof S=="function"?S:void 0},[]);const w=i.useCallback(S=>{y(R=>{if(!R[S])return R;const $={...R};return delete $[S],$})},[]),j=i.useCallback(async(S,R={})=>{var $,U;return(U=($=window.api)==null?void 0:$.action)!=null&&U.run?window.api.action.run(S,{rootPath:n||void 0,workflowId:t,...R}):null},[n,t]),E=i.useCallback(async S=>{var R,$,U,P;if(($=(R=window.api)==null?void 0:R.action)!=null&&$.run){f(S);try{const D=await j(S),z=String((D==null?void 0:D.status)||(D!=null&&D.ok?"succeeded":"failed"));if(z==="awaiting_input"){let F=null;if((P=(U=window.api)==null?void 0:U.action)!=null&&P.status){const J=await window.api.action.status(S,n||void 0);F=(J==null?void 0:J.interactionRequest)||null}y(J=>({...J,[S]:{mode:"policy",fullActionId:"",workspacePath:n,request:F||{type:"confirm",message:"Policy requires operator approval before this action can run.",choices:q0}}})),ge("Action needs operator approval","warning")}else(D==null?void 0:D.ok)!==!1&&z!=="failed"?(w(S),ge(`Action ${S} completed`,"success")):(w(S),ge((D==null?void 0:D.reason)||`Action ${S} failed`,"error"));await C()}catch(D){ge((D==null?void 0:D.message)||"Action run failed","error")}finally{f("")}}},[w,C,n,j]),N=i.useCallback(async(S,R,$)=>{var P,D,z,F;const U=g[S];if(U){f(S);try{if($==="policy"){const J=U.workspacePath||n;if((D=(P=window.api)==null?void 0:P.action)!=null&&D.cancel&&await window.api.action.cancel(S,J||void 0),R==="cancel"){w(S),ge("Action cancelled","info");return}const ee=await j(S,{forceAutoRun:!0,workspacePath:J}),ie=String((ee==null?void 0:ee.status)||(ee!=null&&ee.ok?"succeeded":"failed"));ie==="awaiting_input"?ge("Action still needs approval","warning"):(ee==null?void 0:ee.ok)!==!1&&ie!=="failed"?(w(S),ge(`Action ${S} completed`,"success")):(w(S),ge((ee==null?void 0:ee.reason)||`Action ${S} failed`,"error"))}else if((F=(z=window.api)==null?void 0:z.action)!=null&&F.respond){const J=U.fullActionId||S,ee=U.workspacePath||n,ie=await window.api.action.respond(J,{choiceId:R},ee||void 0);(ie==null?void 0:ie.ok)===!1?ge(ie.reason||"Failed to submit decision","error"):(w(S),ge("Decision recorded","success"))}await C()}catch(J){ge((J==null?void 0:J.message)||"Approval failed","error")}finally{f("")}}},[w,g,C,n,j]),_=i.useCallback(async()=>{var S,R,$,U,P,D;if(!((R=(S=window.api)==null?void 0:S.workspace)!=null&&R.pickRoot)){ge("Workspace picker unavailable","error");return}A(!0);try{const z=await window.api.workspace.pickRoot(),F=String((z==null?void 0:z.path)||(z==null?void 0:z.rootPath)||"").trim();if(!F)return;(U=($=window.api)==null?void 0:$.workspace)!=null&&U.register&&await window.api.workspace.register(F),(D=(P=window.api)==null?void 0:P.workspace)!=null&&D.setActive&&(z!=null&&z.id)&&await window.api.workspace.setActive(z.id),ge("Workspace registered","success"),await C()}catch(z){ge((z==null?void 0:z.message)||"Failed to pick workspace","error")}finally{A(!1)}},[C]);return e.jsxs("div",{className:"space-y-3","data-testid":"operator-inbox-actions-tab",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.18em] font-bold text-emerald-300",children:"Guided Actions"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500 truncate max-w-xs",title:n||"No workspace",children:n||"No active workspace"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[!n&&e.jsxs("button",{type:"button","data-testid":"guided-actions-pick-workspace-btn",disabled:I,onClick:_,className:"inline-flex items-center gap-1 px-2 py-1 rounded-lg border border-cyan-400/25 bg-cyan-500/10 text-[9px] font-mono uppercase text-cyan-100 hover:bg-cyan-500/20 disabled:opacity-50",children:[e.jsx(Jx,{size:11}),I?"Picking…":"Pick workspace"]}),e.jsxs("button",{type:"button","data-testid":"guided-actions-refresh-btn",onClick:C,disabled:p,className:"inline-flex items-center gap-1 px-2 py-1 rounded-lg border border-white/10 text-[9px] font-mono uppercase text-slate-400 hover:text-slate-200",children:[e.jsx(qx,{size:11,className:p?"animate-spin":""}),"Refresh"]})]})]}),u>0&&e.jsxs("div",{className:"rounded-lg border border-amber-400/20 bg-amber-500/10 px-3 py-2 text-[10px] font-mono text-amber-100",children:["Workspace urgency: ",e.jsx("span",{className:"font-bold",children:u})]}),b&&e.jsx("div",{className:"rounded-lg border border-white/8 bg-black/25 px-3 py-2 text-[9px] font-mono text-slate-400 truncate",title:b,children:b}),e.jsxs("div",{className:"space-y-2 max-h-[48vh] overflow-auto",children:[p&&a.length===0&&e.jsx("div",{className:"text-[11px] font-mono text-slate-500 py-6 text-center",children:"Analyzing workspace…"}),!p&&!n&&e.jsx("div",{"data-testid":"guided-actions-no-workspace",className:"text-center py-8 text-[11px] font-mono text-slate-500 border border-dashed border-cyan-400/20 rounded-xl",children:"Register a workspace root to rank guided actions."}),!p&&n&&a.length===0&&e.jsx("div",{"data-testid":"guided-actions-empty",className:"text-center py-8 text-[11px] font-mono text-slate-500 border border-dashed border-white/10 rounded-xl",children:"No ranked actions for this workspace yet."}),a.map(S=>{const R=c[S.id]||{},$=R.risk||"medium",U=m===S.id,P=g[S.id];return e.jsxs("article",{"data-testid":`guided-action-${S.id}`,className:"rounded-xl border border-white/10 bg-black/25 p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yx,{size:12,className:"text-emerald-400 shrink-0"}),e.jsx("span",{className:"text-[12px] font-semibold text-slate-100",children:S.label||R.label||S.id}),e.jsx("span",{className:`text-[8px] font-mono uppercase px-1.5 py-0.5 rounded border ${xv($)}`,children:$})]}),e.jsx("div",{className:"text-[10px] text-slate-500 mt-1",children:S.reason||R.description||""}),e.jsxs("p",{className:"text-[9px] font-mono text-emerald-400/80 mt-0.5",children:["score ",S.score??"—"]})]}),e.jsxs("button",{type:"button","data-testid":`guided-action-run-${S.id}`,disabled:!!m||!!P,onClick:()=>E(S.id),className:"inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg border border-emerald-400/30 bg-emerald-500/10 text-[9px] font-mono uppercase tracking-wider text-emerald-100 shrink-0 disabled:opacity-50",children:[e.jsx(Zx,{size:11}),U?"Running":P?"Awaiting":"Run"]})]}),e.jsx(fv,{actionId:S.id,pending:P,busy:U,onChoice:N})]},S.id)})]})]})}const hv=[{id:"ops",label:"Operations"},{id:"actions",label:"Actions"},{id:"workpad",label:"Workpad"},{id:"health",label:"Health"},{id:"missions",label:"Missions"}];function gv({active:t,label:r,badge:n,onClick:s,testId:a}){return e.jsxs("button",{type:"button","data-testid":a,onClick:s,className:`flex-1 px-2 py-2 rounded-xl border text-[9px] font-mono uppercase tracking-[0.12em] transition-all ${t?"border-violet-400/30 bg-violet-500/15 text-violet-100":"border-transparent text-slate-500 hover:text-slate-300 hover:bg-white/[0.03]"}`,children:[r,n>0?` (${n})`:""]})}function yv({workflowId:t,onOpenWorkpad:r}){const[n,s]=i.useState(()=>et(t));i.useEffect(()=>(Bp(t),s(et(t)),qa(s,t)),[t]);const a=i.useMemo(()=>eh(n),[n]),o=(n.tasks||[]).filter(c=>!c.done).slice(0,12);return e.jsxs("div",{className:"space-y-3","data-testid":"operator-inbox-workpad-tab",children:[e.jsx("div",{className:"grid grid-cols-4 gap-2",children:[{label:"Open",value:a.openTasks,tone:"text-amber-200"},{label:"Overdue",value:a.overdueTasks,tone:"text-rose-300"},{label:"Notes",value:a.notes,tone:"text-slate-200"},{label:"Pins",value:a.pins,tone:"text-violet-200"}].map(({label:c,value:l,tone:u})=>e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/25 px-2 py-1.5 text-center",children:[e.jsx("div",{className:`text-[14px] font-bold font-mono ${u}`,children:l}),e.jsx("div",{className:"text-[8px] uppercase tracking-wider text-slate-500",children:c})]},c))}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-500 truncate",children:["Scope: ",e.jsx("span",{className:"text-slate-300",children:Ga()})]}),typeof r=="function"&&e.jsx("button",{type:"button","data-testid":"operator-inbox-open-workpad-btn",onClick:r,className:"px-2.5 py-1 rounded-lg border border-amber-400/25 bg-amber-500/10 text-[9px] font-mono uppercase tracking-wider text-amber-100",children:"Open full Workpad"})]}),e.jsx("div",{className:"space-y-2 max-h-[42vh] overflow-auto",children:o.length===0?e.jsx("div",{"data-testid":"operator-inbox-workpad-empty",className:"text-center py-8 text-[11px] font-mono text-slate-500 border border-dashed border-white/10 rounded-xl",children:"No open Workpad tasks for this workflow."}):o.map(c=>{const l=_0(c.dueDate,c.done);return e.jsxs("div",{className:"flex items-start gap-2 rounded-xl border border-white/10 bg-black/25 px-3 py-2",children:[e.jsx("button",{type:"button","aria-label":c.done?"Mark incomplete":"Mark complete",onClick:()=>s(Zb(c.id,t)),className:`mt-0.5 h-4 w-4 rounded border flex items-center justify-center shrink-0 transition-colors ${c.done?"border-emerald-400/40 bg-emerald-500/20 text-emerald-200":"border-white/15 bg-black/30 hover:border-violet-400/30"}`,children:c.done&&e.jsx("svg",{className:"w-2.5 h-2.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2.5,children:e.jsx("path",{d:"M5 13l4 4L19 7"})})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[11px] text-slate-100",children:c.title}),c.dueDate&&e.jsx("span",{className:`inline-block mt-1 text-[8px] font-mono uppercase px-1.5 py-0.5 rounded border ${_w(l)}`,children:Cw(c.dueDate,c.done)})]})]},c.id)})})]})}function wv({onRunHealthCheck:t,bulkBusy:r,onEntriesChange:n}){const[s,a]=i.useState({entries:[]}),o=i.useCallback(async()=>{if(window.api&&window.api.system&&typeof window.api.system.healthHistory=="function")try{const l=await window.api.system.healthHistory();a(l&&typeof l=="object"?l:{entries:[]})}catch{a({entries:[]})}},[]);i.useEffect(()=>{o()},[o]);const c=Array.isArray(s.entries)?s.entries:[];return i.useEffect(()=>{typeof n=="function"&&n(c.length)},[c.length,n]),e.jsxs("div",{className:"space-y-3","data-testid":"operator-inbox-health-tab",children:[e.jsx("button",{type:"button","data-testid":"operator-inbox-run-health-btn",disabled:r,onClick:async()=>{typeof t=="function"&&await t(),await o()},className:"w-full px-3 py-2 rounded-xl border border-cyan-400/25 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-wider text-cyan-100 disabled:opacity-50",children:"Run health check now"}),e.jsx("div",{className:"space-y-2 max-h-[46vh] overflow-auto",children:c.length===0?e.jsx("div",{"data-testid":"operator-inbox-health-empty",className:"text-center py-8 text-[11px] font-mono text-slate-500 border border-dashed border-white/10 rounded-xl",children:"No health check history yet."}):c.map(l=>e.jsxs("div",{className:`rounded-xl border px-3 py-2.5 ${l.ok?"border-emerald-400/20 bg-emerald-500/5":"border-rose-400/20 bg-rose-500/5"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:`text-[10px] font-mono uppercase tracking-wider ${l.ok?"text-emerald-300":"text-rose-300"}`,children:l.ok?"Passed":"Issues found"}),e.jsx("span",{className:"text-[9px] font-mono text-slate-500",children:Nw(l.at)})]}),l.summary&&e.jsxs("div",{className:"text-[9px] font-mono text-slate-400 mt-1",children:[l.summary.passed,"/",l.summary.total," passed",l.summary.failed?` · ${l.summary.failed} failed`:"",l.summary.warning?` · ${l.summary.warning} warn`:""]})]},l.id))})]})}function vv(t){const r=Math.max(0,Math.floor(Number(t)||0)),n=Math.floor(r/3600),s=Math.floor(r%3600/60),a=r%60;return n>0?`${n}h ${String(s).padStart(2,"0")}m ${String(a).padStart(2,"0")}s`:`${s}m ${String(a).padStart(2,"0")}s`}function jv(t){if(!t)return"";const r=Date.now()-new Date(t).getTime();return!Number.isFinite(r)||r<0?"":r<1e3?"just now":r<6e4?`${Math.floor(r/1e3)}s`:r<36e5?`${Math.floor(r/6e4)}m`:`${Math.floor(r/36e5)}h`}function kv(t){const r=Math.max(1,Math.round(Number(t||0)/6e4));return r>=60?`${Math.round(r/60)}h`:`${r}m`}function Nv(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(uv)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}const Sv={llm_inference:"LLM",proof_exec:"Proof",provider_sweep:"Sweep",bridge_test:"Bridge",health_check:"Health",command:"Command",mission_schedule:"Mission",daemon:"Engine",daemon_ws:"WS",bridge_health:"Monitor",hosted_proxy:"Proxy",collab:"Collab"};function Cv(t){return Sv[String(t||"")]||String(t||"Task")}const _v=i.memo(function({usedMb:r,label:n}){const s=Math.min(100,Math.max(0,r/2048*100)),a=s>80?"bg-red-500":s>50?"bg-yellow-500":"bg-green-500";return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-[11px] font-mono mb-1",children:[e.jsx("span",{className:"text-slate-400",children:n}),e.jsxs("span",{className:"text-slate-300",children:[r," MB"]})]}),e.jsx("div",{className:"h-2 rounded-full bg-white/5 overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${a} transition-all duration-700`,style:{width:`${s}%`}})})]})});function Ki({task:t,onCancel:r,onRestartDaemon:n,busyId:s}){const a=t.category==="service",o=!!t.cancellable&&typeof r=="function",c=a&&t.kind==="daemon"&&typeof n=="function",l=t.paneId?`pane:${t.paneId}`:"",u=t.workflowId?`wf:${t.workflowId}`:"";return e.jsxs("div",{"data-testid":`task-row-${t.id}`,className:"flex items-start justify-between gap-3 px-3 py-2.5 rounded-xl border border-white/8 bg-black/25 hover:bg-white/[0.03] transition-colors",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[9px] font-mono uppercase tracking-[0.16em] px-1.5 py-0.5 rounded border border-violet-400/20 bg-violet-500/10 text-violet-200",children:Cv(t.kind)}),e.jsx("span",{className:"text-[12px] font-medium text-slate-100 truncate",children:t.label}),t.startedAt&&e.jsx("span",{className:"text-[10px] font-mono text-slate-500",children:jv(t.startedAt)})]}),t.detail&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500 mt-1 truncate",children:t.detail}),(l||u)&&e.jsx("div",{className:"text-[9px] font-mono text-slate-600 mt-1 truncate",children:[u,l].filter(Boolean).join(" · ")})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o&&e.jsx("button",{type:"button","data-testid":`task-cancel-${t.id}`,disabled:s===t.id,onClick:()=>r(t.id),className:"px-2.5 py-1 rounded-lg border border-rose-400/25 bg-rose-500/10 text-[9px] font-semibold uppercase tracking-wider text-rose-200 hover:bg-rose-500/15 disabled:opacity-50",children:s===t.id?"…":"Cancel"}),c&&e.jsx("button",{type:"button","data-testid":"task-manager-restart-daemon-btn",onClick:n,className:"px-2.5 py-1 rounded-lg border border-orange-400/25 bg-orange-500/10 text-[9px] font-semibold uppercase tracking-wider text-orange-200 hover:bg-orange-500/15",children:"Restart"}),!o&&!c&&e.jsx("span",{className:"text-[9px] font-mono uppercase tracking-wider text-slate-600",children:t.status||"running"})]})]})}function Av({memMb:t,settings:r={}}){if(t<1200)return null;const n=[];return t>=1200&&n.push("High RAM — disable particle backdrop in layout settings"),t>=1500&&r.otelExportEnabled&&n.push("OTel export is on — disable if not needed"),t>=1500&&r.hostedProxyEnabled&&n.push("Hosted model proxy adds overhead — disable when idle"),n.length===0?null:e.jsxs("section",{"data-testid":"task-manager-resource-warnings",className:"rounded-xl border border-amber-400/25 bg-amber-500/10 px-3 py-2.5 space-y-1",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] font-bold text-amber-200",children:"Resource warnings"}),n.map(s=>e.jsx("div",{className:"text-[10px] font-mono text-amber-100/90",children:s},s))]})}const Ev=i.memo(function({open:r,onClose:n,stats:s={},connectionInfo:a={},accelStatus:o={},settings:c={},workflowId:l="global",initialTab:u="ops",onOpenWorkpad:x,chatLog:p=[]}){const[d,m]=i.useState({operations:[],services:[],summary:{}}),[f,b]=i.useState([]),[h,g]=i.useState(""),[y,I]=i.useState(!1),[A,C]=i.useState(""),[w,j]=i.useState("ops"),[E,N]=i.useState(0),[_,S]=i.useState(0);i.useEffect(()=>{r&&j(u||"ops")},[r,u]),i.useEffect(()=>{if(!r||typeof n!="function")return;const ne=we=>{we.key==="Escape"&&(we.preventDefault(),n())};return window.addEventListener("keydown",ne),()=>window.removeEventListener("keydown",ne)},[r,n]),i.useEffect(()=>{if(!r)return;const ne=String(l||"global");Bp(ne);const we=()=>N(Xl(et(ne)));return we(),qa(()=>we(),ne)},[r,l]);const R=i.useCallback(async()=>{if(window.api&&window.api.tasks&&typeof window.api.tasks.list=="function")try{const ne=await window.api.tasks.list();m(ne&&typeof ne=="object"?ne:{operations:[],services:[],summary:{}}),b(Nv()),C("")}catch(ne){C(ne&&ne.message?ne.message:String(ne))}},[]);i.useEffect(()=>{if(!r)return;R();const ne=window.setInterval(R,2e3);return()=>window.clearInterval(ne)},[r,R]);const $=i.useCallback(async ne=>{if(window.api&&window.api.tasks&&typeof window.api.tasks.cancel=="function"){g(String(ne));try{const we=await window.api.tasks.cancel(ne);we&&we.ok?ge("Task cancelled","success"):ge(we&&we.reason?`Cancel failed: ${we.reason}`:"Cancel failed","error"),await R()}finally{g("")}}},[R]),U=i.useCallback(async()=>{if(window.api&&window.api.tasks&&typeof window.api.tasks.cancelAll=="function"){I(!0);try{const ne=await window.api.tasks.cancelAll({kinds:["llm_inference","proof_exec","provider_sweep"]}),we=Number(ne&&ne.cancelled)||0;ge(we>0?`Cancelled ${we} operation(s)`:"No cancellable operations",we>0?"success":"info"),await R()}finally{I(!1)}}},[R]),P=i.useCallback(async()=>{if(window.api&&window.api.system&&typeof window.api.system.runHealthCheck=="function"){I(!0);try{const ne=await window.api.system.runHealthCheck(),we=!!(ne&&ne.ok);ge(we?"Health check passed":"Health check found issues",we?"success":"warning"),await R()}catch(ne){ge(ne&&ne.message?ne.message:"Health check failed","error")}finally{I(!1)}}},[R]),D=i.useCallback(async()=>{window.api&&window.api.daemon&&typeof window.api.daemon.restart=="function"&&await window.api.daemon.restart(),await R()},[R]),z=i.useCallback(()=>{typeof x=="function"&&(x(),typeof n=="function"&&n())},[n,x]);if(!r)return null;const F=Number(s.cpuPercent||0),J=Number(s.memoryMb||0),ee=Number(s.tokensUsed||0),ie=Number(s.uptimeSec||0),ye=String(s.platform||"unknown"),pe=String(a.health||"unknown"),K=String(a.provider||"ollama"),H=String(a.model||"llama3"),W=!!o.enabled,Z=String(o.backend||"cpu"),ce=Array.isArray(d.operations)?d.operations:[],fe=Array.isArray(d.services)?d.services:[],me=d.summary&&typeof d.summary=="object"?d.summary:{},ke=Number(me.operations||ce.length);Number(me.services||fe.filter(ne=>ne.status==="running").length);const Pe=f.filter(ne=>!!(ne&&ne.enabled)),_e={ops:ke,workpad:E,health:_,missions:Pe.length};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[124] bg-black/50 backdrop-blur-[2px]",onClick:n}),e.jsxs("aside",{"data-testid":"operator-inbox-drawer",role:"dialog","aria-modal":"true","aria-label":"Operator Inbox",className:"fixed right-4 top-16 bottom-4 z-[125] w-[min(560px,calc(100vw-2rem))] rounded-2xl border border-violet-400/20 bg-shell-deep/98 shadow-[0_18px_80px_rgba(0,0,0,0.7)] flex flex-col backdrop-blur-xl animate-fade-up",children:[e.jsxs("div",{className:"px-5 py-4 border-b border-violet-500/10 bg-shell-soft/60 flex items-center justify-between rounded-t-2xl",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-9 w-9 rounded-xl bg-gradient-to-br from-fuchsia-500/20 to-violet-500/20 border border-fuchsia-400/20 flex items-center justify-center text-violet-200",children:e.jsxs("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.75,children:[e.jsx("path",{d:"M4 4h16v16H4z"}),e.jsx("path",{d:"M4 9h16M9 9v11"})]})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-bold text-white",children:"Operator Inbox"}),e.jsxs("div",{className:"text-[10px] text-slate-500 font-mono",children:[ke," ops · ",E," workpad · ",Pe.length," missions"]})]})]}),e.jsx("button",{type:"button","data-testid":"operator-inbox-close-btn","aria-label":"Close operator inbox",onClick:n,className:"h-8 w-8 rounded-lg border border-white/10 text-slate-400 hover:bg-white/10 hover:text-white flex items-center justify-center text-sm transition-all",children:"✕"})]}),e.jsx("div",{className:"px-3 py-2 border-b border-white/[0.03] bg-black/20 flex gap-1",children:hv.map(ne=>e.jsx(gv,{testId:`operator-inbox-tab-${ne.id}`,active:w===ne.id,label:ne.label,badge:_e[ne.id]||0,onClick:()=>j(ne.id)},ne.id))}),w==="ops"&&e.jsxs("div",{className:"px-4 py-2 border-b border-white/[0.03] bg-white/[0.01] flex flex-wrap gap-2",children:[e.jsx("button",{type:"button","data-testid":"task-manager-cancel-all-btn",disabled:y||ke===0,onClick:U,className:"px-2.5 py-1 rounded-lg border border-rose-400/25 bg-rose-500/10 text-[9px] font-semibold uppercase tracking-wider text-rose-200 hover:bg-rose-500/15 disabled:opacity-50",children:"Cancel all"}),e.jsx("button",{type:"button","data-testid":"task-manager-health-check-btn",disabled:y,onClick:P,className:"px-2.5 py-1 rounded-lg border border-cyan-400/25 bg-cyan-500/10 text-[9px] font-semibold uppercase tracking-wider text-cyan-200 hover:bg-cyan-500/15 disabled:opacity-50",children:"Run health check"})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-4 space-y-4",children:[w==="ops"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-4 gap-2",children:[{label:"CPU",value:`${F}%`},{label:"RAM",value:`${J}MB`},{label:"Bridge",value:pe==="online"?"Online":"Check"},{label:"Uptime",value:vv(ie)}].map(({label:ne,value:we})=>e.jsxs("div",{className:"text-center rounded-lg border border-white/5 bg-black/20 px-2 py-1.5",children:[e.jsx("div",{className:"text-[13px] font-bold font-mono text-slate-200",children:we}),e.jsx("div",{className:"text-[8px] text-slate-500 uppercase tracking-wider",children:ne})]},ne))}),e.jsx(Av,{memMb:J,settings:c}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.18em] font-bold text-cyan-300",children:"Active Operations"}),e.jsx("button",{type:"button",onClick:R,className:"text-[9px] font-mono uppercase tracking-wider text-slate-500 hover:text-slate-300",children:"Refresh"})]}),ce.length>0?e.jsx("div",{className:"space-y-2",children:ce.map(ne=>e.jsx(Ki,{task:ne,onCancel:$,busyId:h},ne.id))}):e.jsx("div",{"data-testid":"task-manager-empty",className:"rounded-xl border border-dashed border-white/10 px-4 py-6 text-center text-[11px] text-slate-500 font-mono",children:"No active operations. LLM streams, proof runs, sweeps, and health checks appear here while running."})]}),e.jsxs("section",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.18em] font-bold text-amber-300 mb-2",children:"Background Services"}),fe.length>0?e.jsx("div",{className:"space-y-2",children:fe.map(ne=>e.jsx(Ki,{task:ne,onRestartDaemon:D},ne.id))}):e.jsx("div",{className:"text-[11px] text-slate-500 font-mono px-1",children:"No background services reported."})]}),e.jsxs("section",{className:"rounded-xl border border-white/8 bg-black/20 p-3 space-y-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.18em] font-bold text-slate-400",children:"Runtime Snapshot"}),e.jsx(_v,{usedMb:J,label:"Process Memory"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-[10px] font-mono",children:[e.jsxs("div",{className:"text-slate-500",children:["Provider ",e.jsx("span",{className:"text-slate-300",children:Ka(K)})]}),e.jsxs("div",{className:"text-slate-500",children:["Model ",e.jsx("span",{className:"text-slate-300 truncate",children:H})]}),e.jsxs("div",{className:"text-slate-500",children:["Tokens ",e.jsx("span",{className:"text-slate-300",children:ee.toLocaleString()})]}),e.jsxs("div",{className:"text-slate-500",children:["Accel ",e.jsx("span",{className:"text-slate-300",children:W?Z:"off"})]}),e.jsxs("div",{className:"text-slate-500",children:["Platform ",e.jsx("span",{className:"text-slate-300",children:ye})]}),e.jsxs("div",{className:"text-slate-500",children:["Bridge ",e.jsx("span",{className:pe==="online"?"text-emerald-300":"text-amber-300",children:pe})]})]})]})]}),w==="workpad"&&e.jsx(yv,{workflowId:l,onOpenWorkpad:z}),w==="actions"&&e.jsx(bv,{workflowId:l,chatLog:p}),w==="health"&&e.jsx(wv,{onRunHealthCheck:P,bulkBusy:y,onEntriesChange:S}),w==="missions"&&e.jsxs("section",{"data-testid":"operator-inbox-missions-tab",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.18em] font-bold text-fuchsia-300 mb-2",children:"Scheduled Missions"}),Pe.length>0?e.jsx("div",{className:"space-y-2",children:Pe.map(ne=>e.jsx(Ki,{task:{id:`mission-${ne.missionId}`,kind:"mission_schedule",label:String(ne.missionId||"mission"),detail:`every ${kv(ne.intervalMs)} · ${ne.dryRun?"dry-run":"live"}`,category:"operation",status:"scheduled",cancellable:!1}},`mission-${ne.missionId}-${ne.intervalMs}`))}):e.jsx("div",{"data-testid":"operator-inbox-missions-empty",className:"text-center py-8 text-[11px] font-mono text-slate-500 border border-dashed border-white/10 rounded-xl",children:"No scheduled missions. Configure them in Mission Control or Readiness."})]}),A&&e.jsx("div",{className:"rounded-xl border border-rose-400/25 bg-rose-500/10 px-3 py-2 text-[10px] font-mono text-rose-200",children:A})]}),e.jsxs("div",{className:"px-4 py-2.5 border-t border-violet-500/10 bg-shell-soft/40 text-[10px] text-slate-500 flex items-center justify-between rounded-b-2xl",children:[e.jsx("span",{children:"Auto-refresh every 2s · Ctrl+Shift+T inbox · Ctrl+Shift+A actions · Ctrl+Shift+C calendar · Esc closes"}),e.jsx("span",{className:"font-mono text-slate-600",children:w})]})]})]})}),uu={info:"border-cyan-300/30 bg-cyan-500/15 text-cyan-100",success:"border-emerald-300/30 bg-emerald-500/15 text-emerald-100",warning:"border-amber-300/30 bg-amber-500/15 text-amber-100",error:"border-rose-300/30 bg-rose-500/15 text-rose-100"},Iv=i.memo(function(){const[r,n]=i.useState({message:"",tone:"info"}),s=i.useRef(null),a=i.useCallback(()=>{s.current&&(window.clearTimeout(s.current),s.current=null),n({message:"",tone:"info"})},[]);i.useEffect(()=>{const l=u=>{const x=u&&u.detail?u.detail:{},p=String(x.message||"").trim();if(!p)return;const d=String(x.tone||"info");n({message:p,tone:d}),s.current&&window.clearTimeout(s.current),s.current=window.setTimeout(()=>{n({message:"",tone:"info"})},3200)};return window.addEventListener("neuralshell:toast",l),()=>{window.removeEventListener("neuralshell:toast",l),s.current&&window.clearTimeout(s.current)}},[]);const o=!!r.message,c=uu[r.tone]||uu.info;return e.jsx("div",{"data-testid":"app-toast-host","aria-live":"polite",className:`fixed bottom-5 left-1/2 -translate-x-1/2 z-[200] max-w-[min(92vw,520px)] transition-all duration-300 ${o?"opacity-100 translate-y-0":"opacity-0 translate-y-2 pointer-events-none"}`,children:e.jsxs("div",{className:`rounded-xl border px-4 py-2.5 text-[11px] font-mono shadow-[0_12px_40px_rgba(0,0,0,0.45)] flex items-center gap-3 ${c}`,children:[e.jsx("span",{"data-testid":"app-toast-message",className:"flex-1 min-w-0",children:r.message||" "}),o&&e.jsx("button",{type:"button","aria-label":"Dismiss notification","data-testid":"app-toast-dismiss-btn",onClick:a,className:"shrink-0 h-6 w-6 rounded-md border border-white/10 text-slate-300 hover:text-white hover:bg-white/10 transition-colors",children:"✕"})]})})}),pu={ready:{border:"border-emerald-300/25",badge:"bg-emerald-500/15 text-emerald-100 border-emerald-400/30",primary:"border-emerald-300/30 bg-emerald-500/10 text-emerald-100 hover:bg-emerald-500/20",secondary:"border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.06]"},degraded:{border:"border-amber-300/25",badge:"bg-amber-500/15 text-amber-100 border-amber-400/30",primary:"border-amber-300/30 bg-amber-500/10 text-amber-100 hover:bg-amber-500/20",secondary:"border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.06]"},blocked:{border:"border-rose-300/25",badge:"bg-rose-500/15 text-rose-100 border-rose-400/30",primary:"border-rose-300/30 bg-rose-500/10 text-rose-100 hover:bg-rose-500/20",secondary:"border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.06]"}},Pv=i.memo(function({open:r,onClose:n,connectionInfo:s,watchdogStatus:a,incidentCount:o=0,setupBlocked:c=!1,sessionDegradedDismissed:l=!1,acknowledgedReady:u=!1,exportAvailable:x=!1,exportBusy:p=!1,onStartOperating:d,onInspectIssue:m,onFixSetup:f,onOpenSettings:b,onContinueAnyway:h,onExportEvidence:g}){const y=i.useRef(null);Wa(r,y,n);const I=i.useMemo(()=>Hl({connectionInfo:s,watchdogStatus:a,incidentCount:o,setupBlocked:c}),[s,a,o,c]),A=i.useMemo(()=>Wl(I,{sessionDegradedDismissed:l,acknowledgedReady:u}),[I,l,u]),C=pu[A.verdict]||pu.blocked;if(!r)return null;const w=()=>{const{id:_}=A.primaryAction;if(_==="start"&&typeof d=="function"){d();return}if(_==="inspect"&&typeof m=="function"){m();return}_==="fix-setup"&&typeof f=="function"&&f()},j=()=>{const{id:_}=A.secondaryAction;if(_==="export"&&typeof g=="function"){g();return}if(_==="continue"&&typeof h=="function"){h();return}_==="open-settings"&&typeof b=="function"&&b()},E=A.secondaryAction.id==="export"&&!x,N=E?"Export Evidence — unavailable in this shell":A.secondaryAction.label;return e.jsx("div",{className:"fixed inset-0 z-[146] bg-black/70 backdrop-blur-sm flex items-center justify-center p-5",onClick:n,children:e.jsxs("section",{ref:y,"data-testid":"readiness-verdict-modal","data-verdict":A.verdict,"data-trust-severity":A.trustSeverity,role:"dialog","aria-modal":"true","aria-label":`Readiness verdict: ${A.title}`,className:`w-full max-w-lg rounded-2xl border bg-slate-950 p-5 shadow-[0_20px_90px_rgba(0,0,0,0.75)] ${C.border}`,onClick:_=>_.stopPropagation(),children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("span",{"data-testid":"readiness-verdict-title",className:`inline-flex px-2 py-0.5 rounded border text-[10px] font-bold uppercase tracking-[0.18em] ${C.badge}`,children:A.title}),e.jsx("p",{className:"text-[12px] text-slate-300 mt-2",children:A.message})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/30 px-3 py-2 text-[10px] font-mono text-slate-400 space-y-1",children:[e.jsxs("div",{children:["Bridge: ",e.jsx("span",{className:"text-slate-200",children:I.bridge})]}),e.jsxs("div",{children:["Provider: ",e.jsxs("span",{className:"text-slate-200",children:[I.provider,"/",I.model||"—"]})]}),e.jsxs("div",{children:["Runtime: ",e.jsx("span",{className:"text-slate-200",children:I.runtimeLabel})]}),I.incidentCount>0&&e.jsxs("div",{children:["Incidents: ",e.jsx("span",{className:"text-amber-200",children:I.incidentCount})]})]}),e.jsxs("div",{className:"mt-5 flex items-center justify-end gap-2",children:[e.jsx("button",{type:"button","data-testid":"readiness-verdict-secondary-btn","data-action-id":A.secondaryAction.id,disabled:E||p,onClick:j,className:`px-3 py-2 rounded-lg border text-[10px] font-mono uppercase tracking-[0.14em] disabled:opacity-50 ${C.secondary}`,children:p?"Exporting…":N}),e.jsx("button",{type:"button","data-testid":"readiness-verdict-primary-btn","data-action-id":A.primaryAction.id,onClick:w,className:`px-4 py-2 rounded-lg border text-[10px] font-mono uppercase tracking-[0.14em] font-bold ${C.primary}`,children:A.primaryAction.label})]})]})})});function Rv(t={}){const r=t&&typeof t=="object"?t:{};Nt({id:"cmd-operator-inbox",slot:"palette.commands",title:"Open Operator Inbox",priority:5,stability:"core",contexts:["global"],contextLabel:"Operator",shortcut:"Ctrl + Shift + T",action:()=>{typeof r.openOperatorInbox=="function"&&r.openOperatorInbox()}}),Nt({id:"cmd-workpad",slot:"palette.commands",title:"Open Workpad",priority:6,stability:"core",contexts:["active-workflow"],contextLabel:"Current workflow",shortcut:"Ctrl + Shift + N",action:()=>{typeof r.openWorkpad=="function"&&r.openWorkpad()}}),Nt({id:"cmd-operator-calendar",slot:"palette.commands",title:"Open ChronoHUD",priority:7,stability:"core",contexts:["global"],contextLabel:"Operator",shortcut:"Ctrl + Shift + C",action:()=>{typeof r.openCalendar=="function"&&r.openCalendar()}}),Nt({id:"cmd-guided-actions",slot:"palette.commands",title:"Open Guided Actions",priority:8,stability:"core",contexts:["global"],contextLabel:"Operator",shortcut:"Ctrl + Shift + A",action:()=>{typeof r.openGuidedActions=="function"&&r.openGuidedActions()}}),Nt({id:"cmd-trust-report",slot:"palette.system",title:"Open Trust Report",priority:9,stability:"core",contexts:["system"],contextLabel:"Trust",action:()=>{typeof r.openTrustReport=="function"&&r.openTrustReport()}}),Nt({id:"cmd-health-check",slot:"palette.system",title:"Run System Health Check",priority:10,stability:"core",contexts:["system"],contextLabel:"Diagnostics",action:async()=>{typeof r.runHealthCheck=="function"&&await r.runHealthCheck()}}),Nt({id:"cmd-export-workpad",slot:"palette.system",title:"Export Workpad Markdown",priority:45,stability:"trusted",contexts:["active-workflow"],contextLabel:"Current workflow",action:()=>{typeof r.exportWorkpad=="function"&&r.exportWorkpad()}})}const Ov=new Set(["system","user","assistant"]),Tv={kernel:"assistant",operator:"assistant"};function Mv(t){return Array.isArray(t)?t.filter(r=>r&&typeof r=="object").map(r=>{const n=String(r.role||"").trim().toLowerCase(),s=Tv[n]||n,a=typeof r.content=="string"?r.content:String(r.content??"");return{role:s,content:a}}).filter(r=>Ov.has(r.role)&&r.content.trim().length>0):[]}async function Dv(t){var n,s,a,o;const r=String(t||"").trim();if(!(!r||!((s=(n=window.api)==null?void 0:n.settings)!=null&&s.get)||!((o=(a=window.api)==null?void 0:a.settings)!=null&&o.update)))try{const c=await window.api.settings.get();if(!c||typeof c!="object")return;const l=Array.isArray(c.connectionProfiles)?c.connectionProfiles:[],u=String(c.activeProfileId||"").trim(),x=u&&l.length?l.map(p=>String((p==null?void 0:p.id)||"")===u?{...p,defaultModel:r}:p):l;await window.api.settings.update({...c,defaultModel:r,connectionProfiles:x})}catch{}}const mu="https://discord.gg/neuralshell";function $v(){if(window.api&&window.api.system&&typeof window.api.system.openExternal=="function"){window.api.system.openExternal(mu).catch(()=>{});return}window.open(mu,"_blank","noopener,noreferrer")}function Lv(t){const r=String(t||"degraded").toLowerCase();return r==="healthy"?"border-emerald-300/35 bg-emerald-500/10 text-emerald-100":r==="critical"?"border-rose-300/40 bg-rose-500/10 text-rose-100":r==="offline"?"border-slate-300/30 bg-slate-500/10 text-slate-200":"border-amber-300/35 bg-amber-500/10 text-amber-100"}function Bv(t){const r=String(t||"").trim();if(!r)return"n/a";const n=new Date(r);return Number.isNaN(n.getTime())?r:n.toLocaleString()}function Fv({node:t,selected:r,onToggleSelect:n,onRemove:s,onOpenFeed:a}){const o=t&&typeof t=="object"?t:{},c=String(o.nodeId||"unknown-node");return e.jsxs("article",{"data-testid":`fleet-node-card-${c}`,"aria-label":`Fleet node ${c}`,className:`rounded-xl border p-3 ${Lv(o.runtimeHealth)} transition-colors`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-mono uppercase tracking-[0.12em] opacity-85",children:String(o.displayName||c)}),e.jsx("div",{className:"text-[9px] font-mono opacity-70",children:c})]}),e.jsxs("label",{className:"inline-flex items-center gap-1 text-[9px] font-mono uppercase tracking-[0.12em]",children:[e.jsx("input",{type:"checkbox",checked:!!r,onChange:()=>n(c),"aria-label":`Select node ${c} for compare`}),"Compare"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-1.5 mt-2 text-[9px] font-mono",children:[e.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-1.5 py-1",children:["Provider: ",e.jsx("span",{className:"text-slate-100",children:String(o.providerHealth||"unknown")})]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-1.5 py-1",children:["Proof: ",e.jsx("span",{className:"text-slate-100",children:String(o.proofStatus||"unknown")})]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-1.5 py-1",children:["Policy: ",e.jsx("span",{className:"text-slate-100",children:String(o.policyProfile||"none")})]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-1.5 py-1",children:["Version: ",e.jsx("span",{className:"text-slate-100",children:String(o.updateVersion||"unknown")})]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-1.5 py-1",children:["Relay: ",e.jsx("span",{className:"text-slate-100",children:String(o.relayStatus||"unknown")})]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-1.5 py-1",children:["Collab: ",e.jsx("span",{className:"text-slate-100",children:String(o.collabState||"unknown")})]})]}),e.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 text-[9px] font-mono opacity-80",children:[e.jsxs("span",{children:["Seen ",Bv(o.lastSeenAt)]}),e.jsxs("span",{children:[Array.isArray(o.alerts)?o.alerts.length:0," alert(s)"]})]}),e.jsxs("div",{className:"mt-2 flex items-center justify-end gap-2",children:[e.jsx("button",{type:"button","data-testid":`fleet-open-feed-${c}`,onClick:()=>a(c),className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"Event Feed"}),e.jsx("button",{type:"button","data-testid":`fleet-remove-node-${c}`,onClick:()=>s(c),className:"px-2 py-1 rounded border border-rose-300/35 bg-rose-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-rose-100",children:"Remove"})]})]})}function Uv({selectedNodes:t=[],compareRows:r=[]}){const n=Array.isArray(t)?t:[],s=n[0]||null,a=n[1]||null;return e.jsxs("section",{"data-testid":"fleet-compare-view",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Compare Selected Nodes"}),!s||!a?e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Select exactly two nodes to compare."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-[10px] font-mono",children:[e.jsx("div",{className:"text-slate-500",children:"Field"}),e.jsx("div",{className:"text-slate-300",children:String(s.displayName||s.nodeId)}),e.jsx("div",{className:"text-slate-300",children:String(a.displayName||a.nodeId)})]}),e.jsxs("div",{className:"max-h-52 overflow-auto space-y-1 pr-1",children:[(Array.isArray(r)?r:[]).map(o=>e.jsxs("div",{className:"grid grid-cols-3 gap-2 rounded border border-amber-300/30 bg-amber-500/10 px-2 py-1.5 text-[10px] font-mono",children:[e.jsx("div",{className:"text-amber-100",children:String(o.label||o.key)}),e.jsx("div",{className:"text-slate-200 break-all",children:String(o.left)}),e.jsx("div",{className:"text-slate-200 break-all",children:String(o.right)})]},o.key)),(!r||r.length===0)&&e.jsx("div",{className:"text-[10px] font-mono text-emerald-300",children:"No meaningful differences across selected fields."})]})]})]})}function ys(t,r,n){return e.jsxs("div",{className:`rounded border px-2 py-1 text-[10px] font-mono ${n}`,children:[e.jsx("span",{className:"opacity-80",children:t}),e.jsx("span",{className:"ml-1 font-bold",children:r})]})}function zv({open:t,onClose:r,fleet:n,onImportLocalRuntime:s}){const[a,o]=i.useState(""),[c,l]=i.useState(""),[u,x]=i.useState("");if(!t)return null;const p=n&&typeof n=="object"?n:{},d=Array.isArray(p.filteredNodes)?p.filteredNodes:[],m=Array.isArray(p.nodes)?p.nodes:[],f=p.healthSummary||{total:0,healthy:0,degraded:0,critical:0,offline:0},b=m.find(g=>String(g.nodeId||"")===String(u||""))||null,h=async g=>{const y=g&&g.target&&g.target.files?g.target.files[0]:null;if(y)try{const I=await p.importFleetFile(y);l(`Imported ${I} node(s) from ${y.name}.`),o("")}catch(I){l(""),o(I&&I.message?I.message:String(I))}finally{g&&g.target&&(g.target.value="")}};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[128] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"fleet-control-panel","aria-label":"Fleet Control Panel",className:"fixed inset-x-6 top-16 bottom-6 z-[129] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.72)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Fleet Control Panel"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Offline-first multi-node view from imported bundles and local runtime snapshots."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("label",{className:"px-2 py-1 rounded border border-cyan-300/35 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100 cursor-pointer",children:["Import Bundle",e.jsx("input",{"data-testid":"fleet-import-input",type:"file",accept:".json,.csv,application/json,text/csv",className:"hidden",onChange:h})]}),e.jsx("button",{type:"button","data-testid":"fleet-import-runtime-btn",onClick:()=>{if(typeof s=="function"){const g=s();g&&(l(`Imported local runtime node: ${g.displayName}.`),o(""))}},className:"px-2 py-1 rounded border border-blue-300/35 bg-blue-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-blue-100",children:"Import Local Node"}),e.jsx("button",{type:"button","data-testid":"fleet-clear-btn",onClick:()=>p.clearFleet(),className:"px-2 py-1 rounded border border-rose-300/35 bg-rose-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-rose-100",children:"Clear"}),e.jsx("button",{type:"button","data-testid":"fleet-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]})]}),e.jsxs("div",{className:"px-4 py-2 border-b border-white/10 bg-black/20 flex flex-wrap items-center gap-2",children:[ys("Total",f.total,"border-white/15 bg-black/25 text-slate-200"),ys("Healthy",f.healthy,"border-emerald-300/35 bg-emerald-500/10 text-emerald-100"),ys("Degraded",f.degraded,"border-amber-300/35 bg-amber-500/10 text-amber-100"),ys("Critical",f.critical,"border-rose-300/35 bg-rose-500/10 text-rose-100"),ys("Offline",f.offline,"border-slate-300/30 bg-slate-500/10 text-slate-200"),e.jsx("div",{className:"ml-auto inline-flex rounded border border-white/10 bg-black/30 overflow-hidden",children:[{id:"all",label:"All"},{id:"healthy",label:"Healthy"},{id:"degraded",label:"Degraded"},{id:"critical",label:"Critical"},{id:"offline",label:"Offline"}].map(g=>e.jsx("button",{type:"button","data-testid":`fleet-filter-${g.id}`,onClick:()=>p.setStatusFilter(g.id),className:`px-2 py-1 text-[9px] font-mono uppercase tracking-[0.12em] border-l border-white/10 first:border-l-0 ${String(p.statusFilter||"all")===g.id?"bg-cyan-500/20 text-cyan-100":"text-slate-300 hover:bg-white/10"}`,children:g.label},g.id))})]}),(c||a)&&e.jsxs("div",{className:"px-4 py-2 border-b border-white/10 bg-black/15",children:[c&&e.jsx("div",{"data-testid":"fleet-import-info",className:"text-[10px] font-mono text-emerald-200",children:c}),a&&e.jsx("div",{"data-testid":"fleet-import-error",className:"text-[10px] font-mono text-rose-200",children:a})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[1.1fr_0.9fr]",children:[e.jsxs("div",{className:"p-3 border-r border-white/10 min-h-0 flex flex-col",children:[e.jsxs("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold mb-2",children:["Node List (",d.length,")"]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto pr-1 space-y-2","data-testid":"fleet-node-list",children:[d.map(g=>e.jsx(Fv,{node:g,selected:Array.isArray(p.selectedNodeIds)&&p.selectedNodeIds.includes(g.nodeId),onToggleSelect:p.toggleNodeSelected,onRemove:p.removeNode,onOpenFeed:x},g.nodeId)),d.length===0&&e.jsx("div",{className:"rounded-lg border border-white/10 bg-black/25 px-3 py-3 text-[10px] font-mono text-slate-500",children:"No nodes loaded. Import JSON/CSV bundles or pull the local runtime."})]})]}),e.jsxs("div",{className:"p-3 min-h-0 overflow-auto space-y-3",children:[e.jsx(Uv,{selectedNodes:p.selectedNodes||[],compareRows:p.compareRows||[]}),e.jsxs("section",{"data-testid":"fleet-node-event-feed",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Node Event Feed"}),e.jsxs("select",{"data-testid":"fleet-event-node-select",value:u,onChange:g=>x(g.target.value),className:"rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200",children:[e.jsx("option",{value:"",children:"Select node"}),m.map(g=>e.jsx("option",{value:g.nodeId,children:g.displayName},g.nodeId))]})]}),b?e.jsxs("div",{className:"max-h-64 overflow-auto space-y-1 pr-1",children:[(Array.isArray(b.events)?b.events:[]).slice(-80).reverse().map(g=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/25 px-2 py-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[10px] font-mono",children:[e.jsx("span",{className:"text-slate-200",children:String(g.type||"fleet.event")}),e.jsx("span",{className:"text-slate-500",children:String(g.at||"")})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:[String(g.source||"fleet")," · ",String(g.severity||"info")]})]},g.id)),(!b.events||b.events.length===0)&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No events for this node yet."})]}):e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Choose a node to inspect its timeline."})]})]})]})]})]})}function xu(t){return t==null?"null":typeof t=="string"?t:JSON.stringify(t)}function Hv({currentState:t={},incomingState:r={}}){const n=t&&typeof t=="object"?t:{},s=r&&typeof r=="object"?r:{},o=Array.from(new Set([...Object.keys(n),...Object.keys(s)])).sort().map(c=>({key:c,before:n[c],after:s[c],changed:JSON.stringify(n[c])!==JSON.stringify(s[c])})).filter(c=>c.changed);return e.jsxs("section",{"data-testid":"restore-preview",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Restore Preview"}),e.jsxs("div",{className:"max-h-60 overflow-auto space-y-1 pr-1",children:[o.map(c=>e.jsxs("div",{className:"grid grid-cols-3 gap-2 rounded border border-amber-300/30 bg-amber-500/10 px-2 py-1 text-[10px] font-mono",children:[e.jsx("div",{className:"text-amber-100 break-all",children:c.key}),e.jsx("div",{className:"text-slate-300 break-all",children:xu(c.before)}),e.jsx("div",{className:"text-slate-100 break-all",children:xu(c.after)})]},c.key)),o.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-emerald-300",children:"No diff detected."})]})]})}const Wv="neuralshell_recovery_last_bundle_v1";async function fu(t){const n=new window.TextEncoder().encode(String(t||"")),s=await window.crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(s)).map(a=>a.toString(16).padStart(2,"0")).join("")}function bu(){if(typeof window>"u"||!window.localStorage)return{};const t=(r,n)=>{try{const s=window.localStorage.getItem(r);return s?JSON.parse(s):n}catch{return n}};return{policyProfiles:t("neuralshell_policy_profiles_v1",[]),nodechainRules:t("neuralshell_nodechain_rules_v1",[]),runtimeSnapshots:t("neuralshell_runtime_snapshots_v1",[]),operatorLayouts:{onboardingProgress:t("neuralshell_onboarding_progress_v1",{}),railLayout:t("neuralshell_rail_layout_prefs_v1",{}),railCollapse:t("neuralshell_rail_collapse_prefs_v1",{})},releaseTruth:t("neuralshell_release_truth_cache_v1",{}),marketplaceReceipts:t("neuralshell_marketplace_receipts_v1",[]),fleetConfig:t("neuralshell_fleet_nodes_v1",[]),analyticsBundles:t("neuralshell_analytics_bundle_cache_v1",{})}}function Ol(t,r){if(t==null)return t;if(Array.isArray(t))return t.map(s=>Ol(s,r));if(typeof t!="object")return t;const n={};return Object.entries(t).forEach(([s,a])=>{const o=String(s||"").toLowerCase();if(!r&&(o.includes("token")||o.includes("secret")||o.includes("password")||o.includes("passphrase")||o.includes("apikey"))){n[s]="[excluded]";return}n[s]=Ol(a,r)}),n}function Kv(t,r){const n=t&&typeof t=="object"?t:{},s=Array.isArray(r)?r:[],a={};return s.forEach(o=>{Object.prototype.hasOwnProperty.call(n,o)&&(a[o]=n[o])}),a}function Vv(t,r){const n=t&&typeof t=="object"?t:{};if(typeof window>"u"||!window.localStorage)return;const s=(a,o)=>{window.localStorage.setItem(a,JSON.stringify(o))};n.policyProfiles&&s("neuralshell_policy_profiles_v1",n.policyProfiles),n.nodechainRules&&s("neuralshell_nodechain_rules_v1",n.nodechainRules),n.runtimeSnapshots&&s("neuralshell_runtime_snapshots_v1",n.runtimeSnapshots),n.operatorLayouts&&typeof n.operatorLayouts=="object"&&(n.operatorLayouts.onboardingProgress&&s("neuralshell_onboarding_progress_v1",n.operatorLayouts.onboardingProgress),n.operatorLayouts.railLayout&&s("neuralshell_rail_layout_prefs_v1",n.operatorLayouts.railLayout),n.operatorLayouts.railCollapse&&s("neuralshell_rail_collapse_prefs_v1",n.operatorLayouts.railCollapse)),n.releaseTruth&&s("neuralshell_release_truth_cache_v1",n.releaseTruth),n.marketplaceReceipts&&s("neuralshell_marketplace_receipts_v1",n.marketplaceReceipts),n.fleetConfig&&s("neuralshell_fleet_nodes_v1",n.fleetConfig),n.analyticsBundles&&s("neuralshell_analytics_bundle_cache_v1",n.analyticsBundles),r==="safe"&&window.api&&window.api.settings&&typeof window.api.settings.update=="function"&&window.api.settings.update({offlineOnlyEnforced:!0,allowRemoteBridge:!1,autoUpdateChannel:"frozen"}).catch(()=>{})}function Gv({open:t,onClose:r}){const[n,s]=i.useState({policyProfiles:!0,nodechainRules:!0,runtimeSnapshots:!0,operatorLayouts:!0,releaseTruth:!0,marketplaceReceipts:!0,fleetConfig:!0,analyticsBundles:!1}),[a,o]=i.useState(!1),[c,l]=i.useState(""),[u,x]=i.useState(""),[p,d]=i.useState(!1),[m,f]=i.useState(null),[b,h]=i.useState(null),[g,y]=i.useState("full"),I=i.useMemo(()=>Object.entries(n).filter(([,E])=>!!E).map(([E])=>E),[n]),A=i.useMemo(()=>bu(),[]),C=async()=>{d(!0);try{const E=bu(),N=Kv(E,I),_={schema:"neuralshell_recovery_bundle_v1",generatedAt:new Date().toISOString(),includeSecrets:!!a,scopes:Ol(N,!!a)},S=await fu(pr(_)),R=await eo("neuralshell_recovery_signing_v1"),$=await to(_,R.privateKeyPem),U=await Tr(R.publicKeyPem),P={schema:"neuralshell_recovery_bundle_signed_v1",payload:_,hash:S,signature:$,signer:{publicKeyPem:R.publicKeyPem,fingerprint:U}};typeof window<"u"&&window.localStorage&&window.localStorage.setItem(Wv,JSON.stringify(P)),je(`neuralshell_recovery_bundle_${Date.now()}.signed.json`,P),l(`Recovery bundle exported (${I.length} scope(s), signer ${U.slice(0,24)}...).`),x(""),X("recovery.bundle.exported",{scopes:I,includeSecrets:!!a},{source:"recovery",severity:"info"})}catch(E){l(""),x(E&&E.message?E.message:String(E))}finally{d(!1)}},w=async E=>{const N=E&&E.target&&E.target.files?E.target.files[0]:null;if(N){d(!0);try{const _=await pt(N),S=JSON.parse(String(_||"{}")),R=S&&S.payload&&typeof S.payload=="object"?S.payload:null,$=String(S&&S.signature?S.signature:""),U=String(S&&S.signer&&S.signer.publicKeyPem?S.signer.publicKeyPem:""),P=String(S&&S.hash?S.hash:"").trim().toLowerCase();if(!R||!$||!U||!P)throw new Error("Bundle missing payload/signature/hash/public key.");const D=await Mt(R,$,U),z=await fu(pr(R)),F=P===z,J={ok:!!(D&&F),signatureValid:!!D,hashValid:!!F,hash:P,computedHash:z};if(f(S),h(J),!J.ok)throw new Error("Bundle verification failed (signature/hash mismatch).");l(`Bundle verified from ${N.name}.`),x(""),X("recovery.bundle.verified",{sourceName:N.name,signatureValid:J.signatureValid,hashValid:J.hashValid},{source:"recovery",severity:"info"})}catch(_){l(""),x(_&&_.message?_.message:String(_)),h(null)}finally{d(!1),E&&E.target&&(E.target.value="")}}},j=()=>{if(!m||!b||!b.ok){x("Import and verify a signed bundle before restore.");return}const E=m&&m.payload&&m.payload.scopes?m.payload.scopes:{};Vv(E,g),l(`Restore applied in ${g} mode.`),x(""),X("recovery.restore.applied",{restoreMode:g,scopeKeys:Object.keys(E||{})},{source:"recovery",severity:g==="safe"?"warning":"info"})};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[130] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"recovery-center",className:"fixed inset-x-8 top-18 bottom-8 z-[131] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Recovery Center"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Signed backup/export, staged restore preview, and safe-mode recovery paths."})]}),e.jsx("button",{type:"button","data-testid":"recovery-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.95fr_1.05fr]",children:[e.jsxs("div",{className:"p-3 border-r border-white/10 min-h-0 overflow-auto space-y-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Backup Scope Selection"}),Object.keys(n).map(E=>e.jsxs("label",{className:"flex items-center gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:!!n[E],onChange:N=>s(_=>({..._,[E]:!!N.target.checked}))}),E]},E)),e.jsxs("label",{className:"flex items-center gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:a,onChange:E=>o(!!E.target.checked)}),"Include secrets (dangerous)"]}),a&&e.jsx("div",{className:"rounded border border-rose-300/35 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-200",children:"Secret export is enabled. Use only for isolated sealed transfers."}),e.jsx("button",{type:"button","data-testid":"recovery-export-btn",disabled:p,onClick:C,className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 disabled:opacity-60",children:p?"Working...":"Export Signed Bundle"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Restore Bundle"}),e.jsxs("label",{className:"inline-flex items-center px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono uppercase tracking-[0.12em] text-cyan-100 cursor-pointer",children:["Import Signed Bundle",e.jsx("input",{type:"file","data-testid":"recovery-import-input",accept:".json,application/json",className:"hidden",onChange:w})]}),e.jsxs("div",{className:"space-y-1 text-[10px] font-mono",children:[e.jsxs("label",{className:"flex items-center gap-2 text-slate-300",children:[e.jsx("input",{type:"radio",name:"restore-mode",value:"full",checked:g==="full",onChange:()=>y("full")}),"Full restore"]}),e.jsxs("label",{className:"flex items-center gap-2 text-slate-300",children:[e.jsx("input",{type:"radio",name:"restore-mode",value:"partial",checked:g==="partial",onChange:()=>y("partial")}),"Partial restore"]}),e.jsxs("label",{className:"flex items-center gap-2 text-slate-300",children:[e.jsx("input",{type:"radio",name:"restore-mode",value:"safe",checked:g==="safe",onChange:()=>y("safe")}),"Safe-mode restore"]})]}),e.jsx("button",{type:"button","data-testid":"recovery-apply-btn",onClick:j,className:"w-full px-3 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-amber-100",children:"Apply Restore"})]}),b&&e.jsxs("section",{"data-testid":"recovery-verify-result",className:"rounded-xl border border-white/10 bg-black/20 p-3 text-[10px] font-mono space-y-1",children:[e.jsx("div",{className:b.ok?"text-emerald-300":"text-rose-300",children:b.ok?"PASS":"FAIL"}),e.jsxs("div",{className:"text-slate-400",children:["Signature: ",b.signatureValid?"valid":"invalid"]}),e.jsxs("div",{className:"text-slate-400",children:["Hash: ",b.hashValid?"valid":"invalid"]})]}),c&&e.jsx("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-[10px] font-mono text-emerald-100",children:c}),u&&e.jsx("div",{className:"rounded border border-rose-300/35 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-200",children:u})]}),e.jsxs("div",{className:"p-3 min-h-0 overflow-auto space-y-3",children:[e.jsx(Hv,{currentState:A,incomingState:m&&m.payload&&m.payload.scopes?m.payload.scopes:{}}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Staged Restore Notes"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-400",children:"Restore is blocked unless signature + hash both verify. Safe mode forces offline-only and frozen update ring before applying payload scopes."})]})]})]})]})]}):null}function Jv(){if(typeof window>"u"||!window.localStorage)return 0;const t=Number(window.localStorage.getItem("neuralshell_support_ingest_count_v1")||"0");return Number.isFinite(t)?Math.max(0,Math.round(t)):0}function qv({open:t,onClose:r,enabled:n,onToggleEnabled:s,runtimeState:a,fleetSummary:o}){const[c]=i.useState(()=>Jv()),l=a&&typeof a=="object"?a:{},u=l.relayState||{},x=l.policyState||{},p=l.updateLane||{},d=o&&typeof o=="object"?o:{total:0,healthy:0,degraded:0,critical:0,offline:0};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[132] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"appliance-console",className:"fixed inset-x-8 top-20 bottom-8 z-[133] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Appliance Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Hardened relay/control profile for operator deployments."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"appliance-toggle-btn",onClick:()=>{const m=!n;typeof s=="function"&&s(m),X("appliance.mode.changed",{enabled:m},{source:"appliance",severity:m?"info":"warning"})},className:`px-3 py-1.5 rounded border text-[10px] font-mono uppercase tracking-[0.12em] ${n?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100"}`,children:n?"Disable Appliance":"Enable Appliance"}),e.jsx("button",{type:"button","data-testid":"appliance-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-4 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold mb-2",children:"Relay / Policy / Updates"}),e.jsxs("div",{className:"space-y-1 text-[10px] font-mono text-slate-300",children:[e.jsxs("div",{children:["Relay Enabled: ",e.jsx("span",{className:"text-slate-100",children:u.enabled?"yes":"no"})]}),e.jsxs("div",{children:["Relay Channel: ",e.jsx("span",{className:"text-slate-100",children:String(u.mappedChannel||"local-only")})]}),e.jsxs("div",{children:["Policy Profile: ",e.jsx("span",{className:"text-slate-100",children:String(x.activePolicyProfile||"none")})]}),e.jsxs("div",{children:["Offline-only: ",e.jsx("span",{className:"text-slate-100",children:x.offlineOnly?"true":"false"})]}),e.jsxs("div",{children:["Update Ring: ",e.jsx("span",{className:"text-slate-100",children:String(x.updateRing||"stable")})]}),e.jsxs("div",{children:["Signature: ",e.jsx("span",{className:"text-slate-100",children:String(p.signatureState||"unknown")})]})]})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold mb-2",children:"Appliance Operations"}),e.jsxs("div",{className:"space-y-1 text-[10px] font-mono text-slate-300",children:[e.jsxs("div",{children:["Support Ingest Bundles: ",e.jsx("span",{className:"text-slate-100",children:c})]}),e.jsxs("div",{children:["Fleet Nodes: ",e.jsx("span",{className:"text-slate-100",children:d.total})]}),e.jsxs("div",{children:["Healthy: ",e.jsx("span",{className:"text-slate-100",children:d.healthy})]}),e.jsxs("div",{children:["Degraded: ",e.jsx("span",{className:"text-slate-100",children:d.degraded})]}),e.jsxs("div",{children:["Critical: ",e.jsx("span",{className:"text-slate-100",children:d.critical})]}),e.jsxs("div",{children:["Offline: ",e.jsx("span",{className:"text-slate-100",children:d.offline})]})]})]})]}),e.jsx("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 text-[10px] font-mono text-slate-400",children:"Appliance mode narrows UX scope to operational controls. Security and proof controls remain enforced and cannot be bypassed by profile branding or appliance toggles."})]})]})]}):null}const Ua={founder:{canRunPolicyRollouts:!0,canRunRecovery:!0,canDeclareIncidents:!0,canManageFleet:!0,canManageAppliance:!0,canViewSalesSlice:!0,canEditNodeChainMissions:!0},operator:{canRunPolicyRollouts:!0,canRunRecovery:!0,canDeclareIncidents:!0,canManageFleet:!0,canManageAppliance:!0,canViewSalesSlice:!1,canEditNodeChainMissions:!0},support:{canRunPolicyRollouts:!1,canRunRecovery:!0,canDeclareIncidents:!0,canManageFleet:!0,canManageAppliance:!0,canViewSalesSlice:!0,canEditNodeChainMissions:!1},security:{canRunPolicyRollouts:!0,canRunRecovery:!0,canDeclareIncidents:!0,canManageFleet:!0,canManageAppliance:!0,canViewSalesSlice:!1,canEditNodeChainMissions:!1},sales:{canRunPolicyRollouts:!1,canRunRecovery:!1,canDeclareIncidents:!1,canManageFleet:!1,canManageAppliance:!1,canViewSalesSlice:!0,canEditNodeChainMissions:!1}};function Yv(t){const r=String(t||"").trim().toLowerCase();return r==="founder"||r==="operator"||r==="support"||r==="security"||r==="sales"?Ua[r]:Ua.operator}function Zv({role:t,onChange:r}){const n=String(t||"operator").toLowerCase(),s=Ua[n]||Ua.operator;return e.jsxs("section",{"data-testid":"role-switcher",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Role Switcher"}),e.jsxs("select",{"data-testid":"role-switcher-select",value:n,onChange:a=>r(a.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200",children:[e.jsx("option",{value:"founder",children:"Founder"}),e.jsx("option",{value:"operator",children:"Operator"}),e.jsx("option",{value:"support",children:"Support"}),e.jsx("option",{value:"security",children:"Security/Compliance"}),e.jsx("option",{value:"sales",children:"Sales/Success"})]}),e.jsx("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5 text-[9px] font-mono text-slate-400",children:Object.entries(s).map(([a,o])=>e.jsxs("div",{children:[a,": ",e.jsx("span",{className:o?"text-emerald-300":"text-slate-500",children:o?"yes":"no"})]},a))})]})}const Y0="neuralshell_shift_console_v1";function Xv(){if(typeof window>"u"||!window.localStorage)return{notes:"",queueDepth:0,pendingActions:[]};try{const t=JSON.parse(window.localStorage.getItem(Y0)||"{}");return{notes:String(t&&t.notes?t.notes:""),queueDepth:Number.isFinite(Number(t&&t.queueDepth))?Number(t.queueDepth):0,pendingActions:Array.isArray(t&&t.pendingActions)?t.pendingActions:[]}}catch{return{notes:"",queueDepth:0,pendingActions:[]}}}async function Qv(t){const n=new window.TextEncoder().encode(String(t||"")),s=await window.crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(s)).map(a=>a.toString(16).padStart(2,"0")).join("")}function ej({open:t,onClose:r,role:n,onChangeRole:s,fleetNodes:a=[],incidents:o=[]}){const[c,l]=i.useState(()=>Xv()),[u,x]=i.useState("");i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(Y0,JSON.stringify(c))},[c]);const p=async()=>{const d=Array.isArray(a)?a.slice(0,10).map(y=>y.nodeId):[],m={schema:"neuralshell_shift_summary_v1",generatedAt:new Date().toISOString(),activeRole:n,queueDepth:Number(c.queueDepth||0),pendingActions:Array.isArray(c.pendingActions)?c.pendingActions:[],handoffNotes:String(c.notes||"").split(/\r?\n/).map(y=>y.trim()).filter(Boolean),incidents:Array.isArray(o)?o.slice(-20):[],assignedNodes:d},f=await eo("neuralshell_shift_signing_v1"),b=await to(m,f.privateKeyPem),h=await Qv(pr(m)),g=await Tr(f.publicKeyPem);je(`neuralshell_shift_summary_${Date.now()}.signed.json`,{schema:"neuralshell_shift_summary_signed_v1",payload:m,hash:h,signature:b,signer:{publicKeyPem:f.publicKeyPem,fingerprint:g}}),X("shift.summary.exported",{role:n,queueDepth:m.queueDepth,assignedNodes:d.length},{source:"shift",severity:"info"}),x(`Signed shift summary exported (${g.slice(0,24)}...).`)};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[134] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"shift-console",className:"fixed inset-x-10 top-20 bottom-8 z-[135] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Shift Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Operator handoff, queue posture, and signed summary export."})]}),e.jsx("button",{type:"button","data-testid":"shift-console-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[320px_1fr]",children:[e.jsxs("div",{className:"p-3 border-r border-white/10 min-h-0 overflow-auto space-y-3",children:[e.jsx(Zv,{role:n,onChange:s}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Shift Queue"}),e.jsxs("label",{className:"text-[10px] font-mono text-slate-300 block",children:["Queue Depth",e.jsx("input",{"data-testid":"shift-queue-depth-input",type:"number",min:"0",value:c.queueDepth,onChange:d=>l(m=>({...m,queueDepth:Math.max(0,Number(d.target.value||0))})),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1"})]}),e.jsx("button",{type:"button","data-testid":"shift-add-pending-action-btn",onClick:()=>l(d=>({...d,pendingActions:[...d.pendingActions||[],`action-${Date.now()}`]})),className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"Add Pending Action"}),e.jsxs("div",{className:"max-h-36 overflow-auto space-y-1 pr-1",children:[(c.pendingActions||[]).map((d,m)=>e.jsx("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[9px] font-mono text-slate-300 break-all",children:d},`${d}-${m}`)),(!c.pendingActions||c.pendingActions.length===0)&&e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:"No pending actions."})]})]})]}),e.jsxs("div",{className:"p-3 min-h-0 overflow-auto space-y-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Handoff Notes"}),e.jsx("textarea",{"data-testid":"shift-handoff-notes-input",value:c.notes,onChange:d=>l(m=>({...m,notes:d.target.value})),className:"w-full min-h-36 rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200",placeholder:"Capture next shift context, blockers, and known risks..."})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Assigned Nodes / Incidents"}),e.jsxs("div",{className:"text-[10px] font-mono text-slate-400",children:["Assigned nodes: ",Array.isArray(a)?a.length:0]}),e.jsxs("div",{className:"text-[10px] font-mono text-slate-400",children:["Open incidents: ",Array.isArray(o)?o.length:0]})]}),e.jsx("button",{type:"button","data-testid":"shift-export-summary-btn",onClick:p,className:"px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100",children:"Export Signed Shift Summary"}),u&&e.jsx("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-[10px] font-mono text-emerald-100",children:u})]})]})]})]}):null}const tj=[{id:"provider_bridge_failure",title:"Provider Bridge Failure",steps:["Retry provider bridge probe.","Switch to safe policy profile if probe fails twice.","Capture diagnostics bundle and attach to incident."]},{id:"relay_failure_repeated",title:"Repeated Relay Failure",steps:["Disable relay path after threshold.","Force local-only mode.","Review relay channel mapping and retry once."]},{id:"proof_engine_stall",title:"Proof Engine Stall",steps:["Abort stalled proof run and capture stdout tail.","Run health probe before retry.","Escalate incident if second run stalls."]},{id:"policy_corruption",title:"Policy Corruption",steps:["Block policy apply and freeze rollout queue.","Restore known-good signed policy bundle.","Run policy verification before reopening rollout."]},{id:"update_verification_failure",title:"Update Verification Failure",steps:["Freeze update lane immediately.","Reject pending pack and keep current version.","Notify operator with evidence hash details."]},{id:"vault_access_failure",title:"Vault Access Failure",steps:["Lock runtime and block sensitive actions.","Prompt sealed recovery flow.","Require manual operator acknowledgement before unlock."]},{id:"fleet_node_degraded",title:"Fleet Node Degraded/Unreachable",steps:["Mark node degraded in fleet panel.","Attempt one health re-probe and capture delta.","Open incident if node stays degraded for next cycle."]}];function rj({onApply:t}){return e.jsxs("section",{"data-testid":"recovery-playbook-view",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Recovery Playbooks"}),e.jsx("div",{className:"max-h-64 overflow-auto space-y-2 pr-1",children:tj.map(r=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 p-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:r.title}),e.jsx("button",{type:"button","data-testid":`playbook-apply-${r.id}`,onClick:()=>{typeof t=="function"&&t(r)},className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"Apply"})]}),e.jsx("ul",{className:"mt-1 space-y-1 text-[9px] font-mono text-slate-400",children:r.steps.map((n,s)=>e.jsxs("li",{children:[s+1,". ",n]},`${r.id}-${s}`))})]},r.id))})]})}function nj({open:t,onClose:r,incidents:n=[],fleetNodes:s=[],onDeclare:a,onResolve:o,onApplyPlaybook:c,onTriggerSafeMode:l}){const[u,x]=i.useState("Runtime Incident"),[p,d]=i.useState("degraded"),[m,f]=i.useState([]),[b,h]=i.useState(""),g=Array.isArray(n)?n:[],y=g.find(w=>String(w.incidentId||"")===String(b||""))||g[0]||null,I=w=>{const j=String(w||"");j&&f(E=>E.includes(j)?E.filter(N=>N!==j):[...E,j])},A=()=>{if(typeof a!="function")return;const w=a({title:u,severity:p,affectedNodes:m});w&&w.incidentId&&h(w.incidentId)},C=()=>{y&&je(`neuralshell_incident_${y.incidentId}.json`,{exportedAt:new Date().toISOString(),incident:y})};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[136] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"incident-mode-panel",className:"fixed inset-x-8 top-16 bottom-6 z-[137] rounded-2xl border border-rose-300/35 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-rose-300 font-bold",children:"Incident Mode"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Declare incidents, capture timeline, and execute recovery playbooks."})]}),e.jsx("button",{type:"button","data-testid":"incident-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.95fr_1.05fr]",children:[e.jsxs("div",{className:"p-3 border-r border-white/10 min-h-0 overflow-auto space-y-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Declare Incident"}),e.jsx("input",{"data-testid":"incident-title-input",value:u,onChange:w=>x(w.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200"}),e.jsxs("select",{"data-testid":"incident-severity-select",value:p,onChange:w=>d(w.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200",children:[e.jsx("option",{value:"warning",children:"warning"}),e.jsx("option",{value:"degraded",children:"degraded"}),e.jsx("option",{value:"critical",children:"critical"})]}),e.jsx("div",{className:"max-h-36 overflow-auto space-y-1 pr-1",children:(Array.isArray(s)?s:[]).map(w=>e.jsxs("label",{className:"flex items-center gap-2 text-[9px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:m.includes(w.nodeId),onChange:()=>I(w.nodeId)}),w.displayName]},w.nodeId))}),e.jsx("button",{type:"button","data-testid":"incident-declare-btn",onClick:A,className:"w-full px-3 py-1.5 rounded border border-rose-300/35 bg-rose-500/10 text-[10px] uppercase tracking-[0.14em] font-mono text-rose-100",children:"Declare Incident"}),e.jsx("button",{type:"button","data-testid":"incident-trigger-safe-mode-btn",onClick:()=>{typeof l=="function"&&l()},className:"w-full px-3 py-1.5 rounded border border-amber-300/35 bg-amber-500/10 text-[10px] uppercase tracking-[0.14em] font-mono text-amber-100",children:"Trigger Safe Mode"})]}),e.jsx(rj,{onApply:w=>{typeof c=="function"&&c(w,y)}})]}),e.jsxs("div",{className:"p-3 min-h-0 overflow-auto space-y-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Incident Queue"}),e.jsxs("div",{className:"space-y-1 max-h-40 overflow-auto pr-1",children:[g.map(w=>e.jsxs("button",{type:"button","data-testid":`incident-row-${w.incidentId}`,onClick:()=>h(w.incidentId),className:`w-full rounded border px-2 py-1.5 text-left ${String(b||y&&y.incidentId||"")===String(w.incidentId)?"border-rose-300/35 bg-rose-500/10":"border-white/10 bg-black/25 hover:bg-white/10"}`,children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:w.title}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:[w.severity," · ",w.status]})]},w.incidentId)),g.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No incidents declared."})]})]}),y&&e.jsxs("section",{"data-testid":"incident-active-view",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:y.title}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:[y.incidentId," · ",y.severity," · ",y.status]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"incident-export-btn",onClick:C,className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"Export"}),e.jsx("button",{type:"button","data-testid":"incident-resolve-btn",onClick:()=>{typeof o=="function"&&o(y.incidentId)},className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-emerald-100",children:"Resolve"})]})]}),e.jsxs("div",{className:"max-h-48 overflow-auto space-y-1 pr-1",children:[(Array.isArray(y.timeline)?y.timeline:[]).slice(-120).reverse().map((w,j)=>e.jsxs("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[9px] font-mono text-slate-300",children:[e.jsxs("div",{children:[w.type," · ",w.source]}),e.jsx("div",{className:"text-slate-500",children:w.at})]},`${w.at}-${j}`)),(!y.timeline||y.timeline.length===0)&&e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:"No timeline events captured yet."})]})]})]})]})]})]}):null}function sj({rows:t=[]}){const r=Array.isArray(t)?t:[];return e.jsxs("section",{"data-testid":"policy-diff-panel",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Policy Diff Preview"}),e.jsxs("div",{className:"max-h-44 overflow-auto space-y-1 pr-1",children:[r.map(n=>e.jsxs("div",{className:"grid grid-cols-3 gap-2 rounded border border-amber-300/30 bg-amber-500/10 px-2 py-1 text-[10px] font-mono",children:[e.jsx("div",{className:"text-amber-100 break-all",children:String(n.key||"field")}),e.jsx("div",{className:"text-slate-300 break-all",children:String(n.before)}),e.jsx("div",{className:"text-slate-100 break-all",children:String(n.after)})]},n.key)),r.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No diff to apply."})]})]})}function aj({history:t=[],onRollback:r}){const n=Array.isArray(t)?t:[];return e.jsxs("section",{"data-testid":"rollback-history-view",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Rollout History"}),e.jsxs("div",{className:"max-h-48 overflow-auto space-y-1 pr-1",children:[n.map(s=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 p-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[10px] font-mono",children:[e.jsx("span",{className:"text-slate-100",children:String(s.policyProfile||s.policyId||"policy")}),e.jsx("span",{className:"text-slate-500",children:String(s.status||"pending")})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["nodes: ",(s.nodeIds||[]).length," · ",String(s.updatedAt||s.createdAt||"")]}),e.jsx("div",{className:"mt-1 flex justify-end",children:e.jsx("button",{type:"button","data-testid":`rollout-rollback-${s.rolloutId}`,onClick:()=>{typeof r=="function"&&r(s)},className:"px-2 py-1 rounded border border-amber-300/30 bg-amber-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-amber-100",children:"Rollback"})})]},s.rolloutId)),n.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No rollout history yet."})]})]})}function oj(t,r,n){const s=Array.isArray(t)?t:[],a=Array.isArray(r)?r:[],o=s.find(u=>a.includes(u.nodeId)),c=o?String(o.policyProfile||"none"):"none",l=String(n||"none");return c===l?[]:[{key:"policyProfile",before:c,after:l}]}function ij({open:t,onClose:r,fleet:n,history:s=[],onApplyRollout:a,onRollbackRollout:o}){const[c,l]=i.useState(""),[u,x]=i.useState(""),[p,d]=i.useState(null),[m,f]=i.useState([]),[b,h]=i.useState("immediate"),[g,y]=i.useState(""),I=Array.isArray(n&&n.nodes)?n.nodes:[],A=String(p&&p.payload&&(p.payload.policyProfile||p.payload.label||p.payload.policyId)?p.payload.policyProfile||p.payload.label||p.payload.policyId:""),C=i.useMemo(()=>oj(I,m,A),[I,A,m]),w=async N=>{const _=N&&N.target&&N.target.files?N.target.files[0]:null;if(_)try{const S=await pt(_),R=JSON.parse(String(S||"{}")),$=R&&R.payload&&typeof R.payload=="object"?R.payload:null,U=String(R&&R.signature?R.signature:""),P=String(R&&R.signer&&R.signer.publicKeyPem?R.signer.publicKeyPem:"");if(!$||!U||!P)throw new Error("Signed bundle requires payload/signature/public key.");if(!await Mt($,U,P))throw new Error("Unsigned or invalid policy bundle rejected.");d(R),l(`Verified policy bundle: ${String($.policyProfile||$.label||$.policyId||"policy")}`),x("")}catch(S){d(null),l(""),x(S&&S.message?S.message:String(S))}finally{N&&N.target&&(N.target.value="")}},j=N=>{const _=String(N||"");f(S=>S.includes(_)?S.filter(R=>R!==_):[...S,_])},E=()=>{if(!p){x("Load a verified signed bundle first.");return}if(!m.length){x("Select at least one node.");return}typeof a=="function"&&(a({bundle:p,nodeIds:m,mode:b,scheduledFor:g}),x(""))};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[138] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"policy-rollout-console",className:"fixed inset-x-8 top-20 bottom-8 z-[139] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Policy Rollout Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Signed policy rollout preview, apply, verify, and rollback history."})]}),e.jsx("button",{type:"button","data-testid":"policy-rollout-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.95fr_1.05fr]",children:[e.jsxs("div",{className:"p-3 border-r border-white/10 min-h-0 overflow-auto space-y-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Signed Bundle Input"}),e.jsxs("label",{className:"inline-flex items-center px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono uppercase tracking-[0.12em] text-cyan-100 cursor-pointer",children:["Import Signed Policy",e.jsx("input",{"data-testid":"policy-rollout-import-input",type:"file",accept:".json,application/json",className:"hidden",onChange:w})]}),c&&e.jsx("div",{className:"text-[10px] font-mono text-emerald-200",children:c}),u&&e.jsx("div",{"data-testid":"policy-rollout-error",className:"text-[10px] font-mono text-rose-200",children:u})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Target Nodes"}),e.jsxs("div",{className:"max-h-40 overflow-auto space-y-1 pr-1",children:[I.map(N=>e.jsxs("label",{className:"flex items-center gap-2 text-[9px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:m.includes(N.nodeId),onChange:()=>j(N.nodeId)}),N.displayName]},N.nodeId)),I.length===0&&e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:"No fleet nodes available."})]}),e.jsxs("div",{className:"space-y-1 text-[10px] font-mono text-slate-300",children:[e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"radio",checked:b==="immediate",onChange:()=>h("immediate")}),"Immediate apply"]}),e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"radio",checked:b==="scheduled",onChange:()=>h("scheduled")}),"Schedule rollout"]}),b==="scheduled"&&e.jsx("input",{"data-testid":"policy-rollout-scheduled-input",type:"datetime-local",value:g,onChange:N=>y(N.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200"})]}),e.jsx("button",{type:"button","data-testid":"policy-rollout-apply-btn",onClick:E,className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100",children:"Apply Rollout"})]})]}),e.jsxs("div",{className:"p-3 min-h-0 overflow-auto space-y-3",children:[e.jsx(sj,{rows:C}),e.jsx(aj,{history:s,onRollback:N=>{typeof o=="function"&&o(N)}})]})]})]})]}):null}function lj({onPackVerified:t}){const[r,n]=i.useState(""),[s,a]=i.useState(""),[o,c]=i.useState(null),l=async u=>{const x=u&&u.target&&u.target.files?u.target.files[0]:null;if(x)try{const p=await pt(x),d=JSON.parse(String(p||"{}")),m=d&&d.payload&&typeof d.payload=="object"?d.payload:null,f=String(d&&d.signature?d.signature:""),b=String(d&&d.signer&&d.signer.publicKeyPem?d.signer.publicKeyPem:"");if(!m||!f||!b)throw new Error("Update pack missing payload/signature/public key.");if(!await Mt(m,f,b))throw new Error("Unverified update pack rejected.");c(d),n(`Verified update pack ${String(m.version||"unknown")}/${String(m.ring||"standard")}.`),a(""),typeof t=="function"&&t(d)}catch(p){c(null),n(""),a(p&&p.message?p.message:String(p))}finally{u&&u.target&&(u.target.value="")}};return e.jsxs("section",{"data-testid":"update-pack-manager",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Offline Update Pack Manager"}),e.jsxs("label",{className:"inline-flex items-center px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono uppercase tracking-[0.12em] text-cyan-100 cursor-pointer",children:["Import Signed Pack",e.jsx("input",{"data-testid":"update-pack-import-input",type:"file",accept:".json,application/json",className:"hidden",onChange:l})]}),r&&e.jsx("div",{className:"text-[10px] font-mono text-emerald-200",children:r}),s&&e.jsx("div",{"data-testid":"update-pack-error",className:"text-[10px] font-mono text-rose-200",children:s}),o&&e.jsxs("div",{"data-testid":"update-pack-verified",className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px] font-mono text-slate-300",children:["Pack ID: ",String(o&&o.payload&&o.payload.packId?o.payload.packId:o&&o.payload&&o.payload.version?`pack-${o.payload.version}`:"n/a")]})]})}const Tl=["canary","standard","delayed","locked"];function cj(t){return(Array.isArray(t)?t:[]).reduce((n,s)=>{const a=String(s&&s.updateRing?s.updateRing:"standard").toLowerCase(),o=Tl.includes(a)?a:"standard";return n[o]+=1,n},{canary:0,standard:0,delayed:0,locked:0})}function dj({fleet:t,verifiedPack:r,onAssignPack:n}){const[s,a]=i.useState("canary"),[o,c]=i.useState([]),l=Array.isArray(t&&t.nodes)?t.nodes:[],u=cj(l),x=d=>{const m=String(d||"");c(f=>f.includes(m)?f.filter(b=>b!==m):[...f,m])},p=()=>{!r||!r.payload||o.length&&typeof n=="function"&&n({nodeIds:o,ring:s,packId:String(r.payload.packId||`pack-${r.payload.version||"unknown"}`),version:String(r.payload.version||"unknown")})};return e.jsxs("section",{"data-testid":"update-ring-console",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Update Ring Console"}),e.jsx("div",{className:"grid grid-cols-4 gap-1 text-[9px] font-mono",children:Tl.map(d=>e.jsxs("div",{className:"rounded border border-white/10 bg-black/30 px-1.5 py-1 text-slate-300",children:[d,": ",u[d]]},d))}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:"Verified pack required before assignment. Unverified packs cannot be applied."}),e.jsx("select",{"data-testid":"update-ring-target-select",value:s,onChange:d=>a(d.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200",children:Tl.map(d=>e.jsx("option",{value:d,children:d},d))}),e.jsxs("div",{className:"max-h-40 overflow-auto space-y-1 pr-1",children:[l.map(d=>e.jsxs("label",{className:"flex items-center gap-2 text-[9px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:o.includes(d.nodeId),onChange:()=>x(d.nodeId)}),d.displayName," (",d.updateRing||"standard",")"]},d.nodeId)),l.length===0&&e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:"No nodes available."})]}),e.jsx("button",{type:"button","data-testid":"update-ring-assign-btn",disabled:!r||!r.payload,onClick:p,className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.14em] text-cyan-100 disabled:opacity-50",children:"Assign Pack To Ring"})]})}function uj({open:t,onClose:r,fleet:n}){const[s,a]=i.useState(null);return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[140] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"offline-update-console",className:"fixed inset-x-10 top-20 bottom-8 z-[141] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Offline Update Packs"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Import verified packs, assign rings, and promote deliberately."})]}),e.jsx("button",{type:"button","data-testid":"offline-update-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-1 xl:grid-cols-2 gap-3 p-3 overflow-auto",children:[e.jsx(lj,{onPackVerified:o=>{a(o),X("update.pack.verified",{version:String(o&&o.payload&&o.payload.version?o.payload.version:"unknown"),ring:String(o&&o.payload&&o.payload.ring?o.payload.ring:"standard")},{source:"updates",severity:"info"})}}),e.jsx(dj,{fleet:n,verifiedPack:s,onAssignPack:o=>{n&&typeof n.assignUpdatePack=="function"&&(n.assignUpdatePack(o.nodeIds,{packId:o.packId,ring:o.ring,version:o.version}),X("update.pack.assigned",{packId:o.packId,ring:o.ring,targets:o.nodeIds.length},{source:"updates",severity:"info"}))}})]})]})]}):null}const ws=[{missionId:"nightly_fleet_health_sweep",label:"Nightly Fleet Health Sweep",description:"Run nightly health sweep and summarize degraded nodes.",target:"fleet",defaultScheduleMinutes:1440,defaultDryRun:!1,steps:["collect_fleet_snapshot","score_runtime_health","emit_summary"]},{missionId:"post_policy_recovery_export",label:"Post-Policy Recovery Export",description:"After policy rollout, export recovery bundle evidence.",target:"fleet",defaultScheduleMinutes:60,defaultDryRun:!0,steps:["verify_policy_rollout","export_recovery_bundle","attach_audit_record"]},{missionId:"weekly_release_truth_audit",label:"Weekly Release Truth Audit",description:"Run weekly release truth checks and report drift.",target:"fleet",defaultScheduleMinutes:10080,defaultDryRun:!0,steps:["run_release_truth_verify","compare_last_report","raise_alert_if_drift"]},{missionId:"degraded_node_incident_trigger",label:"Degraded Node Incident Trigger",description:"Open incident mode when degraded fleet threshold is exceeded.",target:"fleet",defaultScheduleMinutes:15,defaultDryRun:!0,steps:["detect_degraded_nodes","open_incident_mode","assign_operator"]},{missionId:"proof_pass_relay_summary",label:"Proof-Pass Relay Summary",description:"After proof pass, relay summary to approved appliance queue.",target:"node",defaultScheduleMinutes:30,defaultDryRun:!0,steps:["detect_proof_pass","compose_summary","relay_to_approved_queue"]},{missionId:"update_fail_freeze_notify",label:"Update Fail Freeze + Notify",description:"Freeze node updates and alert operator on update verification failure.",target:"node",defaultScheduleMinutes:10,defaultDryRun:!1,steps:["detect_update_verification_failure","freeze_update_lane","notify_operator"]}];class pj{constructor(r=[],n={}){this.hooks=n,this.schedules=Array.isArray(r)?r:[],this.history=[],this.timers=new Map}setSchedules(r){this.schedules=Array.isArray(r)?r:[],this.restart()}getSchedules(){return this.schedules.slice()}getHistory(){return this.history.slice(-500)}restart(){this.stop(),this.start()}start(){this.stop(),this.schedules.forEach(r=>{if(!r||!r.enabled)return;const n=Number(r.intervalMs||0);if(!Number.isFinite(n)||n<1e3)return;const s=window.setInterval(()=>{this.runScheduledMission(r).catch(()=>{})},n);this.timers.set(String(r.missionId||""),s)})}stop(){Array.from(this.timers.values()).forEach(r=>window.clearInterval(r)),this.timers.clear()}async runMission(r,n={}){const s=new Date().toISOString(),a=!!n.dryRun,o={runId:`mission-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,missionId:String(r&&r.missionId?r.missionId:"mission"),label:String(r&&r.label?r.label:"Mission"),target:r&&r.target?r.target:"fleet",targetNodeIds:Array.isArray(n.targetNodeIds)?n.targetNodeIds:[],dryRun:a,status:"completed",startedAt:s,finishedAt:new Date().toISOString(),detail:a?"Dry-run complete. No side effects applied.":"Mission completed."};return this.history.push(o),this.history=this.history.slice(-500),this.hooks.onRun&&await Promise.resolve(this.hooks.onRun(o)),o}cancelRun(r){this.history=this.history.map(n=>String(n.runId||"")!==String(r||"")?n:{...n,status:"cancelled",finishedAt:new Date().toISOString(),detail:"Mission run cancelled."})}async runScheduledMission(r){const n=String(r&&r.missionId?r.missionId:"");if(!n)return;const s={missionId:n,label:n,description:"scheduled mission",target:r&&r.targetNodeIds&&r.targetNodeIds.length?"node":"fleet",defaultScheduleMinutes:Math.max(1,Math.round(Number(r.intervalMs||6e4)/6e4)),defaultDryRun:!!r.dryRun,steps:[]};await this.runMission(s,{dryRun:!!r.dryRun,targetNodeIds:r.targetNodeIds})}}function mj({history:t=[],onCancel:r}){const n=Array.isArray(t)?t:[];return e.jsxs("section",{"data-testid":"mission-history-panel",className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-cyan-300 font-bold",children:"Mission History"}),e.jsxs("div",{className:"max-h-56 overflow-auto space-y-1 pr-1",children:[n.map(s=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 p-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[10px] font-mono",children:[e.jsx("span",{className:"text-slate-100",children:s.label}),e.jsx("span",{className:"text-slate-500",children:s.status})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:[s.missionId," · ",s.startedAt]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:s.detail}),e.jsx("div",{className:"mt-1 flex justify-end",children:e.jsx("button",{type:"button","data-testid":`mission-cancel-${s.runId}`,onClick:()=>{typeof r=="function"&&r(s.runId)},className:"px-2 py-1 rounded border border-amber-300/30 bg-amber-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-amber-100",children:"Cancel"})})]},s.runId)),n.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No missions run yet."})]})]})}const Z0="neuralshell_nodechain_mission_schedules_v1";function xj(){if(typeof window>"u"||!window.localStorage)return[];try{const t=JSON.parse(window.localStorage.getItem(Z0)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function fj(t,r=1){const n=Number(t);return Number.isFinite(n)?n:r}function bj({open:t,onClose:r,fleet:n,onOpenIncidentMode:s}){const[a,o]=i.useState(()=>xj()),[c,l]=i.useState(()=>String(ws[0]&&ws[0].missionId||"")),[u,x]=i.useState([]),[p,d]=i.useState(!0),[m,f]=i.useState(30),[b,h]=i.useState(!1),[g,y]=i.useState([]),I=i.useRef(null);i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(Z0,JSON.stringify(a))},[a]),i.useEffect(()=>{const _=new pj(a,{onRun:S=>{y(R=>[S,...Array.isArray(R)?R:[]].slice(0,300)),X("nodechain.mission.run",{missionId:S.missionId,dryRun:S.dryRun,status:S.status},{source:"nodechain-missions",severity:S.dryRun?"info":"warning"}),!S.dryRun&&S.missionId==="degraded_node_incident_trigger"&&typeof s=="function"&&s()}});return I.current=_,_.start(),()=>{_.stop(),I.current=null}},[s,a]);const A=i.useMemo(()=>ws.find(_=>String(_.missionId||"")===String(c||""))||null,[c]),C=Array.isArray(n&&n.nodes)?n.nodes:[],w=_=>{const S=String(_||"");x(R=>R.includes(S)?R.filter($=>$!==S):[...R,S])},j=async()=>{!I.current||!A||await I.current.runMission(A,{dryRun:p,targetNodeIds:u})},E=()=>{if(!A)return;const _=String(A.missionId||""),S={missionId:_,enabled:!!b,intervalMs:Math.max(1e3,Math.round(fj(m,1)*6e4)),dryRun:!!p,targetNodeIds:u.slice()};o(R=>{const $=Array.isArray(R)?R:[];return $.some(P=>String(P.missionId||"")===_)?$.map(P=>String(P.missionId||"")===_?S:P):[...$,S]})},N=()=>{if(!A)return;const _=String(A.missionId||"");o(S=>Array.isArray(S)?S.map(R=>String(R.missionId||"")===_?{...R,enabled:!1}:R):S)};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[142] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"mission-scheduler",className:"fixed inset-x-8 top-20 bottom-8 z-[143] rounded-2xl border border-cyan-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"NodeChain Mission Scheduler"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Template-driven orchestration with dry-run, schedules, and history."})]}),e.jsx("button",{type:"button","data-testid":"mission-scheduler-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.95fr_1.05fr]",children:[e.jsxs("div",{className:"p-3 border-r border-white/10 min-h-0 overflow-auto space-y-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Mission Template"}),e.jsx("select",{"data-testid":"mission-template-select",value:c,onChange:_=>{l(_.target.value);const S=ws.find(R=>String(R.missionId||"")===String(_.target.value||""));S&&(d(!!S.defaultDryRun),f(Number(S.defaultScheduleMinutes||30)))},className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-200",children:ws.map(_=>e.jsx("option",{value:_.missionId,children:_.label},_.missionId))}),A&&e.jsx("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px] font-mono text-slate-400",children:A.description}),e.jsxs("label",{className:"inline-flex items-center gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:p,onChange:_=>d(!!_.target.checked)}),"Dry-run"]}),e.jsxs("label",{className:"inline-flex items-center gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:b,onChange:_=>h(!!_.target.checked)}),"Schedule enabled"]}),e.jsxs("label",{className:"text-[10px] font-mono text-slate-300 block",children:["Interval Minutes",e.jsx("input",{"data-testid":"mission-interval-input",type:"number",min:"1",value:m,onChange:_=>f(Math.max(1,Number(_.target.value||1))),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1"})]})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/25 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Target Nodes"}),e.jsxs("div",{className:"max-h-36 overflow-auto space-y-1 pr-1",children:[C.map(_=>e.jsxs("label",{className:"flex items-center gap-2 text-[9px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:u.includes(_.nodeId),onChange:()=>w(_.nodeId)}),_.displayName]},_.nodeId)),C.length===0&&e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:"No nodes in fleet."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"mission-run-now-btn",onClick:j,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"Run Now"}),e.jsx("button",{type:"button","data-testid":"mission-save-schedule-btn",onClick:E,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-cyan-100",children:"Save Schedule"}),e.jsx("button",{type:"button","data-testid":"mission-pause-schedule-btn",onClick:N,className:"px-2.5 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[9px] uppercase tracking-[0.12em] font-mono text-amber-100",children:"Pause"})]})]})]}),e.jsx("div",{className:"p-3 min-h-0 overflow-auto space-y-3",children:e.jsx(mj,{history:g,onCancel:_=>{I.current&&(I.current.cancelRun(_),y(I.current.getHistory().slice().reverse()))}})})]})]})]}):null}const hu="neuralshell_airgap_transfer_chain_v1",gu="neuralshell_airgap_import_checklist_v1",yu="neuralshell_airgap_export_checklist_v1",hj="neuralshell_airgap_activated_artifacts_v1",vs=[{id:"import-media-serial",label:"Validate transfer media serial and seal record."},{id:"import-hash-verify",label:"Verify hash and signature before ingest."},{id:"import-quarantine",label:"Quarantine unverified inbound artifacts."},{id:"import-dual-approval",label:"Record dual-operator approval for activation."}],wa=[{id:"export-class-label",label:"Assign courier class and sensitivity label."},{id:"export-manifest-sign",label:"Sign outbound manifest with sender identity."},{id:"export-ledger-record",label:"Record handoff in offline transfer ledger."},{id:"export-receipt-confirm",label:"Capture receiver receipt hash and close transfer."}];function Vi(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function va(t,r){typeof window>"u"||!window.localStorage||window.localStorage.setItem(t,JSON.stringify(r))}function wu(t,r){const n=r&&typeof r=="object"?r:{},s={};return t.forEach(a=>{s[a.id]=!!n[a.id]}),s}function gj(t){const r=String(t&&t.schema?t.schema:"").toLowerCase();return r.includes("update_pack")?"update_pack":r.includes("recovery_bundle")?"evidence_bundle":r.includes("airgap_bundle")?"docs_bundle":r.includes("certificate")||r.includes("cert")?"certificate_bundle":r.includes("trust")?"trust_bundle":"unknown"}async function yj(t){const r=new window.TextEncoder().encode(String(t||"")),n=await window.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}function vu(t,r){return r.reduce((n,s)=>n+(t[s.id]?1:0),0)}function wj({open:t,onClose:r,locked:n=!1,onToggleLocked:s}){const[a,o]=i.useState(()=>{const j=Vi(hu,[]);return Array.isArray(j)?j:[]}),[c,l]=i.useState(()=>wu(vs,Vi(gu,{}))),[u,x]=i.useState(()=>wu(wa,Vi(yu,{}))),[p,d]=i.useState(""),[m,f]=i.useState(""),[b,h]=i.useState(!1);i.useEffect(()=>{va(hu,a)},[a]),i.useEffect(()=>{va(gu,c)},[c]),i.useEffect(()=>{va(yu,u)},[u]);const g=vu(c,vs),y=vu(u,wa),I=a.filter(j=>j.direction==="import"&&j.verified),A=a.filter(j=>j.direction==="import"&&!j.verified),C=async j=>{const E=j&&j.target&&j.target.files?j.target.files[0]:null;if(E){h(!0);try{const N=await pt(E),_=JSON.parse(String(N||"{}")),S=_&&_.payload&&typeof _.payload=="object"?_.payload:null,R=String(_&&_.signature?_.signature:""),$=String(_&&_.signer&&_.signer.publicKeyPem?_.signer.publicKeyPem:""),U=String(_&&_.hash?_.hash:"").trim().toLowerCase();if(!S||!R||!$||!U)throw new Error("Artifact missing payload/signature/public key/hash.");const P=await Mt(S,R,$),D=await yj(pr(S)),F=!!(P&&D===U),J=String(_&&_.direction?_.direction:"import").toLowerCase()==="export"?"export":"import",ee={transferId:`airgap-transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,at:new Date().toISOString(),sourceName:String(E.name||"artifact.json"),direction:J,artifactType:gj(S),classLabel:String(_&&_.classLabel?_.classLabel:"standard"),signerFingerprint:String(_&&_.signer&&_.signer.fingerprint?_.signer.fingerprint:""),hash:U,computedHash:D,verified:F,quarantineState:F?"released":"quarantined",schema:String(S&&S.schema?S.schema:"unknown")};o(ie=>[ee,...Array.isArray(ie)?ie:[]].slice(0,400)),d(F?`Verified ${ee.sourceName} and staged for activation.`:`Quarantined ${ee.sourceName}. Verification failed.`),f(F?"":"Imported artifact failed verification and remains quarantined.")}catch(N){d(""),f(N&&N.message?N.message:String(N))}finally{h(!1),j&&j.target&&(j.target.value="")}}},w=()=>{if(!I.length){f("No verified import artifacts available to activate.");return}if(gString(E.transferId));va(hj,{activatedAt:new Date().toISOString(),transferIds:j}),o(E=>Array.isArray(E)?E.map(N=>j.includes(String(N.transferId))?{...N,quarantineState:"released"}:N):E),!n&&typeof s=="function"&&s(!0),d(`Activated ${j.length} verified artifact(s) for air-gapped runtime.`),f("")};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[142] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"airgap-operations-center",className:"fixed inset-x-8 top-16 bottom-6 z-[143] rounded-2xl border border-slate-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.72)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-slate-200 font-bold",children:"Air-Gapped Operations Center"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Controlled import/export station with verification-first activation and sealed-network lock posture."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"airgap-lock-toggle-btn",onClick:()=>{typeof s=="function"&&s(!n)},className:`px-2.5 py-1.5 rounded border text-[10px] font-mono uppercase tracking-[0.12em] ${n?"border-slate-300/35 bg-slate-500/20 text-slate-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100"}`,children:n?"AirGap Locked":"Enable AirGap Lock"}),e.jsx("button",{type:"button","data-testid":"airgap-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.95fr_1.05fr]",children:[e.jsxs("div",{className:"p-3 border-r border-white/10 min-h-0 overflow-auto space-y-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Import / Export Station"}),e.jsx("div",{className:"text-[10px] text-slate-300",children:"Every inbound or outbound artifact must be recorded in the transfer chain with a verifiable signature/hash result."}),e.jsxs("label",{className:"inline-flex items-center px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono uppercase tracking-[0.12em] text-cyan-100 cursor-pointer",children:["Ingest Signed Artifact",e.jsx("input",{type:"file","data-testid":"airgap-import-input",accept:".json,application/json",className:"hidden",onChange:C})]}),e.jsx("button",{type:"button","data-testid":"airgap-activate-imports-btn",onClick:w,disabled:b,className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100 disabled:opacity-60",children:"Activate Verified Imports"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-[9px] font-mono",children:[e.jsxs("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-emerald-200",children:["verified imports: ",I.length]}),e.jsxs("div",{className:"rounded border border-amber-300/30 bg-amber-500/10 px-2 py-1 text-amber-200",children:["quarantined imports: ",A.length]})]})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:["Import Checklist (",g,"/",vs.length,")"]}),vs.map(j=>e.jsxs("label",{className:"flex items-start gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:!!c[j.id],onChange:E=>l(N=>({...N,[j.id]:!!E.target.checked}))}),e.jsx("span",{children:j.label})]},j.id))]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:["Export Checklist (",y,"/",wa.length,")"]}),wa.map(j=>e.jsxs("label",{className:"flex items-start gap-2 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:!!u[j.id],onChange:E=>x(N=>({...N,[j.id]:!!E.target.checked}))}),e.jsx("span",{children:j.label})]},j.id))]}),e.jsxs("section",{className:"rounded-xl border border-slate-300/25 bg-slate-500/10 p-3",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-300",children:["Network policy: ",e.jsx("span",{className:"text-slate-100 font-semibold",children:"no hidden external network assumptions"})]}),e.jsx("div",{className:"text-[9px] text-slate-400 font-mono mt-1",children:"Critical activation paths require explicit verification results and checklist completion before release."})]})]}),e.jsxs("div",{className:"p-3 min-h-0 overflow-auto space-y-3",children:[e.jsxs("section",{"data-testid":"airgap-transfer-ledger",className:"rounded-xl border border-white/10 bg-black/20 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Transfer Chain Ledger"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Inspectable record of import/export artifacts crossing the air-gap station."})]}),e.jsx("div",{className:`px-2 py-1 rounded border text-[9px] font-mono uppercase ${n?"border-slate-300/30 bg-slate-500/15 text-slate-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100"}`,children:n?"locked":"ready"})]}),e.jsxs("div",{className:"max-h-96 overflow-auto pr-1 space-y-1.5",children:[a.map(j=>e.jsxs("article",{className:`rounded-lg border px-2 py-1.5 ${j.verified?"border-emerald-300/30 bg-emerald-500/10":"border-rose-300/40 bg-rose-500/10"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:j.sourceName}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:new Date(j.at).toLocaleString()})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-300",children:[j.direction," · ",j.artifactType," · ",j.classLabel]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["schema ",j.schema," · ",j.verified?"verified/released":"quarantined"]})]},j.transferId)),a.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No transfer entries yet. Ingest a signed artifact to start the ledger."})]})]}),p&&e.jsx("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-[10px] font-mono text-emerald-100",children:p}),m&&e.jsx("div",{"data-testid":"airgap-import-error",className:"rounded border border-rose-300/40 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-100",children:m})]})]})]})]}):null}async function vj(t){const r=new window.TextEncoder().encode(String(t||"")),n=await window.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}function ju(t,r){const n=new Date(String(t||new Date().toISOString())),s=Number.isNaN(n.getTime())?new Date:n;return s.setUTCDate(s.getUTCDate()+Math.max(1,Number(r||1))),s.toISOString()}function jj(t){const r=new Date(String(t||"")).getTime();if(!Number.isFinite(r))return"unknown";const n=r-Date.now();return n<=0?"expired":n<=1e3*60*60*24*30?"expiring":"healthy"}function kj({caRecord:t,certificates:r,revokedCertificateIds:n,onUpdateCA:s,onUpdateCertificates:a,onUpdateRevocations:o}){const[c,l]=i.useState("Node Alpha"),[u,x]=i.useState("node-alpha"),[p,d]=i.useState("node"),[m,f]=i.useState(365),[b,h]=i.useState(""),[g,y]=i.useState(""),[I,A]=i.useState(!1),C=Array.isArray(r)?r:[],w=Array.isArray(n)?n:[],j=async()=>{A(!0);try{const S=await eo("neuralshell_pki_local_ca_v1"),R=await Tr(S.publicKeyPem),$={schema:"neuralshell_local_ca_v1",caId:String(t&&t.caId?t.caId:`ca-${Date.now()}`),commonName:"ProofForge Local Trust CA",createdAt:String(t&&t.createdAt?t.createdAt:new Date().toISOString()),rotatedAt:new Date().toISOString(),expiresAt:ju(new Date().toISOString(),3650),keyAlgorithm:"ECDSA_P256",publicKeyPem:S.publicKeyPem,privateKeyPem:S.privateKeyPem,fingerprint:R,nextSerial:Number(t&&t.nextSerial?t.nextSerial:1)};s($),h("Local CA ready for certificate issuance."),y("")}catch(S){h(""),y(S&&S.message?S.message:String(S))}finally{A(!1)}},E=async()=>{if(!(t&&t.privateKeyPem&&t.publicKeyPem)){y("Initialize local CA before issuing certificates.");return}A(!0);try{const S=Number(t.nextSerial||1),R={schema:"neuralshell_trust_certificate_v1",serialNumber:`NS-${String(S).padStart(8,"0")}`,kind:String(p||"node"),subjectName:String(c||"Unnamed Subject"),subjectId:String(u||`subject-${S}`),issuedAt:new Date().toISOString(),expiresAt:ju(new Date().toISOString(),Number(m||365)),issuedByCaId:String(t.caId||""),issuedByFingerprint:String(t.fingerprint||""),binding:{rolloutPolicyBinding:p==="fleet"||p==="org",evidenceExchangeBinding:p==="node"||p==="appliance"||p==="fleet"}},$=await to(R,t.privateKeyPem),U=await vj(pr(R));if(!await Mt(R,$,t.publicKeyPem))throw new Error("Issued certificate failed local signature verification.");const D={certificateId:`cert-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,...R,hash:U,signature:$,status:"active"};a([D,...C].slice(0,600)),s({...t,nextSerial:S+1}),h(`Certificate issued: ${D.serialNumber}`),y("")}catch(S){h(""),y(S&&S.message?S.message:String(S))}finally{A(!1)}},N=async S=>{l(String(S.subjectName||"Rotated Subject")),x(String(S.subjectId||"rotated-subject")),d(String(S.kind||"node")),await E()},_=S=>{const R=String(S||"");R&&(w.includes(R)||(o([R,...w]),a(C.map($=>String($.certificateId||"")===R?{...$,status:"revoked",revokedAt:new Date().toISOString(),revokedReason:"manual-revocation"}:$)),h(`Certificate revoked: ${R}`),y("")))};return e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Certificate Lifecycle"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Issue, rotate, revoke, and verify node/appliance/fleet/org certificates."})]}),e.jsx("button",{type:"button","data-testid":"trustfabric-init-ca-btn",onClick:j,disabled:I,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100 disabled:opacity-60",children:t?"Rotate CA Key":"Initialize Local CA"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-[10px] font-mono",children:[e.jsxs("label",{className:"space-y-1",children:[e.jsx("span",{className:"text-slate-400",children:"Subject Name"}),e.jsx("input",{"data-testid":"trustfabric-subject-name-input",value:c,onChange:S=>l(S.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsxs("label",{className:"space-y-1",children:[e.jsx("span",{className:"text-slate-400",children:"Subject ID"}),e.jsx("input",{"data-testid":"trustfabric-subject-id-input",value:u,onChange:S=>x(S.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsxs("label",{className:"space-y-1",children:[e.jsx("span",{className:"text-slate-400",children:"Certificate Kind"}),e.jsxs("select",{"data-testid":"trustfabric-kind-select",value:p,onChange:S=>d(S.target.value),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100",children:[e.jsx("option",{value:"node",children:"node"}),e.jsx("option",{value:"appliance",children:"appliance"}),e.jsx("option",{value:"fleet",children:"fleet"}),e.jsx("option",{value:"org",children:"org"})]})]}),e.jsxs("label",{className:"space-y-1",children:[e.jsx("span",{className:"text-slate-400",children:"Validity (days)"}),e.jsx("input",{"data-testid":"trustfabric-validity-input",type:"number",min:"1",max:"3650",value:m,onChange:S=>f(Number(S.target.value||365)),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]})]}),e.jsx("button",{type:"button","data-testid":"trustfabric-issue-cert-btn",disabled:I,onClick:E,className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100 disabled:opacity-60",children:"Issue Certificate"}),e.jsxs("div",{className:"space-y-1 max-h-64 overflow-auto pr-1",children:[C.map(S=>{const R=w.includes(String(S.certificateId||""))?"revoked":jj(S.expiresAt);return e.jsxs("article",{className:`rounded border px-2 py-1.5 ${R==="revoked"||R==="expired"?"border-rose-300/40 bg-rose-500/10":R==="expiring"?"border-amber-300/35 bg-amber-500/10":"border-emerald-300/30 bg-emerald-500/10"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-100",children:[S.serialNumber," · ",S.subjectName]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:S.kind})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["expires ",new Date(S.expiresAt).toLocaleDateString()," · ",R]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("button",{type:"button","data-testid":`trustfabric-rotate-${S.certificateId}`,onClick:()=>N(S),className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono text-cyan-100",children:"rotate"}),e.jsx("button",{type:"button","data-testid":`trustfabric-revoke-${S.certificateId}`,onClick:()=>_(S.certificateId),className:"px-2 py-1 rounded border border-rose-300/35 bg-rose-500/10 text-[9px] font-mono text-rose-100",children:"revoke"})]})]},S.certificateId)}),C.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No certificates issued yet."})]}),b&&e.jsx("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-[10px] font-mono text-emerald-100",children:b}),g&&e.jsx("div",{"data-testid":"trustfabric-error",className:"rounded border border-rose-300/40 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-100",children:g})]})}function Nj(t){const r=new Date(String(t||"")).getTime();if(!Number.isFinite(r))return"expired";const n=r-Date.now();return n<=0?"expired":n<=1e3*60*60*24*30?"expiring":"healthy"}function Sj({caRecord:t,certificates:r,revokedCertificateIds:n}){const s=Array.isArray(r)?r:[],a=Array.isArray(n)?n:[],[o,c]=i.useState({});i.useEffect(()=>{let u=!0;return(async()=>{const p={};for(const d of s){const m=String(d&&d.certificateId?d.certificateId:"");if(!m)continue;const f={schema:d.schema,serialNumber:d.serialNumber,kind:d.kind,subjectName:d.subjectName,subjectId:d.subjectId,issuedAt:d.issuedAt,expiresAt:d.expiresAt,issuedByCaId:d.issuedByCaId,issuedByFingerprint:d.issuedByFingerprint,binding:d.binding&&typeof d.binding=="object"?d.binding:{}},b=!!(t&&t.publicKeyPem)&&await Mt(f,String(d.signature||""),String(t.publicKeyPem||"")),h=a.includes(m),g=Nj(d.expiresAt);p[m]={signatureValid:b,revoked:h,expiry:g,ok:b&&!h&&g!=="expired"}}u&&c(p)})(),()=>{u=!1}},[t,s,a]);const l=i.useMemo(()=>{const u=Object.values(o);return{total:s.length,healthy:u.filter(x=>x.ok).length,expiring:u.filter(x=>x.expiry==="expiring").length,revoked:u.filter(x=>x.revoked).length}},[s.length,o]);return e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Trust Chain Viewer"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Certificate path state for nodes, appliances, fleets, and org relationships."})]}),e.jsx("button",{type:"button","data-testid":"trustchain-export-btn",onClick:()=>{je("neuralshell_trust_chain_view.json",{exportedAt:new Date().toISOString(),ca:t||null,certificates:s,revocations:a,verificationMap:o})},className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Export"})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-2 text-[9px] font-mono",children:[e.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-2 py-1 text-slate-300",children:["total ",l.total]}),e.jsxs("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-emerald-200",children:["healthy ",l.healthy]}),e.jsxs("div",{className:"rounded border border-amber-300/30 bg-amber-500/10 px-2 py-1 text-amber-200",children:["expiring ",l.expiring]}),e.jsxs("div",{className:"rounded border border-rose-300/35 bg-rose-500/10 px-2 py-1 text-rose-200",children:["revoked ",l.revoked]})]}),e.jsxs("div",{"data-testid":"trustchain-list",className:"max-h-72 overflow-auto pr-1 space-y-1.5",children:[s.map(u=>{const x=String(u&&u.certificateId?u.certificateId:""),p=o[x]||{ok:!1,signatureValid:!1,revoked:!1,expiry:"expired"};return e.jsxs("article",{className:`rounded border px-2 py-1.5 ${p.ok?"border-emerald-300/30 bg-emerald-500/10":p.revoked?"border-rose-300/40 bg-rose-500/10":p.expiry==="expiring"?"border-amber-300/35 bg-amber-500/10":"border-rose-300/40 bg-rose-500/10"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-100",children:[u.serialNumber," · ",u.subjectName]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:u.kind})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["sig=",p.signatureValid?"valid":"invalid"," · expiry=",p.expiry," · revoked=",p.revoked?"yes":"no"]})]},x)}),s.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No certificates available for trust-chain view."})]})]})}const ku="neuralshell_pki_local_ca_v1",Nu="neuralshell_pki_certificates_v1",Su="neuralshell_pki_revocations_v1";function Gi(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function Ji(t,r){typeof window>"u"||!window.localStorage||window.localStorage.setItem(t,JSON.stringify(r))}function Cj(t,r=30){const n=Number(r)*24*60*60*1e3,s=Date.now();return(Array.isArray(t)?t:[]).filter(a=>{const o=new Date(String(a&&a.expiresAt?a.expiresAt:"")).getTime();if(!Number.isFinite(o))return!1;const c=o-s;return c>0&&c<=n})}function _j({open:t,onClose:r}){const[n,s]=i.useState(()=>Gi(ku,null)),[a,o]=i.useState(()=>{const d=Gi(Nu,[]);return Array.isArray(d)?d:[]}),[c,l]=i.useState(()=>{const d=Gi(Su,[]);return Array.isArray(d)?d:[]});i.useEffect(()=>{Ji(ku,n)},[n]),i.useEffect(()=>{Ji(Nu,a)},[a]),i.useEffect(()=>{Ji(Su,c)},[c]);const u=i.useMemo(()=>Cj(a,30),[a]),x=Array.isArray(c)?c.length:0,p=(Array.isArray(a)?a:[]).filter(d=>!c.includes(String(d&&d.certificateId?d.certificateId:"")));return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[144] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"trust-fabric-console",className:"fixed inset-x-8 top-16 bottom-6 z-[145] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"PKI Trust Fabric"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Local CA issuance, certificate lifecycle controls, CRL enforcement, and trust-chain visibility."})]}),e.jsx("button",{type:"button","data-testid":"trust-fabric-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"p-3 border-b border-white/10 grid grid-cols-4 gap-2 text-[9px] font-mono",children:[e.jsxs("div",{className:"rounded border border-cyan-300/30 bg-cyan-500/10 px-2 py-1 text-cyan-100",children:["CA ",n?"initialized":"missing"]}),e.jsxs("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-emerald-100",children:["active certs ",p.length]}),e.jsxs("div",{className:"rounded border border-amber-300/30 bg-amber-500/10 px-2 py-1 text-amber-100",children:["expiring soon ",u.length]}),e.jsxs("div",{className:"rounded border border-rose-300/35 bg-rose-500/10 px-2 py-1 text-rose-100",children:["revoked ",x]})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.95fr_1.05fr] gap-3 p-3 overflow-auto",children:[e.jsx(kj,{caRecord:n,certificates:a,revokedCertificateIds:c,onUpdateCA:s,onUpdateCertificates:o,onUpdateRevocations:l}),e.jsx(Sj,{caRecord:n,certificates:a,revokedCertificateIds:c})]})]})]}):null}const qi="hardware_customization_profiles_v1",Yi="hardware_customization_settings_v1",Cu="luxgrid_profiles_v1",Aj="luxgrid_settings_v1",Ej=["single","multi","row","zone"],Ij=["Static","Pulse","Breathing","Temperature Gradient","Usage Meter","Timer Fade"];function Qe(){return new Date().toISOString()}function Pj(){return[{id:"zone-main",name:"Main Cluster",keyIds:["K1","K2","K3","K4","K5","K6"],color:"#22d3ee",effect:"Static",brightness:80,speed:40,sensorSource:"none"},{id:"zone-nav",name:"Navigation",keyIds:["K7","K8","K9","K10"],color:"#a78bfa",effect:"Pulse",brightness:70,speed:35,sensorSource:"cpu"}]}function _u(t="Thermal HUD"){const r=Qe();return{id:`profile-${Math.random().toString(36).slice(2,9)}`,name:t,description:"Default hardware customization profile.",zones:Pj(),effects:{global:"Static"},createdAt:r,updatedAt:r,lastAppliedAt:""}}function Au(){return[_u("Thermal HUD"),_u("Sleep Ritual")]}function Eu(){return{general:{startInSimulatorMode:!0,startMinimized:!1,minimizeToTray:!1,confirmBeforeExit:!0,themeIntensity:70,animationLevel:"medium"},device:{autoScanOnLaunch:!1,openRgbHost:"127.0.0.1",openRgbPort:6742,hidScanEnabled:!0,vendorLockWarnings:!0},profiles:{autoApplyLastProfile:!1,saveProfileOnChange:!0,defaultProfileId:"",backupProfiles:!0},proof:{saveProofLogs:!0,includeSimulatorProofs:!0,proofOutputFolder:"proof/hardware-customization",timestampFormat:"utc_iso"}}}function Rj(){return[["K1","K2","K3","K4","K5","K6"],["K7","K8","K9","K10","K11","K12"],["K13","K14","K15","K16","K17","K18"],["K19","K20","K21","K22","K23","K24"]].map((r,n)=>r.map((s,a)=>({id:s,rowIndex:n,colIndex:a})))}function Zi(t){const r=Qe();return{id:String(t&&t.id?t.id:`profile-${Math.random().toString(36).slice(2,9)}`),name:String(t&&t.name?t.name:"Imported Profile"),description:String(t&&t.description?t.description:""),zones:Array.isArray(t&&t.zones)?t.zones:[],effects:t&&typeof t.effects=="object"?t.effects:{},createdAt:String(t&&t.createdAt?t.createdAt:r),updatedAt:String(t&&t.updatedAt?t.updatedAt:r),lastAppliedAt:String(t&&t.lastAppliedAt?t.lastAppliedAt:"")}}function Iu(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function Pa(t,r){typeof window>"u"||!window.localStorage||window.localStorage.setItem(t,JSON.stringify(r))}function Xi(t,r,n){const s=Iu(t,null);if(s!=null)return s;const a=Iu(r,null);return a!=null?(Pa(t,a),a):n}function Oj(t,r){const n=new Blob([JSON.stringify(r,null,2)],{type:"application/json"}),s=URL.createObjectURL(n),a=document.createElement("a");a.href=s,a.download=t,a.click(),URL.revokeObjectURL(s)}function Tj(t,r){const n=Array.isArray(r&&r.zones)?r.zones:[];for(const s of n)if(Array.isArray(s.keyIds)&&s.keyIds.includes(t))return s.color||"#1f2937";return"#111827"}function Pu(t,r){return t.find(n=>String(n.id)===String(r))||null}async function Ru(t){const r=[{id:"sim-keyboard",name:"Simulated Keyboard",vendor:"ProofForge",product:"Hardware Simulator",type:"keyboard",mode:"simulator",writable:!0,reason:"Simulator device available.",capabilities:["zones","effects","proof"]}];if(window.api&&window.api.rgb&&typeof window.api.rgb.status=="function"){const n=await window.api.rgb.status().catch(()=>null);!!(n&&n.transport&&n.transport.connected)?r.push({id:"openrgb-bridge",name:"OpenRGB Bridge",vendor:"OpenRGB",product:"OpenRGB Server",type:"bridge",mode:"openrgb",writable:!1,reason:"OpenRGB connected; hardware write adapter not implemented.",capabilities:["status"]}):r.push({id:"openrgb-bridge",name:"OpenRGB Bridge",vendor:"OpenRGB",product:"OpenRGB Server",type:"bridge",mode:"openrgb",writable:!1,reason:"OpenRGB server not connected.",capabilities:[]})}return t.device.hidScanEnabled&&typeof navigator<"u"&&"hid"in navigator&&r.push({id:"hid-local",name:"Local HID Interface",vendor:"OS",product:"HID",type:"keyboard",mode:"hid",writable:!1,reason:"HID device found, no writable RGB endpoint detected.",capabilities:["enumeration"]}),r.push({id:"vendor-lock",name:"Roccat Bridge",vendor:"Roccat",product:"Swarm Managed Device",type:"keyboard",mode:"vendor",writable:!1,reason:"Device may be locked by vendor software. Close Roccat Swarm before Live Mode.",capabilities:["vendor_lock_warning"]}),r}function Mj({open:t,onClose:r,onOpenSettings:n}){const[s,a]=i.useState(()=>Xi(qi,Cu,Au())),[o,c]=i.useState(()=>Xi(Yi,Aj,Eu())),[l,u]=i.useState(()=>{const B=Xi(qi,Cu,Au());return B[0]?B[0].id:""}),[x,p]=i.useState(()=>l),[d,m]=i.useState(""),[f,b]=i.useState(""),[h,g]=i.useState("simulator"),[y,I]=i.useState("No profile applied yet."),[A,C]=i.useState("sim-keyboard"),[w,j]=i.useState("single"),[E,N]=i.useState([]),[_,S]=i.useState(""),[R,$]=i.useState([]),[U,P]=i.useState(null),[D,z]=i.useState(""),[F,J]=i.useState(!1),[ee,ie]=i.useState("general"),[ye,pe]=i.useState("Simulator device available."),K=i.useRef(null);i.useEffect(()=>Pa(qi,s),[s]),i.useEffect(()=>Pa(Yi,o),[o]),i.useEffect(()=>{t&&o.device.autoScanOnLaunch&&Ru(o).then(B=>$(B))},[t,o]);const H=i.useMemo(()=>Pu(s,x)||s[0]||null,[s,x]),W=i.useMemo(()=>Pu(s,l)||s[0]||null,[s,l]),Z=i.useMemo(()=>R.find(B=>B.id===A)||null,[R,A]),ce=i.useMemo(()=>Rj(),[]);if(i.useEffect(()=>{!x&&s[0]&&p(s[0].id),!l&&s[0]&&u(s[0].id)},[s,x,l]),!t)return null;const fe=B=>{a(oe=>oe.map(xe=>xe.id===B.id?B:xe))},me=()=>{if(!H)return;const B=Qe();u(H.id),p(H.id),m(H.id),b(B),g("simulator"),I(`Applied ${H.name} to simulator.`),pe(`Applied ${H.name} to simulator.`),fe({...H,updatedAt:B,lastAppliedAt:B})},ke=()=>{if(!Z||!Z.writable){const oe=Z?Z.reason:"Cannot apply to device: no writable device selected.";g("failed"),I(oe||"Cannot apply to device: no writable device selected."),pe(oe||"Cannot apply to device: no writable device selected.");return}const B=Qe();b(B),m(H?H.id:""),g(Z.mode),I(`Applied ${H?H.name:"profile"} to ${Z.name}.`)},Pe=()=>{const B=Qe(),oe=Zi({name:`New Profile ${s.length+1}`,description:"",zones:[],effects:{global:"Static"},createdAt:B,updatedAt:B});a(xe=>[...xe,oe]),p(oe.id),u(oe.id)},_e=()=>{if(!H)return;const B=Qe(),oe=Zi({...H,id:`profile-${Math.random().toString(36).slice(2,9)}`,name:`${H.name} Copy`,zones:JSON.parse(JSON.stringify(H.zones||[])),effects:JSON.parse(JSON.stringify(H.effects||{})),createdAt:B,updatedAt:B,lastAppliedAt:""});a(xe=>[...xe,oe]),p(oe.id)},ne=()=>{if(!H)return;if(s.length<=1){pe("Cannot delete the last profile.");return}if(!window.confirm(`Delete profile "${H.name}"?`))return;const oe=s.filter(xe=>xe.id!==H.id);a(oe),p(oe[0].id),l===H.id&&u(oe[0].id)},we=()=>{if(!H)return;const B=Qe(),oe={...H,zones:[],effects:{global:"Static"},updatedAt:B};fe(oe),pe(`Reset ${H.name}.`)},De=()=>{H&&Oj(`${H.name.replace(/\s+/g,"_").toLowerCase()}_hardware_profile.json`,H)},re=async B=>{const oe=B.target.files&&B.target.files[0];if(oe)try{const xe=await oe.text(),Re=JSON.parse(xe);if(!Re||typeof Re!="object"||!Re.name)throw new Error("Bad profile import: missing name.");const $e=Zi(Re);a(tt=>[...tt,$e]),p($e.id),pe(`Imported profile "${$e.name}".`)}catch(xe){pe(`Bad import: ${xe&&xe.message?xe.message:"Invalid JSON"}`)}finally{K.current&&(K.current.value="")}},ae=B=>{const oe=B.id;if(w==="single"){N([oe]);return}if(w==="row"){const xe=ce[B.rowIndex].map(Re=>Re.id);N(xe);return}if(w==="zone"&&H){const xe=(H.zones||[]).find(Re=>Re.id===_)||(H.zones||[])[0];N(xe?xe.keyIds||[]:[]);return}N(xe=>xe.includes(oe)?xe.filter(Re=>Re!==oe):[...xe,oe])},M=()=>{if(!H||!_)return;const B=(H.zones||[]).map(oe=>oe.id===_?{...oe,keyIds:Array.from(new Set(E))}:{...oe,keyIds:(oe.keyIds||[]).filter(xe=>!E.includes(xe))});fe({...H,zones:B,updatedAt:Qe()})},V=()=>{if(!H)return;const B={id:`zone-${Math.random().toString(36).slice(2,8)}`,name:`Zone ${(H.zones||[]).length+1}`,keyIds:[],color:"#22d3ee",effect:"Static",brightness:80,speed:40,sensorSource:"none"};fe({...H,zones:[...H.zones||[],B],updatedAt:Qe()}),S(B.id)},G=(B,oe)=>{if(!H)return;const xe=(H.zones||[]).map(Re=>Re.id===B?{...Re,...oe}:Re);fe({...H,zones:xe,updatedAt:Qe()})},te=()=>{if(!H||!_)return;const B=(H.zones||[]).filter(oe=>oe.id!==_);fe({...H,zones:B,updatedAt:Qe()}),S(B[0]?B[0].id:"")},de=async()=>{const B=await Ru(o);$(B),!A&&B[0]&&C(B[0].id),pe(B[0]?B[0].reason:"No devices detected.")},L=()=>{if(!H)return;if(!Z||!Z.writable){const Re={timestamp:Qe(),success:!1,reason:Z&&Z.reason?Z.reason:"No writable device selected"};P(Re),z("proof-failed");return}const B=Array.isArray(H.zones)?H.zones:[],oe=B.reduce((Re,$e)=>Re+(Array.isArray($e.keyIds)?$e.keyIds.length:0),0),xe={timestamp:Qe(),mode:"simulator",deviceId:"sim-keyboard",deviceName:"Simulated Keyboard",profile:H.name,zonesApplied:B.length,keysApplied:oe,success:!0,notes:["Simulator proof only — no physical device changed."]};P(xe),z("proof-success")},be=!!(Z&&Z.writable),Q=H&&(H.zones||[]).find(B=>B.id===_)||null,We=ce.flat();return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[146] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"hardware-appliance-manager",className:"fixed inset-x-8 top-16 bottom-6 z-[147] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Hardware Customization Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"ProofForge can detect supported local devices exposed through Simulator, OpenRGB, HID, or future vendor adapters."})]}),e.jsx("button",{type:"button",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-3 p-3 overflow-auto flex-1 min-h-0",children:[e.jsxs("section",{className:"col-span-1 rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{"data-testid":"active-profile-card",className:"text-[10px] font-mono text-cyan-100",children:["Active: ",W?W.name:"n/a"]}),e.jsx("div",{className:"space-y-1 max-h-44 overflow-auto",children:s.map(B=>e.jsx("button",{type:"button",onClick:()=>p(B.id),className:`w-full text-left px-2 py-1 rounded border text-[10px] font-mono ${B.id===x?"border-cyan-300/40 bg-cyan-500/10 text-cyan-100":"border-white/10 bg-black/30 text-slate-300"}`,children:B.name},B.id))}),e.jsx("input",{"data-testid":"profile-name-input",value:H?H.name:"",onChange:B=>H&&fe({...H,name:B.target.value,updatedAt:Qe()}),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px] text-slate-200"}),e.jsx("textarea",{"data-testid":"profile-description-input",value:H?H.description:"",onChange:B=>H&&fe({...H,description:B.target.value,updatedAt:Qe()}),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px] text-slate-200"}),e.jsxs("div",{className:"grid grid-cols-2 gap-1",children:[e.jsx("button",{"data-testid":"profile-create-button",type:"button",onClick:Pe,className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"New"}),e.jsx("button",{"data-testid":"profile-duplicate-button",type:"button",onClick:_e,className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"Duplicate"}),e.jsx("button",{"data-testid":"profile-rename-button",type:"button",onClick:()=>H&&pe(`Renamed profile to ${H.name}.`),className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"Rename"}),e.jsx("button",{"data-testid":"profile-delete-button",type:"button",onClick:ne,className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"Delete"}),e.jsx("button",{"data-testid":"profile-export-button",type:"button",onClick:De,className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"Export"}),e.jsx("button",{"data-testid":"profile-import-button",type:"button",onClick:()=>K.current&&K.current.click(),className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"Import"}),e.jsx("button",{"data-testid":"profile-reset-button",type:"button",onClick:we,className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"Reset"})]}),e.jsx("input",{ref:K,type:"file",accept:".json,application/json",onChange:re,className:"hidden"})]}),e.jsxs("section",{className:"col-span-2 rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("select",{"data-testid":"selection-mode-select",value:w,onChange:B=>j(B.target.value),className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px]",children:Ej.map(B=>e.jsx("option",{value:B,children:B},B))}),e.jsxs("span",{"data-testid":"selected-key-count",className:"text-[10px] font-mono text-cyan-100",children:[E.length," selected"]}),e.jsx("button",{"data-testid":"selection-clear-button",type:"button",onClick:()=>N([]),className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"Clear"}),e.jsx("button",{"data-testid":"selection-invert-button",type:"button",onClick:()=>N(We.map(B=>B.id).filter(B=>!E.includes(B))),className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"Invert"}),e.jsx("button",{"data-testid":"selection-all-button",type:"button",onClick:()=>N(We.map(B=>B.id)),className:"px-2 py-1 rounded border border-white/10 text-[9px]",children:"All"})]}),e.jsx("div",{className:"space-y-1",children:ce.map(B=>e.jsx("div",{className:"flex gap-1",children:B.map(oe=>{const xe=E.includes(oe.id);return e.jsx("button",{type:"button","data-testid":xe?"keyboard-key-selected":"keyboard-key",onClick:()=>ae(oe),className:`h-8 w-12 rounded border text-[9px] font-mono ${xe?"border-cyan-300 bg-cyan-500/20 text-cyan-100":"border-white/10 text-slate-200"}`,style:{backgroundColor:xe?void 0:Tj(oe.id,H)},children:oe.id},oe.id)})},B[0].id))})]}),e.jsxs("section",{className:"col-span-1 rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("button",{"data-testid":"zone-create-button",type:"button",onClick:V,className:"w-full px-2 py-1 rounded border border-white/10 text-[9px]",children:"Create Zone"}),e.jsxs("select",{value:_,onChange:B=>S(B.target.value),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px]",children:[e.jsx("option",{value:"",children:"Select Zone"}),(H&&H.zones||[]).map(B=>e.jsx("option",{value:B.id,children:B.name},B.id))]}),e.jsx("input",{"data-testid":"zone-rename-input",value:Q?Q.name:"",onChange:B=>Q&&G(Q.id,{name:B.target.value}),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px]"}),e.jsx("button",{"data-testid":"zone-delete-button",type:"button",onClick:te,className:"w-full px-2 py-1 rounded border border-white/10 text-[9px]",children:"Delete Zone"}),e.jsx("input",{"data-testid":"zone-color-picker",type:"color",value:Q?Q.color:"#22d3ee",onChange:B=>Q&&G(Q.id,{color:B.target.value}),className:"w-full h-8"}),e.jsx("select",{"data-testid":"zone-effect-select",value:Q?Q.effect:"Static",onChange:B=>Q&&G(Q.id,{effect:B.target.value}),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px]",children:Ij.map(B=>e.jsx("option",{value:B,children:B},B))}),e.jsx("input",{"data-testid":"zone-brightness-slider",type:"range",min:"0",max:"100",value:Q?Q.brightness:80,onChange:B=>Q&&G(Q.id,{brightness:Number(B.target.value)})}),e.jsx("input",{"data-testid":"zone-speed-slider",type:"range",min:"0",max:"100",value:Q?Q.speed:40,onChange:B=>Q&&G(Q.id,{speed:Number(B.target.value)})}),e.jsxs("select",{"data-testid":"zone-sensor-source-select",value:Q?Q.sensorSource:"none",onChange:B=>Q&&G(Q.id,{sensorSource:B.target.value}),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px]",children:[e.jsx("option",{value:"none",children:"none"}),e.jsx("option",{value:"cpu",children:"cpu"}),e.jsx("option",{value:"gpu",children:"gpu"}),e.jsx("option",{value:"timer",children:"timer"})]}),e.jsx("button",{"data-testid":"assign-selection-zone-button",type:"button",onClick:M,className:"w-full px-2 py-1 rounded border border-white/10 text-[9px]",children:"Assign selection"}),e.jsx("button",{"data-testid":"zone-preview-button",type:"button",onClick:()=>pe(Q?`Previewing ${Q.name}`:"Select a zone first."),className:"w-full px-2 py-1 rounded border border-white/10 text-[9px]",children:"Preview Zone"}),e.jsx("div",{"data-testid":"zone-assigned-keys",className:"text-[9px] font-mono text-slate-400",children:Q&&(Q.keyIds||[]).join(", ")||"none"})]})]}),e.jsxs("div",{className:"px-3 py-2 border-t border-white/10 bg-black/40 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[10px] font-mono",children:[e.jsx("button",{"data-testid":"device-scan-button",type:"button",onClick:de,className:"px-2 py-1 rounded border border-white/10",children:"Scan Devices"}),e.jsx("button",{"data-testid":"app-restart-scan-button",type:"button",onClick:de,className:"px-2 py-1 rounded border border-white/10",children:"Restart Scan"}),e.jsx("button",{"data-testid":"apply-simulator-button",type:"button",onClick:me,className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10",children:"Apply to Simulator"}),e.jsx("button",{"data-testid":"apply-device-button",type:"button",disabled:!be,onClick:ke,className:"px-2 py-1 rounded border border-white/10 disabled:opacity-50",children:"Apply to Device"}),e.jsx("span",{"data-testid":"profile-apply-status",children:ye})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:R.map(B=>e.jsxs("button",{type:"button","data-testid":"device-card",onClick:()=>C(B.id),className:`px-2 py-1 rounded border text-[9px] font-mono ${B.id===A?"border-cyan-300/40 bg-cyan-500/10":"border-white/10"}`,children:[e.jsx("div",{children:B.name}),e.jsx("div",{"data-testid":"device-mode-badge",children:B.mode}),e.jsx("div",{"data-testid":"device-writable-status",children:B.writable?"writable":"read-only"}),e.jsx("div",{"data-testid":"device-lock-reason",children:B.reason})]},B.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[10px] font-mono",children:[e.jsx("span",{"data-testid":"last-applied-status",children:y}),e.jsx("span",{"data-testid":"last-applied-at",children:f||"n/a"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{"data-testid":"proof-run-button",type:"button",onClick:L,className:"px-2 py-1 rounded border border-white/10",children:"Run Proof"}),e.jsx("div",{"data-testid":"proof-mode",className:"text-[10px] font-mono",children:h}),e.jsx("div",{"data-testid":"proof-success",className:"text-[10px] font-mono",children:D})]}),e.jsx("pre",{"data-testid":"proof-output",className:"max-h-32 overflow-auto text-[9px] font-mono border border-white/10 rounded p-2 bg-black/40",children:U?JSON.stringify(U,null,2):"No proof yet."}),e.jsx("div",{"data-testid":"proof-reason",className:"text-[10px] font-mono text-slate-400",children:U&&!U.success?U.reason:""}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{"data-testid":"settings-button",type:"button",onClick:()=>J(!0),className:"px-2 py-1 rounded border border-white/10",children:"Settings"}),e.jsx("button",{"data-testid":"app-settings-button",type:"button",onClick:()=>J(!0),className:"px-2 py-1 rounded border border-white/10",children:"App Settings"}),e.jsx("button",{"data-testid":"app-minimize-button",type:"button",disabled:!(window.api&&window.api.app&&typeof window.api.app.minimize=="function"),onClick:()=>window.api.app.minimize(),className:"px-2 py-1 rounded border border-white/10 disabled:opacity-50",children:"Minimize"}),e.jsx("button",{"data-testid":"app-exit-button",type:"button",disabled:!(window.api&&window.api.app&&typeof window.api.app.exit=="function"),onClick:()=>window.api.app.exit(),className:"px-2 py-1 rounded border border-white/10 disabled:opacity-50",children:"Exit"}),e.jsx("button",{type:"button",onClick:()=>typeof n=="function"&&n(),className:"px-2 py-1 rounded border border-white/10",children:"Open App Settings"})]})]})]}),F&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[148] bg-black/50",onClick:()=>J(!1)}),e.jsxs("section",{"data-testid":"settings-modal",className:"fixed right-12 top-20 z-[149] w-[28rem] rounded-xl border border-white/10 bg-slate-950 p-3 space-y-2",children:[e.jsx("div",{className:"flex gap-1",children:["general","device","profiles","proof"].map(B=>e.jsx("button",{"data-testid":`settings-${B}-tab`,type:"button",onClick:()=>ie(B),className:`px-2 py-1 rounded border text-[9px] ${ee===B?"border-cyan-300/40 bg-cyan-500/10":"border-white/10"}`,children:B},B))}),ee==="general"&&e.jsxs("label",{className:"text-[10px] font-mono flex items-center justify-between",children:["Start in Simulator Mode",e.jsx("input",{type:"checkbox",checked:o.general.startInSimulatorMode,onChange:B=>c(oe=>({...oe,general:{...oe.general,startInSimulatorMode:B.target.checked}}))})]}),ee==="device"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-[10px] font-mono flex items-center justify-between",children:["Auto-scan on launch",e.jsx("input",{"data-testid":"setting-auto-scan",type:"checkbox",checked:o.device.autoScanOnLaunch,onChange:B=>c(oe=>({...oe,device:{...oe.device,autoScanOnLaunch:B.target.checked}}))})]}),e.jsx("input",{"data-testid":"setting-openrgb-host",value:o.device.openRgbHost,onChange:B=>c(oe=>({...oe,device:{...oe.device,openRgbHost:B.target.value}})),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px]"}),e.jsx("input",{"data-testid":"setting-openrgb-port",type:"number",value:o.device.openRgbPort,onChange:B=>c(oe=>({...oe,device:{...oe.device,openRgbPort:Number(B.target.value)}})),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px]"})]}),ee==="profiles"&&e.jsxs("label",{className:"text-[10px] font-mono flex items-center justify-between",children:["Auto-apply last profile",e.jsx("input",{"data-testid":"setting-auto-apply-profile",type:"checkbox",checked:o.profiles.autoApplyLastProfile,onChange:B=>c(oe=>({...oe,profiles:{...oe.profiles,autoApplyLastProfile:B.target.checked}}))})]}),ee==="proof"&&e.jsx("input",{"data-testid":"setting-proof-output-folder",value:o.proof.proofOutputFolder,onChange:B=>c(oe=>({...oe,proof:{...oe.proof,proofOutputFolder:B.target.value}})),className:"w-full rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px]"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{"data-testid":"settings-save-button",type:"button",onClick:()=>{Pa(Yi,o),J(!1)},children:"Save"}),e.jsx("button",{"data-testid":"settings-reset-button",type:"button",onClick:()=>c(Eu()),children:"Reset"})]})]})]})]})}function Dj(t){const r=String(t||"").toLowerCase();return r==="released"?"border-emerald-300/30 bg-emerald-500/10":r==="verified"?"border-cyan-300/30 bg-cyan-500/10":r==="quarantined"?"border-amber-300/35 bg-amber-500/10":"border-white/10 bg-black/20"}function $j({entries:t,onVerifyReceipt:r,onReleaseFromQuarantine:n}){const s=Array.isArray(t)?t:[];return e.jsxs("section",{"data-testid":"transfer-ledger-view",className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Transfer Ledger"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Each handoff is recorded with quarantine, verification, and release transitions."})]}),e.jsxs("div",{className:"max-h-80 overflow-auto pr-1 space-y-1.5",children:[s.map(a=>e.jsxs("article",{className:`rounded border px-2 py-1.5 ${Dj(a.status)}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:a.packageId}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:a.courierClass})]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:[a.sender," ➜ ",a.receiver," · ",a.status]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("button",{type:"button","data-testid":`courier-verify-${a.entryId}`,onClick:()=>{typeof r=="function"&&r(a.entryId)},className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono text-cyan-100",children:"verify receipt"}),e.jsx("button",{type:"button","data-testid":`courier-release-${a.entryId}`,onClick:()=>{typeof n=="function"&&n(a.entryId)},className:"px-2 py-1 rounded border border-emerald-300/30 bg-emerald-500/10 text-[9px] font-mono text-emerald-100",children:"release"})]})]},a.entryId)),s.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No transfer ledger entries yet."})]})]})}const Ou="neuralshell_courier_transfer_ledger_v1";function Lj(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function Bj(t,r){typeof window>"u"||!window.localStorage||window.localStorage.setItem(t,JSON.stringify(r))}async function Fj(t){const r=new window.TextEncoder().encode(String(t||"")),n=await window.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}function Tu(t){const r=String(t||"").trim().toLowerCase();return r==="standard"||r==="sensitive"||r==="sealed"||r==="emergency"?r:"standard"}function Uj({open:t,onClose:r}){const[n,s]=i.useState(()=>{const f=Lj(Ou,[]);return Array.isArray(f)?f:[]}),[a,o]=i.useState("standard"),[c,l]=i.useState(""),[u,x]=i.useState("");i.useEffect(()=>{Bj(Ou,n)},[n]);const p=async f=>{const b=f&&f.target&&f.target.files?f.target.files[0]:null;if(b)try{const h=await pt(b),g=JSON.parse(String(h||"{}")),y=g&&g.payload&&typeof g.payload=="object"?g.payload:null,I=String(g&&g.signature?g.signature:""),A=String(g&&g.hash?g.hash:"").trim().toLowerCase(),C=String(g&&g.signer&&g.signer.publicKeyPem?g.signer.publicKeyPem:"");if(!y||!I||!A||!C)throw new Error("Courier package missing payload/signature/hash/public key.");const w=await Mt(y,I,C),E=await Fj(pr(y))===A;if(!w||!E)throw new Error("Courier package failed verification and remains quarantined.");const N={entryId:`ledger-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,packageId:String(y.packageId||`package-${Date.now()}`),courierClass:Tu(y.courierClass||a),sender:String(y.sender||"sender-unset"),receiver:String(y.receiver||"receiver-unset"),status:"quarantined",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),handoffs:[{handoffId:`handoff-${Date.now()}`,at:new Date().toISOString(),actor:"import-station",action:"imported",detail:{sourceFile:b.name,artifactCount:Array.isArray(y.artifacts)?y.artifacts.length:0}}]};s(_=>[N,...Array.isArray(_)?_:[]].slice(0,500)),l(`Courier package ${N.packageId} quarantined pending receipt verification.`),x("")}catch(h){l(""),x(h&&h.message?h.message:String(h))}finally{f&&f.target&&(f.target.value="")}},d=f=>{const b=String(f||"");b&&(s(h=>Array.isArray(h)?h.map(g=>{if(String(g.entryId||"")!==b)return g;const y=new Date().toISOString();return{...g,status:"verified",updatedAt:y,handoffs:[...Array.isArray(g.handoffs)?g.handoffs:[],{handoffId:`handoff-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,at:y,actor:"receipt-station",action:"verified",detail:{}}].slice(-400)}}):h),l(`Receipt verified for ${b}.`),x(""))},m=f=>{const b=String(f||"");if(!b)return;const h=(Array.isArray(n)?n:[]).find(g=>String(g.entryId||"")===b);if(h){if(String(h.status||"")!=="verified"){x("Release blocked: verify receipt before quarantine release.");return}s(g=>Array.isArray(g)?g.map(y=>{if(String(y.entryId||"")!==b)return y;const I=new Date().toISOString();return{...y,status:"released",updatedAt:I,handoffs:[...Array.isArray(y.handoffs)?y.handoffs:[],{handoffId:`handoff-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,at:I,actor:"release-station",action:"released",detail:{}}].slice(-400)}}):g),l(`Released package ${h.packageId} from quarantine.`),x("")}};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[148] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"courier-transfer-center",className:"fixed inset-x-8 top-16 bottom-6 z-[149] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Offline Evidence Courier"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Quarantine-first courier transfer chain for restricted environment handoffs."})]}),e.jsx("button",{type:"button","data-testid":"courier-transfer-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"p-3 border-b border-white/10 flex items-center gap-2",children:[e.jsxs("select",{"data-testid":"courier-class-select",value:a,onChange:f=>o(Tu(f.target.value)),className:"rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-100",children:[e.jsx("option",{value:"standard",children:"standard"}),e.jsx("option",{value:"sensitive",children:"sensitive"}),e.jsx("option",{value:"sealed",children:"sealed"}),e.jsx("option",{value:"emergency",children:"emergency"})]}),e.jsxs("label",{className:"inline-flex items-center px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono uppercase tracking-[0.12em] text-cyan-100 cursor-pointer",children:["Import Courier Package",e.jsx("input",{type:"file","data-testid":"courier-import-input",className:"hidden",accept:".json,application/json",onChange:p})]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:e.jsx($j,{entries:n,onVerifyReceipt:d,onReleaseFromQuarantine:m})}),(c||u)&&e.jsxs("div",{className:"px-3 py-2 border-t border-white/10",children:[c&&e.jsx("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-[10px] font-mono text-emerald-100",children:c}),u&&e.jsx("div",{"data-testid":"courier-error",className:"mt-1 rounded border border-rose-300/40 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-100",children:u})]})]})]}):null}function zj({templates:t,selectedTemplateId:r,onSelectTemplate:n,onUpdateTemplates:s}){const a=Array.isArray(t)?t:[];return e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Drill Templates"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Scenario definitions for repeatable continuity exercises."})]}),e.jsx("div",{className:"space-y-1 max-h-60 overflow-auto pr-1",children:a.map(o=>e.jsxs("button",{type:"button","data-testid":`drill-template-${o.templateId}`,onClick:()=>{typeof n=="function"&&n(o.templateId)},className:`w-full text-left rounded border px-2 py-1.5 ${r===o.templateId?"border-cyan-300/35 bg-cyan-500/15":"border-white/10 bg-black/20"}`,children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:o.title}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:o.scenarioId})]},o.templateId))}),e.jsx("button",{type:"button","data-testid":"drill-template-add-btn",onClick:()=>{const o={templateId:`drill-custom-${Date.now()}`,scenarioId:"support_incident_export",title:"Custom Continuity Drill",expectedState:{exportCompleted:!0,trustState:"valid"},checklist:["run scenario","capture evidence","review deltas"]};typeof s=="function"&&s([o,...a].slice(0,40))},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Add Template"})]})}function Hj({score:t,runs:r}){const a=(Array.isArray(r)?r:[]).filter(o=>!o.passed).flatMap(o=>Array.isArray(o.deltas)?o.deltas.map(c=>({runId:o.runId,key:c.key,expected:c.expected,actual:c.actual})):[]);return e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Recovery Scorecard"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Readiness score and remediation tasks from failed drills."})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-2 text-[9px] font-mono",children:[e.jsxs("div",{className:"rounded border border-cyan-300/30 bg-cyan-500/10 px-2 py-1 text-cyan-100",children:["score ",t.score]}),e.jsxs("div",{className:"rounded border border-emerald-300/30 bg-emerald-500/10 px-2 py-1 text-emerald-100",children:["passed ",t.passed]}),e.jsxs("div",{className:"rounded border border-rose-300/35 bg-rose-500/10 px-2 py-1 text-rose-100",children:["failed ",t.failed]}),e.jsxs("div",{className:"rounded border border-white/10 bg-black/20 px-2 py-1 text-slate-300",children:["total ",t.total]})]}),e.jsxs("div",{className:"max-h-56 overflow-auto pr-1 space-y-1.5",children:[a.map((o,c)=>e.jsxs("article",{className:"rounded border border-amber-300/35 bg-amber-500/10 px-2 py-1.5",children:[e.jsx("div",{className:"text-[9px] font-mono text-amber-100",children:o.key}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-300",children:["expected ",JSON.stringify(o.expected)]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-300",children:["actual ",JSON.stringify(o.actual)]})]},`${o.runId}-${o.key}-${c}`)),a.length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No remediation tasks. Latest drill set is aligned."})]})]})}const js=[{templateId:"drill-fleet-restore",scenarioId:"fleet_restore",title:"Fleet Restore Drill",expectedState:{fleetHealth:"healthy",restoredNodes:3,trustState:"valid"},checklist:["recover backup bundle","verify trust chain","confirm node telemetry"]},{templateId:"drill-appliance-replacement",scenarioId:"appliance_replacement",title:"Appliance Replacement Drill",expectedState:{provisioned:!0,trustState:"valid",policyProfile:"sealed"},checklist:["replace hardware","provision role","verify diagnostics"]},{templateId:"drill-policy-rollback",scenarioId:"regional_policy_rollback",title:"Regional Policy Rollback Drill",expectedState:{rollbackApplied:!0,incidentsOpen:0},checklist:["apply rollback","verify signatures","validate runtime status"]},{templateId:"drill-revoked-trust",scenarioId:"revoked_trust_relationship",title:"Revoked Trust Relationship Drill",expectedState:{revokedBlocked:!0,alertsRaised:1},checklist:["present revoked certificate","confirm trust path invalidated","capture incident evidence"]}],Mu="neuralshell_continuity_templates_v1",Du="neuralshell_continuity_schedules_v1",$u="neuralshell_continuity_runs_v1";function Qi(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function el(t,r){typeof window>"u"||!window.localStorage||window.localStorage.setItem(t,JSON.stringify(r))}function Wj(t,r){const n=t&&typeof t=="object"?t:{},s=r&&typeof r=="object"?r:{};return Array.from(new Set([...Object.keys(n),...Object.keys(s)])).sort().map(o=>({key:o,expected:n[o],actual:s[o]})).filter(o=>JSON.stringify(o.expected)!==JSON.stringify(o.actual))}function Kj(t){const r=Array.isArray(t)?t:[];if(!r.length)return{score:0,passed:0,failed:0,total:0};const n=r.filter(s=>s&&s.passed).length;return{score:Math.round(n/r.length*100),passed:n,failed:r.length-n,total:r.length}}function Vj({open:t,onClose:r}){const[n,s]=i.useState(()=>{const C=Qi(Mu,js);return Array.isArray(C)&&C.length?C:js}),[a,o]=i.useState(()=>{const C=Array.isArray(js)&&js.length?js[0]:null;return C?C.templateId:""}),[c,l]=i.useState(""),[u,x]=i.useState(()=>{const C=Qi(Du,[]);return Array.isArray(C)?C:[]}),[p,d]=i.useState(()=>{const C=Qi($u,[]);return Array.isArray(C)?C:[]}),[m,f]=i.useState(!1),[b,h]=i.useState("");i.useEffect(()=>{el(Mu,n)},[n]),i.useEffect(()=>{el(Du,u)},[u]),i.useEffect(()=>{el($u,p)},[p]);const g=i.useMemo(()=>(Array.isArray(n)?n:[]).find(C=>C.templateId===a)||null,[a,n]),y=i.useMemo(()=>Kj(p),[p]),I=()=>{if(!g)return;const C=g.expectedState&&typeof g.expectedState=="object"?g.expectedState:{};let w={...C};if(m){const S=Object.keys(C)[0]||"unexpectedState";w[S]=C[S]===!0?!1:`mismatch-${Date.now()}`}const j=Wj(C,w),E=new Date().toISOString(),N={runId:`drill-run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,templateId:g.templateId,title:g.title,startedAt:E,finishedAt:E,passed:j.length===0,expectedState:C,actualState:w,deltas:j,evidence:{artifactId:`drill-evidence-${Date.now()}`,generatedAt:E,summary:j.length===0?"Drill passed expected recovery state.":`Drill failed with ${j.length} delta(s).`,attachablePacks:["audit","support","board"]}};d(_=>[N,...Array.isArray(_)?_:[]].slice(0,300)),h(`Drill ${N.passed?"passed":"failed"}: ${N.title}`)},A=()=>{!g||!c||(x(C=>[{scheduleId:`schedule-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,templateId:g.templateId,title:g.title,scheduledAt:c,status:"scheduled"},...Array.isArray(C)?C:[]].slice(0,200)),h(`Scheduled ${g.title} for ${new Date(c).toLocaleString()}.`),l(""))};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[150] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"continuity-drill-center",className:"fixed inset-x-8 top-16 bottom-6 z-[151] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Continuity Drill Center"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Schedule and run repeatable recovery drills with evidence bundles and scorecard output."})]}),e.jsx("button",{type:"button","data-testid":"continuity-drill-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"p-3 border-b border-white/10 flex items-center gap-2",children:[e.jsx("input",{type:"datetime-local","data-testid":"continuity-schedule-input",value:c,onChange:C=>l(C.target.value),className:"rounded border border-white/10 bg-slate-900 px-2 py-1 text-[10px] font-mono text-slate-100"}),e.jsx("button",{type:"button","data-testid":"continuity-schedule-btn",onClick:A,className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Schedule Drill"}),e.jsxs("label",{className:"inline-flex items-center gap-1 text-[10px] font-mono text-slate-300",children:[e.jsx("input",{type:"checkbox","data-testid":"continuity-simulate-failure",checked:m,onChange:C=>f(!!C.target.checked)}),"simulate failure"]}),e.jsx("button",{type:"button","data-testid":"continuity-run-btn",onClick:I,className:"px-2.5 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Run Drill"}),e.jsx("button",{type:"button","data-testid":"continuity-export-evidence-btn",onClick:()=>{const C=Array.isArray(p)&&p.length?p[0]:null;C&&je(`neuralshell_continuity_evidence_${C.runId}.json`,C)},className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Export Evidence"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.95fr_1.05fr] gap-3 p-3 overflow-auto",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(zj,{templates:n,selectedTemplateId:a,onSelectTemplate:o,onUpdateTemplates:s}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-1",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Scheduled Drills"}),e.jsxs("div",{className:"max-h-44 overflow-auto pr-1 space-y-1",children:[(Array.isArray(u)?u:[]).map(C=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/20 px-2 py-1 text-[9px] font-mono text-slate-300",children:[C.title," · ",new Date(C.scheduledAt).toLocaleString()]},C.scheduleId)),(Array.isArray(u)?u:[]).length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No drills scheduled."})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Hj,{score:y,runs:p}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-1",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Drill Runs"}),e.jsxs("div",{className:"max-h-48 overflow-auto pr-1 space-y-1.5",children:[(Array.isArray(p)?p:[]).map(C=>e.jsxs("article",{className:`rounded border px-2 py-1.5 ${C.passed?"border-emerald-300/30 bg-emerald-500/10":"border-rose-300/35 bg-rose-500/10"}`,children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:C.title}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:[C.passed?"passed":"failed"," · ",C.evidence.artifactId]})]},C.runId)),(Array.isArray(p)?p:[]).length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No drill runs yet."})]})]})]})]}),b&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-cyan-100 bg-cyan-500/10",children:b})]})]}):null}const Lu="neuralshell_procurement_pack_history_v1";function Gj(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function Jj(t,r){typeof window>"u"||!window.localStorage||window.localStorage.setItem(t,JSON.stringify(r))}function qj(t){const r=new Date(String(t||"")).getTime();return Number.isFinite(r)?Math.floor((Date.now()-r)/(24*60*60*1e3)):999}function Yj({open:t,onClose:r}){const[n,s]=i.useState("Institutional Buyer"),[a,o]=i.useState("security-ops"),[c,l]=i.useState("2.1.29"),[u,x]=i.useState("2.1.28"),[p,d]=i.useState(()=>{const h=Gj(Lu,[]);return Array.isArray(h)?h:[]}),[m,f]=i.useState("");i.useEffect(()=>{Jj(Lu,p)},[p]);const b=()=>{const h=new Date().toISOString(),g={generatedAt:h,organization:n,reviewOwner:a,currentVersion:c,previousVersion:u,securityQuestionnaire:{deploymentModel:"local-first + air-gapped capable",trustIdentity:"local CA + certificate lifecycle + revocation",evidenceMovement:"offline courier chain with quarantine/release",continuityDiscipline:"scheduled drill engine + scorecard evidence"},architectureOnePager:{runtime:"local command runtime",modules:["airgap","pki","appliance","courier","continuity","procurement","simulation","institutional_console"],policy:"verification-first activation and explicit trust controls"},dataFlowDeclaration:{inbound:"signed artifact ingestion at import station",outbound:"signed courier transfer with ledger handoffs",cloudDependency:"not required for core operations"},artifactInventory:["airgap_bundle.signed.json","courier_package.signed.json","trust_chain_view.json","continuity_evidence_bundle.json","procurement_pack_manifest.json"],compliancePostureSummary:{localFirst:!0,airGapReady:!0,revocationEnforced:!0,continuityDrillsEnabled:!0},procurementFAQ:[{question:"Does operation require cloud connectivity?",answer:"No. Critical operations run local-first and support sealed environments."},{question:"How are trust identities governed?",answer:"Certificates are issued/rotated/revoked under local CA control."}],deltaSinceLastReview:{previousVersion:u,currentVersion:c,summary:`Review delta from ${u} to ${c} includes air-gap, PKI, appliance, courier, continuity, and institutional console surfaces.`}};je(`neuralshell_security_review_pack_${c}.json`,g),$s(`neuralshell_procurement_faq_${c}.md`,[`# Procurement FAQ (${c})`,"",...g.procurementFAQ.map(y=>`Q: ${y.question} A: ${y.answer} `)].join(` -`)),d(y=>[{id:`proc-pack-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,generatedAt:h,organization:n,reviewOwner:a,currentVersion:l,previousVersion:u},...Array.isArray(y)?y:[]].slice(0,120)),f(`Generated procurement/security review pack for ${n}.`)};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[152] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"procurement-command-center",className:"fixed inset-x-8 top-16 bottom-6 z-[153] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Procurement Command Center"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Buyer-ready security review output generated from local runtime truth."})]}),e.jsx("button",{type:"button","data-testid":"procurement-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.9fr_1.1fr] gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Organization",e.jsx("input",{"data-testid":"procurement-organization-input",value:n,onChange:h=>s(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Review Owner",e.jsx("input",{"data-testid":"procurement-owner-input",value:a,onChange:h=>o(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Current Version",e.jsx("input",{"data-testid":"procurement-current-version-input",value:l,onChange:h=>c(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Previous Version",e.jsx("input",{"data-testid":"procurement-previous-version-input",value:u,onChange:h=>x(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("button",{type:"button","data-testid":"procurement-generate-btn",onClick:b,className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Generate Review Pack"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Pack Freshness"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Recent generation history and staleness indicator."})]}),e.jsxs("div",{className:"max-h-80 overflow-auto pr-1 space-y-1.5",children:[(Array.isArray(p)?p:[]).map(h=>{const g=qj(h.generatedAt);return e.jsxs("article",{className:`rounded border px-2 py-1.5 ${g<=7?"border-emerald-300/30 bg-emerald-500/10":g<=30?"border-amber-300/35 bg-amber-500/10":"border-rose-300/35 bg-rose-500/10"}`,children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:h.organization}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:[h.previousVersion," ➜ ",h.currentVersion," · ",new Date(h.generatedAt).toLocaleString()]})]},h.id)}),(Array.isArray(p)?p:[]).length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No review packs generated yet."})]})]})]}),m&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:m})]})]}):null}function Zj({scenario:t,onRun:r}){const n=t&&typeof t=="object"?t:{},s=String(n.severity||"warning");return e.jsxs("article",{className:`rounded border px-2 py-2 ${s==="critical"?"border-rose-300/35 bg-rose-500/10":s==="degraded"?"border-amber-300/35 bg-amber-500/10":"border-cyan-300/30 bg-cyan-500/10"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:n.title}),e.jsx("div",{className:"text-[9px] font-mono uppercase text-slate-300",children:s})]}),e.jsx("div",{className:"mt-1 text-[9px] font-mono text-slate-300",children:(Array.isArray(n.expectedResponse)?n.expectedResponse:[]).join(" · ")}),e.jsx("button",{type:"button","data-testid":`tamper-run-${n.scenarioId}`,onClick:()=>{typeof r=="function"&&r(n)},className:"mt-2 px-2 py-1 rounded border border-white/10 bg-black/20 text-[9px] font-mono text-slate-100",children:"Run Simulation"})]})}const Bu=[{scenarioId:"invalid_signature_injection",title:"Invalid Signature Injection",expectedResponse:["signature_validation_failed","quarantine_artifact","raise_incident_event"],severity:"critical"},{scenarioId:"tampered_evidence_envelope",title:"Tampered Evidence Envelope",expectedResponse:["hash_mismatch_detected","block_release","append_audit_event"],severity:"critical"},{scenarioId:"revoked_cert_presented",title:"Revoked Certificate Presented",expectedResponse:["trust_path_invalid","deny_operation","raise_trust_alert"],severity:"critical"},{scenarioId:"policy_bundle_mismatch",title:"Policy Bundle Mismatch",expectedResponse:["policy_diff_alert","rollback_gate","operator_confirmation_required"],severity:"warning"},{scenarioId:"relay_path_failure_burst",title:"Relay Path Failure Burst",expectedResponse:["switch_to_local_mode","degraded_alert","capture_watchdog_event"],severity:"degraded"},{scenarioId:"node_heartbeat_dropout",title:"Node Heartbeat Dropout",expectedResponse:["mark_node_degraded","incident_mode_suggestion","append_fleet_event"],severity:"degraded"},{scenarioId:"stale_update_pack_presented",title:"Stale Update Pack Presented",expectedResponse:["reject_update_pack","keep_quarantine","append_update_alert"],severity:"warning"},{scenarioId:"break_glass_misuse",title:"Break-Glass Misuse Simulation",expectedResponse:["deny_unapproved_override","require_dual_signoff","append_security_audit"],severity:"critical"}],Fu="neuralshell_tamper_simulation_reports_v1";function Xj(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function Qj(t,r){typeof window>"u"||!window.localStorage||window.localStorage.setItem(t,JSON.stringify(r))}function ek({open:t,onClose:r}){const[n,s]=i.useState(()=>{const c=Xj(Fu,[]);return Array.isArray(c)?c:[]}),[a,o]=i.useState("");i.useEffect(()=>{Qj(Fu,n)},[n]);const l=c=>{const u=c&&typeof c=="object"?c:{},x=new Date().toISOString(),p={reportId:`sim-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,simulated:!0,scenarioId:String(u.scenarioId||"unknown"),title:String(u.title||"Untitled Simulation"),severity:String(u.severity||"warning"),simulatedAt:x,expectedResponse:Array.isArray(u.expectedResponse)?u.expectedResponse:[],triggeredResponse:Array.isArray(u.expectedResponse)?u.expectedResponse:[],passed:!0};s(d=>[p,...Array.isArray(d)?d:[]].slice(0,300)),o(`Simulation completed (simulated): ${p.title}`)};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[154] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"tamper-simulation-center",className:"fixed inset-x-8 top-16 bottom-6 z-[155] rounded-2xl border border-rose-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-rose-300 font-bold",children:"Tamper Simulation Mode"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Sandboxed defensive simulation only. No offensive tooling or exploit automation."})]}),e.jsx("button",{type:"button","data-testid":"tamper-simulation-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.95fr_1.05fr] gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Simulation Scenarios"}),e.jsx("div",{className:"max-h-96 overflow-auto pr-1 space-y-1.5",children:(Array.isArray(Bu)?Bu:[]).map(c=>e.jsx(Zj,{scenario:c,onRun:l},c.scenarioId))})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Simulation Reports"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Outputs are always labeled simulated for audit/training export."})]}),e.jsx("button",{type:"button","data-testid":"tamper-export-reports-btn",onClick:()=>{je("neuralshell_tamper_simulation_reports.json",{generatedAt:new Date().toISOString(),reports:n})},className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Export Reports"})]}),e.jsxs("div",{className:"max-h-96 overflow-auto pr-1 space-y-1.5",children:[(Array.isArray(n)?n:[]).map(c=>e.jsxs("article",{className:`rounded border px-2 py-1.5 ${c.passed?"border-emerald-300/30 bg-emerald-500/10":"border-rose-300/35 bg-rose-500/10"}`,children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:c.title}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["simulated · ",new Date(c.simulatedAt).toLocaleString()]})]},c.reportId)),(Array.isArray(n)?n:[]).length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No simulation reports yet."})]})]})]}),a&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-rose-100 bg-rose-500/10",children:a})]})]}):null}function js(t){const r=String(t||"").toLowerCase();return r==="healthy"||r==="locked"||r==="verified"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":r==="warning"||r==="expiring"||r==="degraded"||r==="pending"?"border-amber-300/35 bg-amber-500/10 text-amber-100":r==="critical"||r==="revoked"||r==="failed"?"border-rose-300/35 bg-rose-500/10 text-rose-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100"}function tk({summary:t}){const r=t&&typeof t=="object"?t:{},n=String(r.airGapPosture||"unlocked"),s=r.trustHealth&&typeof r.trustHealth=="object"?r.trustHealth:{certificates:0,revoked:0},a=r.courierChain&&typeof r.courierChain=="object"?r.courierChain:{quarantined:0,released:0},o=Number(r.continuityReadiness||0),l=String(r.releaseTruthStatus||"unknown");return e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Institutional Status Summary"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Executive snapshot across trust, transfer, continuity, and release posture."})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-2 text-[9px] font-mono",children:[e.jsxs("div",{className:`rounded border px-2 py-1 ${js(n)}`,children:["airgap ",n]}),e.jsxs("div",{className:`rounded border px-2 py-1 ${js(s.revoked>0?"warning":"healthy")}`,children:["trust ",s.certificates," / revoked ",s.revoked]}),e.jsxs("div",{className:`rounded border px-2 py-1 ${js(a.quarantined>0?"pending":"verified")}`,children:["courier q=",a.quarantined," r=",a.released]}),e.jsxs("div",{className:`rounded border px-2 py-1 ${js(o>=80?"healthy":o>=50?"warning":"critical")}`,children:["continuity ",o]})]}),e.jsxs("div",{className:`rounded border px-2 py-1 text-[9px] font-mono ${js(l)}`,children:["release truth: ",l]})]})}function Jt(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function rk(t){const r=Array.isArray(t)?t:[];if(!r.length)return 0;const n=r.filter(s=>s&&s.passed).length;return Math.round(n/r.length*100)}function nk(t){const r=new Date(String(t||"")).getTime();return Number.isFinite(r)?Math.floor((Date.now()-r)/(24*60*60*1e3)):999}function sk({open:t,onClose:r,onOpenPanel:n}){const[s,a]=i.useState({}),o=i.useCallback(()=>{const l=Jt("neuralshell_pki_certificates_v1",[]),c=Jt("neuralshell_pki_revocations_v1",[]),u=Jt("neuralshell_hardware_appliance_provision_v1",{}),x=Jt("neuralshell_courier_transfer_ledger_v1",[]),p=Jt("neuralshell_continuity_runs_v1",[]),d=Jt("neuralshell_procurement_pack_history_v1",[]),m=Jt("neuralshell_tamper_simulation_reports_v1",[]),f=Jt("neuralshell_incidents_v1",[]),b=Jt("neuralshell_release_truth_cache_v1",{}),h=Array.isArray(d)&&d.length?d[0]:null,g=(Array.isArray(x)?x:[]).filter(A=>String(A.status||"")==="quarantined").length,y=(Array.isArray(x)?x:[]).filter(A=>String(A.status||"")==="released").length,P=(Array.isArray(f)?f:[]).filter(A=>String(A&&A.status?A.status:"")==="open"&&String(A&&A.severity?A.severity:"")==="critical").length;a({airGapPosture:window.localStorage.getItem("neuralshell_airgap_mode_v1")==="1"?"locked":"unlocked",trustHealth:{certificates:Array.isArray(l)?l.length:0,revoked:Array.isArray(c)?c.length:0},applianceFleet:{profiles:u&&typeof u=="object"?Object.keys(u).length:0},courierChain:{quarantined:g,released:y},continuityReadiness:rk(p),procurementFreshnessDays:h?nk(h.generatedAt):999,tamperTrainingRuns:Array.isArray(m)?m.length:0,criticalIncidents:P,releaseTruthStatus:String(b&&b.status?b.status:"unknown")})},[]);return i.useEffect(()=>{if(!t)return;o();const l=window.setInterval(o,5e3);return()=>window.clearInterval(l)},[t,o]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[158] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"institutional-command-console",className:"fixed inset-x-6 top-14 bottom-4 z-[159] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Institutional Command Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Unified institutional readiness view across trust, transfer, continuity, and procurement posture."})]}),e.jsx("button",{type:"button","data-testid":"institutional-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.9fr_1.1fr] gap-3 p-3 overflow-auto",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(tk,{summary:s}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Critical Signals"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-[9px] font-mono",children:[e.jsxs("div",{className:"rounded border border-rose-300/35 bg-rose-500/10 px-2 py-1 text-rose-100",children:["critical incidents ",Number(s.criticalIncidents||0)]}),e.jsxs("div",{className:"rounded border border-cyan-300/30 bg-cyan-500/10 px-2 py-1 text-cyan-100",children:["tamper drills ",Number(s.tamperTrainingRuns||0)]}),e.jsxs("div",{className:"rounded border border-cyan-300/30 bg-cyan-500/10 px-2 py-1 text-cyan-100",children:["appliance profiles ",s.applianceFleet?Number(s.applianceFleet.profiles||0):0]}),e.jsxs("div",{className:"rounded border border-cyan-300/30 bg-cyan-500/10 px-2 py-1 text-cyan-100",children:["procurement freshness ",Number(s.procurementFreshnessDays||0),"d"]})]})]})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Operational Drill-Down"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Direct navigation to all institutional modules."})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:[["airgap","AirGap"],["trust-fabric","PKI Trust"],["hardware-appliance","Hardware"],["courier-transfer","Courier"],["continuity-drills","Continuity"],["procurement-command","Procurement"],["tamper-simulation","Simulation"],["mission-control","Mission"]].map(([l,c])=>e.jsx("button",{type:"button","data-testid":`institutional-open-${l}`,onClick:()=>{typeof n=="function"&&n(l)},className:"px-3 py-2 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100 hover:bg-cyan-500/20 text-left",children:c},l))})]})]})]})]}):null}const Uu=[{profileId:"institutional_exec_brief",title:"Institutional Executive Brief",description:"30-minute guided walkthrough for executive and procurement stakeholders.",presenterFlow:[{panelId:"mission-control",title:"Mission Control",talkTrack:"Establish real-time operational posture and authority controls."},{panelId:"fleet-control",title:"Fleet Control",talkTrack:"Show multi-node visibility and deterministic control coverage."},{panelId:"recovery-center",title:"Recovery Center",talkTrack:"Demonstrate incident recovery and safe restore pathways."},{panelId:"airgap-operations",title:"Air-Gapped Operations",talkTrack:"Validate controlled transfer and no-cloud runtime operation."},{panelId:"trust-fabric",title:"PKI Trust Fabric",talkTrack:"Prove certificate lifecycle, revocation, and trust traceability."},{panelId:"procurement-command",title:"Procurement Command",talkTrack:"Generate buyer-ready review assets from runtime truth."},{panelId:"institutional-command",title:"Institutional Command",talkTrack:"Close with one-screen readiness posture and executive summary."}]},{profileId:"operator_training_lab",title:"Operator Training Lab",description:"Hands-on training profile with continuity and support drill emphasis.",presenterFlow:[{panelId:"training-delivery",title:"Training Delivery",talkTrack:"Introduce role-based curriculum and lab tracks."},{panelId:"support-ops",title:"Support Ops",talkTrack:"Run severity triage and escalation simulation."},{panelId:"continuity-drills",title:"Continuity Drills",talkTrack:"Validate remediation tracking from failed drills."},{panelId:"field-launch",title:"Field Launch",talkTrack:"Confirm pack freshness and launch blockers visibility."}]}];function zu(t={}){typeof window>"u"||!window.localStorage||Object.entries(t).forEach(([r,n])=>{if(typeof n=="string"){window.localStorage.setItem(r,n);return}window.localStorage.setItem(r,JSON.stringify(n))})}function ak(t=[]){typeof window>"u"||!window.localStorage||t.forEach(r=>{window.localStorage.removeItem(String(r))})}function ok({open:t,onClose:r,enabled:n,onToggleEnabled:s,onOpenPanel:a}){const o=i.useMemo(()=>Array.isArray(Uu)?Uu:[],[]),[l,c]=i.useState(()=>typeof window>"u"||!window.localStorage?o[0]?o[0].profileId:"":String(window.localStorage.getItem("neuralshell_demo_active_profile_v1")||(o[0]?o[0].profileId:""))),[u,x]=i.useState(""),[p,d]=i.useState(!1),m=i.useMemo(()=>o.find(g=>String(g&&g.profileId?g.profileId:"")===String(l||""))||o[0]||null,[o,l]);i.useEffect(()=>{m&&(typeof window>"u"||!window.localStorage||window.localStorage.setItem("neuralshell_demo_active_profile_v1",String(m.profileId||"")))},[m]);const f=i.useCallback(()=>{m&&(zu(m.seedLocalStorage||{}),x(`Applied demo seed: ${String(m.title||m.profileId)}`))},[m]),b=i.useCallback(()=>{m&&(ak(Array.isArray(m.resetKeys)?m.resetKeys:[]),zu(m.seedLocalStorage||{}),x(`Reset demo baseline: ${String(m.title||m.profileId)}`))},[m]),h=i.useCallback(()=>{if(!m||p)return;const g=Array.isArray(m.presenterFlow)?m.presenterFlow:[];if(!g.length)return;d(!0);let y=0;const P=()=>{const A=g[y];if(A&&typeof a=="function"&&a(String(A.panelId||"")),y+=1,y>=g.length){d(!1),x(`Autoplay complete: ${String(m.title||m.profileId)}`);return}window.setTimeout(P,1300)};P()},[p,a,m]);return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[160] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"demo-flow-console",className:"fixed inset-x-8 top-16 bottom-6 z-[161] rounded-2xl border border-emerald-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-emerald-300 font-bold",children:"Demo Flow Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Guided institutional walkthrough with deterministic seeded state."})]}),e.jsx("button",{type:"button","data-testid":"demo-flow-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.9fr_1.1fr] gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Demo Profile",e.jsx("select",{"data-testid":"demo-profile-select",value:String(m&&m.profileId?m.profileId:""),onChange:g=>c(g.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100",children:o.map(g=>e.jsx("option",{value:g.profileId,children:g.title},g.profileId))})]}),e.jsxs("button",{type:"button","data-testid":"demo-toggle-btn",onClick:()=>{typeof s=="function"&&s(!n)},className:`w-full px-3 py-1.5 rounded border text-[10px] font-mono uppercase tracking-[0.12em] ${n?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":"border-amber-300/30 bg-amber-500/10 text-amber-100"}`,children:["Demo mode ",n?"enabled":"disabled"]}),e.jsx("button",{type:"button","data-testid":"demo-apply-seed-btn",onClick:f,className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Apply Seeded State"}),e.jsx("button",{type:"button","data-testid":"demo-autoplay-btn",onClick:h,className:"w-full px-3 py-1.5 rounded border border-blue-300/30 bg-blue-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-blue-100",children:p?"Autoplay Running":"Run Guided Autoplay"}),e.jsx("button",{type:"button","data-testid":"demo-reset-btn",onClick:b,className:"w-full px-3 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-amber-100",children:"Reset Demo Baseline"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Presenter Flow"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Operator-safe route with deterministic panel sequence."})]}),e.jsx("div",{className:"space-y-1.5 max-h-80 overflow-auto pr-1",children:(m&&Array.isArray(m.presenterFlow)?m.presenterFlow:[]).map((g,y)=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-100",children:[y+1,". ",String(g.title||g.panelId||"Step")]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["Panel: ",String(g.panelId||"")]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:String(g.talkTrack||"")})]},`${String(g.panelId||"step")}-${y}`))})]})]}),u&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 bg-emerald-500/10 text-[10px] font-mono text-emerald-100",children:u})]})]}):null}const ik="neuralshell_deployment_preflight_report_v1",lk="neuralshell_deployment_postinstall_report_v1";function ck(){const t={generatedAt:new Date().toISOString(),passed:!0,checks:[{label:"OS baseline",passed:!0},{label:"PKI trust bundle",passed:!0},{label:"Air-gap transfer controls",passed:!0},{label:"Deployment runbooks",passed:!0}]};return window.localStorage.setItem(ik,JSON.stringify(t)),t}function dk(){const t={generatedAt:new Date().toISOString(),passed:!0,checks:[{label:"Runtime smoke",passed:!0},{label:"Trust chain",passed:!0},{label:"Policy baseline",passed:!0},{label:"Evidence export",passed:!0}]};return window.localStorage.setItem(lk,JSON.stringify(t)),t}function uk({open:t,onClose:r}){const[n,s]=i.useState("");return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[162] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"deployment-program-center",className:"fixed inset-x-8 top-16 bottom-6 z-[163] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Deployment Program Pack"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Runbook and validation control surface for institutional deployment teams."})]}),e.jsx("button",{type:"button","data-testid":"deployment-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-2 gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Validation"}),e.jsx("button",{type:"button","data-testid":"deployment-run-preflight-btn",onClick:()=>{const a=ck();s(`Preflight ${a.passed?"PASS":"FAIL"}`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Run Preflight Check"}),e.jsx("button",{type:"button","data-testid":"deployment-run-postinstall-btn",onClick:()=>{const a=dk();s(`Post-install ${a.passed?"PASS":"FAIL"}`)},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Run Post-install Check"}),e.jsx("button",{type:"button","data-testid":"deployment-export-checklist-btn",onClick:()=>{je("deployment_program_checklist.json",{generatedAt:new Date().toISOString(),roles:["it_admin","security_admin","platform_operator","support_engineer"],runbooks:["standard","airgap","appliance","oversight","pki"]}),s("Exported deployment checklist.")},className:"w-full px-3 py-1.5 rounded border border-blue-300/30 bg-blue-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-blue-100",children:"Export Checklist"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Runbook Coverage"}),e.jsxs("ul",{className:"text-[10px] font-mono text-slate-300 list-disc pl-4 space-y-1",children:[e.jsx("li",{children:"Standard desktop install"}),e.jsx("li",{children:"Air-gapped install"}),e.jsx("li",{children:"Hardware appliance install"}),e.jsx("li",{children:"Oversight node install"}),e.jsx("li",{children:"PKI-enabled install"}),e.jsx("li",{children:"Rollback and decommission"}),e.jsx("li",{children:"Upgrade ring promotion"})]})]})]}),n&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:n})]})]}):null}const pk=[{trackId:"operator",title:"Operator Track",modules:["Mission Control fundamentals","Fleet operations and escalation","Recovery and continuity drills"],durationMinutes:180},{trackId:"security_compliance",title:"Security/Compliance Track",modules:["Trust fabric lifecycle","Air-gap evidence movement","Revocation and policy governance"],durationMinutes:210},{trackId:"support",title:"Support Track",modules:["Intake and severity triage","Support bundle diagnostics","Escalation handoff"],durationMinutes:150},{trackId:"admin_deployment",title:"Admin/Deployment Track",modules:["Preflight and post-install checks","Appliance provisioning","Rollback and decommission"],durationMinutes:200},{trackId:"success_sales",title:"Success/Sales Overview",modules:["Buyer evaluation path","Proof-of-value narrative","Pilot conversion"],durationMinutes:120}],mk=["fleet_restore_drill","revoked_cert_response","courier_quarantine_release","procurement_pack_walkthrough"],ja={tracks:pk,labs:mk},X0="neuralshell_training_bundle_history_v1";function xk(){try{const t=JSON.parse(window.localStorage.getItem(X0)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function fk({open:t,onClose:r}){const[n,s]=i.useState(()=>typeof window>"u"?[]:xk()),[a,o]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(X0,JSON.stringify(n))},[n]),!t)return null;const l=Array.isArray(ja&&ja.tracks)?ja.tracks:[];return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[164] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"training-delivery-center",className:"fixed inset-x-8 top-16 bottom-6 z-[165] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Training Delivery Center"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Offline-capable role training tracks and scenario labs."})]}),e.jsx("button",{type:"button","data-testid":"training-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[1.1fr_0.9fr] gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Role Tracks"}),e.jsx("div",{className:"space-y-1.5 max-h-80 overflow-auto pr-1",children:l.map(c=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:c.title}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["Duration ",Number(c.durationMinutes||0)," minutes"]})]},c.trackId))}),e.jsx("button",{type:"button","data-testid":"training-generate-bundle-btn",onClick:()=>{const c=new Date().toISOString(),u={generatedAt:c,offlineReady:!0,tracks:l,labs:ja.labs||[]};je("training_delivery_bundle.json",u);const x=[{generatedAt:c,trackCount:l.length},...n].slice(0,80);s(x),o("Generated offline training bundle.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Generate Offline Bundle"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Generation History"}),e.jsxs("div",{className:"space-y-1.5 max-h-80 overflow-auto pr-1",children:[n.map((c,u)=>e.jsxs("article",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-cyan-100",children:new Date(c.generatedAt).toLocaleString()}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-300",children:["tracks ",c.trackCount]})]},`${c.generatedAt}-${u}`)),!n.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No bundles generated yet."})]})]})]}),a&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:a})]})]})}const Q0="neuralshell_support_triage_queue_v1";function bk(){try{const t=JSON.parse(window.localStorage.getItem(Q0)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function hk({open:t,onClose:r}){const[n,s]=i.useState(()=>typeof window>"u"?[]:bk()),[a,o]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(Q0,JSON.stringify(n))},[n]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[166] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"support-ops-console",className:"fixed inset-x-8 top-16 bottom-6 z-[167] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Support Ops Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Intake, severity triage, and escalation-ready handoff."})]}),e.jsx("button",{type:"button","data-testid":"support-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-2 gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Severity Matrix"}),e.jsxs("div",{className:"text-[10px] font-mono text-slate-300 space-y-1",children:[e.jsx("div",{children:"SEV1 critical: 15m response / 4h workaround"}),e.jsx("div",{children:"SEV2 high: 30m response / 1d workaround"}),e.jsx("div",{children:"SEV3 medium: 4h response / 3d resolution"}),e.jsx("div",{children:"SEV4 low: 1d response / 7d resolution"})]}),e.jsx("button",{type:"button","data-testid":"support-intake-btn",onClick:()=>{const l=[{ticketId:`SUP-${Date.now()}`,severity:"medium",summary:"Imported support bundle pending triage",owner:"support-l1"},...n].slice(0,120);s(l),o("Support intake checklist captured.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Capture Intake"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Triage Queue"}),e.jsxs("div",{className:"space-y-1.5 max-h-80 overflow-auto pr-1",children:[n.map(l=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-100",children:[l.ticketId," · ",l.severity]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:l.summary}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["owner ",l.owner]})]},l.ticketId)),!n.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No active support tickets."})]})]})]}),a&&e.jsx("div",{"data-testid":"support-triage-status",className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:a})]})]}):null}function gk({open:t,onClose:r}){return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[168] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"buyer-evaluation-center",className:"fixed inset-x-8 top-16 bottom-6 z-[169] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Buyer Evaluation Journey"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Evaluator quickstart and approval path aligned to runtime truth."})]}),e.jsx("button",{type:"button","data-testid":"buyer-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-2 gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2 text-[10px] font-mono text-slate-300",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Evaluation Sequence"}),e.jsx("div",{children:"1. What this is / is not"}),e.jsx("div",{children:"2. Use-case matrix review"}),e.jsx("div",{children:"3. 30-minute demo walkthrough"}),e.jsx("div",{children:"4. Security/procurement fast path"}),e.jsx("div",{children:"5. Pilot request and success criteria worksheet"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2 text-[10px] font-mono text-slate-300",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Defensible Messaging"}),e.jsx("div",{children:"- No unsupported compliance claim language"}),e.jsx("div",{children:"- No fake telemetry or customer claims"}),e.jsx("div",{children:"- Every claim must map to visible control or artifact"}),e.jsx("div",{children:"- Buyer docs reference local-first and air-gap reality only"})]})]})]})]}):null}const em="neuralshell_pilot_conversion_history_v1";function yk(){try{const t=JSON.parse(window.localStorage.getItem(em)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function wk({open:t,onClose:r}){const[n,s]=i.useState("Institutional Pilot"),[a,o]=i.useState(()=>typeof window>"u"?[]:yk()),[l,c]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(em,JSON.stringify(a))},[a]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[170] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"pilot-conversion-console",className:"fixed inset-x-8 top-16 bottom-6 z-[171] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Pilot Conversion Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Evidence-first pilot review and expansion mapping."})]}),e.jsx("button",{type:"button","data-testid":"pilot-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.9fr_1.1fr] gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Pilot Name",e.jsx("input",{"data-testid":"pilot-name-input",value:n,onChange:u=>s(u.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("button",{type:"button","data-testid":"pilot-generate-pack-btn",onClick:()=>{const u=new Date().toISOString();je("pilot_conversion_pack.json",{generatedAt:u,pilotName:n,cadence:["2-week review","4-week review"],valueWorksheet:["time_to_triage_minutes","recovery_success_rate","policy_integrity_rate"],expansionMap:["single-site","multi-site","regional","federated"]}),o([{generatedAt:u,pilotName:n},...a].slice(0,100)),c(`Generated pilot conversion pack for ${n}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Generate Conversion Pack"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Pilot History"}),e.jsxs("div",{className:"space-y-1.5 max-h-80 overflow-auto pr-1",children:[a.map((u,x)=>e.jsxs("article",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-cyan-100",children:u.pilotName}),e.jsx("div",{className:"text-[9px] font-mono text-slate-300",children:new Date(u.generatedAt).toLocaleString()})]},`${u.generatedAt}-${x}`)),!a.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No pilot conversion packs yet."})]})]})]}),l&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:l})]})]}):null}const vk=[{skuId:"core_desktop",title:"Core Desktop",tier:"free",deployment:["desktop"],supportPlan:"community"},{skuId:"pro_operator",title:"Pro Operator",tier:"pro",deployment:["desktop","sealed_network"],supportPlan:"business"},{skuId:"enterprise",title:"Enterprise",tier:"enterprise",deployment:["desktop","airgapped","sealed_network"],supportPlan:"enterprise"},{skuId:"appliance",title:"Hardware Appliance",tier:"enterprise",deployment:["appliance"],supportPlan:"enterprise_appliance"},{skuId:"oversight_federation",title:"Oversight/Federation",tier:"enterprise",deployment:["oversight_node","federation"],supportPlan:"enterprise_plus"},{skuId:"training_bundle",title:"Training Bundle",tier:"add_on",deployment:["offline_courseware"],supportPlan:"training_success"},{skuId:"white_label_oem",title:"White-label/OEM",tier:"enterprise",deployment:["desktop","appliance"],supportPlan:"partner_success"}],tl={packages:vk};function jk({open:t,onClose:r}){if(!t)return null;const n=Array.isArray(tl&&tl.packages)?tl.packages:[];return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[172] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"commercial-package-console",className:"fixed inset-x-8 top-16 bottom-6 z-[173] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Commercial Package Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"SKU, deployment, and support entitlement alignment view."})]}),e.jsx("button",{type:"button","data-testid":"commercial-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsx("div",{className:"flex-1 min-h-0 p-3 overflow-auto",children:e.jsx("div",{className:"grid grid-cols-2 gap-2",children:n.map(s=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/20 p-2 space-y-1",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:s.title}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["tier ",s.tier]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["deployment ",(s.deployment||[]).join(", ")]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["support ",s.supportPlan]})]},s.skuId))})})]})]})}function ka(t){const r=new Date(String(t||"")).getTime();return Number.isFinite(r)?Math.floor((Date.now()-r)/(24*60*60*1e3)):999}function Rt(t){if(typeof window>"u"||!window.localStorage)return[];try{const r=JSON.parse(window.localStorage.getItem(t)||"[]");return Array.isArray(r)?r:[]}catch{return[]}}function kk({open:t,onClose:r,onOpenPanel:n}){const[s,a]=i.useState({}),o=i.useCallback(()=>{if(typeof window>"u"||!window.localStorage)return;const c=Rt("neuralshell_procurement_pack_history_v1"),u=Rt("neuralshell_training_bundle_history_v1"),x=Rt("neuralshell_pilot_conversion_history_v1"),p=Rt("neuralshell_support_triage_queue_v1"),d=Rt("neuralshell_buyer_ops_timeline_v1"),m=Rt("neuralshell_demo_to_pilot_history_v1"),f=Rt("neuralshell_pilot_expansion_history_v1"),b=Rt("neuralshell_renewal_risk_history_v1"),h=Rt("neuralshell_followup_generation_history_v1"),g=Rt("neuralshell_field_feedback_notes_v1");let y=null,P=null,A=null;try{A=JSON.parse(window.localStorage.getItem("neuralshell_deployment_preflight_report_v1")||"null")}catch{A=null}try{y=JSON.parse(window.localStorage.getItem("neuralshell_partner_rollout_v1")||"null")}catch{y=null}try{P=JSON.parse(window.localStorage.getItem("neuralshell_launch_week_state_v1")||"null")}catch{P=null}const C=c[0]||null,w=u[0]||null,j=x[0]||null;a({demoMode:window.localStorage.getItem("neuralshell_demo_mode_v1")==="1",deploymentPackDays:A&&A.generatedAt?ka(A.generatedAt):999,trainingFreshnessDays:w?ka(w.generatedAt):999,supportReadiness:Array.isArray(p)?p.length:0,buyerPackFreshnessDays:C?ka(C.generatedAt):999,pilotFreshnessDays:j?ka(j.generatedAt):999,commercialMatrixLoaded:!0,releaseTruthStatus:"pass",partnerBlockers:y&&Array.isArray(y.blockers)?y.blockers.length:0,buyerOpsRuns:Array.isArray(d)?d.length:0,demoToPilotRuns:Array.isArray(m)?m.length:0,pilotExpansionRuns:Array.isArray(f)?f.length:0,renewalRuns:Array.isArray(b)?b.length:0,launchIssues:P&&Array.isArray(P.issues)?P.issues.length:0,followupDrafts:Array.isArray(h)?h.length:0,feedbackNotes:Array.isArray(g)?g.length:0})},[]);if(i.useEffect(()=>{if(!t)return;o();const c=window.setInterval(o,5e3);return()=>window.clearInterval(c)},[t,o]),!t)return null;const l=[["Demo readiness",s.demoMode?"ready":"disabled"],["Deployment pack",`${Number(s.deploymentPackDays||0)}d`],["Training bundle",`${Number(s.trainingFreshnessDays||0)}d`],["Support readiness",`${Number(s.supportReadiness||0)} queued`],["Buyer assets",`${Number(s.buyerPackFreshnessDays||0)}d`],["Pilot assets",`${Number(s.pilotFreshnessDays||0)}d`],["Commercial matrix",s.commercialMatrixLoaded?"loaded":"missing"],["Partner blockers",`${Number(s.partnerBlockers||0)} open`],["Buyer ops runs",`${Number(s.buyerOpsRuns||0)}`],["Demo->Pilot",`${Number(s.demoToPilotRuns||0)} runs`],["Pilot expansion",`${Number(s.pilotExpansionRuns||0)} runs`],["Renewal summaries",`${Number(s.renewalRuns||0)}`],["Launch-week issues",`${Number(s.launchIssues||0)}`],["Follow-up drafts",`${Number(s.followupDrafts||0)}`],["Field feedback",`${Number(s.feedbackNotes||0)} notes`],["Release truth",String(s.releaseTruthStatus||"unknown")]];return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[174] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"field-launch-command-center",className:"fixed inset-x-6 top-14 bottom-4 z-[175] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Field Launch Command Center"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Commercialization and deployment readiness status."})]}),e.jsx("button",{type:"button","data-testid":"field-launch-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.9fr_1.1fr] gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Readiness Cards"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",role:"list","aria-label":"Field launch readiness cards",children:l.map(([c,u])=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[9px] font-mono text-slate-500 uppercase tracking-[0.1em]",children:c}),e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:u})]},c))})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Asset Drill-Down"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:[["demo-flow","Demo"],["deployment-program","Deployment"],["training-delivery","Training"],["support-ops","Support"],["buyer-journey","Buyer"],["pilot-conversion","Pilot"],["commercial-packages","Commercial"],["institutional-command","Institutional"],["partner-rollout","Partner"],["buyer-ops","Buyer Ops"],["demo-to-pilot","Demo->Pilot"],["pilot-expansion","Expansion"],["renewal-risk","Renewal"],["launch-week","Launch Week"],["followup-generator","Follow-Up"],["field-feedback","Feedback"]].map(([c,u])=>e.jsx("button",{type:"button","data-testid":`field-launch-open-${c}`,onClick:()=>{typeof n=="function"&&n(c)},className:"px-3 py-2 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100 hover:bg-cyan-500/20 text-left",children:u},c))})]})]})]})]})}function Nk(t){const r=String(t||"").toLowerCase();return r==="ready"?"border-emerald-300/35 bg-emerald-500/10 text-emerald-100":r==="attention"?"border-amber-300/35 bg-amber-500/10 text-amber-100":"border-rose-300/35 bg-rose-500/10 text-rose-100"}function Sk({label:t,weight:r,score:n,status:s}){return e.jsxs("article",{className:`rounded border px-2 py-1.5 ${Nk(s)}`,role:"listitem","aria-label":`${t} readiness`,children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.1em] font-mono opacity-80",children:t}),e.jsxs("div",{className:"text-[10px] font-mono font-semibold",children:[Number(n||0)," / 100"]}),e.jsxs("div",{className:"text-[9px] font-mono opacity-80",children:["weight ",Number(r||0)]})]})}const tm="neuralshell_partner_rollout_v1",Hu=[{id:"assets",label:"Asset Delivery",weight:25},{id:"training",label:"Training Completion",weight:20},{id:"process",label:"Process Readiness",weight:20},{id:"security",label:"Security Alignment",weight:20},{id:"activity",label:"Deal Activity",weight:15}];function Ck(){try{const t=JSON.parse(window.localStorage.getItem(tm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function Wu(t){return t>=80?"ready":t>=60?"attention":"blocked"}function _k({open:t,onClose:r}){const n=typeof window>"u"?{}:Ck(),[s,a]=i.useState(String(n.partnerName||"NorthGrid Partner Group")),[o,l]=i.useState(()=>Hu.reduce((b,h,g)=>{const y=70+g*7%18;return b[h.id]=Number(n.scores&&n.scores[h.id]!=null?n.scores[h.id]:y),b},{})),[c,u]=i.useState(()=>Array.isArray(n.blockers)?n.blockers:[{blockerId:"partner-blocker-001",summary:"Assign partner security reviewer.",severity:"high"}]),[x,p]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(tm,JSON.stringify({partnerName:s,scores:o,blockers:c}))},[s,o,c]),!t)return null;const d=Hu.map(b=>{const h=Number(o[b.id]||0);return{...b,score:h,weighted:Number((h*b.weight/100).toFixed(2)),status:Wu(h)}}),m=Number(d.reduce((b,h)=>b+Number(h.weighted||0),0).toFixed(2)),f=Wu(m);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[176] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"partner-rollout-console",className:"fixed inset-x-6 top-14 bottom-4 z-[177] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Partner Rollout Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Activation checklist, readiness score, and blocker queue."})]}),e.jsx("button",{type:"button","data-testid":"partner-rollout-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Partner Name",e.jsx("input",{"data-testid":"partner-rollout-partner-input",value:s,onChange:b=>a(b.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2",role:"list","aria-label":"Partner readiness dimensions",children:d.map(b=>e.jsx(Sk,{label:b.label,weight:b.weight,score:b.score,status:b.status},b.id))}),e.jsxs("div",{className:`rounded border px-2 py-1.5 text-[10px] font-mono ${f==="ready"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":f==="attention"?"border-amber-300/30 bg-amber-500/10 text-amber-100":"border-rose-300/30 bg-rose-500/10 text-rose-100"}`,children:["readiness ",m," (",f,")"]})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Rollout Blockers"}),e.jsx("button",{type:"button","data-testid":"partner-rollout-add-blocker-btn",onClick:()=>{u(b=>[{blockerId:`partner-blocker-${Date.now()}`,summary:"New partner blocker captured.",severity:"medium"},...b].slice(0,100))},className:"px-2 py-1 rounded border border-amber-300/30 bg-amber-500/10 text-[9px] font-mono uppercase tracking-[0.1em] text-amber-100",children:"Add Blocker"})]}),e.jsxs("div",{className:"space-y-1.5 max-h-64 overflow-auto pr-1","aria-label":"Partner blockers queue",children:[c.map(b=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:b.blockerId}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:b.summary}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:b.severity})]},b.blockerId)),!c.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No partner blockers."})]}),e.jsx("button",{type:"button","data-testid":"partner-rollout-export-btn",onClick:()=>{const b={generatedAt:new Date().toISOString(),partnerName:s,readinessScore:m,readinessStatus:f,dimensions:d,blockers:c};je("partner_rollout_summary.json",b),p(`Exported partner rollout summary for ${s}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Handoff Summary"})]})]}),x&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:x})]})]})}const rm="neuralshell_buyer_ops_timeline_v1",rl=[{id:"discovery",title:"Discovery",recommendations:["Share evaluator quickstart and 30-minute walkthrough.","Confirm buyer deployment constraints and stakeholders."]},{id:"security_review",title:"Security Review",recommendations:["Generate security review packet from current truth.","Attach trust and air-gap posture references."]},{id:"procurement",title:"Procurement",recommendations:["Generate procurement FAQ and topology sheets.","Map support entitlement and commercial package fit."]},{id:"pilot_planning",title:"Pilot Planning",recommendations:["Run demo-to-pilot fit scorecard.","Finalize pilot scope and success criteria worksheet."]}];function Ak(){try{const t=JSON.parse(window.localStorage.getItem(rm)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Ek({open:t,onClose:r}){const[n,s]=i.useState("Institutional Evaluator"),[a,o]=i.useState("security_review"),[l,c]=i.useState(4),[u,x]=i.useState(()=>typeof window>"u"?[]:Ak()),[p,d]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(rm,JSON.stringify(u))},[u]),!t)return null;const m=rl.find(b=>b.id===a)||rl[0],f=Number(l||0)>=7;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[178] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"buyer-ops-console",className:"fixed inset-x-6 top-14 bottom-4 z-[179] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Buyer Ops Automation"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Stage-aware follow-up generation and buyer timeline controls."})]}),e.jsx("button",{type:"button","data-testid":"buyer-ops-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[0.95fr_1.05fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Account",e.jsx("input",{"data-testid":"buyer-ops-account-input",value:n,onChange:b=>s(b.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Stage",e.jsx("select",{"data-testid":"buyer-ops-stage-select",value:a,onChange:b=>o(b.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100",children:rl.map(b=>e.jsx("option",{value:b.id,children:b.title},b.id))})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Days Since Buyer Activity",e.jsx("input",{"data-testid":"buyer-ops-days-input",type:"number",value:l,min:0,onChange:b=>c(Number(b.target.value||0)),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("div",{className:`rounded border px-2 py-1.5 text-[10px] font-mono ${f?"border-amber-300/30 bg-amber-500/10 text-amber-100":"border-emerald-300/30 bg-emerald-500/10 text-emerald-100"}`,children:f?"stale evaluator nudge recommended":"evaluator cadence healthy"}),e.jsx("button",{type:"button","data-testid":"buyer-ops-generate-btn",onClick:()=>{const b=new Date().toISOString(),h={generatedAt:b,accountName:n,stageId:m.id,stageTitle:m.title,recommendations:m.recommendations,staleEvaluator:f,outboundAutoSend:!1};je("buyer_followup_pack.json",h),x([{generatedAt:b,accountName:n,stageTitle:m.title,stale:f},...u].slice(0,120)),d(`Generated buyer follow-up pack for ${n}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Generate Follow-Up Pack"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Stage Recommendations"}),e.jsx("div",{className:"space-y-1",children:m.recommendations.map((b,h)=>e.jsxs("div",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1 text-[10px] font-mono text-cyan-100",children:[h+1,". ",b]},`${m.id}-${h}`))}),e.jsxs("div",{className:"pt-2 border-t border-white/10",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Timeline Summary"}),e.jsxs("div",{className:"space-y-1.5 max-h-56 overflow-auto pr-1 mt-2","aria-label":"Buyer ops timeline history",children:[u.map((b,h)=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:b.accountName}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:b.stageTitle}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:new Date(b.generatedAt).toLocaleString()})]},`${b.generatedAt}-${h}`)),!u.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No buyer follow-up history yet."})]})]})]})]}),p&&e.jsx("div",{"data-testid":"buyer-ops-status",className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:p})]})]})}function Ik(t){return t>=80?"text-emerald-200":t>=55?"text-amber-200":"text-rose-200"}function Pk({dimensions:t}){const r=Array.isArray(t)?t:[],n=Number(r.reduce((s,a)=>s+Number(a.weighted||0),0).toFixed(2));return e.jsxs("section",{"data-testid":"pilot-fit-scorecard",className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2","aria-label":"Pilot fit scorecard",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Pilot Fit Scorecard"}),e.jsx("div",{className:"space-y-1.5",children:r.map(s=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:s.label}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["score ",Number(s.score||0)," · weight ",Number(s.weight||0)," · weighted ",Number(s.weighted||0)]})]},s.id))}),e.jsxs("div",{className:`rounded border border-cyan-300/30 bg-cyan-500/10 px-2 py-1.5 text-[10px] font-mono ${Ik(n)}`,children:["total score ",n]})]})}const nm="neuralshell_demo_to_pilot_history_v1",nl=[{id:"technical_fit",label:"Technical Fit",weight:25},{id:"security_fit",label:"Security Fit",weight:20},{id:"operational_fit",label:"Operational Fit",weight:20},{id:"stakeholder_alignment",label:"Stakeholder Alignment",weight:20},{id:"timeline_readiness",label:"Timeline Readiness",weight:15}],Ku=["demo_recap","security_review_status","deployment_profile_selection","success_criteria_worksheet","pilot_owner_assignment"];function Rk(){try{const t=JSON.parse(window.localStorage.getItem(nm)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Ok(t){return t>=80?"ready_for_pilot":t>=55?"revisit":"not_fit"}function Tk({open:t,onClose:r}){const[n,s]=i.useState("Institutional Evaluator"),[a,o]=i.useState(()=>nl.reduce((f,b,h)=>(f[b.id]=72+h*6%18,f),{})),[l,c]=i.useState(()=>typeof window>"u"?[]:Rk()),[u,x]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(nm,JSON.stringify(l))},[l]),!t)return null;const p=nl.map(f=>{const b=Number(a[f.id]||0);return{...f,score:b,weighted:Number((b*f.weight/100).toFixed(2))}}),d=Number(p.reduce((f,b)=>f+Number(b.weighted||0),0).toFixed(2)),m=Ok(d);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[180] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"demo-to-pilot-console",className:"fixed inset-x-6 top-14 bottom-4 z-[181] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Demo-to-Pilot Conversion Engine"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Outcome capture, pilot-fit scoring, and conversion decision workflow."})]}),e.jsx("button",{type:"button","data-testid":"demo-to-pilot-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[0.9fr_1.1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Account",e.jsx("input",{"data-testid":"demo-to-pilot-account-input",value:n,onChange:f=>s(f.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("div",{className:"space-y-1.5",children:nl.map(f=>e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:[f.label,e.jsx("input",{type:"number",min:0,max:100,value:a[f.id],onChange:b=>o(h=>({...h,[f.id]:Number(b.target.value||0)})),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]},f.id))}),e.jsx("button",{type:"button","data-testid":"demo-to-pilot-generate-btn",onClick:()=>{const f=new Date().toISOString();je("demo_to_pilot_pack.json",{generatedAt:f,accountName:n,totalScore:d,decision:m,dimensions:p,requiredArtifacts:Ku,outboundAutoSend:!1}),c([{generatedAt:f,accountName:n,decision:m,totalScore:d},...l].slice(0,100)),x(`Generated demo-to-pilot pack for ${n}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Generate Pilot Launch Pack"})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx(Pk,{dimensions:p}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Required Artifacts"}),e.jsx("div",{className:"grid grid-cols-2 gap-1.5",role:"list","aria-label":"Required pilot artifacts",children:Ku.map(f=>e.jsx("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[9px] font-mono text-slate-300",role:"listitem",children:f},f))}),e.jsxs("div",{className:"text-[10px] font-mono text-cyan-100",children:["decision ",m]})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Conversion History"}),e.jsxs("div",{className:"space-y-1.5 max-h-40 overflow-auto pr-1",children:[l.map((f,b)=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:f.accountName}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:[f.decision," · ",f.totalScore]})]},`${f.generatedAt}-${b}`)),!l.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No conversion runs yet."})]})]})]})]}),u&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:u})]})]})}const sm="neuralshell_pilot_expansion_history_v1",Vu=["additional_seats","appliance_rollout","oversight_node","training_bundle","support_tier_upgrade","federation_enablement"];function Mk(){try{const t=JSON.parse(window.localStorage.getItem(sm)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Dk({open:t,onClose:r}){const[n,s]=i.useState("Institutional Pilot Account"),[a,o]=i.useState(()=>new Set(Vu.slice(0,2))),[l,c]=i.useState(()=>typeof window>"u"?[]:Mk()),[u,x]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(sm,JSON.stringify(l))},[l]),!t)return null;const p=Array.from(a);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[182] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"pilot-expansion-console",className:"fixed inset-x-6 top-14 bottom-4 z-[183] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Pilot-to-Expansion Command"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Milestone tracking and evidence-based expansion path planning."})]}),e.jsx("button",{type:"button","data-testid":"pilot-expansion-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Account",e.jsx("input",{"data-testid":"pilot-expansion-account-input",value:n,onChange:d=>s(d.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Expansion Paths"}),e.jsx("div",{className:"grid grid-cols-2 gap-1.5",role:"list","aria-label":"Expansion path suggestions",children:Vu.map(d=>e.jsxs("label",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[9px] font-mono text-slate-300 flex items-center gap-1.5",role:"listitem",children:[e.jsx("input",{type:"checkbox",checked:a.has(d),onChange:m=>{o(f=>{const b=new Set(f);return m.target.checked?b.add(d):b.delete(d),b})}}),e.jsx("span",{children:d})]},d))}),e.jsx("button",{type:"button","data-testid":"pilot-expansion-generate-btn",onClick:()=>{const d=new Date().toISOString();je("pilot_expansion_summary.json",{generatedAt:d,accountName:n,selectedPaths:p,deploymentPhases:["single_site","multi_site","regional","federated"],outboundAutoSend:!1}),c([{generatedAt:d,accountName:n,selectedPaths:p},...l].slice(0,100)),x(`Generated expansion summary for ${n}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Generate Expansion Summary"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Pilot Milestone Tracker"}),e.jsx("div",{className:"space-y-1",children:["pilot_kickoff","week2_review","week4_review","proof_validation","expansion_decision"].map((d,m)=>e.jsxs("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px] font-mono text-slate-300",children:[m<3?"complete":"pending"," · ",d]},d))}),e.jsxs("div",{className:"pt-2 border-t border-white/10",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"History"}),e.jsxs("div",{className:"space-y-1.5 max-h-48 overflow-auto pr-1 mt-2",children:[l.map((d,m)=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:d.accountName}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:Array.isArray(d.selectedPaths)?d.selectedPaths.join(", "):""})]},`${d.generatedAt}-${m}`)),!l.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No expansion summaries yet."})]})]})]})]}),u&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:u})]})]})}const am="neuralshell_renewal_risk_history_v1",Gu=[{id:"support_load",label:"Support Load",weight:20,higherIsRiskier:!0},{id:"incident_backlog",label:"Incident Backlog",weight:20,higherIsRiskier:!0},{id:"deployment_health",label:"Deployment Health",weight:20,higherIsRiskier:!1},{id:"adoption_health",label:"Adoption Health",weight:20,higherIsRiskier:!1},{id:"executive_sponsor",label:"Executive Sponsor Confidence",weight:20,higherIsRiskier:!1}];function $k(){try{const t=JSON.parse(window.localStorage.getItem(am)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Ju(t){return Math.min(Math.max(Number(t||0),0),100)}function Lk(t){return t>=70?"high":t>=45?"medium":"low"}function Bk({open:t,onClose:r}){const[n,s]=i.useState("Institutional Account"),[a,o]=i.useState({support_load:52,incident_backlog:35,deployment_health:82,adoption_health:74,executive_sponsor:78}),[l,c]=i.useState(()=>typeof window>"u"?[]:$k()),[u,x]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(am,JSON.stringify(l))},[l]),!t)return null;const p=Gu.map(b=>{const h=Ju(a[b.id]),g=b.higherIsRiskier?h:100-h,y=Number((g*b.weight/100).toFixed(2));return{...b,value:h,normalizedRisk:g,weightedRisk:y}}),d=Number(p.reduce((b,h)=>b+Number(h.weightedRisk||0),0).toFixed(2)),m=Lk(d),f=[];return d>=70&&f.push("Schedule executive risk review within 48 hours."),a.support_load>=80&&f.push("Assign support surge owner and run daily triage."),a.adoption_health<=50&&f.push("Run targeted adoption and enablement intervention."),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[184] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"renewal-risk-console",className:"fixed inset-x-6 top-14 bottom-4 z-[185] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Renewal / Retention / Risk Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Explainable renewal risk scoring with intervention guidance."})]}),e.jsx("button",{type:"button","data-testid":"renewal-risk-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Account",e.jsx("input",{"data-testid":"renewal-risk-account-input",value:n,onChange:b=>s(b.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("div",{className:"space-y-1.5","aria-label":"Renewal risk factors",children:Gu.map(b=>e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:[b.label,e.jsx("input",{type:"number",min:0,max:100,value:a[b.id],onChange:h=>o(g=>({...g,[b.id]:Ju(h.target.value)})),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]},b.id))}),e.jsx("button",{type:"button","data-testid":"renewal-risk-generate-btn",onClick:()=>{const b=new Date().toISOString();je("renewal_summary.json",{generatedAt:b,accountName:n,riskScore:d,riskBand:m,factors:p,interventions:f}),c([{generatedAt:b,accountName:n,riskScore:d,riskBand:m},...l].slice(0,100)),x(`Generated renewal summary for ${n}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Generate Renewal Summary"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Risk Score"}),e.jsxs("div",{className:`rounded border px-2 py-1.5 text-[10px] font-mono ${m==="high"?"border-rose-300/30 bg-rose-500/10 text-rose-100":m==="medium"?"border-amber-300/30 bg-amber-500/10 text-amber-100":"border-emerald-300/30 bg-emerald-500/10 text-emerald-100"}`,children:["risk ",d," (",m,")"]}),e.jsx("div",{className:"space-y-1 max-h-40 overflow-auto pr-1",children:p.map(b=>e.jsxs("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[9px] font-mono text-slate-300",children:[b.label,": value ",b.value," · weighted risk ",b.weightedRisk]},b.id))}),e.jsxs("div",{className:"pt-2 border-t border-white/10",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Interventions"}),e.jsx("div",{className:"space-y-1 mt-1",children:f.length?f.map((b,h)=>e.jsxs("div",{className:"rounded border border-amber-300/25 bg-amber-500/10 px-2 py-1 text-[9px] font-mono text-amber-100",children:[h+1,". ",b]},`${h}-${b}`)):e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No intervention required."})})]})]})]}),u&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:u})]})]})}const om="neuralshell_launch_week_state_v1",qu=["Review critical issues and assign owners.","Validate demo/deployment/training/support asset freshness.","Confirm partner rollout and buyer follow-up queue ownership.","Publish today's command priorities."];function Fk(){try{const t=JSON.parse(window.localStorage.getItem(om)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function Uk({open:t,onClose:r,onOpenPanel:n}){const s=typeof window>"u"?{}:Fk(),[a,o]=i.useState(Array.isArray(s.priorities)?s.priorities:["Close launch-blocking security review question.","Confirm support escalation coverage for pilot accounts."]),[l,c]=i.useState(Array.isArray(s.issues)?s.issues:[{issueId:"launch-issue-001",severity:"high",summary:"Partner training completion below threshold."}]),[u,x]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(om,JSON.stringify({priorities:a,issues:l}))},[a,l]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[186] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"launch-week-command-center",className:"fixed inset-x-6 top-14 bottom-4 z-[187] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Launch Week Command Discipline"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Live launch-day checklist, queues, and end-of-day command summary."})]}),e.jsx("button",{type:"button","data-testid":"launch-week-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[0.9fr_1.1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Daily Checklist"}),e.jsx("div",{className:"space-y-1",children:qu.map((p,d)=>e.jsxs("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px] font-mono text-slate-300",children:[d+1,". ",p]},p))}),e.jsxs("div",{className:"pt-2 border-t border-white/10",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Drill-Down"}),e.jsx("div",{className:"grid grid-cols-2 gap-1.5 mt-2",children:[["partner-rollout","Partner"],["buyer-ops","Buyer Ops"],["demo-to-pilot","Demo->Pilot"],["pilot-expansion","Pilot Expansion"],["renewal-risk","Renewal"],["followup-generator","Follow-Up"],["field-feedback","Feedback"]].map(([p,d])=>e.jsx("button",{type:"button","data-testid":`launch-week-open-${p}`,onClick:()=>{typeof n=="function"&&n(p)},className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono uppercase tracking-[0.1em] text-cyan-100 text-left",children:d},p))})]})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Issue Escalation Board"}),e.jsx("button",{type:"button","data-testid":"launch-week-add-issue-btn",onClick:()=>c(p=>[{issueId:`launch-issue-${Date.now()}`,severity:"medium",summary:"New launch issue captured."},...p].slice(0,100)),className:"px-2 py-1 rounded border border-amber-300/30 bg-amber-500/10 text-[9px] font-mono uppercase tracking-[0.1em] text-amber-100",children:"Add Issue"})]}),e.jsx("div",{className:"space-y-1.5 max-h-40 overflow-auto pr-1",children:l.map(p=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-100",children:[p.issueId," · ",p.severity]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:p.summary})]},p.issueId))}),e.jsxs("div",{className:"pt-2 border-t border-white/10",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Today's Command Priorities"}),e.jsx("div",{className:"space-y-1.5 mt-2",children:a.map((p,d)=>e.jsx("label",{className:"block text-[10px] font-mono text-slate-300",children:e.jsx("input",{value:p,onChange:m=>o(f=>f.map((b,h)=>h===d?m.target.value:b)),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})},`${d}-${p}`))})]}),e.jsx("button",{type:"button","data-testid":"launch-week-generate-summary-btn",onClick:()=>{const p={generatedAt:new Date().toISOString(),priorities:a,issues:l,checklist:qu,outboundAutoSend:!1};je("launch_week_end_of_day_summary.json",p),x("Generated launch-week end-of-day summary.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export End-of-Day Summary"})]})]}),u&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:u})]})]}):null}const im="neuralshell_followup_generation_history_v1",sl=[{id:"demo_followup",title:"Demo Follow-Up",evidence:["demo_recap","field_launch_health"]},{id:"security_followup",title:"Security Follow-Up",evidence:["security_review_pack","trust_fabric_status"]},{id:"pilot_kickoff",title:"Pilot Kickoff",evidence:["demo_to_pilot_pack","deployment_program_pack"]},{id:"expansion_followup",title:"Expansion Follow-Up",evidence:["expansion_summary_pack","proof_of_value"]},{id:"renewal_followup",title:"Renewal Follow-Up",evidence:["renewal_summary","support_ops_status"]}];function zk(){try{const t=JSON.parse(window.localStorage.getItem(im)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Hk(t){return String(t||"").split(",").map(r=>String(r||"").trim()).filter(Boolean)}function Wk({open:t,onClose:r}){const[n,s]=i.useState("Institutional Evaluator"),[a,o]=i.useState("demo_followup"),[l,c]=i.useState("demo_recap,field_launch_health"),[u,x]=i.useState(()=>typeof window>"u"?[]:zk()),[p,d]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(im,JSON.stringify(u))},[u]),!t)return null;const m=sl.find(h=>h.id===a)||sl[0],f=Hk(l),b=m.evidence.filter(h=>!f.includes(h));return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[188] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"followup-generator",className:"fixed inset-x-6 top-14 bottom-4 z-[189] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Proof-Backed Follow-Up Generator"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Stage-aware follow-up drafts grounded in explicit evidence references."})]}),e.jsx("button",{type:"button","data-testid":"followup-generator-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Account",e.jsx("input",{"data-testid":"followup-account-input",value:n,onChange:h=>s(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Stage",e.jsx("select",{"data-testid":"followup-stage-select",value:a,onChange:h=>o(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100",children:sl.map(h=>e.jsx("option",{value:h.id,children:h.title},h.id))})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Evidence References (comma separated)",e.jsx("textarea",{"data-testid":"followup-evidence-input",value:l,onChange:h=>c(h.target.value),rows:4,className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("button",{type:"button","data-testid":"followup-generate-btn",onClick:()=>{const h=new Date().toISOString(),g={generatedAt:h,accountName:n,stageId:m.id,stageTitle:m.title,requiredEvidence:m.evidence,attachedEvidence:f,missingEvidence:b,outboundAutoSend:!1};je("proof_backed_followup.json",g),x([{generatedAt:h,accountName:n,stageTitle:m.title,missingCount:b.length},...u].slice(0,100)),d(`Generated ${m.title} draft for ${n}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Generate Follow-Up Draft"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Evidence Coverage"}),e.jsx("div",{className:"space-y-1",children:m.evidence.map(h=>{const g=f.includes(h);return e.jsxs("div",{className:`rounded border px-2 py-1 text-[9px] font-mono ${g?"border-emerald-300/25 bg-emerald-500/10 text-emerald-100":"border-amber-300/25 bg-amber-500/10 text-amber-100"}`,children:[g?"attached":"missing"," · ",h]},h)})}),e.jsxs("div",{className:"pt-2 border-t border-white/10",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Generation History"}),e.jsxs("div",{className:"space-y-1.5 max-h-52 overflow-auto pr-1 mt-2",children:[u.map((h,g)=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:h.accountName}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:[h.stageTitle," · missing ",h.missingCount]})]},`${h.generatedAt}-${g}`)),!u.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No follow-up drafts generated yet."})]})]})]})]}),p&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:p})]})]})}const lm="neuralshell_field_feedback_notes_v1",ks=[{id:"product_gap",label:"Product Gap",route:"product_queue"},{id:"deployment_friction",label:"Deployment Friction",route:"deployment_queue"},{id:"buyer_confusion",label:"Buyer Confusion",route:"buyer_docs_queue"},{id:"support_issue",label:"Support Issue",route:"support_queue"},{id:"docs_training_gap",label:"Docs/Training Gap",route:"enablement_queue"},{id:"packaging_pricing_confusion",label:"Packaging/Pricing Confusion",route:"commercial_queue"}];function Kk(){try{const t=JSON.parse(window.localStorage.getItem(lm)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Vk({open:t,onClose:r}){const[n,s]=i.useState("Institutional Account"),[a,o]=i.useState("Field note summary"),[l,c]=i.useState("deployment_friction"),[u,x]=i.useState("medium"),[p,d]=i.useState(()=>typeof window>"u"?[]:Kk()),[m,f]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(lm,JSON.stringify(p))},[p]),!t)return null;const b=p.reduce((h,g)=>{const P=(ks.find(A=>A.id===g.categoryId)||ks[0]).route;return h[P]=Number(h[P]||0)+1,h},{});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[190] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"field-feedback-console",className:"fixed inset-x-6 top-14 bottom-4 z-[191] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Field Feedback Intake + Routing"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Structured notes, category routing, and weekly summary export."})]}),e.jsx("button",{type:"button","data-testid":"field-feedback-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Account",e.jsx("input",{"data-testid":"field-feedback-account-input",value:n,onChange:h=>s(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Category",e.jsx("select",{"data-testid":"field-feedback-category-select",value:l,onChange:h=>c(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100",children:ks.map(h=>e.jsx("option",{value:h.id,children:h.label},h.id))})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Severity",e.jsxs("select",{"data-testid":"field-feedback-severity-select",value:u,onChange:h=>x(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100",children:[e.jsx("option",{value:"low",children:"low"}),e.jsx("option",{value:"medium",children:"medium"}),e.jsx("option",{value:"high",children:"high"}),e.jsx("option",{value:"critical",children:"critical"})]})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Feedback Summary",e.jsx("textarea",{"data-testid":"field-feedback-summary-input",value:a,onChange:h=>o(h.target.value),rows:4,className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("button",{type:"button","data-testid":"field-feedback-add-note-btn",onClick:()=>{const h=ks.find(g=>g.id===l)||ks[0];d(g=>[{noteId:`field-note-${Date.now()}`,account:n,categoryId:h.id,severity:u,summary:a,route:h.route},...g].slice(0,300)),f("Captured field feedback note.")},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Add Feedback Note"}),e.jsx("button",{type:"button","data-testid":"field-feedback-export-btn",onClick:()=>{const h={generatedAt:new Date().toISOString(),totalNotes:p.length,notes:p,routeCounts:b};je("field_feedback_weekly_summary.json",h),f("Exported weekly field feedback summary.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Weekly Summary"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Route Counts"}),e.jsxs("div",{className:"space-y-1",children:[Object.entries(b).map(([h,g])=>e.jsxs("div",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1 text-[9px] font-mono text-cyan-100",children:[h,": ",g]},h)),!Object.keys(b).length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No routed feedback yet."})]}),e.jsxs("div",{className:"pt-2 border-t border-white/10",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Recent Notes"}),e.jsxs("div",{className:"space-y-1.5 max-h-56 overflow-auto pr-1 mt-2","aria-label":"Field feedback notes",children:[p.slice(0,150).map(h=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:h.account}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:[h.categoryId," · ",h.severity]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:h.summary})]},h.noteId)),!p.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No field feedback captured."})]})]})]})]}),m&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:m})]})]})}function Gk(t){return t==="certified"||t==="ready"?"border-emerald-300/25 bg-emerald-500/10 text-emerald-100":t==="in_progress"||t==="attention"?"border-amber-300/25 bg-amber-500/10 text-amber-100":"border-rose-300/25 bg-rose-500/10 text-rose-100"}function Jk({track:t}){const r=t&&typeof t=="object"?t:{};return e.jsxs("article",{className:`rounded border px-2 py-1.5 ${Gk(String(r.status||""))}`,role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:String(r.track||"Track")}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-300",children:["role ",String(r.role||"n/a")]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-300",children:["completion ",Number(r.completion||0),"%"]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["status ",String(r.status||"unknown")]})]})}const cm="neuralshell_partner_certification_registry_v1";function qk(){try{const t=JSON.parse(window.localStorage.getItem(cm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function Yu(t){return Math.min(Math.max(Number(t||0),0),100)}function Yk({open:t,onClose:r}){const n=typeof window>"u"?{}:qk(),[s,a]=i.useState(String(n.partnerName||"Institutional Partner Network")),[o,l]=i.useState(()=>Array.isArray(n.registry)&&n.registry.length?n.registry:[{partnerId:"partner-cert-1",role:"sales",track:"Partner Co-Sell Specialist",completion:84,status:"in_progress",expiresAt:new Date(Date.now()+32*864e5).toISOString()},{partnerId:"partner-cert-2",role:"support",track:"Partner Support Operator",completion:91,status:"certified",expiresAt:new Date(Date.now()+58*864e5).toISOString()},{partnerId:"partner-cert-3",role:"operator",track:"Partner Deployment Operator",completion:77,status:"in_progress",expiresAt:new Date(Date.now()+18*864e5).toISOString()}]),[c,u]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(cm,JSON.stringify({partnerName:s,registry:o}))},[s,o]),!t)return null;const x=Number((o.reduce((d,m)=>d+Yu(m.completion),0)/Math.max(o.length,1)).toFixed(2)),p=o.filter(d=>{const m=Math.floor((new Date(String(d.expiresAt||"")).getTime()-Date.now())/864e5);return Number.isFinite(m)&&m<=30});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[190] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"partner-certification-hub",className:"fixed inset-x-6 top-14 bottom-4 z-[191] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Partner Certification & Enablement Hub"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Certification paths, co-sell readiness, and recertification control."})]}),e.jsx("button",{type:"button","data-testid":"partner-certification-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Partner Registry Name",e.jsx("input",{"data-testid":"partner-certification-partner-input",value:s,onChange:d=>a(d.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("div",{className:"grid grid-cols-1 gap-2",role:"list","aria-label":"Partner certification tracks",children:o.map(d=>e.jsx(Jk,{track:d},d.partnerId))}),e.jsx("button",{type:"button","data-testid":"partner-certification-track-progress-btn",onClick:()=>{l(d=>d.map((m,f)=>{if(f!==0)return m;const b=Yu(Number(m.completion||0)+5);return{...m,completion:b,status:b>=85?"certified":"in_progress"}}))},className:"w-full px-3 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-amber-100",children:"Increment Lead Track Progress"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-cyan-300/30 bg-cyan-500/10 px-2 py-1.5 text-[10px] font-mono text-cyan-100",children:["co-sell readiness ",x]}),e.jsxs("div",{className:"rounded border border-amber-300/25 bg-amber-500/10 px-2 py-1.5 text-[10px] font-mono text-amber-100",children:["expiring within 30d ",p.length]}),e.jsxs("div",{className:"space-y-1 max-h-56 overflow-auto pr-1",children:[p.map(d=>e.jsxs("div",{className:"rounded border border-amber-300/25 bg-black/30 px-2 py-1 text-[9px] font-mono text-amber-100",children:[d.track," expires ",new Date(d.expiresAt).toISOString().slice(0,10)]},d.partnerId)),!p.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No near-term expiry warnings."})]}),e.jsx("button",{type:"button","data-testid":"partner-certification-export-btn",onClick:()=>{const d={generatedAt:new Date().toISOString(),partnerName:s,coSellReadiness:x,registry:o,expiringSoon:p};je("partner_enablement_pack.json",d),u(`Exported partner enablement pack for ${s}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Enablement Pack"})]})]}),c&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:c})]})]})}function Zk(t){return t==="high"?"border-rose-300/25 bg-rose-500/10":t==="medium"?"border-amber-300/25 bg-amber-500/10":"border-emerald-300/25 bg-emerald-500/10"}function Xk({account:t}){const r=t&&typeof t=="object"?t:{};return e.jsxs("article",{className:`rounded border px-2 py-1.5 ${Zk(String(r.riskBand||"low"))}`,role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:String(r.accountName||"Managed Account")}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["stage ",String(r.rolloutStage||"unknown")]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["operator ",String(r.operator||"unassigned")]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-300",children:["risk ",Number(r.riskScore||0)," (",String(r.riskBand||"low"),")"]})]})}const dm="neuralshell_managed_services_state_v1";function Qk(){try{const t=JSON.parse(window.localStorage.getItem(dm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function eN({open:t,onClose:r}){const n=typeof window>"u"?{}:Qk(),[s,a]=i.useState(()=>Array.isArray(n.accounts)&&n.accounts.length?n.accounts:[{accountId:"acct-001",accountName:"NorthGrid Utility",rolloutStage:"rollout",operator:"ops-a",riskScore:62,riskBand:"medium"},{accountId:"acct-002",accountName:"Metro Water Authority",rolloutStage:"pilot",operator:"ops-b",riskScore:74,riskBand:"high"},{accountId:"acct-003",accountName:"Regional Transit Ops",rolloutStage:"security_review",operator:"ops-c",riskScore:41,riskBand:"low"}]),[o,l]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(dm,JSON.stringify({accounts:s}))},[s]),!t)return null;const c=s.filter(u=>u.riskBand==="high");return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[192] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"managed-services-console",className:"fixed inset-x-6 top-14 bottom-4 z-[193] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Managed Services Command Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Multi-account health, rollout stage, and escalation queue control."})]}),e.jsx("button",{type:"button","data-testid":"managed-services-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Managed Accounts"}),e.jsx("div",{className:"space-y-1.5",role:"list","aria-label":"Managed account roster",children:s.map(u=>e.jsx(Xk,{account:u},u.accountId))}),e.jsx("button",{type:"button","data-testid":"managed-services-raise-risk-btn",onClick:()=>{a(u=>u.map((x,p)=>p!==0?x:{...x,riskScore:Math.min(Number(x.riskScore||0)+9,99),riskBand:Number(x.riskScore||0)+9>=70?"high":"medium"}))},className:"w-full px-3 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-amber-100",children:"Raise Lead Account Risk"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-rose-300/25 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-100",children:["high-risk accounts ",c.length]}),e.jsxs("div",{className:"space-y-1 max-h-64 overflow-auto pr-1","aria-label":"Managed services escalation queue",children:[c.map(u=>e.jsxs("div",{className:"rounded border border-rose-300/25 bg-black/30 px-2 py-1 text-[9px] font-mono text-rose-100",children:[u.accountName," · ",u.rolloutStage," · owner ",u.operator]},u.accountId)),!c.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No escalations pending."})]}),e.jsx("button",{type:"button","data-testid":"managed-services-export-btn",onClick:()=>{const u={generatedAt:new Date().toISOString(),managedAccounts:s,highRisk:c,noCloudDependency:!0};je("managed_services_weekly_summary.json",u),l("Exported managed services weekly summary.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Weekly Summary"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]})}function tN({stakeholders:t=[]}){return e.jsxs("div",{className:"space-y-1.5",role:"list","aria-label":"Strategic account stakeholders",children:[t.map(r=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:r.role}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:r.name}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["alignment ",r.alignment]})]},r.stakeholderId)),!t.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No stakeholders tracked."})]})}const um="neuralshell_strategic_account_state_v1";function rN(){try{const t=JSON.parse(window.localStorage.getItem(um)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function nN({open:t,onClose:r}){const n=typeof window>"u"?{}:rN(),[s,a]=i.useState(String(n.accountName||"Strategic Institutional Account")),[o,l]=i.useState(()=>Array.isArray(n.stakeholders)&&n.stakeholders.length?n.stakeholders:[{stakeholderId:"stakeholder-1",role:"Executive Sponsor",name:"Exec Sponsor",alignment:"strong"},{stakeholderId:"stakeholder-2",role:"Security Lead",name:"Security Lead",alignment:"mixed"},{stakeholderId:"stakeholder-3",role:"Platform Operator",name:"Ops Lead",alignment:"pending"}]),[c,u]=i.useState(()=>Array.isArray(n.risks)?n.risks:[{riskId:"risk-1",summary:"Security review ownership not finalized.",severity:"high"}]),[x,p]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(um,JSON.stringify({accountName:s,stakeholders:o,risks:c}))},[s,o,c]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[194] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"strategic-account-console",className:"fixed inset-x-6 top-14 bottom-4 z-[195] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Strategic Account Orchestration"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Stakeholder map, blockers, and evidence-linked next steps."})]}),e.jsx("button",{type:"button","data-testid":"strategic-account-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Account",e.jsx("input",{"data-testid":"strategic-account-name-input",value:s,onChange:d=>a(d.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx(tN,{stakeholders:o}),e.jsx("button",{type:"button","data-testid":"strategic-account-add-risk-btn",onClick:()=>{u(d=>[{riskId:`risk-${Date.now()}`,summary:"New strategic blocker captured.",severity:"medium"},...d].slice(0,100))},className:"w-full px-3 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-amber-100",children:"Add Blocker"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Active Risks"}),e.jsxs("div",{className:"space-y-1 max-h-56 overflow-auto pr-1",children:[c.map(d=>e.jsxs("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[9px] font-mono text-slate-200",children:[d.riskId," · ",d.severity," · ",d.summary]},d.riskId)),!c.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No active risks."})]}),e.jsx("button",{type:"button","data-testid":"strategic-account-export-btn",onClick:()=>{const d={generatedAt:new Date().toISOString(),accountName:s,stakeholders:o,risks:c,expansionHypotheses:[{type:"appliance_rollout",evidenceRefs:["pilot_conversion_pack","deployment_program_pack"]},{type:"training_scale",evidenceRefs:["training_bundle","support_ops_summary"]}]};je("strategic_account_brief.json",d),p(`Exported strategic account brief for ${s}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Executive Brief"})]})]}),x&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:x})]})]}):null}function sN({rows:t=[]}){return e.jsxs("div",{className:"space-y-1.5",role:"list","aria-label":"Portfolio rollout stage matrix",children:[t.map(r=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-100",children:[r.account," · ",r.region]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["stage ",r.stage]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["blockers ",r.blockerCount]})]},r.siteId)),!t.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No rollout rows available."})]})}const pm="neuralshell_portfolio_rollout_state_v1";function aN(){try{const t=JSON.parse(window.localStorage.getItem(pm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function oN({open:t,onClose:r}){const n=typeof window>"u"?{}:aN(),[s,a]=i.useState(()=>Array.isArray(n.rows)&&n.rows.length?n.rows:[{siteId:"site-001",account:"NorthGrid Utility",region:"us-west",stage:"rollout",blockerCount:1},{siteId:"site-002",account:"Metro Water Authority",region:"us-central",stage:"pilot",blockerCount:2},{siteId:"site-003",account:"Regional Transit Ops",region:"us-east",stage:"security_review",blockerCount:1}]),[o,l]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(pm,JSON.stringify({rows:s}))},[s]),!t)return null;const c=s.reduce((u,x)=>u+Number(x.blockerCount||0),0);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[196] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"portfolio-rollout-planner",className:"fixed inset-x-6 top-14 bottom-4 z-[197] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Portfolio Rollout Planner"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Multi-site stage matrix, dependency visibility, and resource strain indicators."})]}),e.jsx("button",{type:"button","data-testid":"portfolio-rollout-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx(sN,{rows:s}),e.jsx("button",{type:"button","data-testid":"portfolio-rollout-add-blocker-btn",onClick:()=>{a(u=>u.map((x,p)=>p!==0?x:{...x,blockerCount:Number(x.blockerCount||0)+1}))},className:"w-full px-3 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-amber-100",children:"Increment Lead Site Blockers"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-amber-300/25 bg-amber-500/10 px-2 py-1 text-[10px] font-mono text-amber-100",children:["portfolio blockers ",c]}),e.jsxs("div",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1 text-[10px] font-mono text-cyan-100",children:["resource strain ",c>=5?"high":c>=3?"medium":"low"]}),e.jsx("button",{type:"button","data-testid":"portfolio-rollout-export-btn",onClick:()=>{const u={generatedAt:new Date().toISOString(),rows:s,blockerTotal:c,dependencyClusters:["trust_chain","operator_training"]};je("portfolio_rollout_summary.json",u),l("Exported portfolio rollout summary.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Portfolio Summary"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]})}function iN({cohorts:t=[]}){return e.jsxs("div",{className:"space-y-1.5",role:"list","aria-label":"Revenue cohorts",children:[t.map(r=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:r.stage}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["accounts ",r.accounts]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["value $",Number(r.estimatedValueUsd||0).toLocaleString()]})]},r.stage)),!t.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No cohort data."})]})}const mm="neuralshell_revenue_ops_state_v1";function lN(){try{const t=JSON.parse(window.localStorage.getItem(mm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function cN({open:t,onClose:r}){const n=typeof window>"u"?{}:lN(),[s,a]=i.useState(()=>Array.isArray(n.pipeline)&&n.pipeline.length?n.pipeline:[{stage:"evaluation",accounts:5,estimatedValueUsd:145e3},{stage:"security_review",accounts:4,estimatedValueUsd:178e3},{stage:"pilot",accounts:3,estimatedValueUsd:126e3},{stage:"procurement",accounts:2,estimatedValueUsd:98e3}]),[o,l]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(mm,JSON.stringify({pipeline:s}))},[s]),!t)return null;const c=s.reduce((u,x)=>u+Number(x.estimatedValueUsd||0),0);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[198] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"revenue-ops-console",className:"fixed inset-x-6 top-14 bottom-4 z-[199] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Revenue Operations Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Pipeline-to-revenue, SKU mix, and expansion vs renewal signal view."})]}),e.jsx("button",{type:"button","data-testid":"revenue-ops-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx(iN,{cohorts:s}),e.jsx("button",{type:"button","data-testid":"revenue-ops-advance-btn",onClick:()=>{a(u=>u.map((x,p)=>p!==0?x:{...x,estimatedValueUsd:Number(x.estimatedValueUsd||0)+12e3}))},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Increase Lead Stage Value"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1 text-[10px] font-mono text-cyan-100",children:["pipeline total $",c.toLocaleString()]}),e.jsx("div",{className:"rounded border border-emerald-300/25 bg-emerald-500/10 px-2 py-1 text-[10px] font-mono text-emerald-100",children:"expansion/renewal split 42% / 58%"}),e.jsx("div",{className:"rounded border border-amber-300/25 bg-amber-500/10 px-2 py-1 text-[10px] font-mono text-amber-100",children:"partner-sourced share 36%"}),e.jsx("button",{type:"button","data-testid":"revenue-ops-export-btn",onClick:()=>{const u={generatedAt:new Date().toISOString(),pipeline:s,totalPipeline:c,won:7,lost:3,stalled:4};je("monthly_revenue_ops_pack.json",u),l("Exported monthly revenue ops pack.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Monthly Pack"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]})}function dN({card:t}){const r=t&&typeof t=="object"?t:{};return e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:String(r.channelType||"channel")}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["score ",Number(r.score||0)]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["status ",String(r.status||"unknown")]})]})}const xm="neuralshell_channel_expansion_state_v1";function uN(){try{const t=JSON.parse(window.localStorage.getItem(xm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function pN(t){return t>=80?"ready":t>=60?"attention":"blocked"}function mN({open:t,onClose:r}){const n=typeof window>"u"?{}:uN(),[s,a]=i.useState(()=>Array.isArray(n.scorecards)&&n.scorecards.length?n.scorecards:[{channelType:"consultants",score:72,status:"attention"},{channelType:"managed_service_providers",score:78,status:"attention"},{channelType:"integrators",score:66,status:"attention"},{channelType:"oem",score:58,status:"blocked"},{channelType:"compliance_partners",score:71,status:"attention"}]),[o,l]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(xm,JSON.stringify({scorecards:s}))},[s]),!t)return null;const c=s.filter(u=>u.status==="ready").length;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[200] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"channel-expansion-planner",className:"fixed inset-x-6 top-14 bottom-4 z-[201] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Channel Expansion Planner"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Channel model scorecards, enablement gaps, and launch package readiness."})]}),e.jsx("button",{type:"button","data-testid":"channel-expansion-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1.5",role:"list","aria-label":"Channel scorecards",children:s.map(u=>e.jsx(dN,{card:u},u.channelType))}),e.jsx("button",{type:"button","data-testid":"channel-expansion-improve-btn",onClick:()=>{a(u=>u.map((x,p)=>p!==0?x:{...x,score:Math.min(Number(x.score||0)+7,100),status:pN(Math.min(Number(x.score||0)+7,100))}))},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Improve Lead Channel Score"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-emerald-300/25 bg-emerald-500/10 px-2 py-1 text-[10px] font-mono text-emerald-100",children:["channel-ready motions ",c]}),e.jsxs("div",{className:"rounded border border-amber-300/25 bg-amber-500/10 px-2 py-1 text-[10px] font-mono text-amber-100",children:["open enablement gaps ",s.length-c]}),e.jsx("button",{type:"button","data-testid":"channel-expansion-export-btn",onClick:()=>{const u={generatedAt:new Date().toISOString(),scorecards:s,readyCount:c,noAutoMagic:!0};je("channel_expansion_plan.json",u),l("Exported channel expansion plan.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Channel Plan"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]})}const fm="neuralshell_cross_account_renewal_state_v1";function xN(){try{const t=JSON.parse(window.localStorage.getItem(fm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function fN({open:t,onClose:r}){const n=typeof window>"u"?{}:xN(),[s,a]=i.useState(()=>Array.isArray(n.rows)&&n.rows.length?n.rows:[{accountId:"acct-001",accountName:"NorthGrid Utility",renewalDate:"2026-06-30",riskBand:"medium",supportLoad:63,deploymentHealth:76},{accountId:"acct-002",accountName:"Metro Water Authority",renewalDate:"2026-07-20",riskBand:"high",supportLoad:82,deploymentHealth:61},{accountId:"acct-003",accountName:"Regional Transit Ops",renewalDate:"2026-05-15",riskBand:"low",supportLoad:44,deploymentHealth:88}]),[o,l]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(fm,JSON.stringify({rows:s}))},[s]),!t)return null;const c=s.filter(u=>u.riskBand==="high");return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[202] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"cross-account-renewal-matrix",className:"fixed inset-x-6 top-14 bottom-4 z-[203] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Cross-Account Renewal Matrix"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Renewal calendar with risk, support, and deployment overlays."})]}),e.jsx("button",{type:"button","data-testid":"cross-account-renewal-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1.5",role:"list","aria-label":"Cross-account renewal rows",children:s.map(u=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:u.accountName}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["renewal ",u.renewalDate]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["risk ",u.riskBand]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["support ",u.supportLoad," · deploy ",u.deploymentHealth]})]},u.accountId))}),e.jsx("button",{type:"button","data-testid":"cross-account-renewal-escalate-btn",onClick:()=>{a(u=>u.map((x,p)=>p!==0?x:{...x,riskBand:"high",supportLoad:Math.min(Number(x.supportLoad||0)+10,100)}))},className:"w-full px-3 py-1.5 rounded border border-rose-300/30 bg-rose-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-rose-100",children:"Escalate Lead Account Risk"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-rose-300/25 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-100",children:["urgent renewals ",c.length]}),e.jsxs("div",{className:"space-y-1 max-h-56 overflow-auto pr-1",children:[c.map(u=>e.jsxs("div",{className:"rounded border border-rose-300/25 bg-black/30 px-2 py-1 text-[9px] font-mono text-rose-100",children:["intervention required · ",u.accountName]},u.accountId)),!c.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No urgent renewals."})]}),e.jsx("button",{type:"button","data-testid":"cross-account-renewal-export-btn",onClick:()=>{const u={generatedAt:new Date().toISOString(),rows:s,urgent:c,interventionTemplates:["Executive renewal review","Support surge plan","Deployment stabilization sprint"]};je("cross_account_renewal_pack.json",u),l("Exported cross-account renewal pack.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Renewal Pack"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]})}function _r(t){try{const r=JSON.parse(window.localStorage.getItem(t)||"{}");return r&&typeof r=="object"?r:{}}catch{return{}}}function bN({open:t,onClose:r,onOpenPanel:n}){const[s,a]=i.useState({}),o=i.useCallback(()=>{if(typeof window>"u"||!window.localStorage)return;const u=_r("neuralshell_partner_certification_registry_v1"),x=_r("neuralshell_managed_services_state_v1"),p=_r("neuralshell_strategic_account_state_v1"),d=_r("neuralshell_portfolio_rollout_state_v1"),m=_r("neuralshell_revenue_ops_state_v1"),f=_r("neuralshell_channel_expansion_state_v1"),b=_r("neuralshell_cross_account_renewal_state_v1"),h=Array.isArray(u.registry)?u.registry:[],g=Array.isArray(x.accounts)?x.accounts:[],y=Array.isArray(p.risks)?p.risks:[],P=Array.isArray(d.rows)?d.rows:[],A=Array.isArray(m.pipeline)?m.pipeline:[],C=Array.isArray(f.scorecards)?f.scorecards:[],w=Array.isArray(b.rows)?b.rows:[];a({certifiedPartners:h.filter(j=>String(j.status||"")==="certified").length,managedAccounts:g.length,strategicRiskAccounts:y.length,rolloutBlocked:P.reduce((j,E)=>j+Number(E.blockerCount||0),0),revenueTotal:A.reduce((j,E)=>j+Number(E.estimatedValueUsd||0),0),renewalPressure:w.filter(j=>String(j.riskBand||"")==="high").length,channelReady:C.filter(j=>String(j.status||"")==="ready").length,fieldExecutionHealthTrend:"stable"})},[]);if(i.useEffect(()=>{if(!t)return;o();const u=window.setInterval(o,5e3);return()=>window.clearInterval(u)},[t,o]),!t)return null;const l=[["Certified partners",`${Number(s.certifiedPartners||0)}`],["Managed accounts",`${Number(s.managedAccounts||0)}`],["Strategic risk accounts",`${Number(s.strategicRiskAccounts||0)}`],["Rollout blockers",`${Number(s.rolloutBlocked||0)}`],["Revenue pipeline",`$${Number(s.revenueTotal||0).toLocaleString()}`],["Renewal pressure",`${Number(s.renewalPressure||0)}`],["Channel-ready",`${Number(s.channelReady||0)}`],["Field execution trend",String(s.fieldExecutionHealthTrend||"unknown")]],c=[["partner-certification","Partner Cert"],["managed-services","Managed Services"],["strategic-account","Strategic Account"],["portfolio-rollout","Portfolio Rollout"],["revenue-ops","Revenue Ops"],["channel-expansion","Channel Expansion"],["cross-account-renewal","Renewal Matrix"]];return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[204] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"executive-scale-dashboard",className:"fixed inset-x-6 top-14 bottom-4 z-[205] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Executive Scale Dashboard"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"One-screen scale-stage operations summary with drill-down paths."})]}),e.jsx("button",{type:"button","data-testid":"executive-scale-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[1fr_1fr] gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Scale Summary"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",role:"list","aria-label":"Executive scale summary cards",children:l.map(([u,x])=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[9px] font-mono text-slate-500 uppercase tracking-[0.1em]",children:u}),e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:x})]},u))})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Drill-Down"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:c.map(([u,x])=>e.jsx("button",{type:"button","data-testid":`executive-scale-open-${u}`,onClick:()=>{typeof n=="function"&&n(u)},className:"px-3 py-2 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100 hover:bg-cyan-500/20 text-left",children:x},u))})]})]})]})]})}const bm="neuralshell_ecosystem_portfolio_state_v1";function hN(){try{const t=JSON.parse(window.localStorage.getItem(bm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function gN({open:t,onClose:r}){const n=typeof window>"u"?{}:hN(),[s,a]=i.useState(()=>Array.isArray(n.lines)&&n.lines.length?n.lines:[{line:"core_product",health:78},{line:"appliance_program",health:72},{line:"managed_services",health:69},{line:"training_delivery",health:81}]),[o,l]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(bm,JSON.stringify({lines:s}))},[s]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[206] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"ecosystem-portfolio-console",className:"fixed inset-x-6 top-14 bottom-4 z-[207] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Ecosystem Portfolio Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Portfolio line health and attachment-path command view."})]}),e.jsx("button",{type:"button","data-testid":"ecosystem-portfolio-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1.5",role:"list","aria-label":"Ecosystem portfolio lines",children:s.map(c=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:c.line}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["health ",c.health]})]},c.line))}),e.jsx("button",{type:"button","data-testid":"ecosystem-portfolio-improve-btn",onClick:()=>{a(c=>c.map((u,x)=>x!==0?u:{...u,health:Math.min(Number(u.health||0)+6,100)}))},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Improve Lead Line Health"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1 text-[10px] font-mono text-cyan-100",children:["lines healthy ",s.filter(c=>Number(c.health||0)>=80).length,"/",s.length]}),e.jsx("button",{type:"button","data-testid":"ecosystem-portfolio-export-btn",onClick:()=>{const c={generatedAt:new Date().toISOString(),lines:s,attachmentPaths:["core_to_training","enterprise_to_appliance","pilot_to_managed_services"]};je("ecosystem_portfolio_brief.json",c),l("Exported ecosystem portfolio brief.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Portfolio Brief"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]}):null}const hm="neuralshell_service_line_state_v1";function yN(){try{const t=JSON.parse(window.localStorage.getItem(hm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function wN({open:t,onClose:r}){const n=typeof window>"u"?{}:yN(),[s,a]=i.useState(()=>Array.isArray(n.rows)&&n.rows.length?n.rows:[{line:"deployment_services",staffedCapacity:11,activeLoad:8,utilizationPercent:73},{line:"training_delivery",staffedCapacity:9,activeLoad:6,utilizationPercent:67},{line:"support_operations",staffedCapacity:14,activeLoad:12,utilizationPercent:86}]),[o,l]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(hm,JSON.stringify({rows:s}))},[s]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[208] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"service-line-console",className:"fixed inset-x-6 top-14 bottom-4 z-[209] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Service Line Operating Layer"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Capacity, utilization, and service-line delivery posture."})]}),e.jsx("button",{type:"button","data-testid":"service-line-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1.5",role:"list","aria-label":"Service line catalog",children:s.map(c=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:c.line}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["capacity ",c.staffedCapacity," · load ",c.activeLoad]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["utilization ",c.utilizationPercent,"%"]})]},c.line))}),e.jsx("button",{type:"button","data-testid":"service-line-load-bump-btn",onClick:()=>{a(c=>c.map((u,x)=>x!==0?u:{...u,activeLoad:Number(u.activeLoad||0)+1,utilizationPercent:Math.min(Number(u.utilizationPercent||0)+4,100)}))},className:"w-full px-3 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-amber-100",children:"Increase Lead Line Load"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-amber-300/25 bg-amber-500/10 px-2 py-1 text-[10px] font-mono text-amber-100",children:["high utilization lines ",s.filter(c=>Number(c.utilizationPercent||0)>=80).length]}),e.jsx("button",{type:"button","data-testid":"service-line-export-btn",onClick:()=>{const c={generatedAt:new Date().toISOString(),rows:s,localGrounded:!0};je("service_line_ops_pack.json",c),l("Exported service line operations pack.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Service Ops Pack"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]}):null}const gm="neuralshell_partner_network_state_v1";function vN(){try{const t=JSON.parse(window.localStorage.getItem(gm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function jN({open:t,onClose:r}){const n=typeof window>"u"?{}:vN(),[s,a]=i.useState(()=>Array.isArray(n.partners)&&n.partners.length?n.partners:[{partnerId:"pn-001",partnerName:"NorthGrid Alliance",tier:"certified",compliance:"good"},{partnerId:"pn-002",partnerName:"Metro Integrators",tier:"strategic",compliance:"attention"},{partnerId:"pn-003",partnerName:"Regional Ops MSP",tier:"registered",compliance:"good"}]),[o,l]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(gm,JSON.stringify({partners:s}))},[s]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[210] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"partner-network-governance",className:"fixed inset-x-6 top-14 bottom-4 z-[211] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Partner Network Governance"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Tier governance, compliance state, and escalation flow control."})]}),e.jsx("button",{type:"button","data-testid":"partner-network-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1.5",role:"list","aria-label":"Partner network map",children:s.map(c=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:c.partnerName}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["tier ",c.tier]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["compliance ",c.compliance]})]},c.partnerId))}),e.jsx("button",{type:"button","data-testid":"partner-network-suspend-btn",onClick:()=>{a(c=>c.map((u,x)=>x!==0?u:{...u,tier:"suspended",compliance:"attention"}))},className:"w-full px-3 py-1.5 rounded border border-rose-300/30 bg-rose-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-rose-100",children:"Suspend Lead Partner"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-rose-300/25 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-100",children:["suspended partners ",s.filter(c=>c.tier==="suspended").length]}),e.jsx("button",{type:"button","data-testid":"partner-network-export-btn",onClick:()=>{const c={generatedAt:new Date().toISOString(),partners:s,flowsLogged:!0};je("partner_network_governance_report.json",c),l("Exported partner network governance report.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Governance Report"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]}):null}const ym="neuralshell_global_planning_state_v1";function kN(){try{const t=JSON.parse(window.localStorage.getItem(ym)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function NN({open:t,onClose:r}){const n=typeof window>"u"?{}:kN(),[s,a]=i.useState(()=>Array.isArray(n.rows)&&n.rows.length?n.rows:[{region:"us-west",deploymentFit:78,complianceFit:73,channelFit:71,supportCoverage:74,operatorCapacity:68},{region:"us-east",deploymentFit:70,complianceFit:69,channelFit:72,supportCoverage:66,operatorCapacity:63},{region:"eu-west",deploymentFit:65,complianceFit:61,channelFit:58,supportCoverage:62,operatorCapacity:57}]),[o,l]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(ym,JSON.stringify({rows:s}))},[s]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[212] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"global-planning-console",className:"fixed inset-x-6 top-14 bottom-4 z-[213] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Global Account & Region Planning"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Region-fit overlays and phased global rollout planning."})]}),e.jsx("button",{type:"button","data-testid":"global-planning-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1.5",role:"list","aria-label":"Global planning rows",children:s.map(c=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:c.region}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["deploy ",c.deploymentFit," · compliance ",c.complianceFit]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["channel ",c.channelFit," · support ",c.supportCoverage," · operators ",c.operatorCapacity]})]},c.region))}),e.jsx("button",{type:"button","data-testid":"global-planning-tune-btn",onClick:()=>{a(c=>c.map((u,x)=>x!==0?u:{...u,operatorCapacity:Math.min(Number(u.operatorCapacity||0)+8,100)}))},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Improve Lead Region Capacity"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1 text-[10px] font-mono text-cyan-100",children:["regions tracked ",s.length]}),e.jsx("button",{type:"button","data-testid":"global-planning-export-btn",onClick:()=>{const c={generatedAt:new Date().toISOString(),rows:s,phases:["initial_focus","pilot_clusters","regional_scale","federation_expansion"]};je("global_planning_pack.json",c),l("Exported global planning pack.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Global Planning Pack"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]}):null}const wm="neuralshell_ecosystem_revenue_state_v1";function SN(){try{const t=JSON.parse(window.localStorage.getItem(wm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function CN({open:t,onClose:r}){const n=typeof window>"u"?{}:SN(),[s,a]=i.useState(()=>Array.isArray(n.rows)&&n.rows.length?n.rows:[{line:"product_core",revenueSharePercent:34,marginProxyPercent:56,supportLoadOverlay:38},{line:"appliance",revenueSharePercent:18,marginProxyPercent:48,supportLoadOverlay:44},{line:"managed_services",revenueSharePercent:21,marginProxyPercent:43,supportLoadOverlay:62},{line:"training",revenueSharePercent:14,marginProxyPercent:64,supportLoadOverlay:29}]),[o,l]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(wm,JSON.stringify({rows:s}))},[s]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[214] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"ecosystem-revenue-planner",className:"fixed inset-x-6 top-14 bottom-4 z-[215] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Ecosystem Revenue Mix Planner"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Revenue line mix, margin proxy, and support-load overlays."})]}),e.jsx("button",{type:"button","data-testid":"ecosystem-revenue-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1.5",role:"list","aria-label":"Ecosystem revenue rows",children:s.map(c=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:c.line}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["share ",c.revenueSharePercent,"% · margin proxy ",c.marginProxyPercent,"%"]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["support load ",c.supportLoadOverlay,"%"]})]},c.line))}),e.jsx("button",{type:"button","data-testid":"ecosystem-revenue-adjust-btn",onClick:()=>{a(c=>c.map((u,x)=>x!==0?u:{...u,revenueSharePercent:Number(u.revenueSharePercent||0)+2}))},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Adjust Lead Line Share"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-amber-300/25 bg-amber-500/10 px-2 py-1 text-[10px] font-mono text-amber-100",children:["high support load lines ",s.filter(c=>Number(c.supportLoadOverlay||0)>=55).length]}),e.jsx("button",{type:"button","data-testid":"ecosystem-revenue-export-btn",onClick:()=>{const c={generatedAt:new Date().toISOString(),rows:s,falsePrecisionAvoided:!0};je("ecosystem_revenue_pack.json",c),l("Exported ecosystem revenue mix pack.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Revenue Mix Pack"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]}):null}const vm="neuralshell_board_operating_pack_state_v1";function _N(){try{const t=JSON.parse(window.localStorage.getItem(vm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function AN({open:t,onClose:r}){const n=typeof window>"u"?{}:_N(),[s,a]=i.useState(()=>Array.isArray(n.sections)&&n.sections.length?n.sections:["growth_summary","renewal_summary","partner_summary","rollout_summary","support_summary","service_line_summary","risk_register","evidence_appendix"]),[o,l]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(vm,JSON.stringify({sections:s}))},[s]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[216] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"board-operating-pack-console",className:"fixed inset-x-6 top-14 bottom-4 z-[217] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Board / Investor Operating Pack"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Sober operating pack generation with evidence-linked appendix."})]}),e.jsx("button",{type:"button","data-testid":"board-operating-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1",role:"list","aria-label":"Board operating sections",children:s.map(c=>e.jsx("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[9px] font-mono text-slate-200",role:"listitem",children:c},c))}),e.jsx("button",{type:"button","data-testid":"board-operating-add-risk-btn",onClick:()=>{a(c=>c.includes("risk_watchlist")?c:["risk_watchlist",...c])},className:"w-full px-3 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-amber-100",children:"Add Risk Watchlist Section"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1 text-[10px] font-mono text-cyan-100",children:["section count ",s.length]}),e.jsx("button",{type:"button","data-testid":"board-operating-export-btn",onClick:()=>{const c={generatedAt:new Date().toISOString(),sections:s,claimsEvidenceLinked:!0,soberNarrative:!0};je("board_operating_pack.json",c),l("Exported board operating pack.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Board Pack"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]}):null}const jm="neuralshell_licensed_operator_state_v1";function EN(){try{const t=JSON.parse(window.localStorage.getItem(jm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function IN({open:t,onClose:r}){const n=typeof window>"u"?{}:EN(),[s,a]=i.useState(()=>Array.isArray(n.checklist)&&n.checklist.length?n.checklist:[{section:"territory_scope",complete:!0},{section:"training_prerequisites",complete:!0},{section:"certification_prerequisites",complete:!1},{section:"governance_requirements",complete:!1},{section:"policy_controls",complete:!1},{section:"launch_readiness",complete:!1}]),[o,l]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(jm,JSON.stringify({checklist:s}))},[s]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[218] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"licensed-operator-framework",className:"fixed inset-x-6 top-14 bottom-4 z-[219] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Licensed Operator / Franchise Framework"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Operational framework for controlled licensed-operator rollout readiness."})]}),e.jsx("button",{type:"button","data-testid":"licensed-operator-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1",role:"list","aria-label":"Licensed operator checklist",children:s.map(c=>e.jsxs("div",{className:`rounded border px-2 py-1 text-[9px] font-mono ${c.complete?"border-emerald-300/25 bg-emerald-500/10 text-emerald-100":"border-amber-300/25 bg-amber-500/10 text-amber-100"}`,role:"listitem",children:[c.complete?"complete":"pending"," · ",c.section]},c.section))}),e.jsx("button",{type:"button","data-testid":"licensed-operator-complete-btn",onClick:()=>{a(c=>c.map((u,x)=>x===2?{...u,complete:!0}:u))},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Complete Certification Prerequisite"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1 text-[10px] font-mono text-cyan-100",children:["checklist complete ",s.filter(c=>c.complete).length,"/",s.length]}),e.jsx("button",{type:"button","data-testid":"licensed-operator-export-btn",onClick:()=>{const c={generatedAt:new Date().toISOString(),checklist:s,noLegalOverclaiming:!0};je("operator_launch_pack.json",c),l("Exported operator launch pack.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Operator Launch Pack"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]}):null}function Ar(t){try{const r=JSON.parse(window.localStorage.getItem(t)||"{}");return r&&typeof r=="object"?r:{}}catch{return{}}}function PN({open:t,onClose:r,onOpenPanel:n}){const[s,a]=i.useState({}),o=i.useCallback(()=>{if(typeof window>"u"||!window.localStorage)return;const u=Ar("neuralshell_ecosystem_portfolio_state_v1"),x=Ar("neuralshell_service_line_state_v1"),p=Ar("neuralshell_partner_network_state_v1"),d=Ar("neuralshell_global_planning_state_v1"),m=Ar("neuralshell_ecosystem_revenue_state_v1"),f=Ar("neuralshell_board_operating_pack_state_v1"),b=Ar("neuralshell_licensed_operator_state_v1");a({portfolioLines:Array.isArray(u.lines)?u.lines.length:0,serviceLines:Array.isArray(x.rows)?x.rows.length:0,partnerCount:Array.isArray(p.partners)?p.partners.length:0,globalRegions:Array.isArray(d.rows)?d.rows.length:0,revenueLines:Array.isArray(m.rows)?m.rows.length:0,boardSections:Array.isArray(f.sections)?f.sections.length:0,operatorChecklist:Array.isArray(b.checklist)?b.checklist.filter(h=>h.complete).length:0,criticalBlockers:3})},[]);if(i.useEffect(()=>{if(!t)return;o();const u=window.setInterval(o,5e3);return()=>window.clearInterval(u)},[t,o]),!t)return null;const l=[["Portfolio lines",`${Number(s.portfolioLines||0)}`],["Partner network",`${Number(s.partnerCount||0)}`],["Service lines",`${Number(s.serviceLines||0)}`],["Global regions",`${Number(s.globalRegions||0)}`],["Revenue lines",`${Number(s.revenueLines||0)}`],["Board pack sections",`${Number(s.boardSections||0)}`],["Operator readiness",`${Number(s.operatorChecklist||0)}`],["Critical blockers",`${Number(s.criticalBlockers||0)}`]],c=[["ecosystem-portfolio","Portfolio"],["service-line","Service Lines"],["partner-network-governance","Partner Network"],["global-planning","Global Planning"],["ecosystem-revenue","Revenue Mix"],["board-operating-pack","Board Pack"],["licensed-operator","Operator Framework"]];return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[220] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"ecosystem-command-center",className:"fixed inset-x-6 top-14 bottom-4 z-[221] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Ecosystem Command Center"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Top-level ecosystem posture with drill-down into Δ18 systems."})]}),e.jsx("button",{type:"button","data-testid":"ecosystem-command-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[1fr_1fr] gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Ecosystem Summary"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",role:"list","aria-label":"Ecosystem command summary cards",children:l.map(([u,x])=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[9px] font-mono text-slate-500 uppercase tracking-[0.1em]",children:u}),e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:x})]},u))})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Drill-Down"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:c.map(([u,x])=>e.jsx("button",{type:"button","data-testid":`ecosystem-command-open-${u}`,onClick:()=>{typeof n=="function"&&n(u)},className:"px-3 py-2 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100 hover:bg-cyan-500/20 text-left",children:x},u))})]})]})]})]})}function RN(){const[t,r]=O.useState(null),[n,s]=O.useState(()=>new Set),a=O.useCallback(m=>{r(m)},[]),o=O.useCallback(m=>{m?(r(f=>f===m?null:f),s(f=>{if(!f.has(m))return f;const b=new Set(f);return b.delete(m),b})):r(null)},[]),l=O.useCallback(m=>{r(f=>f===m?null:m)},[]),c=O.useCallback(m=>t===m||n.has(m),[t,n]),u=O.useCallback(m=>{s(f=>{if(f.has(m))return f;const b=new Set(f);return b.add(m),b})},[]),x=O.useCallback(m=>{s(f=>{if(!f.has(m))return f;const b=new Set(f);return b.delete(m),b})},[]),p=O.useCallback(m=>n.has(m),[n]),d=O.useCallback(()=>{r(null),s(new Set)},[]);return O.useMemo(()=>({activePanel:t,open:a,close:o,toggle:l,isOpen:c,pinned:n,pin:u,unpin:x,isPinned:p,closeAll:d}),[t,n,a,o,l,c,u,x,p,d])}function ON({enabled:t=!1,moodEngine:r,personalityProfile:n="balanced"}){const s=i.useRef("");i.useEffect(()=>{if(!t){s.current="";return}if(!(window.api&&window.api.rgb&&typeof window.api.rgb.applyMood=="function"))return;const a=String(r&&r.rgbMood?r.rgbMood:"idle"),o=`${a}:${n}`;s.current!==o&&(s.current=o,window.api.rgb.applyMood({mood:a,personality:String(n||"balanced")}).catch(()=>{s.current=""}))},[t,r,r&&r.rgbMood,n])}const km="neuralshell_adaptive_layout_v1",TN=["presets","panels","insights"],MN=["nav","chat","status","visual"],DN="neuralshell_layout_usage_v1";function Zu(){try{return JSON.parse(window.localStorage.getItem(km)||"null")}catch{return null}}function Na(t){try{window.localStorage.setItem(km,JSON.stringify(t))}catch{}}function $N(){try{const t=JSON.parse(window.localStorage.getItem(DN)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}const Ns=[{id:"thread-rail",label:"Thread Rail",category:"nav",defaultVisible:!0},{id:"workbench-rail",label:"Workbench Rail",category:"nav",defaultVisible:!0},{id:"ambient-status",label:"Ambient Status Bar",category:"status",defaultVisible:!0},{id:"quick-reply",label:"Quick Reply Bar",category:"chat",defaultVisible:!0},{id:"smart-suggest",label:"Smart Suggestions",category:"chat",defaultVisible:!0},{id:"live-token-budget",label:"Token Budget Bar",category:"chat",defaultVisible:!1},{id:"prompt-template",label:"Prompt Templates",category:"chat",defaultVisible:!1},{id:"custom-actions",label:"Custom Actions Bar",category:"chat",defaultVisible:!0},{id:"chat-summary",label:"Chat Summary Bar",category:"chat",defaultVisible:!1},{id:"streaming-bar",label:"Streaming Progress Bar",category:"status",defaultVisible:!0},{id:"particle-bg",label:"Particle Background",category:"visual",defaultVisible:!1}],dr=[{id:"minimal",name:"Minimal",description:"Clean focus — essential chrome only",icon:"◻",color:"sky",panels:{"thread-rail":!0,"workbench-rail":!1,"ambient-status":!0,"quick-reply":!1,"smart-suggest":!1,"streaming-bar":!0},railWidths:{left:56,right:0}},{id:"operator",name:"Operator",description:"Full operator setup — all tools visible",icon:"⬛",color:"violet",panels:{"thread-rail":!0,"workbench-rail":!0,"ambient-status":!0,"quick-reply":!0,"smart-suggest":!0,"live-token-budget":!0,"custom-actions":!0,"streaming-bar":!0},railWidths:{left:240,right:240}},{id:"writing",name:"Writing",description:"Optimized for long-form text work",icon:"✎",color:"emerald",panels:{"thread-rail":!0,"workbench-rail":!1,"ambient-status":!1,"quick-reply":!0,"smart-suggest":!0,"chat-summary":!0,"streaming-bar":!0},railWidths:{left:180,right:0}},{id:"coding",name:"Coding",description:"Workbench-heavy, max context",icon:" ",color:"fuchsia",panels:{"thread-rail":!0,"workbench-rail":!0,"ambient-status":!0,"live-token-budget":!0,"custom-actions":!0,"prompt-template":!0,"streaming-bar":!0},railWidths:{left:220,right:320}},{id:"hud",name:"HUD / Cockpit",description:"Heads-up — slim rails, status + tokens visible, max reading width",icon:"◈",color:"sky",panels:{"thread-rail":!0,"workbench-rail":!1,"ambient-status":!0,"quick-reply":!0,"smart-suggest":!1,"live-token-budget":!0,"custom-actions":!0,"streaming-bar":!0,"chat-summary":!1,"prompt-template":!1,"particle-bg":!1},railWidths:{left:56,right:0}}];function LN(t){var n;const r=((n=Object.entries(t).sort((s,a)=>a[1]-s[1])[0])==null?void 0:n[0])||null;return r?r.includes("status")||r.includes("hud")||r.includes("telemetry")?dr.find(s=>s.id==="hud"):r.includes("workbench")||r.includes("code")?dr.find(s=>s.id==="coding"):r.includes("write")||r.includes("compose")?dr.find(s=>s.id==="writing"):r.includes("mission")||r.includes("fleet")||r.includes("incident")?dr.find(s=>s.id==="operator"):dr.find(s=>s.id==="minimal"):null}const BN=i.memo(function({open:r,onClose:n,onApplyLayout:s}){const[a,o]=i.useState(()=>Zu()||dr[0]),[l,c]=i.useState(()=>{const w=Zu();return(w==null?void 0:w.panels)||Object.fromEntries(Ns.map(j=>[j.id,j.defaultVisible]))}),[u,x]=i.useState($N),[p,d]=i.useState(!1),[m,f]=i.useState("presets");i.useEffect(()=>{const w=j=>x(j.detail.usage);return window.addEventListener("neuralshell:layout-action",w),()=>window.removeEventListener("neuralshell:layout-action",w)},[]);const b=i.useMemo(()=>LN(u),[u]),h=w=>{o(w),c({...Object.fromEntries(Ns.map(E=>[E.id,E.defaultVisible])),...w.panels});const j={...w,panels:{...Object.fromEntries(Ns.map(E=>[E.id,E.defaultVisible])),...w.panels}};Na(j),typeof s=="function"&&s({...j,_shellSync:"full"})},g=w=>{c(j=>{const E={...j,[w]:!j[w]},N={...a,panels:E};Na(N);try{window.dispatchEvent(new CustomEvent("neuralshell:layout-chrome-updated")),window.dispatchEvent(new CustomEvent("neuralshell:apply-layout"))}catch{}return typeof s=="function"&&s({...N,_shellSync:"panels-only"}),E})},y=()=>{Na({id:"custom",name:"Custom",description:"Your saved layout",icon:"★",color:"amber",panels:l});try{window.dispatchEvent(new CustomEvent("neuralshell:layout-chrome-updated"))}catch{}d(!0),setTimeout(()=>d(!1),1800)},P=()=>{const w=Object.fromEntries(Ns.map(E=>[E.id,E.defaultVisible]));c(w);const j={...dr[0],panels:w};Na(j),typeof s=="function"&&s({...j,_shellSync:"full"})},A=Object.entries(u).sort((w,j)=>j[1]-w[1]).slice(0,5),C=i.useRef(null);return Wa(r,C,n),r?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[210] bg-black/60 backdrop-blur-sm","aria-hidden":"true",onClick:n}),e.jsxs("section",{ref:C,"data-testid":"adaptive-layout-engine",role:"dialog","aria-modal":"true","aria-labelledby":"adaptive-layout-engine-title",className:"fixed right-6 top-14 bottom-4 w-96 z-[211] rounded-2xl border border-indigo-300/20 bg-slate-950 shadow-[0_24px_96px_rgba(99,102,241,0.12)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-5 py-3 border-b border-white/10 bg-gradient-to-r from-indigo-950/50 to-slate-950 flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Xx,{size:15,className:"text-indigo-400","aria-hidden":"true"}),e.jsxs("div",{children:[e.jsx("h2",{id:"adaptive-layout-engine-title",className:"text-[11px] font-bold tracking-wide uppercase text-indigo-300",children:"Adaptive Layout Engine"}),e.jsx("div",{className:"text-[11px] font-mono text-slate-400",children:"Usage-learned panel arrangement"})]})]}),e.jsx("button",{type:"button","data-accessible-overlay-close":!0,onClick:n,"aria-label":"Close adaptive layout engine",title:"Close",className:"h-7 w-7 rounded-full border border-white/10 text-slate-400 hover:bg-white/10 flex items-center justify-center",children:e.jsx(yp,{size:12,"aria-hidden":"true"})})]}),e.jsx("div",{className:"flex border-b border-white/10 bg-black/20",children:TN.map(w=>e.jsx("button",{type:"button",onClick:()=>f(w),className:`px-4 py-2 text-[12px] font-mono uppercase tracking-wider transition-all ${m===w?"border-b-2 border-indigo-400 text-indigo-300 bg-indigo-500/5":"text-slate-500 hover:text-slate-300"}`,children:w},w))}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-4 space-y-3",children:[m==="presets"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[11px] font-mono text-slate-400 px-0.5 leading-relaxed",children:"Presets push rail widths and Flows / Bench collapse to the main window. Use the Panels tab for per-widget chrome without changing rail sizes."}),b&&e.jsxs("div",{className:"rounded-xl border border-indigo-400/20 bg-indigo-500/8 p-3 flex items-start gap-3",children:[e.jsx(gp,{size:14,className:"text-indigo-400 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-bold text-indigo-300",children:"Recommended for you"}),e.jsxs("div",{className:"text-[11px] font-mono text-slate-400 mt-0.5",children:["Based on your usage patterns: ",e.jsx("span",{className:"text-indigo-300",children:b.name})]}),e.jsx("button",{type:"button",onClick:()=>h(b),className:"mt-2 px-2.5 py-1 rounded border border-indigo-400/30 bg-indigo-500/15 text-[11px] font-mono text-indigo-300 hover:bg-indigo-500/25",children:"Apply Recommendation"})]})]}),dr.map(w=>e.jsxs("button",{type:"button",onClick:()=>h(w),className:`w-full text-left rounded-xl border p-3 transition-all ${(a==null?void 0:a.id)===w.id?"border-indigo-400/40 bg-indigo-500/10":"border-white/10 bg-black/20 hover:border-white/20"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:w.icon}),e.jsxs("div",{children:[e.jsx("div",{className:`text-[12px] font-bold ${(a==null?void 0:a.id)===w.id?"text-indigo-300":"text-slate-200"}`,children:w.name}),e.jsx("div",{className:"text-[11px] font-mono text-slate-400",children:w.description})]})]}),(a==null?void 0:a.id)===w.id&&e.jsx(od,{size:12,className:"text-indigo-400 shrink-0"})]}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1",children:Object.entries(w.panels||{}).filter(([,j])=>j).map(([j])=>e.jsx("span",{className:"text-[11px] font-mono px-1 py-0.5 rounded bg-white/5 border border-white/10 text-slate-500",children:j},j))})]},w.id))]}),m==="panels"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:MN.map(w=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-slate-500 px-1",children:w}),Ns.filter(j=>j.category===w).map(j=>e.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-white/8 bg-black/20 px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[12px] font-mono text-slate-200",children:j.label}),e.jsx("div",{className:"text-[11px] font-mono text-slate-400",children:j.id})]}),e.jsx("button",{type:"button",onClick:()=>g(j.id),className:`relative w-10 h-5 rounded-full border transition-all ${l[j.id]?"border-indigo-400/40 bg-indigo-500/30":"border-white/10 bg-white/5"}`,children:e.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full transition-all ${l[j.id]?"left-5 bg-indigo-400":"left-0.5 bg-slate-600"}`})})]},j.id))]},w))}),e.jsxs("div",{className:"flex gap-2 pt-1 border-t border-white/10",children:[e.jsx("button",{type:"button",onClick:y,className:"flex-1 py-2 rounded-lg border border-emerald-400/25 bg-emerald-500/10 text-[11px] font-mono text-emerald-300 flex items-center justify-center gap-1.5",children:p?e.jsxs(e.Fragment,{children:[e.jsx(od,{size:10})," Saved!"]}):e.jsxs(e.Fragment,{children:[e.jsx(Qx,{size:10})," Save Layout"]})}),e.jsxs("button",{type:"button",onClick:P,className:"flex-1 py-2 rounded-lg border border-white/10 text-[11px] font-mono text-slate-400 flex items-center justify-center gap-1.5",children:[e.jsx(ef,{size:10})," Reset"]})]})]}),m==="insights"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"text-[11px] font-mono text-slate-400 uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(tf,{size:9})," Top Actions"]}),A.length===0&&e.jsx("div",{className:"text-[11px] font-mono text-slate-400",children:"No usage data yet. Use the app to build your profile."}),A.map(([w,j])=>{var E;return e.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-mono",children:[e.jsx("span",{className:"text-slate-400 truncate flex-1",children:w}),e.jsx("div",{className:"w-24 h-1.5 rounded-full bg-white/5 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-indigo-400",style:{width:`${Math.min(100,j/(((E=A[0])==null?void 0:E[1])||1)*100)}%`}})}),e.jsx("span",{className:"text-slate-500 w-6 text-right",children:j})]},w)})]}),e.jsxs("div",{className:"rounded-xl border border-indigo-400/15 bg-indigo-500/5 p-3 text-[11px] font-mono text-indigo-300 space-y-1",children:[e.jsx("div",{className:"font-bold text-indigo-200",children:"How it works"}),e.jsx("div",{className:"text-slate-400",children:"The engine tracks which panels, commands, and features you use most frequently."}),e.jsx("div",{className:"text-slate-400",children:"Based on this, it recommends the preset that best matches your workflow."}),e.jsx("div",{className:"text-slate-400",children:"Applying a preset updates the main shell: rail widths and Flows / Bench collapse follow the preset map (minimal and HUD → narrow rails, operator and coding → spacious)."}),e.jsxs("div",{className:"text-slate-400",children:["Call ",e.jsx("span",{className:"text-indigo-300",children:"recordLayoutAction(action)"})," from any component to contribute usage signals."]})]})]})]})]})]}):null}),FN=i.lazy(()=>Kl(()=>Promise.resolve().then(()=>Pg),void 0,import.meta.url)),UN={"voice-mode":{title:"Voice Bridge",subtitle:"WebRTC voice channel for collab rooms"},"agent-store":{title:"Agent Marketplace",subtitle:"Install operator agents into your workspace"},"projects-mode":{title:"Project Scope",subtitle:"Tag the active chat pane with a project context"},"knowledge-base":{title:"Knowledge Base",subtitle:"Attach reference context to your session"},"ai-memory":{title:"AI Memory",subtitle:"Pinned session notes for the active workflow"},"multi-model-split":{title:"Multi-Model Compare",subtitle:"Split the workspace to compare models side-by-side"}};function xn({open:t,panelId:r,onClose:n,children:s,wide:a=!1}){if(!t)return null;const o=UN[r]||{title:"Workspace Panel",subtitle:""};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[138] bg-black/45 backdrop-blur-[1px]",onClick:n,"aria-hidden":"true"}),e.jsxs("aside",{"data-testid":`workspace-panel-${r}`,className:`fixed right-0 top-0 bottom-0 z-[139] bg-slate-950 border-l border-cyan-400/20 shadow-[-16px_0_40px_rgba(0,0,0,0.55)] flex flex-col ${a?"w-full max-w-2xl":"w-full max-w-md"}`,children:[e.jsxs("header",{className:"px-5 py-4 border-b border-white/10 flex items-start justify-between gap-3 shrink-0",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.18em] text-cyan-300 font-bold",children:"Workspace"}),e.jsx("h3",{className:"text-lg font-semibold text-slate-100 mt-0.5",children:o.title}),o.subtitle&&e.jsx("p",{className:"text-[11px] text-slate-500 font-mono mt-1",children:o.subtitle})]}),e.jsx("button",{type:"button",onClick:n,className:"h-9 w-9 rounded-full hover:bg-white/5 text-slate-400 hover:text-white transition-colors","aria-label":"Close panel",children:"✕"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-5 custom-scrollbar",children:s})]})]})}function zN({onApply:t,onClose:r}){const[n,s]=i.useState("");return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("label",{className:"block space-y-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-widest text-slate-400 font-bold",children:"Project name"}),e.jsx("input",{value:n,onChange:a=>s(a.target.value),placeholder:"e.g. release-2138, client-alpha",className:"w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-sm text-slate-200 outline-none focus:border-cyan-400/50 font-mono"})]}),e.jsx("button",{type:"button",onClick:()=>{t(String(n||"").trim()),r()},className:"w-full px-3 py-2 rounded-xl border border-sky-300/30 bg-sky-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-sky-200 hover:bg-sky-500/20",children:"Apply to active pane"})]})}function HN(){return e.jsxs("div",{className:"space-y-3 text-[12px] text-slate-400 leading-relaxed",children:[e.jsx("p",{children:"Attach files and notes from the workbench rail, or drop artifacts into chat messages."}),e.jsxs("ul",{className:"list-disc pl-5 space-y-1 font-mono text-[11px] text-slate-500",children:[e.jsxs("li",{children:["Use ",e.jsx("code",{className:"text-cyan-300",children:"/proof"})," to validate operator flows"]}),e.jsx("li",{children:"Save sessions to preserve context across locks"}),e.jsx("li",{children:"Import env provider profiles in Settings"})]})]})}function WN({memoryKey:t}){const[r,n]=i.useState(()=>{try{return String(window.localStorage.getItem(t)||"")}catch{return""}});return i.useEffect(()=>{try{window.localStorage.setItem(t,r)}catch{}},[t,r]),e.jsxs("div",{className:"space-y-3",children:[e.jsx("textarea",{value:r,onChange:s=>n(s.target.value),rows:12,placeholder:"Pinned notes for this workflow — goals, constraints, decisions…",className:"w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-sm text-slate-200 outline-none focus:border-rose-400/40 font-mono resize-y min-h-52"}),e.jsx("p",{className:"text-[10px] text-slate-500 font-mono",children:"Saved locally per workflow. Toggle the memory chip to keep this drawer open while chatting."})]})}function KN({onLaunch:t,onClose:r}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-[12px] text-slate-400",children:"Opens a two-pane split so you can compare models on the same prompt. A second pane is created automatically if needed."}),e.jsx("button",{type:"button",onClick:()=>{t(),r()},className:"w-full px-3 py-2 rounded-xl border border-indigo-300/30 bg-indigo-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-indigo-200 hover:bg-indigo-500/20",children:"Launch split compare"})]})}function VN({panels:t,collab:r,workflowId:n}){const s=i.useCallback(l=>{t&&typeof t.close=="function"&&t.close(l)},[t]),a=i.useCallback((l,c={})=>{window.dispatchEvent(new CustomEvent("neuralshell:workspace-panel-action",{detail:{action:l,...c}}))},[]),o=`neuralshell_ai_memory_${String(n||"default")}`;return t?e.jsxs(e.Fragment,{children:[e.jsx(xn,{open:t.isOpen("voice-mode"),panelId:"voice-mode",onClose:()=>s("voice-mode"),children:e.jsx(Kh,{collab:r})}),e.jsx(xn,{open:t.isOpen("agent-store"),panelId:"agent-store",wide:!0,onClose:()=>s("agent-store"),children:e.jsx(i.Suspense,{fallback:e.jsx("div",{className:"text-slate-500 text-sm font-mono",children:"Loading agents…"}),children:e.jsx(FN,{})})}),e.jsx(xn,{open:t.isOpen("projects-mode"),panelId:"projects-mode",onClose:()=>s("projects-mode"),children:e.jsx(zN,{onApply:l=>a("set-project",{project:l}),onClose:()=>s("projects-mode")})}),e.jsx(xn,{open:t.isOpen("knowledge-base"),panelId:"knowledge-base",onClose:()=>s("knowledge-base"),children:e.jsx(HN,{})}),e.jsx(xn,{open:t.isOpen("ai-memory"),panelId:"ai-memory",onClose:()=>s("ai-memory"),children:e.jsx(WN,{memoryKey:o})}),e.jsx(xn,{open:t.isOpen("multi-model-split"),panelId:"multi-model-split",onClose:()=>s("multi-model-split"),children:e.jsx(KN,{onLaunch:()=>a("multi-model-split"),onClose:()=>s("multi-model-split")})})]}):null}function GN(){return`peer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function JN(t){const r=String(t||"").trim()||"default",[n,s]=i.useState(!1),[a]=i.useState(()=>GN()),[o,l]=i.useState({}),[c,u]=i.useState(null),x=i.useRef(null);i.useEffect(()=>{let d=!1,m=null;const f=()=>{if(x.current){try{x.current.close()}catch{}x.current=null}},b=async()=>{try{const h=await window.api.collab.getStatus();if(d)return;const g=String(h&&h.host?h.host:"127.0.0.1"),y=Number(h&&h.port?h.port:55116),P=new WebSocket(`ws://${g}:${y}`);x.current=P,P.onopen=()=>{d||(s(!0),P.send(JSON.stringify({action:"join",room:r,peerId:a})))},P.onclose=()=>{d||(s(!1),m==null&&(m=window.setTimeout(()=>{m=null,b()},1200)))},P.onmessage=A=>{let C=null;try{C=JSON.parse(String(A.data||""))}catch{return}if(!C||typeof C!="object"||C.action!=="event")return;const w=String(C.eventType||""),j=String(C.fromPeerId||""),E=C.payload&&typeof C.payload=="object"?C.payload:{};if(w==="cursor"){const N=Number(E.x||0),_=Number(E.y||0);l(S=>({...S,[j]:{x:N,y:_,updatedAt:new Date().toISOString()}}))}u({eventType:w,payload:E,fromPeerId:j})}}catch{if(d)return;s(!1),m==null&&(m=window.setTimeout(()=>{m=null,b()},1200))}};return b(),()=>{d=!0,m!=null&&window.clearTimeout(m),f()}},[a,r]);const p=i.useCallback((d,m)=>!x.current||x.current.readyState!==WebSocket.OPEN?!1:(x.current.send(JSON.stringify({action:"publish",room:r,eventType:String(d||""),payload:m&&typeof m=="object"?m:{}})),!0),[r]);return{connected:n,peerId:a,roomId:r,remoteCursors:o,lastEvent:c,publish:p}}function qt(t,r=""){if(typeof window>"u"||!window.localStorage)return r;const n=window.localStorage.getItem(t);return n==null?r:String(n||r)}function qN(){if(typeof window>"u"||!window.localStorage)return"default";try{const t=JSON.parse(window.localStorage.getItem("neuralshell_branding_profile_active_v1")||"{}");return String(t&&t.profileId?t.profileId:"default")}catch{return"default"}}function YN(){const t=qt("neuralshell_voice_rtt_median_v1","");if(!t)return null;const r=Number(t);return Number.isFinite(r)?Math.round(r):null}function ZN(){return{providerHealth:{activeProvider:"ollama",model:"llama3",latencyMs:null,online:!1,lastSweepResult:"unknown",lastSweepAt:""},vaultState:{locked:!1,activeProfile:"default",exportImportStatus:"idle",policyBound:!1},proofEngine:{lastProofStatus:"idle",currentStage:"idle",lastBundleHash:"",parityState:"unknown"},relayState:{enabled:!1,mappedChannel:"local-only",lastRelaySend:"",relayError:""},collabVoiceState:{peersActive:0,currentRoom:"default",voiceRttMs:null,sessionHealth:"offline"},policyState:{activePolicyProfile:"none",updateRing:"stable",offlineOnly:!1,approvedProviders:[]},updateLane:{currentVersion:"2.1.29",lastUpdateCheck:"",signatureState:"unknown",stagedUpdateAvailable:!1},sealIdentity:{sealIdentity:"unknown",machineTrust:"unknown",whiteLabelProfile:"default"},watchdog:{status:"unknown",pid:null,wsRunning:!1},releaseHealth:{status:"unknown"},refreshedAt:new Date().toISOString()}}function XN({connectionInfo:t,workflowId:r,runtimeTier:n,sessionHydrationStatus:s,collabConnected:a,collabRoomId:o,collabPeerCount:l}){const[c,u]=i.useState(()=>ZN()),x=i.useRef(null),p=i.useCallback(async()=>{var z,F,J,ee,ie,ye,pe,K,H,W,Z,ce,fe,me,ke,Pe;const[d,m,f,b,h,g,y,P]=await Promise.all([(F=(z=window.api)==null?void 0:z.settings)!=null&&F.get?window.api.settings.get().catch(()=>({})):Promise.resolve({}),(ee=(J=window.api)==null?void 0:J.daemon)!=null&&ee.status?window.api.daemon.status().catch(()=>({})):Promise.resolve({}),(ye=(ie=window.api)==null?void 0:ie.autoUpdate)!=null&&ye.getPolicy?window.api.autoUpdate.getPolicy().catch(()=>({})):Promise.resolve({}),(K=(pe=window.api)==null?void 0:pe.autoUpdate)!=null&&K.pending?window.api.autoUpdate.pending().catch(()=>({})):Promise.resolve({}),(W=(H=window.api)==null?void 0:H.releaseHealth)!=null&&W.check?window.api.releaseHealth.check().catch(()=>({})):Promise.resolve({}),(ce=(Z=window.api)==null?void 0:Z.collab)!=null&&ce.getStatus?window.api.collab.getStatus().catch(()=>({})):Promise.resolve({}),(me=(fe=window.api)==null?void 0:fe.identity)!=null&&me.pubkey?window.api.identity.pubkey().catch(()=>({})):Promise.resolve({}),(Pe=(ke=window.api)==null?void 0:ke.modelPool)!=null&&Pe.status?window.api.modelPool.status().catch(()=>({})):Promise.resolve({})]),A=String(t&&t.provider?t.provider:"ollama"),C=String(t&&t.model?t.model:"llama3"),j=String(t&&t.health?t.health:"unknown")==="online",E=qt("neuralshell_provider_sweep_last_v1",j?"passed":"unknown"),N=qt("neuralshell_provider_sweep_at_v1",""),_=Number.isFinite(Number(P&&P.idleMs))?Math.round(Number(P.idleMs)):null,S=d&&d.enterprisePolicyEnforced&&typeof d.enterprisePolicyEnforced=="object"?d.enterprisePolicyEnforced:{},R=Array.isArray(S.allowedProviders)?S.allowedProviders.map(_e=>String(_e||"").trim().toLowerCase()).filter(Boolean):[],$=String(S.label||S.policyId||"none"),U=String(d&&d.autoUpdateChannel?d.autoUpdateChannel:f&&f.channel?f.channel:"stable"),I={providerHealth:{activeProvider:A,model:C,latencyMs:_,online:j,lastSweepResult:E,lastSweepAt:N},vaultState:{locked:String(s||"")==="locked",activeProfile:String(r||"default"),exportImportStatus:qt("neuralshell_vault_last_action_v1","idle"),policyBound:!!(S&&Object.keys(S).length>0)},proofEngine:{lastProofStatus:qt("neuralshell_proof_last_status_v1","idle"),currentStage:qt("neuralshell_proof_stage_v1","idle"),lastBundleHash:qt("neuralshell_proof_last_bundle_hash_v1",""),parityState:String(h&&h.status?h.status:"unknown")},relayState:{enabled:!!(d&&d.proofRelayEnabled),mappedChannel:String(o||"default"),lastRelaySend:qt("neuralshell_relay_last_send_v1",""),relayError:qt("neuralshell_relay_last_error_v1","")},collabVoiceState:{peersActive:Math.max(0,Number(l||0)),currentRoom:String(o||(g&&g.roomId?g.roomId:"default")),voiceRttMs:YN(),sessionHealth:a?"healthy":"degraded"},policyState:{activePolicyProfile:$,updateRing:U,offlineOnly:!!(d&&d.offlineOnlyEnforced),approvedProviders:R},updateLane:{currentVersion:String(d&&d.appVersion?d.appVersion:"2.1.29"),lastUpdateCheck:String(b&&b.checkedAt?b.checkedAt:""),signatureState:b&&b.verified?"verified":"unverified",stagedUpdateAvailable:!!(b&&b.available)},sealIdentity:{sealIdentity:String(y&&y.fingerprint?y.fingerprint:"unknown"),machineTrust:String(n||"unknown").toLowerCase(),whiteLabelProfile:qN()},watchdog:{status:String(m&&m.status?m.status:"unknown"),pid:Number.isFinite(Number(m&&m.pid))?Number(m.pid):null,wsRunning:!!(m&&m.wsBridge&&m.wsBridge.running)},releaseHealth:{status:String(h&&h.status?h.status:"unknown")},refreshedAt:new Date().toISOString()},D=x.current;return D&&D.providerHealth.online!==I.providerHealth.online&&X(I.providerHealth.online?"provider.sweep.passed":"provider.sweep.failed",{provider:I.providerHealth.activeProvider,model:I.providerHealth.model},{severity:I.providerHealth.online?"info":"degraded",source:"runtime"}),D&&D.watchdog.status!==I.watchdog.status&&X("runtime.watchdog.alert",{status:I.watchdog.status,pid:I.watchdog.pid},{severity:I.watchdog.status==="running"?"info":"warning",source:"watchdog"}),D&&D.policyState.activePolicyProfile!==I.policyState.activePolicyProfile&&X("policy.changed",{policyProfile:I.policyState.activePolicyProfile,updateRing:I.policyState.updateRing},{severity:"info",source:"policy"}),D&&D.vaultState.locked!==I.vaultState.locked&&X(I.vaultState.locked?"vault.locked":"vault.unlocked",{activeProfile:I.vaultState.activeProfile},{severity:I.vaultState.locked?"warning":"info",source:"vault"}),x.current=I,u(I),I},[a,l,o,t,n,s,r]);return i.useEffect(()=>{p();const d=window.setInterval(p,6e3);return()=>window.clearInterval(d)},[p]),{runtimeState:c,refreshRuntimeState:p}}function QN(){const[t,r]=i.useState(()=>Pl().slice(-250));i.useEffect(()=>(r(Pl().slice(-250)),K0(s=>{r(a=>[...a,s].slice(-250))})),[]);const n=t.length?t[t.length-1]:null;return{events:t,latest:n}}const Ss=[{id:"welcome_intro",title:"Welcome / Mode Intro",description:"Establish local-first runtime authority and operating mode.",critical:!1},{id:"provider_sweep",title:"Provider Sweep",description:"Probe provider bridge health and establish baseline.",critical:!0},{id:"vault_setup",title:"Vault Setup",description:"Create and verify a local vault secret.",critical:!0},{id:"policy_profile_selection",title:"Policy Profile Selection",description:"Select enforcement profile and allowed providers.",critical:!0},{id:"update_ring_selection",title:"Update Ring Selection",description:"Select stable/beta/canary/frozen update lane.",critical:!0},{id:"run_proof",title:"Run 90-second Proof",description:"Run proof command and capture runtime evidence.",critical:!0},{id:"install_core_agent",title:"Install Core Agent",description:"Install the proof_guard operator agent into your local workspace.",critical:!0},{id:"license_import",title:"Import Tier/License",description:"Optional: import enterprise/pro license payload.",critical:!1},{id:"share_badge",title:"Share Badge / Skip",description:"Open badge share path or skip.",critical:!1},{id:"open_mission_control",title:"Open Mission Control",description:"Land in runtime cockpit and review system posture.",critical:!0}],Nm="neuralshell_first_boot_progress_v1",Xu="neuralshell_first_boot_events_v1",Sa="neuralshell_first_boot_dismissed_v1";function eS(){if(typeof window>"u"||!window.localStorage)return{};try{const t=JSON.parse(window.localStorage.getItem(Nm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function Qu(t){typeof window>"u"||!window.localStorage||window.localStorage.setItem(Nm,JSON.stringify(t||{}))}function Er(t,r="",n={}){if(!(typeof window>"u"||!window.localStorage))try{const s=JSON.parse(window.localStorage.getItem(Xu)||"[]"),a=Array.isArray(s)?s:[],o={at:new Date().toISOString(),type:String(t||""),stepId:String(r||""),detail:n&&typeof n=="object"?n:{}};a.push(o),window.localStorage.setItem(Xu,JSON.stringify(a.slice(-250)))}catch{}}function tS(){const[t,r]=i.useState(()=>eS()),[n,s]=i.useState(()=>typeof window>"u"||!window.localStorage?!0:!(window.localStorage.getItem(Sa)==="1")),[a,o]=i.useState(""),l=i.useMemo(()=>(Array.isArray(Ss)?Ss:[]).filter(b=>!!t[String(b.id||"")]).length,[t]),c=i.useMemo(()=>l>=(Array.isArray(Ss)?Ss.length:0),[l]),u=i.useCallback(b=>{const h=String(b||"");h&&(r(g=>{const y={...g||{},[h]:!0};return Qu(y),y}),Er("step_completed",h),X("firstboot.step.completed",{stepId:h},{source:"firstboot",severity:"info"}))},[]),x=i.useCallback(b=>{const h=String(b||"");h&&(Er("step_skipped",h),X("firstboot.step.skipped",{stepId:h},{source:"firstboot",severity:"info"}))},[]),p=i.useCallback(()=>{typeof window<"u"&&window.localStorage&&window.localStorage.setItem(Sa,"1"),s(!1),Er("wizard_dismissed")},[]),d=i.useCallback(()=>{typeof window<"u"&&window.localStorage&&window.localStorage.removeItem(Sa),s(!0),Er("wizard_reopened")},[]),m=i.useCallback(()=>{r({}),Qu({}),typeof window<"u"&&window.localStorage&&window.localStorage.removeItem(Sa),s(!0),Er("wizard_reset"),X("firstboot.reset",{},{source:"firstboot",severity:"warning"})},[]),f=i.useCallback(async(b,h)=>{const g=String(b||"");if(!g)return!1;o(g),Er("step_started",g),X("firstboot.step.started",{stepId:g},{source:"firstboot",severity:"info"});try{return typeof h=="function"&&await Promise.resolve(h()),u(g),!0}catch(y){const P=y&&y.message?y.message:String(y);return Er("step_failed",g,{message:P}),X("firstboot.step.failed",{stepId:g,message:P},{source:"firstboot",severity:"warning"}),!1}finally{o("")}},[u]);return{steps:Ss,progress:t,open:n,setOpen:s,busyStepId:a,completedCount:l,allDone:c,completeStep:u,markSkipped:x,runStep:f,dismiss:p,reopen:d,reset:m}}async function rS(){if(typeof window>"u"||!window.api||!window.api.omega||typeof window.api.omega.status!="function")throw new Error("OMEGA status API unavailable");return window.api.omega.status()}function nS({enabled:t=!0,intervalMs:r=12e3}={}){const[n,s]=O.useState(null),[a,o]=O.useState(!!t),[l,c]=O.useState(""),u=O.useRef(!0),x=O.useCallback(async()=>{if(!t)return null;o(!0),c("");try{const p=await rS();return u.current&&s(p),p}catch(p){if(!u.current)return null;const d=p&&p.message?p.message:String(p);return c(d),null}finally{u.current&&o(!1)}},[t]);return O.useEffect(()=>{if(u.current=!0,!t)return;x();const p=window.setInterval(()=>{x()},Math.max(4e3,Number(r)||12e3));return()=>{u.current=!1,window.clearInterval(p)}},[t,r,x]),{report:n,loading:a,error:l,refresh:x}}const ep="neuralshell_fleet_nodes_v1",tp="neuralshell_fleet_filter_v1",rp="neuralshell_fleet_selected_v1";function Ie(t,r=""){return String(t??r).trim()||r}function Sm(t){const r=Ie(t);if(!r)return new Date().toISOString();const n=new Date(r);return Number.isNaN(n.getTime())?new Date().toISOString():n.toISOString()}function lc(t){const r=Ie(t).toLowerCase();return r==="healthy"?"healthy":r==="critical"?"critical":r==="offline"?"offline":"degraded"}function sS(t){return Array.isArray(t)?t.map(r=>Ie(r)).filter(Boolean):t==null?[]:Ie(t).split(/[|,]/).map(r=>Ie(r)).filter(Boolean)}function Ra(t,r=0){const n=Ie(t&&t.severity,"info").toLowerCase(),s=n==="critical"?"critical":n==="degraded"?"degraded":n==="warning"?"warning":"info";return{id:Ie(t&&t.id,`fleet-event-${Date.now()}-${r}`),at:Sm(t&&t.at),type:Ie(t&&t.type,"fleet.event"),severity:s,source:Ie(t&&t.source,"fleet"),detail:t&&t.detail&&typeof t.detail=="object"?t.detail:{}}}function gn(t,r="local-import"){const n=t&&typeof t=="object"?t:{},s=Ie(n.nodeId||n.id||n.node||n.machineId);return{nodeId:s||`node-${Math.random().toString(36).slice(2,8)}`,displayName:Ie(n.displayName||n.name||s||"Imported Node"),runtimeHealth:lc(n.runtimeHealth||n.health||n.status),providerHealth:Ie(n.providerHealth||n.provider||"unknown"),proofStatus:Ie(n.proofStatus||n.proof||"unknown"),policyProfile:Ie(n.policyProfile||n.policy||"none"),updateVersion:Ie(n.updateVersion||n.version||"unknown"),relayStatus:Ie(n.relayStatus||n.relay||"unknown"),collabState:Ie(n.collabState||n.collab||"unknown"),lastSeenAt:Sm(n.lastSeenAt||n.lastSeen||n.updatedAt),alerts:sS(n.alerts),importedFrom:Ie(n.importedFrom||r,r),updateRing:Ie(n.updateRing,"standard"),activePackId:Ie(n.activePackId,""),applianceMode:!!n.applianceMode,events:Array.isArray(n.events)?n.events.map((a,o)=>Ra(a,o)).slice(-160):[]}}function al(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function ol(t,r){typeof window>"u"||!window.localStorage||window.localStorage.setItem(t,JSON.stringify(r))}function np(t,r){const n=new Map;return(Array.isArray(t)?t:[]).forEach(s=>{const a=gn(s,s&&s.importedFrom?s.importedFrom:"local-import");n.set(a.nodeId,a)}),(Array.isArray(r)?r:[]).forEach(s=>{const a=gn(s,s&&s.importedFrom?s.importedFrom:"local-import"),o=n.get(a.nodeId);if(!o){n.set(a.nodeId,a);return}n.set(a.nodeId,{...o,...a,events:[...o.events||[],...a.events||[]].slice(-160),alerts:Array.from(new Set([...o.alerts||[],...a.alerts||[]]))})}),Array.from(n.values()).sort((s,a)=>String(s.displayName||"").localeCompare(String(a.displayName||"")))}function aS(t){return(Array.isArray(t)?t:[]).reduce((r,n)=>{const s=lc(n&&n.runtimeHealth);return r.total+=1,r[s]+=1,r},{total:0,healthy:0,degraded:0,critical:0,offline:0})}function oS(t,r){return!t||!r?[]:[{key:"runtimeHealth",label:"Runtime Health",left:t.runtimeHealth,right:r.runtimeHealth},{key:"providerHealth",label:"Provider Health",left:t.providerHealth,right:r.providerHealth},{key:"proofStatus",label:"Proof Status",left:t.proofStatus,right:r.proofStatus},{key:"policyProfile",label:"Policy Profile",left:t.policyProfile,right:r.policyProfile},{key:"updateVersion",label:"Update Version",left:t.updateVersion,right:r.updateVersion},{key:"updateRing",label:"Update Ring",left:t.updateRing,right:r.updateRing},{key:"relayStatus",label:"Relay Status",left:t.relayStatus,right:r.relayStatus},{key:"collabState",label:"Collab State",left:t.collabState,right:r.collabState},{key:"alertCount",label:"Alert Count",left:t.alerts.length,right:r.alerts.length}].map(s=>({...s,changed:String(s.left)!==String(s.right)})).filter(s=>s.changed)}function iS(){const[t,r]=i.useState(()=>{const w=al(ep,[]);return Array.isArray(w)?w.map(j=>gn(j,j&&j.importedFrom?j.importedFrom:"local-import")):[]}),[n,s]=i.useState(()=>{const w=Ie(al(tp,"all"),"all").toLowerCase();return w==="healthy"||w==="degraded"||w==="critical"||w==="offline"?w:"all"}),[a,o]=i.useState(()=>{const w=al(rp,[]);return Array.isArray(w)?w.map(j=>Ie(j)).filter(Boolean).slice(0,2):[]});i.useEffect(()=>{ol(ep,t)},[t]),i.useEffect(()=>{ol(tp,n)},[n]),i.useEffect(()=>{ol(rp,a)},[a]);const l=i.useMemo(()=>n==="all"?t:t.filter(w=>lc(w.runtimeHealth)===n),[t,n]),c=i.useMemo(()=>aS(t),[t]),u=i.useMemo(()=>{const w=new Map(t.map(j=>[j.nodeId,j]));return a.map(j=>w.get(String(j))).filter(Boolean)},[t,a]),x=i.useMemo(()=>oS(u[0]||null,u[1]||null),[u]),p=i.useCallback((w,j="local-import")=>{const N=(Array.isArray(w)?w:[]).map(_=>gn(_,j));return r(_=>np(_,N)),X("fleet.nodes.imported",{imported:N.length,sourceName:j},{source:"fleet",severity:"info"}),N.length},[]),d=i.useCallback(async w=>{if(!w)return 0;const j=await pt(w),E=Ds(j,String(w.name||""));return p(E,String(w.name||"local-file"))},[p]),m=i.useCallback((w,j={})=>{const E=w&&typeof w=="object"?w:{},N=gn({nodeId:j.nodeId||"local-runtime",displayName:j.displayName||"Local Runtime",runtimeHealth:E.watchdog&&E.watchdog.status==="running"?"healthy":"degraded",providerHealth:E.providerHealth&&E.providerHealth.online?"online":"offline",proofStatus:E.proofEngine&&E.proofEngine.lastProofStatus?E.proofEngine.lastProofStatus:"idle",policyProfile:E.policyState&&E.policyState.activePolicyProfile?E.policyState.activePolicyProfile:"none",updateVersion:E.updateLane&&E.updateLane.currentVersion?E.updateLane.currentVersion:"unknown",relayStatus:E.relayState&&E.relayState.enabled?"enabled":"disabled",collabState:E.collabVoiceState&&E.collabVoiceState.sessionHealth?E.collabVoiceState.sessionHealth:"unknown",lastSeenAt:new Date().toISOString(),importedFrom:"runtime-local",updateRing:E.policyState&&E.policyState.updateRing?E.policyState.updateRing:"standard",applianceMode:!!j.applianceMode},"runtime-local");return r(_=>np(_,[N])),N},[]),f=i.useCallback(w=>{const j=Ie(w);j&&o(E=>E.includes(j)?E.filter(N=>N!==j):[...E,j].slice(-2))},[]),b=i.useCallback(w=>{const j=Ie(w);j&&(r(E=>E.filter(N=>String(N.nodeId||"")!==j)),o(E=>E.filter(N=>N!==j)),X("fleet.node.removed",{nodeId:j},{source:"fleet",severity:"warning"}))},[]),h=i.useCallback(()=>{r([]),o([]),X("fleet.nodes.cleared",{},{source:"fleet",severity:"warning"})},[]),g=i.useCallback((w,j)=>{const E=Ie(w);if(!E)return;const N=j&&typeof j=="object"?j:{};r(_=>_.map(S=>String(S.nodeId||"")!==E?S:gn({...S,...N,nodeId:E},S.importedFrom||"fleet-update")))},[]),y=i.useCallback((w,j)=>{const E=Ie(w);E&&r(N=>N.map(_=>{if(String(_.nodeId||"")!==E)return _;const S=Ra({id:j.id||`fleet-event-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,at:j.at||new Date().toISOString(),type:j.type||"fleet.event",severity:j.severity||"info",source:j.source||"fleet",detail:j.detail||{}});return{..._,events:[..._.events||[],S].slice(-160)}}))},[]),P=i.useCallback((w,j,E={})=>{const N=w&&typeof w=="object"?w:{},_=Array.isArray(j)?j.map($=>Ie($)).filter(Boolean):[],S=Ie(N.policyProfile||N.label||N.policyId,"fleet-policy"),R=Ie(E.mode,"immediate");return r($=>$.map(U=>_.includes(String(U.nodeId||""))?{...U,policyProfile:S,lastSeenAt:new Date().toISOString(),events:[...U.events||[],Ra({type:"fleet.policy.rollout",severity:"info",source:"fleet-policy",detail:{policyProfile:S,mode:R}})].slice(-160)}:U)),X("fleet.policy.rollout",{policyProfile:S,targets:_.length,mode:R},{source:"fleet-policy",severity:"info"}),{policyProfile:S,targets:_.length}},[]),A=i.useCallback((w,j)=>{const E=Ie(w);E&&(g(E,{policyProfile:Ie(j,"none"),lastSeenAt:new Date().toISOString()}),y(E,{type:"fleet.policy.rollback",severity:"warning",source:"fleet-policy",detail:{previousPolicy:Ie(j,"none")}}))},[y,g]),C=i.useCallback((w,j)=>{const E=Array.isArray(w)?w.map(R=>Ie(R)).filter(Boolean):[],N=Ie(j&&j.packId,""),_=Ie(j&&j.ring,"standard"),S=Ie(j&&j.version,"unknown");r(R=>R.map($=>E.includes(String($.nodeId||""))?{...$,activePackId:N,updateRing:_,updateVersion:S,events:[...$.events||[],Ra({type:"fleet.update.pack.assigned",severity:"info",source:"fleet-updates",detail:{packId:N,ring:_,version:S}})].slice(-160)}:$)),X("fleet.update.pack.assigned",{targets:E.length,packId:N,ring:_,version:S},{source:"fleet-updates",severity:"info"})},[]);return{nodes:t,filteredNodes:l,statusFilter:n,setStatusFilter:s,healthSummary:c,selectedNodeIds:a,selectedNodes:u,compareRows:x,importFleetRecords:p,importFleetFile:d,importRuntimeNode:m,toggleNodeSelected:f,removeNode:b,clearFleet:h,updateNode:g,appendNodeEvent:y,applyPolicyBundle:P,rollbackPolicy:A,assignUpdatePack:C}}function lS(t){return t&&t.online?null:{source:"provider-bridge",severity:"degraded",message:`Provider bridge is offline (${String(t&&t.provider?t.provider:"unknown")}/${String(t&&t.model?t.model:"unknown")}).`,suggestedAction:"Run provider sweep and switch to safe local profile."}}function cS(t){const r=!!(t&&t.enabled),n=String(t&&t.relayError?t.relayError:"");return!r||!n?null:{source:"relay",severity:"warning",message:`Relay is enabled with error: ${n}`,suggestedAction:"Disable relay path and retry provider/transport checks."}}function dS(t){const r=String(t&&t.signatureState?t.signatureState:"unknown").toLowerCase(),n=!!(t&&t.stagedUpdateAvailable);return r==="verified"||!n&&r==="unknown"?null:{source:"update-lane",severity:"critical",message:`Update verification is ${r}.`,suggestedAction:"Freeze update apply lane until signature/hash verification passes."}}function uS(t){const r=!!(t&&t.locked),n=String(t&&t.exportImportStatus?t.exportImportStatus:"idle").toLowerCase();return!r&&!n.includes("error")?null:{source:"vault",severity:r?"warning":"degraded",message:r?"Vault is currently locked.":`Vault action state indicates issue: ${n}`,suggestedAction:"Unlock vault and verify read/write with a local secret round-trip."}}function pS(t,r){return`${t}:${r}`.toLowerCase()}class mS{constructor(r={}){this.hooks=r,this.alerts=new Map}getAlerts(){return Array.from(this.alerts.values()).sort((r,n)=>String(n.at).localeCompare(String(r.at)))}acknowledgeAlert(r){const n=this.alerts.get(String(r||""));return n?(this.alerts.set(n.id,{...n,acknowledged:!0}),!0):!1}async evaluate(r){const n=[lS({online:!!(r&&r.providerHealth&&r.providerHealth.online),provider:String(r&&r.providerHealth?r.providerHealth.activeProvider:""),model:String(r&&r.providerHealth?r.providerHealth.model:"")}),cS({enabled:!!(r&&r.relayState&&r.relayState.enabled),relayError:String(r&&r.relayState?r.relayState.relayError:"")}),dS({signatureState:String(r&&r.updateLane?r.updateLane.signatureState:""),stagedUpdateAvailable:!!(r&&r.updateLane&&r.updateLane.stagedUpdateAvailable)}),uS({locked:!!(r&&r.vaultState&&r.vaultState.locked),exportImportStatus:String(r&&r.vaultState?r.vaultState.exportImportStatus:"")})].filter(Boolean),s=new Set;for(const a of n){const o=pS(a.source,a.message);if(s.add(o),!this.alerts.get(o)){const c={id:o,source:a.source,severity:a.severity,message:a.message,suggestedAction:a.suggestedAction,at:new Date().toISOString(),sticky:a.severity==="degraded"||a.severity==="critical",acknowledged:!1};this.alerts.set(o,c),this.hooks.onAlert&&this.hooks.onAlert(c)}await this.tryRecover(a)}return Array.from(this.alerts.values()).forEach(a=>{if(!s.has(a.id)&&!a.sticky){this.alerts.delete(a.id);return}!s.has(a.id)&&a.sticky&&!a.recoveredAt&&this.alerts.set(a.id,{...a,recoveredAt:new Date().toISOString()})}),this.getAlerts()}async tryRecover(r){try{if(r.source==="provider-bridge"&&this.hooks.retryProviderProbe){await Promise.resolve(this.hooks.retryProviderProbe());return}if(r.source==="relay"&&this.hooks.disableRelayPath){await Promise.resolve(this.hooks.disableRelayPath());return}r.source==="update-lane"&&this.hooks.freezeUpdateLane&&(await Promise.resolve(this.hooks.freezeUpdateLane()),this.hooks.switchSafePolicy&&await Promise.resolve(this.hooks.switchSafePolicy()))}catch{}}}const Cs="NeuralShell_QuickStart",xS=new Set(["/help","/proof","/roi","/status","/workflows","/guard","/omega","/kernel","/clear"]),fS="### OMEGA Kernel — Constitutional Scan",il="https://gumroad.com/l/neuralshell-operator",bS="https://github.com/Z3r0DayZion-install/NeuralShell/issues/new?template=bug_report.md&title=Feedback%3A+",sp="neuralshell_readiness_verdict_ack_v1",ap="neuralshell_readiness_degraded_session_v1",ll="neuralshell_onboarding_dismissed_v1",hS="neuralshell_onboarding_progress_v1",op=1440,gS=1280,yS=1080,Cm="neuralshell_rail_layout_prefs_v1",_m="neuralshell_rail_collapse_prefs_v1",ip="neuralshell_rail_resize_hint_dismissed_v1",lp="neuralshell_appliance_mode_v1",cp="neuralshell_airgap_mode_v1",dp="neuralshell_demo_mode_v1",cl="neuralshell_runtime_role_v1",up="neuralshell_incidents_v1",pp="neuralshell_policy_rollout_history_v1",Ml="neuralshell_internal_gtm_mode_v1",jn=288,kn=288,st=236,at=236,Ot=480,Tt=500,Ca=24,mp=16,wS="neuralshell_nodechain_rules_v1",vS=["releaseHealth:check","audit:verify","verification:run"],dl=Object.freeze({expanded:Object.freeze({thread:!1,workbench:!1}),balanced:Object.freeze({thread:!1,workbench:!0}),focused:Object.freeze({thread:!1,workbench:!0})});function xp(){return`Workflow_${Math.random().toString(36).slice(2,7).toUpperCase()}`}function jS(){if(typeof window>"u"||!window.localStorage)return 0;try{const t=JSON.parse(window.localStorage.getItem(hS)||"{}");return Object.values(t&&typeof t=="object"?t:{}).filter(Boolean).length}catch{return 0}}function ze(t,r,n){const s=Number.isFinite(Number(n))?Math.max(180,Math.round(Number(n))):Math.max(180,Math.round(Number(r)||180)),a=Number.isFinite(Number(r))?Math.min(Math.max(180,Math.round(Number(r))),s):Math.min(220,s),o=Number.isFinite(Number(t))?Number(t):a;return Math.round(Math.min(Math.max(o,a),s))}function kS(){if(typeof window>"u"||!window.localStorage)return{thread:jn,workbench:kn};try{const t=JSON.parse(window.localStorage.getItem(Cm)||"{}");return{thread:ze(t&&typeof t=="object"?t.thread:jn,st,Ot),workbench:ze(t&&typeof t=="object"?t.workbench:kn,at,Tt)}}catch{return{thread:jn,workbench:kn}}}function NS(){const t={expanded:{thread:!1,workbench:!1},balanced:{thread:!1,workbench:!1},focused:{thread:!1,workbench:!1}};if(typeof window>"u"||!window.localStorage)return t;try{const r=JSON.parse(window.localStorage.getItem(_m)||"{}"),n=r&&typeof r=="object"?r:{};return{expanded:{thread:!!(n.expanded&&n.expanded.thread),workbench:!!(n.expanded&&n.expanded.workbench)},balanced:{thread:!!(n.balanced&&n.balanced.thread),workbench:!!(n.balanced&&n.balanced.workbench)},focused:{thread:!!(n.focused&&n.focused.thread),workbench:!!(n.focused&&n.focused.workbench)}}}catch{return t}}function fp(){if(typeof window>"u"||!window.localStorage)return vn;try{const t=JSON.parse(window.localStorage.getItem(wS)||"[]");return!Array.isArray(t)||!t.length?vn:t}catch{return vn}}function SS(){return typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem(Ml)==="1"}const bp={hud:{thread:st,workbench:at},compact:{thread:252,workbench:252},balanced:{thread:jn,workbench:kn},wide:{thread:340,workbench:340}},CS={minimal:"hud",hud:"hud",writing:"compact",operator:"wide",coding:"wide"},_S=3500,AS=50;function za(t){return!t||typeof t!="object"?"":String(t.content??"")}function ES(t){if(!t||typeof t!="object")return!1;const r=String(t.role||"").toLowerCase();return r==="kernel"||r==="assistant"}function Am(t,r,n){const a=(Array.isArray(t)?t.slice(Math.max(0,r)):[]).filter(ES);return a.length?/^\/help\b/i.test(String(n||"").trim())?[...a].reverse().find(c=>{const u=za(c);return u.includes(Ap)||u.includes("ProofForge Operator Guide")})||null:/^\/(omega|kernel)\b/i.test(String(n||"").trim())&&[...a].reverse().find(c=>za(c).includes(fS))||a[a.length-1]:null}async function IS(t,r,n){const s=Date.now()+_S;for(;Date.now()<=s;){const a=Am(t(),r,n);if(a)return za(a);await new Promise(o=>{setTimeout(o,AS)})}return""}function PS(){k0();const t=RN(),{isPanelChromeVisible:r}=Wp(),n=Xt(k=>k.visualStyle),[s,a]=i.useState(!1),{model:o,setModel:l,workflowId:c,xpState:u,sessions:x,chatLog:p,appendChat:d,setChatLog:m,createSession:f,unlockSession:b,selectSession:h,lockSession:g,saveActiveSession:y,isSessionUnlocked:P,sessionHydrationStatus:A,sessionError:C,saveStatus:w,autoLockOnBlur:j,setAutoLockOnBlur:E,stats:N,showPalette:_,togglePalette:S,closePalette:R,showSettings:$,openPalette:U,openSettings:I,closeSettings:D}=$l(),z=i.useCallback(()=>{Lt(!1),I()},[I]);i.useEffect(()=>{typeof document>"u"||(document.documentElement.dataset.visualStyle=String(n||"operator"))},[n]);const F=String(n||"")==="frutiger-aero",J=i.useCallback(async k=>{const v=String(k||"").trim();if(!v)return;await l(v),ne(q=>({...q,model:v}));const T=yn.getState();yn.getState().setConnectionInfo({provider:T.provider,baseUrl:T.baseUrl,model:v,allowRemoteBridge:T.allowRemoteBridge,health:T.health,reason:T.reason}),await Dv(v),await Te().catch(()=>{})},[l]),ee=i.useCallback(()=>{$v(),br(!0)},[]),ie=i.useRef(p);i.useEffect(()=>{ie.current=p},[p]);const[ye,pe]=i.useState(""),[K,H]=i.useState({open:!1,mode:"create",targetSession:""}),[W,Z]=i.useState("PREVIEW"),[ce,fe]=i.useState({tierId:"free",tierLabel:"Audit-Only",capabilities:[]}),me=i.useCallback(async()=>{if(String(W||"").toUpperCase()==="OPERATOR"){ge("Operator license already active.","success");return}const k=window.prompt("Enter ProofForge Operator License (ns_op_...):");if(!k)return;const v=String(k).trim();if(!(v.startsWith("ns_op_")||v==="founder"||v==="test")){ge("Invalid license format.","error");return}if(!(window.api&&window.api.settings&&typeof window.api.settings.update=="function")){ge("Settings bridge unavailable.","error");return}await window.api.settings.update({tier:"OPERATOR"}),Z("OPERATOR"),fe(T=>({...T,tierId:"pro",tierLabel:"Operator"})),ge("License accepted. Welcome, Operator.","success")},[W]),[ke,Pe]=i.useState(!1),[_e,ne]=i.useState({provider:"ollama",baseUrl:"",model:"llama3",allowRemoteBridge:!1,health:"unknown",reason:""}),[we,Be]=i.useState(!1),[re,ae]=i.useState({rgbEnabled:!1,personalityProfile:"balanced"}),[M,V]=i.useState(null),[G,te]=i.useState({enabled:!1,backend:"cpu",device:""}),[de,L]=i.useState(!1),[be,Q]=i.useState(!1),[We,B]=i.useState(!1),[oe,xe]=i.useState(!1),[Re,De]=i.useState(!1),[tt,Ge]=i.useState(!1),[An,Dt]=i.useState(!1),[En,er]=i.useState(!1),[Dr,Ct]=i.useState(!1),[In,mt]=i.useState(!1),[$t,_t]=i.useState(!1),[Ae,tr]=i.useState(!1),[ro,$r]=i.useState(!1),[no,mr]=i.useState(!1),[so,Lr]=i.useState(!1),[ao,xr]=i.useState(!1),[oo,Br]=i.useState(!1),[io,Fr]=i.useState(!1),[lo,Ur]=i.useState(!1),[co,fr]=i.useState(!1),[uo,zr]=i.useState(!1),[po,Hr]=i.useState(!1),[mo,br]=i.useState(!1),[xo,Wr]=i.useState(!1),[fo,Kr]=i.useState(!1),[bo,Vr]=i.useState(!1),[ho,hr]=i.useState(!1),[go,Gr]=i.useState(!1),[yo,Jr]=i.useState(!1),[wo,qr]=i.useState(!1),[vo,Yr]=i.useState(!1),[jo,Zr]=i.useState(!1),[ko,Xr]=i.useState(!1),[No,Qr]=i.useState(!1),[So,en]=i.useState(!1),[Co,Pn]=i.useState(!1),[_o,Rn]=i.useState(!1),[Ao,On]=i.useState(!1),[Eo,Tn]=i.useState(!1),[Io,Mn]=i.useState(!1),[Po,Dn]=i.useState(!1),[Ro,$n]=i.useState(!1),[Oo,Ln]=i.useState(!1),[To,Bn]=i.useState(!1),[Mo,Fn]=i.useState(!1),[Do,Un]=i.useState(!1),[$o,zn]=i.useState(!1),[Lo,Hn]=i.useState(!1),[Bo,Wn]=i.useState(!1),[Fo,Kn]=i.useState(!1),[Uo,Vn]=i.useState(!1),[Gn,Im]=i.useState(()=>typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem(lp)==="1"),[Ls,Pm]=i.useState(()=>typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem(cp)==="1"),[Bs,Rm]=i.useState(()=>typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem(dp)==="1"),[gt,Om]=i.useState(()=>{if(typeof window>"u"||!window.localStorage)return"operator";const k=String(window.localStorage.getItem(cl)||"operator").trim().toLowerCase();return k==="founder"||k==="operator"||k==="support"||k==="security"||k==="sales"?k:"operator"}),[Jn,Fs]=i.useState(()=>{if(typeof window>"u"||!window.localStorage)return[];try{const k=JSON.parse(window.localStorage.getItem(up)||"[]");return Array.isArray(k)?k:[]}catch{return[]}}),[Us,cc]=i.useState(()=>{if(typeof window>"u"||!window.localStorage)return[];try{const k=JSON.parse(window.localStorage.getItem(pp)||"[]");return Array.isArray(k)?k:[]}catch{return[]}}),[Oe,Tm]=i.useState(()=>SS()),tn=i.useMemo(()=>Yv(gt),[gt]),[zo,qn]=i.useState(!1),[Ho,rr]=i.useState(!1),[Wo,rn]=i.useState(!1),[Ko,zs]=i.useState(!1),[gr,Lt]=i.useState(()=>typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem("neuralshell_first_boot_completed_v1")!=="1"),[Mm,Dm]=i.useState(()=>typeof window>"u"||!window.localStorage?!0:window.localStorage.getItem("neuralshell_spine_dismissed_v1")!=="1"),[$m,Lm]=i.useState(!1),[Vo,Yn]=i.useState(!1),[Go,Zn]=i.useState(!1),[Jo,qo]=i.useState("ops"),[Yo,yt]=i.useState(!1),[nn,Bm]=i.useState(()=>typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem(sp)==="1"||window.localStorage.getItem("neuralshell_readiness_checklist_v1")==="1"),[sn,Fm]=i.useState(()=>typeof window>"u"||!window.sessionStorage?!1:window.sessionStorage.getItem(ap)==="1"),[ot,Um]=i.useState({}),Hs=i.useMemo(()=>({internalGtmMode:Oe,devUnlock:!!(ot!=null&&ot.devUnlock)}),[Oe,ot==null?void 0:ot.devUnlock]),Bt=i.useMemo(()=>ru(Me.PILOT,Hs),[Hs]),Ce=i.useMemo(()=>ru(Me.INTERNAL,Hs),[Hs]),At=i.useCallback(k=>Bt&&typeof k=="function"?k:void 0,[Bt]),Ee=i.useCallback(k=>Ce&&typeof k=="function"?k:void 0,[Ce]),dc=i.useRef("unknown"),[LS,BS]=i.useState({status:"unknown"}),[Xn,uc]=i.useState([]),[Zo,zm]=i.useState(()=>[{view:"home",ts:Date.now()}]),[nr,Xo]=i.useState(0),Hm=nr>0,Wm=nr{zm(v=>[...v.slice(0,nr+1),{view:k,ts:Date.now()}].slice(-60)),Xo(v=>v+1)},[nr]);const Qn=i.useCallback(()=>{nr>0&&Xo(k=>k-1)},[nr]),es=i.useCallback(()=>{nrk+1)},[nr,Zo.length]),xt=i.useCallback((k="ops")=>{qo(k||"ops"),Zn(!0)},[]),Qo=i.useCallback(()=>{sr(!0)},[]),pc=i.useCallback(()=>{rn(!0)},[]),ei=i.useCallback(()=>{zs(!0)},[]),mc=i.useCallback(()=>{xt("actions")},[xt]),xc=i.useCallback(()=>{const k=th(et(c));if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){navigator.clipboard.writeText(k).then(()=>{ge("Workpad markdown copied","success")}).catch(()=>ge("Export failed","error"));return}ge("Clipboard unavailable","warning")},[c]),fc=i.useCallback(async()=>{if(window.api&&window.api.system&&typeof window.api.system.runHealthCheck=="function")try{const k=await window.api.system.runHealthCheck(),v=!!(k&&k.ok);ge(v?"Health check passed":"Health check found issues",v?"success":"warning")}catch(k){ge(k&&k.message?k.message:"Health check failed","error")}},[]);i.useEffect(()=>{Rv({openOperatorInbox:()=>xt("ops"),openWorkpad:Qo,openCalendar:pc,openGuidedActions:mc,openTrustReport:ei,runHealthCheck:fc,exportWorkpad:xc})},[xc,mc,pc,xt,ei,Qo,fc]);const[ti,sr]=i.useState(()=>typeof window<"u"&&(window.location.pathname==="/scratchpad"||window.location.hash==="#/scratchpad")),[Xe,Km]=i.useState(()=>typeof window<"u"&&Number.isFinite(window.innerWidth)?window.innerWidth:op),[ar,ts]=i.useState(!1),[Ft,rs]=i.useState(!1),[Ye,Ws]=i.useState(()=>kS()),[rt,Vm]=i.useState(()=>NS()),[ri,Gm]=i.useState(()=>typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem(ip)!=="1"),[FS,Jm]=i.useState(""),[ni,bc]=i.useState(xp()),[Ks,si]=i.useState(""),[hc,yr]=i.useState(""),[qm,gc]=i.useState(!1),[Ym,yc]=i.useState(!1),[wc,Zm]=i.useState({outputPath:"",sha256:""}),[or,vc]=i.useState(()=>typeof window>"u"||!window.localStorage?!1:!(window.localStorage.getItem(ll)==="1")&&jS()<4),ai=i.useRef(null),oi=i.useRef(null),jc=i.useRef(null),kc=i.useRef(null),ii=i.useRef(null),Nc=i.useId(),Sc=i.useId(),Cc=i.useRef(0),li=i.useRef(new Map),ci=i.useRef(new Map),wr=i.useRef(null),_c=i.useRef(null),Vs=i.useRef(""),Gs=i.useRef(null),Ac=i.useRef(""),Ec=i.useRef(""),Ze=String(W||"").toUpperCase()==="AUDITOR",Ic=Array.isArray(ce.capabilities)?ce.capabilities:[],di=Ic.includes("onboarding_wizard")||String(ce.tierId||"")==="enterprise",Xm=Ic.includes("issue_assist"),Qm=i.useMemo(()=>{const v=(Array.isArray(p)?p:[]).reduce((T,q)=>{const Y=String(q&&q.content?q.content:"");return T+Math.ceil(Y.length/4)},0);return Math.max(0,128e3-v)},[p]),wt=JN(String(c||"default")),ns=i.useMemo(()=>Object.keys(wt.remoteCursors||{}).length,[wt.remoteCursors]),{runtimeState:Se,refreshRuntimeState:ft}=XN({connectionInfo:_e,workflowId:String(c||""),runtimeTier:String(W||""),sessionHydrationStatus:String(A||""),collabConnected:!!wt.connected,collabRoomId:String(wt.roomId||"default"),collabPeerCount:ns}),{report:Js,loading:Pc,error:Rc,refresh:ui}=nS({enabled:!0,intervalMs:12e3}),{events:an}=QN(),ex=tS(),vt=iS(),{steps:Oc,progress:Tc,open:Et,busyStepId:tx,allDone:vr,completeStep:Mc,markSkipped:Dc,runStep:$c,dismiss:ss,reopen:Ut,reset:rx}=ex;i.useEffect(()=>{if(Et||or)return;const k=window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("neuralshell:focus-composer"))},500);return()=>window.clearTimeout(k)},[Et,or,c]),i.useCallback(({trustState:k}={})=>{if(String(k||"").toUpperCase()==="MISSING_SECRET"){z(),window.setTimeout(()=>{const T=document.getElementById("section-connection");T&&typeof T.scrollIntoView=="function"&&T.scrollIntoView({behavior:"smooth",block:"start"})},180);return}Ut()},[z,Ut]);const zt=i.useMemo(()=>(Array.isArray(Xn)?Xn:[]).filter(k=>!k.acknowledged),[Xn]),as=i.useMemo(()=>zt.length?zt.some(k=>String(k.severity||"")==="critical")?"fatal":zt.some(k=>String(k.severity||"")==="degraded"||String(k.severity||"")==="warning")?"degraded":"running":String(Se&&Se.watchdog&&Se.watchdog.status||"running"),[Se,zt]),nx=i.useMemo(()=>{const k=[...Array.isArray(p)?p:[]].reverse().find(v=>Array.isArray(v&&v.stdoutLines)&&v.stdoutLines.length);return k?k.stdoutLines.slice(-120).join(` -`):""},[p]),Lc=i.useRef(ns),Ue=i.useMemo(()=>Xe>=gS?"expanded":Xe>=yS?"balanced":"focused",[Xe]),on=Ue!=="focused",os=Ue==="expanded",qs=Ue==="focused",Ys=Ue!=="expanded",pi=rt[Ue]||dl[Ue]||dl.expanded,is=on&&!!pi.thread,Zs=os&&!!pi.workbench,Bc=r("thread-rail",!0),mi=r("workbench-rail",!0),ln=on&&!is&&Bc,Xs=os&&!Zs&&mi,xi=Ue==="expanded",Fc=xi&&!!pi.workbench,Uc=xi&&!Fc&&mi,sx=ri&&ln,ax=i.useMemo(()=>{const k=Object.entries(bp).find(([,v])=>{const T=ze(v.thread,st,Ot),q=ze(v.workbench,at,Tt);return T===Ye.thread&&q===Ye.workbench});return k?k[0]:""},[Ye.thread,Ye.workbench]),Qs=i.useMemo(()=>{const k=Math.floor(Xe*(Ue==="expanded"?.34:.42));return ze(k,st,Ot)},[Ue,Xe]),ea=i.useMemo(()=>{const k=Math.floor(Xe*.34);return ze(k,at,Tt)},[Xe]),fi=i.useMemo(()=>ze(Ye.thread,st,Math.min(Ot,Xe-Ca)),[Ye.thread,Xe]),bi=i.useMemo(()=>ze(Ye.workbench,at,Math.min(Tt,Xe-Ca)),[Ye.workbench,Xe]),hi=i.useMemo(()=>ze(Ye.thread,st,Qs),[Qs,Ye.thread]),gi=i.useMemo(()=>ze(Ye.workbench,at,ea),[ea,Ye.workbench]);i.useEffect(()=>{const k=()=>{const v=Number.isFinite(window.innerWidth)?window.innerWidth:op;Km(v)};return k(),window.addEventListener("resize",k),()=>window.removeEventListener("resize",k)},[]),i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(lp,Gn?"1":"0")},[Gn]),i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(cp,Ls?"1":"0")},[Ls]),i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(dp,Bs?"1":"0")},[Bs]),i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(Ml,Oe?"1":"0")},[Oe]),i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(cl,String(gt||"operator"))},[gt]),i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(up,JSON.stringify(Array.isArray(Jn)?Jn:[]))},[Jn]),i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(pp,JSON.stringify(Array.isArray(Us)?Us:[]))},[Us]),i.useEffect(()=>{Ue!=="focused"&&ar&&ts(!1),Ue==="expanded"&&Ft&&rs(!1)},[Ue,ar,Ft]),i.useEffect(()=>{if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(Cm,JSON.stringify({thread:ze(Ye.thread,st,Ot),workbench:ze(Ye.workbench,at,Tt)}))}catch{}},[Ye.thread,Ye.workbench]),i.useEffect(()=>{if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(_m,JSON.stringify({expanded:{thread:!!(rt.expanded&&rt.expanded.thread),workbench:!!(rt.expanded&&rt.expanded.workbench)},balanced:{thread:!!(rt.balanced&&rt.balanced.thread),workbench:!!(rt.balanced&&rt.balanced.workbench)},focused:{thread:!!(rt.focused&&rt.focused.thread),workbench:!!(rt.focused&&rt.focused.workbench)}}))}catch{}},[rt]);const nt=i.useCallback(()=>(Cc.current+=1,`msg-${Date.now()}-${Cc.current}`),[]),zc=i.useCallback((k,v={})=>{const T=nt();return d({id:T,role:"kernel",content:String(k||""),...v}),T},[d,nt]),ta=i.useCallback((k,v)=>{const T=String(k||"").trim();if(!T)return;const q=v&&typeof v=="object"?v:{};m(Y=>Array.isArray(Y)?Y.map(ue=>{if(String(ue&&ue.id?ue.id:"")!==T)return ue;const se=Array.isArray(ue.stdoutLines)?[...ue.stdoutLines]:[],le=String(q.line||"").trim();return le&&se.push(le),{...ue,stdoutLines:se.slice(-240),stdoutDone:!!q.done||!!ue.stdoutDone}}):Y)},[m]),Hc=i.useCallback(async(k,v)=>{if(window.api&&window.api.proof&&typeof window.api.proof.exec=="function")try{const T=await window.api.proof.exec({command:k}),q=String(T&&T.sessionId?T.sessionId:"").trim();if(!q)return;li.current.set(q,String(v||"").trim()),ci.current.set(q,{command:String(k||"").trim().toLowerCase(),messageId:String(v||"").trim()})}catch(T){ta(v,{line:`[${k}] stream failed: ${T&&T.message?T.message:String(T)}`,done:!0})}},[ta]),Te=i.useCallback(async()=>{var v,T,q,Y,ue,se;let k=!1;try{const[le,$e,ve]=await Promise.all([(T=(v=window.api)==null?void 0:v.settings)!=null&&T.get?window.api.settings.get():Promise.resolve({}),(Y=(q=window.api)==null?void 0:q.state)!=null&&Y.get?window.api.state.get():Promise.resolve({}),(se=(ue=window.api)==null?void 0:ue.llm)!=null&&se.health?window.api.llm.health().catch(()=>null):Promise.resolve(null)]);k=!0,Z(String(le&&le.tier||"PREVIEW").toUpperCase()),fe({tierId:String(le&&le.tierId||"free"),tierLabel:String(le&&le.tierLabel||"Audit-Only"),capabilities:Array.isArray(le&&le.capabilities)?le.capabilities:[]});const jt=Array.isArray(le&&le.connectionProfiles)?le.connectionProfiles:[],Je=jt.find(Nr=>String(Nr&&Nr.id||"")===String(le&&le.activeProfileId||""))||jt[0]||null,Ne=String(le&&le.provider||Je&&Je.provider||ve&&ve.provider||"ollama");ne({provider:Ne,baseUrl:String(le&&le.ollamaBaseUrl||Ne!=="ollama"&&Je&&Je.baseUrl||Ne!=="ollama"&&ve&&ve.baseUrl||""),model:String($e&&$e.model||ve&&ve.model||o||"llama3"),allowRemoteBridge:!!(le&&le.allowRemoteBridge),health:ve&&ve.ok?"online":ve?"offline":"unknown",reason:ve&&!ve.ok?String(ve.reason||"Bridge unavailable"):""}),Um(le&&typeof le=="object"?le:{});const It=ve&&ve.ok?"online":ve?"offline":"unknown";String(dc.current||"unknown")==="online"&&It==="offline"&&ge("Bridge went offline — check Settings or Task Manager","error"),dc.current=It,yn.getState().setConnectionInfo({provider:String(le&&le.provider||Je&&Je.provider||ve&&ve.provider||"ollama"),baseUrl:String(le&&le.ollamaBaseUrl||Je&&Je.baseUrl||ve&&ve.baseUrl||""),model:String($e&&$e.model||ve&&ve.model||o||"llama3"),allowRemoteBridge:!!(le&&le.allowRemoteBridge),health:ve&&ve.ok?"online":ve?"offline":"unknown",reason:ve&&!ve.ok?String(ve.reason||"Bridge unavailable"):""}),ae({rgbEnabled:!!(le&&le.rgbEnabled),personalityProfile:String(le&&le.personalityProfile||"balanced")})}catch{}finally{k&&Pe(!0)}},[o]);i.useEffect(()=>{Te()},[Te]),i.useEffect(()=>{!(ot!=null&&ot.devUnlock)||typeof window>"u"||!window.localStorage||(window.localStorage.setItem(Ml,"1"),window.localStorage.setItem(cl,"founder"),Tm(!0))},[ot==null?void 0:ot.devUnlock]);const ox=i.useCallback(async()=>{var k,v,T,q,Y,ue;if(!((v=(k=window.api)==null?void 0:k.bridge)!=null&&v.test&&((q=(T=window.api)==null?void 0:T.settings)!=null&&q.get))){ge("Bridge verify unavailable","warning");return}try{const se=await window.api.settings.get(),le=Array.isArray(se==null?void 0:se.connectionProfiles)?se.connectionProfiles:[],$e=String((se==null?void 0:se.activeProfileId)||"").trim(),ve=le.find(Ne=>String((Ne==null?void 0:Ne.id)||"")===$e)||le[0]||null;if(!ve){ge("No connection profile configured","warning");return}const jt=await window.api.bridge.test({provider:String(ve.provider||se.provider||"ollama"),baseUrl:String(ve.baseUrl||se.ollamaBaseUrl||""),defaultModel:String(ve.defaultModel||se.defaultModel||"llama3"),allowRemoteBridge:!!se.allowRemoteBridge,apiKey:se.apiKey,apiKeyPresent:se.apiKeyPresent});await Te();const Je=!!(jt&&jt.ok);ge(Je?`Bridge online (${Number(jt.modelCount)||0} models)`:"Bridge offline — start Ollama or check Settings",Je?"success":"warning"),(ue=(Y=window.api)==null?void 0:Y.state)!=null&&ue.logProfileEvent&&ve.id&&await window.api.state.logProfileEvent(String(ve.id),"verification_requested",Je?"Manual verification succeeded from profile bar.":"Manual verification failed from profile bar.")}catch(se){await Te().catch(()=>{}),ge(ml(se==null?void 0:se.message)||"Verification failed","error")}},[Te]),[Wc,Kc]=i.useState(!1),ls=!!(typeof window<"u"&&window.api&&window.api.support&&typeof window.api.support.exportBundle=="function"),yi=i.useCallback(async()=>{if(ls){Kc(!0);try{const k=await window.api.support.exportBundle({includeUserText:!1,workpadSnapshots:yl(),timeProof:Cl({workflowId:c})});k&&k.ok?(ge(`Evidence exported: ${k.outputPath}`,"success"),window.dispatchEvent(new window.CustomEvent("neuralshell:support-bundle-exported",{detail:{outputPath:String(k.outputPath||""),sha256:String(k.sha256||"")}}))):ge("Evidence export failed","error")}catch(k){ge(k&&k.message?k.message:"Evidence export failed","error")}finally{Kc(!1)}}},[ls]),Vc=i.useMemo(()=>Hl({connectionInfo:_e,watchdogStatus:as,incidentCount:zt.length,setupBlocked:!!(Et&&!vr)}),[_e,as,zt.length,Et,vr]),Gc=i.useMemo(()=>Wl(Vc,{sessionDegradedDismissed:sn,acknowledgedReady:nn}),[Vc,sn,nn]),ix=i.useCallback(()=>{typeof window<"u"&&window.localStorage&&(window.localStorage.setItem(sp,"1"),window.localStorage.setItem("neuralshell_readiness_checklist_v1","1")),Bm(!0),yt(!1),window.dispatchEvent(new window.CustomEvent("neuralshell:focus-composer")),ge("Ready — composer focused","success")},[]),lx=i.useCallback(()=>{typeof window<"u"&&window.sessionStorage&&window.sessionStorage.setItem(ap,"1"),Fm(!0),yt(!1)},[]),cn=Uy({isThinking:we,isTyping:!!String(ye||"").trim(),connectionHealth:_e==null?void 0:_e.health});ON({enabled:re.rgbEnabled,moodEngine:cn,personalityProfile:re.personalityProfile}),i.useEffect(()=>{if(!re.rgbEnabled){V(null);return}let k=!0;const v=async()=>{if(window.api&&window.api.rgb&&typeof window.api.rgb.status=="function")try{const q=await window.api.rgb.status();k&&V(q&&typeof q=="object"?q:null)}catch{k&&V(null)}};v();const T=window.setInterval(v,5e3);return()=>{k=!1,window.clearInterval(T)}},[re.rgbEnabled,cn==null?void 0:cn.rgbMood]);const Jc=i.useRef($);i.useEffect(()=>{const k=Jc.current,v=$;(v&&!k||!v&&k)&&Te(),Jc.current=v},[$,Te]),i.useEffect(()=>{let k=!0;const v=async()=>{try{if(!(window.api&&window.api.accel&&typeof window.api.accel.status=="function"))return;const q=await window.api.accel.status();if(!k)return;te(q&&typeof q=="object"?{enabled:!!q.enabled,backend:String(q.backend||"cpu"),device:String(q.device||"")}:{enabled:!1,backend:"cpu",device:""})}catch{}};v();const T=window.setInterval(v,2e4);return()=>{k=!1,window.clearInterval(T)}},[]),i.useEffect(()=>{const k=window.setInterval(()=>{Te()},12e3);return()=>{window.clearInterval(k)}},[Te]),i.useEffect(()=>{const k=()=>{Te()};return window.addEventListener("neuralshell:settings-updated",k),()=>window.removeEventListener("neuralshell:settings-updated",k)},[Te]),i.useEffect(()=>{ke&&(di||or&&vc(!1))},[di,ke,or]),i.useEffect(()=>{if(window.api&&window.api.proof&&typeof window.api.proof.onStdout=="function")return window.api.proof.onStdout(k=>{const v=k&&typeof k=="object"?k:{},T=String(v.sessionId||"").trim();if(!T)return;const q=li.current.get(T),Y=ci.current.get(T);q&&(ta(q,{line:String(v.line||""),done:!!v.done}),v.done&&(li.current.delete(T),ci.current.delete(T),Y&&String(Y.command||"")==="proof"&&(X("proof.passed",{messageId:String(Y.messageId||""),sessionId:T},{source:"proof",severity:"info"}),typeof window<"u"&&window.localStorage&&(window.localStorage.setItem("neuralshell_proof_last_status_v1","passed"),window.localStorage.setItem("neuralshell_proof_stage_v1","complete")))))})},[ta]),i.useEffect(()=>{const k=v=>{const T=v&&v.detail&&typeof v.detail=="object"?v.detail:{};Zm({outputPath:String(T.outputPath||""),sha256:String(T.sha256||"")})};return window.addEventListener("neuralshell:support-bundle-exported",k),()=>{window.removeEventListener("neuralshell:support-bundle-exported",k)}},[]),i.useEffect(()=>{const k=()=>Lm(!0);return window.addEventListener("neuralshell:support-bundle-exported",k),()=>{window.removeEventListener("neuralshell:support-bundle-exported",k)}},[]);const cx=i.useCallback(()=>{Dm(!1),typeof window<"u"&&window.localStorage&&window.localStorage.setItem("neuralshell_spine_dismissed_v1","1")},[]);i.useEffect(()=>{!ke||!Et||typeof window>"u"||!window.localStorage||window.localStorage.getItem(ll)==="1"&&ss()},[ss,Et,ke]),i.useEffect(()=>{if(ke){if(gr||Et||or){yt(!1);return}if(nn&&sn){yt(!1);return}if(!Gc.shouldPrompt){yt(!1);return}yt(!0)}},[Et,vr,nn,Gc.shouldPrompt,ke,sn,gr,or]),i.useEffect(()=>{const k=v=>{const T=v&&v.detail?String(v.detail):"LLM stream failed";ge(T,"error")};return window.addEventListener("llm-stream-error",k),()=>window.removeEventListener("llm-stream-error",k)},[]),i.useEffect(()=>{const k=Number(Lc.current||0),v=Number(ns||0);v>k?X("collab.peer.joined",{roomId:String(wt.roomId||"default"),peerCount:v},{source:"collab",severity:"info"}):v{if(!(Se&&Se.updateLane))return;const k=String(Se.updateLane.signatureState||"").toLowerCase();k!==Ac.current&&(Ac.current=k,!(k==="verified"||k==="unknown")&&X("update.verification.failed",{signatureState:k,stagedUpdateAvailable:!!Se.updateLane.stagedUpdateAvailable},{source:"update-lane",severity:"critical"}))},[Se]),i.useEffect(()=>{const k=Array.isArray(an)&&an.length?an[an.length-1]:null;!k||!k.id||String(Ec.current||"")!==String(k.id)&&(Ec.current=String(k.id),Fs(v=>(Array.isArray(v)?v:[]).map(q=>{if(String(q&&q.status?q.status:"")!=="open")return q;const Y=Array.isArray(q.timeline)?q.timeline:[];return{...q,timeline:[...Y,{at:String(k.at||new Date().toISOString()),type:String(k.type||"runtime.event"),source:String(k.source||"runtime"),detail:k.payload&&typeof k.payload=="object"?k.payload:{}}].slice(-400)}})))},[an]);const Ht=i.useCallback(k=>{const v=String(k||"").trim().toLowerCase();if(v==="mission"||v==="mission-control"){B(!0);return}if(v==="demo"||v==="demo-flow"||v==="demo_flow"){fr(!0);return}if(v==="fleet"||v==="fleet-control"){if(!tn.canManageFleet){X("role.access.denied",{panel:v,role:gt},{source:"roles",severity:"warning"});return}xe(!0);return}if(v==="recovery"||v==="recovery-center"){if(!tn.canRunRecovery){X("role.access.denied",{panel:v,role:gt},{source:"roles",severity:"warning"});return}De(!0);return}if(v==="appliance"||v==="appliance-console"){if(!tn.canManageAppliance){X("role.access.denied",{panel:v,role:gt},{source:"roles",severity:"warning"});return}Ge(!0);return}if(v==="airgap"||v==="air-gap"||v==="airgap-operations"){Dt(!0);return}if(v==="trust"||v==="trust-fabric"||v==="pki"){er(!0);return}if(v==="hardware"||v==="hardware-appliance"){Ct(!0);return}if(v==="courier"||v==="courier-transfer"){mt(!0);return}if(v==="continuity"||v==="continuity-drills"){_t(!0);return}if(v==="procurement"||v==="procurement-command"){tr(!0);return}if(v==="tamper"||v==="tamper-simulation"){$r(!0);return}if(v==="institutional"||v==="institutional-command"){mr(!0);return}if(v==="deployment"||v==="deployment-program"||v==="deployment_program"){zr(!0);return}if(v==="training"||v==="training-delivery"||v==="training_delivery"){Hr(!0);return}if(v==="support"||v==="support-ops"||v==="support_ops"){br(!0);return}if(v==="buyer"||v==="buyer-journey"||v==="buyer_journey"){Wr(!0);return}if(v==="pilot"||v==="pilot-conversion"||v==="pilot_conversion"){Kr(!0);return}if(v==="commercial"||v==="commercial-packages"||v==="commercial_packages"){Vr(!0);return}if(v==="launch"||v==="field-launch"||v==="field_launch"){hr(!0);return}if(v==="partner"||v==="partner-rollout"||v==="partner_rollout"){Gr(!0);return}if(v==="buyerops"||v==="buyer-ops"||v==="buyer_ops"){Jr(!0);return}if(v==="demotopilot"||v==="demo-to-pilot"||v==="demo_to_pilot"){qr(!0);return}if(v==="expansion"||v==="pilot-expansion"||v==="pilot_expansion"){Yr(!0);return}if(v==="renewal"||v==="renewal-risk"||v==="renewal_risk"){Zr(!0);return}if(v==="launchweek"||v==="launch-week"||v==="launch_week"){Xr(!0);return}if(v==="followup"||v==="followup-generator"||v==="followup_generator"){Qr(!0);return}if(v==="feedback"||v==="field-feedback"||v==="field_feedback"){en(!0);return}if(v==="partner-certification"||v==="partner_certification"){Pn(!0);return}if(v==="managed-services"||v==="managed_services"){Rn(!0);return}if(v==="strategic-account"||v==="strategic_account"){On(!0);return}if(v==="portfolio-rollout"||v==="portfolio_rollout"){Tn(!0);return}if(v==="revenue-ops"||v==="revenue_ops"){Mn(!0);return}if(v==="channel-expansion"||v==="channel_expansion"){Dn(!0);return}if(v==="cross-account-renewal"||v==="cross_account_renewal"){$n(!0);return}if(v==="executive-scale"||v==="executive_scale"){Ln(!0);return}if(v==="ecosystem-portfolio"||v==="ecosystem_portfolio"){Bn(!0);return}if(v==="service-line"||v==="service_line"){Fn(!0);return}if(v==="partner-network-governance"||v==="partner_network_governance"){Un(!0);return}if(v==="global-planning"||v==="global_planning"){zn(!0);return}if(v==="ecosystem-revenue"||v==="ecosystem_revenue"){Hn(!0);return}if(v==="board-operating-pack"||v==="board_operating_pack"){Wn(!0);return}if(v==="licensed-operator"||v==="licensed_operator"){Kn(!0);return}if(v==="ecosystem-command"||v==="ecosystem_command"){Vn(!0);return}if(v==="shift"||v==="shift-console"){Lr(!0);return}if(v==="incident"||v==="incident-mode"){if(!tn.canDeclareIncidents){X("role.access.denied",{panel:v,role:gt},{source:"roles",severity:"warning"});return}xr(!0);return}if(v==="policy-rollout"||v==="rollout"){if(!tn.canRunPolicyRollouts){X("role.access.denied",{panel:v,role:gt},{source:"roles",severity:"warning"});return}Br(!0);return}if(v==="update-packs"||v==="offline-updates"){Fr(!0);return}if(v==="missions"||v==="mission-scheduler"){Ur(!0);return}if(v==="watchdog"){rr(!0);return}if(v==="nodechain"){qn(!0);return}if(v==="firstboot"||v==="first-boot"){Ut(),Lt(!0);return}if(v==="split"||v==="split-workspace"){Yn(!0);return}if(v==="task-manager"||v==="tasks"||v==="inbox"||v==="operator-inbox"){xt("ops");return}v==="settings"&&I()},[gt,xt,I,Ut,tn]),wi=i.useCallback(async()=>{X("runtime.snapshot.requested",{source:"nodechain"},{source:"snapshots",severity:"info"})},[]),qc=i.useMemo(()=>({showAlert:async k=>{const v=k&&typeof k=="object"?k:{};X("runtime.watchdog.alert",v,{source:"nodechain",severity:String(v.severity||"warning").toLowerCase()})},openPanel:async k=>{const v=String(k&&k.panel?k.panel:"");Ht(v)},shareProofBadge:async()=>{window.api&&window.api.system&&typeof window.api.system.openExternal=="function"&&await window.api.system.openExternal("https://raw.githubusercontent.com/Z3r0DayZion-install/NeuralShell/main/assets/proof_badge.svg")},snapshotState:async()=>{await wi()},disableRelay:async()=>{if(!(window.api&&window.api.settings&&typeof window.api.settings.get=="function"))return;const k=await window.api.settings.get();await window.api.settings.update({...k||{},proofRelayEnabled:!1}),X("relay.failed",{reason:"NodeChain disabled relay path after failures."},{source:"relay",severity:"degraded"}),await Te(),await ft()},blockUpdateApply:async()=>{window.api&&window.api.autoUpdate&&typeof window.api.autoUpdate.setPolicy=="function"&&await window.api.autoUpdate.setPolicy({autoApply:!1,blockedBy:"nodechain"})},promptVaultSave:async()=>{window.dispatchEvent(new window.CustomEvent("neuralshell:prompt-vault-save"))},writeAuditLog:async k=>{window.api&&window.api.logger&&typeof window.api.logger.log=="function"&&await window.api.logger.log("info","nodechain-action",k||{})},switchSafePolicy:async()=>{if(!(window.api&&window.api.settings&&typeof window.api.settings.get=="function"))return;const k=await window.api.settings.get();await window.api.settings.update({...k||{},offlineOnlyEnforced:!0,allowRemoteBridge:!1,autoUpdateChannel:"frozen"}),await Te(),await ft()},runLocalScript:async k=>{if(!(window.api&&window.api.command&&typeof window.api.command.run=="function"))return;const v=String(k&&k.commandId?k.commandId:"").trim(),T=Array.isArray(k&&k.args)?k.args:[];await window.api.command.run(v,T)}}),[Ht,Te,ft,wi]);i.useEffect(()=>{const k=fp(),v=JSON.stringify(k||[]),T=new H0(k,qc,vS);_c.current=T,Vs.current=v,T.start();const q=K0(Y=>{const ue=fp(),se=JSON.stringify(ue||[]);se!==Vs.current&&(Vs.current=se,T.setRules(ue)),T.dispatch({type:String(Y&&Y.type?Y.type:""),at:String(Y&&Y.at?Y.at:new Date().toISOString()),payload:Y&&Y.payload&&typeof Y.payload=="object"?Y.payload:{}},!1).then(le=>{if(!Array.isArray(le)||!le.length)return;const $e=le.some(ve=>String(ve.status||"")==="failed");X("nodechain.rule.executed",{eventType:String(Y&&Y.type?Y.type:""),runs:le.length,failed:$e},{source:"nodechain",severity:$e?"warning":"info"})}).catch(()=>{})});return()=>{q(),T.stop(),_c.current=null,Vs.current=""}},[qc]),i.useEffect(()=>{Gs.current||(Gs.current=new mS({retryProviderProbe:async()=>{await Te(),await ft()},disableRelayPath:async()=>{if(!(window.api&&window.api.settings&&typeof window.api.settings.get=="function"))return;const v=await window.api.settings.get();await window.api.settings.update({...v||{},proofRelayEnabled:!1}),await Te(),await ft()},freezeUpdateLane:async()=>{window.api&&window.api.autoUpdate&&typeof window.api.autoUpdate.setPolicy=="function"&&await window.api.autoUpdate.setPolicy({autoApply:!1,frozenBy:"watchdog"})},switchSafePolicy:async()=>{if(!(window.api&&window.api.settings&&typeof window.api.settings.get=="function"))return;const v=await window.api.settings.get();await window.api.settings.update({...v||{},allowRemoteBridge:!1,offlineOnlyEnforced:!0,autoUpdateChannel:"frozen"}),await Te(),await ft()},onAlert:v=>{X("runtime.watchdog.alert",{source:v.source,message:v.message,suggestedAction:v.suggestedAction},{source:"watchdog",severity:v.severity})}}));const k=Gs.current;!k||!(Se&&Se.providerHealth)||k.evaluate({providerHealth:{online:!!Se.providerHealth.online,activeProvider:String(Se.providerHealth.activeProvider||"ollama"),model:String(Se.providerHealth.model||"llama3")},relayState:{enabled:!!(Se.relayState&&Se.relayState.enabled),relayError:String(Se.relayState&&Se.relayState.relayError?Se.relayState.relayError:"")},updateLane:{signatureState:String(Se.updateLane&&Se.updateLane.signatureState?Se.updateLane.signatureState:"unknown"),stagedUpdateAvailable:!!(Se.updateLane&&Se.updateLane.stagedUpdateAvailable)},vaultState:{locked:!!(Se.vaultState&&Se.vaultState.locked),exportImportStatus:String(Se.vaultState&&Se.vaultState.exportImportStatus?Se.vaultState.exportImportStatus:"idle")}}).then(v=>{uc(Array.isArray(v)?v:[])}).catch(()=>{})},[Te,ft,Se]),i.useEffect(()=>{const k=()=>{d({id:nt(),role:"kernel",content:"NodeChain prompted a vault save. Open Settings > Vault to seal the current runtime state."})};return window.addEventListener("neuralshell:prompt-vault-save",k),()=>{window.removeEventListener("neuralshell:prompt-vault-save",k)}},[d,nt]);const ra=i.useCallback(()=>{if(Ze){d({role:"kernel",content:"Audit-only mode is active. Session creation is disabled in this runtime."});return}H({open:!0,mode:"create",targetSession:""}),bc(xp()),si(""),yr("")},[d,Ze]),jr=i.useCallback(k=>{H({open:!0,mode:"unlock",targetSession:String(k||"")}),si(""),yr("")},[]),kr=i.useCallback(()=>{H({open:!1,mode:"create",targetSession:""}),yr("")},[]);i.useEffect(()=>{if(!K.open)return;const k=document.body.style.overflow;document.body.style.overflow="hidden",document.activeElement&&typeof document.activeElement.focus=="function"&&(ii.current=document.activeElement);const v=K.mode==="create"?ai.current:oi.current;v&&typeof v.focus=="function"&&v.focus();const T=q=>{if(q.key!=="Tab")return;const Y=[ai.current,oi.current,jc.current,kc.current].filter($e=>$e&&!$e.disabled);if(!Y.length)return;const ue=Y[0],se=Y[Y.length-1],le=document.activeElement;if(q.shiftKey){(le===ue||!Y.includes(le))&&(q.preventDefault(),se.focus());return}(le===se||!Y.includes(le))&&(q.preventDefault(),ue.focus())};return document.addEventListener("keydown",T),()=>{document.removeEventListener("keydown",T),document.body.style.overflow=k;const q=ii.current;q&&typeof q.focus=="function"&&q.focus(),ii.current=null}},[K.open,K.mode]),i.useEffect(()=>{const k=v=>{v.button===3&&(v.preventDefault(),Qn()),v.button===4&&(v.preventDefault(),es())};return window.addEventListener("mouseup",k),()=>window.removeEventListener("mouseup",k)},[Qn,es]),i.useEffect(()=>{const k=ue=>{const se=ue&&ue.detail?String(ue.detail):"system";Xt.getState().setTheme(se)},v=()=>{ra()},T=()=>{U()},q=()=>{I()},Y=()=>{xt("ops")};return window.addEventListener("tray:set-theme",k),window.addEventListener("tray:new-workflow",v),window.addEventListener("tray:open-palette",T),window.addEventListener("tray:open-settings",q),window.addEventListener("tray:open-task-manager",Y),()=>{window.removeEventListener("tray:set-theme",k),window.removeEventListener("tray:new-workflow",v),window.removeEventListener("tray:open-palette",T),window.removeEventListener("tray:open-settings",q),window.removeEventListener("tray:open-task-manager",Y)}},[ra,xt,U,I]),i.useEffect(()=>{const k=v=>{const T=document.activeElement,q=T&&T.tagName?String(T.tagName).toLowerCase():"",Y=!!(T&&(q==="input"||q==="textarea"||T.isContentEditable||T.dataset&&(T.dataset.testid==="chat-input"||T.dataset.testid==="slash-palette-input")));if(v.altKey&&v.key==="ArrowLeft"){v.preventDefault(),Qn();return}if(v.altKey&&v.key==="ArrowRight"){v.preventDefault(),es();return}if((v.ctrlKey||v.metaKey)&&v.key===","){v.preventDefault(),I();return}if((v.ctrlKey||v.metaKey)&&v.shiftKey&&(v.key==="t"||v.key==="T")){v.preventDefault(),Zn(se=>se?!1:(qo("ops"),!0));return}if((v.ctrlKey||v.metaKey)&&v.shiftKey&&(v.key==="n"||v.key==="N")){v.preventDefault(),sr(se=>!se);return}if((v.ctrlKey||v.metaKey)&&v.shiftKey&&(v.key==="c"||v.key==="C")){v.preventDefault(),rn(se=>!se);return}if((v.ctrlKey||v.metaKey)&&v.shiftKey&&(v.key==="a"||v.key==="A")){v.preventDefault(),Zn(se=>se&&Jo==="actions"?!1:(qo("actions"),!0));return}if((v.ctrlKey||v.metaKey)&&v.key==="k"){if(v.preventDefault(),_){S();return}if(Y)return;S()}if(v.altKey&&(v.code==="BracketLeft"||v.code==="BracketRight")&&!Y){const se=v.code==="BracketLeft"?-mp:mp,le=v.shiftKey?"workbench":"thread";(le==="workbench"?os||Ys:on||qs)&&(v.preventDefault(),Ws(ve=>{const jt=le==="workbench"?at:st,Je=le==="workbench"?Tt:Ot,Ne=Number.isFinite(Number(ve[le]))?Number(ve[le]):le==="workbench"?kn:jn,It=ze(Ne+se,jt,Je);return It===ve[le]?ve:{...ve,[le]:It}}))}v.key==="Escape"&&(R(),D(),be&&Q(!1),We&&B(!1),oe&&xe(!1),Re&&De(!1),tt&&Ge(!1),An&&Dt(!1),En&&er(!1),Dr&&Ct(!1),In&&mt(!1),$t&&_t(!1),Ae&&tr(!1),ro&&$r(!1),no&&mr(!1),co&&fr(!1),uo&&zr(!1),po&&Hr(!1),mo&&br(!1),xo&&Wr(!1),fo&&Kr(!1),bo&&Vr(!1),ho&&hr(!1),go&&Gr(!1),yo&&Jr(!1),wo&&qr(!1),vo&&Yr(!1),jo&&Zr(!1),ko&&Xr(!1),No&&Qr(!1),So&&en(!1),Co&&Pn(!1),_o&&Rn(!1),Ao&&On(!1),Eo&&Tn(!1),Io&&Mn(!1),Po&&Dn(!1),Ro&&$n(!1),Oo&&Ln(!1),To&&Bn(!1),Mo&&Fn(!1),Do&&Un(!1),$o&&zn(!1),Lo&&Hn(!1),Bo&&Wn(!1),Fo&&Kn(!1),Uo&&Vn(!1),so&&Lr(!1),ao&&xr(!1),oo&&Br(!1),io&&Fr(!1),lo&&Ur(!1),zo&&qn(!1),Ho&&rr(!1),Wo&&rn(!1),Ko&&zs(!1),gr&&Lt(!1),Vo&&Yn(!1),Go&&Zn(!1),ti&&sr(!1),Yo&&yt(!1),K.open&&kr(),ar&&ts(!1),Ft&&rs(!1))};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[S,R,D,I,Qn,es,be,We,oe,Re,tt,An,En,Dr,In,$t,Ae,ro,no,co,uo,po,mo,xo,fo,bo,ho,go,yo,wo,vo,jo,ko,No,So,Co,_o,Ao,Eo,Io,Po,Ro,Oo,To,Mo,Do,$o,Lo,Bo,Fo,Uo,so,ao,oo,io,lo,zo,Ho,Wo,Ko,Jo,gr,Vo,Go,ti,Yo,_,K.open,kr,on,os,qs,Ys,ar,Ft]);const Yc=i.useCallback(k=>{const v=String(k||"").trim();if(v){if(v===Cs||P(v)){h(v);return}jr(v)}},[P,jr,h]),dx=i.useCallback(async k=>{if(k.preventDefault(),yr(""),K.mode==="create"){if(Ze){yr("Audit-only mode is active. Session creation is disabled.");return}const T=await f({name:ni,passphrase:Ks});if(!T.ok){yr(T.error||"Failed to create session.");return}kr();return}const v=await b(K.targetSession,Ks);if(!v.ok){yr(v.error||"Failed to unlock session.");return}kr()},[K.mode,K.targetSession,ni,Ks,f,b,kr,Ze]),Zc=i.useCallback(async()=>{if(Ze){d({role:"kernel",content:"Audit-only mode is active. Session saving is disabled."});return}!(await y("manual")).ok&&c&&c!==Cs&&jr(c)},[y,c,jr,Ze,d]),Xc=i.useCallback(async()=>{if(Ze){d({role:"kernel",content:"Audit-only mode is active. Retry save is disabled."});return}!(await y("retry")).ok&&c&&c!==Cs&&jr(c)},[y,c,jr,Ze,d]),Qc=i.useCallback(()=>{if(Ze){d({role:"kernel",content:"Audit-only mode is active. Lock action is disabled."});return}!c||c===Cs||g(c)},[c,g,Ze,d]),Wt=async k=>{const v=k||ye;if(!v.trim())return;d({id:nt(),role:"user",content:v}),pe("");const T=v.trim().toLowerCase(),q=T.startsWith("/")?T.split(/\s+/)[0]:"";if(Ze){if(!T.startsWith("/")){Be(!1),d({role:"kernel",content:"Audit-only mode accepts proof/status commands only. Use /proof, /roi, /status, /guard, /help, /workflows, or /clear."});return}if(!xS.has(q)){Be(!1),d({role:"kernel",content:`Audit-only mode blocked command: ${q}`});return}}if(T.startsWith("/")){if(Be(!1),T==="/clear"||T==="/purge"||T==="/reset"){m([]);return}setTimeout(()=>{if(T==="/help")d({role:"kernel",content:Ep});else if(T==="/guard"||T==="/omega"||T==="/kernel")(async()=>{try{const Y=window.api&&window.api.omega&&typeof window.api.omega.status=="function"?await window.api.omega.status():null;Y&&await ui();const ue=T==="/guard"?Y&&Y.formatted&&Y.formatted.guard:Y&&Y.formatted&&Y.formatted.omega;d({role:"kernel",content:ue||"OMEGA kernel status is unavailable in this runtime."})}catch(Y){d({role:"kernel",content:`OMEGA probe failed: ${Y&&Y.message?Y.message:String(Y)}`})}})();else if(T==="/status")d({role:"kernel",content:`Node Status: OPERATIONAL +`)),d(y=>[{id:`proc-pack-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,generatedAt:h,organization:n,reviewOwner:a,currentVersion:c,previousVersion:u},...Array.isArray(y)?y:[]].slice(0,120)),f(`Generated procurement/security review pack for ${n}.`)};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[152] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"procurement-command-center",className:"fixed inset-x-8 top-16 bottom-6 z-[153] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Procurement Command Center"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Buyer-ready security review output generated from local runtime truth."})]}),e.jsx("button",{type:"button","data-testid":"procurement-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.9fr_1.1fr] gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Organization",e.jsx("input",{"data-testid":"procurement-organization-input",value:n,onChange:h=>s(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Review Owner",e.jsx("input",{"data-testid":"procurement-owner-input",value:a,onChange:h=>o(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Current Version",e.jsx("input",{"data-testid":"procurement-current-version-input",value:c,onChange:h=>l(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Previous Version",e.jsx("input",{"data-testid":"procurement-previous-version-input",value:u,onChange:h=>x(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("button",{type:"button","data-testid":"procurement-generate-btn",onClick:b,className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Generate Review Pack"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Pack Freshness"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Recent generation history and staleness indicator."})]}),e.jsxs("div",{className:"max-h-80 overflow-auto pr-1 space-y-1.5",children:[(Array.isArray(p)?p:[]).map(h=>{const g=qj(h.generatedAt);return e.jsxs("article",{className:`rounded border px-2 py-1.5 ${g<=7?"border-emerald-300/30 bg-emerald-500/10":g<=30?"border-amber-300/35 bg-amber-500/10":"border-rose-300/35 bg-rose-500/10"}`,children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:h.organization}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:[h.previousVersion," ➜ ",h.currentVersion," · ",new Date(h.generatedAt).toLocaleString()]})]},h.id)}),(Array.isArray(p)?p:[]).length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No review packs generated yet."})]})]})]}),m&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:m})]})]}):null}function Zj({scenario:t,onRun:r}){const n=t&&typeof t=="object"?t:{},s=String(n.severity||"warning");return e.jsxs("article",{className:`rounded border px-2 py-2 ${s==="critical"?"border-rose-300/35 bg-rose-500/10":s==="degraded"?"border-amber-300/35 bg-amber-500/10":"border-cyan-300/30 bg-cyan-500/10"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:n.title}),e.jsx("div",{className:"text-[9px] font-mono uppercase text-slate-300",children:s})]}),e.jsx("div",{className:"mt-1 text-[9px] font-mono text-slate-300",children:(Array.isArray(n.expectedResponse)?n.expectedResponse:[]).join(" · ")}),e.jsx("button",{type:"button","data-testid":`tamper-run-${n.scenarioId}`,onClick:()=>{typeof r=="function"&&r(n)},className:"mt-2 px-2 py-1 rounded border border-white/10 bg-black/20 text-[9px] font-mono text-slate-100",children:"Run Simulation"})]})}const Bu=[{scenarioId:"invalid_signature_injection",title:"Invalid Signature Injection",expectedResponse:["signature_validation_failed","quarantine_artifact","raise_incident_event"],severity:"critical"},{scenarioId:"tampered_evidence_envelope",title:"Tampered Evidence Envelope",expectedResponse:["hash_mismatch_detected","block_release","append_audit_event"],severity:"critical"},{scenarioId:"revoked_cert_presented",title:"Revoked Certificate Presented",expectedResponse:["trust_path_invalid","deny_operation","raise_trust_alert"],severity:"critical"},{scenarioId:"policy_bundle_mismatch",title:"Policy Bundle Mismatch",expectedResponse:["policy_diff_alert","rollback_gate","operator_confirmation_required"],severity:"warning"},{scenarioId:"relay_path_failure_burst",title:"Relay Path Failure Burst",expectedResponse:["switch_to_local_mode","degraded_alert","capture_watchdog_event"],severity:"degraded"},{scenarioId:"node_heartbeat_dropout",title:"Node Heartbeat Dropout",expectedResponse:["mark_node_degraded","incident_mode_suggestion","append_fleet_event"],severity:"degraded"},{scenarioId:"stale_update_pack_presented",title:"Stale Update Pack Presented",expectedResponse:["reject_update_pack","keep_quarantine","append_update_alert"],severity:"warning"},{scenarioId:"break_glass_misuse",title:"Break-Glass Misuse Simulation",expectedResponse:["deny_unapproved_override","require_dual_signoff","append_security_audit"],severity:"critical"}],Fu="neuralshell_tamper_simulation_reports_v1";function Xj(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function Qj(t,r){typeof window>"u"||!window.localStorage||window.localStorage.setItem(t,JSON.stringify(r))}function ek({open:t,onClose:r}){const[n,s]=i.useState(()=>{const l=Xj(Fu,[]);return Array.isArray(l)?l:[]}),[a,o]=i.useState("");i.useEffect(()=>{Qj(Fu,n)},[n]);const c=l=>{const u=l&&typeof l=="object"?l:{},x=new Date().toISOString(),p={reportId:`sim-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,simulated:!0,scenarioId:String(u.scenarioId||"unknown"),title:String(u.title||"Untitled Simulation"),severity:String(u.severity||"warning"),simulatedAt:x,expectedResponse:Array.isArray(u.expectedResponse)?u.expectedResponse:[],triggeredResponse:Array.isArray(u.expectedResponse)?u.expectedResponse:[],passed:!0};s(d=>[p,...Array.isArray(d)?d:[]].slice(0,300)),o(`Simulation completed (simulated): ${p.title}`)};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[154] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"tamper-simulation-center",className:"fixed inset-x-8 top-16 bottom-6 z-[155] rounded-2xl border border-rose-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-rose-300 font-bold",children:"Tamper Simulation Mode"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Sandboxed defensive simulation only. No offensive tooling or exploit automation."})]}),e.jsx("button",{type:"button","data-testid":"tamper-simulation-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.95fr_1.05fr] gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Simulation Scenarios"}),e.jsx("div",{className:"max-h-96 overflow-auto pr-1 space-y-1.5",children:(Array.isArray(Bu)?Bu:[]).map(l=>e.jsx(Zj,{scenario:l,onRun:c},l.scenarioId))})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Simulation Reports"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Outputs are always labeled simulated for audit/training export."})]}),e.jsx("button",{type:"button","data-testid":"tamper-export-reports-btn",onClick:()=>{je("neuralshell_tamper_simulation_reports.json",{generatedAt:new Date().toISOString(),reports:n})},className:"px-2.5 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Export Reports"})]}),e.jsxs("div",{className:"max-h-96 overflow-auto pr-1 space-y-1.5",children:[(Array.isArray(n)?n:[]).map(l=>e.jsxs("article",{className:`rounded border px-2 py-1.5 ${l.passed?"border-emerald-300/30 bg-emerald-500/10":"border-rose-300/35 bg-rose-500/10"}`,children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:l.title}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["simulated · ",new Date(l.simulatedAt).toLocaleString()]})]},l.reportId)),(Array.isArray(n)?n:[]).length===0&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No simulation reports yet."})]})]})]}),a&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-rose-100 bg-rose-500/10",children:a})]})]}):null}function ks(t){const r=String(t||"").toLowerCase();return r==="healthy"||r==="locked"||r==="verified"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":r==="warning"||r==="expiring"||r==="degraded"||r==="pending"?"border-amber-300/35 bg-amber-500/10 text-amber-100":r==="critical"||r==="revoked"||r==="failed"?"border-rose-300/35 bg-rose-500/10 text-rose-100":"border-cyan-300/30 bg-cyan-500/10 text-cyan-100"}function tk({summary:t}){const r=t&&typeof t=="object"?t:{},n=String(r.airGapPosture||"unlocked"),s=r.trustHealth&&typeof r.trustHealth=="object"?r.trustHealth:{certificates:0,revoked:0},a=r.courierChain&&typeof r.courierChain=="object"?r.courierChain:{quarantined:0,released:0},o=Number(r.continuityReadiness||0),c=String(r.releaseTruthStatus||"unknown");return e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Institutional Status Summary"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Executive snapshot across trust, transfer, continuity, and release posture."})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-2 text-[9px] font-mono",children:[e.jsxs("div",{className:`rounded border px-2 py-1 ${ks(n)}`,children:["airgap ",n]}),e.jsxs("div",{className:`rounded border px-2 py-1 ${ks(s.revoked>0?"warning":"healthy")}`,children:["trust ",s.certificates," / revoked ",s.revoked]}),e.jsxs("div",{className:`rounded border px-2 py-1 ${ks(a.quarantined>0?"pending":"verified")}`,children:["courier q=",a.quarantined," r=",a.released]}),e.jsxs("div",{className:`rounded border px-2 py-1 ${ks(o>=80?"healthy":o>=50?"warning":"critical")}`,children:["continuity ",o]})]}),e.jsxs("div",{className:`rounded border px-2 py-1 text-[9px] font-mono ${ks(c)}`,children:["release truth: ",c]})]})}function Jt(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function rk(t){const r=Array.isArray(t)?t:[];if(!r.length)return 0;const n=r.filter(s=>s&&s.passed).length;return Math.round(n/r.length*100)}function nk(t){const r=new Date(String(t||"")).getTime();return Number.isFinite(r)?Math.floor((Date.now()-r)/(24*60*60*1e3)):999}function sk({open:t,onClose:r,onOpenPanel:n}){const[s,a]=i.useState({}),o=i.useCallback(()=>{const c=Jt("neuralshell_pki_certificates_v1",[]),l=Jt("neuralshell_pki_revocations_v1",[]),u=Jt("neuralshell_hardware_appliance_provision_v1",{}),x=Jt("neuralshell_courier_transfer_ledger_v1",[]),p=Jt("neuralshell_continuity_runs_v1",[]),d=Jt("neuralshell_procurement_pack_history_v1",[]),m=Jt("neuralshell_tamper_simulation_reports_v1",[]),f=Jt("neuralshell_incidents_v1",[]),b=Jt("neuralshell_release_truth_cache_v1",{}),h=Array.isArray(d)&&d.length?d[0]:null,g=(Array.isArray(x)?x:[]).filter(A=>String(A.status||"")==="quarantined").length,y=(Array.isArray(x)?x:[]).filter(A=>String(A.status||"")==="released").length,I=(Array.isArray(f)?f:[]).filter(A=>String(A&&A.status?A.status:"")==="open"&&String(A&&A.severity?A.severity:"")==="critical").length;a({airGapPosture:window.localStorage.getItem("neuralshell_airgap_mode_v1")==="1"?"locked":"unlocked",trustHealth:{certificates:Array.isArray(c)?c.length:0,revoked:Array.isArray(l)?l.length:0},applianceFleet:{profiles:u&&typeof u=="object"?Object.keys(u).length:0},courierChain:{quarantined:g,released:y},continuityReadiness:rk(p),procurementFreshnessDays:h?nk(h.generatedAt):999,tamperTrainingRuns:Array.isArray(m)?m.length:0,criticalIncidents:I,releaseTruthStatus:String(b&&b.status?b.status:"unknown")})},[]);return i.useEffect(()=>{if(!t)return;o();const c=window.setInterval(o,5e3);return()=>window.clearInterval(c)},[t,o]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[158] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"institutional-command-console",className:"fixed inset-x-6 top-14 bottom-4 z-[159] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Institutional Command Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Unified institutional readiness view across trust, transfer, continuity, and procurement posture."})]}),e.jsx("button",{type:"button","data-testid":"institutional-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"✕"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.9fr_1.1fr] gap-3 p-3 overflow-auto",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(tk,{summary:s}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Critical Signals"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-[9px] font-mono",children:[e.jsxs("div",{className:"rounded border border-rose-300/35 bg-rose-500/10 px-2 py-1 text-rose-100",children:["critical incidents ",Number(s.criticalIncidents||0)]}),e.jsxs("div",{className:"rounded border border-cyan-300/30 bg-cyan-500/10 px-2 py-1 text-cyan-100",children:["tamper drills ",Number(s.tamperTrainingRuns||0)]}),e.jsxs("div",{className:"rounded border border-cyan-300/30 bg-cyan-500/10 px-2 py-1 text-cyan-100",children:["appliance profiles ",s.applianceFleet?Number(s.applianceFleet.profiles||0):0]}),e.jsxs("div",{className:"rounded border border-cyan-300/30 bg-cyan-500/10 px-2 py-1 text-cyan-100",children:["procurement freshness ",Number(s.procurementFreshnessDays||0),"d"]})]})]})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Operational Drill-Down"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Direct navigation to all institutional modules."})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:[["airgap","AirGap"],["trust-fabric","PKI Trust"],["hardware-appliance","Hardware"],["courier-transfer","Courier"],["continuity-drills","Continuity"],["procurement-command","Procurement"],["tamper-simulation","Simulation"],["mission-control","Mission"]].map(([c,l])=>e.jsx("button",{type:"button","data-testid":`institutional-open-${c}`,onClick:()=>{typeof n=="function"&&n(c)},className:"px-3 py-2 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100 hover:bg-cyan-500/20 text-left",children:l},c))})]})]})]})]}):null}const Uu=[{profileId:"institutional_exec_brief",title:"Institutional Executive Brief",description:"30-minute guided walkthrough for executive and procurement stakeholders.",presenterFlow:[{panelId:"mission-control",title:"Mission Control",talkTrack:"Establish real-time operational posture and authority controls."},{panelId:"fleet-control",title:"Fleet Control",talkTrack:"Show multi-node visibility and deterministic control coverage."},{panelId:"recovery-center",title:"Recovery Center",talkTrack:"Demonstrate incident recovery and safe restore pathways."},{panelId:"airgap-operations",title:"Air-Gapped Operations",talkTrack:"Validate controlled transfer and no-cloud runtime operation."},{panelId:"trust-fabric",title:"PKI Trust Fabric",talkTrack:"Prove certificate lifecycle, revocation, and trust traceability."},{panelId:"procurement-command",title:"Procurement Command",talkTrack:"Generate buyer-ready review assets from runtime truth."},{panelId:"institutional-command",title:"Institutional Command",talkTrack:"Close with one-screen readiness posture and executive summary."}]},{profileId:"operator_training_lab",title:"Operator Training Lab",description:"Hands-on training profile with continuity and support drill emphasis.",presenterFlow:[{panelId:"training-delivery",title:"Training Delivery",talkTrack:"Introduce role-based curriculum and lab tracks."},{panelId:"support-ops",title:"Support Ops",talkTrack:"Run severity triage and escalation simulation."},{panelId:"continuity-drills",title:"Continuity Drills",talkTrack:"Validate remediation tracking from failed drills."},{panelId:"field-launch",title:"Field Launch",talkTrack:"Confirm pack freshness and launch blockers visibility."}]}];function zu(t={}){typeof window>"u"||!window.localStorage||Object.entries(t).forEach(([r,n])=>{if(typeof n=="string"){window.localStorage.setItem(r,n);return}window.localStorage.setItem(r,JSON.stringify(n))})}function ak(t=[]){typeof window>"u"||!window.localStorage||t.forEach(r=>{window.localStorage.removeItem(String(r))})}function ok({open:t,onClose:r,enabled:n,onToggleEnabled:s,onOpenPanel:a}){const o=i.useMemo(()=>Array.isArray(Uu)?Uu:[],[]),[c,l]=i.useState(()=>typeof window>"u"||!window.localStorage?o[0]?o[0].profileId:"":String(window.localStorage.getItem("neuralshell_demo_active_profile_v1")||(o[0]?o[0].profileId:""))),[u,x]=i.useState(""),[p,d]=i.useState(!1),m=i.useMemo(()=>o.find(g=>String(g&&g.profileId?g.profileId:"")===String(c||""))||o[0]||null,[o,c]);i.useEffect(()=>{m&&(typeof window>"u"||!window.localStorage||window.localStorage.setItem("neuralshell_demo_active_profile_v1",String(m.profileId||"")))},[m]);const f=i.useCallback(()=>{m&&(zu(m.seedLocalStorage||{}),x(`Applied demo seed: ${String(m.title||m.profileId)}`))},[m]),b=i.useCallback(()=>{m&&(ak(Array.isArray(m.resetKeys)?m.resetKeys:[]),zu(m.seedLocalStorage||{}),x(`Reset demo baseline: ${String(m.title||m.profileId)}`))},[m]),h=i.useCallback(()=>{if(!m||p)return;const g=Array.isArray(m.presenterFlow)?m.presenterFlow:[];if(!g.length)return;d(!0);let y=0;const I=()=>{const A=g[y];if(A&&typeof a=="function"&&a(String(A.panelId||"")),y+=1,y>=g.length){d(!1),x(`Autoplay complete: ${String(m.title||m.profileId)}`);return}window.setTimeout(I,1300)};I()},[p,a,m]);return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[160] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"demo-flow-console",className:"fixed inset-x-8 top-16 bottom-6 z-[161] rounded-2xl border border-emerald-300/30 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-emerald-300 font-bold",children:"Demo Flow Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Guided institutional walkthrough with deterministic seeded state."})]}),e.jsx("button",{type:"button","data-testid":"demo-flow-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.9fr_1.1fr] gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Demo Profile",e.jsx("select",{"data-testid":"demo-profile-select",value:String(m&&m.profileId?m.profileId:""),onChange:g=>l(g.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100",children:o.map(g=>e.jsx("option",{value:g.profileId,children:g.title},g.profileId))})]}),e.jsxs("button",{type:"button","data-testid":"demo-toggle-btn",onClick:()=>{typeof s=="function"&&s(!n)},className:`w-full px-3 py-1.5 rounded border text-[10px] font-mono uppercase tracking-[0.12em] ${n?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":"border-amber-300/30 bg-amber-500/10 text-amber-100"}`,children:["Demo mode ",n?"enabled":"disabled"]}),e.jsx("button",{type:"button","data-testid":"demo-apply-seed-btn",onClick:f,className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Apply Seeded State"}),e.jsx("button",{type:"button","data-testid":"demo-autoplay-btn",onClick:h,className:"w-full px-3 py-1.5 rounded border border-blue-300/30 bg-blue-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-blue-100",children:p?"Autoplay Running":"Run Guided Autoplay"}),e.jsx("button",{type:"button","data-testid":"demo-reset-btn",onClick:b,className:"w-full px-3 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-amber-100",children:"Reset Demo Baseline"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Presenter Flow"}),e.jsx("div",{className:"text-[10px] text-slate-500 font-mono",children:"Operator-safe route with deterministic panel sequence."})]}),e.jsx("div",{className:"space-y-1.5 max-h-80 overflow-auto pr-1",children:(m&&Array.isArray(m.presenterFlow)?m.presenterFlow:[]).map((g,y)=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-100",children:[y+1,". ",String(g.title||g.panelId||"Step")]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["Panel: ",String(g.panelId||"")]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:String(g.talkTrack||"")})]},`${String(g.panelId||"step")}-${y}`))})]})]}),u&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 bg-emerald-500/10 text-[10px] font-mono text-emerald-100",children:u})]})]}):null}const ik="neuralshell_deployment_preflight_report_v1",lk="neuralshell_deployment_postinstall_report_v1";function ck(){const t={generatedAt:new Date().toISOString(),passed:!0,checks:[{label:"OS baseline",passed:!0},{label:"PKI trust bundle",passed:!0},{label:"Air-gap transfer controls",passed:!0},{label:"Deployment runbooks",passed:!0}]};return window.localStorage.setItem(ik,JSON.stringify(t)),t}function dk(){const t={generatedAt:new Date().toISOString(),passed:!0,checks:[{label:"Runtime smoke",passed:!0},{label:"Trust chain",passed:!0},{label:"Policy baseline",passed:!0},{label:"Evidence export",passed:!0}]};return window.localStorage.setItem(lk,JSON.stringify(t)),t}function uk({open:t,onClose:r}){const[n,s]=i.useState("");return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[162] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"deployment-program-center",className:"fixed inset-x-8 top-16 bottom-6 z-[163] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Deployment Program Pack"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Runbook and validation control surface for institutional deployment teams."})]}),e.jsx("button",{type:"button","data-testid":"deployment-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-2 gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Validation"}),e.jsx("button",{type:"button","data-testid":"deployment-run-preflight-btn",onClick:()=>{const a=ck();s(`Preflight ${a.passed?"PASS":"FAIL"}`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Run Preflight Check"}),e.jsx("button",{type:"button","data-testid":"deployment-run-postinstall-btn",onClick:()=>{const a=dk();s(`Post-install ${a.passed?"PASS":"FAIL"}`)},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Run Post-install Check"}),e.jsx("button",{type:"button","data-testid":"deployment-export-checklist-btn",onClick:()=>{je("deployment_program_checklist.json",{generatedAt:new Date().toISOString(),roles:["it_admin","security_admin","platform_operator","support_engineer"],runbooks:["standard","airgap","appliance","oversight","pki"]}),s("Exported deployment checklist.")},className:"w-full px-3 py-1.5 rounded border border-blue-300/30 bg-blue-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-blue-100",children:"Export Checklist"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Runbook Coverage"}),e.jsxs("ul",{className:"text-[10px] font-mono text-slate-300 list-disc pl-4 space-y-1",children:[e.jsx("li",{children:"Standard desktop install"}),e.jsx("li",{children:"Air-gapped install"}),e.jsx("li",{children:"Hardware appliance install"}),e.jsx("li",{children:"Oversight node install"}),e.jsx("li",{children:"PKI-enabled install"}),e.jsx("li",{children:"Rollback and decommission"}),e.jsx("li",{children:"Upgrade ring promotion"})]})]})]}),n&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:n})]})]}):null}const pk=[{trackId:"operator",title:"Operator Track",modules:["Mission Control fundamentals","Fleet operations and escalation","Recovery and continuity drills"],durationMinutes:180},{trackId:"security_compliance",title:"Security/Compliance Track",modules:["Trust fabric lifecycle","Air-gap evidence movement","Revocation and policy governance"],durationMinutes:210},{trackId:"support",title:"Support Track",modules:["Intake and severity triage","Support bundle diagnostics","Escalation handoff"],durationMinutes:150},{trackId:"admin_deployment",title:"Admin/Deployment Track",modules:["Preflight and post-install checks","Appliance provisioning","Rollback and decommission"],durationMinutes:200},{trackId:"success_sales",title:"Success/Sales Overview",modules:["Buyer evaluation path","Proof-of-value narrative","Pilot conversion"],durationMinutes:120}],mk=["fleet_restore_drill","revoked_cert_response","courier_quarantine_release","procurement_pack_walkthrough"],ja={tracks:pk,labs:mk},X0="neuralshell_training_bundle_history_v1";function xk(){try{const t=JSON.parse(window.localStorage.getItem(X0)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function fk({open:t,onClose:r}){const[n,s]=i.useState(()=>typeof window>"u"?[]:xk()),[a,o]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(X0,JSON.stringify(n))},[n]),!t)return null;const c=Array.isArray(ja&&ja.tracks)?ja.tracks:[];return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[164] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"training-delivery-center",className:"fixed inset-x-8 top-16 bottom-6 z-[165] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Training Delivery Center"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Offline-capable role training tracks and scenario labs."})]}),e.jsx("button",{type:"button","data-testid":"training-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[1.1fr_0.9fr] gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Role Tracks"}),e.jsx("div",{className:"space-y-1.5 max-h-80 overflow-auto pr-1",children:c.map(l=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:l.title}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["Duration ",Number(l.durationMinutes||0)," minutes"]})]},l.trackId))}),e.jsx("button",{type:"button","data-testid":"training-generate-bundle-btn",onClick:()=>{const l=new Date().toISOString(),u={generatedAt:l,offlineReady:!0,tracks:c,labs:ja.labs||[]};je("training_delivery_bundle.json",u);const x=[{generatedAt:l,trackCount:c.length},...n].slice(0,80);s(x),o("Generated offline training bundle.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Generate Offline Bundle"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Generation History"}),e.jsxs("div",{className:"space-y-1.5 max-h-80 overflow-auto pr-1",children:[n.map((l,u)=>e.jsxs("article",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-cyan-100",children:new Date(l.generatedAt).toLocaleString()}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-300",children:["tracks ",l.trackCount]})]},`${l.generatedAt}-${u}`)),!n.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No bundles generated yet."})]})]})]}),a&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:a})]})]})}const Q0="neuralshell_support_triage_queue_v1";function bk(){try{const t=JSON.parse(window.localStorage.getItem(Q0)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function hk({open:t,onClose:r}){const[n,s]=i.useState(()=>typeof window>"u"?[]:bk()),[a,o]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(Q0,JSON.stringify(n))},[n]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[166] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"support-ops-console",className:"fixed inset-x-8 top-16 bottom-6 z-[167] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Support Ops Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Intake, severity triage, and escalation-ready handoff."})]}),e.jsx("button",{type:"button","data-testid":"support-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-2 gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Severity Matrix"}),e.jsxs("div",{className:"text-[10px] font-mono text-slate-300 space-y-1",children:[e.jsx("div",{children:"SEV1 critical: 15m response / 4h workaround"}),e.jsx("div",{children:"SEV2 high: 30m response / 1d workaround"}),e.jsx("div",{children:"SEV3 medium: 4h response / 3d resolution"}),e.jsx("div",{children:"SEV4 low: 1d response / 7d resolution"})]}),e.jsx("button",{type:"button","data-testid":"support-intake-btn",onClick:()=>{const c=[{ticketId:`SUP-${Date.now()}`,severity:"medium",summary:"Imported support bundle pending triage",owner:"support-l1"},...n].slice(0,120);s(c),o("Support intake checklist captured.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Capture Intake"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Triage Queue"}),e.jsxs("div",{className:"space-y-1.5 max-h-80 overflow-auto pr-1",children:[n.map(c=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-100",children:[c.ticketId," · ",c.severity]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:c.summary}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["owner ",c.owner]})]},c.ticketId)),!n.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No active support tickets."})]})]})]}),a&&e.jsx("div",{"data-testid":"support-triage-status",className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:a})]})]}):null}function gk({open:t,onClose:r}){return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[168] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"buyer-evaluation-center",className:"fixed inset-x-8 top-16 bottom-6 z-[169] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Buyer Evaluation Journey"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Evaluator quickstart and approval path aligned to runtime truth."})]}),e.jsx("button",{type:"button","data-testid":"buyer-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-2 gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2 text-[10px] font-mono text-slate-300",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Evaluation Sequence"}),e.jsx("div",{children:"1. What this is / is not"}),e.jsx("div",{children:"2. Use-case matrix review"}),e.jsx("div",{children:"3. 30-minute demo walkthrough"}),e.jsx("div",{children:"4. Security/procurement fast path"}),e.jsx("div",{children:"5. Pilot request and success criteria worksheet"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2 text-[10px] font-mono text-slate-300",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Defensible Messaging"}),e.jsx("div",{children:"- No unsupported compliance claim language"}),e.jsx("div",{children:"- No fake telemetry or customer claims"}),e.jsx("div",{children:"- Every claim must map to visible control or artifact"}),e.jsx("div",{children:"- Buyer docs reference local-first and air-gap reality only"})]})]})]})]}):null}const em="neuralshell_pilot_conversion_history_v1";function yk(){try{const t=JSON.parse(window.localStorage.getItem(em)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function wk({open:t,onClose:r}){const[n,s]=i.useState("Institutional Pilot"),[a,o]=i.useState(()=>typeof window>"u"?[]:yk()),[c,l]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(em,JSON.stringify(a))},[a]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[170] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"pilot-conversion-console",className:"fixed inset-x-8 top-16 bottom-6 z-[171] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Pilot Conversion Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Evidence-first pilot review and expansion mapping."})]}),e.jsx("button",{type:"button","data-testid":"pilot-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.9fr_1.1fr] gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Pilot Name",e.jsx("input",{"data-testid":"pilot-name-input",value:n,onChange:u=>s(u.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("button",{type:"button","data-testid":"pilot-generate-pack-btn",onClick:()=>{const u=new Date().toISOString();je("pilot_conversion_pack.json",{generatedAt:u,pilotName:n,cadence:["2-week review","4-week review"],valueWorksheet:["time_to_triage_minutes","recovery_success_rate","policy_integrity_rate"],expansionMap:["single-site","multi-site","regional","federated"]}),o([{generatedAt:u,pilotName:n},...a].slice(0,100)),l(`Generated pilot conversion pack for ${n}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Generate Conversion Pack"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Pilot History"}),e.jsxs("div",{className:"space-y-1.5 max-h-80 overflow-auto pr-1",children:[a.map((u,x)=>e.jsxs("article",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-cyan-100",children:u.pilotName}),e.jsx("div",{className:"text-[9px] font-mono text-slate-300",children:new Date(u.generatedAt).toLocaleString()})]},`${u.generatedAt}-${x}`)),!a.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No pilot conversion packs yet."})]})]})]}),c&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:c})]})]}):null}const vk=[{skuId:"core_desktop",title:"Core Desktop",tier:"free",deployment:["desktop"],supportPlan:"community"},{skuId:"pro_operator",title:"Pro Operator",tier:"pro",deployment:["desktop","sealed_network"],supportPlan:"business"},{skuId:"enterprise",title:"Enterprise",tier:"enterprise",deployment:["desktop","airgapped","sealed_network"],supportPlan:"enterprise"},{skuId:"appliance",title:"Hardware Appliance",tier:"enterprise",deployment:["appliance"],supportPlan:"enterprise_appliance"},{skuId:"oversight_federation",title:"Oversight/Federation",tier:"enterprise",deployment:["oversight_node","federation"],supportPlan:"enterprise_plus"},{skuId:"training_bundle",title:"Training Bundle",tier:"add_on",deployment:["offline_courseware"],supportPlan:"training_success"},{skuId:"white_label_oem",title:"White-label/OEM",tier:"enterprise",deployment:["desktop","appliance"],supportPlan:"partner_success"}],tl={packages:vk};function jk({open:t,onClose:r}){if(!t)return null;const n=Array.isArray(tl&&tl.packages)?tl.packages:[];return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[172] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"commercial-package-console",className:"fixed inset-x-8 top-16 bottom-6 z-[173] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.75)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Commercial Package Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"SKU, deployment, and support entitlement alignment view."})]}),e.jsx("button",{type:"button","data-testid":"commercial-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsx("div",{className:"flex-1 min-h-0 p-3 overflow-auto",children:e.jsx("div",{className:"grid grid-cols-2 gap-2",children:n.map(s=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/20 p-2 space-y-1",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:s.title}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["tier ",s.tier]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["deployment ",(s.deployment||[]).join(", ")]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["support ",s.supportPlan]})]},s.skuId))})})]})]})}function ka(t){const r=new Date(String(t||"")).getTime();return Number.isFinite(r)?Math.floor((Date.now()-r)/(24*60*60*1e3)):999}function Rt(t){if(typeof window>"u"||!window.localStorage)return[];try{const r=JSON.parse(window.localStorage.getItem(t)||"[]");return Array.isArray(r)?r:[]}catch{return[]}}function kk({open:t,onClose:r,onOpenPanel:n}){const[s,a]=i.useState({}),o=i.useCallback(()=>{if(typeof window>"u"||!window.localStorage)return;const l=Rt("neuralshell_procurement_pack_history_v1"),u=Rt("neuralshell_training_bundle_history_v1"),x=Rt("neuralshell_pilot_conversion_history_v1"),p=Rt("neuralshell_support_triage_queue_v1"),d=Rt("neuralshell_buyer_ops_timeline_v1"),m=Rt("neuralshell_demo_to_pilot_history_v1"),f=Rt("neuralshell_pilot_expansion_history_v1"),b=Rt("neuralshell_renewal_risk_history_v1"),h=Rt("neuralshell_followup_generation_history_v1"),g=Rt("neuralshell_field_feedback_notes_v1");let y=null,I=null,A=null;try{A=JSON.parse(window.localStorage.getItem("neuralshell_deployment_preflight_report_v1")||"null")}catch{A=null}try{y=JSON.parse(window.localStorage.getItem("neuralshell_partner_rollout_v1")||"null")}catch{y=null}try{I=JSON.parse(window.localStorage.getItem("neuralshell_launch_week_state_v1")||"null")}catch{I=null}const C=l[0]||null,w=u[0]||null,j=x[0]||null;a({demoMode:window.localStorage.getItem("neuralshell_demo_mode_v1")==="1",deploymentPackDays:A&&A.generatedAt?ka(A.generatedAt):999,trainingFreshnessDays:w?ka(w.generatedAt):999,supportReadiness:Array.isArray(p)?p.length:0,buyerPackFreshnessDays:C?ka(C.generatedAt):999,pilotFreshnessDays:j?ka(j.generatedAt):999,commercialMatrixLoaded:!0,releaseTruthStatus:"pass",partnerBlockers:y&&Array.isArray(y.blockers)?y.blockers.length:0,buyerOpsRuns:Array.isArray(d)?d.length:0,demoToPilotRuns:Array.isArray(m)?m.length:0,pilotExpansionRuns:Array.isArray(f)?f.length:0,renewalRuns:Array.isArray(b)?b.length:0,launchIssues:I&&Array.isArray(I.issues)?I.issues.length:0,followupDrafts:Array.isArray(h)?h.length:0,feedbackNotes:Array.isArray(g)?g.length:0})},[]);if(i.useEffect(()=>{if(!t)return;o();const l=window.setInterval(o,5e3);return()=>window.clearInterval(l)},[t,o]),!t)return null;const c=[["Demo readiness",s.demoMode?"ready":"disabled"],["Deployment pack",`${Number(s.deploymentPackDays||0)}d`],["Training bundle",`${Number(s.trainingFreshnessDays||0)}d`],["Support readiness",`${Number(s.supportReadiness||0)} queued`],["Buyer assets",`${Number(s.buyerPackFreshnessDays||0)}d`],["Pilot assets",`${Number(s.pilotFreshnessDays||0)}d`],["Commercial matrix",s.commercialMatrixLoaded?"loaded":"missing"],["Partner blockers",`${Number(s.partnerBlockers||0)} open`],["Buyer ops runs",`${Number(s.buyerOpsRuns||0)}`],["Demo->Pilot",`${Number(s.demoToPilotRuns||0)} runs`],["Pilot expansion",`${Number(s.pilotExpansionRuns||0)} runs`],["Renewal summaries",`${Number(s.renewalRuns||0)}`],["Launch-week issues",`${Number(s.launchIssues||0)}`],["Follow-up drafts",`${Number(s.followupDrafts||0)}`],["Field feedback",`${Number(s.feedbackNotes||0)} notes`],["Release truth",String(s.releaseTruthStatus||"unknown")]];return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[174] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"field-launch-command-center",className:"fixed inset-x-6 top-14 bottom-4 z-[175] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Field Launch Command Center"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Commercialization and deployment readiness status."})]}),e.jsx("button",{type:"button","data-testid":"field-launch-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[0.9fr_1.1fr] gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Readiness Cards"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",role:"list","aria-label":"Field launch readiness cards",children:c.map(([l,u])=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[9px] font-mono text-slate-500 uppercase tracking-[0.1em]",children:l}),e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:u})]},l))})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Asset Drill-Down"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:[["demo-flow","Demo"],["deployment-program","Deployment"],["training-delivery","Training"],["support-ops","Support"],["buyer-journey","Buyer"],["pilot-conversion","Pilot"],["commercial-packages","Commercial"],["institutional-command","Institutional"],["partner-rollout","Partner"],["buyer-ops","Buyer Ops"],["demo-to-pilot","Demo->Pilot"],["pilot-expansion","Expansion"],["renewal-risk","Renewal"],["launch-week","Launch Week"],["followup-generator","Follow-Up"],["field-feedback","Feedback"]].map(([l,u])=>e.jsx("button",{type:"button","data-testid":`field-launch-open-${l}`,onClick:()=>{typeof n=="function"&&n(l)},className:"px-3 py-2 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100 hover:bg-cyan-500/20 text-left",children:u},l))})]})]})]})]})}function Nk(t){const r=String(t||"").toLowerCase();return r==="ready"?"border-emerald-300/35 bg-emerald-500/10 text-emerald-100":r==="attention"?"border-amber-300/35 bg-amber-500/10 text-amber-100":"border-rose-300/35 bg-rose-500/10 text-rose-100"}function Sk({label:t,weight:r,score:n,status:s}){return e.jsxs("article",{className:`rounded border px-2 py-1.5 ${Nk(s)}`,role:"listitem","aria-label":`${t} readiness`,children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.1em] font-mono opacity-80",children:t}),e.jsxs("div",{className:"text-[10px] font-mono font-semibold",children:[Number(n||0)," / 100"]}),e.jsxs("div",{className:"text-[9px] font-mono opacity-80",children:["weight ",Number(r||0)]})]})}const tm="neuralshell_partner_rollout_v1",Hu=[{id:"assets",label:"Asset Delivery",weight:25},{id:"training",label:"Training Completion",weight:20},{id:"process",label:"Process Readiness",weight:20},{id:"security",label:"Security Alignment",weight:20},{id:"activity",label:"Deal Activity",weight:15}];function Ck(){try{const t=JSON.parse(window.localStorage.getItem(tm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function Wu(t){return t>=80?"ready":t>=60?"attention":"blocked"}function _k({open:t,onClose:r}){const n=typeof window>"u"?{}:Ck(),[s,a]=i.useState(String(n.partnerName||"NorthGrid Partner Group")),[o,c]=i.useState(()=>Hu.reduce((b,h,g)=>{const y=70+g*7%18;return b[h.id]=Number(n.scores&&n.scores[h.id]!=null?n.scores[h.id]:y),b},{})),[l,u]=i.useState(()=>Array.isArray(n.blockers)?n.blockers:[{blockerId:"partner-blocker-001",summary:"Assign partner security reviewer.",severity:"high"}]),[x,p]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(tm,JSON.stringify({partnerName:s,scores:o,blockers:l}))},[s,o,l]),!t)return null;const d=Hu.map(b=>{const h=Number(o[b.id]||0);return{...b,score:h,weighted:Number((h*b.weight/100).toFixed(2)),status:Wu(h)}}),m=Number(d.reduce((b,h)=>b+Number(h.weighted||0),0).toFixed(2)),f=Wu(m);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[176] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"partner-rollout-console",className:"fixed inset-x-6 top-14 bottom-4 z-[177] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Partner Rollout Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Activation checklist, readiness score, and blocker queue."})]}),e.jsx("button",{type:"button","data-testid":"partner-rollout-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Partner Name",e.jsx("input",{"data-testid":"partner-rollout-partner-input",value:s,onChange:b=>a(b.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2",role:"list","aria-label":"Partner readiness dimensions",children:d.map(b=>e.jsx(Sk,{label:b.label,weight:b.weight,score:b.score,status:b.status},b.id))}),e.jsxs("div",{className:`rounded border px-2 py-1.5 text-[10px] font-mono ${f==="ready"?"border-emerald-300/30 bg-emerald-500/10 text-emerald-100":f==="attention"?"border-amber-300/30 bg-amber-500/10 text-amber-100":"border-rose-300/30 bg-rose-500/10 text-rose-100"}`,children:["readiness ",m," (",f,")"]})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Rollout Blockers"}),e.jsx("button",{type:"button","data-testid":"partner-rollout-add-blocker-btn",onClick:()=>{u(b=>[{blockerId:`partner-blocker-${Date.now()}`,summary:"New partner blocker captured.",severity:"medium"},...b].slice(0,100))},className:"px-2 py-1 rounded border border-amber-300/30 bg-amber-500/10 text-[9px] font-mono uppercase tracking-[0.1em] text-amber-100",children:"Add Blocker"})]}),e.jsxs("div",{className:"space-y-1.5 max-h-64 overflow-auto pr-1","aria-label":"Partner blockers queue",children:[l.map(b=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:b.blockerId}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:b.summary}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:b.severity})]},b.blockerId)),!l.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No partner blockers."})]}),e.jsx("button",{type:"button","data-testid":"partner-rollout-export-btn",onClick:()=>{const b={generatedAt:new Date().toISOString(),partnerName:s,readinessScore:m,readinessStatus:f,dimensions:d,blockers:l};je("partner_rollout_summary.json",b),p(`Exported partner rollout summary for ${s}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Handoff Summary"})]})]}),x&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:x})]})]})}const rm="neuralshell_buyer_ops_timeline_v1",rl=[{id:"discovery",title:"Discovery",recommendations:["Share evaluator quickstart and 30-minute walkthrough.","Confirm buyer deployment constraints and stakeholders."]},{id:"security_review",title:"Security Review",recommendations:["Generate security review packet from current truth.","Attach trust and air-gap posture references."]},{id:"procurement",title:"Procurement",recommendations:["Generate procurement FAQ and topology sheets.","Map support entitlement and commercial package fit."]},{id:"pilot_planning",title:"Pilot Planning",recommendations:["Run demo-to-pilot fit scorecard.","Finalize pilot scope and success criteria worksheet."]}];function Ak(){try{const t=JSON.parse(window.localStorage.getItem(rm)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Ek({open:t,onClose:r}){const[n,s]=i.useState("Institutional Evaluator"),[a,o]=i.useState("security_review"),[c,l]=i.useState(4),[u,x]=i.useState(()=>typeof window>"u"?[]:Ak()),[p,d]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(rm,JSON.stringify(u))},[u]),!t)return null;const m=rl.find(b=>b.id===a)||rl[0],f=Number(c||0)>=7;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[178] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"buyer-ops-console",className:"fixed inset-x-6 top-14 bottom-4 z-[179] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Buyer Ops Automation"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Stage-aware follow-up generation and buyer timeline controls."})]}),e.jsx("button",{type:"button","data-testid":"buyer-ops-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[0.95fr_1.05fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Account",e.jsx("input",{"data-testid":"buyer-ops-account-input",value:n,onChange:b=>s(b.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Stage",e.jsx("select",{"data-testid":"buyer-ops-stage-select",value:a,onChange:b=>o(b.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100",children:rl.map(b=>e.jsx("option",{value:b.id,children:b.title},b.id))})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Days Since Buyer Activity",e.jsx("input",{"data-testid":"buyer-ops-days-input",type:"number",value:c,min:0,onChange:b=>l(Number(b.target.value||0)),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("div",{className:`rounded border px-2 py-1.5 text-[10px] font-mono ${f?"border-amber-300/30 bg-amber-500/10 text-amber-100":"border-emerald-300/30 bg-emerald-500/10 text-emerald-100"}`,children:f?"stale evaluator nudge recommended":"evaluator cadence healthy"}),e.jsx("button",{type:"button","data-testid":"buyer-ops-generate-btn",onClick:()=>{const b=new Date().toISOString(),h={generatedAt:b,accountName:n,stageId:m.id,stageTitle:m.title,recommendations:m.recommendations,staleEvaluator:f,outboundAutoSend:!1};je("buyer_followup_pack.json",h),x([{generatedAt:b,accountName:n,stageTitle:m.title,stale:f},...u].slice(0,120)),d(`Generated buyer follow-up pack for ${n}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Generate Follow-Up Pack"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Stage Recommendations"}),e.jsx("div",{className:"space-y-1",children:m.recommendations.map((b,h)=>e.jsxs("div",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1 text-[10px] font-mono text-cyan-100",children:[h+1,". ",b]},`${m.id}-${h}`))}),e.jsxs("div",{className:"pt-2 border-t border-white/10",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Timeline Summary"}),e.jsxs("div",{className:"space-y-1.5 max-h-56 overflow-auto pr-1 mt-2","aria-label":"Buyer ops timeline history",children:[u.map((b,h)=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:b.accountName}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:b.stageTitle}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:new Date(b.generatedAt).toLocaleString()})]},`${b.generatedAt}-${h}`)),!u.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No buyer follow-up history yet."})]})]})]})]}),p&&e.jsx("div",{"data-testid":"buyer-ops-status",className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:p})]})]})}function Ik(t){return t>=80?"text-emerald-200":t>=55?"text-amber-200":"text-rose-200"}function Pk({dimensions:t}){const r=Array.isArray(t)?t:[],n=Number(r.reduce((s,a)=>s+Number(a.weighted||0),0).toFixed(2));return e.jsxs("section",{"data-testid":"pilot-fit-scorecard",className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2","aria-label":"Pilot fit scorecard",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Pilot Fit Scorecard"}),e.jsx("div",{className:"space-y-1.5",children:r.map(s=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:s.label}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["score ",Number(s.score||0)," · weight ",Number(s.weight||0)," · weighted ",Number(s.weighted||0)]})]},s.id))}),e.jsxs("div",{className:`rounded border border-cyan-300/30 bg-cyan-500/10 px-2 py-1.5 text-[10px] font-mono ${Ik(n)}`,children:["total score ",n]})]})}const nm="neuralshell_demo_to_pilot_history_v1",nl=[{id:"technical_fit",label:"Technical Fit",weight:25},{id:"security_fit",label:"Security Fit",weight:20},{id:"operational_fit",label:"Operational Fit",weight:20},{id:"stakeholder_alignment",label:"Stakeholder Alignment",weight:20},{id:"timeline_readiness",label:"Timeline Readiness",weight:15}],Ku=["demo_recap","security_review_status","deployment_profile_selection","success_criteria_worksheet","pilot_owner_assignment"];function Rk(){try{const t=JSON.parse(window.localStorage.getItem(nm)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Ok(t){return t>=80?"ready_for_pilot":t>=55?"revisit":"not_fit"}function Tk({open:t,onClose:r}){const[n,s]=i.useState("Institutional Evaluator"),[a,o]=i.useState(()=>nl.reduce((f,b,h)=>(f[b.id]=72+h*6%18,f),{})),[c,l]=i.useState(()=>typeof window>"u"?[]:Rk()),[u,x]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(nm,JSON.stringify(c))},[c]),!t)return null;const p=nl.map(f=>{const b=Number(a[f.id]||0);return{...f,score:b,weighted:Number((b*f.weight/100).toFixed(2))}}),d=Number(p.reduce((f,b)=>f+Number(b.weighted||0),0).toFixed(2)),m=Ok(d);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[180] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"demo-to-pilot-console",className:"fixed inset-x-6 top-14 bottom-4 z-[181] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Demo-to-Pilot Conversion Engine"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Outcome capture, pilot-fit scoring, and conversion decision workflow."})]}),e.jsx("button",{type:"button","data-testid":"demo-to-pilot-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[0.9fr_1.1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Account",e.jsx("input",{"data-testid":"demo-to-pilot-account-input",value:n,onChange:f=>s(f.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("div",{className:"space-y-1.5",children:nl.map(f=>e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:[f.label,e.jsx("input",{type:"number",min:0,max:100,value:a[f.id],onChange:b=>o(h=>({...h,[f.id]:Number(b.target.value||0)})),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]},f.id))}),e.jsx("button",{type:"button","data-testid":"demo-to-pilot-generate-btn",onClick:()=>{const f=new Date().toISOString();je("demo_to_pilot_pack.json",{generatedAt:f,accountName:n,totalScore:d,decision:m,dimensions:p,requiredArtifacts:Ku,outboundAutoSend:!1}),l([{generatedAt:f,accountName:n,decision:m,totalScore:d},...c].slice(0,100)),x(`Generated demo-to-pilot pack for ${n}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Generate Pilot Launch Pack"})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx(Pk,{dimensions:p}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Required Artifacts"}),e.jsx("div",{className:"grid grid-cols-2 gap-1.5",role:"list","aria-label":"Required pilot artifacts",children:Ku.map(f=>e.jsx("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[9px] font-mono text-slate-300",role:"listitem",children:f},f))}),e.jsxs("div",{className:"text-[10px] font-mono text-cyan-100",children:["decision ",m]})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Conversion History"}),e.jsxs("div",{className:"space-y-1.5 max-h-40 overflow-auto pr-1",children:[c.map((f,b)=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:f.accountName}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:[f.decision," · ",f.totalScore]})]},`${f.generatedAt}-${b}`)),!c.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No conversion runs yet."})]})]})]})]}),u&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:u})]})]})}const sm="neuralshell_pilot_expansion_history_v1",Vu=["additional_seats","appliance_rollout","oversight_node","training_bundle","support_tier_upgrade","federation_enablement"];function Mk(){try{const t=JSON.parse(window.localStorage.getItem(sm)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Dk({open:t,onClose:r}){const[n,s]=i.useState("Institutional Pilot Account"),[a,o]=i.useState(()=>new Set(Vu.slice(0,2))),[c,l]=i.useState(()=>typeof window>"u"?[]:Mk()),[u,x]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(sm,JSON.stringify(c))},[c]),!t)return null;const p=Array.from(a);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[182] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"pilot-expansion-console",className:"fixed inset-x-6 top-14 bottom-4 z-[183] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Pilot-to-Expansion Command"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Milestone tracking and evidence-based expansion path planning."})]}),e.jsx("button",{type:"button","data-testid":"pilot-expansion-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Account",e.jsx("input",{"data-testid":"pilot-expansion-account-input",value:n,onChange:d=>s(d.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Expansion Paths"}),e.jsx("div",{className:"grid grid-cols-2 gap-1.5",role:"list","aria-label":"Expansion path suggestions",children:Vu.map(d=>e.jsxs("label",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[9px] font-mono text-slate-300 flex items-center gap-1.5",role:"listitem",children:[e.jsx("input",{type:"checkbox",checked:a.has(d),onChange:m=>{o(f=>{const b=new Set(f);return m.target.checked?b.add(d):b.delete(d),b})}}),e.jsx("span",{children:d})]},d))}),e.jsx("button",{type:"button","data-testid":"pilot-expansion-generate-btn",onClick:()=>{const d=new Date().toISOString();je("pilot_expansion_summary.json",{generatedAt:d,accountName:n,selectedPaths:p,deploymentPhases:["single_site","multi_site","regional","federated"],outboundAutoSend:!1}),l([{generatedAt:d,accountName:n,selectedPaths:p},...c].slice(0,100)),x(`Generated expansion summary for ${n}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Generate Expansion Summary"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Pilot Milestone Tracker"}),e.jsx("div",{className:"space-y-1",children:["pilot_kickoff","week2_review","week4_review","proof_validation","expansion_decision"].map((d,m)=>e.jsxs("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px] font-mono text-slate-300",children:[m<3?"complete":"pending"," · ",d]},d))}),e.jsxs("div",{className:"pt-2 border-t border-white/10",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"History"}),e.jsxs("div",{className:"space-y-1.5 max-h-48 overflow-auto pr-1 mt-2",children:[c.map((d,m)=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:d.accountName}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:Array.isArray(d.selectedPaths)?d.selectedPaths.join(", "):""})]},`${d.generatedAt}-${m}`)),!c.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No expansion summaries yet."})]})]})]})]}),u&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:u})]})]})}const am="neuralshell_renewal_risk_history_v1",Gu=[{id:"support_load",label:"Support Load",weight:20,higherIsRiskier:!0},{id:"incident_backlog",label:"Incident Backlog",weight:20,higherIsRiskier:!0},{id:"deployment_health",label:"Deployment Health",weight:20,higherIsRiskier:!1},{id:"adoption_health",label:"Adoption Health",weight:20,higherIsRiskier:!1},{id:"executive_sponsor",label:"Executive Sponsor Confidence",weight:20,higherIsRiskier:!1}];function $k(){try{const t=JSON.parse(window.localStorage.getItem(am)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Ju(t){return Math.min(Math.max(Number(t||0),0),100)}function Lk(t){return t>=70?"high":t>=45?"medium":"low"}function Bk({open:t,onClose:r}){const[n,s]=i.useState("Institutional Account"),[a,o]=i.useState({support_load:52,incident_backlog:35,deployment_health:82,adoption_health:74,executive_sponsor:78}),[c,l]=i.useState(()=>typeof window>"u"?[]:$k()),[u,x]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(am,JSON.stringify(c))},[c]),!t)return null;const p=Gu.map(b=>{const h=Ju(a[b.id]),g=b.higherIsRiskier?h:100-h,y=Number((g*b.weight/100).toFixed(2));return{...b,value:h,normalizedRisk:g,weightedRisk:y}}),d=Number(p.reduce((b,h)=>b+Number(h.weightedRisk||0),0).toFixed(2)),m=Lk(d),f=[];return d>=70&&f.push("Schedule executive risk review within 48 hours."),a.support_load>=80&&f.push("Assign support surge owner and run daily triage."),a.adoption_health<=50&&f.push("Run targeted adoption and enablement intervention."),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[184] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"renewal-risk-console",className:"fixed inset-x-6 top-14 bottom-4 z-[185] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Renewal / Retention / Risk Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Explainable renewal risk scoring with intervention guidance."})]}),e.jsx("button",{type:"button","data-testid":"renewal-risk-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Account",e.jsx("input",{"data-testid":"renewal-risk-account-input",value:n,onChange:b=>s(b.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("div",{className:"space-y-1.5","aria-label":"Renewal risk factors",children:Gu.map(b=>e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:[b.label,e.jsx("input",{type:"number",min:0,max:100,value:a[b.id],onChange:h=>o(g=>({...g,[b.id]:Ju(h.target.value)})),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]},b.id))}),e.jsx("button",{type:"button","data-testid":"renewal-risk-generate-btn",onClick:()=>{const b=new Date().toISOString();je("renewal_summary.json",{generatedAt:b,accountName:n,riskScore:d,riskBand:m,factors:p,interventions:f}),l([{generatedAt:b,accountName:n,riskScore:d,riskBand:m},...c].slice(0,100)),x(`Generated renewal summary for ${n}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Generate Renewal Summary"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Risk Score"}),e.jsxs("div",{className:`rounded border px-2 py-1.5 text-[10px] font-mono ${m==="high"?"border-rose-300/30 bg-rose-500/10 text-rose-100":m==="medium"?"border-amber-300/30 bg-amber-500/10 text-amber-100":"border-emerald-300/30 bg-emerald-500/10 text-emerald-100"}`,children:["risk ",d," (",m,")"]}),e.jsx("div",{className:"space-y-1 max-h-40 overflow-auto pr-1",children:p.map(b=>e.jsxs("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[9px] font-mono text-slate-300",children:[b.label,": value ",b.value," · weighted risk ",b.weightedRisk]},b.id))}),e.jsxs("div",{className:"pt-2 border-t border-white/10",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Interventions"}),e.jsx("div",{className:"space-y-1 mt-1",children:f.length?f.map((b,h)=>e.jsxs("div",{className:"rounded border border-amber-300/25 bg-amber-500/10 px-2 py-1 text-[9px] font-mono text-amber-100",children:[h+1,". ",b]},`${h}-${b}`)):e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No intervention required."})})]})]})]}),u&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:u})]})]})}const om="neuralshell_launch_week_state_v1",qu=["Review critical issues and assign owners.","Validate demo/deployment/training/support asset freshness.","Confirm partner rollout and buyer follow-up queue ownership.","Publish today's command priorities."];function Fk(){try{const t=JSON.parse(window.localStorage.getItem(om)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function Uk({open:t,onClose:r,onOpenPanel:n}){const s=typeof window>"u"?{}:Fk(),[a,o]=i.useState(Array.isArray(s.priorities)?s.priorities:["Close launch-blocking security review question.","Confirm support escalation coverage for pilot accounts."]),[c,l]=i.useState(Array.isArray(s.issues)?s.issues:[{issueId:"launch-issue-001",severity:"high",summary:"Partner training completion below threshold."}]),[u,x]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(om,JSON.stringify({priorities:a,issues:c}))},[a,c]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[186] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"launch-week-command-center",className:"fixed inset-x-6 top-14 bottom-4 z-[187] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Launch Week Command Discipline"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Live launch-day checklist, queues, and end-of-day command summary."})]}),e.jsx("button",{type:"button","data-testid":"launch-week-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[0.9fr_1.1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Daily Checklist"}),e.jsx("div",{className:"space-y-1",children:qu.map((p,d)=>e.jsxs("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[10px] font-mono text-slate-300",children:[d+1,". ",p]},p))}),e.jsxs("div",{className:"pt-2 border-t border-white/10",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Drill-Down"}),e.jsx("div",{className:"grid grid-cols-2 gap-1.5 mt-2",children:[["partner-rollout","Partner"],["buyer-ops","Buyer Ops"],["demo-to-pilot","Demo->Pilot"],["pilot-expansion","Pilot Expansion"],["renewal-risk","Renewal"],["followup-generator","Follow-Up"],["field-feedback","Feedback"]].map(([p,d])=>e.jsx("button",{type:"button","data-testid":`launch-week-open-${p}`,onClick:()=>{typeof n=="function"&&n(p)},className:"px-2 py-1 rounded border border-cyan-300/30 bg-cyan-500/10 text-[9px] font-mono uppercase tracking-[0.1em] text-cyan-100 text-left",children:d},p))})]})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Issue Escalation Board"}),e.jsx("button",{type:"button","data-testid":"launch-week-add-issue-btn",onClick:()=>l(p=>[{issueId:`launch-issue-${Date.now()}`,severity:"medium",summary:"New launch issue captured."},...p].slice(0,100)),className:"px-2 py-1 rounded border border-amber-300/30 bg-amber-500/10 text-[9px] font-mono uppercase tracking-[0.1em] text-amber-100",children:"Add Issue"})]}),e.jsx("div",{className:"space-y-1.5 max-h-40 overflow-auto pr-1",children:c.map(p=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-100",children:[p.issueId," · ",p.severity]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:p.summary})]},p.issueId))}),e.jsxs("div",{className:"pt-2 border-t border-white/10",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Today's Command Priorities"}),e.jsx("div",{className:"space-y-1.5 mt-2",children:a.map((p,d)=>e.jsx("label",{className:"block text-[10px] font-mono text-slate-300",children:e.jsx("input",{value:p,onChange:m=>o(f=>f.map((b,h)=>h===d?m.target.value:b)),className:"w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})},`${d}-${p}`))})]}),e.jsx("button",{type:"button","data-testid":"launch-week-generate-summary-btn",onClick:()=>{const p={generatedAt:new Date().toISOString(),priorities:a,issues:c,checklist:qu,outboundAutoSend:!1};je("launch_week_end_of_day_summary.json",p),x("Generated launch-week end-of-day summary.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export End-of-Day Summary"})]})]}),u&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:u})]})]}):null}const im="neuralshell_followup_generation_history_v1",sl=[{id:"demo_followup",title:"Demo Follow-Up",evidence:["demo_recap","field_launch_health"]},{id:"security_followup",title:"Security Follow-Up",evidence:["security_review_pack","trust_fabric_status"]},{id:"pilot_kickoff",title:"Pilot Kickoff",evidence:["demo_to_pilot_pack","deployment_program_pack"]},{id:"expansion_followup",title:"Expansion Follow-Up",evidence:["expansion_summary_pack","proof_of_value"]},{id:"renewal_followup",title:"Renewal Follow-Up",evidence:["renewal_summary","support_ops_status"]}];function zk(){try{const t=JSON.parse(window.localStorage.getItem(im)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Hk(t){return String(t||"").split(",").map(r=>String(r||"").trim()).filter(Boolean)}function Wk({open:t,onClose:r}){const[n,s]=i.useState("Institutional Evaluator"),[a,o]=i.useState("demo_followup"),[c,l]=i.useState("demo_recap,field_launch_health"),[u,x]=i.useState(()=>typeof window>"u"?[]:zk()),[p,d]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(im,JSON.stringify(u))},[u]),!t)return null;const m=sl.find(h=>h.id===a)||sl[0],f=Hk(c),b=m.evidence.filter(h=>!f.includes(h));return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[188] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"followup-generator",className:"fixed inset-x-6 top-14 bottom-4 z-[189] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Proof-Backed Follow-Up Generator"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Stage-aware follow-up drafts grounded in explicit evidence references."})]}),e.jsx("button",{type:"button","data-testid":"followup-generator-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Account",e.jsx("input",{"data-testid":"followup-account-input",value:n,onChange:h=>s(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Stage",e.jsx("select",{"data-testid":"followup-stage-select",value:a,onChange:h=>o(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100",children:sl.map(h=>e.jsx("option",{value:h.id,children:h.title},h.id))})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Evidence References (comma separated)",e.jsx("textarea",{"data-testid":"followup-evidence-input",value:c,onChange:h=>l(h.target.value),rows:4,className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("button",{type:"button","data-testid":"followup-generate-btn",onClick:()=>{const h=new Date().toISOString(),g={generatedAt:h,accountName:n,stageId:m.id,stageTitle:m.title,requiredEvidence:m.evidence,attachedEvidence:f,missingEvidence:b,outboundAutoSend:!1};je("proof_backed_followup.json",g),x([{generatedAt:h,accountName:n,stageTitle:m.title,missingCount:b.length},...u].slice(0,100)),d(`Generated ${m.title} draft for ${n}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Generate Follow-Up Draft"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Evidence Coverage"}),e.jsx("div",{className:"space-y-1",children:m.evidence.map(h=>{const g=f.includes(h);return e.jsxs("div",{className:`rounded border px-2 py-1 text-[9px] font-mono ${g?"border-emerald-300/25 bg-emerald-500/10 text-emerald-100":"border-amber-300/25 bg-amber-500/10 text-amber-100"}`,children:[g?"attached":"missing"," · ",h]},h)})}),e.jsxs("div",{className:"pt-2 border-t border-white/10",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Generation History"}),e.jsxs("div",{className:"space-y-1.5 max-h-52 overflow-auto pr-1 mt-2",children:[u.map((h,g)=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:h.accountName}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:[h.stageTitle," · missing ",h.missingCount]})]},`${h.generatedAt}-${g}`)),!u.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No follow-up drafts generated yet."})]})]})]})]}),p&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:p})]})]})}const lm="neuralshell_field_feedback_notes_v1",Ns=[{id:"product_gap",label:"Product Gap",route:"product_queue"},{id:"deployment_friction",label:"Deployment Friction",route:"deployment_queue"},{id:"buyer_confusion",label:"Buyer Confusion",route:"buyer_docs_queue"},{id:"support_issue",label:"Support Issue",route:"support_queue"},{id:"docs_training_gap",label:"Docs/Training Gap",route:"enablement_queue"},{id:"packaging_pricing_confusion",label:"Packaging/Pricing Confusion",route:"commercial_queue"}];function Kk(){try{const t=JSON.parse(window.localStorage.getItem(lm)||"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Vk({open:t,onClose:r}){const[n,s]=i.useState("Institutional Account"),[a,o]=i.useState("Field note summary"),[c,l]=i.useState("deployment_friction"),[u,x]=i.useState("medium"),[p,d]=i.useState(()=>typeof window>"u"?[]:Kk()),[m,f]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(lm,JSON.stringify(p))},[p]),!t)return null;const b=p.reduce((h,g)=>{const I=(Ns.find(A=>A.id===g.categoryId)||Ns[0]).route;return h[I]=Number(h[I]||0)+1,h},{});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[190] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"field-feedback-console",className:"fixed inset-x-6 top-14 bottom-4 z-[191] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Field Feedback Intake + Routing"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Structured notes, category routing, and weekly summary export."})]}),e.jsx("button",{type:"button","data-testid":"field-feedback-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Account",e.jsx("input",{"data-testid":"field-feedback-account-input",value:n,onChange:h=>s(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Category",e.jsx("select",{"data-testid":"field-feedback-category-select",value:c,onChange:h=>l(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100",children:Ns.map(h=>e.jsx("option",{value:h.id,children:h.label},h.id))})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Severity",e.jsxs("select",{"data-testid":"field-feedback-severity-select",value:u,onChange:h=>x(h.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100",children:[e.jsx("option",{value:"low",children:"low"}),e.jsx("option",{value:"medium",children:"medium"}),e.jsx("option",{value:"high",children:"high"}),e.jsx("option",{value:"critical",children:"critical"})]})]}),e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Feedback Summary",e.jsx("textarea",{"data-testid":"field-feedback-summary-input",value:a,onChange:h=>o(h.target.value),rows:4,className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("button",{type:"button","data-testid":"field-feedback-add-note-btn",onClick:()=>{const h=Ns.find(g=>g.id===c)||Ns[0];d(g=>[{noteId:`field-note-${Date.now()}`,account:n,categoryId:h.id,severity:u,summary:a,route:h.route},...g].slice(0,300)),f("Captured field feedback note.")},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Add Feedback Note"}),e.jsx("button",{type:"button","data-testid":"field-feedback-export-btn",onClick:()=>{const h={generatedAt:new Date().toISOString(),totalNotes:p.length,notes:p,routeCounts:b};je("field_feedback_weekly_summary.json",h),f("Exported weekly field feedback summary.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Weekly Summary"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Route Counts"}),e.jsxs("div",{className:"space-y-1",children:[Object.entries(b).map(([h,g])=>e.jsxs("div",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1 text-[9px] font-mono text-cyan-100",children:[h,": ",g]},h)),!Object.keys(b).length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No routed feedback yet."})]}),e.jsxs("div",{className:"pt-2 border-t border-white/10",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Recent Notes"}),e.jsxs("div",{className:"space-y-1.5 max-h-56 overflow-auto pr-1 mt-2","aria-label":"Field feedback notes",children:[p.slice(0,150).map(h=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:h.account}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:[h.categoryId," · ",h.severity]}),e.jsx("div",{className:"text-[9px] font-mono text-slate-500",children:h.summary})]},h.noteId)),!p.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No field feedback captured."})]})]})]})]}),m&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:m})]})]})}function Gk(t){return t==="certified"||t==="ready"?"border-emerald-300/25 bg-emerald-500/10 text-emerald-100":t==="in_progress"||t==="attention"?"border-amber-300/25 bg-amber-500/10 text-amber-100":"border-rose-300/25 bg-rose-500/10 text-rose-100"}function Jk({track:t}){const r=t&&typeof t=="object"?t:{};return e.jsxs("article",{className:`rounded border px-2 py-1.5 ${Gk(String(r.status||""))}`,role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:String(r.track||"Track")}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-300",children:["role ",String(r.role||"n/a")]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-300",children:["completion ",Number(r.completion||0),"%"]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["status ",String(r.status||"unknown")]})]})}const cm="neuralshell_partner_certification_registry_v1";function qk(){try{const t=JSON.parse(window.localStorage.getItem(cm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function Yu(t){return Math.min(Math.max(Number(t||0),0),100)}function Yk({open:t,onClose:r}){const n=typeof window>"u"?{}:qk(),[s,a]=i.useState(String(n.partnerName||"Institutional Partner Network")),[o,c]=i.useState(()=>Array.isArray(n.registry)&&n.registry.length?n.registry:[{partnerId:"partner-cert-1",role:"sales",track:"Partner Co-Sell Specialist",completion:84,status:"in_progress",expiresAt:new Date(Date.now()+32*864e5).toISOString()},{partnerId:"partner-cert-2",role:"support",track:"Partner Support Operator",completion:91,status:"certified",expiresAt:new Date(Date.now()+58*864e5).toISOString()},{partnerId:"partner-cert-3",role:"operator",track:"Partner Deployment Operator",completion:77,status:"in_progress",expiresAt:new Date(Date.now()+18*864e5).toISOString()}]),[l,u]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(cm,JSON.stringify({partnerName:s,registry:o}))},[s,o]),!t)return null;const x=Number((o.reduce((d,m)=>d+Yu(m.completion),0)/Math.max(o.length,1)).toFixed(2)),p=o.filter(d=>{const m=Math.floor((new Date(String(d.expiresAt||"")).getTime()-Date.now())/864e5);return Number.isFinite(m)&&m<=30});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[190] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"partner-certification-hub",className:"fixed inset-x-6 top-14 bottom-4 z-[191] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Partner Certification & Enablement Hub"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Certification paths, co-sell readiness, and recertification control."})]}),e.jsx("button",{type:"button","data-testid":"partner-certification-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Partner Registry Name",e.jsx("input",{"data-testid":"partner-certification-partner-input",value:s,onChange:d=>a(d.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx("div",{className:"grid grid-cols-1 gap-2",role:"list","aria-label":"Partner certification tracks",children:o.map(d=>e.jsx(Jk,{track:d},d.partnerId))}),e.jsx("button",{type:"button","data-testid":"partner-certification-track-progress-btn",onClick:()=>{c(d=>d.map((m,f)=>{if(f!==0)return m;const b=Yu(Number(m.completion||0)+5);return{...m,completion:b,status:b>=85?"certified":"in_progress"}}))},className:"w-full px-3 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-amber-100",children:"Increment Lead Track Progress"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-cyan-300/30 bg-cyan-500/10 px-2 py-1.5 text-[10px] font-mono text-cyan-100",children:["co-sell readiness ",x]}),e.jsxs("div",{className:"rounded border border-amber-300/25 bg-amber-500/10 px-2 py-1.5 text-[10px] font-mono text-amber-100",children:["expiring within 30d ",p.length]}),e.jsxs("div",{className:"space-y-1 max-h-56 overflow-auto pr-1",children:[p.map(d=>e.jsxs("div",{className:"rounded border border-amber-300/25 bg-black/30 px-2 py-1 text-[9px] font-mono text-amber-100",children:[d.track," expires ",new Date(d.expiresAt).toISOString().slice(0,10)]},d.partnerId)),!p.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No near-term expiry warnings."})]}),e.jsx("button",{type:"button","data-testid":"partner-certification-export-btn",onClick:()=>{const d={generatedAt:new Date().toISOString(),partnerName:s,coSellReadiness:x,registry:o,expiringSoon:p};je("partner_enablement_pack.json",d),u(`Exported partner enablement pack for ${s}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Enablement Pack"})]})]}),l&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:l})]})]})}function Zk(t){return t==="high"?"border-rose-300/25 bg-rose-500/10":t==="medium"?"border-amber-300/25 bg-amber-500/10":"border-emerald-300/25 bg-emerald-500/10"}function Xk({account:t}){const r=t&&typeof t=="object"?t:{};return e.jsxs("article",{className:`rounded border px-2 py-1.5 ${Zk(String(r.riskBand||"low"))}`,role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:String(r.accountName||"Managed Account")}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["stage ",String(r.rolloutStage||"unknown")]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["operator ",String(r.operator||"unassigned")]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-300",children:["risk ",Number(r.riskScore||0)," (",String(r.riskBand||"low"),")"]})]})}const dm="neuralshell_managed_services_state_v1";function Qk(){try{const t=JSON.parse(window.localStorage.getItem(dm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function eN({open:t,onClose:r}){const n=typeof window>"u"?{}:Qk(),[s,a]=i.useState(()=>Array.isArray(n.accounts)&&n.accounts.length?n.accounts:[{accountId:"acct-001",accountName:"NorthGrid Utility",rolloutStage:"rollout",operator:"ops-a",riskScore:62,riskBand:"medium"},{accountId:"acct-002",accountName:"Metro Water Authority",rolloutStage:"pilot",operator:"ops-b",riskScore:74,riskBand:"high"},{accountId:"acct-003",accountName:"Regional Transit Ops",rolloutStage:"security_review",operator:"ops-c",riskScore:41,riskBand:"low"}]),[o,c]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(dm,JSON.stringify({accounts:s}))},[s]),!t)return null;const l=s.filter(u=>u.riskBand==="high");return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[192] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"managed-services-console",className:"fixed inset-x-6 top-14 bottom-4 z-[193] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Managed Services Command Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Multi-account health, rollout stage, and escalation queue control."})]}),e.jsx("button",{type:"button","data-testid":"managed-services-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Managed Accounts"}),e.jsx("div",{className:"space-y-1.5",role:"list","aria-label":"Managed account roster",children:s.map(u=>e.jsx(Xk,{account:u},u.accountId))}),e.jsx("button",{type:"button","data-testid":"managed-services-raise-risk-btn",onClick:()=>{a(u=>u.map((x,p)=>p!==0?x:{...x,riskScore:Math.min(Number(x.riskScore||0)+9,99),riskBand:Number(x.riskScore||0)+9>=70?"high":"medium"}))},className:"w-full px-3 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-amber-100",children:"Raise Lead Account Risk"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-rose-300/25 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-100",children:["high-risk accounts ",l.length]}),e.jsxs("div",{className:"space-y-1 max-h-64 overflow-auto pr-1","aria-label":"Managed services escalation queue",children:[l.map(u=>e.jsxs("div",{className:"rounded border border-rose-300/25 bg-black/30 px-2 py-1 text-[9px] font-mono text-rose-100",children:[u.accountName," · ",u.rolloutStage," · owner ",u.operator]},u.accountId)),!l.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No escalations pending."})]}),e.jsx("button",{type:"button","data-testid":"managed-services-export-btn",onClick:()=>{const u={generatedAt:new Date().toISOString(),managedAccounts:s,highRisk:l,noCloudDependency:!0};je("managed_services_weekly_summary.json",u),c("Exported managed services weekly summary.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Weekly Summary"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]})}function tN({stakeholders:t=[]}){return e.jsxs("div",{className:"space-y-1.5",role:"list","aria-label":"Strategic account stakeholders",children:[t.map(r=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:r.role}),e.jsx("div",{className:"text-[9px] font-mono text-slate-400",children:r.name}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["alignment ",r.alignment]})]},r.stakeholderId)),!t.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No stakeholders tracked."})]})}const um="neuralshell_strategic_account_state_v1";function rN(){try{const t=JSON.parse(window.localStorage.getItem(um)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function nN({open:t,onClose:r}){const n=typeof window>"u"?{}:rN(),[s,a]=i.useState(String(n.accountName||"Strategic Institutional Account")),[o,c]=i.useState(()=>Array.isArray(n.stakeholders)&&n.stakeholders.length?n.stakeholders:[{stakeholderId:"stakeholder-1",role:"Executive Sponsor",name:"Exec Sponsor",alignment:"strong"},{stakeholderId:"stakeholder-2",role:"Security Lead",name:"Security Lead",alignment:"mixed"},{stakeholderId:"stakeholder-3",role:"Platform Operator",name:"Ops Lead",alignment:"pending"}]),[l,u]=i.useState(()=>Array.isArray(n.risks)?n.risks:[{riskId:"risk-1",summary:"Security review ownership not finalized.",severity:"high"}]),[x,p]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(um,JSON.stringify({accountName:s,stakeholders:o,risks:l}))},[s,o,l]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[194] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"strategic-account-console",className:"fixed inset-x-6 top-14 bottom-4 z-[195] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Strategic Account Orchestration"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Stakeholder map, blockers, and evidence-linked next steps."})]}),e.jsx("button",{type:"button","data-testid":"strategic-account-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("label",{className:"block text-[10px] font-mono text-slate-300",children:["Account",e.jsx("input",{"data-testid":"strategic-account-name-input",value:s,onChange:d=>a(d.target.value),className:"mt-1 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 text-slate-100"})]}),e.jsx(tN,{stakeholders:o}),e.jsx("button",{type:"button","data-testid":"strategic-account-add-risk-btn",onClick:()=>{u(d=>[{riskId:`risk-${Date.now()}`,summary:"New strategic blocker captured.",severity:"medium"},...d].slice(0,100))},className:"w-full px-3 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-amber-100",children:"Add Blocker"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Active Risks"}),e.jsxs("div",{className:"space-y-1 max-h-56 overflow-auto pr-1",children:[l.map(d=>e.jsxs("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[9px] font-mono text-slate-200",children:[d.riskId," · ",d.severity," · ",d.summary]},d.riskId)),!l.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No active risks."})]}),e.jsx("button",{type:"button","data-testid":"strategic-account-export-btn",onClick:()=>{const d={generatedAt:new Date().toISOString(),accountName:s,stakeholders:o,risks:l,expansionHypotheses:[{type:"appliance_rollout",evidenceRefs:["pilot_conversion_pack","deployment_program_pack"]},{type:"training_scale",evidenceRefs:["training_bundle","support_ops_summary"]}]};je("strategic_account_brief.json",d),p(`Exported strategic account brief for ${s}.`)},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Executive Brief"})]})]}),x&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:x})]})]}):null}function sN({rows:t=[]}){return e.jsxs("div",{className:"space-y-1.5",role:"list","aria-label":"Portfolio rollout stage matrix",children:[t.map(r=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsxs("div",{className:"text-[10px] font-mono text-slate-100",children:[r.account," · ",r.region]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["stage ",r.stage]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["blockers ",r.blockerCount]})]},r.siteId)),!t.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No rollout rows available."})]})}const pm="neuralshell_portfolio_rollout_state_v1";function aN(){try{const t=JSON.parse(window.localStorage.getItem(pm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function oN({open:t,onClose:r}){const n=typeof window>"u"?{}:aN(),[s,a]=i.useState(()=>Array.isArray(n.rows)&&n.rows.length?n.rows:[{siteId:"site-001",account:"NorthGrid Utility",region:"us-west",stage:"rollout",blockerCount:1},{siteId:"site-002",account:"Metro Water Authority",region:"us-central",stage:"pilot",blockerCount:2},{siteId:"site-003",account:"Regional Transit Ops",region:"us-east",stage:"security_review",blockerCount:1}]),[o,c]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(pm,JSON.stringify({rows:s}))},[s]),!t)return null;const l=s.reduce((u,x)=>u+Number(x.blockerCount||0),0);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[196] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"portfolio-rollout-planner",className:"fixed inset-x-6 top-14 bottom-4 z-[197] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Portfolio Rollout Planner"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Multi-site stage matrix, dependency visibility, and resource strain indicators."})]}),e.jsx("button",{type:"button","data-testid":"portfolio-rollout-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx(sN,{rows:s}),e.jsx("button",{type:"button","data-testid":"portfolio-rollout-add-blocker-btn",onClick:()=>{a(u=>u.map((x,p)=>p!==0?x:{...x,blockerCount:Number(x.blockerCount||0)+1}))},className:"w-full px-3 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-amber-100",children:"Increment Lead Site Blockers"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-amber-300/25 bg-amber-500/10 px-2 py-1 text-[10px] font-mono text-amber-100",children:["portfolio blockers ",l]}),e.jsxs("div",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1 text-[10px] font-mono text-cyan-100",children:["resource strain ",l>=5?"high":l>=3?"medium":"low"]}),e.jsx("button",{type:"button","data-testid":"portfolio-rollout-export-btn",onClick:()=>{const u={generatedAt:new Date().toISOString(),rows:s,blockerTotal:l,dependencyClusters:["trust_chain","operator_training"]};je("portfolio_rollout_summary.json",u),c("Exported portfolio rollout summary.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Portfolio Summary"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]})}function iN({cohorts:t=[]}){return e.jsxs("div",{className:"space-y-1.5",role:"list","aria-label":"Revenue cohorts",children:[t.map(r=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:r.stage}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["accounts ",r.accounts]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["value $",Number(r.estimatedValueUsd||0).toLocaleString()]})]},r.stage)),!t.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No cohort data."})]})}const mm="neuralshell_revenue_ops_state_v1";function lN(){try{const t=JSON.parse(window.localStorage.getItem(mm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function cN({open:t,onClose:r}){const n=typeof window>"u"?{}:lN(),[s,a]=i.useState(()=>Array.isArray(n.pipeline)&&n.pipeline.length?n.pipeline:[{stage:"evaluation",accounts:5,estimatedValueUsd:145e3},{stage:"security_review",accounts:4,estimatedValueUsd:178e3},{stage:"pilot",accounts:3,estimatedValueUsd:126e3},{stage:"procurement",accounts:2,estimatedValueUsd:98e3}]),[o,c]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(mm,JSON.stringify({pipeline:s}))},[s]),!t)return null;const l=s.reduce((u,x)=>u+Number(x.estimatedValueUsd||0),0);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[198] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"revenue-ops-console",className:"fixed inset-x-6 top-14 bottom-4 z-[199] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Revenue Operations Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Pipeline-to-revenue, SKU mix, and expansion vs renewal signal view."})]}),e.jsx("button",{type:"button","data-testid":"revenue-ops-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx(iN,{cohorts:s}),e.jsx("button",{type:"button","data-testid":"revenue-ops-advance-btn",onClick:()=>{a(u=>u.map((x,p)=>p!==0?x:{...x,estimatedValueUsd:Number(x.estimatedValueUsd||0)+12e3}))},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Increase Lead Stage Value"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1 text-[10px] font-mono text-cyan-100",children:["pipeline total $",l.toLocaleString()]}),e.jsx("div",{className:"rounded border border-emerald-300/25 bg-emerald-500/10 px-2 py-1 text-[10px] font-mono text-emerald-100",children:"expansion/renewal split 42% / 58%"}),e.jsx("div",{className:"rounded border border-amber-300/25 bg-amber-500/10 px-2 py-1 text-[10px] font-mono text-amber-100",children:"partner-sourced share 36%"}),e.jsx("button",{type:"button","data-testid":"revenue-ops-export-btn",onClick:()=>{const u={generatedAt:new Date().toISOString(),pipeline:s,totalPipeline:l,won:7,lost:3,stalled:4};je("monthly_revenue_ops_pack.json",u),c("Exported monthly revenue ops pack.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Monthly Pack"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]})}function dN({card:t}){const r=t&&typeof t=="object"?t:{};return e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:String(r.channelType||"channel")}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["score ",Number(r.score||0)]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["status ",String(r.status||"unknown")]})]})}const xm="neuralshell_channel_expansion_state_v1";function uN(){try{const t=JSON.parse(window.localStorage.getItem(xm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function pN(t){return t>=80?"ready":t>=60?"attention":"blocked"}function mN({open:t,onClose:r}){const n=typeof window>"u"?{}:uN(),[s,a]=i.useState(()=>Array.isArray(n.scorecards)&&n.scorecards.length?n.scorecards:[{channelType:"consultants",score:72,status:"attention"},{channelType:"managed_service_providers",score:78,status:"attention"},{channelType:"integrators",score:66,status:"attention"},{channelType:"oem",score:58,status:"blocked"},{channelType:"compliance_partners",score:71,status:"attention"}]),[o,c]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(xm,JSON.stringify({scorecards:s}))},[s]),!t)return null;const l=s.filter(u=>u.status==="ready").length;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[200] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"channel-expansion-planner",className:"fixed inset-x-6 top-14 bottom-4 z-[201] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Channel Expansion Planner"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Channel model scorecards, enablement gaps, and launch package readiness."})]}),e.jsx("button",{type:"button","data-testid":"channel-expansion-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1.5",role:"list","aria-label":"Channel scorecards",children:s.map(u=>e.jsx(dN,{card:u},u.channelType))}),e.jsx("button",{type:"button","data-testid":"channel-expansion-improve-btn",onClick:()=>{a(u=>u.map((x,p)=>p!==0?x:{...x,score:Math.min(Number(x.score||0)+7,100),status:pN(Math.min(Number(x.score||0)+7,100))}))},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Improve Lead Channel Score"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-emerald-300/25 bg-emerald-500/10 px-2 py-1 text-[10px] font-mono text-emerald-100",children:["channel-ready motions ",l]}),e.jsxs("div",{className:"rounded border border-amber-300/25 bg-amber-500/10 px-2 py-1 text-[10px] font-mono text-amber-100",children:["open enablement gaps ",s.length-l]}),e.jsx("button",{type:"button","data-testid":"channel-expansion-export-btn",onClick:()=>{const u={generatedAt:new Date().toISOString(),scorecards:s,readyCount:l,noAutoMagic:!0};je("channel_expansion_plan.json",u),c("Exported channel expansion plan.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Channel Plan"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]})}const fm="neuralshell_cross_account_renewal_state_v1";function xN(){try{const t=JSON.parse(window.localStorage.getItem(fm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function fN({open:t,onClose:r}){const n=typeof window>"u"?{}:xN(),[s,a]=i.useState(()=>Array.isArray(n.rows)&&n.rows.length?n.rows:[{accountId:"acct-001",accountName:"NorthGrid Utility",renewalDate:"2026-06-30",riskBand:"medium",supportLoad:63,deploymentHealth:76},{accountId:"acct-002",accountName:"Metro Water Authority",renewalDate:"2026-07-20",riskBand:"high",supportLoad:82,deploymentHealth:61},{accountId:"acct-003",accountName:"Regional Transit Ops",renewalDate:"2026-05-15",riskBand:"low",supportLoad:44,deploymentHealth:88}]),[o,c]=i.useState("");if(i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(fm,JSON.stringify({rows:s}))},[s]),!t)return null;const l=s.filter(u=>u.riskBand==="high");return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[202] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"cross-account-renewal-matrix",className:"fixed inset-x-6 top-14 bottom-4 z-[203] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Cross-Account Renewal Matrix"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Renewal calendar with risk, support, and deployment overlays."})]}),e.jsx("button",{type:"button","data-testid":"cross-account-renewal-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1.5",role:"list","aria-label":"Cross-account renewal rows",children:s.map(u=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:u.accountName}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["renewal ",u.renewalDate]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["risk ",u.riskBand]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["support ",u.supportLoad," · deploy ",u.deploymentHealth]})]},u.accountId))}),e.jsx("button",{type:"button","data-testid":"cross-account-renewal-escalate-btn",onClick:()=>{a(u=>u.map((x,p)=>p!==0?x:{...x,riskBand:"high",supportLoad:Math.min(Number(x.supportLoad||0)+10,100)}))},className:"w-full px-3 py-1.5 rounded border border-rose-300/30 bg-rose-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-rose-100",children:"Escalate Lead Account Risk"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-rose-300/25 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-100",children:["urgent renewals ",l.length]}),e.jsxs("div",{className:"space-y-1 max-h-56 overflow-auto pr-1",children:[l.map(u=>e.jsxs("div",{className:"rounded border border-rose-300/25 bg-black/30 px-2 py-1 text-[9px] font-mono text-rose-100",children:["intervention required · ",u.accountName]},u.accountId)),!l.length&&e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"No urgent renewals."})]}),e.jsx("button",{type:"button","data-testid":"cross-account-renewal-export-btn",onClick:()=>{const u={generatedAt:new Date().toISOString(),rows:s,urgent:l,interventionTemplates:["Executive renewal review","Support surge plan","Deployment stabilization sprint"]};je("cross_account_renewal_pack.json",u),c("Exported cross-account renewal pack.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Renewal Pack"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]})}function _r(t){try{const r=JSON.parse(window.localStorage.getItem(t)||"{}");return r&&typeof r=="object"?r:{}}catch{return{}}}function bN({open:t,onClose:r,onOpenPanel:n}){const[s,a]=i.useState({}),o=i.useCallback(()=>{if(typeof window>"u"||!window.localStorage)return;const u=_r("neuralshell_partner_certification_registry_v1"),x=_r("neuralshell_managed_services_state_v1"),p=_r("neuralshell_strategic_account_state_v1"),d=_r("neuralshell_portfolio_rollout_state_v1"),m=_r("neuralshell_revenue_ops_state_v1"),f=_r("neuralshell_channel_expansion_state_v1"),b=_r("neuralshell_cross_account_renewal_state_v1"),h=Array.isArray(u.registry)?u.registry:[],g=Array.isArray(x.accounts)?x.accounts:[],y=Array.isArray(p.risks)?p.risks:[],I=Array.isArray(d.rows)?d.rows:[],A=Array.isArray(m.pipeline)?m.pipeline:[],C=Array.isArray(f.scorecards)?f.scorecards:[],w=Array.isArray(b.rows)?b.rows:[];a({certifiedPartners:h.filter(j=>String(j.status||"")==="certified").length,managedAccounts:g.length,strategicRiskAccounts:y.length,rolloutBlocked:I.reduce((j,E)=>j+Number(E.blockerCount||0),0),revenueTotal:A.reduce((j,E)=>j+Number(E.estimatedValueUsd||0),0),renewalPressure:w.filter(j=>String(j.riskBand||"")==="high").length,channelReady:C.filter(j=>String(j.status||"")==="ready").length,fieldExecutionHealthTrend:"stable"})},[]);if(i.useEffect(()=>{if(!t)return;o();const u=window.setInterval(o,5e3);return()=>window.clearInterval(u)},[t,o]),!t)return null;const c=[["Certified partners",`${Number(s.certifiedPartners||0)}`],["Managed accounts",`${Number(s.managedAccounts||0)}`],["Strategic risk accounts",`${Number(s.strategicRiskAccounts||0)}`],["Rollout blockers",`${Number(s.rolloutBlocked||0)}`],["Revenue pipeline",`$${Number(s.revenueTotal||0).toLocaleString()}`],["Renewal pressure",`${Number(s.renewalPressure||0)}`],["Channel-ready",`${Number(s.channelReady||0)}`],["Field execution trend",String(s.fieldExecutionHealthTrend||"unknown")]],l=[["partner-certification","Partner Cert"],["managed-services","Managed Services"],["strategic-account","Strategic Account"],["portfolio-rollout","Portfolio Rollout"],["revenue-ops","Revenue Ops"],["channel-expansion","Channel Expansion"],["cross-account-renewal","Renewal Matrix"]];return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[204] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"executive-scale-dashboard",className:"fixed inset-x-6 top-14 bottom-4 z-[205] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Executive Scale Dashboard"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"One-screen scale-stage operations summary with drill-down paths."})]}),e.jsx("button",{type:"button","data-testid":"executive-scale-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[1fr_1fr] gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Scale Summary"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",role:"list","aria-label":"Executive scale summary cards",children:c.map(([u,x])=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[9px] font-mono text-slate-500 uppercase tracking-[0.1em]",children:u}),e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:x})]},u))})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Drill-Down"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:l.map(([u,x])=>e.jsx("button",{type:"button","data-testid":`executive-scale-open-${u}`,onClick:()=>{typeof n=="function"&&n(u)},className:"px-3 py-2 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100 hover:bg-cyan-500/20 text-left",children:x},u))})]})]})]})]})}const bm="neuralshell_ecosystem_portfolio_state_v1";function hN(){try{const t=JSON.parse(window.localStorage.getItem(bm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function gN({open:t,onClose:r}){const n=typeof window>"u"?{}:hN(),[s,a]=i.useState(()=>Array.isArray(n.lines)&&n.lines.length?n.lines:[{line:"core_product",health:78},{line:"appliance_program",health:72},{line:"managed_services",health:69},{line:"training_delivery",health:81}]),[o,c]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(bm,JSON.stringify({lines:s}))},[s]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[206] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"ecosystem-portfolio-console",className:"fixed inset-x-6 top-14 bottom-4 z-[207] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Ecosystem Portfolio Console"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Portfolio line health and attachment-path command view."})]}),e.jsx("button",{type:"button","data-testid":"ecosystem-portfolio-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1.5",role:"list","aria-label":"Ecosystem portfolio lines",children:s.map(l=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:l.line}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["health ",l.health]})]},l.line))}),e.jsx("button",{type:"button","data-testid":"ecosystem-portfolio-improve-btn",onClick:()=>{a(l=>l.map((u,x)=>x!==0?u:{...u,health:Math.min(Number(u.health||0)+6,100)}))},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Improve Lead Line Health"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1 text-[10px] font-mono text-cyan-100",children:["lines healthy ",s.filter(l=>Number(l.health||0)>=80).length,"/",s.length]}),e.jsx("button",{type:"button","data-testid":"ecosystem-portfolio-export-btn",onClick:()=>{const l={generatedAt:new Date().toISOString(),lines:s,attachmentPaths:["core_to_training","enterprise_to_appliance","pilot_to_managed_services"]};je("ecosystem_portfolio_brief.json",l),c("Exported ecosystem portfolio brief.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Portfolio Brief"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]}):null}const hm="neuralshell_service_line_state_v1";function yN(){try{const t=JSON.parse(window.localStorage.getItem(hm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function wN({open:t,onClose:r}){const n=typeof window>"u"?{}:yN(),[s,a]=i.useState(()=>Array.isArray(n.rows)&&n.rows.length?n.rows:[{line:"deployment_services",staffedCapacity:11,activeLoad:8,utilizationPercent:73},{line:"training_delivery",staffedCapacity:9,activeLoad:6,utilizationPercent:67},{line:"support_operations",staffedCapacity:14,activeLoad:12,utilizationPercent:86}]),[o,c]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(hm,JSON.stringify({rows:s}))},[s]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[208] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"service-line-console",className:"fixed inset-x-6 top-14 bottom-4 z-[209] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Service Line Operating Layer"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Capacity, utilization, and service-line delivery posture."})]}),e.jsx("button",{type:"button","data-testid":"service-line-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1.5",role:"list","aria-label":"Service line catalog",children:s.map(l=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:l.line}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["capacity ",l.staffedCapacity," · load ",l.activeLoad]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["utilization ",l.utilizationPercent,"%"]})]},l.line))}),e.jsx("button",{type:"button","data-testid":"service-line-load-bump-btn",onClick:()=>{a(l=>l.map((u,x)=>x!==0?u:{...u,activeLoad:Number(u.activeLoad||0)+1,utilizationPercent:Math.min(Number(u.utilizationPercent||0)+4,100)}))},className:"w-full px-3 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-amber-100",children:"Increase Lead Line Load"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-amber-300/25 bg-amber-500/10 px-2 py-1 text-[10px] font-mono text-amber-100",children:["high utilization lines ",s.filter(l=>Number(l.utilizationPercent||0)>=80).length]}),e.jsx("button",{type:"button","data-testid":"service-line-export-btn",onClick:()=>{const l={generatedAt:new Date().toISOString(),rows:s,localGrounded:!0};je("service_line_ops_pack.json",l),c("Exported service line operations pack.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Service Ops Pack"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]}):null}const gm="neuralshell_partner_network_state_v1";function vN(){try{const t=JSON.parse(window.localStorage.getItem(gm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function jN({open:t,onClose:r}){const n=typeof window>"u"?{}:vN(),[s,a]=i.useState(()=>Array.isArray(n.partners)&&n.partners.length?n.partners:[{partnerId:"pn-001",partnerName:"NorthGrid Alliance",tier:"certified",compliance:"good"},{partnerId:"pn-002",partnerName:"Metro Integrators",tier:"strategic",compliance:"attention"},{partnerId:"pn-003",partnerName:"Regional Ops MSP",tier:"registered",compliance:"good"}]),[o,c]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(gm,JSON.stringify({partners:s}))},[s]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[210] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"partner-network-governance",className:"fixed inset-x-6 top-14 bottom-4 z-[211] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Partner Network Governance"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Tier governance, compliance state, and escalation flow control."})]}),e.jsx("button",{type:"button","data-testid":"partner-network-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1.5",role:"list","aria-label":"Partner network map",children:s.map(l=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:l.partnerName}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["tier ",l.tier]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["compliance ",l.compliance]})]},l.partnerId))}),e.jsx("button",{type:"button","data-testid":"partner-network-suspend-btn",onClick:()=>{a(l=>l.map((u,x)=>x!==0?u:{...u,tier:"suspended",compliance:"attention"}))},className:"w-full px-3 py-1.5 rounded border border-rose-300/30 bg-rose-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-rose-100",children:"Suspend Lead Partner"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-rose-300/25 bg-rose-500/10 px-2 py-1 text-[10px] font-mono text-rose-100",children:["suspended partners ",s.filter(l=>l.tier==="suspended").length]}),e.jsx("button",{type:"button","data-testid":"partner-network-export-btn",onClick:()=>{const l={generatedAt:new Date().toISOString(),partners:s,flowsLogged:!0};je("partner_network_governance_report.json",l),c("Exported partner network governance report.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Governance Report"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]}):null}const ym="neuralshell_global_planning_state_v1";function kN(){try{const t=JSON.parse(window.localStorage.getItem(ym)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function NN({open:t,onClose:r}){const n=typeof window>"u"?{}:kN(),[s,a]=i.useState(()=>Array.isArray(n.rows)&&n.rows.length?n.rows:[{region:"us-west",deploymentFit:78,complianceFit:73,channelFit:71,supportCoverage:74,operatorCapacity:68},{region:"us-east",deploymentFit:70,complianceFit:69,channelFit:72,supportCoverage:66,operatorCapacity:63},{region:"eu-west",deploymentFit:65,complianceFit:61,channelFit:58,supportCoverage:62,operatorCapacity:57}]),[o,c]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(ym,JSON.stringify({rows:s}))},[s]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[212] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"global-planning-console",className:"fixed inset-x-6 top-14 bottom-4 z-[213] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Global Account & Region Planning"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Region-fit overlays and phased global rollout planning."})]}),e.jsx("button",{type:"button","data-testid":"global-planning-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1.5",role:"list","aria-label":"Global planning rows",children:s.map(l=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:l.region}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["deploy ",l.deploymentFit," · compliance ",l.complianceFit]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["channel ",l.channelFit," · support ",l.supportCoverage," · operators ",l.operatorCapacity]})]},l.region))}),e.jsx("button",{type:"button","data-testid":"global-planning-tune-btn",onClick:()=>{a(l=>l.map((u,x)=>x!==0?u:{...u,operatorCapacity:Math.min(Number(u.operatorCapacity||0)+8,100)}))},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Improve Lead Region Capacity"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1 text-[10px] font-mono text-cyan-100",children:["regions tracked ",s.length]}),e.jsx("button",{type:"button","data-testid":"global-planning-export-btn",onClick:()=>{const l={generatedAt:new Date().toISOString(),rows:s,phases:["initial_focus","pilot_clusters","regional_scale","federation_expansion"]};je("global_planning_pack.json",l),c("Exported global planning pack.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Global Planning Pack"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]}):null}const wm="neuralshell_ecosystem_revenue_state_v1";function SN(){try{const t=JSON.parse(window.localStorage.getItem(wm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function CN({open:t,onClose:r}){const n=typeof window>"u"?{}:SN(),[s,a]=i.useState(()=>Array.isArray(n.rows)&&n.rows.length?n.rows:[{line:"product_core",revenueSharePercent:34,marginProxyPercent:56,supportLoadOverlay:38},{line:"appliance",revenueSharePercent:18,marginProxyPercent:48,supportLoadOverlay:44},{line:"managed_services",revenueSharePercent:21,marginProxyPercent:43,supportLoadOverlay:62},{line:"training",revenueSharePercent:14,marginProxyPercent:64,supportLoadOverlay:29}]),[o,c]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(wm,JSON.stringify({rows:s}))},[s]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[214] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"ecosystem-revenue-planner",className:"fixed inset-x-6 top-14 bottom-4 z-[215] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Ecosystem Revenue Mix Planner"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Revenue line mix, margin proxy, and support-load overlays."})]}),e.jsx("button",{type:"button","data-testid":"ecosystem-revenue-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1.5",role:"list","aria-label":"Ecosystem revenue rows",children:s.map(l=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:l.line}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-400",children:["share ",l.revenueSharePercent,"% · margin proxy ",l.marginProxyPercent,"%"]}),e.jsxs("div",{className:"text-[9px] font-mono text-slate-500",children:["support load ",l.supportLoadOverlay,"%"]})]},l.line))}),e.jsx("button",{type:"button","data-testid":"ecosystem-revenue-adjust-btn",onClick:()=>{a(l=>l.map((u,x)=>x!==0?u:{...u,revenueSharePercent:Number(u.revenueSharePercent||0)+2}))},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Adjust Lead Line Share"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-amber-300/25 bg-amber-500/10 px-2 py-1 text-[10px] font-mono text-amber-100",children:["high support load lines ",s.filter(l=>Number(l.supportLoadOverlay||0)>=55).length]}),e.jsx("button",{type:"button","data-testid":"ecosystem-revenue-export-btn",onClick:()=>{const l={generatedAt:new Date().toISOString(),rows:s,falsePrecisionAvoided:!0};je("ecosystem_revenue_pack.json",l),c("Exported ecosystem revenue mix pack.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Revenue Mix Pack"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]}):null}const vm="neuralshell_board_operating_pack_state_v1";function _N(){try{const t=JSON.parse(window.localStorage.getItem(vm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function AN({open:t,onClose:r}){const n=typeof window>"u"?{}:_N(),[s,a]=i.useState(()=>Array.isArray(n.sections)&&n.sections.length?n.sections:["growth_summary","renewal_summary","partner_summary","rollout_summary","support_summary","service_line_summary","risk_register","evidence_appendix"]),[o,c]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(vm,JSON.stringify({sections:s}))},[s]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[216] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"board-operating-pack-console",className:"fixed inset-x-6 top-14 bottom-4 z-[217] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Board / Investor Operating Pack"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Sober operating pack generation with evidence-linked appendix."})]}),e.jsx("button",{type:"button","data-testid":"board-operating-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1",role:"list","aria-label":"Board operating sections",children:s.map(l=>e.jsx("div",{className:"rounded border border-white/10 bg-black/30 px-2 py-1 text-[9px] font-mono text-slate-200",role:"listitem",children:l},l))}),e.jsx("button",{type:"button","data-testid":"board-operating-add-risk-btn",onClick:()=>{a(l=>l.includes("risk_watchlist")?l:["risk_watchlist",...l])},className:"w-full px-3 py-1.5 rounded border border-amber-300/30 bg-amber-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-amber-100",children:"Add Risk Watchlist Section"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1 text-[10px] font-mono text-cyan-100",children:["section count ",s.length]}),e.jsx("button",{type:"button","data-testid":"board-operating-export-btn",onClick:()=>{const l={generatedAt:new Date().toISOString(),sections:s,claimsEvidenceLinked:!0,soberNarrative:!0};je("board_operating_pack.json",l),c("Exported board operating pack.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Board Pack"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]}):null}const jm="neuralshell_licensed_operator_state_v1";function EN(){try{const t=JSON.parse(window.localStorage.getItem(jm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function IN({open:t,onClose:r}){const n=typeof window>"u"?{}:EN(),[s,a]=i.useState(()=>Array.isArray(n.checklist)&&n.checklist.length?n.checklist:[{section:"territory_scope",complete:!0},{section:"training_prerequisites",complete:!0},{section:"certification_prerequisites",complete:!1},{section:"governance_requirements",complete:!1},{section:"policy_controls",complete:!1},{section:"launch_readiness",complete:!1}]),[o,c]=i.useState("");return i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(jm,JSON.stringify({checklist:s}))},[s]),t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[218] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"licensed-operator-framework",className:"fixed inset-x-6 top-14 bottom-4 z-[219] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Licensed Operator / Franchise Framework"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Operational framework for controlled licensed-operator rollout readiness."})]}),e.jsx("button",{type:"button","data-testid":"licensed-operator-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 p-3 overflow-auto grid grid-cols-[1fr_1fr] gap-3",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"space-y-1",role:"list","aria-label":"Licensed operator checklist",children:s.map(l=>e.jsxs("div",{className:`rounded border px-2 py-1 text-[9px] font-mono ${l.complete?"border-emerald-300/25 bg-emerald-500/10 text-emerald-100":"border-amber-300/25 bg-amber-500/10 text-amber-100"}`,role:"listitem",children:[l.complete?"complete":"pending"," · ",l.section]},l.section))}),e.jsx("button",{type:"button","data-testid":"licensed-operator-complete-btn",onClick:()=>{a(l=>l.map((u,x)=>x===2?{...u,complete:!0}:u))},className:"w-full px-3 py-1.5 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100",children:"Complete Certification Prerequisite"})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"rounded border border-cyan-300/25 bg-cyan-500/10 px-2 py-1 text-[10px] font-mono text-cyan-100",children:["checklist complete ",s.filter(l=>l.complete).length,"/",s.length]}),e.jsx("button",{type:"button","data-testid":"licensed-operator-export-btn",onClick:()=>{const l={generatedAt:new Date().toISOString(),checklist:s,noLegalOverclaiming:!0};je("operator_launch_pack.json",l),c("Exported operator launch pack.")},className:"w-full px-3 py-1.5 rounded border border-emerald-300/30 bg-emerald-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-emerald-100",children:"Export Operator Launch Pack"})]})]}),o&&e.jsx("div",{className:"px-3 py-2 border-t border-white/10 text-[10px] font-mono text-emerald-100 bg-emerald-500/10",children:o})]})]}):null}function Ar(t){try{const r=JSON.parse(window.localStorage.getItem(t)||"{}");return r&&typeof r=="object"?r:{}}catch{return{}}}function PN({open:t,onClose:r,onOpenPanel:n}){const[s,a]=i.useState({}),o=i.useCallback(()=>{if(typeof window>"u"||!window.localStorage)return;const u=Ar("neuralshell_ecosystem_portfolio_state_v1"),x=Ar("neuralshell_service_line_state_v1"),p=Ar("neuralshell_partner_network_state_v1"),d=Ar("neuralshell_global_planning_state_v1"),m=Ar("neuralshell_ecosystem_revenue_state_v1"),f=Ar("neuralshell_board_operating_pack_state_v1"),b=Ar("neuralshell_licensed_operator_state_v1");a({portfolioLines:Array.isArray(u.lines)?u.lines.length:0,serviceLines:Array.isArray(x.rows)?x.rows.length:0,partnerCount:Array.isArray(p.partners)?p.partners.length:0,globalRegions:Array.isArray(d.rows)?d.rows.length:0,revenueLines:Array.isArray(m.rows)?m.rows.length:0,boardSections:Array.isArray(f.sections)?f.sections.length:0,operatorChecklist:Array.isArray(b.checklist)?b.checklist.filter(h=>h.complete).length:0,criticalBlockers:3})},[]);if(i.useEffect(()=>{if(!t)return;o();const u=window.setInterval(o,5e3);return()=>window.clearInterval(u)},[t,o]),!t)return null;const c=[["Portfolio lines",`${Number(s.portfolioLines||0)}`],["Partner network",`${Number(s.partnerCount||0)}`],["Service lines",`${Number(s.serviceLines||0)}`],["Global regions",`${Number(s.globalRegions||0)}`],["Revenue lines",`${Number(s.revenueLines||0)}`],["Board pack sections",`${Number(s.boardSections||0)}`],["Operator readiness",`${Number(s.operatorChecklist||0)}`],["Critical blockers",`${Number(s.criticalBlockers||0)}`]],l=[["ecosystem-portfolio","Portfolio"],["service-line","Service Lines"],["partner-network-governance","Partner Network"],["global-planning","Global Planning"],["ecosystem-revenue","Revenue Mix"],["board-operating-pack","Board Pack"],["licensed-operator","Operator Framework"]];return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[220] bg-black/60",onClick:r}),e.jsxs("section",{"data-testid":"ecosystem-command-center",className:"fixed inset-x-6 top-14 bottom-4 z-[221] rounded-2xl border border-cyan-300/25 bg-slate-950 shadow-[0_20px_90px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-black/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-cyan-300 font-bold",children:"Ecosystem Command Center"}),e.jsx("div",{className:"text-[10px] font-mono text-slate-500",children:"Top-level ecosystem posture with drill-down into Δ18 systems."})]}),e.jsx("button",{type:"button","data-testid":"ecosystem-command-close-btn",onClick:r,className:"h-8 w-8 rounded-full border border-white/10 text-slate-300 hover:bg-white/10",children:"x"})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-[1fr_1fr] gap-3 p-3 overflow-auto",children:[e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Ecosystem Summary"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",role:"list","aria-label":"Ecosystem command summary cards",children:c.map(([u,x])=>e.jsxs("article",{className:"rounded border border-white/10 bg-black/30 px-2 py-1.5",role:"listitem",children:[e.jsx("div",{className:"text-[9px] font-mono text-slate-500 uppercase tracking-[0.1em]",children:u}),e.jsx("div",{className:"text-[10px] font-mono text-slate-100",children:x})]},u))})]}),e.jsxs("section",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.14em] text-slate-300 font-bold",children:"Drill-Down"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:l.map(([u,x])=>e.jsx("button",{type:"button","data-testid":`ecosystem-command-open-${u}`,onClick:()=>{typeof n=="function"&&n(u)},className:"px-3 py-2 rounded border border-cyan-300/30 bg-cyan-500/10 text-[10px] font-mono uppercase tracking-[0.12em] text-cyan-100 hover:bg-cyan-500/20 text-left",children:x},u))})]})]})]})]})}function RN(){const[t,r]=O.useState(null),[n,s]=O.useState(()=>new Set),a=O.useCallback(m=>{r(m)},[]),o=O.useCallback(m=>{m?(r(f=>f===m?null:f),s(f=>{if(!f.has(m))return f;const b=new Set(f);return b.delete(m),b})):r(null)},[]),c=O.useCallback(m=>{r(f=>f===m?null:m)},[]),l=O.useCallback(m=>t===m||n.has(m),[t,n]),u=O.useCallback(m=>{s(f=>{if(f.has(m))return f;const b=new Set(f);return b.add(m),b})},[]),x=O.useCallback(m=>{s(f=>{if(!f.has(m))return f;const b=new Set(f);return b.delete(m),b})},[]),p=O.useCallback(m=>n.has(m),[n]),d=O.useCallback(()=>{r(null),s(new Set)},[]);return O.useMemo(()=>({activePanel:t,open:a,close:o,toggle:c,isOpen:l,pinned:n,pin:u,unpin:x,isPinned:p,closeAll:d}),[t,n,a,o,c,l,u,x,p,d])}function ON({enabled:t=!1,moodEngine:r,personalityProfile:n="balanced"}){const s=i.useRef("");i.useEffect(()=>{if(!t){s.current="";return}if(!(window.api&&window.api.rgb&&typeof window.api.rgb.applyMood=="function"))return;const a=String(r&&r.rgbMood?r.rgbMood:"idle"),o=`${a}:${n}`;s.current!==o&&(s.current=o,window.api.rgb.applyMood({mood:a,personality:String(n||"balanced")}).catch(()=>{s.current=""}))},[t,r,r&&r.rgbMood,n])}const km="neuralshell_adaptive_layout_v1",TN=["presets","panels","insights"],MN=["nav","chat","status","visual"],DN="neuralshell_layout_usage_v1";function Zu(){try{return JSON.parse(window.localStorage.getItem(km)||"null")}catch{return null}}function Na(t){try{window.localStorage.setItem(km,JSON.stringify(t))}catch{}}function $N(){try{const t=JSON.parse(window.localStorage.getItem(DN)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}const Ss=[{id:"thread-rail",label:"Thread Rail",category:"nav",defaultVisible:!0},{id:"workbench-rail",label:"Workbench Rail",category:"nav",defaultVisible:!0},{id:"ambient-status",label:"Ambient Status Bar",category:"status",defaultVisible:!0},{id:"quick-reply",label:"Quick Reply Bar",category:"chat",defaultVisible:!0},{id:"smart-suggest",label:"Smart Suggestions",category:"chat",defaultVisible:!0},{id:"live-token-budget",label:"Token Budget Bar",category:"chat",defaultVisible:!1},{id:"prompt-template",label:"Prompt Templates",category:"chat",defaultVisible:!1},{id:"custom-actions",label:"Custom Actions Bar",category:"chat",defaultVisible:!0},{id:"chat-summary",label:"Chat Summary Bar",category:"chat",defaultVisible:!1},{id:"streaming-bar",label:"Streaming Progress Bar",category:"status",defaultVisible:!0},{id:"particle-bg",label:"Particle Background",category:"visual",defaultVisible:!1}],dr=[{id:"minimal",name:"Minimal",description:"Clean focus — essential chrome only",icon:"◻",color:"sky",panels:{"thread-rail":!0,"workbench-rail":!1,"ambient-status":!0,"quick-reply":!1,"smart-suggest":!1,"streaming-bar":!0},railWidths:{left:56,right:0}},{id:"operator",name:"Operator",description:"Full operator setup — all tools visible",icon:"⬛",color:"violet",panels:{"thread-rail":!0,"workbench-rail":!0,"ambient-status":!0,"quick-reply":!0,"smart-suggest":!0,"live-token-budget":!0,"custom-actions":!0,"streaming-bar":!0},railWidths:{left:240,right:240}},{id:"writing",name:"Writing",description:"Optimized for long-form text work",icon:"✎",color:"emerald",panels:{"thread-rail":!0,"workbench-rail":!1,"ambient-status":!1,"quick-reply":!0,"smart-suggest":!0,"chat-summary":!0,"streaming-bar":!0},railWidths:{left:180,right:0}},{id:"coding",name:"Coding",description:"Workbench-heavy, max context",icon:" ",color:"fuchsia",panels:{"thread-rail":!0,"workbench-rail":!0,"ambient-status":!0,"live-token-budget":!0,"custom-actions":!0,"prompt-template":!0,"streaming-bar":!0},railWidths:{left:220,right:320}},{id:"hud",name:"HUD / Cockpit",description:"Heads-up — slim rails, status + tokens visible, max reading width",icon:"◈",color:"sky",panels:{"thread-rail":!0,"workbench-rail":!1,"ambient-status":!0,"quick-reply":!0,"smart-suggest":!1,"live-token-budget":!0,"custom-actions":!0,"streaming-bar":!0,"chat-summary":!1,"prompt-template":!1,"particle-bg":!1},railWidths:{left:56,right:0}}];function LN(t){var n;const r=((n=Object.entries(t).sort((s,a)=>a[1]-s[1])[0])==null?void 0:n[0])||null;return r?r.includes("status")||r.includes("hud")||r.includes("telemetry")?dr.find(s=>s.id==="hud"):r.includes("workbench")||r.includes("code")?dr.find(s=>s.id==="coding"):r.includes("write")||r.includes("compose")?dr.find(s=>s.id==="writing"):r.includes("mission")||r.includes("fleet")||r.includes("incident")?dr.find(s=>s.id==="operator"):dr.find(s=>s.id==="minimal"):null}const BN=i.memo(function({open:r,onClose:n,onApplyLayout:s}){const[a,o]=i.useState(()=>Zu()||dr[0]),[c,l]=i.useState(()=>{const w=Zu();return(w==null?void 0:w.panels)||Object.fromEntries(Ss.map(j=>[j.id,j.defaultVisible]))}),[u,x]=i.useState($N),[p,d]=i.useState(!1),[m,f]=i.useState("presets");i.useEffect(()=>{const w=j=>x(j.detail.usage);return window.addEventListener("neuralshell:layout-action",w),()=>window.removeEventListener("neuralshell:layout-action",w)},[]);const b=i.useMemo(()=>LN(u),[u]),h=w=>{o(w),l({...Object.fromEntries(Ss.map(E=>[E.id,E.defaultVisible])),...w.panels});const j={...w,panels:{...Object.fromEntries(Ss.map(E=>[E.id,E.defaultVisible])),...w.panels}};Na(j),typeof s=="function"&&s({...j,_shellSync:"full"})},g=w=>{l(j=>{const E={...j,[w]:!j[w]},N={...a,panels:E};Na(N);try{window.dispatchEvent(new CustomEvent("neuralshell:layout-chrome-updated")),window.dispatchEvent(new CustomEvent("neuralshell:apply-layout"))}catch{}return typeof s=="function"&&s({...N,_shellSync:"panels-only"}),E})},y=()=>{Na({id:"custom",name:"Custom",description:"Your saved layout",icon:"★",color:"amber",panels:c});try{window.dispatchEvent(new CustomEvent("neuralshell:layout-chrome-updated"))}catch{}d(!0),setTimeout(()=>d(!1),1800)},I=()=>{const w=Object.fromEntries(Ss.map(E=>[E.id,E.defaultVisible]));l(w);const j={...dr[0],panels:w};Na(j),typeof s=="function"&&s({...j,_shellSync:"full"})},A=Object.entries(u).sort((w,j)=>j[1]-w[1]).slice(0,5),C=i.useRef(null);return Wa(r,C,n),r?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[210] bg-black/60 backdrop-blur-sm","aria-hidden":"true",onClick:n}),e.jsxs("section",{ref:C,"data-testid":"adaptive-layout-engine",role:"dialog","aria-modal":"true","aria-labelledby":"adaptive-layout-engine-title",className:"fixed right-6 top-14 bottom-4 w-96 z-[211] rounded-2xl border border-indigo-300/20 bg-slate-950 shadow-[0_24px_96px_rgba(99,102,241,0.12)] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-5 py-3 border-b border-white/10 bg-gradient-to-r from-indigo-950/50 to-slate-950 flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Xx,{size:15,className:"text-indigo-400","aria-hidden":"true"}),e.jsxs("div",{children:[e.jsx("h2",{id:"adaptive-layout-engine-title",className:"text-[11px] font-bold tracking-wide uppercase text-indigo-300",children:"Adaptive Layout Engine"}),e.jsx("div",{className:"text-[11px] font-mono text-slate-400",children:"Usage-learned panel arrangement"})]})]}),e.jsx("button",{type:"button","data-accessible-overlay-close":!0,onClick:n,"aria-label":"Close adaptive layout engine",title:"Close",className:"h-7 w-7 rounded-full border border-white/10 text-slate-400 hover:bg-white/10 flex items-center justify-center",children:e.jsx(yp,{size:12,"aria-hidden":"true"})})]}),e.jsx("div",{className:"flex border-b border-white/10 bg-black/20",children:TN.map(w=>e.jsx("button",{type:"button",onClick:()=>f(w),className:`px-4 py-2 text-[12px] font-mono uppercase tracking-wider transition-all ${m===w?"border-b-2 border-indigo-400 text-indigo-300 bg-indigo-500/5":"text-slate-500 hover:text-slate-300"}`,children:w},w))}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-4 space-y-3",children:[m==="presets"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[11px] font-mono text-slate-400 px-0.5 leading-relaxed",children:"Presets push rail widths and Flows / Bench collapse to the main window. Use the Panels tab for per-widget chrome without changing rail sizes."}),b&&e.jsxs("div",{className:"rounded-xl border border-indigo-400/20 bg-indigo-500/8 p-3 flex items-start gap-3",children:[e.jsx(gp,{size:14,className:"text-indigo-400 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-bold text-indigo-300",children:"Recommended for you"}),e.jsxs("div",{className:"text-[11px] font-mono text-slate-400 mt-0.5",children:["Based on your usage patterns: ",e.jsx("span",{className:"text-indigo-300",children:b.name})]}),e.jsx("button",{type:"button",onClick:()=>h(b),className:"mt-2 px-2.5 py-1 rounded border border-indigo-400/30 bg-indigo-500/15 text-[11px] font-mono text-indigo-300 hover:bg-indigo-500/25",children:"Apply Recommendation"})]})]}),dr.map(w=>e.jsxs("button",{type:"button",onClick:()=>h(w),className:`w-full text-left rounded-xl border p-3 transition-all ${(a==null?void 0:a.id)===w.id?"border-indigo-400/40 bg-indigo-500/10":"border-white/10 bg-black/20 hover:border-white/20"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:w.icon}),e.jsxs("div",{children:[e.jsx("div",{className:`text-[12px] font-bold ${(a==null?void 0:a.id)===w.id?"text-indigo-300":"text-slate-200"}`,children:w.name}),e.jsx("div",{className:"text-[11px] font-mono text-slate-400",children:w.description})]})]}),(a==null?void 0:a.id)===w.id&&e.jsx(od,{size:12,className:"text-indigo-400 shrink-0"})]}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1",children:Object.entries(w.panels||{}).filter(([,j])=>j).map(([j])=>e.jsx("span",{className:"text-[11px] font-mono px-1 py-0.5 rounded bg-white/5 border border-white/10 text-slate-500",children:j},j))})]},w.id))]}),m==="panels"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:MN.map(w=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-slate-500 px-1",children:w}),Ss.filter(j=>j.category===w).map(j=>e.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-white/8 bg-black/20 px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[12px] font-mono text-slate-200",children:j.label}),e.jsx("div",{className:"text-[11px] font-mono text-slate-400",children:j.id})]}),e.jsx("button",{type:"button",onClick:()=>g(j.id),className:`relative w-10 h-5 rounded-full border transition-all ${c[j.id]?"border-indigo-400/40 bg-indigo-500/30":"border-white/10 bg-white/5"}`,children:e.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full transition-all ${c[j.id]?"left-5 bg-indigo-400":"left-0.5 bg-slate-600"}`})})]},j.id))]},w))}),e.jsxs("div",{className:"flex gap-2 pt-1 border-t border-white/10",children:[e.jsx("button",{type:"button",onClick:y,className:"flex-1 py-2 rounded-lg border border-emerald-400/25 bg-emerald-500/10 text-[11px] font-mono text-emerald-300 flex items-center justify-center gap-1.5",children:p?e.jsxs(e.Fragment,{children:[e.jsx(od,{size:10})," Saved!"]}):e.jsxs(e.Fragment,{children:[e.jsx(Qx,{size:10})," Save Layout"]})}),e.jsxs("button",{type:"button",onClick:I,className:"flex-1 py-2 rounded-lg border border-white/10 text-[11px] font-mono text-slate-400 flex items-center justify-center gap-1.5",children:[e.jsx(ef,{size:10})," Reset"]})]})]}),m==="insights"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"text-[11px] font-mono text-slate-400 uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(tf,{size:9})," Top Actions"]}),A.length===0&&e.jsx("div",{className:"text-[11px] font-mono text-slate-400",children:"No usage data yet. Use the app to build your profile."}),A.map(([w,j])=>{var E;return e.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-mono",children:[e.jsx("span",{className:"text-slate-400 truncate flex-1",children:w}),e.jsx("div",{className:"w-24 h-1.5 rounded-full bg-white/5 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-indigo-400",style:{width:`${Math.min(100,j/(((E=A[0])==null?void 0:E[1])||1)*100)}%`}})}),e.jsx("span",{className:"text-slate-500 w-6 text-right",children:j})]},w)})]}),e.jsxs("div",{className:"rounded-xl border border-indigo-400/15 bg-indigo-500/5 p-3 text-[11px] font-mono text-indigo-300 space-y-1",children:[e.jsx("div",{className:"font-bold text-indigo-200",children:"How it works"}),e.jsx("div",{className:"text-slate-400",children:"The engine tracks which panels, commands, and features you use most frequently."}),e.jsx("div",{className:"text-slate-400",children:"Based on this, it recommends the preset that best matches your workflow."}),e.jsx("div",{className:"text-slate-400",children:"Applying a preset updates the main shell: rail widths and Flows / Bench collapse follow the preset map (minimal and HUD → narrow rails, operator and coding → spacious)."}),e.jsxs("div",{className:"text-slate-400",children:["Call ",e.jsx("span",{className:"text-indigo-300",children:"recordLayoutAction(action)"})," from any component to contribute usage signals."]})]})]})]})]})]}):null}),FN=i.lazy(()=>Kl(()=>Promise.resolve().then(()=>Pg),void 0,import.meta.url)),UN={"voice-mode":{title:"Voice Bridge",subtitle:"WebRTC voice channel for collab rooms"},"agent-store":{title:"Agent Marketplace",subtitle:"Install operator agents into your workspace"},"projects-mode":{title:"Project Scope",subtitle:"Tag the active chat pane with a project context"},"knowledge-base":{title:"Knowledge Base",subtitle:"Attach reference context to your session"},"ai-memory":{title:"AI Memory",subtitle:"Pinned session notes for the active workflow"},"multi-model-split":{title:"Multi-Model Compare",subtitle:"Split the workspace to compare models side-by-side"}};function xn({open:t,panelId:r,onClose:n,children:s,wide:a=!1}){if(!t)return null;const o=UN[r]||{title:"Workspace Panel",subtitle:""};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[138] bg-black/45 backdrop-blur-[1px]",onClick:n,"aria-hidden":"true"}),e.jsxs("aside",{"data-testid":`workspace-panel-${r}`,className:`fixed right-0 top-0 bottom-0 z-[139] bg-slate-950 border-l border-cyan-400/20 shadow-[-16px_0_40px_rgba(0,0,0,0.55)] flex flex-col ${a?"w-full max-w-2xl":"w-full max-w-md"}`,children:[e.jsxs("header",{className:"px-5 py-4 border-b border-white/10 flex items-start justify-between gap-3 shrink-0",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.18em] text-cyan-300 font-bold",children:"Workspace"}),e.jsx("h3",{className:"text-lg font-semibold text-slate-100 mt-0.5",children:o.title}),o.subtitle&&e.jsx("p",{className:"text-[11px] text-slate-500 font-mono mt-1",children:o.subtitle})]}),e.jsx("button",{type:"button",onClick:n,className:"h-9 w-9 rounded-full hover:bg-white/5 text-slate-400 hover:text-white transition-colors","aria-label":"Close panel",children:"✕"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-5 custom-scrollbar",children:s})]})]})}function zN({onApply:t,onClose:r}){const[n,s]=i.useState("");return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("label",{className:"block space-y-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-widest text-slate-400 font-bold",children:"Project name"}),e.jsx("input",{value:n,onChange:a=>s(a.target.value),placeholder:"e.g. release-2138, client-alpha",className:"w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-sm text-slate-200 outline-none focus:border-cyan-400/50 font-mono"})]}),e.jsx("button",{type:"button",onClick:()=>{t(String(n||"").trim()),r()},className:"w-full px-3 py-2 rounded-xl border border-sky-300/30 bg-sky-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-sky-200 hover:bg-sky-500/20",children:"Apply to active pane"})]})}function HN(){return e.jsxs("div",{className:"space-y-3 text-[12px] text-slate-400 leading-relaxed",children:[e.jsx("p",{children:"Attach files and notes from the workbench rail, or drop artifacts into chat messages."}),e.jsxs("ul",{className:"list-disc pl-5 space-y-1 font-mono text-[11px] text-slate-500",children:[e.jsxs("li",{children:["Use ",e.jsx("code",{className:"text-cyan-300",children:"/proof"})," to validate operator flows"]}),e.jsx("li",{children:"Save sessions to preserve context across locks"}),e.jsx("li",{children:"Import env provider profiles in Settings"})]})]})}function WN({memoryKey:t}){const[r,n]=i.useState(()=>{try{return String(window.localStorage.getItem(t)||"")}catch{return""}});return i.useEffect(()=>{try{window.localStorage.setItem(t,r)}catch{}},[t,r]),e.jsxs("div",{className:"space-y-3",children:[e.jsx("textarea",{value:r,onChange:s=>n(s.target.value),rows:12,placeholder:"Pinned notes for this workflow — goals, constraints, decisions…",className:"w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-sm text-slate-200 outline-none focus:border-rose-400/40 font-mono resize-y min-h-52"}),e.jsx("p",{className:"text-[10px] text-slate-500 font-mono",children:"Saved locally per workflow. Toggle the memory chip to keep this drawer open while chatting."})]})}function KN({onLaunch:t,onClose:r}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-[12px] text-slate-400",children:"Opens a two-pane split so you can compare models on the same prompt. A second pane is created automatically if needed."}),e.jsx("button",{type:"button",onClick:()=>{t(),r()},className:"w-full px-3 py-2 rounded-xl border border-indigo-300/30 bg-indigo-500/10 text-[10px] uppercase tracking-[0.16em] font-bold text-indigo-200 hover:bg-indigo-500/20",children:"Launch split compare"})]})}function VN({panels:t,collab:r,workflowId:n}){const s=i.useCallback(c=>{t&&typeof t.close=="function"&&t.close(c)},[t]),a=i.useCallback((c,l={})=>{window.dispatchEvent(new CustomEvent("neuralshell:workspace-panel-action",{detail:{action:c,...l}}))},[]),o=`neuralshell_ai_memory_${String(n||"default")}`;return t?e.jsxs(e.Fragment,{children:[e.jsx(xn,{open:t.isOpen("voice-mode"),panelId:"voice-mode",onClose:()=>s("voice-mode"),children:e.jsx(Kh,{collab:r})}),e.jsx(xn,{open:t.isOpen("agent-store"),panelId:"agent-store",wide:!0,onClose:()=>s("agent-store"),children:e.jsx(i.Suspense,{fallback:e.jsx("div",{className:"text-slate-500 text-sm font-mono",children:"Loading agents…"}),children:e.jsx(FN,{})})}),e.jsx(xn,{open:t.isOpen("projects-mode"),panelId:"projects-mode",onClose:()=>s("projects-mode"),children:e.jsx(zN,{onApply:c=>a("set-project",{project:c}),onClose:()=>s("projects-mode")})}),e.jsx(xn,{open:t.isOpen("knowledge-base"),panelId:"knowledge-base",onClose:()=>s("knowledge-base"),children:e.jsx(HN,{})}),e.jsx(xn,{open:t.isOpen("ai-memory"),panelId:"ai-memory",onClose:()=>s("ai-memory"),children:e.jsx(WN,{memoryKey:o})}),e.jsx(xn,{open:t.isOpen("multi-model-split"),panelId:"multi-model-split",onClose:()=>s("multi-model-split"),children:e.jsx(KN,{onLaunch:()=>a("multi-model-split"),onClose:()=>s("multi-model-split")})})]}):null}function GN(){return`peer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function JN(t){const r=String(t||"").trim()||"default",[n,s]=i.useState(!1),[a]=i.useState(()=>GN()),[o,c]=i.useState({}),[l,u]=i.useState(null),x=i.useRef(null);i.useEffect(()=>{let d=!1,m=null;const f=()=>{if(x.current){try{x.current.close()}catch{}x.current=null}},b=async()=>{try{const h=await window.api.collab.getStatus();if(d)return;const g=String(h&&h.host?h.host:"127.0.0.1"),y=Number(h&&h.port?h.port:55116),I=new WebSocket(`ws://${g}:${y}`);x.current=I,I.onopen=()=>{d||(s(!0),I.send(JSON.stringify({action:"join",room:r,peerId:a})))},I.onclose=()=>{d||(s(!1),m==null&&(m=window.setTimeout(()=>{m=null,b()},1200)))},I.onmessage=A=>{let C=null;try{C=JSON.parse(String(A.data||""))}catch{return}if(!C||typeof C!="object"||C.action!=="event")return;const w=String(C.eventType||""),j=String(C.fromPeerId||""),E=C.payload&&typeof C.payload=="object"?C.payload:{};if(w==="cursor"){const N=Number(E.x||0),_=Number(E.y||0);c(S=>({...S,[j]:{x:N,y:_,updatedAt:new Date().toISOString()}}))}u({eventType:w,payload:E,fromPeerId:j})}}catch{if(d)return;s(!1),m==null&&(m=window.setTimeout(()=>{m=null,b()},1200))}};return b(),()=>{d=!0,m!=null&&window.clearTimeout(m),f()}},[a,r]);const p=i.useCallback((d,m)=>!x.current||x.current.readyState!==WebSocket.OPEN?!1:(x.current.send(JSON.stringify({action:"publish",room:r,eventType:String(d||""),payload:m&&typeof m=="object"?m:{}})),!0),[r]);return{connected:n,peerId:a,roomId:r,remoteCursors:o,lastEvent:l,publish:p}}function qt(t,r=""){if(typeof window>"u"||!window.localStorage)return r;const n=window.localStorage.getItem(t);return n==null?r:String(n||r)}function qN(){if(typeof window>"u"||!window.localStorage)return"default";try{const t=JSON.parse(window.localStorage.getItem("neuralshell_branding_profile_active_v1")||"{}");return String(t&&t.profileId?t.profileId:"default")}catch{return"default"}}function YN(){const t=qt("neuralshell_voice_rtt_median_v1","");if(!t)return null;const r=Number(t);return Number.isFinite(r)?Math.round(r):null}function ZN(){return{providerHealth:{activeProvider:"ollama",model:"llama3",latencyMs:null,online:!1,lastSweepResult:"unknown",lastSweepAt:""},vaultState:{locked:!1,activeProfile:"default",exportImportStatus:"idle",policyBound:!1},proofEngine:{lastProofStatus:"idle",currentStage:"idle",lastBundleHash:"",parityState:"unknown"},relayState:{enabled:!1,mappedChannel:"local-only",lastRelaySend:"",relayError:""},collabVoiceState:{peersActive:0,currentRoom:"default",voiceRttMs:null,sessionHealth:"offline"},policyState:{activePolicyProfile:"none",updateRing:"stable",offlineOnly:!1,approvedProviders:[]},updateLane:{currentVersion:"2.1.29",lastUpdateCheck:"",signatureState:"unknown",stagedUpdateAvailable:!1},sealIdentity:{sealIdentity:"unknown",machineTrust:"unknown",whiteLabelProfile:"default"},watchdog:{status:"unknown",pid:null,wsRunning:!1},releaseHealth:{status:"unknown"},refreshedAt:new Date().toISOString()}}function XN({connectionInfo:t,workflowId:r,runtimeTier:n,sessionHydrationStatus:s,collabConnected:a,collabRoomId:o,collabPeerCount:c}){const[l,u]=i.useState(()=>ZN()),x=i.useRef(null),p=i.useCallback(async()=>{var z,F,J,ee,ie,ye,pe,K,H,W,Z,ce,fe,me,ke,Pe;const[d,m,f,b,h,g,y,I]=await Promise.all([(F=(z=window.api)==null?void 0:z.settings)!=null&&F.get?window.api.settings.get().catch(()=>({})):Promise.resolve({}),(ee=(J=window.api)==null?void 0:J.daemon)!=null&&ee.status?window.api.daemon.status().catch(()=>({})):Promise.resolve({}),(ye=(ie=window.api)==null?void 0:ie.autoUpdate)!=null&&ye.getPolicy?window.api.autoUpdate.getPolicy().catch(()=>({})):Promise.resolve({}),(K=(pe=window.api)==null?void 0:pe.autoUpdate)!=null&&K.pending?window.api.autoUpdate.pending().catch(()=>({})):Promise.resolve({}),(W=(H=window.api)==null?void 0:H.releaseHealth)!=null&&W.check?window.api.releaseHealth.check().catch(()=>({})):Promise.resolve({}),(ce=(Z=window.api)==null?void 0:Z.collab)!=null&&ce.getStatus?window.api.collab.getStatus().catch(()=>({})):Promise.resolve({}),(me=(fe=window.api)==null?void 0:fe.identity)!=null&&me.pubkey?window.api.identity.pubkey().catch(()=>({})):Promise.resolve({}),(Pe=(ke=window.api)==null?void 0:ke.modelPool)!=null&&Pe.status?window.api.modelPool.status().catch(()=>({})):Promise.resolve({})]),A=String(t&&t.provider?t.provider:"ollama"),C=String(t&&t.model?t.model:"llama3"),j=String(t&&t.health?t.health:"unknown")==="online",E=qt("neuralshell_provider_sweep_last_v1",j?"passed":"unknown"),N=qt("neuralshell_provider_sweep_at_v1",""),_=Number.isFinite(Number(I&&I.idleMs))?Math.round(Number(I.idleMs)):null,S=d&&d.enterprisePolicyEnforced&&typeof d.enterprisePolicyEnforced=="object"?d.enterprisePolicyEnforced:{},R=Array.isArray(S.allowedProviders)?S.allowedProviders.map(_e=>String(_e||"").trim().toLowerCase()).filter(Boolean):[],$=String(S.label||S.policyId||"none"),U=String(d&&d.autoUpdateChannel?d.autoUpdateChannel:f&&f.channel?f.channel:"stable"),P={providerHealth:{activeProvider:A,model:C,latencyMs:_,online:j,lastSweepResult:E,lastSweepAt:N},vaultState:{locked:String(s||"")==="locked",activeProfile:String(r||"default"),exportImportStatus:qt("neuralshell_vault_last_action_v1","idle"),policyBound:!!(S&&Object.keys(S).length>0)},proofEngine:{lastProofStatus:qt("neuralshell_proof_last_status_v1","idle"),currentStage:qt("neuralshell_proof_stage_v1","idle"),lastBundleHash:qt("neuralshell_proof_last_bundle_hash_v1",""),parityState:String(h&&h.status?h.status:"unknown")},relayState:{enabled:!!(d&&d.proofRelayEnabled),mappedChannel:String(o||"default"),lastRelaySend:qt("neuralshell_relay_last_send_v1",""),relayError:qt("neuralshell_relay_last_error_v1","")},collabVoiceState:{peersActive:Math.max(0,Number(c||0)),currentRoom:String(o||(g&&g.roomId?g.roomId:"default")),voiceRttMs:YN(),sessionHealth:a?"healthy":"degraded"},policyState:{activePolicyProfile:$,updateRing:U,offlineOnly:!!(d&&d.offlineOnlyEnforced),approvedProviders:R},updateLane:{currentVersion:String(d&&d.appVersion?d.appVersion:"2.1.29"),lastUpdateCheck:String(b&&b.checkedAt?b.checkedAt:""),signatureState:b&&b.verified?"verified":"unverified",stagedUpdateAvailable:!!(b&&b.available)},sealIdentity:{sealIdentity:String(y&&y.fingerprint?y.fingerprint:"unknown"),machineTrust:String(n||"unknown").toLowerCase(),whiteLabelProfile:qN()},watchdog:{status:String(m&&m.status?m.status:"unknown"),pid:Number.isFinite(Number(m&&m.pid))?Number(m.pid):null,wsRunning:!!(m&&m.wsBridge&&m.wsBridge.running)},releaseHealth:{status:String(h&&h.status?h.status:"unknown")},refreshedAt:new Date().toISOString()},D=x.current;return D&&D.providerHealth.online!==P.providerHealth.online&&X(P.providerHealth.online?"provider.sweep.passed":"provider.sweep.failed",{provider:P.providerHealth.activeProvider,model:P.providerHealth.model},{severity:P.providerHealth.online?"info":"degraded",source:"runtime"}),D&&D.watchdog.status!==P.watchdog.status&&X("runtime.watchdog.alert",{status:P.watchdog.status,pid:P.watchdog.pid},{severity:P.watchdog.status==="running"?"info":"warning",source:"watchdog"}),D&&D.policyState.activePolicyProfile!==P.policyState.activePolicyProfile&&X("policy.changed",{policyProfile:P.policyState.activePolicyProfile,updateRing:P.policyState.updateRing},{severity:"info",source:"policy"}),D&&D.vaultState.locked!==P.vaultState.locked&&X(P.vaultState.locked?"vault.locked":"vault.unlocked",{activeProfile:P.vaultState.activeProfile},{severity:P.vaultState.locked?"warning":"info",source:"vault"}),x.current=P,u(P),P},[a,c,o,t,n,s,r]);return i.useEffect(()=>{p();const d=window.setInterval(p,6e3);return()=>window.clearInterval(d)},[p]),{runtimeState:l,refreshRuntimeState:p}}function QN(){const[t,r]=i.useState(()=>Pl().slice(-250));i.useEffect(()=>(r(Pl().slice(-250)),K0(s=>{r(a=>[...a,s].slice(-250))})),[]);const n=t.length?t[t.length-1]:null;return{events:t,latest:n}}const Cs=[{id:"welcome_intro",title:"Welcome / Mode Intro",description:"Establish local-first runtime authority and operating mode.",critical:!1},{id:"provider_sweep",title:"Provider Sweep",description:"Probe provider bridge health and establish baseline.",critical:!0},{id:"vault_setup",title:"Vault Setup",description:"Create and verify a local vault secret.",critical:!0},{id:"policy_profile_selection",title:"Policy Profile Selection",description:"Select enforcement profile and allowed providers.",critical:!0},{id:"update_ring_selection",title:"Update Ring Selection",description:"Select stable/beta/canary/frozen update lane.",critical:!0},{id:"run_proof",title:"Run 90-second Proof",description:"Run proof command and capture runtime evidence.",critical:!0},{id:"install_core_agent",title:"Install Core Agent",description:"Install the proof_guard operator agent into your local workspace.",critical:!0},{id:"license_import",title:"Import Tier/License",description:"Optional: import enterprise/pro license payload.",critical:!1},{id:"share_badge",title:"Share Badge / Skip",description:"Open badge share path or skip.",critical:!1},{id:"open_mission_control",title:"Open Mission Control",description:"Land in runtime cockpit and review system posture.",critical:!0}],Nm="neuralshell_first_boot_progress_v1",Xu="neuralshell_first_boot_events_v1",Sa="neuralshell_first_boot_dismissed_v1";function eS(){if(typeof window>"u"||!window.localStorage)return{};try{const t=JSON.parse(window.localStorage.getItem(Nm)||"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function Qu(t){typeof window>"u"||!window.localStorage||window.localStorage.setItem(Nm,JSON.stringify(t||{}))}function Er(t,r="",n={}){if(!(typeof window>"u"||!window.localStorage))try{const s=JSON.parse(window.localStorage.getItem(Xu)||"[]"),a=Array.isArray(s)?s:[],o={at:new Date().toISOString(),type:String(t||""),stepId:String(r||""),detail:n&&typeof n=="object"?n:{}};a.push(o),window.localStorage.setItem(Xu,JSON.stringify(a.slice(-250)))}catch{}}function tS(){const[t,r]=i.useState(()=>eS()),[n,s]=i.useState(()=>typeof window>"u"||!window.localStorage?!0:!(window.localStorage.getItem(Sa)==="1")),[a,o]=i.useState(""),c=i.useMemo(()=>(Array.isArray(Cs)?Cs:[]).filter(b=>!!t[String(b.id||"")]).length,[t]),l=i.useMemo(()=>c>=(Array.isArray(Cs)?Cs.length:0),[c]),u=i.useCallback(b=>{const h=String(b||"");h&&(r(g=>{const y={...g||{},[h]:!0};return Qu(y),y}),Er("step_completed",h),X("firstboot.step.completed",{stepId:h},{source:"firstboot",severity:"info"}))},[]),x=i.useCallback(b=>{const h=String(b||"");h&&(Er("step_skipped",h),X("firstboot.step.skipped",{stepId:h},{source:"firstboot",severity:"info"}))},[]),p=i.useCallback(()=>{typeof window<"u"&&window.localStorage&&window.localStorage.setItem(Sa,"1"),s(!1),Er("wizard_dismissed")},[]),d=i.useCallback(()=>{typeof window<"u"&&window.localStorage&&window.localStorage.removeItem(Sa),s(!0),Er("wizard_reopened")},[]),m=i.useCallback(()=>{r({}),Qu({}),typeof window<"u"&&window.localStorage&&window.localStorage.removeItem(Sa),s(!0),Er("wizard_reset"),X("firstboot.reset",{},{source:"firstboot",severity:"warning"})},[]),f=i.useCallback(async(b,h)=>{const g=String(b||"");if(!g)return!1;o(g),Er("step_started",g),X("firstboot.step.started",{stepId:g},{source:"firstboot",severity:"info"});try{return typeof h=="function"&&await Promise.resolve(h()),u(g),!0}catch(y){const I=y&&y.message?y.message:String(y);return Er("step_failed",g,{message:I}),X("firstboot.step.failed",{stepId:g,message:I},{source:"firstboot",severity:"warning"}),!1}finally{o("")}},[u]);return{steps:Cs,progress:t,open:n,setOpen:s,busyStepId:a,completedCount:c,allDone:l,completeStep:u,markSkipped:x,runStep:f,dismiss:p,reopen:d,reset:m}}async function rS(){if(typeof window>"u"||!window.api||!window.api.omega||typeof window.api.omega.status!="function")throw new Error("OMEGA status API unavailable");return window.api.omega.status()}function nS({enabled:t=!0,intervalMs:r=12e3}={}){const[n,s]=O.useState(null),[a,o]=O.useState(!!t),[c,l]=O.useState(""),u=O.useRef(!0),x=O.useCallback(async()=>{if(!t)return null;o(!0),l("");try{const p=await rS();return u.current&&s(p),p}catch(p){if(!u.current)return null;const d=p&&p.message?p.message:String(p);return l(d),null}finally{u.current&&o(!1)}},[t]);return O.useEffect(()=>{if(u.current=!0,!t)return;x();const p=window.setInterval(()=>{x()},Math.max(4e3,Number(r)||12e3));return()=>{u.current=!1,window.clearInterval(p)}},[t,r,x]),{report:n,loading:a,error:c,refresh:x}}const ep="neuralshell_fleet_nodes_v1",tp="neuralshell_fleet_filter_v1",rp="neuralshell_fleet_selected_v1";function Ie(t,r=""){return String(t??r).trim()||r}function Sm(t){const r=Ie(t);if(!r)return new Date().toISOString();const n=new Date(r);return Number.isNaN(n.getTime())?new Date().toISOString():n.toISOString()}function lc(t){const r=Ie(t).toLowerCase();return r==="healthy"?"healthy":r==="critical"?"critical":r==="offline"?"offline":"degraded"}function sS(t){return Array.isArray(t)?t.map(r=>Ie(r)).filter(Boolean):t==null?[]:Ie(t).split(/[|,]/).map(r=>Ie(r)).filter(Boolean)}function Ra(t,r=0){const n=Ie(t&&t.severity,"info").toLowerCase(),s=n==="critical"?"critical":n==="degraded"?"degraded":n==="warning"?"warning":"info";return{id:Ie(t&&t.id,`fleet-event-${Date.now()}-${r}`),at:Sm(t&&t.at),type:Ie(t&&t.type,"fleet.event"),severity:s,source:Ie(t&&t.source,"fleet"),detail:t&&t.detail&&typeof t.detail=="object"?t.detail:{}}}function yn(t,r="local-import"){const n=t&&typeof t=="object"?t:{},s=Ie(n.nodeId||n.id||n.node||n.machineId);return{nodeId:s||`node-${Math.random().toString(36).slice(2,8)}`,displayName:Ie(n.displayName||n.name||s||"Imported Node"),runtimeHealth:lc(n.runtimeHealth||n.health||n.status),providerHealth:Ie(n.providerHealth||n.provider||"unknown"),proofStatus:Ie(n.proofStatus||n.proof||"unknown"),policyProfile:Ie(n.policyProfile||n.policy||"none"),updateVersion:Ie(n.updateVersion||n.version||"unknown"),relayStatus:Ie(n.relayStatus||n.relay||"unknown"),collabState:Ie(n.collabState||n.collab||"unknown"),lastSeenAt:Sm(n.lastSeenAt||n.lastSeen||n.updatedAt),alerts:sS(n.alerts),importedFrom:Ie(n.importedFrom||r,r),updateRing:Ie(n.updateRing,"standard"),activePackId:Ie(n.activePackId,""),applianceMode:!!n.applianceMode,events:Array.isArray(n.events)?n.events.map((a,o)=>Ra(a,o)).slice(-160):[]}}function al(t,r){if(typeof window>"u"||!window.localStorage)return r;try{const n=JSON.parse(window.localStorage.getItem(t)||"null");return n??r}catch{return r}}function ol(t,r){typeof window>"u"||!window.localStorage||window.localStorage.setItem(t,JSON.stringify(r))}function np(t,r){const n=new Map;return(Array.isArray(t)?t:[]).forEach(s=>{const a=yn(s,s&&s.importedFrom?s.importedFrom:"local-import");n.set(a.nodeId,a)}),(Array.isArray(r)?r:[]).forEach(s=>{const a=yn(s,s&&s.importedFrom?s.importedFrom:"local-import"),o=n.get(a.nodeId);if(!o){n.set(a.nodeId,a);return}n.set(a.nodeId,{...o,...a,events:[...o.events||[],...a.events||[]].slice(-160),alerts:Array.from(new Set([...o.alerts||[],...a.alerts||[]]))})}),Array.from(n.values()).sort((s,a)=>String(s.displayName||"").localeCompare(String(a.displayName||"")))}function aS(t){return(Array.isArray(t)?t:[]).reduce((r,n)=>{const s=lc(n&&n.runtimeHealth);return r.total+=1,r[s]+=1,r},{total:0,healthy:0,degraded:0,critical:0,offline:0})}function oS(t,r){return!t||!r?[]:[{key:"runtimeHealth",label:"Runtime Health",left:t.runtimeHealth,right:r.runtimeHealth},{key:"providerHealth",label:"Provider Health",left:t.providerHealth,right:r.providerHealth},{key:"proofStatus",label:"Proof Status",left:t.proofStatus,right:r.proofStatus},{key:"policyProfile",label:"Policy Profile",left:t.policyProfile,right:r.policyProfile},{key:"updateVersion",label:"Update Version",left:t.updateVersion,right:r.updateVersion},{key:"updateRing",label:"Update Ring",left:t.updateRing,right:r.updateRing},{key:"relayStatus",label:"Relay Status",left:t.relayStatus,right:r.relayStatus},{key:"collabState",label:"Collab State",left:t.collabState,right:r.collabState},{key:"alertCount",label:"Alert Count",left:t.alerts.length,right:r.alerts.length}].map(s=>({...s,changed:String(s.left)!==String(s.right)})).filter(s=>s.changed)}function iS(){const[t,r]=i.useState(()=>{const w=al(ep,[]);return Array.isArray(w)?w.map(j=>yn(j,j&&j.importedFrom?j.importedFrom:"local-import")):[]}),[n,s]=i.useState(()=>{const w=Ie(al(tp,"all"),"all").toLowerCase();return w==="healthy"||w==="degraded"||w==="critical"||w==="offline"?w:"all"}),[a,o]=i.useState(()=>{const w=al(rp,[]);return Array.isArray(w)?w.map(j=>Ie(j)).filter(Boolean).slice(0,2):[]});i.useEffect(()=>{ol(ep,t)},[t]),i.useEffect(()=>{ol(tp,n)},[n]),i.useEffect(()=>{ol(rp,a)},[a]);const c=i.useMemo(()=>n==="all"?t:t.filter(w=>lc(w.runtimeHealth)===n),[t,n]),l=i.useMemo(()=>aS(t),[t]),u=i.useMemo(()=>{const w=new Map(t.map(j=>[j.nodeId,j]));return a.map(j=>w.get(String(j))).filter(Boolean)},[t,a]),x=i.useMemo(()=>oS(u[0]||null,u[1]||null),[u]),p=i.useCallback((w,j="local-import")=>{const N=(Array.isArray(w)?w:[]).map(_=>yn(_,j));return r(_=>np(_,N)),X("fleet.nodes.imported",{imported:N.length,sourceName:j},{source:"fleet",severity:"info"}),N.length},[]),d=i.useCallback(async w=>{if(!w)return 0;const j=await pt(w),E=Ds(j,String(w.name||""));return p(E,String(w.name||"local-file"))},[p]),m=i.useCallback((w,j={})=>{const E=w&&typeof w=="object"?w:{},N=yn({nodeId:j.nodeId||"local-runtime",displayName:j.displayName||"Local Runtime",runtimeHealth:E.watchdog&&E.watchdog.status==="running"?"healthy":"degraded",providerHealth:E.providerHealth&&E.providerHealth.online?"online":"offline",proofStatus:E.proofEngine&&E.proofEngine.lastProofStatus?E.proofEngine.lastProofStatus:"idle",policyProfile:E.policyState&&E.policyState.activePolicyProfile?E.policyState.activePolicyProfile:"none",updateVersion:E.updateLane&&E.updateLane.currentVersion?E.updateLane.currentVersion:"unknown",relayStatus:E.relayState&&E.relayState.enabled?"enabled":"disabled",collabState:E.collabVoiceState&&E.collabVoiceState.sessionHealth?E.collabVoiceState.sessionHealth:"unknown",lastSeenAt:new Date().toISOString(),importedFrom:"runtime-local",updateRing:E.policyState&&E.policyState.updateRing?E.policyState.updateRing:"standard",applianceMode:!!j.applianceMode},"runtime-local");return r(_=>np(_,[N])),N},[]),f=i.useCallback(w=>{const j=Ie(w);j&&o(E=>E.includes(j)?E.filter(N=>N!==j):[...E,j].slice(-2))},[]),b=i.useCallback(w=>{const j=Ie(w);j&&(r(E=>E.filter(N=>String(N.nodeId||"")!==j)),o(E=>E.filter(N=>N!==j)),X("fleet.node.removed",{nodeId:j},{source:"fleet",severity:"warning"}))},[]),h=i.useCallback(()=>{r([]),o([]),X("fleet.nodes.cleared",{},{source:"fleet",severity:"warning"})},[]),g=i.useCallback((w,j)=>{const E=Ie(w);if(!E)return;const N=j&&typeof j=="object"?j:{};r(_=>_.map(S=>String(S.nodeId||"")!==E?S:yn({...S,...N,nodeId:E},S.importedFrom||"fleet-update")))},[]),y=i.useCallback((w,j)=>{const E=Ie(w);E&&r(N=>N.map(_=>{if(String(_.nodeId||"")!==E)return _;const S=Ra({id:j.id||`fleet-event-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,at:j.at||new Date().toISOString(),type:j.type||"fleet.event",severity:j.severity||"info",source:j.source||"fleet",detail:j.detail||{}});return{..._,events:[..._.events||[],S].slice(-160)}}))},[]),I=i.useCallback((w,j,E={})=>{const N=w&&typeof w=="object"?w:{},_=Array.isArray(j)?j.map($=>Ie($)).filter(Boolean):[],S=Ie(N.policyProfile||N.label||N.policyId,"fleet-policy"),R=Ie(E.mode,"immediate");return r($=>$.map(U=>_.includes(String(U.nodeId||""))?{...U,policyProfile:S,lastSeenAt:new Date().toISOString(),events:[...U.events||[],Ra({type:"fleet.policy.rollout",severity:"info",source:"fleet-policy",detail:{policyProfile:S,mode:R}})].slice(-160)}:U)),X("fleet.policy.rollout",{policyProfile:S,targets:_.length,mode:R},{source:"fleet-policy",severity:"info"}),{policyProfile:S,targets:_.length}},[]),A=i.useCallback((w,j)=>{const E=Ie(w);E&&(g(E,{policyProfile:Ie(j,"none"),lastSeenAt:new Date().toISOString()}),y(E,{type:"fleet.policy.rollback",severity:"warning",source:"fleet-policy",detail:{previousPolicy:Ie(j,"none")}}))},[y,g]),C=i.useCallback((w,j)=>{const E=Array.isArray(w)?w.map(R=>Ie(R)).filter(Boolean):[],N=Ie(j&&j.packId,""),_=Ie(j&&j.ring,"standard"),S=Ie(j&&j.version,"unknown");r(R=>R.map($=>E.includes(String($.nodeId||""))?{...$,activePackId:N,updateRing:_,updateVersion:S,events:[...$.events||[],Ra({type:"fleet.update.pack.assigned",severity:"info",source:"fleet-updates",detail:{packId:N,ring:_,version:S}})].slice(-160)}:$)),X("fleet.update.pack.assigned",{targets:E.length,packId:N,ring:_,version:S},{source:"fleet-updates",severity:"info"})},[]);return{nodes:t,filteredNodes:c,statusFilter:n,setStatusFilter:s,healthSummary:l,selectedNodeIds:a,selectedNodes:u,compareRows:x,importFleetRecords:p,importFleetFile:d,importRuntimeNode:m,toggleNodeSelected:f,removeNode:b,clearFleet:h,updateNode:g,appendNodeEvent:y,applyPolicyBundle:I,rollbackPolicy:A,assignUpdatePack:C}}function lS(t){return t&&t.online?null:{source:"provider-bridge",severity:"degraded",message:`Provider bridge is offline (${String(t&&t.provider?t.provider:"unknown")}/${String(t&&t.model?t.model:"unknown")}).`,suggestedAction:"Run provider sweep and switch to safe local profile."}}function cS(t){const r=!!(t&&t.enabled),n=String(t&&t.relayError?t.relayError:"");return!r||!n?null:{source:"relay",severity:"warning",message:`Relay is enabled with error: ${n}`,suggestedAction:"Disable relay path and retry provider/transport checks."}}function dS(t){const r=String(t&&t.signatureState?t.signatureState:"unknown").toLowerCase(),n=!!(t&&t.stagedUpdateAvailable);return r==="verified"||!n&&r==="unknown"?null:{source:"update-lane",severity:"degraded",message:`Update verification is ${r}.`,suggestedAction:"Freeze update apply lane until signature/hash verification passes."}}function uS(t){const r=!!(t&&t.locked),n=String(t&&t.exportImportStatus?t.exportImportStatus:"idle").toLowerCase();return!r&&!n.includes("error")?null:{source:"vault",severity:r?"warning":"degraded",message:r?"Vault is currently locked.":`Vault action state indicates issue: ${n}`,suggestedAction:"Unlock vault and verify read/write with a local secret round-trip."}}function pS(t,r){return`${t}:${r}`.toLowerCase()}class mS{constructor(r={}){this.hooks=r,this.alerts=new Map}getAlerts(){return Array.from(this.alerts.values()).sort((r,n)=>String(n.at).localeCompare(String(r.at)))}acknowledgeAlert(r){const n=this.alerts.get(String(r||""));return n?(this.alerts.set(n.id,{...n,acknowledged:!0}),!0):!1}async evaluate(r){const n=[lS({online:!!(r&&r.providerHealth&&r.providerHealth.online),provider:String(r&&r.providerHealth?r.providerHealth.activeProvider:""),model:String(r&&r.providerHealth?r.providerHealth.model:"")}),cS({enabled:!!(r&&r.relayState&&r.relayState.enabled),relayError:String(r&&r.relayState?r.relayState.relayError:"")}),dS({signatureState:String(r&&r.updateLane?r.updateLane.signatureState:""),stagedUpdateAvailable:!!(r&&r.updateLane&&r.updateLane.stagedUpdateAvailable)}),uS({locked:!!(r&&r.vaultState&&r.vaultState.locked),exportImportStatus:String(r&&r.vaultState?r.vaultState.exportImportStatus:"")})].filter(Boolean),s=new Set;for(const a of n){const o=pS(a.source,a.message);if(s.add(o),!this.alerts.get(o)){const l={id:o,source:a.source,severity:a.severity,message:a.message,suggestedAction:a.suggestedAction,at:new Date().toISOString(),sticky:a.severity==="degraded"||a.severity==="critical",acknowledged:!1};this.alerts.set(o,l),this.hooks.onAlert&&this.hooks.onAlert(l)}await this.tryRecover(a)}return Array.from(this.alerts.values()).forEach(a=>{if(!s.has(a.id)&&!a.sticky){this.alerts.delete(a.id);return}!s.has(a.id)&&a.sticky&&!a.recoveredAt&&this.alerts.set(a.id,{...a,recoveredAt:new Date().toISOString()})}),this.getAlerts()}async tryRecover(r){try{if(r.source==="provider-bridge"&&this.hooks.retryProviderProbe){await Promise.resolve(this.hooks.retryProviderProbe());return}if(r.source==="relay"&&this.hooks.disableRelayPath){await Promise.resolve(this.hooks.disableRelayPath());return}r.source==="update-lane"&&this.hooks.freezeUpdateLane&&(await Promise.resolve(this.hooks.freezeUpdateLane()),this.hooks.switchSafePolicy&&await Promise.resolve(this.hooks.switchSafePolicy()))}catch{}}}const fn="NeuralShell_QuickStart",xS=new Set(["/help","/proof","/roi","/status","/workflows","/guard","/omega","/kernel","/clear"]),fS="### OMEGA Kernel — Constitutional Scan",il="https://gumroad.com/l/neuralshell-operator",bS="https://github.com/Z3r0DayZion-install/NeuralShell/issues/new?template=bug_report.md&title=Feedback%3A+",sp="neuralshell_readiness_verdict_ack_v1",ap="neuralshell_readiness_degraded_session_v1",ll="neuralshell_onboarding_dismissed_v1",hS="neuralshell_onboarding_progress_v1",op=1440,gS=1280,yS=1080,Cm="neuralshell_rail_layout_prefs_v1",_m="neuralshell_rail_collapse_prefs_v1",ip="neuralshell_rail_resize_hint_dismissed_v1",lp="neuralshell_appliance_mode_v1",cp="neuralshell_airgap_mode_v1",dp="neuralshell_demo_mode_v1",cl="neuralshell_runtime_role_v1",up="neuralshell_incidents_v1",pp="neuralshell_policy_rollout_history_v1",Ml="neuralshell_internal_gtm_mode_v1",kn=288,Nn=288,st=236,at=236,Ot=480,Tt=500,Ca=24,mp=16,wS="neuralshell_nodechain_rules_v1",vS=["releaseHealth:check","audit:verify","verification:run"],dl=Object.freeze({expanded:Object.freeze({thread:!1,workbench:!1}),balanced:Object.freeze({thread:!1,workbench:!0}),focused:Object.freeze({thread:!1,workbench:!0})});function xp(){return`Workflow_${Math.random().toString(36).slice(2,7).toUpperCase()}`}function jS(){if(typeof window>"u"||!window.localStorage)return 0;try{const t=JSON.parse(window.localStorage.getItem(hS)||"{}");return Object.values(t&&typeof t=="object"?t:{}).filter(Boolean).length}catch{return 0}}function ze(t,r,n){const s=Number.isFinite(Number(n))?Math.max(180,Math.round(Number(n))):Math.max(180,Math.round(Number(r)||180)),a=Number.isFinite(Number(r))?Math.min(Math.max(180,Math.round(Number(r))),s):Math.min(220,s),o=Number.isFinite(Number(t))?Number(t):a;return Math.round(Math.min(Math.max(o,a),s))}function kS(){if(typeof window>"u"||!window.localStorage)return{thread:kn,workbench:Nn};try{const t=JSON.parse(window.localStorage.getItem(Cm)||"{}");return{thread:ze(t&&typeof t=="object"?t.thread:kn,st,Ot),workbench:ze(t&&typeof t=="object"?t.workbench:Nn,at,Tt)}}catch{return{thread:kn,workbench:Nn}}}function NS(){const t={expanded:{thread:!1,workbench:!1},balanced:{thread:!1,workbench:!1},focused:{thread:!1,workbench:!1}};if(typeof window>"u"||!window.localStorage)return t;try{const r=JSON.parse(window.localStorage.getItem(_m)||"{}"),n=r&&typeof r=="object"?r:{};return{expanded:{thread:!!(n.expanded&&n.expanded.thread),workbench:!!(n.expanded&&n.expanded.workbench)},balanced:{thread:!!(n.balanced&&n.balanced.thread),workbench:!!(n.balanced&&n.balanced.workbench)},focused:{thread:!!(n.focused&&n.focused.thread),workbench:!!(n.focused&&n.focused.workbench)}}}catch{return t}}function fp(){if(typeof window>"u"||!window.localStorage)return jn;try{const t=JSON.parse(window.localStorage.getItem(wS)||"[]");return!Array.isArray(t)||!t.length?jn:t}catch{return jn}}function SS(){return typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem(Ml)==="1"}const bp={hud:{thread:st,workbench:at},compact:{thread:252,workbench:252},balanced:{thread:kn,workbench:Nn},wide:{thread:340,workbench:340}},CS={minimal:"hud",hud:"hud",writing:"compact",operator:"wide",coding:"wide"},_S=3500,AS=50;function za(t){return!t||typeof t!="object"?"":String(t.content??"")}function ES(t){if(!t||typeof t!="object")return!1;const r=String(t.role||"").toLowerCase();return r==="kernel"||r==="assistant"}function Am(t,r,n){const a=(Array.isArray(t)?t.slice(Math.max(0,r)):[]).filter(ES);return a.length?/^\/help\b/i.test(String(n||"").trim())?[...a].reverse().find(l=>{const u=za(l);return u.includes(Ap)||u.includes("ProofForge Operator Guide")})||null:/^\/(omega|kernel)\b/i.test(String(n||"").trim())&&[...a].reverse().find(l=>za(l).includes(fS))||a[a.length-1]:null}async function IS(t,r,n){const s=Date.now()+_S;for(;Date.now()<=s;){const a=Am(t(),r,n);if(a)return za(a);await new Promise(o=>{setTimeout(o,AS)})}return""}function PS(){k0();const t=RN(),{isPanelChromeVisible:r}=Wp(),n=Xt(k=>k.visualStyle),[s,a]=i.useState(!1),{model:o,setModel:c,workflowId:l,xpState:u,sessions:x,chatLog:p,appendChat:d,setChatLog:m,createSession:f,unlockSession:b,selectSession:h,lockSession:g,saveActiveSession:y,isSessionUnlocked:I,sessionHydrationStatus:A,sessionError:C,saveStatus:w,autoLockOnBlur:j,setAutoLockOnBlur:E,stats:N,showPalette:_,togglePalette:S,closePalette:R,showSettings:$,openPalette:U,openSettings:P,closeSettings:D}=$l(),z=i.useCallback(()=>{Lt(!1),P()},[P]);i.useEffect(()=>{typeof document>"u"||(document.documentElement.dataset.visualStyle=String(n||"operator"))},[n]);const F=String(n||"")==="frutiger-aero",J=i.useCallback(async k=>{const v=String(k||"").trim();if(!v)return;await c(v),ne(q=>({...q,model:v}));const T=wn.getState();wn.getState().setConnectionInfo({provider:T.provider,baseUrl:T.baseUrl,model:v,allowRemoteBridge:T.allowRemoteBridge,health:T.health,reason:T.reason}),await Dv(v),await Te().catch(()=>{})},[c]),ee=i.useCallback(()=>{$v(),br(!0)},[]),ie=i.useRef(p);i.useEffect(()=>{ie.current=p},[p]);const[ye,pe]=i.useState(""),[K,H]=i.useState({open:!1,mode:"create",targetSession:""}),[W,Z]=i.useState("PREVIEW"),[ce,fe]=i.useState({tierId:"free",tierLabel:"Audit-Only",capabilities:[]}),me=i.useCallback(async()=>{if(String(W||"").toUpperCase()==="OPERATOR"){ge("Operator license already active.","success");return}const k=window.prompt("Enter ProofForge Operator License (ns_op_...):");if(!k)return;const v=String(k).trim();if(!(v.startsWith("ns_op_")||v==="founder"||v==="test")){ge("Invalid license format.","error");return}if(!(window.api&&window.api.settings&&typeof window.api.settings.update=="function")){ge("Settings bridge unavailable.","error");return}await window.api.settings.update({tier:"OPERATOR"}),Z("OPERATOR"),fe(T=>({...T,tierId:"pro",tierLabel:"Operator"})),ge("License accepted. Welcome, Operator.","success")},[W]),[ke,Pe]=i.useState(!1),[_e,ne]=i.useState({provider:"ollama",baseUrl:"",model:"llama3",allowRemoteBridge:!1,health:"unknown",reason:""}),[we,De]=i.useState(!1),[re,ae]=i.useState({rgbEnabled:!1,personalityProfile:"balanced"}),[M,V]=i.useState(null),[G,te]=i.useState({enabled:!1,backend:"cpu",device:""}),[de,L]=i.useState(!1),[be,Q]=i.useState(!1),[We,B]=i.useState(!1),[oe,xe]=i.useState(!1),[Re,$e]=i.useState(!1),[tt,Ge]=i.useState(!1),[En,Dt]=i.useState(!1),[In,er]=i.useState(!1),[Dr,Ct]=i.useState(!1),[Pn,mt]=i.useState(!1),[$t,_t]=i.useState(!1),[Ae,tr]=i.useState(!1),[ro,$r]=i.useState(!1),[no,mr]=i.useState(!1),[so,Lr]=i.useState(!1),[ao,xr]=i.useState(!1),[oo,Br]=i.useState(!1),[io,Fr]=i.useState(!1),[lo,Ur]=i.useState(!1),[co,fr]=i.useState(!1),[uo,zr]=i.useState(!1),[po,Hr]=i.useState(!1),[mo,br]=i.useState(!1),[xo,Wr]=i.useState(!1),[fo,Kr]=i.useState(!1),[bo,Vr]=i.useState(!1),[ho,hr]=i.useState(!1),[go,Gr]=i.useState(!1),[yo,Jr]=i.useState(!1),[wo,qr]=i.useState(!1),[vo,Yr]=i.useState(!1),[jo,Zr]=i.useState(!1),[ko,Xr]=i.useState(!1),[No,Qr]=i.useState(!1),[So,en]=i.useState(!1),[Co,Rn]=i.useState(!1),[_o,On]=i.useState(!1),[Ao,Tn]=i.useState(!1),[Eo,Mn]=i.useState(!1),[Io,Dn]=i.useState(!1),[Po,$n]=i.useState(!1),[Ro,Ln]=i.useState(!1),[Oo,Bn]=i.useState(!1),[To,Fn]=i.useState(!1),[Mo,Un]=i.useState(!1),[Do,zn]=i.useState(!1),[$o,Hn]=i.useState(!1),[Lo,Wn]=i.useState(!1),[Bo,Kn]=i.useState(!1),[Fo,Vn]=i.useState(!1),[Uo,Gn]=i.useState(!1),[Jn,Im]=i.useState(()=>typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem(lp)==="1"),[Ls,Pm]=i.useState(()=>typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem(cp)==="1"),[Bs,Rm]=i.useState(()=>typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem(dp)==="1"),[gt,Om]=i.useState(()=>{if(typeof window>"u"||!window.localStorage)return"operator";const k=String(window.localStorage.getItem(cl)||"operator").trim().toLowerCase();return k==="founder"||k==="operator"||k==="support"||k==="security"||k==="sales"?k:"operator"}),[qn,Fs]=i.useState(()=>{if(typeof window>"u"||!window.localStorage)return[];try{const k=JSON.parse(window.localStorage.getItem(up)||"[]");return Array.isArray(k)?k:[]}catch{return[]}}),[Us,cc]=i.useState(()=>{if(typeof window>"u"||!window.localStorage)return[];try{const k=JSON.parse(window.localStorage.getItem(pp)||"[]");return Array.isArray(k)?k:[]}catch{return[]}}),[Oe,Tm]=i.useState(()=>SS()),tn=i.useMemo(()=>Yv(gt),[gt]),[zo,Yn]=i.useState(!1),[Ho,rr]=i.useState(!1),[Wo,rn]=i.useState(!1),[Ko,zs]=i.useState(!1),[gr,Lt]=i.useState(()=>typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem("neuralshell_first_boot_completed_v1")!=="1"),[Mm,Dm]=i.useState(()=>typeof window>"u"||!window.localStorage?!0:window.localStorage.getItem("neuralshell_spine_dismissed_v1")!=="1"),[$m,Lm]=i.useState(!1),[Vo,Zn]=i.useState(!1),[Go,Xn]=i.useState(!1),[Jo,qo]=i.useState("ops"),[Yo,yt]=i.useState(!1),[nn,Bm]=i.useState(()=>typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem(sp)==="1"||window.localStorage.getItem("neuralshell_readiness_checklist_v1")==="1"),[sn,Fm]=i.useState(()=>typeof window>"u"||!window.sessionStorage?!1:window.sessionStorage.getItem(ap)==="1"),[ot,Um]=i.useState({}),Hs=i.useMemo(()=>({internalGtmMode:Oe,devUnlock:!!(ot!=null&&ot.devUnlock)}),[Oe,ot==null?void 0:ot.devUnlock]),Bt=i.useMemo(()=>ru(Me.PILOT,Hs),[Hs]),Ce=i.useMemo(()=>ru(Me.INTERNAL,Hs),[Hs]),At=i.useCallback(k=>Bt&&typeof k=="function"?k:void 0,[Bt]),Ee=i.useCallback(k=>Ce&&typeof k=="function"?k:void 0,[Ce]),dc=i.useRef("unknown"),[LS,BS]=i.useState({status:"unknown"}),[Qn,uc]=i.useState([]),[Zo,zm]=i.useState(()=>[{view:"home",ts:Date.now()}]),[nr,Xo]=i.useState(0),Hm=nr>0,Wm=nr{zm(v=>[...v.slice(0,nr+1),{view:k,ts:Date.now()}].slice(-60)),Xo(v=>v+1)},[nr]);const es=i.useCallback(()=>{nr>0&&Xo(k=>k-1)},[nr]),ts=i.useCallback(()=>{nrk+1)},[nr,Zo.length]),xt=i.useCallback((k="ops")=>{qo(k||"ops"),Xn(!0)},[]),Qo=i.useCallback(()=>{sr(!0)},[]),pc=i.useCallback(()=>{rn(!0)},[]),ei=i.useCallback(()=>{zs(!0)},[]),mc=i.useCallback(()=>{xt("actions")},[xt]),xc=i.useCallback(()=>{const k=th(et(l));if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){navigator.clipboard.writeText(k).then(()=>{ge("Workpad markdown copied","success")}).catch(()=>ge("Export failed","error"));return}ge("Clipboard unavailable","warning")},[l]),fc=i.useCallback(async()=>{if(window.api&&window.api.system&&typeof window.api.system.runHealthCheck=="function")try{const k=await window.api.system.runHealthCheck(),v=!!(k&&k.ok);ge(v?"Health check passed":"Health check found issues",v?"success":"warning")}catch(k){ge(k&&k.message?k.message:"Health check failed","error")}},[]);i.useEffect(()=>{Rv({openOperatorInbox:()=>xt("ops"),openWorkpad:Qo,openCalendar:pc,openGuidedActions:mc,openTrustReport:ei,runHealthCheck:fc,exportWorkpad:xc})},[xc,mc,pc,xt,ei,Qo,fc]);const[ti,sr]=i.useState(()=>typeof window<"u"&&(window.location.pathname==="/scratchpad"||window.location.hash==="#/scratchpad")),[Xe,Km]=i.useState(()=>typeof window<"u"&&Number.isFinite(window.innerWidth)?window.innerWidth:op),[ar,rs]=i.useState(!1),[Ft,ns]=i.useState(!1),[Ye,Ws]=i.useState(()=>kS()),[rt,Vm]=i.useState(()=>NS()),[ri,Gm]=i.useState(()=>typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem(ip)!=="1"),[FS,Jm]=i.useState(""),[ni,bc]=i.useState(xp()),[Ks,si]=i.useState(""),[hc,yr]=i.useState(""),[qm,gc]=i.useState(!1),[Ym,yc]=i.useState(!1),[wc,Zm]=i.useState({outputPath:"",sha256:""}),[or,vc]=i.useState(()=>typeof window>"u"||!window.localStorage?!1:!(window.localStorage.getItem(ll)==="1")&&jS()<4),ai=i.useRef(null),oi=i.useRef(null),jc=i.useRef(null),kc=i.useRef(null),ii=i.useRef(null),Nc=i.useId(),Sc=i.useId(),Cc=i.useRef(0),li=i.useRef(new Map),ci=i.useRef(new Map),wr=i.useRef(null),_c=i.useRef(null),Vs=i.useRef(""),Gs=i.useRef(null),Ac=i.useRef(""),Ec=i.useRef(""),Ze=String(W||"").toUpperCase()==="AUDITOR",Ic=Array.isArray(ce.capabilities)?ce.capabilities:[],di=Ic.includes("onboarding_wizard")||String(ce.tierId||"")==="enterprise",Xm=Ic.includes("issue_assist"),Qm=i.useMemo(()=>{const v=(Array.isArray(p)?p:[]).reduce((T,q)=>{const Y=String(q&&q.content?q.content:"");return T+Math.ceil(Y.length/4)},0);return Math.max(0,128e3-v)},[p]),wt=JN(String(l||"default")),ss=i.useMemo(()=>Object.keys(wt.remoteCursors||{}).length,[wt.remoteCursors]),{runtimeState:Se,refreshRuntimeState:ft}=XN({connectionInfo:_e,workflowId:String(l||""),runtimeTier:String(W||""),sessionHydrationStatus:String(A||""),collabConnected:!!wt.connected,collabRoomId:String(wt.roomId||"default"),collabPeerCount:ss}),{report:Js,loading:Pc,error:Rc,refresh:ui}=nS({enabled:!0,intervalMs:12e3}),{events:an}=QN(),ex=tS(),vt=iS(),{steps:Oc,progress:Tc,open:Et,busyStepId:tx,allDone:vr,completeStep:Mc,markSkipped:Dc,runStep:$c,dismiss:as,reopen:Ut,reset:rx}=ex;i.useEffect(()=>{if(Et||or)return;const k=window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("neuralshell:focus-composer"))},500);return()=>window.clearTimeout(k)},[Et,or,l]),i.useCallback(({trustState:k}={})=>{if(String(k||"").toUpperCase()==="MISSING_SECRET"){z(),window.setTimeout(()=>{const T=document.getElementById("section-connection");T&&typeof T.scrollIntoView=="function"&&T.scrollIntoView({behavior:"smooth",block:"start"})},180);return}Ut()},[z,Ut]);const zt=i.useMemo(()=>(Array.isArray(Qn)?Qn:[]).filter(k=>!k.acknowledged),[Qn]),os=i.useMemo(()=>zt.length?zt.some(k=>String(k.severity||"")==="critical")?"fatal":zt.some(k=>String(k.severity||"")==="degraded"||String(k.severity||"")==="warning")?"degraded":"running":String(Se&&Se.watchdog&&Se.watchdog.status||"running"),[Se,zt]),nx=i.useMemo(()=>{const k=[...Array.isArray(p)?p:[]].reverse().find(v=>Array.isArray(v&&v.stdoutLines)&&v.stdoutLines.length);return k?k.stdoutLines.slice(-120).join(` +`):""},[p]),Lc=i.useRef(ss),Ue=i.useMemo(()=>Xe>=gS?"expanded":Xe>=yS?"balanced":"focused",[Xe]),on=Ue!=="focused",is=Ue==="expanded",qs=Ue==="focused",Ys=Ue!=="expanded",pi=rt[Ue]||dl[Ue]||dl.expanded,ls=on&&!!pi.thread,Zs=is&&!!pi.workbench,Bc=r("thread-rail",!0),mi=r("workbench-rail",!0),ln=on&&!ls&&Bc,Xs=is&&!Zs&&mi,xi=Ue==="expanded",Fc=xi&&!!pi.workbench,Uc=xi&&!Fc&&mi,sx=ri&&ln,ax=i.useMemo(()=>{const k=Object.entries(bp).find(([,v])=>{const T=ze(v.thread,st,Ot),q=ze(v.workbench,at,Tt);return T===Ye.thread&&q===Ye.workbench});return k?k[0]:""},[Ye.thread,Ye.workbench]),Qs=i.useMemo(()=>{const k=Math.floor(Xe*(Ue==="expanded"?.34:.42));return ze(k,st,Ot)},[Ue,Xe]),ea=i.useMemo(()=>{const k=Math.floor(Xe*.34);return ze(k,at,Tt)},[Xe]),fi=i.useMemo(()=>ze(Ye.thread,st,Math.min(Ot,Xe-Ca)),[Ye.thread,Xe]),bi=i.useMemo(()=>ze(Ye.workbench,at,Math.min(Tt,Xe-Ca)),[Ye.workbench,Xe]),hi=i.useMemo(()=>ze(Ye.thread,st,Qs),[Qs,Ye.thread]),gi=i.useMemo(()=>ze(Ye.workbench,at,ea),[ea,Ye.workbench]);i.useEffect(()=>{const k=()=>{const v=Number.isFinite(window.innerWidth)?window.innerWidth:op;Km(v)};return k(),window.addEventListener("resize",k),()=>window.removeEventListener("resize",k)},[]),i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(lp,Jn?"1":"0")},[Jn]),i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(cp,Ls?"1":"0")},[Ls]),i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(dp,Bs?"1":"0")},[Bs]),i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(Ml,Oe?"1":"0")},[Oe]),i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(cl,String(gt||"operator"))},[gt]),i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(up,JSON.stringify(Array.isArray(qn)?qn:[]))},[qn]),i.useEffect(()=>{typeof window>"u"||!window.localStorage||window.localStorage.setItem(pp,JSON.stringify(Array.isArray(Us)?Us:[]))},[Us]),i.useEffect(()=>{Ue!=="focused"&&ar&&rs(!1),Ue==="expanded"&&Ft&&ns(!1)},[Ue,ar,Ft]),i.useEffect(()=>{if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(Cm,JSON.stringify({thread:ze(Ye.thread,st,Ot),workbench:ze(Ye.workbench,at,Tt)}))}catch{}},[Ye.thread,Ye.workbench]),i.useEffect(()=>{if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(_m,JSON.stringify({expanded:{thread:!!(rt.expanded&&rt.expanded.thread),workbench:!!(rt.expanded&&rt.expanded.workbench)},balanced:{thread:!!(rt.balanced&&rt.balanced.thread),workbench:!!(rt.balanced&&rt.balanced.workbench)},focused:{thread:!!(rt.focused&&rt.focused.thread),workbench:!!(rt.focused&&rt.focused.workbench)}}))}catch{}},[rt]);const nt=i.useCallback(()=>(Cc.current+=1,`msg-${Date.now()}-${Cc.current}`),[]),zc=i.useCallback((k,v={})=>{const T=nt();return d({id:T,role:"kernel",content:String(k||""),...v}),T},[d,nt]),ta=i.useCallback((k,v)=>{const T=String(k||"").trim();if(!T)return;const q=v&&typeof v=="object"?v:{};m(Y=>Array.isArray(Y)?Y.map(ue=>{if(String(ue&&ue.id?ue.id:"")!==T)return ue;const se=Array.isArray(ue.stdoutLines)?[...ue.stdoutLines]:[],le=String(q.line||"").trim();return le&&se.push(le),{...ue,stdoutLines:se.slice(-240),stdoutDone:!!q.done||!!ue.stdoutDone}}):Y)},[m]),Hc=i.useCallback(async(k,v)=>{if(window.api&&window.api.proof&&typeof window.api.proof.exec=="function")try{const T=await window.api.proof.exec({command:k}),q=String(T&&T.sessionId?T.sessionId:"").trim();if(!q)return;li.current.set(q,String(v||"").trim()),ci.current.set(q,{command:String(k||"").trim().toLowerCase(),messageId:String(v||"").trim()})}catch(T){ta(v,{line:`[${k}] stream failed: ${T&&T.message?T.message:String(T)}`,done:!0})}},[ta]),Te=i.useCallback(async()=>{var v,T,q,Y,ue,se;let k=!1;try{const[le,Le,ve]=await Promise.all([(T=(v=window.api)==null?void 0:v.settings)!=null&&T.get?window.api.settings.get():Promise.resolve({}),(Y=(q=window.api)==null?void 0:q.state)!=null&&Y.get?window.api.state.get():Promise.resolve({}),(se=(ue=window.api)==null?void 0:ue.llm)!=null&&se.health?window.api.llm.health().catch(()=>null):Promise.resolve(null)]);k=!0,Z(String(le&&le.tier||"PREVIEW").toUpperCase()),fe({tierId:String(le&&le.tierId||"free"),tierLabel:String(le&&le.tierLabel||"Audit-Only"),capabilities:Array.isArray(le&&le.capabilities)?le.capabilities:[]});const jt=Array.isArray(le&&le.connectionProfiles)?le.connectionProfiles:[],Je=jt.find(Nr=>String(Nr&&Nr.id||"")===String(le&&le.activeProfileId||""))||jt[0]||null,Ne=String(le&&le.provider||Je&&Je.provider||ve&&ve.provider||"ollama");ne({provider:Ne,baseUrl:String(le&&le.ollamaBaseUrl||Ne!=="ollama"&&Je&&Je.baseUrl||Ne!=="ollama"&&ve&&ve.baseUrl||""),model:String(Le&&Le.model||ve&&ve.model||o||"llama3"),allowRemoteBridge:!!(le&&le.allowRemoteBridge),health:ve&&ve.ok?"online":ve?"offline":"unknown",reason:ve&&!ve.ok?String(ve.reason||"Bridge unavailable"):""}),Um(le&&typeof le=="object"?le:{});const It=ve&&ve.ok?"online":ve?"offline":"unknown";String(dc.current||"unknown")==="online"&&It==="offline"&&ge("Bridge went offline — check Settings or Task Manager","error"),dc.current=It,wn.getState().setConnectionInfo({provider:String(le&&le.provider||Je&&Je.provider||ve&&ve.provider||"ollama"),baseUrl:String(le&&le.ollamaBaseUrl||Je&&Je.baseUrl||ve&&ve.baseUrl||""),model:String(Le&&Le.model||ve&&ve.model||o||"llama3"),allowRemoteBridge:!!(le&&le.allowRemoteBridge),health:ve&&ve.ok?"online":ve?"offline":"unknown",reason:ve&&!ve.ok?String(ve.reason||"Bridge unavailable"):""}),ae({rgbEnabled:!!(le&&le.rgbEnabled),personalityProfile:String(le&&le.personalityProfile||"balanced")})}catch{}finally{k&&Pe(!0)}},[o]);i.useEffect(()=>{Te()},[Te]),i.useEffect(()=>{!(ot!=null&&ot.devUnlock)||typeof window>"u"||!window.localStorage||(window.localStorage.setItem(Ml,"1"),window.localStorage.setItem(cl,"founder"),Tm(!0))},[ot==null?void 0:ot.devUnlock]);const ox=i.useCallback(async()=>{var k,v,T,q,Y,ue;if(!((v=(k=window.api)==null?void 0:k.bridge)!=null&&v.test&&((q=(T=window.api)==null?void 0:T.settings)!=null&&q.get))){ge("Bridge verify unavailable","warning");return}try{const se=await window.api.settings.get(),le=Array.isArray(se==null?void 0:se.connectionProfiles)?se.connectionProfiles:[],Le=String((se==null?void 0:se.activeProfileId)||"").trim(),ve=le.find(Ne=>String((Ne==null?void 0:Ne.id)||"")===Le)||le[0]||null;if(!ve){ge("No connection profile configured","warning");return}const jt=await window.api.bridge.test({provider:String(ve.provider||se.provider||"ollama"),baseUrl:String(ve.baseUrl||se.ollamaBaseUrl||""),defaultModel:String(ve.defaultModel||se.defaultModel||"llama3"),allowRemoteBridge:!!se.allowRemoteBridge,apiKey:se.apiKey,apiKeyPresent:se.apiKeyPresent});await Te();const Je=!!(jt&&jt.ok);ge(Je?`Bridge online (${Number(jt.modelCount)||0} models)`:"Bridge offline — start Ollama or check Settings",Je?"success":"warning"),(ue=(Y=window.api)==null?void 0:Y.state)!=null&&ue.logProfileEvent&&ve.id&&await window.api.state.logProfileEvent(String(ve.id),"verification_requested",Je?"Manual verification succeeded from profile bar.":"Manual verification failed from profile bar.")}catch(se){await Te().catch(()=>{}),ge(ml(se==null?void 0:se.message)||"Verification failed","error")}},[Te]),[Wc,Kc]=i.useState(!1),cs=!!(typeof window<"u"&&window.api&&window.api.support&&typeof window.api.support.exportBundle=="function"),yi=i.useCallback(async()=>{if(cs){Kc(!0);try{const k=await window.api.support.exportBundle({includeUserText:!1,workpadSnapshots:yl(),timeProof:Cl({workflowId:l})});k&&k.ok?(ge(`Evidence exported: ${k.outputPath}`,"success"),window.dispatchEvent(new window.CustomEvent("neuralshell:support-bundle-exported",{detail:{outputPath:String(k.outputPath||""),sha256:String(k.sha256||"")}}))):ge("Evidence export failed","error")}catch(k){ge(k&&k.message?k.message:"Evidence export failed","error")}finally{Kc(!1)}}},[cs]),Vc=i.useMemo(()=>Hl({connectionInfo:_e,watchdogStatus:os,incidentCount:zt.length,setupBlocked:!!(Et&&!vr)}),[_e,os,zt.length,Et,vr]),Gc=i.useMemo(()=>Wl(Vc,{sessionDegradedDismissed:sn,acknowledgedReady:nn}),[Vc,sn,nn]),ix=i.useCallback(()=>{typeof window<"u"&&window.localStorage&&(window.localStorage.setItem(sp,"1"),window.localStorage.setItem("neuralshell_readiness_checklist_v1","1")),Bm(!0),yt(!1),window.dispatchEvent(new window.CustomEvent("neuralshell:focus-composer")),ge("Ready — composer focused","success")},[]),lx=i.useCallback(()=>{typeof window<"u"&&window.sessionStorage&&window.sessionStorage.setItem(ap,"1"),Fm(!0),yt(!1)},[]),cn=Uy({isThinking:we,isTyping:!!String(ye||"").trim(),connectionHealth:_e==null?void 0:_e.health});ON({enabled:re.rgbEnabled,moodEngine:cn,personalityProfile:re.personalityProfile}),i.useEffect(()=>{if(!re.rgbEnabled){V(null);return}let k=!0;const v=async()=>{if(window.api&&window.api.rgb&&typeof window.api.rgb.status=="function")try{const q=await window.api.rgb.status();k&&V(q&&typeof q=="object"?q:null)}catch{k&&V(null)}};v();const T=window.setInterval(v,5e3);return()=>{k=!1,window.clearInterval(T)}},[re.rgbEnabled,cn==null?void 0:cn.rgbMood]);const Jc=i.useRef($);i.useEffect(()=>{const k=Jc.current,v=$;(v&&!k||!v&&k)&&Te(),Jc.current=v},[$,Te]),i.useEffect(()=>{let k=!0;const v=async()=>{try{if(!(window.api&&window.api.accel&&typeof window.api.accel.status=="function"))return;const q=await window.api.accel.status();if(!k)return;te(q&&typeof q=="object"?{enabled:!!q.enabled,backend:String(q.backend||"cpu"),device:String(q.device||"")}:{enabled:!1,backend:"cpu",device:""})}catch{}};v();const T=window.setInterval(v,2e4);return()=>{k=!1,window.clearInterval(T)}},[]),i.useEffect(()=>{const k=window.setInterval(()=>{Te()},12e3);return()=>{window.clearInterval(k)}},[Te]),i.useEffect(()=>{const k=()=>{Te()};return window.addEventListener("neuralshell:settings-updated",k),()=>window.removeEventListener("neuralshell:settings-updated",k)},[Te]),i.useEffect(()=>{ke&&(di||or&&vc(!1))},[di,ke,or]),i.useEffect(()=>{if(window.api&&window.api.proof&&typeof window.api.proof.onStdout=="function")return window.api.proof.onStdout(k=>{const v=k&&typeof k=="object"?k:{},T=String(v.sessionId||"").trim();if(!T)return;const q=li.current.get(T),Y=ci.current.get(T);q&&(ta(q,{line:String(v.line||""),done:!!v.done}),v.done&&(li.current.delete(T),ci.current.delete(T),Y&&String(Y.command||"")==="proof"&&(X("proof.passed",{messageId:String(Y.messageId||""),sessionId:T},{source:"proof",severity:"info"}),typeof window<"u"&&window.localStorage&&(window.localStorage.setItem("neuralshell_proof_last_status_v1","passed"),window.localStorage.setItem("neuralshell_proof_stage_v1","complete")))))})},[ta]),i.useEffect(()=>{const k=v=>{const T=v&&v.detail&&typeof v.detail=="object"?v.detail:{};Zm({outputPath:String(T.outputPath||""),sha256:String(T.sha256||"")})};return window.addEventListener("neuralshell:support-bundle-exported",k),()=>{window.removeEventListener("neuralshell:support-bundle-exported",k)}},[]),i.useEffect(()=>{const k=()=>Lm(!0);return window.addEventListener("neuralshell:support-bundle-exported",k),()=>{window.removeEventListener("neuralshell:support-bundle-exported",k)}},[]);const cx=i.useCallback(()=>{Dm(!1),typeof window<"u"&&window.localStorage&&window.localStorage.setItem("neuralshell_spine_dismissed_v1","1")},[]);i.useEffect(()=>{!ke||!Et||typeof window>"u"||!window.localStorage||window.localStorage.getItem(ll)==="1"&&as()},[as,Et,ke]),i.useEffect(()=>{if(ke){if(gr||Et||or){yt(!1);return}if(nn&&sn){yt(!1);return}if(!Gc.shouldPrompt){yt(!1);return}yt(!0)}},[Et,vr,nn,Gc.shouldPrompt,ke,sn,gr,or]),i.useEffect(()=>{const k=v=>{const T=v&&v.detail?String(v.detail):"LLM stream failed";ge(T,"error")};return window.addEventListener("llm-stream-error",k),()=>window.removeEventListener("llm-stream-error",k)},[]),i.useEffect(()=>{const k=Number(Lc.current||0),v=Number(ss||0);v>k?X("collab.peer.joined",{roomId:String(wt.roomId||"default"),peerCount:v},{source:"collab",severity:"info"}):v{if(!(Se&&Se.updateLane))return;const k=String(Se.updateLane.signatureState||"").toLowerCase();k!==Ac.current&&(Ac.current=k,!(k==="verified"||k==="unknown")&&X("update.verification.failed",{signatureState:k,stagedUpdateAvailable:!!Se.updateLane.stagedUpdateAvailable},{source:"update-lane",severity:"critical"}))},[Se]),i.useEffect(()=>{const k=Array.isArray(an)&&an.length?an[an.length-1]:null;!k||!k.id||String(Ec.current||"")!==String(k.id)&&(Ec.current=String(k.id),Fs(v=>(Array.isArray(v)?v:[]).map(q=>{if(String(q&&q.status?q.status:"")!=="open")return q;const Y=Array.isArray(q.timeline)?q.timeline:[];return{...q,timeline:[...Y,{at:String(k.at||new Date().toISOString()),type:String(k.type||"runtime.event"),source:String(k.source||"runtime"),detail:k.payload&&typeof k.payload=="object"?k.payload:{}}].slice(-400)}})))},[an]);const Ht=i.useCallback(k=>{const v=String(k||"").trim().toLowerCase();if(v==="mission"||v==="mission-control"){B(!0);return}if(v==="demo"||v==="demo-flow"||v==="demo_flow"){fr(!0);return}if(v==="fleet"||v==="fleet-control"){if(!tn.canManageFleet){X("role.access.denied",{panel:v,role:gt},{source:"roles",severity:"warning"});return}xe(!0);return}if(v==="recovery"||v==="recovery-center"){if(!tn.canRunRecovery){X("role.access.denied",{panel:v,role:gt},{source:"roles",severity:"warning"});return}$e(!0);return}if(v==="appliance"||v==="appliance-console"){if(!tn.canManageAppliance){X("role.access.denied",{panel:v,role:gt},{source:"roles",severity:"warning"});return}Ge(!0);return}if(v==="airgap"||v==="air-gap"||v==="airgap-operations"){Dt(!0);return}if(v==="trust"||v==="trust-fabric"||v==="pki"){er(!0);return}if(v==="hardware"||v==="hardware-appliance"){Ct(!0);return}if(v==="courier"||v==="courier-transfer"){mt(!0);return}if(v==="continuity"||v==="continuity-drills"){_t(!0);return}if(v==="procurement"||v==="procurement-command"){tr(!0);return}if(v==="tamper"||v==="tamper-simulation"){$r(!0);return}if(v==="institutional"||v==="institutional-command"){mr(!0);return}if(v==="deployment"||v==="deployment-program"||v==="deployment_program"){zr(!0);return}if(v==="training"||v==="training-delivery"||v==="training_delivery"){Hr(!0);return}if(v==="support"||v==="support-ops"||v==="support_ops"){br(!0);return}if(v==="buyer"||v==="buyer-journey"||v==="buyer_journey"){Wr(!0);return}if(v==="pilot"||v==="pilot-conversion"||v==="pilot_conversion"){Kr(!0);return}if(v==="commercial"||v==="commercial-packages"||v==="commercial_packages"){Vr(!0);return}if(v==="launch"||v==="field-launch"||v==="field_launch"){hr(!0);return}if(v==="partner"||v==="partner-rollout"||v==="partner_rollout"){Gr(!0);return}if(v==="buyerops"||v==="buyer-ops"||v==="buyer_ops"){Jr(!0);return}if(v==="demotopilot"||v==="demo-to-pilot"||v==="demo_to_pilot"){qr(!0);return}if(v==="expansion"||v==="pilot-expansion"||v==="pilot_expansion"){Yr(!0);return}if(v==="renewal"||v==="renewal-risk"||v==="renewal_risk"){Zr(!0);return}if(v==="launchweek"||v==="launch-week"||v==="launch_week"){Xr(!0);return}if(v==="followup"||v==="followup-generator"||v==="followup_generator"){Qr(!0);return}if(v==="feedback"||v==="field-feedback"||v==="field_feedback"){en(!0);return}if(v==="partner-certification"||v==="partner_certification"){Rn(!0);return}if(v==="managed-services"||v==="managed_services"){On(!0);return}if(v==="strategic-account"||v==="strategic_account"){Tn(!0);return}if(v==="portfolio-rollout"||v==="portfolio_rollout"){Mn(!0);return}if(v==="revenue-ops"||v==="revenue_ops"){Dn(!0);return}if(v==="channel-expansion"||v==="channel_expansion"){$n(!0);return}if(v==="cross-account-renewal"||v==="cross_account_renewal"){Ln(!0);return}if(v==="executive-scale"||v==="executive_scale"){Bn(!0);return}if(v==="ecosystem-portfolio"||v==="ecosystem_portfolio"){Fn(!0);return}if(v==="service-line"||v==="service_line"){Un(!0);return}if(v==="partner-network-governance"||v==="partner_network_governance"){zn(!0);return}if(v==="global-planning"||v==="global_planning"){Hn(!0);return}if(v==="ecosystem-revenue"||v==="ecosystem_revenue"){Wn(!0);return}if(v==="board-operating-pack"||v==="board_operating_pack"){Kn(!0);return}if(v==="licensed-operator"||v==="licensed_operator"){Vn(!0);return}if(v==="ecosystem-command"||v==="ecosystem_command"){Gn(!0);return}if(v==="shift"||v==="shift-console"){Lr(!0);return}if(v==="incident"||v==="incident-mode"){if(!tn.canDeclareIncidents){X("role.access.denied",{panel:v,role:gt},{source:"roles",severity:"warning"});return}xr(!0);return}if(v==="policy-rollout"||v==="rollout"){if(!tn.canRunPolicyRollouts){X("role.access.denied",{panel:v,role:gt},{source:"roles",severity:"warning"});return}Br(!0);return}if(v==="update-packs"||v==="offline-updates"){Fr(!0);return}if(v==="missions"||v==="mission-scheduler"){Ur(!0);return}if(v==="watchdog"){rr(!0);return}if(v==="nodechain"){Yn(!0);return}if(v==="firstboot"||v==="first-boot"){Ut(),Lt(!0);return}if(v==="split"||v==="split-workspace"){Zn(!0);return}if(v==="task-manager"||v==="tasks"||v==="inbox"||v==="operator-inbox"){xt("ops");return}v==="settings"&&P()},[gt,xt,P,Ut,tn]),wi=i.useCallback(async()=>{X("runtime.snapshot.requested",{source:"nodechain"},{source:"snapshots",severity:"info"})},[]),qc=i.useMemo(()=>({showAlert:async k=>{const v=k&&typeof k=="object"?k:{};X("runtime.watchdog.alert",v,{source:"nodechain",severity:String(v.severity||"warning").toLowerCase()})},openPanel:async k=>{const v=String(k&&k.panel?k.panel:"");Ht(v)},shareProofBadge:async()=>{window.api&&window.api.system&&typeof window.api.system.openExternal=="function"&&await window.api.system.openExternal("https://raw.githubusercontent.com/Z3r0DayZion-install/NeuralShell/main/assets/proof_badge.svg")},snapshotState:async()=>{await wi()},disableRelay:async()=>{if(!(window.api&&window.api.settings&&typeof window.api.settings.get=="function"))return;const k=await window.api.settings.get();await window.api.settings.update({...k||{},proofRelayEnabled:!1}),X("relay.failed",{reason:"NodeChain disabled relay path after failures."},{source:"relay",severity:"degraded"}),await Te(),await ft()},blockUpdateApply:async()=>{window.api&&window.api.autoUpdate&&typeof window.api.autoUpdate.setPolicy=="function"&&await window.api.autoUpdate.setPolicy({autoApply:!1,blockedBy:"nodechain"})},promptVaultSave:async()=>{window.dispatchEvent(new window.CustomEvent("neuralshell:prompt-vault-save"))},writeAuditLog:async k=>{window.api&&window.api.logger&&typeof window.api.logger.log=="function"&&await window.api.logger.log("info","nodechain-action",k||{})},switchSafePolicy:async()=>{if(!(window.api&&window.api.settings&&typeof window.api.settings.get=="function"))return;const k=await window.api.settings.get();await window.api.settings.update({...k||{},offlineOnlyEnforced:!0,allowRemoteBridge:!1,autoUpdateChannel:"frozen"}),await Te(),await ft()},runLocalScript:async k=>{if(!(window.api&&window.api.command&&typeof window.api.command.run=="function"))return;const v=String(k&&k.commandId?k.commandId:"").trim(),T=Array.isArray(k&&k.args)?k.args:[];await window.api.command.run(v,T)}}),[Ht,Te,ft,wi]);i.useEffect(()=>{const k=fp(),v=JSON.stringify(k||[]),T=new H0(k,qc,vS);_c.current=T,Vs.current=v,T.start();const q=K0(Y=>{const ue=fp(),se=JSON.stringify(ue||[]);se!==Vs.current&&(Vs.current=se,T.setRules(ue)),T.dispatch({type:String(Y&&Y.type?Y.type:""),at:String(Y&&Y.at?Y.at:new Date().toISOString()),payload:Y&&Y.payload&&typeof Y.payload=="object"?Y.payload:{}},!1).then(le=>{if(!Array.isArray(le)||!le.length)return;const Le=le.some(ve=>String(ve.status||"")==="failed");X("nodechain.rule.executed",{eventType:String(Y&&Y.type?Y.type:""),runs:le.length,failed:Le},{source:"nodechain",severity:Le?"warning":"info"})}).catch(()=>{})});return()=>{q(),T.stop(),_c.current=null,Vs.current=""}},[qc]),i.useEffect(()=>{Gs.current||(Gs.current=new mS({retryProviderProbe:async()=>{await Te(),await ft()},disableRelayPath:async()=>{if(!(window.api&&window.api.settings&&typeof window.api.settings.get=="function"))return;const v=await window.api.settings.get();await window.api.settings.update({...v||{},proofRelayEnabled:!1}),await Te(),await ft()},freezeUpdateLane:async()=>{window.api&&window.api.autoUpdate&&typeof window.api.autoUpdate.setPolicy=="function"&&await window.api.autoUpdate.setPolicy({autoApply:!1,frozenBy:"watchdog"})},switchSafePolicy:async()=>{if(!(window.api&&window.api.settings&&typeof window.api.settings.get=="function"))return;const v=await window.api.settings.get();await window.api.settings.update({...v||{},allowRemoteBridge:!1,offlineOnlyEnforced:!0,autoUpdateChannel:"frozen"}),await Te(),await ft()},onAlert:v=>{X("runtime.watchdog.alert",{source:v.source,message:v.message,suggestedAction:v.suggestedAction},{source:"watchdog",severity:v.severity})}}));const k=Gs.current;!k||!(Se&&Se.providerHealth)||k.evaluate({providerHealth:{online:!!Se.providerHealth.online,activeProvider:String(Se.providerHealth.activeProvider||"ollama"),model:String(Se.providerHealth.model||"llama3")},relayState:{enabled:!!(Se.relayState&&Se.relayState.enabled),relayError:String(Se.relayState&&Se.relayState.relayError?Se.relayState.relayError:"")},updateLane:{signatureState:String(Se.updateLane&&Se.updateLane.signatureState?Se.updateLane.signatureState:"unknown"),stagedUpdateAvailable:!!(Se.updateLane&&Se.updateLane.stagedUpdateAvailable)},vaultState:{locked:!!(Se.vaultState&&Se.vaultState.locked),exportImportStatus:String(Se.vaultState&&Se.vaultState.exportImportStatus?Se.vaultState.exportImportStatus:"idle")}}).then(v=>{uc(Array.isArray(v)?v:[])}).catch(()=>{})},[Te,ft,Se]),i.useEffect(()=>{const k=()=>{d({id:nt(),role:"kernel",content:"NodeChain prompted a vault save. Open Settings > Vault to seal the current runtime state."})};return window.addEventListener("neuralshell:prompt-vault-save",k),()=>{window.removeEventListener("neuralshell:prompt-vault-save",k)}},[d,nt]);const ra=i.useCallback(()=>{if(Ze){d({role:"kernel",content:"Audit-only mode is active. Session creation is disabled in this runtime."});return}H({open:!0,mode:"create",targetSession:""}),bc(xp()),si(""),yr("")},[d,Ze]),jr=i.useCallback(k=>{H({open:!0,mode:"unlock",targetSession:String(k||"")}),si(""),yr("")},[]),kr=i.useCallback(()=>{H({open:!1,mode:"create",targetSession:""}),yr("")},[]);i.useEffect(()=>{if(!K.open)return;const k=document.body.style.overflow;document.body.style.overflow="hidden",document.activeElement&&typeof document.activeElement.focus=="function"&&(ii.current=document.activeElement);const v=K.mode==="create"?ai.current:oi.current;v&&typeof v.focus=="function"&&v.focus();const T=q=>{if(q.key!=="Tab")return;const Y=[ai.current,oi.current,jc.current,kc.current].filter(Le=>Le&&!Le.disabled);if(!Y.length)return;const ue=Y[0],se=Y[Y.length-1],le=document.activeElement;if(q.shiftKey){(le===ue||!Y.includes(le))&&(q.preventDefault(),se.focus());return}(le===se||!Y.includes(le))&&(q.preventDefault(),ue.focus())};return document.addEventListener("keydown",T),()=>{document.removeEventListener("keydown",T),document.body.style.overflow=k;const q=ii.current;q&&typeof q.focus=="function"&&q.focus(),ii.current=null}},[K.open,K.mode]),i.useEffect(()=>{const k=v=>{v.button===3&&(v.preventDefault(),es()),v.button===4&&(v.preventDefault(),ts())};return window.addEventListener("mouseup",k),()=>window.removeEventListener("mouseup",k)},[es,ts]),i.useEffect(()=>{const k=ue=>{const se=ue&&ue.detail?String(ue.detail):"system";Xt.getState().setTheme(se)},v=()=>{ra()},T=()=>{U()},q=()=>{P()},Y=()=>{xt("ops")};return window.addEventListener("tray:set-theme",k),window.addEventListener("tray:new-workflow",v),window.addEventListener("tray:open-palette",T),window.addEventListener("tray:open-settings",q),window.addEventListener("tray:open-task-manager",Y),()=>{window.removeEventListener("tray:set-theme",k),window.removeEventListener("tray:new-workflow",v),window.removeEventListener("tray:open-palette",T),window.removeEventListener("tray:open-settings",q),window.removeEventListener("tray:open-task-manager",Y)}},[ra,xt,U,P]),i.useEffect(()=>{const k=v=>{const T=document.activeElement,q=T&&T.tagName?String(T.tagName).toLowerCase():"",Y=!!(T&&(q==="input"||q==="textarea"||T.isContentEditable||T.dataset&&(T.dataset.testid==="chat-input"||T.dataset.testid==="slash-palette-input")));if(v.altKey&&v.key==="ArrowLeft"){v.preventDefault(),es();return}if(v.altKey&&v.key==="ArrowRight"){v.preventDefault(),ts();return}if((v.ctrlKey||v.metaKey)&&v.key===","){v.preventDefault(),P();return}if((v.ctrlKey||v.metaKey)&&v.shiftKey&&(v.key==="t"||v.key==="T")){v.preventDefault(),Xn(se=>se?!1:(qo("ops"),!0));return}if((v.ctrlKey||v.metaKey)&&v.shiftKey&&(v.key==="n"||v.key==="N")){v.preventDefault(),sr(se=>!se);return}if((v.ctrlKey||v.metaKey)&&v.shiftKey&&(v.key==="c"||v.key==="C")){v.preventDefault(),rn(se=>!se);return}if((v.ctrlKey||v.metaKey)&&v.shiftKey&&(v.key==="a"||v.key==="A")){v.preventDefault(),Xn(se=>se&&Jo==="actions"?!1:(qo("actions"),!0));return}if((v.ctrlKey||v.metaKey)&&v.key==="k"){if(v.preventDefault(),_){S();return}if(Y)return;S()}if(v.altKey&&(v.code==="BracketLeft"||v.code==="BracketRight")&&!Y){const se=v.code==="BracketLeft"?-mp:mp,le=v.shiftKey?"workbench":"thread";(le==="workbench"?is||Ys:on||qs)&&(v.preventDefault(),Ws(ve=>{const jt=le==="workbench"?at:st,Je=le==="workbench"?Tt:Ot,Ne=Number.isFinite(Number(ve[le]))?Number(ve[le]):le==="workbench"?Nn:kn,It=ze(Ne+se,jt,Je);return It===ve[le]?ve:{...ve,[le]:It}}))}v.key==="Escape"&&(R(),D(),be&&Q(!1),We&&B(!1),oe&&xe(!1),Re&&$e(!1),tt&&Ge(!1),En&&Dt(!1),In&&er(!1),Dr&&Ct(!1),Pn&&mt(!1),$t&&_t(!1),Ae&&tr(!1),ro&&$r(!1),no&&mr(!1),co&&fr(!1),uo&&zr(!1),po&&Hr(!1),mo&&br(!1),xo&&Wr(!1),fo&&Kr(!1),bo&&Vr(!1),ho&&hr(!1),go&&Gr(!1),yo&&Jr(!1),wo&&qr(!1),vo&&Yr(!1),jo&&Zr(!1),ko&&Xr(!1),No&&Qr(!1),So&&en(!1),Co&&Rn(!1),_o&&On(!1),Ao&&Tn(!1),Eo&&Mn(!1),Io&&Dn(!1),Po&&$n(!1),Ro&&Ln(!1),Oo&&Bn(!1),To&&Fn(!1),Mo&&Un(!1),Do&&zn(!1),$o&&Hn(!1),Lo&&Wn(!1),Bo&&Kn(!1),Fo&&Vn(!1),Uo&&Gn(!1),so&&Lr(!1),ao&&xr(!1),oo&&Br(!1),io&&Fr(!1),lo&&Ur(!1),zo&&Yn(!1),Ho&&rr(!1),Wo&&rn(!1),Ko&&zs(!1),gr&&Lt(!1),Vo&&Zn(!1),Go&&Xn(!1),ti&&sr(!1),Yo&&yt(!1),K.open&&kr(),ar&&rs(!1),Ft&&ns(!1))};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[S,R,D,P,es,ts,be,We,oe,Re,tt,En,In,Dr,Pn,$t,Ae,ro,no,co,uo,po,mo,xo,fo,bo,ho,go,yo,wo,vo,jo,ko,No,So,Co,_o,Ao,Eo,Io,Po,Ro,Oo,To,Mo,Do,$o,Lo,Bo,Fo,Uo,so,ao,oo,io,lo,zo,Ho,Wo,Ko,Jo,gr,Vo,Go,ti,Yo,_,K.open,kr,on,is,qs,Ys,ar,Ft]);const Yc=i.useCallback(k=>{const v=String(k||"").trim();if(v){if(v===fn||I(v)){h(v);return}jr(v)}},[I,jr,h]),dx=i.useCallback(async k=>{if(k.preventDefault(),yr(""),K.mode==="create"){if(Ze){yr("Audit-only mode is active. Session creation is disabled.");return}const T=await f({name:ni,passphrase:Ks});if(!T.ok){yr(T.error||"Failed to create session.");return}kr();return}const v=await b(K.targetSession,Ks);if(!v.ok){yr(v.error||"Failed to unlock session.");return}kr()},[K.mode,K.targetSession,ni,Ks,f,b,kr,Ze]),Zc=i.useCallback(async()=>{if(Ze){d({role:"kernel",content:"Audit-only mode is active. Session saving is disabled."});return}!(await y("manual")).ok&&l&&l!==fn&&jr(l)},[y,l,jr,Ze,d]),Xc=i.useCallback(async()=>{if(Ze){d({role:"kernel",content:"Audit-only mode is active. Retry save is disabled."});return}!(await y("retry")).ok&&l&&l!==fn&&jr(l)},[y,l,jr,Ze,d]),Qc=i.useCallback(()=>{if(Ze){d({role:"kernel",content:"Audit-only mode is active. Lock action is disabled."});return}!l||l===fn||g(l)},[l,g,Ze,d]),Wt=async k=>{const v=k||ye;if(!v.trim())return;d({id:nt(),role:"user",content:v}),pe("");const T=v.trim().toLowerCase(),q=T.startsWith("/")?T.split(/\s+/)[0]:"";if(Ze){if(!T.startsWith("/")){De(!1),d({role:"kernel",content:"Audit-only mode accepts proof/status commands only. Use /proof, /roi, /status, /guard, /help, /workflows, or /clear."});return}if(!xS.has(q)){De(!1),d({role:"kernel",content:`Audit-only mode blocked command: ${q}`});return}}if(!T.startsWith("/")&&l&&l!==fn&&!I(l)){De(!1),d({role:"kernel",content:`Session "${l}" is locked. Unlock it to send chat messages (proof commands still work).`});return}if(T.startsWith("/")){if(De(!1),T==="/clear"||T==="/purge"||T==="/reset"){m([]);return}setTimeout(()=>{if(T==="/help")d({role:"kernel",content:Ep});else if(T==="/guard"||T==="/omega"||T==="/kernel")(async()=>{try{const Y=window.api&&window.api.omega&&typeof window.api.omega.status=="function"?await window.api.omega.status():null;Y&&await ui();const ue=T==="/guard"?Y&&Y.formatted&&Y.formatted.guard:Y&&Y.formatted&&Y.formatted.omega;d({role:"kernel",content:ue||"OMEGA kernel status is unavailable in this runtime."})}catch(Y){d({role:"kernel",content:`OMEGA probe failed: ${Y&&Y.message?Y.message:String(Y)}`})}})();else if(T==="/status")d({role:"kernel",content:`Node Status: OPERATIONAL Integrity: SEALED CPU: ${N.cpuPercent}% Memory: ${N.memoryMb}MB`});else if(T==="/workflows")d({role:"kernel",content:`Active Workflows: ${x.join(` -`)}`});else if(T==="/resume")d({role:"kernel",content:"Restoring previous session context... Done. All workstation metrics verified."});else if(T==="/ecosystem")Q(!0),d({role:"kernel",content:"Opening Ecosystem Launcher."}),X("runtime.panel.opened",{panel:"ecosystem"},{source:"runtime",severity:"info"});else if(T==="/mission")B(!0),d({role:"kernel",content:"Opening Mission Control cockpit."}),X("runtime.panel.opened",{panel:"mission-control"},{source:"runtime",severity:"info"});else if(T==="/fleet")xe(!0),d({role:"kernel",content:"Opening Fleet Control panel."}),X("runtime.panel.opened",{panel:"fleet-control"},{source:"runtime",severity:"info"});else if(T==="/recovery")De(!0),d({role:"kernel",content:"Opening Recovery Center."}),X("runtime.panel.opened",{panel:"recovery-center"},{source:"runtime",severity:"info"});else if(T==="/appliance")Ge(!0),d({role:"kernel",content:"Opening Appliance Console."}),X("runtime.panel.opened",{panel:"appliance-console"},{source:"runtime",severity:"info"});else if(T==="/airgap")Dt(!0),d({role:"kernel",content:"Opening Air-Gapped Operations Center."}),X("runtime.panel.opened",{panel:"airgap-operations"},{source:"runtime",severity:"info"});else if(T==="/trustfabric")er(!0),d({role:"kernel",content:"Opening PKI Trust Fabric."}),X("runtime.panel.opened",{panel:"trust-fabric"},{source:"runtime",severity:"info"});else if(T==="/hardware")Ct(!0),d({role:"kernel",content:"Opening Hardware Customization Console."}),X("runtime.panel.opened",{panel:"hardware-customization"},{source:"runtime",severity:"info"});else if(T==="/courier")mt(!0),d({role:"kernel",content:"Opening Offline Evidence Courier."}),X("runtime.panel.opened",{panel:"courier-transfer"},{source:"runtime",severity:"info"});else if(T==="/drills"||T==="/continuity")_t(!0),d({role:"kernel",content:"Opening Continuity Drill Center."}),X("runtime.panel.opened",{panel:"continuity-drills"},{source:"runtime",severity:"info"});else if(T==="/procurement")tr(!0),d({role:"kernel",content:"Opening Procurement Command Center."}),X("runtime.panel.opened",{panel:"procurement-command"},{source:"runtime",severity:"info"});else if(T==="/simulate"||T==="/tamper")$r(!0),d({role:"kernel",content:"Opening Tamper Simulation Center."}),X("runtime.panel.opened",{panel:"tamper-simulation"},{source:"runtime",severity:"warning"});else if(T==="/institutional")mr(!0),d({role:"kernel",content:"Opening Institutional Command Console."}),X("runtime.panel.opened",{panel:"institutional-command"},{source:"runtime",severity:"info"});else if(T==="/demoflow")fr(!0),d({role:"kernel",content:"Opening Demo Flow Console."}),X("runtime.panel.opened",{panel:"demo-flow"},{source:"runtime",severity:"info"});else if(T==="/deployment")zr(!0),d({role:"kernel",content:"Opening Deployment Program Pack."}),X("runtime.panel.opened",{panel:"deployment-program"},{source:"runtime",severity:"info"});else if(T==="/training")Hr(!0),d({role:"kernel",content:"Opening Training Delivery Center."}),X("runtime.panel.opened",{panel:"training-delivery"},{source:"runtime",severity:"info"});else if(T==="/support")br(!0),d({role:"kernel",content:"Opening Support Ops Console."}),X("runtime.panel.opened",{panel:"support-ops"},{source:"runtime",severity:"info"});else if(T==="/buyer")Wr(!0),d({role:"kernel",content:"Opening Buyer Evaluation Journey."}),X("runtime.panel.opened",{panel:"buyer-journey"},{source:"runtime",severity:"info"});else if(T==="/pilot")Kr(!0),d({role:"kernel",content:"Opening Pilot Conversion Console."}),X("runtime.panel.opened",{panel:"pilot-conversion"},{source:"runtime",severity:"info"});else if(T==="/commercial")Vr(!0),d({role:"kernel",content:"Opening Commercial Package Console."}),X("runtime.panel.opened",{panel:"commercial-packages"},{source:"runtime",severity:"info"});else if(T==="/launch"||T==="/fieldlaunch")hr(!0),d({role:"kernel",content:"Opening Field Launch Command Center."}),X("runtime.panel.opened",{panel:"field-launch"},{source:"runtime",severity:"info"});else if(T==="/partner"||T==="/partnerrollout")Gr(!0),d({role:"kernel",content:"Opening Partner Rollout Console."}),X("runtime.panel.opened",{panel:"partner-rollout"},{source:"runtime",severity:"info"});else if(T==="/buyerops")Jr(!0),d({role:"kernel",content:"Opening Buyer Ops Automation."}),X("runtime.panel.opened",{panel:"buyer-ops"},{source:"runtime",severity:"info"});else if(T==="/demotopilot")qr(!0),d({role:"kernel",content:"Opening Demo-to-Pilot Conversion Engine."}),X("runtime.panel.opened",{panel:"demo-to-pilot"},{source:"runtime",severity:"info"});else if(T==="/expansion")Yr(!0),d({role:"kernel",content:"Opening Pilot Expansion Command."}),X("runtime.panel.opened",{panel:"pilot-expansion"},{source:"runtime",severity:"info"});else if(T==="/renewal")Zr(!0),d({role:"kernel",content:"Opening Renewal Risk Console."}),X("runtime.panel.opened",{panel:"renewal-risk"},{source:"runtime",severity:"info"});else if(T==="/launchweek")Xr(!0),d({role:"kernel",content:"Opening Launch Week Command Center."}),X("runtime.panel.opened",{panel:"launch-week"},{source:"runtime",severity:"info"});else if(T==="/followup")Qr(!0),d({role:"kernel",content:"Opening Proof-Backed Follow-Up Generator."}),X("runtime.panel.opened",{panel:"followup-generator"},{source:"runtime",severity:"info"});else if(T==="/feedback"||T==="/fieldfeedback")en(!0),d({role:"kernel",content:"Opening Field Feedback Console."}),X("runtime.panel.opened",{panel:"field-feedback"},{source:"runtime",severity:"info"});else if(T==="/shift")Lr(!0),d({role:"kernel",content:"Opening Shift Console."}),X("runtime.panel.opened",{panel:"shift-console"},{source:"runtime",severity:"info"});else if(T==="/incident")xr(!0),d({role:"kernel",content:"Opening Incident Mode."}),X("runtime.panel.opened",{panel:"incident-mode"},{source:"runtime",severity:"warning"});else if(T==="/rollout")Br(!0),d({role:"kernel",content:"Opening Policy Rollout Console."}),X("runtime.panel.opened",{panel:"policy-rollout"},{source:"runtime",severity:"info"});else if(T==="/updates")Fr(!0),d({role:"kernel",content:"Opening Offline Update Console."}),X("runtime.panel.opened",{panel:"offline-update-console"},{source:"runtime",severity:"info"});else if(T==="/missions")Ur(!0),d({role:"kernel",content:"Opening Mission Scheduler."}),X("runtime.panel.opened",{panel:"mission-scheduler"},{source:"runtime",severity:"info"});else if(T==="/nodechain")qn(!0),d({role:"kernel",content:"Opening NodeChain runtime engine panel."}),X("runtime.panel.opened",{panel:"nodechain"},{source:"runtime",severity:"info"});else if(T==="/watchdog")rr(!0),d({role:"kernel",content:"Opening runtime watchdog alerts drawer."}),X("runtime.panel.opened",{panel:"watchdog"},{source:"runtime",severity:"info"});else if(T==="/firstboot")Ut(),Lt(!0),d({role:"kernel",content:"Opening first-boot authority funnel."}),X("runtime.panel.opened",{panel:"first-boot"},{source:"runtime",severity:"info"});else if(T==="/tasks"||T==="/taskmanager"||T==="/processes"||T==="/inbox")xt("ops"),d({role:"kernel",content:"Operator Inbox opened — operations, Workpad tasks, health history, and missions."}),X("runtime.panel.opened",{panel:"operator-inbox"},{source:"runtime",severity:"info"});else if(T==="/workpad"||T==="/pad"||T==="/notepad"||T==="/scratchpad")sr(!0),d({role:"kernel",content:"Workpad opened — notes, personal tasks, pins, and capture log. Try `/workpad` anytime."}),X("runtime.panel.opened",{panel:"workpad"},{source:"runtime",severity:"info"});else if(T==="/calendar"||T==="/deadlines")rn(!0),d({role:"kernel",content:"ChronoHUD opened — local events, deadlines, Workpad due dates, and provider truth."}),X("runtime.panel.opened",{panel:"operator-calendar"},{source:"runtime",severity:"info"});else if(T==="/trust"||T==="/trustreport")zs(!0),d({role:"kernel",content:"Trust Report opened — forensic profile history and export."}),X("runtime.panel.opened",{panel:"trust-report"},{source:"runtime",severity:"info"});else if(T==="/actions"||T==="/guided")xt("actions"),d({role:"kernel",content:"Guided Actions opened — ranked pipelines from workspace intelligence."}),X("runtime.panel.opened",{panel:"guided-actions"},{source:"runtime",severity:"info"});else if(T==="/split")Yn(!0),d({role:"kernel",content:"Opening live split workspace."}),X("runtime.panel.opened",{panel:"split-workspace"},{source:"runtime",severity:"info"});else if(T==="/proof"||T==="/demo"){X("proof.started",{workflowId:String(c||"default")},{source:"proof",severity:"info"}),typeof window<"u"&&window.localStorage&&(window.localStorage.setItem("neuralshell_proof_last_status_v1","running"),window.localStorage.setItem("neuralshell_proof_stage_v1","executing"));const Y=zc(["### 90-Second Value Proof","","1. **Trust + Locality**","- Security policy reports `AIRGAP_ENFORCED` and `SEALED` integrity in this runtime.","","2. **Execution Safety**","- Workspace edits stay operator-controlled with explicit apply/preview gates.","","3. **Session Reliability**",`- Active workflows available right now: ${x.length}`,"- Session state can be saved, locked, and restored with passphrase control.","","4. **Release Evidence Path**","- Built-in release gate + packaged smoke checks produce verifiable proof artifacts.","","Next steps:","- Create a workflow in the left rail","- Run `/guard` and `/status`","- Save, lock, unlock, and verify restore in under 2 minutes"].join(` +`)}`});else if(T==="/resume")d({role:"kernel",content:"Restoring previous session context... Done. All workstation metrics verified."});else if(T==="/ecosystem")Q(!0),d({role:"kernel",content:"Opening Ecosystem Launcher."}),X("runtime.panel.opened",{panel:"ecosystem"},{source:"runtime",severity:"info"});else if(T==="/mission")B(!0),d({role:"kernel",content:"Opening Mission Control cockpit."}),X("runtime.panel.opened",{panel:"mission-control"},{source:"runtime",severity:"info"});else if(T==="/fleet")xe(!0),d({role:"kernel",content:"Opening Fleet Control panel."}),X("runtime.panel.opened",{panel:"fleet-control"},{source:"runtime",severity:"info"});else if(T==="/recovery")$e(!0),d({role:"kernel",content:"Opening Recovery Center."}),X("runtime.panel.opened",{panel:"recovery-center"},{source:"runtime",severity:"info"});else if(T==="/appliance")Ge(!0),d({role:"kernel",content:"Opening Appliance Console."}),X("runtime.panel.opened",{panel:"appliance-console"},{source:"runtime",severity:"info"});else if(T==="/airgap")Dt(!0),d({role:"kernel",content:"Opening Air-Gapped Operations Center."}),X("runtime.panel.opened",{panel:"airgap-operations"},{source:"runtime",severity:"info"});else if(T==="/trustfabric")er(!0),d({role:"kernel",content:"Opening PKI Trust Fabric."}),X("runtime.panel.opened",{panel:"trust-fabric"},{source:"runtime",severity:"info"});else if(T==="/hardware")Ct(!0),d({role:"kernel",content:"Opening Hardware Customization Console."}),X("runtime.panel.opened",{panel:"hardware-customization"},{source:"runtime",severity:"info"});else if(T==="/courier")mt(!0),d({role:"kernel",content:"Opening Offline Evidence Courier."}),X("runtime.panel.opened",{panel:"courier-transfer"},{source:"runtime",severity:"info"});else if(T==="/drills"||T==="/continuity")_t(!0),d({role:"kernel",content:"Opening Continuity Drill Center."}),X("runtime.panel.opened",{panel:"continuity-drills"},{source:"runtime",severity:"info"});else if(T==="/procurement")tr(!0),d({role:"kernel",content:"Opening Procurement Command Center."}),X("runtime.panel.opened",{panel:"procurement-command"},{source:"runtime",severity:"info"});else if(T==="/simulate"||T==="/tamper")$r(!0),d({role:"kernel",content:"Opening Tamper Simulation Center."}),X("runtime.panel.opened",{panel:"tamper-simulation"},{source:"runtime",severity:"warning"});else if(T==="/institutional")mr(!0),d({role:"kernel",content:"Opening Institutional Command Console."}),X("runtime.panel.opened",{panel:"institutional-command"},{source:"runtime",severity:"info"});else if(T==="/demoflow")fr(!0),d({role:"kernel",content:"Opening Demo Flow Console."}),X("runtime.panel.opened",{panel:"demo-flow"},{source:"runtime",severity:"info"});else if(T==="/deployment")zr(!0),d({role:"kernel",content:"Opening Deployment Program Pack."}),X("runtime.panel.opened",{panel:"deployment-program"},{source:"runtime",severity:"info"});else if(T==="/training")Hr(!0),d({role:"kernel",content:"Opening Training Delivery Center."}),X("runtime.panel.opened",{panel:"training-delivery"},{source:"runtime",severity:"info"});else if(T==="/support")br(!0),d({role:"kernel",content:"Opening Support Ops Console."}),X("runtime.panel.opened",{panel:"support-ops"},{source:"runtime",severity:"info"});else if(T==="/buyer")Wr(!0),d({role:"kernel",content:"Opening Buyer Evaluation Journey."}),X("runtime.panel.opened",{panel:"buyer-journey"},{source:"runtime",severity:"info"});else if(T==="/pilot")Kr(!0),d({role:"kernel",content:"Opening Pilot Conversion Console."}),X("runtime.panel.opened",{panel:"pilot-conversion"},{source:"runtime",severity:"info"});else if(T==="/commercial")Vr(!0),d({role:"kernel",content:"Opening Commercial Package Console."}),X("runtime.panel.opened",{panel:"commercial-packages"},{source:"runtime",severity:"info"});else if(T==="/launch"||T==="/fieldlaunch")hr(!0),d({role:"kernel",content:"Opening Field Launch Command Center."}),X("runtime.panel.opened",{panel:"field-launch"},{source:"runtime",severity:"info"});else if(T==="/partner"||T==="/partnerrollout")Gr(!0),d({role:"kernel",content:"Opening Partner Rollout Console."}),X("runtime.panel.opened",{panel:"partner-rollout"},{source:"runtime",severity:"info"});else if(T==="/buyerops")Jr(!0),d({role:"kernel",content:"Opening Buyer Ops Automation."}),X("runtime.panel.opened",{panel:"buyer-ops"},{source:"runtime",severity:"info"});else if(T==="/demotopilot")qr(!0),d({role:"kernel",content:"Opening Demo-to-Pilot Conversion Engine."}),X("runtime.panel.opened",{panel:"demo-to-pilot"},{source:"runtime",severity:"info"});else if(T==="/expansion")Yr(!0),d({role:"kernel",content:"Opening Pilot Expansion Command."}),X("runtime.panel.opened",{panel:"pilot-expansion"},{source:"runtime",severity:"info"});else if(T==="/renewal")Zr(!0),d({role:"kernel",content:"Opening Renewal Risk Console."}),X("runtime.panel.opened",{panel:"renewal-risk"},{source:"runtime",severity:"info"});else if(T==="/launchweek")Xr(!0),d({role:"kernel",content:"Opening Launch Week Command Center."}),X("runtime.panel.opened",{panel:"launch-week"},{source:"runtime",severity:"info"});else if(T==="/followup")Qr(!0),d({role:"kernel",content:"Opening Proof-Backed Follow-Up Generator."}),X("runtime.panel.opened",{panel:"followup-generator"},{source:"runtime",severity:"info"});else if(T==="/feedback"||T==="/fieldfeedback")en(!0),d({role:"kernel",content:"Opening Field Feedback Console."}),X("runtime.panel.opened",{panel:"field-feedback"},{source:"runtime",severity:"info"});else if(T==="/shift")Lr(!0),d({role:"kernel",content:"Opening Shift Console."}),X("runtime.panel.opened",{panel:"shift-console"},{source:"runtime",severity:"info"});else if(T==="/incident")xr(!0),d({role:"kernel",content:"Opening Incident Mode."}),X("runtime.panel.opened",{panel:"incident-mode"},{source:"runtime",severity:"warning"});else if(T==="/rollout")Br(!0),d({role:"kernel",content:"Opening Policy Rollout Console."}),X("runtime.panel.opened",{panel:"policy-rollout"},{source:"runtime",severity:"info"});else if(T==="/updates")Fr(!0),d({role:"kernel",content:"Opening Offline Update Console."}),X("runtime.panel.opened",{panel:"offline-update-console"},{source:"runtime",severity:"info"});else if(T==="/missions")Ur(!0),d({role:"kernel",content:"Opening Mission Scheduler."}),X("runtime.panel.opened",{panel:"mission-scheduler"},{source:"runtime",severity:"info"});else if(T==="/nodechain")Yn(!0),d({role:"kernel",content:"Opening NodeChain runtime engine panel."}),X("runtime.panel.opened",{panel:"nodechain"},{source:"runtime",severity:"info"});else if(T==="/watchdog")rr(!0),d({role:"kernel",content:"Opening runtime watchdog alerts drawer."}),X("runtime.panel.opened",{panel:"watchdog"},{source:"runtime",severity:"info"});else if(T==="/firstboot")Ut(),Lt(!0),d({role:"kernel",content:"Opening first-boot authority funnel."}),X("runtime.panel.opened",{panel:"first-boot"},{source:"runtime",severity:"info"});else if(T==="/tasks"||T==="/taskmanager"||T==="/processes"||T==="/inbox")xt("ops"),d({role:"kernel",content:"Operator Inbox opened — operations, Workpad tasks, health history, and missions."}),X("runtime.panel.opened",{panel:"operator-inbox"},{source:"runtime",severity:"info"});else if(T==="/workpad"||T==="/pad"||T==="/notepad"||T==="/scratchpad")sr(!0),d({role:"kernel",content:"Workpad opened — notes, personal tasks, pins, and capture log. Try `/workpad` anytime."}),X("runtime.panel.opened",{panel:"workpad"},{source:"runtime",severity:"info"});else if(T==="/calendar"||T==="/deadlines")rn(!0),d({role:"kernel",content:"ChronoHUD opened — local events, deadlines, Workpad due dates, and provider truth."}),X("runtime.panel.opened",{panel:"operator-calendar"},{source:"runtime",severity:"info"});else if(T==="/trust"||T==="/trustreport")zs(!0),d({role:"kernel",content:"Trust Report opened — forensic profile history and export."}),X("runtime.panel.opened",{panel:"trust-report"},{source:"runtime",severity:"info"});else if(T==="/actions"||T==="/guided")xt("actions"),d({role:"kernel",content:"Guided Actions opened — ranked pipelines from workspace intelligence."}),X("runtime.panel.opened",{panel:"guided-actions"},{source:"runtime",severity:"info"});else if(T==="/split")Zn(!0),d({role:"kernel",content:"Opening live split workspace."}),X("runtime.panel.opened",{panel:"split-workspace"},{source:"runtime",severity:"info"});else if(T==="/proof"||T==="/demo"){X("proof.started",{workflowId:String(l||"default")},{source:"proof",severity:"info"}),typeof window<"u"&&window.localStorage&&(window.localStorage.setItem("neuralshell_proof_last_status_v1","running"),window.localStorage.setItem("neuralshell_proof_stage_v1","executing"));const Y=zc(["### 90-Second Value Proof","","1. **Trust + Locality**","- Security policy reports `AIRGAP_ENFORCED` and `SEALED` integrity in this runtime.","","2. **Execution Safety**","- Workspace edits stay operator-controlled with explicit apply/preview gates.","","3. **Session Reliability**",`- Active workflows available right now: ${x.length}`,"- Session state can be saved, locked, and restored with passphrase control.","","4. **Release Evidence Path**","- Built-in release gate + packaged smoke checks produce verifiable proof artifacts.","","Next steps:","- Create a workflow in the left rail","- Run `/guard` and `/status`","- Save, lock, unlock, and verify restore in under 2 minutes"].join(` `),{stdoutLines:[],stdoutDone:!1});Hc("proof",Y),(typeof window>"u"||!window.localStorage||window.localStorage.getItem("neuralshell_success_capture_suppressed_v1")!=="1")&&yc(!0)}else if(T==="/unit-test"){const Y=zc(["### Unit Test Probe","","- Triggered local test routine from inline command lane.","- Streaming stdout is attached below for live verification output."].join(` -`),{stdoutLines:[],stdoutDone:!1});Hc("unit-test",Y)}else if(T==="/roi"||T==="/pitch"){const le=Math.round(165),$e=le*120;d({role:"kernel",content:["### ProofForge ROI Snapshot","","- Time reclaimed target: ~45 minutes/day/operator",`- Annual recovered capacity: ~${le} hours/operator`,`- Value at $120/hour: ~$${$e.toLocaleString()} per operator/year`,"","Where the gain comes from:","- Faster triage with one command and evidence lane","- Fewer release regressions via strict guardrails","- Less context switching between tooling surfaces","","Fast close path:","- Run `/proof` now","- Save and lock one workflow","- Export release artifacts from the same console"].join(` -`)})}else d({role:"kernel",content:`Unknown command: ${T}`})},400);return}Jm(v),Be(!0);try{const Y=[...p,{role:"user",content:v}],ue=Mv(Y),se=await window.api.llm.chat(ue),le=se&&se.message&&typeof se.message.content=="string"?se.message.content:se&&typeof se.content=="string"?se.content:"";d({id:nt(),role:"kernel",content:le||"No response from provider."})}catch(Y){const ue=ml(Y&&Y.message?Y.message:String(Y))||"Provider request failed.";d({id:nt(),role:"kernel",content:`Chat error: ${ue}`})}finally{Be(!1)}};i.useCallback(async()=>{if(Ze){d({role:"kernel",content:"Audit-only mode is active. Offline kill switch changes are disabled."});return}try{const v={...await window.api.settings.get()||{},provider:"ollama",apiKey:"",ollamaBaseUrl:"http://127.0.0.1:11434",allowRemoteBridge:!1,connectOnStartup:!1};await window.api.llm.cancelStream().catch(()=>!1),await window.api.settings.update(v),d({role:"kernel",content:"Offline kill switch engaged. Hosted providers disabled and bridge stream cancelled."}),await Te()}catch(k){d({role:"kernel",content:`Offline kill switch failed: ${k&&k.message?k.message:String(k)}`})}},[d,Ze,Te]);const ed=i.useCallback(async()=>{const k=window.api&&window.api.system&&typeof window.api.system.openExternal=="function"?window.api.system.openExternal:null;if(!k){d({role:"kernel",content:`Upgrade link: ${il}`});return}try{await k(il),d({role:"kernel",content:"Opening Pro upgrade page in your browser."})}catch(v){d({role:"kernel",content:`Unable to open upgrade page automatically. Use: ${il}`}),window.api&&window.api.logger&&typeof window.api.logger.log=="function"&&window.api.logger.log("warn","upgrade-link-open-failed",{reason:v&&v.message?v.message:String(v)}).catch(()=>{})}},[d]),ux=i.useCallback(async(k,v,T)=>{const q=String(v??"").trim();if(!q)return"";const Y=Array.isArray(ie.current)?ie.current.length:0,ue=()=>Array.isArray(ie.current)?ie.current:[];try{await Wt(q);const se=Am(ue(),Y,q);return se?za(se):await IS(ue,Y,q)}catch(se){return`Error: ${se&&se.message?se.message:String(se)}`}},[Wt]),px=c&&c!==Cs&&A==="locked",td=i.useCallback(k=>{const v=String(k||"").trim();v&&(pe(v),window.dispatchEvent(new window.CustomEvent("neuralshell:focus-composer")))},[]),mx=i.useCallback(()=>{vc(!1),typeof window<"u"&&window.localStorage&&window.localStorage.setItem(ll,"1")},[]),xx=i.useCallback(async k=>{await $c(k,async()=>{var T,q,Y,ue,se,le,$e,ve,jt,Je;const v=String(k||"");if(v==="welcome_intro"){d({id:nt(),role:"kernel",content:"Welcome to ProofForge runtime authority mode. You are configuring a local-first, proof-aware workstation."});return}if(v==="provider_sweep"){if((q=(T=window.api)==null?void 0:T.settings)!=null&&q.get&&((ue=(Y=window.api)==null?void 0:Y.settings)!=null&&ue.update)){const Ne=await window.api.settings.get();await window.api.settings.update({...Ne||{},connectOnStartup:!0})}if(await Te(),await ft(),(le=(se=window.api)==null?void 0:se.bridge)!=null&&le.test&&((ve=($e=window.api)==null?void 0:$e.settings)!=null&&ve.get))try{const Ne=await window.api.settings.get(),It=Array.isArray(Ne==null?void 0:Ne.connectionProfiles)?Ne.connectionProfiles:[],ad=String((Ne==null?void 0:Ne.activeProfileId)||"").trim(),Nr=It.find(Ni=>String((Ni==null?void 0:Ni.id)||"")===ad)||It[0]||null;Nr&&await window.api.bridge.test({provider:String(Nr.provider||Ne.provider||"ollama"),baseUrl:String(Nr.baseUrl||Ne.ollamaBaseUrl||""),defaultModel:String(Nr.defaultModel||Ne.defaultModel||"llama3"),allowRemoteBridge:!!Ne.allowRemoteBridge,apiKey:Ne.apiKey,apiKeyPresent:Ne.apiKeyPresent})}catch{}await Te(),await ft(),d({id:nt(),role:"kernel",content:"Provider sweep completed. Bridge connectivity baseline refreshed."});return}if(v==="vault_setup"){I(),window.dispatchEvent(new window.CustomEvent("neuralshell:prompt-vault-save"));return}if(v==="policy_profile_selection"){if(window.api&&window.api.settings&&typeof window.api.settings.get=="function"){const Ne=await window.api.settings.get();await window.api.settings.update({...Ne||{},offlineOnlyEnforced:!!(Ne&&Ne.offlineOnlyEnforced)})}await Te(),await ft();return}if(v==="update_ring_selection"){if(window.api&&window.api.settings&&typeof window.api.settings.get=="function"){const Ne=await window.api.settings.get();await window.api.settings.update({...Ne||{},autoUpdateChannel:String(Ne&&Ne.autoUpdateChannel||"stable")})}await Te(),await ft();return}if(v==="run_proof"){await Wt("/proof");return}if(v==="install_core_agent"){if((Je=(jt=window.api)==null?void 0:jt.agents)!=null&&Je.install)try{const Ne=await window.api.agents.install("proof_guard",{}),It=!!(Ne&&Ne.ok);d({id:nt(),role:"kernel",content:It?`Core agent installed: proof_guard${Ne.installPath?` → ${Ne.installPath}`:""}.`:"Core agent install did not complete — open Settings → Agent Store to retry."})}catch(Ne){d({id:nt(),role:"kernel",content:`Agent install failed: ${Ne&&Ne.message?Ne.message:String(Ne)}. Open Settings → Agent Store to retry.`})}I();return}if(v==="license_import"){I();return}if(v==="share_badge"){window.api&&window.api.system&&typeof window.api.system.openExternal=="function"&&await window.api.system.openExternal("https://raw.githubusercontent.com/Z3r0DayZion-install/NeuralShell/main/assets/proof_badge.svg");return}v==="open_mission_control"&&B(!0)})},[d,Wt,nt,I,Te,ft,$c]),fx=i.useCallback(k=>{Dc(k),Mc(k)},[Mc,Dc]),bx=i.useCallback(()=>{if(vr&&B(!0),ss(),Lt(!1),typeof window<"u"&&window.localStorage){window.localStorage.setItem("neuralshell_first_boot_completed_v1","1");const k=(Array.isArray(Fa)?Fa:[]).find(v=>v.id==="getting_started");k&&zp(k,c||"global")}},[ss,vr,c]),hx=i.useCallback(k=>{const v=Gs.current;v&&typeof v.acknowledgeAlert=="function"&&(v.acknowledgeAlert(k),uc(v.getAlerts()))},[]),gx=i.useCallback(()=>vt.importRuntimeNode(Se,{nodeId:"local-runtime",displayName:"Local Runtime"}),[vt,Se]),yx=i.useCallback(k=>{const v=k&&typeof k=="object"?k:{};d({id:nt(),role:"kernel",content:`Snapshot restore applied: provider=${String(v.provider||"n/a")}, model=${String(v.model||"n/a")}, policy=${String(v.policyProfile||"n/a")}.`}),v.activePanels&&Array.isArray(v.activePanels)&&v.activePanels.includes("mission-control")&&B(!0)},[d,nt]),dn=i.useCallback(()=>{if(Gm(!1),!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(ip,"1")}catch{}},[]),Kt=i.useCallback((k,v)=>{const T=k==="workbench"?"workbench":"thread",q=Ue==="focused"?"focused":Ue==="balanced"?"balanced":"expanded",Y=!!v;Vm(ue=>{const se=ue[q]||dl[q];return!!(se&&se[T])===Y?ue:{...ue,[q]:{thread:T==="thread"?Y:!!(se&&se.thread),workbench:T==="workbench"?Y:!!(se&&se.workbench)}}})},[Ue]),rd=i.useCallback(()=>{Kt("thread",!is)},[Kt,is]),nd=i.useCallback(()=>{Kt("workbench",!Zs)},[Kt,Zs]),un=i.useCallback((k,v)=>{const T=k==="workbench"?"workbench":"thread",ue=ze(v,T==="workbench"?at:st,T==="workbench"?Tt:Ot);Ws(se=>se[T]===ue?se:{...se,[T]:ue})},[]),vi=i.useCallback(k=>{const v=String(k||"").trim().toLowerCase(),T=bp[v];T&&Ws({thread:ze(T.thread,st,Ot),workbench:ze(T.workbench,at,Tt)})},[]),wx=i.useCallback(k=>{if(!k||typeof k!="object")return;const v=String(k._shellSync||"full");if(v==="full"||v==="panels-only")try{window.dispatchEvent(new CustomEvent("neuralshell:apply-layout")),window.dispatchEvent(new CustomEvent("neuralshell:layout-chrome-updated"))}catch{}if(v==="panels-only")return;const T=CS[String(k.id||"").trim().toLowerCase()];if(T&&vi(T),k.railWidths&&typeof k.railWidths=="object"){const Y=Number(k.railWidths.left),ue=Number(k.railWidths.right);Ws(se=>({thread:Number.isFinite(Y)?ze(Y,st,Ot):se.thread,workbench:Number.isFinite(ue)?ze(ue,at,Tt):se.workbench}))}const q=k.panels&&typeof k.panels=="object"?k.panels:{};q["thread-rail"]===!1?Kt("thread",!0):q["thread-rail"]===!0&&Kt("thread",!1),q["workbench-rail"]===!1?Kt("workbench",!0):q["workbench-rail"]===!0&&Ue==="expanded"&&Kt("workbench",!1)},[vi,Ue,Kt]),ji=i.useCallback(()=>{un("thread",jn)},[un]),ki=i.useCallback(()=>{un("workbench",kn)},[un]),vx=i.useCallback(k=>{k.button!==0||!ln||(k.preventDefault(),dn(),wr.current={rail:"thread",startX:Number(k.clientX||0),startWidth:hi,minWidth:st,maxWidth:Qs},document.body.style.userSelect="none",document.body.style.cursor="col-resize")},[dn,Qs,hi,ln]),jx=i.useCallback(k=>{k.button!==0||!Xs||(k.preventDefault(),dn(),wr.current={rail:"workbench",startX:Number(k.clientX||0),startWidth:gi,minWidth:at,maxWidth:ea},document.body.style.userSelect="none",document.body.style.cursor="col-resize")},[dn,ea,gi,Xs]),kx=i.useCallback(k=>{k.button!==0||!ar||(k.preventDefault(),wr.current={rail:"thread",startX:Number(k.clientX||0),startWidth:fi,minWidth:st,maxWidth:Math.min(Ot,Math.max(st,Xe-Ca))},document.body.style.userSelect="none",document.body.style.cursor="col-resize")},[fi,ar,Xe]),Nx=i.useCallback(k=>{k.button!==0||!Ft||(k.preventDefault(),wr.current={rail:"workbench",startX:Number(k.clientX||0),startWidth:bi,minWidth:at,maxWidth:Math.min(Tt,Math.max(at,Xe-Ca))},document.body.style.userSelect="none",document.body.style.cursor="col-resize")},[bi,Ft,Xe]);i.useEffect(()=>{const k=()=>{wr.current&&(wr.current=null,document.body.style.userSelect="",document.body.style.cursor="")},v=T=>{const q=wr.current;if(!q)return;const Y=Number(T.clientX||0);if(!Number.isFinite(Y))return;const ue=q.rail==="thread"?Y-q.startX:q.startX-Y,se=ze(q.startWidth+ue,q.minWidth,q.maxWidth);un(q.rail,se)};return window.addEventListener("pointermove",v),window.addEventListener("pointerup",k),window.addEventListener("pointercancel",k),()=>{window.removeEventListener("pointermove",v),window.removeEventListener("pointerup",k),window.removeEventListener("pointercancel",k),k()}},[un]),i.useEffect(()=>{if(!ri||!ln&&!Xs)return;const k=window.setTimeout(()=>{dn()},9e3);return()=>{window.clearTimeout(k)}},[dn,ln,Xs,ri]);const Sx=i.useCallback(()=>{rs(!1),ts(k=>!k)},[]),sd=i.useCallback(()=>{ts(!1),rs(k=>!k)},[]);return e.jsxs("div",{className:`h-screen w-screen flex flex-col overflow-hidden font-sans relative ${F?"aero-shell-root text-slate-800 selection:bg-sky-300/40":"bg-slate-950 text-slate-200 selection:bg-cyan-500/30"}`,children:[F&&e.jsx(Yh,{}),e.jsxs("div",{className:"relative z-10 flex flex-col h-full min-h-0",children:[e.jsx(Jh,{report:Js}),e.jsx(Gf,{model:o,setModel:J,stats:N,xpState:u,workflowId:c,onOpenPalette:U,onOpenSettings:z,onOpenAnalytics:()=>L(!0),onOpenEcosystem:()=>Q(!0),onOpenMissionControl:()=>B(!0),onOpenFleetControl:()=>xe(!0),onOpenApplianceConsole:()=>Ge(!0),onOpenAirGapOperations:()=>Dt(!0),onOpenInstitutionalCommand:()=>mr(!0),onOpenDemoFlow:Oe?()=>fr(!0):void 0,onOpenFieldLaunch:Oe?()=>hr(!0):void 0,onToggleScratchpad:()=>sr(k=>!k),watchdogStatus:as,watchdogAlertCount:zt.length,onOpenRuntimeAlerts:()=>rr(!0),runtimeTier:W,connectionInfo:_e,tokensRemaining:Qm,collabConnected:wt.connected,collabRoomId:wt.roomId,collabPeerCount:ns,accelStatus:G,applianceModeEnabled:Gn,airGapLocked:Ls,demoModeEnabled:Bs,feedbackDisabled:!_e.allowRemoteBridge,feedbackUrl:bS,onOpenIssueAssist:Xm?()=>gc(!0):void 0,tierId:ce.tierId,tierLabel:ce.tierLabel,canGoBack:Hm,canGoForward:Wm,onGoBack:Qn,onGoForward:es,onOpenTaskManager:()=>xt("ops"),onOpenCalendar:()=>rn(!0),onOpenSupport:ee,onTierUnlock:me,omegaReport:Js,onRunOmega:()=>Wt("/omega"),suppressDuplicateRuntimeStatus:!0}),e.jsx(Zf,{connectionInfo:_e,watchdogStatus:as,incidentCount:zt.length,setupBlocked:!!(Et&&!vr),sessionDegradedDismissed:sn,acknowledgedReady:nn,exportAvailable:ls,exportBusy:Wc,onExportEvidence:yi,onInspectIssue:()=>rr(!0),onFixSetup:()=>{z(),Ut()},onRunChecks:ox,onToggleInspector:Ue!=="expanded"?sd:void 0,inspectorOpen:!!(Ft||Uc),layoutMode:Ue}),px&&e.jsxs("div",{"data-testid":"session-lock-banner",className:"px-5 py-2 border-b border-amber-400/20 bg-amber-400/10 text-[11px] font-mono text-amber-100 flex items-center justify-between gap-3",children:[e.jsx("span",{children:C||`Session "${c}" is locked.`}),e.jsx("button",{"data-testid":"session-lock-unlock-btn",onClick:()=>jr(c),className:"px-3 py-1 rounded border border-amber-300/40 text-[10px] uppercase tracking-wider font-bold hover:bg-amber-300/20",children:"Unlock Session"})]}),e.jsx(rb,{activeRailPresetId:ax,onApplyRailPreset:vi,onResetRailWidths:()=>{ji(),ki()},showInlineThreadRail:on,threadRailCollapsed:is,onToggleThreadRailCollapse:rd,showInlineWorkbenchRail:os,workbenchRailCollapsed:Zs,onToggleWorkbenchRailCollapse:nd,canOpenThreadRailOverlay:qs&&Bc,leftRailOverlayOpen:ar,onToggleLeftRailOverlay:Sx,canOpenWorkbenchRailOverlay:Ys&&mi,rightRailOverlayOpen:Ft,onToggleRightRailOverlay:sd,firstBootSteps:Oc,firstBootProgress:Tc,onReopenFirstBoot:()=>{Ut(),Lt(!0)},onResetFirstBoot:()=>{rx(),Lt(!0)},onOpenCustomize:()=>a(!0)}),e.jsx("div",{className:"flex-1 flex min-h-0 overflow-hidden relative",children:e.jsx(Ph,{moodColors:cn.colors,moodEngine:cn,rgbEnabled:re.rgbEnabled,rgbStatus:M,isThinking:we,isTyping:!!String(ye||"").trim(),particlesEnabled:r("particle-bg",!1),showInlineThreadRailPanel:ln,sessions:x,workflowId:c,onSelectSession:Yc,onCreateSession:ra,onSaveSession:Zc,onRetrySave:Xc,onLockSession:Qc,saveStatus:w,isSessionUnlocked:P,sessionHydrationStatus:A,autoLockOnBlur:!!j,onToggleAutoLock:E,auditOnly:Ze,onUpgradeToPro:ed,chatLog:p,inlineThreadRailWidth:hi,onBeginThreadRailResize:vx,onResetThreadRailWidth:ji,showThreadRailResizeHint:sx,showInlineThreadRail:on,threadRailCollapsed:is,onToggleThreadRailCollapse:rd,onSendMessage:ux,preferAppSend:!0,onOpenTaskManager:()=>xt("ops"),onToggleWorkpad:()=>sr(k=>!k),collab:wt,panels:t,showInlineWorkbenchRailPanel:Uc,onBeginWorkbenchRailResize:jx,onResetWorkbenchRailWidth:ki,stats:N,onExecute:Wt,onInsertPrompt:td,inlineWorkbenchRailWidth:gi,showInlineWorkbenchRail:xi,workbenchRailCollapsed:Fc,onToggleWorkbenchRailCollapse:nd,showScratchpad:ti,onCloseScratchpad:()=>sr(!1),connectionInfo:_e,omegaReport:Js,omegaLoading:Pc,omegaError:Rc,onRefreshOmega:ui,activeModel:o,onModelChange:J,visualStyle:n})}),qs&&ar&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[72] bg-black/55",onClick:()=>ts(!1)}),e.jsxs("div",{className:"fixed left-0 top-14 bottom-0 z-[73] flex items-stretch",children:[e.jsx(Sp,{sessions:x,workflowId:c,onSelectSession:Yc,onCreateSession:ra,onSaveSession:Zc,onRetrySave:Xc,onLockSession:Qc,saveStatus:w,isSessionUnlocked:P,sessionHydrationStatus:A,autoLockOnBlur:!!j,onToggleAutoLock:E,auditOnly:Ze,onUpgradeToPro:ed,widthPx:fi}),e.jsx("button",{type:"button",role:"separator","aria-label":"Resize overlay workflow rail","aria-orientation":"vertical","data-testid":"thread-rail-overlay-resize-handle",onPointerDown:kx,onDoubleClick:ji,title:"Drag to resize overlay. Double-click to reset.",className:"group z-20 w-2 -mx-1 cursor-col-resize touch-none select-none flex items-stretch",children:e.jsx("span",{className:"mx-auto my-2 w-px bg-white/30 transition-colors group-hover:bg-cyan-300/90"})})]})]}),Ys&&Ft&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[72] bg-black/55",onClick:()=>rs(!1)}),e.jsxs("div",{className:"fixed right-0 top-14 bottom-0 z-[73] flex items-stretch",children:[e.jsx("button",{type:"button",role:"separator","aria-label":"Resize overlay workbench rail","aria-orientation":"vertical","data-testid":"workbench-rail-overlay-resize-handle",onPointerDown:Nx,onDoubleClick:ki,title:"Drag to resize overlay. Double-click to reset.",className:"group z-20 w-2 -mx-1 cursor-col-resize touch-none select-none flex items-stretch",children:e.jsx("span",{className:"mx-auto my-2 w-px bg-white/30 transition-colors group-hover:bg-cyan-300/90"})}),e.jsx(Kp,{stats:N,workflowId:c,onExecute:Wt,onInsertPrompt:td,auditOnly:Ze,widthPx:bi,connectionInfo:_e,omegaReport:Js,omegaLoading:Pc,omegaError:Rc,onRefreshOmega:ui})]})]}),_&&e.jsx(cg,{onClose:R}),e.jsx(BN,{open:s,onClose:()=>a(!1),onApplyLayout:wx}),e.jsx(VN,{panels:t,collab:wt,workflowId:c}),$&&e.jsx(ow,{connectionInfo:_e}),de&&e.jsx(kw,{onClose:()=>L(!1),capabilities:ce.capabilities}),e.jsx(y1,{open:be,onClose:()=>Q(!1),capabilities:ce.capabilities,tierId:ce.tierId,onOpenMissionControl:()=>{Q(!1),B(!0)},onOpenFleetControl:()=>{Q(!1),xe(!0)},onOpenRecoveryCenter:()=>{Q(!1),De(!0)},onOpenApplianceConsole:()=>{Q(!1),Ge(!0)},onOpenAirGapOperations:()=>{Q(!1),Dt(!0)},onOpenTrustFabric:Oe?()=>{Q(!1),er(!0)}:void 0,onOpenHardwareAppliance:Oe?()=>{Q(!1),Ct(!0)}:void 0,onOpenCourierTransfer:()=>{Q(!1),mt(!0)},onOpenContinuityDrills:Oe?()=>{Q(!1),_t(!0)}:void 0,onOpenProcurementCommand:()=>{Q(!1),tr(!0)},onOpenTamperSimulation:()=>{Q(!1),$r(!0)},onOpenInstitutionalCommand:()=>{Q(!1),mr(!0)},onOpenDemoFlow:Oe?()=>{Q(!1),fr(!0)}:void 0,onOpenDeploymentProgram:()=>{Q(!1),zr(!0)},onOpenTrainingDelivery:()=>{Q(!1),Hr(!0)},onOpenSupportOps:()=>{Q(!1),br(!0)},onOpenBuyerJourney:()=>{Q(!1),Wr(!0)},onOpenPilotConversion:Oe?()=>{Q(!1),Kr(!0)}:void 0,onOpenCommercialPackages:()=>{Q(!1),Vr(!0)},onOpenFieldLaunch:Oe?()=>{Q(!1),hr(!0)}:void 0,onOpenPartnerRollout:()=>{Q(!1),Gr(!0)},onOpenBuyerOps:()=>{Q(!1),Jr(!0)},onOpenDemoToPilot:()=>{Q(!1),qr(!0)},onOpenPilotExpansion:()=>{Q(!1),Yr(!0)},onOpenRenewalRisk:()=>{Q(!1),Zr(!0)},onOpenLaunchWeek:Oe?()=>{Q(!1),Xr(!0)}:void 0,onOpenFollowupGenerator:()=>{Q(!1),Qr(!0)},onOpenFieldFeedback:()=>{Q(!1),en(!0)},onOpenPartnerCertification:()=>{Q(!1),Pn(!0)},onOpenManagedServices:Oe?()=>{Q(!1),Rn(!0)}:void 0,onOpenStrategicAccount:Oe?()=>{Q(!1),On(!0)}:void 0,onOpenPortfolioRollout:Oe?()=>{Q(!1),Tn(!0)}:void 0,onOpenRevenueOps:Oe?()=>{Q(!1),Mn(!0)}:void 0,onOpenChannelExpansion:Oe?()=>{Q(!1),Dn(!0)}:void 0,onOpenCrossAccountRenewal:Oe?()=>{Q(!1),$n(!0)}:void 0,onOpenExecutiveScale:Oe?()=>{Q(!1),Ln(!0)}:void 0,onOpenEcosystemPortfolio:Oe?()=>{Q(!1),Bn(!0)}:void 0,onOpenServiceLine:Oe?()=>{Q(!1),Fn(!0)}:void 0,onOpenPartnerNetworkGovernance:Oe?()=>{Q(!1),Un(!0)}:void 0,onOpenGlobalPlanning:Oe?()=>{Q(!1),zn(!0)}:void 0,onOpenEcosystemRevenue:()=>{Q(!1),Hn(!0)},onOpenBoardOperatingPack:Oe?()=>{Q(!1),Wn(!0)}:void 0,onOpenLicensedOperator:Oe?()=>{Q(!1),Kn(!0)}:void 0,onOpenEcosystemCommand:Oe?()=>{Q(!1),Vn(!0)}:void 0,onOpenShiftConsole:()=>{Q(!1),Lr(!0)},onOpenIncidentMode:()=>{Q(!1),xr(!0)},onOpenPolicyRollout:()=>{Q(!1),Br(!0)},onOpenOfflineUpdates:()=>{Q(!1),Fr(!0)},onOpenMissionScheduler:()=>{Q(!1),Ur(!0)},applianceModeEnabled:Gn}),e.jsx(C1,{open:We,onClose:()=>B(!1),runtimeState:Se,events:an,onOpenSettings:I,onOpenFleet:At(()=>xe(!0)),onOpenRecovery:At(()=>De(!0)),onOpenAppliance:At(()=>Ge(!0)),onOpenAirGap:At(()=>Dt(!0)),onOpenTrustFabric:Ee(()=>er(!0)),onOpenHardwareAppliance:Ee(()=>Ct(!0)),onOpenCourierTransfer:At(()=>mt(!0)),onOpenContinuityDrills:Ee(()=>_t(!0)),onOpenProcurementCommand:Ee(()=>tr(!0)),onOpenTamperSimulation:Ee(()=>$r(!0)),onOpenInstitutionalCommand:Ee(()=>mr(!0)),onOpenDemoFlow:Ee(()=>fr(!0)),onOpenDeploymentProgram:Ee(()=>zr(!0)),onOpenTrainingDelivery:At(()=>Hr(!0)),onOpenSupportOps:At(()=>br(!0)),onOpenBuyerJourney:Ee(()=>Wr(!0)),onOpenPilotConversion:Ee(()=>Kr(!0)),onOpenCommercialPackages:Ee(()=>Vr(!0)),onOpenFieldLaunch:Ee(()=>hr(!0)),onOpenPartnerRollout:Ee(()=>Gr(!0)),onOpenBuyerOps:Ee(()=>Jr(!0)),onOpenDemoToPilot:Ee(()=>qr(!0)),onOpenPilotExpansion:Ee(()=>Yr(!0)),onOpenRenewalRisk:Ee(()=>Zr(!0)),onOpenLaunchWeek:Ee(()=>Xr(!0)),onOpenFollowupGenerator:Ee(()=>Qr(!0)),onOpenFieldFeedback:Ee(()=>en(!0)),onOpenPartnerCertification:Ee(()=>Pn(!0)),onOpenManagedServices:Ee(()=>Rn(!0)),onOpenStrategicAccount:Ee(()=>On(!0)),onOpenPortfolioRollout:Ee(()=>Tn(!0)),onOpenRevenueOps:Ee(()=>Mn(!0)),onOpenChannelExpansion:Ee(()=>Dn(!0)),onOpenCrossAccountRenewal:Ee(()=>$n(!0)),onOpenExecutiveScale:Ee(()=>Ln(!0)),onOpenEcosystemPortfolio:Ee(()=>Bn(!0)),onOpenServiceLine:Ee(()=>Fn(!0)),onOpenPartnerNetworkGovernance:Ee(()=>Un(!0)),onOpenGlobalPlanning:Ee(()=>zn(!0)),onOpenEcosystemRevenue:Ee(()=>Hn(!0)),onOpenBoardOperatingPack:Ee(()=>Wn(!0)),onOpenLicensedOperator:Ee(()=>Kn(!0)),onOpenEcosystemCommand:Ee(()=>Vn(!0)),onOpenShift:At(()=>Lr(!0)),onOpenIncidentMode:At(()=>xr(!0)),onOpenPolicyRollout:At(()=>Br(!0)),onOpenOfflineUpdates:()=>Fr(!0),onOpenMissionScheduler:()=>Ur(!0),onOpenNodeChain:()=>qn(!0),onOpenWatchdog:()=>rr(!0),onOpenFirstBoot:()=>{Ut(),Lt(!0)},onOpenSplitWorkspace:()=>Yn(!0),showInternalSurfaces:Ce}),Ce&&e.jsx("div",{"data-testid":"internal-gtm-surfaces-enabled",hidden:!0,"aria-hidden":"true"}),Bt&&e.jsxs(e.Fragment,{children:[e.jsx(zv,{open:oe,onClose:()=>xe(!1),fleet:vt,onImportLocalRuntime:gx}),e.jsx(Gv,{open:Re,onClose:()=>De(!1)}),e.jsx(qv,{open:tt,onClose:()=>Ge(!1),enabled:Gn,onToggleEnabled:async k=>{if(Im(!!k),!!(window.api&&window.api.settings&&typeof window.api.settings.get=="function"))try{const v=await window.api.settings.get(),T=v&&typeof v=="object"?v:{};k&&await window.api.settings.update({...T,offlineOnlyEnforced:!0,allowRemoteBridge:!1,autoUpdateChannel:"locked"})}catch{}},runtimeState:Se,fleetSummary:vt.healthSummary}),e.jsx(wj,{open:An,onClose:()=>Dt(!1),locked:Ls,onToggleLocked:async k=>{const v=!!k;if(Pm(v),!!(window.api&&window.api.settings&&typeof window.api.settings.get=="function")){try{const T=await window.api.settings.get(),q=T&&typeof T=="object"?T:{};await window.api.settings.update({...q,offlineOnlyEnforced:v,allowRemoteBridge:v?!1:!!q.allowRemoteBridge,autoUpdateChannel:v?"frozen":String(q.autoUpdateChannel||"stable")})}catch{}X(v?"airgap.lock.enabled":"airgap.lock.disabled",{source:"airgap-operations"},{source:"airgap",severity:v?"critical":"warning"})}}})]}),Ce&&e.jsx(_j,{open:En,onClose:()=>er(!1)}),Ce&&e.jsx(Mj,{open:Dr,onClose:()=>Ct(!1),onOpenSettings:I}),Bt&&e.jsx(Uj,{open:In,onClose:()=>mt(!1)}),Ce&&e.jsx(Vj,{open:$t,onClose:()=>_t(!1)}),Ce&&e.jsx(Yj,{open:Ae,onClose:()=>tr(!1)}),Ce&&e.jsx(ek,{open:ro,onClose:()=>$r(!1)}),Ce&&e.jsx(sk,{open:no,onClose:()=>mr(!1),onOpenPanel:Ht}),Ce&&e.jsx(ok,{open:co,onClose:()=>fr(!1),enabled:Bs,onToggleEnabled:Rm,onOpenPanel:Ht}),Ce&&e.jsx(uk,{open:uo,onClose:()=>zr(!1)}),Bt&&e.jsx(fk,{open:po,onClose:()=>Hr(!1)}),Bt&&e.jsx(hk,{open:mo,onClose:()=>br(!1)}),Ce&&e.jsx(gk,{open:xo,onClose:()=>Wr(!1)}),Ce&&e.jsx(wk,{open:fo,onClose:()=>Kr(!1)}),Ce&&e.jsx(jk,{open:bo,onClose:()=>Vr(!1)}),Ce&&e.jsx(kk,{open:ho,onClose:()=>hr(!1),onOpenPanel:Ht}),Ce&&e.jsx(_k,{open:go,onClose:()=>Gr(!1)}),Ce&&e.jsx(Ek,{open:yo,onClose:()=>Jr(!1)}),Ce&&e.jsx(Tk,{open:wo,onClose:()=>qr(!1)}),Ce&&e.jsx(Dk,{open:vo,onClose:()=>Yr(!1)}),Ce&&e.jsx(Bk,{open:jo,onClose:()=>Zr(!1)}),Ce&&e.jsx(Uk,{open:ko,onClose:()=>Xr(!1),onOpenPanel:Ht}),Ce&&e.jsx(Wk,{open:No,onClose:()=>Qr(!1)}),Ce&&e.jsx(Vk,{open:So,onClose:()=>en(!1)}),Ce&&e.jsx(Yk,{open:Co,onClose:()=>Pn(!1)}),Ce&&e.jsx(eN,{open:_o,onClose:()=>Rn(!1)}),Ce&&e.jsx(nN,{open:Ao,onClose:()=>On(!1)}),Ce&&e.jsx(oN,{open:Eo,onClose:()=>Tn(!1)}),Ce&&e.jsx(cN,{open:Io,onClose:()=>Mn(!1)}),Ce&&e.jsx(mN,{open:Po,onClose:()=>Dn(!1)}),Ce&&e.jsx(fN,{open:Ro,onClose:()=>$n(!1)}),Ce&&e.jsx(bN,{open:Oo,onClose:()=>Ln(!1),onOpenPanel:Ht}),Ce&&e.jsx(gN,{open:To,onClose:()=>Bn(!1)}),Ce&&e.jsx(wN,{open:Mo,onClose:()=>Fn(!1)}),Ce&&e.jsx(jN,{open:Do,onClose:()=>Un(!1)}),Ce&&e.jsx(NN,{open:$o,onClose:()=>zn(!1)}),Ce&&e.jsx(CN,{open:Lo,onClose:()=>Hn(!1)}),Ce&&e.jsx(AN,{open:Bo,onClose:()=>Wn(!1)}),Ce&&e.jsx(IN,{open:Fo,onClose:()=>Kn(!1)}),Ce&&e.jsx(PN,{open:Uo,onClose:()=>Vn(!1),onOpenPanel:Ht}),Bt&&e.jsx(ej,{open:so,onClose:()=>Lr(!1),role:gt,onChangeRole:k=>Om(k),fleetNodes:vt.nodes,incidents:Jn.filter(k=>String(k&&k.status?k.status:"")==="open")}),Bt&&e.jsx(nj,{open:ao,onClose:()=>xr(!1),incidents:Jn,fleetNodes:vt.nodes,onDeclare:k=>{const v={incidentId:`inc-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,title:String(k&&k.title?k.title:"Runtime Incident"),severity:String(k&&k.severity?k.severity:"degraded"),status:"open",declaredAt:new Date().toISOString(),affectedNodes:Array.isArray(k&&k.affectedNodes)?k.affectedNodes:[],timeline:[]};return Fs(T=>[v,...Array.isArray(T)?T:[]].slice(0,250)),X("incident.declared",{incidentId:v.incidentId,severity:v.severity,affectedNodes:v.affectedNodes.length},{source:"incident",severity:v.severity==="critical"?"critical":"degraded"}),v},onResolve:k=>{Fs(v=>Array.isArray(v)?v.map(T=>String(T.incidentId||"")===String(k||"")?{...T,status:"resolved",resolvedAt:new Date().toISOString()}:T):v),X("incident.resolved",{incidentId:String(k||"")},{source:"incident",severity:"info"})},onApplyPlaybook:(k,v)=>{const T=String(v&&v.incidentId?v.incidentId:"");T&&(Fs(q=>Array.isArray(q)?q.map(Y=>String(Y.incidentId||"")!==T?Y:{...Y,timeline:[...Array.isArray(Y.timeline)?Y.timeline:[],{at:new Date().toISOString(),type:"incident.playbook.applied",source:"incident",detail:{playbookId:String(k&&k.id?k.id:""),playbookTitle:String(k&&k.title?k.title:"")}}].slice(-400)}):q),X("incident.playbook.applied",{incidentId:T,playbookId:String(k&&k.id?k.id:"")},{source:"incident",severity:"warning"}))},onTriggerSafeMode:async()=>{if(window.api&&window.api.settings&&typeof window.api.settings.get=="function"){try{const k=await window.api.settings.get();await window.api.settings.update({...k||{},offlineOnlyEnforced:!0,allowRemoteBridge:!1,autoUpdateChannel:"frozen"})}catch{}X("incident.safe_mode.enabled",{},{source:"incident",severity:"critical"})}}}),Bt&&e.jsx(ij,{open:oo,onClose:()=>Br(!1),fleet:vt,history:Us,onApplyRollout:({bundle:k,nodeIds:v,mode:T,scheduledFor:q})=>{const Y=k&&k.payload&&typeof k.payload=="object"?k.payload:{},ue=String(Y.policyProfile||Y.label||Y.policyId||"fleet-policy"),se=String(Y.policyId||ue||"policy"),le={rolloutId:`rollout-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,policyId:se,policyProfile:ue,nodeIds:Array.isArray(v)?v:[],mode:String(T||"immediate"),scheduledFor:q||"",status:"applied",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};vt.applyPolicyBundle({policyProfile:ue,policyId:se},le.nodeIds,{mode:le.mode}),cc($e=>[le,...Array.isArray($e)?$e:[]].slice(0,250)),X("fleet.policy.rollout.applied",{rolloutId:le.rolloutId,policyProfile:ue,targets:le.nodeIds.length,mode:le.mode},{source:"fleet-policy",severity:"info"})},onRollbackRollout:k=>{const v=k&&typeof k=="object"?k:{},T=Array.isArray(v.nodeIds)?v.nodeIds:[];T.forEach(q=>{vt.rollbackPolicy(q,"none")}),cc(q=>Array.isArray(q)?q.map(Y=>String(Y.rolloutId||"")===String(v.rolloutId||"")?{...Y,status:"rolled_back",updatedAt:new Date().toISOString()}:Y):q),X("fleet.policy.rollout.rolled_back",{rolloutId:String(v.rolloutId||""),targets:T.length},{source:"fleet-policy",severity:"warning"})}}),e.jsx(uj,{open:io,onClose:()=>Fr(!1),fleet:vt}),e.jsx(bj,{open:lo,onClose:()=>Ur(!1),fleet:vt,onOpenIncidentMode:()=>xr(!0)}),e.jsx(P1,{open:zo,onClose:()=>qn(!1),onSnapshotRequest:wi,onOpenPanel:Ht}),e.jsx(O1,{open:Ho,alerts:Xn,onClose:()=>rr(!1),onAcknowledge:hx}),e.jsx(q1,{open:Wo,onClose:()=>rn(!1),workflowId:c}),e.jsx(ev,{open:Ko,onClose:()=>zs(!1)}),e.jsx(cv,{open:Vo,onClose:()=>Yn(!1),runtimeState:Se,onRestoreSnapshotPayload:yx,alerts:Xn,proofStdout:nx,releaseHealth:Se&&Se.releaseHealth?Se.releaseHealth:{}}),e.jsx(Ev,{open:Go,onClose:()=>Zn(!1),stats:N,connectionInfo:_e,accelStatus:G,settings:ot,workflowId:c,initialTab:Jo,onOpenWorkpad:()=>sr(!0),chatLog:p}),e.jsx(Pv,{open:Yo,onClose:()=>yt(!1),connectionInfo:_e,watchdogStatus:as,incidentCount:zt.length,setupBlocked:!!(Et&&!vr),sessionDegradedDismissed:sn,acknowledgedReady:nn,exportAvailable:ls,exportBusy:Wc,onStartOperating:ix,onInspectIssue:()=>{yt(!1),rr(!0)},onFixSetup:()=>{yt(!1),z(),Ut()},onOpenSettings:()=>{yt(!1),z()},onContinueAnyway:lx,onExportEvidence:yi}),e.jsx(Iv,{}),gr&&e.jsx(tv,{open:gr,steps:Oc,progress:Tc,busyStepId:tx,onRunStep:xx,onSkipStep:fx,onClose:()=>{Lt(!1),ss(),typeof window<"u"&&window.localStorage&&window.localStorage.setItem("neuralshell_first_boot_completed_v1","1")},onFinish:bx}),di&&or&&!gr&&e.jsx(Rw,{open:or,onClose:mx,onOpenSettings:I,onRunCommand:Wt}),e.jsx(Tw,{open:qm,onClose:()=>gc(!1),metadata:{tier:ce.tierLabel,version:"NeuralShell_V2.2.0",workflowId:c||"",supportBundlePath:wc.outputPath||"",supportBundleHash:wc.sha256||""}}),e.jsx($w,{open:Ym,onClose:()=>yc(!1),workflowId:c||"",tierLabel:ce.tierLabel}),K.open&&e.jsx("div",{"data-testid":"session-modal-overlay",className:"fixed inset-0 z-[90] bg-black/60 backdrop-blur-sm flex items-center justify-center p-4",onMouseDown:k=>{k.target===k.currentTarget&&kr()},children:e.jsxs("div",{"data-testid":"session-modal",role:"dialog","aria-modal":"true","aria-labelledby":Nc,"aria-describedby":Sc,className:"w-full max-w-md rounded-2xl border border-cyan-400/20 bg-slate-950 shadow-[0_20px_80px_rgba(0,0,0,0.7)] p-6",children:[e.jsx("h2",{id:Nc,className:"text-lg font-bold text-cyan-100 tracking-wide mb-2",children:K.mode==="create"?"Create Session":"Unlock Session"}),e.jsx("p",{id:Sc,className:"text-[11px] text-slate-400 font-mono mb-5",children:K.mode==="create"?"Set a session name and passphrase. The passphrase stays local to this runtime.":`Enter the passphrase for "${K.targetSession}".`}),e.jsxs("form",{onSubmit:dx,className:"space-y-4",children:[K.mode==="create"&&e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Session Name"}),e.jsx("input",{ref:ai,"data-testid":"session-modal-name-input",value:ni,onChange:k=>bc(k.target.value),placeholder:"Workflow_ALPHA",autoFocus:!0,className:"mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm text-slate-100 outline-none focus:border-cyan-400/40"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Passphrase"}),e.jsx("input",{ref:oi,"data-testid":"session-modal-pass-input",type:"password",value:Ks,onChange:k=>si(k.target.value),placeholder:"Required",autoFocus:K.mode!=="create",className:"mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm text-slate-100 outline-none focus:border-cyan-400/40"})]}),hc&&e.jsx("div",{"data-testid":"session-modal-error",className:"text-[11px] text-rose-300 font-mono",children:hc}),e.jsxs("div",{className:"pt-2 flex gap-2 justify-end",children:[e.jsx("button",{ref:jc,type:"button","data-testid":"session-modal-cancel-btn",onClick:kr,className:"px-4 py-2 rounded-lg border border-white/10 text-[10px] uppercase tracking-[0.14em] font-bold text-slate-300 hover:bg-white/5",children:"Cancel"}),e.jsx("button",{ref:kc,type:"submit","data-testid":"session-modal-submit-btn",className:"px-4 py-2 rounded-lg border border-cyan-300/30 bg-cyan-400/10 text-[10px] uppercase tracking-[0.14em] font-bold text-cyan-200 hover:bg-cyan-400/20",children:K.mode==="create"?"Create Session":"Unlock Session"})]})]})]})})]}),Mm&&e.jsx(hf,{workflowId:c,proofStatus:Se&&Se.proofEngine?Se.proofEngine.lastProofStatus:"idle",exportEvidenceAvailable:ls,evidenceExported:$m,onRunProof:()=>Wt("/proof"),onOpenTrustReport:ei,onExportEvidence:yi,onOpenWorkpad:Qo,onDismiss:cx})]})}function RS(t){return t?Array.isArray(t.messages)?t.messages.map(r=>({role:String(r&&r.role?r.role:"assistant"),content:String(r&&r.content?r.content:"")})):t.content?[{role:"assistant",content:String(t.content)}]:[]:[]}function OS({hash:t}){const[r,n]=i.useState("loading"),[s,a]=i.useState(""),[o,l]=i.useState(null);i.useEffect(()=>{let u=!0;return(async()=>{try{const p=String(window.location.hash||"").replace(/^#/,"").trim();let d=null;if(p)d=await Th(p);else{const m=await Dh(t);d=await Vp(m)}if(!u)return;l(d),n("ready")}catch(p){if(!u)return;a(p&&p.message?String(p.message):"Unable to load share payload."),n("error")}})(),()=>{u=!1}},[t]);const c=RS(o);return e.jsx("div",{className:"min-h-screen bg-slate-950 text-slate-100 px-6 py-10",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.2em] text-cyan-400/70 font-bold",children:"ProofForge Share"}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mt-1",children:"Read-Only Conversation"}),e.jsxs("div",{className:"text-[11px] font-mono text-slate-400 mt-1",children:["/share/",t]})]}),r==="loading"&&e.jsx("div",{className:"rounded-2xl border border-white/10 bg-black/30 p-5 text-[12px] font-mono text-slate-300",children:"Decrypting shared payload..."}),r==="error"&&e.jsx("div",{className:"rounded-2xl border border-rose-300/30 bg-rose-500/10 p-5 text-[12px] font-mono text-rose-200",children:s||"Failed to load shared conversation."}),r==="ready"&&e.jsxs("div",{className:"space-y-4",children:[c.length===0&&e.jsx("div",{className:"rounded-2xl border border-white/10 bg-black/30 p-5 text-[12px] font-mono text-slate-300",children:"Share payload is valid but empty."}),c.map((u,x)=>e.jsxs("div",{className:`rounded-2xl border p-4 text-[13px] leading-relaxed whitespace-pre-wrap ${u.role==="user"?"border-cyan-300/30 bg-cyan-500/10 text-cyan-50 ml-10":"border-white/10 bg-black/35 text-slate-200 mr-10"}`,children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.2em] text-slate-500 mb-2",children:u.role}),u.content]},`${u.role}-${x}`))]})]})})}function Em(t){return String(t||"").trim().replace(/[^a-zA-Z0-9_-]/g,"")}function TS(t){const r=String(t||"").match(/^\/share\/([a-zA-Z0-9_-]+)$/);return r?Em(r[1]):""}function MS(t){const r=String(t||"").match(/^#\/share\/([a-zA-Z0-9_-]+)/);return r?Em(r[1]):""}function DS(t,r){const n=String(t||"").trim(),s=String(r||"").trim();return n==="/scratchpad"||s==="#/scratchpad"}function $S(t,r=""){const n=TS(t);if(n)return{name:"share",hash:n};const s=MS(r);return s?{name:"share",hash:s}:DS(t,r)?{name:"scratchpad"}:{name:"app"}}const hp=$S(window.location.pathname,window.location.hash);rf.createRoot(document.getElementById("root")).render(e.jsx(i.StrictMode,{children:hp.name==="share"?e.jsx(OS,{hash:hp.hash}):e.jsx(uf,{children:e.jsx(PS,{})})}));export{QS as A,XS as B,KS as C,Zb as D,qS as E,n2 as F,c2 as G,Ew as H,_0 as I,s2 as J,Cw as K,_w as L,Aw as W,qa as a,Zl as b,ge as c,t2 as d,th as e,Fa as f,i2 as g,zp as h,r2 as i,WS as j,Ta as k,et as l,Qt as m,Ga as n,GS as o,a2 as p,Nw as q,l2 as r,Bp as s,o2 as t,e2 as u,JS as v,eh as w,ZS as x,YS as y,VS as z}; +`),{stdoutLines:[],stdoutDone:!1});Hc("unit-test",Y)}else if(T==="/roi"||T==="/pitch"){const le=Math.round(165),Le=le*120;d({role:"kernel",content:["### ProofForge ROI Snapshot","","- Time reclaimed target: ~45 minutes/day/operator",`- Annual recovered capacity: ~${le} hours/operator`,`- Value at $120/hour: ~$${Le.toLocaleString()} per operator/year`,"","Where the gain comes from:","- Faster triage with one command and evidence lane","- Fewer release regressions via strict guardrails","- Less context switching between tooling surfaces","","Fast close path:","- Run `/proof` now","- Save and lock one workflow","- Export release artifacts from the same console"].join(` +`)})}else d({role:"kernel",content:`Unknown command: ${T}`})},400);return}Jm(v),De(!0);try{const Y=[...p,{role:"user",content:v}],ue=Mv(Y),se=await window.api.llm.chat(ue),le=se&&se.message&&typeof se.message.content=="string"?se.message.content:se&&typeof se.content=="string"?se.content:"";d({id:nt(),role:"kernel",content:le||"No response from provider."})}catch(Y){const ue=ml(Y&&Y.message?Y.message:String(Y))||"Provider request failed.";d({id:nt(),role:"kernel",content:`Chat error: ${ue}`})}finally{De(!1)}};i.useCallback(async()=>{if(Ze){d({role:"kernel",content:"Audit-only mode is active. Offline kill switch changes are disabled."});return}try{const v={...await window.api.settings.get()||{},provider:"ollama",apiKey:"",ollamaBaseUrl:"http://127.0.0.1:11434",allowRemoteBridge:!1,connectOnStartup:!1};await window.api.llm.cancelStream().catch(()=>!1),await window.api.settings.update(v),d({role:"kernel",content:"Offline kill switch engaged. Hosted providers disabled and bridge stream cancelled."}),await Te()}catch(k){d({role:"kernel",content:`Offline kill switch failed: ${k&&k.message?k.message:String(k)}`})}},[d,Ze,Te]);const ed=i.useCallback(async()=>{const k=window.api&&window.api.system&&typeof window.api.system.openExternal=="function"?window.api.system.openExternal:null;if(!k){d({role:"kernel",content:`Upgrade link: ${il}`});return}try{await k(il),d({role:"kernel",content:"Opening Pro upgrade page in your browser."})}catch(v){d({role:"kernel",content:`Unable to open upgrade page automatically. Use: ${il}`}),window.api&&window.api.logger&&typeof window.api.logger.log=="function"&&window.api.logger.log("warn","upgrade-link-open-failed",{reason:v&&v.message?v.message:String(v)}).catch(()=>{})}},[d]),ux=i.useCallback(async(k,v,T)=>{const q=String(v??"").trim();if(!q)return"";const Y=Array.isArray(ie.current)?ie.current.length:0,ue=()=>Array.isArray(ie.current)?ie.current:[];try{await Wt(q);const se=Am(ue(),Y,q);return se?za(se):await IS(ue,Y,q)}catch(se){return`Error: ${se&&se.message?se.message:String(se)}`}},[Wt]),px=l&&l!==fn&&A==="locked",td=i.useCallback(k=>{const v=String(k||"").trim();v&&(pe(v),window.dispatchEvent(new window.CustomEvent("neuralshell:focus-composer")))},[]),mx=i.useCallback(()=>{vc(!1),typeof window<"u"&&window.localStorage&&window.localStorage.setItem(ll,"1")},[]),xx=i.useCallback(async k=>{await $c(k,async()=>{var T,q,Y,ue,se,le,Le,ve,jt,Je;const v=String(k||"");if(v==="welcome_intro"){d({id:nt(),role:"kernel",content:"Welcome to ProofForge runtime authority mode. You are configuring a local-first, proof-aware workstation."});return}if(v==="provider_sweep"){if((q=(T=window.api)==null?void 0:T.settings)!=null&&q.get&&((ue=(Y=window.api)==null?void 0:Y.settings)!=null&&ue.update)){const Ne=await window.api.settings.get();await window.api.settings.update({...Ne||{},connectOnStartup:!0})}if(await Te(),await ft(),(le=(se=window.api)==null?void 0:se.bridge)!=null&&le.test&&((ve=(Le=window.api)==null?void 0:Le.settings)!=null&&ve.get))try{const Ne=await window.api.settings.get(),It=Array.isArray(Ne==null?void 0:Ne.connectionProfiles)?Ne.connectionProfiles:[],ad=String((Ne==null?void 0:Ne.activeProfileId)||"").trim(),Nr=It.find(Ni=>String((Ni==null?void 0:Ni.id)||"")===ad)||It[0]||null;Nr&&await window.api.bridge.test({provider:String(Nr.provider||Ne.provider||"ollama"),baseUrl:String(Nr.baseUrl||Ne.ollamaBaseUrl||""),defaultModel:String(Nr.defaultModel||Ne.defaultModel||"llama3"),allowRemoteBridge:!!Ne.allowRemoteBridge,apiKey:Ne.apiKey,apiKeyPresent:Ne.apiKeyPresent})}catch{}await Te(),await ft(),d({id:nt(),role:"kernel",content:"Provider sweep completed. Bridge connectivity baseline refreshed."});return}if(v==="vault_setup"){P(),window.dispatchEvent(new window.CustomEvent("neuralshell:prompt-vault-save"));return}if(v==="policy_profile_selection"){if(window.api&&window.api.settings&&typeof window.api.settings.get=="function"){const Ne=await window.api.settings.get();await window.api.settings.update({...Ne||{},offlineOnlyEnforced:!!(Ne&&Ne.offlineOnlyEnforced)})}await Te(),await ft();return}if(v==="update_ring_selection"){if(window.api&&window.api.settings&&typeof window.api.settings.get=="function"){const Ne=await window.api.settings.get();await window.api.settings.update({...Ne||{},autoUpdateChannel:String(Ne&&Ne.autoUpdateChannel||"stable")})}await Te(),await ft();return}if(v==="run_proof"){await Wt("/proof");return}if(v==="install_core_agent"){if((Je=(jt=window.api)==null?void 0:jt.agents)!=null&&Je.install)try{const Ne=await window.api.agents.install("proof_guard",{}),It=!!(Ne&&Ne.ok);d({id:nt(),role:"kernel",content:It?`Core agent installed: proof_guard${Ne.installPath?` → ${Ne.installPath}`:""}.`:"Core agent install did not complete — open Settings → Agent Store to retry."})}catch(Ne){d({id:nt(),role:"kernel",content:`Agent install failed: ${Ne&&Ne.message?Ne.message:String(Ne)}. Open Settings → Agent Store to retry.`})}P();return}if(v==="license_import"){P();return}if(v==="share_badge"){window.api&&window.api.system&&typeof window.api.system.openExternal=="function"&&await window.api.system.openExternal("https://raw.githubusercontent.com/Z3r0DayZion-install/NeuralShell/main/assets/proof_badge.svg");return}v==="open_mission_control"&&B(!0)})},[d,Wt,nt,P,Te,ft,$c]),fx=i.useCallback(k=>{Dc(k),Mc(k)},[Mc,Dc]),bx=i.useCallback(()=>{if(vr&&B(!0),as(),Lt(!1),typeof window<"u"&&window.localStorage){window.localStorage.setItem("neuralshell_first_boot_completed_v1","1");const k=(Array.isArray(Fa)?Fa:[]).find(v=>v.id==="getting_started");k&&zp(k,l||"global")}},[as,vr,l]),hx=i.useCallback(k=>{const v=Gs.current;v&&typeof v.acknowledgeAlert=="function"&&(v.acknowledgeAlert(k),uc(v.getAlerts()))},[]),gx=i.useCallback(()=>vt.importRuntimeNode(Se,{nodeId:"local-runtime",displayName:"Local Runtime"}),[vt,Se]),yx=i.useCallback(k=>{const v=k&&typeof k=="object"?k:{};d({id:nt(),role:"kernel",content:`Snapshot restore applied: provider=${String(v.provider||"n/a")}, model=${String(v.model||"n/a")}, policy=${String(v.policyProfile||"n/a")}.`}),v.activePanels&&Array.isArray(v.activePanels)&&v.activePanels.includes("mission-control")&&B(!0)},[d,nt]),dn=i.useCallback(()=>{if(Gm(!1),!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(ip,"1")}catch{}},[]),Kt=i.useCallback((k,v)=>{const T=k==="workbench"?"workbench":"thread",q=Ue==="focused"?"focused":Ue==="balanced"?"balanced":"expanded",Y=!!v;Vm(ue=>{const se=ue[q]||dl[q];return!!(se&&se[T])===Y?ue:{...ue,[q]:{thread:T==="thread"?Y:!!(se&&se.thread),workbench:T==="workbench"?Y:!!(se&&se.workbench)}}})},[Ue]),rd=i.useCallback(()=>{Kt("thread",!ls)},[Kt,ls]),nd=i.useCallback(()=>{Kt("workbench",!Zs)},[Kt,Zs]),un=i.useCallback((k,v)=>{const T=k==="workbench"?"workbench":"thread",ue=ze(v,T==="workbench"?at:st,T==="workbench"?Tt:Ot);Ws(se=>se[T]===ue?se:{...se,[T]:ue})},[]),vi=i.useCallback(k=>{const v=String(k||"").trim().toLowerCase(),T=bp[v];T&&Ws({thread:ze(T.thread,st,Ot),workbench:ze(T.workbench,at,Tt)})},[]),wx=i.useCallback(k=>{if(!k||typeof k!="object")return;const v=String(k._shellSync||"full");if(v==="full"||v==="panels-only")try{window.dispatchEvent(new CustomEvent("neuralshell:apply-layout")),window.dispatchEvent(new CustomEvent("neuralshell:layout-chrome-updated"))}catch{}if(v==="panels-only")return;const T=CS[String(k.id||"").trim().toLowerCase()];if(T&&vi(T),k.railWidths&&typeof k.railWidths=="object"){const Y=Number(k.railWidths.left),ue=Number(k.railWidths.right);Ws(se=>({thread:Number.isFinite(Y)?ze(Y,st,Ot):se.thread,workbench:Number.isFinite(ue)?ze(ue,at,Tt):se.workbench}))}const q=k.panels&&typeof k.panels=="object"?k.panels:{};q["thread-rail"]===!1?Kt("thread",!0):q["thread-rail"]===!0&&Kt("thread",!1),q["workbench-rail"]===!1?Kt("workbench",!0):q["workbench-rail"]===!0&&Ue==="expanded"&&Kt("workbench",!1)},[vi,Ue,Kt]),ji=i.useCallback(()=>{un("thread",kn)},[un]),ki=i.useCallback(()=>{un("workbench",Nn)},[un]),vx=i.useCallback(k=>{k.button!==0||!ln||(k.preventDefault(),dn(),wr.current={rail:"thread",startX:Number(k.clientX||0),startWidth:hi,minWidth:st,maxWidth:Qs},document.body.style.userSelect="none",document.body.style.cursor="col-resize")},[dn,Qs,hi,ln]),jx=i.useCallback(k=>{k.button!==0||!Xs||(k.preventDefault(),dn(),wr.current={rail:"workbench",startX:Number(k.clientX||0),startWidth:gi,minWidth:at,maxWidth:ea},document.body.style.userSelect="none",document.body.style.cursor="col-resize")},[dn,ea,gi,Xs]),kx=i.useCallback(k=>{k.button!==0||!ar||(k.preventDefault(),wr.current={rail:"thread",startX:Number(k.clientX||0),startWidth:fi,minWidth:st,maxWidth:Math.min(Ot,Math.max(st,Xe-Ca))},document.body.style.userSelect="none",document.body.style.cursor="col-resize")},[fi,ar,Xe]),Nx=i.useCallback(k=>{k.button!==0||!Ft||(k.preventDefault(),wr.current={rail:"workbench",startX:Number(k.clientX||0),startWidth:bi,minWidth:at,maxWidth:Math.min(Tt,Math.max(at,Xe-Ca))},document.body.style.userSelect="none",document.body.style.cursor="col-resize")},[bi,Ft,Xe]);i.useEffect(()=>{const k=()=>{wr.current&&(wr.current=null,document.body.style.userSelect="",document.body.style.cursor="")},v=T=>{const q=wr.current;if(!q)return;const Y=Number(T.clientX||0);if(!Number.isFinite(Y))return;const ue=q.rail==="thread"?Y-q.startX:q.startX-Y,se=ze(q.startWidth+ue,q.minWidth,q.maxWidth);un(q.rail,se)};return window.addEventListener("pointermove",v),window.addEventListener("pointerup",k),window.addEventListener("pointercancel",k),()=>{window.removeEventListener("pointermove",v),window.removeEventListener("pointerup",k),window.removeEventListener("pointercancel",k),k()}},[un]),i.useEffect(()=>{if(!ri||!ln&&!Xs)return;const k=window.setTimeout(()=>{dn()},9e3);return()=>{window.clearTimeout(k)}},[dn,ln,Xs,ri]);const Sx=i.useCallback(()=>{ns(!1),rs(k=>!k)},[]),sd=i.useCallback(()=>{rs(!1),ns(k=>!k)},[]);return e.jsxs("div",{className:`h-screen w-screen flex flex-col overflow-hidden font-sans relative ${F?"aero-shell-root text-slate-800 selection:bg-sky-300/40":"bg-slate-950 text-slate-200 selection:bg-cyan-500/30"}`,children:[F&&e.jsx(Yh,{}),e.jsxs("div",{className:"relative z-10 flex flex-col h-full min-h-0",children:[e.jsx(Jh,{report:Js}),e.jsx(Gf,{model:o,setModel:J,stats:N,xpState:u,workflowId:l,onOpenPalette:U,onOpenSettings:z,onOpenAnalytics:()=>L(!0),onOpenEcosystem:()=>Q(!0),onOpenMissionControl:()=>B(!0),onOpenFleetControl:()=>xe(!0),onOpenApplianceConsole:()=>Ge(!0),onOpenAirGapOperations:()=>Dt(!0),onOpenInstitutionalCommand:()=>mr(!0),onOpenDemoFlow:Oe?()=>fr(!0):void 0,onOpenFieldLaunch:Oe?()=>hr(!0):void 0,onToggleScratchpad:()=>sr(k=>!k),watchdogStatus:os,watchdogAlertCount:zt.length,onOpenRuntimeAlerts:()=>rr(!0),runtimeTier:W,connectionInfo:_e,tokensRemaining:Qm,collabConnected:wt.connected,collabRoomId:wt.roomId,collabPeerCount:ss,accelStatus:G,applianceModeEnabled:Jn,airGapLocked:Ls,demoModeEnabled:Bs,feedbackDisabled:!_e.allowRemoteBridge,feedbackUrl:bS,onOpenIssueAssist:Xm?()=>gc(!0):void 0,tierId:ce.tierId,tierLabel:ce.tierLabel,canGoBack:Hm,canGoForward:Wm,onGoBack:es,onGoForward:ts,onOpenTaskManager:()=>xt("ops"),onOpenCalendar:()=>rn(!0),onOpenSupport:ee,onTierUnlock:me,omegaReport:Js,onRunOmega:()=>Wt("/omega"),suppressDuplicateRuntimeStatus:!0}),e.jsx(Zf,{connectionInfo:_e,watchdogStatus:os,incidentCount:zt.length,setupBlocked:!!(Et&&!vr),sessionDegradedDismissed:sn,acknowledgedReady:nn,exportAvailable:cs,exportBusy:Wc,onExportEvidence:yi,onInspectIssue:()=>rr(!0),onFixSetup:()=>{z(),Ut()},onRunChecks:ox,onToggleInspector:Ue!=="expanded"?sd:void 0,inspectorOpen:!!(Ft||Uc),layoutMode:Ue}),px&&e.jsxs("div",{"data-testid":"session-lock-banner",className:"px-5 py-2 border-b border-amber-400/20 bg-amber-400/10 text-[11px] font-mono text-amber-100 flex items-center justify-between gap-3",children:[e.jsx("span",{children:C||`Session "${l}" is locked.`}),e.jsx("button",{"data-testid":"session-lock-unlock-btn",onClick:()=>jr(l),className:"px-3 py-1 rounded border border-amber-300/40 text-[10px] uppercase tracking-wider font-bold hover:bg-amber-300/20",children:"Unlock Session"})]}),e.jsx(rb,{activeRailPresetId:ax,onApplyRailPreset:vi,onResetRailWidths:()=>{ji(),ki()},showInlineThreadRail:on,threadRailCollapsed:ls,onToggleThreadRailCollapse:rd,showInlineWorkbenchRail:is,workbenchRailCollapsed:Zs,onToggleWorkbenchRailCollapse:nd,canOpenThreadRailOverlay:qs&&Bc,leftRailOverlayOpen:ar,onToggleLeftRailOverlay:Sx,canOpenWorkbenchRailOverlay:Ys&&mi,rightRailOverlayOpen:Ft,onToggleRightRailOverlay:sd,firstBootSteps:Oc,firstBootProgress:Tc,onReopenFirstBoot:()=>{Ut(),Lt(!0)},onResetFirstBoot:()=>{rx(),Lt(!0)},onOpenCustomize:()=>a(!0)}),e.jsx("div",{className:"flex-1 flex min-h-0 overflow-hidden relative",children:e.jsx(Ph,{moodColors:cn.colors,moodEngine:cn,rgbEnabled:re.rgbEnabled,rgbStatus:M,isThinking:we,isTyping:!!String(ye||"").trim(),particlesEnabled:r("particle-bg",!1),showInlineThreadRailPanel:ln,sessions:x,workflowId:l,onSelectSession:Yc,onCreateSession:ra,onSaveSession:Zc,onRetrySave:Xc,onLockSession:Qc,saveStatus:w,isSessionUnlocked:I,sessionHydrationStatus:A,autoLockOnBlur:!!j,onToggleAutoLock:E,auditOnly:Ze,onUpgradeToPro:ed,chatLog:p,inlineThreadRailWidth:hi,onBeginThreadRailResize:vx,onResetThreadRailWidth:ji,showThreadRailResizeHint:sx,showInlineThreadRail:on,threadRailCollapsed:ls,onToggleThreadRailCollapse:rd,onSendMessage:ux,preferAppSend:!0,onOpenTaskManager:()=>xt("ops"),onToggleWorkpad:()=>sr(k=>!k),collab:wt,panels:t,showInlineWorkbenchRailPanel:Uc,onBeginWorkbenchRailResize:jx,onResetWorkbenchRailWidth:ki,stats:N,onExecute:Wt,onInsertPrompt:td,inlineWorkbenchRailWidth:gi,showInlineWorkbenchRail:xi,workbenchRailCollapsed:Fc,onToggleWorkbenchRailCollapse:nd,showScratchpad:ti,onCloseScratchpad:()=>sr(!1),connectionInfo:_e,omegaReport:Js,omegaLoading:Pc,omegaError:Rc,onRefreshOmega:ui,activeModel:o,onModelChange:J,visualStyle:n})}),qs&&ar&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[72] bg-black/55",onClick:()=>rs(!1)}),e.jsxs("div",{className:"fixed left-0 top-14 bottom-0 z-[73] flex items-stretch",children:[e.jsx(Sp,{sessions:x,workflowId:l,onSelectSession:Yc,onCreateSession:ra,onSaveSession:Zc,onRetrySave:Xc,onLockSession:Qc,saveStatus:w,isSessionUnlocked:I,sessionHydrationStatus:A,autoLockOnBlur:!!j,onToggleAutoLock:E,auditOnly:Ze,onUpgradeToPro:ed,widthPx:fi}),e.jsx("button",{type:"button",role:"separator","aria-label":"Resize overlay workflow rail","aria-orientation":"vertical","data-testid":"thread-rail-overlay-resize-handle",onPointerDown:kx,onDoubleClick:ji,title:"Drag to resize overlay. Double-click to reset.",className:"group z-20 w-2 -mx-1 cursor-col-resize touch-none select-none flex items-stretch",children:e.jsx("span",{className:"mx-auto my-2 w-px bg-white/30 transition-colors group-hover:bg-cyan-300/90"})})]})]}),Ys&&Ft&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[72] bg-black/55",onClick:()=>ns(!1)}),e.jsxs("div",{className:"fixed right-0 top-14 bottom-0 z-[73] flex items-stretch",children:[e.jsx("button",{type:"button",role:"separator","aria-label":"Resize overlay workbench rail","aria-orientation":"vertical","data-testid":"workbench-rail-overlay-resize-handle",onPointerDown:Nx,onDoubleClick:ki,title:"Drag to resize overlay. Double-click to reset.",className:"group z-20 w-2 -mx-1 cursor-col-resize touch-none select-none flex items-stretch",children:e.jsx("span",{className:"mx-auto my-2 w-px bg-white/30 transition-colors group-hover:bg-cyan-300/90"})}),e.jsx(Kp,{stats:N,workflowId:l,onExecute:Wt,onInsertPrompt:td,auditOnly:Ze,widthPx:bi,connectionInfo:_e,omegaReport:Js,omegaLoading:Pc,omegaError:Rc,onRefreshOmega:ui})]})]}),_&&e.jsx(cg,{onClose:R}),e.jsx(BN,{open:s,onClose:()=>a(!1),onApplyLayout:wx}),e.jsx(VN,{panels:t,collab:wt,workflowId:l}),$&&e.jsx(ow,{connectionInfo:_e}),de&&e.jsx(kw,{onClose:()=>L(!1),capabilities:ce.capabilities}),e.jsx(y1,{open:be,onClose:()=>Q(!1),capabilities:ce.capabilities,tierId:ce.tierId,onOpenMissionControl:()=>{Q(!1),B(!0)},onOpenFleetControl:()=>{Q(!1),xe(!0)},onOpenRecoveryCenter:()=>{Q(!1),$e(!0)},onOpenApplianceConsole:()=>{Q(!1),Ge(!0)},onOpenAirGapOperations:()=>{Q(!1),Dt(!0)},onOpenTrustFabric:Oe?()=>{Q(!1),er(!0)}:void 0,onOpenHardwareAppliance:Oe?()=>{Q(!1),Ct(!0)}:void 0,onOpenCourierTransfer:()=>{Q(!1),mt(!0)},onOpenContinuityDrills:Oe?()=>{Q(!1),_t(!0)}:void 0,onOpenProcurementCommand:()=>{Q(!1),tr(!0)},onOpenTamperSimulation:()=>{Q(!1),$r(!0)},onOpenInstitutionalCommand:()=>{Q(!1),mr(!0)},onOpenDemoFlow:Oe?()=>{Q(!1),fr(!0)}:void 0,onOpenDeploymentProgram:()=>{Q(!1),zr(!0)},onOpenTrainingDelivery:()=>{Q(!1),Hr(!0)},onOpenSupportOps:()=>{Q(!1),br(!0)},onOpenBuyerJourney:()=>{Q(!1),Wr(!0)},onOpenPilotConversion:Oe?()=>{Q(!1),Kr(!0)}:void 0,onOpenCommercialPackages:()=>{Q(!1),Vr(!0)},onOpenFieldLaunch:Oe?()=>{Q(!1),hr(!0)}:void 0,onOpenPartnerRollout:()=>{Q(!1),Gr(!0)},onOpenBuyerOps:()=>{Q(!1),Jr(!0)},onOpenDemoToPilot:()=>{Q(!1),qr(!0)},onOpenPilotExpansion:()=>{Q(!1),Yr(!0)},onOpenRenewalRisk:()=>{Q(!1),Zr(!0)},onOpenLaunchWeek:Oe?()=>{Q(!1),Xr(!0)}:void 0,onOpenFollowupGenerator:()=>{Q(!1),Qr(!0)},onOpenFieldFeedback:()=>{Q(!1),en(!0)},onOpenPartnerCertification:()=>{Q(!1),Rn(!0)},onOpenManagedServices:Oe?()=>{Q(!1),On(!0)}:void 0,onOpenStrategicAccount:Oe?()=>{Q(!1),Tn(!0)}:void 0,onOpenPortfolioRollout:Oe?()=>{Q(!1),Mn(!0)}:void 0,onOpenRevenueOps:Oe?()=>{Q(!1),Dn(!0)}:void 0,onOpenChannelExpansion:Oe?()=>{Q(!1),$n(!0)}:void 0,onOpenCrossAccountRenewal:Oe?()=>{Q(!1),Ln(!0)}:void 0,onOpenExecutiveScale:Oe?()=>{Q(!1),Bn(!0)}:void 0,onOpenEcosystemPortfolio:Oe?()=>{Q(!1),Fn(!0)}:void 0,onOpenServiceLine:Oe?()=>{Q(!1),Un(!0)}:void 0,onOpenPartnerNetworkGovernance:Oe?()=>{Q(!1),zn(!0)}:void 0,onOpenGlobalPlanning:Oe?()=>{Q(!1),Hn(!0)}:void 0,onOpenEcosystemRevenue:()=>{Q(!1),Wn(!0)},onOpenBoardOperatingPack:Oe?()=>{Q(!1),Kn(!0)}:void 0,onOpenLicensedOperator:Oe?()=>{Q(!1),Vn(!0)}:void 0,onOpenEcosystemCommand:Oe?()=>{Q(!1),Gn(!0)}:void 0,onOpenShiftConsole:()=>{Q(!1),Lr(!0)},onOpenIncidentMode:()=>{Q(!1),xr(!0)},onOpenPolicyRollout:()=>{Q(!1),Br(!0)},onOpenOfflineUpdates:()=>{Q(!1),Fr(!0)},onOpenMissionScheduler:()=>{Q(!1),Ur(!0)},applianceModeEnabled:Jn}),e.jsx(C1,{open:We,onClose:()=>B(!1),runtimeState:Se,events:an,onOpenSettings:P,onOpenFleet:At(()=>xe(!0)),onOpenRecovery:At(()=>$e(!0)),onOpenAppliance:At(()=>Ge(!0)),onOpenAirGap:At(()=>Dt(!0)),onOpenTrustFabric:Ee(()=>er(!0)),onOpenHardwareAppliance:Ee(()=>Ct(!0)),onOpenCourierTransfer:At(()=>mt(!0)),onOpenContinuityDrills:Ee(()=>_t(!0)),onOpenProcurementCommand:Ee(()=>tr(!0)),onOpenTamperSimulation:Ee(()=>$r(!0)),onOpenInstitutionalCommand:Ee(()=>mr(!0)),onOpenDemoFlow:Ee(()=>fr(!0)),onOpenDeploymentProgram:Ee(()=>zr(!0)),onOpenTrainingDelivery:At(()=>Hr(!0)),onOpenSupportOps:At(()=>br(!0)),onOpenBuyerJourney:Ee(()=>Wr(!0)),onOpenPilotConversion:Ee(()=>Kr(!0)),onOpenCommercialPackages:Ee(()=>Vr(!0)),onOpenFieldLaunch:Ee(()=>hr(!0)),onOpenPartnerRollout:Ee(()=>Gr(!0)),onOpenBuyerOps:Ee(()=>Jr(!0)),onOpenDemoToPilot:Ee(()=>qr(!0)),onOpenPilotExpansion:Ee(()=>Yr(!0)),onOpenRenewalRisk:Ee(()=>Zr(!0)),onOpenLaunchWeek:Ee(()=>Xr(!0)),onOpenFollowupGenerator:Ee(()=>Qr(!0)),onOpenFieldFeedback:Ee(()=>en(!0)),onOpenPartnerCertification:Ee(()=>Rn(!0)),onOpenManagedServices:Ee(()=>On(!0)),onOpenStrategicAccount:Ee(()=>Tn(!0)),onOpenPortfolioRollout:Ee(()=>Mn(!0)),onOpenRevenueOps:Ee(()=>Dn(!0)),onOpenChannelExpansion:Ee(()=>$n(!0)),onOpenCrossAccountRenewal:Ee(()=>Ln(!0)),onOpenExecutiveScale:Ee(()=>Bn(!0)),onOpenEcosystemPortfolio:Ee(()=>Fn(!0)),onOpenServiceLine:Ee(()=>Un(!0)),onOpenPartnerNetworkGovernance:Ee(()=>zn(!0)),onOpenGlobalPlanning:Ee(()=>Hn(!0)),onOpenEcosystemRevenue:Ee(()=>Wn(!0)),onOpenBoardOperatingPack:Ee(()=>Kn(!0)),onOpenLicensedOperator:Ee(()=>Vn(!0)),onOpenEcosystemCommand:Ee(()=>Gn(!0)),onOpenShift:At(()=>Lr(!0)),onOpenIncidentMode:At(()=>xr(!0)),onOpenPolicyRollout:At(()=>Br(!0)),onOpenOfflineUpdates:()=>Fr(!0),onOpenMissionScheduler:()=>Ur(!0),onOpenNodeChain:()=>Yn(!0),onOpenWatchdog:()=>rr(!0),onOpenFirstBoot:()=>{Ut(),Lt(!0)},onOpenSplitWorkspace:()=>Zn(!0),showInternalSurfaces:Ce}),Ce&&e.jsx("div",{"data-testid":"internal-gtm-surfaces-enabled",hidden:!0,"aria-hidden":"true"}),Bt&&e.jsxs(e.Fragment,{children:[e.jsx(zv,{open:oe,onClose:()=>xe(!1),fleet:vt,onImportLocalRuntime:gx}),e.jsx(Gv,{open:Re,onClose:()=>$e(!1)}),e.jsx(qv,{open:tt,onClose:()=>Ge(!1),enabled:Jn,onToggleEnabled:async k=>{if(Im(!!k),!!(window.api&&window.api.settings&&typeof window.api.settings.get=="function"))try{const v=await window.api.settings.get(),T=v&&typeof v=="object"?v:{};k&&await window.api.settings.update({...T,offlineOnlyEnforced:!0,allowRemoteBridge:!1,autoUpdateChannel:"locked"})}catch{}},runtimeState:Se,fleetSummary:vt.healthSummary}),e.jsx(wj,{open:En,onClose:()=>Dt(!1),locked:Ls,onToggleLocked:async k=>{const v=!!k;if(Pm(v),!!(window.api&&window.api.settings&&typeof window.api.settings.get=="function")){try{const T=await window.api.settings.get(),q=T&&typeof T=="object"?T:{};await window.api.settings.update({...q,offlineOnlyEnforced:v,allowRemoteBridge:v?!1:!!q.allowRemoteBridge,autoUpdateChannel:v?"frozen":String(q.autoUpdateChannel||"stable")})}catch{}X(v?"airgap.lock.enabled":"airgap.lock.disabled",{source:"airgap-operations"},{source:"airgap",severity:v?"critical":"warning"})}}})]}),Ce&&e.jsx(_j,{open:In,onClose:()=>er(!1)}),Ce&&e.jsx(Mj,{open:Dr,onClose:()=>Ct(!1),onOpenSettings:P}),Bt&&e.jsx(Uj,{open:Pn,onClose:()=>mt(!1)}),Ce&&e.jsx(Vj,{open:$t,onClose:()=>_t(!1)}),Ce&&e.jsx(Yj,{open:Ae,onClose:()=>tr(!1)}),Ce&&e.jsx(ek,{open:ro,onClose:()=>$r(!1)}),Ce&&e.jsx(sk,{open:no,onClose:()=>mr(!1),onOpenPanel:Ht}),Ce&&e.jsx(ok,{open:co,onClose:()=>fr(!1),enabled:Bs,onToggleEnabled:Rm,onOpenPanel:Ht}),Ce&&e.jsx(uk,{open:uo,onClose:()=>zr(!1)}),Bt&&e.jsx(fk,{open:po,onClose:()=>Hr(!1)}),Bt&&e.jsx(hk,{open:mo,onClose:()=>br(!1)}),Ce&&e.jsx(gk,{open:xo,onClose:()=>Wr(!1)}),Ce&&e.jsx(wk,{open:fo,onClose:()=>Kr(!1)}),Ce&&e.jsx(jk,{open:bo,onClose:()=>Vr(!1)}),Ce&&e.jsx(kk,{open:ho,onClose:()=>hr(!1),onOpenPanel:Ht}),Ce&&e.jsx(_k,{open:go,onClose:()=>Gr(!1)}),Ce&&e.jsx(Ek,{open:yo,onClose:()=>Jr(!1)}),Ce&&e.jsx(Tk,{open:wo,onClose:()=>qr(!1)}),Ce&&e.jsx(Dk,{open:vo,onClose:()=>Yr(!1)}),Ce&&e.jsx(Bk,{open:jo,onClose:()=>Zr(!1)}),Ce&&e.jsx(Uk,{open:ko,onClose:()=>Xr(!1),onOpenPanel:Ht}),Ce&&e.jsx(Wk,{open:No,onClose:()=>Qr(!1)}),Ce&&e.jsx(Vk,{open:So,onClose:()=>en(!1)}),Ce&&e.jsx(Yk,{open:Co,onClose:()=>Rn(!1)}),Ce&&e.jsx(eN,{open:_o,onClose:()=>On(!1)}),Ce&&e.jsx(nN,{open:Ao,onClose:()=>Tn(!1)}),Ce&&e.jsx(oN,{open:Eo,onClose:()=>Mn(!1)}),Ce&&e.jsx(cN,{open:Io,onClose:()=>Dn(!1)}),Ce&&e.jsx(mN,{open:Po,onClose:()=>$n(!1)}),Ce&&e.jsx(fN,{open:Ro,onClose:()=>Ln(!1)}),Ce&&e.jsx(bN,{open:Oo,onClose:()=>Bn(!1),onOpenPanel:Ht}),Ce&&e.jsx(gN,{open:To,onClose:()=>Fn(!1)}),Ce&&e.jsx(wN,{open:Mo,onClose:()=>Un(!1)}),Ce&&e.jsx(jN,{open:Do,onClose:()=>zn(!1)}),Ce&&e.jsx(NN,{open:$o,onClose:()=>Hn(!1)}),Ce&&e.jsx(CN,{open:Lo,onClose:()=>Wn(!1)}),Ce&&e.jsx(AN,{open:Bo,onClose:()=>Kn(!1)}),Ce&&e.jsx(IN,{open:Fo,onClose:()=>Vn(!1)}),Ce&&e.jsx(PN,{open:Uo,onClose:()=>Gn(!1),onOpenPanel:Ht}),Bt&&e.jsx(ej,{open:so,onClose:()=>Lr(!1),role:gt,onChangeRole:k=>Om(k),fleetNodes:vt.nodes,incidents:qn.filter(k=>String(k&&k.status?k.status:"")==="open")}),Bt&&e.jsx(nj,{open:ao,onClose:()=>xr(!1),incidents:qn,fleetNodes:vt.nodes,onDeclare:k=>{const v={incidentId:`inc-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,title:String(k&&k.title?k.title:"Runtime Incident"),severity:String(k&&k.severity?k.severity:"degraded"),status:"open",declaredAt:new Date().toISOString(),affectedNodes:Array.isArray(k&&k.affectedNodes)?k.affectedNodes:[],timeline:[]};return Fs(T=>[v,...Array.isArray(T)?T:[]].slice(0,250)),X("incident.declared",{incidentId:v.incidentId,severity:v.severity,affectedNodes:v.affectedNodes.length},{source:"incident",severity:v.severity==="critical"?"critical":"degraded"}),v},onResolve:k=>{Fs(v=>Array.isArray(v)?v.map(T=>String(T.incidentId||"")===String(k||"")?{...T,status:"resolved",resolvedAt:new Date().toISOString()}:T):v),X("incident.resolved",{incidentId:String(k||"")},{source:"incident",severity:"info"})},onApplyPlaybook:(k,v)=>{const T=String(v&&v.incidentId?v.incidentId:"");T&&(Fs(q=>Array.isArray(q)?q.map(Y=>String(Y.incidentId||"")!==T?Y:{...Y,timeline:[...Array.isArray(Y.timeline)?Y.timeline:[],{at:new Date().toISOString(),type:"incident.playbook.applied",source:"incident",detail:{playbookId:String(k&&k.id?k.id:""),playbookTitle:String(k&&k.title?k.title:"")}}].slice(-400)}):q),X("incident.playbook.applied",{incidentId:T,playbookId:String(k&&k.id?k.id:"")},{source:"incident",severity:"warning"}))},onTriggerSafeMode:async()=>{if(window.api&&window.api.settings&&typeof window.api.settings.get=="function"){try{const k=await window.api.settings.get();await window.api.settings.update({...k||{},offlineOnlyEnforced:!0,allowRemoteBridge:!1,autoUpdateChannel:"frozen"})}catch{}X("incident.safe_mode.enabled",{},{source:"incident",severity:"critical"})}}}),Bt&&e.jsx(ij,{open:oo,onClose:()=>Br(!1),fleet:vt,history:Us,onApplyRollout:({bundle:k,nodeIds:v,mode:T,scheduledFor:q})=>{const Y=k&&k.payload&&typeof k.payload=="object"?k.payload:{},ue=String(Y.policyProfile||Y.label||Y.policyId||"fleet-policy"),se=String(Y.policyId||ue||"policy"),le={rolloutId:`rollout-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,policyId:se,policyProfile:ue,nodeIds:Array.isArray(v)?v:[],mode:String(T||"immediate"),scheduledFor:q||"",status:"applied",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};vt.applyPolicyBundle({policyProfile:ue,policyId:se},le.nodeIds,{mode:le.mode}),cc(Le=>[le,...Array.isArray(Le)?Le:[]].slice(0,250)),X("fleet.policy.rollout.applied",{rolloutId:le.rolloutId,policyProfile:ue,targets:le.nodeIds.length,mode:le.mode},{source:"fleet-policy",severity:"info"})},onRollbackRollout:k=>{const v=k&&typeof k=="object"?k:{},T=Array.isArray(v.nodeIds)?v.nodeIds:[];T.forEach(q=>{vt.rollbackPolicy(q,"none")}),cc(q=>Array.isArray(q)?q.map(Y=>String(Y.rolloutId||"")===String(v.rolloutId||"")?{...Y,status:"rolled_back",updatedAt:new Date().toISOString()}:Y):q),X("fleet.policy.rollout.rolled_back",{rolloutId:String(v.rolloutId||""),targets:T.length},{source:"fleet-policy",severity:"warning"})}}),e.jsx(uj,{open:io,onClose:()=>Fr(!1),fleet:vt}),e.jsx(bj,{open:lo,onClose:()=>Ur(!1),fleet:vt,onOpenIncidentMode:()=>xr(!0)}),e.jsx(P1,{open:zo,onClose:()=>Yn(!1),onSnapshotRequest:wi,onOpenPanel:Ht}),e.jsx(O1,{open:Ho,alerts:Qn,onClose:()=>rr(!1),onAcknowledge:hx}),e.jsx(q1,{open:Wo,onClose:()=>rn(!1),workflowId:l}),e.jsx(ev,{open:Ko,onClose:()=>zs(!1)}),e.jsx(cv,{open:Vo,onClose:()=>Zn(!1),runtimeState:Se,onRestoreSnapshotPayload:yx,alerts:Qn,proofStdout:nx,releaseHealth:Se&&Se.releaseHealth?Se.releaseHealth:{}}),e.jsx(Ev,{open:Go,onClose:()=>Xn(!1),stats:N,connectionInfo:_e,accelStatus:G,settings:ot,workflowId:l,initialTab:Jo,onOpenWorkpad:()=>sr(!0),chatLog:p}),e.jsx(Pv,{open:Yo,onClose:()=>yt(!1),connectionInfo:_e,watchdogStatus:os,incidentCount:zt.length,setupBlocked:!!(Et&&!vr),sessionDegradedDismissed:sn,acknowledgedReady:nn,exportAvailable:cs,exportBusy:Wc,onStartOperating:ix,onInspectIssue:()=>{yt(!1),rr(!0)},onFixSetup:()=>{yt(!1),z(),Ut()},onOpenSettings:()=>{yt(!1),z()},onContinueAnyway:lx,onExportEvidence:yi}),e.jsx(Iv,{}),gr&&e.jsx(tv,{open:gr,steps:Oc,progress:Tc,busyStepId:tx,onRunStep:xx,onSkipStep:fx,onClose:()=>{Lt(!1),as(),typeof window<"u"&&window.localStorage&&window.localStorage.setItem("neuralshell_first_boot_completed_v1","1")},onFinish:bx}),di&&or&&!gr&&e.jsx(Rw,{open:or,onClose:mx,onOpenSettings:P,onRunCommand:Wt}),e.jsx(Tw,{open:qm,onClose:()=>gc(!1),metadata:{tier:ce.tierLabel,version:"NeuralShell_V2.2.0",workflowId:l||"",supportBundlePath:wc.outputPath||"",supportBundleHash:wc.sha256||""}}),e.jsx($w,{open:Ym,onClose:()=>yc(!1),workflowId:l||"",tierLabel:ce.tierLabel}),K.open&&e.jsx("div",{"data-testid":"session-modal-overlay",className:"fixed inset-0 z-[90] bg-black/60 backdrop-blur-sm flex items-center justify-center p-4",onMouseDown:k=>{k.target===k.currentTarget&&kr()},children:e.jsxs("div",{"data-testid":"session-modal",role:"dialog","aria-modal":"true","aria-labelledby":Nc,"aria-describedby":Sc,className:"w-full max-w-md rounded-2xl border border-cyan-400/20 bg-slate-950 shadow-[0_20px_80px_rgba(0,0,0,0.7)] p-6",children:[e.jsx("h2",{id:Nc,className:"text-lg font-bold text-cyan-100 tracking-wide mb-2",children:K.mode==="create"?"Create Session":"Unlock Session"}),e.jsx("p",{id:Sc,className:"text-[11px] text-slate-400 font-mono mb-5",children:K.mode==="create"?"Set a session name and passphrase. The passphrase stays local to this runtime.":`Enter the passphrase for "${K.targetSession}".`}),e.jsxs("form",{onSubmit:dx,className:"space-y-4",children:[K.mode==="create"&&e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Session Name"}),e.jsx("input",{ref:ai,"data-testid":"session-modal-name-input",value:ni,onChange:k=>bc(k.target.value),placeholder:"Workflow_ALPHA",autoFocus:!0,className:"mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm text-slate-100 outline-none focus:border-cyan-400/40"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em] text-slate-400 font-bold",children:"Passphrase"}),e.jsx("input",{ref:oi,"data-testid":"session-modal-pass-input",type:"password",value:Ks,onChange:k=>si(k.target.value),placeholder:"Required",autoFocus:K.mode!=="create",className:"mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm text-slate-100 outline-none focus:border-cyan-400/40"})]}),hc&&e.jsx("div",{"data-testid":"session-modal-error",className:"text-[11px] text-rose-300 font-mono",children:hc}),e.jsxs("div",{className:"pt-2 flex gap-2 justify-end",children:[e.jsx("button",{ref:jc,type:"button","data-testid":"session-modal-cancel-btn",onClick:kr,className:"px-4 py-2 rounded-lg border border-white/10 text-[10px] uppercase tracking-[0.14em] font-bold text-slate-300 hover:bg-white/5",children:"Cancel"}),e.jsx("button",{ref:kc,type:"submit","data-testid":"session-modal-submit-btn",className:"px-4 py-2 rounded-lg border border-cyan-300/30 bg-cyan-400/10 text-[10px] uppercase tracking-[0.14em] font-bold text-cyan-200 hover:bg-cyan-400/20",children:K.mode==="create"?"Create Session":"Unlock Session"})]})]})]})})]}),Mm&&e.jsx(hf,{workflowId:l,proofStatus:Se&&Se.proofEngine?Se.proofEngine.lastProofStatus:"idle",exportEvidenceAvailable:cs,evidenceExported:$m,onRunProof:()=>Wt("/proof"),onOpenTrustReport:ei,onExportEvidence:yi,onOpenWorkpad:Qo,onDismiss:cx})]})}function RS(t){return t?Array.isArray(t.messages)?t.messages.map(r=>({role:String(r&&r.role?r.role:"assistant"),content:String(r&&r.content?r.content:"")})):t.content?[{role:"assistant",content:String(t.content)}]:[]:[]}function OS({hash:t}){const[r,n]=i.useState("loading"),[s,a]=i.useState(""),[o,c]=i.useState(null);i.useEffect(()=>{let u=!0;return(async()=>{try{const p=String(window.location.hash||"").replace(/^#/,"").trim();let d=null;if(p)d=await Th(p);else{const m=await Dh(t);d=await Vp(m)}if(!u)return;c(d),n("ready")}catch(p){if(!u)return;a(p&&p.message?String(p.message):"Unable to load share payload."),n("error")}})(),()=>{u=!1}},[t]);const l=RS(o);return e.jsx("div",{className:"min-h-screen bg-slate-950 text-slate-100 px-6 py-10",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.2em] text-cyan-400/70 font-bold",children:"ProofForge Share"}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mt-1",children:"Read-Only Conversation"}),e.jsxs("div",{className:"text-[11px] font-mono text-slate-400 mt-1",children:["/share/",t]})]}),r==="loading"&&e.jsx("div",{className:"rounded-2xl border border-white/10 bg-black/30 p-5 text-[12px] font-mono text-slate-300",children:"Decrypting shared payload..."}),r==="error"&&e.jsx("div",{className:"rounded-2xl border border-rose-300/30 bg-rose-500/10 p-5 text-[12px] font-mono text-rose-200",children:s||"Failed to load shared conversation."}),r==="ready"&&e.jsxs("div",{className:"space-y-4",children:[l.length===0&&e.jsx("div",{className:"rounded-2xl border border-white/10 bg-black/30 p-5 text-[12px] font-mono text-slate-300",children:"Share payload is valid but empty."}),l.map((u,x)=>e.jsxs("div",{className:`rounded-2xl border p-4 text-[13px] leading-relaxed whitespace-pre-wrap ${u.role==="user"?"border-cyan-300/30 bg-cyan-500/10 text-cyan-50 ml-10":"border-white/10 bg-black/35 text-slate-200 mr-10"}`,children:[e.jsx("div",{className:"text-[9px] uppercase tracking-[0.2em] text-slate-500 mb-2",children:u.role}),u.content]},`${u.role}-${x}`))]})]})})}function Em(t){return String(t||"").trim().replace(/[^a-zA-Z0-9_-]/g,"")}function TS(t){const r=String(t||"").match(/^\/share\/([a-zA-Z0-9_-]+)$/);return r?Em(r[1]):""}function MS(t){const r=String(t||"").match(/^#\/share\/([a-zA-Z0-9_-]+)/);return r?Em(r[1]):""}function DS(t,r){const n=String(t||"").trim(),s=String(r||"").trim();return n==="/scratchpad"||s==="#/scratchpad"}function $S(t,r=""){const n=TS(t);if(n)return{name:"share",hash:n};const s=MS(r);return s?{name:"share",hash:s}:DS(t,r)?{name:"scratchpad"}:{name:"app"}}const hp=$S(window.location.pathname,window.location.hash);rf.createRoot(document.getElementById("root")).render(e.jsx(i.StrictMode,{children:hp.name==="share"?e.jsx(OS,{hash:hp.hash}):e.jsx(uf,{children:e.jsx(PS,{})})}));export{QS as A,XS as B,KS as C,Zb as D,qS as E,n2 as F,c2 as G,Ew as H,_0 as I,s2 as J,Cw as K,_w as L,Aw as W,qa as a,Zl as b,ge as c,t2 as d,th as e,Fa as f,i2 as g,zp as h,r2 as i,WS as j,Ta as k,et as l,Qt as m,Ga as n,GS as o,a2 as p,Nw as q,l2 as r,Bp as s,o2 as t,e2 as u,JS as v,eh as w,ZS as x,YS as y,VS as z}; diff --git a/docs/receipts/PR165_LLM_HEALTH_SNAPSHOT_UNIFY_RECEIPT_2026-06-26.md b/docs/receipts/PR165_LLM_HEALTH_SNAPSHOT_UNIFY_RECEIPT_2026-06-26.md new file mode 100644 index 00000000..2a2d27d7 --- /dev/null +++ b/docs/receipts/PR165_LLM_HEALTH_SNAPSHOT_UNIFY_RECEIPT_2026-06-26.md @@ -0,0 +1,99 @@ +# PR #165 — LLM Health Snapshot Unify and Session-Lock Repair Receipt + +**Date:** 2026-06-26 +**Type:** product / runtime bug fix +**Branch:** `product/llm-health-snapshot-unify` +**Master at branch:** `73f2cf5` (post-PR #164) + +--- + +## Root causes fixed + +### 1. Local Ollama health check tested at api.openai.com + +`checkLocalOllama` in `src/core/systemHealthCheck.js` used `settings.ollamaBaseUrl` +as its base URL. The `ollamaBaseUrl` field is a multipurpose "base URL" key that +stores the endpoint for whatever provider is currently selected. When the previous +provider was OpenAI, `ollamaBaseUrl` held `https://api.openai.com`. The function +then tested *that* URL while labeling the check "Local Ollama," producing the +confusing result: + +``` +Local Ollama +Ollama not detected at https://api.openai.com +request failed with status 404 +``` + +**Fix:** When `settings.provider !== 'ollama'`, always use `http://127.0.0.1:11434` +regardless of `ollamaBaseUrl`. When the active provider *is* Ollama, `ollamaBaseUrl` +is used as-is (it holds the correct local endpoint after a provider switch). + +### 2. Hosted policy check reported "openai selected" when route was ollama + +`checkHostedPolicy` read `settings.provider` directly. If there was an active +connection profile with `provider: 'openai'`, and `settings.provider` was also +`'openai'` (stale settings), the check reported "Provider openai selected but +Hosted Provider Access is disabled" even though the UI showed ollama/llama3. + +**Fix:** Prefer the active connection profile's provider over the raw +`settings.provider`. Falls back to `settings.provider` if no active profile exists. + +### 3. "Runtime Fatal" from update verification watchdog + +`updateVerificationCheck.ts` returned `severity: "critical"` for any non-verified +update lane state. In App.jsx, any unacknowledged `critical` watchdog alert triggers +`watchdogStatus = 'fatal'`, which surfaces as "Runtime Fatal" in the trust strip. +An update verification issue (e.g. signatures not yet checked) is not a runtime +process crash and should not collapse the entire runtime health to fatal. + +**Fix:** Downgrade update verification severity from `"critical"` to `"degraded"`. +The comment documents that "critical" is reserved for runtime process crashes, +data corruption, or security breaches. + +### 4. Locked sessions returned confusing vault/NodeChain responses in chat + +`executeSignal` checked `auditOnly` (Auditor tier) but did not check whether the +active session was locked. A locked session could still reach the LLM, but the +response was filtered through NodeChain/vault guards, producing internal messages +like "NodeChain prompted a vault save" instead of the expected model response. +The user had no indication that the session lock was blocking normal chat. + +**Fix:** Before freeform chat (non-command input), check `isSessionUnlocked(workflowId)`. +If the session is locked, append a clear message: +``` +Session "Workflow_RYV9B" is locked. Unlock it to send chat messages (proof commands still work). +``` +Commands (`/proof`, `/roi`, etc.) are exempt because they are local operations, +not LLM calls. + +--- + +## Files changed + +| File | Change | +|---|---| +| `src/core/systemHealthCheck.js` | `checkLocalOllama`: force local URL when provider != ollama. `checkHostedPolicy`: prefer active profile provider | +| `src/renderer/src/runtime/watchdog/checks/updateVerificationCheck.ts` | severity: `"critical"` → `"degraded"` | +| `src/renderer/src/App.jsx` | `executeSignal`: session lock check blocks freeform chat with clear message | + +--- + +## What was NOT changed + +- Watchdog severity taxonomy — update verification was the only `critical` source + from the watchdog; the rest (vault, relay, provider) were already `warning`/`degraded` +- The `vaultHealthCheck` `"warning"` severity — vault locked is a session state, not + a health failure, but changing its severity class touches more components +- The `ollamaBaseUrl` field name — it's a universal base URL field, not Ollama-specific; + renaming it is out of scope for a targeted repair PR + +--- + +## Runtime proof (all PASS) + +| Gate | Result | +|---|---| +| `npm run build:renderer` | PASS | +| `npm run test:local:ops` | PASS (13/13 + spine + bridge-diagnosis) | +| `npm run smoke:operator` | PASS (exit 0) | +| `npm audit --omit=dev --audit-level=high` | 0 vulnerabilities | diff --git a/src/core/systemHealthCheck.js b/src/core/systemHealthCheck.js index 9540f6c3..2d68bf17 100644 --- a/src/core/systemHealthCheck.js +++ b/src/core/systemHealthCheck.js @@ -138,10 +138,14 @@ async function checkActiveLlmBridge(deps = {}) { async function checkLocalOllama(deps = {}, options = {}) { const settings = deps.settings && typeof deps.settings === "object" ? deps.settings : {}; - const baseUrl = String( - settings.ollamaBaseUrl - || "http://127.0.0.1:11434" - ).trim(); + // ollamaBaseUrl stores the base URL for whatever provider is currently selected. + // When the active provider is not Ollama, it may hold a hosted URL (e.g. api.openai.com) + // which has no relationship to where the local Ollama server runs. + // Always fall back to the standard local endpoint when Ollama is not the active provider. + const activeProvider = String(settings.provider || "ollama"); + const baseUrl = activeProvider === "ollama" + ? String(settings.ollamaBaseUrl || "http://127.0.0.1:11434").trim() + : "http://127.0.0.1:11434"; const started = Date.now(); const probe = new LLMService({ provider: "ollama", @@ -441,7 +445,15 @@ async function checkAuditChain(deps = {}) { async function checkHostedPolicy(deps = {}) { const settings = deps.settings || {}; const allowRemote = Boolean(settings.allowRemoteBridge); - const provider = String(settings.provider || "ollama"); + // Prefer the active connection profile's provider over the raw settings.provider. + // The raw provider field can be stale when a profile was switched but not yet saved. + const profiles = Array.isArray(settings.connectionProfiles) ? settings.connectionProfiles : []; + const activeProfile = profiles.find((p) => + String(p?.id || '') === String(settings.activeProfileId || '') + ) || profiles[0] || null; + const profileProvider = activeProfile ? String(activeProfile.provider || '').trim().toLowerCase() : ''; + const rawProvider = String(settings.provider || "ollama"); + const provider = profileProvider || rawProvider; const remote = provider !== "ollama"; if (remote && !allowRemote) { return buildCheck({ diff --git a/src/renderer/src/App.jsx b/src/renderer/src/App.jsx index 5aa5995b..3f603dff 100644 --- a/src/renderer/src/App.jsx +++ b/src/renderer/src/App.jsx @@ -2552,6 +2552,17 @@ function App() { } } + // Freeform chat is blocked when the session is locked. Commands (/proof, etc.) + // pass through because they are local proof operations, not LLM calls. + if (!command.startsWith('/') && workflowId && workflowId !== QUICKSTART_SESSION && !isSessionUnlocked(workflowId)) { + setIsThinking(false); + appendChat({ + role: 'kernel', + content: `Session "${workflowId}" is locked. Unlock it to send chat messages (proof commands still work).`, + }); + return; + } + if (command.startsWith('/')) { setIsThinking(false); if (command === '/clear' || command === '/purge' || command === '/reset') { diff --git a/src/renderer/src/runtime/watchdog/checks/updateVerificationCheck.ts b/src/renderer/src/runtime/watchdog/checks/updateVerificationCheck.ts index a89a61a6..bc2d0b97 100644 --- a/src/renderer/src/runtime/watchdog/checks/updateVerificationCheck.ts +++ b/src/renderer/src/runtime/watchdog/checks/updateVerificationCheck.ts @@ -10,7 +10,9 @@ export function updateVerificationCheck(input: UpdateVerificationInput) { if (!staged && signatureState === "unknown") return null; return { source: "update-lane", - severity: "critical", + // degraded, not critical — update lane issues are deploy-time, not runtime-crash. + // Reserve "critical" for runtime process crashes, data corruption, or security breaches. + severity: "degraded", message: `Update verification is ${signatureState}.`, suggestedAction: "Freeze update apply lane until signature/hash verification passes.", };