@codeyam-editor/codeyam-editor 0.1.0-staging.0f231be

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,38 @@
1
+ var Po=Object.defineProperty;var Do=(e,t,r)=>t in e?Po(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Oe=(e,t,r)=>Do(e,typeof t!="symbol"?t+"":t,r);import{j as n}from"./markdown-v0F0UEt3.js";import{b as i,R as Ne,c as vt}from"./react-CSS0HapR.js";import{S as Ao,j as rn,X as dt,Y as Fn,Z as As,_ as Ls,$ as Lo,a0 as Mo,a1 as Io,a2 as Fo,a3 as Oo,W as Bo,a4 as $o,a5 as _o,a6 as zo,a7 as Ze,f as Ho,a8 as Wo,a9 as Vo,aa as Uo,h as Ko,ab as Mr,ac as Go,ad as Yo,ae as Jo}from"./ScenarioDataPanel-DbnhCRfn.js";import{e as Xo,a as qo,l as V,g as er,d as Qo,p as On,t as Ms,u as Is}from"./index-CnDCJXUg.js";import{M as et}from"./Markdown-BHBqz-Mj.js";function Ir({onRunTests:e,disabled:t,currentRunner:r}){return t?n.jsxs("span",{className:"text-xs font-medium text-[var(--text-dim)] inline-flex items-center gap-1.5",children:[n.jsx("span",{className:"inline-block h-3 w-3 animate-spin rounded-full border-2 border-current border-r-transparent"}),r?`Running ${r}…`:"Running…"]}):n.jsx("span",{role:"button",tabIndex:0,onClick:s=>{s.stopPropagation(),e()},onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&(s.stopPropagation(),e())},className:"text-xs font-medium text-[var(--accent-active)] hover:underline cursor-pointer",children:"Run Tests"})}function Zo({passed:e,failed:t,notRun:r}){const s=e+t+r;if(s===0)return null;const a=2,o=[{count:e,color:"var(--accent-green)"},{count:t,color:"var(--accent-red)"},{count:r,color:"var(--text-dim)"}].filter(u=>u.count>0),l=o.map(u=>Math.max(u.count/s*100,a)),c=l.reduce((u,f)=>u+f,0),d=l.map(u=>u/c*100);return n.jsx("div",{className:"h-1.5 flex-1 rounded-full bg-[var(--bg-input)] overflow-hidden max-w-32",children:n.jsx("div",{className:"h-full flex",children:o.map((u,f)=>n.jsx("div",{className:"h-full transition-all",style:{width:`${d[f]}%`,background:u.color}},u.color))})})}function Fs({tests:e,loading:t,refreshing:r,onRunTests:s,currentRunner:a}){const o=e.total>0,l=e.discovered>0,c=e.discovered>e.total?e.discovered-e.total:0;return t?n.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[n.jsx("div",{className:"h-1.5 w-16 rounded-full bg-[var(--bg-input)] animate-pulse"}),n.jsx("span",{className:"text-xs text-[var(--text-dim)]",children:r?"Running tests…":"Loading tests…"})]}):o?n.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[n.jsx(Zo,{passed:e.passed,failed:e.failed,notRun:c}),n.jsxs("span",{className:"text-xs font-medium text-[var(--accent-green)]",children:[e.passed," passed"]}),e.failed>0&&n.jsxs("span",{className:"text-xs font-medium text-[var(--accent-red)]",children:["· ",e.failed," failed"]}),e.ignored>0&&n.jsxs("span",{className:"text-xs text-[var(--text-dim)]",children:["· ",e.ignored," skipped"]}),c>0&&n.jsxs("span",{className:"text-xs text-[var(--text-dim)]",children:["· ",c," not run"]}),s&&n.jsx(Ir,{onRunTests:s,disabled:r,currentRunner:a})]}):l?n.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[n.jsxs("span",{className:"text-xs text-[var(--text-dim)]",children:[e.discovered," ",e.discovered===1?"test":"tests"," (not run)"]}),s&&n.jsx(Ir,{onRunTests:s})]}):n.jsx("span",{className:"text-xs text-[var(--text-dim)]",children:"No tests"})}function ei({tests:e,loading:t,refreshing:r,onRunTests:s,currentRunner:a}){return n.jsxs("div",{className:"px-5 pb-5 pt-2 flex items-center gap-5 border-t border-[var(--border-default)]",children:[n.jsx(Fs,{tests:e,loading:t,refreshing:r,onRunTests:s,currentRunner:a}),n.jsx("span",{className:"text-[var(--text-dim)] group-hover:text-[var(--accent-active)] transition ml-auto text-sm",children:"→"})]})}function Os({type:e}){const t=e==="web";return n.jsx("span",{className:`rounded px-1.5 py-0.5 text-xs font-medium ${t?"bg-[var(--accent-blue)]/20 text-[var(--accent-blue)]":"bg-[var(--accent-purple)]/20 text-[var(--accent-purple)]"}`,children:t?"web":"backend"})}function ti({app:e}){return n.jsxs("div",{className:"px-5 pt-5 pb-2",children:[n.jsxs("div",{className:"flex items-center gap-3 mb-1",children:[n.jsx("h3",{className:"text-lg font-semibold text-[var(--text-primary)]",children:e.name}),n.jsx(Os,{type:e.type})]}),e.description?n.jsx("p",{className:"text-sm text-[var(--text-muted)] leading-relaxed",children:e.description}):null]})}function We(e){return e.startsWith("http")?e:`/api/screenshots/${e}`}function ni({thumbnails:e}){return n.jsx("div",{className:"flex gap-2 overflow-hidden",children:e.map((t,r)=>n.jsx("img",{src:We(t),alt:"",className:"h-20 w-32 rounded border border-[var(--border-default)] object-cover object-top"},`${t}:${r}`))})}function ri({thumbnails:e}){return n.jsx("div",{className:"px-5 py-3 flex-1",children:e.length>0?n.jsx(ni,{thumbnails:e.slice(0,4)}):n.jsx("div",{className:"h-20"})})}function si({stats:e,onClick:t,testsLoading:r,testsRefreshing:s,onRunTests:a,currentRunner:o}){const{app:l,tests:c,scenarios:d}=e;return n.jsxs("button",{onClick:t,className:"group flex w-full cursor-pointer flex-col rounded-lg border border-[var(--border-default)] bg-[var(--bg-card)] text-left transition hover:border-[var(--accent-active)]/40 hover:bg-[var(--bg-surface)]",children:[n.jsx(ti,{app:l}),n.jsx(ri,{thumbnails:d.thumbnails}),n.jsx(ei,{tests:c,loading:r,refreshing:s,onRunTests:a,currentRunner:o})]})}const tt={apps:[],isSingleApp:!1,onSelectApps:()=>{},onSelectApp:()=>{},onSelectRoute:()=>{}};function sn(e){return e.scenarioType==="application"||e.scenarioType==="component"?e.scenarioType:e.componentName?"component":"application"}function Qe(e){return sn(e)==="application"}function tr(e){return sn(e)==="component"}function nr(e){return{overrideCounts:{mocks:0,seeds:0,inheritedMocks:0,inheritedSeeds:0},...e,scenarioType:sn(e)}}function Rt(){const[e,t]=i.useState({}),r=i.useRef({});return i.useEffect(()=>{let s=!1;const a=async()=>{try{const l=await fetch("/api/editor-dev-server");if(!l.ok)return;const c=await l.json();if(s)return;const d=typeof c.scenariosVersion=="number"?c.scenariosVersion:void 0,u=typeof c.plansVersion=="number"?c.plansVersion:void 0,f=typeof c.testsVersion=="number"?c.testsVersion:void 0;(d!==r.current.scenariosVersion||u!==r.current.plansVersion||f!==r.current.testsVersion)&&(r.current={scenariosVersion:d,plansVersion:u,testsVersion:f},t(r.current))}catch{}};a();const o=setInterval(a,500);return()=>{s=!0,clearInterval(o)}},[]),e}function ai(e){const[t,r]=i.useState({status:"idle"}),{scenariosVersion:s}=Rt();return i.useEffect(()=>{if(!e){r({status:"idle"});return}let a=!1;return r({status:"loading"}),(async()=>{try{const o=await fetch(`/api/entities/${e}`);if(a)return;if(o.status===404){r({status:"not-found"});return}if(!o.ok){r({status:"error",message:`HTTP ${o.status}`});return}const l=await o.json(),c={...l,scenarios:Array.isArray(l.scenarios)?l.scenarios.map(nr):[]};r({status:"loaded",entity:c})}catch(o){if(a)return;r({status:"error",message:o instanceof Error?o.message:"Failed to load entity"})}})(),()=>{a=!0}},[e,s]),t}function yn({message:e}){return n.jsx("div",{className:"px-5 py-8 text-center text-[var(--accent-red)]",children:e})}function Fr(){return n.jsx("div",{className:"px-5 py-8 text-center text-[var(--text-dim)]",children:"Loading routes..."})}function oi(e){return e.kind==="function"?"Functions don't have visual scenarios. Coverage for this function lives in its unit tests.":e.kind==="component"?`No component scenarios for ${e.displayName}. Create one with \`codeyam-editor editor register\` or capture from the live preview.`:"No scenarios for this entity yet."}function ii(e){return typeof e!="string"&&typeof e.onClick=="function"}function li(e){return typeof e=="string"?e:e.label}function ci(e,t){(e.key==="Enter"||e.key===" ")&&(e.preventDefault(),t())}function di({segments:e}){if(e.length===0)return null;const t=e.length-1;return n.jsx("span",{className:"text-sm",style:{color:"var(--text-muted)"},children:e.map((r,s)=>{const a=li(r),o=s===t,l=!o&&ii(r);return n.jsxs("span",{children:[n.jsx("span",{style:{color:"var(--text-dim)"},children:" / "}),l?n.jsx("button",{type:"button",onClick:r.onClick,onKeyDown:c=>ci(c,r.onClick),className:"cursor-pointer hover:text-[var(--text-primary)] transition",style:{color:"inherit",background:"none",padding:0},children:a}):n.jsx("span",{style:o?{color:"var(--text-primary)"}:void 0,children:a})]},s)})})}function rr({apps:e,selectedApp:t,selectedRouteEntity:r,currentEntity:s,isSingleApp:a,onSelectApps:o,onSelectApp:l,onSelectRoute:c}){const d=[];return!a&&e.length>0&&d.push({label:"Apps",onClick:o}),t&&d.push({label:t.name,onClick:()=>l(t.dir)}),r!==null&&s!=null&&r?d.push({label:r.displayName,onClick:()=>c(r.route)}):r&&d.push({label:r.displayName}),s&&d.push({label:s.displayName}),n.jsx(di,{segments:d})}function ui({entity:e,app:t=null,routeEntity:r=null,navContext:s=tt}){var o;const a=e.kind==="component"?"Component":"Function";return n.jsxs("header",{className:"border-b border-[var(--border-subtle)] px-5 py-3",children:[n.jsx("div",{className:"mb-1",children:n.jsx(rr,{apps:s.apps,selectedApp:t,selectedRouteEntity:r,currentEntity:e,isSingleApp:s.isSingleApp,onSelectApps:s.onSelectApps,onSelectApp:s.onSelectApp,onSelectRoute:s.onSelectRoute})}),n.jsxs("div",{className:"flex items-baseline gap-2",children:[n.jsx("span",{className:"rounded-md border border-[var(--border-subtle)] bg-[var(--bg-card)] px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-[var(--text-dim)]",children:a}),n.jsx("h2",{className:"text-base font-semibold text-[var(--text-primary)]",children:e.displayName})]}),n.jsx("p",{className:"mt-0.5 font-mono text-[10px] text-[var(--text-dim)]",children:e.filePath}),((o=e.glossaryEntry)==null?void 0:o.description)&&n.jsx("p",{className:"mt-2 text-xs text-[var(--text-secondary)]",children:e.glossaryEntry.description})]})}function fi({entityRef:e,onNavigate:t}){return n.jsxs("button",{type:"button",onClick:()=>t(e.hash),className:"w-full rounded-lg border border-[var(--border-subtle)] bg-[var(--bg-card)] p-3 text-left transition hover:border-[var(--border-default)]",children:[n.jsxs("div",{className:"flex items-baseline gap-2",children:[n.jsx("span",{className:"rounded-md border border-[var(--border-subtle)] bg-[var(--bg-page)] px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-[var(--text-dim)]",children:e.kind}),n.jsx("span",{className:"text-sm font-medium text-[var(--text-primary)]",children:e.name})]}),n.jsx("p",{className:"mt-0.5 font-mono text-[10px] text-[var(--text-dim)]",children:e.filePath})]})}function Or({refs:e,onNavigate:t}){return n.jsx("ul",{className:"grid grid-cols-1 gap-1",children:e.map(r=>n.jsx("li",{children:n.jsx(fi,{entityRef:r,onNavigate:t})},r.hash))})}function wn({title:e,isEmpty:t,emptyCopy:r,children:s}){return n.jsxs("section",{children:[n.jsx("h3",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-[var(--text-dim)]",children:e}),t?n.jsx("p",{className:"text-xs italic text-[var(--text-dim)]",children:r}):s]})}function pi(e,t,r){const[s,a]=i.useState(!1),[o,l]=i.useState(""),[c,d]=i.useState(!1),u=i.useCallback(()=>{a(!0),l(t)},[t]),f=i.useCallback(()=>{a(!1)},[]),p=i.useCallback(async()=>{if(!(!o.trim()||c)){d(!0);try{const m=await fetch(`/api/scenarios/${encodeURIComponent(e)}`);if(!m.ok)throw new Error(`HTTP ${m.status}`);const h=await m.json();h.name=o.trim(),await fetch(`/api/scenarios/${encodeURIComponent(e)}`,{method:"DELETE"}),await fetch("/api/scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)}),a(!1),r()}catch{}finally{d(!1)}}},[o,c,e,r]);return{renaming:s,renameName:o,renameSaving:c,setRenameName:l,startRename:u,cancelRename:f,submitRename:p}}function mi(e,t,r){const[s,a]=i.useState(!1),o=i.useCallback(async l=>{if(l.stopPropagation(),!!confirm(`Delete scenario "${t}"?`)){a(!0);try{await fetch(`/api/scenarios/${encodeURIComponent(e)}`,{method:"DELETE"}),r()}catch{}finally{a(!1)}}},[t,e,r]);return{deleting:s,handleDelete:o}}function xi({mocks:e,seeds:t}){const r=[];return e>0&&r.push(`${e} ${e===1?"mock":"mocks"} overridden`),t>0&&r.push(`${t} ${t===1?"seed":"seeds"} overridden`),r.length===0?null:r.join(" · ")}function hi({overrideCounts:e}){const t=e?xi(e):null;return t?n.jsx("div",{className:"text-xs text-[var(--text-dim)] mt-1",children:t}):null}const gi=new Set(["Desktop"]);function vi({scenario:e,isSelected:t}){const r=e.dimensions.length>0&&!(e.dimensions.length===1&&gi.has(e.dimensions[0]));return n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:`text-base font-medium truncate ${t?"text-[var(--accent-active)]":"text-[var(--text-primary)]"}`,children:e.name}),e.description?n.jsx("div",{className:"text-sm text-[var(--text-secondary)] mt-1 whitespace-pre-line",children:e.description}):null,n.jsx(hi,{overrideCounts:e.overrideCounts}),n.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[r?n.jsx("span",{className:"text-xs text-[var(--text-dim)]",children:e.dimensions.join(", ")}):null,e.componentName?n.jsx("span",{className:"text-xs text-[var(--accent-purple)]",children:e.componentName}):null]})]})}function bi({screenshotPath:e}){const[t,r]=i.useState(!1);return e&&!t?n.jsx("img",{src:We(e),alt:"",className:"h-[180px] w-[288px] rounded border border-[var(--border-subtle)] bg-[var(--bg-card)] object-cover object-top shrink-0",onError:()=>r(!0)}):n.jsx("div",{className:"h-[180px] w-[288px] rounded border border-[var(--border-subtle)] bg-[var(--bg-card)] shrink-0 flex items-center justify-center",children:n.jsx("span",{className:"text-[10px] text-[var(--text-dim)]",children:"No preview"})})}function yi({onViewData:e,onRename:t,onDelete:r,deleting:s}){return n.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[n.jsx("button",{onClick:e,className:"text-xs text-[var(--accent-active)] hover:opacity-70 cursor-pointer bg-transparent border-none p-0",children:"View / Edit Data"}),n.jsx("button",{onClick:t,className:"text-xs text-[var(--text-dim)] hover:text-[var(--text-primary)] cursor-pointer bg-transparent border-none p-0",children:"Rename"}),n.jsx("button",{onClick:r,disabled:s,className:"text-xs text-red-400/60 hover:text-red-400 cursor-pointer bg-transparent border-none p-0",children:"Delete"})]})}function wi({name:e,saving:t,onChange:r,onSubmit:s,onCancel:a}){return n.jsxs("form",{className:"flex items-center gap-2",onSubmit:s,onClick:o=>o.stopPropagation(),children:[n.jsx("input",{type:"text",value:e,onChange:o=>r(o.target.value),className:"flex-1 px-2 py-1.5 text-sm bg-[var(--bg-input)] text-[var(--text-primary)] border border-[var(--border-default)] rounded outline-none focus:border-[var(--accent-active)] min-w-0",autoFocus:!0,disabled:t}),n.jsx("button",{type:"submit",disabled:t||!e.trim(),className:"px-3 py-1.5 text-xs bg-[var(--accent-active)] text-[var(--bg-base)] rounded hover:opacity-90 disabled:opacity-40 cursor-pointer border-none",children:t?"...":"Save"}),n.jsx("button",{type:"button",onClick:a,className:"px-3 py-1.5 text-xs text-[var(--text-dim)] hover:text-[var(--text-primary)] cursor-pointer bg-transparent border-none",children:"Cancel"})]})}function ji({scenario:e,isSelected:t,onSelect:r,onViewData:s,onScenariosChanged:a,children:o}){const l=pi(e.slug,e.name,a),{deleting:c,handleDelete:d}=mi(e.slug,e.name,a);return n.jsxs("div",{onClick:l.renaming?void 0:r,className:`rounded-lg p-3 text-left transition cursor-pointer ${t?"bg-[#1a2e1a] border border-[var(--accent-active)]/40":"bg-[var(--bg-card)] border border-transparent hover:bg-[var(--bg-input)]"}`,style:{opacity:c?.4:1},children:[n.jsxs("div",{className:"flex items-start gap-4",children:[n.jsx(bi,{screenshotPath:e.screenshotPaths[0]??null}),n.jsx("div",{className:"flex-1 min-w-0",children:l.renaming?n.jsx(wi,{name:l.renameName,saving:l.renameSaving,onChange:l.setRenameName,onSubmit:u=>{u.preventDefault(),l.submitRename()},onCancel:l.cancelRename}):n.jsxs(n.Fragment,{children:[n.jsx(vi,{scenario:e,isSelected:t}),t&&n.jsx(yi,{onViewData:u=>{u.stopPropagation(),s()},onRename:u=>{u.stopPropagation(),l.startRename()},onDelete:d,deleting:c})]})})]}),o&&n.jsx("div",{className:"mt-3 cursor-default",onClick:u=>u.stopPropagation(),children:o})]})}function Ni(){return n.jsx("div",{className:"rounded-xl border border-dashed border-[var(--border-default)] px-4 py-5 text-sm text-[var(--text-dim)]",children:"No scenarios registered for this route yet."})}function Bs({scenarios:e,selectedSlug:t,onSelectScenario:r,onScenariosChanged:s}){const[a,o]=i.useState(null);return e.length===0?n.jsx(Ni,{}):n.jsx("div",{className:"grid grid-cols-1 gap-2",children:e.map(l=>n.jsx(ji,{scenario:l,isSelected:l.slug===t,onSelect:()=>{a&&a!==l.slug&&o(null),r(l.slug)},onViewData:()=>o(a===l.slug?null:l.slug),onScenariosChanged:s,children:a===l.slug&&n.jsx(Ao,{variant:"inline",slug:l.slug,scenarioName:l.name,onClose:()=>o(null)})},l.slug))})}function Ci({app:e=null,navContext:t=tt,routeEntity:r=null,entity:s,selectedSlug:a,onSelectScenario:o,onNavigateToEntity:l,onScenariosChanged:c}){return n.jsxs("div",{className:"flex flex-col",children:[n.jsx(ui,{app:e,navContext:t,routeEntity:r,entity:s}),n.jsxs("div",{className:"flex-1 overflow-auto px-5 py-4 space-y-4",children:[n.jsx(wn,{title:"Scenarios",emptyCopy:oi(s),isEmpty:s.scenarios.length===0,children:n.jsx(Bs,{scenarios:s.scenarios,selectedSlug:a,onSelectScenario:o,onScenariosChanged:c})}),s.kind!=="function"&&n.jsx(wn,{title:"Direct imports",emptyCopy:s.kind==="component"?"This component renders no other tracked components or functions.":"No imports tracked for this entity.",isEmpty:s.directImports.length===0,children:n.jsx(Or,{refs:s.directImports,onNavigate:l})}),s.kind==="function"&&n.jsx(wn,{title:"Callers",emptyCopy:"Not called from any tracked entity. This may be a public export, an unused function, or a function whose callers haven't been re-analyzed yet.",isEmpty:s.callers.length===0,children:n.jsx(Or,{refs:s.callers,onNavigate:l})})]})]})}function Tt(e,t){const r=`${e}:${t}`;let s=2166136261;for(let a=0;a<r.length;a++)s^=r.charCodeAt(a),s=Math.imul(s,16777619);return(s>>>0).toString(16).padStart(8,"0")}function nt(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}function Si(e){const t=[],r=[];for(const s of e){const a=nt(s);/^[A-Z]/.test(a)&&!a.startsWith("use")?t.push(s):r.push(s)}return{componentImports:t,functionImports:r}}function ki({ancestor:e,onNavigateToEntity:t}){const r=t?()=>t(Tt(e.filePath,nt(e.filePath))):void 0;return n.jsxs("div",{role:"button",tabIndex:0,onClick:r,onKeyDown:s=>{r&&(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),r())},className:"cursor-pointer rounded-md border border-[var(--border-subtle)] bg-[var(--bg-card)] px-3 py-2 transition hover:border-[var(--border-default)]",children:[n.jsx("p",{className:"text-sm font-medium text-[var(--text-primary)]",children:e.displayName}),n.jsx("p",{className:"mt-0.5 font-mono text-[10px] text-[var(--text-dim)]",children:e.filePath})]})}function Ei({layoutChain:e,onNavigateToEntity:t}){return e.length===0?null:n.jsxs("section",{className:"border-b border-[var(--border-subtle)] px-5 py-3",children:[n.jsx("h3",{className:"mb-2 text-xs font-medium uppercase tracking-wide text-[var(--text-dim)]",children:"Layout chain"}),n.jsx("div",{className:"flex flex-col gap-1",children:e.map(r=>n.jsx(ki,{ancestor:r,onNavigateToEntity:t},`${r.kind}:${r.filePath}`))})]})}function Ri({importPath:e,derivedName:t,allScenarios:r,routeEntities:s}){const a=r.filter(l=>l.scenarioType==="component"&&(l.pageFilePath===e||l.componentName===t)),o=s.filter(l=>l.directImports.length===1&&l.directImports[0]===e&&nt(l.directImports[0])===t);if(o.length===1){const l=o[0].scenarios,c=[...a];for(const d of l)c.some(u=>u.slug===d.slug)||c.push(d);return c}return a}function Gt(e){const t=[];for(const r of e.split("/"))r===""||r==="."||(r===".."?t.pop():t.push(r));return t.join("/")}function Ti(e){const t=new Map;for(const[r,s]of Object.entries(e)){const a=Gt(r),o=nt(a),l=Tt(a,o);t.has(l)||t.set(l,{hash:l,filePath:a,entityName:o,imports:s.imports.map(Gt),importedBy:s.importedBy.map(Gt)})}return t}function Pi(e,t){if(!e)return null;const r=Gt(t);for(const s of e.values())if(s.filePath===r)return s;return null}function $s(e,t){if(!e)return[];const r=[];for(const s of t){const a=Pi(e,s);a&&r.push(a)}return r}function Di(e,t){return e.find(r=>r.pageFilePath===t)??null}function _s(e){const t=e.split("/"),r=t.pop()??e,s=t.join("/");return{fileName:r,dirPath:s}}function Ai({displayName:e,entity:t,isNavigable:r}){return n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("span",{className:"text-lg font-semibold text-[var(--text-secondary)]",children:e}),t?n.jsx("span",{className:"rounded bg-[var(--bg-input)] px-1.5 py-0.5 font-mono text-[9px] text-[var(--text-dim)]",children:t.hash.slice(0,8)}):null,r?n.jsx("span",{className:"ml-auto text-[10px] text-[var(--text-dim)]",children:"→"}):null]})}function Li({scenarios:e,onSelectScenario:t}){return e.length===0?n.jsx("p",{className:"mt-1 text-[10px] text-[var(--text-dim)]",children:"No scenarios"}):n.jsxs("div",{className:"mt-2 flex flex-row gap-1.5",children:[e.slice(0,4).map(r=>{const s=r.screenshotPaths[0]??null;return n.jsxs("button",{type:"button",onClick:a=>{a.stopPropagation(),t(r.slug)},className:"flex w-[192px] shrink-0 flex-col gap-1 transition",children:[n.jsx("div",{className:"rounded border border-[var(--border-subtle)] bg-[var(--bg-card)] transition hover:border-[var(--border-default)]",children:s?n.jsx("img",{src:We(s),alt:r.name,className:"h-[120px] w-[192px] rounded object-cover object-top",onError:a=>{a.currentTarget.style.visibility="hidden"}}):n.jsx("div",{className:"flex h-[120px] w-[192px] items-center justify-center rounded",children:n.jsx("span",{className:"text-[8px] text-[var(--text-dim)]",children:"--"})})}),n.jsx("span",{className:"w-full truncate text-center text-[10px] text-[var(--text-secondary)]",children:r.name})]},r.slug)}),e.length>4&&n.jsx("div",{className:"flex h-[120px] items-center px-1",children:n.jsxs("span",{className:"text-[10px] text-[var(--text-dim)]",children:["+",e.length-4]})})]})}function Mi({importPath:e,entity:t,scenarios:r,onNavigate:s,onSelectScenario:a}){const{fileName:o,dirPath:l}=_s(e),c=(t==null?void 0:t.entityName)??o.replace(/\.[^.]+$/,"");return n.jsxs("div",{role:s?"button":void 0,tabIndex:s?0:void 0,onClick:s??void 0,onKeyDown:s?d=>{(d.key==="Enter"||d.key===" ")&&s()}:void 0,className:`rounded-lg border border-[var(--border-subtle)] bg-[var(--bg-card)] p-3 transition hover:border-[var(--border-default)] ${s?"cursor-pointer":""}`,children:[n.jsx(Ai,{displayName:c,entity:t,isNavigable:s!==null}),n.jsxs("p",{className:"mt-0.5 font-mono text-[10px] text-[var(--text-dim)]",children:[l,"/"]}),n.jsx(Li,{scenarios:r,onSelectScenario:a})]})}function Ii(){return n.jsx("p",{className:"py-4 text-center text-xs text-[var(--text-dim)]",children:"No dependencies found"})}function Fi({directImports:e,entityLookup:t,allScenarios:r,routeEntities:s,onNavigateToRoute:a,onNavigateToEntity:o,onSelectScenario:l}){const c=i.useMemo(()=>$s(t,e),[t,e]);return e.length===0?n.jsx(Ii,{}):n.jsx("div",{className:"grid grid-cols-1 gap-1",children:e.map(d=>{const u=c.find(b=>b.filePath===d)??null,f=(u==null?void 0:u.entityName)??nt(d),p=Ri({importPath:d,derivedName:f,allScenarios:r??[],routeEntities:s??[]}),m=Di(s??[],d),h=Tt(d,f),j=m?()=>a(m.route):o?()=>o(h):null;return n.jsx(Mi,{importPath:d,entity:u,scenarios:p,onNavigate:j,onSelectScenario:l},d)})})}function Oi(e,t,r){const s=new Set,a=e.replace(/\.(ts|tsx)$/,"");s.add(`${a}.test.ts`),s.add(`${a}.test.tsx`);const o=t.get(e);if(o!=null&&o.importedBy)for(const c of o.importedBy)/\.test\.(ts|tsx)$/.test(c)&&s.add(c);return r.flatMap(c=>c.tests).filter(c=>s.has(c.file))}function Bi({status:e}){return e==="passed"?n.jsx("span",{className:"mt-0.5 text-xs text-[var(--accent-green)]",children:"✓"}):e==="failed"?n.jsx("span",{className:"mt-0.5 text-xs text-[var(--accent-red)]",children:"✗"}):n.jsx("span",{className:"mt-0.5 text-xs text-[var(--text-dim)]",children:"○"})}function $i({test:e}){const t=e.description.length>0;return n.jsxs("div",{className:"flex items-start gap-2 py-1",children:[n.jsx(Bi,{status:e.status}),n.jsx("div",{children:t?n.jsxs(n.Fragment,{children:[n.jsx("p",{className:"text-sm text-[var(--text-secondary)]",children:e.description}),n.jsx("p",{className:"font-mono text-xs text-[var(--text-dim)]",children:e.key})]}):n.jsxs(n.Fragment,{children:[n.jsx("p",{className:"text-sm text-[var(--text-secondary)]",children:e.key}),n.jsx("p",{className:"text-xs italic text-[var(--text-dim)]",children:"no description"})]})})]})}function _i({importPath:e,entityName:t,tests:r,onNavigate:s}){const{dirPath:a}=_s(e);return n.jsxs("div",{role:s?"button":void 0,tabIndex:s?0:void 0,onClick:s??void 0,onKeyDown:s?o=>{(o.key==="Enter"||o.key===" ")&&s()}:void 0,className:`rounded-lg border border-[var(--border-subtle)] bg-[var(--bg-card)] p-3 transition hover:border-[var(--border-default)] ${s?"cursor-pointer":""}`,children:[n.jsx("p",{className:"text-sm font-medium text-[var(--text-primary)]",children:t}),n.jsxs("p",{className:"mt-0.5 font-mono text-[10px] text-[var(--text-dim)]",children:[a,"/"]}),n.jsx("div",{className:"mt-2",children:r.length>0?n.jsx("div",{className:"space-y-0.5",children:r.map((o,l)=>n.jsx($i,{test:o},`${o.file}:${o.key??o.line??l}`))}):n.jsx("p",{className:"text-xs text-[var(--text-dim)] italic",children:"No tests"})})]})}function zi(){return n.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[n.jsx("p",{className:"text-sm text-[var(--text-muted)]",children:"No function imports found"}),n.jsx("p",{className:"mt-1 text-xs text-[var(--text-dim)]",children:"This component only imports other components"})]})}function Hi({functionImports:e,entityLookup:t,testGroups:r,onNavigateToEntity:s}){const a=i.useMemo(()=>$s(t,e),[t,e]);return e.length===0?n.jsx(zi,{}):n.jsx("div",{className:"grid grid-cols-1 gap-1",children:e.map(o=>{const l=a.find(f=>f.filePath===o)??null,c=(l==null?void 0:l.entityName)??nt(o),d=Oi(o,t,r),u=s?()=>s(Tt(o,c)):null;return n.jsx(_i,{importPath:o,entityName:c,tests:d,onNavigate:u},o)})})}function Wi({activeTab:e,routeEntity:t,componentImports:r,functionImports:s,testGroups:a,selectedSlug:o,entityLookup:l,allScenarios:c,routeEntities:d,onSelectScenario:u,onNavigateToRoute:f,onNavigateToEntity:p,onScenariosChanged:m}){return n.jsxs("div",{className:"flex-1 overflow-auto px-5 py-4",children:[e==="scenarios"&&n.jsx(Bs,{scenarios:t.scenarios,selectedSlug:o,onSelectScenario:u,onScenariosChanged:m}),e==="components"&&n.jsx(Fi,{directImports:r,entityLookup:l,allScenarios:c,routeEntities:d,onNavigateToRoute:f,onNavigateToEntity:p,onSelectScenario:u}),e==="functions"&&n.jsx(Hi,{functionImports:s,entityLookup:l,testGroups:a,onNavigateToEntity:p})]})}function Vi({displayName:e,pageFilePath:t,app:r=null,routeEntity:s=null,navContext:a=tt}){return n.jsxs("div",{className:"px-5 py-4",children:[n.jsx("div",{className:"mb-2",children:n.jsx(rr,{apps:a.apps,selectedApp:r,selectedRouteEntity:s,isSingleApp:a.isSingleApp,onSelectApps:a.onSelectApps,onSelectApp:a.onSelectApp,onSelectRoute:a.onSelectRoute})}),n.jsx("h2",{className:"text-xl font-medium text-[var(--text-primary)]",children:e}),t?n.jsx("p",{className:"mt-1 font-mono text-xs text-[var(--text-dim)]",children:t}):null]})}function Ui({activeTab:e,onTabChange:t,scenarioCount:r,componentCount:s,functionCount:a}){const o=[{key:"scenarios",label:"Scenarios",count:r},{key:"components",label:"Components",count:s},{key:"functions",label:"Functions",count:a}];return n.jsx("div",{className:"flex w-full border-t border-b border-[var(--border-default)]",children:o.map(l=>n.jsxs("button",{onClick:()=>t(l.key),className:`cursor-pointer px-4 py-2 font-mono text-xs font-medium uppercase tracking-wider transition border-b-2 ${e===l.key?"text-[var(--accent-active)] border-[var(--accent-active)]":"text-[var(--text-dim)] border-transparent hover:text-[var(--text-muted)]"}`,type:"button",children:[l.label," (",l.count,")"]},l.key))})}function Ki({app:e=null,navContext:t=tt,routeEntity:r,selectedSlug:s,entityLookup:a,allScenarios:o,routeEntities:l,testGroups:c,onSelectScenario:d,onNavigateToRoute:u,onNavigateToEntity:f,onScenariosChanged:p}){const[m,h]=i.useState("scenarios"),{componentImports:j,functionImports:b}=i.useMemo(()=>Si(r.directImports),[r.directImports]);return n.jsxs("div",{className:"flex flex-col",children:[n.jsx(Vi,{app:e,navContext:t,routeEntity:r,displayName:r.displayName,pageFilePath:r.pageFilePath}),n.jsx(Ei,{layoutChain:r.layoutChain??[],onNavigateToEntity:f}),n.jsx(Ui,{activeTab:m,onTabChange:h,scenarioCount:r.scenarios.length,componentCount:j.length,functionCount:b.length}),n.jsx(Wi,{activeTab:m,routeEntity:r,componentImports:j,functionImports:b,testGroups:c,selectedSlug:s,entityLookup:a,allScenarios:o,routeEntities:l,onSelectScenario:d,onNavigateToRoute:u,onNavigateToEntity:f,onScenariosChanged:p})]})}function jn(e){const t=Xo(e);if(t)return{selectedAppDir:t,selectedEntityHash:null};const r=qo(e);return r?{selectedAppDir:null,selectedEntityHash:r}:{selectedAppDir:null,selectedEntityHash:null}}function Nn(e){return`/apps/${e}`}function Gi(e){return`/entities/${e}`}function Bn(e){return e.pageFilePath?Tt(e.pageFilePath,nt(e.pageFilePath)):null}function zs(e){const t=Bn(e);return t===null?null:Gi(t)}function Hs({href:e,onNavigate:t,children:r,...s}){return n.jsx("a",{...s,href:e,onClick:a=>{a.button===0&&!a.metaKey&&!a.ctrlKey&&!a.shiftKey&&!a.altKey&&(a.preventDefault(),t())},children:r})}function Yi({scenario:e,onSelect:t}){const r=e.screenshotPaths[0]??null,[s,a]=i.useState(!1),o=r&&!s;return n.jsxs("button",{type:"button",onClick:t,className:`relative text-left w-full${t?" cursor-pointer group/thumb":""}`,children:[o?n.jsx("img",{src:We(r),alt:e.name,className:"aspect-[16/10] w-full rounded border border-[var(--border-subtle)] bg-[var(--bg-card)] object-cover object-top transition group-hover/thumb:border-[var(--text-dim)]",onError:()=>a(!0)}):n.jsx("div",{className:"aspect-[16/10] w-full rounded border border-[var(--border-subtle)] bg-[var(--bg-card)] flex items-center justify-center transition group-hover/thumb:border-[var(--text-dim)]",children:n.jsx("span",{className:"text-[10px] text-[var(--text-dim)]",children:"No preview"})}),e.dimensions.length>0?n.jsx("span",{className:"absolute bottom-1 right-1 rounded bg-black/60 px-1 py-0.5 text-[8px] text-white",children:e.dimensions[0]}):null,n.jsx("p",{className:"mt-1 truncate text-[10px] text-[var(--text-dim)]",children:e.name})]})}function Ji({routeEntity:e,onSelectRoute:t,onSelectScenario:r}){const s=e.scenarios.length,a=zs(e),o="group flex w-full cursor-pointer items-center gap-2 text-left",l=n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-sm font-medium text-[var(--text-secondary)] group-hover:text-[var(--text-primary)] transition",children:e.displayName}),n.jsx("span",{className:"font-mono text-xs text-[var(--text-dim)]",children:e.route}),s>0?n.jsxs("span",{className:"text-xs text-[var(--text-dim)]",children:["[",s,"]"]}):null,n.jsx("span",{className:"ml-auto text-xs text-[var(--text-dim)] group-hover:text-[var(--text-muted)] transition",children:"›"})]});return n.jsxs("div",{className:"mb-4",children:[a?n.jsx(Hs,{href:a,onNavigate:()=>t(e.route),className:o,children:l}):n.jsx("button",{onClick:()=>t(e.route),className:o,type:"button",children:l}),s>0?n.jsx("div",{className:"mt-2 grid grid-cols-3 gap-2",children:e.scenarios.map(c=>n.jsx(Yi,{scenario:c,onSelect:r?()=>r(c.slug):void 0},c.slug))}):n.jsx("p",{className:"mt-1 text-[10px] text-[var(--text-dim)]",children:"No scenarios yet"})]})}function Xi(){return n.jsx("div",{className:"px-5 py-8 text-center text-[var(--text-dim)]",children:"No routes discovered yet."})}function qi(){return n.jsx("div",{className:"mb-3",children:n.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-[var(--text-dim)]",children:"Pages"})})}function Qi({routeEntities:e,onSelectRoute:t,onSelectScenario:r}){return e.length===0?n.jsx(Xi,{}):n.jsxs("div",{className:"px-5 py-5",children:[n.jsx(qi,{}),n.jsx("div",{children:e.map(s=>n.jsx(Ji,{routeEntity:s,onSelectRoute:t,onSelectScenario:r},s.route))})]})}function Zi({feature:e,passed:t,failed:r,total:s}){return n.jsxs("div",{className:"px-5 py-2 flex items-center gap-3",children:[n.jsx("span",{className:"text-sm font-medium text-[var(--text-primary)]",children:e}),n.jsxs("span",{className:"text-xs text-[var(--text-dim)]",children:[s," test",s!==1?"s":""]}),s>0&&n.jsxs("span",{className:`text-xs font-medium ${r>0?"text-[var(--accent-red)]":"text-[var(--accent-green)]"}`,children:[t,"/",s]})]})}function el({test:e}){const t=(e.description??"").length>0,r=e.status==="passed"?"text-[var(--accent-green)]":e.status==="failed"?"text-[var(--accent-red)]":"text-[var(--text-dim)]",s=e.status==="passed"?"✓":e.status==="failed"?"✗":"○";return n.jsxs("div",{className:"flex items-start gap-2 py-1 px-3",children:[n.jsx("span",{className:`text-xs leading-5 ${r}`,children:s}),n.jsx("div",{className:"min-w-0",children:t?n.jsxs(n.Fragment,{children:[n.jsx("p",{className:"text-xs text-[var(--text-secondary)] truncate",children:e.description}),n.jsx("p",{className:"font-mono text-[10px] text-[var(--text-dim)] truncate",children:e.key})]}):n.jsx("p",{className:"text-xs text-[var(--text-secondary)] truncate",children:e.key})})]})}function tl({groups:e}){return e.length===0?n.jsx("div",{className:"px-5 py-8 text-center text-[var(--text-dim)]",children:"No tests found."}):n.jsx("div",{className:"py-3",children:e.map(t=>{const r=t.tests.filter(o=>o.status==="passed").length,s=t.tests.filter(o=>o.status==="failed").length,a=t.tests.length;return n.jsxs("div",{className:"mb-1",children:[n.jsx(Zi,{feature:t.feature,passed:r,failed:s,total:a}),n.jsx("div",{className:"px-5 pb-2",children:t.tests.map((o,l)=>n.jsx(el,{test:o},`${o.file}-${o.key??o.line??l}`))})]},t.feature)})})}function nl({app:e=null,navContext:t=tt,isWeb:r,routeEntities:s,routesLoading:a,routesError:o,selectedEntityHash:l,selectedRouteEntity:c,testGroups:d,selectedSlug:u,entityLookup:f,allScenarios:p,onSelectScenario:m,onSelectRoute:h,onSelectEntity:j,onBackToRoutes:b,onScenariosChanged:g}){const w=ai(l&&!c?l:null);return r?a?n.jsx(Fr,{}):o?n.jsx(yn,{message:o}):c?n.jsx(Ki,{app:e,navContext:t,routeEntity:c,selectedSlug:u,entityLookup:f,allScenarios:p,routeEntities:s,testGroups:d,onSelectScenario:m,onNavigateToRoute:h,onNavigateToEntity:j,onScenariosChanged:g}):l?w.status==="loading"||w.status==="idle"?n.jsx(Fr,{}):w.status==="not-found"?n.jsx(yn,{message:"Entity not found. The dependency graph may need to be refreshed."}):w.status==="error"?n.jsx(yn,{message:w.message}):n.jsx(Ci,{app:e,navContext:t,routeEntity:c,entity:w.entity,selectedSlug:u,onSelectScenario:m,onNavigateToEntity:j??(()=>{}),onScenariosChanged:g}):n.jsx(Qi,{routeEntities:s,onSelectRoute:h,onSelectScenario:m}):n.jsx(tl,{groups:d})}function rl({app:e,showDetail:t,navContext:r=tt,stats:s,testsLoading:a,testsRefreshing:o,onRunTests:l,currentRunner:c}){return t?null:n.jsxs("div",{className:"px-5 py-4 border-b border-[var(--border-default)]",children:[n.jsx("div",{className:"mb-2",children:n.jsx(rr,{apps:r.apps,selectedApp:e,selectedRouteEntity:null,isSingleApp:r.isSingleApp,onSelectApps:r.onSelectApps,onSelectApp:r.onSelectApp,onSelectRoute:r.onSelectRoute})}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("h2",{className:"text-lg font-medium text-[var(--text-primary)]",children:e.name}),n.jsx(Os,{type:e.type})]}),e.description?n.jsx("p",{className:"text-sm text-[var(--text-muted)] mt-1",children:e.description}):null,s?n.jsx("div",{className:"mt-3",children:n.jsx(Fs,{tests:s.tests,loading:a,refreshing:o,onRunTests:l,currentRunner:c})}):null]})}function sr({coverage:e,prefix:t,testId:r,className:s,onClick:a}){if(!e||e.totalLines===0)return null;const o=`${Math.round(e.percent)}% coverage`,l=n.jsxs(n.Fragment,{children:[t??"",o]}),c=`${e.hitLines}/${e.totalLines} lines covered`;return a?n.jsx("span",{role:"button",tabIndex:0,className:s??"text-xs font-medium text-[var(--accent-active)] hover:underline cursor-pointer","data-testid":r??"coverage-badge",title:c,onClick:d=>{d.stopPropagation(),a()},onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&(d.stopPropagation(),d.preventDefault(),a())},children:l}):n.jsx("span",{className:s??"text-xs font-medium text-[var(--text-secondary)]","data-testid":r??"coverage-badge",title:c,children:l})}function sl({projectTitle:e,coverage:t,onCoverageClick:r}){const s=typeof e=="string"&&e.length>0,a=!!(t&&t.totalLines>0);return!s&&!a?null:n.jsxs("div",{className:"px-5 pt-5 pb-3 flex items-center justify-between",children:[s?n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)]",children:e}):n.jsx("span",{}),n.jsx(sr,{coverage:t,testId:"app-detail-coverage",onClick:r})]})}function al({app:e,navContext:t=tt,routeEntities:r,routesLoading:s,routesError:a,selectedEntityHash:o,selectedRouteEntity:l,testGroups:c,selectedSlug:d,entityLookup:u,allScenarios:f,onSelectScenario:p,onSelectRoute:m,onSelectEntity:h,onBackToRoutes:j,onScenariosChanged:b,projectTitle:g,coverage:w,showProjectBand:v,onCoverageClick:x,stats:y,testsLoading:N,testsRefreshing:C,onRunTests:S,currentRunner:k}){const R=e.type==="web",E=!!v&&!l;return n.jsxs("div",{children:[E?n.jsx(sl,{projectTitle:g,coverage:w,onCoverageClick:x}):null,n.jsx(rl,{app:e,showDetail:!!(l||o),navContext:t,stats:y,testsLoading:N,testsRefreshing:C,onRunTests:S,currentRunner:k}),n.jsx(nl,{app:e,navContext:t,isWeb:R,routeEntities:r,routesLoading:s,routesError:a,selectedEntityHash:o??null,selectedRouteEntity:l,testGroups:c,selectedSlug:d,entityLookup:u,allScenarios:f,onSelectScenario:p,onSelectRoute:m,onSelectEntity:h,onBackToRoutes:j,onScenariosChanged:b})]})}function Ws(e){const t=new Date(e);if(isNaN(t.getTime()))return e;const r=new Date,s=r.getTime()-t.getTime(),a=Math.floor(s/6e4),o=Math.floor(s/36e5),l=Math.floor(s/864e5);return a<1?"just now":a<60?`${a}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:t.toLocaleDateString("en-US",{month:"short",day:"numeric",year:t.getFullYear()!==r.getFullYear()?"numeric":void 0})}function ol(e){switch(e){case"feature":return"text-blue-400";case"fix":return"text-red-400";case"refactor":return"text-purple-400";case"milestone":return"text-yellow-400";default:return"text-gray-400"}}function uv(e){let t=0,r=0,s=0;for(const a of e)a.status==="added"?t++:a.status==="deleted"?s++:r++;return{added:t,modified:r,deleted:s}}function il({total:e,passed:t,failed:r}){if(e===0)return null;const s=r>0?"text-[var(--accent-red)]":"text-[var(--accent-green)]";return n.jsxs("span",{className:`text-xs ${s}`,children:[t,"/",e," passed"]})}const ll=192;function Vs({children:e,variant:t="compact",maxHeight:r=ll}){const s=i.useRef(null),[a,o]=i.useState(!1),[l,c]=i.useState(!1);return i.useEffect(()=>{const d=s.current;if(!d)return;const u=()=>c(d.scrollHeight>r);u();const f=new ResizeObserver(u);return f.observe(d),()=>f.disconnect()},[e,r]),n.jsxs("div",{children:[n.jsxs("div",{ref:s,style:{maxHeight:a?"none":`${r}px`,overflow:"hidden",position:"relative"},children:[n.jsx(et,{variant:t,children:e}),!a&&l&&n.jsx("div",{style:{position:"absolute",bottom:0,left:0,right:0,height:"2rem",background:"linear-gradient(transparent, var(--bg-card))",pointerEvents:"none"}})]}),l&&n.jsx("button",{onClick:()=>o(d=>!d),className:"text-xs cursor-pointer mt-1",style:{color:"var(--accent-blue)",background:"none",border:"none",padding:0},children:a?"Show less":"Show more"})]})}function cl({screenshots:e}){return e.length===0?null:n.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((t,r)=>n.jsxs("div",{className:"text-center",children:[t.screenshotPath?n.jsx("img",{src:We(t.screenshotPath),alt:t.name,className:"h-16 w-24 rounded border border-[var(--border-default)] object-cover"}):n.jsx("div",{className:"flex h-16 w-24 items-center justify-center rounded border border-dashed border-[var(--border-default)] text-xs text-[var(--text-dim)]",children:"No shot"}),n.jsx("p",{className:"mt-0.5 text-xs text-[var(--text-dim)] truncate w-24",children:t.name})]},`${t.screenshotPath??"missing"}:${t.name}:${r}`))})}const dl={1:"Plan",2:"Explore",3:"Confirm",4:"Prepare",5:"Seed Data",6:"Live Preview Loop",7:"Verify Prototype",8:"Confirm Mode",9:"Demo",10:"Deconstruct",11:"Extract TDD",12:"Glossary",13:"Dependency Graph",14:"Isolation Routes",15:"Component Scenarios",16:"App Scenarios",17:"Present",18:"Reconcile",19:"Finalize",20:"Journal",21:"Pre-Commit Sync",22:"Commit",23:"Push",24:"Feature Complete"},ul={1:"Plan",2:"Explore",3:"Confirm Plan",4:"Prepare",5:"Prototype",6:"Confirm Mode",7:"Demo",8:"Deconstruct",9:"Extract TDD",10:"Glossary",11:"Dependency Graph",12:"Present",13:"Reconcile",14:"Finalize",15:"Journal",16:"Pre-Commit Sync",17:"Commit",18:"Push",19:"Feature Complete"},fl={1:"Plan the feature and confirm the approach with the user before writing any code.",2:"Map out all the files you'll need to read or modify; check for reference implementations.",3:"Repeat the plan back to the user and gate on explicit approval before any code is written.",4:"Prepare the project environment and dependencies for prototyping.",5:"Wire up API routes and seed the database with realistic, demo-rich data.",6:"Iterate on the prototype with the live preview — navigate, edit, verify.",7:"Verify the prototype's routes, images, and client errors before presenting.",8:"Confirm or switch the workflow mode before the demo.",9:"Present the live preview and get user approval to proceed.",10:"Read the code and plan all component and function extractions.",11:"Extract components and functions via TDD; cover library functions with multiple tests.",12:"Register every new test and glossary entry produced in the prior step.",13:"Rebuild the dependency graph after extraction.",14:"Create isolation routes for every visual component.",15:"Register and capture component-level scenarios for every visual component.",16:"Create app-level scenarios that show full pages with realistic data.",17:"Final approval gate — recapture screenshots and present a summary of all work to the user.",18:"Run the audit gate, reconcile any registry/glossary drift until clean.",19:"Finalize the session — run the full suite once.",20:"Create or update the journal entry documenting what was built.",21:"Sync local state with the remote so the next commit lands on a merged tree.",22:"Commit all changes to git.",23:"Push the branch to the remote repository.",24:"Fire the feature-complete modal — the cycle ends here."},pl={1:"Plan the feature and confirm the approach with the user before writing any code.",2:"Map out all the files you'll need to read or modify; check for reference implementations.",3:"Repeat the plan back to the user and gate on explicit approval before any code is written.",4:"Prepare the project environment.",5:"Build the feature. Tests come at the Deconstruct cluster.",6:"Confirm or switch the workflow mode before the demo.",7:"Show the prototype results and gate on the user's yes/iterate decision before any verification work.",8:"Read the code and plan all function/method/helper extractions.",9:"Extract functions/methods/helpers via TDD; every change must have a red-if-reverted test.",10:"Register every new test and glossary entry produced in the prior step.",11:"Rebuild the dependency graph after extraction.",12:"Present the /results page with architecture diagram, tests, and changed files.",13:"Run the audit gate, reconcile any registry/glossary drift until clean.",14:"Finalize the session — run the full suite once.",15:"Author the session narrative against post-Verify code, then create the journal entry.",16:"Sync local state with the remote so the next commit lands on a merged tree.",17:"Commit all changes to git.",18:"Push the branch to the remote repository.",19:"Fire the feature-complete modal — the cycle ends here."},ml=24,Us=19;function $e(e){return e==="backend"?"backend":"ui"}function ar(e,t){return($e(t)==="backend"?ul:dl)[e]??"?"}function xl(e,t){return($e(t)==="backend"?pl:fl)[e]??""}function hl(e){return $e(e)==="backend"?Us:ml}function gl(e){return $e(e)==="backend"?"Backend Flow":"UI Flow"}function Ks(e,t){const r=$e(t);return{description:xl(e,r),label:ar(e,r),prefix:gl(r),totalSteps:hl(r)}}const vl={1:"Understanding your idea",2:"Looking through your project",3:"Confirming the approach with you",4:"Preparing your workspace",5:"Adding sample data",6:"Building your app",7:"Checking the prototype",8:"Confirming the next step with you",9:"Showing you the result",10:"Reading the code carefully",11:"Adding tests",12:"Documenting the building blocks",13:"Mapping connections in your code",14:"Setting up isolation routes",15:"Capturing component snapshots",16:"Capturing whole-page snapshots",17:"Showing you the final review",18:"Reconciling everything",19:"Finalizing the build",20:"Writing a journal entry",21:"Syncing with the latest",22:"Saving your changes",23:"Pushing your work",24:"All done"},bl={1:"Understanding your idea",2:"Looking through your project",3:"Confirming the approach with you",4:"Preparing your workspace",5:"Building your app",6:"Confirming the next step with you",7:"Showing you the result",8:"Reading the code carefully",9:"Adding tests",10:"Documenting the building blocks",11:"Mapping connections in your code",12:"Showing you the final review",13:"Reconciling everything",14:"Finalizing the build",15:"Writing a journal entry",16:"Syncing with the latest",17:"Saving your changes",18:"Pushing your work",19:"All done"},yl=[{phaseId:"understand",phaseLabel:"Understanding your idea",phaseSteps:[1,2,3]},{phaseId:"setup",phaseLabel:"Setting things up",phaseSteps:[4,5]},{phaseId:"build",phaseLabel:"Building your app",phaseSteps:[6,7,8,9]},{phaseId:"tidy",phaseLabel:"Tidying the code so it stays maintainable",phaseSteps:[10,11,12,13,14,15,16]},{phaseId:"review",phaseLabel:"Final review",phaseSteps:[17,18,19,20,21]},{phaseId:"save",phaseLabel:"Saving your work",phaseSteps:[22,23,24]}],wl=[{phaseId:"understand",phaseLabel:"Understanding your idea",phaseSteps:[1,2,3]},{phaseId:"setup",phaseLabel:"Setting things up",phaseSteps:[4]},{phaseId:"build",phaseLabel:"Building your app",phaseSteps:[5,6,7]},{phaseId:"tidy",phaseLabel:"Tidying the code so it stays maintainable",phaseSteps:[8,9,10,11]},{phaseId:"review",phaseLabel:"Final review",phaseSteps:[12,13,14,15,16]},{phaseId:"save",phaseLabel:"Saving your work",phaseSteps:[17,18,19]}];function jl(e,t){return($e(t)==="backend"?bl:vl)[e]??""}function Nl(e){return $e(e)==="backend"?wl:yl}function Cl({currentStep:e}){const t=Array.from({length:Us},(r,s)=>s+1);return n.jsx("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg p-4 overflow-x-auto",children:n.jsx("div",{className:"flex items-center gap-1 min-w-max",children:t.map((r,s)=>{const a=r<e,o=r===e,l=ar(r,"backend");return n.jsxs("div",{className:"flex items-center",children:[s>0&&n.jsx("div",{className:`w-4 h-px mx-0.5 ${a?"bg-[#005c75]":"bg-[var(--border-default)]"}`}),n.jsxs("div",{className:`flex items-center gap-1 px-2 py-1 rounded text-xs whitespace-nowrap ${o?"bg-[#005c75] text-white font-medium":a?"bg-[#e0f5f9] text-[#005c75] font-medium":"text-[var(--text-muted)]"}`,children:[a&&n.jsx("span",{className:"text-[10px]",children:"✓"}),o&&n.jsx("span",{className:"text-[10px]",children:"●"}),l]})]},r)})})})}function $n(e){if(e<1e3)return`${e}ms`;const t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;const r=Math.floor(t/60),s=(t%60).toFixed(0);return`${r}m ${s}s`}function Sl({stats:e}){const[t,r]=i.useState(!1);if(!e)return n.jsx("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg px-4 py-2 text-center","data-testid":"runner-stats-bar",children:n.jsx("span",{className:"text-xs text-[var(--text-muted)]",children:"No test results cached"})});const s=e.per_runner&&e.per_runner.length>1;return n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg px-4 py-2","data-testid":"runner-stats-bar",children:[n.jsxs("div",{className:`flex items-center justify-between ${s?"cursor-pointer":""}`,onClick:()=>s&&r(!t),children:[n.jsxs("div",{className:"flex items-center gap-4",children:[n.jsxs("span",{className:"text-sm font-medium text-[var(--text-primary)]","data-testid":"runner-stats-total",children:[e.total," tests"]}),e.passed>0&&n.jsxs("span",{className:"text-xs text-green-600 font-medium","data-testid":"runner-stats-passed",children:[e.passed," passed"]}),e.failed>0&&n.jsxs("span",{className:"text-xs text-red-500 font-medium","data-testid":"runner-stats-failed",children:[e.failed," failed"]}),e.ignored>0&&n.jsxs("span",{className:"text-xs text-[var(--text-muted)] font-medium","data-testid":"runner-stats-ignored",children:[e.ignored," ignored"]}),e.duration_ms!=null&&n.jsx("span",{className:"text-xs text-[var(--text-muted)]","data-testid":"runner-stats-duration",children:$n(e.duration_ms)})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[e.runners.map(a=>n.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-[var(--bg-input)] text-[var(--text-secondary)] rounded font-mono","data-testid":"runner-badge",children:a},a)),s&&n.jsx("span",{className:"text-xs text-[var(--text-muted)] ml-1",children:t?"▲":"▼"})]})]}),t&&s&&n.jsx("div",{className:"mt-2 pt-2 border-t border-[var(--border-subtle)] space-y-1","data-testid":"per-runner-breakdown",children:e.per_runner.map(a=>n.jsxs("div",{className:"flex items-center justify-between text-xs","data-testid":"per-runner-row",children:[n.jsx("span",{className:"font-mono text-[var(--text-secondary)]",children:a.name}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsxs("span",{className:"text-[var(--text-muted)]",children:[a.total," tests"]}),a.passed>0&&n.jsxs("span",{className:"text-green-600",children:[a.passed," passed"]}),a.failed>0&&n.jsxs("span",{className:"text-red-500",children:[a.failed," failed"]}),a.ignored>0&&n.jsxs("span",{className:"text-[var(--text-muted)]",children:[a.ignored," ignored"]}),a.duration_ms!=null&&n.jsx("span",{className:"text-[var(--text-muted)]",children:$n(a.duration_ms)})]})]},a.name))})]})}function Gs({status:e}){switch(e){case"passing":return n.jsx("span",{className:"text-green-500 text-xs mt-0.5 shrink-0",children:"✓"});case"failing":return n.jsx("span",{className:"text-red-500 text-xs mt-0.5 shrink-0",children:"✗"});case"running":return n.jsx("span",{className:"text-blue-400 text-xs mt-0.5 shrink-0 animate-spin",children:"◠"});default:return n.jsx("span",{className:"text-gray-400 text-xs mt-0.5 shrink-0",children:"●"})}}function kl({narrative:e}){const t=e.changes.flatMap(l=>l.tests);if(t.length===0)return null;const r=t.filter(l=>l.verified===!0),s=t.filter(l=>l.verified===!1),a=r.filter(l=>l.status==="passing").length,o=r.filter(l=>l.status==="failing").length;return n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg overflow-hidden","data-testid":"tests-summary-card",children:[n.jsxs("div",{className:"px-4 py-2 border-b border-[var(--border-subtle)] bg-[var(--bg-input)] flex items-center justify-between",children:[n.jsx("h2",{className:"text-sm font-semibold text-[var(--text-primary)] m-0",children:"Tests"}),n.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[a>0&&n.jsxs("span",{className:"text-green-600 font-medium",children:[a," passing"]}),o>0&&n.jsxs("span",{className:"text-red-500 font-medium",children:[o," failing"]}),s.length>0&&n.jsxs("span",{className:"text-amber-600 font-medium","data-testid":"unverified-count",children:[s.length," unverified"]})]})]}),n.jsxs("div",{className:"p-3 space-y-1",children:[r.map(l=>n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Gs,{status:l.status}),n.jsx("span",{className:"text-xs text-[var(--text-secondary)] font-mono",children:l.name}),l.file&&n.jsx("span",{className:"text-[10px] text-[var(--text-muted)] font-mono",children:l.file})]},l.name)),s.length>0&&n.jsxs("div",{className:"mt-2 pt-2 border-t border-amber-200","data-testid":"unverified-tests",children:[n.jsx("div",{className:"text-[10px] font-medium text-amber-600 mb-1",children:"Unverified — not found in test files"}),s.map(l=>n.jsxs("div",{className:"flex items-center gap-2 opacity-50",children:[n.jsx("span",{className:"text-amber-500 text-xs",children:"?"}),n.jsx("span",{className:"text-xs text-[var(--text-muted)] font-mono line-through",children:l.name})]},l.name))]})]})]})}function El({narrative:e}){return n.jsxs("div",{className:"space-y-4",children:[n.jsx("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg p-4",children:n.jsx("p",{className:"text-sm text-[var(--text-primary)] leading-relaxed",children:e.summary})}),e.changes.map((t,r)=>n.jsx(Rl,{change:t},r))]})}function Rl({change:e}){const[t,r]=i.useState(!1),s=e.tests.filter(l=>l.verified!==!1),a=s.filter(l=>l.status==="passing").length,o=s.filter(l=>l.status==="failing").length;return n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg overflow-hidden","data-testid":"narrative-change-card",children:[n.jsx("div",{className:"p-4 cursor-pointer select-none",onClick:()=>r(!t),"data-testid":"narrative-change-header",children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("h3",{className:"text-sm font-semibold text-[var(--text-primary)] m-0",children:e.title}),n.jsxs("div",{className:"flex items-center gap-2",children:[t&&s.length>0&&n.jsxs("span",{className:"text-[10px] text-[var(--text-muted)]","data-testid":"collapsed-test-summary",children:[a>0&&n.jsxs("span",{className:"text-green-600",children:[a,"✓"]}),o>0&&n.jsxs("span",{className:"text-red-500 ml-1",children:[o,"✗"]})]}),n.jsx("span",{className:"text-[var(--text-muted)] text-xs",children:t?"▶":"▼"})]})]})}),!t&&n.jsxs("div",{className:"px-4 pb-4 -mt-2",children:[n.jsx("p",{className:"text-sm text-[var(--text-secondary)] m-0",children:e.description}),e.files.length>0&&n.jsx("div",{className:"mt-2 space-y-0.5",children:e.files.map(l=>n.jsx("div",{className:"text-xs text-[var(--text-muted)] font-mono",children:l},l))}),e.tests.length>0&&n.jsxs("div",{className:"mt-3 space-y-1.5",children:[s.map(l=>n.jsx(Tl,{test:l},l.name)),e.tests.some(l=>l.verified===!1)&&n.jsxs("div",{className:"text-[10px] text-amber-600 mt-1",children:[e.tests.filter(l=>l.verified===!1).length," test(s) not found in source files"]})]})]})]})}function Tl({test:e}){const[t,r]=i.useState(!1),s=e.status==="failing"&&e.failureMessage;return n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(Gs,{status:e.status}),n.jsxs("div",{className:"flex-1",children:[e.description&&n.jsx("div",{className:"text-xs text-[var(--text-secondary)] leading-relaxed",children:e.description}),n.jsx("div",{className:"text-[11px] text-[var(--text-muted)] font-mono",children:e.name}),e.file&&n.jsx("div",{className:"text-[10px] text-[var(--text-dim)] font-mono",children:e.file}),s&&n.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-600 mt-0.5 underline cursor-pointer",onClick:()=>r(!t),"data-testid":"toggle-failure-message",children:t?"Hide error":"Show error"})]})]}),s&&t&&n.jsx("div",{className:"mt-1 ml-5 p-2 bg-red-50 border border-red-200 rounded text-[11px] font-mono text-red-700 whitespace-pre-wrap overflow-x-auto","data-testid":"failure-message",children:e.failureMessage})]})}function Pl({step:e,fileCount:t,testCount:r}){return n.jsx("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg p-6 text-center",children:e<=2?n.jsx("p",{className:"text-sm text-[var(--text-muted)]",children:"Build will begin at the Prototype step."}):n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-sm text-[var(--text-secondary)]",children:"Building in progress..."}),n.jsxs("div",{className:"flex justify-center gap-6",children:[n.jsx(Br,{label:"Files Modified",value:t}),n.jsx(Br,{label:"Tests Modified",value:r,color:r>0?"green":void 0})]})]})})}function Br({label:e,value:t,color:r}){return n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:`text-lg font-bold ${r==="green"?"text-green-600":"text-[var(--text-primary)]"}`,children:t}),n.jsx("span",{className:"text-xs text-[var(--text-muted)]",children:e})]})}function or({status:e}){const t=e==="added"?"var(--accent-green)":e==="deleted"?"var(--accent-red)":"var(--accent-blue)",r=e==="added"?"+":e==="deleted"?"-":"~";return n.jsx("span",{className:"font-mono text-xs font-semibold",style:{color:t,minWidth:"0.75rem",textAlign:"center"},children:r})}const Dl=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/__tests__\//,/tests?\//];function Cn(e){return Dl.some(t=>t.test(e))}function Al({files:e,defaultCollapsed:t}){const[r,s]=i.useState(t),a=e.filter(d=>d.path&&Cn(d.path)),o=e.filter(d=>d.path&&d.path.endsWith(".rs")&&!Cn(d.path)),l=e.filter(d=>d.path&&(d.path.endsWith(".json")||d.path.endsWith(".toml")||d.path.endsWith(".lock")||d.path.endsWith(".txt"))),c=e.filter(d=>d.path&&!Cn(d.path)&&!d.path.endsWith(".rs")&&!d.path.endsWith(".json")&&!d.path.endsWith(".toml")&&!d.path.endsWith(".lock")&&!d.path.endsWith(".txt"));return n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg overflow-hidden","data-testid":"modified-files-section",children:[n.jsxs("div",{className:"px-4 py-2 border-b border-[var(--border-subtle)] bg-[var(--bg-input)] cursor-pointer select-none flex items-center justify-between",onClick:()=>s(!r),"data-testid":"modified-files-header",children:[n.jsxs("h2",{className:"text-sm font-semibold text-[var(--text-primary)] m-0",children:["Modified Files (",e.length,")"]}),n.jsx("span",{className:"text-[var(--text-muted)] text-xs",children:r?"▶":"▼"})]}),!r&&n.jsxs("div",{className:"divide-y divide-gray-100",children:[a.length>0&&n.jsx($t,{title:"Tests",files:a}),o.length>0&&n.jsx($t,{title:"Rust Source",files:o}),c.length>0&&n.jsx($t,{title:"Other Source",files:c}),l.length>0&&n.jsx($t,{title:"Configuration",files:l})]})]})}function $t({title:e,files:t}){return n.jsxs("div",{className:"p-3","data-testid":"file-group",children:[n.jsxs("div",{className:"text-xs font-medium text-[var(--text-secondary)] mb-1","data-testid":"file-group-title",children:[e," (",t.length,")"]}),n.jsx("div",{className:"space-y-0.5",children:t.map(r=>n.jsxs("div",{className:"text-xs text-[var(--text-secondary)] font-mono pl-4 flex items-center gap-1",children:[n.jsx(or,{status:r.status}),n.jsx("span",{children:r.path})]},r.path))})]})}const Ll=5e3,$r=50;function Ml(){const[e,t]=i.useState([]),[r,s]=i.useState(0),[a,o]=i.useState(null),[l,c]=i.useState(!0),[d,u]=i.useState(!1),[f,p]=i.useState(null),m=i.useRef("idle"),h=i.useRef([]),j=i.useRef(null);i.useEffect(()=>{h.current=e},[e]),i.useEffect(()=>{j.current=a},[a]);const b=i.useCallback(async()=>{if(m.current==="idle"){m.current="initial",c(!0),p(null);try{const v=await fetch(`/api/history?limit=${$r}`);if(!v.ok)throw new Error(`HTTP ${v.status}`);const x=await v.json();t(x.entries??[]),s(x.total??0),o(x.nextCursor??null),x.error&&p(x.error)}catch(v){p(v instanceof Error?v.message:"Failed to load history")}finally{c(!1),m.current="idle"}}},[]),g=i.useCallback(async()=>{var x;if(m.current!=="idle")return;const v=(x=h.current[0])==null?void 0:x.commit.sha;if(!v){await b();return}m.current="poll";try{const y=await fetch(`/api/history?since=${encodeURIComponent(v)}`);if(!y.ok)throw new Error(`HTTP ${y.status}`);const N=await y.json(),C=new Set(h.current.map(k=>k.commit.sha)),S=(N.entries??[]).filter(k=>!C.has(k.commit.sha));S.length>0&&(t(k=>[...S,...k]),s(k=>k+S.length))}catch(y){p(y instanceof Error?y.message:"Failed to poll history")}finally{m.current="idle"}},[b]),w=i.useCallback(async()=>{if(m.current!=="idle")return;const v=j.current;if(v){m.current="more",u(!0);try{const x=await fetch(`/api/history?limit=${$r}&before=${encodeURIComponent(v)}`);if(!x.ok)throw new Error(`HTTP ${x.status}`);const y=await x.json();t(N=>[...N,...y.entries??[]]),o(y.nextCursor??null),typeof y.total=="number"&&s(y.total)}catch(x){p(x instanceof Error?x.message:"Failed to load more commits")}finally{u(!1),m.current="idle"}}},[]);return i.useEffect(()=>{b();const v=setInterval(()=>{g()},Ll);return()=>clearInterval(v)},[b,g]),{rows:e,total:r,hasMore:a!==null,loading:l,loadingMore:d,error:f,loadMore:w,reload:b}}function Il({commit:e}){return n.jsxs("div",{className:"rounded-lg border px-4 py-3",style:{borderColor:"var(--border-default)",background:"var(--bg-card)"},children:[n.jsxs("div",{className:"flex items-center gap-2 text-xs",style:{color:"var(--text-dim)"},children:[n.jsx("span",{className:"font-mono uppercase tracking-wide",style:{color:"var(--text-muted)"},children:"commit"}),n.jsx("span",{className:"font-mono",style:{color:"var(--text-secondary)"},children:e.shortSha}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{children:Ws(e.timestamp)}),e.authorName&&n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{children:e.authorName})]})]}),n.jsx("p",{className:"mt-1 text-sm truncate",style:{color:"var(--text-primary)"},children:e.subject})]})}const Fl=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/__tests__\//,/tests?\//];function Ol(e){return e.filter(t=>Fl.some(r=>r.test(t.path)))}function Ys({entry:e,commit:t}){const r=Ol(e.modifiedFiles??[]);return n.jsxs("div",{className:"rounded-lg border",style:{borderColor:"var(--border-default)",background:"var(--bg-card)"},children:[n.jsxs("div",{className:"px-4 pt-4 pb-3",style:{borderBottom:"1px solid var(--border-subtle)"},children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("span",{className:`text-xs font-medium uppercase tracking-wide ${ol(e.type)}`,children:e.type}),n.jsx("span",{className:"text-xs",style:{color:"var(--text-dim)"},children:Ws(e.timestamp)}),t&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-xs",style:{color:"var(--text-dim)"},children:"·"}),n.jsx("span",{className:"font-mono text-xs",style:{color:"var(--text-secondary)"},children:t.shortSha}),t.authorName&&n.jsxs("span",{className:"text-xs",style:{color:"var(--text-dim)"},children:["· ",t.authorName]})]})]}),n.jsx("h3",{className:"text-sm font-semibold",style:{color:"var(--text-primary)"},children:e.title})]}),n.jsxs("div",{className:"px-4 py-3 flex flex-col gap-3",children:[e.userRequest&&n.jsxs("div",{children:[n.jsx("p",{className:"text-xs font-medium mb-1",style:{color:"var(--text-muted)"},children:"Prompt"}),n.jsx(Vs,{children:e.userRequest})]}),(e.scenarioScreenshots??[]).length>0&&n.jsxs("div",{children:[n.jsx("p",{className:"text-xs font-medium mb-1",style:{color:"var(--text-muted)"},children:"Screenshots"}),n.jsx(cl,{screenshots:e.scenarioScreenshots??[]})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("p",{className:"text-xs font-medium",style:{color:"var(--text-muted)"},children:"Tests"}),e.testResults&&n.jsx(il,{total:e.testResults.total,passed:e.testResults.passed,failed:e.testResults.failed})]}),r.length>0?n.jsx("ul",{className:"flex flex-col gap-0.5",children:r.map(s=>n.jsxs("li",{className:"flex items-center gap-1.5",children:[n.jsx(or,{status:s.status}),n.jsx("span",{className:"font-mono text-xs truncate",style:{color:"var(--text-secondary)"},children:s.path})]},s.path))}):n.jsx("p",{className:"text-xs",style:{color:"var(--text-dim)"},children:"No test files changed"})]})]})]})}function ir({children:e,testId:t}){return n.jsx("div",{className:"overflow-y-auto px-4 py-4",style:{maxHeight:"calc(100vh - 110px)"},"data-testid":t,children:e})}function Bl(){const{rows:e,total:t,hasMore:r,loading:s,loadingMore:a,error:o,loadMore:l}=Ml();if(s)return n.jsx("div",{className:"py-12 text-center text-[var(--text-muted)]",children:"Loading history..."});if(o&&e.length===0)return n.jsxs("div",{className:"py-12 text-center text-[var(--accent-red)]",children:["Failed to load history: ",o]});if(e.length===0)return n.jsxs("div",{className:"py-12 text-center text-[var(--text-dim)]",children:[n.jsx("p",{children:"No commits yet."}),n.jsx("p",{className:"mt-2 text-sm",children:"Commits and journal entries will appear here as you build features."})]});const c=Math.max(t,e.length);return n.jsxs(ir,{children:[n.jsxs("p",{className:"mb-3 text-xs",style:{color:"var(--text-dim)"},children:[e.length," of ",c," commit",c===1?"":"s"]}),n.jsx("div",{className:"flex flex-col gap-3",children:e.map(d=>d.entry?n.jsx(Ys,{entry:d.entry,commit:d.commit},d.commit.sha):n.jsx(Il,{commit:d.commit},d.commit.sha))}),r?n.jsx("div",{className:"mt-4 flex justify-center",children:n.jsx("button",{type:"button",onClick:()=>void l(),disabled:a,className:"rounded border border-[var(--border)] px-3 py-1 text-sm text-[var(--text-muted)] hover:bg-[var(--bg-subtle)] disabled:opacity-50",children:a?"Loading...":"Load older commits"})}):null]})}const Sn={sound:"soft-double-tap",systemNotification:!0,idleOnStop:!1,idleOnNotification:!0},$l=[{id:"soft-double-tap",label:"Soft double tap"},{id:"gentle-chime",label:"Gentle chime"},{id:"warm-ding",label:"Warm ding"},{id:"mellow-two-tone",label:"Mellow two-tone"},{id:"triangle-bell",label:"Triangle bell"},{id:"off",label:"No sound"}],Js="codeyam-editor-notifications";function _l(){try{const e=localStorage.getItem(Js);if(!e)return Sn;const t=JSON.parse(e);return{...Sn,...t}}catch{return Sn}}function zl(e){localStorage.setItem(Js,JSON.stringify(e))}const Hl={"soft-double-tap":e=>([0,.12].forEach(t=>{const r=e.createOscillator(),s=e.createGain();r.connect(s),s.connect(e.destination),r.type="sine",r.frequency.value=392,s.gain.setValueAtTime(.25,e.currentTime+t),s.gain.exponentialRampToValueAtTime(.01,e.currentTime+t+.1),r.start(e.currentTime+t),r.stop(e.currentTime+t+.1)}),{count:2,longestStopSec:.22}),"gentle-chime":e=>{const t=e.createOscillator(),r=e.createGain();return t.connect(r),r.connect(e.destination),t.type="sine",t.frequency.setValueAtTime(523,e.currentTime),t.frequency.setValueAtTime(659,e.currentTime+.15),r.gain.setValueAtTime(.3,e.currentTime),r.gain.exponentialRampToValueAtTime(.01,e.currentTime+.4),t.start(),t.stop(e.currentTime+.4),{count:1,longestStopSec:.4}},"warm-ding":e=>{const t=e.createOscillator(),r=e.createGain();return t.connect(r),r.connect(e.destination),t.type="sine",t.frequency.value=330,r.gain.setValueAtTime(.35,e.currentTime),r.gain.exponentialRampToValueAtTime(.01,e.currentTime+.6),t.start(),t.stop(e.currentTime+.6),{count:1,longestStopSec:.6}},"mellow-two-tone":e=>{const t=e.createOscillator(),r=e.createGain();return t.connect(r),r.connect(e.destination),t.type="sine",t.frequency.setValueAtTime(294,e.currentTime),t.frequency.setValueAtTime(440,e.currentTime+.18),r.gain.setValueAtTime(.3,e.currentTime),r.gain.exponentialRampToValueAtTime(.01,e.currentTime+.5),t.start(),t.stop(e.currentTime+.5),{count:1,longestStopSec:.5}},"triangle-bell":e=>{const t=e.createOscillator(),r=e.createGain();return t.connect(r),r.connect(e.destination),t.type="triangle",t.frequency.value=523,r.gain.setValueAtTime(.4,e.currentTime),r.gain.exponentialRampToValueAtTime(.01,e.currentTime+.8),t.start(),t.stop(e.currentTime+.8),{count:1,longestStopSec:.8}}};function kn(e,t){const r=t;V(e,{name:r==null?void 0:r.name,message:r==null?void 0:r.message})}function Xs(e){if(e==="off")return;V("audio-playsound-entered",{soundId:e});let t;try{t=new AudioContext}catch(s){kn("audio-context-failed",s);return}V("audio-context-created",{state:t.state});const r=()=>{let s;try{s=Hl[e](t)}catch(a){kn("audio-context-failed",a),t.close().catch(()=>{});return}V("audio-oscillators-scheduled",{soundId:e,count:s.count,longestStopSec:s.longestStopSec}),setTimeout(()=>{t.close().then(()=>V("audio-context-closed")).catch(()=>{})},(s.longestStopSec+.1)*1e3)};t.state==="running"?r():t.state==="suspended"?(V("audio-context-resume-attempted"),t.resume().then(()=>{V("audio-context-resume-ok",{state:t.state}),r()},s=>{kn("audio-context-resume-failed",s),t.close().catch(()=>{})})):(V("audio-context-failed",{name:"UnexpectedState",message:`AudioContext state "${t.state}"`}),t.close().catch(()=>{}))}const Wl="I came to the Build tab to find the AI waiting for me but never saw any of the idle notifications — no sound, no orange dot on the Build tab, no idle banner. Please diagnose using the trace below.\n\nStart with the **UI idle trace** section: a single `debounce-cancelled` line with a `trigger` field identifies which silent path killed the 1500ms debounce before `debounce-resolved` could fire. Cross-reference with the **Rust idle trace** and **editor-server.log** sections to confirm the backend actually sent `agent-idle` and to see the timing.";function Vl(){const e=typeof Notification<"u"?Notification.permission:"unknown",t=typeof document<"u"&&typeof document.hasFocus=="function"?document.hasFocus():!1,r=typeof document<"u"?document.hidden:!1;let s=null;try{s=typeof localStorage<"u"?localStorage.getItem("codeyam.idleDebug"):null}catch{}const a=typeof navigator<"u"?navigator.userAgent:"unknown";return{notificationPermission:e,hasFocus:t,hidden:r,idleDebug:s,userAgent:a}}function _r(e){return e.length===0?"_(no events in window)_":`\`\`\`jsonl
2
+ ${e.map(r=>JSON.stringify(r)).join(`
3
+ `)}
4
+ \`\`\``}function En(e,t){return e.trim().length===0?`_(${t} empty)_`:`\`\`\`
5
+ ${e}
6
+ \`\`\``}function Ul(e){var g,w,v;const{bundle:t,browser:r,uiBufferText:s,prompt:a,agentName:o}=e,l=(t==null?void 0:t.now)??new Date().toISOString(),c=(t==null?void 0:t.session)??er(),d=(t==null?void 0:t.windowMinutes)??10,u=((g=t==null?void 0:t.environment)==null?void 0:g.editorVersion)??"unknown",f=((w=t==null?void 0:t.environment)==null?void 0:w.platform)??"unknown",p=((v=t==null?void 0:t.environment)==null?void 0:v.projectDir)??"unknown",m=(a??Wl).trim(),h=[`- Notification.permission: ${r.notificationPermission}`,`- document.hasFocus(): ${r.hasFocus}`,`- document.hidden: ${r.hidden}`,`- localStorage.codeyam.idleDebug: ${r.idleDebug===null?"(unset)":JSON.stringify(r.idleDebug)}`,`- userAgent: ${r.userAgent}`].join(`
7
+ `),j=t&&t.truncations.length>0?`> **Truncations:** ${t.truncations.join("; ")}`:"";return["# CodeYam Notification Debug Bundle","",m,"","---","",`**Captured:** ${l}`,`**UI session:** ${c} (window: last ${d} minutes)`,`**Editor version:** ${u}`,`**Platform:** ${f}`,`**Project:** ${p}`,o?`**Agent:** ${o}`:null,"","**Browser state:**",h,"",j,"","## UI idle trace (persisted)","",_r((t==null?void 0:t.uiTrace)??[]),"","## UI idle trace (in-memory ring buffer — may be ahead of persisted)","",En(s,"in-memory buffer"),"","## Rust idle trace","",_r((t==null?void 0:t.rustTrace)??[]),"","## editor-server.log (filtered to idle= within window)","",En((t==null?void 0:t.editorServerLog)??"","editor-server.log"),"","## dev-server.log (last lines)","",En((t==null?void 0:t.devServerLog)??"","dev-server.log"),""].filter(x=>x!==null).join(`
8
+ `)}async function Kl(e={}){const t=encodeURIComponent(er());let r=null,s=null;try{const c=await fetch(`/api/idle-trace/bundle?session=${t}&minutes=10`);c.ok?r=await c.json():s=`HTTP ${c.status}`}catch(c){s=c instanceof Error?c.message:String(c)}const a=Vl(),o=Qo({agentName:e.agentName});return{markdown:Ul({bundle:r,browser:a,uiBufferText:o,prompt:e.prompt,agentName:e.agentName}),bundle:r,error:s}}const Gl=1500;function Yl(e=Gl){const[t,r]=i.useState(null),s=i.useRef(null),a=i.useCallback((o,l)=>{s.current!==null&&clearTimeout(s.current),r(o),s.current=setTimeout(()=>{r(null),s.current=null},l??e)},[e]);return i.useEffect(()=>()=>{s.current!==null&&(clearTimeout(s.current),s.current=null)},[]),{label:t,flash:a}}const Jl=2500;function Xl({agentName:e}){const[t,r]=i.useState(!1),{label:s,flash:a}=Yl(Jl),o=async()=>{r(!0);const{markdown:l,bundle:c,error:d}=await Kl({agentName:e});try{await navigator.clipboard.writeText(l);const u=((c==null?void 0:c.uiTrace.length)??0)+((c==null?void 0:c.rustTrace.length)??0),f=Math.round(l.length/1024*10)/10,p=d?`Copied (offline — ${u} events, ${f} KB)`:`Copied ${u} events · ${f} KB`;a(p)}catch{a("Copy failed")}finally{r(!1)}};return n.jsx("button",{onClick:()=>void o(),disabled:t,className:"text-left text-[11px] px-2 py-1 rounded cursor-pointer transition-colors font-medium",style:{background:"transparent",color:"var(--text-secondary)"},"data-testid":"notification-debug-copy",children:s??(t?"Gathering bundle…":"Debug Notifications")})}function zr({label:e,checked:t,onChange:r,className:s}){return n.jsxs("label",{className:`flex items-center gap-2 cursor-pointer${s?` ${s}`:""}`,children:[n.jsx("input",{type:"checkbox",checked:t,onChange:a=>r(a.target.checked),className:"accent-green-500"}),n.jsx("span",{className:"text-[11px]",style:{color:"var(--text-secondary)"},children:e})]})}function ql({settings:e,onChange:t,agentName:r}){const[s,a]=i.useState(!1),o=i.useRef(null),l=e.idleOnStop??!1,c=e.idleOnNotification??!0,d=e.sound!=="off"||e.systemNotification||l||c;return i.useEffect(()=>{if(!s)return;const u=f=>{o.current&&!o.current.contains(f.target)&&a(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[s]),n.jsxs("div",{className:"h-7 flex items-center px-3 text-xs shrink-0",style:{background:"var(--bg-nav)",borderTop:"1px solid var(--border-default)"},children:[n.jsx("div",{className:"flex-1"}),n.jsxs("div",{className:"relative",ref:o,children:[n.jsx("button",{onClick:()=>{a(!s),typeof Notification<"u"&&Notification.permission==="default"&&Notification.requestPermission()},className:"cursor-pointer transition-colors",style:{color:d?"var(--accent-green)":"var(--text-dim)",fontSize:"11px"},children:d?"Notifications On":"Notifications Off"}),s&&n.jsxs("div",{className:"absolute bottom-full right-0 mb-2 w-56 rounded-lg shadow-xl p-3 flex flex-col gap-3 z-50",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-[11px] mb-1.5",style:{color:"var(--text-muted)"},children:"Notification sound"}),n.jsx("div",{className:"flex flex-col gap-0.5",children:$l.map(u=>n.jsx("button",{onClick:()=>{t({...e,sound:u.id}),u.id!=="off"&&Xs(u.id)},className:"text-left text-[11px] px-2 py-1 rounded cursor-pointer transition-colors",style:{background:e.sound===u.id?"var(--bg-input)":"transparent",color:e.sound===u.id?"var(--text-primary)":"var(--text-secondary)"},children:u.label},u.id))})]}),n.jsxs("div",{className:"pt-2",style:{borderTop:"1px solid var(--border-default)"},children:[n.jsx("div",{className:"text-[11px] mb-1.5",style:{color:"var(--text-muted)"},children:"Trigger idle on"}),n.jsx(zr,{label:"Claude stops",checked:l,onChange:u=>t({...e,idleOnStop:u})}),n.jsx(zr,{label:"Claude sends a notification",checked:c,onChange:u=>t({...e,idleOnNotification:u}),className:"mt-1"})]}),n.jsxs("div",{className:"pt-2",style:{borderTop:"1px solid var(--border-default)"},children:[n.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:e.systemNotification,onChange:u=>{const f=u.target.checked;t({...e,systemNotification:f}),f&&typeof Notification<"u"&&Notification.permission==="default"&&Notification.requestPermission()},className:"accent-green-500"}),n.jsx("span",{className:"text-[11px]",style:{color:"var(--text-secondary)"},children:"System notification"})]}),n.jsx("div",{className:"text-[10px] mt-1 ml-5",style:{color:"var(--text-dim)"},children:"Shows when tab is not visible"}),typeof Notification<"u"&&Notification.permission==="denied"&&n.jsx("div",{className:"text-[10px] mt-1 ml-5",style:{color:"var(--accent-red, #ef4444)"},children:"Notifications are blocked. Click the lock icon in your address bar → Site settings → Notifications → Allow"})]}),n.jsx("div",{className:"pt-2",style:{borderTop:"1px solid var(--border-default)"},children:n.jsx(Xl,{agentName:r})})]})]})]})}function Ql(){const[e,t]=i.useState(null);return i.useEffect(()=>{fetch("/api/editor-setup-answers").then(r=>{if(!r.ok)throw new Error(`HTTP ${r.status}`);return r.json()}).then(r=>{t(r!==null)}).catch(()=>{t(!1)})},[]),{saved:e}}function Zl({projectDescription:e}){return n.jsxs(n.Fragment,{children:[n.jsx("h2",{className:"text-xl font-semibold",children:"Building your project…"}),n.jsx("blockquote",{className:"mt-4 border-l-2 border-[var(--accent-active)] pl-4 text-sm italic text-[var(--text-dim)]",children:e}),n.jsxs("p",{className:"mt-6 text-sm text-[var(--text-dim)]",children:["Your app will appear here as it’s built. The agent is scaffolding it now on the ",n.jsx("strong",{children:"Build"})," tab — open it to follow along."]})]})}function ec(){return n.jsxs(n.Fragment,{children:[n.jsx("h2",{className:"text-xl font-semibold",children:"No app scaffolded yet"}),n.jsxs("p",{className:"mt-4 text-sm text-[var(--text-dim)]",children:["Your project hasn’t been scaffolded yet. Open the"," ",n.jsx("strong",{children:"Build"})," tab to start building."]})]})}function tc({onClick:e}){return n.jsx("button",{type:"button",onClick:e,"data-testid":"app-overview-empty-open-build",className:"mt-6 inline-flex items-center gap-2 rounded border border-[var(--accent-active)] bg-[var(--accent-active)] px-4 py-2 text-xs font-medium uppercase tracking-wide text-black transition-colors hover:bg-[var(--accent-active)]/90 cursor-pointer",children:"Open Build tab"})}function nc({projectDescription:e,onOpenBuildTab:t}){const r=e!==null&&e.trim().length>0;return n.jsxs("div",{className:"mx-auto max-w-2xl px-5 py-12 text-[var(--text-primary)]",children:[r?n.jsx(Zl,{projectDescription:e}):n.jsx(ec,{}),n.jsx(tc,{onClick:t})]})}function rc({stats:e,onSelectApp:t,testsLoading:r,testsRefreshing:s,onRunTests:a,currentRunner:o}){return n.jsx("div",{className:"flex flex-col gap-4",children:e.map(l=>n.jsx(si,{stats:l,onClick:()=>t(l.app.dir),testsLoading:r,testsRefreshing:s,onRunTests:a,currentRunner:o},l.app.dir))})}function sc({projectTitle:e,coverage:t,onCoverageClick:r}){return n.jsxs("div",{className:"flex items-center justify-between mb-4",children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)]",children:e}),n.jsx(sr,{coverage:t,testId:"app-overview-coverage",onClick:r})]})}async function ac(e){try{e.description&&await fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDescription:e.description})});const t={appFormats:e.appFormats,techStackId:e.techStackId,designApproach:e.designApproach};e.defaultDevice&&(t.defaultDevice=e.defaultDevice),await fetch("/api/editor-setup-answers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}catch{}}const Hr=["product-type","description","tech-stack","design-approach"];function oc(e){return e==="files"||e==="chat"?[...Hr,"design-details"]:Hr}function ic(){const[e,t]=i.useState([]);return i.useEffect(()=>{fetch("/api/editor-stacks").then(r=>r.json()).then(t).catch(()=>{})},[]),{techStacks:e}}const Jt=20*1024*1024,lc=3e4,cc=3e3;function qs(e){return new Promise((t,r)=>{const s=new FileReader;s.onload=()=>{const a=s.result;if(typeof a!="string"){r(new Error("Unexpected FileReader result"));return}const o=a.indexOf(",");t(o===-1?a:a.slice(o+1))},s.onerror=()=>r(s.error??new Error("read failed")),s.readAsDataURL(e)})}function dc(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`drop-${Date.now()}-${Math.random().toString(36).slice(2)}`}function uc(e){return/^[A-Za-z0-9._/\-]+$/.test(e)?e:`"${e.replace(/(["\\$`])/g,"\\$1")}"`}function fc(e){const t=e.items;if(!t||t.length===0||typeof t[0].webkitGetAsEntry!="function")return!1;for(const s of Array.from(t)){const a=s.webkitGetAsEntry();if(a&&a.isDirectory)return!0}return!1}function Xe({title:e,subtitle:t,children:r}){return n.jsxs("div",{children:[n.jsx("h2",{style:{fontSize:"var(--text-xl, 22px)",fontWeight:700,color:"var(--text-primary)",marginBottom:"var(--spacing-xs, 4px)"},children:e}),n.jsx("p",{style:{fontSize:"var(--text-sm, 14px)",color:"var(--text-muted)",marginBottom:"var(--spacing-lg, 24px)"},children:t}),r]})}function pc({onUploadComplete:e}){const[t,r]=i.useState([]),[s,a]=i.useState(!1),[o,l]=i.useState(null),[c,d]=i.useState(null),[u,f]=i.useState(!1),p=i.useRef(null),m=i.useCallback(w=>{d(null);const v=w.filter(x=>x.size>Jt?(d(`${x.name} is larger than the ${Jt/(1024*1024)}MB cap`),!1):!0);r(x=>[...x,...v.map(y=>({id:`${y.name}-${y.size}-${Math.random().toString(36).slice(2)}`,file:y,description:""}))])},[]),h=i.useCallback(w=>{w.target.files&&m(Array.from(w.target.files)),w.target.value=""},[m]),j=i.useCallback((w,v)=>{r(x=>x.map(y=>y.id===w?{...y,description:v}:y))},[]),b=i.useCallback(w=>{r(v=>v.filter(x=>x.id!==w))},[]),g=i.useCallback(async()=>{if(t.length!==0){a(!0),d(null);try{const w=await Promise.all(t.map(async N=>({filename:N.file.name,contentBase64:await qs(N.file),description:N.description}))),v=await fetch("/api/editor-design-uploads",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:w})});if(!v.ok)throw new Error(`Upload failed: ${v.status}`);const y=(await v.json()).written??w.map(N=>N.filename);l(y),e==null||e(y)}catch(w){d(w instanceof Error?w.message:String(w))}finally{a(!1)}}},[t,e]);return n.jsxs(Xe,{title:"Add your design files",subtitle:"Drop in anything: brand assets, mockups, references. Tell us briefly what each one shows.",children:[n.jsxs("label",{onDragOver:w=>{w.preventDefault(),f(!0)},onDragLeave:()=>f(!1),onDrop:w=>{w.preventDefault(),f(!1),m(Array.from(w.dataTransfer.files))},style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"var(--spacing-xl, 32px)",border:`2px dashed ${u?"var(--accent-default)":"var(--border-default)"}`,borderRadius:12,background:u?"var(--bg-elevated, rgba(255,255,255,0.03))":"var(--bg-input)",cursor:"pointer",textAlign:"center",gap:"var(--spacing-xs, 4px)"},children:[n.jsx("input",{ref:p,type:"file",multiple:!0,onChange:h,style:{display:"none"}}),n.jsx("div",{style:{fontSize:"var(--text-sm, 14px)",color:"var(--text-primary)",fontWeight:500},children:"Drop files here, or click to choose"}),n.jsx("div",{style:{fontSize:"var(--text-xs, 12px)",color:"var(--text-secondary)"},children:"PNG, JPG, PDF, Markdown — anything that describes your design"})]}),t.length>0&&n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-sm, 8px)",marginTop:"var(--spacing-md, 12px)"},children:t.map(w=>n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-xs, 4px)",padding:"var(--spacing-sm, 8px)",border:"1px solid var(--border-default)",borderRadius:8,background:"var(--bg-input)"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsx("span",{style:{fontSize:"var(--text-sm, 14px)",color:"var(--text-primary)",fontWeight:500},children:w.file.name}),n.jsx("button",{type:"button",onClick:()=>b(w.id),style:{fontSize:"var(--text-xs, 12px)",color:"var(--text-secondary)",background:"transparent",border:"none",cursor:"pointer"},children:"Remove"})]}),n.jsx("textarea",{value:w.description,onChange:v=>j(w.id,v.target.value),placeholder:"What does this file show? (optional)",rows:2,style:{width:"100%",padding:"var(--spacing-sm, 8px)",background:"var(--bg-default)",border:"1px solid var(--border-default)",borderRadius:6,color:"var(--text-primary)",fontSize:"var(--text-xs, 12px)",resize:"vertical",outline:"none",fontFamily:"inherit"}})]},w.id))}),c&&n.jsx("div",{style:{marginTop:"var(--spacing-sm, 8px)",color:"var(--accent-danger, #f87171)",fontSize:"var(--text-xs, 12px)"},children:c}),o&&o.length>0&&n.jsxs("div",{style:{marginTop:"var(--spacing-sm, 8px)",color:"var(--text-secondary)",fontSize:"var(--text-xs, 12px)"},children:["Uploaded ",o.length," file",o.length===1?"":"s","."]}),n.jsx("button",{type:"button",onClick:g,disabled:t.length===0||s,style:{marginTop:"var(--spacing-md, 12px)",padding:"var(--spacing-sm, 8px) var(--spacing-md, 12px)",background:t.length===0||s?"var(--bg-elevated)":"var(--accent-default)",color:"var(--text-on-accent, white)",border:"none",borderRadius:6,fontSize:"var(--text-sm, 14px)",fontWeight:500,cursor:t.length===0||s?"not-allowed":"pointer"},children:s?"Uploading…":"Save uploads"})]})}function bt({label:e,description:t,selected:r,onClick:s,multi:a}){return n.jsxs("button",{onClick:s,style:{display:"flex",alignItems:"center",gap:"var(--spacing-md, 12px)",width:"100%",textAlign:"left",padding:"var(--spacing-sm, 8px) var(--spacing-md, 12px)",background:"var(--bg-input)",border:r?"1.5px solid var(--accent-active)":"1px solid var(--border-default)",borderRadius:8,cursor:"pointer",transition:"border-color 0.15s"},children:[n.jsx(mc,{selected:r,multi:a}),n.jsxs("div",{children:[n.jsx("span",{style:{fontSize:"var(--text-sm, 14px)",fontWeight:500,color:"var(--text-primary)"},children:e}),t&&n.jsx("span",{style:{display:"block",fontSize:"var(--text-xs, 12px)",color:"var(--text-muted)",marginTop:2},children:t})]})]})}function mc({selected:e,multi:t}){return n.jsx("span",{style:{width:16,height:16,borderRadius:t?3:"50%",border:e?"none":"1.5px solid var(--text-dim)",background:e?"var(--accent-active)":"transparent",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:e&&n.jsx("span",{style:{color:"#000",fontSize:11,fontWeight:700,lineHeight:1},children:"✓"})})}const xc=[{id:"files",label:"I have design files and/or a design system",description:"Upload screenshots, mockups, brand guides — anything that defines the look you want."},{id:"chat",label:"I need help on this, can we chat about it?",description:"After setup we'll generate mockups against curated moodboards and you pick a direction."},{id:"skip",label:"I'm not too worried about design, can we start building?",description:"Skip design for now. You can revisit it any time."}];function hc({selected:e,onSelect:t}){return n.jsx(Xe,{title:"How should we approach design?",subtitle:"Pick whichever feels right — you can always change direction later.",children:n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-sm, 8px)"},children:xc.map(r=>n.jsx(bt,{label:r.label,description:r.description,selected:e===r.id,onClick:()=>t(r.id)},r.id))})})}function gc(e,t){const r=i.useRef(t);i.useEffect(()=>{r.current=t},[t]),i.useEffect(()=>{if(!e)return;let s=!1,a=null;const o=async()=>{try{const c=await(await fetch("/api/editor-design-state")).json();!s&&c.active&&r.current(c.active)}catch{}finally{s||(a=window.setTimeout(o,3e3))}};return o(),()=>{s=!0,a!==null&&window.clearTimeout(a)}},[e])}function vc({description:e,onDesignSelected:t,onPreviewUrl:r}){const[s,a]=i.useState({kind:"preparing"});return i.useEffect(()=>(r==null||r("/design-exploration"),()=>{r==null||r(null)}),[r]),i.useEffect(()=>{let o=!1;return(async()=>{try{const[l,c]=await Promise.all([fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDescription:e})}),fetch("/api/editor-design-systems-install",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"})]);if(!c.ok){const d=await c.text().catch(()=>`${c.status}`);throw new Error(d||`install failed: ${c.status}`)}l.ok||console.warn("[QuestionnaireDesignChatStep] editor-project-info failed; skill will prompt for description",l.status),o||a({kind:"ready"})}catch(l){o||a({kind:"error",message:l instanceof Error?l.message:String(l)})}})(),()=>{o=!0}},[e]),gc(s.kind==="ready",t),n.jsxs(Xe,{title:"Explore design directions",subtitle:"Chat with the agent, then pick a mockup by number from the Live Preview.",children:[s.kind==="preparing"&&n.jsx("div",{style:{display:"inline-block",padding:"var(--spacing-xs, 4px) var(--spacing-sm, 8px)",marginBottom:"var(--spacing-sm, 8px)",borderRadius:999,background:"var(--bg-elevated)",color:"var(--text-secondary)",fontSize:"var(--text-xs, 12px)"},children:"Preparing design moodboards…"}),s.kind==="error"&&n.jsxs("div",{style:{padding:"var(--spacing-md, 12px)",marginBottom:"var(--spacing-sm, 8px)",borderRadius:8,background:"var(--bg-danger-soft, rgba(248,113,113,0.12))",color:"var(--accent-danger, #f87171)",fontSize:"var(--text-sm, 14px)"},children:["Couldn't prepare design moodboards: ",s.message,". Try the Files or Skip approach instead."]}),s.kind==="ready"&&n.jsx(rn,{slashCommand:"/codeyam-design",height:420})]})}const bc=[{id:"Desktop",label:"Desktop",description:"Standard desktop browser viewport"},{id:"Tablet",label:"Tablet",description:"Tablet-sized portrait viewport"},{id:"Mobile",label:"Mobile",description:"Phone-sized portrait viewport"}];function yc({selected:e,onSelect:t}){return n.jsx("div",{style:{marginTop:"var(--spacing-xl, 32px)"},children:n.jsx(Xe,{title:"Where will this web app primarily be viewed?",subtitle:"This sets the default viewport for every scenario captured in your project.",children:n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-sm, 8px)"},children:bc.map(r=>n.jsx(bt,{label:r.label,description:r.description,selected:e===r.id,onClick:()=>t(r.id)},r.id))})})})}function wc(){return n.jsx("div",{style:{padding:"var(--spacing-sm, 8px) var(--spacing-lg, 16px)",background:"var(--bg-surface)",borderBottom:"1px solid var(--border-subtle)",fontSize:"var(--text-sm, 14px)",color:"var(--text-muted)"},children:"Before we dive in, help us comprehend what you want to build better."})}function jc({step:e,canAdvance:t,isFinalStep:r,isAdvancing:s,onBack:a,onNext:o,onFinish:l}){return n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--spacing-md, 12px)",marginTop:"var(--spacing-lg, 24px)"},children:[e>1&&n.jsx("button",{onClick:a,style:{background:"none",border:"1px solid var(--border-default)",color:"var(--text-secondary)",padding:"var(--spacing-sm, 8px) var(--spacing-lg, 16px)",borderRadius:6,cursor:"pointer",fontSize:"var(--text-sm, 14px)"},children:"← Back"}),r?n.jsx("button",{onClick:l,disabled:!t,style:{background:t?"var(--accent-active)":"var(--bg-surface)",border:"none",color:t?"#000":"var(--text-dim)",padding:"var(--spacing-sm, 8px) var(--spacing-lg, 16px)",borderRadius:6,cursor:t?"pointer":"not-allowed",fontSize:"var(--text-sm, 14px)",fontWeight:600},children:"FINISH →"}):n.jsx("button",{onClick:o,disabled:!t||s,style:{background:t?"var(--accent-active)":"var(--bg-surface)",border:"none",color:t?"#000":"var(--text-dim)",padding:"var(--spacing-sm, 8px) var(--spacing-lg, 16px)",borderRadius:6,cursor:t&&!s?"pointer":"not-allowed",fontSize:"var(--text-sm, 14px)",fontWeight:600,opacity:s?.7:1},children:s?"…":"NEXT →"})]})}function Nc({currentStep:e,stepLabels:t,onStepClick:r}){return n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-xs, 4px)",paddingTop:"var(--spacing-lg, 24px)"},children:t.map((s,a)=>{const o=a+1,l=o===e,c=o<e;return n.jsx("button",{onClick:()=>{c&&r(o)},style:{background:"none",border:"none",cursor:c?"pointer":"default",padding:"var(--spacing-xs, 4px) 0",fontSize:"var(--text-sm, 14px)",color:l?"var(--text-primary)":c?"var(--text-secondary)":"var(--text-dim)",fontWeight:l?500:400,textAlign:"left",transition:"color 0.15s"},children:s},o)})})}const Cc=[{id:"web",label:"Website/Web App"},{id:"desktop",label:"Desktop App"},{id:"chrome-extension",label:"Chrome Extension"},{id:"mobile",label:"Mobile App"},{id:"other",label:"Other"}],Sc={"product-type":"What Type Of Your Product Do You Want To Build?",description:"Describe Your Product","tech-stack":"Do You Have A Preferred Tech Stack?","design-approach":"How Should We Approach Design","design-details":"Design Details"},Wr=560,kc=960;function Ec({onComplete:e,onPreviewUrl:t}){const[r,s]=i.useState(1),[a,o]=i.useState({appFormats:[],description:"",techStackId:null,designApproach:null,defaultDevice:null}),[l,c]=i.useState(null),{techStacks:d}=ic(),u=oc(a.designApproach),f=u[r-1],p=r===u.length,m=u.map(C=>Sc[C]),h=i.useCallback(C=>{o(S=>{const k=S.appFormats.includes(C),R=k?S.appFormats.filter(T=>T!==C):[...S.appFormats,C],E=C==="web"&&k?null:S.defaultDevice;return{...S,appFormats:R,defaultDevice:E}})},[]),j=i.useCallback(C=>{o(S=>({...S,defaultDevice:C}))},[]),b=i.useCallback(C=>{o(S=>({...S,designApproach:S.designApproach===C?null:C}))},[]),g=i.useCallback(async()=>{await ac(a),e==null||e(a)},[a,e]),w=i.useRef(!1);i.useEffect(()=>{w.current||f==="design-details"&&a.designApproach==="chat"&&l!==null&&(w.current=!0,g())},[f,a.designApproach,l,g]);const v=i.useCallback(()=>{s(C=>C+1)},[]),x=a.appFormats.includes("web"),y=(()=>{switch(f){case"product-type":return a.appFormats.length>0&&(!x||a.defaultDevice!==null);case"description":return a.description.trim().length>0;case"design-approach":return a.designApproach!==null;case"design-details":return a.designApproach==="chat"?l!==null:!0;default:return!0}})(),N=f==="description"?kc:f==="design-details"&&a.designApproach==="chat"?"100%":Wr;return n.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"auto"},children:[n.jsx(wc,{}),n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",padding:"var(--spacing-xl, 32px)"},children:[n.jsxs("div",{style:{maxWidth:N},children:[f==="product-type"&&n.jsxs(n.Fragment,{children:[n.jsx(Xe,{title:"What type of your product do you want to build?",subtitle:"Select as many as you need.",children:n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-sm, 8px)"},children:Cc.map(C=>n.jsx(bt,{label:C.label,selected:a.appFormats.includes(C.id),onClick:()=>h(C.id),multi:!0},C.id))})}),x&&n.jsx(yc,{selected:a.defaultDevice,onSelect:j})]}),f==="description"&&n.jsx(Xe,{title:"Describe your product",subtitle:"What are you building? This helps us set up the right starting point.",children:n.jsx("textarea",{value:a.description,onChange:C=>o(S=>({...S,description:C.target.value})),placeholder:"e.g. A task management app for remote teams with real-time collaboration...",style:{width:"100%",minHeight:180,padding:"var(--spacing-md, 12px)",background:"var(--bg-input)",border:"1px solid var(--border-default)",borderRadius:8,color:"var(--text-primary)",fontSize:"var(--text-sm, 14px)",resize:"vertical",outline:"none",fontFamily:"inherit"}})}),f==="tech-stack"&&n.jsx(Xe,{title:"Do you have a preferred tech stack?",subtitle:"Choose a starting template, or let CodeYam decide.",children:n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-sm, 8px)"},children:[n.jsx(bt,{label:"Let CodeYam decide",description:"We'll pick the best stack based on your product",selected:a.techStackId===null,onClick:()=>o(C=>({...C,techStackId:null}))}),d.map(C=>n.jsx(bt,{label:C.name,description:C.description,selected:a.techStackId===C.id,onClick:()=>o(S=>({...S,techStackId:C.id}))},C.id))]})}),f==="design-approach"&&n.jsx(hc,{selected:a.designApproach,onSelect:b}),f==="design-details"&&a.designApproach==="files"&&n.jsx(pc,{}),f==="design-details"&&a.designApproach==="chat"&&n.jsx(vc,{description:a.description,onDesignSelected:c,onPreviewUrl:t})]}),n.jsxs("div",{style:{maxWidth:Wr},children:[n.jsx(jc,{step:r,canAdvance:y,isFinalStep:p,onBack:()=>s(C=>C-1),onNext:()=>{y&&v()},onFinish:g}),n.jsx(Nc,{currentStep:r,stepLabels:m,onStepClick:s})]})]})]})}function Rc({projectTitle:e,projectDescription:t,stats:r,coverage:s,onSelectApp:a,configLoading:o,testsLoading:l,testsRefreshing:c,onRunTests:d,currentRunner:u,stepState:f,onPreviewUrl:p,onComplete:m,onOpenBuildTab:h,onCoverageClick:j}){const{saved:b}=Ql();return r.length===0?o||b===null?null:!f&&!b?n.jsx(Ec,{onPreviewUrl:p,onComplete:m}):n.jsx(nc,{projectDescription:t??null,onOpenBuildTab:h??(()=>{})}):n.jsxs("div",{className:"px-5 py-5",children:[n.jsx(sc,{projectTitle:e,coverage:s,onCoverageClick:j}),n.jsx(rc,{stats:r,onSelectApp:a,testsLoading:l,testsRefreshing:c,onRunTests:d,currentRunner:u})]})}function Tc({sessionContent:e,stepIndicator:t}){return n.jsxs("div",{className:"flex flex-col h-full",children:[t,e]})}function Pc({activeTab:e,buildTab:t,footer:r,resultsPanel:s,showResultsPanel:a}){return n.jsxs("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:e==="build"?"visible":"hidden",pointerEvents:e==="build"?"auto":"none"},children:[n.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[n.jsx("div",{style:{flex:a?"0 0 50%":"1 1 auto",minHeight:0,overflow:"hidden",display:"flex",flexDirection:"column"},children:t}),a?s:null]}),r]})}function Dc(e=!1){return{title:"Session Ready to Resume",description:e?"CodeYam saved this build session while it was waiting on the next workflow action. Review the current feature and step below, then click resume when you're ready to continue.":"CodeYam found a saved build session for this feature. Review the current feature and step below, then click resume when you're ready to continue.",buttonLabel:"Resume Session",providersLabel:null}}function Ac(e,t){const r=dt(e),s=dt(t);return{title:"Saved Handoff Ready",description:`A ${r} build session is still in progress for this feature. CodeYam saved the workflow state so ${s} can continue from the same step instead of starting over.`,buttonLabel:"Continue with Saved Handoff",providersLabel:`${r} to ${s}`}}function Lc({resumeMode:e,previousProvider:t,currentProvider:r,awaitingUserInput:s=!1}){return e!=="handoff"||t==null||r==null||t===r?Dc(s):Ac(t,r)}function Mc({label:e,onContinue:t}){return n.jsx("button",{onClick:t,className:"w-full px-4 py-2 text-sm rounded transition-colors cursor-pointer font-medium",style:{background:"var(--accent-blue)",color:"var(--text-primary)"},children:e})}function Ic({children:e}){return n.jsx("div",{className:"flex items-center justify-center h-full",role:"dialog","aria-modal":"true",style:{background:"var(--bg-deep)",color:"var(--text-secondary)"},children:n.jsx("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:e})})}function Fc({description:e,title:t}){return n.jsxs(n.Fragment,{children:[n.jsx("h2",{className:"text-lg font-semibold mb-3",style:{color:"var(--text-primary)"},children:t}),n.jsx("p",{className:"text-sm mb-4",style:{color:"var(--text-muted)"},children:e})]})}function Rn({label:e,rowClassName:t,value:r}){return n.jsxs("div",{className:t,children:[n.jsxs("span",{style:{color:"var(--text-muted)"},children:[e,":"]})," ",n.jsx("span",{style:{color:"var(--text-primary)"},children:r})]})}function Oc({featureName:e,editorStep:t,editorStepLabel:r,providersLabel:s}){return n.jsxs("div",{className:"rounded p-3 mb-5 text-sm",style:{background:"var(--bg-deep)"},children:[e&&n.jsx(Rn,{label:"Feature",value:e,rowClassName:"mb-1"}),t!=null&&r&&n.jsx(Rn,{label:"Step",value:`${t} (${r})`}),s&&n.jsx(Rn,{label:"Providers",value:s,rowClassName:"mt-1"})]})}function Bc(e){const t=i.useCallback(r=>{r.key==="Enter"&&(r.preventDefault(),e())},[e]);i.useEffect(()=>(window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)),[t])}function $c({featureName:e,editorStep:t,workflowMode:r,previousProvider:s,currentProvider:a,resumeMode:o,awaitingUserInput:l=!1,onContinue:c}){const d=Lc({resumeMode:o,previousProvider:s,currentProvider:a,awaitingUserInput:l}),u=t==null?null:ar(t,r);return Bc(c),n.jsxs(Ic,{children:[n.jsx(Fc,{title:d.title,description:d.description}),n.jsx(Oc,{featureName:e,editorStep:t,editorStepLabel:u,providersLabel:d.providersLabel}),n.jsx(Mc,{label:d.buttonLabel,onContinue:c})]})}function _c({awaitingUserInput:e,currentProvider:t,editorStep:r,featureName:s,onContinue:a,previousProvider:o,resumeMode:l,workflowMode:c}){return n.jsx($c,{featureName:s,editorStep:r,workflowMode:c,previousProvider:o,currentProvider:t,resumeMode:l,awaitingUserInput:e,onContinue:a})}function zc({awaitingPlanLaunchChoice:e,configLoading:t,sessionDecision:r,sessionInfo:s,sessionLoading:a,stepState:o}){return{recoveryFeatureName:(o==null?void 0:o.feature)??(s==null?void 0:s.feature)??null,recoveryStep:(o==null?void 0:o.step)??(s==null?void 0:s.step)??null,recoveryMode:(o==null?void 0:o.mode)??(s==null?void 0:s.mode)??null,showTerminal:!a&&!t&&(r==="continue"||r==="fresh"||r==="no-session")&&(o!==null||s!==null),shouldResumeSameProvider:r==="continue"&&(s==null?void 0:s.resumeMode)==="resume"}}const _n=8e3,Hc="agent-banner-ready";let Xt=!1,qt=!1,qe=[],Vr=!1;function Wc(){Vr||typeof window>"u"||(Vr=!0,window.addEventListener(Hc,()=>{if(qt)return;qt=!0;const e=qe;qe=[];for(const t of e)t()}))}Wc();function Vc(){return qt?Promise.resolve("banner"):new Promise(e=>{let t=!1;const r=()=>{t||(t=!0,clearTimeout(s),e("banner"))};qe.push(r);const s=setTimeout(()=>{if(t)return;t=!0;const a=qe.indexOf(r);a>=0&&qe.splice(a,1),e("fallback")},_n)})}async function Qs(e,t,r=0,s=Fn){if(Xt){V("dispatch-rename-suppressed",{caller:t,label:e});return}Xt=!0,V("dispatch-rename",{phase:"queued",caller:t,label:e,fallbackMs:_n,postReadyDelayMs:r});const a=await Vc();r>0&&await new Promise(o=>setTimeout(o,r)),a==="fallback"&&V("dispatch-rename-fallback",{caller:t,label:e,fallbackMs:_n}),V("dispatch-rename",{phase:"fired",caller:t,label:e,source:a,postReadyDelayMs:r}),As(e,s)}function Uc(){Xt=!1,qt=!1,qe=[]}function Kc(){Xt=!1,qe=[]}function Gc({provider:e,agentStartMode:t,currentFeature:r}){const s=i.useRef(!1);i.useEffect(()=>{if(!(s.current||e!=="claude"||t!=="fresh")){if(r!==null){s.current=!0;return}s.current=!0,Qs(Lo("/codeyam-editor"),"build-session-seed",Ls)}},[e,t,r])}function Yc({snippet:e,onRetry:t,onDismiss:r}){return n.jsx("div",{"data-testid":"build-tab-startup-error",className:"border-b border-red-500/30 bg-red-950/40 text-red-100 px-4 py-3",children:n.jsxs("div",{className:"flex items-start justify-between gap-4",children:[n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"font-medium text-sm mb-1",children:"Claude didn't start"}),n.jsx("pre",{"data-testid":"build-tab-startup-error-snippet",className:"font-mono text-xs whitespace-pre-wrap break-words bg-black/40 text-red-50 px-2 py-1 rounded max-h-40 overflow-auto",children:e})]}),n.jsxs("div",{className:"flex items-start gap-2 shrink-0",children:[n.jsx("button",{type:"button",onClick:t,"data-testid":"build-tab-startup-error-retry",className:"px-3 py-1.5 rounded bg-red-500 text-white text-sm font-medium cursor-pointer hover:bg-red-400",children:"Retry"}),n.jsx("button",{type:"button",onClick:r,"data-testid":"build-tab-startup-error-dismiss","aria-label":"Dismiss",title:"Dismiss",className:"px-2 py-1.5 rounded text-red-200 text-sm cursor-pointer hover:bg-red-900/40",children:"×"})]})]})})}const Jc=1e3;let zn=0;function _t(){zn=Date.now()}function Xc(){return zn===0?1/0:Date.now()-zn}function qc(){return Xc()<Jc}function Qt(){window.focus()}function Qc(e,t,r=50){const s=i.useRef(t);s.current=t,i.useEffect(()=>{const a=e.current;if(!a)return;let o=null;const l=new ResizeObserver(c=>{o&&clearTimeout(o);const d=c[0];d&&(o=setTimeout(()=>{s.current(d)},r))});return l.observe(a),()=>{o&&clearTimeout(o),l.disconnect()}},[e,r])}function Zc({wsRef:e,insertInput:t}){const[r,s]=i.useState(!1),[a,o]=i.useState(null),l=i.useRef(new Map),c=i.useRef(0);i.useEffect(()=>{if(a===null)return;const x=window.setTimeout(()=>o(null),cc);return()=>window.clearTimeout(x)},[a]);const d=i.useCallback(x=>{o(x)},[]),u=i.useCallback((x,y)=>{const N=l.current.get(x);N&&(l.current.delete(x),N.resolve(y))},[]),f=i.useCallback((x,y)=>{const N=l.current.get(x);N&&(l.current.delete(x),N.reject(y))},[]),p=i.useCallback(x=>{for(const[,y]of l.current)y.reject(x);l.current.clear()},[]),m=i.useCallback(async x=>{if(x.size>Jt)throw new Error(`File too large (max ${Jt/(1024*1024)} MB)`);const y=e.current;if(!y||y.readyState!==WebSocket.OPEN)throw new Error("Not connected — try again in a moment");const N=await qs(x),C=dc(),S=new Promise((k,R)=>{const E=window.setTimeout(()=>{l.current.delete(C)&&R(new Error("Timed out waiting for save to complete"))},lc);l.current.set(C,{resolve:T=>{window.clearTimeout(E),k(T)},reject:T=>{window.clearTimeout(E),R(new Error(T))}})});return y.send(JSON.stringify({type:"drop",id:C,name:x.name||"unnamed",mime:x.type||"application/octet-stream",data:N})),S},[e]),h=i.useCallback(async x=>{if(x.length===0)return;const y=[];for(const N of x)try{y.push(await m(N))}catch(C){const S=C instanceof Error?C.message:String(C);d(`Attach failed: ${S}`);return}t(y.map(uc).join(" ")+" ")},[m,d,t]),j=i.useCallback(x=>{x.dataTransfer.types.includes("Files")&&(x.preventDefault(),c.current+=1,s(!0))},[]),b=i.useCallback(x=>{x.dataTransfer.types.includes("Files")&&x.preventDefault()},[]),g=i.useCallback(x=>{x.dataTransfer.types.includes("Files")&&(c.current=Math.max(0,c.current-1),c.current===0&&s(!1))},[]),w=i.useCallback(async x=>{if(!x.dataTransfer.types.includes("Files"))return;if(x.preventDefault(),c.current=0,s(!1),fc(x.dataTransfer)){d("Folder drops are not supported — drag individual files instead");return}const y=Array.from(x.dataTransfer.files).filter(N=>N.size>0);await h(y)},[h,d]),v=i.useCallback(async x=>{var C;const y=(C=x.clipboardData)==null?void 0:C.items;if(!y)return;const N=[];for(const S of Array.from(y))if(S.kind==="file"&&S.type.startsWith("image/")){const k=S.getAsFile();k&&N.push(k)}N.length!==0&&(x.preventDefault(),await h(N))},[h]);return{dragActive:r,errorToast:a,dropHandlers:{onDragEnter:j,onDragOver:b,onDragLeave:g,onDrop:w},pasteHandler:v,resolveDrop:u,rejectDrop:f,cancelAllDrops:p,showError:d}}function ut(e=typeof window<"u"?window:void 0){return e?e.self!==e.top:!1}function ed({isInIframe:e,previewKind:t,selectedScenario:r}){return e?!1:t!=="application"?!0:!r||!Qe(r)}function td(){return n.jsx("div",{"data-testid":"terminal-drop-overlay",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(30, 30, 30, 0.85)",color:"#D7FF63",fontFamily:"'IBM Plex Mono', monospace",fontSize:14,border:"2px dashed #D7FF63",borderRadius:6,pointerEvents:"none",zIndex:5},children:"Drop file to attach"})}function nd({message:e}){return n.jsx("div",{"data-testid":"terminal-drop-toast",style:{position:"absolute",bottom:12,left:"50%",transform:"translateX(-50%)",background:"#3a1f1f",color:"#ff9494",border:"1px solid #7a3939",borderRadius:4,padding:"6px 12px",fontFamily:"'IBM Plex Mono', monospace",fontSize:12,zIndex:6,pointerEvents:"none"},children:e})}const Ur=15;function rd({provider:e,agentStartMode:t,sessionId:r,onAgentIdle:s,onAgentActive:a,onUserInput:o,onStartupFailed:l,onStartupFailedCleared:c}){if(ut())return null;const d=i.useRef(null),u=i.useRef(null),f=i.useRef(null),p=i.useRef(null),m=i.useRef(!1),h=i.useRef(t??"fresh"),j=i.useRef(r??null),[b,g]=i.useState({kind:"connecting"}),[w,v]=i.useState(0);i.useEffect(()=>{h.current=t??"fresh",j.current=r??null},[t,r]);const x=i.useRef(s);x.current=s;const y=i.useRef(a);y.current=a;const N=i.useRef(o);N.current=o;const C=i.useRef(l);C.current=l;const S=i.useRef(c);S.current=c;const k=Zc({wsRef:p,insertInput:E=>{var T,M;((T=p.current)==null?void 0:T.readyState)===WebSocket.OPEN&&p.current.send(JSON.stringify({type:"input",data:E})),_t(),(M=N.current)==null||M.call(N)}}),R=i.useRef(k);return R.current=k,Qc(d,()=>{var E;f.current&&u.current&&(f.current.fit(),((E=p.current)==null?void 0:E.readyState)===WebSocket.OPEN&&p.current.send(JSON.stringify({type:"resize",cols:u.current.cols,rows:u.current.rows})))}),i.useEffect(()=>{if(!d.current||m.current)return;m.current=!0;const E=new Mo.Terminal({cursorBlink:!0,fontSize:13,fontFamily:"'IBM Plex Mono', monospace",theme:{background:"#1e1e1e",foreground:"#cccccc",cursor:"#D7FF63",selectionBackground:"#264f78"}}),T=new Io.FitAddon;E.loadAddon(T),E.open(d.current),u.current=E,f.current=T;const M=Fo(E,d.current,{onError:L=>R.current.showError(L)}),F=Oo(E,{sendInput:L=>{var A,X;((A=p.current)==null?void 0:A.readyState)===WebSocket.OPEN&&p.current.send(JSON.stringify({type:"input",data:L})),_t(),(X=N.current)==null||X.call(N)}});requestAnimationFrame(()=>{T.fit(),E.focus()});let I=!1,z=0,J=null;function D(){try{const L=new WebSocket($o({provider:e,mode:h.current,sessionId:j.current??void 0}));p.current=L,L.binaryType="arraybuffer",L.onmessage=A=>{var X,G,ee,W;if(A.data instanceof ArrayBuffer)E.write(new Uint8Array(A.data));else if(typeof A.data=="string")try{const P=JSON.parse(A.data);if(P.type==="session-id")h.current="resume",j.current=P.sessionId??null;else if(P.type==="agent-idle"||P.type==="claude-idle"){const ne=typeof P.source=="string"?P.source:void 0;V("ws-message-received",{type:P.type,source:ne}),(X=x.current)==null||X.call(x,ne)}else if(P.type==="agent-active"||P.type==="claude-active")V("ws-message-received-active",{type:P.type}),(G=y.current)==null||G.call(y);else if(P.type==="idle-diag"){const{site:ne,event:se,...ae}=P;V(`rust:${se??"unknown"}`,{site:ne,...ae})}else P.type==="drop-complete"?R.current.resolveDrop(String(P.id??""),String(P.path??"")):P.type==="drop-error"?R.current.rejectDrop(String(P.id??""),String(P.message??"drop failed")):P.type==="startup-failed"?(ee=C.current)==null||ee.call(C,String(P.snippet??"")):P.type==="startup-failed-cleared"?(W=S.current)==null||W.call(S):P.type==="agent-banner-ready"&&(V("agent-banner-ready",{}),window.dispatchEvent(new CustomEvent("agent-banner-ready")))}catch{}},L.onopen=()=>{z=0,g({kind:"open"}),V("ws-open"),L.send(JSON.stringify({type:"resize",cols:E.cols,rows:E.rows}));try{typeof localStorage<"u"&&localStorage.getItem("codeyam.idleDebug")==="1"&&(L.send(JSON.stringify({type:"enable-idle-diag",sessionId:er()})),V("idle-diag-enabled"))}catch{}},L.onerror=()=>{},L.onclose=async()=>{if(V("ws-close",{reconnectAttempts:z}),R.current.cancelAllDrops("Not connected"),I){g({kind:"ended"}),E.writeln(`\r
9
+ \x1B[90m[Terminal session ended]\x1B[0m`);return}const A=await _o();if(!I){if(!A){g({kind:"server-stopped"}),J==null||J(),J=zo(2e3,()=>{I||window.location.reload()});return}if(z<Ur){const X=z<4?1e3*Math.pow(2,z):1e4;z++,g({kind:"reconnecting",attempt:z,maxAttempts:Ur}),setTimeout(()=>{I||D()},X)}else g({kind:"failed"})}}}catch{g({kind:"failed"})}}D();let O=0;const H=1e3;function $(){var A;const L=Date.now();L-O>=H&&((A=p.current)==null?void 0:A.readyState)===WebSocket.OPEN&&(p.current.send(JSON.stringify({type:"browser-activity"})),O=L)}document.addEventListener("mousemove",$),document.addEventListener("keydown",$),document.addEventListener("mousedown",$),E.onData(L=>{var A,X;((A=p.current)==null?void 0:A.readyState)===WebSocket.OPEN?p.current.send(JSON.stringify({type:"input",data:L})):v(G=>G+1),_t(),(X=N.current)==null||X.call(N)});const K=d.current;function B(L){var ee,W,P;const A=((ee=L.clipboardData)==null?void 0:ee.getData("text"))??"";if(!A)return;L.preventDefault(),L.stopPropagation();const X=A.replace(/\r\n/g,"\r").replace(/\n/g,"\r"),G=E.modes.bracketedPasteMode?`\x1B[200~${X}\x1B[201~`:X;((W=p.current)==null?void 0:W.readyState)===WebSocket.OPEN?p.current.send(JSON.stringify({type:"input",data:G})):v(ne=>ne+1),_t(),(P=N.current)==null||P.call(N)}K.addEventListener("paste",B,!0);function Q(L){var G,ee;const A=L.detail;if(!A)return;((G=p.current)==null?void 0:G.readyState)===WebSocket.OPEN?((ee=p.current)==null||ee.send(JSON.stringify({type:"input",data:A})),V("terminal-send-input",{len:A.length,firstChars:A.slice(0,16),wsOpen:!0,dropped:!1})):V("terminal-send-input",{len:A.length,firstChars:A.slice(0,16),wsOpen:!1,dropped:!0})}window.addEventListener("terminal-send-input",Q);function U(){Qt(),E.focus()}return window.addEventListener("terminal-focus",U),()=>{var L;I=!0,J==null||J(),J=null,document.removeEventListener("mousemove",$),document.removeEventListener("keydown",$),document.removeEventListener("mousedown",$),window.removeEventListener("terminal-send-input",Q),window.removeEventListener("terminal-focus",U),K.removeEventListener("paste",B,!0),F(),(L=p.current)==null||L.close(),M(),E.dispose(),m.current=!1}},[e]),n.jsxs("div",{className:"relative flex-1 flex flex-col",style:{minHeight:0},"data-terminal-emulator":!0,onDragEnter:k.dropHandlers.onDragEnter,onDragOver:k.dropHandlers.onDragOver,onDragLeave:k.dropHandlers.onDragLeave,onDrop:k.dropHandlers.onDrop,onPaste:k.pasteHandler,children:[n.jsx("div",{ref:d,className:"flex-1",style:{background:"#1e1e1e",minHeight:0,paddingTop:3,paddingLeft:3},onClick:()=>{var E;Qt(),(E=u.current)==null||E.focus()}}),k.dragActive&&n.jsx(td,{}),k.errorToast&&n.jsx(nd,{message:k.errorToast}),n.jsx(Bo,{status:b,pulseKey:w,onRefresh:()=>window.location.reload()})]})}function sd({onAgentActive:e,onAgentIdle:t,onUserInput:r,provider:s,sessionId:a,shouldResumeSameProvider:o,currentFeature:l}){const[c,d]=i.useState(null),[u,f]=i.useState(0);Gc({provider:s,agentStartMode:o?"resume":"fresh",currentFeature:l}),i.useEffect(()=>()=>{Uc()},[]);const p=i.useCallback(j=>{d(j)},[]),m=i.useCallback(()=>{d(null)},[]),h=i.useCallback(()=>{d(null),f(j=>j+1)},[]);return n.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[c!==null&&n.jsx(Yc,{snippet:c,onRetry:h,onDismiss:m}),n.jsx(rd,{provider:s,agentStartMode:o?"resume":"fresh",sessionId:o?a:null,onAgentIdle:t,onAgentActive:e,onUserInput:r,onStartupFailed:p,onStartupFailedCleared:m},u)]})}function ad(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return i.useMemo(()=>s=>{t.forEach(a=>a(s))},t)}const an=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function ft(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function lr(e){return"nodeType"in e}function Ce(e){var t,r;return e?ft(e)?e:lr(e)&&(t=(r=e.ownerDocument)==null?void 0:r.defaultView)!=null?t:window:window}function cr(e){const{Document:t}=Ce(e);return e instanceof t}function Pt(e){return ft(e)?!1:e instanceof Ce(e).HTMLElement}function Zs(e){return e instanceof Ce(e).SVGElement}function pt(e){return e?ft(e)?e.document:lr(e)?cr(e)?e:Pt(e)||Zs(e)?e.ownerDocument:document:document:document}const Be=an?i.useLayoutEffect:i.useEffect;function dr(e){const t=i.useRef(e);return Be(()=>{t.current=e}),i.useCallback(function(){for(var r=arguments.length,s=new Array(r),a=0;a<r;a++)s[a]=arguments[a];return t.current==null?void 0:t.current(...s)},[])}function od(){const e=i.useRef(null),t=i.useCallback((s,a)=>{e.current=setInterval(s,a)},[]),r=i.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,r]}function Ct(e,t){t===void 0&&(t=[e]);const r=i.useRef(e);return Be(()=>{r.current!==e&&(r.current=e)},t),r}function Dt(e,t){const r=i.useRef();return i.useMemo(()=>{const s=e(r.current);return r.current=s,s},[...t])}function Zt(e){const t=dr(e),r=i.useRef(null),s=i.useCallback(a=>{a!==r.current&&(t==null||t(a,r.current)),r.current=a},[]);return[r,s]}function Hn(e){const t=i.useRef();return i.useEffect(()=>{t.current=e},[e]),t.current}let Tn={};function At(e,t){return i.useMemo(()=>{if(t)return t;const r=Tn[e]==null?0:Tn[e]+1;return Tn[e]=r,e+"-"+r},[e,t])}function ea(e){return function(t){for(var r=arguments.length,s=new Array(r>1?r-1:0),a=1;a<r;a++)s[a-1]=arguments[a];return s.reduce((o,l)=>{const c=Object.entries(l);for(const[d,u]of c){const f=o[d];f!=null&&(o[d]=f+e*u)}return o},{...t})}}const lt=ea(1),St=ea(-1);function id(e){return"clientX"in e&&"clientY"in e}function ur(e){if(!e)return!1;const{KeyboardEvent:t}=Ce(e.target);return t&&e instanceof t}function ld(e){if(!e)return!1;const{TouchEvent:t}=Ce(e.target);return t&&e instanceof t}function Wn(e){if(ld(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:r}=e.touches[0];return{x:t,y:r}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:r}=e.changedTouches[0];return{x:t,y:r}}}return id(e)?{x:e.clientX,y:e.clientY}:null}const kt=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:r}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(r?Math.round(r):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:r}=e;return"scaleX("+t+") scaleY("+r+")"}},Transform:{toString(e){if(e)return[kt.Translate.toString(e),kt.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:r,easing:s}=e;return t+" "+r+"ms "+s}}}),Kr="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function cd(e){return e.matches(Kr)?e:e.querySelector(Kr)}const dd={display:"none"};function ud(e){let{id:t,value:r}=e;return Ne.createElement("div",{id:t,style:dd},r)}function fd(e){let{id:t,announcement:r,ariaLiveType:s="assertive"}=e;const a={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Ne.createElement("div",{id:t,style:a,role:"status","aria-live":s,"aria-atomic":!0},r)}function pd(){const[e,t]=i.useState("");return{announce:i.useCallback(s=>{s!=null&&t(s)},[]),announcement:e}}const ta=i.createContext(null);function md(e){const t=i.useContext(ta);i.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function xd(){const[e]=i.useState(()=>new Set),t=i.useCallback(s=>(e.add(s),()=>e.delete(s)),[e]);return[i.useCallback(s=>{let{type:a,event:o}=s;e.forEach(l=>{var c;return(c=l[a])==null?void 0:c.call(l,o)})},[e]),t]}const hd={draggable:`
10
+ To pick up a draggable item, press the space bar.
11
+ While dragging, use the arrow keys to move the item.
12
+ Press space again to drop the item in its new position, or press escape to cancel.
13
+ `},gd={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:r}=e;return r?"Draggable item "+t.id+" was moved over droppable area "+r.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:r}=e;return r?"Draggable item "+t.id+" was dropped over droppable area "+r.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function vd(e){let{announcements:t=gd,container:r,hiddenTextDescribedById:s,screenReaderInstructions:a=hd}=e;const{announce:o,announcement:l}=pd(),c=At("DndLiveRegion"),[d,u]=i.useState(!1);if(i.useEffect(()=>{u(!0)},[]),md(i.useMemo(()=>({onDragStart(p){let{active:m}=p;o(t.onDragStart({active:m}))},onDragMove(p){let{active:m,over:h}=p;t.onDragMove&&o(t.onDragMove({active:m,over:h}))},onDragOver(p){let{active:m,over:h}=p;o(t.onDragOver({active:m,over:h}))},onDragEnd(p){let{active:m,over:h}=p;o(t.onDragEnd({active:m,over:h}))},onDragCancel(p){let{active:m,over:h}=p;o(t.onDragCancel({active:m,over:h}))}}),[o,t])),!d)return null;const f=Ne.createElement(Ne.Fragment,null,Ne.createElement(ud,{id:s,value:a.draggable}),Ne.createElement(fd,{id:c,announcement:l}));return r?vt.createPortal(f,r):f}var le;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(le||(le={}));function en(){}function Gr(e,t){return i.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function bd(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return i.useMemo(()=>[...t].filter(s=>s!=null),[...t])}const Ae=Object.freeze({x:0,y:0});function na(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function ra(e,t){let{data:{value:r}}=e,{data:{value:s}}=t;return r-s}function yd(e,t){let{data:{value:r}}=e,{data:{value:s}}=t;return s-r}function Yr(e){let{left:t,top:r,height:s,width:a}=e;return[{x:t,y:r},{x:t+a,y:r},{x:t,y:r+s},{x:t+a,y:r+s}]}function sa(e,t){if(!e||e.length===0)return null;const[r]=e;return r[t]}function Jr(e,t,r){return t===void 0&&(t=e.left),r===void 0&&(r=e.top),{x:t+e.width*.5,y:r+e.height*.5}}const wd=e=>{let{collisionRect:t,droppableRects:r,droppableContainers:s}=e;const a=Jr(t,t.left,t.top),o=[];for(const l of s){const{id:c}=l,d=r.get(c);if(d){const u=na(Jr(d),a);o.push({id:c,data:{droppableContainer:l,value:u}})}}return o.sort(ra)},jd=e=>{let{collisionRect:t,droppableRects:r,droppableContainers:s}=e;const a=Yr(t),o=[];for(const l of s){const{id:c}=l,d=r.get(c);if(d){const u=Yr(d),f=a.reduce((m,h,j)=>m+na(u[j],h),0),p=Number((f/4).toFixed(4));o.push({id:c,data:{droppableContainer:l,value:p}})}}return o.sort(ra)};function Nd(e,t){const r=Math.max(t.top,e.top),s=Math.max(t.left,e.left),a=Math.min(t.left+t.width,e.left+e.width),o=Math.min(t.top+t.height,e.top+e.height),l=a-s,c=o-r;if(s<a&&r<o){const d=t.width*t.height,u=e.width*e.height,f=l*c,p=f/(d+u-f);return Number(p.toFixed(4))}return 0}const Cd=e=>{let{collisionRect:t,droppableRects:r,droppableContainers:s}=e;const a=[];for(const o of s){const{id:l}=o,c=r.get(l);if(c){const d=Nd(c,t);d>0&&a.push({id:l,data:{droppableContainer:o,value:d}})}}return a.sort(yd)};function Sd(e,t,r){return{...e,scaleX:t&&r?t.width/r.width:1,scaleY:t&&r?t.height/r.height:1}}function aa(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Ae}function kd(e){return function(r){for(var s=arguments.length,a=new Array(s>1?s-1:0),o=1;o<s;o++)a[o-1]=arguments[o];return a.reduce((l,c)=>({...l,top:l.top+e*c.y,bottom:l.bottom+e*c.y,left:l.left+e*c.x,right:l.right+e*c.x}),{...r})}}const Ed=kd(1);function Rd(e){if(e.startsWith("matrix3d(")){const t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(e.startsWith("matrix(")){const t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function Td(e,t,r){const s=Rd(t);if(!s)return e;const{scaleX:a,scaleY:o,x:l,y:c}=s,d=e.left-l-(1-a)*parseFloat(r),u=e.top-c-(1-o)*parseFloat(r.slice(r.indexOf(" ")+1)),f=a?e.width/a:e.width,p=o?e.height/o:e.height;return{width:f,height:p,top:u,right:d+f,bottom:u+p,left:d}}const Pd={ignoreTransform:!1};function mt(e,t){t===void 0&&(t=Pd);let r=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:u,transformOrigin:f}=Ce(e).getComputedStyle(e);u&&(r=Td(r,u,f))}const{top:s,left:a,width:o,height:l,bottom:c,right:d}=r;return{top:s,left:a,width:o,height:l,bottom:c,right:d}}function Xr(e){return mt(e,{ignoreTransform:!0})}function Dd(e){const t=e.innerWidth,r=e.innerHeight;return{top:0,left:0,right:t,bottom:r,width:t,height:r}}function Ad(e,t){return t===void 0&&(t=Ce(e).getComputedStyle(e)),t.position==="fixed"}function Ld(e,t){t===void 0&&(t=Ce(e).getComputedStyle(e));const r=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(a=>{const o=t[a];return typeof o=="string"?r.test(o):!1})}function on(e,t){const r=[];function s(a){if(t!=null&&r.length>=t||!a)return r;if(cr(a)&&a.scrollingElement!=null&&!r.includes(a.scrollingElement))return r.push(a.scrollingElement),r;if(!Pt(a)||Zs(a)||r.includes(a))return r;const o=Ce(e).getComputedStyle(a);return a!==e&&Ld(a,o)&&r.push(a),Ad(a,o)?r:s(a.parentNode)}return e?s(e):r}function oa(e){const[t]=on(e,1);return t??null}function Pn(e){return!an||!e?null:ft(e)?e:lr(e)?cr(e)||e===pt(e).scrollingElement?window:Pt(e)?e:null:null}function ia(e){return ft(e)?e.scrollX:e.scrollLeft}function la(e){return ft(e)?e.scrollY:e.scrollTop}function Vn(e){return{x:ia(e),y:la(e)}}var ue;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(ue||(ue={}));function ca(e){return!an||!e?!1:e===document.scrollingElement}function da(e){const t={x:0,y:0},r=ca(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},s={x:e.scrollWidth-r.width,y:e.scrollHeight-r.height},a=e.scrollTop<=t.y,o=e.scrollLeft<=t.x,l=e.scrollTop>=s.y,c=e.scrollLeft>=s.x;return{isTop:a,isLeft:o,isBottom:l,isRight:c,maxScroll:s,minScroll:t}}const Md={x:.2,y:.2};function Id(e,t,r,s,a){let{top:o,left:l,right:c,bottom:d}=r;s===void 0&&(s=10),a===void 0&&(a=Md);const{isTop:u,isBottom:f,isLeft:p,isRight:m}=da(e),h={x:0,y:0},j={x:0,y:0},b={height:t.height*a.y,width:t.width*a.x};return!u&&o<=t.top+b.height?(h.y=ue.Backward,j.y=s*Math.abs((t.top+b.height-o)/b.height)):!f&&d>=t.bottom-b.height&&(h.y=ue.Forward,j.y=s*Math.abs((t.bottom-b.height-d)/b.height)),!m&&c>=t.right-b.width?(h.x=ue.Forward,j.x=s*Math.abs((t.right-b.width-c)/b.width)):!p&&l<=t.left+b.width&&(h.x=ue.Backward,j.x=s*Math.abs((t.left+b.width-l)/b.width)),{direction:h,speed:j}}function Fd(e){if(e===document.scrollingElement){const{innerWidth:o,innerHeight:l}=window;return{top:0,left:0,right:o,bottom:l,width:o,height:l}}const{top:t,left:r,right:s,bottom:a}=e.getBoundingClientRect();return{top:t,left:r,right:s,bottom:a,width:e.clientWidth,height:e.clientHeight}}function ua(e){return e.reduce((t,r)=>lt(t,Vn(r)),Ae)}function Od(e){return e.reduce((t,r)=>t+ia(r),0)}function Bd(e){return e.reduce((t,r)=>t+la(r),0)}function $d(e,t){if(t===void 0&&(t=mt),!e)return;const{top:r,left:s,bottom:a,right:o}=t(e);oa(e)&&(a<=0||o<=0||r>=window.innerHeight||s>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const _d=[["x",["left","right"],Od],["y",["top","bottom"],Bd]];class fr{constructor(t,r){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const s=on(r),a=ua(s);this.rect={...t},this.width=t.width,this.height=t.height;for(const[o,l,c]of _d)for(const d of l)Object.defineProperty(this,d,{get:()=>{const u=c(s),f=a[o]-u;return this.rect[d]+f},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class yt{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(r=>{var s;return(s=this.target)==null?void 0:s.removeEventListener(...r)})},this.target=t}add(t,r,s){var a;(a=this.target)==null||a.addEventListener(t,r,s),this.listeners.push([t,r,s])}}function zd(e){const{EventTarget:t}=Ce(e);return e instanceof t?e:pt(e)}function Dn(e,t){const r=Math.abs(e.x),s=Math.abs(e.y);return typeof t=="number"?Math.sqrt(r**2+s**2)>t:"x"in t&&"y"in t?r>t.x&&s>t.y:"x"in t?r>t.x:"y"in t?s>t.y:!1}var Te;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(Te||(Te={}));function qr(e){e.preventDefault()}function Hd(e){e.stopPropagation()}var q;(function(e){e.Space="Space",e.Down="ArrowDown",e.Right="ArrowRight",e.Left="ArrowLeft",e.Up="ArrowUp",e.Esc="Escape",e.Enter="Enter",e.Tab="Tab"})(q||(q={}));const fa={start:[q.Space,q.Enter],cancel:[q.Esc],end:[q.Space,q.Enter,q.Tab]},Wd=(e,t)=>{let{currentCoordinates:r}=t;switch(e.code){case q.Right:return{...r,x:r.x+25};case q.Left:return{...r,x:r.x-25};case q.Down:return{...r,y:r.y+25};case q.Up:return{...r,y:r.y-25}}};class pr{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:r}}=t;this.props=t,this.listeners=new yt(pt(r)),this.windowListeners=new yt(Ce(r)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Te.Resize,this.handleCancel),this.windowListeners.add(Te.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Te.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:r}=this.props,s=t.node.current;s&&$d(s),r(Ae)}handleKeyDown(t){if(ur(t)){const{active:r,context:s,options:a}=this.props,{keyboardCodes:o=fa,coordinateGetter:l=Wd,scrollBehavior:c="smooth"}=a,{code:d}=t;if(o.end.includes(d)){this.handleEnd(t);return}if(o.cancel.includes(d)){this.handleCancel(t);return}const{collisionRect:u}=s.current,f=u?{x:u.left,y:u.top}:Ae;this.referenceCoordinates||(this.referenceCoordinates=f);const p=l(t,{active:r,context:s.current,currentCoordinates:f});if(p){const m=St(p,f),h={x:0,y:0},{scrollableAncestors:j}=s.current;for(const b of j){const g=t.code,{isTop:w,isRight:v,isLeft:x,isBottom:y,maxScroll:N,minScroll:C}=da(b),S=Fd(b),k={x:Math.min(g===q.Right?S.right-S.width/2:S.right,Math.max(g===q.Right?S.left:S.left+S.width/2,p.x)),y:Math.min(g===q.Down?S.bottom-S.height/2:S.bottom,Math.max(g===q.Down?S.top:S.top+S.height/2,p.y))},R=g===q.Right&&!v||g===q.Left&&!x,E=g===q.Down&&!y||g===q.Up&&!w;if(R&&k.x!==p.x){const T=b.scrollLeft+m.x,M=g===q.Right&&T<=N.x||g===q.Left&&T>=C.x;if(M&&!m.y){b.scrollTo({left:T,behavior:c});return}M?h.x=b.scrollLeft-T:h.x=g===q.Right?b.scrollLeft-N.x:b.scrollLeft-C.x,h.x&&b.scrollBy({left:-h.x,behavior:c});break}else if(E&&k.y!==p.y){const T=b.scrollTop+m.y,M=g===q.Down&&T<=N.y||g===q.Up&&T>=C.y;if(M&&!m.x){b.scrollTo({top:T,behavior:c});return}M?h.y=b.scrollTop-T:h.y=g===q.Down?b.scrollTop-N.y:b.scrollTop-C.y,h.y&&b.scrollBy({top:-h.y,behavior:c});break}}this.handleMove(t,lt(St(p,this.referenceCoordinates),h))}}}handleMove(t,r){const{onMove:s}=this.props;t.preventDefault(),s(r)}handleEnd(t){const{onEnd:r}=this.props;t.preventDefault(),this.detach(),r()}handleCancel(t){const{onCancel:r}=this.props;t.preventDefault(),this.detach(),r()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}pr.activators=[{eventName:"onKeyDown",handler:(e,t,r)=>{let{keyboardCodes:s=fa,onActivation:a}=t,{active:o}=r;const{code:l}=e.nativeEvent;if(s.start.includes(l)){const c=o.activatorNode.current;return c&&e.target!==c?!1:(e.preventDefault(),a==null||a({event:e.nativeEvent}),!0)}return!1}}];function Qr(e){return!!(e&&"distance"in e)}function Zr(e){return!!(e&&"delay"in e)}class mr{constructor(t,r,s){var a;s===void 0&&(s=zd(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=r;const{event:o}=t,{target:l}=o;this.props=t,this.events=r,this.document=pt(l),this.documentListeners=new yt(this.document),this.listeners=new yt(s),this.windowListeners=new yt(Ce(l)),this.initialCoordinates=(a=Wn(o))!=null?a:Ae,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:t,props:{options:{activationConstraint:r,bypassActivationConstraint:s}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add(Te.Resize,this.handleCancel),this.windowListeners.add(Te.DragStart,qr),this.windowListeners.add(Te.VisibilityChange,this.handleCancel),this.windowListeners.add(Te.ContextMenu,qr),this.documentListeners.add(Te.Keydown,this.handleKeydown),r){if(s!=null&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Zr(r)){this.timeoutId=setTimeout(this.handleStart,r.delay),this.handlePending(r);return}if(Qr(r)){this.handlePending(r);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,r){const{active:s,onPending:a}=this.props;a(s,t,this.initialCoordinates,r)}handleStart(){const{initialCoordinates:t}=this,{onStart:r}=this.props;t&&(this.activated=!0,this.documentListeners.add(Te.Click,Hd,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Te.SelectionChange,this.removeTextSelection),r(t))}handleMove(t){var r;const{activated:s,initialCoordinates:a,props:o}=this,{onMove:l,options:{activationConstraint:c}}=o;if(!a)return;const d=(r=Wn(t))!=null?r:Ae,u=St(a,d);if(!s&&c){if(Qr(c)){if(c.tolerance!=null&&Dn(u,c.tolerance))return this.handleCancel();if(Dn(u,c.distance))return this.handleStart()}if(Zr(c)&&Dn(u,c.tolerance))return this.handleCancel();this.handlePending(c,u);return}t.cancelable&&t.preventDefault(),l(d)}handleEnd(){const{onAbort:t,onEnd:r}=this.props;this.detach(),this.activated||t(this.props.active),r()}handleCancel(){const{onAbort:t,onCancel:r}=this.props;this.detach(),this.activated||t(this.props.active),r()}handleKeydown(t){t.code===q.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const Vd={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class xr extends mr{constructor(t){const{event:r}=t,s=pt(r.target);super(t,Vd,s)}}xr.activators=[{eventName:"onPointerDown",handler:(e,t)=>{let{nativeEvent:r}=e,{onActivation:s}=t;return!r.isPrimary||r.button!==0?!1:(s==null||s({event:r}),!0)}}];const Ud={move:{name:"mousemove"},end:{name:"mouseup"}};var Un;(function(e){e[e.RightClick=2]="RightClick"})(Un||(Un={}));class Kd extends mr{constructor(t){super(t,Ud,pt(t.event.target))}}Kd.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:r}=e,{onActivation:s}=t;return r.button===Un.RightClick?!1:(s==null||s({event:r}),!0)}}];const An={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class Gd extends mr{constructor(t){super(t,An)}static setup(){return window.addEventListener(An.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(An.move.name,t)};function t(){}}}Gd.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:r}=e,{onActivation:s}=t;const{touches:a}=r;return a.length>1?!1:(s==null||s({event:r}),!0)}}];var wt;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(wt||(wt={}));var tn;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(tn||(tn={}));function Yd(e){let{acceleration:t,activator:r=wt.Pointer,canScroll:s,draggingRect:a,enabled:o,interval:l=5,order:c=tn.TreeOrder,pointerCoordinates:d,scrollableAncestors:u,scrollableAncestorRects:f,delta:p,threshold:m}=e;const h=Xd({delta:p,disabled:!o}),[j,b]=od(),g=i.useRef({x:0,y:0}),w=i.useRef({x:0,y:0}),v=i.useMemo(()=>{switch(r){case wt.Pointer:return d?{top:d.y,bottom:d.y,left:d.x,right:d.x}:null;case wt.DraggableRect:return a}},[r,a,d]),x=i.useRef(null),y=i.useCallback(()=>{const C=x.current;if(!C)return;const S=g.current.x*w.current.x,k=g.current.y*w.current.y;C.scrollBy(S,k)},[]),N=i.useMemo(()=>c===tn.TreeOrder?[...u].reverse():u,[c,u]);i.useEffect(()=>{if(!o||!u.length||!v){b();return}for(const C of N){if((s==null?void 0:s(C))===!1)continue;const S=u.indexOf(C),k=f[S];if(!k)continue;const{direction:R,speed:E}=Id(C,k,v,t,m);for(const T of["x","y"])h[T][R[T]]||(E[T]=0,R[T]=0);if(E.x>0||E.y>0){b(),x.current=C,j(y,l),g.current=E,w.current=R;return}}g.current={x:0,y:0},w.current={x:0,y:0},b()},[t,y,s,b,o,l,JSON.stringify(v),JSON.stringify(h),j,u,N,f,JSON.stringify(m)])}const Jd={x:{[ue.Backward]:!1,[ue.Forward]:!1},y:{[ue.Backward]:!1,[ue.Forward]:!1}};function Xd(e){let{delta:t,disabled:r}=e;const s=Hn(t);return Dt(a=>{if(r||!s||!a)return Jd;const o={x:Math.sign(t.x-s.x),y:Math.sign(t.y-s.y)};return{x:{[ue.Backward]:a.x[ue.Backward]||o.x===-1,[ue.Forward]:a.x[ue.Forward]||o.x===1},y:{[ue.Backward]:a.y[ue.Backward]||o.y===-1,[ue.Forward]:a.y[ue.Forward]||o.y===1}}},[r,t,s])}function qd(e,t){const r=t!=null?e.get(t):void 0,s=r?r.node.current:null;return Dt(a=>{var o;return t==null?null:(o=s??a)!=null?o:null},[s,t])}function Qd(e,t){return i.useMemo(()=>e.reduce((r,s)=>{const{sensor:a}=s,o=a.activators.map(l=>({eventName:l.eventName,handler:t(l.handler,s)}));return[...r,...o]},[]),[e,t])}var Et;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Et||(Et={}));var Kn;(function(e){e.Optimized="optimized"})(Kn||(Kn={}));const es=new Map;function Zd(e,t){let{dragging:r,dependencies:s,config:a}=t;const[o,l]=i.useState(null),{frequency:c,measure:d,strategy:u}=a,f=i.useRef(e),p=g(),m=Ct(p),h=i.useCallback(function(w){w===void 0&&(w=[]),!m.current&&l(v=>v===null?w:v.concat(w.filter(x=>!v.includes(x))))},[m]),j=i.useRef(null),b=Dt(w=>{if(p&&!r)return es;if(!w||w===es||f.current!==e||o!=null){const v=new Map;for(let x of e){if(!x)continue;if(o&&o.length>0&&!o.includes(x.id)&&x.rect.current){v.set(x.id,x.rect.current);continue}const y=x.node.current,N=y?new fr(d(y),y):null;x.rect.current=N,N&&v.set(x.id,N)}return v}return w},[e,o,r,p,d]);return i.useEffect(()=>{f.current=e},[e]),i.useEffect(()=>{p||h()},[r,p]),i.useEffect(()=>{o&&o.length>0&&l(null)},[JSON.stringify(o)]),i.useEffect(()=>{p||typeof c!="number"||j.current!==null||(j.current=setTimeout(()=>{h(),j.current=null},c))},[c,p,h,...s]),{droppableRects:b,measureDroppableContainers:h,measuringScheduled:o!=null};function g(){switch(u){case Et.Always:return!1;case Et.BeforeDragging:return r;default:return!r}}}function pa(e,t){return Dt(r=>e?r||(typeof t=="function"?t(e):e):null,[t,e])}function eu(e,t){return pa(e,t)}function tu(e){let{callback:t,disabled:r}=e;const s=dr(t),a=i.useMemo(()=>{if(r||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:o}=window;return new o(s)},[s,r]);return i.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function ln(e){let{callback:t,disabled:r}=e;const s=dr(t),a=i.useMemo(()=>{if(r||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:o}=window;return new o(s)},[r]);return i.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function nu(e){return new fr(mt(e),e)}function ts(e,t,r){t===void 0&&(t=nu);const[s,a]=i.useState(null);function o(){a(d=>{if(!e)return null;if(e.isConnected===!1){var u;return(u=d??r)!=null?u:null}const f=t(e);return JSON.stringify(d)===JSON.stringify(f)?d:f})}const l=tu({callback(d){if(e)for(const u of d){const{type:f,target:p}=u;if(f==="childList"&&p instanceof HTMLElement&&p.contains(e)){o();break}}}}),c=ln({callback:o});return Be(()=>{o(),e?(c==null||c.observe(e),l==null||l.observe(document.body,{childList:!0,subtree:!0})):(c==null||c.disconnect(),l==null||l.disconnect())},[e]),s}function ru(e){const t=pa(e);return aa(e,t)}const ns=[];function su(e){const t=i.useRef(e),r=Dt(s=>e?s&&s!==ns&&e&&t.current&&e.parentNode===t.current.parentNode?s:on(e):ns,[e]);return i.useEffect(()=>{t.current=e},[e]),r}function au(e){const[t,r]=i.useState(null),s=i.useRef(e),a=i.useCallback(o=>{const l=Pn(o.target);l&&r(c=>c?(c.set(l,Vn(l)),new Map(c)):null)},[]);return i.useEffect(()=>{const o=s.current;if(e!==o){l(o);const c=e.map(d=>{const u=Pn(d);return u?(u.addEventListener("scroll",a,{passive:!0}),[u,Vn(u)]):null}).filter(d=>d!=null);r(c.length?new Map(c):null),s.current=e}return()=>{l(e),l(o)};function l(c){c.forEach(d=>{const u=Pn(d);u==null||u.removeEventListener("scroll",a)})}},[a,e]),i.useMemo(()=>e.length?t?Array.from(t.values()).reduce((o,l)=>lt(o,l),Ae):ua(e):Ae,[e,t])}function rs(e,t){t===void 0&&(t=[]);const r=i.useRef(null);return i.useEffect(()=>{r.current=null},t),i.useEffect(()=>{const s=e!==Ae;s&&!r.current&&(r.current=e),!s&&r.current&&(r.current=null)},[e]),r.current?St(e,r.current):Ae}function ou(e){i.useEffect(()=>{if(!an)return;const t=e.map(r=>{let{sensor:s}=r;return s.setup==null?void 0:s.setup()});return()=>{for(const r of t)r==null||r()}},e.map(t=>{let{sensor:r}=t;return r}))}function iu(e,t){return i.useMemo(()=>e.reduce((r,s)=>{let{eventName:a,handler:o}=s;return r[a]=l=>{o(l,t)},r},{}),[e,t])}function ma(e){return i.useMemo(()=>e?Dd(e):null,[e])}const ss=[];function lu(e,t){t===void 0&&(t=mt);const[r]=e,s=ma(r?Ce(r):null),[a,o]=i.useState(ss);function l(){o(()=>e.length?e.map(d=>ca(d)?s:new fr(t(d),d)):ss)}const c=ln({callback:l});return Be(()=>{c==null||c.disconnect(),l(),e.forEach(d=>c==null?void 0:c.observe(d))},[e]),a}function cu(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return Pt(t)?t:e}function du(e){let{measure:t}=e;const[r,s]=i.useState(null),a=i.useCallback(u=>{for(const{target:f}of u)if(Pt(f)){s(p=>{const m=t(f);return p?{...p,width:m.width,height:m.height}:m});break}},[t]),o=ln({callback:a}),l=i.useCallback(u=>{const f=cu(u);o==null||o.disconnect(),f&&(o==null||o.observe(f)),s(f?t(f):null)},[t,o]),[c,d]=Zt(l);return i.useMemo(()=>({nodeRef:c,rect:r,setRef:d}),[r,c,d])}const uu=[{sensor:xr,options:{}},{sensor:pr,options:{}}],fu={current:{}},Yt={draggable:{measure:Xr},droppable:{measure:Xr,strategy:Et.WhileDragging,frequency:Kn.Optimized},dragOverlay:{measure:mt}};class jt extends Map{get(t){var r;return t!=null&&(r=super.get(t))!=null?r:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:r}=t;return!r})}getNodeFor(t){var r,s;return(r=(s=this.get(t))==null?void 0:s.node.current)!=null?r:void 0}}const pu={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new jt,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:en},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Yt,measureDroppableContainers:en,windowRect:null,measuringScheduled:!1},mu={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:en,draggableNodes:new Map,over:null,measureDroppableContainers:en},cn=i.createContext(mu),xa=i.createContext(pu);function xu(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new jt}}}function hu(e,t){switch(t.type){case le.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case le.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case le.DragEnd:case le.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case le.RegisterDroppable:{const{element:r}=t,{id:s}=r,a=new jt(e.droppable.containers);return a.set(s,r),{...e,droppable:{...e.droppable,containers:a}}}case le.SetDroppableDisabled:{const{id:r,key:s,disabled:a}=t,o=e.droppable.containers.get(r);if(!o||s!==o.key)return e;const l=new jt(e.droppable.containers);return l.set(r,{...o,disabled:a}),{...e,droppable:{...e.droppable,containers:l}}}case le.UnregisterDroppable:{const{id:r,key:s}=t,a=e.droppable.containers.get(r);if(!a||s!==a.key)return e;const o=new jt(e.droppable.containers);return o.delete(r),{...e,droppable:{...e.droppable,containers:o}}}default:return e}}function gu(e){let{disabled:t}=e;const{active:r,activatorEvent:s,draggableNodes:a}=i.useContext(cn),o=Hn(s),l=Hn(r==null?void 0:r.id);return i.useEffect(()=>{if(!t&&!s&&o&&l!=null){if(!ur(o)||document.activeElement===o.target)return;const c=a.get(l);if(!c)return;const{activatorNode:d,node:u}=c;if(!d.current&&!u.current)return;requestAnimationFrame(()=>{for(const f of[d.current,u.current]){if(!f)continue;const p=cd(f);if(p){p.focus();break}}})}},[s,t,a,l,o]),null}function vu(e,t){let{transform:r,...s}=t;return e!=null&&e.length?e.reduce((a,o)=>o({transform:a,...s}),r):r}function bu(e){return i.useMemo(()=>({draggable:{...Yt.draggable,...e==null?void 0:e.draggable},droppable:{...Yt.droppable,...e==null?void 0:e.droppable},dragOverlay:{...Yt.dragOverlay,...e==null?void 0:e.dragOverlay}}),[e==null?void 0:e.draggable,e==null?void 0:e.droppable,e==null?void 0:e.dragOverlay])}function yu(e){let{activeNode:t,measure:r,initialRect:s,config:a=!0}=e;const o=i.useRef(!1),{x:l,y:c}=typeof a=="boolean"?{x:a,y:a}:a;Be(()=>{if(!l&&!c||!t){o.current=!1;return}if(o.current||!s)return;const u=t==null?void 0:t.node.current;if(!u||u.isConnected===!1)return;const f=r(u),p=aa(f,s);if(l||(p.x=0),c||(p.y=0),o.current=!0,Math.abs(p.x)>0||Math.abs(p.y)>0){const m=oa(u);m&&m.scrollBy({top:p.y,left:p.x})}},[t,l,c,s,r])}const ha=i.createContext({...Ae,scaleX:1,scaleY:1});var Ke;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(Ke||(Ke={}));const wu=i.memo(function(t){var r,s,a,o;let{id:l,accessibility:c,autoScroll:d=!0,children:u,sensors:f=uu,collisionDetection:p=Cd,measuring:m,modifiers:h,...j}=t;const b=i.useReducer(hu,void 0,xu),[g,w]=b,[v,x]=xd(),[y,N]=i.useState(Ke.Uninitialized),C=y===Ke.Initialized,{draggable:{active:S,nodes:k,translate:R},droppable:{containers:E}}=g,T=S!=null?k.get(S):null,M=i.useRef({initial:null,translated:null}),F=i.useMemo(()=>{var re;return S!=null?{id:S,data:(re=T==null?void 0:T.data)!=null?re:fu,rect:M}:null},[S,T]),I=i.useRef(null),[z,J]=i.useState(null),[D,O]=i.useState(null),H=Ct(j,Object.values(j)),$=At("DndDescribedBy",l),K=i.useMemo(()=>E.getEnabled(),[E]),B=bu(m),{droppableRects:Q,measureDroppableContainers:U,measuringScheduled:L}=Zd(K,{dragging:C,dependencies:[R.x,R.y],config:B.droppable}),A=qd(k,S),X=i.useMemo(()=>D?Wn(D):null,[D]),G=pn(),ee=eu(A,B.draggable.measure);yu({activeNode:S!=null?k.get(S):null,config:G.layoutShiftCompensation,initialRect:ee,measure:B.draggable.measure});const W=ts(A,B.draggable.measure,ee),P=ts(A?A.parentElement:null),ne=i.useRef({activatorEvent:null,active:null,activeNode:A,collisionRect:null,collisions:null,droppableRects:Q,draggableNodes:k,draggingNode:null,draggingNodeRect:null,droppableContainers:E,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),se=E.getNodeFor((r=ne.current.over)==null?void 0:r.id),ae=du({measure:B.dragOverlay.measure}),ce=(s=ae.nodeRef.current)!=null?s:A,Y=C?(a=ae.rect)!=null?a:W:null,te=!!(ae.nodeRef.current&&ae.rect),fe=ru(te?null:W),ge=ma(ce?Ce(ce):null),be=su(C?se??A:null),ke=lu(be),de=vu(h,{transform:{x:R.x-fe.x,y:R.y-fe.y,scaleX:1,scaleY:1},activatorEvent:D,active:F,activeNodeRect:W,containerNodeRect:P,draggingNodeRect:Y,over:ne.current.over,overlayNodeRect:ae.rect,scrollableAncestors:be,scrollableAncestorRects:ke,windowRect:ge}),rt=X?lt(X,R):null,_e=au(be),st=rs(_e),Ee=rs(_e,[W]),Pe=lt(de,st),_=Y?Ed(Y,de):null,oe=F&&_?p({active:F,collisionRect:_,droppableRects:Q,droppableContainers:K,pointerCoordinates:rt}):null,ze=sa(oe,"id"),[pe,Ge]=i.useState(null),dn=te?de:lt(de,Ee),un=Sd(dn,(o=pe==null?void 0:pe.rect)!=null?o:null,W),De=i.useRef(null),xt=i.useCallback((re,he)=>{let{sensor:me,options:Le}=he;if(I.current==null)return;const ye=k.get(I.current);if(!ye)return;const ve=re.nativeEvent,we=new me({active:I.current,activeNode:ye,event:ve,options:Le,context:ne,onAbort(ie){if(!k.get(ie))return;const{onDragAbort:Re}=H.current,je={id:ie};Re==null||Re(je),v({type:"onDragAbort",event:je})},onPending(ie,Me,Re,je){if(!k.get(ie))return;const{onDragPending:Ye}=H.current,Ie={id:ie,constraint:Me,initialCoordinates:Re,offset:je};Ye==null||Ye(Ie),v({type:"onDragPending",event:Ie})},onStart(ie){const Me=I.current;if(Me==null)return;const Re=k.get(Me);if(!Re)return;const{onDragStart:je}=H.current,xe={activatorEvent:ve,active:{id:Me,data:Re.data,rect:M}};vt.unstable_batchedUpdates(()=>{je==null||je(xe),N(Ke.Initializing),w({type:le.DragStart,initialCoordinates:ie,active:Me}),v({type:"onDragStart",event:xe}),J(De.current),O(ve)})},onMove(ie){w({type:le.DragMove,coordinates:ie})},onEnd:Ue(le.DragEnd),onCancel:Ue(le.DragCancel)});De.current=we;function Ue(ie){return async function(){const{active:Re,collisions:je,over:xe,scrollAdjustedTranslate:Ye}=ne.current;let Ie=null;if(Re&&Ye){const{cancelDrop:Je}=H.current;Ie={activatorEvent:ve,active:Re,collisions:je,delta:Ye,over:xe},ie===le.DragEnd&&typeof Je=="function"&&await Promise.resolve(Je(Ie))&&(ie=le.DragCancel)}I.current=null,vt.unstable_batchedUpdates(()=>{w({type:ie}),N(Ke.Uninitialized),Ge(null),J(null),O(null),De.current=null;const Je=ie===le.DragEnd?"onDragEnd":"onDragCancel";if(Ie){const ht=H.current[Je];ht==null||ht(Ie),v({type:Je,event:Ie})}})}}},[k]),fn=i.useCallback((re,he)=>(me,Le)=>{const ye=me.nativeEvent,ve=k.get(Le);if(I.current!==null||!ve||ye.dndKit||ye.defaultPrevented)return;const we={active:ve};re(me,he.options,we)===!0&&(ye.dndKit={capturedBy:he.sensor},I.current=Le,xt(me,he))},[k,xt]),It=Qd(f,fn);ou(f),Be(()=>{W&&y===Ke.Initializing&&N(Ke.Initialized)},[W,y]),i.useEffect(()=>{const{onDragMove:re}=H.current,{active:he,activatorEvent:me,collisions:Le,over:ye}=ne.current;if(!he||!me)return;const ve={active:he,activatorEvent:me,collisions:Le,delta:{x:Pe.x,y:Pe.y},over:ye};vt.unstable_batchedUpdates(()=>{re==null||re(ve),v({type:"onDragMove",event:ve})})},[Pe.x,Pe.y]),i.useEffect(()=>{const{active:re,activatorEvent:he,collisions:me,droppableContainers:Le,scrollAdjustedTranslate:ye}=ne.current;if(!re||I.current==null||!he||!ye)return;const{onDragOver:ve}=H.current,we=Le.get(ze),Ue=we&&we.rect.current?{id:we.id,rect:we.rect.current,data:we.data,disabled:we.disabled}:null,ie={active:re,activatorEvent:he,collisions:me,delta:{x:ye.x,y:ye.y},over:Ue};vt.unstable_batchedUpdates(()=>{Ge(Ue),ve==null||ve(ie),v({type:"onDragOver",event:ie})})},[ze]),Be(()=>{ne.current={activatorEvent:D,active:F,activeNode:A,collisionRect:_,collisions:oe,droppableRects:Q,draggableNodes:k,draggingNode:ce,draggingNodeRect:Y,droppableContainers:E,over:pe,scrollableAncestors:be,scrollAdjustedTranslate:Pe},M.current={initial:Y,translated:_}},[F,A,oe,_,k,ce,Y,Q,E,pe,be,Pe]),Yd({...G,delta:R,draggingRect:_,pointerCoordinates:rt,scrollableAncestors:be,scrollableAncestorRects:ke});const Ft=i.useMemo(()=>({active:F,activeNode:A,activeNodeRect:W,activatorEvent:D,collisions:oe,containerNodeRect:P,dragOverlay:ae,draggableNodes:k,droppableContainers:E,droppableRects:Q,over:pe,measureDroppableContainers:U,scrollableAncestors:be,scrollableAncestorRects:ke,measuringConfiguration:B,measuringScheduled:L,windowRect:ge}),[F,A,W,D,oe,P,ae,k,E,Q,pe,U,be,ke,B,L,ge]),Ve=i.useMemo(()=>({activatorEvent:D,activators:It,active:F,activeNodeRect:W,ariaDescribedById:{draggable:$},dispatch:w,draggableNodes:k,over:pe,measureDroppableContainers:U}),[D,It,F,W,w,$,k,pe,U]);return Ne.createElement(ta.Provider,{value:x},Ne.createElement(cn.Provider,{value:Ve},Ne.createElement(xa.Provider,{value:Ft},Ne.createElement(ha.Provider,{value:un},u)),Ne.createElement(gu,{disabled:(c==null?void 0:c.restoreFocus)===!1})),Ne.createElement(vd,{...c,hiddenTextDescribedById:$}));function pn(){const re=(z==null?void 0:z.autoScrollEnabled)===!1,he=typeof d=="object"?d.enabled===!1:d===!1,me=C&&!re&&!he;return typeof d=="object"?{...d,enabled:me}:{enabled:me}}}),ju=i.createContext(null),as="button",Nu="Draggable";function Cu(e){let{id:t,data:r,disabled:s=!1,attributes:a}=e;const o=At(Nu),{activators:l,activatorEvent:c,active:d,activeNodeRect:u,ariaDescribedById:f,draggableNodes:p,over:m}=i.useContext(cn),{role:h=as,roleDescription:j="draggable",tabIndex:b=0}=a??{},g=(d==null?void 0:d.id)===t,w=i.useContext(g?ha:ju),[v,x]=Zt(),[y,N]=Zt(),C=iu(l,t),S=Ct(r);Be(()=>(p.set(t,{id:t,key:o,node:v,activatorNode:y,data:S}),()=>{const R=p.get(t);R&&R.key===o&&p.delete(t)}),[p,t]);const k=i.useMemo(()=>({role:h,tabIndex:b,"aria-disabled":s,"aria-pressed":g&&h===as?!0:void 0,"aria-roledescription":j,"aria-describedby":f.draggable}),[s,h,b,g,j,f.draggable]);return{active:d,activatorEvent:c,activeNodeRect:u,attributes:k,isDragging:g,listeners:s?void 0:C,node:v,over:m,setNodeRef:x,setActivatorNodeRef:N,transform:w}}function Su(){return i.useContext(xa)}const ku="Droppable",Eu={timeout:25};function Ru(e){let{data:t,disabled:r=!1,id:s,resizeObserverConfig:a}=e;const o=At(ku),{active:l,dispatch:c,over:d,measureDroppableContainers:u}=i.useContext(cn),f=i.useRef({disabled:r}),p=i.useRef(!1),m=i.useRef(null),h=i.useRef(null),{disabled:j,updateMeasurementsFor:b,timeout:g}={...Eu,...a},w=Ct(b??s),v=i.useCallback(()=>{if(!p.current){p.current=!0;return}h.current!=null&&clearTimeout(h.current),h.current=setTimeout(()=>{u(Array.isArray(w.current)?w.current:[w.current]),h.current=null},g)},[g]),x=ln({callback:v,disabled:j||!l}),y=i.useCallback((k,R)=>{x&&(R&&(x.unobserve(R),p.current=!1),k&&x.observe(k))},[x]),[N,C]=Zt(y),S=Ct(t);return i.useEffect(()=>{!x||!N.current||(x.disconnect(),p.current=!1,x.observe(N.current))},[N,x]),i.useEffect(()=>(c({type:le.RegisterDroppable,element:{id:s,key:o,disabled:r,node:N,rect:m,data:S}}),()=>c({type:le.UnregisterDroppable,key:o,id:s})),[s]),i.useEffect(()=>{r!==f.current.disabled&&(c({type:le.SetDroppableDisabled,id:s,key:o,disabled:r}),f.current.disabled=r)},[s,o,r,c]),{active:l,rect:m,isOver:(d==null?void 0:d.id)===s,node:N,over:d,setNodeRef:C}}function hr(e,t,r){const s=e.slice();return s.splice(r<0?s.length+r:r,0,s.splice(t,1)[0]),s}function Tu(e,t){return e.reduce((r,s,a)=>{const o=t.get(s);return o&&(r[a]=o),r},Array(e.length))}function zt(e){return e!==null&&e>=0}function Pu(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function Du(e){return typeof e=="boolean"?{draggable:e,droppable:e}:e}const ga=e=>{let{rects:t,activeIndex:r,overIndex:s,index:a}=e;const o=hr(t,s,r),l=t[a],c=o[a];return!c||!l?null:{x:c.left-l.left,y:c.top-l.top,scaleX:c.width/l.width,scaleY:c.height/l.height}},Ht={scaleX:1,scaleY:1},Au=e=>{var t;let{activeIndex:r,activeNodeRect:s,index:a,rects:o,overIndex:l}=e;const c=(t=o[r])!=null?t:s;if(!c)return null;if(a===r){const u=o[l];return u?{x:0,y:r<l?u.top+u.height-(c.top+c.height):u.top-c.top,...Ht}:null}const d=Lu(o,a,r);return a>r&&a<=l?{x:0,y:-c.height-d,...Ht}:a<r&&a>=l?{x:0,y:c.height+d,...Ht}:{x:0,y:0,...Ht}};function Lu(e,t,r){const s=e[t],a=e[t-1],o=e[t+1];return s?r<t?a?s.top-(a.top+a.height):o?o.top-(s.top+s.height):0:o?o.top-(s.top+s.height):a?s.top-(a.top+a.height):0:0}const va="Sortable",ba=Ne.createContext({activeIndex:-1,containerId:va,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:ga,disabled:{draggable:!1,droppable:!1}});function Mu(e){let{children:t,id:r,items:s,strategy:a=ga,disabled:o=!1}=e;const{active:l,dragOverlay:c,droppableRects:d,over:u,measureDroppableContainers:f}=Su(),p=At(va,r),m=c.rect!==null,h=i.useMemo(()=>s.map(C=>typeof C=="object"&&"id"in C?C.id:C),[s]),j=l!=null,b=l?h.indexOf(l.id):-1,g=u?h.indexOf(u.id):-1,w=i.useRef(h),v=!Pu(h,w.current),x=g!==-1&&b===-1||v,y=Du(o);Be(()=>{v&&j&&f(h)},[v,h,j,f]),i.useEffect(()=>{w.current=h},[h]);const N=i.useMemo(()=>({activeIndex:b,containerId:p,disabled:y,disableTransforms:x,items:h,overIndex:g,useDragOverlay:m,sortedRects:Tu(h,d),strategy:a}),[b,p,y.draggable,y.droppable,x,h,g,d,m,a]);return Ne.createElement(ba.Provider,{value:N},t)}const Iu=e=>{let{id:t,items:r,activeIndex:s,overIndex:a}=e;return hr(r,s,a).indexOf(t)},Fu=e=>{let{containerId:t,isSorting:r,wasDragging:s,index:a,items:o,newIndex:l,previousItems:c,previousContainerId:d,transition:u}=e;return!u||!s||c!==o&&a===l?!1:r?!0:l!==a&&t===d},Ou={duration:200,easing:"ease"},ya="transform",Bu=kt.Transition.toString({property:ya,duration:0,easing:"linear"}),$u={roleDescription:"sortable"};function _u(e){let{disabled:t,index:r,node:s,rect:a}=e;const[o,l]=i.useState(null),c=i.useRef(r);return Be(()=>{if(!t&&r!==c.current&&s.current){const d=a.current;if(d){const u=mt(s.current,{ignoreTransform:!0}),f={x:d.left-u.left,y:d.top-u.top,scaleX:d.width/u.width,scaleY:d.height/u.height};(f.x||f.y)&&l(f)}}r!==c.current&&(c.current=r)},[t,r,s,a]),i.useEffect(()=>{o&&l(null)},[o]),o}function zu(e){let{animateLayoutChanges:t=Fu,attributes:r,disabled:s,data:a,getNewIndex:o=Iu,id:l,strategy:c,resizeObserverConfig:d,transition:u=Ou}=e;const{items:f,containerId:p,activeIndex:m,disabled:h,disableTransforms:j,sortedRects:b,overIndex:g,useDragOverlay:w,strategy:v}=i.useContext(ba),x=Hu(s,h),y=f.indexOf(l),N=i.useMemo(()=>({sortable:{containerId:p,index:y,items:f},...a}),[p,a,y,f]),C=i.useMemo(()=>f.slice(f.indexOf(l)),[f,l]),{rect:S,node:k,isOver:R,setNodeRef:E}=Ru({id:l,data:N,disabled:x.droppable,resizeObserverConfig:{updateMeasurementsFor:C,...d}}),{active:T,activatorEvent:M,activeNodeRect:F,attributes:I,setNodeRef:z,listeners:J,isDragging:D,over:O,setActivatorNodeRef:H,transform:$}=Cu({id:l,data:N,attributes:{...$u,...r},disabled:x.draggable}),K=ad(E,z),B=!!T,Q=B&&!j&&zt(m)&&zt(g),U=!w&&D,L=U&&Q?$:null,X=Q?L??(c??v)({rects:b,activeNodeRect:F,activeIndex:m,overIndex:g,index:y}):null,G=zt(m)&&zt(g)?o({id:l,items:f,activeIndex:m,overIndex:g}):y,ee=T==null?void 0:T.id,W=i.useRef({activeId:ee,items:f,newIndex:G,containerId:p}),P=f!==W.current.items,ne=t({active:T,containerId:p,isDragging:D,isSorting:B,id:l,index:y,items:f,newIndex:W.current.newIndex,previousItems:W.current.items,previousContainerId:W.current.containerId,transition:u,wasDragging:W.current.activeId!=null}),se=_u({disabled:!ne,index:y,node:k,rect:S});return i.useEffect(()=>{B&&W.current.newIndex!==G&&(W.current.newIndex=G),p!==W.current.containerId&&(W.current.containerId=p),f!==W.current.items&&(W.current.items=f)},[B,G,p,f]),i.useEffect(()=>{if(ee===W.current.activeId)return;if(ee!=null&&W.current.activeId==null){W.current.activeId=ee;return}const ce=setTimeout(()=>{W.current.activeId=ee},50);return()=>clearTimeout(ce)},[ee]),{active:T,activeIndex:m,attributes:I,data:N,rect:S,index:y,newIndex:G,items:f,isOver:R,isSorting:B,isDragging:D,listeners:J,node:k,overIndex:g,over:O,setNodeRef:K,setActivatorNodeRef:H,setDroppableNodeRef:E,setDraggableNodeRef:z,transform:se??X,transition:ae()};function ae(){if(se||P&&W.current.newIndex===y)return Bu;if(!(U&&!ur(M)||!u)&&(B||ne))return kt.Transition.toString({...u,property:ya})}}function Hu(e,t){var r,s;return typeof e=="boolean"?{draggable:e,droppable:!1}:{draggable:(r=e==null?void 0:e.draggable)!=null?r:t.draggable,droppable:(s=e==null?void 0:e.droppable)!=null?s:t.droppable}}function nn(e){if(!e)return!1;const t=e.data.current;return!!(t&&"sortable"in t&&typeof t.sortable=="object"&&"containerId"in t.sortable&&"items"in t.sortable&&"index"in t.sortable)}const Wu=[q.Down,q.Right,q.Up,q.Left],Vu=(e,t)=>{let{context:{active:r,collisionRect:s,droppableRects:a,droppableContainers:o,over:l,scrollableAncestors:c}}=t;if(Wu.includes(e.code)){if(e.preventDefault(),!r||!s)return;const d=[];o.getEnabled().forEach(p=>{if(!p||p!=null&&p.disabled)return;const m=a.get(p.id);if(m)switch(e.code){case q.Down:s.top<m.top&&d.push(p);break;case q.Up:s.top>m.top&&d.push(p);break;case q.Left:s.left>m.left&&d.push(p);break;case q.Right:s.left<m.left&&d.push(p);break}});const u=jd({collisionRect:s,droppableRects:a,droppableContainers:d});let f=sa(u,"id");if(f===(l==null?void 0:l.id)&&u.length>1&&(f=u[1].id),f!=null){const p=o.get(r.id),m=o.get(f),h=m?a.get(m.id):null,j=m==null?void 0:m.node.current;if(j&&h&&p&&m){const g=on(j).some((C,S)=>c[S]!==C),w=wa(p,m),v=Uu(p,m),x=g||!w?{x:0,y:0}:{x:v?s.width-h.width:0,y:v?s.height-h.height:0},y={x:h.left,y:h.top};return x.x&&x.y?y:St(y,x)}}}};function wa(e,t){return!nn(e)||!nn(t)?!1:e.data.current.sortable.containerId===t.data.current.sortable.containerId}function Uu(e,t){return!nn(e)||!nn(t)||!wa(e,t)?!1:e.data.current.sortable.index<t.data.current.sortable.index}function ja(e,t=Date.now()){if(!e)return"unknown";const r=Date.parse(e);if(Number.isNaN(r))return e;const s=Math.round((t-r)/1e3);if(s<60)return"just now";const a=Math.round(s/60);if(a<60)return`${a}m ago`;const o=Math.round(a/60);return o<24?`${o}h ago`:`${Math.round(o/24)}d ago`}function Na({title:e,filePath:t}){return n.jsxs("div",{className:"px-3 py-2 border-b border-[var(--border-subtle)]",children:[n.jsx("div",{className:"text-sm font-medium text-[var(--text-primary)] break-words",children:e}),n.jsx("div",{"data-testid":"plan-expanded-header-file-path",className:"mt-0.5 text-xs font-mono text-[var(--text-dim)] break-all",children:t})]})}function Ku(){const[e,t]=i.useState(!1),[r,s]=i.useState(null);return{updatePlan:i.useCallback(async(o,l)=>{t(!0),s(null);try{const c=await fetch(`/api/plans/${o}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify(l)});if(!c.ok){const d=await c.json().catch(()=>({}));throw new Error(d.error??`HTTP ${c.status}`)}}catch(c){const d=c instanceof Error?c.message:"Failed to save plan";throw s(d),c instanceof Error?c:new Error(d)}finally{t(!1)}},[]),saving:e,error:r}}function Gu({slug:e,onClose:t}){return n.jsx("div",{className:"px-3 py-2 border-t border-[var(--border-subtle)]",children:n.jsx(rn,{slashCommand:`/codeyam-edit-plan ${e}`,height:360,onClose:t})})}function Yu({titleDraft:e,bodyDraft:t,saving:r,error:s,onTitleChange:a,onBodyChange:o,onSave:l,onCancel:c}){const d=Math.min(20,Math.max(8,t.split(`
14
+ `).length));return n.jsxs("div",{className:"border-t border-[var(--border-subtle)] px-3 py-2 flex flex-col gap-2",children:[n.jsx("input",{type:"text",value:e,onChange:u=>a(u.target.value),"aria-label":"Plan title",className:"w-full px-2 py-1 text-sm rounded border border-[var(--border-subtle)] bg-[var(--bg-input,transparent)] text-[var(--text-primary)]"}),n.jsx("textarea",{value:t,onChange:u=>o(u.target.value),"aria-label":"Plan body",rows:d,className:"w-full px-2 py-1 text-xs rounded border border-[var(--border-subtle)] bg-[var(--bg-input,transparent)] text-[var(--text-primary)] font-mono resize-y"}),s&&n.jsx("p",{className:"text-xs text-[var(--accent-red)]",role:"alert",children:s}),n.jsxs("div",{className:"flex gap-2 justify-end",children:[n.jsx("button",{type:"button",onClick:c,disabled:r,className:"px-2.5 py-1 text-xs rounded border border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer disabled:opacity-60",children:"Cancel"}),n.jsx("button",{type:"button",onClick:l,disabled:r,className:"px-2.5 py-1 text-xs rounded border border-[var(--accent-active)] bg-[var(--accent-active)] text-black hover:bg-[var(--accent-active)]/90 cursor-pointer disabled:opacity-60",children:r?"Saving…":"Save"})]})]})}function Ju({onClick:e}){return n.jsx("button",{type:"button",onClick:e,className:"px-2.5 py-1 text-xs rounded border border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer",children:"Edit"})}function Xu({providerLabel:e,onClick:t}){return n.jsxs("button",{type:"button",onClick:t,className:"flex items-center gap-1.5 px-2.5 py-1 rounded border text-xs cursor-pointer transition-colors border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:border-[var(--accent-active)]/40",title:`Open a chat with ${e} seeded with this plan's contents`,children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),"Edit with ",e]})}function qu({dep:e}){const t=e.title===null,r=e.satisfied?"completed":t?"missing":"blocked",s=e.satisfied?{borderColor:"var(--border-subtle)",color:"var(--text-dim)"}:{borderColor:"var(--accent-warn, #c08a2c)",color:"var(--accent-warn, #c08a2c)"};return n.jsxs("li",{"data-testid":`plan-row-dep-${e.slug}`,className:"text-sm flex items-center gap-2",children:[n.jsx("span",{className:"text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded border whitespace-nowrap",style:s,children:r}),n.jsx("span",{className:e.satisfied?"text-[var(--text-dim)] truncate":"text-[var(--text-primary)] truncate",children:t?`missing: ${e.slug}`:e.title})]})}function Qu({dependencies:e}){return n.jsxs("div",{"data-testid":"plan-row-deps",className:"px-3 py-2 border-b border-[var(--border-subtle)]",children:[n.jsx("p",{className:"text-[10px] uppercase tracking-wide text-[var(--text-dim)] mb-1.5",children:"Depends on"}),n.jsx("ul",{className:"flex flex-col gap-1",children:e.map(t=>n.jsx(qu,{dep:t},t.slug))})]})}function Zu({title:e,filePath:t,body:r,providerLabel:s,onEdit:a,onChat:o,dependencies:l}){return n.jsxs("div",{className:"border-t border-[var(--border-subtle)]",children:[n.jsx(Na,{title:e,filePath:t}),l&&l.length>0&&n.jsx(Qu,{dependencies:l}),n.jsx("div",{className:"px-3 py-2 max-h-[40vh] overflow-y-auto",children:n.jsx(et,{variant:"compact",children:r})}),n.jsxs("div",{className:"flex gap-2 justify-end px-3 py-2 border-t border-[var(--border-subtle)]",children:[n.jsx(Ju,{onClick:a}),n.jsx(Xu,{providerLabel:s,onClick:o})]})]})}function ef({plan:e,dependencies:t}){const[r,s]=i.useState("view"),[a,o]=i.useState(e.title),[l,c]=i.useState(e.body),{updatePlan:d,saving:u,error:f}=Ku(),{config:p}=Ze(),m=dt(p==null?void 0:p.provider);return i.useEffect(()=>{o(e.title),c(e.body),s("view")},[e.slug]),r==="chat"?n.jsx(Gu,{slug:e.slug,onClose:()=>s("view")}):r==="edit"?n.jsx(Yu,{titleDraft:a,bodyDraft:l,saving:u,error:f,onTitleChange:o,onBodyChange:c,onSave:async()=>{try{await d(e.slug,{title:a,body:l}),s("view")}catch{}},onCancel:()=>{o(e.title),c(e.body),s("view")}}):n.jsx(Zu,{title:e.title,filePath:e.filePath,body:e.body,providerLabel:m,onEdit:()=>s("edit"),onChat:()=>s("chat"),dependencies:t})}const Ca="Building is in progress, please wait for it to complete before starting a new build session.";function tf({slug:e,onRun:t,launching:r=!1,blocked:s=!1,onBlockedClick:a}){const o=f=>{if(f.stopPropagation(),!r){if(s){a==null||a();return}t(e)}},l="text-[10px] uppercase tracking-wide px-2 py-0.5 rounded border border-[var(--accent)] text-[var(--accent)] cursor-pointer hover:bg-[var(--accent)] hover:text-[var(--surface-bg)] disabled:opacity-60 disabled:cursor-not-allowed transition",c=" opacity-60 cursor-not-allowed hover:bg-transparent hover:text-[var(--accent)]",d=r,u=s&&!r;return n.jsx("button",{type:"button",onClick:o,disabled:d,"data-testid":`plan-run-${e}`,title:u?Ca:void 0,className:l+(u?c:""),children:r?"Launching…":"Run"})}function Sa({plan:e,expanded:t,onToggle:r,onRun:s,launching:a=!1,blocked:o=!1,onBlockedClick:l,position:c,dragHandleRef:d,dragHandleAttributes:u,dragHandleListeners:f,sortableRef:p,sortableStyle:m,isDragging:h=!1,unsatisfiedDepCount:j=0,unsatisfiedDepTooltip:b,dependencies:g,expandedBodyVariant:w="full"}){const v=x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),r())};return n.jsxs("li",{ref:p,style:m,className:`border border-[var(--border-subtle)] rounded-lg bg-[var(--bg-surface,transparent)] ${h?"opacity-60 shadow-lg":""}`,children:[n.jsxs("div",{role:"button",tabIndex:0,onClick:r,onKeyDown:v,className:"w-full text-left px-3 py-2 flex items-center justify-between gap-3 bg-transparent cursor-pointer",children:[d&&n.jsx("span",{ref:d,"data-testid":`plan-drag-${e.slug}`,"aria-label":"Reorder plan",...u??{},...f??{},onClick:x=>x.stopPropagation(),className:"cursor-grab active:cursor-grabbing text-[var(--text-dim)] select-none leading-none px-1 -ml-1",children:"⋮⋮"}),typeof c=="number"&&n.jsxs("span",{className:"text-xs text-[var(--text-dim)] tabular-nums min-w-[1.25rem]",children:[c,"."]}),n.jsx("span",{className:"flex-1 min-w-0 truncate text-sm text-[var(--text-primary)]",children:e.title}),s&&n.jsx(tf,{slug:e.slug,onRun:s,launching:a,blocked:o,onBlockedClick:l}),n.jsx("span",{className:"text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded border border-[var(--border-subtle)] text-[var(--text-dim)]",children:e.mode}),j>0&&n.jsxs("span",{"data-testid":`plan-dep-chip-${e.slug}`,title:b,className:"text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded border",style:{borderColor:"var(--accent-warn, #c08a2c)",color:"var(--accent-warn, #c08a2c)"},children:["blocked: depends on ",j," plan",j===1?"":"s"]}),n.jsx("span",{className:"text-[10px] text-[var(--text-dim)] whitespace-nowrap",children:ja(e.createdAt)})]}),t&&(w==="view"?n.jsxs("div",{className:"border-t border-[var(--border-subtle)]",children:[n.jsx(Na,{title:e.title,filePath:e.filePath}),n.jsx("div",{className:"px-3 py-2 max-h-[40vh] overflow-y-auto",children:n.jsx(et,{variant:"compact",children:e.body})})]}):n.jsx(ef,{plan:e,dependencies:g}))]})}function nf({plan:e,position:t,expanded:r,onToggle:s,onRun:a,launching:o,blocked:l,onBlockedClick:c,draggable:d,unsatisfiedDepCount:u,unsatisfiedDepTooltip:f,dependencies:p}){const{attributes:m,listeners:h,setNodeRef:j,setActivatorNodeRef:b,transform:g,transition:w,isDragging:v}=zu({id:e.slug,disabled:!d}),x={transform:kt.Transform.toString(g),transition:w};return n.jsx(Sa,{plan:e,expanded:r,onToggle:s,onRun:a,launching:o,blocked:l,onBlockedClick:c,position:t,sortableRef:j,sortableStyle:x,isDragging:v,dragHandleRef:d?b:void 0,dragHandleAttributes:d?m:void 0,dragHandleListeners:d?h:void 0,unsatisfiedDepCount:u,unsatisfiedDepTooltip:f,dependencies:p})}function gr({plans:e,loading:t,error:r,onRun:s,launchingSlug:a,launchError:o,blocked:l=!1,onBlockedClick:c,onReorder:d,depAnnotationsBySlug:u,dependenciesBySlug:f}){const[p,m]=i.useState(null),[h,j]=i.useState(null),[b,g]=i.useState(null);i.useEffect(()=>{j(null)},[e]);const w=h??e,v=w.length;return n.jsxs("div",{className:"mt-6",children:[n.jsxs("h3",{className:"text-xs font-medium uppercase tracking-wide text-[var(--text-dim)]",children:["Queued Changes (",v,")"]}),o&&n.jsxs("p",{className:"mt-2 text-sm text-[var(--accent-red)]",children:["Failed to launch plan: ",o]}),b&&n.jsxs("p",{className:"mt-2 text-sm text-[var(--accent-red)]",children:["Failed to reorder plans: ",b]}),n.jsx(rf,{plans:w,loading:t,error:r,expandedSlug:p,onToggle:x=>m(y=>y===x?null:x),onRun:s,launchingSlug:a??null,blocked:l,onBlockedClick:c,depAnnotationsBySlug:u,dependenciesBySlug:f,onReorder:d?async x=>{j(x),g(null);try{await d(x.map(y=>y.slug))}catch(y){j(null),g(y instanceof Error?y.message:"Unknown error")}}:void 0})]})}function rf({plans:e,loading:t,error:r,expandedSlug:s,onToggle:a,onRun:o,launchingSlug:l,blocked:c,onBlockedClick:d,onReorder:u,depAnnotationsBySlug:f,dependenciesBySlug:p}){const m=bd(Gr(xr,{activationConstraint:{distance:4}}),Gr(pr,{coordinateGetter:Vu})),h=i.useMemo(()=>e.map(g=>g.slug),[e]);if(t)return n.jsx("p",{className:"mt-3 text-sm text-[var(--text-muted)]",children:"Loading plans…"});if(r)return n.jsxs("p",{className:"mt-3 text-sm text-[var(--accent-red)]",children:["Failed to load plans: ",r]});if(e.length===0)return n.jsx("p",{className:"mt-3 text-sm text-[var(--text-dim)]",children:"No plans yet. Click PLAN NEXT CHANGE to create one."});const j=g=>{const{active:w,over:v}=g;if(!v||w.id===v.id||!u)return;const x=e.findIndex(N=>N.slug===w.id),y=e.findIndex(N=>N.slug===v.id);x===-1||y===-1||u(hr(e,x,y))},b=n.jsx("ul",{className:"mt-3 flex flex-col gap-2","data-testid":"plan-list",children:e.map((g,w)=>{const v=f==null?void 0:f[g.slug];return n.jsx(nf,{plan:g,position:w+1,expanded:s===g.slug,onToggle:()=>a(g.slug),onRun:o,launching:l===g.slug,blocked:c,onBlockedClick:d,draggable:!!u,unsatisfiedDepCount:v==null?void 0:v.count,unsatisfiedDepTooltip:v==null?void 0:v.tooltip,dependencies:p==null?void 0:p[g.slug]},g.slug)})});return u?n.jsx(wu,{sensors:m,collisionDetection:wd,onDragEnd:j,children:n.jsx(Mu,{items:h,strategy:Au,children:b})}):b}function sf({awaitingPlanLaunchChoice:e,configLoading:t,sessionLoading:r,sessionDecision:s,sessionInfo:a,stepState:o,provider:l,onContinueSession:c,onAgentIdle:d,onAgentActive:u,onUserInput:f,pendingPlans:p,pendingPlansLoading:m,pendingPlansError:h,onLaunchPlan:j,launchingSlug:b,launchError:g,onReorderPlans:w,isAgentBuilding:v}){const{recoveryFeatureName:x,recoveryStep:y,recoveryMode:N,showTerminal:C,shouldResumeSameProvider:S}=zc({awaitingPlanLaunchChoice:e,configLoading:t,sessionLoading:r,sessionDecision:s,sessionInfo:a,stepState:o});return s==="pending"?n.jsx(_c,{featureName:x,editorStep:y,workflowMode:N,currentProvider:l,previousProvider:(a==null?void 0:a.provider)??null,resumeMode:(a==null?void 0:a.resumeMode)??"fresh",awaitingUserInput:(a==null?void 0:a.awaitingUserInput)??!1,onContinue:c}):e&&p.length>0&&a===null&&o===null?n.jsx(ir,{children:n.jsx(gr,{plans:p,loading:m,error:h,onRun:k=>{var E;const R=((E=p.find(T=>T.slug===k))==null?void 0:E.title)??k;j(k,R)},launchingSlug:b,launchError:g,blocked:v,onReorder:w})}):C?n.jsx(sd,{provider:l,shouldResumeSameProvider:S,sessionId:(a==null?void 0:a.sessionId)??null,onAgentIdle:d,onAgentActive:u,onUserInput:f,currentFeature:(o==null?void 0:o.feature)??null}):s==="no-session"&&o===null?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-slate-500 space-y-4 px-10 text-center",children:[n.jsx("div",{className:"text-lg font-medium text-slate-400",children:"Ready to build"}),n.jsx("p",{className:"max-w-md",children:"Your first session will start automatically. You can queue changes or wait for the project to initialize."})]}):null}function af(e){return e?{step:e.step??0,feature:e.feature??null,startedAt:e.startedAt??"",mode:$e(e.mode),slug:e.slug??null}:null}const of=3e3;function Lt(){const[e,t]=i.useState(null),[r,s]=i.useState(!0),a=i.useRef(null),o=i.useRef(null);return i.useEffect(()=>{const l=()=>{fetch("/api/step").then(c=>c.json()).then(c=>{const d=af(c),u=JSON.stringify(d);u!==o.current&&(o.current=u,t(d)),s(!1)}).catch(()=>{s(!1)})};return l(),a.current=setInterval(l,of),()=>{a.current&&clearInterval(a.current)}},[]),{stepState:e,loading:r}}const Se={hasSession:!1,resumeMode:"fresh",provider:null,feature:null,step:null,mode:null,label:null,sessionId:null,awaitingUserInput:!1,reopenResults:!1,preview:null,agentBrokerLive:!1};function lf(e){return{hasSession:(e==null?void 0:e.hasSession)??Se.hasSession,resumeMode:(e==null?void 0:e.resumeMode)??Se.resumeMode,provider:(e==null?void 0:e.provider)??Se.provider,feature:(e==null?void 0:e.feature)??Se.feature,step:(e==null?void 0:e.step)??Se.step,mode:(e==null?void 0:e.mode)==null?Se.mode:$e(e.mode),label:(e==null?void 0:e.label)??Se.label,sessionId:(e==null?void 0:e.sessionId)??Se.sessionId,awaitingUserInput:(e==null?void 0:e.awaitingUserInput)??Se.awaitingUserInput,reopenResults:(e==null?void 0:e.reopenResults)??Se.reopenResults,preview:(e==null?void 0:e.preview)??Se.preview,agentBrokerLive:(e==null?void 0:e.agentBrokerLive)??Se.agentBrokerLive}}function ka(e){const t=e==null?void 0:e.pollIntervalMs,[r,s]=i.useState(null),[a,o]=i.useState(!0),l=i.useCallback(async()=>{o(!0);try{const d=await(await fetch("/api/session-info")).json();s(lf(d))}catch{s(Se)}finally{o(!1)}},[]);return i.useEffect(()=>{l()},[l]),i.useEffect(()=>{if(t==null||t<=0)return;const c=setInterval(()=>{l()},t);return()=>clearInterval(c)},[t,l]),{sessionInfo:r,loading:a,refetch:l}}const cf=5e3;function df(){const[e,t]=i.useState(null),[r,s]=i.useState(!0),a=i.useRef(null);return i.useEffect(()=>{const o=()=>{fetch("/api/prompt").then(l=>l.json()).then(l=>{t(l.prompt??null),s(!1)}).catch(()=>s(!1))};return o(),a.current=setInterval(o,cf),()=>{a.current&&clearInterval(a.current)}},[]),{prompt:e,loading:r}}function uf({currentDecision:e,sessionInfo:t,sessionLoading:r}){return r||!t?e:e==="continue"&&t.hasSession?"continue":t.resumeMode==="resume"||t.resumeMode==="handoff"?"pending":"fresh"}function ff({sessionLoading:e,sessionInfo:t,onSessionDetected:r}){const s=i.useRef(!1),[a,o]=i.useState("no-session");i.useEffect(()=>{o(c=>uf({currentDecision:c,sessionInfo:t,sessionLoading:e})),!e&&t&&(t.resumeMode==="resume"||t.resumeMode==="handoff")&&!s.current&&r&&(s.current=!0,r())},[e,t,r]);const l=i.useCallback(()=>{o("continue")},[]);return{sessionDecision:a,handleContinueSession:l}}function pf(){const e=document.activeElement;return e===null||e===document.body||e===document.documentElement||e instanceof HTMLElement&&e.dataset.navTab==="true"}function mf(e,t,r,s=0){return e>=r.left-s&&e<=r.right+s&&t>=r.top-s&&t<=r.bottom+s}function os(e){Qt(),e.blur(),window.dispatchEvent(new Event("terminal-focus")),queueMicrotask(()=>{document.activeElement instanceof HTMLIFrameElement&&window.dispatchEvent(new Event("terminal-focus"))})}function xf(e){const t=i.useRef(!1);i.useEffect(()=>{if(!e)return;function r(){if(!t.current&&pf()){t.current=!0;try{Qt(),window.dispatchEvent(new Event("terminal-focus"))}finally{t.current=!1}}}function s(){queueMicrotask(r)}function a(l){const c=document.activeElement;c instanceof HTMLIFrameElement&&l.target!==c&&os(c)}function o(l){const c=document.activeElement;if(!(c instanceof HTMLIFrameElement))return;const d=c.getBoundingClientRect();mf(l.clientX,l.clientY,d,1)||os(c)}return document.addEventListener("focusout",s),window.addEventListener("focus",s),document.addEventListener("visibilitychange",s),document.addEventListener("mouseup",s),document.addEventListener("pointerdown",a,!0),document.addEventListener("mousedown",a,!0),document.addEventListener("click",a,!0),document.addEventListener("pointermove",o,{capture:!0,passive:!0}),()=>{document.removeEventListener("focusout",s),window.removeEventListener("focus",s),document.removeEventListener("visibilitychange",s),document.removeEventListener("mouseup",s),document.removeEventListener("pointerdown",a,!0),document.removeEventListener("mousedown",a,!0),document.removeEventListener("click",a,!0),document.removeEventListener("pointermove",o,{capture:!0})}},[e])}function hf({sessionLoading:e,sessionInfo:t,onRestorePreview:r}){const s=i.useRef(!1);i.useEffect(()=>{e||!(t!=null&&t.preview)||t.resumeMode!=="resume"&&t.resumeMode!=="handoff"||s.current||(s.current=!0,r==null||r(t.preview))},[r,t,e])}function gf(e){const t=i.useRef(e);i.useEffect(()=>{e&&e!==t.current&&(As(e),t.current=e)},[e])}function is(e,t,r){i.useEffect(()=>{if(!t)return;const s=a=>{e.current&&!e.current.contains(a.target)&&r()};return document.addEventListener("mousedown",s),()=>document.removeEventListener("mousedown",s)},[e,t,r])}function vf({displayName:e,hasPrompt:t,expanded:r,onToggle:s}){return t?n.jsxs("button",{onClick:s,className:"flex items-center gap-1 cursor-pointer transition-colors min-w-0",style:{color:"var(--text-secondary)"},children:[n.jsx("span",{className:"font-medium truncate",children:e}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",className:`shrink-0 transition-transform ${r?"rotate-180":""}`,children:n.jsx("path",{d:"M2 4l3 3 3-3"})})]}):n.jsx("span",{className:"font-medium truncate",style:{color:"var(--text-secondary)"},children:e})}function bf({prompt:e}){return n.jsx("div",{style:{background:"var(--bg-input)",borderBottom:"1px solid var(--border-default)",maxHeight:"16rem",overflowY:"auto",padding:"0 0.75rem 0.75rem"},children:n.jsx(et,{variant:"compact",children:e})})}function yf({currentStep:e,isExpanded:t,mode:r,onToggle:s=()=>{},stepNum:a}){const o=a===e,l=a<e,{description:c,label:d}=Ks(a,r);return n.jsxs("div",{onClick:s,className:"cursor-pointer",children:[n.jsxs("div",{className:"w-full px-3 py-1 flex items-center gap-2 text-left transition-colors",style:{color:o?"var(--accent-active)":l?"var(--text-secondary)":"var(--text-muted)",fontWeight:o?500:void 0},onMouseEnter:u=>u.currentTarget.style.background="var(--bg-input)",onMouseLeave:u=>u.currentTarget.style.background="transparent",children:[n.jsxs("span",{className:"w-5 text-right tabular-nums shrink-0",children:[a,"."]}),n.jsx("span",{className:"flex-1",children:d}),c&&n.jsx("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",className:`shrink-0 opacity-40 transition-transform ${t?"rotate-180":""}`,children:n.jsx("path",{d:"M2 4l3 3 3-3"})})]}),t&&c&&n.jsx("div",{className:"px-3 pb-1.5 pl-10",children:n.jsx("p",{className:"text-[10px] m-0 leading-relaxed",style:{color:"var(--text-dim)"},children:c})})]},a)}function wf({step:e,feature:t,mode:r,projectTitle:s,userPrompt:a}){const[o,l]=i.useState(!1),[c,d]=i.useState(null),[u,f]=i.useState(!1),p=i.useRef(null),m=i.useRef(null);is(p,o,i.useCallback(()=>l(!1),[])),is(m,u,i.useCallback(()=>f(!1),[]));const h=t&&e>0,j=t||"New Working Session",b=$e(r),g=Ks(e,b),w=h?g.label:null,v=g.totalSteps,x=g.prefix;return e===0?n.jsxs("div",{className:"h-8 flex items-center justify-between px-3 text-xs shrink-0 select-none",style:{background:"var(--bg-input)",borderBottom:"1px solid var(--border-default)"},children:[n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[n.jsx("span",{className:"truncate",style:{color:"var(--text-dim)"},children:s||"New Project"}),n.jsx("span",{style:{color:"var(--text-dim)",opacity:.5},children:">"}),n.jsx("span",{className:"font-medium truncate",style:{color:"var(--text-muted)"},children:j})]}),n.jsx("span",{style:{color:"var(--text-dim)"},children:t?"Starting…":"Waiting for session"})]}):n.jsxs("div",{className:"shrink-0",ref:m,children:[n.jsxs("div",{className:"h-8 flex items-center justify-between px-3 text-xs select-none",style:{background:"var(--bg-input)",borderBottom:u?"none":"1px solid var(--border-default)"},children:[n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[n.jsx("span",{className:"truncate",style:{color:"var(--text-dim)"},children:s||"New Project"}),n.jsx("span",{style:{color:"var(--text-dim)",opacity:.5},children:">"}),n.jsx(vf,{displayName:j,hasPrompt:!!a,expanded:u,onToggle:()=>f(y=>!y)})]}),h&&n.jsxs("div",{className:"relative",ref:p,children:[n.jsxs("button",{onClick:()=>l(y=>!y),className:"flex items-center gap-1.5 cursor-pointer transition-colors",style:{color:"var(--text-secondary)"},children:[n.jsx("span",{style:{color:"var(--text-dim)"},children:"::"}),n.jsxs("span",{children:[x," ",e,n.jsxs("span",{style:{color:"var(--text-dim)"},children:[" / ",v]}),": ",w]}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",className:`transition-transform ${o?"rotate-180":""}`,children:n.jsx("path",{d:"M2 4l3 3 3-3"})})]}),o&&n.jsx("div",{className:"absolute right-0 top-full mt-1 w-52 rounded-lg shadow-lg z-30 py-1",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:Array.from({length:v},(y,N)=>N+1).map(y=>{const N=c===y;return n.jsx(yf,{currentStep:e,isExpanded:N,mode:b,onToggle:()=>d(N?null:y),stepNum:y},y)})})]})]}),u&&a&&n.jsx(bf,{prompt:a})]})}function jf({awaitingPlanLaunchChoice:e,isActive:t,onSessionDetected:r,onAgentIdle:s,onAgentActive:a,onUserInput:o,provider:l,onRestorePreview:c,pendingPlans:d,pendingPlansLoading:u,pendingPlansError:f,onLaunchPlan:p,launchingSlug:m,launchError:h,onReorderPlans:j,isAgentBuilding:b}){const{stepState:g}=Lt(),{config:w,loading:v}=Ze(),{prompt:x}=df(),{sessionInfo:y,loading:N}=ka(),{sessionDecision:C,handleContinueSession:S}=ff({sessionLoading:N,sessionInfo:y,onSessionDetected:r});return xf(t),hf({sessionLoading:N,sessionInfo:y,onRestorePreview:c}),gf((g==null?void 0:g.feature)??null),n.jsx(Tc,{stepIndicator:n.jsx(wf,{step:(g==null?void 0:g.step)??0,feature:(g==null?void 0:g.feature)??null,mode:(g==null?void 0:g.mode)??"ui",projectTitle:(w==null?void 0:w.projectName)??null,userPrompt:x}),sessionContent:n.jsx(sf,{awaitingPlanLaunchChoice:e,configLoading:v,sessionLoading:N,sessionDecision:C,sessionInfo:y,stepState:g,provider:l,onContinueSession:S,onAgentIdle:s,onAgentActive:a,onUserInput:o,pendingPlans:d,pendingPlansLoading:u,pendingPlansError:f,onLaunchPlan:p,launchingSlug:m,launchError:h,onReorderPlans:j,isAgentBuilding:b})})}function Ea({screenshotPath:e,cacheBuster:t,alt:r,className:s="",title:a}){const[o,l]=i.useState("loading"),[c,d]=i.useState(!1),u=i.useRef(null),f=e?We(e):"",p=f.startsWith("http"),m=t&&!p?`${f}?cb=${t}`:f,h=()=>{l("success"),d(!0)},j=()=>{l("error"),d(!1)};return i.useEffect(()=>{l("loading"),d(!1);const b=u.current;b!=null&&b.complete&&(b.naturalHeight!==0?(l("success"),d(!0)):(l("error"),d(!1)))},[m]),e?n.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",title:a,children:[n.jsx("img",{ref:u,src:m,alt:r,onLoad:h,onError:j,className:s||"max-w-full max-h-full object-contain",style:{visibility:c?"visible":"hidden",position:c?"relative":"absolute"}}),o==="loading"&&n.jsx("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n.jsx("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&n.jsxs("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n.jsx("span",{className:"text-2xl text-gray-400",children:"📷"}),n.jsx("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n.jsx("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:a,children:n.jsx("span",{className:"text-2xl text-gray-400",children:"📷"})})}function Nf({refreshing:e,onRefresh:t,onClose:r}){return n.jsxs("div",{className:"shrink-0 px-4 py-2 bg-[var(--bg-card)] border-b border-[var(--border-default)] flex items-center justify-between",children:[n.jsx("div",{className:"flex items-center gap-2",children:n.jsx("h2",{className:"text-sm font-semibold text-[var(--text-primary)] m-0",children:"Working Session Results"})}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{onClick:t,disabled:e,className:"text-[var(--text-muted)] hover:text-[var(--text-secondary)] text-xs leading-none px-2 py-1 border border-[var(--border-default)] rounded disabled:opacity-50",title:"Refresh session data",children:e?"…":"↻"}),n.jsx("button",{onClick:r,className:"text-[var(--text-muted)] hover:text-[var(--text-secondary)] text-lg leading-none px-1",title:"Close results panel",children:"✕"})]})]})}function it(e,t){if(e.length===0)return{selectedIndex:-1,scenario:null};if("direction"in t){const s=t.direction==="next"?1:-1,a=(t.selectedIndex+s+e.length)%e.length;return{selectedIndex:a,scenario:e[a]}}if("slug"in t){const s=e.findIndex(a=>a.slug===t.slug);return s>=0?{selectedIndex:s,scenario:e[s]}:it(e,{defaultSelection:!0,selectedIndex:t.selectedIndex})}const r=Math.min(t.selectedIndex??0,e.length-1);return{selectedIndex:r,scenario:e[r]}}function Cf(e){return e==null?"":typeof e=="string"?e:typeof e=="object"&&typeof e.name=="string"?e.name:String(e)}const Sf="/api/editor-session-summary",kf=3e3;function Ef(e=kf){const[t,r]=i.useState(null),[s,a]=i.useState(!0),[o,l]=i.useState(!1),c=i.useCallback(async()=>{l(!0);try{const d=await fetch(Sf);d.ok&&r(await d.json())}catch{}l(!1),a(!1)},[]);return i.useEffect(()=>{c()},[c]),i.useEffect(()=>{if(e<=0)return;const d=window.setInterval(c,e);return()=>window.clearInterval(d)},[c,e]),{summary:t,loading:s,refreshing:o,refresh:c}}function Rf({onClose:e,onSelectScenario:t}){var m,h;const{summary:r,loading:s,refreshing:a,refresh:o}=Ef(),[l,c]=i.useState(0),d=i.useMemo(()=>r?[...r.application,...r.components]:[],[r]),u=i.useCallback(j=>{d.length!==0&&(document.activeElement instanceof HTMLIFrameElement||qc()||(j.key==="ArrowRight"?(j.preventDefault(),c(b=>{const g=it(d,{direction:"next",selectedIndex:b});return g.scenario&&(t==null||t(g.scenario.slug,g.scenario.url)),g.selectedIndex})):j.key==="ArrowLeft"&&(j.preventDefault(),c(b=>{const g=it(d,{direction:"previous",selectedIndex:b});return g.scenario&&(t==null||t(g.scenario.slug,g.scenario.url)),g.selectedIndex}))))},[d,t]);i.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]);const f=i.useRef(!1);if(i.useEffect(()=>{if(f.current||d.length===0)return;f.current=!0;const j=it(d,{defaultSelection:!0,selectedIndex:l});j.scenario&&(t==null||t(j.scenario.slug,j.scenario.url))},[d,t,l]),s)return n.jsx("div",{className:"flex-1 flex items-center justify-center p-8 bg-[var(--bg-deep)]",children:n.jsx("div",{className:"animate-spin w-6 h-6 border-2 border-[var(--border-default)] border-t-[#005c75] rounded-full"})});if(!r)return n.jsx("div",{className:"flex-1 flex items-center justify-center p-8 bg-[var(--bg-deep)]",children:n.jsx("div",{className:"text-sm text-[var(--text-muted)]",children:"No session data available."})});const p=r.application.length+r.components.length;return n.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col bg-[var(--bg-deep)]",style:{borderTop:"2px solid #005c75"},children:[n.jsx(Nf,{refreshing:a,onRefresh:o,onClose:e}),n.jsxs("div",{className:"flex-1 overflow-auto p-4 space-y-4",children:[r.userPrompt&&n.jsx(Tf,{text:r.userPrompt}),n.jsx(Wt,{title:"Application",icon:"🌐",count:r.application.length,empty:p===0?"No scenarios in this session":void 0,children:r.application.length>0&&n.jsx(Df,{scenarios:r.application,selectedSlug:(m=d[l])==null?void 0:m.slug,onSelect:(j,b)=>{var w,v;const g=it(d,{slug:j,selectedIndex:l});g.selectedIndex>=0&&c(g.selectedIndex),t==null||t(((w=g.scenario)==null?void 0:w.slug)??j,((v=g.scenario)==null?void 0:v.url)??b)}})}),n.jsx(Wt,{title:"Components",icon:"🧩",count:r.components.length,children:r.components.length>0&&n.jsx(Pf,{scenarios:r.components,selectedSlug:(h=d[l])==null?void 0:h.slug,onSelect:(j,b)=>{var w,v;const g=it(d,{slug:j,selectedIndex:l});g.selectedIndex>=0&&c(g.selectedIndex),t==null||t(((w=g.scenario)==null?void 0:w.slug)??j,((v=g.scenario)==null?void 0:v.url)??b)}})}),n.jsx(Wt,{title:"Functions",icon:"⚙️",count:r.functions.length,children:r.functions.length>0&&n.jsx(Lf,{functions:r.functions})}),n.jsx(Wt,{title:"Modified Files",icon:"📄",count:r.modifiedFiles.length,children:r.modifiedFiles.length>0&&n.jsx(Mf,{files:r.modifiedFiles})})]})]})}function Tf({text:e}){const[t,r]=i.useState(!1),s=e.split(`
15
+ `)[0],a=e.includes(`
16
+ `)||e.length>120;return n.jsxs("div",{className:"px-1 pb-2",children:[n.jsx("div",{className:"text-[10px] font-semibold text-[var(--text-muted)] uppercase tracking-wide mb-1",children:"User Request"}),t?n.jsxs("div",{children:[n.jsx(et,{variant:"compact",children:e}),a&&n.jsx("button",{onClick:()=>r(!1),className:"text-blue-600 hover:underline text-xs mt-1",children:"Show less"})]}):n.jsxs("div",{className:"text-xs text-[var(--text-secondary)] leading-relaxed",children:[s.slice(0,120),a&&n.jsx("button",{onClick:()=>r(!0),className:"text-blue-600 hover:underline ml-1 text-xs",children:"Read more..."})]})]})}function Wt({title:e,icon:t,count:r,empty:s,children:a}){return n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg overflow-hidden",children:[n.jsxs("div",{className:"px-4 py-2 border-b border-[var(--border-subtle)] bg-[var(--bg-input)] flex items-center gap-2",children:[n.jsx("span",{className:"text-xs",children:t}),n.jsx("span",{className:"text-xs font-semibold text-[var(--text-primary)]",children:e}),n.jsxs("span",{className:"text-[10px] text-[var(--text-muted)]",children:["(",r,")"]})]}),n.jsx("div",{className:"p-3",children:r===0?n.jsx("div",{className:"text-xs text-[var(--text-muted)] italic",children:s||`No ${e.toLowerCase()} in this session`}):a})]})}function Gn({scenarios:e,selectedSlug:t,onSelect:r}){return n.jsx("div",{className:"overflow-x-auto",children:n.jsx("div",{className:"flex gap-2",style:{minWidth:"min-content"},children:e.map(s=>n.jsx(Af,{scenario:s,isSelected:s.slug===t,onSelect:r},s.slug))})})}function Pf({scenarios:e,selectedSlug:t,onSelect:r}){const s={};for(const o of e){const l=o.componentName||"Unknown";s[l]||(s[l]=[]),s[l].push(o)}const a=Object.keys(s).sort();return n.jsx("div",{className:"space-y-3",children:a.map(o=>n.jsxs("div",{children:[n.jsx("div",{className:"text-[11px] font-medium text-[var(--text-secondary)] mb-1",children:o}),n.jsx(Gn,{scenarios:s[o],selectedSlug:t,onSelect:r})]},o))})}function Df({scenarios:e,selectedSlug:t,onSelect:r}){if(!e.some(l=>l.routeName))return n.jsx(Gn,{scenarios:e,selectedSlug:t,onSelect:r});const a={};for(const l of e){const c=l.routeName||"Other";a[c]||(a[c]=[]),a[c].push(l)}const o=Object.keys(a).sort();return n.jsx("div",{className:"space-y-3",children:o.map(l=>n.jsxs("div",{children:[n.jsx("div",{className:"text-[11px] font-medium text-[var(--text-secondary)] mb-1",children:l}),n.jsx(Gn,{scenarios:a[l],selectedSlug:t,onSelect:r})]},l))})}function Af({scenario:e,isSelected:t,onSelect:r}){const s=e.name.replace(/\s*\[.*\]\s*$/,"").trim();return n.jsxs("div",{className:"shrink-0 cursor-pointer group",onClick:()=>r==null?void 0:r(e.slug,e.url),title:e.name,children:[n.jsx("div",{className:`w-24 h-24 rounded overflow-hidden transition-colors ${t?"border-2 border-[#005c75] shadow-md":"border border-[var(--border-default)] group-hover:border-[#005c75]"}`,style:{background:"#e8edf1"},children:e.screenshotPaths.length>0?n.jsx(Ea,{screenshotPath:e.screenshotPaths[0],alt:e.name,className:"w-full h-full object-cover object-top"}):n.jsx("div",{className:"w-full h-full flex items-center justify-center text-[var(--text-muted)] text-lg",children:"📷"})}),n.jsx("div",{className:`mt-1 text-[10px] truncate w-24 ${t?"text-[#005c75] font-medium":"text-[var(--text-secondary)] group-hover:text-[#005c75]"}`,children:s})]})}function Lf({functions:e}){return n.jsx("div",{className:"divide-y divide-gray-100 -mx-3 -mb-3",children:e.map(t=>n.jsxs("div",{className:"px-3 py-2",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("span",{className:"text-[10px] text-[var(--text-muted)] mt-0.5 shrink-0",children:"fn"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:t.name}),t.description&&n.jsx("div",{className:"text-[10px] text-[var(--text-muted)] mt-0.5",children:t.description}),n.jsx("div",{className:"text-[10px] text-[var(--text-muted)] font-mono mt-0.5",children:t.filePath})]})]}),t.tests.length>0&&n.jsx("div",{className:"ml-5 mt-1.5 space-y-0.5",children:t.tests.map((r,s)=>n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"text-green-500 text-[10px]",children:"✓"}),n.jsx("span",{className:"text-[10px] text-[var(--text-secondary)]",children:Cf(r)})]},s))}),t.testFile&&t.tests.length===0&&n.jsx("div",{className:"ml-5 mt-1 text-[10px] text-[var(--text-muted)] font-mono",children:t.testFile})]},`${t.filePath}::${t.name}`))})}function Mf({files:e}){return n.jsx("div",{className:"divide-y divide-gray-100 -mx-3 -mb-3",children:e.map(t=>n.jsxs("div",{className:"px-3 py-1.5 flex items-center gap-2",children:[n.jsx(or,{status:t.status}),n.jsx("span",{className:"text-xs text-[var(--text-secondary)] font-mono truncate",children:t.path})]},t.path))})}function If({showStepResults:e,showResultsPanel:t,openResults:r,closeResults:s}){const a=i.useRef(!1);i.useEffect(()=>{if(e){a.current=!0,t||r();return}a.current&&(a.current=!1,s())},[s,r,t,e])}function Ff({showResultsCommandKey:e,hideResultsCommandKey:t,showStepResults:r}){const[s,a]=i.useState(!1),[o,l]=i.useState(0),c=i.useCallback(()=>{a(!0),l(u=>u+1)},[]),d=i.useCallback(()=>{a(!1)},[]);return i.useEffect(()=>{e&&c()},[c,e]),i.useEffect(()=>{t&&d()},[d,t]),If({showStepResults:r,showResultsPanel:s,openResults:c,closeResults:d}),{closeResults:d,openResults:c,resultsKey:o,showResultsPanel:s}}function Of(e){return(e==null?void 0:e.mode)==="ui"&&(e==null?void 0:e.slug)==="feature-complete"}function Bf({awaitingPlanLaunchChoice:e,buildActivated:t,activeTab:r,onSessionDetected:s,onSelectScenario:a,showResultsCommandKey:o,hideResultsCommandKey:l,onAgentIdle:c,onAgentActive:d,onUserInput:u,notifSettings:f,onSettingsChange:p,provider:m,onRestorePreview:h,pendingPlans:j,pendingPlansLoading:b,pendingPlansError:g,onLaunchPlan:w,launchingSlug:v,launchError:x,onReorderPlans:y,isAgentBuilding:N}){const{stepState:C}=Lt(),{closeResults:S,resultsKey:k,showResultsPanel:R}=Ff({showResultsCommandKey:o,hideResultsCommandKey:l,showStepResults:Of(C)});return t?n.jsx(Pc,{activeTab:r,showResultsPanel:R,buildTab:n.jsx(jf,{awaitingPlanLaunchChoice:e,isActive:r==="build",onSessionDetected:s,onAgentIdle:c,onAgentActive:d,onUserInput:u,provider:m,onRestorePreview:h,pendingPlans:j,pendingPlansLoading:b,pendingPlansError:g,onLaunchPlan:w,launchingSlug:v,launchError:x,onReorderPlans:y,isAgentBuilding:N}),resultsPanel:n.jsx(Rf,{onClose:S,onSelectScenario:a},k),footer:n.jsx(ql,{settings:f,onChange:p,agentName:m})}):null}function $f({className:e="h-5"}){return n.jsxs("svg",{className:e,viewBox:"0 0 79 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":"CodeYam Editor",children:[n.jsx("path",{d:"M5.50742 6.94462H6.6669C6.89825 6.94462 7.12013 6.85463 7.28372 6.69444C7.44731 6.53426 7.53921 6.317 7.53921 6.09047C7.53921 5.86394 7.44731 5.64668 7.28372 5.4865C7.12013 5.32631 6.89825 5.23633 6.6669 5.23633H5.51133C5.27997 5.23633 5.05809 5.32631 4.8945 5.4865C4.73091 5.64668 4.639 5.86394 4.639 6.09047C4.639 6.20264 4.61644 6.31372 4.57261 6.41735C4.52877 6.52098 4.46451 6.61513 4.38351 6.69444C4.3025 6.77376 4.20634 6.83668 4.1005 6.8796C3.99467 6.92253 3.88124 6.94462 3.76668 6.94462H2.61111C2.38009 6.94462 2.15851 7.03435 1.99498 7.19412C1.83144 7.35389 1.7393 7.57066 1.73878 7.79687C1.73878 8.02307 1.64715 8.24003 1.48398 8.40016C1.32081 8.56029 1.09944 8.6505 0.868421 8.65101C0.637744 8.65202 0.416859 8.74245 0.25411 8.90253C0.0913609 9.0626 -2.30897e-06 9.27929 0 9.50516C-5.79344e-07 9.73086 0.0914247 9.94733 0.254229 10.1071C0.417033 10.2669 0.637923 10.3569 0.868421 10.3574C1.09944 10.3579 1.32081 10.4481 1.48398 10.6082C1.64715 10.7684 1.73878 10.9853 1.73878 11.2115C1.73878 11.4381 1.83069 11.6553 1.99429 11.8155C2.15788 11.9757 2.37976 12.0657 2.61111 12.0657H3.76668C3.9977 12.0657 4.21928 12.1554 4.38282 12.3152C4.54635 12.475 4.63848 12.6917 4.639 12.9179C4.639 13.1445 4.73091 13.3617 4.8945 13.5219C5.05809 13.6821 5.27997 13.7721 5.51133 13.7721H6.6669C6.78136 13.7721 6.8947 13.75 7.00043 13.707C7.10615 13.6641 7.20218 13.6011 7.28303 13.5218C7.36388 13.4424 7.42794 13.3483 7.47157 13.2447C7.51519 13.141 7.53753 13.03 7.53727 12.9179C7.53727 12.6919 7.44556 12.4751 7.28234 12.3153C7.11911 12.1555 6.89773 12.0657 6.6669 12.0657H5.50937C5.27836 12.0652 5.05698 11.975 4.89381 11.8148C4.73064 11.6547 4.639 11.4377 4.639 11.2115C4.639 10.985 4.5471 10.7678 4.38351 10.6076C4.21991 10.4474 3.99804 10.3574 3.76668 10.3574H2.59745C2.36929 10.3574 2.15025 10.2697 1.98746 10.1132C1.82468 9.95667 1.73117 9.74381 1.72707 9.52044C1.72707 9.52044 1.72707 9.52045 1.72707 9.50516C1.72707 9.50516 1.72707 9.49369 1.72707 9.48796C1.73117 9.26459 1.82468 9.05173 1.98746 8.89519C2.15025 8.73866 2.36929 8.65097 2.59745 8.65101H3.76668C3.99804 8.65101 4.21991 8.56102 4.38351 8.40084C4.5471 8.24065 4.639 8.0234 4.639 7.79687C4.639 7.57117 4.73043 7.35468 4.89324 7.19491C5.05604 7.03514 5.27692 6.94513 5.50742 6.94462Z",fill:"currentColor"}),n.jsx("path",{d:"M17.1351 5.27098C16.9037 5.27098 16.6818 5.36096 16.5183 5.52115C16.3547 5.68133 16.2628 5.89859 16.2628 6.12512V7.83152C16.2628 7.94368 16.2402 8.05475 16.1964 8.15838C16.1525 8.26201 16.0883 8.35618 16.0073 8.43549C15.9263 8.51481 15.8301 8.57771 15.7243 8.62064C15.6184 8.66356 15.505 8.68566 15.3904 8.68566C15.1594 8.68616 14.938 8.77637 14.7749 8.9365C14.6117 9.09663 14.5201 9.31361 14.5201 9.53981C14.5196 9.76602 14.4274 9.98278 14.2639 10.1426C14.1003 10.3023 13.8788 10.392 13.6477 10.392C13.4167 10.392 13.1951 10.3023 13.0316 10.1426C12.8681 9.98278 12.7759 9.76602 12.7754 9.53981C12.7754 9.31361 12.6838 9.09663 12.5206 8.9365C12.3574 8.77637 12.1361 8.68616 11.9051 8.68566C11.7905 8.68566 11.6771 8.66356 11.5712 8.62064C11.4654 8.57771 11.3692 8.51481 11.2882 8.43549C11.2072 8.35618 11.143 8.26201 11.0991 8.15838C11.0553 8.05475 11.0327 7.94368 11.0327 7.83152V6.13086C11.0383 6.01542 11.0199 5.90007 10.9786 5.7918C10.9374 5.68352 10.8741 5.58458 10.7926 5.50095C10.7112 5.41732 10.6132 5.35074 10.5047 5.30526C10.3962 5.25977 10.2794 5.23633 10.1614 5.23633C10.0434 5.23633 9.92656 5.25977 9.81805 5.30526C9.70955 5.35074 9.61161 5.41732 9.53015 5.50095C9.44869 5.58458 9.38541 5.68352 9.34414 5.7918C9.30287 5.90007 9.28446 6.01542 9.29004 6.13086V7.83724C9.29004 8.06345 9.38168 8.28041 9.54485 8.44054C9.70802 8.60067 9.9294 8.69089 10.1604 8.6914C10.3918 8.6914 10.6136 8.78138 10.7772 8.94157C10.9408 9.10175 11.0327 9.31901 11.0327 9.54554C11.0332 9.77174 11.1254 9.98851 11.2889 10.1483C11.4525 10.308 11.674 10.3978 11.9051 10.3978C12.1351 10.3983 12.3556 10.4877 12.5186 10.6466C12.6816 10.8055 12.7739 11.021 12.7754 11.2462V12.966C12.7754 13.1922 12.8671 13.4091 13.0302 13.5693C13.1934 13.7294 13.4148 13.8196 13.6458 13.8201C13.8771 13.8201 14.099 13.7301 14.2626 13.5699C14.4262 13.4097 14.5181 13.1925 14.5181 12.966V11.2596C14.5181 11.0334 14.6097 10.8164 14.7729 10.6563C14.9361 10.4961 15.1575 10.4059 15.3885 10.4054C15.6195 10.4054 15.8411 10.3157 16.0046 10.1559C16.1682 9.99616 16.2603 9.77938 16.2608 9.55318C16.2608 9.32664 16.3527 9.10939 16.5163 8.9492C16.6799 8.78902 16.9018 8.69904 17.1331 8.69904C17.3641 8.69853 17.5855 8.60832 17.7487 8.44819C17.9119 8.28806 18.0035 8.07109 18.0035 7.84488V6.13086C18.0043 6.01853 17.9824 5.90715 17.9392 5.80311C17.8959 5.69907 17.8321 5.6044 17.7515 5.52453C17.6708 5.44466 17.5748 5.38115 17.4691 5.33764C17.3633 5.29414 17.2498 5.27148 17.1351 5.27098Z",fill:"currentColor"}),n.jsx("path",{d:"M28.609 14.209C27.883 14.209 27.2597 14.0807 26.739 13.824C26.2183 13.5673 25.793 13.2337 25.463 12.823C25.1403 12.4123 24.902 11.965 24.748 11.481C24.594 10.997 24.517 10.5313 24.517 10.084V9.842C24.517 9.34333 24.594 8.852 24.748 8.368C24.9093 7.884 25.155 7.444 25.485 7.048C25.815 6.652 26.233 6.33667 26.739 6.102C27.2523 5.86 27.8573 5.739 28.554 5.739C29.28 5.739 29.9107 5.871 30.446 6.135C30.9887 6.39167 31.4213 6.75833 31.744 7.235C32.0667 7.70433 32.261 8.25433 32.327 8.885H30.754C30.6953 8.51833 30.5633 8.21033 30.358 7.961C30.16 7.70433 29.907 7.51367 29.599 7.389C29.291 7.257 28.9427 7.191 28.554 7.191C28.158 7.191 27.806 7.26067 27.498 7.4C27.19 7.532 26.9333 7.72267 26.728 7.972C26.5227 8.22133 26.365 8.51467 26.255 8.852C26.1523 9.18933 26.101 9.56333 26.101 9.974C26.101 10.37 26.1523 10.7367 26.255 11.074C26.365 11.4113 26.5263 11.7083 26.739 11.965C26.9517 12.2143 27.212 12.4087 27.52 12.548C27.8353 12.6873 28.1983 12.757 28.609 12.757C29.2103 12.757 29.7163 12.6103 30.127 12.317C30.545 12.0163 30.798 11.5983 30.886 11.063H32.459C32.3857 11.635 32.1913 12.1593 31.876 12.636C31.5607 13.1127 31.128 13.494 30.578 13.78C30.028 14.066 29.3717 14.209 28.609 14.209ZM36.5271 14.209C35.9991 14.209 35.5334 14.1247 35.1301 13.956C34.7268 13.7873 34.3858 13.56 34.1071 13.274C33.8284 12.9807 33.6158 12.6507 33.4691 12.284C33.3298 11.9173 33.2601 11.536 33.2601 11.14V10.909C33.2601 10.4983 33.3334 10.1097 33.4801 9.743C33.6341 9.369 33.8504 9.039 34.1291 8.753C34.4151 8.45967 34.7598 8.23233 35.1631 8.071C35.5664 7.90233 36.0211 7.818 36.5271 7.818C37.0331 7.818 37.4878 7.90233 37.8911 8.071C38.2944 8.23233 38.6354 8.45967 38.9141 8.753C39.2001 9.039 39.4164 9.369 39.5631 9.743C39.7098 10.1097 39.7831 10.4983 39.7831 10.909V11.14C39.7831 11.536 39.7098 11.9173 39.5631 12.284C39.4238 12.6507 39.2148 12.9807 38.9361 13.274C38.6574 13.56 38.3164 13.7873 37.9131 13.956C37.5098 14.1247 37.0478 14.209 36.5271 14.209ZM36.5271 12.9C36.9011 12.9 37.2164 12.8193 37.4731 12.658C37.7298 12.4893 37.9241 12.2657 38.0561 11.987C38.1881 11.701 38.2541 11.3783 38.2541 11.019C38.2541 10.6523 38.1844 10.3297 38.0451 10.051C37.9131 9.765 37.7151 9.54133 37.4511 9.38C37.1944 9.21133 36.8864 9.127 36.5271 9.127C36.1678 9.127 35.8561 9.21133 35.5921 9.38C35.3354 9.54133 35.1374 9.765 34.9981 10.051C34.8588 10.3297 34.7891 10.6523 34.7891 11.019C34.7891 11.3783 34.8551 11.701 34.9871 11.987C35.1264 12.2657 35.3244 12.4893 35.5811 12.658C35.8378 12.8193 36.1531 12.9 36.5271 12.9ZM43.5969 14.198C43.1789 14.198 42.7939 14.121 42.4419 13.967C42.0899 13.813 41.7856 13.5967 41.5289 13.318C41.2723 13.0393 41.0743 12.7167 40.9349 12.35C40.7956 11.976 40.7259 11.5727 40.7259 11.14V10.909C40.7259 10.4837 40.7919 10.084 40.9239 9.71C41.0633 9.336 41.2539 9.00967 41.4959 8.731C41.7453 8.45233 42.0423 8.236 42.3869 8.082C42.7389 7.92067 43.1276 7.84 43.5529 7.84C44.0223 7.84 44.4329 7.94267 44.7849 8.148C45.1443 8.346 45.4303 8.64667 45.6429 9.05C45.8556 9.45333 45.9729 9.95933 45.9949 10.568L45.5439 10.04V5.97H47.0729V14H45.8629V11.459H46.1269C46.1049 12.0677 45.9803 12.5773 45.7529 12.988C45.5256 13.3913 45.2249 13.6957 44.8509 13.901C44.4843 14.099 44.0663 14.198 43.5969 14.198ZM43.9379 12.911C44.2386 12.911 44.5136 12.845 44.7629 12.713C45.0123 12.5737 45.2103 12.3757 45.3569 12.119C45.5109 11.855 45.5879 11.547 45.5879 11.195V10.755C45.5879 10.403 45.5109 10.1097 45.3569 9.875C45.2029 9.633 45.0013 9.44967 44.7519 9.325C44.5026 9.193 44.2313 9.127 43.9379 9.127C43.6079 9.127 43.3146 9.20767 43.0579 9.369C42.8086 9.523 42.6106 9.743 42.4639 10.029C42.3246 10.315 42.2549 10.6487 42.2549 11.03C42.2549 11.4113 42.3283 11.745 42.4749 12.031C42.6216 12.3097 42.8196 12.526 43.0689 12.68C43.3256 12.834 43.6153 12.911 43.9379 12.911ZM51.4863 14.209C50.973 14.209 50.522 14.121 50.1333 13.945C49.752 13.769 49.433 13.5343 49.1763 13.241C48.927 12.9403 48.7363 12.6067 48.6043 12.24C48.4797 11.8733 48.4173 11.4993 48.4173 11.118V10.909C48.4173 10.513 48.4797 10.1317 48.6043 9.765C48.7363 9.391 48.927 9.061 49.1763 8.775C49.433 8.48167 49.7483 8.25067 50.1223 8.082C50.4963 7.906 50.929 7.818 51.4203 7.818C52.0657 7.818 52.6047 7.961 53.0373 8.247C53.4773 8.52567 53.8073 8.896 54.0273 9.358C54.2473 9.81267 54.3573 10.304 54.3573 10.832V11.382H49.0663V10.447H53.4003L52.9273 10.909C52.9273 10.5277 52.8723 10.2013 52.7623 9.93C52.6523 9.65867 52.4837 9.44967 52.2563 9.303C52.0363 9.15633 51.7577 9.083 51.4203 9.083C51.083 9.083 50.797 9.16 50.5623 9.314C50.3277 9.468 50.148 9.69167 50.0233 9.985C49.906 10.271 49.8473 10.6157 49.8473 11.019C49.8473 11.393 49.906 11.7267 50.0233 12.02C50.1407 12.306 50.3203 12.5333 50.5623 12.702C50.8043 12.8633 51.1123 12.944 51.4863 12.944C51.8603 12.944 52.1647 12.8707 52.3993 12.724C52.634 12.57 52.7843 12.383 52.8503 12.163H54.2583C54.1703 12.5737 54.0017 12.933 53.7523 13.241C53.503 13.549 53.184 13.7873 52.7953 13.956C52.414 14.1247 51.9777 14.209 51.4863 14.209ZM57.2956 10.931L54.8756 5.97H56.4816L58.3296 9.853L57.9776 9.743H59.0226L58.6486 9.853L60.3316 5.97H61.8496L59.6166 10.931H57.2956ZM57.6916 14V10.689H59.2206V14H57.6916ZM66.0534 14V12.229H65.8004V10.26C65.8004 9.91533 65.7161 9.65867 65.5474 9.49C65.3788 9.32133 65.1184 9.237 64.7664 9.237C64.5831 9.237 64.3631 9.24067 64.1064 9.248C63.8498 9.25533 63.5894 9.26633 63.3254 9.281C63.0688 9.28833 62.8378 9.29933 62.6324 9.314V8.016C62.8011 8.00133 62.9918 7.98667 63.2044 7.972C63.4171 7.95733 63.6334 7.95 63.8534 7.95C64.0808 7.94267 64.2934 7.939 64.4914 7.939C65.1074 7.939 65.6171 8.01967 66.0204 8.181C66.4311 8.34233 66.7391 8.59533 66.9444 8.94C67.1571 9.28467 67.2634 9.73567 67.2634 10.293V14H66.0534ZM64.1284 14.154C63.6958 14.154 63.3144 14.077 62.9844 13.923C62.6618 13.769 62.4088 13.549 62.2254 13.263C62.0494 12.977 61.9614 12.6323 61.9614 12.229C61.9614 11.789 62.0678 11.4297 62.2804 11.151C62.5004 10.8723 62.8048 10.6633 63.1934 10.524C63.5894 10.3847 64.0514 10.315 64.5794 10.315H65.9654V11.228H64.5574C64.2054 11.228 63.9341 11.316 63.7434 11.492C63.5601 11.6607 63.4684 11.8807 63.4684 12.152C63.4684 12.4233 63.5601 12.6433 63.7434 12.812C63.9341 12.9807 64.2054 13.065 64.5574 13.065C64.7701 13.065 64.9644 13.0283 65.1404 12.955C65.3238 12.8743 65.4741 12.7423 65.5914 12.559C65.7161 12.3683 65.7858 12.1117 65.8004 11.789L66.1744 12.218C66.1378 12.636 66.0351 12.988 65.8664 13.274C65.7051 13.56 65.4778 13.78 65.1844 13.934C64.8984 14.0807 64.5464 14.154 64.1284 14.154ZM68.9012 14V8.027H70.1112V10.59H70.0012C70.0012 9.98867 70.0782 9.48633 70.2322 9.083C70.3862 8.67233 70.6136 8.36433 70.9142 8.159C71.2222 7.94633 71.6036 7.84 72.0582 7.84H72.1242C72.5862 7.84 72.9676 7.94633 73.2682 8.159C73.5762 8.36433 73.8036 8.67233 73.9502 9.083C74.1042 9.48633 74.1812 9.98867 74.1812 10.59H73.7962C73.7962 9.98867 73.8732 9.48633 74.0272 9.083C74.1886 8.67233 74.4196 8.36433 74.7202 8.159C75.0282 7.94633 75.4096 7.84 75.8642 7.84H75.9302C76.3922 7.84 76.7772 7.94633 77.0852 8.159C77.3932 8.36433 77.6242 8.67233 77.7782 9.083C77.9396 9.48633 78.0202 9.98867 78.0202 10.59V14H76.4912V10.447C76.4912 10.073 76.3959 9.776 76.2052 9.556C76.0146 9.32867 75.7432 9.215 75.3912 9.215C75.0392 9.215 74.7569 9.33233 74.5442 9.567C74.3316 9.79433 74.2252 10.1023 74.2252 10.491V14H72.6962V10.447C72.6962 10.073 72.6009 9.776 72.4102 9.556C72.2196 9.32867 71.9482 9.215 71.5962 9.215C71.2442 9.215 70.9619 9.33233 70.7492 9.567C70.5366 9.79433 70.4302 10.1023 70.4302 10.491V14H68.9012Z",fill:"currentColor"})]})}function _f({name:e}){const t={width:13,height:13,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"};return e==="Desktop"?n.jsxs("svg",{...t,children:[n.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),n.jsx("path",{d:"M8 21h8M12 17v4"})]}):e==="Laptop"?n.jsxs("svg",{...t,children:[n.jsx("path",{d:"M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8H4V6z"}),n.jsx("path",{d:"M2 18h20"})]}):e==="Tablet"?n.jsxs("svg",{...t,children:[n.jsx("rect",{x:"5",y:"2",width:"14",height:"20",rx:"2"}),n.jsx("path",{d:"M12 18h.01"})]}):e==="Mobile"?n.jsxs("svg",{...t,children:[n.jsx("rect",{x:"7",y:"2",width:"10",height:"20",rx:"2"}),n.jsx("path",{d:"M12 18h.01"})]}):n.jsx("span",{className:"text-xs",children:e})}const ls=["·","✢","✳","✶","✻","✽"],zf=160;function Hf(){const[e,t]=i.useState(0);return i.useEffect(()=>{const r=window.setInterval(()=>t(s=>(s+1)%ls.length),zf);return()=>window.clearInterval(r)},[]),n.jsx("span",{"data-testid":"nav-build-dot-active","aria-label":"Build in progress",className:"mr-1 inline-block w-3 text-center text-[#29C0CF] leading-none text-[11px] tabular-nums",children:ls[e]})}function Wf({size:e=16}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),n.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]})}function Vf({onNavigateToBuild:e,onDismiss:t}){return i.useEffect(()=>(V("banner-mounted",{}),()=>{V("banner-unmounted",{})}),[]),n.jsx("div",{className:"bg-black border-t border-[#333] px-4 py-1.5 flex items-center justify-center",children:n.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-lg border border-[#FF8B43]/60 bg-[#2a1500] shrink-0",children:[n.jsxs("button",{type:"button",onClick:e,className:"flex items-center gap-2 cursor-pointer",children:[n.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-[#FF8B43] shrink-0"}),n.jsxs("span",{className:"text-sm text-[#FF8B43]",children:["Claude is waiting for you."," ",n.jsx("span",{className:"text-[#FF8B43] font-medium underline",children:"Build."})]})]}),n.jsx("button",{type:"button",onClick:r=>{r.stopPropagation(),t()},className:"p-0.5 text-[#FF8B43]/60 hover:text-[#FF8B43] transition-colors cursor-pointer",title:"Dismiss",children:n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",fill:"none",children:n.jsx("path",{d:"M3 3l8 8M11 3l-8 8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})})]})})}function He(){const e=()=>{typeof window<"u"&&window.dispatchEvent(new Event("terminal-focus"))};e();const t=requestAnimationFrame(e),r=setTimeout(e,50);return()=>{cancelAnimationFrame(t),clearTimeout(r)}}const Uf=[{key:"home",label:"Home"},{key:"plan",label:"Plan"},{key:"build",label:"Build"},{key:"history",label:"History"}];function Kf(){if(typeof document>"u")return;const e=document.activeElement;e instanceof HTMLElement&&e.blur()}function Gf({activeTab:e,onTabChange:t,onSendTranscript:r,buildIdle:s=!1,isAgentBuilding:a=!1,bannerVisible:o=!1,onDismissIdleBanner:l}){const c=o&&e!=="build",d=s,u=a&&!s,f=u?"green":d?"orange":"none",p=i.useRef(f);return i.useEffect(()=>{p.current!==f&&(V("build-tab-dot-change",{from:p.current,to:f}),p.current=f)},[f]),n.jsxs("div",{className:"shrink-0",children:[n.jsxs("div",{className:"bg-black h-10 flex items-center px-4 gap-4",children:[n.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[n.jsx("div",{className:"flex items-center gap-2 shrink-0",children:n.jsx($f,{className:"h-5 text-white shrink-0"})}),n.jsx("span",{className:"text-[#8E8E8E] text-sm shrink-0",children:"/"}),n.jsx("div",{className:"flex items-center gap-1",children:Uf.map(m=>n.jsxs(Hs,{href:On(m.key),"data-nav-tab":"true",onNavigate:()=>{t(m.key),Kf(),m.key==="build"&&He()},className:`px-2.5 py-2.5 text-sm transition-colors cursor-pointer border-b ${e===m.key?"text-[#D7FF63] border-[#D7FF63] font-medium":"text-[#8E8E8E] border-transparent hover:text-white font-light"}`,children:[m.key==="build"&&u&&n.jsx(Hf,{}),m.key==="build"&&d&&n.jsx("span",{"data-testid":"nav-build-dot-idle",className:"mr-1 inline-block w-2 h-2 rounded-full bg-[#FF8B43]"}),m.label]},m.key))})]}),n.jsx("div",{className:"flex-1"}),n.jsx("button",{onClick:r,className:"p-1.5 rounded-md transition-colors cursor-pointer text-[#8E8E8E] hover:text-white",title:"Send Session Feedback",children:n.jsx(Wf,{})}),!1]}),c&&n.jsx(Vf,{onNavigateToBuild:()=>t("build"),onDismiss:l??(()=>{})})]})}function Yf(e,t){for(const r of e.filesByDirectory)for(const s of r.files)if(s.filePath===t)return s;return null}function Ra(e){return e>=80?"#16a34a":e>=50?"#eab308":"#dc2626"}function Mt({coverage:e}){const t=Math.max(0,Math.min(100,e.percent)),r=Ra(t);return n.jsxs("div",{className:"flex items-center gap-2 min-w-[140px]","data-testid":"coverage-bar",children:[n.jsx("div",{className:"flex-1 h-1.5 rounded-full bg-gray-200 overflow-hidden",children:n.jsx("div",{"data-testid":"coverage-bar-fill",className:"h-full rounded-full",style:{width:`${t}%`,backgroundColor:r}})}),n.jsxs("span",{className:"text-xs font-mono tabular-nums",style:{color:r},children:[Math.round(t),"%"]})]})}function Jf({file:e,onSelectFile:t}){return n.jsxs("li",{className:"flex items-center gap-3 py-2","data-testid":"coverage-details-directory-file-row",children:[n.jsx("button",{type:"button",onClick:()=>t(e),className:"flex-1 min-w-0 text-left text-xs text-gray-700 truncate hover:underline cursor-pointer",children:e.filePath}),n.jsx(Mt,{coverage:e.coverage})]})}function Xf({group:e,onSelectFile:t}){return n.jsxs("details",{"data-testid":"coverage-details-directory-group",children:[n.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-gray-800",children:[e.directory||"(root)"," ·"," ",n.jsxs("span",{className:"text-gray-500",children:[e.files.length," file",e.files.length===1?"":"s"]})]}),n.jsx("ul",{className:"divide-y divide-gray-100 mt-2",children:e.files.map(r=>n.jsx(Jf,{file:r,onSelectFile:t},r.filePath))})]})}function qf({directories:e,onSelectFile:t}){return e.length===0?null:n.jsxs("section",{className:"bg-white border border-gray-200 rounded-lg p-4","data-testid":"coverage-details-directories-section",children:[n.jsx("h3",{className:"text-sm font-semibold text-gray-900 m-0 mb-2",children:"By directory"}),n.jsx("div",{className:"flex flex-col gap-3",children:e.map(r=>n.jsx(Xf,{group:r,onSelectFile:t},r.directory||"(root)"))})]})}function Qf({entry:e,onSelectFile:t}){return n.jsxs("li",{className:"flex items-center gap-3 py-2","data-testid":"coverage-details-entry-row",children:[n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("button",{type:"button",onClick:()=>t(e.filePath),className:"text-sm font-medium text-gray-900 truncate text-left hover:underline cursor-pointer",children:e.name}),n.jsx("div",{className:"text-xs text-gray-500 truncate",children:e.filePath}),e.linkedTests.length>0&&n.jsxs("div",{className:"text-xs text-gray-400 truncate",children:[e.linkedTests.length," linked test",e.linkedTests.length===1?"":"s"]})]}),n.jsx(Mt,{coverage:{percent:e.percent,hitLines:e.hitLines,totalLines:e.totalLines}})]})}function Zf({entries:e,onSelectFile:t}){return n.jsxs("section",{className:"bg-white border border-gray-200 rounded-lg p-4","data-testid":"coverage-details-entries-section",children:[n.jsx("h3",{className:"text-sm font-semibold text-gray-900 m-0 mb-2",children:"By glossary entry"}),e.length===0?n.jsx("p",{className:"text-xs text-gray-500","data-testid":"coverage-details-entries-empty",children:"No glossary entries have coverage data yet."}):n.jsx("ul",{className:"divide-y divide-gray-100",children:e.map(r=>n.jsx(Qf,{entry:r,onSelectFile:t},`${r.filePath}::${r.name}`))})]})}function Ta({file:e}){return n.jsxs("li",{className:"flex items-center gap-3 py-2","data-testid":"orphaned-file-row",children:[n.jsx("div",{className:"flex-1 min-w-0",children:n.jsx("div",{className:"text-xs text-gray-500 truncate",children:e.filePath})}),n.jsx("span",{className:"text-[10px] uppercase tracking-wide text-gray-400",title:"Coverage at file level — no glossary entry maps to this file.",children:"file-level"}),n.jsx(Mt,{coverage:e.coverage})]})}function ep({files:e,onSelectFile:t}){return e.length===0?null:n.jsxs("section",{className:"bg-white border border-gray-200 rounded-lg p-4","data-testid":"coverage-details-orphaned-section",children:[n.jsx("h3",{className:"text-sm font-semibold text-gray-900 m-0 mb-2",children:"Orphaned files"}),n.jsxs("div",{className:"text-xs text-gray-500 mb-2",children:[e.length," file",e.length===1?"":"s"," with coverage but no glossary entry."]}),n.jsx("ul",{className:"divide-y divide-gray-100",children:e.map(r=>n.jsx("div",{onClick:()=>t(r.filePath),role:"button",tabIndex:0,className:"cursor-pointer",onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),t(r.filePath))},children:n.jsx(Ta,{file:r})},r.filePath))})]})}function tp({line:e,hits:t}){const r=t>0;return n.jsxs("li",{className:"flex items-center gap-3 py-1 font-mono text-xs","data-testid":r?"coverage-line-hit":"coverage-line-miss",children:[n.jsx("span",{className:"w-12 text-right text-gray-400",children:e}),n.jsx("span",{className:r?"px-2 py-0.5 rounded bg-green-100 text-green-800":"px-2 py-0.5 rounded bg-red-100 text-red-800",children:r?`×${t}`:"miss"})]})}function np({file:e,onBack:t}){const r=Object.entries(e.lines).map(([s,a])=>({line:Number(s),hits:a})).sort((s,a)=>s.line-a.line);return n.jsxs("div",{"data-testid":"coverage-file-drilldown",className:"flex flex-col gap-3",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("button",{type:"button",onClick:t,className:"text-xs font-medium text-[var(--accent-active)] hover:underline cursor-pointer","data-testid":"coverage-file-drilldown-back",children:"← Back"}),n.jsx("div",{className:"text-sm font-medium text-gray-900 truncate mt-1",children:e.filePath})]}),n.jsx(Mt,{coverage:e.coverage})]}),r.length===0?n.jsx("p",{className:"text-xs text-gray-500",children:"No instrumented lines in this file."}):n.jsx("ul",{className:"divide-y divide-gray-100 max-h-[50vh] overflow-y-auto","data-testid":"coverage-file-drilldown-lines",children:r.map(({line:s,hits:a})=>n.jsx(tp,{line:s,hits:a},s))})]})}function vr({title:e,aggregate:t,aggregateTestId:r}){return n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsx("h2",{className:"text-sm font-semibold text-gray-900 m-0",children:e}),t&&t.totalLines>0&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("span",{className:"text-xs text-gray-500",children:[t.hitLines,"/",t.totalLines," lines"]}),n.jsxs("span",{className:"text-xs font-semibold",style:{color:Ra(t.percent)},"data-testid":r,children:[Math.round(t.percent),"% overall"]})]})]})}function Pa({warnings:e}){return e.length===0?null:n.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4","data-testid":"coverage-warnings-banner",children:n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("span",{className:"text-amber-600 text-lg leading-none mt-0.5","aria-hidden":"true",children:"!"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("h3",{className:"text-sm font-semibold text-amber-800 m-0",children:"Coverage Warnings"}),n.jsx("ul",{className:"mt-1 space-y-1 text-sm text-amber-700 list-none p-0 m-0",children:e.map((t,r)=>n.jsx("li",{className:"break-words",children:t},r))})]})]})})}function rp({onClose:e,fetchDetails:t=sp,initialData:r}){const[s,a]=i.useState(r??null),[o,l]=i.useState(null),[c,d]=i.useState(null);i.useEffect(()=>{if(r)return;let p=!1;return t().then(m=>{p||a(m)}).catch(m=>{p||l(m instanceof Error?m.message:String(m))}),()=>{p=!0}},[t,r]);const u=i.useCallback(p=>{p.key==="Escape"&&(p.preventDefault(),c?d(null):e())},[e,c]);i.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]);const f=p=>{if(!s)return;const m=Yf(s,p);m&&d(m)};return n.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},"data-testid":"coverage-details-modal",onClick:e,children:n.jsxs("div",{className:"max-w-3xl w-full mx-4 p-6 rounded-lg bg-[var(--bg-card)] max-h-[90vh] overflow-y-auto",onClick:p=>p.stopPropagation(),children:[n.jsxs("div",{className:"flex items-start justify-between gap-3 mb-4",children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] m-0",children:"Project coverage"}),n.jsx("button",{type:"button",onClick:e,className:"text-sm text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer","data-testid":"coverage-details-modal-close","aria-label":"Close",children:"✕"})]}),o&&n.jsxs("p",{className:"text-sm text-red-700","data-testid":"coverage-details-modal-error",children:["Failed to load coverage details: ",o]}),!s&&!o&&n.jsx("p",{className:"text-sm text-[var(--text-muted)]","data-testid":"coverage-details-modal-loading",children:"Loading coverage details…"}),s&&c&&n.jsx(np,{file:c,onBack:()=>d(null)}),s&&!c&&n.jsxs("div",{className:"flex flex-col gap-6",children:[n.jsx(vr,{title:"Overall",aggregate:s.projectWide,aggregateTestId:"coverage-details-modal-aggregate"}),s.coverageWarnings.length>0&&n.jsx(Pa,{warnings:s.coverageWarnings}),n.jsx(Zf,{entries:s.entries,onSelectFile:f}),n.jsx(ep,{files:s.orphanedFiles,onSelectFile:f}),n.jsx(qf,{directories:s.filesByDirectory,onSelectFile:d})]})]})})}function sp(){return fetch("/api/coverage/details").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()})}function ap({appDetailProps:e,appOverviewProps:t,selectedApp:r}){const[s,a]=i.useState(!1),o=()=>a(!0),l=()=>a(!1),c=r?n.jsx(al,{app:r,...e,onCoverageClick:o}):n.jsx(Rc,{...t,onCoverageClick:o},"app-overview");return n.jsxs(n.Fragment,{children:[c,s&&n.jsx(rp,{onClose:l})]})}function op({activeTab:e,awaitingPlanLaunchChoice:t,buildActivated:r,hideResultsCommandKey:s,onSelectScenario:a,onSessionDetected:o,showResultsCommandKey:l,onAgentIdle:c,onAgentActive:d,onUserInput:u,notifSettings:f,onSettingsChange:p,provider:m,onRestorePreview:h,pendingPlans:j,pendingPlansLoading:b,pendingPlansError:g,onLaunchPlan:w,launchingSlug:v,launchError:x,onReorderPlans:y,isAgentBuilding:N}){return r?n.jsx(Bf,{awaitingPlanLaunchChoice:t,buildActivated:r,activeTab:e,onSessionDetected:o,onSelectScenario:a,showResultsCommandKey:l,hideResultsCommandKey:s,onAgentIdle:c,onAgentActive:d,onUserInput:u,notifSettings:f,onSettingsChange:p,provider:m,onRestorePreview:h,pendingPlans:j,pendingPlansLoading:b,pendingPlansError:g,onLaunchPlan:w,launchingSlug:v,launchError:x,onReorderPlans:y,isAgentBuilding:N}):null}function ip({onMouseDown:e}){return n.jsx("div",{onMouseDown:e,className:"shrink-0 flex items-center justify-center group",style:{width:12,cursor:"col-resize",background:"var(--bg-surface)",borderLeft:"1px solid var(--border-default)",borderRight:"1px solid var(--border-default)"},children:n.jsx("div",{className:"w-0.5 h-8 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",style:{background:"var(--text-dim)"}})})}function lp({isCollapsed:e,leftPane:t,onResizeStart:r,previewPane:s,splitRef:a}){return n.jsxs("div",{ref:a,className:"fixed inset-0 flex",style:{background:"var(--bg-surface)"},children:[!e&&n.jsxs(n.Fragment,{children:[t,n.jsx(ip,{onMouseDown:r})]}),s]})}function br(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),{plansVersion:l}=Rt(),c=i.useCallback(async()=>{s(!0),o(null);try{const d=await fetch("/api/plans");if(!d.ok)throw new Error(`HTTP ${d.status}`);const u=await d.json();t(Array.isArray(u)?u.map(f=>({...f,dependsOn:Array.isArray(f.dependsOn)?f.dependsOn:[]})):[])}catch(d){o(d instanceof Error?d.message:"Failed to load plans")}finally{s(!1)}},[]);return i.useEffect(()=>{c()},[c,l]),{plans:e,loading:r,error:a,refetch:c}}function Da(e=10){const[t,r]=i.useState([]),[s,a]=i.useState(!0),[o,l]=i.useState(null),c=i.useCallback(async()=>{a(!0),l(null);try{const d=await fetch(`/api/plans/completed?limit=${e}`);if(!d.ok)throw new Error(`HTTP ${d.status}`);const u=await d.json();r(Array.isArray(u)?u:[])}catch(d){l(d instanceof Error?d.message:"Failed to load completed plans")}finally{a(!1)}},[e]);return i.useEffect(()=>{c()},[c]),{plans:t,loading:s,error:o,refetch:c}}function cp(e,t,r){const s=new Map(r.map(o=>[o.slug,o])),a=new Map(t.map(o=>[o.slug,o]));return e.dependsOn.map(o=>{const l=s.get(o),c=a.get(o);return{slug:o,title:(c==null?void 0:c.title)??(l==null?void 0:l.title)??null,satisfied:l!==void 0}})}function Aa(e){return e.filter(t=>!t.satisfied)}function La(e){const{plans:t}=Da();return i.useMemo(()=>{const r={},s={};for(const a of e){const o=a.dependsOn??[];if(o.length===0)continue;const l=cp({...a,dependsOn:o},e,t);s[a.slug]=l;const c=Aa(l);c.length!==0&&(r[a.slug]={count:c.length,tooltip:c.map(d=>d.title??`missing: ${d.slug}`).join(", ")})}return{annotationsBySlug:r,dependenciesBySlug:s}},[e,t])}let ct={hasActiveSession:!1,isAgentBuilding:!1,stepStateFeature:null};function Ma(e){ct={...ct,...e}}function dp(){return ct}function up(){return ct.hasActiveSession||ct.isAgentBuilding||!!ct.stepStateFeature}const fp=500;async function yr(){let e=!1,t;try{const r=await fetch("/api/session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})});t=r.status,r.ok&&(e=!0)}catch{}e&&Ma({hasActiveSession:!1,isAgentBuilding:!1,stepStateFeature:null}),V("clear-editor-session",{ok:e,...t!==void 0?{status:t}:{},snapshotReset:e})}async function wr(e={}){const t=dp(),r=e.caller??"unknown",s=e.bypassLiveGuard===!0;if(up()&&!s){V("launch-editor-skill",{caller:r,suppressed:!0,snapshot:t,bypassLiveGuard:!1});return}Kc(),V("launch-editor-skill",{caller:r,suppressed:!1,snapshot:t,bypassLiveGuard:s}),e.provider!=="gemini"&&(Qs(e.renameLabel??"Editor",r,Ls),Fn("/clear\r"),await new Promise(a=>setTimeout(()=>{Fn("/codeyam-editor\r"),a()},fp)))}async function pp(e={}){await yr(),await wr(e)}function jr(e){const t=Ms(e),[r,s]=i.useState(t==="build"),[a,o]=i.useState(t==="plan");i.useEffect(()=>{t==="build"&&s(!0),t==="plan"&&o(!0)},[t]);const l=i.useCallback(d=>{window.history.pushState(null,"",On(d)),d==="build"&&s(!0),d==="plan"&&o(!0)},[]),c=i.useCallback(()=>{window.history.pushState(null,"",On("build")),s(!0)},[]);return{activeTab:t,buildActivated:r,planActivated:a,navigateToTab:l,showBuildTab:c}}function Nr(){const{showBuildTab:e}=jr(typeof window>"u"?"/":window.location.pathname),{config:t}=Ze(),[r,s]=i.useState(null),[a,o]=i.useState(null),l=i.useCallback(async(c,d)=>{if(r)return!1;o(null),s(c);try{try{await yr()}catch{}const u=await fetch(`/api/plans/${encodeURIComponent(c)}/select`,{method:"POST"});if(!u.ok){let f=`HTTP ${u.status}`;try{const p=await u.json();p!=null&&p.error&&(f=p.error)}catch{}throw new Error(f)}return e(),await wr({caller:"plan-launcher",renameLabel:d,provider:t==null?void 0:t.provider,bypassLiveGuard:!0}),!0}catch(u){return o(u instanceof Error?u.message:"Failed to launch plan"),!1}finally{s(null)}},[r,e,t==null?void 0:t.provider]);return{launchingSlug:r,error:a,launchPlan:l}}function Ia(e){return{reorderPlans:i.useCallback(async r=>{const s=await fetch("/api/plans/reorder",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({slugs:r})});if(!s.ok){const a=await s.json().catch(()=>({}));throw new Error(a.error??`HTTP ${s.status}`)}e==null||e()},[e])}}const mp={describe:"Claude Code will remember your plans and suggest them once the current building session is over.",prototype:"Build a working prototype with the agent. When it's right, formalize into Build to decompose, test, and ship."};function xp({subTab:e="describe"}={}){return n.jsxs(n.Fragment,{children:[n.jsx("h2",{className:"text-lg font-medium text-[var(--text-primary)]",children:"Plan your next move"}),n.jsx("p",{className:"mt-1 text-sm text-[var(--text-dim)]",children:mp[e]})]})}function hp({onClose:e}){const t=r=>{r.target===r.currentTarget&&e()};return n.jsx("div",{"data-testid":"plan-run-blocked-modal",onClick:t,className:"absolute inset-0 z-10 flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},children:n.jsxs("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] mb-2",children:"Build in progress"}),n.jsx("p",{className:"text-sm text-[var(--text-muted)] mb-4",children:Ca}),n.jsx("div",{className:"flex flex-col gap-3",children:n.jsx("button",{onClick:e,"data-testid":"plan-run-blocked-ok",className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition",style:{background:"var(--accent-active)",color:"var(--bg-deep)"},type:"button",children:"OK"})})]})})}function gp({deps:e,onClose:t}){const r=s=>{s.target===s.currentTarget&&t()};return n.jsx("div",{"data-testid":"plan-run-dependencies-modal",onClick:r,className:"absolute inset-0 z-10 flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},children:n.jsxs("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] mb-2",children:"Prerequisite plans not yet built"}),n.jsx("p",{className:"text-sm text-[var(--text-muted)] mb-4",children:"This plan depends on the following changes that have not yet been built. Run them first, then come back to this one."}),n.jsx("ul",{className:"flex flex-col gap-1.5 mb-4",children:e.map(s=>n.jsx("li",{"data-testid":`plan-dep-${s.slug}`,className:"text-sm text-[var(--text-primary)]",children:s.title===null?n.jsxs("span",{className:"text-[var(--text-muted)]",children:["missing: ",s.slug," — was the prerequisite plan deleted?"]}):s.title},s.slug))}),n.jsx("div",{className:"flex flex-col gap-3",children:n.jsx("button",{onClick:t,"data-testid":"plan-run-dependencies-ok",className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition",style:{background:"var(--accent-active)",color:"var(--bg-deep)"},type:"button",children:"OK"})})]})})}const vp=[{id:"describe",label:"Describe A Plan"},{id:"prototype",label:"Prototype A Plan"}];function bp({active:e,onChange:t}){return n.jsx("div",{className:"mt-3 flex items-center gap-1 border-b border-[var(--border-subtle)]",role:"tablist","data-testid":"plan-sub-tabs",children:vp.map(r=>{const s=r.id===e;return n.jsx("button",{type:"button",role:"tab","aria-selected":s,"data-testid":`plan-sub-tab-${r.id}`,onClick:()=>t(r.id),className:"px-2.5 py-2 text-sm transition-colors cursor-pointer border-b -mb-px "+(s?"text-[var(--accent-active)] border-[var(--accent-active)] font-medium":"text-[var(--text-dim)] border-transparent hover:text-[var(--text-primary)] font-light"),children:r.label},r.id)})})}function cs(e){return e.source==="prototype"}function yp(e,t){const[r,s]=i.useState(!1),a=i.useRef(new Set),o=Nr(),l=()=>{a.current=new Set(e.filter(cs).map(c=>c.slug)),s(!0)};return i.useEffect(()=>{if(!r||o.launchingSlug)return;const c=e.filter(cs).find(d=>!a.current.has(d.slug));c&&(s(!1),o.launchPlan(c.slug,c.title).then(d=>{d&&(t==null||t())}))},[r,o,e,t]),{awaitingFormalize:r,launchError:o.error,launchingSlug:o.launchingSlug,beginFormalize:l}}function wp({onClose:e}){return n.jsx(rn,{slashCommand:"/codeyam-prototype",height:480,onClose:e})}const jp="Building is in-process. Prototyping is only available when building is not ongoing. Please wait for the current building session to complete before prototyping.";function Np(){return n.jsxs("div",{"data-testid":"prototype-building-banner",className:"mt-3 rounded border px-4 py-3 text-sm",style:{background:"var(--bg-surface)",borderColor:"var(--border-default)",color:"var(--text-muted)"},children:[n.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:"Build in progress."})," ",jp]})}function ds({open:e,disabled:t=!1,onToggle:r}){const s="mt-3 inline-flex items-center gap-2 rounded border px-3 py-1.5 text-xs font-medium uppercase tracking-wide transition-colors",a=t?"border-[var(--border-default)] text-[var(--text-dim)] cursor-not-allowed":"border-[var(--accent-active)] text-[var(--accent-active)] hover:bg-[var(--accent-active)] hover:text-black cursor-pointer";return n.jsx("button",{type:"button",onClick:t?void 0:r,disabled:t,"aria-disabled":t,title:t?"Building is in progress.":e?"Close Prototype":"Start Prototyping","data-testid":"start-prototyping",className:`${s} ${a}`,children:e?"Close Prototype":"Start Prototyping"})}const Yn=800;function Nt(e){window.dispatchEvent(new CustomEvent("miniagent-send-input",{detail:e}))}function Jn(e){return new Promise(t=>{let r=!1;const s=()=>{r||(r=!0,window.removeEventListener("miniagent-output",s),clearTimeout(a),t())},a=setTimeout(s,e);window.addEventListener("miniagent-output",s,{once:!0})})}const Cp='The user has clicked "Finish and Formalize in Build". Stop prototyping. Write a plan file at .codeyam/plans/<slug>.md describing what was prototyped. Use frontmatter with `mode: ui` and `step: 10` (or `mode: backend` and `step: 8` for backend mode) and `source: prototype`. Pick a kebab-case slug that matches the feature you prototyped. Once the Write succeeds, output "Done — opening Build to finalize." and stop.';function Sp({disabled:e=!1,onClick:t}={}){const[r,s]=i.useState(!1),a=i.useRef(!1),o=async()=>{if(!(e||a.current)){a.current=!0,s(!0);try{Nt(Cp),await Jn(Yn),Nt("\r"),t==null||t()}finally{a.current=!1,s(!1)}}},l=e||r;return n.jsx("button",{type:"button",onClick:o,disabled:l,"data-testid":"finish-and-formalize",className:"mt-3 inline-flex items-center gap-2 rounded border px-3 py-1.5 text-xs font-medium uppercase tracking-wide transition-colors "+(l?"border-[var(--border-default)] text-[var(--text-dim)] cursor-not-allowed":"border-[var(--accent-active)] text-[var(--accent-active)] hover:bg-[var(--accent-active)] hover:text-black cursor-pointer"),children:"Finish and Formalize in Build"})}function kp(e,t){return`Launches a chat window with ${e} to ${t==="describe"?"describe your plan":"start prototyping"}.`}function Fa({providerLabel:e,kind:t}){return n.jsx("p",{className:"mt-2 text-xs text-[var(--text-dim)]","data-testid":`plan-chat-launch-caption-${t}`,children:kp(e,t)})}function Ep({isAgentBuilding:e,onLaunched:t}){const[r,s]=i.useState(!1),{plans:a}=br(),{config:o}=Ze(),l=dt(o==null?void 0:o.provider),c=yp(a,()=>{s(!1),t==null||t()}),d=()=>{if(e)return;const f=!r;f&&He(),s(f)},u=()=>{s(!1)};return e?n.jsxs("div",{"data-testid":"prototype-pane",children:[n.jsx(Np,{}),n.jsx(ds,{open:!1,disabled:!0,onToggle:()=>{}})]}):n.jsxs("div",{"data-testid":"prototype-pane",children:[n.jsx(ds,{open:r,onToggle:d}),!r&&n.jsx(Fa,{providerLabel:l,kind:"prototype"}),r&&n.jsxs(n.Fragment,{children:[n.jsx(wp,{onClose:u}),n.jsx(Sp,{disabled:c.awaitingFormalize||c.launchingSlug!==null,onClick:c.beginFormalize}),c.awaitingFormalize&&n.jsx("p",{className:"mt-2 text-xs text-[var(--text-dim)]","data-testid":"prototype-awaiting-formalize",children:"Waiting for the agent to write the plan file…"}),c.launchError&&n.jsxs("p",{className:"mt-2 text-xs",style:{color:"var(--accent-error, #ff6b6b)"},"data-testid":"prototype-launch-error",children:["Launch failed: ",c.launchError]})]})]})}function Rp({open:e,onToggle:t}){return n.jsx("button",{type:"button",onClick:t,className:"mt-3 inline-flex items-center gap-2 rounded border border-[var(--accent-active)] px-3 py-1.5 text-xs font-medium uppercase tracking-wide text-[var(--accent-active)] hover:bg-[var(--accent-active)] hover:text-black transition-colors cursor-pointer","data-testid":"plan-next-change",children:e?"Close Planner":"Plan Next Change"})}function Tp({onClose:e}){return n.jsx(rn,{slashCommand:"/codeyam-plan",height:360,onClose:e})}function Pp({providerLabel:e,chatOpen:t,onChatToggle:r,onChatClose:s}){return n.jsxs("div",{"data-testid":"describe-pane",children:[n.jsx(Rp,{open:t,onToggle:r}),!t&&n.jsx(Fa,{providerLabel:e,kind:"describe"}),t&&n.jsx(Tp,{onClose:s})]})}function Dp(e){const[t,r]=i.useState(null),[s,a]=i.useState(!0),[o,l]=i.useState(null);return i.useEffect(()=>{let c=!1;return(async()=>{a(!0),l(null);try{const d=new Date(new Date(e).getTime()-1).toISOString(),u=await fetch(`/api/journal?since=${encodeURIComponent(d)}`);if(!u.ok)throw new Error(`HTTP ${u.status}`);const p=((await u.json()).entries??[]).find(m=>m.timestamp===e)??null;c||r(p)}catch(d){c||(r(null),l(d instanceof Error?d.message:"Failed to load journal entry"))}finally{c||a(!1)}})(),()=>{c=!0}},[e]),{entry:t,loading:s,error:o}}function Ap({journalTimestamp:e}){const{entry:t,loading:r,error:s}=Dp(e);return r?n.jsx("p",{className:"text-sm text-[var(--text-muted)]",children:"Loading journal entry…"}):s?n.jsxs("p",{className:"text-sm text-[var(--accent-red)]",children:["Failed to load journal entry: ",s]}):t?n.jsx(Ys,{entry:t}):n.jsx("p",{className:"text-sm text-[var(--text-dim)]",children:"No journal entry found for this plan yet."})}function Lp({plan:e,expanded:t,onToggle:r}){return n.jsxs("li",{className:"border border-[var(--border-subtle)] rounded-lg",children:[n.jsxs("button",{type:"button",onClick:r,className:"w-full text-left px-3 py-2 flex items-center justify-between gap-3 bg-transparent cursor-pointer","data-testid":"completed-plan-row",children:[n.jsx("span",{className:"flex-1 min-w-0 truncate text-sm text-[var(--text-primary)]",children:e.title}),n.jsx("span",{className:"text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded border border-[var(--border-subtle)] text-[var(--text-dim)]",children:e.mode}),n.jsx("span",{className:"text-[10px] text-[var(--text-dim)] whitespace-nowrap",children:ja(e.completedAt)}),n.jsx("span",{className:"text-xs text-[var(--text-dim)] whitespace-nowrap","data-testid":"completed-plan-row-chevron",children:t?"▼":"▶"})]}),t&&n.jsx("div",{className:"px-3 py-2 border-t border-[var(--border-subtle)]","data-testid":"completed-plan-row-body",children:n.jsx(Ap,{journalTimestamp:e.journalTimestamp})})]})}function Mp({plans:e,loading:t,error:r}){const[s,a]=i.useState(null),o=e.length;return n.jsxs("div",{className:"mt-6",children:[n.jsxs("h3",{className:"text-xs font-medium uppercase tracking-wide text-[var(--text-dim)]",children:["Completed Plans (",o,")"]}),n.jsx(Ip,{plans:e,loading:t,error:r,expandedSlug:s,onToggle:l=>a(c=>c===l?null:l)})]})}function Ip({plans:e,loading:t,error:r,expandedSlug:s,onToggle:a}){return t?n.jsx("p",{className:"mt-3 text-sm text-[var(--text-muted)]",children:"Loading completed plans…"}):r?n.jsxs("p",{className:"mt-3 text-sm text-[var(--accent-red)]",children:["Failed to load completed plans: ",r]}):e.length===0?n.jsx("p",{className:"mt-3 text-sm text-[var(--text-dim)]",children:"Plans you complete will appear here."}):n.jsx("ul",{className:"mt-3 flex flex-col gap-2","data-testid":"recent-plans-list",children:e.map(o=>n.jsx(Lp,{plan:o,expanded:s===o.slug,onToggle:()=>a(o.slug)},o.slug))})}function Fp({chatOpen:e,onChatOpenChange:t,isActive:r=!0,isAgentBuilding:s=!1,launchingSlug:a,launchError:o,onLaunchPlan:l,initialSubTab:c="describe"}={}){const{plans:d,loading:u,error:f,refetch:p}=br(),{plans:m,loading:h,error:j}=Da(),{config:b}=Ze(),g=dt(b==null?void 0:b.provider),w=l!==void 0,v=Nr(),x=w?a??null:v.launchingSlug,y=w?o??null:v.error,[N,C]=i.useState(!1),[S,k]=i.useState(!1),[R,E]=i.useState(null),[T,M]=i.useState(c),F=e!==void 0,I=F?e:N,z=B=>{F||C(B),t==null||t(B)},J=()=>{z(!1),p()},D=()=>{const B=!I;B&&He(),z(B)};i.useEffect(()=>{if(!(!r||!I))return He()},[r,I]);const{annotationsBySlug:O,dependenciesBySlug:H}=La(d),$=B=>{var L;const Q=Aa(H[B]??[]);if(Q.length>0){E(Q);return}const U=((L=d.find(A=>A.slug===B))==null?void 0:L.title)??B;if(l){l(B,U);return}v.launchPlan(B,U)},{reorderPlans:K}=Ia(p);return n.jsxs(ir,{testId:"plan-tab",children:[n.jsx(xp,{subTab:T}),n.jsx(bp,{active:T,onChange:M}),T==="describe"&&n.jsx(Pp,{providerLabel:g,chatOpen:I,onChatToggle:D,onChatClose:J}),T==="prototype"&&n.jsx(Ep,{isAgentBuilding:s,onLaunched:()=>M("describe")}),n.jsx(gr,{plans:d,loading:u,error:f,onRun:$,launchingSlug:x,launchError:y,blocked:s,onBlockedClick:()=>k(!0),onReorder:K,depAnnotationsBySlug:O,dependenciesBySlug:H}),n.jsx(Mp,{plans:m,loading:h,error:j}),S&&n.jsx(hp,{onClose:()=>k(!1)}),R&&!S&&n.jsx(gp,{deps:R,onClose:()=>E(null)})]})}function Op({activeTab:e,planActivated:t,chatOpen:r,onChatOpenChange:s,isAgentBuilding:a=!1,launchingPlanSlug:o,planLaunchError:l,onLaunchPlan:c}){return t?n.jsx("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:e==="plan"?"visible":"hidden",pointerEvents:e==="plan"?"auto":"none"},children:n.jsx(Fp,{chatOpen:r,onChatOpenChange:s,isActive:e==="plan",isAgentBuilding:a,launchingSlug:o,launchError:l,onLaunchPlan:c})}):null}function Bp({visible:e,children:t}){return n.jsx("div",{className:"absolute inset-0 flex flex-col overflow-auto",style:{visibility:e?"visible":"hidden"},children:t})}function $p({activeTab:e,children:t}){const r=["home","build","plan","history","settings"];return n.jsx("div",{className:"flex-1 min-h-0 overflow-hidden relative",children:r.map(s=>n.jsx(Bp,{visible:e===s,children:t[s]},s))})}function _p({title:e}){return n.jsx("div",{className:"flex h-full items-center justify-center",style:{color:"var(--text-dim)"},children:n.jsxs("p",{className:"text-sm",children:[e," — coming soon"]})})}function zp({activeTab:e,appTabContent:t,leftWidth:r}){const s=e!=="build"&&e!=="plan",[a,o]=i.useState(!1);return i.useEffect(()=>{e==="history"&&o(!0)},[e]),n.jsx("div",{className:"absolute inset-0 flex flex-col",style:{visibility:s?"visible":"hidden",pointerEvents:s?"auto":"none"},children:n.jsx($p,{activeTab:e,width:r,children:{home:t,build:null,plan:null,history:a?n.jsx(Bl,{}):null,settings:n.jsx(_p,{title:"Settings"})}})})}function Hp({plans:e,onPickPlan:t,launchingSlug:r,planError:s,onSubmitPrompt:a,submittingPrompt:o,promptError:l,onCancel:c,pendingPlansLoading:d,pendingPlansError:u,isAgentBuilding:f}){const[p,m]=i.useState(""),{annotationsBySlug:h,dependenciesBySlug:j}=La(e),b=i.useCallback(y=>{y.key==="Escape"&&(y.preventDefault(),c())},[c]);i.useEffect(()=>(window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)),[b]);const g=p.trim(),w=g.length===0||o||r!==null,v=()=>{w||a(g)},x=y=>{(y.metaKey||y.ctrlKey)&&y.key==="Enter"&&(y.preventDefault(),v())};return n.jsx("div",{className:"absolute inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},"data-testid":"build-launch-modal",children:n.jsxs("div",{className:"max-w-lg w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] mb-2",children:"What do you want to build?"}),n.jsx("p",{className:"text-sm text-[var(--text-muted)] mb-4",children:"Pick a queued plan to run, or describe a new build and kick it off directly."}),e.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"max-h-48 overflow-y-auto mb-3","data-testid":"build-launch-modal-plan-list",children:n.jsx(gr,{plans:e,loading:d,error:u,onRun:y=>{var C;const N=((C=e.find(S=>S.slug===y))==null?void 0:C.title)??y;t(y,N)},launchingSlug:r,launchError:s,blocked:f,depAnnotationsBySlug:h,dependenciesBySlug:j})}),n.jsxs("div",{className:"flex items-center gap-3 my-4 text-xs text-[var(--text-dim)]","aria-hidden":"true",children:[n.jsx("span",{className:"flex-1 h-px bg-[var(--border-subtle)]"}),n.jsx("span",{children:"or"}),n.jsx("span",{className:"flex-1 h-px bg-[var(--border-subtle)]"})]})]}),n.jsx("p",{className:"text-xs uppercase tracking-wide text-[var(--text-dim)] mb-2",children:"Describe what you want to build"}),n.jsx("textarea",{value:p,onChange:y=>m(y.target.value),onKeyDown:x,rows:4,disabled:o||r!==null,placeholder:"e.g. Add a dark-mode toggle to the settings page",className:"w-full px-3 py-2 rounded-md text-sm resize-y disabled:opacity-50 disabled:cursor-not-allowed",style:{background:"var(--bg-deep, #0e0e0e)",color:"var(--text-primary)",border:"1px solid var(--border-default)"},"data-testid":"build-launch-modal-textarea"}),l&&n.jsx("p",{className:"mt-2 text-xs",style:{color:"var(--text-danger, #ff6b6b)"},"data-testid":"build-launch-modal-prompt-error",children:l}),n.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:c,className:"px-4 py-2 rounded-md text-sm font-medium transition cursor-pointer",style:{background:"transparent",color:"var(--text-secondary)",border:"1px solid var(--border-default)"},"data-testid":"build-launch-modal-cancel",children:"Cancel"}),n.jsx("button",{type:"button",onClick:v,disabled:w,className:"px-4 py-2 rounded-md text-sm font-medium transition cursor-pointer disabled:cursor-not-allowed disabled:opacity-50",style:{background:"var(--accent-active, #4a9eff)",color:"var(--text-on-accent, #fff)",border:"1px solid transparent"},"data-testid":"build-launch-modal-submit",children:o?"Starting…":"Start build"})]}),n.jsx("p",{className:"mt-3 text-center text-xs text-[var(--text-dim)]",children:"Cmd/Ctrl+Enter submits · Escape cancels"})]})})}function Wp({onCreateNewPlan:e,onViewPlans:t}){return n.jsxs("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},"data-testid":"plan-complete-dialog",children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] mb-2",children:"Plan Saved!"}),n.jsx("p",{className:"text-sm text-[var(--text-muted)] mb-6",children:"Your plan has been committed. Start another plan, or head back to see the list."}),n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsx("button",{onClick:e,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition cursor-pointer",style:{background:"var(--accent-active)",color:"var(--bg-deep)"},type:"button",children:"Create New Plan"}),n.jsx("button",{onClick:t,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition cursor-pointer",style:{background:"transparent",color:"var(--text-secondary)",border:"1px solid var(--border-default)"},type:"button",children:"View Plans"})]})]})}function Vp({onCreateNewPlan:e,onViewPlans:t}){return n.jsx("div",{className:"absolute inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},children:n.jsx(Wp,{onCreateNewPlan:e,onViewPlans:t})})}function Up(e){return!e||!(e instanceof Element)?!1:!!e.closest("[data-terminal-emulator], .xterm")}function Kp(e){return!e||!(e instanceof Element)?!1:!!e.closest("[data-post-push-modal]")}function Gp({onStartNextFeature:e,onContinueInSession:t,onSendTranscript:r,onSelectPlan:s,pendingPlanCount:a=0}){const o=a>0&&s,l={background:"var(--accent-active)",color:"var(--bg-deep)"},c={background:"transparent",color:"var(--text-secondary)",border:"1px solid var(--border-default)"};return n.jsxs("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] mb-2",children:"Feature Complete!"}),n.jsx("p",{className:"text-sm text-[var(--text-muted)] mb-6",children:"Your changes have been committed and pushed. You can start a new feature with a fresh context, or continue working in the current session."}),n.jsxs("div",{className:"flex flex-col gap-3",children:[o&&n.jsx("button",{onClick:s,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition cursor-pointer",style:l,type:"button",children:"Select A Plan"}),n.jsx("button",{onClick:e,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition cursor-pointer",style:o?c:l,type:"button",children:"Start Next Feature"}),n.jsx("button",{onClick:t,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition cursor-pointer",style:c,type:"button",children:"Continue in Current Session"}),r&&n.jsx("button",{onClick:r,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition cursor-pointer",style:{background:"transparent",color:"var(--text-dim)",border:"1px solid var(--border-default)"},type:"button",children:"Send Session Feedback"})]}),n.jsx("p",{className:"mt-4 text-center text-xs text-[var(--text-dim)]",children:o?"Press Enter to pick a queued plan":"Press Enter to start a new feature with a fresh context"})]})}function Yp({onStartNextFeature:e,onContinueInSession:t,onSendTranscript:r,onSelectPlan:s,pendingPlanCount:a=0}){const o=i.useCallback(l=>{if(l.key!=="Enter"||Up(l.target))return;const c=l.target===document.body||l.target===document.documentElement||l.target===document;!Kp(l.target)&&!c||(l.preventDefault(),a>0&&s?s():e())},[s,e,a]);return i.useEffect(()=>(window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)),[o]),n.jsx("div",{className:"absolute inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},"data-post-push-modal":!0,children:n.jsx(Gp,{onStartNextFeature:e,onContinueInSession:t,onSendTranscript:r,onSelectPlan:s,pendingPlanCount:a})})}function Jp({plans:e,onSelect:t,onCancel:r,launchingSlug:s,error:a}){const[o,l]=i.useState(null),c=i.useMemo(()=>{const f={};for(const p of e)f[p.slug]=p;return f},[e]),d=i.useCallback(f=>{const p=c[f];p&&t(p.slug,p.title)},[t,c]),u=i.useCallback(f=>{if(f.key==="Escape"){f.preventDefault(),r();return}f.key==="Enter"&&e.length>0&&!s&&(f.preventDefault(),t(e[0].slug,e[0].title))},[s,r,t,e]);return i.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]),e.length===0?null:n.jsx("div",{className:"absolute inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},"data-testid":"select-plan-modal",children:n.jsxs("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] mb-2",children:"Select A Plan"}),n.jsx("p",{className:"text-sm text-[var(--text-muted)] mb-4",children:"Pick a queued plan to run next. Its body primes the editor workflow in a fresh session."}),n.jsx("ul",{className:"flex flex-col gap-2 max-h-[50vh] overflow-y-auto mb-2",children:e.map((f,p)=>n.jsx(Sa,{plan:f,position:p+1,expanded:o===f.slug,onToggle:()=>l(m=>m===f.slug?null:f.slug),onRun:d,launching:s===f.slug,expandedBodyVariant:"view"},f.slug))}),a&&n.jsx("p",{className:"text-xs mb-3",style:{color:"var(--text-danger, #ff6b6b)"},"data-testid":"select-plan-error",children:a}),n.jsx("button",{type:"button",onClick:r,className:"w-full px-4 py-2 rounded-md text-sm font-medium transition cursor-pointer",style:{background:"transparent",color:"var(--text-secondary)",border:"1px solid var(--border-default)"},children:"Cancel"}),n.jsx("p",{className:"mt-3 text-center text-xs text-[var(--text-dim)]",children:"Press Enter to launch the first plan, Escape to cancel"})]})})}function Xp({activeTab:e,onSendTranscript:t,appTabContent:r,awaitingPlanLaunchChoice:s,buildActivated:a,planActivated:o,buildIdle:l=!1,isAgentBuilding:c=!1,bannerVisible:d=!1,onDismissIdleBanner:u,hideResultsCommandKey:f,leftWidth:p,navigateToTab:m,onAgentActive:h,onAgentIdle:j,onUserInput:b,notifSettings:g,onSettingsChange:w,provider:v,onContinueInSession:x,onRestorePreview:y,onResultsScenarioSelect:N,onSessionDetected:C,onStartNextFeature:S,showPostPushModal:k,showResultsCommandKey:R,planChatOpen:E,onPlanChatOpenChange:T,showPlanCompleteModal:M,onCreateNewPlan:F,onViewPlans:I,pendingPlans:z,onSelectPlan:J,selectPlanOpen:D,onPickPlan:O,onCancelSelectPlan:H,launchingPlanSlug:$,planLaunchError:K,showBuildLaunchModal:B=!1,onSubmitBuildPrompt:Q,submittingBuildPrompt:U=!1,buildPromptError:L=null,onCancelBuildLaunchModal:A,pendingPlansLoading:X,pendingPlansError:G,onReorderPlans:ee}){return n.jsxs("div",{className:"shrink-0 flex flex-col overflow-hidden",style:{width:p,background:"var(--bg-deep)"},children:[n.jsx(Gf,{activeTab:e,onTabChange:m,onSendTranscript:t,buildIdle:l,isAgentBuilding:c,bannerVisible:d,onDismissIdleBanner:u}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden relative",children:[n.jsx(op,{awaitingPlanLaunchChoice:s,buildActivated:a,activeTab:e,onSessionDetected:C,onSelectScenario:N,showResultsCommandKey:R,hideResultsCommandKey:f,onAgentIdle:j,onAgentActive:h,onUserInput:b,notifSettings:g,onSettingsChange:w,provider:v,onRestorePreview:y,pendingPlans:z,pendingPlansLoading:X,pendingPlansError:G,onLaunchPlan:O,launchingSlug:$,launchError:K,onReorderPlans:ee,isAgentBuilding:c}),n.jsx(Op,{activeTab:e,planActivated:o,chatOpen:E,onChatOpenChange:T,isAgentBuilding:c,launchingPlanSlug:$,planLaunchError:K,onLaunchPlan:O}),n.jsx(zp,{activeTab:e,appTabContent:r,leftWidth:p}),k&&e==="build"&&!D?n.jsx(Yp,{onStartNextFeature:S,onContinueInSession:x,onSendTranscript:t,onSelectPlan:J,pendingPlanCount:z.length}):null,D&&e==="build"?n.jsx(Jp,{plans:z,onSelect:O,onCancel:H,launchingSlug:$,error:K}):null,B&&e==="build"&&!k&&Q&&A?n.jsx(Hp,{plans:z,onPickPlan:O,launchingSlug:$,planError:K,onSubmitPrompt:Q,submittingPrompt:U,promptError:L,onCancel:A,pendingPlansLoading:X,pendingPlansError:G,isAgentBuilding:c}):null,M&&e==="plan"?n.jsx(Vp,{onCreateNewPlan:F,onViewPlans:I}):null]})]})}const us=5173;function Cr(e){if(e.startsWith("http"))try{return new URL(e).pathname}catch{return e}return e.split("?")[0]??e}function Oa(e){return e?parseInt(e.port||(e.protocol==="https:"?"443":"80"),10):0}function Ba(e,{appPort:t,currentPort:r,previewOrigin:s}){return e.startsWith("http")?e:s?`${s}${e}`:r===t?e:`http://localhost:${t}${e}`}function $a(e,t,r,s,a){if(r&&r.length>0)return Ba(r,{appPort:s,currentPort:t,previewOrigin:a});const o=`/scenario/${e}`;return a?`${a}${o}`:t===us?o:`http://localhost:${us}${o}`}async function fs(e,t=null){try{const r={pid:e};t&&(r.url=t),await fetch("/api/editor-iframe-loaded",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})}catch{}}async function qp(e){try{await fetch("/api/editor-iframe-error",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({error:e})})}catch{}}async function Qp(e){try{await fetch("/api/editor-iframe-banner",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({seedError:e})})}catch{}}function Zp(e,t,r,s,a){const o=e-a*2,l=t-a*2;return o<=0||l<=0?1:Math.min(1,o/r,l/s)}const em=32;function tm({currentHeight:e,currentWidth:t,isFilled:r}){const[s,a]=i.useState(null),o=i.useRef(null),l=i.useRef(null),c=i.useCallback(f=>{const p=f.getBoundingClientRect();a({width:p.width,height:p.height})},[]),d=i.useCallback(f=>{if(o.current&&(o.current.disconnect(),o.current=null),l.current=f,!f){a(null);return}c(f);const p=new ResizeObserver(()=>{const m=l.current;m&&c(m)});p.observe(f),o.current=p},[c]),u=r||!s?1:Zp(s.width,s.height,t,e,em);return{containerRef:d,containerSize:s,scale:u}}function nm(e,t,r){switch(e){case 1:case 2:return"Setting up...";case 3:return`Building — ${t} files modified, ${r} tests modified`;case 4:return"Verifying — running tests...";case 5:return"Ready for review";case 6:return"Refactoring...";case 7:case 8:return"Finalizing...";case 9:return"Ready for approval";case 10:return"Complete";default:return""}}async function ps(){const e=Date.now();try{const t=await fetch("/api/editor-session-summary"),r=Date.now()-e;return t.ok?{ok:!0,data:await t.json(),statusCode:t.status,durationMs:r,error:null}:{ok:!1,data:null,statusCode:t.status,durationMs:r,error:`HTTP ${t.status}`}}catch(t){return{ok:!1,data:null,statusCode:null,durationMs:Date.now()-e,error:t instanceof Error?t.message:String(t)}}}const rm=50,sm={status:"loading",lastSuccessAt:null,lastErrorAt:null,lastErrorMessage:null,fetchCount:0,errorCount:0};function am(e,t,r){return{status:t.ok?"connected":"disconnected",lastSuccessAt:t.ok?r:e.lastSuccessAt,lastErrorAt:t.ok?e.lastErrorAt:r,lastErrorMessage:t.ok?e.lastErrorMessage:t.error,fetchCount:e.fetchCount+1,errorCount:e.errorCount+(t.ok?0:1)}}function om(e,t){return{timestamp:t,success:e.ok,statusCode:e.statusCode,durationMs:e.durationMs,error:e.error}}function im(e,t){return[t,...e].slice(0,rm)}function lm(){const[e,t]=i.useState(sm),[r,s]=i.useState([]),a=i.useCallback(l=>{const c=Date.now();s(d=>im(d,om(l,c))),t(d=>am(d,l,c))},[]),o=i.useCallback(()=>{t(l=>({...l,status:"polling"}))},[]);return{connectionState:e,fetchLog:r,recordFetch:a,markPolling:o}}function cm(){const[e,t]=i.useState(()=>Date.now());return i.useEffect(()=>{const r=setInterval(()=>t(Date.now()),1e3);return()=>clearInterval(r)},[]),e}function dm(e){switch(e.status){case"connected":return{dotClass:"bg-green-500",label:"Connected",labelClass:"text-green-400"};case"polling":return{dotClass:"bg-yellow-400 animate-pulse",label:"Polling...",labelClass:"text-yellow-400"};case"disconnected":return{dotClass:"bg-red-500",label:"Disconnected",labelClass:"text-red-400"};case"loading":default:return{dotClass:"bg-[var(--text-muted)]",label:"Connecting...",labelClass:"text-[var(--text-muted)]"}}}function um({state:e}){const t=cm(),{dotClass:r,label:s,labelClass:a}=dm(e);return n.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[11px] font-medium","data-testid":"connection-status-badge",children:[n.jsx("span",{className:`w-2 h-2 rounded-full ${r}`,"data-testid":"connection-status-dot"}),n.jsx("span",{className:a,"data-testid":"connection-status-label",children:s}),e.lastSuccessAt!=null&&n.jsxs("span",{className:"text-[var(--text-muted)]","data-testid":"connection-status-updated",children:["Updated ",Ho(e.lastSuccessAt,t)]})]})}function fm({entry:e}){return n.jsxs("div",{className:"flex items-center gap-2","data-testid":"connection-log-entry",children:[n.jsx("span",{className:"text-[var(--text-muted)] w-20 shrink-0","data-testid":"connection-log-time",children:new Date(e.timestamp).toLocaleTimeString()}),e.success?n.jsx("span",{className:"text-green-600 w-4 shrink-0","data-testid":"connection-log-result",children:"✓"}):n.jsx("span",{className:"text-red-500 w-4 shrink-0","data-testid":"connection-log-result",children:"✗"}),n.jsx("span",{className:`w-12 shrink-0 ${e.success?"text-[var(--text-secondary)]":"text-red-500"}`,"data-testid":"connection-log-status",children:e.statusCode!=null?e.statusCode:"—"}),n.jsx("span",{className:"text-[var(--text-muted)] w-14 shrink-0","data-testid":"connection-log-duration",children:$n(e.durationMs)}),e.error&&n.jsx("span",{className:"text-red-500 truncate","data-testid":"connection-log-error",children:e.error})]})}function pm({state:e,entries:t}){const[r,s]=i.useState(!0);return n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg overflow-hidden","data-testid":"connection-log-section",children:[n.jsxs("div",{className:"px-4 py-2 border-b border-[var(--border-subtle)] bg-[var(--bg-input)] cursor-pointer select-none flex items-center justify-between",onClick:()=>s(!r),"data-testid":"connection-log-header",children:[n.jsxs("h2",{className:"text-sm font-semibold text-[var(--text-primary)] m-0",children:["Connection Log (",e.fetchCount," fetches, ",e.errorCount," errors)"]}),n.jsx("span",{className:"text-[var(--text-muted)] text-xs",children:r?"▶":"▼"})]}),!r&&n.jsx("div",{className:"p-3","data-testid":"connection-log-body",children:t.length===0?n.jsx("div",{className:"text-xs text-[var(--text-muted)] text-center py-2",children:"No fetch attempts yet"}):n.jsx("div",{className:"space-y-1 font-mono text-[11px]",children:t.map(a=>n.jsx(fm,{entry:a},a.timestamp))})})]})}function mm({totalLines:e}){return n.jsxs("div",{className:"text-xs text-[var(--text-secondary)] bg-[var(--bg-input)] border border-[var(--border-subtle)] rounded-md p-3","data-testid":"functions-coverage-empty-state",children:["Your runner reported coverage on ",e," instrumented lines, but no glossary entries are defined for functions. Add entries with"," ",n.jsx("code",{className:"font-mono text-[11px] bg-[var(--bg-card)] px-1 py-0.5 border border-[var(--border-default)] rounded",children:"codeyam-editor editor glossary-add"})," ","to see per-function coverage here."]})}function xm({functions:e,aggregate:t,projectWide:r=null}){const s=e.length===0&&r!==null&&r.totalLines>0;return e.length===0&&!s?null:n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg p-4",children:[n.jsx(vr,{title:"Function Coverage",aggregate:t,aggregateTestId:"functions-coverage-aggregate"}),s&&n.jsx(mm,{totalLines:r.totalLines}),e.length>0&&n.jsx("ul",{className:"divide-y divide-gray-100",children:e.map(a=>n.jsxs("li",{className:"flex items-center gap-3 py-2",children:[n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-[var(--text-primary)] truncate",children:a.name}),n.jsx("div",{className:"text-xs text-[var(--text-muted)] truncate",children:a.filePath})]}),a.coverage&&a.coverage.totalLines>0?n.jsx(Mt,{coverage:a.coverage}):n.jsx("span",{className:"text-xs text-[var(--text-muted)] min-w-[140px] text-right",children:"no coverage"})]},`${a.filePath}::${a.name}`))})]})}function hm({projectWide:e,orphanedFiles:t}){return!e||e.totalLines===0?null:n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg p-4","data-testid":"project-wide-coverage-rollup",children:[n.jsx(vr,{title:"Project Coverage",aggregate:e,aggregateTestId:"project-wide-coverage-percent"}),t.length>0&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"text-xs text-[var(--text-muted)] mb-2",children:[t.length," file",t.length===1?"":"s"," with file-level coverage (no glossary entry)"]}),n.jsx("ul",{className:"divide-y divide-gray-100",children:t.map(r=>n.jsx(Ta,{file:r},r.filePath))})]})]})}function gm(){return n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg p-4","data-testid":"coverage-thresholds-empty",children:[n.jsx("h2",{className:"text-sm font-semibold text-[var(--text-primary)] m-0 mb-2",children:"Coverage Thresholds"}),n.jsxs("p",{className:"text-xs text-[var(--text-muted)] m-0",children:["No threshold report yet — run"," ",n.jsx("code",{className:"text-[11px] bg-[var(--bg-input)] px-1 rounded",children:"codeyam-editor editor coverage-check"}),"."]})]})}function vm({global:e,failureCount:t}){const r=t===0;return n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsx("h2",{className:"text-sm font-semibold text-[var(--text-primary)] m-0",children:"Coverage Thresholds"}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(sr,{coverage:e}),n.jsx("span",{className:r?"text-xs font-semibold text-green-700":"text-xs font-semibold text-red-700","data-testid":"coverage-thresholds-status",children:r?"PASS":`FAIL (${t})`})]})]})}function bm(){return n.jsxs("p",{className:"text-[11px] text-[var(--text-muted)] mb-3 m-0",children:["Using built-in defaults (global ≥ 70%, per-file ≥ 50%). Add a",n.jsx("code",{className:"mx-1 bg-[var(--bg-input)] px-1 rounded",children:"coverageThresholds"}),"block to editor.json to customize."]})}function ym({ranRunners:e}){return n.jsxs("p",{className:"text-xs text-[var(--text-secondary)] m-0",children:["All configured thresholds passed across"," ",e.join(", ")||"no runners","."]})}function Vt(e){return e.kind==="global"?`${e.actual.toFixed(1)}% < required ${e.required.toFixed(1)}%`:e.kind==="perFile"?`${e.path}: ${e.actual.toFixed(1)}% < ${e.required.toFixed(1)}%`:e.kind==="perGlossaryEntry"?`${e.name}: ${e.actual.toFixed(1)}% < ${e.required.toFixed(1)}%`:`dropped ${e.actualDrop.toFixed(1)}% (max allowed ${e.maxAllowed.toFixed(1)}%)`}function wm(e){const t={global:[],perFile:[],perGlossaryEntry:[],regression:[]};for(const r of e)r.kind==="global"?t.global.push(r):r.kind==="perFile"?t.perFile.push(r):r.kind==="perGlossaryEntry"?t.perGlossaryEntry.push(r):t.regression.push(r);return t}function Ut({title:e,items:t}){return n.jsxs("div",{children:[n.jsx("div",{className:"text-[11px] uppercase tracking-wide text-gray-500 mb-1",children:e}),n.jsx("ul",{className:"text-xs text-red-700 space-y-1 m-0 pl-4 list-disc",children:t.map(r=>n.jsx("li",{children:r},r))})]})}function jm({failures:e}){const t=wm(e);return n.jsxs("div",{className:"space-y-3",children:[t.global.length>0&&n.jsx(Ut,{title:"Global",items:t.global.map(Vt)}),t.perFile.length>0&&n.jsx(Ut,{title:"Per-file",items:t.perFile.map(Vt)}),t.perGlossaryEntry.length>0&&n.jsx(Ut,{title:"Per-glossary-entry",items:t.perGlossaryEntry.map(Vt)}),t.regression.length>0&&n.jsx(Ut,{title:"Regression",items:t.regression.map(Vt)})]})}function Nm({report:e}){if(!e)return n.jsx(gm,{});const t=e.failures.length===0;return n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg p-4","data-testid":"coverage-thresholds-panel",children:[n.jsx(vm,{global:e.global,failureCount:e.failures.length}),e.usedDefaultThresholds&&n.jsx(bm,{}),t?n.jsx(ym,{ranRunners:e.ranRunners}):n.jsx(jm,{failures:e.failures})]})}const Cm=new Set([3,4,6]),Sm=5e3;function km(){const[e,t]=i.useState(null),[r,s]=i.useState(!0),{connectionState:a,fetchLog:o,recordFetch:l,markPolling:c}=lm(),d=i.useRef(null);if(i.useEffect(()=>{async function m(){const h=await ps();l(h),h.ok&&h.data&&t(h.data),s(!1)}return m(),()=>{d.current&&clearInterval(d.current)}},[l]),i.useEffect(()=>(d.current&&(clearInterval(d.current),d.current=null),e!=null&&e.step&&Cm.has(e.step)&&(d.current=setInterval(async()=>{c();const m=await ps();l(m),m.ok&&m.data&&t(m.data)},Sm)),()=>{d.current&&clearInterval(d.current)}),[e==null?void 0:e.step,l,c]),r)return n.jsx("div",{className:"min-h-screen bg-[var(--bg-deep)] flex items-center justify-center",children:n.jsx("div",{className:"animate-spin w-6 h-6 border-2 border-[var(--border-default)] border-t-[#005c75] rounded-full"})});if(!e)return n.jsx("div",{className:"min-h-screen bg-[var(--bg-deep)] flex items-center justify-center text-[var(--text-muted)] text-sm",children:"No session data available."});const u=e.step??0,f=e.functions.reduce((m,h)=>m+h.tests.length,0),p=nm(u,e.modifiedFiles.length,f);return n.jsx("div",{className:"min-h-screen bg-[var(--bg-deep)] p-6",children:n.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg p-4",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[n.jsx("span",{className:"text-xs px-2 py-0.5 bg-[#005c75] text-white rounded font-medium",children:"BACKEND"}),n.jsx(um,{state:a}),n.jsx("h1",{className:"text-lg font-semibold text-[var(--text-primary)] m-0",children:e.feature||"Working Session Results"})]}),e.userPrompt&&n.jsxs("div",{className:"mt-3 bg-[var(--bg-input)] border border-[var(--border-subtle)] rounded-md p-3","data-testid":"user-prompt-section",children:[n.jsx("div",{className:"text-xs font-semibold text-[var(--text-muted)] uppercase tracking-wide mb-1",children:"Prompt"}),n.jsx(Vs,{children:e.userPrompt})]})]}),n.jsx(Cl,{currentStep:u}),n.jsx(Sl,{stats:e.testRunnerStats}),n.jsx(Pa,{warnings:e.coverageWarnings??[]}),p&&n.jsx("div",{className:"text-sm text-[var(--text-secondary)] text-center",children:p}),e.narrative&&n.jsx(kl,{narrative:e.narrative}),e.narrative?n.jsx(El,{narrative:e.narrative}):n.jsx(Pl,{step:u,fileCount:e.modifiedFiles.length,testCount:f}),n.jsx(hm,{projectWide:e.projectWideCoverage??null,orphanedFiles:e.orphanedFiles??[]}),n.jsx(xm,{functions:e.functions,aggregate:e.coverage??null,projectWide:e.projectWideCoverage??null}),n.jsx(Nm,{report:e.coverageThresholds??null}),e.modifiedFiles.length>0&&n.jsx(Al,{files:e.modifiedFiles,defaultCollapsed:e.narrative!==null}),n.jsx(pm,{state:a,entries:o})]})})}function Em(){return n.jsx("div",{className:"flex-1 flex flex-col min-w-0 overflow-auto",style:{background:"var(--bg-deep)"},children:n.jsx(km,{})})}function Rm({onClose:e}){const[t,r]=i.useState(""),s=i.useRef(null);return i.useEffect(()=>{var a;(a=s.current)==null||a.focus()},[]),i.useEffect(()=>{const a=o=>{o.key==="Escape"&&e()};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e]),n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:a=>{a.target===a.currentTarget&&e()},children:n.jsxs("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] mb-1",children:"Create New State"}),n.jsx("p",{className:"text-sm text-[var(--text-muted)] mb-4",children:"Describe the state you want Claude to build."}),n.jsx("textarea",{ref:s,value:t,onChange:a=>r(a.target.value),placeholder:"e.g. Empty inbox with a friendly empty-state illustration",rows:5,className:"w-full px-3 py-2 text-sm rounded mb-4 resize-none focus:outline-none",style:{background:"var(--bg-input)",border:"1px solid var(--border-default)",color:"var(--text-primary)"}}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 rounded-md text-sm transition cursor-pointer",style:{background:"transparent",color:"var(--text-secondary)",border:"1px solid var(--border-default)"},children:"Cancel"}),n.jsx("button",{type:"button",disabled:!0,title:"Coming soon",className:"px-4 py-2 rounded-md text-sm font-medium opacity-50 cursor-not-allowed",style:{background:"var(--accent-active)",color:"var(--bg-deep)"},children:"Send to Claude"})]})]})})}const Ln=1280,ms=1600;function Tm({mockup:e,displayNumber:t}){const r=i.useRef(null),[s,a]=i.useState(0);i.useEffect(()=>{const l=r.current;if(!l)return;const c=()=>{const u=l.clientWidth;u>0&&a(u/Ln)};if(c(),typeof ResizeObserver>"u")return;const d=new ResizeObserver(c);return d.observe(l),()=>d.disconnect()},[]);const o=e.name.replace(/^\d{1,2}-/,"").replace(/-/g," ");return n.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",border:"1px solid var(--border-default)",borderRadius:12,overflow:"hidden",background:"var(--bg-surface)"},children:[n.jsx("div",{ref:r,style:{position:"relative",width:"100%",aspectRatio:`${Ln} / ${ms}`,overflow:"hidden",background:"white"},children:n.jsx("iframe",{src:e.url,title:e.name,sandbox:"",style:{width:Ln,height:ms,border:"none",background:"white",transform:s>0?`scale(${s})`:"scale(0)",transformOrigin:"top left",pointerEvents:"none",position:"absolute",top:0,left:0}})}),n.jsxs("div",{style:{padding:"var(--spacing-sm, 8px) var(--spacing-md, 12px)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"var(--spacing-sm, 8px)"},children:[n.jsxs("span",{style:{display:"inline-flex",alignItems:"baseline",gap:6,color:"var(--text-primary)",fontSize:"var(--text-sm, 14px)",minWidth:0},children:[n.jsxs("span",{style:{fontWeight:700},children:[t,"."]}),n.jsx("span",{style:{textTransform:"capitalize",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o})]}),n.jsx("button",{type:"button",onClick:()=>window.open(e.url,"_blank","noopener,noreferrer"),style:{padding:"var(--spacing-xs, 4px) var(--spacing-md, 12px)",background:"var(--bg-elevated)",color:"var(--text-primary)",border:"1px solid var(--border-default)",borderRadius:6,fontSize:"var(--text-xs, 12px)",cursor:"pointer",flexShrink:0},children:"Open full"})]})]})}function Pm({displayNumber:e}){return n.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",border:"1px dashed var(--border-default)",borderRadius:12,overflow:"hidden",background:"var(--bg-surface)"},children:[n.jsx("style",{children:`
17
+ @keyframes mockup-placeholder-pulse {
18
+ 0%, 100% { opacity: 0.55; }
19
+ 50% { opacity: 1; }
20
+ }
21
+ `}),n.jsxs("div",{style:{position:"relative",width:"100%",aspectRatio:"1280 / 1600",overflow:"hidden",background:"linear-gradient(135deg, var(--bg-elevated) 0%, var(--bg-surface) 100%)",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:16,color:"var(--text-secondary)",animation:"mockup-placeholder-pulse 1.8s ease-in-out infinite"},children:[n.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("path",{d:"M12 20h9"}),n.jsx("path",{d:"M16.5 3.5a2.121 2.121 0 1 1 3 3L7 19l-4 1 1-4Z"})]}),n.jsx("div",{style:{fontSize:"var(--text-sm, 14px)",fontWeight:500,textAlign:"center",padding:"0 16px"},children:"The AI is designing this mockup…"})]}),n.jsx("div",{style:{padding:"var(--spacing-sm, 8px) var(--spacing-md, 12px)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"var(--spacing-sm, 8px)"},children:n.jsxs("span",{style:{display:"inline-flex",alignItems:"baseline",gap:6,color:"var(--text-primary)",fontSize:"var(--text-sm, 14px)",minWidth:0},children:[n.jsxs("span",{style:{fontWeight:700},children:[e,"."]}),n.jsx("span",{style:{color:"var(--text-secondary)",fontStyle:"italic"},children:"Generating…"})]})})]})}function Dm(){const[e,t]=i.useState(null),[r,s]=i.useState(null),[a,o]=i.useState(null),l=i.useRef(!0),c=i.useCallback(async()=>{try{const[p,m]=await Promise.all([fetch("/api/editor-mockups"),fetch("/api/editor-mockups-target")]),h=await p.json(),j=await m.json();l.current&&(t(h),s(j.count))}catch(p){l.current&&o(p instanceof Error?p.message:String(p))}},[]);if(i.useEffect(()=>{l.current=!0,c();const p=window.setInterval(c,4e3);return()=>{l.current=!1,window.clearInterval(p)}},[c]),!e)return n.jsx("div",{style:{padding:"var(--spacing-lg, 16px)"},children:n.jsx("div",{style:{color:"var(--text-secondary)"},children:"Loading design mockups…"})});const d=e.reduce((p,m)=>{const h=/^(\d{1,2})-/.exec(m.filename);return h?Math.max(p,parseInt(h[1],10)):p},0),u=Math.max(r??0,d);if(u===0)return n.jsxs("div",{style:{padding:"var(--spacing-lg, 16px)"},children:[n.jsx("h3",{style:{margin:0,color:"var(--text-primary)"},children:"Design exploration"}),n.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"var(--text-sm, 14px)",lineHeight:1.5,marginTop:"var(--spacing-sm, 8px)"},children:"Generating mockups — they'll appear here as the agent writes them."})]});const f=Array.from({length:u},(p,m)=>{const h=m+1,j=String(h).padStart(2,"0"),b=e.find(g=>g.filename.startsWith(`${j}-`))??null;return{number:h,mockup:b}});return n.jsxs("div",{className:"flex-1 flex flex-col min-w-0",style:{padding:"var(--spacing-lg, 16px)",gap:"var(--spacing-md, 12px)",overflow:"auto"},children:[n.jsxs("div",{children:[n.jsx("h3",{style:{margin:0,color:"var(--text-primary)"},children:"Pick a design direction"}),n.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"var(--text-sm, 14px)",marginTop:"var(--spacing-xs, 4px)"},children:`Refer to mockups by number in the chat — e.g. "Let's use 4" — to lock in a direction.`})]}),a&&n.jsx("div",{style:{padding:"var(--spacing-sm, 8px) var(--spacing-md, 12px)",borderRadius:8,background:"var(--bg-danger-soft, rgba(248,113,113,0.12))",color:"var(--accent-danger, #f87171)",fontSize:"var(--text-sm, 14px)"},children:a}),n.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",columnGap:"var(--spacing-lg, 16px)",rowGap:"var(--spacing-xl, 28px)"},children:f.map(p=>p.mockup?n.jsx(Tm,{mockup:p.mockup,displayNumber:p.number},`mockup-${p.number}`):n.jsx(Pm,{displayNumber:p.number},`placeholder-${p.number}`))})]})}function Xn(e){const t=e.replace(/\s*\[[^\]]*\]\s*$/,""),r=t.indexOf(" - ");return r===-1?{pageName:null,stateName:t}:{pageName:t.slice(0,r),stateName:t.slice(r+3)}}function _a(e){return tr(e)?e.componentName??Xn(e.name).pageName:Xn(e.name).pageName}function Sr(e){return Xn(e.name).stateName}function Am({isCollapsed:e,onToggle:t}){return n.jsx("button",{onClick:t,className:`p-1.5 rounded transition-colors cursor-pointer ${e?"text-white bg-[#666] hover:bg-[#777]":"text-gray-500 hover:text-gray-300"}`,title:e?"Show editor":"Hide editor",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:e?n.jsxs(n.Fragment,{children:[n.jsx("path",{d:"M13 17l5-5-5-5"}),n.jsx("path",{d:"M6 17l5-5-5-5"})]}):n.jsxs(n.Fragment,{children:[n.jsx("path",{d:"M11 17l-5-5 5-5"}),n.jsx("path",{d:"M18 17l-5-5 5-5"})]})})})}function xs({label:e,value:t,disabled:r,onCommit:s}){const[a,o]=i.useState(String(t));i.useEffect(()=>{o(String(t))},[t]);const l=()=>{const c=Number.parseInt(a,10);if(!Number.isFinite(c)||c<=0){o(String(t));return}c!==t&&s(c)};return n.jsxs("label",{className:`flex items-center gap-0.5 px-1 py-0.5 rounded bg-[#2A2929] text-xs ${r?"opacity-50 cursor-not-allowed":""}`,children:[n.jsx("span",{className:"text-[10px] font-semibold text-gray-500 select-none",children:e}),n.jsx("input",{type:"text",inputMode:"numeric",value:a,disabled:r,"aria-label":e==="H"?"Height":"Width",onChange:c=>o(c.target.value.replace(/[^0-9]/g,"")),onBlur:l,onKeyDown:c=>{c.key==="Enter"?(l(),c.target.blur()):c.key==="Escape"&&(o(String(t)),c.target.blur())},className:"w-8 bg-transparent text-gray-200 text-center text-[11px] font-mono focus:outline-none disabled:cursor-not-allowed [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})]})}function Lm({isFilled:e,onToggle:t}){return n.jsx("button",{onClick:t,className:`p-1.5 rounded transition-colors cursor-pointer ${e?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:e?"Exit fullscreen":"Fill page with preview",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:e?n.jsxs(n.Fragment,{children:[n.jsx("polyline",{points:"4 14 10 14 10 20"}),n.jsx("polyline",{points:"20 10 14 10 14 4"}),n.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),n.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):n.jsxs(n.Fragment,{children:[n.jsx("polyline",{points:"15 3 21 3 21 9"}),n.jsx("polyline",{points:"9 21 3 21 3 15"}),n.jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),n.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})})})}function Mm({previewUrl:e}){return n.jsx("button",{onClick:()=>{e&&window.open(e,"_blank")},className:"p-1.5 rounded text-gray-500 hover:text-gray-300 transition-colors cursor-pointer",title:"Open preview in new window",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),n.jsx("polyline",{points:"15 3 21 3 21 9"}),n.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})})}function za(e){const t=new Map;for(const r of e){const s=r.url??"Uncategorized",a=t.get(s)??[];a.push(r),t.set(s,a)}return Array.from(t.entries()).map(([r,s])=>({route:r,scenarios:s})).sort((r,s)=>r.route==="Uncategorized"?1:s.route==="Uncategorized"?-1:r.route.localeCompare(s.route))}function Im(e,t){const r=t.trim().toLowerCase();return r?e.filter(s=>{const a=(s.url??"").toLowerCase(),o=s.name.toLowerCase(),l=(s.componentName??"").toLowerCase();return a.includes(r)||o.includes(r)||l.includes(r)}):e}function Ha(e,t,r){i.useEffect(()=>{const s=o=>{const l=o.target;e.current&&e.current.contains(l)||r!=null&&r.current&&r.current.contains(l)||t()},a=o=>{o.key==="Escape"&&t()};return document.addEventListener("mousedown",s),document.addEventListener("keydown",a),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",a)}},[e,t,r])}function Fm({tab:e,hasQuery:t}){return t?n.jsx("p",{className:"text-xs text-gray-500 px-2 py-6 text-center",children:"No matches for your search."}):n.jsxs("p",{className:"text-xs text-gray-500 px-2 py-6 text-center",children:["No ",e==="pages"?"pages":"components"," yet."]})}function Om({scenario:e,active:t,onClick:r}){const s=e.screenshotPaths[0],a=Sr(e);return n.jsxs("button",{onClick:r,className:`w-32 text-left rounded border transition-colors cursor-pointer ${t?"border-[#007a99] bg-[#1a2a30]":"border-[#3d3d3d] bg-[#1a1a1a] hover:border-[#555]"}`,title:e.name,children:[n.jsx("div",{className:"aspect-[4/3] w-full overflow-hidden rounded-t border-b border-[#3d3d3d] bg-[#0f0f0f] flex items-center justify-center",children:s?n.jsx("img",{src:We(s),alt:e.name,className:"w-full h-full object-cover"}):n.jsx("span",{className:"text-[10px] text-gray-600",children:"No screenshot"})}),n.jsx("div",{className:"px-2 py-1 text-[11px] text-gray-200 truncate",children:a})]})}function Bm({group:e,currentSlug:t,onSelect:r}){const s=e.scenarios[0]?_a(e.scenarios[0]):null;return n.jsxs("div",{className:"mb-4 last:mb-0",children:[n.jsxs("div",{className:"flex items-baseline gap-1.5 mb-1.5 px-1",children:[n.jsx("span",{className:"text-xs font-semibold text-gray-200 truncate",children:s??e.route}),s?n.jsx("span",{className:"text-[10px] text-gray-500 font-mono truncate",children:e.route}):null]}),n.jsx("div",{className:"flex flex-wrap gap-2",children:e.scenarios.map(a=>n.jsx(Om,{scenario:a,active:a.slug===t,onClick:()=>r(a.slug)},a.slug))})]})}function hs({label:e,active:t,count:r,onClick:s}){return n.jsxs("button",{onClick:s,className:`flex items-center gap-1.5 px-2 py-1 rounded text-[10px] font-semibold tracking-wider cursor-pointer transition-colors ${t?"text-white bg-[#3a3a3a]":"text-gray-500 hover:text-gray-300"}`,children:[e,n.jsx("span",{className:`text-[10px] font-mono px-1 rounded ${t?"bg-[#555] text-gray-200":"bg-[#2a2a2a] text-gray-500"}`,children:r})]})}function $m({scenarioGroups:e,currentSlug:t,onSelect:r,onClose:s,triggerRef:a}){const[o,l]=i.useState("pages"),[c,d]=i.useState(""),u=i.useRef(null),f=i.useRef(null);i.useEffect(()=>{var w;(w=f.current)==null||w.focus()},[]),Ha(u,s,a);const p=i.useMemo(()=>e.flatMap(w=>w.scenarios),[e]),m=i.useMemo(()=>Im(p,c),[p,c]),h=i.useMemo(()=>m.filter(Qe),[m]),j=i.useMemo(()=>m.filter(tr),[m]),b=o==="pages"?h:j,g=i.useMemo(()=>za(b),[b]);return n.jsxs("div",{ref:u,className:"absolute top-full left-0 mt-1 bg-[#222] border border-[#3d3d3d] rounded-lg shadow-2xl z-50 w-[560px] max-h-[480px] flex flex-col",role:"dialog",children:[n.jsxs("div",{className:"flex items-center border-b border-[#3d3d3d] px-2 py-1.5 gap-2",children:[n.jsx(hs,{label:"PAGES",active:o==="pages",count:h.length,onClick:()=>l("pages")}),n.jsx(hs,{label:"COMPONENTS",active:o==="components",count:j.length,onClick:()=>l("components")}),n.jsx("div",{className:"flex-1"}),n.jsx("input",{ref:f,value:c,onChange:w=>d(w.target.value),placeholder:"Search…",className:"w-48 px-2 py-1 text-xs bg-[#1a1a1a] border border-[#3d3d3d] rounded text-gray-200 focus:outline-none focus:border-[#007a99]"}),n.jsx("button",{onClick:s,"aria-label":"Close",className:"p-1 text-gray-500 hover:text-gray-200 cursor-pointer",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M18 6L6 18M6 6l12 12"})})})]}),n.jsx("div",{className:"overflow-y-auto p-3 flex-1 min-h-0",children:g.length===0?n.jsx(Fm,{tab:o,hasQuery:c.trim().length>0}):g.map(w=>n.jsx(Bm,{group:w,currentSlug:t,onSelect:v=>{r(v),s()}},w.route))})]})}function _m(){return n.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("path",{d:"M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"}),n.jsx("path",{d:"M14 3v6h6"})]})}function zm(){return n.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("rect",{x:"3",y:"3",width:"8",height:"8",rx:"1"}),n.jsx("rect",{x:"13",y:"3",width:"8",height:"8",rx:"1"}),n.jsx("rect",{x:"3",y:"13",width:"8",height:"8",rx:"1"}),n.jsx("rect",{x:"13",y:"13",width:"8",height:"8",rx:"1"})]})}function Wa({className:e}){return n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:e??"opacity-70 shrink-0 text-gray-400",children:n.jsx("polyline",{points:"6 9 12 15 18 9"})})}function Hm({currentScenario:e,isOpen:t,onClick:r,buttonRef:s}){const a=e?tr(e):!1,o=(e==null?void 0:e.screenshotPaths[0])??null,l=e?a?e.componentName??e.name:_a(e)??e.url??e.name:"Select a page";return n.jsxs("button",{ref:s,onClick:r,className:`flex items-center gap-1.5 max-w-[260px] pl-0.5 pr-1.5 py-0.5 rounded transition-colors cursor-pointer text-xs ${e?"text-gray-200":"text-gray-500"} ${t?"bg-[#555]":"hover:bg-[#4a4a4a]"}`,title:l,"aria-haspopup":"menu","aria-expanded":t,children:[n.jsxs("span",{className:"flex items-center gap-0.5 bg-[#1f1f1f] border border-[#3d3d3d] rounded p-0.5",children:[n.jsx("span",{className:"w-6 h-4 overflow-hidden rounded-sm bg-[#0f0f0f] flex items-center justify-center text-gray-500",children:o?n.jsx("img",{src:We(o),alt:"",className:"w-full h-full object-cover"}):a?n.jsx(zm,{}):n.jsx(_m,{})}),n.jsx(Wa,{})]}),n.jsx("span",{className:"truncate",children:l})]})}function Wm(e,t){const r=e.url??"Uncategorized",s=t.find(a=>a.route===r);return(s==null?void 0:s.scenarios)??[e]}function Vm({scenario:e,active:t,onClick:r}){const s=e.screenshotPaths[0];return n.jsxs("button",{onClick:r,className:`flex items-center gap-2 w-full px-2 py-1.5 text-left transition-colors cursor-pointer ${t?"bg-[#1a2a30]":"hover:bg-[#2a2a2a]"}`,children:[n.jsx("div",{className:"w-10 h-7 shrink-0 rounded overflow-hidden border border-[#3d3d3d] bg-[#0f0f0f] flex items-center justify-center",children:s?n.jsx("img",{src:We(s),alt:"",className:"w-full h-full object-cover"}):null}),n.jsx("div",{className:`text-xs truncate flex-1 min-w-0 ${t?"text-white":"text-gray-200"}`,children:Sr(e)})]})}function Um({currentScenario:e,scenarioGroups:t,onSelect:r,onCreateNew:s,onClose:a,triggerRef:o}){const l=i.useRef(null);Ha(l,a,o);const c=i.useMemo(()=>Wm(e,t),[e,t]);return n.jsxs("div",{ref:l,className:"absolute top-full right-0 mt-1 bg-[#222] border border-[#3d3d3d] rounded-lg shadow-2xl z-50 w-72 max-h-[400px] flex flex-col",role:"menu",children:[n.jsx("div",{className:"overflow-y-auto py-1 flex-1 min-h-0",children:c.map(d=>n.jsx(Vm,{scenario:d,active:d.slug===e.slug,onClick:()=>{r(d.slug),a()}},d.slug))}),n.jsx("button",{onClick:()=>{s(),a()},className:"border-t border-[#3d3d3d] px-3 py-2 text-left text-[11px] font-mono tracking-wide text-[var(--accent-active)] hover:bg-[var(--accent-active)]/10 cursor-pointer",children:"+ CREATE NEW STATE"})]})}function Km({label:e,disabled:t,isOpen:r,onClick:s,buttonRef:a}){return n.jsxs("button",{ref:a,onClick:()=>{t||s()},disabled:t,className:`flex items-center gap-1.5 max-w-[200px] h-7 px-2.5 rounded transition-colors text-xs ${t?"bg-[#3a3a3a] text-gray-600 cursor-not-allowed":r?"bg-[#444] text-gray-200 cursor-pointer":"bg-[#3a3a3a] text-gray-200 hover:bg-[#444] cursor-pointer"}`,title:t?"No active state":e,"aria-haspopup":"menu","aria-expanded":r,children:[n.jsx("span",{className:"truncate",children:e}),n.jsx(Wa,{className:"opacity-70 shrink-0"})]})}function Gm({viewport:e,isActive:t,onSelect:r}){return n.jsx("button",{onClick:r,className:`p-1 rounded transition-colors cursor-pointer ${t?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:`${e.name} (${e.width}×${e.height})`,children:n.jsx(_f,{name:e.name})})}function Ym({viewports:e,active:t,onChange:r,currentWidth:s,currentHeight:a,previewUrl:o,isCollapsed:l,onToggleCollapsed:c,isFilled:d,onToggleFilled:u,containerWidth:f,containerHeight:p,onCustomSizeChange:m,currentScenario:h,scenarioGroups:j,onShowScenarioPreview:b,onCreateStateRequest:g}){const[w,v]=i.useState(!1),[x,y]=i.useState(!1),N=i.useRef(null),C=i.useRef(null),S=d&&f?Math.round(f):s,k=d&&p?Math.round(p):a,R=h?Sr(h):"No state",E=!h;return n.jsxs("div",{className:"bg-[#2d2d2d] border-b border-[#3d3d3d] shrink-0 h-10 grid grid-cols-[1fr_auto_1fr] items-center px-2",children:[n.jsx("div",{className:"justify-self-start",children:n.jsx(Am,{isCollapsed:l,onToggle:c})}),n.jsxs("div",{className:"flex items-center gap-2 justify-self-center",children:[n.jsxs("div",{className:"relative flex items-center bg-[#3a3a3a] rounded h-7 px-1 gap-1",children:[n.jsx(Hm,{currentScenario:h,isOpen:w,onClick:()=>{v(T=>!T),y(!1)},buttonRef:N}),w&&n.jsx($m,{scenarioGroups:j,currentSlug:(h==null?void 0:h.slug)??null,onSelect:b,onClose:()=>v(!1),triggerRef:N}),n.jsx("span",{className:"w-px h-5 bg-[#555] mx-1 shrink-0","aria-hidden":"true"}),e.map(T=>n.jsx(Gm,{viewport:T,isActive:!d&&t===T.name,onSelect:()=>{d&&u(),r(T.name)}},T.name)),n.jsx(Lm,{isFilled:d,onToggle:u}),n.jsx(xs,{label:"H",value:k,disabled:d,onCommit:T=>m(s,T)}),n.jsx(xs,{label:"W",value:S,disabled:d,onCommit:T=>m(T,a)}),n.jsx(Mm,{previewUrl:o})]}),n.jsx("div",{className:"flex items-center gap-2 shrink-0",children:n.jsxs("div",{className:"relative",children:[n.jsx(Km,{label:R,disabled:E,isOpen:x,onClick:()=>{y(T=>!T),v(!1)},buttonRef:C}),x&&h&&n.jsx(Um,{currentScenario:h,scenarioGroups:j,onSelect:b,onCreateNew:g,onClose:()=>y(!1),triggerRef:C})]})})]}),n.jsx("div",{"aria-hidden":"true"})]})}function Jm(){return n.jsxs("div",{style:{padding:"3rem 1rem",textAlign:"center",color:"var(--text-muted)"},children:[n.jsx("h2",{style:{fontSize:"1.125rem",fontWeight:600,color:"var(--text-secondary)",margin:"0 0 0.5rem 0"},children:"No plan loaded"}),n.jsx("p",{style:{margin:0,fontSize:"0.875rem"},children:"Ask the AI to draft a plan, or pick one from the Plan tab."})]})}function Xm({title:e}){return n.jsx("h1",{style:{fontSize:"1.5rem",fontWeight:600,color:"var(--text-primary)",margin:"0 0 1rem 0",paddingBottom:"0.75rem",borderBottom:"1px solid var(--border-subtle)"},children:e})}function qm({prompt:e}){return n.jsxs("section",{"aria-label":"What you asked for",style:{border:"1px solid var(--border-subtle)",borderRadius:"8px",padding:"1rem 1.25rem",marginBottom:"1.5rem",background:"var(--bg-elevated)"},children:[n.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:"0.5rem"},children:"What you asked for"}),n.jsx(et,{children:e})]})}function Qm(){const e=Ms(Is());return n.jsx("footer",{style:{color:"var(--text-muted)",fontSize:"0.8125rem"},children:e==="build"?n.jsxs(n.Fragment,{children:["Watch the ",n.jsx("strong",{children:"terminal"})," on the left to follow along step by step."]}):n.jsxs(n.Fragment,{children:["Open the ",n.jsx("strong",{children:"Build"})," tab to follow along step by step."]})})}function Zm(){return n.jsxs("header",{style:{marginBottom:"1.5rem"},children:[n.jsx("h1",{style:{fontSize:"1.5rem",fontWeight:600,color:"var(--text-primary)",margin:"0 0 0.5rem 0"},children:"Setting up your project"}),n.jsx("p",{style:{margin:0,color:"var(--text-muted)",fontSize:"0.875rem"},children:"Hold tight — your app is being built. This usually takes a few minutes."})]})}function ex(e,t){if(e.phaseSteps.length===0)return"pending";const r=e.phaseSteps[0],s=e.phaseSteps[e.phaseSteps.length-1];return t>s?"complete":t>=r?"active":"pending"}const tx={complete:"✓",active:"●",pending:"○"},nx={complete:"var(--accent-green, #16a34a)",active:"var(--accent-blue, #2563eb)",pending:"var(--text-muted)"};function rx({phase:e,status:t,activeStepLabel:r}){const s=t==="pending"?"var(--text-muted)":"var(--text-primary)";return n.jsxs("li",{"data-phase-id":e.phaseId,"data-phase-status":t,style:{display:"flex",alignItems:"flex-start",gap:"0.75rem"},children:[n.jsx("span",{"aria-hidden":"true",style:{width:"1.25rem",flexShrink:0,color:nx[t],fontSize:"1rem",lineHeight:"1.4",textAlign:"center"},children:tx[t]}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{color:s,fontSize:"0.9375rem",fontWeight:t==="active"?600:400},children:e.phaseLabel}),t==="active"&&r?n.jsxs("div",{style:{marginTop:"0.25rem",color:"var(--text-secondary)",fontSize:"0.8125rem"},children:["Now: ",r]}):null]})]})}function sx({currentStep:e,mode:t}){const r=Nl(t),s=jl(e,t)||null;return n.jsx("section",{"aria-label":"Progress",style:{marginBottom:"1.5rem"},children:n.jsx("ol",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:"0.75rem"},children:r.map(a=>{const o=ex(a,e);return n.jsx(rx,{phase:a,status:o,activeStepLabel:o==="active"?s:null},a.phaseId)})})})}function ax(e){let t=e;const r=t.match(/^Feature: [^\n]*\n\nProject context: /);return r?t=t.slice(r[0].length):t.startsWith("Project context: ")&&(t=t.slice(17)),t.endsWith(`
22
+ `)&&(t=t.slice(0,-1)),t}function ox({prompt:e,currentStep:t,mode:r}){return n.jsxs(n.Fragment,{children:[n.jsx(Zm,{}),n.jsx(qm,{prompt:ax(e)}),n.jsx(sx,{currentStep:t,mode:r}),n.jsx(Qm,{})]})}const gs={prompt:null,title:null};function ix(){const[e,t]=i.useState(gs),[r,s]=i.useState(!0);return i.useEffect(()=>{let a=!1;return(async()=>{try{const l=await(await fetch("/api/prompt")).json();a||t({prompt:l.prompt??null,title:l.title??null})}catch{a||t(gs)}finally{a||s(!1)}})(),()=>{a=!0}},[]),{...e,loading:r}}function lx(){const{prompt:e,title:t,loading:r}=ix(),{stepState:s}=Lt();return n.jsx("div",{className:"flex-1 flex flex-col min-w-0 overflow-auto",style:{background:"var(--bg-deep)"},children:n.jsx("div",{style:{padding:"1.5rem 2rem",maxWidth:"880px",width:"100%",margin:"0 auto"},children:r?null:e?t?n.jsxs(n.Fragment,{children:[n.jsx(Xm,{title:t}),n.jsx(et,{children:e})]}):n.jsx(ox,{prompt:e,currentStep:(s==null?void 0:s.step)??1,mode:(s==null?void 0:s.mode)??"ui"}):n.jsx(Jm,{})})})}function cx({message:e}){return n.jsx("span",{style:{color:"var(--text-dim)"},children:e})}function dx(e,t,r){const s=[e];return t&&s.push(`reload:${t}`),r&&s.push(`command:${r}`),s.join("::")}function ux({currentWidth:e,currentHeight:t,isFilled:r,scale:s}){const a=n.jsx("div",{className:"w-full h-full border border-dashed rounded flex items-center justify-center text-center px-6",style:{borderColor:"var(--border-default)",background:"var(--bg-surface)",color:"var(--text-dim)"},children:n.jsxs("div",{className:"text-sm leading-relaxed",children:[n.jsx("div",{className:"font-medium",children:"Live Preview unavailable"}),n.jsxs("div",{className:"opacity-70 mt-1",children:[e,"×",t]})]})});return r?a:n.jsx("div",{className:"shadow-[0_10px_30px_rgba(0,0,0,0.45)]",style:{width:e,height:t,transform:s<1?`scale(${s})`:void 0,transformOrigin:"center center",flexShrink:0},children:a})}const fx=i.forwardRef(function({currentHeight:t,currentWidth:r,isFilled:s,previewUrl:a,scale:o,reloadNonce:l,commandNonce:c,onLoad:d,onError:u},f){if(ut())return n.jsx(ux,{currentWidth:r,currentHeight:t,isFilled:s,scale:o});const p=dx(a,l,c),m=()=>{u&&u("iframe error event")};return s?n.jsx("iframe",{ref:f,src:a,title:"Live Preview",className:"w-full h-full border-none",style:{background:"var(--bg-deep)"},onLoad:d,onError:m},p):n.jsx("div",{className:"shadow-[0_10px_30px_rgba(0,0,0,0.45)]",style:{width:r,height:t,transform:o<1?`scale(${o})`:void 0,transformOrigin:"center center",flexShrink:0},children:n.jsx("iframe",{ref:f,src:a,title:"Live Preview",style:{width:"100%",height:"100%",border:"none",background:"var(--bg-deep)"},onLoad:d,onError:m},p)})});function px(e,t){const r=i.useRef(!1);i.useEffect(()=>{r.current||e&&e.startCommand&&(e.intendedRunning||e.status==="stopped"&&(r.current=!0,t()))},[e,t])}function mx(e,t){const[r,s]=i.useState(!1),a=i.useCallback(()=>{r?(s(!1),e.deactivate(),e.clearSelection()):(s(!0),e.activate())},[r,e]);return i.useEffect(()=>{r&&(s(!1),e.clearSelection())},[t]),{isActive:r,toggle:a}}function xx(e,t=!0,r="running"){const s=i.useRef(null),a=i.useRef(!1),[o,l]=i.useState(0),c=i.useRef(null);i.useEffect(()=>{e!=null&&(s.current!=null&&e!==s.current?l(f=>f+1):s.current==null&&a.current&&t&&fs(e,c.current),s.current=e)},[e,t]);const d=i.useCallback(f=>{a.current=!0,f&&(c.current=f),t&&e!=null&&fs(e,f??c.current)},[e,t]),u=i.useCallback(f=>{t&&qp(f)},[t]);return{reloadNonce:o,handleIframeLoad:d,handleIframeError:u}}const hx=500,gx=2e3,vx=1e3,bx=2;function yx(){return typeof window>"u"?!1:window.location.pathname.startsWith("/scenario/")?!0:ut()}function wx(e,t=!1){const r=yx(),[s,a]=i.useState(r?!0:null),[o,l]=i.useState(null),[c,d]=i.useState(0),[u,f]=i.useState(0),p=i.useRef(null),m=i.useRef(null),h=i.useRef(null),j=i.useRef(!1),b=i.useRef(e),g=i.useRef(t);i.useEffect(()=>{b.current=e},[e]),i.useEffect(()=>{g.current=t},[t]);const w=i.useCallback(()=>{m.current!=null&&(clearTimeout(m.current),m.current=null)},[]),v=i.useCallback(async()=>{if(j.current||g.current)return;const C=b.current;if(!C)return;h.current&&h.current.abort();const S=new AbortController;h.current=S;const k=setTimeout(()=>S.abort(),vx);let R=!1;try{await fetch(C,{mode:"no-cors",cache:"no-store",signal:S.signal}),R=!0}catch{R=!1}finally{clearTimeout(k)}if(!j.current){if(l(Date.now()),R){if(d(0),p.current!==!0){const E=p.current===!1;p.current=!0,a(!0),E&&f(T=>T+1)}}else d(E=>{const T=E+1;return T>=bx&&p.current!==!1&&(p.current=!1,a(!1)),T});x()}},[]),x=i.useCallback(()=>{if(j.current)return;w();const C=p.current===!0?gx:hx;m.current=setTimeout(()=>{m.current=null,v()},C)},[w,v]),y=i.useCallback(()=>{w(),v()},[w,v]);i.useEffect(()=>{if(!r)return j.current=!1,v(),()=>{j.current=!0,w(),h.current&&(h.current.abort(),h.current=null)}},[v,w,r]),i.useEffect(()=>{r||v()},[e,v,r]);const N=i.useRef(t);return i.useEffect(()=>{if(r)return;const C=N.current;N.current=t,C&&!t&&v()},[t,v,r]),{healthy:s,lastProbeAt:o,failedProbeCount:c,reloadNonce:u,invalidate:y}}const Kt={windowMs:1e4,threshold:4,ringBufferSize:16};function jx({pidNonce:e,probeNonce:t,draftNonce:r,windowMs:s=Kt.windowMs,threshold:a=Kt.threshold}){const[o,l]=i.useState(!1),[c,d]=i.useState([]),[u,f]=i.useState(0),p=i.useRef(!1),m=i.useRef(e),h=i.useRef(t),j=i.useRef(r),b=i.useCallback(w=>{const v=Date.now(),x=v-s;let y=[];d(C=>{const S=C.filter(k=>k.timestampMs>=x);return S.push({reason:w,timestampMs:v}),S.length>Kt.ringBufferSize&&S.splice(0,S.length-Kt.ringBufferSize),y=S,S});const N=y.filter(C=>C.timestampMs>=x).length;if(!p.current&&N>=a){p.current=!0,l(!0);return}p.current||f(C=>C+1)},[s,a]);i.useEffect(()=>{e!==m.current&&(m.current=e,b("pid"))},[e,b]),i.useEffect(()=>{t!==h.current&&(h.current=t,b("probe"))},[t,b]),i.useEffect(()=>{r!==j.current&&(j.current=r,b("draft"))},[r,b]);const g=i.useCallback(()=>{p.current=!1,l(!1),d([]),f(w=>w+1)},[]);return{tripped:o,recentReloads:c,gatedNonce:u,reset:g}}const vs=20,Nx="codeyam-error-capture";function Cx(e,t=0){const[r,s]=i.useState([]),a=i.useCallback(()=>s([]),[]);return i.useEffect(()=>{s([])},[t]),i.useEffect(()=>{function o(l){const c=l.data;if(!c||c.source!==Nx)return;const d=e.current;if(d&&l.source!==d.contentWindow)return;const u=c.payload;!u||typeof u!="object"||!u.dedupeKey||s(f=>{const p=f.findIndex(h=>h.dedupeKey===u.dedupeKey);if(p>=0){const h=f.slice();return h[p]={...h[p],count:h[p].count+1,timestampMs:u.timestampMs},h}const m=[...f,{...u,count:1}];return m.length>vs?m.slice(m.length-vs):m})}return window.addEventListener("message",o),()=>window.removeEventListener("message",o)},[e]),{errors:r,clear:a}}const Mn=[500,1e3,2e3];async function Sx(e){try{const r=await(await fetch(`/api/probe-url?url=${encodeURIComponent(e)}`)).json();return{status:typeof(r==null?void 0:r.status)=="number"?r.status:null}}catch{return{status:null}}}async function kx(){try{const t=await(await fetch("/api/dev-server-log/slice?lines=40")).json();return Array.isArray(t==null?void 0:t.lines)?t.lines:[]}catch{return[]}}function Ex(e,t){const[r,s]=i.useState({status:null,clickThroughBroken:!1,logLines:[],loading:!1});return i.useEffect(()=>{if(!e){s({status:null,clickThroughBroken:!1,logLines:[],loading:!1});return}let a=!1;return s({status:null,clickThroughBroken:!1,logLines:[],loading:!0}),(async()=>{const o=1+Mn.length;let l=null;for(let d=0;d<o;d++){if(a)return;const{status:u}=await Sx(e);if(a)return;if(l=u,u===null||u<500){s({status:u,clickThroughBroken:!1,logLines:[],loading:!1});return}d<Mn.length&&await new Promise(f=>setTimeout(f,Mn[d]))}const c=await kx();a||s({status:l,clickThroughBroken:!0,logLines:c,loading:!1})})(),()=>{a=!0}},[e,t]),r}function Rx({url:e,status:t,logLines:r,onRetry:s}){return n.jsx("div",{role:"alert","data-testid":"iframe-click-through-error-card",className:"absolute inset-0 z-20 flex items-center justify-center bg-zinc-950/85 p-6",children:n.jsxs("div",{className:"max-w-2xl w-full rounded-md border border-red-700 bg-zinc-900 text-zinc-100 shadow-xl",children:[n.jsxs("div",{className:"px-5 py-4 border-b border-red-800 flex justify-between items-start",children:[n.jsxs("div",{className:"flex-1 min-w-0 pr-4",children:[n.jsxs("div",{className:"text-sm font-semibold text-red-300",children:["Scenario render failed (HTTP ",t,")"]}),n.jsx("div",{className:"mt-1 text-xs text-zinc-400 break-all",children:e}),n.jsx("div",{className:"mt-2 text-xs text-zinc-300",children:"The iframe URL returned a server error. This is a bug — capture and click should always agree. Check the dev-server log below and refresh once the underlying error is fixed."})]}),n.jsx("button",{type:"button",onClick:s,className:"flex-shrink-0 px-2.5 py-1 text-xs rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer",children:"Retry"})]}),n.jsx("div",{className:"px-5 py-4 max-h-72 overflow-auto font-mono text-[11px] leading-snug text-zinc-300 whitespace-pre-wrap",children:r.length>0?r.join(`
23
+ `):n.jsxs("span",{className:"text-zinc-500 italic",children:["No dev-server log lines available — see"," ",n.jsx("code",{children:".codeyam/logs/dev-server.log"}),"."]})})]})})}function Tx(e){if(e===null||!e.startCommand)return{isRestarting:!1,isFailed:!1,isStarting:!1,isStopped:!1};const t=e.status==="failed",r=!t&&e.status!=="running"&&e.intendedRunning,s=!t&&e.intendedRunning&&e.status!=="running"&&(e.restartCount??0)===0,a=e.status==="stopped"&&!e.intendedRunning;return{isRestarting:r,isFailed:t,isStarting:s,isStopped:a}}function Px(e){const{hasDevServerConfigured:t,probeHealthy:r,backendRunning:s,backendIframeHealthy:a,isStarting:o,isRestarting:l,isFailed:c,isStopped:d,isPrePrototype:u}=e;return!t||r===!0&&(s&&a!==!1)?null:c?"crashed":u?"scaffolding":d?"stopped":l?"restarting":o?"starting":r===!1||a===!1?"reconnecting":r===null?"probing":"reconnecting"}function Dx(e){return e===null||e.status!=="running"?!1:e.liveIframeHealthy!==!1}const Ax=5,Lx=3;function Mx(e,t){return e===null||e<=0?!1:e<=(t==="backend"?Lx:Ax)}const bs="Setting up your project",ys="Preparing your project — the preview will appear once it's ready.",Ix={1:"Aligning on the plan with you.",2:"Aligning on the plan with you.",3:"Aligning on the plan with you.",4:"Preparing the project environment.",5:"Wiring routes and seeding sample data."},Fx={1:"Aligning on the plan with you.",2:"Aligning on the plan with you.",3:"Preparing the project environment."};function Ox(e,t){return e===null?{title:bs,body:ys}:{title:bs,body:(t==="backend"?Fx:Ix)[e]??ys}}function Bx({restartCount:e}){return n.jsxs("div",{className:"relative",children:[n.jsx("div",{className:"w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin"}),n.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-[10px] font-bold text-primary",children:e>0?`#${e}`:""})]})}const $x={probing:{title:"Checking Live Preview",body:"Probing the dev server before showing the iframe…",spinner:!0},starting:{title:"Starting Dev Server",body:"Waiting for the development server to start…",spinner:!0},restarting:{title:"Dev Server Restarting",body:"The Live Preview server crashed unexpectedly. CodeYam is automatically recovering it…",spinner:!0},reconnecting:{title:"Reconnecting Live Preview",body:"Waiting for the dev server to respond…",spinner:!0},stopped:{title:"Dev Server Not Running",body:"Starting automatically…",spinner:!1},crashed:{title:"Dev Server Crashed",body:"Recovery is taking longer than usual.",spinner:!1},scaffolding:{title:"Setting up your project",body:"Preparing your project — the preview will appear once it's ready.",spinner:!0}};function _x({variant:e,restartCount:t=0,showRetry:r=!1,onRetry:s,bodyOverride:a}){const{title:o,body:l,spinner:c}=$x[e],d=a??l;return n.jsx("div",{"data-testid":"preview-unhealthy-overlay","data-variant":e,className:"absolute inset-0 bg-white/90 dark:bg-gray-900/90 backdrop-blur-sm flex flex-col items-center justify-center z-50 animate-in fade-in duration-300",children:n.jsxs("div",{className:"flex flex-col items-center space-y-4 text-center max-w-md p-6",children:[c?n.jsx(Bx,{restartCount:t}):n.jsx("div",{className:"w-12 h-12 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center",children:n.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-6 h-6 text-gray-500 dark:text-gray-400","aria-hidden":"true",children:[n.jsx("rect",{x:"6",y:"5",width:"4",height:"14",rx:"1"}),n.jsx("rect",{x:"14",y:"5",width:"4",height:"14",rx:"1"})]})}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:o}),n.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:d})]}),r&&s&&n.jsx("button",{type:"button",onClick:s,className:"mt-2 px-4 py-1.5 text-sm font-medium rounded border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-800",children:"Retry now"})]})})}function zx(e){return e.slice().reverse().map(t=>{const r=t.filename!=null?`
24
+ at ${t.filename}${t.lineno!=null?`:${t.lineno}`:""}${t.colno!=null?`:${t.colno}`:""}`:"",s=t.stack?`
25
+ ${t.stack}`:"",a=t.count>1?` (×${t.count})`:"";return`[${t.type}]${a} ${t.message}${r}${s}`}).join(`
26
+
27
+ `)}function Hx(e){if(e.length===0)return"no reloads recorded";const t={};for(const r of e)t[r.reason]=(t[r.reason]??0)+1;return Object.entries(t).map(([r,s])=>`${r}×${s}`).join(", ")}async function Wx(e){try{if(typeof navigator<"u"&&navigator.clipboard&&typeof navigator.clipboard.writeText=="function")return await navigator.clipboard.writeText(e),!0}catch{}return!1}function Vx({count:e,onExpand:t,onClear:r}){const s=`${e} ${e===1?"Error":"Errors"}`;return n.jsx("div",{"data-testid":"preview-error-badge",className:"absolute bottom-3 right-3 z-50 pointer-events-auto",children:n.jsxs("div",{className:"flex items-center gap-1.5 rounded-full shadow-lg border border-red-300 dark:border-red-800 bg-white dark:bg-gray-900",style:{background:"var(--bg-surface, rgba(255,255,255,0.97))"},children:[n.jsxs("button",{type:"button",onClick:t,"aria-label":`Expand ${s}`,className:"cursor-pointer flex items-center gap-1.5 pl-2.5 pr-2 py-1 text-xs font-medium text-red-700 dark:text-red-300 hover:bg-red-50 dark:hover:bg-red-950/40 rounded-l-full",children:[n.jsx("span",{"aria-hidden":"true",className:"inline-block h-1.5 w-1.5 rounded-full bg-red-600"}),n.jsx("span",{children:s}),n.jsx("span",{"aria-hidden":"true",className:"text-gray-400",children:"›"})]}),n.jsx("button",{type:"button",onClick:r,"aria-label":"Dismiss errors",className:"cursor-pointer px-2 py-1 text-xs text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 rounded-r-full",children:"✕"})]})})}function Ux({headline:e,tripped:t,onClear:r,closeAriaLabel:s="Dismiss errors"}){return n.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-3 border-b border-red-200 dark:border-red-900",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-sm font-semibold text-red-700 dark:text-red-300",children:e}),n.jsx("p",{className:"mt-0.5 text-xs text-gray-500 dark:text-gray-400",children:t?"Iframe frozen on its last load attempt. Copy the errors below, fix the code, then click Retry.":"Errors recorded from the running app. Copy them below to share with Claude."})]}),n.jsx("button",{type:"button",onClick:r,className:"cursor-pointer text-xs text-gray-400 hover:text-gray-600 dark:hover:text-gray-200","aria-label":s,children:"✕"})]})}function Kx({error:e,expanded:t,onToggle:r}){return n.jsxs("li",{className:"rounded border border-red-200 dark:border-red-900 bg-red-50/60 dark:bg-red-950/30",children:[n.jsxs("button",{type:"button",onClick:r,className:"w-full flex items-start gap-2 text-left px-2 py-1.5 hover:bg-red-100/60 dark:hover:bg-red-900/30",children:[n.jsx("span",{className:"mt-0.5 text-red-500","aria-hidden":"true",children:t?"▾":"▸"}),n.jsxs("span",{className:"flex-1 min-w-0",children:[n.jsx("span",{className:"font-mono text-[10px] uppercase tracking-wide text-red-500 dark:text-red-400 mr-2",children:e.type}),n.jsx("span",{className:"text-gray-900 dark:text-gray-100 break-words",children:e.message}),e.count>1&&n.jsxs("span",{className:"ml-2 text-gray-500",children:["×",e.count]}),e.filename&&n.jsxs("span",{className:"block text-[11px] text-gray-500 mt-0.5 truncate",children:[e.filename,e.lineno!=null?`:${e.lineno}`:"",e.colno!=null?`:${e.colno}`:""]})]})]}),t&&e.stack&&n.jsx("pre",{className:"px-3 pb-2 text-[11px] font-mono text-gray-700 dark:text-gray-300 whitespace-pre-wrap break-words",children:e.stack})]})}function Gx({errors:e,emptyHint:t}){const[r,s]=i.useState(null);return e.length===0?n.jsx("ul",{className:"flex-1 overflow-auto px-2 py-2 space-y-1 text-xs",children:n.jsx("li",{className:"text-gray-500 px-2 py-3",children:t??"No runtime errors captured yet."})}):n.jsx("ul",{className:"flex-1 overflow-auto px-2 py-2 space-y-1 text-xs",children:e.slice().reverse().map(a=>n.jsx(Kx,{error:a,expanded:r===a.dedupeKey,onToggle:()=>s(r===a.dedupeKey?null:a.dedupeKey)},a.dedupeKey))})}function Yx({canCopy:e,reasonsSummary:t,copyState:r,onCopy:s,onCopyForClaude:a,onRetry:o}){return n.jsxs("div",{className:"flex flex-wrap items-center gap-2 px-3 py-2 border-t border-red-200 dark:border-red-900 bg-gray-50 dark:bg-gray-900/40",children:[n.jsx("button",{type:"button",onClick:s,disabled:!e,className:"px-2.5 py-1 text-xs rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 cursor-pointer disabled:cursor-not-allowed",children:"Copy errors"}),n.jsx("button",{type:"button",onClick:a,disabled:!e,className:"px-2.5 py-1 text-xs rounded bg-red-600 text-white hover:bg-red-700 disabled:opacity-50 cursor-pointer disabled:cursor-not-allowed",children:"Copy and ask Claude"}),n.jsx("button",{type:"button",onClick:o,className:"px-2.5 py-1 text-xs rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer",children:"Retry"}),n.jsxs("span",{className:"ml-auto text-[11px] text-gray-500",children:["Reloads in last 10s: ",t,r==="copied"&&n.jsx("span",{className:"ml-2 text-emerald-600",children:"copied ✓"}),r==="failed"&&n.jsx("span",{className:"ml-2 text-red-500",children:"copy blocked"})]})]})}const Jx=`Fix this error in the live preview. Here is what the captured runtime error reported:
28
+
29
+ `;function Xx({tripped:e,errors:t,recentReloads:r,serverHealthy:s,onRetry:a,onClear:o}){const[l,c]=i.useState("idle"),[d,u]=i.useState(!0),f=i.useMemo(()=>zx(t),[t]),p=i.useMemo(()=>Hx(r),[r]);if(i.useEffect(()=>{t.length===0&&u(!0)},[t.length]),!e&&t.length===0)return null;const m=s&&!e,h=m&&d&&t.length>0,j=e?`Live Preview paused — ${t.length} error${t.length===1?"":"s"} captured`:`${t.length} runtime error${t.length===1?"":"s"} captured`;async function b(g){const w=await Wx(g+f);c(w?"copied":"failed"),setTimeout(()=>c("idle"),1500)}return h?n.jsx("div",{"data-testid":"preview-error-overlay","data-tripped":"false","data-collapsed":"true",className:"absolute inset-0 z-50 pointer-events-none",children:n.jsx(Vx,{count:t.length,onExpand:()=>u(!1),onClear:o})}):n.jsx("div",{"data-testid":"preview-error-overlay","data-tripped":e?"true":"false","data-collapsed":"false",className:"absolute inset-0 z-50 flex flex-col items-stretch p-4 pointer-events-none",children:n.jsxs("div",{className:"mx-auto w-full max-w-2xl rounded-lg shadow-lg pointer-events-auto flex flex-col",style:{background:"var(--bg-surface, rgba(255,255,255,0.97))",border:"1px solid var(--border-default, #ef4444)",maxHeight:"100%"},children:[n.jsx(Ux,{headline:j,tripped:e,onClear:m?()=>u(!0):o,closeAriaLabel:m?"Minimize errors":"Dismiss errors"}),n.jsx(Gx,{errors:t,emptyHint:e?`Breaker tripped before any runtime error was reported. Reasons in window: ${p}.`:null}),n.jsx(Yx,{canCopy:t.length>0,reasonsSummary:p,copyState:l,onCopy:()=>b(""),onCopyForClaude:()=>b(Jx),onRetry:a})]})})}function qx({previewUrl:e}){const t=i.useMemo(()=>{try{return new URL(e,window.location.origin).searchParams.get("_codeyam_scenario")}catch{return null}},[e]);return t?n.jsxs("div",{className:"absolute top-2 left-2 z-30 flex items-center gap-1.5 px-2 py-1 rounded bg-black/60 backdrop-blur-sm border border-white/10 shadow-lg pointer-events-none select-none",children:[n.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-green-500 animate-pulse"}),n.jsxs("span",{className:"text-[10px] font-medium text-white/90 tracking-wide uppercase",children:["Scenario: ",t]})]}):null}function Qx(){return n.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800",children:[n.jsxs("div",{className:"flex items-center space-x-2",children:[n.jsx("div",{className:"w-2 h-2 rounded-full bg-red-500 animate-pulse"}),n.jsx("h3",{className:"text-sm font-bold text-gray-900 dark:text-gray-100 uppercase tracking-tight",children:"Dev Server Crash Recovery Failed"})]}),n.jsx("div",{className:"text-[10px] text-gray-500 dark:text-gray-400 font-medium",children:"LAST 50 LOG LINES"})]})}function Zx({logs:e}){return n.jsx("div",{className:"flex-1 bg-black p-4 font-mono text-[11px] leading-relaxed overflow-y-auto text-gray-300",children:e.length>0?e.map((t,r)=>n.jsx("div",{className:"whitespace-pre-wrap break-all border-l-2 border-gray-800 pl-3 mb-1",children:t},r)):n.jsx("div",{className:"italic text-gray-600",children:"No logs captured..."})})}function eh({text:e,label:t="Copy",copiedLabel:r="Copied!",writer:s,className:a="shrink-0 px-3 py-1.5 text-xs font-medium rounded-md bg-red-600 hover:bg-red-700 disabled:bg-red-300 disabled:cursor-not-allowed text-white transition-colors"}){const{copied:o,copy:l}=Wo({writer:s});return n.jsx("button",{type:"button",onClick:()=>{l(e)},disabled:e.length===0,className:a,children:o?r:t})}function th(){return n.jsxs("div",{className:"flex-1",children:[n.jsx("p",{className:"text-sm text-red-800 dark:text-red-300 font-medium mb-1",children:"CodeYam was unable to restart the dev server after several attempts."}),n.jsx("p",{className:"text-xs text-red-700/80 dark:text-red-400/80",children:"Copy the logs and share them with Claude to investigate the underlying bug."})]})}function nh({logs:e,copyWriter:t}){return n.jsx("div",{className:"p-4 bg-red-50 dark:bg-red-950/30 border-t border-red-100 dark:border-red-900/50",children:n.jsxs("div",{className:"flex items-start justify-between gap-4",children:[n.jsx(th,{}),n.jsx(eh,{text:e.join(`
30
+ `),label:"Copy logs",writer:t})]})})}function rh({logs:e}){return n.jsxs("div",{className:"absolute inset-0 bg-white dark:bg-gray-900 flex flex-col z-[60] overflow-hidden",children:[n.jsx(Qx,{}),n.jsx(Zx,{logs:e}),n.jsx(nh,{logs:e})]})}const ws=20;function sh(e){if(!e)return null;try{return new Date(e).toLocaleTimeString()}catch{return null}}function ah({lastError:e,failureCount:t,failedAtMs:r,holder:s,onRetry:a,onReap:o}){const[l,c]=i.useState(!1),d=e.split(`
31
+ `),u=d.length>ws,f=l||!u?d:d.slice(d.length-ws),p=sh(r);return n.jsxs("div",{"data-testid":"dev-server-failed-panel",className:"absolute inset-0 bg-white dark:bg-gray-900 flex flex-col z-[60] overflow-hidden",children:[n.jsxs("header",{className:"px-6 py-4 border-b border-gray-200 dark:border-gray-700",children:[n.jsxs("h2",{className:"text-base font-semibold text-gray-900 dark:text-gray-100",children:["Dev server failed to start after ",t," ",t===1?"attempt":"attempts"]}),p&&n.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:["Last attempt: ",p]}),s&&n.jsxs("div",{"data-testid":"dev-server-failed-holder",className:"mt-3 rounded border border-amber-300 dark:border-amber-700 bg-amber-50 dark:bg-amber-900/30 px-3 py-2 text-xs text-amber-900 dark:text-amber-100",children:[n.jsxs("div",{children:["Port ",n.jsx("span",{className:"font-semibold",children:s.port})," is held by:"]}),n.jsxs("div",{className:"mt-1 font-mono",children:["PID ",s.pid," — ",s.command]})]})]}),n.jsx("pre",{"data-testid":"dev-server-failed-error",className:"flex-1 overflow-auto px-6 py-4 m-0 font-mono text-xs leading-relaxed text-gray-800 dark:text-gray-200 whitespace-pre-wrap",children:f.join(`
32
+ `)}),n.jsxs("footer",{className:"px-6 py-3 border-t border-gray-200 dark:border-gray-700 flex items-center justify-between gap-3",children:[u?n.jsx("button",{type:"button",onClick:()=>c(m=>!m),className:"text-xs text-gray-600 dark:text-gray-300 underline hover:text-gray-900 dark:hover:text-gray-100",children:l?"Show less":`Show all ${d.length} lines`}):n.jsx("span",{}),n.jsxs("div",{className:"flex items-center gap-2",children:[s&&o&&n.jsx("button",{type:"button","data-testid":"dev-server-failed-reap",onClick:o,className:"px-4 py-1.5 text-sm font-medium rounded border border-amber-500 text-amber-700 dark:text-amber-200 hover:bg-amber-100 dark:hover:bg-amber-900/50",children:"Kill orphan and retry"}),n.jsx("button",{type:"button","data-testid":"dev-server-failed-retry",onClick:a,className:"px-4 py-1.5 text-sm font-medium rounded bg-blue-600 text-white hover:bg-blue-700",children:"Retry"})]})]})]})}const js=48,oh=100,ih=320,lh=192;function ch({containerHeight:e,containerWidth:t,viewportHeight:r,viewportWidth:s}){if(!(s!=null&&r!=null&&t!=null&&e!=null&&s>0&&r>0&&t>0&&e>0))return{width:ih,height:lh,hasViewport:!1};const o=t-js*2,l=e-js*2-oh,c=Math.min(1,o/s,l/r);return{width:Math.round(s*c),height:Math.round(r*c),hasViewport:!0}}function dh({containerHeight:e,containerWidth:t,onDismiss:r,scenarioName:s,screenshotPath:a,viewportHeight:o,viewportWidth:l}){const{width:c,height:d,hasViewport:u}=ch({containerWidth:t,containerHeight:e,viewportWidth:l,viewportHeight:o}),f={width:c,height:d,...u?{overflowY:"auto"}:{}};return n.jsx("div",{className:"absolute inset-0 bg-white/90 dark:bg-gray-900/90 backdrop-blur-sm flex flex-col items-center justify-center z-50 animate-in fade-in duration-300",children:n.jsxs("div",{className:"flex flex-col items-center space-y-4 text-center p-6",children:[n.jsx("div",{className:"rounded-lg overflow-hidden border border-gray-200 dark:border-gray-700 shadow-md",style:f,children:n.jsx(Ea,{screenshotPath:a??void 0,alt:s??"Scenario preview",className:u?"w-full h-auto":"max-w-full max-h-full object-contain"})}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:"The app is being edited"}),n.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Live preview will load when the build agent is idle"})]}),n.jsx("button",{onClick:r,className:"text-xs text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:"Dismiss"})]})})}function uh({isActive:e,onToggle:t}){return n.jsx("button",{onClick:t,title:e?"Exit Debug Mode":"Debug Mode",className:"absolute z-50",style:{bottom:16,right:16,width:40,height:40,borderRadius:"50%",border:e?"2px solid var(--accent-blue)":"1px solid var(--border-default)",background:e?"var(--accent-blue)":"var(--bg-surface)",color:e?"#000":"var(--text-secondary)",cursor:"pointer",display:"none",alignItems:"center",justifyContent:"center",opacity:e?1:.6,transition:"all 0.15s ease",fontSize:18},onMouseEnter:r=>{r.currentTarget.style.opacity="1"},onMouseLeave:r=>{e||(r.currentTarget.style.opacity="0.6")},children:e?"✕":"🔍"})}function fh(){const[e,t]=i.useState(null),r=i.useCallback(async(a,o)=>{try{const l=await fetch("/api/open-in-editor",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file:a,line:o})}),c=await l.json().catch(()=>({}));if(!l.ok||(c==null?void 0:c.success)!==!0){t({message:(c==null?void 0:c.error)??`HTTP ${l.status}`,command:(c==null?void 0:c.command)??null});return}t(null)}catch(l){t({message:l instanceof Error?l.message:String(l),command:null})}},[]),s=i.useCallback(()=>t(null),[]);return{openInEditor:r,lastError:e,clearError:s}}function ph({tag:e,id:t,className:r,text:s,detectionMethod:a,previewUrl:o}){return n.jsxs("div",{className:"flex-1 flex flex-col gap-3 min-w-0",children:[n.jsx("div",{className:"rounded overflow-hidden flex-1",style:{background:"var(--bg-deep)",border:"1px solid var(--border-default)",minHeight:200,display:"flex",alignItems:"center",justifyContent:"center"},children:n.jsxs("div",{style:{color:"var(--text-secondary)",fontSize:12},children:[n.jsxs("div",{className:"text-center",style:{color:"var(--text-secondary)"},children:["Preview: ",o.split("/").pop()]}),n.jsxs("div",{className:"mt-2 p-3 rounded",style:{background:"var(--bg-surface)",border:"1px dashed var(--border-default)",fontSize:11,fontFamily:"monospace"},children:["<",e,t?` id="${t}"`:"",r?` class="${r.slice(0,40)}"`:"",">",n.jsx("br",{}),s.slice(0,60),s.length>60?"...":""]})]})}),n.jsxs("div",{style:{fontSize:11,color:"var(--text-secondary)"},children:["Detected via: ",a]})]})}function mh({ancestors:e,onOpenInEditor:t}){return e.length===0?n.jsx("div",{style:{color:"var(--text-secondary)",fontSize:12,fontStyle:"italic"},children:"No component ancestry available."}):n.jsx("ul",{className:"flex flex-col gap-1",style:{listStyle:"none",padding:0,margin:0},children:e.map((r,s)=>{const a=r.sourceFile&&r.lineNumber?`${r.sourceFile}:${r.lineNumber}`:r.sourceFile??"(unknown source)",o=!!r.sourceFile;return n.jsxs("li",{className:"flex items-center gap-2 px-2 py-1 rounded",style:{background:"var(--bg-deep)"},children:[n.jsx("span",{style:{color:"var(--text-primary)",fontWeight:600,fontSize:12},children:r.componentName??"<anonymous>"}),n.jsx("span",{style:{color:"var(--text-secondary)",fontFamily:"monospace",fontSize:11,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a}),o&&n.jsx("button",{onClick:()=>t(r.sourceFile,r.lineNumber),className:"px-2 py-0.5 rounded text-xs",style:{background:"transparent",border:"1px solid var(--border-default)",color:"var(--accent-blue)",cursor:"pointer",fontSize:11},children:"Open in editor"})]},`${r.componentName??"anon"}-${s}`)})})}function xh({ancestors:e,onOpenInEditor:t}){const[r,s]=i.useState(e.length>1);return e.length===0?null:n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsxs("button",{onClick:()=>s(a=>!a),className:"text-left",style:{background:"transparent",border:"none",color:"var(--text-secondary)",fontSize:12,cursor:"pointer",padding:0},children:[r?"▾":"▸"," Component ancestry (",e.length,")"]}),r&&n.jsx(mh,{ancestors:e,onOpenInEditor:t})]})}function hh({propsNames:e}){if(e.length===0)return null;const t=()=>{var r;(r=navigator.clipboard)==null||r.writeText(e.join(", "))};return n.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[n.jsx("span",{style:{color:"var(--text-secondary)",fontSize:12},children:"props:"}),e.map(r=>n.jsx("span",{onClick:t,className:"px-1.5 py-0.5 rounded",style:{background:"var(--bg-deep)",color:"var(--text-primary)",fontFamily:"monospace",fontSize:11,cursor:"pointer"},title:"Click to copy prop names",children:r},r))]})}function gh({componentDisplay:e,sourceDisplay:t,tag:r,id:s,boundingBox:a,feedback:o,onFeedbackChange:l,creating:c,hasComponentName:d,ancestors:u,propsNames:f,onOpenInEditor:p,onGoToIsolated:m,onCreatePlan:h,onClose:j}){const b=c||!o.trim();return n.jsxs("div",{className:"flex-1 flex flex-col gap-3 min-w-0",children:[n.jsx("h3",{style:{color:"var(--text-primary)",fontSize:16,fontWeight:600,margin:0},children:e}),t&&n.jsx("div",{className:"px-2 py-1 rounded",style:{background:"var(--bg-deep)",fontSize:12,fontFamily:"monospace",color:"var(--accent-blue)"},children:t}),n.jsxs("div",{className:"flex flex-col gap-1",style:{color:"var(--text-secondary)",fontSize:12},children:[n.jsxs("div",{children:["Element: <",r,">",s?` #${s}`:""]}),n.jsxs("div",{children:["Position: ",Math.round(a.x),", ",Math.round(a.y)," (",Math.round(a.width),"x",Math.round(a.height),")"]})]}),n.jsx(hh,{propsNames:f}),n.jsx(xh,{ancestors:u,onOpenInEditor:p}),n.jsx("textarea",{value:o,onChange:g=>l(g.target.value),placeholder:"Describe the issue or desired change...",className:"flex-1 p-2 rounded resize-none",style:{background:"var(--bg-deep)",border:"1px solid var(--border-default)",color:"var(--text-primary)",fontSize:13,minHeight:80,outline:"none"}}),n.jsxs("div",{className:"flex gap-2",children:[d&&n.jsx("button",{onClick:m,className:"px-3 py-1.5 rounded text-sm",style:{background:"var(--bg-deep)",border:"1px solid var(--border-default)",color:"var(--text-primary)",cursor:"pointer"},children:"Go to Isolated Component"}),n.jsx("button",{onClick:h,disabled:b,className:"px-3 py-1.5 rounded text-sm flex-1",style:{background:b?"var(--bg-deep)":"var(--accent-blue)",border:"none",color:b?"var(--text-secondary)":"#000",cursor:b?"not-allowed":"pointer",fontWeight:600},children:c?"Creating...":"Create Fix Plan"}),n.jsx("button",{onClick:j,className:"px-3 py-1.5 rounded text-sm",style:{background:"transparent",border:"1px solid var(--border-default)",color:"var(--text-secondary)",cursor:"pointer"},children:"Cancel"})]})]})}function vh({error:e,onDismiss:t}){return n.jsxs("div",{onClick:r=>r.stopPropagation(),className:"fixed bottom-4 left-1/2 px-3 py-2 rounded",style:{transform:"translateX(-50%)",background:"var(--bg-surface)",border:"1px solid var(--accent-red, #f85149)",color:"var(--text-primary)",fontSize:12,zIndex:60,maxWidth:520},children:[n.jsxs("div",{children:["Open in editor failed: ",e.message]}),e.command&&n.jsx("div",{style:{fontFamily:"monospace",fontSize:11,marginTop:4},children:e.command}),n.jsx("button",{onClick:t,className:"mt-1",style:{background:"transparent",border:"none",color:"var(--accent-blue)",cursor:"pointer",fontSize:11,padding:0},children:"Dismiss"})]})}function bh({element:e,previewUrl:t,onClose:r,onGoToIsolated:s,onCreatePlan:a}){const[o,l]=i.useState(""),[c,d]=i.useState(!1),{openInEditor:u,lastError:f,clearError:p}=fh(),m=async()=>{d(!0);try{await a(o,e)}finally{d(!1)}},h=e.componentName??`<${e.element.tag}>`,j=e.sourceFile?`${e.sourceFile}${e.lineNumber?`:${e.lineNumber}`:""}`:null;return n.jsxs("div",{className:"absolute inset-0 z-50 flex items-center justify-center",style:{background:"rgba(0, 0, 0, 0.7)"},onClick:r,children:[n.jsxs("div",{className:"flex gap-4 p-6 rounded-lg max-w-3xl w-full mx-4",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)",maxHeight:"80vh"},onClick:b=>b.stopPropagation(),children:[n.jsx(ph,{tag:e.element.tag,id:e.element.id,className:e.element.className,text:e.element.text,detectionMethod:e.detectionMethod,previewUrl:t}),n.jsx(gh,{componentDisplay:h,sourceDisplay:j,tag:e.element.tag,id:e.element.id,boundingBox:e.element.boundingBox,feedback:o,onFeedbackChange:l,creating:c,hasComponentName:!!e.componentName,ancestors:e.ancestors,propsNames:e.propsNames,onOpenInEditor:u,onGoToIsolated:()=>s(e.componentName),onCreatePlan:m,onClose:r})]}),f&&n.jsx(vh,{error:f,onDismiss:p})]})}function yh(){return n.jsx("div",{className:"absolute z-40 px-2 py-1 rounded",style:{bottom:8,right:8,background:"var(--bg-surface)",border:"1px solid var(--accent-blue)",color:"var(--accent-blue)",fontSize:11,fontWeight:600,pointerEvents:"none",fontFamily:"system-ui"},"data-testid":"debug-freeze-pill",children:"Debug — frozen"})}function wh({hoveredElement:e}){return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"absolute inset-0 z-40",style:{border:"3px solid var(--accent-blue)",cursor:"crosshair",pointerEvents:"none"}}),e&&n.jsx("div",{className:"absolute z-40 px-2 py-1 rounded",style:{top:8,left:8,background:"var(--accent-blue)",color:"#000",fontSize:12,fontWeight:600,pointerEvents:"none"},children:e.componentName??`<${e.element.tag}>`}),n.jsx(yh,{})]})}function jh(){return n.jsx("div",{className:"absolute z-40 pointer-events-none",style:{top:0,left:0,right:0,bottom:0,border:"2px solid var(--accent-blue, #58a6ff)",borderRadius:4,boxSizing:"border-box"},children:n.jsx("div",{style:{position:"absolute",top:0,left:16,padding:"2px 8px",background:"var(--accent-blue, #58a6ff)",color:"#000",fontSize:10,fontWeight:700,fontFamily:"system-ui, -apple-system, sans-serif",borderRadius:"0 0 4px 4px",letterSpacing:.5},children:"INSPECT MODE"})})}function Nh(e,t,r){const{width:s,maxHeight:a,gap:o}=r,l=e.y+e.height+o,c=l+a>t.height,d=c?Math.max(o,e.y-a-o):l,u=Math.max(o,Math.min(e.x,t.width-s-o));return{top:d,left:u,placedAbove:c}}function Ch({onDismiss:e}){return n.jsx("div",{onClick:e,style:{position:"fixed",inset:0,zIndex:999998,background:"transparent"}})}function Sh({match:e,onOpen:t}){return n.jsxs("button",{onClick:()=>t(e),style:{width:"100%",textAlign:"left",padding:"6px 8px",background:"rgba(88, 166, 255, 0.12)",color:"inherit",border:"1px solid rgba(88, 166, 255, 0.4)",borderRadius:4,cursor:"pointer",fontFamily:"monospace",fontSize:11},children:[n.jsx("div",{style:{fontWeight:600},children:e.endpoint}),n.jsx("div",{style:{opacity:.85},children:e.jsonPath})]})}function kh({matches:e,onOpen:t}){return n.jsx("ul",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:6},children:e.map((r,s)=>n.jsx("li",{children:n.jsx(Sh,{match:r,onOpen:t})},`${r.endpoint}${r.jsonPath}${s}`))})}function Eh({clickedText:e,matches:t,corpusEmpty:r,onOpenInPanel:s}){return n.jsxs("div",{style:{padding:"8px 12px"},children:[n.jsxs("div",{style:{opacity:.7,marginBottom:6,wordBreak:"break-all"},children:["Clicked: ",n.jsx("code",{children:Rh(e,120)||"(empty)"})]}),r?n.jsx("div",{style:{opacity:.85},children:"No mocks were consumed on this page load yet."}):t.length===0?n.jsx("div",{style:{opacity:.85},children:"No direct mock value matches — this value may be computed or concatenated."}):n.jsx(kh,{matches:t,onOpen:s})]})}function Rh(e,t){return e.length<=t?e:e.slice(0,t-1)+"…"}function Th({onDismiss:e}){return n.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--border-muted, #374151)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsx("span",{style:{fontWeight:600},children:"Data source"}),n.jsx("button",{onClick:e,"aria-label":"Dismiss",style:{background:"transparent",color:"inherit",border:"none",cursor:"pointer",fontSize:14,lineHeight:1},children:"×"})]})}const Ns=320,Cs=320,Ph=8;function Dh({clickedText:e,matches:t,anchor:r,onOpenInPanel:s,onDismiss:a,corpusEmpty:o}){i.useEffect(()=>{function f(p){p.key==="Escape"&&a()}return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[a]);const l=typeof window<"u"?window.innerHeight:800,c=typeof window<"u"?window.innerWidth:1200,{top:d,left:u}=Nh(r,{width:c,height:l},{width:Ns,maxHeight:Cs,gap:Ph});return n.jsxs(n.Fragment,{children:[n.jsx(Ch,{onDismiss:a}),n.jsxs("div",{style:{position:"fixed",top:d,left:u,width:Ns,maxHeight:Cs,zIndex:999999,background:"var(--bg-surface, #1f2937)",color:"var(--text-primary, #f3f4f6)",border:"1px solid var(--border-muted, #374151)",borderRadius:8,boxShadow:"0 10px 30px rgba(0,0,0,0.5)",fontFamily:"system-ui, -apple-system, sans-serif",fontSize:12,overflow:"auto"},role:"dialog","aria-label":"Mock data source inspector",children:[n.jsx(Th,{onDismiss:a}),n.jsx(Eh,{clickedText:e,matches:t,corpusEmpty:o,onOpenInPanel:s})]})]})}function Ah({healthy:e,reason:t}){const r=e===!0?"healthy":e===!1?"unhealthy":"unknown",a={healthy:{bg:"#1f3a24",border:"#2f6b3a",dot:"#4ade80",label:"Live"},unhealthy:{bg:"#3a1f1f",border:"#6b2f2f",dot:"#f87171",label:"Stale"},unknown:{bg:"#2a2a2a",border:"#444",dot:"#9ca3af",label:"—"}}[r];return n.jsxs("div",{role:"status","aria-label":`Live preview iframe: ${r}`,title:r==="healthy"?"Live Preview iframe is healthy and matches the running dev server.":r==="unhealthy"?t?`Live Preview iframe is stale: ${t}`:"Live Preview iframe is stale and out of sync with the dev server.":"Live Preview iframe health unknown.",style:{position:"absolute",top:8,right:8,display:"inline-flex",alignItems:"center",gap:6,padding:"4px 8px",borderRadius:999,backgroundColor:a.bg,border:`1px solid ${a.border}`,color:"#fff",fontSize:11,fontFamily:"monospace",zIndex:30,pointerEvents:"auto"},children:[n.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:a.dot,boxShadow:r==="healthy"?`0 0 6px ${a.dot}`:void 0}}),n.jsx("span",{children:a.label})]})}function Ss(e){if(!e||typeof e!="object")return null;const t=e;return{componentName:t.componentName??null,sourceFile:t.sourceFile??null,lineNumber:t.lineNumber??null,detectionMethod:t.detectionMethod??"dom-heuristics",ancestors:Array.isArray(t.ancestors)?t.ancestors:[],propsNames:Array.isArray(t.propsNames)?t.propsNames:[],element:t.element}}function Lh(e){const[t,r]=i.useState(!1),[s,a]=i.useState(null),[o,l]=i.useState(null),c=i.useRef(!1),d=i.useCallback(m=>{const h=e.current;h!=null&&h.contentWindow&&h.contentWindow.postMessage({type:m},"*")},[e]),u=i.useCallback(()=>{r(!0),a(null),l(null),d("codeyam:debug:activate")},[d]),f=i.useCallback(()=>{r(!1),a(null),l(null),d("codeyam:debug:deactivate")},[d]),p=i.useCallback(()=>{l(null)},[]);return i.useEffect(()=>{function m(h){!h.data||typeof h.data.type!="string"||(h.data.type==="codeyam:debug:hover"?a(Ss(h.data.payload)):h.data.type==="codeyam:debug:selected"&&l(Ss(h.data.payload)))}return window.addEventListener("message",m),()=>window.removeEventListener("message",m)},[]),i.useEffect(()=>{c.current&&!t&&(c.current=!1),t&&(c.current=!0)},[t]),{isActive:t,hoveredElement:s,selectedElement:o,activate:u,deactivate:f,clearSelection:p}}const Mh=/^\/api\/mock-panel(\/.*)?$/;function Ih(e,t){return e.toUpperCase()!=="GET"?!1:Mh.test(t)}function Fh(e){return Array.isArray(e)?e.filter(t=>t.consumedThisPageLoad&&!Ih(t.method,t.pathPattern)).map(t=>({endpoint:`${t.method} ${t.pathPattern}`,body:t.body})):[]}async function Oh(e,t,r){return(await fetch("/api/debug/create-plan",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({feedback:e,componentName:t.componentName,sourceFile:t.sourceFile,lineNumber:t.lineNumber,detectionMethod:t.detectionMethod,element:t.element,previewUrl:r})})).json()}const Bh=12;function $h(e,t,r){if(t.length===0)return[];const s=[];return qn(e,t,r,"$",0,new Set,s),s}function _h(e,t){const r=[];for(const o of e)for(const l of $h(o.body,t,o.endpoint))r.push(l);const s=new Set,a=[];for(const o of r){const l=`${o.endpoint}\0${o.jsonPath}`;s.has(l)||(s.add(l),a.push(o))}return a.sort((o,l)=>{const c=l.matchedValue.length-o.matchedValue.length;return c!==0?c:l.pathDepth-o.pathDepth}),a}function qn(e,t,r,s,a,o,l){if(e==null)return;const c=typeof e;if(c==="string"||c==="number"||c==="boolean"){String(e)===t&&l.push({endpoint:r,jsonPath:s,matchedValue:String(e),pathDepth:a});return}if(!(a>=Bh)&&!o.has(e)){if(o.add(e),Array.isArray(e))for(let d=0;d<e.length;d++)qn(e[d],t,r,`${s}[${d}]`,a+1,o,l);else if(c==="object")for(const[d,u]of Object.entries(e))qn(u,t,r,`${s}.${d}`,a+1,o,l);o.delete(e)}}const zh={backgroundColor:"#1e1e1e",backgroundImage:"conic-gradient(#262626 25%, #1e1e1e 0 50%, #262626 0 75%, #1e1e1e 0)",backgroundSize:"16px 16px"};function Hh({buildingScenarioName:e,buildingScenarioSlug:t,buildingScreenshotPath:r,containerHeight:s,containerRef:a,containerWidth:o,currentHeight:l,currentWidth:c,emptyStateMessage:d,isFilled:u,onDismissBuildingOverlay:f,previewSlug:p,previewUrl:m,previewOrigin:h,scale:j,commandNonce:b}){const g=i.useRef(null),w=a??g,v=i.useRef(null),{status:x,restart:y}=Vo();px(x,y);const{isRestarting:N,isFailed:C,isStarting:S,isStopped:k}=Tx(x),{stepState:R}=Lt(),E=Mx((R==null?void 0:R.step)??null,(R==null?void 0:R.mode)??"ui"),T=(x==null?void 0:x.liveIframeHealthy)!==void 0,{reloadNonce:M,handleIframeLoad:F,handleIframeError:I}=xx((x==null?void 0:x.pid)??null,T,x==null?void 0:x.status),z=(x==null?void 0:x.status)==="failed",{healthy:J,failedProbeCount:D,reloadNonce:O,invalidate:H}=wx(m,z),[$,K]=i.useState(0);i.useEffect(()=>Uo(()=>{K(Ee=>Ee+1)}),[]);const B=jx({pidNonce:M,probeNonce:O,draftNonce:$}),Q=B.gatedNonce,{errors:U,clear:L}=Cx(v,Q),A=Ex(m,Q),X=i.useCallback(()=>{B.reset(),L(),H()},[B,L,H]),G=Px({hasDevServerConfigured:!!(x!=null&&x.startCommand),probeHealthy:J,backendRunning:(x==null?void 0:x.status)==="running",backendIframeHealthy:x==null?void 0:x.liveIframeHealthy,isStarting:S,isRestarting:N,isFailed:C,isStopped:k,isPrePrototype:E}),ee=G==="scaffolding"?Ox((R==null?void 0:R.step)??null,(R==null?void 0:R.mode)??"ui").body:void 0,W=D>=10,{isActive:P,hoveredElement:ne,selectedElement:se,activate:ae,deactivate:ce,clearSelection:Y}=Lh(v),te=i.useCallback(()=>{P?ce():ae()},[P,ae,ce]),{entries:fe}=Ko(p??null),{isActive:ge,toggle:be}=mx({activate:ae,deactivate:ce,clearSelection:Y},M);i.useEffect(()=>(Mr({isActive:ge,previewSlug:p??null}),()=>{Mr({isActive:!1,previewSlug:null})}),[ge,p]),i.useEffect(()=>Go(()=>{be()}),[be]);const ke=ge&&se?se.element.text.trim():"",de=i.useMemo(()=>Fh(fe),[fe]),rt=i.useMemo(()=>!ge||!ke?[]:_h(de,ke),[ge,ke,de]),_e=i.useCallback(async Ee=>{Y(),ce();try{const _=await(await fetch("/api/scenarios")).json(),oe=Array.isArray(_)?_.find(ze=>ze.componentName===Ee):null;if(oe!=null&&oe.slug){const ze=Oa(window.location),pe=$a(oe.slug,ze,null,0,h);window.history.pushState(null,"",pe);return}}catch{}window.history.pushState(null,"","/entities")},[Y,ce,h]),st=i.useCallback(async(Ee,Pe)=>{try{await Oh(Ee,Pe,m),Y(),ce()}catch(_){console.error("Failed to create debug plan:",_)}},[m,Y,ce]);return n.jsx("div",{ref:w,className:`relative flex-1 flex overflow-hidden ${u?"":"items-center justify-center p-8"}`,style:u?{backgroundColor:"#fff"}:zh,children:m?n.jsxs(n.Fragment,{children:[n.jsx(fx,{ref:v,currentHeight:l,currentWidth:c,isFilled:u,previewUrl:m,scale:j,reloadNonce:Q,onLoad:()=>F(m),onError:I}),n.jsx(qx,{previewUrl:m}),n.jsx(Ah,{healthy:x==null?void 0:x.liveIframeHealthy,reason:(x==null?void 0:x.iframeLastError)??null}),P&&n.jsx(wh,{hoveredElement:ne}),ge&&n.jsx(jh,{}),se&&!ge&&n.jsx(bh,{element:se,previewUrl:m,onClose:Y,onGoToIsolated:_e,onCreatePlan:st}),se&&ge&&n.jsx(Dh,{clickedText:ke,matches:rt,anchor:se.element.boundingBox,corpusEmpty:de.length===0,onOpenInPanel:Ee=>{Yo({routeKey:Ee.endpoint,jsonPath:Ee.jsonPath}),Y()},onDismiss:Y}),!t&&n.jsx(uh,{isActive:P,onToggle:te}),z?n.jsx(ah,{lastError:(x==null?void 0:x.lastError)??(x==null?void 0:x.lastExit)??"(no error message captured)",failureCount:(x==null?void 0:x.failureCount)??0,failedAtMs:x==null?void 0:x.failedAtMs,holder:x==null?void 0:x.holder,onRetry:y,onReap:async()=>{await fetch("/api/editor-dev-server/reap",{method:"POST",headers:{"Content-Type":"application/json"}})}}):G&&(G==="crashed"?n.jsx(rh,{logs:(x==null?void 0:x.logs)??[]}):n.jsx(_x,{variant:G,restartCount:(x==null?void 0:x.restartCount)??0,showRetry:W,onRetry:H,bodyOverride:ee})),n.jsx(Xx,{tripped:B.tripped,errors:U,recentReloads:B.recentReloads,serverHealthy:Dx(x),onRetry:X,onClear:L}),A.clickThroughBroken&&A.status!==null&&n.jsx(Rx,{url:m,status:A.status,logLines:A.logLines,onRetry:X}),t&&f&&n.jsx(dh,{containerHeight:s,containerWidth:o,onDismiss:f,scenarioName:e??null,screenshotPath:r??null,viewportHeight:l,viewportWidth:c})]}):n.jsx(cx,{message:d})})}function Wh({error:e,onRetry:t}){return n.jsxs("div",{role:"alert",className:"flex items-center justify-between gap-3 border-b border-[var(--accent-red)] bg-[var(--accent-red)]/10 px-4 py-2 text-sm text-[var(--accent-red)]",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"font-semibold",children:"Seed failed — DB state is unknown"}),n.jsx("div",{className:"truncate text-xs opacity-90",children:e})]}),t?n.jsx("button",{type:"button",onClick:t,className:"shrink-0 rounded border border-[var(--accent-red)] px-2 py-1 text-xs hover:bg-[var(--accent-red)] hover:text-white",children:"Retry"}):null]})}function Vh(){return n.jsx("div",{role:"status","aria-live":"polite",className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-[var(--bg-deep)]/90 backdrop-blur-sm text-[var(--text-muted)]",children:"Loading scenario..."})}function Uh({emptyStateMessage:e,previewSlug:t,previewUrl:r,viewports:s,activeViewport:a,onViewportChange:o,isCollapsed:l,onToggleCollapsed:c,isFilled:d,onToggleFilled:u,currentWidth:f,currentHeight:p,onCustomSizeChange:m,buildingScenarioSlug:h,buildingScreenshotPath:j,buildingScenarioName:b,onDismissBuildingOverlay:g,previewSeeding:w,previewSeedError:v,onRetrySeed:x,currentScenario:y,scenarioGroups:N,onShowScenarioPreview:C,commandNonce:S,previewOrigin:k}){const[R,E]=i.useState(!1),{containerRef:T,containerSize:M,scale:F}=tm({currentHeight:p,currentWidth:f,isFilled:d});i.useEffect(()=>{ut()||Qp(v??null)},[v]);const I=r?Cr(r):"",z=I==="/results"||I.startsWith("/results/"),J=I==="/plan-preview",D=I==="/design-exploration";return J?n.jsx(lx,{}):z?n.jsx(Em,{}):D?n.jsx(Dm,{}):n.jsxs("div",{"data-preview-pane":"true",className:"flex-1 flex flex-col min-w-0",children:[n.jsx(Ym,{viewports:s,active:a,onChange:o,currentWidth:f,currentHeight:p,previewUrl:r,isCollapsed:l,onToggleCollapsed:c,isFilled:d,onToggleFilled:u,containerWidth:(M==null?void 0:M.width)??null,containerHeight:(M==null?void 0:M.height)??null,onCustomSizeChange:m,currentScenario:y??null,scenarioGroups:N??[],onShowScenarioPreview:C??(()=>{}),onCreateStateRequest:()=>E(!0)}),v?n.jsx(Wh,{error:v,onRetry:x}):null,n.jsxs("div",{className:"relative flex-1 flex flex-col min-h-0",children:[n.jsx(Hh,{containerRef:T,containerHeight:M==null?void 0:M.height,containerWidth:M==null?void 0:M.width,currentHeight:p,currentWidth:f,emptyStateMessage:e??"Select a scenario to preview",isFilled:d,previewSlug:t,previewUrl:r,previewOrigin:k,scale:F,buildingScenarioSlug:h,buildingScreenshotPath:j,buildingScenarioName:b,onDismissBuildingOverlay:g,commandNonce:S}),w?n.jsx(Vh,{}):null]}),R?n.jsx(Rm,{onClose:()=>E(!1)}):null]})}function Kh(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),{scenariosVersion:l}=Rt(),c=i.useCallback(async()=>{s(!0),o(null);try{const u=await fetch("/api/scenarios");if(!u.ok)throw new Error(`HTTP ${u.status}`);const f=(await u.json()).map(nr);t(za(f))}catch(u){o(u instanceof Error?u.message:"Failed to load scenarios")}finally{s(!1)}},[]);i.useEffect(()=>{c()},[c,l]);const d=e.reduce((u,f)=>u+f.scenarios.length,0);return{groups:e,loading:r,error:a,totalScenarios:d,reload:c}}function Gh(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),{scenariosVersion:l}=Rt(),c=i.useCallback(async()=>{s(!0),o(null);try{const d=await fetch("/api/app-route-entities");if(!d.ok)throw new Error(`HTTP ${d.status}`);const u=await d.json();t(Array.isArray(u)?u.map(f=>({...f,scenarios:Array.isArray(f==null?void 0:f.scenarios)?f.scenarios.map(nr):[]})):[])}catch(d){o(d instanceof Error?d.message:"Failed to load app routes"),t([])}finally{s(!1)}},[]);return i.useEffect(()=>{c()},[c,l]),{routeEntities:e,loading:r,error:a,reload:c}}function ks(e){const t=new Map;for(const r of e){const s=Yh(r.path);let a=t.get(s);a||(a=[],t.set(s,a));for(const o of r.tests)a.push({...o,file:r.path})}return Array.from(t.entries()).map(([r,s])=>({feature:r,tests:s})).filter(r=>r.tests.length>0).sort((r,s)=>r.feature.localeCompare(s.feature))}function Yh(e){const r=e.replace(/\\/g,"/").replace(/^\.\//,"").split("/").filter(s=>s.length>0);return r.length===0?"Other":r[0]==="crates"&&r.length>=2?`crates/${r[1]}`:e==="(no-file)"?"(no-file)":r[0]}function Va(e,t){if(t===".")return e;const r=t.endsWith("/")?t:`${t}/`;return e.map(s=>({feature:s.feature,tests:s.tests.filter(a=>a.file.startsWith(r))})).filter(s=>s.tests.length>0)}function Ua(e,t,r){return r==="backend"?[]:e.map(s=>({...s,scenarios:s.scenarios.filter(Qe)})).filter(s=>s.scenarios.length>0)}function Ka(e){let t=0,r=0,s=0,a=0,o=0;for(const l of e)for(const c of l.tests)o+=1,t+=1,c.status==="passed"?r+=1:c.status==="skipped"?a+=1:c.status==="failed"&&(s+=1);return{total:t,passed:r,failed:s,ignored:a,discovered:o}}function Jh(e){return e.reduce((t,r)=>t+r.scenarios.length,0)}const Xh=3e3;function qh(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(!1),[l,c]=i.useState(null),[d,u]=i.useState(!1),[f,p]=i.useState(null),[m,h]=i.useState(null),[j,b]=i.useState(null),g=i.useRef(null),w=i.useRef(null),v=i.useRef(!1),x=i.useRef(null),{testsVersion:y}=Rt(),N=i.useCallback(async(M=!1)=>{var J;(J=g.current)==null||J.abort();const F=new AbortController;g.current=F;const{signal:I}=F;M&&(v.current=!0,o(!0));const z=!M&&x.current!==null;z||(s(!0),c(null));try{if(!M&&!z)try{const $=await fetch("/api/test-results/summary",{signal:I});if($.ok){const K=await $.json();K.running?p(K.currentRunner??null):K.stats&&(h(K.stats),b(K.coverage??null))}}catch{}let D,O;if(z){D=x.current;const $=await fetch("/api/test-results",{signal:I});if(!$.ok)throw new Error(`test-results: HTTP ${$.status}`);O=await $.json()}else if(M){const $=await fetch("/api/test-results/refresh",{method:"POST",signal:I});if(!$.ok)throw new Error(`test-results: HTTP ${$.status}`);O=await $.json(),D=x.current??[]}else{const[$,K]=await Promise.all([fetch("/api/tests",{signal:I}),fetch("/api/test-results",{signal:I})]);if(!$.ok)throw new Error(`tests: HTTP ${$.status}`);if(!K.ok)throw new Error(`test-results: HTTP ${K.status}`);D=ks(await $.json()),O=await K.json(),x.current=D}if(p(O.currentRunner??null),O.running&&v.current){w.current=setTimeout(()=>N(!1),Xh);return}const H=v.current;if(v.current=!1,H){const $=await fetch("/api/tests",{signal:I});$.ok&&(D=ks(await $.json()),x.current=D)}t(D),u(O.cached??!1),b(O.coverage??null),h(null),s(!1),o(!1)}catch(D){if(D instanceof DOMException&&D.name==="AbortError")return;v.current=!1,c(D instanceof Error?D.message:"Failed to load tests"),s(!1),o(!1)}},[]);i.useEffect(()=>(x.current=null,N(),()=>{var M;(M=g.current)==null||M.abort(),w.current&&clearTimeout(w.current)}),[N,y]);const{total:C,passed:S,failed:k,ignored:R,discovered:E}=i.useMemo(()=>Ka(e),[e]),T=i.useCallback(()=>{v.current||N(!0)},[N]);return{groups:e,loading:r,refreshing:a,error:l,cached:d,currentRunner:f,summaryStats:m,coverage:j,totalTests:C,passedTests:S,failedTests:k,ignoredTests:R,discoveredTests:E,reload:N,refresh:T}}function kr(e,t){return e.filter(r=>r.appDir===t)}function Ga(e,t){return t?e.find(r=>r.route===t)??null:null}function Ya(e,t,r){const s=Ua(e,t,r);return eg(s)}function Qh(e){const t=e.filter(o=>o.defaultScenarioSlug);if(t.length===0)return null;const r=t.find(o=>o.route==="/"&&o.defaultScenarioSlug);if(r!=null&&r.defaultScenarioSlug)return r.defaultScenarioSlug;const s=t.find(o=>o.defaultScenarioSlug&&o.scenarios.some(l=>Qn(l)));if(s!=null&&s.defaultScenarioSlug)return s.defaultScenarioSlug;const a=[...t].sort((o,l)=>o.route.length-l.route.length||o.route.localeCompare(l.route))[0];return(a==null?void 0:a.defaultScenarioSlug)??null}function Zh(e){return(e==null?void 0:e.defaultScenarioSlug)??null}function Ja(e,t){const r=e.find(s=>s.type==="web");return r?Ya(t,r.dir,r.type):null}function eg(e){const t=e.flatMap(c=>c.scenarios.filter(d=>Qe(d)).map(d=>({route:c.route,scenario:d})));if(t.length===0)return null;const r=t.find(({route:c,scenario:d})=>c==="/"&&Qn(d));if(r)return r.scenario.slug;const s=t.find(({route:c})=>c==="/");if(s)return s.scenario.slug;const a=t.find(({scenario:c})=>Qn(c));if(a)return a.scenario.slug;let o=null,l=1/0;for(const c of e)if(!(c.route.length>=l)){for(const d of c.scenarios)if(Qe(d)){o=d.slug,l=c.route.length;break}}return o}function Qn(e){return/\bhome\b/i.test(e.name)}function Es(e){return new Set(e.flatMap(t=>t.scenarios.map(r=>r.slug)))}function In({selectedApp:e,appRouteEntities:t,scenarioGroups:r}){return e?Qh(t)??Ya(r,e.dir,e.type):null}function tg({apps:e,hasExplicitAppSelection:t,scenarioGroups:r}){return t||e.length===0||r.length===0?null:Ja(e,r)}function Rs(e){return Zh(e)}function ng({apps:e,routeEntities:t,selectedApp:r,appRouteEntities:s}){if(r)return s;const a=e.find(o=>o.type==="web");return a?kr(t,a.dir):[]}function rg({previewRouteEntities:e,selectedRouteEntity:t}){var s;if(t!=null&&t.route)return t.route;if(e.length===0)return null;const r=e.find(a=>a.route==="/");return r?r.route:((s=[...e].sort((a,o)=>a.route.length-o.route.length||a.route.localeCompare(o.route))[0])==null?void 0:s.route)??null}function sg({previewRouteEntities:e,path:t}){var s;const r=Cr(t);return((s=Ga(e,r))==null?void 0:s.defaultScenarioSlug)??null}function ag(e){return e.startsWith("/scenario/")||e.startsWith("/isolated-components/")}function og(e){return ag(e)?!1:e==="/"||e==="/apps"||e==="/apps/"}function ig(e,t,r=""){const s=jn(r),[a,o]=i.useState(s.selectedAppDir),[l,c]=i.useState(s.selectedEntityHash);i.useEffect(()=>{const v=jn(r);o(x=>x===v.selectedAppDir?x:v.selectedAppDir),c(x=>x===v.selectedEntityHash?x:v.selectedEntityHash)},[r]),i.useEffect(()=>{if(typeof window>"u"||e.length!==1)return;const v=jn(r);if(v.selectedAppDir||v.selectedEntityHash||!og(r))return;const x=Nn(e[0].dir);`${window.location.pathname}${window.location.search}`!==x&&(window.history.replaceState({},"",x),o(e[0].dir))},[e,r]);const d=i.useMemo(()=>l?t.find(v=>Bn(v)===l)??null:null,[t,l]),u=i.useMemo(()=>a?e.find(v=>v.dir===a)??null:d?e.find(v=>v.dir===d.appDir)??null:l?e.find(v=>v.type==="web")??e[0]??null:null,[e,a,d,l]),f=i.useMemo(()=>u?kr(t,u.dir):[],[t,u]),p=i.useMemo(()=>l?d:null,[l,d]);function m(v){if(typeof window>"u")return;const x=`${window.location.pathname}${window.location.search}`;v!==x&&window.history.pushState({},"",v)}function h(v){o(v),c(null),m(Nn(v))}function j(){o(null),c(null),m("/apps")}function b(v){const x=f.find(C=>C.route===v);if(!x)return;const y=Bn(x),N=zs(x);!y||!N||(c(y),m(N))}function g(v){c(v),m(`/entities/${v}`)}function w(){c(null),m(a?Nn(a):"/apps")}return{selectedApp:u,appRouteEntities:f,selectedEntityHash:l,selectedRouteEntity:p,selectApp:h,deselectApp:j,selectRoute:b,selectEntity:g,deselectRoute:w}}function lg(e,t,r,s,a=""){const[o,l]=i.useState(null),c=i.useRef(!1),d=i.useRef(!1),{selectedApp:u,appRouteEntities:f,selectedEntityHash:p,selectedRouteEntity:m,selectApp:h,deselectApp:j,selectRoute:b,selectEntity:g,deselectRoute:w}=ig(e,t,a),v=i.useMemo(()=>Es(f),[f]),x=i.useMemo(()=>Es(m?[m]:[]),[m]),y=i.useMemo(()=>In({selectedApp:u,appRouteEntities:f,scenarioGroups:r}),[f,r,u]),N=i.useMemo(()=>Rs(m),[m]),C=i.useMemo(()=>u?Va(s,u.dir):[],[s,u]);i.useEffect(()=>{if(c.current)return;const F=tg({apps:e,scenarioGroups:r,hasExplicitAppSelection:!!u});F&&(l(F),c.current=!0)},[e,r,u]),i.useEffect(()=>{if(u){if(d.current){d.current=!1;return}if(m){if(!N||o&&x.has(o))return;l(N);return}y&&(o&&v.has(o)||l(y))}},[y,N,o,u,v,m,x]);function S(F){h(F);const I=e.find(J=>J.dir===F);if(!I)return;const z=In({selectedApp:I,appRouteEntities:kr(t,I.dir),scenarioGroups:r});l(z)}function k(){j(),l(Ja(e,r))}function R(F){b(F);const I=Rs(Ga(f,F));l(I)}const E=i.useCallback(F=>{d.current=!0,l(F)},[]);function T(){if(w(),!u)return;const F=In({selectedApp:u,appRouteEntities:f,scenarioGroups:r});F&&l(F)}function M(F){g(F)}return{selectedApp:u,appRouteEntities:f,appTestGroups:C,selectedEntityHash:p,selectedRouteEntity:m,previewSlug:o,setPreviewSlug:l,setPreviewSlugExplicit:E,selectApp:S,deselectApp:k,selectRoute:R,selectEntity:M,deselectRoute:T}}const cg=1e3;function dg(e){const t=i.useRef(e);t.current=e,i.useEffect(()=>{let r=!0;async function s(){if(r){try{const a=await fetch("/api/editor-commands");if(a.ok){const o=await a.json();for(const l of o)t.current(l)}}catch{}r&&setTimeout(s,cg)}}return s(),()=>{r=!1}},[])}function ug(){const[e,t]=i.useState({}),[r,s]=i.useState(!0),[a,o]=i.useState(null);i.useEffect(()=>{let c=!1;return fetch("/api/dependency-graph").then(d=>{if(!d.ok)throw new Error(`HTTP ${d.status}`);return d.json()}).then(d=>{if(c)return;const u="files"in d?d.files:d;t(u),s(!1)}).catch(d=>{c||(o(d.message),s(!1))}),()=>{c=!0}},[]);const l=i.useMemo(()=>Ti(e),[e]);return{graph:e,entityLookup:l,loading:r,error:a}}const fg=["/apps","/entities","/app","/build","/history","/settings","/plan"];function Xa(e){if(!e)return!1;const t=Cr(e);return fg.some(r=>t===r||t.startsWith(`${r}/`))}function pg(e,t,r){const s=typeof window<"u"?Oa(window.location):0;let a="";if(sn(e)==="component"?a=$a(e.slug,s,e.url,t,r):e.url&&(a=Ba(e.url,{appPort:t,currentPort:s,previewOrigin:r})),a&&!Xa(a))try{const o=!a.startsWith("http"),l=typeof window<"u"?window.location.origin:"http://localhost",c=new URL(a,l);return c.searchParams.set("_codeyam_scenario",e.slug),o?c.pathname+c.search+c.hash:c.toString()}catch{return a}return a}function mg(e,t,r){return e.startsWith("http")||e?e:r?`${r}/results`:`http://localhost:${t}/results`}function xg(e,t,r){return e.startsWith("http")||e?e:r?`${r}/plan-preview`:`http://localhost:${t}/plan-preview`}function qa(e,t){if(!t)return null;for(const r of e)for(const s of r.scenarios)if(s.slug===t||s.id===t)return s;return null}function hg({directPreviewPath:e,fallbackPreviewPath:t,previewKind:r,selectedScenario:s,port:a,previewOrigin:o}){return r==="blank"?"":e&&(r==="application"||r==="results"||r==="plan-preview")?r==="results"?mg(e,a,o):r==="plan-preview"?xg(e,a,o):e.startsWith("http")?e:o?`${o}${e}`:`http://localhost:${a}${e}`:s?pg({slug:s.slug,scenarioType:s.scenarioType,componentName:s.componentName,url:s.url},a,o):t?t.startsWith("http")?t:o?`${o}${t}`:`http://localhost:${a}${t}`:""}function gg(e,t=Date.now()){const r=e.includes("?")?"&":"?";return`${e}${r}_cb=${t}`}function Zn(e,t){if(!e)return null;for(const r of t)for(const s of r.scenarios)if(s.slug===e)return s;return null}function vg({apps:e,appRouteEntities:t,directPreviewPath:r,fallbackPort:s,previewKind:a,previewOrigin:o,previewSlug:l,routeEntities:c,scenarioGroups:d,selectedApp:u,selectedRouteEntity:f}){const p=qa(d,l),m=ng({apps:e,routeEntities:c,selectedApp:u,appRouteEntities:t}),h=rg({previewRouteEntities:m,selectedRouteEntity:f}),j=e.some(w=>w.type==="web");let b="blank";a==="plan-preview"&&r?b="plan-preview":a==="results"&&r?b="results":a==="application"&&r?b="application":p?b=Qe(p)?"application":"component":h&&(b="application");const g=hg({directPreviewPath:r,fallbackPreviewPath:h,previewKind:b,selectedScenario:p,port:s,previewOrigin:o});return{selectedScenario:p,previewRouteEntities:m,fallbackPreviewPath:h,resolvedPreviewKind:b,basePreviewUrl:g,hasWebApp:j}}function bg({allowEditorRoutePreview:e,command:t,configLoaded:r,previewRouteEntities:s,scenarioGroups:a,selectedScenario:o}){const l=t.dimension??null,c=!!t.dimension,d=t.commandNonce;if(t.scenarioSlug??t.scenarioId){const b=t.scenarioSlug??t.scenarioId,g=qa(a,b);return g?{clearCustomSize:c,scenarioSlug:g.slug,type:"show-scenario",viewportName:l,commandNonce:d}:t.path?{clearCustomSize:c,path:t.path,previewKind:"application",previewSlug:null,preserveDirectPreviewPathOnSlugChange:!0,type:"show-path",viewportName:l,commandNonce:d}:{clearCustomSize:c,scenarioSlug:b,type:"show-scenario",viewportName:l,commandNonce:d}}if(!t.path)return{clearCustomSize:c,type:"refresh",viewportName:l,commandNonce:d};const u=t.path,f=u.startsWith("http")?new URL(u).pathname:u.split("?")[0]??u,p=f==="/results"||f.startsWith("/results/"),m=f==="/plan-preview",h=Xa(u);if(m)return{clearCustomSize:c,path:u,previewKind:"plan-preview",previewSlug:null,preserveDirectPreviewPathOnSlugChange:!1,type:"show-path",viewportName:l,commandNonce:d};if(p)return{clearCustomSize:c,path:u,previewKind:"results",previewSlug:null,preserveDirectPreviewPathOnSlugChange:!1,type:"show-path",viewportName:l,commandNonce:d};if(h&&!e)return{clearCustomSize:c,type:r?"ignore":"defer",viewportName:l,commandNonce:d};if(h&&e)return{clearCustomSize:c,path:u,previewKind:"application",previewSlug:null,preserveDirectPreviewPathOnSlugChange:!0,type:"show-path",viewportName:l,commandNonce:d};const j=sg({previewRouteEntities:s,path:u});return j?{clearCustomSize:c,scenarioSlug:j,type:"show-scenario",viewportName:l,commandNonce:d}:{clearCustomSize:c,path:u,previewKind:"application",previewSlug:!o||!Qe(o)?null:void 0,preserveDirectPreviewPathOnSlugChange:!1,type:"show-path",viewportName:l,commandNonce:d}}function yg(e,t,r,s,a){const o=s.dimensions;return o.length===0||o.includes(e)&&t===null&&r===null?null:o.find(l=>a.some(c=>c.name===l))??o[0]}const wg=[{name:"Desktop",width:1440,height:900},{name:"Laptop",width:1024,height:768},{name:"Tablet",width:768,height:1024},{name:"Mobile",width:375,height:667}];function jg(e,t){const r=Object.entries(e);if(r.length===0)return wg;const s=r.map(([a,o])=>({name:a,width:o.width,height:o.height}));if(t){const a=s.findIndex(o=>o.name===t);if(a>0){const[o]=s.splice(a,1);s.unshift(o)}}return s}function Ng({isInIframe:e,persistedPath:t,previewKind:r,resolvedViewport:s,selectedScenario:a}){i.useEffect(()=>{e||fetch("/api/editor-preview-state",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind:r==="blank"?null:r,path:t,scenarioSlug:(a==null?void 0:a.slug)??null,scenarioId:(a==null?void 0:a.id)??null,dimension:s.name,width:s.width,height:s.height})}).catch(()=>{})},[e,t,r,s.height,s.name,s.width,a==null?void 0:a.id,a==null?void 0:a.slug])}function Cg({isInIframe:e,onActivated:t,previewKind:r,scenariosLoaded:s,selectedScenario:a}){const[o,l]=i.useState(!1),[c,d]=i.useState(null);return i.useEffect(()=>{if(!s||e)return;if(ed({isInIframe:e,previewKind:r,selectedScenario:a})){fetch("/api/editor-deactivate-scenario",{method:"POST"}).catch(()=>{});return}if(!a||a.scenarioType!=="application")return;let u=!1;return l(!0),d(null),fetch("/api/editor-activate-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:a.slug})}).then(async f=>{const p=await f.json().catch(()=>null);if(!u){if(!p||p.success===!1||p.seedError){d(p&&(p.seedError||p.error)||"scenario activation failed");return}t()}}).catch(f=>{u||d(f instanceof Error?f.message:String(f))}).finally(()=>{u||l(!1)}),()=>{u=!0}},[e,t,r,s,a==null?void 0:a.componentName,a==null?void 0:a.scenarioType,a==null?void 0:a.slug]),{seeding:o,seedError:c}}function Sg({apps:e,appRouteEntities:t,configLoaded:r,defaultScreenSize:s,port:a,previewOrigin:o,projectName:l,previewSlug:c,routeEntities:d,scenarioGroups:u,scenariosLoaded:f,screenSizes:p,selectedApp:m,selectedRouteEntity:h,setPreviewSlug:j}){const[b,g]=i.useState("Desktop"),[w,v]=i.useState(null),[x,y]=i.useState(null),[N,C]=i.useState(null),[S,k]=i.useState(null),[R,E]=i.useState(()=>Date.now()),[T,M]=i.useState(0),F=i.useRef(null),I=i.useRef(!1),z=i.useMemo(()=>jg(p,s),[s,p]),J=i.useMemo(()=>w!==null&&x!==null?{name:"Custom",width:w,height:x}:z.find(Y=>Y.name===b)??z[0]??{name:"Desktop",width:1440,height:900},[b,x,w,z]),D=ut(),O=l==="CodeYam Editor",{basePreviewUrl:H,fallbackPreviewPath:$,hasWebApp:K,previewRouteEntities:B,resolvedPreviewKind:Q,selectedScenario:U}=i.useMemo(()=>vg({apps:e,appRouteEntities:t,directPreviewPath:N,fallbackPort:a,previewKind:S,previewOrigin:o,previewSlug:c,routeEntities:d,scenarioGroups:u,selectedApp:m,selectedRouteEntity:h}),[e,t,N,a,S,o,c,d,u,m,h]),L=i.useMemo(()=>H?gg(H,R):"",[H,R]),A=i.useCallback(Y=>{g(Y),v(null),y(null)},[]),X=i.useCallback((Y,te)=>{v(Y),y(te)},[]),G=i.useCallback(Y=>{j(Y),C(null),k(null),E(Date.now());const te=Zn(Y,u);if(!te)return;const fe=yg(b,w,x,te,z);fe!==null&&(g(fe),v(null),y(null))},[b,x,w,u,j,z]),ee=i.useCallback(Y=>{const te=bg({allowEditorRoutePreview:O,command:Y,configLoaded:r,previewRouteEntities:B,scenarioGroups:u,selectedScenario:U});if(te.viewportName&&g(te.viewportName),te.clearCustomSize&&(v(null),y(null)),te.type==="show-scenario"){G(te.scenarioSlug),M(fe=>fe+1);return}if(te.type==="defer"){F.current=Y;return}if(te.type==="refresh"){E(Date.now()),M(fe=>fe+1);return}te.type!=="ignore"&&(te.type==="show-path"&&(k(te.previewKind),C(te.path),I.current=te.preserveDirectPreviewPathOnSlugChange,typeof te.previewSlug=="string"?j(te.previewSlug):te.previewSlug===null&&j(null)),E(Date.now()),M(fe=>fe+1))},[r,O,B,u,U,j,G]);i.useEffect(()=>{if(!r)return;const Y=F.current;Y&&(F.current=null,ee(Y))},[r,ee]),i.useEffect(()=>{if(!(!c||N===null)){if(I.current){I.current=!1;return}C(null),k(null),E(Date.now())}},[N,c]);const W=i.useMemo(()=>Q==="results"||Q==="plan-preview"?N:Q==="application"?N??(U==null?void 0:U.url)??$:null,[N,$,Q,U==null?void 0:U.url]),P=i.useCallback(()=>{E(Date.now())},[]);Ng({isInIframe:D,persistedPath:W,previewKind:Q,resolvedViewport:J,selectedScenario:U?{id:U.id??null,slug:U.slug}:null});const{seeding:ne,seedError:se}=Cg({isInIframe:D,onActivated:P,previewKind:Q,scenariosLoaded:f,selectedScenario:U?{slug:U.slug,scenarioType:U.scenarioType,componentName:U.componentName??null}:null}),ae=K?"Select a scenario to preview":"No web app is available for Live Preview.",ce=i.useCallback(Y=>{C(Y),k(Y?"application":null),E(Date.now())},[]);return{viewports:z,resolvedViewport:J,previewUrl:L,emptyStateMessage:ae,handleViewportChange:A,handleCustomSizeChange:X,showScenarioPreview:G,handlePreviewCommand:ee,setPreviewPath:ce,previewSeeding:ne,previewSeedError:se,commandNonce:T}}function kg(){const[e,t]=i.useState(!1),r=i.useCallback(()=>{t(!0)},[]),s=i.useCallback(()=>{},[]),a=i.useCallback(()=>{},[]),o=i.useCallback(()=>{t(!1)},[]);return{showPostPushModal:e,onFeatureCompleteCommand:r,onAgentIdle:s,onAgentActive:a,dismissModal:o}}function Eg(){const[e,t]=i.useState(!1),r=i.useCallback(()=>{t(!0)},[]),s=i.useCallback(()=>{t(!1)},[]);return{showPlanCompleteModal:e,onPlanCompleteCommand:r,dismissPlanCompleteModal:s}}function Rg(){const{showBuildTab:e}=jr(typeof window>"u"?"/":window.location.pathname),{config:t}=Ze(),[r,s]=i.useState(!1),[a,o]=i.useState(null),l=i.useCallback(async c=>{if(r)return!1;o(null),s(!0);try{try{await yr()}catch{}const d=await fetch("/api/build/start-from-prompt",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:c})});if(!d.ok){let u=`HTTP ${d.status}`;try{const f=await d.json();f!=null&&f.error&&(u=f.error)}catch{}throw new Error(u)}return e(),await wr({provider:t==null?void 0:t.provider}),!0}catch(d){return o(d instanceof Error?d.message:"Failed to launch build"),!1}finally{s(!1)}},[r,e,t==null?void 0:t.provider]);return{launching:r,error:a,launchPrompt:l}}function Tg({onTransitionToLive:e}){const[t,r]=i.useState(!1),[s,a]=i.useState(null),o=i.useRef(!1),l=i.useRef(null),c=i.useRef(e);c.current=e;const d=i.useCallback(()=>{o.current=!0,r(!0)},[]),u=i.useCallback(()=>{o.current=!1,r(!1);const m=l.current;m&&(l.current=null,a(null),c.current(m))},[]),f=i.useCallback(m=>o.current?(l.current=m,a(m),!0):!1,[]),p=i.useCallback(()=>{l.current=null,a(null)},[]);return{isAgentBuilding:t,isAgentBuildingRef:o,buildingScenarioSlug:s,onAgentIdle:u,onAgentActive:d,guardScenarioSelect:f,clearBuildingOverlay:p}}function Pg(e,t,r){return e.map(s=>{const a=Va(t,s.dir),o=Ua(r,s.dir,s.type),{total:l,passed:c,failed:d,ignored:u,discovered:f}=Ka(a),p=Jh(o);return{app:s,tests:{total:l,passed:c,failed:d,ignored:u,discovered:f},scenarios:{total:p,thumbnails:Dg(o)}}})}function Dg(e){const t=[];for(const r of e)for(const s of r.scenarios)if(s.screenshotPaths.length>0&&t.push(s.screenshotPaths[0]),t.length>=6)return t;return t}const Ag="No app configured yet — pick a tech stack and design system on the left to get started.";function Lg({hasNoApps:e,hasStepState:t,defaultMessage:r}){return e&&!t?Ag:r}function Ts(e,t){return(t==null?void 0:t.previewOrigin)??(e==null?void 0:e.previewOrigin)??null}function Mg(e,t){return t?{scenarioSlug:e,path:t}:{scenarioSlug:e}}function Ig(e){return e.activeTab==="build"&&!e.hasActiveSession&&!e.isAgentBuilding&&!e.showPostPushModal&&e.launchingPlanSlug===null&&!e.submittingBuildPrompt&&!e.stepStateFeature&&e.pendingPlanCount>0&&!e.buildLaunchModalDismissed}const Fg=300,Ps=150;function Og(e){const[t,r]=i.useState(null),s=i.useRef(!1),[a,o]=i.useState(!1),l=i.useCallback(()=>{var u;return((u=e.current)==null?void 0:u.clientWidth)??1200},[e]),c=t??Math.floor(l()/2),d=i.useCallback(u=>{u.preventDefault(),s.current=!0,o(!0)},[]);return i.useEffect(()=>{const u=p=>{var b;if(!s.current)return;const m=((b=e.current)==null?void 0:b.getBoundingClientRect().left)??0,h=p.clientX-m,j=l();h<Ps?r(0):h>j-Ps?r(j):r(Math.max(Fg,h))},f=()=>{s.current&&(s.current=!1,o(!1))};return document.addEventListener("mousemove",u),document.addEventListener("mouseup",f),()=>{document.removeEventListener("mousemove",u),document.removeEventListener("mouseup",f)}},[e,l]),{leftWidth:c,isDragging:a,handleMouseDown:d}}const Bg=3e3;function $g({hot:e,isInIframe:t,reload:r=()=>window.location.reload(),sustainedDisconnectMs:s=Bg}){return()=>{}}function _g(){i.useEffect(()=>$g({hot:void 0,isInIframe:ut()}),[])}async function zg(){Nt("\x1B"),await Jn(Yn),Nt("/clear\r"),await Jn(Yn),Nt("/codeyam-plan\r")}function Hg(){fetch("/api/clear-build-agent-session",{method:"POST"}).catch(()=>{})}function Wg(e){const t=i.useRef(null),r=i.useRef(null);i.useEffect(()=>{if(typeof document>"u")return;r.current||(r.current=document.createElement("canvas"),r.current.width=64,r.current.height=64);const s=document.querySelector('link[rel="icon"]');if(!s){V("favicon-redraw",{idle:e,hasIcon:!1});return}if(t.current||(t.current=s.href),!e){s.href=t.current,V("favicon-restore",{});return}V("favicon-redraw",{idle:!0,hasIcon:!0});const a=new Image;a.crossOrigin="anonymous",a.onload=()=>{const o=r.current,l=o.getContext("2d");l.clearRect(0,0,64,64);const c=56,d=(64-c)/2;l.drawImage(a,d,d,c,c);const u=12,f=64-u-1,p=u+1;l.beginPath(),l.arc(f,p,u,0,2*Math.PI),l.fillStyle="#ef4444",l.fill(),s.href=o.toDataURL("image/png")},a.src=t.current},[e]),i.useEffect(()=>()=>{if(typeof document>"u")return;const s=document.querySelector('link[rel="icon"]');s&&t.current&&(s.href=t.current)},[])}const Vg=120*1e3,Qa=1500;class Ug{constructor(t,r,s=V){Oe(this,"deferred",!1);Oe(this,"userActiveSinceLastOutput",!1);Oe(this,"lastActivitySource",null);Oe(this,"lastActivityAt",null);Oe(this,"lastNotificationTime",null);Oe(this,"actions");Oe(this,"env");Oe(this,"now");Oe(this,"log");this.actions=t,this.env=r,this.now=r.now??(()=>Date.now()),this.log=s}reportUserActivity(t){this.userActiveSinceLastOutput=!0,this.lastActivitySource=t,this.lastActivityAt=this.now()}resetActivityFlag(){this.userActiveSinceLastOutput=!1}onIdle(t,r){this.deferred=!1;const s=this.env.hasBrowserFocus(),a=this.lastNotificationTime===null?null:this.now()-this.lastNotificationTime,o=this.lastActivityAt===null?null:this.now()-this.lastActivityAt,l={buildTabActive:r,hasBrowserFocus:s,msSinceLastNotification:a,userActiveSinceLastOutput:this.userActiveSinceLastOutput,lastActivitySource:this.lastActivitySource,msSinceLastActivity:o},c=o!==null&&o<Qa;if(r&&s&&c)return this.userActiveSinceLastOutput=!1,this.log("suppressed-user-active",l),"suppressed";if(a!==null&&a<Vg)return this.log("cooldown",l),"cooldown";const d=this.notify(t);return this.log(d==="played"?"notify-played":"notify-played-no-sound",l),d}onBuildTabChange(t,r){return!t&&this.deferred?(this.deferred=!1,this.notify(r),!0):!1}onActive(){const t=this.deferred;this.deferred=!1,this.log("on-active",{hadDeferred:t}),this.actions.closeSystemNotification(),this.log("system-notification-closed-on-active",{hadDeferred:t})}onUserEngagement(){const t=this.deferred;return this.deferred=!1,t}get isDeferred(){return this.deferred}notify(t){const r=!!(t!=null&&t.sound)&&t.sound!=="off";r?(this.actions.playSound(t.sound),this.log("sound-played",{soundId:t.sound})):this.log("sound-skipped-off",{});const s=this.env.hasBrowserFocus(),a=typeof Notification<"u"?Notification.permission:"unknown";return!s&&(t!=null&&t.systemNotification)?this.env.hasNotificationPermission()?(this.actions.showSystemNotification(),this.log("system-notification-shown",{notificationPermission:a})):this.log("system-notification-skipped-no-permission",{notificationPermission:a}):s&&this.log("system-notification-skipped-focus",{notificationPermission:a}),this.lastNotificationTime=this.now(),r?"played":"played-no-sound"}}function Kg(e,t){return new Ug({playSound:Xs,showSystemNotification:()=>{if(typeof Notification>"u"||Notification.permission!=="granted")return;t.current&&t.current.close();const r=e.current,s=new Notification(`${r} is ready for you`,{body:`${r} has finished and is waiting for your input.`,tag:"build-agent-idle"});s.onclick=()=>{window.focus(),s.close(),t.current=null},t.current=s},closeSystemNotification:()=>{typeof Notification>"u"||t.current&&(t.current.close(),t.current=null)}},{hasBrowserFocus:()=>document.hasFocus(),hasNotificationPermission:()=>typeof Notification<"u"&&Notification.permission==="granted"})}function Gg(e,t){return e==="hook-stop"?t.idleOnStop:t.idleOnNotification}const Yg=600*1e3,Jg=3e3;function Xg({agentName:e,isBuildTabActive:t,isAgentBuilding:r,buildSessionLive:s,featureCompleteKey:a,navigateToTab:o,onAgentIdleImmediate:l,onAgentActiveImmediate:c}){const d=i.useRef(e);d.current=e;const u=i.useRef(t);u.current=t;const f=i.useRef(l);f.current=l;const p=i.useRef(c);p.current=c;const[m,h]=i.useState(_l),[j,b]=i.useState(!1),g=i.useRef(!1);g.current=j;const w=i.useRef(!1),v=i.useRef(null),x=i.useRef(null),y=i.useRef(null),N=i.useRef(typeof document<"u"&&document.hidden?Date.now():null),C=i.useRef(null),S=i.useRef(s??!1);S.current=s??!1,Wg(j),y.current||(y.current=Kg(d,x));const k=i.useCallback(D=>{h(D),zl(D)},[]),R=i.useCallback(D=>{v.current!==null&&(clearTimeout(v.current),v.current=null,V("debounce-cancelled",{trigger:D}))},[]),E=i.useCallback(D=>{g.current&&V("idle-cleared",{trigger:D}),b(!1),g.current=!1,C.current=null,x.current&&(x.current.close(),x.current=null)},[]),T=i.useCallback(D=>{var O;if(!Gg(D,m)){V("idle-suppressed-by-pref",{source:D});return}V("ws-idle-received",{buildTabActive:u.current,source:D}),(O=f.current)==null||O.call(f),R("re-arm-on-idle"),v.current=setTimeout(()=>{var B;v.current=null;const H=N.current,$=H===null?null:Date.now()-H,K=H!==null&&Date.now()-H>Yg;V("debounce-resolved",{suppressedForOvernight:K,msHidden:$,buildTabActive:u.current}),K||(B=y.current)==null||B.onIdle(m,u.current),b(!0),g.current=!0,C.current=Date.now(),w.current=!1,V("agent-currently-idle-set",{suppressedForOvernight:K}),u.current&&He()},Qa)},[m,R]),M=i.useCallback(()=>{var D,O,H;(D=p.current)==null||D.call(p),R("agent-active"),(O=y.current)==null||O.onActive(),(H=y.current)==null||H.resetActivityFlag(),g.current&&S.current&&C.current!==null&&Date.now()-C.current>Jg&&E("remote-resume")},[R,E]),F=i.useCallback(()=>{var D,O;R("user-input"),g.current&&((D=y.current)==null||D.onUserEngagement(),(O=y.current)==null||O.reportUserActivity("terminal-input"),w.current=!0,E("user-input"))},[R,E]),I=i.useCallback(D=>{var O;D==="build"&&(R("navigate-build"),g.current&&((O=y.current)==null||O.onUserEngagement(),w.current=!0,E("navigate-build"))),o(D)},[o,R,E]),z=i.useCallback(()=>{var D;R("dismiss-banner"),(D=y.current)==null||D.onUserEngagement(),w.current=!0,E("dismiss-banner")},[R,E]);i.useEffect(()=>{function D(){var L;g.current&&(w.current||(R("ack-notification"),(L=y.current)==null||L.onUserEngagement(),w.current=!0,V("notification-acknowledged",{trigger:"user-return"})))}function O(L){var A;g.current&&u.current&&document.hasFocus()&&(document.hidden||((A=y.current)==null||A.onUserEngagement(),w.current=!0,E(L)))}function H(L){var A;document.hasFocus()&&D(),(A=y.current)==null||A.reportUserActivity(L)}const $=()=>H("mousemove"),K=()=>H("mousedown"),B=()=>H("keydown");function Q(){document.hidden?N.current===null&&(N.current=Date.now()):(N.current=null,D(),O("tab-visible-on-build"))}function U(){var L;D(),O("window-focus-on-build"),(L=y.current)==null||L.reportUserActivity("focus")}return window.addEventListener("focus",U),document.addEventListener("visibilitychange",Q),document.addEventListener("mousemove",$),document.addEventListener("mousedown",K),document.addEventListener("keydown",B),()=>{R("unmount"),window.removeEventListener("focus",U),document.removeEventListener("visibilitychange",Q),document.removeEventListener("mousemove",$),document.removeEventListener("mousedown",K),document.removeEventListener("keydown",B)}},[R,E]);const J=i.useRef(a??0);return i.useEffect(()=>{var H;const D=a??0;if(D===J.current)return;J.current=D;const O=u.current&&document.hasFocus();V("feature-complete-fast-path",{skipBecauseWatching:O}),!O&&((H=y.current)==null||H.onIdle(m,!1),b(!0),g.current=!0,C.current=Date.now(),w.current=!1)},[a,m]),i.useEffect(()=>{var D,O;if((D=y.current)==null||D.onBuildTabChange(t,m),t)return g.current&&typeof document<"u"&&document.hasFocus()&&!document.hidden&&((O=y.current)==null||O.onUserEngagement(),w.current=!0,E("build-tab-active-on-focus")),He()},[t,m,E]),{buildIdle:j,bannerVisible:j,notifSettings:m,handleSettingsChange:k,handleAgentIdle:T,handleAgentActive:M,handleUserInput:F,handleNavigateToTab:I,dismissIdleBanner:z}}const qg=1e4;function Qg(e){const{isAgentBuilding:t,submittingBuildPrompt:r,launchingPlanSlug:s,sessionInfo:a,refetchSessionInfo:o}=e,[l,c]=i.useState(!1),d=i.useRef(!1),u=i.useCallback((f,p)=>{d.current!==f&&(V("build-session-live-change",{from:d.current,to:f,trigger:p}),d.current=f,c(f))},[]);return i.useEffect(()=>{t&&u(!0,"agent-active")},[t,u]),i.useEffect(()=>{r&&u(!0,"launch-prompt")},[r,u]),i.useEffect(()=>{s!==null&&u(!0,"launch-plan")},[s,u]),i.useEffect(()=>{(a==null?void 0:a.hasSession)===!0&&u(!0,"session-detected")},[a,u]),i.useEffect(()=>{(a==null?void 0:a.agentBrokerLive)===!0&&u(!0,"broker-live-detected")},[a,u]),i.useEffect(()=>{a&&!a.hasSession&&!a.agentBrokerLive&&u(!1,"session-ended")},[a,u]),i.useEffect(()=>{if(!l)return;const f=setInterval(()=>{o()},qg);return()=>clearInterval(f)},[l,o]),{buildSessionLive:l,transitionBuildSessionLive:u}}function Ds(e){const{isAgentBuilding:t,trigger:r,transitionBuildSessionLive:s}=e;if(t){V("build-session-live-suppress-clear",{trigger:r,reason:"agent-still-active"});return}s(!1,r)}function Zg(){const[e,t]=i.useState({loading:!1,error:null,downloaded:!1}),r=i.useCallback(async a=>{t({loading:!0,error:null,downloaded:!1});try{const l=await(await fetch("/api/editor-transcript-package")).json();if(!l.success){t({loading:!1,error:l.error||"Failed to package transcript",downloaded:!1});return}let c=l.content;a!=null&&a.trim()&&(c=`## User Notes
33
+
34
+ ${a.trim()}
35
+
36
+ ${c}`);const d=new Blob([c],{type:"text/markdown"}),u=URL.createObjectURL(d),f=document.createElement("a");f.href=u,f.download=l.filename,document.body.appendChild(f),f.click(),document.body.removeChild(f),URL.revokeObjectURL(u),t({loading:!1,error:null,downloaded:!0})}catch(o){t({loading:!1,error:o instanceof Error?o.message:"Network error",downloaded:!1})}},[]),s=i.useCallback(()=>{t({loading:!1,error:null,downloaded:!1})},[]);return{...e,sendTranscript:r,reset:s}}function ev(e,t){var o;const r="feedback@codeyam.com",s=encodeURIComponent(`CodeYam Session Feedback: ${e||"Session"}`+(t!=null&&t.category?` [${t.category}]`:"")),a=encodeURIComponent([((o=t==null?void 0:t.note)==null?void 0:o.trim())||"(no note)","","(Please attach the downloaded transcript file.)"].join(`
37
+
38
+ `));return`mailto:${r}?subject=${s}&body=${a}`}const tv=["bug","suggestion","question","praise"];function nv({featureName:e,onClose:t}){const[r,s]=i.useState(""),[a,o]=i.useState(null),[l,c]=i.useState(!1),{loading:d,error:u,downloaded:f,sendTranscript:p}=Zg(),m=i.useCallback(()=>{p(r)},[p,r]),h=i.useCallback(()=>{navigator.clipboard.writeText("feedback@codeyam.com").then(()=>{c(!0),setTimeout(()=>c(!1),2e3)})},[]),j=i.useCallback(b=>{o(g=>g===b?null:b)},[]);return n.jsxs("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] mb-2",children:"Send Session Transcript"}),n.jsx("p",{className:"text-sm text-[var(--text-muted)] mb-4",children:"Download your session transcript and send it to the CodeYam team for feedback or debugging."}),n.jsxs("div",{className:"mb-3",children:[n.jsx("span",{className:"block text-xs text-[var(--text-muted)] mb-1.5",children:"Tag (optional)"}),n.jsx("div",{className:"flex flex-wrap gap-1.5",children:tv.map(b=>{const g=a===b;return n.jsx("button",{type:"button","aria-pressed":g,onClick:()=>j(b),className:"px-2.5 py-1 rounded-full text-xs transition cursor-pointer",style:{background:g?"var(--accent-active)":"transparent",color:g?"var(--bg-deep)":"var(--text-secondary)",border:"1px solid var(--border-default)"},children:b},b)})})]}),n.jsx("textarea",{value:r,onChange:b=>s(b.target.value),placeholder:"What's on your mind? (optional)",className:"w-full h-20 px-3 py-2 text-sm rounded-md mb-4 resize-none",style:{background:"var(--bg-input, var(--bg-deep))",color:"var(--text-primary)",border:"1px solid var(--border-default)"}}),u&&n.jsx("p",{className:"text-sm text-red-400 mb-3",children:u}),n.jsxs("div",{className:"flex flex-col gap-3",children:[f?n.jsxs(n.Fragment,{children:[n.jsx("p",{className:"text-sm text-green-400 text-center",children:"Transcript downloaded!"}),n.jsx("a",{href:ev(e,{note:r,category:a}),className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition text-center block",style:{background:"var(--accent-active)",color:"var(--bg-deep)"},children:"Open Email Client"}),n.jsx("button",{onClick:h,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition",style:{background:"transparent",color:"var(--text-secondary)",border:"1px solid var(--border-default)"},type:"button",children:l?"Copied!":"Copy Email Address"}),n.jsx("p",{className:"text-xs text-[var(--text-dim)] text-center",children:"Attach the downloaded file to your email"})]}):n.jsx("button",{onClick:m,disabled:d,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition",style:{background:"var(--accent-active)",color:"var(--bg-deep)",opacity:d?.6:1},type:"button",children:d?"Packaging transcript...":"Download Transcript"}),n.jsx("button",{onClick:t,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition",style:{background:"transparent",color:"var(--text-secondary)",border:f?"none":"1px solid var(--border-default)"},type:"button",children:f?"Done":"Cancel"})]})]})}function rv(){var Lr;_g();const e=Is(),{activeTab:t,buildActivated:r,planActivated:s,navigateToTab:a,showBuildTab:o}=jr(e),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[f,p]=i.useState(0),[m,h]=i.useState(0),[j,b]=i.useState(0),{showPostPushModal:g,onFeatureCompleteCommand:w,onAgentIdle:v,onAgentActive:x,dismissModal:y}=kg(),{showPlanCompleteModal:N,onPlanCompleteCommand:C,dismissPlanCompleteModal:S}=Eg(),[k,R]=i.useState(!1),[E,T]=i.useState(!1),[M,F]=i.useState(!1),I=i.useCallback(()=>{F(!0)},[]),z=i.useCallback(()=>{F(!1)},[]),{plans:J,loading:D,error:O,refetch:H}=br(),{reorderPlans:$}=Ia(H),{launchPlan:K,launchingSlug:B,error:Q}=Nr(),{launchPrompt:U,launching:L,error:A}=Rg(),{sessionInfo:X,refetch:G}=ka({pollIntervalMs:15e3}),[ee,W]=i.useState(!1),{stepState:P}=Lt(),ne=i.useRef(null),{leftWidth:se,handleMouseDown:ae}=Og(ne),{entityLookup:ce}=ug(),{groups:Y,loading:te,refreshing:fe,currentRunner:ge,coverage:be,refresh:ke}=qh(),{groups:de,loading:rt,reload:_e}=Kh(),{routeEntities:st,loading:Ee,error:Pe}=Gh(),{config:_,apps:oe,loading:ze,refetch:pe}=Ze(),Ge=i.useMemo(()=>Pg(oe,Y,de),[oe,de,Y]),dn=i.useCallback(()=>{c(Z=>!Z)},[]),un=i.useCallback(()=>{u(Z=>!Z)},[]),{selectedApp:De,appRouteEntities:xt,appTestGroups:fn,selectedEntityHash:It,selectedRouteEntity:Ft,previewSlug:Ve,setPreviewSlugExplicit:pn,selectApp:re,deselectApp:he,selectRoute:me,selectEntity:Le,deselectRoute:ye}=lg(oe,st,de,Y,e),{viewports:ve,resolvedViewport:we,previewUrl:Ue,emptyStateMessage:ie,handleViewportChange:Me,handleCustomSizeChange:Re,showScenarioPreview:je,handlePreviewCommand:xe,setPreviewPath:Ye,previewSeeding:Ie,previewSeedError:Je,commandNonce:ht}=Sg({apps:oe,appRouteEntities:xt,configLoaded:!ze,port:(_==null?void 0:_.port)??5173,previewOrigin:Ts(_,De),projectName:(_==null?void 0:_.projectName)??null,routeEntities:st,screenSizes:(_==null?void 0:_.screenSizes)??{},defaultScreenSize:(_==null?void 0:_.defaultScreenSize)??null,scenarioGroups:de,scenariosLoaded:!rt,selectedApp:De,selectedRouteEntity:Ft,previewSlug:Ve,setPreviewSlug:pn}),{isAgentBuilding:gt,isAgentBuildingRef:mn,buildingScenarioSlug:xn,onAgentIdle:Er,onAgentActive:Rr,guardScenarioSelect:Tr,clearBuildingOverlay:at}=Tg({onTransitionToLive:je}),hn=(X==null?void 0:X.resumeMode)==="resume"||(X==null?void 0:X.resumeMode)==="handoff",{buildSessionLive:Pr,transitionBuildSessionLive:gn}=Qg({isAgentBuilding:gt,submittingBuildPrompt:L,launchingPlanSlug:B,sessionInfo:X,refetchSessionInfo:G});i.useEffect(()=>{Ma({hasActiveSession:hn,isAgentBuilding:gt,stepStateFeature:(P==null?void 0:P.feature)??null})},[hn,gt,P==null?void 0:P.feature]),i.useEffect(()=>{const Z=_==null?void 0:_.projectName;document.title=typeof Z=="string"&&Z.length>0?`CodeYam: ${Z}`:"CodeYam"},[_==null?void 0:_.projectName]);const Za=i.useCallback(()=>{v(),Er()},[v,Er]),eo=i.useCallback(()=>{x(),Rr()},[x,Rr]),Ot=(_==null?void 0:_.provider)??Jo,to=dt(Ot),{buildIdle:no,bannerVisible:ro,notifSettings:so,handleSettingsChange:ao,handleAgentIdle:oo,handleAgentActive:io,handleUserInput:lo,handleNavigateToTab:co,dismissIdleBanner:uo}=Xg({agentName:to,isBuildTabActive:t==="build",isAgentBuilding:gt,buildSessionLive:Pr,featureCompleteKey:j,navigateToTab:a,onAgentIdleImmediate:Za,onAgentActiveImmediate:eo}),Dr=i.useCallback(Z=>{Tr(Z)||je(Z)},[Tr,je]),ot=i.useMemo(()=>Zn(xn,de),[xn,de]),fo=((Lr=ot==null?void 0:ot.screenshotPaths)==null?void 0:Lr[0])??null,po=(ot==null?void 0:ot.name)??null,mo=i.useCallback(Z=>{switch(Z.type){case"preview":("scenarioSlug"in Z||"scenarioId"in Z)&&_e(),xe(Z);break;case"showResults":at(),_e(),p(Fe=>Fe+1),(P==null?void 0:P.mode)==="backend"&&xe({path:"/results",dimension:"Desktop"});break;case"hideResults":h(Fe=>Fe+1);break;case"featureComplete":at(),w(),b(Fe=>Fe+1),pe(),Ds({isAgentBuilding:mn.current,trigger:"feature-complete",transitionBuildSessionLive:gn});break;case"planComplete":C(),pe(),Ds({isAgentBuilding:mn.current,trigger:"plan-complete",transitionBuildSessionLive:gn});break}},[at,xe,mn,w,C,pe,_e,P,gn]);dg(mo);const Bt=(P==null?void 0:P.slug)==="ui-confirm-plan"||(P==null?void 0:P.slug)==="backend-confirm-plan",vn=i.useRef(null);i.useEffect(()=>{if(!P||!Bt){vn.current=null;return}vn.current!==P.step&&(vn.current=P.step,xe({path:"/plan-preview",dimension:"Desktop"}))},[P,Bt,xe]);const bn=i.useRef(null);i.useEffect(()=>{if(!P||P.mode!=="backend"||P.step<2||Bt){bn.current=null;return}bn.current!==P.step&&(bn.current=P.step,xe({path:"/results",dimension:"Desktop"}))},[P,Bt,xe]);const xo=i.useCallback(async()=>{y(),await pp({provider:Ot,renameLabel:(P==null?void 0:P.feature)??void 0,caller:"post-push-modal",bypassLiveGuard:!0}),He()},[y,Ot,P]),ho=i.useCallback(()=>{y(),He()},[y]),go=i.useCallback(()=>{zg(),S(),He()},[S]),vo=i.useCallback(()=>{R(!1),Hg(),S()},[S]),bo=i.useCallback(()=>{T(!0)},[]),yo=i.useCallback(()=>{T(!1)},[]),wo=i.useCallback(async(Z,Fe)=>{await K(Z,Fe)&&(T(!1),W(!0),y(),G())},[K,y,G]),jo=i.useCallback(async Z=>{await U(Z)&&(W(!0),G())},[U,G]),No=i.useCallback(()=>{W(!0)},[]),Ar=Ig({activeTab:t,hasActiveSession:hn,isAgentBuilding:gt,showPostPushModal:g,launchingPlanSlug:B,submittingBuildPrompt:L,stepStateFeature:(P==null?void 0:P.feature)??null,pendingPlanCount:J.length,buildLaunchModalDismissed:ee}),Co=Ar||E;i.useEffect(()=>{t==="build"&&G()},[t,G]),i.useEffect(()=>{t==="home"&&pe()},[t,pe]);const So=i.useCallback(async(Z,Fe)=>{at(),xe(Mg(Z,Fe))},[at,xe]),ko=i.useCallback(Z=>{(Z.scenarioSlug||Z.path)&&xe({...Z.scenarioSlug?{scenarioSlug:Z.scenarioSlug}:{},...Z.path?{path:Z.path}:{},...Z.dimension?{dimension:Z.dimension}:{}})},[xe]),Eo=i.useMemo(()=>({apps:oe,isSingleApp:oe.length===1,onSelectApps:he,onSelectApp:re,onSelectRoute:me}),[oe,he,re,me]),Ro=i.useMemo(()=>De?Ge.find(Z=>Z.app.dir===De.dir)??null:null,[Ge,De]),To=n.jsx(ap,{selectedApp:De,appDetailProps:{navContext:Eo,routeEntities:xt,routesLoading:Ee,routesError:Pe,selectedEntityHash:It,selectedRouteEntity:Ft,testGroups:fn,selectedSlug:Ve,entityLookup:ce,allScenarios:de.flatMap(Z=>Z.scenarios),onSelectScenario:Dr,onSelectRoute:me,onSelectEntity:Le,onBackToRoutes:ye,onScenariosChanged:_e,projectTitle:(_==null?void 0:_.projectName)??null,coverage:be,showProjectBand:oe.length===1,stats:Ro,testsLoading:te,testsRefreshing:fe,onRunTests:ke,currentRunner:ge},appOverviewProps:{projectTitle:(_==null?void 0:_.projectName)??"Project",projectDescription:(_==null?void 0:_.projectDescription)??null,stats:Ge,coverage:be,onSelectApp:re,configLoading:ze,testsLoading:te,testsRefreshing:fe,onRunTests:ke,currentRunner:ge,stepState:P,onPreviewUrl:Ye,onComplete:async()=>{await pe(),a("build")},onOpenBuildTab:()=>a("build")}});return n.jsxs(n.Fragment,{children:[n.jsx(lp,{splitRef:ne,isCollapsed:l,onResizeStart:ae,leftPane:n.jsx(Xp,{activeTab:t,onSendTranscript:I,appTabContent:To,awaitingPlanLaunchChoice:Co,buildActivated:r,planActivated:s,buildIdle:no,isAgentBuilding:Pr,bannerVisible:ro,onDismissIdleBanner:uo,hideResultsCommandKey:m,leftWidth:se,navigateToTab:co,onAgentActive:io,onAgentIdle:oo,onUserInput:lo,notifSettings:so,onSettingsChange:ao,provider:Ot,onRestorePreview:ko,onResultsScenarioSelect:So,onSessionDetected:o,showPostPushModal:g,onStartNextFeature:xo,onContinueInSession:ho,showResultsCommandKey:f,planChatOpen:k,onPlanChatOpenChange:R,showPlanCompleteModal:N,onCreateNewPlan:go,onViewPlans:vo,pendingPlans:J,onSelectPlan:bo,selectPlanOpen:E,onPickPlan:wo,onCancelSelectPlan:yo,launchingPlanSlug:B,planLaunchError:Q,showBuildLaunchModal:Ar,onSubmitBuildPrompt:jo,submittingBuildPrompt:L,buildPromptError:A,onCancelBuildLaunchModal:No,pendingPlansLoading:D,pendingPlansError:O,onReorderPlans:$}),previewPane:n.jsx(Uh,{emptyStateMessage:Lg({hasNoApps:Ge.length===0,hasStepState:!!P,defaultMessage:ie}),previewSlug:Ve,previewUrl:Ue,viewports:ve,activeViewport:we.name,onViewportChange:Me,isCollapsed:l,onToggleCollapsed:dn,isFilled:d,onToggleFilled:un,currentWidth:we.width,currentHeight:we.height,onCustomSizeChange:Re,buildingScenarioSlug:xn,buildingScreenshotPath:fo,buildingScenarioName:po,onDismissBuildingOverlay:at,previewSeeding:Ie,previewSeedError:Je,onRetrySeed:()=>{Ve&&je(Ve)},currentScenario:Zn(Ve,de),scenarioGroups:de,onShowScenarioPreview:Dr,commandNonce:ht,previewOrigin:Ts(_,De)})}),M?n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},children:n.jsx(nv,{featureName:(P==null?void 0:P.feature)??null,onClose:z})}):null]})}const fv=Object.freeze(Object.defineProperty({__proto__:null,EditorShell:rv},Symbol.toStringTag,{value:"Module"}));export{th as $,wi as A,bi as B,Vs as C,hi as D,Wf as E,vi as F,Ea as G,Ni as H,kh as I,qi as J,Xi as K,Ji as L,Hf as M,Hs as N,Kx as O,Vx as P,Gx as Q,Bx as R,cl as S,il as T,Yx as U,Ux as V,Xx as W,_x as X,rh as Y,Zx as Z,Qx as _,$i as a,Mp as a$,nh as a0,eh as a1,sc as a2,rc as a3,tc as a4,ec as a5,Zl as a6,nc as a7,ri as a8,ti as a9,_m as aA,Wa as aB,zm as aC,Vm as aD,Bm as aE,Om as aF,Fm as aG,hs as aH,Gm as aI,Km as aJ,Rm as aK,Um as aL,$m as aM,Hm as aN,Ym as aO,nd as aP,td as aQ,rd as aR,Vp as aS,Wp as aT,Jp as aU,Gp as aV,Yp as aW,Hp as aX,ir as aY,Ap as aZ,Lp as a_,Zo as aa,Ir as ab,ei as ac,tp as ad,Jf as ae,Xf as af,qf as ag,ep as ah,Qf as ai,Zf as aj,np as ak,rp as al,hm as am,mm as an,Ta as ao,vr as ap,xm as aq,Pa as ar,Mt as as,Gs as at,pm as au,fm as av,um as aw,km as ax,Nf as ay,Rf as az,Nn as b,ki as b$,nf as b0,gr as b1,gp as b2,hp as b3,tf as b4,Zu as b5,Yu as b6,Qu as b7,Gu as b8,ef as b9,xs as bA,Am as bB,ni as bC,Bi as bD,el as bE,tl as bF,Zi as bG,Bp as bH,yf as bI,wf as bJ,ji as bK,Bs as bL,Yi as bM,Qi as bN,Ui as bO,Vi as bP,Hi as bQ,zi as bR,_i as bS,Wi as bT,Ki as bU,Li as bV,Fi as bW,Ii as bX,Ai as bY,Mi as bZ,Ei as b_,Xu as ba,Ju as bb,qu as bc,Sa as bd,Na as be,Fa as bf,Np as bg,Sp as bh,ds as bi,wp as bj,Ep as bk,Pp as bl,bp as bm,Tp as bn,Rp as bo,xp as bp,Fp as bq,_p as br,Mm as bs,Lm as bt,Or as bu,fi as bv,wn as bw,ui as bx,Ci as by,rv as bz,uv as c,Vf as c$,Fs as c0,sl as c1,rl as c2,Fr as c3,yn as c4,nl as c5,Xe as c6,Nc as c7,Uh as c8,Ah as c9,Al as cA,Pl as cB,El as cC,kl as cD,Sl as cE,Cl as cF,$p as cG,zr as cH,Xl as cI,ql as cJ,Il as cK,Ys as cL,Bl as cM,or as cN,vf as cO,zp as cP,Op as cQ,Xp as cR,lp as cS,op as cT,ap as cU,Oc as cV,Rn as cW,$c as cX,Fc as cY,Ic as cZ,Mc as c_,Qm as ca,rx as cb,sx as cc,qm as cd,Zm as ce,ox as cf,Xm as cg,Jm as ch,lx as ci,Em as cj,fx as ck,cx as cl,Hh as cm,bf as cn,ip as co,bt as cp,jc as cq,yc as cr,wc as cs,Dm as ct,Pm as cu,Tm as cv,vc as cw,hc as cx,pc as cy,Ec as cz,sr as d,Gf as d0,_f as d1,$f as d2,vh as d3,yh as d4,hh as d5,xh as d6,mh as d7,wh as d8,gh as d9,ph as da,bh as db,uh as dc,dh as dd,rr as de,di as df,Os as dg,sd as dh,Yc as di,sf as dj,_c as dk,Pc as dl,Bf as dm,Tc as dn,jf as dp,Rc as dq,al as dr,si as ds,fv as dt,ol as e,Ws as f,nv as g,Sh as h,Th as i,Eh as j,Ch as k,Dh as l,Rx as m,jh as n,Ut as o,_s as p,jm as q,We as r,ym as s,bm as t,vm as u,gm as v,Nm as w,Vh as x,Wh as y,yi as z};