function Le(e,n){for(var s=0;s<n.length;s++){const a=n[s];if(typeof a!="string"&&!Array.isArray(a)){for(const i in a)if(i!=="default"&&!(i in e)){const d=Object.getOwnPropertyDescriptor(a,i);d&&Object.defineProperty(e,i,d.get?d:{enumerable:!0,get:()=>a[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}var xs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Oe(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ce={exports:{}},se={};/**
 * @license React
 * react-jsx-runtime.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var he;function De(){if(he)return se;he=1;var e=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function s(a,i,d){var o=null;if(d!==void 0&&(o=""+d),i.key!==void 0&&(o=""+i.key),"key"in i){d={};for(var c in i)c!=="key"&&(d[c]=i[c])}else d=i;return i=d.ref,{$$typeof:e,type:a,key:o,ref:i!==void 0?i:null,props:d}}return se.Fragment=n,se.jsx=s,se.jsxs=s,se}var pe;function Me(){return pe||(pe=1,ce.exports=De()),ce.exports}var t=Me(),ue={exports:{}},P={};/**
 * @license React
 * react.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var be;function Ge(){if(be)return P;be=1;var e=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),d=Symbol.for("react.consumer"),o=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),y=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),f=Symbol.for("react.activity"),p=Symbol.iterator;function g(l){return l===null||typeof l!="object"?null:(l=p&&l[p]||l["@@iterator"],typeof l=="function"?l:null)}var N={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,v={};function E(l,k,$){this.props=l,this.context=k,this.refs=v,this.updater=$||N}E.prototype.isReactComponent={},E.prototype.setState=function(l,k){if(typeof l!="object"&&typeof l!="function"&&l!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,l,k,"setState")},E.prototype.forceUpdate=function(l){this.updater.enqueueForceUpdate(this,l,"forceUpdate")};function w(){}w.prototype=E.prototype;function T(l,k,$){this.props=l,this.context=k,this.refs=v,this.updater=$||N}var x=T.prototype=new w;x.constructor=T,C(x,E.prototype),x.isPureReactComponent=!0;var j=Array.isArray;function h(){}var b={H:null,A:null,T:null,S:null},S=Object.prototype.hasOwnProperty;function A(l,k,$){var _=$.ref;return{$$typeof:e,type:l,key:k,ref:_!==void 0?_:null,props:$}}function D(l,k){return A(l.type,k,l.props)}function I(l){return typeof l=="object"&&l!==null&&l.$$typeof===e}function O(l){var k={"=":"=0",":":"=2"};return"$"+l.replace(/[=:]/g,function($){return k[$]})}var L=/\/+/g;function F(l,k){return typeof l=="object"&&l!==null&&l.key!=null?O(""+l.key):k.toString(36)}function q(l){switch(l.status){case"fulfilled":return l.value;case"rejected":throw l.reason;default:switch(typeof l.status=="string"?l.then(h,h):(l.status="pending",l.then(function(k){l.status==="pending"&&(l.status="fulfilled",l.value=k)},function(k){l.status==="pending"&&(l.status="rejected",l.reason=k)})),l.status){case"fulfilled":return l.value;case"rejected":throw l.reason}}throw l}function Y(l,k,$,_,M){var G=typeof l;(G==="undefined"||G==="boolean")&&(l=null);var U=!1;if(l===null)U=!0;else switch(G){case"bigint":case"string":case"number":U=!0;break;case"object":switch(l.$$typeof){case e:case n:U=!0;break;case m:return U=l._init,Y(U(l._payload),k,$,_,M)}}if(U)return M=M(l),U=_===""?"."+F(l,0):_,j(M)?($="",U!=null&&($=U.replace(L,"$&/")+"/"),Y(M,k,$,"",function(R){return R})):M!=null&&(I(M)&&(M=D(M,$+(M.key==null||l&&l.key===M.key?"":(""+M.key).replace(L,"$&/")+"/")+U)),k.push(M)),1;U=0;var K=_===""?".":_+":";if(j(l))for(var B=0;B<l.length;B++)_=l[B],G=K+F(_,B),U+=Y(_,k,$,G,M);else if(B=g(l),typeof B=="function")for(l=B.call(l),B=0;!(_=l.next()).done;)_=_.value,G=K+F(_,B++),U+=Y(_,k,$,G,M);else if(G==="object"){if(typeof l.then=="function")return Y(q(l),k,$,_,M);throw k=String(l),Error("Objects are not valid as a React child (found: "+(k==="[object Object]"?"object with keys {"+Object.keys(l).join(", ")+"}":k)+"). If you meant to render a collection of children, use an array instead.")}return U}function z(l,k,$){if(l==null)return l;var _=[],M=0;return Y(l,_,"","",function(G){return k.call($,G,M++)}),_}function ee(l){if(l._status===-1){var k=l._result;k=k(),k.then(function($){(l._status===0||l._status===-1)&&(l._status=1,l._result=$)},function($){(l._status===0||l._status===-1)&&(l._status=2,l._result=$)}),l._status===-1&&(l._status=0,l._result=k)}if(l._status===1)return l._result.default;throw l._result}var Q=typeof reportError=="function"?reportError:function(l){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var k=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof l=="object"&&l!==null&&typeof l.message=="string"?String(l.message):String(l),error:l});if(!window.dispatchEvent(k))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",l);return}console.error(l)},W={map:z,forEach:function(l,k,$){z(l,function(){k.apply(this,arguments)},$)},count:function(l){var k=0;return z(l,function(){k++}),k},toArray:function(l){return z(l,function(k){return k})||[]},only:function(l){if(!I(l))throw Error("React.Children.only expected to receive a single React element child.");return l}};return P.Activity=f,P.Children=W,P.Component=E,P.Fragment=s,P.Profiler=i,P.PureComponent=T,P.StrictMode=a,P.Suspense=u,P.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=b,P.__COMPILER_RUNTIME={__proto__:null,c:function(l){return b.H.useMemoCache(l)}},P.cache=function(l){return function(){return l.apply(null,arguments)}},P.cacheSignal=function(){return null},P.cloneElement=function(l,k,$){if(l==null)throw Error("The argument must be a React element, but you passed "+l+".");var _=C({},l.props),M=l.key;if(k!=null)for(G in k.key!==void 0&&(M=""+k.key),k)!S.call(k,G)||G==="key"||G==="__self"||G==="__source"||G==="ref"&&k.ref===void 0||(_[G]=k[G]);var G=arguments.length-2;if(G===1)_.children=$;else if(1<G){for(var U=Array(G),K=0;K<G;K++)U[K]=arguments[K+2];_.children=U}return A(l.type,M,_)},P.createContext=function(l){return l={$$typeof:o,_currentValue:l,_currentValue2:l,_threadCount:0,Provider:null,Consumer:null},l.Provider=l,l.Consumer={$$typeof:d,_context:l},l},P.createElement=function(l,k,$){var _,M={},G=null;if(k!=null)for(_ in k.key!==void 0&&(G=""+k.key),k)S.call(k,_)&&_!=="key"&&_!=="__self"&&_!=="__source"&&(M[_]=k[_]);var U=arguments.length-2;if(U===1)M.children=$;else if(1<U){for(var K=Array(U),B=0;B<U;B++)K[B]=arguments[B+2];M.children=K}if(l&&l.defaultProps)for(_ in U=l.defaultProps,U)M[_]===void 0&&(M[_]=U[_]);return A(l,G,M)},P.createRef=function(){return{current:null}},P.forwardRef=function(l){return{$$typeof:c,render:l}},P.isValidElement=I,P.lazy=function(l){return{$$typeof:m,_payload:{_status:-1,_result:l},_init:ee}},P.memo=function(l,k){return{$$typeof:y,type:l,compare:k===void 0?null:k}},P.startTransition=function(l){var k=b.T,$={};b.T=$;try{var _=l(),M=b.S;M!==null&&M($,_),typeof _=="object"&&_!==null&&typeof _.then=="function"&&_.then(h,Q)}catch(G){Q(G)}finally{k!==null&&$.types!==null&&(k.types=$.types),b.T=k}},P.unstable_useCacheRefresh=function(){return b.H.useCacheRefresh()},P.use=function(l){return b.H.use(l)},P.useActionState=function(l,k,$){return b.H.useActionState(l,k,$)},P.useCallback=function(l,k){return b.H.useCallback(l,k)},P.useContext=function(l){return b.H.useContext(l)},P.useDebugValue=function(){},P.useDeferredValue=function(l,k){return b.H.useDeferredValue(l,k)},P.useEffect=function(l,k){return b.H.useEffect(l,k)},P.useEffectEvent=function(l){return b.H.useEffectEvent(l)},P.useId=function(){return b.H.useId()},P.useImperativeHandle=function(l,k,$){return b.H.useImperativeHandle(l,k,$)},P.useInsertionEffect=function(l,k){return b.H.useInsertionEffect(l,k)},P.useLayoutEffect=function(l,k){return b.H.useLayoutEffect(l,k)},P.useMemo=function(l,k){return b.H.useMemo(l,k)},P.useOptimistic=function(l,k){return b.H.useOptimistic(l,k)},P.useReducer=function(l,k,$){return b.H.useReducer(l,k,$)},P.useRef=function(l){return b.H.useRef(l)},P.useState=function(l){return b.H.useState(l)},P.useSyncExternalStore=function(l,k,$){return b.H.useSyncExternalStore(l,k,$)},P.useTransition=function(){return b.H.useTransition()},P.version="19.2.7",P}var ye;function Fe(){return ye||(ye=1,ue.exports=Ge()),ue.exports}var r=Fe();const Ue=Oe(r),js=Le({__proto__:null,default:Ue},[r]);let fe=null;function Ns(e){fe=e??null}function J(e,n={}){const s={...n.headers||{}};return fe&&(s["X-Compose-Workspace-Id"]=fe),fetch(e,{...n,headers:s})}const He="";let Ee=null;function ge(e){Ee=e||null}function Be(){return Ee||He||""}function V(e={}){const n=Be();return n?{...e,"x-compose-token":n}:e}const Je=[{id:"explore_design",name:"Explore Design",agent:"claude",phase:"design",hasGate:!1},{id:"design_review",name:"Design Review",agent:"codex",phase:"design",hasGate:!1},{id:"design_gate",name:"Design Gate",agent:"human",phase:"design",hasGate:!0},{id:"prd",name:"PRD",agent:"claude",phase:"design",hasGate:!1},{id:"prd_review",name:"PRD Review",agent:"codex",phase:"design",hasGate:!1},{id:"prd_gate",name:"PRD Gate",agent:"human",phase:"design",hasGate:!0},{id:"architecture",name:"Architecture",agent:"claude",phase:"design",hasGate:!1},{id:"architecture_review",name:"Arch Review",agent:"codex",phase:"design",hasGate:!1},{id:"architecture_gate",name:"Arch Gate",agent:"human",phase:"design",hasGate:!0},{id:"blueprint",name:"Blueprint",agent:"claude",phase:"blueprint",hasGate:!1},{id:"verification",name:"Verification",agent:"claude",phase:"blueprint",hasGate:!1},{id:"blueprint_review",name:"BP Review",agent:"codex",phase:"blueprint",hasGate:!1},{id:"plan",name:"Plan",agent:"claude",phase:"implementation",hasGate:!1},{id:"plan_review",name:"Plan Review",agent:"codex",phase:"implementation",hasGate:!1},{id:"plan_gate",name:"Plan Gate",agent:"human",phase:"implementation",hasGate:!0},{id:"execute",name:"Execute",agent:"claude",phase:"implementation",hasGate:!1},{id:"review",name:"Review Loop",agent:"codex",phase:"implementation",hasGate:!1},{id:"coverage",name:"Coverage Sweep",agent:"claude",phase:"implementation",hasGate:!1},{id:"report",name:"Report",agent:"claude",phase:"ship",hasGate:!1},{id:"report_review",name:"Report Review",agent:"codex",phase:"ship",hasGate:!1},{id:"report_gate",name:"Report Gate",agent:"human",phase:"ship",hasGate:!0},{id:"docs",name:"Docs",agent:"claude",phase:"ship",hasGate:!1},{id:"ship",name:"Ship",agent:"claude",phase:"ship",hasGate:!1},{id:"ship_gate",name:"Ship Gate",agent:"human",phase:"ship",hasGate:!0}],qe=new Set(["complete","completed","aborted","failed","killed","done"]);function ae(e){return qe.has(e)}function Ye(e,n,s){const a=Array.isArray(n)?Object.fromEntries(n.map(o=>[o.id,o.status])):{},i=Array.isArray(n)?Object.fromEntries(n.map(o=>[o.id,o])):{},d=e.map(o=>{const c=i[o.id],u=c?{...o,...c}:{...o};return u.id===s&&!a[u.id]&&(u.status="active"),u});if(Array.isArray(n))for(const o of n)e.find(c=>c.id===o.id)||d.push({id:o.id,name:o.id.replace(/_/g," "),agent:"claude",phase:"implementation",...o});return d}function We(e,n,s){if(!e)return!1;const{featureCode:a,status:i,currentStepId:d}=e;if(i!=="running"||!d||!d.endsWith("_gate"))return!1;const o=Array.isArray(s)?s:[],c=o.find(u=>u.featureCode===a)||o.find(u=>u.title===a)||o.find(u=>u.title&&u.title.startsWith(a+":"));return c?(Array.isArray(n)?n:[]).some(u=>u.itemId===c.id&&!u.resolvedAt):!1}const Ke=[{id:"agents",label:"Agents",icon:"◇"},{id:"roadmap",label:"Roadmap",icon:"⚡"},{id:"builds",label:"Builds",icon:"⏵"},{id:"ideas",label:"Ideas",icon:"✦"}];function ze({active:e,onSelect:n,badges:s}){return t.jsx("nav",{className:"m-bottom-nav",role:"tablist","aria-label":"Mobile navigation",children:Ke.map(a=>{const i=s==null?void 0:s[a.id];return t.jsxs("button",{type:"button",className:"m-nav-btn",role:"tab","aria-pressed":e===a.id?"true":"false","aria-label":a.label,"data-tab":a.id,"data-testid":`mobile-nav-${a.id}`,onClick:()=>n(a.id),children:[t.jsxs("span",{className:"m-nav-icon-wrap",children:[t.jsx("span",{className:"m-nav-icon","aria-hidden":"true",children:a.icon}),i&&t.jsx("span",{className:`m-nav-badge m-nav-badge-${i.level||"info"}`,"data-testid":`mobile-nav-badge-${a.id}`,"aria-hidden":"true",children:i.count!=null?String(i.count):""})]}),t.jsx("span",{className:"m-nav-label",children:a.label})]},a.id)})})}async function Xe(e,n={}){const s=await J(e,n);let a=null;try{a=await s.json()}catch{}if(!s.ok){const i=a&&a.error||`HTTP ${s.status}`;throw new Error(i)}return a}function Ve(){const[e,n]=r.useState([]),[s,a]=r.useState(!0),[i,d]=r.useState(null),o=r.useRef(!0),c=r.useCallback(async()=>{try{const u=await Xe("/api/agents/tree");if(!o.current)return;n(Array.isArray(u==null?void 0:u.agents)?u.agents:[]),d(null)}catch(u){if(!o.current)return;d(u.message)}finally{o.current&&a(!1)}},[]);return r.useEffect(()=>(o.current=!0,c(),()=>{o.current=!1}),[c]),r.useEffect(()=>{if(typeof window>"u"||typeof WebSocket>"u")return;let u=null,y=!1,m=null;function f(){if(!y){try{const g=window.location.protocol==="https:"?"wss:":"ws:";u=new WebSocket(`${g}//${window.location.host}/ws/vision`)}catch{p();return}u.onmessage=g=>{try{const N=JSON.parse(g.data);if(!N||!N.type)return;(N.type==="agentSpawned"||N.type==="agentStopped"||N.type==="agentStatusChanged"||N.type==="agentTreeUpdated")&&c()}catch{}},u.onclose=()=>{y||p()},u.onerror=()=>{try{u.close()}catch{}}}}function p(){m&&clearTimeout(m),m=setTimeout(f,3e3)}return f(),()=>{y=!0,m&&clearTimeout(m);try{u&&(u.onclose=null,u.close())}catch{}}},[c]),{agents:e,loading:s,error:i,refetch:c}}const de={};function re(e){if(typeof window>"u"||!window.location)return e;const n=typeof import.meta<"u"&&(de==null?void 0:de.VITE_AGENT_PORT)||"4002";return`${window.location.protocol}//${window.location.hostname}:${n}${e}`}const Qe=5e3;async function xe(e,n){const s=await fetch(re(e),{method:"POST",headers:V({"Content-Type":"application/json"}),body:JSON.stringify(n||{})});let a=null;try{a=await s.json()}catch{}if(!s.ok){const i=a&&a.error||`HTTP ${s.status}`;throw new Error(i)}return a}function Ze(){const[e,n]=r.useState(!1),[s,a]=r.useState(null),[i,d]=r.useState(!0),[o,c]=r.useState(null),[u,y]=r.useState(!1),m=r.useRef(!0),f=r.useCallback(async()=>{try{const C=await(await fetch(re("/api/agent/session/status"))).json().catch(()=>({}));if(!m.current)return;n(!!C.active),a(C.sessionId||null),c(null)}catch(N){if(!m.current)return;c(N.message)}finally{m.current&&d(!1)}},[]);r.useEffect(()=>{m.current=!0,f();const N=setInterval(f,Qe);return()=>{m.current=!1,clearInterval(N)}},[f]);const p=r.useCallback(async N=>{const C=(N||"").trim();if(!C)throw new Error("message is empty");y(!0);try{const E=await xe(s?"/api/agent/message":"/api/agent/session",{prompt:C});return f(),E}finally{y(!1)}},[s,f]),g=r.useCallback(async()=>xe("/api/agent/interrupt",{}),[]);return{active:e,sessionId:s,loading:i,error:o,sending:u,sendMessage:p,interrupt:g,refresh:f}}function et(e){if(!e)return"";const n=typeof e=="string"?Date.parse(e):Number(e);if(!n||Number.isNaN(n))return"";const s=Date.now()-n;return s<5e3?"just now":s<6e4?`${Math.floor(s/1e3)}s ago`:s<36e5?`${Math.floor(s/6e4)}m ago`:`${Math.floor(s/36e5)}h ago`}function tt({agent:e,onOpen:n,onAfterKill:s}){const[a,i]=r.useState(!1),[d,o]=r.useState(null),c=e.agentId||e.id,u=e.status||"unknown",y=e.lastActivityAt||e.lastEventAt||e.startedAt||null,m=r.useCallback(async p=>{if(p==null||p.stopPropagation(),!!c){i(!0),o(null);try{const g=await J(re(`/api/agent/${encodeURIComponent(c)}/stop`),{method:"POST",headers:V({"Content-Type":"application/json"}),body:JSON.stringify({})});if(!g.ok){let N=null;try{N=await g.json()}catch{}throw new Error(N&&N.error||`HTTP ${g.status}`)}s==null||s(c)}catch(g){o(g.message)}finally{i(!1)}}},[c,s]),f=r.useCallback(()=>n==null?void 0:n(e),[n,e]);return t.jsxs("div",{className:"m-agent-card","data-testid":`mobile-agent-card-${c}`,role:"button",tabIndex:0,onClick:f,onKeyDown:p=>{p.key==="Enter"&&f()},children:[t.jsxs("div",{className:"m-agent-card-row",children:[t.jsx("div",{className:"m-agent-card-id",title:c,children:c||"(no id)"}),t.jsx("span",{className:"m-status-pill","data-status":u,children:u})]}),t.jsxs("div",{className:"m-agent-card-meta",children:[t.jsx("span",{className:"m-agent-card-time",children:et(y)}),t.jsx("button",{type:"button",className:"m-btn m-btn-danger m-btn-sm","data-testid":`mobile-agent-kill-${c}`,disabled:a||u!=="running",onClick:m,children:a?"Killing…":"Kill"})]}),d&&t.jsx("div",{className:"m-agent-card-error",children:d})]})}const st=3e4,nt=5,at=3e4;function rt({url:e,onEvent:n,onOpen:s,onClose:a,onError:i,onRetry:d,onStall:o,onExhausted:c,namedEvents:u=["hydrate"],maxBackoffMs:y=st,maxRetries:m=nt,stallTimeoutMs:f=at}){if(!e)throw new Error("createAgentStream: url is required");if(typeof EventSource>"u")return{close(){}};let p=null,g=!1,N=0,C=null,v=null;function E(){v&&clearTimeout(v),!g&&(v=setTimeout(()=>{o==null||o({elapsedMs:f})},f))}function w(){v&&(clearTimeout(v),v=null)}function T(h,b){if(E(),!!n)try{const S=JSON.parse(b);n(S,h)}catch{}}function x(){if(w(),g||C)return;if(N>=m){const b=new Error(`agent-stream: failed after ${m} retries`);i==null||i(b),g=!0;try{p==null||p.close()}catch{}p=null,a==null||a(),c==null||c();return}const h=Math.min(y,1e3*Math.pow(2,N));N+=1,d==null||d({attempt:N,maxRetries:m,nextBackoffMs:h}),C=setTimeout(()=>{C=null,j()},h)}function j(){if(!g){try{p=new EventSource(e)}catch(h){i==null||i(h),x();return}p.onopen=()=>{N=0,w(),s==null||s()},p.onmessage=h=>T("message",h.data);for(const h of u)p.addEventListener(h,b=>T(h,b.data));p.onerror=h=>{i==null||i(h instanceof Error?h:new Error("agent-stream error"));try{p==null||p.close()}catch{}p=null,a==null||a(),x()}}}return j(),{close(){g=!0,w(),C&&(clearTimeout(C),C=null);try{p==null||p.close()}catch{}p=null},reconnect(){g=!1,N=0,w(),C&&(clearTimeout(C),C=null);try{p==null||p.close()}catch{}p=null,j()}}}function it(){return typeof window>"u"||!window.location?"":re("/api/agent/stream")}function lt(e){return!e||typeof e!="object"?null:e.agentId||e.agent_id||e.id||null}function Re({url:e,agentId:n,max:s=500,enabled:a=!0}={}){const[i,d]=r.useState([]),[o,c]=r.useState(!1),u=r.useRef(null),y=r.useMemo(()=>e||it(),[e]);return r.useEffect(()=>{if(!a||!y)return;const f=rt({url:y,onOpen:()=>c(!0),onClose:()=>c(!1),onEvent:p=>{d(g=>{const N=g.length>=s?g.slice(g.length-s+1):g.slice();return N.push(p),N})}});return u.current=f,()=>{try{f.close()}catch{}}},[y,a,s]),{events:r.useMemo(()=>n?i.filter(f=>lt(f)===n):i,[i,n]),allEvents:i,connected:o}}function ot(e,n){if(typeof e=="string")return e;if(e!=null&&e.type&&(e!=null&&e.message))return`[${e.type}] ${typeof e.message=="string"?e.message:JSON.stringify(e.message)}`;if(e!=null&&e.type)return`[${e.type}] ${JSON.stringify(e).slice(0,240)}`;try{return JSON.stringify(e)}catch{return`(unserializable #${n})`}}function ct({agent:e,onClose:n}){const s=(e==null?void 0:e.agentId)||(e==null?void 0:e.id),{events:a}=Re({agentId:s}),i=r.useRef(null),[d,o]=r.useState(!1),[c,u]=r.useState(null);r.useEffect(()=>{var m;(m=i.current)==null||m.scrollIntoView({behavior:"smooth"})},[a.length]);const y=r.useCallback(async()=>{if(s){o(!0),u(null);try{const m=await J(re(`/api/agent/${encodeURIComponent(s)}/stop`),{method:"POST",headers:V({"Content-Type":"application/json"}),body:JSON.stringify({})});if(!m.ok){let f=null;try{f=await m.json()}catch{}throw new Error(f&&f.error||`HTTP ${m.status}`)}}catch(m){u(m.message)}finally{o(!1)}}},[s]);return e?t.jsxs("div",{className:"m-overlay","data-testid":"mobile-agent-detail",role:"dialog","aria-modal":"true",children:[t.jsxs("header",{className:"m-overlay-header",children:[t.jsxs("div",{className:"m-overlay-header-inner",children:[t.jsx("div",{className:"m-overlay-title",title:s,children:s}),t.jsx("span",{className:"m-status-pill","data-status":e.status,children:e.status||"unknown"})]}),t.jsxs("div",{className:"m-overlay-actions",children:[t.jsx("button",{type:"button",className:"m-btn m-btn-danger m-btn-sm",disabled:d,onClick:y,"data-testid":"mobile-agent-detail-kill",children:d?"Killing…":"Kill"}),t.jsx("button",{type:"button",className:"m-btn m-btn-sm",onClick:n,"data-testid":"mobile-agent-detail-close",children:"Close"})]})]}),t.jsxs("div",{className:"m-overlay-body m-agent-log",children:[a.length===0?t.jsx("div",{className:"m-empty",children:"No live events for this agent yet."}):a.map((m,f)=>t.jsx("div",{className:"m-agent-log-line",children:ot(m,f)},f)),t.jsx("div",{ref:i})]}),c&&t.jsx("div",{className:"m-agent-card-error",children:c})]}):null}function ut({session:e}){const{active:n,sessionId:s,sending:a,sendMessage:i}=e,[d,o]=r.useState(""),[c,u]=r.useState(null),y=r.useCallback(async m=>{if(m==null||m.preventDefault(),!!d.trim()){u(null);try{await i(d),o("")}catch(f){u(f.message)}}},[d,i]);return t.jsxs("div",{className:"m-session-card","data-testid":"mobile-interactive-session",children:[t.jsxs("div",{className:"m-session-card-row",children:[t.jsx("div",{className:"m-session-card-title",children:"Interactive session"}),t.jsx("span",{className:"m-status-pill","data-status":n?"in_progress":"planned",children:n?"active":"ready"})]}),t.jsx("div",{className:"m-session-card-id",children:s?`id: ${s}`:"No active session"}),t.jsxs("form",{className:"m-session-card-form",onSubmit:y,children:[t.jsx("input",{type:"text",className:"m-input",placeholder:n?"Message Claude…":"Start a new session…",value:d,onChange:m=>o(m.target.value),"data-testid":"mobile-interactive-session-input",disabled:a}),t.jsx("button",{type:"submit",className:"m-btn m-btn-primary m-btn-sm",disabled:a||!d.trim(),"data-testid":"mobile-interactive-session-send",children:a?"Sending…":"Send"})]}),c&&t.jsx("div",{className:"m-agent-card-error",children:c})]})}function dt({gate:e,onOpen:n}){const s=e.id,a=e.flowId||e.flow||"",i=e.stepId||e.step||"",d=e.summary||e.comment||"",o=e.toPhase||e.fromPhase||"";return t.jsxs("div",{className:"m-gate-card","data-testid":`mobile-gate-card-${s}`,role:"button",tabIndex:0,onClick:()=>n==null?void 0:n(e),onKeyDown:c=>{c.key==="Enter"&&(n==null||n(e))},children:[t.jsxs("div",{className:"m-gate-card-row",children:[t.jsx("div",{className:"m-gate-card-title",children:a||s}),o&&t.jsx("span",{className:"m-status-pill","data-status":"in_progress",children:o})]}),t.jsx("div",{className:"m-gate-card-step",children:i}),d&&t.jsx("div",{className:"m-gate-card-summary",children:d})]})}const mt=[{id:"approve",label:"Approve",kind:"primary"},{id:"revise",label:"Revise",kind:"warn"},{id:"kill",label:"Kill",kind:"danger"}];function ft({gate:e,onResolve:n,onClose:s}){const[a,i]=r.useState(null),[d,o]=r.useState(""),[c,u]=r.useState(""),[y,m]=r.useState(!1),[f,p]=r.useState(null),g=r.useCallback(async N=>{if(N==null||N.preventDefault(),!a){p("Pick an outcome");return}if(a==="kill"&&!d.trim()){p("Reason is required when killing a gate");return}m(!0),p(null);try{await n(e.id,{outcome:a,reason:d.trim(),summary:c.trim()}),s==null||s()}catch(C){p(C.message)}finally{m(!1)}},[e,a,d,c,n,s]);return t.jsx("div",{className:"m-sheet-backdrop","data-testid":"mobile-gate-sheet",onClick:s,children:t.jsxs("div",{className:"m-sheet",role:"dialog","aria-modal":"true",onClick:N=>N.stopPropagation(),children:[t.jsxs("div",{className:"m-sheet-header",children:[t.jsx("div",{className:"m-sheet-title",children:"Resolve gate"}),t.jsxs("div",{className:"m-sheet-subtitle",children:[e.flowId,":",e.stepId]})]}),t.jsxs("form",{onSubmit:g,className:"m-sheet-body",children:[t.jsx("div",{className:"m-sheet-outcomes",role:"radiogroup","aria-label":"Outcome",children:mt.map(N=>t.jsx("button",{type:"button",role:"radio","aria-checked":a===N.id,className:`m-btn m-btn-${N.kind} ${a===N.id?"m-btn-active":""}`,"data-testid":`mobile-gate-outcome-${N.id}`,onClick:()=>i(N.id),children:N.label},N.id))}),t.jsxs("label",{className:"m-field",children:[t.jsxs("span",{className:"m-field-label",children:["Reason ",a==="kill"?"(required)":"(optional)"]}),t.jsx("textarea",{className:"m-textarea","data-testid":"mobile-gate-reason",value:d,onChange:N=>o(N.target.value),rows:2})]}),t.jsxs("label",{className:"m-field",children:[t.jsx("span",{className:"m-field-label",children:"Summary (optional)"}),t.jsx("textarea",{className:"m-textarea","data-testid":"mobile-gate-summary",value:c,onChange:N=>u(N.target.value),rows:2})]}),f&&t.jsx("div",{className:"m-agent-card-error",children:f}),t.jsxs("div",{className:"m-sheet-actions",children:[t.jsx("button",{type:"button",className:"m-btn m-btn-sm",onClick:s,disabled:y,children:"Cancel"}),t.jsx("button",{type:"submit",className:"m-btn m-btn-primary m-btn-sm",disabled:y||!a,"data-testid":"mobile-gate-submit",children:y?"Submitting…":"Submit"})]})]})]})})}function ht({gates:e=[],gatesLoading:n=!1,resolveGate:s}){const{agents:a,loading:i,refetch:d}=Ve(),o=Ze(),[c,u]=r.useState(null),[y,m]=r.useState(null),f=r.useCallback(()=>{d(),u(null)},[d]);return t.jsxs("section",{"data-testid":"mobile-tab-agents",className:"m-agents-tab",children:[t.jsxs("div",{className:"m-section","data-testid":"mobile-section-spawned",children:[t.jsx("h2",{className:"m-section-title",children:"Spawned agents"}),i?t.jsx("div",{className:"m-empty",children:"Loading agents…"}):a.length===0?t.jsx("div",{className:"m-empty",children:"No spawned agents."}):t.jsx("div",{className:"m-stack",children:a.map(p=>t.jsx(tt,{agent:p,onOpen:u,onAfterKill:f},p.agentId||p.id))})]}),t.jsxs("div",{className:"m-section","data-testid":"mobile-section-session",children:[t.jsx("h2",{className:"m-section-title",children:"Interactive session"}),t.jsx(ut,{session:o})]}),t.jsxs("div",{className:"m-section","data-testid":"mobile-section-gates",children:[t.jsx("h2",{className:"m-section-title",children:"Pending gates"}),n?t.jsx("div",{className:"m-empty",children:"Loading gates…"}):e.length===0?t.jsx("div",{className:"m-empty",children:"No pending gates."}):t.jsx("div",{className:"m-stack",children:e.map(p=>t.jsx(dt,{gate:p,onOpen:m},p.id))})]}),c&&t.jsx(ct,{agent:c,onClose:()=>u(null)}),y&&t.jsx(ft,{gate:y,onResolve:s,onClose:()=>m(null)})]})}const pt=[{value:"planned",label:"planned"},{value:"in_progress",label:"in progress"},{value:"blocked",label:"blocked"},{value:"complete",label:"complete"},{value:"parked",label:"parked"},{value:"killed",label:"killed"}];function bt({statuses:e=[],onToggleStatus:n,group:s="",groupOptions:a=[],onChangeGroup:i,keyword:d="",onChangeKeyword:o}){return t.jsxs("div",{className:"m-filter-bar","data-testid":"mobile-filter-bar",children:[t.jsx("div",{className:"m-filter-chips",role:"group","aria-label":"Status filter",children:pt.map(c=>{const u=e.includes(c.value);return t.jsx("button",{type:"button",className:"m-filter-chip","aria-pressed":u,"data-testid":`mobile-filter-status-${c.value}`,onClick:()=>n==null?void 0:n(c.value),children:c.label},c.value)})}),t.jsxs("div",{className:"m-filter-row",children:[t.jsxs("select",{className:"m-filter-select","data-testid":"mobile-filter-group",value:s,onChange:c=>i==null?void 0:i(c.target.value),"aria-label":"Group filter",children:[t.jsx("option",{value:"",children:"All groups"}),a.map(c=>t.jsx("option",{value:c,children:c},c))]}),t.jsx("input",{type:"search",className:"m-filter-keyword","data-testid":"mobile-filter-keyword",placeholder:"Search title or description",value:d,onChange:c=>o==null?void 0:o(c.target.value),"aria-label":"Keyword filter"})]})]})}const yt=new Set(["planned","in_progress","blocked","complete","partial","superseded","parked"]);function Ae({status:e,children:n}){const s=typeof e=="string"?e.toLowerCase():"",a=yt.has(s)?s:"unknown",i=n??e??"unknown";return t.jsx("span",{className:"m-status-pill","data-status":a,children:i})}function gt(e,n=140){if(typeof e!="string")return"";const s=e.trim();return s.length<=n?s:s.slice(0,n-1).trimEnd()+"…"}function xt({item:e,onSelect:n}){if(!e)return null;const s=e.title||e.id||"Untitled",a=e.status||"unknown",i=e.group||"",d=gt(e.description||"");return t.jsxs("button",{type:"button",className:"m-item-card","data-testid":`mobile-item-card-${e.id}`,onClick:()=>n==null?void 0:n(e),children:[t.jsxs("div",{className:"m-item-card-row",children:[t.jsx("div",{className:"m-item-card-title",children:s}),t.jsx(Ae,{status:a})]}),t.jsxs("div",{className:"m-item-card-meta",children:[i?t.jsx("span",{className:"m-item-card-group","data-testid":"mobile-item-group",children:i}):null,e.id?t.jsx("span",{className:"m-item-card-id",children:e.id}):null]}),d?t.jsx("div",{className:"m-item-card-desc",children:d}):null]})}const jt=["planned","ready","in_progress","review","complete","blocked","parked","killed","superseded"],Nt=["informs","blocks","supports","contradicts","implements"];function vt({item:e,onClose:n,onSave:s,onDelete:a,allItems:i=[],addConnection:d,removeConnection:o,fetchItemDetail:c}){const u=r.useMemo(()=>({status:(e==null?void 0:e.status)||"planned",group:(e==null?void 0:e.group)||"",confidence:(e==null?void 0:e.confidence)??""}),[e]),[y,m]=r.useState(u.status),[f,p]=r.useState(u.group),[g,N]=r.useState(u.confidence),[C,v]=r.useState(!1),[E,w]=r.useState(!1),[T,x]=r.useState(!1),j=r.useRef(null),[h,b]=r.useState([]),[S,A]=r.useState(!1),[D,I]=r.useState(!1),[O,L]=r.useState(""),[F,q]=r.useState("informs"),[Y,z]=r.useState(!1),[ee,Q]=r.useState(null),W=r.useRef(null);if(r.useEffect(()=>{m(u.status),p(u.group),N(u.confidence),w(!1),b([]),I(!1),L(""),q("informs"),Q(null),j.current&&clearTimeout(j.current),W.current&&clearTimeout(W.current)},[e==null?void 0:e.id,u.status,u.group,u.confidence]),r.useEffect(()=>{!(e!=null&&e.id)||!c||(A(!0),c(e.id).then(R=>{var H;R!=null&&R.ok&&Array.isArray((H=R.item)==null?void 0:H.connections)&&b(R.item.connections)}).finally(()=>A(!1)))},[e==null?void 0:e.id,c]),r.useEffect(()=>()=>{j.current&&clearTimeout(j.current),W.current&&clearTimeout(W.current)},[]),!e)return null;const l=y!==u.status||f!==u.group||String(g)!==String(u.confidence);function k(){w(!1),j.current&&clearTimeout(j.current)}function $(){E&&k(),ee!==null&&(Q(null),W.current&&clearTimeout(W.current))}const _=async()=>{if(!l||C)return;const R={};if(y!==u.status&&(R.status=y),f!==u.group&&(R.group=f),String(g)!==String(u.confidence)){const H=g===""?null:Number(g);H!==null&&Number.isFinite(H)?R.confidence=H:g===""&&(R.confidence=null)}v(!0);try{await(s==null?void 0:s(e.id,R))}finally{v(!1)}},M=async()=>{if(!E)w(!0),j.current=setTimeout(()=>{w(!1)},3e3);else{j.current&&clearTimeout(j.current),w(!1),x(!0);try{await(a==null?void 0:a(e.id))}finally{x(!1)}}},G=r.useMemo(()=>{const R=O.toLowerCase();return i.filter(H=>H.id===e.id?!1:R?H.id.toLowerCase().includes(R)||(H.title||"").toLowerCase().includes(R):!0)},[i,e==null?void 0:e.id,O]),U=async R=>{z(!0);const H=await(d==null?void 0:d({fromId:e.id,toId:R.id,type:F}));if(H!=null&&H.ok){const X=H.connection||{id:`local-${Date.now()}`,fromId:e.id,toId:R.id,type:F};b(te=>[...te,X]),I(!1),L(""),q("informs")}z(!1)},K=async(R,H)=>{if(ee!==H)W.current&&clearTimeout(W.current),Q(H),W.current=setTimeout(()=>{Q(null)},3e3);else{W.current&&clearTimeout(W.current),Q(null);const X=await(o==null?void 0:o(R.id));X!=null&&X.ok&&b(te=>te.filter(le=>le.id!==R.id))}};function B(R){const H=i.find(X=>X.id===R);return(H==null?void 0:H.title)||R}return t.jsx("div",{className:"m-sheet-overlay",role:"dialog","aria-modal":"true","data-testid":"mobile-item-sheet",children:t.jsxs("div",{className:"m-sheet",children:[t.jsxs("header",{className:"m-sheet-header",children:[t.jsx("button",{type:"button",className:"m-sheet-close",onClick:n,"data-testid":"mobile-item-sheet-close","aria-label":"Close",children:"×"}),t.jsxs("div",{className:"m-sheet-title-row",children:[t.jsx("div",{className:"m-sheet-title",children:e.title||e.id}),t.jsx(Ae,{status:y})]})]}),t.jsxs("div",{className:"m-sheet-body",children:[e.description?t.jsxs("section",{className:"m-sheet-section",children:[t.jsx("div",{className:"m-sheet-label",children:"Description"}),t.jsx("p",{className:"m-sheet-desc",children:e.description})]}):null,t.jsxs("section",{className:"m-sheet-section",children:[t.jsx("label",{className:"m-sheet-label",htmlFor:"m-sheet-status",children:"Status"}),t.jsx("select",{id:"m-sheet-status",className:"m-sheet-input","data-testid":"mobile-item-sheet-status",value:y,onChange:R=>{$(),m(R.target.value)},children:jt.map(R=>t.jsx("option",{value:R,children:R},R))})]}),t.jsxs("section",{className:"m-sheet-section",children:[t.jsx("label",{className:"m-sheet-label",htmlFor:"m-sheet-group",children:"Group"}),t.jsx("input",{id:"m-sheet-group",type:"text",className:"m-sheet-input","data-testid":"mobile-item-sheet-group",value:f,onChange:R=>{$(),p(R.target.value)}})]}),t.jsxs("section",{className:"m-sheet-section",children:[t.jsx("label",{className:"m-sheet-label",htmlFor:"m-sheet-confidence",children:"Confidence (0–4)"}),t.jsx("input",{id:"m-sheet-confidence",type:"number",min:"0",max:"4",step:"1",className:"m-sheet-input","data-testid":"mobile-item-sheet-confidence",value:g,onChange:R=>{$(),N(R.target.value)}})]}),t.jsxs("section",{className:"m-sheet-section m-sheet-connections",children:[t.jsxs("div",{className:"m-sheet-connections-header",children:[t.jsx("span",{className:"m-sheet-label",children:"Connections"}),!D&&t.jsx("button",{type:"button",className:"m-conn-add-btn","data-testid":"mobile-item-conn-add",onClick:()=>{$(),I(!0)},children:"+ Add"})]}),S?t.jsx("div",{className:"m-conn-loading",children:"Loading…"}):h.length===0&&!D?t.jsx("div",{className:"m-conn-empty",children:"No connections"}):t.jsx("ul",{className:"m-conn-list",children:h.map((R,H)=>{const X=R.fromId===e.id,te=X?R.toId:R.fromId,le=B(te),oe=ee===H;return t.jsxs("li",{className:"m-conn-row",children:[t.jsx("span",{className:"m-conn-dir",children:X?"→":"←"}),t.jsx("span",{className:"m-conn-title",children:le}),t.jsx("span",{className:"m-conn-type",children:R.type}),t.jsx("button",{type:"button",className:`m-conn-remove${oe?" m-conn-remove--armed":""}`,"data-testid":`mobile-item-conn-remove-${H}`,"aria-label":oe?"Confirm remove connection":"Remove connection",onClick:()=>{$(),K(R,H)},children:oe?"✓":"×"})]},R.id)})}),D&&t.jsxs("div",{className:"m-conn-picker",children:[t.jsxs("div",{className:"m-conn-picker-row",children:[t.jsx("input",{type:"text",className:"m-sheet-input m-conn-search",placeholder:"Search items…",value:O,onChange:R=>L(R.target.value),"data-testid":"mobile-item-conn-search",autoFocus:!0}),t.jsx("select",{className:"m-sheet-input m-conn-type-select",value:F,onChange:R=>q(R.target.value),"data-testid":"mobile-item-conn-type",children:Nt.map(R=>t.jsx("option",{value:R,children:R},R))})]}),t.jsxs("ul",{className:"m-conn-picker-list",children:[G.map(R=>t.jsx("li",{children:t.jsxs("button",{type:"button",className:"m-conn-picker-item",disabled:Y,onClick:()=>U(R),"data-testid":`mobile-item-conn-pick-${R.id}`,children:[t.jsx("span",{className:"m-conn-picker-title",children:R.title||R.id}),t.jsx("span",{className:"m-conn-picker-id",children:R.id})]})},R.id)),G.length===0&&t.jsx("li",{className:"m-conn-picker-empty",children:"No items found"})]}),t.jsx("button",{type:"button",className:"m-sheet-btn m-sheet-btn-secondary",onClick:()=>{I(!1),L(""),q("informs")},children:"Cancel"})]})]})]}),t.jsxs("footer",{className:"m-sheet-footer",children:[t.jsx("button",{type:"button",className:`m-sheet-btn m-sheet-btn-danger${E?" m-sheet-btn-danger--armed":""}`,onClick:M,disabled:T,"data-testid":"mobile-item-sheet-delete",children:T?"Deleting…":E?"Confirm delete":"Delete"}),t.jsxs("div",{className:"m-sheet-footer-right",children:[t.jsx("button",{type:"button",className:"m-sheet-btn m-sheet-btn-secondary",onClick:n,"data-testid":"mobile-item-sheet-cancel",children:"Cancel"}),t.jsx("button",{type:"button",className:"m-sheet-btn m-sheet-btn-primary",onClick:_,disabled:!l||C,"data-testid":"mobile-item-sheet-save",children:C?"Saving…":"Save"})]})]})]})})}const wt=["planned","ready","in_progress","review","complete","blocked","parked","killed","superseded"];function St({open:e,onClose:n,onCreate:s,groupOptions:a=[]}){const[i,d]=r.useState(""),[o,c]=r.useState(""),[u,y]=r.useState(""),[m,f]=r.useState("planned"),[p,g]=r.useState(""),[N,C]=r.useState(!1),[v,E]=r.useState(null),w=r.useId();if(!e)return null;function T(){d(""),c(""),y(""),f("planned"),g(""),E(null),C(!1)}function x(){T(),n==null||n()}async function j(h){if(h.preventDefault(),!i.trim()){E("Title is required");return}C(!0),E(null);try{const b={title:i.trim()};if(o.trim()&&(b.description=o.trim()),u.trim()&&(b.group=u.trim()),m&&(b.status=m),p!==""){const S=Number(p);Number.isFinite(S)&&(b.confidence=S)}await(s==null?void 0:s(b)),x()}catch(b){E(b.message||"Failed to create item"),C(!1)}}return t.jsx("div",{className:"m-sheet-overlay","data-testid":"mobile-create-sheet",role:"dialog","aria-modal":"true","aria-label":"Create roadmap item",onClick:h=>{h.target===h.currentTarget&&x()},children:t.jsxs("div",{className:"m-sheet",children:[t.jsxs("header",{className:"m-sheet-header",children:[t.jsx("button",{type:"button",className:"m-sheet-close","aria-label":"Close",onClick:x,disabled:N,children:"×"}),t.jsx("div",{className:"m-sheet-title-row",children:t.jsx("div",{className:"m-sheet-title",children:"New roadmap item"})})]}),t.jsxs("form",{className:"m-sheet-body",onSubmit:j,children:[t.jsxs("div",{className:"m-sheet-section",children:[t.jsx("label",{className:"m-sheet-label",htmlFor:"m-create-title",children:"Title"}),t.jsx("input",{id:"m-create-title",type:"text",className:"m-sheet-input",value:i,onChange:h=>d(h.target.value),placeholder:"Feature title","data-testid":"mobile-create-title",autoFocus:!0,required:!0})]}),t.jsxs("div",{className:"m-sheet-section",children:[t.jsx("label",{className:"m-sheet-label",htmlFor:"m-create-desc",children:"Description (optional)"}),t.jsx("textarea",{id:"m-create-desc",className:"m-sheet-input m-textarea",value:o,onChange:h=>c(h.target.value),rows:3,"data-testid":"mobile-create-desc"})]}),t.jsxs("div",{className:"m-sheet-section",children:[t.jsx("label",{className:"m-sheet-label",htmlFor:"m-create-group",children:"Group (optional)"}),t.jsx("input",{id:"m-create-group",type:"text",className:"m-sheet-input",value:u,onChange:h=>y(h.target.value),list:w,placeholder:"e.g. core, infra","data-testid":"mobile-create-group"}),t.jsx("datalist",{id:w,children:a.map(h=>t.jsx("option",{value:h},h))})]}),t.jsxs("div",{className:"m-sheet-section",children:[t.jsx("label",{className:"m-sheet-label",htmlFor:"m-create-status",children:"Status"}),t.jsx("select",{id:"m-create-status",className:"m-sheet-input",value:m,onChange:h=>f(h.target.value),"data-testid":"mobile-create-status",children:wt.map(h=>t.jsx("option",{value:h,children:h},h))})]}),t.jsxs("div",{className:"m-sheet-section",children:[t.jsx("label",{className:"m-sheet-label",htmlFor:"m-create-confidence",children:"Confidence (0–4, optional)"}),t.jsx("input",{id:"m-create-confidence",type:"number",min:"0",max:"4",step:"1",className:"m-sheet-input",value:p,onChange:h=>g(h.target.value),"data-testid":"mobile-create-confidence"})]}),v?t.jsx("div",{className:"m-form-error",role:"alert","data-testid":"mobile-create-error",children:v}):null]}),t.jsxs("footer",{className:"m-sheet-footer",children:[t.jsx("button",{type:"button",className:"m-sheet-btn m-sheet-btn-secondary",onClick:x,disabled:N,"data-testid":"mobile-create-cancel",children:"Cancel"}),t.jsx("div",{className:"m-sheet-footer-right",children:t.jsx("button",{type:"button",className:"m-sheet-btn m-sheet-btn-primary",disabled:N||!i.trim(),"data-testid":"mobile-create-submit",onClick:j,children:N?"Creating…":"Create"})})]})]})})}function $e({message:e,kind:n="error",durationMs:s=3e3,onDismiss:a}){return r.useEffect(()=>{if(!e)return;const i=setTimeout(()=>a==null?void 0:a(),s);return()=>clearTimeout(i)},[e,s,a]),e?t.jsx("div",{className:"m-toast",role:"status","data-kind":n,"data-testid":"mobile-toast",children:e}):null}function kt(e){const n=new Set;for(const s of e){const a=((s==null?void 0:s.group)||"").trim();a&&n.add(a)}return Array.from(n).sort()}function Ct(e,n){if(!n)return!0;const s=n.toLowerCase(),a=(e.title||"").toLowerCase(),i=(e.description||"").toLowerCase();return a.includes(s)||i.includes(s)}function Tt({items:e=[],loading:n=!1,error:s=null,applyOptimisticEdit:a,createItem:i,deleteItem:d,addConnection:o,removeConnection:c,fetchItemDetail:u}){const[y,m]=r.useState([]),[f,p]=r.useState(""),[g,N]=r.useState(""),[C,v]=r.useState(null),[E,w]=r.useState(!1),[T,x]=r.useState(null),j=r.useMemo(()=>kt(e),[e]),h=r.useMemo(()=>e.filter(O=>!(y.length&&!y.includes(O.status)||f&&O.group!==f||!Ct(O,g))),[e,y,f,g]),b=r.useMemo(()=>e.find(O=>O.id===C)||null,[e,C]),S=O=>{m(L=>L.includes(O)?L.filter(F=>F!==O):[...L,O])},A=async(O,L)=>{const F=await a(O,L);F!=null&&F.ok?v(null):x((F==null?void 0:F.error)||"Save failed")},D=async O=>{const L=await(i==null?void 0:i(O));if(!(L!=null&&L.ok))throw new Error((L==null?void 0:L.error)||"Create failed")},I=async O=>{const L=await(d==null?void 0:d(O));L!=null&&L.ok?v(null):x((L==null?void 0:L.error)||"Delete failed")};return t.jsxs("section",{className:"m-roadmap","data-testid":"mobile-tab-roadmap",children:[t.jsx(bt,{statuses:y,onToggleStatus:S,group:f,groupOptions:j,onChangeGroup:p,keyword:g,onChangeKeyword:N}),s?t.jsx("div",{className:"m-roadmap-error","data-testid":"mobile-roadmap-error",children:s}):null,n?t.jsx("div",{className:"m-roadmap-skeleton","data-testid":"mobile-roadmap-loading",children:Array.from({length:4}).map((O,L)=>t.jsx("div",{className:"m-skel-card"},L))}):h.length===0?t.jsx("div",{className:"m-roadmap-empty","data-testid":"mobile-roadmap-empty",children:e.length===0?"No roadmap items yet.":"No items match the current filters."}):t.jsx("ul",{className:"m-roadmap-list","data-testid":"mobile-roadmap-list",children:h.map(O=>t.jsx("li",{children:t.jsx(xt,{item:O,onSelect:L=>v(L.id)})},O.id))}),b?t.jsx(vt,{item:b,onClose:()=>v(null),onSave:A,onDelete:I,allItems:e,addConnection:o,removeConnection:c,fetchItemDetail:u}):null,t.jsx(St,{open:E,onClose:()=>w(!1),onCreate:D,groupOptions:j}),t.jsx("button",{type:"button",className:"m-fab","data-testid":"mobile-roadmap-fab","aria-label":"Create new roadmap item",onClick:()=>w(!0),children:"+"}),t.jsx($e,{message:T,onDismiss:()=>x(null)})]})}const Z="—";async function ne(e,n={}){const s=await J(e,n);let a=null;try{a=await s.json()}catch{}if(!s.ok){const i=a&&a.error||`HTTP ${s.status}`;throw new Error(i)}return a}function Et(){const[e,n]=r.useState([]),[s,a]=r.useState([]),[i,d]=r.useState(!0),[o,c]=r.useState(null),[u,y]=r.useState([]),m=r.useRef(e);m.current=e;const f=r.useCallback((w,T)=>{const x=`t_${Date.now()}_${Math.random().toString(36).slice(2,6)}`;y(j=>[...j,{id:x,kind:w,message:T}]),setTimeout(()=>{y(j=>j.filter(h=>h.id!==x))},3500)},[]),p=r.useCallback(w=>{y(T=>T.filter(x=>x.id!==w))},[]),g=r.useCallback(async()=>{try{const w=await ne("/api/ideabox");n(Array.isArray(w==null?void 0:w.ideas)?w.ideas:[]),a(Array.isArray(w==null?void 0:w.killed)?w.killed:[]),c(null)}catch(w){c(w.message),f("error",`Failed to load ideas: ${w.message}`)}finally{d(!1)}},[f]);r.useEffect(()=>{let w=!0;return(async()=>w&&await g())(),()=>{w=!1}},[g]),r.useEffect(()=>{if(typeof window>"u"||typeof WebSocket>"u")return;let w=null,T=!1,x=null;function j(){if(!T){try{const b=window.location.protocol==="https:"?"wss:":"ws:";w=new WebSocket(`${b}//${window.location.host}/ws/vision`)}catch{h();return}w.onmessage=b=>{try{const S=JSON.parse(b.data);S&&S.type==="ideaboxUpdated"&&g()}catch{}},w.onclose=()=>{T||h()},w.onerror=()=>{try{w.close()}catch{}}}}function h(){x&&clearTimeout(x),x=setTimeout(j,3e3)}return j(),()=>{T=!0,x&&clearTimeout(x);try{w&&(w.onclose=null,w.close())}catch{}}},[g]);const N=r.useCallback(async({title:w,description:T,source:x,tags:j,cluster:h})=>{if(!w||!w.trim()){const A=new Error("title is required");throw f("error",A.message),A}const b=`tmp_${Date.now()}`,S={id:b,num:0,title:w.trim(),description:T||"",source:x||"",tags:Array.isArray(j)?j:[],cluster:h||null,status:"NEW",priority:Z,_pending:!0};n(A=>[S,...A]);try{const A=await ne("/api/ideabox/ideas",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:w.trim(),description:T,source:x,tags:j,cluster:h})});return n(D=>D.map(I=>I.id===b?{...A}:I)),f("ok","Idea captured"),A}catch(A){throw n(D=>D.filter(I=>I.id!==b)),f("error",`Capture failed: ${A.message}`),A}},[f]),C=r.useCallback(async(w,{featureCode:T}={})=>{const x=m.current;n(j=>j.map(h=>h.id===w?{...h,_promoting:!0}:h));try{const j=await ne(`/api/ideabox/ideas/${encodeURIComponent(w)}/promote`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({featureCode:T||""})});return f("ok",`Promoted${j!=null&&j.featureCode?` → ${j.featureCode}`:""}`),g(),j}catch(j){throw n(x),f("error",`Promote failed: ${j.message}`),j}},[f,g]),v=r.useCallback(async(w,{reason:T}={})=>{const x=m.current,j=x.find(h=>h.id===w);n(h=>h.filter(b=>b.id!==w)),j&&a(h=>[{...j,status:"KILLED",reason:T||""},...h]);try{const h=await ne(`/api/ideabox/ideas/${encodeURIComponent(w)}/kill`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:T||""})});return f("ok","Idea killed"),g(),h}catch(h){throw n(x),a(b=>b.filter(S=>S.id!==w||S.status!=="KILLED")),f("error",`Kill failed: ${h.message}`),h}},[f,g]),E=r.useCallback(async(w,T)=>{if(!["P0","P1","P2",Z].includes(T)){const h=new Error(`Invalid priority: ${T}`);throw f("error",h.message),h}const j=m.current;n(h=>h.map(b=>b.id===w?{...b,priority:T}:b));try{const h=await ne(`/api/ideabox/ideas/${encodeURIComponent(w)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({priority:T})});return f("ok",`Priority → ${T===Z?"Untriaged":T}`),h}catch(h){throw n(j),f("error",`Set priority failed: ${h.message}`),h}},[f]);return{ideas:e,killed:s,loading:i,error:o,toasts:u,dismissToast:p,refetch:g,createIdea:N,promote:C,kill:v,setPriority:E}}function Rt(e,n={}){const{onSwipeLeft:s,onSwipeRight:a,onDrag:i,onDragEnd:d,threshold:o=80,axis:c="x"}=n,u=r.useRef({onSwipeLeft:s,onSwipeRight:a,onDrag:i,onDragEnd:d});u.current={onSwipeLeft:s,onSwipeRight:a,onDrag:i,onDragEnd:d},r.useEffect(()=>{const y=e&&e.current;if(!y)return;let m=0,f=0,p=null,g=!1,N=0;function C(w){if(!(w.button!==void 0&&w.button!==0)){p=w.pointerId,m=w.clientX,f=w.clientY,g=!0,N=0;try{y.setPointerCapture(w.pointerId)}catch{}}}function v(w){var j,h,b,S;if(!g||w.pointerId!==p)return;const T=w.clientX-m,x=w.clientY-f;if(c==="x"&&Math.abs(x)>Math.abs(T)&&Math.abs(x)>12){g=!1,(h=(j=u.current).onDragEnd)==null||h.call(j,0,!1);return}N=T,(S=(b=u.current).onDrag)==null||S.call(b,T)}function E(w){var j,h,b,S,A,D;if(!g||w&&w.pointerId!==p)return;const T=N;g=!1;try{y.releasePointerCapture(p)}catch{}p=null;let x=!1;T<=-o?((h=(j=u.current).onSwipeLeft)==null||h.call(j),x=!0):T>=o&&((S=(b=u.current).onSwipeRight)==null||S.call(b),x=!0),(D=(A=u.current).onDragEnd)==null||D.call(A,T,x)}return y.addEventListener("pointerdown",C),y.addEventListener("pointermove",v),y.addEventListener("pointerup",E),y.addEventListener("pointercancel",E),()=>{y.removeEventListener("pointerdown",C),y.removeEventListener("pointermove",v),y.removeEventListener("pointerup",E),y.removeEventListener("pointercancel",E)}},[e,o,c])}function At(e){return e==="P0"||e==="P1"||e==="P2"?e.toLowerCase():"untriaged"}function $t(e){return e==="P0"||e==="P1"||e==="P2"?e:"Untriaged"}function _t({idea:e,onTap:n,onSwipeLeft:s,onSwipeRight:a}){const i=r.useRef(null),[d,o]=r.useState(0),[c,u]=r.useState(null),y=r.useCallback(g=>{o(g),g<=-40?u("kill"):g>=40?u("promote"):u(null)},[]),m=r.useCallback(()=>{o(0),u(null)},[]);Rt(i,{onSwipeLeft:()=>s==null?void 0:s(e),onSwipeRight:()=>a==null?void 0:a(e),onDrag:y,onDragEnd:m,threshold:80});const f=At(e.priority),p=Array.isArray(e.tags)?e.tags:[];return t.jsxs("div",{className:"m-idea-row","data-testid":`idea-row-${e.id}`,children:[t.jsx("div",{className:"m-idea-action m-idea-action-left","aria-hidden":"true",children:"Promote"}),t.jsx("div",{className:"m-idea-action m-idea-action-right","aria-hidden":"true",children:"Kill"}),t.jsxs("article",{ref:i,className:`m-idea-card${c?` is-intent-${c}`:""}`,"data-testid":"idea-card","data-idea-id":e.id,"data-priority":f,style:{transform:`translateX(${d}px)`},role:"button",tabIndex:0,onClick:()=>{Math.abs(d)<4&&(n==null||n(e))},onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),n==null||n(e))},children:[t.jsxs("div",{className:"m-idea-head",children:[t.jsx("span",{className:"m-priority-badge","data-priority":f,"data-testid":`priority-badge-${e.id}`,children:$t(e.priority)}),e.cluster?t.jsx("span",{className:"m-idea-cluster",title:e.cluster,children:e.cluster}):null]}),t.jsx("h3",{className:"m-idea-title","data-testid":`idea-title-${e.id}`,children:e.title}),p.length>0?t.jsx("div",{className:"m-idea-tags",children:p.map(g=>t.jsx("span",{className:"m-idea-tag",children:g},g))}):null]})]})}function It({open:e,onClose:n,onSubmit:s,existingClusters:a=[]}){const[i,d]=r.useState(""),[o,c]=r.useState(""),[u,y]=r.useState(""),[m,f]=r.useState([]),[p,g]=r.useState(""),[N,C]=r.useState(!1),[v,E]=r.useState(null),w=r.useId(),T=r.useMemo(()=>{const S=new Set;for(const A of a)A&&typeof A=="string"&&S.add(A);return[...S].sort()},[a]);if(!e)return null;function x(){d(""),c(""),y(""),f([]),g(""),E(null),C(!1)}function j(){x(),n==null||n()}function h(){const S=u.trim();S&&(m.includes(S)||f([...m,S]),y(""))}async function b(S){if(S.preventDefault(),!i.trim()){E("Title is required");return}C(!0),E(null);try{await(s==null?void 0:s({title:i.trim(),description:o.trim()||void 0,tags:m.length?m:void 0,cluster:p.trim()||void 0})),j()}catch(A){E(A.message||"Failed to capture"),C(!1)}}return t.jsx("div",{className:"m-sheet-overlay","data-testid":"capture-sheet",role:"dialog","aria-modal":"true","aria-label":"Capture idea",onClick:S=>{S.target===S.currentTarget&&j()},children:t.jsxs("div",{className:"m-sheet",children:[t.jsxs("header",{className:"m-sheet-header",children:[t.jsx("button",{type:"button",className:"m-sheet-close","aria-label":"Close capture",onClick:j,disabled:N,children:"×"}),t.jsx("div",{className:"m-sheet-title-row",children:t.jsx("div",{className:"m-sheet-title",children:"Capture idea"})})]}),t.jsxs("form",{className:"m-sheet-body",onSubmit:b,children:[t.jsxs("div",{className:"m-sheet-section",children:[t.jsx("label",{className:"m-sheet-label",htmlFor:"m-capture-title",children:"Title"}),t.jsx("input",{id:"m-capture-title",type:"text",className:"m-sheet-input",value:i,onChange:S=>d(S.target.value),placeholder:"What's the idea?","data-testid":"capture-title",autoFocus:!0,required:!0})]}),t.jsxs("div",{className:"m-sheet-section",children:[t.jsx("label",{className:"m-sheet-label",htmlFor:"m-capture-desc",children:"Description (optional)"}),t.jsx("textarea",{id:"m-capture-desc",className:"m-sheet-input m-textarea",value:o,onChange:S=>c(S.target.value),rows:4,"data-testid":"capture-description"})]}),t.jsxs("div",{className:"m-sheet-section",children:[t.jsx("label",{className:"m-sheet-label",htmlFor:"m-capture-tag",children:"Tags (optional)"}),t.jsxs("div",{className:"m-tag-input-row",children:[t.jsx("input",{id:"m-capture-tag",type:"text",className:"m-sheet-input",value:u,onChange:S=>y(S.target.value),onKeyDown:S=>{(S.key==="Enter"||S.key===",")&&(S.preventDefault(),h())},placeholder:"Add tag and press Enter","data-testid":"capture-tag-input"}),t.jsx("button",{type:"button",className:"m-sheet-btn m-sheet-btn-secondary m-tag-add",onClick:h,children:"Add"})]}),m.length>0?t.jsx("div",{className:"m-idea-tags","data-testid":"capture-tags",children:m.map(S=>t.jsxs("span",{className:"m-idea-tag",children:[S,t.jsx("button",{type:"button",className:"m-tag-remove","aria-label":`Remove tag ${S}`,onClick:()=>f(m.filter(A=>A!==S)),children:"×"})]},S))}):null]}),t.jsxs("div",{className:"m-sheet-section",children:[t.jsx("label",{className:"m-sheet-label",htmlFor:"m-capture-cluster",children:"Cluster (optional)"}),t.jsx("input",{id:"m-capture-cluster",type:"text",className:"m-sheet-input",value:p,onChange:S=>g(S.target.value),list:w,placeholder:"Group into a theme","data-testid":"capture-cluster"}),t.jsx("datalist",{id:w,children:T.map(S=>t.jsx("option",{value:S},S))})]}),v?t.jsx("div",{className:"m-form-error",role:"alert",children:v}):null]}),t.jsxs("footer",{className:"m-sheet-footer",children:[t.jsx("button",{type:"button",className:"m-sheet-btn m-sheet-btn-secondary",onClick:j,disabled:N,"data-testid":"capture-cancel",children:"Cancel"}),t.jsx("button",{type:"button",className:"m-sheet-btn m-sheet-btn-primary",disabled:N||!i.trim(),"data-testid":"capture-submit",onClick:b,children:N?"Saving…":"Capture"})]})]})})}const Pt=[{value:"P0",label:"P0"},{value:"P1",label:"P1"},{value:"P2",label:"P2"},{value:Z,label:"Untriaged"}];function Lt({value:e,onChange:n,disabled:s=!1}){return t.jsx("div",{className:"m-priority-selector",role:"radiogroup","aria-label":"Priority",children:Pt.map(a=>{const i=e===a.value,d=`m-priority-chip${i?" is-selected":""}`;return t.jsx("button",{type:"button",role:"radio","aria-checked":i?"true":"false",className:d,"data-priority":a.value===Z?"untriaged":a.value.toLowerCase(),"data-testid":`priority-chip-${a.value===Z?"untriaged":a.value.toLowerCase()}`,disabled:s,onClick:()=>n(a.value),children:a.label},a.value)})})}function Ot({idea:e,open:n,onClose:s,onPromote:a,onKill:i,onSetPriority:d}){const[o,c]=r.useState(!1);if(!n||!e)return null;const u=Array.isArray(e.tags)?e.tags:[],y=e.priority||Z;async function m(f,p=!0){c(!0);try{await f(),p&&(s==null||s())}catch{}finally{c(!1)}}return t.jsx("div",{className:"m-sheet-overlay","data-testid":"idea-detail-sheet",role:"dialog","aria-modal":"true","aria-label":`Idea ${e.id}`,onClick:f=>{f.target===f.currentTarget&&(s==null||s())},children:t.jsxs("div",{className:"m-sheet",children:[t.jsxs("header",{className:"m-sheet-header",children:[t.jsx("button",{type:"button",className:"m-sheet-close","aria-label":"Close detail",onClick:s,disabled:o,children:"×"}),t.jsx("div",{className:"m-sheet-title-row",children:t.jsx("div",{className:"m-sheet-title",children:e.title})}),t.jsxs("div",{className:"m-detail-meta",children:[t.jsx("span",{className:"m-detail-meta-id",children:e.id}),t.jsx("span",{className:"m-detail-meta-status",children:e.status||"NEW"}),e.cluster?t.jsx("span",{className:"m-detail-meta-cluster",children:e.cluster}):null]})]}),t.jsxs("div",{className:"m-sheet-body",children:[e.description?t.jsxs("div",{className:"m-sheet-section",children:[t.jsx("div",{className:"m-sheet-label",children:"Description"}),t.jsx("p",{className:"m-sheet-desc",children:e.description})]}):null,e.source?t.jsxs("div",{className:"m-sheet-section",children:[t.jsx("div",{className:"m-sheet-label",children:"Source"}),t.jsx("p",{className:"m-sheet-desc",children:e.source})]}):null,u.length>0?t.jsxs("div",{className:"m-sheet-section",children:[t.jsx("div",{className:"m-sheet-label",children:"Tags"}),t.jsx("div",{className:"m-idea-tags",children:u.map(f=>t.jsx("span",{className:"m-idea-tag",children:f},f))})]}):null,t.jsxs("div",{className:"m-sheet-section",children:[t.jsx("div",{className:"m-sheet-label",children:"Priority"}),t.jsx(Lt,{value:y,disabled:o,onChange:f=>m(()=>d==null?void 0:d(e.id,f),!1)})]})]}),t.jsxs("footer",{className:"m-sheet-footer",children:[t.jsx("button",{type:"button",className:"m-sheet-btn m-sheet-btn-secondary","data-testid":"detail-kill",disabled:o,onClick:()=>m(()=>i==null?void 0:i(e.id)),children:"Kill"}),t.jsx("button",{type:"button",className:"m-sheet-btn m-sheet-btn-primary","data-testid":"detail-promote",disabled:o,onClick:()=>m(()=>a==null?void 0:a(e.id)),children:"Promote"})]})]})})}const Dt=[{id:"all",label:"All"},{id:"P0",label:"P0"},{id:"P1",label:"P1"},{id:"P2",label:"P2"},{id:"untriaged",label:"Untriaged"}],je={P0:3,P1:2,P2:1};function Mt(e){return[...e].sort((n,s)=>{const a=je[n.priority]||0,i=je[s.priority]||0;if(a!==i)return i-a;const d=typeof n.num=="number"?n.num:0;return(typeof s.num=="number"?s.num:0)-d})}function Gt(){const{ideas:e,loading:n,toasts:s,dismissToast:a,createIdea:i,promote:d,kill:o,setPriority:c}=Et(),[u,y]=r.useState("all"),[m,f]=r.useState(!1),[p,g]=r.useState(null),N=r.useMemo(()=>{let v=e;return u==="untriaged"?v=v.filter(E=>!E.priority||E.priority===Z||E.priority===""):u!=="all"&&(v=v.filter(E=>E.priority===u)),Mt(v)},[e,u]),C=r.useMemo(()=>{const v=new Set;for(const E of e)E.cluster&&v.add(E.cluster);return[...v]},[e]);return t.jsxs("section",{className:"m-ideas-tab","data-testid":"mobile-tab-ideas",children:[t.jsxs("div",{className:"m-ideas-toolbar",children:[t.jsx("button",{type:"button",className:"m-sheet-btn m-sheet-btn-primary m-capture-btn",onClick:()=>f(!0),"data-testid":"open-capture","aria-label":"Capture new idea",children:"+ Capture"}),t.jsx("div",{className:"m-filter-chips",role:"tablist","aria-label":"Priority filter",children:Dt.map(v=>t.jsx("button",{type:"button",role:"tab","aria-pressed":u===v.id?"true":"false","aria-selected":u===v.id?"true":"false",className:"m-filter-chip",onClick:()=>y(v.id),"data-testid":`filter-${v.id}`,children:v.label},v.id))})]}),n?t.jsx("div",{className:"m-ideas-list","data-testid":"ideas-loading",children:[0,1,2].map(v=>t.jsx("div",{className:"m-idea-skeleton","aria-hidden":"true"},v))}):N.length===0?t.jsxs("div",{className:"m-empty-state","data-testid":"ideas-empty",children:[t.jsx("div",{className:"m-empty-title",children:e.length===0?"No ideas yet":"Nothing matches this filter"}),t.jsx("div",{className:"m-empty-body",children:e.length===0?"Tap Capture to add your first idea.":"Try All to see everything."})]}):t.jsx("div",{className:"m-ideas-list","data-testid":"ideas-list",children:N.map(v=>t.jsx(_t,{idea:v,onTap:E=>g(E),onSwipeLeft:E=>o(E.id),onSwipeRight:E=>d(E.id)},v.id))}),t.jsx(It,{open:m,onClose:()=>f(!1),onSubmit:i,existingClusters:C}),t.jsx(Ot,{idea:p,open:!!p,onClose:()=>g(null),onPromote:v=>d(v),onKill:v=>o(v),onSetPriority:(v,E)=>c(v,E)}),t.jsx("div",{className:"m-toast-stack","aria-live":"polite","data-testid":"toasts",children:s.map(v=>t.jsx("div",{className:"m-toast","data-kind":v.kind==="error"?"error":"ok",role:v.kind==="error"?"alert":"status",onClick:()=>a(v.id),children:v.message},v.id))})]})}function Ft(e){if(!e)return"";const n=typeof e=="string"?Date.parse(e):Number(e);if(!n||Number.isNaN(n))return"";const s=Date.now()-n;return s<5e3?"just now":s<6e4?`${Math.floor(s/1e3)}s ago`:s<36e5?`${Math.floor(s/6e4)}m ago`:`${Math.floor(s/36e5)}h ago`}function Ut(e,n=3){return e?Array.isArray(e.logTail)?e.logTail.slice(-n):Array.isArray(e.recentLogs)?e.recentLogs.slice(-n):Array.isArray(e.steps)?e.steps.slice(-n).map(s=>`${s.id||s.name||""}: ${s.status||""}`.trim()):[]:[]}function Ht({active:e,onOpen:n,onAbort:s,aborting:a}){const[i,d]=r.useState(null),o=(e==null?void 0:e.featureCode)||"(unknown)",c=(e==null?void 0:e.mode)||"feature",u=(e==null?void 0:e.status)||"unknown",y=(e==null?void 0:e.startedAt)||(e==null?void 0:e.started_at)||null,m=Ut(e),f=r.useCallback(async g=>{if(g==null||g.stopPropagation(),!!(e!=null&&e.featureCode)){d(null);try{await(s==null?void 0:s({featureCode:e.featureCode}))}catch(N){d(N.message||"Failed to abort")}}},[e,s]),p=r.useCallback(()=>n==null?void 0:n(e),[n,e]);return t.jsxs("div",{className:"m-build-card","data-testid":"mobile-build-card","data-feature":o,role:"button",tabIndex:0,onClick:p,onKeyDown:g=>{g.key==="Enter"&&p()},children:[t.jsxs("div",{className:"m-build-card-row",children:[t.jsx("div",{className:"m-build-card-feature",title:o,children:o}),t.jsx("span",{className:"m-status-pill","data-status":u,children:u})]}),t.jsxs("div",{className:"m-build-card-meta",children:[t.jsx("span",{className:"m-build-card-mode","data-mode":c,children:c}),t.jsx("span",{className:"m-build-card-time",children:Ft(y)})]}),m.length>0&&t.jsx("div",{className:"m-build-card-tail",children:m.map((g,N)=>t.jsx("div",{className:"m-build-card-tail-line",children:String(g).slice(0,200)},N))}),t.jsx("div",{className:"m-build-card-actions",children:t.jsx("button",{type:"button",className:"m-btn m-btn-danger m-btn-sm","data-testid":"mobile-build-abort",disabled:a||ae(u),onClick:f,children:a?"Aborting…":"Abort"})}),i&&t.jsx("div",{className:"m-agent-card-error",children:i})]})}const Bt={design:"Design",blueprint:"Blueprint",implementation:"Implementation",ship:"Ship"},Jt=["design","blueprint","implementation","ship"];function qt(e){return e==="active"?"◉":e==="done"||e==="complete"||e==="completed"?"●":e==="failed"||e==="error"?"✕":"○"}function Ne(e){return e==="done"||e==="complete"||e==="completed"}function Yt(e){return e==="failed"||e==="error"}function Wt(e){return e||null}function Kt(e){const n=[];let s=0;for(;s<e.length;){const a=e[s];if(!Ne(a.status)){n.push({type:"step",step:a}),s++;continue}let i=s;for(;i<e.length&&Ne(e[i].status);)i++;const d=i-s;if(d>=3)n.push({type:"collapsed",steps:e.slice(s,i),count:d});else for(let o=s;o<i;o++)n.push({type:"step",step:e[o]});s=i}return n}function _e({step:e}){const n=qt(e.status),s=Yt(e.status),a=e.status==="active";return t.jsxs("div",{className:["m-step-row",a?"m-step-row--active":"",s?"m-step-row--failed":""].filter(Boolean).join(" "),"data-testid":`mobile-build-step-${e.id}`,"data-status":e.status||"pending",children:[t.jsx("span",{className:`m-step-glyph${a?" m-step-glyph--pulse":""}`,"aria-hidden":"true",children:n}),t.jsx("span",{className:"m-step-name",children:e.name||e.id}),Wt(e.agent)&&t.jsx("span",{className:"m-step-agent-chip",children:e.agent}),s&&e.summary&&t.jsx("div",{className:"m-step-summary",children:e.summary})]})}function zt({segment:e,expandedKey:n,onToggle:s}){const a=n===e.steps[0].id;return t.jsx("div",{className:"m-step-collapsed-row","data-testid":"mobile-build-steps-collapsed",role:"button",tabIndex:0,"aria-expanded":a,onClick:()=>s(e.steps[0].id),onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&s(e.steps[0].id)},children:a?e.steps.map(i=>t.jsx(_e,{step:i},i.id)):t.jsxs("span",{className:"m-step-collapsed-label",children:[e.count," done ✓"]})})}function Xt({active:e}){const[n,s]=r.useState(null),a=Ye(Je,(e==null?void 0:e.steps)??null,(e==null?void 0:e.currentStepId)??null),i={};for(const c of a){const u=c.phase||"implementation";i[u]||(i[u]=[]),i[u].push(c)}const d=Jt.filter(c=>{var u;return((u=i[c])==null?void 0:u.length)>0});function o(c){s(u=>u===c?null:c)}return t.jsx("div",{className:"m-build-steps-list","data-testid":"mobile-build-steps",children:d.map(c=>{const u=i[c],y=Kt(u);return t.jsxs("div",{className:"m-build-steps-phase",children:[t.jsx("div",{className:"m-build-steps-phase-header",children:Bt[c]||c}),t.jsx("div",{className:"m-build-steps-phase-rows",children:y.map((m,f)=>m.type==="collapsed"?t.jsx(zt,{segment:m,expandedKey:n,onToggle:o},`collapsed-${f}`):t.jsx(_e,{step:m.step},m.step.id))})]},c)})})}function Vt(e,n){if(typeof e=="string")return e;if(e!=null&&e.type&&(e!=null&&e.message))return`[${e.type}] ${typeof e.message=="string"?e.message:JSON.stringify(e.message)}`;if(e!=null&&e.type)return`[${e.type}] ${JSON.stringify(e).slice(0,240)}`;try{return JSON.stringify(e)}catch{return`(unserializable #${n})`}}function Qt({active:e,onClose:n,onAbort:s}){const a=e==null?void 0:e.featureCode,{events:i}=Re({agentId:(e==null?void 0:e.flowId)||null}),d=r.useRef(null),[o,c]=r.useState(!1),[u,y]=r.useState(null),[m,f]=r.useState("steps");r.useEffect(()=>{var C;(C=d.current)==null||C.scrollIntoView({behavior:"smooth"})},[i.length]);const p=r.useCallback(async()=>{if(a){c(!0),y(null);try{await(s==null?void 0:s({featureCode:a}))}catch(C){y(C.message||"Failed to abort")}finally{c(!1)}}},[a,s]);if(!e)return null;const g=e.status||"unknown",N=e.mode||"feature";return t.jsxs("div",{className:"m-overlay","data-testid":"mobile-build-detail",role:"dialog","aria-modal":"true",children:[t.jsxs("header",{className:"m-overlay-header",children:[t.jsxs("div",{className:"m-overlay-header-inner",children:[t.jsx("div",{className:"m-overlay-title",title:a,children:a}),t.jsx("span",{className:"m-status-pill","data-status":g,children:g}),t.jsx("span",{className:"m-build-card-mode","data-mode":N,children:N})]}),t.jsxs("div",{className:"m-overlay-actions",children:[t.jsx("button",{type:"button",className:"m-btn m-btn-danger m-btn-sm",disabled:o||ae(g),onClick:p,"data-testid":"mobile-build-detail-abort",children:o?"Aborting…":"Abort"}),t.jsx("button",{type:"button",className:"m-btn m-btn-sm",onClick:n,"data-testid":"mobile-build-detail-close",children:"Close"})]})]}),t.jsxs("div",{className:"m-build-detail-tabs",children:[t.jsx("button",{type:"button",className:`m-build-detail-tab${m==="steps"?" is-active":""}`,"data-testid":"mobile-build-detail-tab-steps","aria-pressed":m==="steps",onClick:()=>f("steps"),children:"Steps"}),t.jsx("button",{type:"button",className:`m-build-detail-tab${m==="log"?" is-active":""}`,"data-testid":"mobile-build-detail-tab-log","aria-pressed":m==="log",onClick:()=>f("log"),children:"Log"})]}),m==="steps"?t.jsx("div",{className:"m-overlay-body",children:t.jsx(Xt,{active:e})}):t.jsxs("div",{className:"m-overlay-body m-agent-log",children:[i.length===0?t.jsx("div",{className:"m-empty",children:"No live events yet."}):i.map((C,v)=>t.jsx("div",{className:"m-agent-log-line",children:Vt(C,v)},v)),t.jsx("div",{ref:d})]}),u&&t.jsx("div",{className:"m-agent-card-error",children:u})]})}function Zt(e){if(!e)return"";const n=typeof e=="string"?Date.parse(e):Number(e);if(!n||Number.isNaN(n))return"";const s=Date.now()-n;return s<5e3?"just now":s<6e4?`${Math.floor(s/1e3)}s ago`:s<36e5?`${Math.floor(s/6e4)}m ago`:s<864e5?`${Math.floor(s/36e5)}h ago`:`${Math.floor(s/864e5)}d ago`}function es(e){if(!e||typeof e!="number")return"—";if(e<1e3)return`${e}ms`;if(e<6e4)return`${Math.floor(e/1e3)}s`;if(e<36e5){const a=Math.floor(e/6e4),i=Math.floor(e%6e4/1e3);return i>0?`${a}m ${i}s`:`${a}m`}const n=Math.floor(e/36e5),s=Math.floor(e%36e5/6e4);return s>0?`${n}h ${s}m`:`${n}h`}const ve=80;function ts(e){if(!e)return"";const n=e.toLowerCase();return n==="complete"||n==="completed"?"ok":n==="failed"||n==="error"?"error":n==="aborted"||n==="killed"?"warn":""}function ss({build:e,index:n}){const[s,a]=r.useState(!1),i=Zt(e.completedAt),d=e.failureReason?e.failureReason.slice(0,ve)+(e.failureReason.length>ve?"…":""):null,o=ts(e.status);return t.jsxs("div",{className:`m-build-history-row${s?" is-expanded":""}`,"data-testid":`mobile-build-history-${n}`,"data-status":e.status||"unknown",role:"button",tabIndex:0,"aria-expanded":s,onClick:()=>a(c=>!c),onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&a(u=>!u)},children:[t.jsxs("div",{className:"m-build-history-summary",children:[t.jsx("span",{className:"m-build-history-code",children:e.featureCode||"(unknown)"}),t.jsx("span",{className:`m-status-pill${o?" m-status-pill--"+o:""}`,"data-status":e.status,children:e.status||"unknown"}),i&&t.jsx("span",{className:"m-build-history-rel",children:i}),!s&&d&&t.jsx("span",{className:"m-build-history-reason-trunc",children:d})]}),s&&t.jsxs("div",{className:"m-build-history-detail",children:[e.mode!=null&&t.jsxs("div",{className:"m-build-history-field",children:[t.jsx("span",{className:"m-build-history-field-label",children:"Mode"}),t.jsx("span",{className:"m-build-history-field-value",children:e.mode})]}),e.durationMs!=null&&t.jsxs("div",{className:"m-build-history-field",children:[t.jsx("span",{className:"m-build-history-field-label",children:"Duration"}),t.jsx("span",{className:"m-build-history-field-value",children:es(e.durationMs)})]}),e.stepCount!=null&&t.jsxs("div",{className:"m-build-history-field",children:[t.jsx("span",{className:"m-build-history-field-label",children:"Steps"}),t.jsx("span",{className:"m-build-history-field-value",children:e.stepCount})]}),e.failureReason&&t.jsxs("div",{className:"m-build-history-field m-build-history-field--block",children:[t.jsx("span",{className:"m-build-history-field-label",children:"Failure reason"}),t.jsx("span",{className:"m-build-history-field-value m-build-history-failure",children:e.failureReason})]}),e.startedAt&&t.jsxs("div",{className:"m-build-history-field",children:[t.jsx("span",{className:"m-build-history-field-label",children:"Started"}),t.jsx("span",{className:"m-build-history-field-value",children:new Date(e.startedAt).toLocaleString()})]}),e.completedAt&&t.jsxs("div",{className:"m-build-history-field",children:[t.jsx("span",{className:"m-build-history-field-label",children:"Completed"}),t.jsx("span",{className:"m-build-history-field-value",children:new Date(e.completedAt).toLocaleString()})]})]})]})}function ns({builds:e,loading:n,error:s}){return n?t.jsx("div",{className:"m-build-history","data-testid":"mobile-build-history",children:t.jsx("div",{className:"m-empty",children:"Loading history…"})}):s?t.jsx("div",{className:"m-build-history","data-testid":"mobile-build-history",children:t.jsxs("div",{className:"m-empty",children:["Error: ",s]})}):t.jsx("div",{className:"m-build-history","data-testid":"mobile-build-history",children:!e||e.length===0?t.jsx("div",{className:"m-empty",children:"No past builds."}):e.map((a,i)=>t.jsx(ss,{build:a,index:i},a.flowId||i))})}async function as(){var e;try{const n=await J("/api/vision/items");if(!n.ok)return[];const s=await n.json(),a=Array.isArray(s==null?void 0:s.items)?s.items:Array.isArray(s)?s:[],i=new Set;for(const d of a){const o=((e=d==null?void 0:d.lifecycle)==null?void 0:e.featureCode)||(d==null?void 0:d.featureCode)||(d==null?void 0:d.id);o&&typeof o=="string"&&i.add(o)}return[...i].sort()}catch{return[]}}function rs({open:e,onClose:n,onSubmit:s}){const[a,i]=r.useState(""),[d,o]=r.useState("feature"),[c,u]=r.useState(""),[y,m]=r.useState(!1),[f,p]=r.useState(null),[g,N]=r.useState([]),C=r.useId();r.useEffect(()=>{if(!e)return;let x=!0;return as().then(j=>{x&&N(j)}),()=>{x=!1}},[e]);const v=r.useMemo(()=>g,[g]);if(!e)return null;function E(){i(""),o("feature"),u(""),p(null),m(!1)}function w(){E(),n==null||n()}async function T(x){if(x==null||x.preventDefault(),!a.trim()){p("Feature code is required");return}m(!0),p(null);try{await(s==null?void 0:s({featureCode:a.trim(),mode:d,description:c.trim()})),w()}catch(j){p(j.message||"Failed to start build"),m(!1)}}return t.jsx("div",{className:"m-sheet-overlay","data-testid":"mobile-start-build-sheet",role:"dialog","aria-modal":"true","aria-label":"Start build",onClick:x=>{x.target===x.currentTarget&&w()},children:t.jsxs("div",{className:"m-sheet",children:[t.jsxs("header",{className:"m-sheet-header",children:[t.jsx("button",{type:"button",className:"m-sheet-close","aria-label":"Close start build",onClick:w,disabled:y,children:"×"}),t.jsx("div",{className:"m-sheet-title-row",children:t.jsx("div",{className:"m-sheet-title",children:"Start build"})})]}),t.jsxs("form",{className:"m-sheet-body",onSubmit:T,children:[t.jsxs("div",{className:"m-sheet-section",children:[t.jsx("label",{className:"m-sheet-label",htmlFor:"m-build-feature",children:"Feature code"}),t.jsx("input",{id:"m-build-feature",type:"text",className:"m-sheet-input",value:a,onChange:x=>i(x.target.value),placeholder:"e.g. COMP-MOBILE","data-testid":"mobile-build-feature-input",list:C,autoFocus:!0,required:!0}),t.jsx("datalist",{id:C,children:v.map(x=>t.jsx("option",{value:x},x))})]}),t.jsxs("div",{className:"m-sheet-section",children:[t.jsx("div",{className:"m-sheet-label",children:"Mode"}),t.jsxs("div",{className:"m-build-mode-row",role:"radiogroup","aria-label":"Build mode",children:[t.jsx("button",{type:"button",role:"radio","aria-checked":d==="feature",className:`m-priority-chip${d==="feature"?" is-selected":""}`,"data-testid":"mobile-build-mode-feature",onClick:()=>o("feature"),children:"Feature"}),t.jsx("button",{type:"button",role:"radio","aria-checked":d==="bug",className:`m-priority-chip${d==="bug"?" is-selected":""}`,"data-testid":"mobile-build-mode-bug",onClick:()=>o("bug"),children:"Bug"})]})]}),t.jsxs("div",{className:"m-sheet-section",children:[t.jsx("label",{className:"m-sheet-label",htmlFor:"m-build-desc",children:"Description (optional)"}),t.jsx("textarea",{id:"m-build-desc",className:"m-sheet-input m-textarea",value:c,onChange:x=>u(x.target.value),rows:4,"data-testid":"mobile-build-description"})]}),f?t.jsx("div",{className:"m-form-error",role:"alert",children:f}):null]}),t.jsxs("footer",{className:"m-sheet-footer",children:[t.jsx("button",{type:"button",className:"m-sheet-btn m-sheet-btn-secondary",onClick:w,disabled:y,"data-testid":"mobile-build-cancel",children:"Cancel"}),t.jsx("button",{type:"button",className:"m-sheet-btn m-sheet-btn-primary",disabled:y||!a.trim(),"data-testid":"mobile-build-submit",onClick:T,children:y?"Starting…":"Start"})]})]})})}const Ie=4e3,we={info:{color:"hsl(var(--foreground))",bg:"hsl(var(--muted))"},warn:{color:"hsl(var(--warning, 32 95% 52%))",bg:"hsl(var(--muted))"},error:{color:"hsl(var(--destructive))",bg:"hsl(var(--destructive) / 0.08)"}};function vs(){const[e,n]=r.useState(null),s=r.useRef(null);if(r.useEffect(()=>{function i(d){const{message:o,level:c="info",ttl:u=Ie}=d.detail??{};o&&(clearTimeout(s.current),n({message:o,level:c}),u>0&&(s.current=setTimeout(()=>n(null),u)))}return window.addEventListener("compose:notify",i),()=>{window.removeEventListener("compose:notify",i),clearTimeout(s.current)}},[]),!e)return null;const a=we[e.level]??we.info;return t.jsxs("div",{className:"h-6 flex items-center justify-between px-3 gap-2 shrink-0 text-[11px] font-mono",style:{background:a.bg,color:a.color,borderTop:"1px solid hsl(var(--border))"},role:"status","aria-live":"polite",children:[t.jsx("span",{className:"flex-1 min-w-0 truncate",children:e.message}),t.jsx("button",{className:"shrink-0 opacity-60 hover:opacity-100 text-[10px]",onClick:()=>{clearTimeout(s.current),n(null)},"aria-label":"Dismiss notification",children:"✕"})]})}function ie(e,n="info",s=Ie){try{window.dispatchEvent(new CustomEvent("compose:notify",{detail:{message:e,level:n,ttl:s}}))}catch{}}async function Se(e,n={}){const s=await J(e,n);let a=null;try{a=await s.json()}catch{}if(!s.ok){const i=a&&a.error||`HTTP ${s.status}`;throw new Error(i)}return a}const is=new Set(["complete","completed"]);function ls({active:e,limit:n=20}={}){const[s,a]=r.useState([]),[i,d]=r.useState(!0),[o,c]=r.useState(null),u=r.useRef(new Map),y=r.useRef(new Map),m=r.useRef(!0),f=r.useRef(null),p=r.useCallback(C=>{a(C),c(null);for(const v of C){const E=v.flowId;if(!E)continue;const w=u.current.get(E);if(w&&is.has(w)&&v.status==="failed"&&y.current.get(E)!==v.status){y.current.set(E,v.status);try{ie(`Build failed post-checks: ${v.featureCode}`,"error",0)}catch{}}}},[]),g=r.useCallback(async({pendingFlowId:C}={})=>{try{const v=await Se(`/api/builds?limit=${n}`);if(!m.current)return;const E=Array.isArray(v==null?void 0:v.builds)?v.builds:[];p(E),C&&(E.some(T=>T.flowId===C)||(f.current&&clearTimeout(f.current),f.current=setTimeout(async()=>{if(m.current)try{const T=await Se(`/api/builds?limit=${n}`);if(!m.current)return;const x=Array.isArray(T==null?void 0:T.builds)?T.builds:[];p(x)}catch(T){m.current&&c(T.message)}},2500)))}catch(v){if(!m.current)return;c(v.message)}finally{m.current&&d(!1)}},[n,p]);r.useEffect(()=>(m.current=!0,g(),()=>{m.current=!1,f.current&&clearTimeout(f.current)}),[g]);const N=r.useRef(null);return r.useEffect(()=>{if(!e)return;N.current,N.current=e;const C=e.flowId;!C||!ae(e.status)||u.current.has(C)||(u.current.set(C,e.status),g({pendingFlowId:C}))},[e,g]),{builds:s,loading:i,error:o,refetch:g}}function os({active:e,loading:n,error:s,startBuild:a,abortBuild:i}){const[d,o]=r.useState(!1),[c,u]=r.useState(!1),[y,m]=r.useState(!1),[f,p]=r.useState(null),{builds:g,loading:N,error:C}=ls({active:e}),v=!!(e&&e.featureCode&&!ae(e.status)),E=r.useCallback(async({featureCode:T,mode:x,description:j})=>{try{await a({featureCode:T,mode:x,description:j}),p({kind:"ok",message:`Build started for ${T}`})}catch(h){const b=(h==null?void 0:h.status)===409?`A build for ${T} is already active`:(h==null?void 0:h.message)||"Failed to start build";throw p({kind:"error",message:b}),h}},[a]),w=r.useCallback(async({featureCode:T})=>{m(!0);try{await i({featureCode:T}),p({kind:"ok",message:`Aborted ${T}`}),u(!1)}catch(x){throw p({kind:"error",message:(x==null?void 0:x.message)||"Failed to abort"}),x}finally{m(!1)}},[i]);return t.jsxs("section",{"data-testid":"mobile-tab-builds",className:"m-builds-tab",children:[t.jsxs("div",{className:"m-section",children:[t.jsx("h2",{className:"m-section-title",children:"Current build"}),n?t.jsx("div",{className:"m-empty","data-testid":"mobile-build-loading",children:"Loading…"}):v?t.jsx(Ht,{active:e,onOpen:()=>u(!0),onAbort:w,aborting:y}):t.jsxs("div",{className:"m-empty-state","data-testid":"mobile-build-empty",children:[t.jsx("div",{className:"m-empty-title",children:"No active build"}),t.jsx("div",{className:"m-empty-body",children:e&&ae(e.status)?`Last build: ${e.featureCode} (${e.status})`:"Start a build to track progress here."}),t.jsx("button",{type:"button",className:"m-btn m-btn-primary","data-testid":"mobile-build-start",onClick:()=>o(!0),children:"Start build"})]}),s&&t.jsxs("div",{className:"m-empty","data-testid":"mobile-build-error",children:["Error: ",s]})]}),v&&t.jsx("div",{className:"m-section",children:t.jsx("button",{type:"button",className:"m-btn m-btn-sm","data-testid":"mobile-build-start-secondary",onClick:()=>o(!0),children:"Start another build"})}),t.jsxs("div",{className:"m-section","data-testid":"mobile-build-history-section",children:[t.jsx("h2",{className:"m-section-title",children:"History"}),t.jsx(ns,{builds:g,loading:N,error:C})]}),t.jsx(rs,{open:d,onClose:()=>o(!1),onSubmit:E}),c&&e&&t.jsx(Qt,{active:e,onClose:()=>u(!1),onAbort:w}),t.jsx($e,{message:f==null?void 0:f.message,kind:f==null?void 0:f.kind,onDismiss:()=>p(null)})]})}const cs=3;function us({onNavigate:e}){const[n,s]=r.useState([]),a=r.useRef(new Map),i=r.useRef(0),d=r.useCallback(c=>{clearTimeout(a.current.get(c)),a.current.delete(c),s(u=>u.filter(y=>y.id!==c))},[]);if(r.useEffect(()=>{function c(u){const{message:y,level:m="info",ttl:f}=u.detail??{};if(!y)return;const p=++i.current;s(N=>{const C=[...N,{id:p,message:y,level:m}];if(C.length>cs){const v=C.shift();clearTimeout(a.current.get(v.id)),a.current.delete(v.id)}return C});const g=typeof f=="number"&&f>0&&isFinite(f)?f:0;if(g>0){const N=setTimeout(()=>{s(C=>C.filter(v=>v.id!==p)),a.current.delete(p)},g);a.current.set(p,N)}}return window.addEventListener("compose:notify",c),()=>{window.removeEventListener("compose:notify",c);for(const u of a.current.values())clearTimeout(u);a.current.clear()}},[]),n.length===0)return null;function o(c){return c==="warn"?"agents":"builds"}return t.jsx("div",{className:"m-alert-bar","data-testid":"mobile-alert-bar","aria-live":"polite",children:n.map(c=>t.jsxs("div",{className:`m-alert m-alert-${c.level}`,"data-testid":`mobile-alert-${c.level}`,role:"status",onClick:()=>{e==null||e(o(c.level)),d(c.id)},children:[t.jsx("span",{className:"m-alert-msg",children:c.message}),t.jsx("button",{type:"button",className:"m-alert-dismiss","aria-label":"Dismiss",onClick:u=>{u.stopPropagation(),d(c.id)},children:"✕"})]},c.id))})}async function ke(e,n={}){const s=await J(e,n);let a=null;try{a=await s.json()}catch{}if(!s.ok){const i=a&&a.error||`HTTP ${s.status}`;throw new Error(i)}return a}function ds(){const[e,n]=r.useState([]),[s,a]=r.useState(!0),[i,d]=r.useState(null),o=r.useRef(!0),c=r.useCallback(async()=>{try{const y=await ke("/api/vision/gates");if(!o.current)return;n(Array.isArray(y==null?void 0:y.gates)?y.gates:[]),d(null)}catch(y){if(!o.current)return;d(y.message)}finally{o.current&&a(!1)}},[]);r.useEffect(()=>(o.current=!0,c(),()=>{o.current=!1}),[c]),r.useEffect(()=>{if(typeof window>"u"||typeof WebSocket>"u")return;let y=null,m=!1,f=null;function p(){if(!m){try{const N=window.location.protocol==="https:"?"wss:":"ws:";y=new WebSocket(`${N}//${window.location.host}/ws/vision`)}catch{g();return}y.onmessage=N=>{try{const C=JSON.parse(N.data);if(!C||!C.type)return;(C.type==="gateCreated"||C.type==="gateResolved"||C.type==="gateUpdated")&&c()}catch{}},y.onclose=()=>{m||g()},y.onerror=()=>{try{y.close()}catch{}}}}function g(){f&&clearTimeout(f),f=setTimeout(p,3e3)}return p(),()=>{m=!0,f&&clearTimeout(f);try{y&&(y.onclose=null,y.close())}catch{}}},[c]);const u=r.useCallback(async(y,{outcome:m,reason:f,summary:p}={})=>{if(!["approve","revise","kill"].includes(m))throw new Error(`outcome must be approve|revise|kill (got ${m})`);const g=[];f&&g.push(f),p&&g.push(p);const N=g.join(" — ")||void 0,C={outcome:m};N&&(C.comment=N);const v=await ke(`/api/vision/gates/${encodeURIComponent(y)}/resolve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});return c(),v},[c]);return{gates:e,loading:s,error:i,refetch:c,resolve:u}}async function me(e,n={}){const s=await J(e,n);let a=null;try{a=await s.json()}catch{}if(!s.ok){const i=a&&a.error||`HTTP ${s.status}`,d=new Error(i);throw d.status=s.status,d.data=a,d}return a}function ms(){const[e,n]=r.useState(null),[s,a]=r.useState(!0),[i,d]=r.useState(null),o=r.useRef(!0),c=r.useCallback(async()=>{try{const m=await me("/api/build/state");if(!o.current)return;n((m==null?void 0:m.state)??null),d(null)}catch(m){if(!o.current)return;d(m.message)}finally{o.current&&a(!1)}},[]);r.useEffect(()=>(o.current=!0,c(),()=>{o.current=!1}),[c]),r.useEffect(()=>{if(typeof window>"u"||typeof WebSocket>"u")return;let m=null,f=!1,p=null;function g(){if(!f){try{const C=window.location.protocol==="https:"?"wss:":"ws:";m=new WebSocket(`${C}//${window.location.host}/ws/vision`)}catch{N();return}m.onmessage=C=>{try{const v=JSON.parse(C.data);if(!v||!v.type)return;v.type==="buildState"&&c()}catch{}},m.onclose=()=>{f||N()},m.onerror=()=>{try{m.close()}catch{}}}}function N(){p&&clearTimeout(p),p=setTimeout(g,3e3)}return g(),()=>{f=!0,p&&clearTimeout(p);try{m&&(m.onclose=null,m.close())}catch{}}},[c]);const u=r.useCallback(async({featureCode:m,mode:f="feature",description:p=""}={})=>{if(!m)throw new Error("featureCode required");const g=await me("/api/build/start",{method:"POST",headers:V({"Content-Type":"application/json"}),body:JSON.stringify({featureCode:m,mode:f,description:p})});return c(),g},[c]),y=r.useCallback(async({featureCode:m}={})=>{if(!m)throw new Error("featureCode required");const f=await me("/api/build/abort",{method:"POST",headers:V({"Content-Type":"application/json"}),body:JSON.stringify({featureCode:m})});return c(),f},[c]);return{active:e,loading:s,error:i,refetch:c,startBuild:u,abortBuild:y}}function fs({url:e,onMessage:n,onOpen:s,onClose:a,onError:i,maxBackoffMs:d=3e4}){let o=null,c=0,u=!1,y=null;function m(){if(!u){try{o=new WebSocket(e)}catch(p){i==null||i(p),f();return}o.onopen=()=>{c=0,s==null||s(o)},o.onmessage=p=>n==null?void 0:n(p),o.onclose=()=>{a==null||a(),f()},o.onerror=p=>{i==null||i(p)}}}function f(){if(u||y)return;const p=Math.min(d,1e3*Math.pow(2,c++));y=setTimeout(()=>{y=null,m()},p)}return m(),{get socket(){return o},isOpen(){return(o==null?void 0:o.readyState)===1},send(p){(o==null?void 0:o.readyState)===1&&o.send(p)},close(){if(u=!0,y&&(clearTimeout(y),y=null),o){try{o.onclose=null,o.onerror=null,o.close()}catch{}o=null}}}}function hs(){return`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/vision`}function ps(){const[e,n]=r.useState([]),[s,a]=r.useState(!0),[i,d]=r.useState(null),[o,c]=r.useState(!1),u=r.useRef(e);u.current=e;const y=r.useRef(new Map),m=r.useRef(new Map),f=r.useRef(new Set),p=r.useRef(0),g=r.useCallback(async()=>{try{const j=await(await J("/api/vision/items")).json(),h=Array.isArray(j==null?void 0:j.items)?j.items:Array.isArray(j)?j:[];n(h),d(null)}catch(x){d((x==null?void 0:x.message)||"Failed to load items")}finally{a(!1)}},[]);r.useEffect(()=>{let x=!1;g();const j=fs({url:hs(),onOpen:()=>{x||c(!0)},onClose:()=>{x||c(!1)},onMessage:h=>{var A,D;if(x)return;let b;try{b=JSON.parse(h.data)}catch{return}if(!b||typeof b!="object")return;const S=b.type;(S==="visionState"||S==="hydrate")&&Array.isArray(b.items)?n(()=>{const I=y.current,O=m.current,L=f.current;let F=b.items;if(I.size>0&&(F=F.map(q=>{const Y=I.get(q.id);return Y?{...q,...Y}:q})),L.size>0&&(F=F.filter(q=>!L.has(q.id))),O.size>0){const q=new Set(F.map(z=>z.id)),Y=[...O.values()].filter(z=>!q.has(z.id));Y.length>0&&(F=[...Y,...F])}return F}):S==="itemUpdated"&&((A=b.item)!=null&&A.id)?n(I=>{const O=I.findIndex(F=>F.id===b.item.id);if(O===-1)return[...I,b.item];const L=I.slice();return L[O]={...L[O],...b.item},L}):S==="itemCreated"&&((D=b.item)!=null&&D.id)?n(I=>I.some(O=>O.id===b.item.id)?I:[...I,b.item]):S==="itemDeleted"&&b.id?n(I=>I.filter(O=>O.id!==b.id)):S==="state"&&Array.isArray(b.items)?n(b.items):(S==="visionUpdated"||S==="roadmapUpdated")&&g()}});return()=>{x=!0;try{j.close()}catch{}}},[g]);const N=r.useCallback(async(x,j)=>{if(!x||!j||typeof j!="object")return{ok:!1,error:"invalid patch"};const h=u.current;if(!h.find(A=>A.id===x))return{ok:!1,error:"item not found"};y.current.set(x,j);const S=h.map(A=>A.id===x?{...A,...j}:A);n(S);try{const A=await J(`/api/vision/items/${x}`,{method:"PATCH",headers:V({"Content-Type":"application/json"}),body:JSON.stringify(j)}),D=await A.json().catch(()=>({}));if(!A.ok)return y.current.delete(x),n(h),{ok:!1,error:(D==null?void 0:D.error)||`HTTP ${A.status}`};y.current.delete(x);const I=(D==null?void 0:D.item)||(D==null?void 0:D.updated)||null;return I&&I.id===x&&n(O=>O.map(L=>L.id===x?{...L,...I}:L)),{ok:!0,item:I||S.find(O=>O.id===x)}}catch(A){return y.current.delete(x),n(h),{ok:!1,error:(A==null?void 0:A.message)||"Network error"}}},[]),C=r.useCallback(async x=>{if(!x||typeof x!="object")return{ok:!1,error:"invalid fields"};const j=`tmp-${++p.current}`,h={...x,type:"feature",id:j};m.current.set(j,h),n(b=>[h,...b]);try{const b=await J("/api/vision/items",{method:"POST",headers:V({"Content-Type":"application/json"}),body:JSON.stringify({...x,type:"feature"})}),S=await b.json().catch(()=>({}));if(!b.ok)return m.current.delete(j),n(D=>D.filter(I=>I.id!==j)),{ok:!1,error:(S==null?void 0:S.error)||`HTTP ${b.status}`};const A=(S==null?void 0:S.item)||(S!=null&&S.id?S:null);return m.current.delete(j),n(D=>A&&D.some(I=>I.id===A.id)?D.filter(I=>I.id!==j):D.map(I=>I.id===j&&A?{...I,...A}:I)),{ok:!0,item:A}}catch(b){return m.current.delete(j),n(S=>S.filter(A=>A.id!==j)),{ok:!1,error:(b==null?void 0:b.message)||"Network error"}}},[]),v=r.useCallback(async x=>{if(!x)return{ok:!1,error:"id required"};const j=u.current;f.current.add(x),n(h=>h.filter(b=>b.id!==x));try{const h=await J(`/api/vision/items/${x}`,{method:"DELETE",headers:V({"Content-Type":"application/json"})}),b=await h.json().catch(()=>({}));return h.ok?(f.current.delete(x),{ok:!0}):(f.current.delete(x),n(j),{ok:!1,error:(b==null?void 0:b.error)||`HTTP ${h.status}`})}catch(h){return f.current.delete(x),n(j),{ok:!1,error:(h==null?void 0:h.message)||"Network error"}}},[]),E=r.useCallback(async({fromId:x,toId:j,type:h})=>{try{const b=await J("/api/vision/connections",{method:"POST",headers:V({"Content-Type":"application/json"}),body:JSON.stringify({fromId:x,toId:j,type:h})}),S=await b.json().catch(()=>({}));return b.ok?{ok:!0,connection:(S==null?void 0:S.connection)||S}:{ok:!1,error:(S==null?void 0:S.error)||`HTTP ${b.status}`}}catch(b){return{ok:!1,error:(b==null?void 0:b.message)||"Network error"}}},[]),w=r.useCallback(async x=>{try{const j=await J(`/api/vision/connections/${x}`,{method:"DELETE",headers:V({"Content-Type":"application/json"})}),h=await j.json().catch(()=>({}));return j.ok?{ok:!0}:{ok:!1,error:(h==null?void 0:h.error)||`HTTP ${j.status}`}}catch(j){return{ok:!1,error:(j==null?void 0:j.message)||"Network error"}}},[]),T=r.useCallback(async x=>{try{const j=await J(`/api/vision/items/${x}`),h=await j.json().catch(()=>({}));return j.ok?{ok:!0,item:h}:{ok:!1,error:(h==null?void 0:h.error)||`HTTP ${j.status}`}}catch(j){return{ok:!1,error:(j==null?void 0:j.message)||"Network error"}}},[]);return{items:e,loading:s,error:i,connected:o,refetch:g,applyOptimisticEdit:N,createItem:C,deleteItem:v,addConnection:E,removeConnection:w,fetchItemDetail:T}}function bs({active:e,gates:n,items:s}){const a=r.useRef(null),i=r.useRef(new Map);r.useEffect(()=>{if(Array.isArray(n)){if(a.current===null){a.current=new Set(n.map(d=>d.id));return}for(const d of n)if(!a.current.has(d.id)){a.current.add(d.id);const o=(Array.isArray(s)?s:[]).find(u=>u.id===d.itemId),c=(o==null?void 0:o.title)||"Gate pending";ie(`Gate pending: ${c}`,"warn",0)}}},[n,s]),r.useEffect(()=>{if(!e||!e.flowId)return;const d=i.current.get(e.flowId),o=e.status;d!==void 0&&d!==o&&(o==="failed"?ie(`Build failed: ${e.featureCode||e.flowId}`,"error",0):(o==="complete"||o==="completed")&&ie(`Build complete: ${e.featureCode||e.flowId}`,"info",4e3)),i.current.set(e.flowId,o)},[e])}const Pe=["agents","roadmap","builds","ideas"],Ce="agents",Te="compose:mobile:sensitiveToken";function ys(e){const n=e.match(/^\/m(?:\/([^/?#]+))?\/?$/);if(!n)return Ce;const s=n[1];return s&&Pe.includes(s)?s:Ce}function gs(){const[e,n]=r.useState(()=>ys(window.location.pathname));r.useEffect(()=>{try{const h=new URL(window.location.href),b=h.searchParams.get("token");if(b){try{localStorage.setItem(Te,b)}catch{}ge(b),h.searchParams.delete("token"),window.history.replaceState({},"",h.pathname+(h.search?h.search:"")+h.hash)}else{let S=null;try{S=localStorage.getItem(Te)}catch{}S&&ge(S)}}catch{}},[]),r.useEffect(()=>{if(!(typeof navigator>"u")&&"serviceWorker"in navigator)try{navigator.serviceWorker.register("/m-sw.js").catch(h=>{console.warn("[compose-mobile] SW registration failed:",h)})}catch(h){console.warn("[compose-mobile] SW registration threw:",h)}},[]);const s=r.useCallback(h=>{if(Pe.includes(h)){n(h);try{const b=new URL(window.location.href);b.pathname=`/m/${h}`,window.history.replaceState({},"",b.pathname+b.search+b.hash)}catch{}}},[]),{gates:a,loading:i,resolve:d}=ds(),{active:o,loading:c,error:u,startBuild:y,abortBuild:m}=ms(),{items:f,loading:p,error:g,applyOptimisticEdit:N,createItem:C,deleteItem:v,addConnection:E,removeConnection:w,fetchItemDetail:T}=ps();bs({active:o,gates:a,items:f});const x={};a.length>0&&(x.agents={count:a.length,level:"warn"}),(o==null?void 0:o.status)==="failed"?x.builds={level:"error"}:We(o,a,f)&&(x.builds={level:"warn"});let j=null;return e==="agents"?j=t.jsx(ht,{gates:a,gatesLoading:i,resolveGate:d}):e==="roadmap"?j=t.jsx(Tt,{items:f,loading:p,error:g,applyOptimisticEdit:N,createItem:C,deleteItem:v,addConnection:E,removeConnection:w,fetchItemDetail:T}):e==="ideas"?j=t.jsx(Gt,{}):e==="builds"&&(j=t.jsx(os,{active:o,loading:c,error:u,startBuild:y,abortBuild:m})),t.jsxs("div",{className:"m-root","data-testid":"mobile-root",children:[t.jsx("header",{className:"m-header",children:t.jsx("div",{className:"m-header-title",children:"Compose"})}),t.jsx(us,{onNavigate:s}),t.jsx("main",{className:"m-main","data-testid":"mobile-main","data-tab":e,children:j}),t.jsx(ze,{active:e,onSelect:s,badges:x})]})}const ws=Object.freeze(Object.defineProperty({__proto__:null,default:gs},Symbol.toStringTag,{value:"Module"}));export{ws as M,vs as N,Je as P,js as R,r as a,Ue as b,xs as c,rt as d,fs as e,V as f,Oe as g,re as h,t as j,Ye as m,ie as n,Fe as r,Ns as s,J as w};
