@codeyam-editor/codeyam-editor 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/npm/cloud-branch-switch.js +1 -1
  2. package/npm/cloud.js +1693 -96
  3. package/npm/container.js +14 -0
  4. package/npm/disk-pressure.js +167 -0
  5. package/npm/editor-dev.js +107 -15
  6. package/npm/editor.js +97 -37
  7. package/npm/fleet-auth-health.js +75 -0
  8. package/npm/fleet-auth.js +6 -1
  9. package/npm/fleet-build-data.js +130 -0
  10. package/npm/fleet-cleanup.js +145 -7
  11. package/npm/fleet-destroy-safety.js +55 -0
  12. package/npm/fleet-effect-status.js +33 -32
  13. package/npm/fleet-host.js +74 -0
  14. package/npm/fleet-job-badge.js +46 -2
  15. package/npm/fleet-launchd.js +171 -0
  16. package/npm/fleet-live-status.js +123 -0
  17. package/npm/fleet-plans.js +231 -0
  18. package/npm/fleet-prewarm.js +165 -0
  19. package/npm/fleet-public-url.js +160 -0
  20. package/npm/fleet-queue.js +38 -1
  21. package/npm/fleet-reconcile.js +100 -1
  22. package/npm/fleet-reset.js +298 -13
  23. package/npm/fleet-roster.js +6 -8
  24. package/npm/fleet-self-update.js +142 -0
  25. package/npm/fleet-setup-steps.js +105 -0
  26. package/npm/fleet-sleep-status.js +33 -0
  27. package/npm/fleet-strand.js +150 -0
  28. package/npm/fleet-stuck-status.js +111 -0
  29. package/npm/fleet-vm-access.js +234 -0
  30. package/npm/fleet-vm-readiness.js +104 -0
  31. package/npm/fleet-vm-slugs.js +116 -0
  32. package/npm/google-ingress.js +211 -0
  33. package/npm/ingress-invoke.js +292 -0
  34. package/npm/launch-config.js +310 -4
  35. package/npm/scenario-check.js +684 -33
  36. package/npm/scenario-handlers.js +94 -12
  37. package/npm/scenario-metrics.js +116 -1
  38. package/npm/scenario-mocks.js +20 -0
  39. package/npm/scenario-playwright.js +366 -29
  40. package/npm/script-drift.js +81 -0
  41. package/npm/utils.js +453 -43
  42. package/npm/vm-urls.js +69 -8
  43. package/package.json +5 -5
  44. package/ui/dist/assets/ContainerInspector-D7VZkkaj.js +2 -0
  45. package/ui/dist/assets/EditorShell-DHhIaotd.css +1 -0
  46. package/ui/dist/assets/EditorShell-r-796N_W.js +191 -0
  47. package/ui/dist/assets/{Markdown-BHBqz-Mj.js → Markdown-BoLHHFXH.js} +1 -1
  48. package/ui/dist/assets/ProjectLauncherScreen-Ck-XWkQN.js +1 -0
  49. package/ui/dist/assets/ScenarioDataPanel-B9iDSUpA.js +5 -0
  50. package/ui/dist/assets/ScenarioDataPanelFullPage-CBLTGC4-.js +1 -0
  51. package/ui/dist/assets/ScenarioRenderer-BhLfT-nX.js +21 -0
  52. package/ui/dist/assets/StepsSimulator-BFldWyoX.js +1 -0
  53. package/ui/dist/assets/index-CIXZkwfB.css +1 -0
  54. package/ui/dist/assets/{index-KDFAgt2e.js → index-QsOiOG9x.js} +9 -9
  55. package/ui/dist/assets/useEvents-DHkLJZR4.js +1 -0
  56. package/ui/dist/codeyam-mark.svg +4 -0
  57. package/ui/dist/codeyam-wordmark.svg +5 -0
  58. package/ui/dist/index.html +2 -2
  59. package/ui/dist/assets/ContainerInspector-C8EkH4PP.js +0 -2
  60. package/ui/dist/assets/EditorShell-CGsBSA6u.js +0 -186
  61. package/ui/dist/assets/ScenarioDataPanel-nuLXJzLf.js +0 -5
  62. package/ui/dist/assets/ScenarioDataPanelFullPage-Bnghtj8a.js +0 -1
  63. package/ui/dist/assets/ScenarioRenderer-B_Za9jL8.js +0 -1
  64. package/ui/dist/assets/StepsSimulator-CRtmlyNZ.js +0 -1
  65. package/ui/dist/assets/index-Bih6HJ_u.css +0 -1
  66. package/ui/dist/assets/useEvents-DggWrtHe.js +0 -1
@@ -1,186 +0,0 @@
1
- var rl=Object.defineProperty;var sl=(e,t,r)=>t in e?rl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var He=(e,t,r)=>sl(e,typeof t!="symbol"?t+"":t,r);import{j as n}from"./markdown-v0F0UEt3.js";import{b as i,R as ke,c as Nt}from"./react-CSS0HapR.js";import{S as al,a0 as dt,a1 as lt,_ as Sn,a2 as ir,a3 as gn,a4 as Ca,a5 as Sa,a6 as Ea,a7 as Ra,a8 as Ta,W as ol,a9 as il,aa as ll,ab as cl,ac as dl,ad as Sr,f as ul,ae as fl,e as Pa,af as pl,ag as ml,ah as hl,h as xl,ai as xs,aj as gl,ak as bl,$ as vl,Z as yl,al as wl,am as jl}from"./ScenarioDataPanel-nuLXJzLf.js";import{e as kl,a as Nl,g as Er,d as Cl,l as K,p as Lt,t as Sl,u as El}from"./index-KDFAgt2e.js";import{M as ht}from"./Markdown-BHBqz-Mj.js";function gs({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 Rl({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 Da({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(Rl,{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(gs,{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(gs,{onRunTests:s})]}):n.jsx("span",{className:"text-xs text-[var(--text-dim)]",children:"No tests"})}function Tl({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(Da,{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 Aa({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 Pl({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(Aa,{type:e.type})]}),e.description?n.jsx("p",{className:"text-sm text-[var(--text-muted)] leading-relaxed",children:e.description}):null]})}function Ge(e){return e.startsWith("http")?e:`/api/screenshots/${e}`}function Dl({thumbnails:e}){return n.jsx("div",{className:"flex gap-2 overflow-hidden",children:e.map((t,r)=>n.jsx("img",{src:Ge(t),alt:"",className:"h-20 w-32 rounded border border-[var(--border-default)] object-cover object-top"},`${t}:${r}`))})}function Al({thumbnails:e}){return n.jsx("div",{className:"px-5 py-3 flex-1",children:e.length>0?n.jsx(Dl,{thumbnails:e.slice(0,4)}):n.jsx("div",{className:"h-20"})})}function Fl({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(Pl,{app:l}),n.jsx(Al,{thumbnails:d.thumbnails}),n.jsx(Tl,{tests:c,loading:r,refreshing:s,onRunTests:a,currentRunner:o})]})}const xt={apps:[],isSingleApp:!1,onSelectApps:()=>{},onSelectApp:()=>{},onSelectRoute:()=>{}};function En(e){return e.scenarioType==="application"||e.scenarioType==="component"?e.scenarioType:e.componentName?"component":"application"}function Et(e){return En(e)==="application"}function Rr(e){return En(e)==="component"}function Tr(e){return{overrideCounts:{mocks:0,seeds:0,inheritedMocks:0,inheritedSeeds:0},...e,scenarioType:En(e)}}function gt(){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,p=typeof c.claimsVersion=="number"?c.claimsVersion:void 0;(d!==r.current.scenariosVersion||u!==r.current.plansVersion||f!==r.current.testsVersion||p!==r.current.claimsVersion)&&(r.current={scenariosVersion:d,plansVersion:u,testsVersion:f,claimsVersion:p},t(r.current))}catch{}};a();const o=setInterval(a,500);return()=>{s=!0,clearInterval(o)}},[]),e}function Ll(e){const[t,r]=i.useState({status:"idle"}),{scenariosVersion:s}=gt();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(Tr):[]};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 Wn({message:e}){return n.jsx("div",{className:"px-5 py-8 text-center text-[var(--accent-red)]",children:e})}function bs(){return n.jsx("div",{className:"px-5 py-8 text-center text-[var(--text-dim)]",children:"Loading routes..."})}function Ml(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 Il({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 Vn({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(Il,{entityRef:r,onNavigate:t})},r.hash))})}function $l(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 Bl(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 Ol({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 zl({overrideCounts:e}){const t=e?Ol(e):null;return t?n.jsx("div",{className:"text-xs text-[var(--text-dim)] mt-1",children:t}):null}const _l=new Set(["Desktop"]);function Hl({scenario:e,isSelected:t}){const r=e.dimensions.length>0&&!(e.dimensions.length===1&&_l.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(zl,{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 Wl({screenshotPath:e}){const[t,r]=i.useState(!1);return e&&!t?n.jsx("img",{src:Ge(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 Vl({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 Ul({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 Kl({scenario:e,isSelected:t,onSelect:r,onViewData:s,onScenariosChanged:a,children:o}){const l=$l(e.slug,e.name,a),{deleting:c,handleDelete:d}=Bl(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(Wl,{screenshotPath:e.screenshotPaths[0]??null}),n.jsx("div",{className:"flex-1 min-w-0",children:l.renaming?n.jsx(Ul,{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(Hl,{scenario:e,isSelected:t}),t&&n.jsx(Vl,{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 Gl(){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 Fa({scenarios:e,selectedSlug:t,onSelectScenario:r,onScenariosChanged:s}){const[a,o]=i.useState(null);return e.length===0?n.jsx(Gl,{}):n.jsx("div",{className:"grid grid-cols-1 gap-2",children:e.map(l=>n.jsx(Kl,{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(al,{variant:"inline",slug:l.slug,scenarioName:l.name,onClose:()=>o(null)})},l.slug))})}const Yl="This component renders no other tracked components.",ql="This component imports no tracked functions.",Jl="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.";function Xl({activeTab:e,entity:t,componentRefs:r,functionRefs:s,selectedSlug:a,onSelectScenario:o,onNavigateToEntity:l,onScenariosChanged:c}){return n.jsxs("div",{className:"flex-1 overflow-auto px-5 py-4",children:[e==="scenarios"&&(t.scenarios.length===0?n.jsx(en,{copy:Ml(t)}):n.jsx(Fa,{scenarios:t.scenarios,selectedSlug:a,onSelectScenario:o,onScenariosChanged:c})),e==="components"&&(r.length===0?n.jsx(en,{copy:Yl}):n.jsx(Vn,{refs:r,onNavigate:l})),e==="functions"&&(s.length===0?n.jsx(en,{copy:ql}):n.jsx(Vn,{refs:s,onNavigate:l})),e==="callers"&&(t.callers.length===0?n.jsx(en,{copy:Jl}):n.jsx(Vn,{refs:t.callers,onNavigate:l}))]})}function en({copy:e}){return n.jsx("p",{className:"text-xs italic text-[var(--text-dim)]",children:e})}function Ql(e){return typeof e!="string"&&typeof e.onClick=="function"}function Zl(e){return typeof e=="string"?e:e.label}function ec(e,t){(e.key==="Enter"||e.key===" ")&&(e.preventDefault(),t())}function tc({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=Zl(r),o=s===t,l=!o&&Ql(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=>ec(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 Pr({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(tc,{segments:d})}function nc({entity:e,app:t=null,routeEntity:r=null,navContext:s=xt}){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(Pr,{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})]})}const rc=["scenarios","components","functions"];function La({activeTab:e,onTabChange:t,scenarioCount:r,componentCount:s=0,functionCount:a=0,callersCount:o=0,tabs:l=rc}){const c={scenarios:"Scenarios",components:"Components",functions:"Functions",callers:"Callers"},d={scenarios:r,components:s,functions:a,callers:o};return n.jsx("div",{className:"flex w-full border-t border-b border-[var(--border-default)]",children:l.map(u=>n.jsxs("button",{onClick:()=>t(u),className:`cursor-pointer px-4 py-2 font-mono text-xs font-medium uppercase tracking-wider transition border-b-2 ${e===u?"text-[var(--accent-active)] border-[var(--accent-active)]":"text-[var(--text-dim)] border-transparent hover:text-[var(--text-muted)]"}`,type:"button",children:[c[u]," (",d[u],")"]},u))})}const sc=["scenarios","components","functions"],ac=["scenarios","callers"];function oc({app:e=null,navContext:t=xt,routeEntity:r=null,entity:s,selectedSlug:a,onSelectScenario:o,onNavigateToEntity:l,onScenariosChanged:c}){const[d,u]=i.useState("scenarios"),{componentRefs:f,functionRefs:p}=i.useMemo(()=>{const h=[],b=[];for(const g of s.directImports)g.kind==="function"?b.push(g):h.push(g);return{componentRefs:h,functionRefs:b}},[s.directImports]),m=s.kind==="function"?ac:sc;return n.jsxs("div",{className:"flex flex-col",children:[n.jsx(nc,{app:e,navContext:t,routeEntity:r,entity:s}),n.jsx(La,{activeTab:d,onTabChange:u,scenarioCount:s.scenarios.length,componentCount:f.length,functionCount:p.length,callersCount:s.callers.length,tabs:m}),n.jsx(Xl,{activeTab:d,entity:s,componentRefs:f,functionRefs:p,selectedSlug:a,onSelectScenario:o,onNavigateToEntity:l,onScenariosChanged:c})]})}function Vt(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 bt(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}function ic(e){const t=[],r=[];for(const s of e){const a=bt(s);/^[A-Z]/.test(a)&&!a.startsWith("use")?t.push(s):r.push(s)}return{componentImports:t,functionImports:r}}function lc({ancestor:e,onNavigateToEntity:t}){const r=t?()=>t(Vt(e.filePath,bt(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 cc({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(lc,{ancestor:r,onNavigateToEntity:t},`${r.kind}:${r.filePath}`))})]})}function dc({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&&bt(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 fn(e){const t=[];for(const r of e.split("/"))r===""||r==="."||(r===".."?t.pop():t.push(r));return t.join("/")}function uc(e){const t=new Map;for(const[r,s]of Object.entries(e)){const a=fn(r),o=bt(a),l=Vt(a,o);t.has(l)||t.set(l,{hash:l,filePath:a,entityName:o,imports:s.imports.map(fn),importedBy:s.importedBy.map(fn)})}return t}function fc(e,t){if(!e)return null;const r=fn(t);for(const s of e.values())if(s.filePath===r)return s;return null}function Ma(e,t){if(!e)return[];const r=[];for(const s of t){const a=fc(e,s);a&&r.push(a)}return r}function pc(e,t){return e.find(r=>r.pageFilePath===t)??null}function Ia(e){const t=e.split("/"),r=t.pop()??e,s=t.join("/");return{fileName:r,dirPath:s}}function mc({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 hc({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:Ge(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 xc({importPath:e,entity:t,scenarios:r,onNavigate:s,onSelectScenario:a}){const{fileName:o,dirPath:l}=Ia(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(mc,{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(hc,{scenarios:r,onSelectScenario:a})]})}function gc(){return n.jsx("p",{className:"py-4 text-center text-xs text-[var(--text-dim)]",children:"No dependencies found"})}function bc({directImports:e,entityLookup:t,allScenarios:r,routeEntities:s,onNavigateToRoute:a,onNavigateToEntity:o,onSelectScenario:l}){const c=i.useMemo(()=>Ma(t,e),[t,e]);return e.length===0?n.jsx(gc,{}):n.jsx("div",{className:"grid grid-cols-1 gap-1",children:e.map(d=>{const u=c.find(g=>g.filePath===d)??null,f=(u==null?void 0:u.entityName)??bt(d),p=dc({importPath:d,derivedName:f,allScenarios:r??[],routeEntities:s??[]}),m=pc(s??[],d),h=Vt(d,f),b=m?()=>a(m.route):o?()=>o(h):null;return n.jsx(xc,{importPath:d,entity:u,scenarios:p,onNavigate:b,onSelectScenario:l},d)})})}function vc(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 yc({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 wc({test:e}){const t=e.description.length>0;return n.jsxs("div",{className:"flex items-start gap-2 py-1",children:[n.jsx(yc,{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 jc({importPath:e,entityName:t,tests:r,onNavigate:s}){const{dirPath:a}=Ia(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(wc,{test:o},`${o.file}:${o.key??o.line??l}`))}):n.jsx("p",{className:"text-xs text-[var(--text-dim)] italic",children:"No tests"})})]})}function kc(){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 Nc({functionImports:e,entityLookup:t,testGroups:r,onNavigateToEntity:s}){const a=i.useMemo(()=>Ma(t,e),[t,e]);return e.length===0?n.jsx(kc,{}):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)??bt(o),d=vc(o,t,r),u=s?()=>s(Vt(o,c)):null;return n.jsx(jc,{importPath:o,entityName:c,tests:d,onNavigate:u},o)})})}function Cc({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(Fa,{scenarios:t.scenarios,selectedSlug:o,onSelectScenario:u,onScenariosChanged:m}),e==="components"&&n.jsx(bc,{directImports:r,entityLookup:l,allScenarios:c,routeEntities:d,onNavigateToRoute:f,onNavigateToEntity:p,onSelectScenario:u}),e==="functions"&&n.jsx(Nc,{functionImports:s,entityLookup:l,testGroups:a,onNavigateToEntity:p})]})}function Sc({displayName:e,pageFilePath:t,app:r=null,routeEntity:s=null,navContext:a=xt}){return n.jsxs("div",{className:"px-5 py-4",children:[n.jsx("div",{className:"mb-2",children:n.jsx(Pr,{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 Ec({app:e=null,navContext:t=xt,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:b,functionImports:g}=i.useMemo(()=>ic(r.directImports),[r.directImports]);return n.jsxs("div",{className:"flex flex-col",children:[n.jsx(Sc,{app:e,navContext:t,routeEntity:r,displayName:r.displayName,pageFilePath:r.pageFilePath}),n.jsx(cc,{layoutChain:r.layoutChain??[],onNavigateToEntity:f}),n.jsx(La,{activeTab:m,onTabChange:h,scenarioCount:r.scenarios.length,componentCount:b.length,functionCount:g.length}),n.jsx(Cc,{activeTab:m,routeEntity:r,componentImports:b,functionImports:g,testGroups:c,selectedSlug:s,entityLookup:a,allScenarios:o,routeEntities:l,onSelectScenario:d,onNavigateToRoute:u,onNavigateToEntity:f,onScenariosChanged:p})]})}function Un(e){const t=kl(e);if(t)return{selectedAppDir:t,selectedEntityHash:null};const r=Nl(e);return r?{selectedAppDir:null,selectedEntityHash:r}:{selectedAppDir:null,selectedEntityHash:null}}function Kn(e){return`/apps/${e}`}function Rc(e){return`/entities/${e}`}function lr(e){return e.pageFilePath?Vt(e.pageFilePath,bt(e.pageFilePath)):null}function $a(e){const t=lr(e);return t===null?null:Rc(t)}function Ba({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 Tc({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:Ge(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 Pc({routeEntity:e,onSelectRoute:t,onSelectScenario:r}){const s=e.scenarios.length,a=$a(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(Ba,{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(Tc,{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 Dc(){return n.jsx("div",{className:"px-5 py-8 text-center text-[var(--text-dim)]",children:"No routes discovered yet."})}function Ac(){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 Fc({routeEntities:e,onSelectRoute:t,onSelectScenario:r}){return e.length===0?n.jsx(Dc,{}):n.jsxs("div",{className:"px-5 py-5",children:[n.jsx(Ac,{}),n.jsx("div",{children:e.map(s=>n.jsx(Pc,{routeEntity:s,onSelectRoute:t,onSelectScenario:r},s.route))})]})}function Lc({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 Mc({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 Ic({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(Lc,{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(Mc,{test:o},`${o.file}-${o.key??o.line??l}`))})]},t.feature)})})}function $c({app:e=null,navContext:t=xt,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:b,onBackToRoutes:g,onScenariosChanged:y}){const w=Ll(l&&!c?l:null);return r?a?n.jsx(bs,{}):o?n.jsx(Wn,{message:o}):c?n.jsx(Ec,{app:e,navContext:t,routeEntity:c,selectedSlug:u,entityLookup:f,allScenarios:p,routeEntities:s,testGroups:d,onSelectScenario:m,onNavigateToRoute:h,onNavigateToEntity:b,onScenariosChanged:y}):l?w.status==="loading"||w.status==="idle"?n.jsx(bs,{}):w.status==="not-found"?n.jsx(Wn,{message:"Entity not found. The dependency graph may need to be refreshed."}):w.status==="error"?n.jsx(Wn,{message:w.message}):n.jsx(oc,{app:e,navContext:t,routeEntity:c,entity:w.entity,selectedSlug:u,onSelectScenario:m,onNavigateToEntity:b??(()=>{}),onScenariosChanged:y}):n.jsx(Fc,{routeEntities:s,onSelectRoute:h,onSelectScenario:m}):n.jsx(Ic,{groups:d})}function Bc({app:e,showDetail:t,navContext:r=xt,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(Pr,{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(Aa,{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(Da,{tests:s.tests,loading:a,refreshing:o,onRunTests:l,currentRunner:c})}):null]})}function Dr({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 Oc({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(Dr,{coverage:t,testId:"app-detail-coverage",onClick:r})]})}function zc({name:e,id:t,capabilitiesTally:r,expanded:s,onToggle:a}){const o=e??t;return n.jsxs("button",{type:"button",onClick:a,className:"flex w-full items-center gap-2 text-left text-xs text-[var(--text-secondary)] hover:text-[var(--text-primary)]","data-testid":"stack-summary","aria-expanded":s,children:[n.jsx("span",{className:`inline-block transition-transform ${s?"rotate-90":""}`,children:"▶"}),n.jsxs("span",{className:"font-medium text-[var(--text-primary)]",children:["Stack",o?` — ${o}`:""]}),e&&t?n.jsxs("span",{className:"text-[var(--text-dim)]",children:["(",t,")"]}):null,n.jsxs("span",{className:"text-[var(--text-dim)]",children:["— ",r]})]})}const cr=["layout-web","interactions-click","interactions-touch-gestures","native-haptics","native-geolocation","native-clipboard","native-network","native-storage","routing","http-mocks","real-device"],Oa={"layout-web":{label:"Web layout",description:"Visual layout and styling rendered in the web preview"},"interactions-click":{label:"Click interactions",description:"Pointer / click-driven UI behavior"},"interactions-touch-gestures":{label:"Touch gestures",description:"Swipe, pinch, and other multi-touch gestures"},"native-haptics":{label:"Haptic feedback",description:"Vibration / tactile feedback APIs"},"native-geolocation":{label:"Geolocation",description:"Device location APIs"},"native-clipboard":{label:"Clipboard",description:"Native copy / paste access"},"native-network":{label:"Network status",description:"Connectivity / reachability APIs"},"native-storage":{label:"Persistent storage",description:"On-device persistence (preferences, local DB, secure store)"},routing:{label:"Routing",description:"Navigation between screens / pages"},"http-mocks":{label:"HTTP mocking",description:"Network requests intercepted and replayed from scenarios"},"real-device":{label:"Real-device behavior",description:"Behavior that only manifests on a physical device or native build"}},za={verified:{label:"Verified",badgeClass:"bg-[var(--accent-green)]/20 text-[var(--accent-green)]",meaning:"The editor's scenarios actually exercise this — a regression fails a test."},stubbed:{label:"Stubbed",badgeClass:"bg-[var(--accent-orange)]/20 text-[var(--accent-orange)]",meaning:"No-op'd in web preview (e.g. a native API logged to console). Tests don't fail, but nothing is really verified — check on a real device."},manual:{label:"Manual",badgeClass:"bg-[var(--accent-blue)]/20 text-[var(--accent-blue)]",meaning:"Must be checked by hand on a real device or native build target."},"not-applicable":{label:"N/A",badgeClass:"bg-[var(--bg-subtle)] text-[var(--text-dim)]",meaning:"This stack doesn't expose the capability."}};function _c(e){var t;return((t=Oa[e])==null?void 0:t.label)??e}function Hc(e,t){var a,o;const r=(a=Oa[e])==null?void 0:a.description,s=((o=za[t])==null?void 0:o.meaning)??"";return r?`${r}. ${s}`:s}function Wc({capabilities:e,defaultExpanded:t=!1}){const[r,s]=i.useState(t),a=cr.filter(c=>c in e),o=Object.keys(e).filter(c=>!cr.includes(c)),l={verified:0,stubbed:0,manual:0,"not-applicable":0};for(const c of a){const d=e[c];d in l&&(l[d]+=1)}return n.jsxs("div",{className:"px-5 py-2","data-testid":"capabilities-panel",children:[n.jsxs("button",{type:"button",onClick:()=>s(c=>!c),className:"flex w-full items-center gap-2 text-left text-xs text-[var(--text-secondary)] hover:text-[var(--text-primary)]","data-testid":"capabilities-summary","aria-expanded":r,children:[n.jsx("span",{className:`inline-block transition-transform ${r?"rotate-90":""}`,children:"▶"}),n.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:"Stack capabilities"}),n.jsxs("span",{className:"text-[var(--text-dim)]",children:["— ",l.verified," verified · ",l.stubbed," stubbed ·"," ",l.manual," manual · ",l["not-applicable"]," n/a"]})]}),r?n.jsxs("div",{className:"mt-2 space-y-1","data-testid":"capabilities-rows",children:[a.map(c=>n.jsx(vs,{token:c,state:e[c]},c)),o.length>0?n.jsxs("div",{className:"mt-3","data-testid":"capabilities-unknown-group",children:[n.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-[var(--accent-warn)]",children:[n.jsx("span",{title:"These tokens aren't recognized — likely typos",children:"⚠"}),"Unknown capabilities"]}),o.map(c=>n.jsx(vs,{token:c,state:e[c],unknown:!0},c))]}):null]}):null]})}function vs({token:e,state:t,unknown:r}){const s=za[t],a=r?"This token isn't recognized — may be a typo.":Hc(e,t);return n.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs","data-testid":`capability-row-${e}`,children:[n.jsxs("span",{className:"flex items-center gap-1 text-[var(--text-secondary)]",children:[_c(e),n.jsx("span",{className:"cursor-help text-[var(--text-dim)]",title:a,"aria-label":a,children:"ⓘ"})]}),n.jsx("span",{className:`rounded px-1.5 py-0.5 ${(s==null?void 0:s.badgeClass)??"bg-[var(--bg-subtle)] text-[var(--text-dim)]"}`,children:(s==null?void 0:s.label)??t})]})}function Vc({capabilities:e}){return e&&Object.keys(e).length>0?n.jsx(Wc,{capabilities:e,defaultExpanded:!1}):n.jsxs("div",{className:"text-xs text-[var(--text-dim)]","data-testid":"stack-capabilities-empty-hint",children:["Capabilities not declared. Run"," ",n.jsx("code",{className:"rounded bg-[var(--bg-subtle)] px-1 py-0.5 text-[var(--text-secondary)]",children:"codeyam-editor editor capabilities-list"})," ","to learn more."]})}function Uc({fields:e,capabilities:t}){return n.jsxs("div",{className:"mt-2 space-y-2","data-testid":"stack-body",children:[e.description?n.jsx("p",{className:"text-xs text-[var(--text-secondary)]","data-testid":"stack-description",children:e.description}):null,e.technologies.length>0?n.jsx("ul",{className:"flex flex-wrap gap-1","data-testid":"stack-technologies",children:e.technologies.map(r=>n.jsx("li",{className:"rounded bg-[var(--bg-subtle)] px-1.5 py-0.5 text-[10px] text-[var(--text-secondary)]",children:r},r))}):null,e.commands.length>0?n.jsx("dl",{className:"space-y-0.5 text-xs","data-testid":"stack-commands",children:e.commands.map(({key:r,value:s})=>n.jsxs("div",{className:"flex items-baseline gap-2",children:[n.jsx("dt",{className:"w-10 text-[var(--text-dim)]",children:r}),n.jsx("dd",{className:"text-[var(--text-secondary)]",children:n.jsx("code",{className:"rounded bg-[var(--bg-subtle)] px-1 py-0.5",children:s})})]},r))}):null,e.routingSummary?n.jsxs("div",{className:"text-xs text-[var(--text-secondary)]","data-testid":"stack-routing",children:[n.jsx("span",{className:"text-[var(--text-dim)]",children:"routing"})," ",e.routingSummary]}):null,n.jsx("div",{className:"border-t border-[var(--border-subtle)] pt-2",children:n.jsx(Vc,{capabilities:t})})]})}function Kc({skip:e=!1}={}){const[t,r]=i.useState(null);return i.useEffect(()=>{if(e)return;let s=!1;return fetch("/api/project-stack").then(a=>a.ok?a.json():{}).then(a=>{s||r(a&&typeof a=="object"&&!Array.isArray(a)?a:{})}).catch(()=>{s||r({})}),()=>{s=!0}},[e]),t}const Gc=["dev","test","build"];function ot(e){return typeof e=="string"&&e.length>0?e:null}function _a(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Yc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function qc(e){const t=_a(e);if(!t)return[];const r=[];for(const s of Gc){const a=ot(t[s]);a&&r.push({key:s,value:a})}return r}function Jc(e){const t=_a(e);if(!t)return null;const r=ot(t.type);if(!r)return null;const s=ot(t.pagesDir)??ot(t.isolationRoute)??ot(t.componentManifest);return s?`${r} (${s})`:r}function Xc(e){const t=e.capabilities;return!t||typeof t!="object"||Array.isArray(t)?null:t}function Qc(e){if(!e||Object.keys(e).length===0)return"capabilities not declared";const t={verified:0,stubbed:0,manual:0,"not-applicable":0};for(const r of cr){const s=e[r];s&&s in t&&(t[s]+=1)}return`${t.verified} verified · ${t.stubbed} stubbed · ${t.manual} manual · ${t["not-applicable"]} n/a`}function Zc(e){return e?{id:ot(e.id),name:ot(e.name),description:ot(e.description),technologies:Yc(e.technologies),commands:qc(e.commands),routingSummary:Jc(e.routing)}:{id:null,name:null,description:null,technologies:[],commands:[],routingSummary:null}}function ed({stack:e,defaultExpanded:t=!1}){const r=e!==void 0,[s,a]=i.useState(t),o=Kc({skip:r}),l=r?e:o;if(!l||Object.keys(l).length===0)return null;const c=Zc(l),d=Xc(l);return n.jsxs("div",{className:"px-5 py-2","data-testid":"stack-panel",children:[n.jsx(zc,{name:c.name,id:c.id,capabilitiesTally:Qc(d),expanded:s,onToggle:()=>a(u=>!u)}),s?n.jsx(Uc,{fields:c,capabilities:d}):null]})}function td({app:e,navContext:t=xt,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:b,onScenariosChanged:g,projectTitle:y,coverage:w,showProjectBand:v,onCoverageClick:x,stats:j,testsLoading:k,testsRefreshing:N,onRunTests:C,currentRunner:S}){const R=e.type==="web",E=!!v&&!l;return n.jsxs("div",{children:[E?n.jsxs(n.Fragment,{children:[n.jsx(Oc,{projectTitle:y,coverage:w,onCoverageClick:x}),n.jsx(ed,{})]}):null,n.jsx(Bc,{app:e,showDetail:!!(l||o),navContext:t,stats:j,testsLoading:k,testsRefreshing:N,onRunTests:C,currentRunner:S}),n.jsx($c,{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:b,onScenariosChanged:g})]})}function Ha(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 nd(e){switch(e){case"feature":return"text-[#D7FF63]";case"fix":return"text-red-400";case"refactor":return"text-purple-400";case"milestone":return"text-yellow-400";default:return"text-gray-400"}}function O1(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 rd({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 sd=192;function Wa({children:e,variant:t="compact",maxHeight:r=sd}){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(ht,{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 ad({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:Ge(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 od={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"},id={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"},ld={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."},cd={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."},dd=24,Va=19;function Ye(e){return e==="backend"?"backend":"ui"}function Ar(e,t){return(Ye(t)==="backend"?id:od)[e]??"?"}function ud(e,t){return(Ye(t)==="backend"?cd:ld)[e]??""}function fd(e){return Ye(e)==="backend"?Va:dd}function pd(e){return Ye(e)==="backend"?"Backend Flow":"UI Flow"}function Ua(e,t){const r=Ye(t);return{description:ud(e,r),label:Ar(e,r),prefix:pd(r),totalSteps:fd(r)}}const md=[{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:"Making the code 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]}],hd=[{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:"Making the code 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 xd(e){return Ye(e)==="backend"?hd:md}function gd({currentStep:e}){const t=Array.from({length:Va},(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 dr(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 bd({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:dr(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:dr(a.duration_ms)})]})]},a.name))})]})}function Ka({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-[#D7FF63] 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 vd({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(Ka,{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 yd({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(wd,{change:t},r))]})}function wd({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(jd,{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 jd({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(Ka,{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 kd({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(ys,{label:"Files Modified",value:t}),n.jsx(ys,{label:"Tests Modified",value:r,color:r>0?"green":void 0})]})]})})}function ys({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 Fr({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 Nd=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/__tests__\//,/tests?\//];function Gn(e){return Nd.some(t=>t.test(e))}function Cd({files:e,defaultCollapsed:t}){const[r,s]=i.useState(t),a=e.filter(d=>d.path&&Gn(d.path)),o=e.filter(d=>d.path&&d.path.endsWith(".rs")&&!Gn(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&&!Gn(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(tn,{title:"Tests",files:a}),o.length>0&&n.jsx(tn,{title:"Rust Source",files:o}),c.length>0&&n.jsx(tn,{title:"Other Source",files:c}),l.length>0&&n.jsx(tn,{title:"Configuration",files:l})]})]})}function tn({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(Fr,{status:r.status}),n.jsx("span",{children:r.path})]},r.path))})]})}const Sd=5e3,ws=50;function Ed(){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([]),b=i.useRef(null);i.useEffect(()=>{h.current=e},[e]),i.useEffect(()=>{b.current=a},[a]);const g=i.useCallback(async()=>{if(m.current==="idle"){m.current="initial",c(!0),p(null);try{const v=await fetch(`/api/history?limit=${ws}`);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"}}},[]),y=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 g();return}m.current="poll";try{const j=await fetch(`/api/history?since=${encodeURIComponent(v)}`);if(!j.ok)throw new Error(`HTTP ${j.status}`);const k=await j.json(),N=new Set(h.current.map(S=>S.commit.sha)),C=(k.entries??[]).filter(S=>!N.has(S.commit.sha));C.length>0&&(t(S=>[...C,...S]),s(S=>S+C.length))}catch(j){p(j instanceof Error?j.message:"Failed to poll history")}finally{m.current="idle"}},[g]),w=i.useCallback(async()=>{if(m.current!=="idle")return;const v=b.current;if(v){m.current="more",u(!0);try{const x=await fetch(`/api/history?limit=${ws}&before=${encodeURIComponent(v)}`);if(!x.ok)throw new Error(`HTTP ${x.status}`);const j=await x.json();t(k=>[...k,...j.entries??[]]),o(j.nextCursor??null),typeof j.total=="number"&&s(j.total)}catch(x){p(x instanceof Error?x.message:"Failed to load more commits")}finally{u(!1),m.current="idle"}}},[]);return i.useEffect(()=>{g();const v=setInterval(()=>{y()},Sd);return()=>clearInterval(v)},[g,y]),{rows:e,total:r,hasMore:a!==null,loading:l,loadingMore:d,error:f,loadMore:w,reload:g}}function Rd({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:Ha(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 Td=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/__tests__\//,/tests?\//];function Pd(e){return e.filter(t=>Td.some(r=>r.test(t.path)))}function Ga({entry:e,commit:t}){const r=Pd(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 ${nd(e.type)}`,children:e.type}),n.jsx("span",{className:"text-xs",style:{color:"var(--text-dim)"},children:Ha(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(Wa,{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(ad,{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(rd,{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(Fr,{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 Lr({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 Dd(){const{rows:e,total:t,hasMore:r,loading:s,loadingMore:a,error:o,loadMore:l}=Ed();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(Lr,{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(Ga,{entry:d.entry,commit:d.commit},d.commit.sha):n.jsx(Rd,{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 Ad="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 Fd(){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 js(e){return e.length===0?"_(no events in window)_":`\`\`\`jsonl
2
- ${e.map(r=>JSON.stringify(r)).join(`
3
- `)}
4
- \`\`\``}function Yn(e,t){return e.trim().length===0?`_(${t} empty)_`:`\`\`\`
5
- ${e}
6
- \`\`\``}function Ld(e){var y,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=((y=t==null?void 0:t.environment)==null?void 0:y.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??Ad).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
- `),b=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,"",b,"","## UI idle trace (persisted)","",js((t==null?void 0:t.uiTrace)??[]),"","## UI idle trace (in-memory ring buffer — may be ahead of persisted)","",Yn(s,"in-memory buffer"),"","## Rust idle trace","",js((t==null?void 0:t.rustTrace)??[]),"","## editor-server.log (filtered to idle= within window)","",Yn((t==null?void 0:t.editorServerLog)??"","editor-server.log"),"","## dev-server.log (last lines)","",Yn((t==null?void 0:t.devServerLog)??"","dev-server.log"),""].filter(x=>x!==null).join(`
8
- `)}async function Md(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=Fd(),o=Cl({agentName:e.agentName});return{markdown:Ld({bundle:r,browser:a,uiBufferText:o,prompt:e.prompt,agentName:e.agentName}),bundle:r,error:s}}const Id=1500;function $d(e=Id){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 Bd=2500;function Od({agentName:e}){const[t,r]=i.useState(!1),{label:s,flash:a}=$d(Bd),o=async()=>{r(!0);const{markdown:l,bundle:c,error:d}=await Md({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")})}const qn={sound:"soft-double-tap",systemNotification:!0,idleOnStop:!1,idleOnNotification:!0},zd=[{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"}],Ya="codeyam-editor-notifications";function qa(){try{const e=localStorage.getItem(Ya);if(!e)return qn;const t=JSON.parse(e);return{...qn,...t}}catch{return qn}}function Ja(e){localStorage.setItem(Ya,JSON.stringify(e))}const _d={"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 Jn(e,t){const r=t;K(e,{name:r==null?void 0:r.name,message:r==null?void 0:r.message})}function Xa(e){if(e==="off")return;K("audio-playsound-entered",{soundId:e});let t;try{t=new AudioContext}catch(s){Jn("audio-context-failed",s);return}K("audio-context-created",{state:t.state});const r=()=>{let s;try{s=_d[e](t)}catch(a){Jn("audio-context-failed",a),t.close().catch(()=>{});return}K("audio-oscillators-scheduled",{soundId:e,count:s.count,longestStopSec:s.longestStopSec}),setTimeout(()=>{t.close().then(()=>K("audio-context-closed")).catch(()=>{})},(s.longestStopSec+.1)*1e3)};t.state==="running"?r():t.state==="suspended"?(K("audio-context-resume-attempted"),t.resume().then(()=>{K("audio-context-resume-ok",{state:t.state}),r()},s=>{Jn("audio-context-resume-failed",s),t.close().catch(()=>{})})):(K("audio-context-failed",{name:"UnexpectedState",message:`AudioContext state "${t.state}"`}),t.close().catch(()=>{}))}function ks({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 Mr({settings:e,onChange:t}){const r=e.idleOnStop??!1,s=e.idleOnNotification??!0;return n.jsxs(n.Fragment,{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:zd.map(a=>n.jsx("button",{onClick:()=>{t({...e,sound:a.id}),a.id!=="off"&&Xa(a.id)},className:"text-left text-[11px] px-2 py-1 rounded cursor-pointer transition-colors",style:{background:e.sound===a.id?"var(--bg-input)":"transparent",color:e.sound===a.id?"var(--text-primary)":"var(--text-secondary)"},children:a.label},a.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(ks,{label:"Claude stops",checked:r,onChange:a=>t({...e,idleOnStop:a})}),n.jsx(ks,{label:"Claude sends a notification",checked:s,onChange:a=>t({...e,idleOnNotification:a}),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:a=>{const o=a.target.checked;t({...e,systemNotification:o}),o&&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"})]})]})}function Hd({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.jsx(Mr,{settings:e,onChange:t}),n.jsx("div",{className:"pt-2",style:{borderTop:"1px solid var(--border-default)"},children:n.jsx(Od,{agentName:r})})]})]})]})}const Qa="codeyam-editor-notifications-prompted",Wd="codeyam-editor-notifications";function Za(){try{localStorage.setItem(Qa,"1")}catch{}}function Vd(){try{return localStorage.getItem(Qa)!==null||localStorage.getItem(Wd)!==null}catch{return!0}}function Ud({settings:e,onChange:t}){const[r,s]=i.useState(()=>!Vd());if(!r)return null;const a=()=>{Za(),s(!1)},o=()=>{t({...e,systemNotification:!0}),typeof Notification<"u"&&Notification.permission==="default"&&Notification.requestPermission(),a()};return n.jsxs("div",{className:"rounded-lg p-4 mb-4 flex flex-col gap-3",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"var(--text-sm, 14px)",fontWeight:600,color:"var(--text-primary)"},children:"Want to be notified when Claude finishes?"}),n.jsx("div",{style:{fontSize:"var(--text-xs, 12px)",color:"var(--text-muted)",marginTop:2},children:"We'll ping you when the agent stops or pauses, so you can step away while it works."})]}),n.jsx("button",{onClick:a,className:"cursor-pointer shrink-0",style:{color:"var(--text-dim)",fontSize:"11px"},children:"Not now"})]}),n.jsx("div",{className:"flex flex-col gap-3 rounded p-3",style:{background:"var(--bg-nav)",border:"1px solid var(--border-default)"},children:n.jsx(Mr,{settings:e,onChange:t})}),n.jsx("button",{onClick:o,className:"self-start px-3 py-2 rounded cursor-pointer transition-colors",style:{background:"var(--accent-green, #16a34a)",color:"#fff",fontSize:"var(--text-sm, 14px)",fontWeight:600},children:"Enable notifications"})]})}function Kd(){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 Gd({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 Yd(){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 qd({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 Jd({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(Gd,{projectDescription:e}):n.jsx(Yd,{}),n.jsx(qd,{onClick:t})]})}function Xd({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(Fl,{stats:l,onClick:()=>t(l.app.dir),testsLoading:r,testsRefreshing:s,onRunTests:a,currentRunner:o},l.app.dir))})}function Qd({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(Dr,{coverage:t,testId:"app-overview-coverage",onClick:r})]})}async function Zd(e){try{e.description&&await fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDescription:e.description,allowOverwrite:!0})});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 Ns=["product-type","description","tech-stack","notifications","design-approach"];function eu(e){return e==="files"||e==="chat"?[...Ns,"design-details"]:Ns}const eo="codeyam.questionnaire.draft";function Ir(e){return`${eo}:${e}`}function tu(e){if(e===null||typeof e!="object")return!1;const t=e;if(typeof t.step!="number"||!Number.isFinite(t.step)||typeof t.savedAt!="string"||t.designChatLaunched!==void 0&&typeof t.designChatLaunched!="boolean")return!1;const r=t.answers;if(r===null||typeof r!="object")return!1;const s=r;return!(!Array.isArray(s.appFormats)||!s.appFormats.every(a=>typeof a=="string")||typeof s.description!="string"||s.techStackId!==null&&typeof s.techStackId!="string"||s.designApproach!==null&&typeof s.designApproach!="string"||s.defaultDevice!==null&&typeof s.defaultDevice!="string")}function Xn(e){try{const t=localStorage.getItem(Ir(e));if(t===null)return null;const r=JSON.parse(t);return tu(r)?r:null}catch{return null}}function nu(e,t){try{localStorage.setItem(Ir(e),JSON.stringify(t))}catch{}}function ru(e){try{localStorage.removeItem(Ir(e))}catch{}}function su(){try{localStorage.removeItem(eo)}catch{}}function au(){const[e,t]=i.useState([]);return i.useEffect(()=>{fetch("/api/editor-stacks").then(r=>r.json()).then(t).catch(()=>{})},[]),{techStacks:e}}function ou(){const[e,t]=i.useState({projectDir:null,loaded:!1});return i.useEffect(()=>{let r=!1;return fetch("/api/codeyam-server-identity").then(s=>s.ok?s.json():null).then(s=>{if(r)return;const a=s&&typeof s=="object"&&typeof s.projectDir=="string"?s.projectDir:null;t({projectDir:a,loaded:!0})}).catch(()=>{r||t({projectDir:null,loaded:!0})}),()=>{r=!0}},[]),e}const bn=20*1024*1024,iu=3e4,lu=3e3;function to(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 cu(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`drop-${Date.now()}-${Math.random().toString(36).slice(2)}`}function du(e){return/^[A-Za-z0-9._/\-]+$/.test(e)?e:`"${e.replace(/(["\\$`])/g,"\\$1")}"`}function uu(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 it({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 fu({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>bn?(d(`${x.name} is larger than the ${bn/(1024*1024)}MB cap`),!1):!0);r(x=>[...x,...v.map(j=>({id:`${j.name}-${j.size}-${Math.random().toString(36).slice(2)}`,file:j,description:""}))])},[]),h=i.useCallback(w=>{w.target.files&&m(Array.from(w.target.files)),w.target.value=""},[m]),b=i.useCallback((w,v)=>{r(x=>x.map(j=>j.id===w?{...j,description:v}:j))},[]),g=i.useCallback(w=>{r(v=>v.filter(x=>x.id!==w))},[]),y=i.useCallback(async()=>{if(t.length!==0){a(!0),d(null);try{const w=await Promise.all(t.map(async k=>({filename:k.file.name,contentBase64:await to(k.file),description:k.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 j=(await v.json()).written??w.map(k=>k.filename);l(j),e==null||e(j)}catch(w){d(w instanceof Error?w.message:String(w))}finally{a(!1)}}},[t,e]);return n.jsxs(it,{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:()=>g(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=>b(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:y,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 Mt({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(pu,{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 pu({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 mu=[{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 hu({selected:e,onSelect:t}){return n.jsx(it,{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:mu.map(r=>n.jsx(Mt,{label:r.label,description:r.description,selected:e===r.id,onClick:()=>t(r.id)},r.id))})})}function xu(){const[e,t]=i.useState(()=>qa());i.useEffect(()=>{Za()},[]);const r=a=>{t(a),Ja(a)},s=()=>{r({...e,systemNotification:!0}),typeof Notification<"u"&&Notification.permission==="default"&&Notification.requestPermission()};return n.jsx(it,{title:"Want to be notified when Claude finishes?",subtitle:"Building can take a while. Turn on a sound or a system notification and we'll ping you when the agent stops or pauses — so you can step away while it works.",children:n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-md, 12px)"},children:[n.jsx("button",{onClick:s,className:"text-left px-3 py-2 rounded cursor-pointer transition-colors",style:{background:e.systemNotification?"var(--bg-input)":"var(--accent-green, #16a34a)",color:e.systemNotification?"var(--text-primary)":"#fff",fontSize:"var(--text-sm, 14px)",fontWeight:600,border:"1px solid var(--border-default)"},children:e.systemNotification?"System notifications enabled":"Enable notifications"}),n.jsx("div",{className:"flex flex-col gap-3 rounded p-3",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:n.jsx(Mr,{settings:e,onChange:r})}),n.jsx("p",{style:{fontSize:"var(--text-xs, 12px)",color:"var(--text-dim)"},children:'This is optional — you can skip it and change it any time from the "Notifications" control in the footer.'})]})})}function gu(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 bu({providerLabel:e,preparing:t,onLaunch:r}){return n.jsxs("div",{children:[n.jsxs("p",{style:{margin:"0 0 var(--spacing-lg, 16px)",fontSize:"var(--text-md, 15px)",lineHeight:1.5,color:"var(--text-primary)"},children:["Click the button below to launch a chat window with ",e," so that ",e," can generate some design options for you to consider and iterate on."]}),n.jsx("button",{onClick:r,disabled:t,style:{background:t?"var(--bg-surface)":"var(--accent-active)",border:"none",color:t?"var(--text-dim)":"#000",padding:"var(--spacing-sm, 8px) var(--spacing-lg, 16px)",borderRadius:6,cursor:t?"not-allowed":"pointer",fontSize:"var(--text-sm, 14px)",fontWeight:600},children:t?"Preparing design moodboards…":`Launch ${e} Design Chat`})]})}function vu({description:e,launched:t,onLaunched:r,onDesignSelected:s,onPreviewUrl:a}){const[o,l]=i.useState({kind:"preparing"}),{config:c}=dt(),d=lt(c==null?void 0:c.provider);i.useEffect(()=>(a==null||a("/design-exploration"),()=>{a==null||a(null)}),[a]),i.useEffect(()=>{let f=!1;return(async()=>{try{const[p,m]=await Promise.all([fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDescription:e,allowOverwrite:!0})}),fetch("/api/editor-design-systems-install",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"})]);if(!m.ok){const h=await m.text().catch(()=>`${m.status}`);throw new Error(h||`install failed: ${m.status}`)}p.ok||console.warn("[QuestionnaireDesignChatStep] editor-project-info failed; skill will prompt for description",p.status),f||l({kind:"ready"})}catch(p){f||l({kind:"error",message:p instanceof Error?p.message:String(p)})}})(),()=>{f=!0}},[e]),gu(t,s);const u=o.kind==="preparing";return n.jsx(it,{title:"Explore design directions",subtitle:"Chat with the agent, then pick a mockup by number from the Live Preview.",children:t?n.jsx(Sn,{chatName:"initial-design",slashCommand:"/codeyam-design",height:420}):o.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: ",o.message,". Try the Files or Skip approach instead."]}):n.jsx(bu,{providerLabel:d,preparing:u,onLaunch:r})})}const yu=[{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 wu({selected:e,onSelect:t}){return n.jsx("div",{style:{marginTop:"var(--spacing-xl, 32px)"},children:n.jsx(it,{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:yu.map(r=>n.jsx(Mt,{label:r.label,description:r.description,selected:e===r.id,onClick:()=>t(r.id)},r.id))})})})}function no(){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 ju({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 ku({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 Nu=[{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"}],Cu={"product-type":"What Type Of Product Do You Want To Build?",description:"Describe Your Product","tech-stack":"Do You Have A Preferred Tech Stack?",notifications:"Notifications","design-approach":"How Should We Approach Design","design-details":"Design Details"},Cs=560,Su=960;function Eu(e){const{projectDir:t,loaded:r}=ou(),s=i.useRef(!1);return i.useEffect(()=>{r&&!s.current&&(s.current=!0,su())},[r]),r?n.jsx(Ru,{...e,projectDir:t}):n.jsx("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"auto"},children:n.jsx(no,{})})}function Ru({onComplete:e,onPreviewUrl:t,projectDir:r}){const[s,a]=i.useState(()=>{const T=r?Xn(r):null;return T?T.step:1}),[o,l]=i.useState(()=>{const T=r?Xn(r):null;return(T==null?void 0:T.answers)??{appFormats:[],description:"",techStackId:null,designApproach:null,defaultDevice:null}}),[c,d]=i.useState(null),[u,f]=i.useState(()=>{const T=r?Xn(r):null;return(T==null?void 0:T.designChatLaunched)??!1}),p=i.useRef(u),{techStacks:m}=au(),h=eu(o.designApproach),b=h[s-1],g=s===h.length,y=h.map(T=>Cu[T]);i.useEffect(()=>{s>h.length&&a(h.length)},[s,h.length]);const w=i.useRef(!0);i.useEffect(()=>{if(w.current){w.current=!1;return}r!==null&&nu(r,{step:s,answers:o,designChatLaunched:u,savedAt:new Date().toISOString()})},[s,o,u,r]);const v=i.useCallback(()=>{f(!0)},[]),[x,j]=i.useState(p.current?{state:"pending"}:{state:"ready",active:null});i.useEffect(()=>{if(!p.current)return;let T=!1;return(async()=>{try{const Y=await(await fetch("/api/editor-design-state")).json();T||j({state:"ready",active:Y.active??null})}catch{T||j({state:"ready",active:null})}})(),()=>{T=!0}},[]);const k=i.useCallback(T=>{l(O=>{const Y=O.appFormats.includes(T),P=Y?O.appFormats.filter(V=>V!==T):[...O.appFormats,T],$=T==="web"&&Y?null:O.defaultDevice;return{...O,appFormats:P,defaultDevice:$}})},[]),N=i.useCallback(T=>{l(O=>({...O,defaultDevice:T}))},[]),C=i.useCallback(T=>{l(O=>({...O,designApproach:O.designApproach===T?null:T}))},[]),S=i.useCallback(async()=>{await Zd(o),r!==null&&ru(r),e==null||e(o)},[o,e,r]),R=i.useRef(!1);i.useEffect(()=>{R.current||x.state==="ready"&&b==="design-details"&&o.designApproach==="chat"&&c!==null&&c!==x.active&&(R.current=!0,S())},[b,o.designApproach,c,S,x]);const E=i.useCallback(()=>{a(T=>T+1)},[]),A=o.appFormats.includes("web"),D=(()=>{switch(b){case"product-type":return o.appFormats.length>0&&(!A||o.defaultDevice!==null);case"description":return o.description.trim().length>0;case"notifications":return!0;case"design-approach":return o.designApproach!==null;case"design-details":return o.designApproach==="chat"?c!==null:!0;default:return!0}})(),B=b==="description"?Su:b==="design-details"&&o.designApproach==="chat"?"100%":Cs;return n.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"auto"},children:[n.jsx(no,{}),n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",padding:"var(--spacing-xl, 32px)"},children:[n.jsxs("div",{style:{maxWidth:B},children:[b==="product-type"&&n.jsxs(n.Fragment,{children:[n.jsx(it,{title:"What type of 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:Nu.map(T=>n.jsx(Mt,{label:T.label,selected:o.appFormats.includes(T.id),onClick:()=>k(T.id),multi:!0},T.id))})}),A&&n.jsx(wu,{selected:o.defaultDevice,onSelect:N})]}),b==="description"&&n.jsx(it,{title:"Describe your product",subtitle:"What are you building? This helps us set up the right starting point.",children:n.jsx("textarea",{value:o.description,onChange:T=>l(O=>({...O,description:T.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"}})}),b==="tech-stack"&&n.jsx(it,{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(Mt,{label:"Let CodeYam decide",description:"We'll pick the best stack based on your product",selected:o.techStackId===null,onClick:()=>l(T=>({...T,techStackId:null}))}),m.map(T=>n.jsx(Mt,{label:T.name,description:T.description,selected:o.techStackId===T.id,onClick:()=>l(O=>({...O,techStackId:T.id}))},T.id))]})}),b==="notifications"&&n.jsx(xu,{}),b==="design-approach"&&n.jsx(hu,{selected:o.designApproach,onSelect:C}),b==="design-details"&&o.designApproach==="files"&&n.jsx(fu,{}),b==="design-details"&&o.designApproach==="chat"&&n.jsx(vu,{description:o.description,launched:u,onLaunched:v,onDesignSelected:d,onPreviewUrl:t})]}),n.jsxs("div",{style:{maxWidth:Cs},children:[n.jsx(ju,{step:s,canAdvance:D,isFinalStep:g,onBack:()=>a(T=>T-1),onNext:()=>{D&&E()},onFinish:S}),n.jsx(ku,{currentStep:s,stepLabels:y,onStepClick:a})]})]})]})}function Tu({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:b}){const{saved:g}=Kd();return r.length===0?o||g===null?null:!f&&!g?n.jsx(Eu,{onPreviewUrl:p,onComplete:m}):n.jsx(Jd,{projectDescription:t??null,onOpenBuildTab:h??(()=>{})}):n.jsxs("div",{className:"px-5 py-5",children:[n.jsx(Qd,{projectTitle:e,coverage:s,onCoverageClick:b}),n.jsx(Xd,{stats:r,onSelectApp:a,testsLoading:l,testsRefreshing:c,onRunTests:d,currentRunner:u})]})}function Pu({sessionContent:e,stepIndicator:t}){return n.jsxs("div",{className:"flex flex-col h-full",children:[t,e]})}function Du({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 Au(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 Fu(e,t){const r=lt(e),s=lt(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 Lu({resumeMode:e,previousProvider:t,currentProvider:r,awaitingUserInput:s=!1}){return e!=="handoff"||t==null||r==null||t===r?Au(s):Fu(t,r)}function Mu({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-active, #D7FF63)",color:"var(--text-on-accent, #0F0F0F)"},children:e})}function Iu({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 $u({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 Qn({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 Bu({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(Qn,{label:"Feature",value:e,rowClassName:"mb-1"}),t!=null&&r&&n.jsx(Qn,{label:"Step",value:`${t} (${r})`}),s&&n.jsx(Qn,{label:"Providers",value:s,rowClassName:"mt-1"})]})}function Ou(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 zu({featureName:e,editorStep:t,workflowMode:r,previousProvider:s,currentProvider:a,resumeMode:o,awaitingUserInput:l=!1,onContinue:c}){const d=Lu({resumeMode:o,previousProvider:s,currentProvider:a,awaitingUserInput:l}),u=t==null?null:Ar(t,r);return Ou(c),n.jsxs(Iu,{children:[n.jsx($u,{title:d.title,description:d.description}),n.jsx(Bu,{featureName:e,editorStep:t,editorStepLabel:u,providersLabel:d.providersLabel}),n.jsx(Mu,{label:d.buttonLabel,onContinue:c})]})}function _u({awaitingUserInput:e,currentProvider:t,editorStep:r,featureName:s,onContinue:a,previousProvider:o,resumeMode:l,workflowMode:c}){return n.jsx(zu,{featureName:s,editorStep:r,workflowMode:c,previousProvider:o,currentProvider:t,resumeMode:l,awaitingUserInput:e,onContinue:a})}function Hu({sessionDecision:e,sessionInfo:t,stepState:r}){return{recoveryFeatureName:(r==null?void 0:r.feature)??(t==null?void 0:t.feature)??null,recoveryStep:(r==null?void 0:r.step)??(t==null?void 0:t.step)??null,recoveryMode:(r==null?void 0:r.mode)??(t==null?void 0:t.mode)??null,showTerminal:(e==="continue"||e==="fresh"||e==="no-session")&&(r!==null||t!==null),shouldResumeSameProvider:e==="continue"&&(t==null?void 0:t.resumeMode)==="resume"}}const pn=8e3,Wu="agent-banner-ready",Vu="agent-auth-required";let vn=!1,yn=!1,Ke=[],Ss=!1,rt=null,at=null,mn=!1;function Uu(){Ss||typeof window>"u"||(Ss=!0,window.addEventListener(Wu,()=>{const e=!yn;if(e){yn=!0;const t=Ke;Ke=[];for(const r of t)r("banner")}if(mn&&(mn=!1,at&&rt===null)){K("dispatch-rename-after-auth",{label:at.label,reason:"first-observed-frame-after-auth"}),rt=at,gn(at.label,at.send);return}rt&&(K("dispatch-rename-reapply",{label:rt.label,reason:e?"first-observed-frame":"second-observed-frame"}),gn(rt.label,rt.send))}),window.addEventListener(Vu,()=>{mn=!0,K("agent-auth-required-observed",{});const e=Ke;Ke=[];for(const t of e)t("auth-required")}))}Uu();function Ku(){return yn?Promise.resolve("banner"):new Promise(e=>{let t=!1;const r=a=>{t||(t=!0,clearTimeout(s),e(a))};Ke.push(r);const s=setTimeout(()=>{if(t)return;t=!0;const a=Ke.indexOf(r);a>=0&&Ke.splice(a,1),e("fallback")},pn)})}async function ro(e,t,r=0,s=ir,a=!1){if(vn){K("dispatch-rename-suppressed",{caller:t,label:e});return}vn=!0,at={label:e,send:s},K("dispatch-rename",{phase:"queued",caller:t,label:e,fallbackMs:pn,postReadyDelayMs:r});const o=await Ku();if(o==="auth-required"){K("dispatch-rename-deferred-for-auth",{caller:t,label:e});return}if(a&&o==="fallback"){K("dispatch-rename-skipped-no-banner",{caller:t,label:e,fallbackMs:pn});return}r>0&&await new Promise(l=>setTimeout(l,r)),o==="fallback"&&K("dispatch-rename-fallback",{caller:t,label:e,fallbackMs:pn}),K("dispatch-rename",{phase:"fired",caller:t,label:e,source:o,postReadyDelayMs:r}),rt={label:e,send:s},gn(e,s)}function Gu(){vn=!1,yn=!1,Ke=[],rt=null,at=null,mn=!1}function Yu(){vn=!1,Ke=[],at=null}const qu="Editor";function Ju({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,ro(qu,"build-session-seed",Ca,void 0,!0)}},[e,t,r])}function Xu({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 Qu=1e3;let ur=0;function nn(){ur=Date.now()}function Zu(){return ur===0?1/0:Date.now()-ur}function ef(){return Zu()<Qu}function wn(){window.focus()}function so(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 tf({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),lu);return()=>window.clearTimeout(x)},[a]);const d=i.useCallback(x=>{o(x)},[]),u=i.useCallback((x,j)=>{const k=l.current.get(x);k&&(l.current.delete(x),k.resolve(j))},[]),f=i.useCallback((x,j)=>{const k=l.current.get(x);k&&(l.current.delete(x),k.reject(j))},[]),p=i.useCallback(x=>{for(const[,j]of l.current)j.reject(x);l.current.clear()},[]),m=i.useCallback(async x=>{if(x.size>bn)throw new Error(`File too large (max ${bn/(1024*1024)} MB)`);const j=e.current;if(!j||j.readyState!==WebSocket.OPEN)throw new Error("Not connected — try again in a moment");const k=await to(x),N=cu(),C=new Promise((S,R)=>{const E=window.setTimeout(()=>{l.current.delete(N)&&R(new Error("Timed out waiting for save to complete"))},iu);l.current.set(N,{resolve:A=>{window.clearTimeout(E),S(A)},reject:A=>{window.clearTimeout(E),R(new Error(A))}})});return j.send(JSON.stringify({type:"drop",id:N,name:x.name||"unnamed",mime:x.type||"application/octet-stream",data:k})),C},[e]),h=i.useCallback(async x=>{if(x.length===0)return;const j=[];for(const k of x)try{j.push(await m(k))}catch(N){const C=N instanceof Error?N.message:String(N);d(`Attach failed: ${C}`);return}t(j.map(du).join(" ")+" ")},[m,d,t]),b=i.useCallback(x=>{x.dataTransfer.types.includes("Files")&&(x.preventDefault(),c.current+=1,s(!0))},[]),g=i.useCallback(x=>{x.dataTransfer.types.includes("Files")&&x.preventDefault()},[]),y=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),uu(x.dataTransfer)){d("Folder drops are not supported — drag individual files instead");return}const j=Array.from(x.dataTransfer.files).filter(k=>k.size>0);await h(j)},[h,d]),v=i.useCallback(async x=>{var N;const j=(N=x.clipboardData)==null?void 0:N.items;if(!j)return;const k=[];for(const C of Array.from(j))if(C.kind==="file"&&C.type.startsWith("image/")){const S=C.getAsFile();S&&k.push(S)}k.length!==0&&(x.preventDefault(),await h(k))},[h]);return{dragActive:r,errorToast:a,dropHandlers:{onDragEnter:b,onDragOver:g,onDragLeave:y,onDrop:w},pasteHandler:v,resolveDrop:u,rejectDrop:f,cancelAllDrops:p,showError:d}}function ao(e){const[t,r]=i.useState(0);i.useEffect(()=>{if(t===0)return;const a=window.setTimeout(()=>r(0),e);return()=>window.clearTimeout(a)},[t,e]);const s=i.useCallback(()=>{r(a=>a+1)},[]);return[t>0,s]}function vt(e=typeof window<"u"?window:void 0){return e?e.self!==e.top:!1}function nf({isInIframe:e,previewKind:t,selectedScenario:r}){return e?!1:t!=="application"?!0:!r||!Et(r)}function rf(){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 sf({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})}function oo(){return n.jsx("div",{"data-testid":"terminal-copied-toast",style:{position:"absolute",bottom:12,left:"50%",transform:"translateX(-50%)",background:"#1f3a23",color:"#94ff94",border:"1px solid #397a39",borderRadius:4,padding:"6px 12px",fontFamily:"'IBM Plex Mono', monospace",fontSize:12,zIndex:6,pointerEvents:"none"},children:"Copied"})}const Es=15;function af({provider:e,agentStartMode:t,sessionId:r,onAgentIdle:s,onAgentActive:a,onUserInput:o,onStartupFailed:l,onStartupFailedCleared:c}){if(vt())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"),b=i.useRef(r??null),[g,y]=i.useState({kind:"connecting"}),[w,v]=i.useState(0),[x,j]=ao(1200);i.useEffect(()=>{h.current=t??"fresh",b.current=r??null},[t,r]);const k=i.useRef(s);k.current=s;const N=i.useRef(a);N.current=a;const C=i.useRef(o);C.current=o;const S=i.useRef(l);S.current=l;const R=i.useRef(c);R.current=c;const E=tf({wsRef:p,insertInput:D=>{var B,T;((B=p.current)==null?void 0:B.readyState)===WebSocket.OPEN&&p.current.send(JSON.stringify({type:"input",data:D})),nn(),(T=C.current)==null||T.call(C)}}),A=i.useRef(E);return A.current=E,so(d,()=>{var D;f.current&&u.current&&(f.current.fit(),((D=p.current)==null?void 0:D.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 D=new Sa.Terminal({cursorBlink:!0,fontSize:13,fontFamily:"'IBM Plex Mono', monospace",rightClickSelectsWord:!1,theme:{background:"#1e1e1e",foreground:"#cccccc",cursor:"#D7FF63",selectionBackground:"#264f78"}}),B=new Ea.FitAddon;D.loadAddon(B),D.open(d.current),u.current=D,f.current=B;const T=Ra(D,d.current,{onError:W=>A.current.showError(W),onCopy:()=>j()}),O=Ta(D,{sendInput:W=>{var z,J;((z=p.current)==null?void 0:z.readyState)===WebSocket.OPEN&&p.current.send(JSON.stringify({type:"input",data:W})),nn(),(J=C.current)==null||J.call(C)}});requestAnimationFrame(()=>{B.fit(),D.focus()});let Y=!1,P=0,$=null;function V(){try{const W=new WebSocket(il({provider:e,mode:h.current,sessionId:b.current??void 0,cols:D.cols,rows:D.rows}));p.current=W,W.binaryType="arraybuffer",W.onmessage=z=>{var J,U,se,ie;if(z.data instanceof ArrayBuffer)D.write(new Uint8Array(z.data));else if(typeof z.data=="string")try{const I=JSON.parse(z.data);if(I.type==="error"){Y=!0,y({kind:"server-error",message:ll(I)});return}if(I.type==="session-id")h.current="resume",b.current=I.sessionId??null;else if(I.type==="agent-idle"||I.type==="claude-idle"){const ne=typeof I.source=="string"?I.source:void 0;K("ws-message-received",{type:I.type,source:ne}),(J=k.current)==null||J.call(k,ne)}else if(I.type==="agent-active"||I.type==="claude-active")K("ws-message-received-active",{type:I.type}),(U=N.current)==null||U.call(N);else if(I.type==="idle-diag"){const{site:ne,event:le,...Z}=I;K(`rust:${le??"unknown"}`,{site:ne,...Z})}else I.type==="drop-complete"?A.current.resolveDrop(String(I.id??""),String(I.path??"")):I.type==="drop-error"?A.current.rejectDrop(String(I.id??""),String(I.message??"drop failed")):I.type==="startup-failed"?(se=S.current)==null||se.call(S,String(I.snippet??"")):I.type==="startup-failed-cleared"?(ie=R.current)==null||ie.call(R):I.type==="agent-banner-ready"?(K("agent-banner-ready",{}),window.dispatchEvent(new CustomEvent("agent-banner-ready"))):I.type==="agent-auth-required"?(K("agent-auth-required",{}),window.dispatchEvent(new CustomEvent("agent-auth-required"))):I.type==="agent-auth-resolved"&&(K("agent-auth-resolved",{}),window.dispatchEvent(new CustomEvent("agent-auth-resolved")))}catch{}},W.onopen=()=>{P=0,y({kind:"open"}),K("ws-open"),W.send(JSON.stringify({type:"resize",cols:D.cols,rows:D.rows}));try{typeof localStorage<"u"&&localStorage.getItem("codeyam.idleDebug")==="1"&&(W.send(JSON.stringify({type:"enable-idle-diag",sessionId:Er()})),K("idle-diag-enabled"))}catch{}},W.onerror=()=>{},W.onclose=async()=>{if(K("ws-close",{reconnectAttempts:P}),A.current.cancelAllDrops("Not connected"),Y){y(J=>J.kind==="server-error"?J:{kind:"ended"}),D.writeln(`\r
9
- \x1B[90m[Terminal session ended]\x1B[0m`);return}const z=await cl();if(!Y){if(!z){y({kind:"server-stopped"}),$==null||$(),$=dl(2e3,()=>{Y||window.location.reload()});return}if(P<Es){const J=P<4?1e3*Math.pow(2,P):1e4;P++,y({kind:"reconnecting",attempt:P,maxAttempts:Es}),setTimeout(()=>{Y||V()},J)}else y({kind:"failed"})}}}catch{y({kind:"failed"})}}try{B.fit()}catch{}V();let _=0;const X=1e3;function F(){var z;const W=Date.now();W-_>=X&&((z=p.current)==null?void 0:z.readyState)===WebSocket.OPEN&&(p.current.send(JSON.stringify({type:"browser-activity"})),_=W)}document.addEventListener("mousemove",F),document.addEventListener("keydown",F),document.addEventListener("mousedown",F),D.onData(W=>{var z,J;((z=p.current)==null?void 0:z.readyState)===WebSocket.OPEN?p.current.send(JSON.stringify({type:"input",data:W})):v(U=>U+1),nn(),(J=C.current)==null||J.call(C)});const L=d.current;function M(W){var I,ne,le,Z;const z=W,J=(I=z.clipboardData)==null?void 0:I.items;if(J){for(const de of Array.from(J))if(de.kind==="file"&&de.type.startsWith("image/")){W.preventDefault(),W.stopPropagation(),A.current.pasteHandler(z);return}}const U=((ne=z.clipboardData)==null?void 0:ne.getData("text"))??"";if(!U)return;W.preventDefault(),W.stopPropagation();const se=U.replace(/\r\n/g,"\r").replace(/\n/g,"\r"),ie=D.modes.bracketedPasteMode?`\x1B[200~${se}\x1B[201~`:se;((le=p.current)==null?void 0:le.readyState)===WebSocket.OPEN?p.current.send(JSON.stringify({type:"input",data:ie})):v(de=>de+1),nn(),(Z=C.current)==null||Z.call(C)}L.addEventListener("paste",M,!0);function Q(W){var U,se;const z=W.detail;if(!z)return;((U=p.current)==null?void 0:U.readyState)===WebSocket.OPEN?((se=p.current)==null||se.send(JSON.stringify({type:"input",data:z})),K("terminal-send-input",{len:z.length,firstChars:z.slice(0,16),wsOpen:!0,dropped:!1})):K("terminal-send-input",{len:z.length,firstChars:z.slice(0,16),wsOpen:!1,dropped:!0})}window.addEventListener("terminal-send-input",Q);function q(){wn(),D.focus()}return window.addEventListener("terminal-focus",q),()=>{var W;Y=!0,$==null||$(),$=null,document.removeEventListener("mousemove",F),document.removeEventListener("keydown",F),document.removeEventListener("mousedown",F),window.removeEventListener("terminal-send-input",Q),window.removeEventListener("terminal-focus",q),L.removeEventListener("paste",M,!0),O(),(W=p.current)==null||W.close(),T(),D.dispose(),m.current=!1}},[e]),n.jsxs("div",{className:"relative flex-1 flex flex-col",style:{minHeight:0},"data-terminal-emulator":!0,onDragEnter:E.dropHandlers.onDragEnter,onDragOver:E.dropHandlers.onDragOver,onDragLeave:E.dropHandlers.onDragLeave,onDrop:E.dropHandlers.onDrop,onPaste:E.pasteHandler,children:[n.jsx("div",{ref:d,className:"flex-1",style:{background:"#1e1e1e",minHeight:0,paddingTop:3,paddingLeft:3},onClick:()=>{var D;wn(),(D=u.current)==null||D.focus()}}),E.dragActive&&n.jsx(rf,{}),E.errorToast&&n.jsx(sf,{message:E.errorToast}),x&&n.jsx(oo,{}),n.jsx(ol,{status:g,pulseKey:w,onRefresh:()=>window.location.reload()})]})}function of({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);Ju({provider:s,agentStartMode:o?"resume":"fresh",currentFeature:l}),i.useEffect(()=>()=>{Gu()},[]);const p=i.useCallback(b=>{d(b)},[]),m=i.useCallback(()=>{d(null)},[]),h=i.useCallback(()=>{d(null),f(b=>b+1)},[]);return n.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[c!==null&&n.jsx(Xu,{snippet:c,onRetry:h,onDismiss:m}),n.jsx(af,{provider:s,agentStartMode:o?"resume":"fresh",sessionId:o?a:null,onAgentIdle:t,onAgentActive:e,onUserInput:r,onStartupFailed:p,onStartupFailedCleared:m},u)]})}function lf(){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 Rn=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Rt(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function $r(e){return"nodeType"in e}function Ne(e){var t,r;return e?Rt(e)?e:$r(e)&&(t=(r=e.ownerDocument)==null?void 0:r.defaultView)!=null?t:window:window}function Br(e){const{Document:t}=Ne(e);return e instanceof t}function Ut(e){return Rt(e)?!1:e instanceof Ne(e).HTMLElement}function io(e){return e instanceof Ne(e).SVGElement}function Tt(e){return e?Rt(e)?e.document:$r(e)?Br(e)?e:Ut(e)||io(e)?e.ownerDocument:document:document:document}const Ve=Rn?i.useLayoutEffect:i.useEffect;function Or(e){const t=i.useRef(e);return Ve(()=>{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 cf(){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 zt(e,t){t===void 0&&(t=[e]);const r=i.useRef(e);return Ve(()=>{r.current!==e&&(r.current=e)},t),r}function Kt(e,t){const r=i.useRef();return i.useMemo(()=>{const s=e(r.current);return r.current=s,s},[...t])}function jn(e){const t=Or(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 fr(e){const t=i.useRef();return i.useEffect(()=>{t.current=e},[e]),t.current}let Zn={};function Gt(e,t){return i.useMemo(()=>{if(t)return t;const r=Zn[e]==null?0:Zn[e]+1;return Zn[e]=r,e+"-"+r},[e,t])}function lo(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 Ct=lo(1),_t=lo(-1);function df(e){return"clientX"in e&&"clientY"in e}function zr(e){if(!e)return!1;const{KeyboardEvent:t}=Ne(e.target);return t&&e instanceof t}function uf(e){if(!e)return!1;const{TouchEvent:t}=Ne(e.target);return t&&e instanceof t}function pr(e){if(uf(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 df(e)?{x:e.clientX,y:e.clientY}:null}const Ht=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[Ht.Translate.toString(e),Ht.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:r,easing:s}=e;return t+" "+r+"ms "+s}}}),Rs="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function ff(e){return e.matches(Rs)?e:e.querySelector(Rs)}const pf={display:"none"};function mf(e){let{id:t,value:r}=e;return ke.createElement("div",{id:t,style:pf},r)}function hf(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 ke.createElement("div",{id:t,style:a,role:"status","aria-live":s,"aria-atomic":!0},r)}function xf(){const[e,t]=i.useState("");return{announce:i.useCallback(s=>{s!=null&&t(s)},[]),announcement:e}}const co=i.createContext(null);function gf(e){const t=i.useContext(co);i.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function bf(){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 vf={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
- `},yf={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 wf(e){let{announcements:t=yf,container:r,hiddenTextDescribedById:s,screenReaderInstructions:a=vf}=e;const{announce:o,announcement:l}=xf(),c=Gt("DndLiveRegion"),[d,u]=i.useState(!1);if(i.useEffect(()=>{u(!0)},[]),gf(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=ke.createElement(ke.Fragment,null,ke.createElement(mf,{id:s,value:a.draggable}),ke.createElement(hf,{id:c,announcement:l}));return r?Nt.createPortal(f,r):f}var pe;(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"})(pe||(pe={}));function kn(){}function Ts(e,t){return i.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function jf(){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 $e=Object.freeze({x:0,y:0});function uo(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function fo(e,t){let{data:{value:r}}=e,{data:{value:s}}=t;return r-s}function kf(e,t){let{data:{value:r}}=e,{data:{value:s}}=t;return s-r}function Ps(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 po(e,t){if(!e||e.length===0)return null;const[r]=e;return r[t]}function Ds(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 Nf=e=>{let{collisionRect:t,droppableRects:r,droppableContainers:s}=e;const a=Ds(t,t.left,t.top),o=[];for(const l of s){const{id:c}=l,d=r.get(c);if(d){const u=uo(Ds(d),a);o.push({id:c,data:{droppableContainer:l,value:u}})}}return o.sort(fo)},Cf=e=>{let{collisionRect:t,droppableRects:r,droppableContainers:s}=e;const a=Ps(t),o=[];for(const l of s){const{id:c}=l,d=r.get(c);if(d){const u=Ps(d),f=a.reduce((m,h,b)=>m+uo(u[b],h),0),p=Number((f/4).toFixed(4));o.push({id:c,data:{droppableContainer:l,value:p}})}}return o.sort(fo)};function Sf(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 Ef=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=Sf(c,t);d>0&&a.push({id:l,data:{droppableContainer:o,value:d}})}}return a.sort(kf)};function Rf(e,t,r){return{...e,scaleX:t&&r?t.width/r.width:1,scaleY:t&&r?t.height/r.height:1}}function mo(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:$e}function Tf(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 Pf=Tf(1);function Df(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 Af(e,t,r){const s=Df(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 Ff={ignoreTransform:!1};function Pt(e,t){t===void 0&&(t=Ff);let r=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:u,transformOrigin:f}=Ne(e).getComputedStyle(e);u&&(r=Af(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 As(e){return Pt(e,{ignoreTransform:!0})}function Lf(e){const t=e.innerWidth,r=e.innerHeight;return{top:0,left:0,right:t,bottom:r,width:t,height:r}}function Mf(e,t){return t===void 0&&(t=Ne(e).getComputedStyle(e)),t.position==="fixed"}function If(e,t){t===void 0&&(t=Ne(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 Tn(e,t){const r=[];function s(a){if(t!=null&&r.length>=t||!a)return r;if(Br(a)&&a.scrollingElement!=null&&!r.includes(a.scrollingElement))return r.push(a.scrollingElement),r;if(!Ut(a)||io(a)||r.includes(a))return r;const o=Ne(e).getComputedStyle(a);return a!==e&&If(a,o)&&r.push(a),Mf(a,o)?r:s(a.parentNode)}return e?s(e):r}function ho(e){const[t]=Tn(e,1);return t??null}function er(e){return!Rn||!e?null:Rt(e)?e:$r(e)?Br(e)||e===Tt(e).scrollingElement?window:Ut(e)?e:null:null}function xo(e){return Rt(e)?e.scrollX:e.scrollLeft}function go(e){return Rt(e)?e.scrollY:e.scrollTop}function mr(e){return{x:xo(e),y:go(e)}}var ge;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(ge||(ge={}));function bo(e){return!Rn||!e?!1:e===document.scrollingElement}function vo(e){const t={x:0,y:0},r=bo(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 $f={x:.2,y:.2};function Bf(e,t,r,s,a){let{top:o,left:l,right:c,bottom:d}=r;s===void 0&&(s=10),a===void 0&&(a=$f);const{isTop:u,isBottom:f,isLeft:p,isRight:m}=vo(e),h={x:0,y:0},b={x:0,y:0},g={height:t.height*a.y,width:t.width*a.x};return!u&&o<=t.top+g.height?(h.y=ge.Backward,b.y=s*Math.abs((t.top+g.height-o)/g.height)):!f&&d>=t.bottom-g.height&&(h.y=ge.Forward,b.y=s*Math.abs((t.bottom-g.height-d)/g.height)),!m&&c>=t.right-g.width?(h.x=ge.Forward,b.x=s*Math.abs((t.right-g.width-c)/g.width)):!p&&l<=t.left+g.width&&(h.x=ge.Backward,b.x=s*Math.abs((t.left+g.width-l)/g.width)),{direction:h,speed:b}}function Of(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 yo(e){return e.reduce((t,r)=>Ct(t,mr(r)),$e)}function zf(e){return e.reduce((t,r)=>t+xo(r),0)}function _f(e){return e.reduce((t,r)=>t+go(r),0)}function Hf(e,t){if(t===void 0&&(t=Pt),!e)return;const{top:r,left:s,bottom:a,right:o}=t(e);ho(e)&&(a<=0||o<=0||r>=window.innerHeight||s>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const Wf=[["x",["left","right"],zf],["y",["top","bottom"],_f]];class _r{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=Tn(r),a=yo(s);this.rect={...t},this.width=t.width,this.height=t.height;for(const[o,l,c]of Wf)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 It{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 Vf(e){const{EventTarget:t}=Ne(e);return e instanceof t?e:Tt(e)}function tr(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 Fe;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(Fe||(Fe={}));function Fs(e){e.preventDefault()}function Uf(e){e.stopPropagation()}var te;(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"})(te||(te={}));const wo={start:[te.Space,te.Enter],cancel:[te.Esc],end:[te.Space,te.Enter,te.Tab]},Kf=(e,t)=>{let{currentCoordinates:r}=t;switch(e.code){case te.Right:return{...r,x:r.x+25};case te.Left:return{...r,x:r.x-25};case te.Down:return{...r,y:r.y+25};case te.Up:return{...r,y:r.y-25}}};class Hr{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 It(Tt(r)),this.windowListeners=new It(Ne(r)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Fe.Resize,this.handleCancel),this.windowListeners.add(Fe.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Fe.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:r}=this.props,s=t.node.current;s&&Hf(s),r($e)}handleKeyDown(t){if(zr(t)){const{active:r,context:s,options:a}=this.props,{keyboardCodes:o=wo,coordinateGetter:l=Kf,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}:$e;this.referenceCoordinates||(this.referenceCoordinates=f);const p=l(t,{active:r,context:s.current,currentCoordinates:f});if(p){const m=_t(p,f),h={x:0,y:0},{scrollableAncestors:b}=s.current;for(const g of b){const y=t.code,{isTop:w,isRight:v,isLeft:x,isBottom:j,maxScroll:k,minScroll:N}=vo(g),C=Of(g),S={x:Math.min(y===te.Right?C.right-C.width/2:C.right,Math.max(y===te.Right?C.left:C.left+C.width/2,p.x)),y:Math.min(y===te.Down?C.bottom-C.height/2:C.bottom,Math.max(y===te.Down?C.top:C.top+C.height/2,p.y))},R=y===te.Right&&!v||y===te.Left&&!x,E=y===te.Down&&!j||y===te.Up&&!w;if(R&&S.x!==p.x){const A=g.scrollLeft+m.x,D=y===te.Right&&A<=k.x||y===te.Left&&A>=N.x;if(D&&!m.y){g.scrollTo({left:A,behavior:c});return}D?h.x=g.scrollLeft-A:h.x=y===te.Right?g.scrollLeft-k.x:g.scrollLeft-N.x,h.x&&g.scrollBy({left:-h.x,behavior:c});break}else if(E&&S.y!==p.y){const A=g.scrollTop+m.y,D=y===te.Down&&A<=k.y||y===te.Up&&A>=N.y;if(D&&!m.x){g.scrollTo({top:A,behavior:c});return}D?h.y=g.scrollTop-A:h.y=y===te.Down?g.scrollTop-k.y:g.scrollTop-N.y,h.y&&g.scrollBy({top:-h.y,behavior:c});break}}this.handleMove(t,Ct(_t(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()}}Hr.activators=[{eventName:"onKeyDown",handler:(e,t,r)=>{let{keyboardCodes:s=wo,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 Ls(e){return!!(e&&"distance"in e)}function Ms(e){return!!(e&&"delay"in e)}class Wr{constructor(t,r,s){var a;s===void 0&&(s=Vf(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=Tt(l),this.documentListeners=new It(this.document),this.listeners=new It(s),this.windowListeners=new It(Ne(l)),this.initialCoordinates=(a=pr(o))!=null?a:$e,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(Fe.Resize,this.handleCancel),this.windowListeners.add(Fe.DragStart,Fs),this.windowListeners.add(Fe.VisibilityChange,this.handleCancel),this.windowListeners.add(Fe.ContextMenu,Fs),this.documentListeners.add(Fe.Keydown,this.handleKeydown),r){if(s!=null&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Ms(r)){this.timeoutId=setTimeout(this.handleStart,r.delay),this.handlePending(r);return}if(Ls(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(Fe.Click,Uf,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Fe.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=pr(t))!=null?r:$e,u=_t(a,d);if(!s&&c){if(Ls(c)){if(c.tolerance!=null&&tr(u,c.tolerance))return this.handleCancel();if(tr(u,c.distance))return this.handleStart()}if(Ms(c)&&tr(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===te.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const Gf={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Vr extends Wr{constructor(t){const{event:r}=t,s=Tt(r.target);super(t,Gf,s)}}Vr.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 Yf={move:{name:"mousemove"},end:{name:"mouseup"}};var hr;(function(e){e[e.RightClick=2]="RightClick"})(hr||(hr={}));class qf extends Wr{constructor(t){super(t,Yf,Tt(t.event.target))}}qf.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:r}=e,{onActivation:s}=t;return r.button===hr.RightClick?!1:(s==null||s({event:r}),!0)}}];const nr={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class Jf extends Wr{constructor(t){super(t,nr)}static setup(){return window.addEventListener(nr.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(nr.move.name,t)};function t(){}}}Jf.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 $t;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})($t||($t={}));var Nn;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(Nn||(Nn={}));function Xf(e){let{acceleration:t,activator:r=$t.Pointer,canScroll:s,draggingRect:a,enabled:o,interval:l=5,order:c=Nn.TreeOrder,pointerCoordinates:d,scrollableAncestors:u,scrollableAncestorRects:f,delta:p,threshold:m}=e;const h=Zf({delta:p,disabled:!o}),[b,g]=cf(),y=i.useRef({x:0,y:0}),w=i.useRef({x:0,y:0}),v=i.useMemo(()=>{switch(r){case $t.Pointer:return d?{top:d.y,bottom:d.y,left:d.x,right:d.x}:null;case $t.DraggableRect:return a}},[r,a,d]),x=i.useRef(null),j=i.useCallback(()=>{const N=x.current;if(!N)return;const C=y.current.x*w.current.x,S=y.current.y*w.current.y;N.scrollBy(C,S)},[]),k=i.useMemo(()=>c===Nn.TreeOrder?[...u].reverse():u,[c,u]);i.useEffect(()=>{if(!o||!u.length||!v){g();return}for(const N of k){if((s==null?void 0:s(N))===!1)continue;const C=u.indexOf(N),S=f[C];if(!S)continue;const{direction:R,speed:E}=Bf(N,S,v,t,m);for(const A of["x","y"])h[A][R[A]]||(E[A]=0,R[A]=0);if(E.x>0||E.y>0){g(),x.current=N,b(j,l),y.current=E,w.current=R;return}}y.current={x:0,y:0},w.current={x:0,y:0},g()},[t,j,s,g,o,l,JSON.stringify(v),JSON.stringify(h),b,u,k,f,JSON.stringify(m)])}const Qf={x:{[ge.Backward]:!1,[ge.Forward]:!1},y:{[ge.Backward]:!1,[ge.Forward]:!1}};function Zf(e){let{delta:t,disabled:r}=e;const s=fr(t);return Kt(a=>{if(r||!s||!a)return Qf;const o={x:Math.sign(t.x-s.x),y:Math.sign(t.y-s.y)};return{x:{[ge.Backward]:a.x[ge.Backward]||o.x===-1,[ge.Forward]:a.x[ge.Forward]||o.x===1},y:{[ge.Backward]:a.y[ge.Backward]||o.y===-1,[ge.Forward]:a.y[ge.Forward]||o.y===1}}},[r,t,s])}function ep(e,t){const r=t!=null?e.get(t):void 0,s=r?r.node.current:null;return Kt(a=>{var o;return t==null?null:(o=s??a)!=null?o:null},[s,t])}function tp(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 Wt;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Wt||(Wt={}));var xr;(function(e){e.Optimized="optimized"})(xr||(xr={}));const Is=new Map;function np(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=y(),m=zt(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]),b=i.useRef(null),g=Kt(w=>{if(p&&!r)return Is;if(!w||w===Is||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 j=x.node.current,k=j?new _r(d(j),j):null;x.rect.current=k,k&&v.set(x.id,k)}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"||b.current!==null||(b.current=setTimeout(()=>{h(),b.current=null},c))},[c,p,h,...s]),{droppableRects:g,measureDroppableContainers:h,measuringScheduled:o!=null};function y(){switch(u){case Wt.Always:return!1;case Wt.BeforeDragging:return r;default:return!r}}}function jo(e,t){return Kt(r=>e?r||(typeof t=="function"?t(e):e):null,[t,e])}function rp(e,t){return jo(e,t)}function sp(e){let{callback:t,disabled:r}=e;const s=Or(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 Pn(e){let{callback:t,disabled:r}=e;const s=Or(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 ap(e){return new _r(Pt(e),e)}function $s(e,t,r){t===void 0&&(t=ap);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=sp({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=Pn({callback:o});return Ve(()=>{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 op(e){const t=jo(e);return mo(e,t)}const Bs=[];function ip(e){const t=i.useRef(e),r=Kt(s=>e?s&&s!==Bs&&e&&t.current&&e.parentNode===t.current.parentNode?s:Tn(e):Bs,[e]);return i.useEffect(()=>{t.current=e},[e]),r}function lp(e){const[t,r]=i.useState(null),s=i.useRef(e),a=i.useCallback(o=>{const l=er(o.target);l&&r(c=>c?(c.set(l,mr(l)),new Map(c)):null)},[]);return i.useEffect(()=>{const o=s.current;if(e!==o){l(o);const c=e.map(d=>{const u=er(d);return u?(u.addEventListener("scroll",a,{passive:!0}),[u,mr(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=er(d);u==null||u.removeEventListener("scroll",a)})}},[a,e]),i.useMemo(()=>e.length?t?Array.from(t.values()).reduce((o,l)=>Ct(o,l),$e):yo(e):$e,[e,t])}function Os(e,t){t===void 0&&(t=[]);const r=i.useRef(null);return i.useEffect(()=>{r.current=null},t),i.useEffect(()=>{const s=e!==$e;s&&!r.current&&(r.current=e),!s&&r.current&&(r.current=null)},[e]),r.current?_t(e,r.current):$e}function cp(e){i.useEffect(()=>{if(!Rn)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 dp(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 ko(e){return i.useMemo(()=>e?Lf(e):null,[e])}const zs=[];function up(e,t){t===void 0&&(t=Pt);const[r]=e,s=ko(r?Ne(r):null),[a,o]=i.useState(zs);function l(){o(()=>e.length?e.map(d=>bo(d)?s:new _r(t(d),d)):zs)}const c=Pn({callback:l});return Ve(()=>{c==null||c.disconnect(),l(),e.forEach(d=>c==null?void 0:c.observe(d))},[e]),a}function fp(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return Ut(t)?t:e}function pp(e){let{measure:t}=e;const[r,s]=i.useState(null),a=i.useCallback(u=>{for(const{target:f}of u)if(Ut(f)){s(p=>{const m=t(f);return p?{...p,width:m.width,height:m.height}:m});break}},[t]),o=Pn({callback:a}),l=i.useCallback(u=>{const f=fp(u);o==null||o.disconnect(),f&&(o==null||o.observe(f)),s(f?t(f):null)},[t,o]),[c,d]=jn(l);return i.useMemo(()=>({nodeRef:c,rect:r,setRef:d}),[r,c,d])}const mp=[{sensor:Vr,options:{}},{sensor:Hr,options:{}}],hp={current:{}},hn={draggable:{measure:As},droppable:{measure:As,strategy:Wt.WhileDragging,frequency:xr.Optimized},dragOverlay:{measure:Pt}};class Bt 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 xp={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Bt,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:kn},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:hn,measureDroppableContainers:kn,windowRect:null,measuringScheduled:!1},gp={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:kn,draggableNodes:new Map,over:null,measureDroppableContainers:kn},Dn=i.createContext(gp),No=i.createContext(xp);function bp(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Bt}}}function vp(e,t){switch(t.type){case pe.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case pe.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 pe.DragEnd:case pe.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case pe.RegisterDroppable:{const{element:r}=t,{id:s}=r,a=new Bt(e.droppable.containers);return a.set(s,r),{...e,droppable:{...e.droppable,containers:a}}}case pe.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 Bt(e.droppable.containers);return l.set(r,{...o,disabled:a}),{...e,droppable:{...e.droppable,containers:l}}}case pe.UnregisterDroppable:{const{id:r,key:s}=t,a=e.droppable.containers.get(r);if(!a||s!==a.key)return e;const o=new Bt(e.droppable.containers);return o.delete(r),{...e,droppable:{...e.droppable,containers:o}}}default:return e}}function yp(e){let{disabled:t}=e;const{active:r,activatorEvent:s,draggableNodes:a}=i.useContext(Dn),o=fr(s),l=fr(r==null?void 0:r.id);return i.useEffect(()=>{if(!t&&!s&&o&&l!=null){if(!zr(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=ff(f);if(p){p.focus();break}}})}},[s,t,a,l,o]),null}function wp(e,t){let{transform:r,...s}=t;return e!=null&&e.length?e.reduce((a,o)=>o({transform:a,...s}),r):r}function jp(e){return i.useMemo(()=>({draggable:{...hn.draggable,...e==null?void 0:e.draggable},droppable:{...hn.droppable,...e==null?void 0:e.droppable},dragOverlay:{...hn.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 kp(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;Ve(()=>{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=mo(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=ho(u);m&&m.scrollBy({top:p.y,left:p.x})}},[t,l,c,s,r])}const Co=i.createContext({...$e,scaleX:1,scaleY:1});var st;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(st||(st={}));const Np=i.memo(function(t){var r,s,a,o;let{id:l,accessibility:c,autoScroll:d=!0,children:u,sensors:f=mp,collisionDetection:p=Ef,measuring:m,modifiers:h,...b}=t;const g=i.useReducer(vp,void 0,bp),[y,w]=g,[v,x]=bf(),[j,k]=i.useState(st.Uninitialized),N=j===st.Initialized,{draggable:{active:C,nodes:S,translate:R},droppable:{containers:E}}=y,A=C!=null?S.get(C):null,D=i.useRef({initial:null,translated:null}),B=i.useMemo(()=>{var ue;return C!=null?{id:C,data:(ue=A==null?void 0:A.data)!=null?ue:hp,rect:D}:null},[C,A]),T=i.useRef(null),[O,Y]=i.useState(null),[P,$]=i.useState(null),V=zt(b,Object.values(b)),_=Gt("DndDescribedBy",l),X=i.useMemo(()=>E.getEnabled(),[E]),F=jp(m),{droppableRects:L,measureDroppableContainers:M,measuringScheduled:Q}=np(X,{dragging:N,dependencies:[R.x,R.y],config:F.droppable}),q=ep(S,C),W=i.useMemo(()=>P?pr(P):null,[P]),z=Dt(),J=rp(q,F.draggable.measure);kp({activeNode:C!=null?S.get(C):null,config:z.layoutShiftCompensation,initialRect:J,measure:F.draggable.measure});const U=$s(q,F.draggable.measure,J),se=$s(q?q.parentElement:null),ie=i.useRef({activatorEvent:null,active:null,activeNode:q,collisionRect:null,collisions:null,droppableRects:L,draggableNodes:S,draggingNode:null,draggingNodeRect:null,droppableContainers:E,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),I=E.getNodeFor((r=ie.current.over)==null?void 0:r.id),ne=pp({measure:F.dragOverlay.measure}),le=(s=ne.nodeRef.current)!=null?s:q,Z=N?(a=ne.rect)!=null?a:U:null,de=!!(ne.nodeRef.current&&ne.rect),we=op(de?null:U),ce=ko(le?Ne(le):null),re=ip(N?I??q:null),Be=up(re),Te=wp(h,{transform:{x:R.x-we.x,y:R.y-we.y,scaleX:1,scaleY:1},activatorEvent:P,active:B,activeNodeRect:U,containerNodeRect:se,draggingNodeRect:Z,over:ie.current.over,overlayNodeRect:ne.rect,scrollableAncestors:re,scrollableAncestorRects:Be,windowRect:ce}),qe=W?Ct(W,R):null,G=lp(re),ut=Os(G),yt=Os(G,[U]),Oe=Ct(Te,ut),Ce=Z?Pf(Z,Te):null,Pe=B&&Ce?p({active:B,collisionRect:Ce,droppableRects:L,droppableContainers:X,pointerCoordinates:qe}):null,wt=po(Pe,"id"),[be,Je]=i.useState(null),Le=de?Te:Ct(Te,yt),je=Rf(Le,(o=be==null?void 0:be.rect)!=null?o:null,U),Xe=i.useRef(null),Qe=i.useCallback((ue,me)=>{let{sensor:he,options:Ee}=me;if(T.current==null)return;const H=S.get(T.current);if(!H)return;const ae=ue.nativeEvent,fe=new he({active:T.current,activeNode:H,event:ae,options:Ee,context:ie,onAbort(oe){if(!S.get(oe))return;const{onDragAbort:Ae}=V.current,ve={id:oe};Ae==null||Ae(ve),v({type:"onDragAbort",event:ve})},onPending(oe,De,Ae,ve){if(!S.get(oe))return;const{onDragPending:ft}=V.current,ze={id:oe,constraint:De,initialCoordinates:Ae,offset:ve};ft==null||ft(ze),v({type:"onDragPending",event:ze})},onStart(oe){const De=T.current;if(De==null)return;const Ae=S.get(De);if(!Ae)return;const{onDragStart:ve}=V.current,et={activatorEvent:ae,active:{id:De,data:Ae.data,rect:D}};Nt.unstable_batchedUpdates(()=>{ve==null||ve(et),k(st.Initializing),w({type:pe.DragStart,initialCoordinates:oe,active:De}),v({type:"onDragStart",event:et}),Y(Xe.current),$(ae)})},onMove(oe){w({type:pe.DragMove,coordinates:oe})},onEnd:xe(pe.DragEnd),onCancel:xe(pe.DragCancel)});Xe.current=fe;function xe(oe){return async function(){const{active:Ae,collisions:ve,over:et,scrollAdjustedTranslate:ft}=ie.current;let ze=null;if(Ae&&ft){const{cancelDrop:tt}=V.current;ze={activatorEvent:ae,active:Ae,collisions:ve,delta:ft,over:et},oe===pe.DragEnd&&typeof tt=="function"&&await Promise.resolve(tt(ze))&&(oe=pe.DragCancel)}T.current=null,Nt.unstable_batchedUpdates(()=>{w({type:oe}),k(st.Uninitialized),Je(null),Y(null),$(null),Xe.current=null;const tt=oe===pe.DragEnd?"onDragEnd":"onDragCancel";if(ze){const Me=V.current[tt];Me==null||Me(ze),v({type:tt,event:ze})}})}}},[S]),Se=i.useCallback((ue,me)=>(he,Ee)=>{const H=he.nativeEvent,ae=S.get(Ee);if(T.current!==null||!ae||H.dndKit||H.defaultPrevented)return;const fe={active:ae};ue(he,me.options,fe)===!0&&(H.dndKit={capturedBy:me.sensor},T.current=Ee,Qe(he,me))},[S,Qe]),Ze=tp(f,Se);cp(f),Ve(()=>{U&&j===st.Initializing&&k(st.Initialized)},[U,j]),i.useEffect(()=>{const{onDragMove:ue}=V.current,{active:me,activatorEvent:he,collisions:Ee,over:H}=ie.current;if(!me||!he)return;const ae={active:me,activatorEvent:he,collisions:Ee,delta:{x:Oe.x,y:Oe.y},over:H};Nt.unstable_batchedUpdates(()=>{ue==null||ue(ae),v({type:"onDragMove",event:ae})})},[Oe.x,Oe.y]),i.useEffect(()=>{const{active:ue,activatorEvent:me,collisions:he,droppableContainers:Ee,scrollAdjustedTranslate:H}=ie.current;if(!ue||T.current==null||!me||!H)return;const{onDragOver:ae}=V.current,fe=Ee.get(wt),xe=fe&&fe.rect.current?{id:fe.id,rect:fe.rect.current,data:fe.data,disabled:fe.disabled}:null,oe={active:ue,activatorEvent:me,collisions:he,delta:{x:H.x,y:H.y},over:xe};Nt.unstable_batchedUpdates(()=>{Je(xe),ae==null||ae(oe),v({type:"onDragOver",event:oe})})},[wt]),Ve(()=>{ie.current={activatorEvent:P,active:B,activeNode:q,collisionRect:Ce,collisions:Pe,droppableRects:L,draggableNodes:S,draggingNode:le,draggingNodeRect:Z,droppableContainers:E,over:be,scrollableAncestors:re,scrollAdjustedTranslate:Oe},D.current={initial:Z,translated:Ce}},[B,q,Pe,Ce,S,le,Z,L,E,be,re,Oe]),Xf({...z,delta:R,draggingRect:Ce,pointerCoordinates:qe,scrollableAncestors:re,scrollableAncestorRects:Be});const Ue=i.useMemo(()=>({active:B,activeNode:q,activeNodeRect:U,activatorEvent:P,collisions:Pe,containerNodeRect:se,dragOverlay:ne,draggableNodes:S,droppableContainers:E,droppableRects:L,over:be,measureDroppableContainers:M,scrollableAncestors:re,scrollableAncestorRects:Be,measuringConfiguration:F,measuringScheduled:Q,windowRect:ce}),[B,q,U,P,Pe,se,ne,S,E,L,be,M,re,Be,F,Q,ce]),ye=i.useMemo(()=>({activatorEvent:P,activators:Ze,active:B,activeNodeRect:U,ariaDescribedById:{draggable:_},dispatch:w,draggableNodes:S,over:be,measureDroppableContainers:M}),[P,Ze,B,U,w,_,S,be,M]);return ke.createElement(co.Provider,{value:x},ke.createElement(Dn.Provider,{value:ye},ke.createElement(No.Provider,{value:Ue},ke.createElement(Co.Provider,{value:je},u)),ke.createElement(yp,{disabled:(c==null?void 0:c.restoreFocus)===!1})),ke.createElement(wf,{...c,hiddenTextDescribedById:_}));function Dt(){const ue=(O==null?void 0:O.autoScrollEnabled)===!1,me=typeof d=="object"?d.enabled===!1:d===!1,he=N&&!ue&&!me;return typeof d=="object"?{...d,enabled:he}:{enabled:he}}}),Cp=i.createContext(null),_s="button",Sp="Draggable";function Ep(e){let{id:t,data:r,disabled:s=!1,attributes:a}=e;const o=Gt(Sp),{activators:l,activatorEvent:c,active:d,activeNodeRect:u,ariaDescribedById:f,draggableNodes:p,over:m}=i.useContext(Dn),{role:h=_s,roleDescription:b="draggable",tabIndex:g=0}=a??{},y=(d==null?void 0:d.id)===t,w=i.useContext(y?Co:Cp),[v,x]=jn(),[j,k]=jn(),N=dp(l,t),C=zt(r);Ve(()=>(p.set(t,{id:t,key:o,node:v,activatorNode:j,data:C}),()=>{const R=p.get(t);R&&R.key===o&&p.delete(t)}),[p,t]);const S=i.useMemo(()=>({role:h,tabIndex:g,"aria-disabled":s,"aria-pressed":y&&h===_s?!0:void 0,"aria-roledescription":b,"aria-describedby":f.draggable}),[s,h,g,y,b,f.draggable]);return{active:d,activatorEvent:c,activeNodeRect:u,attributes:S,isDragging:y,listeners:s?void 0:N,node:v,over:m,setNodeRef:x,setActivatorNodeRef:k,transform:w}}function Rp(){return i.useContext(No)}const Tp="Droppable",Pp={timeout:25};function Dp(e){let{data:t,disabled:r=!1,id:s,resizeObserverConfig:a}=e;const o=Gt(Tp),{active:l,dispatch:c,over:d,measureDroppableContainers:u}=i.useContext(Dn),f=i.useRef({disabled:r}),p=i.useRef(!1),m=i.useRef(null),h=i.useRef(null),{disabled:b,updateMeasurementsFor:g,timeout:y}={...Pp,...a},w=zt(g??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},y)},[y]),x=Pn({callback:v,disabled:b||!l}),j=i.useCallback((S,R)=>{x&&(R&&(x.unobserve(R),p.current=!1),S&&x.observe(S))},[x]),[k,N]=jn(j),C=zt(t);return i.useEffect(()=>{!x||!k.current||(x.disconnect(),p.current=!1,x.observe(k.current))},[k,x]),i.useEffect(()=>(c({type:pe.RegisterDroppable,element:{id:s,key:o,disabled:r,node:k,rect:m,data:C}}),()=>c({type:pe.UnregisterDroppable,key:o,id:s})),[s]),i.useEffect(()=>{r!==f.current.disabled&&(c({type:pe.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:k,over:d,setNodeRef:N}}function Ur(e,t,r){const s=e.slice();return s.splice(r<0?s.length+r:r,0,s.splice(t,1)[0]),s}function Ap(e,t){return e.reduce((r,s,a)=>{const o=t.get(s);return o&&(r[a]=o),r},Array(e.length))}function rn(e){return e!==null&&e>=0}function Fp(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 Lp(e){return typeof e=="boolean"?{draggable:e,droppable:e}:e}const So=e=>{let{rects:t,activeIndex:r,overIndex:s,index:a}=e;const o=Ur(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}},sn={scaleX:1,scaleY:1},Mp=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,...sn}:null}const d=Ip(o,a,r);return a>r&&a<=l?{x:0,y:-c.height-d,...sn}:a<r&&a>=l?{x:0,y:c.height+d,...sn}:{x:0,y:0,...sn}};function Ip(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 Eo="Sortable",Ro=ke.createContext({activeIndex:-1,containerId:Eo,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:So,disabled:{draggable:!1,droppable:!1}});function $p(e){let{children:t,id:r,items:s,strategy:a=So,disabled:o=!1}=e;const{active:l,dragOverlay:c,droppableRects:d,over:u,measureDroppableContainers:f}=Rp(),p=Gt(Eo,r),m=c.rect!==null,h=i.useMemo(()=>s.map(N=>typeof N=="object"&&"id"in N?N.id:N),[s]),b=l!=null,g=l?h.indexOf(l.id):-1,y=u?h.indexOf(u.id):-1,w=i.useRef(h),v=!Fp(h,w.current),x=y!==-1&&g===-1||v,j=Lp(o);Ve(()=>{v&&b&&f(h)},[v,h,b,f]),i.useEffect(()=>{w.current=h},[h]);const k=i.useMemo(()=>({activeIndex:g,containerId:p,disabled:j,disableTransforms:x,items:h,overIndex:y,useDragOverlay:m,sortedRects:Ap(h,d),strategy:a}),[g,p,j.draggable,j.droppable,x,h,y,d,m,a]);return ke.createElement(Ro.Provider,{value:k},t)}const Bp=e=>{let{id:t,items:r,activeIndex:s,overIndex:a}=e;return Ur(r,s,a).indexOf(t)},Op=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},zp={duration:200,easing:"ease"},To="transform",_p=Ht.Transition.toString({property:To,duration:0,easing:"linear"}),Hp={roleDescription:"sortable"};function Wp(e){let{disabled:t,index:r,node:s,rect:a}=e;const[o,l]=i.useState(null),c=i.useRef(r);return Ve(()=>{if(!t&&r!==c.current&&s.current){const d=a.current;if(d){const u=Pt(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 Vp(e){let{animateLayoutChanges:t=Op,attributes:r,disabled:s,data:a,getNewIndex:o=Bp,id:l,strategy:c,resizeObserverConfig:d,transition:u=zp}=e;const{items:f,containerId:p,activeIndex:m,disabled:h,disableTransforms:b,sortedRects:g,overIndex:y,useDragOverlay:w,strategy:v}=i.useContext(Ro),x=Up(s,h),j=f.indexOf(l),k=i.useMemo(()=>({sortable:{containerId:p,index:j,items:f},...a}),[p,a,j,f]),N=i.useMemo(()=>f.slice(f.indexOf(l)),[f,l]),{rect:C,node:S,isOver:R,setNodeRef:E}=Dp({id:l,data:k,disabled:x.droppable,resizeObserverConfig:{updateMeasurementsFor:N,...d}}),{active:A,activatorEvent:D,activeNodeRect:B,attributes:T,setNodeRef:O,listeners:Y,isDragging:P,over:$,setActivatorNodeRef:V,transform:_}=Ep({id:l,data:k,attributes:{...Hp,...r},disabled:x.draggable}),X=lf(E,O),F=!!A,L=F&&!b&&rn(m)&&rn(y),M=!w&&P,Q=M&&L?_:null,W=L?Q??(c??v)({rects:g,activeNodeRect:B,activeIndex:m,overIndex:y,index:j}):null,z=rn(m)&&rn(y)?o({id:l,items:f,activeIndex:m,overIndex:y}):j,J=A==null?void 0:A.id,U=i.useRef({activeId:J,items:f,newIndex:z,containerId:p}),se=f!==U.current.items,ie=t({active:A,containerId:p,isDragging:P,isSorting:F,id:l,index:j,items:f,newIndex:U.current.newIndex,previousItems:U.current.items,previousContainerId:U.current.containerId,transition:u,wasDragging:U.current.activeId!=null}),I=Wp({disabled:!ie,index:j,node:S,rect:C});return i.useEffect(()=>{F&&U.current.newIndex!==z&&(U.current.newIndex=z),p!==U.current.containerId&&(U.current.containerId=p),f!==U.current.items&&(U.current.items=f)},[F,z,p,f]),i.useEffect(()=>{if(J===U.current.activeId)return;if(J!=null&&U.current.activeId==null){U.current.activeId=J;return}const le=setTimeout(()=>{U.current.activeId=J},50);return()=>clearTimeout(le)},[J]),{active:A,activeIndex:m,attributes:T,data:k,rect:C,index:j,newIndex:z,items:f,isOver:R,isSorting:F,isDragging:P,listeners:Y,node:S,overIndex:y,over:$,setNodeRef:X,setActivatorNodeRef:V,setDroppableNodeRef:E,setDraggableNodeRef:O,transform:I??W,transition:ne()};function ne(){if(I||se&&U.current.newIndex===j)return _p;if(!(M&&!zr(D)||!u)&&(F||ie))return Ht.Transition.toString({...u,property:To})}}function Up(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 Cn(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 Kp=[te.Down,te.Right,te.Up,te.Left],Gp=(e,t)=>{let{context:{active:r,collisionRect:s,droppableRects:a,droppableContainers:o,over:l,scrollableAncestors:c}}=t;if(Kp.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 te.Down:s.top<m.top&&d.push(p);break;case te.Up:s.top>m.top&&d.push(p);break;case te.Left:s.left>m.left&&d.push(p);break;case te.Right:s.left<m.left&&d.push(p);break}});const u=Cf({collisionRect:s,droppableRects:a,droppableContainers:d});let f=po(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,b=m==null?void 0:m.node.current;if(b&&h&&p&&m){const y=Tn(b).some((N,C)=>c[C]!==N),w=Po(p,m),v=Yp(p,m),x=y||!w?{x:0,y:0}:{x:v?s.width-h.width:0,y:v?s.height-h.height:0},j={x:h.left,y:h.top};return x.x&&x.y?j:_t(j,x)}}}};function Po(e,t){return!Cn(e)||!Cn(t)?!1:e.data.current.sortable.containerId===t.data.current.sortable.containerId}function Yp(e,t){return!Cn(e)||!Cn(t)||!Po(e,t)?!1:e.data.current.sortable.index<t.data.current.sortable.index}function ct(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 Do({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 Yt(){const[e,t]=i.useState(()=>Date.now());return i.useEffect(()=>{const r=setInterval(()=>t(Date.now()),1e3);return()=>clearInterval(r)},[]),e}function Ao(e){return{dead:e.sessionAlive===!1}}function qp({claim:e,staleFetch:t=!1}){const r=Yt(),{dead:s}=Ao(e),a=e.claimedBy.agentProvider??"agent",o=s?" (inactive)":"",l=ct(e.claimedBy.startedAt,r),c=e.source==="local"?`● this session · started ${l}`:e.source==="same-machine"?`claimed by ${a}@${e.claimedBy.machine} (same machine) · ${l}`:`claimed by ${a}@${e.claimedBy.machine} · ${l}`;return n.jsxs("span",{"data-testid":`plan-row-claim-badge-${e.slug}`,title:`Source: ${e.source}${o}${t?" (data may be stale)":""}`,className:"text-[10px] font-medium whitespace-nowrap px-1.5 py-0.5 rounded border",style:{borderColor:"var(--accent-orange)",backgroundColor:"color-mix(in srgb, var(--accent-orange) 12%, transparent)",color:"var(--text-primary)"},children:[c,o]})}function Jp(){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 Xp({slug:e,onClose:t}){return n.jsx("div",{className:"px-3 py-2 border-t border-[var(--border-subtle)]",children:n.jsx(Sn,{chatName:`edit-plan-${e}`,slashCommand:`/codeyam-edit-plan ${e}`,height:360,onClose:t})})}function Qp({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 Zp({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 em({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 tm({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 nm({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(tm,{dep:t},t.slug))})]})}function rm({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(Do,{title:e,filePath:t}),l&&l.length>0&&n.jsx(nm,{dependencies:l}),n.jsx("div",{className:"px-3 py-2 max-h-[40vh] overflow-y-auto",children:n.jsx(ht,{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(Zp,{onClick:a}),n.jsx(em,{providerLabel:s,onClick:o})]})]})}function sm({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}=Jp(),{config:p}=dt(),m=lt(p==null?void 0:p.provider);return i.useEffect(()=>{o(e.title),c(e.body),s("view")},[e.slug]),r==="chat"?n.jsx(Xp,{slug:e.slug,onClose:()=>s("view")}):r==="edit"?n.jsx(Qp,{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(rm,{title:e.title,filePath:e.filePath,body:e.body,providerLabel:m,onEdit:()=>s("edit"),onChat:()=>s("chat"),dependencies:t})}const Fo="Building is in progress, please wait for it to complete before starting a new build session.";function am({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?Fo:void 0,className:l+(u?c:""),children:r?"Launching…":"Run"})}function Lo({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:b=0,unsatisfiedDepTooltip:g,dependencies:y,claim:w,staleFetch:v=!1,expandedBodyVariant:x="full"}){const j=k=>{(k.key==="Enter"||k.key===" ")&&(k.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:j,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:k=>k.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(am,{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}),b>0&&n.jsxs("span",{"data-testid":`plan-row-blocked-${e.slug}`,title:g,className:"text-[10px] whitespace-nowrap px-1.5 py-0.5 rounded border border-[var(--border-subtle)] text-[var(--text-dim)] inline-flex items-center gap-1",children:["🔒 blocked · ",b," dep",b===1?"":"s"]}),w&&n.jsx(qp,{claim:w,staleFetch:v}),n.jsx("span",{className:"text-[10px] text-[var(--text-dim)] whitespace-nowrap",children:ct(e.createdAt)})]}),t&&(x==="view"?n.jsxs("div",{className:"border-t border-[var(--border-subtle)]",children:[n.jsx(Do,{title:e.title,filePath:e.filePath}),n.jsx("div",{className:"px-3 py-2 max-h-[40vh] overflow-y-auto",children:n.jsx(ht,{variant:"compact",children:e.body})})]}):n.jsx(sm,{plan:e,dependencies:y}))]})}function om({plan:e,position:t,expanded:r,onToggle:s,onRun:a,launching:o,blocked:l,onBlockedClick:c,draggable:d,unsatisfiedDepCount:u,unsatisfiedDepTooltip:f,dependencies:p,claim:m,staleFetch:h}){const{attributes:b,listeners:g,setNodeRef:y,setActivatorNodeRef:w,transform:v,transition:x,isDragging:j}=Vp({id:e.slug,disabled:!d}),k={transform:Ht.Transform.toString(v),transition:x};return n.jsx(Lo,{plan:e,expanded:r,onToggle:s,onRun:a,launching:o,blocked:l,onBlockedClick:c,position:t,sortableRef:y,sortableStyle:k,isDragging:j,dragHandleRef:d?w:void 0,dragHandleAttributes:d?b:void 0,dragHandleListeners:d?g:void 0,unsatisfiedDepCount:u,unsatisfiedDepTooltip:f,dependencies:p,claim:m,staleFetch:h})}function Kr({plans:e,loading:t,error:r,onRun:s,launchingSlug:a,launchError:o,blocked:l=!1,onBlockedClick:c,onReorder:d,depAnnotationsBySlug:u,dependenciesBySlug:f,claimsBySlug:p,staleFetch:m}){const[h,b]=i.useState(null),[g,y]=i.useState(null),[w,v]=i.useState(null);i.useEffect(()=>{y(null)},[e]);const x=g??e,j=x.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 (",j,")"]}),o&&n.jsxs("p",{className:"mt-2 text-sm text-[var(--accent-red)]",children:["Failed to launch plan: ",o]}),w&&n.jsxs("p",{className:"mt-2 text-sm text-[var(--accent-red)]",children:["Failed to reorder plans: ",w]}),n.jsx(im,{plans:x,loading:t,error:r,expandedSlug:h,onToggle:k=>b(N=>N===k?null:k),onRun:s,launchingSlug:a??null,blocked:l,onBlockedClick:c,depAnnotationsBySlug:u,dependenciesBySlug:f,claimsBySlug:p,staleFetch:m,onReorder:d?async k=>{y(k),v(null);try{await d(k.map(N=>N.slug))}catch(N){y(null),v(N instanceof Error?N.message:"Unknown error")}}:void 0})]})}function im({plans:e,loading:t,error:r,expandedSlug:s,onToggle:a,onRun:o,launchingSlug:l,blocked:c,onBlockedClick:d,onReorder:u,depAnnotationsBySlug:f,dependenciesBySlug:p,claimsBySlug:m,staleFetch:h}){const b=jf(Ts(Vr,{activationConstraint:{distance:4}}),Ts(Hr,{coordinateGetter:Gp})),g=i.useMemo(()=>e.map(v=>v.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 y=v=>{const{active:x,over:j}=v;if(!j||x.id===j.id||!u)return;const k=e.findIndex(C=>C.slug===x.id),N=e.findIndex(C=>C.slug===j.id);k===-1||N===-1||u(Ur(e,k,N))},w=n.jsx("ul",{className:"mt-3 flex flex-col gap-2","data-testid":"plan-list",children:e.map((v,x)=>{const j=f==null?void 0:f[v.slug],k=m==null?void 0:m.get(v.slug);return n.jsx(om,{plan:v,position:x+1,expanded:s===v.slug,onToggle:()=>a(v.slug),onRun:o,launching:l===v.slug,blocked:c,onBlockedClick:d,draggable:!!u,unsatisfiedDepCount:j==null?void 0:j.count,unsatisfiedDepTooltip:j==null?void 0:j.tooltip,dependencies:p==null?void 0:p[v.slug],claim:k,staleFetch:h},v.slug)})});return u?n.jsx(Np,{sensors:b,collisionDetection:Nf,onDragEnd:y,children:n.jsx($p,{items:g,strategy:Mp,children:w})}):w}function lm({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:b,launchingSlug:g,launchError:y,onReorderPlans:w,isAgentBuilding:v}){const{recoveryFeatureName:x,recoveryStep:j,recoveryMode:k,showTerminal:N,shouldResumeSameProvider:C}=Hu({sessionDecision:s,sessionInfo:a,stepState:o});return s==="pending"?n.jsx(_u,{featureName:x,editorStep:j,workflowMode:k,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(Lr,{children:n.jsx(Kr,{plans:p,loading:m,error:h,onRun:S=>{var E;const R=((E=p.find(A=>A.slug===S))==null?void 0:E.title)??S;b(S,R)},launchingSlug:g,launchError:y,blocked:v,onReorder:w})}):N?n.jsx(of,{provider:l,shouldResumeSameProvider:C,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 cm(e){return e?{step:e.step??0,feature:e.feature??null,startedAt:e.startedAt??"",mode:Ye(e.mode),slug:e.slug??null}:null}const dm=3e3;function qt(){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=cm(c),u=JSON.stringify(d);u!==o.current&&(o.current=u,t(d)),s(!1)}).catch(()=>{s(!1)})};return l(),a.current=setInterval(l,dm),()=>{a.current&&clearInterval(a.current)}},[]),{stepState:e,loading:r}}const Re={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 um(e){return{hasSession:(e==null?void 0:e.hasSession)??Re.hasSession,resumeMode:(e==null?void 0:e.resumeMode)??Re.resumeMode,provider:(e==null?void 0:e.provider)??Re.provider,feature:(e==null?void 0:e.feature)??Re.feature,step:(e==null?void 0:e.step)??Re.step,mode:(e==null?void 0:e.mode)==null?Re.mode:Ye(e.mode),label:(e==null?void 0:e.label)??Re.label,sessionId:(e==null?void 0:e.sessionId)??Re.sessionId,awaitingUserInput:(e==null?void 0:e.awaitingUserInput)??Re.awaitingUserInput,reopenResults:(e==null?void 0:e.reopenResults)??Re.reopenResults,preview:(e==null?void 0:e.preview)??Re.preview,agentBrokerLive:(e==null?void 0:e.agentBrokerLive)??Re.agentBrokerLive}}function Mo(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(um(d))}catch{s(Re)}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 fm=5e3;function pm(){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,fm),()=>{a.current&&clearInterval(a.current)}},[]),{prompt:e,loading:r}}function mm({currentDecision:e,sessionInfo:t,sessionLoading:r}){return r||!t?e:e==="continue"&&t.hasSession?"continue":e==="fresh"&&t.hasSession&&t.resumeMode==="resume"?"fresh":t.resumeMode==="resume"||t.resumeMode==="handoff"?"pending":"fresh"}let xn=null;const hm=1e4;function xm(){xn=Date.now()}function gm(){if(xn==null)return!1;const e=Date.now()-xn;return xn=null,e<=hm}function bm({sessionLoading:e,sessionInfo:t,onSessionDetected:r}){const s=i.useRef(!1),[a,o]=i.useState(()=>gm()?"fresh":"no-session");i.useEffect(()=>{o(c=>mm({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 vm(){const e=document.activeElement;return e===null||e===document.body||e===document.documentElement||e instanceof HTMLElement&&e.dataset.navTab==="true"}function ym(e,t,r,s=0){return e>=r.left-s&&e<=r.right+s&&t>=r.top-s&&t<=r.bottom+s}function Hs(e){wn(),e.blur(),window.dispatchEvent(new Event("terminal-focus")),queueMicrotask(()=>{document.activeElement instanceof HTMLIFrameElement&&window.dispatchEvent(new Event("terminal-focus"))})}function wm(e){const t=i.useRef(!1);i.useEffect(()=>{if(!e)return;function r(){if(!t.current&&vm()){t.current=!0;try{wn(),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&&Hs(c)}function o(l){const c=document.activeElement;if(!(c instanceof HTMLIFrameElement))return;const d=c.getBoundingClientRect();ym(l.clientX,l.clientY,d,1)||Hs(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 jm({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 km(e){const t=i.useRef(e);i.useEffect(()=>{e&&e!==t.current&&(gn(e),t.current=e)},[e])}function Nm(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 Cm({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 Sm({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(ht,{variant:"compact",children:e})})}function Em({currentStep:e,isExpanded:t,mode:r,onToggle:s=()=>{},stepNum:a}){const o=a===e,l=a<e,{description:c,label:d}=Ua(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 Rm({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,m]=i.useState(null),h=i.useRef(null),b=i.useRef(null),g=i.useRef(null),y=i.useRef(null);i.useLayoutEffect(()=>{if(!o)return;const S=()=>{var E;const R=(E=b.current)==null?void 0:E.getBoundingClientRect();R&&m({top:R.bottom+4,right:window.innerWidth-R.right})};return S(),window.addEventListener("resize",S),window.addEventListener("scroll",S,!0),()=>{window.removeEventListener("resize",S),window.removeEventListener("scroll",S,!0)}},[o]),i.useEffect(()=>{if(!o)return;const S=R=>{var A,D;const E=R.target;(A=h.current)!=null&&A.contains(E)||(D=g.current)!=null&&D.contains(E)||l(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[o]),Nm(y,u,i.useCallback(()=>f(!1),[]));const w=t&&e>0,v=t||"New Working Session",x=Ye(r),j=Ua(e,x),k=w?j.label:null,N=j.totalSteps,C=j.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:v})]}),n.jsx("span",{style:{color:"var(--text-dim)"},children:t?"Starting…":"Waiting for session"})]}):n.jsxs("div",{className:"shrink-0",ref:y,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(Cm,{displayName:v,hasPrompt:!!a,expanded:u,onToggle:()=>f(S=>!S)})]}),w&&n.jsxs("div",{className:"relative",ref:h,children:[n.jsxs("button",{ref:b,onClick:()=>l(S=>!S),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:[C," ",e,n.jsxs("span",{style:{color:"var(--text-dim)"},children:[" / ",N]}),": ",k]}),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&&p&&Nt.createPortal(n.jsx("div",{ref:g,className:"w-52 rounded-lg shadow-lg py-1",style:{position:"fixed",top:p.top,right:p.right,zIndex:60,background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:Array.from({length:N},(S,R)=>R+1).map(S=>{const R=c===S;return n.jsx(Em,{currentStep:e,isExpanded:R,mode:x,onToggle:()=>d(R?null:S),stepNum:S},S)})}),document.body)]})]}),u&&a&&n.jsx(Sm,{prompt:a})]})}function Tm({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:b,isAgentBuilding:g}){const{stepState:y}=qt(),{config:w,loading:v}=dt(),{prompt:x}=pm(),{sessionInfo:j,loading:k}=Mo(),{sessionDecision:N,handleContinueSession:C}=bm({sessionLoading:k,sessionInfo:j,onSessionDetected:r});return wm(t),jm({sessionLoading:k,sessionInfo:j,onRestorePreview:c}),km((y==null?void 0:y.feature)??null),n.jsx(Pu,{stepIndicator:n.jsx(Rm,{step:(y==null?void 0:y.step)??0,feature:(y==null?void 0:y.feature)??null,mode:(y==null?void 0:y.mode)??"ui",projectTitle:(w==null?void 0:w.projectTitle)??null,userPrompt:x}),sessionContent:n.jsx(lm,{awaitingPlanLaunchChoice:e,configLoading:v,sessionLoading:k,sessionDecision:N,sessionInfo:j,stepState:y,provider:l,onContinueSession:C,onAgentIdle:s,onAgentActive:a,onUserInput:o,pendingPlans:d,pendingPlansLoading:u,pendingPlansError:f,onLaunchPlan:p,launchingSlug:m,launchError:h,onReorderPlans:b,isAgentBuilding:g})})}function Io({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?Ge(e):"",p=f.startsWith("http"),m=t&&!p?`${f}?cb=${t}`:f,h=()=>{l("success"),d(!0)},b=()=>{l("error"),d(!1)};return i.useEffect(()=>{l("loading"),d(!1);const g=u.current;g!=null&&g.complete&&(g.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:b,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 Pm({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 kt(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]}:kt(e,{defaultSelection:!0,selectedIndex:t.selectedIndex})}const r=Math.min(t.selectedIndex??0,e.length-1);return{selectedIndex:r,scenario:e[r]}}function Dm(e){return e==null?"":typeof e=="string"?e:typeof e=="object"&&typeof e.name=="string"?e.name:String(e)}const Am="/api/editor-session-summary",Fm=3e3;function Lm(e=Fm){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(Am);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 Mm({onClose:e,onSelectScenario:t,previewSlug:r=null}){var g;const{summary:s,loading:a,refreshing:o,refresh:l}=Lm(),[c,d]=i.useState(0),u=i.useMemo(()=>s?[...s.application,...s.components]:[],[s]),f=i.useMemo(()=>r&&u.some(y=>y.slug===r)?r:null,[u,r]),p=f??((g=u[c])==null?void 0:g.slug);i.useEffect(()=>{if(!f)return;const y=u.findIndex(w=>w.slug===f);y>=0&&y!==c&&d(y)},[u,f,c]);const m=i.useCallback(y=>{u.length!==0&&(document.activeElement instanceof HTMLIFrameElement||ef()||(y.key==="ArrowRight"?(y.preventDefault(),d(w=>{const v=kt(u,{direction:"next",selectedIndex:w});return v.scenario&&(t==null||t(v.scenario.slug,v.scenario.url)),v.selectedIndex})):y.key==="ArrowLeft"&&(y.preventDefault(),d(w=>{const v=kt(u,{direction:"previous",selectedIndex:w});return v.scenario&&(t==null||t(v.scenario.slug,v.scenario.url)),v.selectedIndex}))))},[u,t]);i.useEffect(()=>(window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)),[m]);const h=i.useRef(!1);if(i.useEffect(()=>{if(h.current||u.length===0)return;h.current=!0;const y=kt(u,{defaultSelection:!0,selectedIndex:c});y.scenario&&(t==null||t(y.scenario.slug,y.scenario.url))},[u,t,c]),a)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(!s)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 b=s.application.length+s.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(Pm,{refreshing:o,onRefresh:l,onClose:e}),n.jsxs("div",{className:"flex-1 overflow-auto p-4 space-y-4",children:[s.userPrompt&&n.jsx(Im,{text:s.userPrompt}),n.jsx(an,{title:"Application",icon:"🌐",count:s.application.length,empty:b===0?"No scenarios in this session":void 0,children:s.application.length>0&&n.jsx(Bm,{scenarios:s.application,selectedSlug:p,onSelect:(y,w)=>{var x,j;const v=kt(u,{slug:y,selectedIndex:c});v.selectedIndex>=0&&d(v.selectedIndex),t==null||t(((x=v.scenario)==null?void 0:x.slug)??y,((j=v.scenario)==null?void 0:j.url)??w)}})}),n.jsx(an,{title:"Components",icon:"🧩",count:s.components.length,children:s.components.length>0&&n.jsx($m,{scenarios:s.components,selectedSlug:p,onSelect:(y,w)=>{var x,j;const v=kt(u,{slug:y,selectedIndex:c});v.selectedIndex>=0&&d(v.selectedIndex),t==null||t(((x=v.scenario)==null?void 0:x.slug)??y,((j=v.scenario)==null?void 0:j.url)??w)}})}),n.jsx(an,{title:"Functions",icon:"⚙️",count:s.functions.length,children:s.functions.length>0&&n.jsx(zm,{functions:s.functions})}),n.jsx(an,{title:"Modified Files",icon:"📄",count:s.modifiedFiles.length,children:s.modifiedFiles.length>0&&n.jsx(_m,{files:s.modifiedFiles})})]})]})}function Im({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(ht,{variant:"compact",children:e}),a&&n.jsx("button",{onClick:()=>r(!1),className:"text-[#D7FF63] 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-[#D7FF63] hover:underline ml-1 text-xs",children:"Read more..."})]})]})}function an({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 gr({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(Om,{scenario:s,isSelected:s.slug===t,onSelect:r},s.slug))})})}function $m({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(gr,{scenarios:s[o],selectedSlug:t,onSelect:r})]},o))})}function Bm({scenarios:e,selectedSlug:t,onSelect:r}){if(!e.some(l=>l.routeName))return n.jsx(gr,{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(gr,{scenarios:a[l],selectedSlug:t,onSelect:r})]},l))})}function Om({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(Io,{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 zm({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:Dm(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 _m({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(Fr,{status:t.status}),n.jsx("span",{className:"text-xs text-[var(--text-secondary)] font-mono truncate",children:t.path})]},t.path))})}function Hm({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 Wm({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]),Hm({showStepResults:r,showResultsPanel:s,openResults:c,closeResults:d}),{closeResults:d,openResults:c,resultsKey:o,showResultsPanel:s}}function Vm(e){return(e==null?void 0:e.mode)==="ui"&&(e==null?void 0:e.slug)==="feature-complete"}function Um({awaitingPlanLaunchChoice:e,buildActivated:t,activeTab:r,onSessionDetected:s,onSelectScenario:a,previewSlug:o=null,showResultsCommandKey:l,hideResultsCommandKey:c,onAgentIdle:d,onAgentActive:u,onUserInput:f,notifSettings:p,onSettingsChange:m,provider:h,onRestorePreview:b,pendingPlans:g,pendingPlansLoading:y,pendingPlansError:w,onLaunchPlan:v,launchingSlug:x,launchError:j,onReorderPlans:k,isAgentBuilding:N}){const{stepState:C}=qt(),{closeResults:S,resultsKey:R,showResultsPanel:E}=Wm({showResultsCommandKey:l,hideResultsCommandKey:c,showStepResults:Vm(C)});return t?n.jsx(Du,{activeTab:r,showResultsPanel:E,buildTab:n.jsx(Tm,{awaitingPlanLaunchChoice:e,isActive:r==="build",onSessionDetected:s,onAgentIdle:d,onAgentActive:u,onUserInput:f,provider:h,onRestorePreview:b,pendingPlans:g,pendingPlansLoading:y,pendingPlansError:w,onLaunchPlan:v,launchingSlug:x,launchError:j,onReorderPlans:k,isAgentBuilding:N}),resultsPanel:n.jsx(Mm,{onClose:S,onSelectScenario:a,previewSlug:o},R),footer:n.jsx(Hd,{settings:p,onChange:m,agentName:h})}):null}function Km({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 Gm({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 Ws=["·","✢","✳","✶","✻","✽"],Ym=160;function $o(){const[e,t]=i.useState(0);return i.useEffect(()=>{const r=window.setInterval(()=>t(s=>(s+1)%Ws.length),Ym);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-[#D7FF63] leading-none text-[11px] tabular-nums",children:Ws[e]})}function qm({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 Jm({onNavigateToBuild:e,onDismiss:t}){return i.useEffect(()=>(K("banner-mounted",{}),()=>{K("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 We(){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 Xm=[{key:"home",label:"Home"},{key:"plan",label:"Plan"},{key:"build",label:"Build"},{key:"history",label:"History"}];function Vs(){if(typeof document>"u")return;const e=document.activeElement;e instanceof HTMLElement&&e.blur()}function Qm({activeTab:e,onTabChange:t,onSendTranscript:r,buildIdle:s=!1,isAgentBuilding:a=!1,bannerVisible:o=!1,onDismissIdleBanner:l,buildDisabled:c=!1}){const d=o&&e!=="build",u=s,f=a&&!s,p=f?"green":u?"orange":"none",m=i.useRef(p);return i.useEffect(()=>{m.current!==p&&(K("build-tab-dot-change",{from:m.current,to:p}),m.current=p)},[p]),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(Km,{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:Xm.map(h=>h.key==="build"&&c?n.jsx("button",{type:"button","data-nav-tab":"true","data-testid":"nav-build-disabled",title:"Connect your provider account on the Home tab to enable Build",onClick:()=>{t("home"),Vs()},className:"px-2.5 py-2.5 text-sm text-[#5A5A5A] cursor-not-allowed font-light",children:h.label},h.key):n.jsxs(Ba,{href:Lt(h.key),"data-nav-tab":"true",onNavigate:()=>{t(h.key),Vs(),h.key==="build"&&We()},className:`px-2.5 py-2.5 text-sm transition-colors cursor-pointer ${e===h.key?"text-[#D7FF63] font-medium":"text-[#8E8E8E] hover:text-white font-light"}`,children:[h.key==="build"&&f&&n.jsx($o,{}),h.key==="build"&&u&&n.jsx("span",{"data-testid":"nav-build-dot-idle",className:"mr-1 inline-block w-2 h-2 rounded-full bg-[#FF8B43]"}),h.label]},h.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(qm,{})}),!1]}),d&&n.jsx(Jm,{onNavigateToBuild:()=>t("build"),onDismiss:l??(()=>{})})]})}function Zm(e,t){for(const r of e.filesByDirectory)for(const s of r.files)if(s.filePath===t)return s;return null}function Bo(e){return e>=80?"#16a34a":e>=50?"#eab308":"#dc2626"}function Jt({coverage:e}){const t=Math.max(0,Math.min(100,e.percent)),r=Bo(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 eh({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(Jt,{coverage:e.coverage})]})}function th({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(eh,{file:r,onSelectFile:t},r.filePath))})]})}function nh({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(th,{group:r,onSelectFile:t},r.directory||"(root)"))})]})}function rh({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(Jt,{coverage:{percent:e.percent,hitLines:e.hitLines,totalLines:e.totalLines}})]})}function sh({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(rh,{entry:r,onSelectFile:t},`${r.filePath}::${r.name}`))})]})}function Oo({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(Jt,{coverage:e.coverage})]})}function ah({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(Oo,{file:r})},r.filePath))})]})}function oh({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 ih({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(Jt,{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(oh,{line:s,hits:a},s))})]})}function Gr({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:Bo(t.percent)},"data-testid":r,children:[Math.round(t.percent),"% overall"]})]})]})}function zo({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 lh({onClose:e,fetchDetails:t=ch,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=Zm(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(ih,{file:c,onBack:()=>d(null)}),s&&!c&&n.jsxs("div",{className:"flex flex-col gap-6",children:[n.jsx(Gr,{title:"Overall",aggregate:s.projectWide,aggregateTestId:"coverage-details-modal-aggregate"}),s.coverageWarnings.length>0&&n.jsx(zo,{warnings:s.coverageWarnings}),n.jsx(sh,{entries:s.entries,onSelectFile:f}),n.jsx(ah,{files:s.orphanedFiles,onSelectFile:f}),n.jsx(nh,{directories:s.filesByDirectory,onSelectFile:d})]})]})})}function ch(){return fetch("/api/coverage/details").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()})}function dh({appDetailProps:e,appOverviewProps:t,selectedApp:r}){const[s,a]=i.useState(!1),o=()=>a(!0),l=()=>a(!1),c=r?n.jsx(td,{app:r,...e,onCoverageClick:o}):n.jsx(Tu,{...t,onCoverageClick:o},"app-overview");return n.jsxs(n.Fragment,{children:[c,s&&n.jsx(lh,{onClose:l})]})}function uh({activeTab:e,awaitingPlanLaunchChoice:t,buildActivated:r,hideResultsCommandKey:s,onSelectScenario:a,onSessionDetected:o,previewSlug:l,showResultsCommandKey:c,onAgentIdle:d,onAgentActive:u,onUserInput:f,notifSettings:p,onSettingsChange:m,provider:h,onRestorePreview:b,pendingPlans:g,pendingPlansLoading:y,pendingPlansError:w,onLaunchPlan:v,launchingSlug:x,launchError:j,onReorderPlans:k,isAgentBuilding:N}){return r?n.jsx(Um,{awaitingPlanLaunchChoice:t,buildActivated:r,activeTab:e,onSessionDetected:o,onSelectScenario:a,previewSlug:l,showResultsCommandKey:c,hideResultsCommandKey:s,onAgentIdle:d,onAgentActive:u,onUserInput:f,notifSettings:p,onSettingsChange:m,provider:h,onRestorePreview:b,pendingPlans:g,pendingPlansLoading:y,pendingPlansError:w,onLaunchPlan:v,launchingSlug:x,launchError:j,onReorderPlans:k,isAgentBuilding:N}):null}function fh({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)"}})})}const ph=[{key:"editor",label:"Editor"},{key:"preview",label:"Preview"}];function mh({active:e,onChange:t,isAgentBuilding:r=!1,buildIdle:s=!1}){const a=r&&!s,o=s;return n.jsx("div",{"data-testid":"mobile-pane-switcher",className:"shrink-0 flex w-full",style:{background:"var(--bg-nav)",borderTop:"1px solid var(--border-default)",paddingBottom:"env(safe-area-inset-bottom)"},children:ph.map(l=>{const c=e===l.key;return n.jsxs("button",{"data-testid":`mobile-pane-switcher-${l.key}`,onClick:()=>t(l.key),"aria-pressed":c,className:`flex-1 flex items-center justify-center gap-1 h-12 text-sm border-t-2 transition-colors cursor-pointer ${c?"text-[#D7FF63] border-[#D7FF63] font-medium":"text-[#8E8E8E] border-transparent font-light"}`,children:[l.key==="editor"&&a&&n.jsx($o,{}),l.key==="editor"&&o&&n.jsx("span",{"data-testid":"mobile-pane-switcher-dot-idle",className:"mr-1 inline-block w-2 h-2 rounded-full bg-[#FF8B43]"}),l.label]},l.key)})})}function hh({isCollapsed:e,leftPane:t,onResizeStart:r,previewPane:s,splitRef:a,isNarrow:o,mobilePane:l,onMobilePaneChange:c,isAgentBuilding:d=!1,buildIdle:u=!1}){return o?n.jsxs("div",{ref:a,className:"fixed inset-0 flex flex-col",style:{background:"var(--bg-surface)"},children:[n.jsxs("div",{className:"flex-1 min-h-0 relative",children:[n.jsx("div",{className:`absolute inset-0 flex ${l==="editor"?"":"hidden"}`,children:t}),n.jsx("div",{className:`absolute inset-0 flex ${l==="preview"?"":"hidden"}`,children:s})]}),n.jsx(mh,{active:l,onChange:c,isAgentBuilding:d,buildIdle:u})]}):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(fh,{onMouseDown:r})]}),s]})}function Yr(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),{plansVersion:l}=gt(),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 xh(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),{plansVersion:l,claimsVersion:c}=gt(),d=i.useCallback(async()=>{s(!0),o(null);try{const u=await fetch("/api/plan-claims");if(!u.ok)throw new Error(`HTTP ${u.status}`);const f=await u.json();t(Array.isArray(f)?f:[])}catch(u){o(u instanceof Error?u.message:"Failed to load plan claims")}finally{s(!1)}},[]);return i.useEffect(()=>{d()},[d,l,c]),{claims:e,loading:r,error:a,refetch:d}}function gh(){const[e,t]=i.useState(null),{claimsVersion:r}=gt(),s=i.useCallback(async()=>{try{const a=await fetch("/api/plan-claims/sync-status");if(!a.ok)return;const o=await a.json();t(o)}catch{}},[]);return i.useEffect(()=>{s()},[s,r]),i.useEffect(()=>{const a=setInterval(()=>void s(),1e4);return()=>clearInterval(a)},[s]),{status:e}}function bh(){const[e,t]=i.useState(null),r=i.useCallback(async()=>{try{const s=await fetch("/api/server/staleness");if(!s.ok)return;const a=await s.json();t(a)}catch{}},[]);return i.useEffect(()=>{r()},[r]),i.useEffect(()=>{const s=setInterval(()=>void r(),6e4);return()=>clearInterval(s)},[r]),{staleness:e}}const rr="codeyam-editor editor plan-claims-status",vh="git push origin HEAD";function yh(e,t){switch(e){case"credential":return{message:"Plan tracking isn't reaching the remote — git credentials need refreshing. Run the command below from a shell to wake the credential helper.",command:vh};case"network":return{message:"Plan tracking can't reach the remote (network failure). Check connectivity, then run the command below for details.",command:rr};case"git-spawn":return{message:"Plan tracking can't launch git. Run the command below for the failing invocation.",command:rr};default:return{message:`Plan tracking is failing (${t} failed ticks). Teammates' in-flight plans may not appear. Run the command below for details.`,command:rr}}}function wh({status:e}){const{copied:t,copy:r}=Sr(),s=(e==null?void 0:e.consecutiveFailures)??0;if((e==null?void 0:e.enabled)===!1||s<3)return null;const{message:a,command:o}=yh(e==null?void 0:e.lastErrorCategory,s);return n.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3","data-testid":"plan-claim-sync-banner",role:"alert",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 text-sm text-amber-800",children:[a," ",n.jsx("code",{className:"text-xs",children:o})," ",n.jsx("button",{type:"button",className:"underline text-amber-700 hover:text-amber-900",onClick:()=>void r(o),children:t?"Copied":"Copy command"})]})]})})}const Us="codeyam-editor editor restart-server";function _o({staleness:e,backendOutOfDate:t=!1}){var l;const{copied:r,copy:s}=Sr(),a=!!(e!=null&&e.stale);if(!a&&!t)return null;const o=((l=e==null?void 0:e.info)==null?void 0:l.minutesStale)??0;return n.jsx("div",{className:"bg-rose-50 border border-rose-200 rounded-lg p-3","data-testid":"server-staleness-banner",role:"alert",children:n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("span",{className:"text-rose-600 text-lg leading-none mt-0.5","aria-hidden":"true",children:"!"}),n.jsxs("div",{className:"flex-1 min-w-0 text-sm text-rose-800",children:[a?n.jsxs(n.Fragment,{children:["The editor-server is running a stale binary (rebuilt ",o," min ago). Restart it to pick up the latest plan tracking fixes."]}):n.jsx(n.Fragment,{children:"The editor-server is out of date — it's running an older build that can't drive the Build tab. Restart it to reconnect."})," ","Run ",n.jsx("code",{className:"text-xs",children:Us}),"."," ",n.jsx("button",{type:"button",className:"underline text-rose-700 hover:text-rose-900",onClick:()=>void s(Us),children:r?"Copied":"Copy command"})]})]})})}function jh(e){const t=new Map;for(const r of e){const s=t.get(r.slug);(!s||s.source!=="local"&&r.source==="local")&&t.set(r.slug,r)}return t}function kh(e,t){return e.filter(r=>r.source==="local"||!t.has(r.slug))}function Nh(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 Ho(){const[e,t]=i.useState(()=>new Set),[r,s]=i.useState(!0),[a,o]=i.useState(null),l=i.useCallback(async()=>{s(!0),o(null);try{const c=await fetch("/api/plans/completed/slugs");if(!c.ok)throw new Error(`HTTP ${c.status}`);const d=await c.json(),u=Array.isArray(d==null?void 0:d.slugs)?d.slugs:[];t(new Set(u.filter(f=>typeof f=="string")))}catch(c){o(c instanceof Error?c.message:"Failed to load completed plan slugs")}finally{s(!1)}},[]);return i.useEffect(()=>{l()},[l]),{slugs:e,loading:r,error:a,refetch:l}}function Ch(e,t,r){const s=new Map(t.map(a=>[a.slug,a]));return e.dependsOn.map(a=>{var o;return{slug:a,title:((o=s.get(a))==null?void 0:o.title)??null,satisfied:r.has(a)}})}function Wo(e){return e.filter(t=>!t.satisfied)}function Vo(e){const{slugs:t}=Ho();return i.useMemo(()=>{const r={},s={};for(const a of e){const o=a.dependsOn??[];if(o.length===0)continue;const l=Ch({...a,dependsOn:o},e,t);s[a.slug]=l;const c=Wo(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 St={hasActiveSession:!1,isAgentBuilding:!1,stepStateFeature:null};function qr(e){St={...St,...e}}function Sh(){return St}function Eh(){return St.hasActiveSession||St.isAgentBuilding||!!St.stepStateFeature}const Rh=500;async function Th(){var e;try{const t=await fetch("/api/config");if(!t.ok)return!0;const r=await t.json();return((e=r==null?void 0:r.providerAuth)==null?void 0:e.state)==="authenticated"}catch{return!0}}async function Jr(){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&&qr({hasActiveSession:!1,isAgentBuilding:!1,stepStateFeature:null}),K("clear-editor-session",{ok:e,...t!==void 0?{status:t}:{},snapshotReset:e})}async function Ph(){let e=!1,t;try{const r=await fetch("/api/stop-building",{method:"POST",headers:{"Content-Type":"application/json"}});t=r.status,r.ok&&(e=!0)}catch{}e&&qr({hasActiveSession:!1,isAgentBuilding:!1,stepStateFeature:null}),K("stop-building",{ok:e,...t!==void 0?{status:t}:{},snapshotReset:e})}async function Xr(e={}){const t=Sh(),r=e.caller??"unknown",s=e.bypassLiveGuard===!0;if(Eh()&&!s){K("launch-editor-skill",{caller:r,suppressed:!0,snapshot:t,bypassLiveGuard:!1});return}Yu(),K("launch-editor-skill",{caller:r,suppressed:!1,snapshot:t,bypassLiveGuard:s}),e.provider!=="gemini"&&(ro(e.renameLabel??"Editor",r,Ca),ir("/clear\r"),await new Promise(a=>setTimeout(()=>{ir("/codeyam-editor\r"),a()},Rh)))}async function Dh(e={}){if(await Jr(),!await Th()){K("launch-editor-skill",{caller:e.caller??"unknown",suppressed:!0,reason:"provider-not-authenticated"}),console.warn("[launchEditorWorkflow] provider not authenticated; aborting launch (the terminal gate would refuse the PTY).");return}await Xr(e)}function Qr(e,t=!1,r=t){const s=Sl(e),a=t&&s==="build"?"home":s,[o,l]=i.useState(a==="build"),[c,d]=i.useState(a==="plan");i.useEffect(()=>{a==="build"&&l(!0),a==="plan"&&d(!0)},[a]),i.useEffect(()=>{r&&s==="build"&&window.history.replaceState(null,"",Lt("home"))},[r,s]);const u=i.useCallback(p=>{if(t&&p==="build"){window.history.pushState(null,"",Lt("home"));return}window.history.pushState(null,"",Lt(p)),p==="build"&&l(!0),p==="plan"&&d(!0)},[t]),f=i.useCallback(()=>{t||(window.history.pushState(null,"",Lt("build")),l(!0))},[t]);return{activeTab:a,buildActivated:o,planActivated:c,navigateToTab:u,showBuildTab:f}}function Zr(){const{showBuildTab:e}=Qr(typeof window>"u"?"/":window.location.pathname),{config:t}=dt(),[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 Jr(),xm()}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)}e()}catch(u){return o(u instanceof Error?u.message:"Failed to launch plan"),s(null),!1}return s(null),Xr({caller:"plan-launcher",renameLabel:d,provider:t==null?void 0:t.provider,bypassLiveGuard:!0}).catch(u=>{o(u instanceof Error?u.message:"Failed to launch plan")}),!0},[r,e,t==null?void 0:t.provider]);return{launchingSlug:r,error:a,launchPlan:l}}function Uo(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 Ah={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 Fh({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:Ah[e]})]})}function Lh({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:Fo}),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 Mh({claim:e,onCancel:t,onConfirm:r}){const s=Yt(),a=e.claimedBy.agentProvider??"agent",o=e.claimedBy.currentStep??"unknown",l=e.sessionAlive===!1,c=l?"Previous session (no longer running)":"Another session is working on this plan",d=l?"Reclaim and run":"Run anyway";i.useEffect(()=>{const f=p=>{p.key==="Escape"&&t()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[t]);const u=f=>{f.target===f.currentTarget&&t()};return n.jsx("div",{"data-testid":"plan-run-foreign-claim-modal",onClick:u,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",{"data-testid":"plan-foreign-claim-heading",className:"text-lg font-semibold text-[var(--text-primary)] mb-2",children:c}),n.jsxs("div",{className:"text-sm text-[var(--text-muted)] mb-4 flex flex-col gap-1",children:[n.jsxs("span",{"data-testid":"plan-foreign-claim-identity",children:["claimed by ",a,"@",e.claimedBy.machine]}),n.jsxs("span",{children:["started ",ct(e.claimedBy.startedAt,s)]}),n.jsxs("span",{"data-testid":"plan-foreign-claim-step",children:["on step ",o," (",ct(e.currentStepEnteredAt,s)," on step)"]})]}),n.jsxs("div",{className:"flex gap-3",children:[n.jsx("button",{onClick:t,"data-testid":"plan-run-foreign-claim-cancel",className:"flex-1 px-4 py-2.5 rounded-md text-sm font-medium transition",style:{background:"var(--bg-elevated, transparent)",border:"1px solid var(--border-default)",color:"var(--text-primary)"},type:"button",children:"Cancel"}),n.jsx("button",{onClick:r,"data-testid":"plan-run-foreign-claim-confirm",className:"flex-1 px-4 py-2.5 rounded-md text-sm font-medium transition",style:{background:"var(--accent-warn, #c08a2c)",color:"var(--bg-deep)"},type:"button",children:d})]})]})})}function Ih({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 $h=[{id:"describe",label:"Describe A Plan"},{id:"prototype",label:"Prototype A Plan"}];function Bh({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:$h.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 Ks(e){return e.source==="prototype"}function Oh(e,t){const[r,s]=i.useState(!1),a=i.useRef(new Set),o=Zr(),l=()=>{a.current=new Set(e.filter(Ks).map(c=>c.slug)),s(!0)};return i.useEffect(()=>{if(!r||o.launchingSlug)return;const c=e.filter(Ks).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 zh({onClose:e}){return n.jsx(Sn,{chatName:"prototype",slashCommand:"/codeyam-prototype",height:480,onClose:e})}const _h="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 Hh(){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."})," ",_h]})}function Gs({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 br=800;function Ot(e){window.dispatchEvent(new CustomEvent("miniagent-send-input",{detail:e}))}function vr(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 Wh='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 Vh({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{Ot(Wh),await vr(br),Ot("\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 Uh(e,t){return`Launches a chat window with ${e} to ${t==="describe"?"describe your plan":"start prototyping"}.`}function Ko({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:Uh(e,t)})}function Kh({isAgentBuilding:e,onLaunched:t}){const[r,s]=i.useState(!1),{plans:a}=Yr(),{config:o}=dt(),l=lt(o==null?void 0:o.provider),c=Oh(a,()=>{s(!1),t==null||t()}),d=()=>{if(e)return;const f=!r;f&&We(),s(f)},u=()=>{s(!1)};return e?n.jsxs("div",{"data-testid":"prototype-pane",children:[n.jsx(Hh,{}),n.jsx(Gs,{open:!1,disabled:!0,onToggle:()=>{}})]}):n.jsxs("div",{"data-testid":"prototype-pane",children:[n.jsx(Gs,{open:r,onToggle:d}),!r&&n.jsx(Ko,{providerLabel:l,kind:"prototype"}),r&&n.jsxs(n.Fragment,{children:[n.jsx(zh,{onClose:u}),n.jsx(Vh,{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 Gh({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 Yh({onClose:e}){return n.jsx(Sn,{chatName:"plan",slashCommand:"/codeyam-plan",height:360,onClose:e})}function qh({providerLabel:e,chatOpen:t,onChatToggle:r,onChatClose:s}){return n.jsxs("div",{"data-testid":"describe-pane",children:[n.jsx(Gh,{open:t,onToggle:r}),!t&&n.jsx(Ko,{providerLabel:e,kind:"describe"}),t&&n.jsx(Yh,{onClose:s})]})}function Jh({claim:e}){const t=Yt(),r=e.claimedBy.agentProvider??"agent",s=e.claimedBy.machine,a=e.claimedBy.currentStep??null,o=ct(e.currentStepEnteredAt,t),l=ct(e.claimedBy.startedAt,t),{dead:c}=Ao(e);return n.jsxs("li",{className:"flex flex-col gap-1 rounded border border-[var(--border-subtle)] px-3 py-2","data-testid":`in-flight-row-${e.slug}`,"data-session-alive":c?"false":void 0,children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"font-medium text-sm text-[var(--text-default)]",children:e.title}),n.jsx("span",{className:"text-[10px] uppercase tracking-wide text-[var(--text-dim)]","data-testid":`in-flight-source-${e.slug}`,children:e.source})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-[var(--text-muted)]",children:[n.jsxs("span",{"data-testid":`plan-claim-identity-${e.slug}`,children:["claimed by ",r,"@",s]}),a&&n.jsxs("span",{"data-testid":`plan-claim-step-${e.slug}`,children:["step ",a," · ",o," on step"]}),n.jsxs("span",{"data-testid":`plan-claim-started-${e.slug}`,children:["started ",l]}),c&&n.jsx("span",{className:"text-[var(--text-muted)]",children:"(inactive)"})]})]})}function Xh({claims:e}){return e.length===0?null:n.jsxs("div",{className:"mt-6","data-testid":"in-flight-section",children:[n.jsxs("h3",{className:"text-xs font-medium uppercase tracking-wide text-[var(--text-dim)]",children:["In Flight (",e.length,")"]}),n.jsx("ul",{className:"mt-3 flex flex-col gap-2","data-testid":"in-flight-list",children:e.map(t=>n.jsx(Jh,{claim:t},`${t.slug}:${t.claimedBy.sessionId}:${t.claimedBy.pid}`))})]})}const Qh=5e3;function Zh(){const[e,t]=i.useState([]),[r,s]=i.useState(null),[a,o]=i.useState(null),[l,c]=i.useState(!0),[d,u]=i.useState(null),f=i.useRef(!1),p=i.useCallback(async()=>{c(!0),u(null);try{const b=await fetch("/api/branch-queue/status");if(!b.ok)throw new Error(`HTTP ${b.status}`);const g=await b.json();if(f.current)return;t(Array.isArray(g.entries)?g.entries:[]),s(g.branch??null),o(g.remote??null)}catch(b){if(f.current)return;u(b instanceof Error?b.message:"Failed to load branch queue"),t([])}finally{f.current||c(!1)}},[]);i.useEffect(()=>{f.current=!1,p();const b=setInterval(()=>{p()},Qh);return()=>{f.current=!0,clearInterval(b)}},[p]);const m=i.useCallback(async(b,g,y)=>{const w={uuid:b,priority:g};typeof y=="number"&&(w.expectedPriority=y);const v=await fetch("/api/branch-queue/set-priority",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(w)});if(!v.ok){const x=await v.text().catch(()=>"");throw new Error(`set-priority ${v.status}: ${x}`)}await p()},[p]),h=i.useCallback(async b=>{const g=await fetch("/api/branch-queue/release",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({uuid:b})});if(!g.ok){const y=await g.text().catch(()=>"");throw new Error(`release ${g.status}: ${y}`)}await p()},[p]);return{entries:e,branch:r,remote:a,loading:l,error:d,setPriority:m,release:h,refetch:p}}function ex(){const[e,t]=i.useState(null),[r,s]=i.useState(null),a=i.useCallback(c=>{t(c)},[]),o=i.useCallback(c=>{s(c)},[]),l=i.useCallback(()=>{t(null),s(null)},[]);return{dragSourceUuid:e,dragOverUuid:r,beginDrag:a,hoverOver:o,reset:l}}function tx(e,t,r){var c;if(e.length===0)return 0;if(t===r)return e[t].meta.priority;if(t<0||t>=e.length)return((c=e[0])==null?void 0:c.meta.priority)??0;const s=e[t];if(r<=0)return e[0].meta.priority+1;if(r>=e.length-1){const d=e[e.length-1];return d.uuid===s.uuid?e[e.length-2].meta.priority-1:d.meta.priority-1}const a=e.filter((d,u)=>u!==t),o=r-1>=0&&r-1<a.length?a[r-1]:null,l=r>=0&&r<a.length?a[r]:null;return o&&l?o.meta.priority-l.meta.priority>=2?l.meta.priority+1:o.meta.priority:o?o.meta.priority:l?l.meta.priority+1:s.meta.priority}function nx({priority:e,uuid:t,onNudge:r}){const s=e===0?"priority 0":e>0?`priority +${e}`:`priority ${e}`;return n.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] rounded border border-[var(--border-subtle)] px-2 py-1 text-[var(--text-muted)]","data-testid":`commit-queue-priority-chip-${t}`,children:[n.jsx("button",{type:"button",className:"text-[var(--text-dim)] hover:text-[var(--text-default)] px-0.5","data-testid":`commit-queue-nudge-down-${t}`,onClick:()=>void r(-1),"aria-label":"Lower priority",children:"−"}),n.jsx("span",{"data-testid":`commit-queue-priority-value-${t}`,children:s}),n.jsx("button",{type:"button",className:"text-[var(--text-dim)] hover:text-[var(--text-default)] px-0.5","data-testid":`commit-queue-nudge-up-${t}`,onClick:()=>void r(1),"aria-label":"Raise priority",children:"+"})]})}function rx({uuid:e,onRelease:t}){const[r,s]=i.useState(!1);return r?n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx("button",{type:"button",className:"text-xs px-2 py-1 rounded border border-[var(--accent-danger)] text-[var(--accent-danger)] hover:bg-[var(--accent-danger)] hover:text-white cursor-pointer","data-testid":`commit-queue-release-confirm-${e}`,onClick:async()=>{await t(),s(!1)},children:"Confirm release"}),n.jsx("button",{type:"button",className:"text-xs px-2 py-1 rounded border border-[var(--border-subtle)] text-[var(--text-dim)] cursor-pointer",onClick:()=>s(!1),children:"Cancel"})]}):n.jsx("button",{type:"button",className:"opacity-0 group-hover:opacity-100 transition-opacity text-xs px-2 py-1 rounded border border-[var(--border-subtle)] text-[var(--text-dim)] hover:border-[var(--accent-danger)] hover:text-[var(--accent-danger)] cursor-pointer","data-testid":`commit-queue-release-${e}`,onClick:()=>s(!0),title:"Force release this queue entry",children:"Force release"})}function sx({entry:e,isHead:t}){const r=Yt(),s=e.meta.agentProvider??"agent",a=e.meta.machine,o=e.meta.currentStep??null,l=ct(e.meta.startedAt??e.committerDate,r);return n.jsxs("div",{className:"flex-1 flex flex-col gap-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("span",{className:"text-sm font-medium text-[var(--text-default)] truncate",children:[s,"@",a]}),t&&n.jsx("span",{className:"text-[10px] uppercase tracking-wide text-[var(--accent-strong)]","data-testid":`commit-queue-head-marker-${e.uuid}`,children:"← head"})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-[var(--text-muted)]",children:[o&&n.jsxs("span",{"data-testid":`commit-queue-step-${e.uuid}`,children:["step ",o]}),n.jsxs("span",{"data-testid":`commit-queue-started-${e.uuid}`,children:["started ",l]}),n.jsxs("span",{"data-testid":`commit-queue-pid-${e.uuid}`,children:["pid ",e.meta.pid]})]})]})}function ax({entry:e,position:t,isHead:r,onPriorityNudge:s,onRelease:a,onDragStart:o,onDragOver:l,onDrop:c,isDragging:d,isDragOver:u}){return n.jsxs("li",{"data-testid":`commit-queue-row-${e.uuid}`,draggable:!0,onDragStart:f=>{f.dataTransfer.effectAllowed="move",f.dataTransfer.setData("text/plain",e.uuid),o()},onDragOver:f=>{f.preventDefault(),f.dataTransfer.dropEffect="move",l()},onDrop:f=>{f.preventDefault(),c()},className:`group flex items-center gap-3 rounded border px-3 py-2 ${r?"border-[var(--accent-strong)]":"border-[var(--border-subtle)]"} ${d?"opacity-40":""} ${u?"ring-2 ring-[var(--accent-strong)]":""}`,children:[n.jsx("span",{"aria-hidden":!0,className:"cursor-grab select-none text-[var(--text-dim)] hover:text-[var(--text-default)]",title:"Drag to reorder","data-testid":`commit-queue-drag-${e.uuid}`,children:"⋮⋮"}),n.jsxs("span",{className:"text-xs font-mono text-[var(--text-dim)] w-6 text-right","data-testid":`commit-queue-position-${e.uuid}`,children:[t,"."]}),n.jsx(sx,{entry:e,isHead:r}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(nx,{priority:e.meta.priority,uuid:e.uuid,onNudge:s}),n.jsx(rx,{uuid:e.uuid,onRelease:a})]})]})}function ox({entriesOverride:e,branchOverride:t}={}){const r=Zh(),s=e??r.entries,a=t??r.branch,o=e?async()=>{}:r.setPriority,l=e?async()=>{}:r.release,c=ex(),[d,u]=i.useState(null);if(!e&&r.loading&&s.length===0||s.length===0)return null;const f=async h=>{const b=c.dragSourceUuid;if(b===null)return;const g=s.findIndex(v=>v.uuid===b);if(c.reset(),g===-1||g===h)return;const y=tx(s,g,h),w=s[g].meta.priority;if(y!==w){u(null);try{await o(b,y,w)}catch(v){u(v instanceof Error?v.message:"Failed to update priority")}}},p=async(h,b)=>{const g=h.meta.priority;u(null);try{await o(h.uuid,g+b,g)}catch(y){u(y instanceof Error?y.message:"Failed to update priority")}},m=async h=>{u(null);try{await l(h.uuid)}catch(b){u(b instanceof Error?b.message:"Failed to release")}};return n.jsxs("div",{className:"mt-6","data-testid":"commit-queue-section",children:[n.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[n.jsxs("h3",{className:"text-xs font-medium uppercase tracking-wide text-[var(--text-dim)]",children:["Commit Queue (",s.length,")"]}),a&&n.jsx("span",{className:"text-[11px] text-[var(--text-dim)]","data-testid":"commit-queue-branch",children:a})]}),d&&n.jsx("div",{className:"mt-2 text-xs text-[var(--accent-danger)]","data-testid":"commit-queue-error",children:d}),n.jsx("ol",{className:"mt-3 flex flex-col gap-2","data-testid":"commit-queue-list",children:s.map((h,b)=>n.jsx(ax,{entry:h,position:b+1,isHead:b===0,onPriorityNudge:g=>p(h,g),onRelease:()=>m(h),onDragStart:()=>c.beginDrag(h.uuid),onDragOver:()=>c.hoverOver(h.uuid),onDrop:()=>f(b),isDragging:c.dragSourceUuid===h.uuid,isDragOver:c.dragOverUuid===h.uuid&&c.dragSourceUuid!==h.uuid},h.uuid))})]})}function ix(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 lx({journalTimestamp:e}){const{entry:t,loading:r,error:s}=ix(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(Ga,{entry:t}):n.jsx("p",{className:"text-sm text-[var(--text-dim)]",children:"No journal entry found for this plan yet."})}function cx({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:ct(e.completedAt)}),e.completedBy&&n.jsxs("span",{className:"text-[10px] text-[var(--text-dim)] whitespace-nowrap","data-testid":`completed-plan-by-${e.slug}`,children:["completed by ",e.completedBy.agentProvider??"agent","@",e.completedBy.machine]}),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(lx,{journalTimestamp:e.journalTimestamp})})]})}function dx({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(ux,{plans:e,loading:t,error:r,expandedSlug:s,onToggle:l=>a(c=>c===l?null:l)})]})}function ux({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(cx,{plan:o,expanded:s===o.slug,onToggle:()=>a(o.slug)},o.slug))})}function fx({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}=Yr(),{claims:m}=xh(),{slugs:h}=Ho(),{status:b}=gh(),{staleness:g}=bh(),y=((b==null?void 0:b.consecutiveFailures)??0)>=3,{plans:w,loading:v,error:x}=Nh(),{config:j}=dt(),k=lt(j==null?void 0:j.provider),N=l!==void 0,C=Zr(),S=N?a??null:C.launchingSlug,R=N?o??null:C.error,[E,A]=i.useState(!1),[D,B]=i.useState(!1),[T,O]=i.useState(null),[Y,P]=i.useState(null),$=i.useMemo(()=>jh(m),[m]),V=i.useMemo(()=>kh(m,h),[m,h]),[_,X]=i.useState(c),F=e!==void 0,L=F?e:E,M=I=>{F||A(I),t==null||t(I)},Q=()=>{M(!1),p()},q=()=>{const I=!L;I&&We(),M(I)};i.useEffect(()=>{if(!(!r||!L))return We()},[r,L]);const{annotationsBySlug:W,dependenciesBySlug:z}=Vo(d),J=I=>{var le;const ne=((le=d.find(Z=>Z.slug===I))==null?void 0:le.title)??I;if(l){l(I,ne);return}C.launchPlan(I,ne)},U=I=>{const ne=Wo(z[I]??[]);if(ne.length>0){O(ne);return}const le=$.get(I);if(le&&le.source!=="local"){P(le);return}J(I)},se=()=>{const I=Y;if(I){if(P(null),I.sessionAlive===!1){fetch(`/api/plan-claims/${encodeURIComponent(I.slug)}/reclaim`,{method:"POST"}).catch(()=>{}).finally(()=>J(I.slug));return}J(I.slug)}},{reorderPlans:ie}=Uo(p);return n.jsxs(Lr,{testId:"plan-tab",children:[n.jsx(Fh,{subTab:_}),n.jsx(Bh,{active:_,onChange:X}),_==="describe"&&n.jsx(qh,{providerLabel:k,chatOpen:L,onChatToggle:q,onChatClose:Q}),_==="prototype"&&n.jsx(Kh,{isAgentBuilding:s,onLaunched:()=>X("describe")}),n.jsx(_o,{staleness:g}),n.jsx(wh,{status:b}),n.jsx(Kr,{plans:d,loading:u,error:f,onRun:U,launchingSlug:S,launchError:R,blocked:s,onBlockedClick:()=>B(!0),onReorder:ie,depAnnotationsBySlug:W,dependenciesBySlug:z,claimsBySlug:$,staleFetch:y}),n.jsx(Xh,{claims:V}),n.jsx(ox,{}),n.jsx(dx,{plans:w,loading:v,error:x}),D&&n.jsx(Lh,{onClose:()=>B(!1)}),T&&!D&&n.jsx(Ih,{deps:T,onClose:()=>O(null)}),Y&&n.jsx(Mh,{claim:Y,onCancel:()=>P(null),onConfirm:se})]})}function px({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(fx,{chatOpen:r,onChatOpenChange:s,isActive:e==="plan",isAgentBuilding:a,launchingSlug:o,launchError:l,onLaunchPlan:c})}):null}function mx({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 hx({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(mx,{visible:e===s,children:t[s]},s))})}function xx({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 gx({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(hx,{activeTab:e,width:r,children:{home:t,build:null,plan:null,history:a?n.jsx(Dd,{}):null,settings:n.jsx(xx,{title:"Settings"})}})})}function bx({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:b}=Vo(e),g=i.useCallback(j=>{j.key==="Escape"&&(j.preventDefault(),c())},[c]);i.useEffect(()=>(window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)),[g]);const y=p.trim(),w=y.length===0||o||r!==null,v=()=>{w||a(y)},x=j=>{(j.metaKey||j.ctrlKey)&&j.key==="Enter"&&(j.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(Kr,{plans:e,loading:d,error:u,onRun:j=>{var N;const k=((N=e.find(C=>C.slug===j))==null?void 0:N.title)??j;t(j,k)},launchingSlug:r,launchError:s,blocked:f,depAnnotationsBySlug:h,dependenciesBySlug:b})}),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:j=>m(j.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, #D7FF63)",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 vx({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 yx({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(vx,{onCreateNewPlan:e,onViewPlans:t})})}function wx(e){return!e||!(e instanceof Element)?!1:!!e.closest("[data-terminal-emulator], .xterm")}function jx(e){return!e||!(e instanceof Element)?!1:!!e.closest("[data-post-push-modal]")}function kx({onStartNextFeature:e,onContinueInSession:t,onStopBuilding:r,onSendTranscript:s,onSelectPlan:a,pendingPlanCount:o=0}){const l=o>0&&a,c={background:"var(--accent-active)",color:"var(--bg-deep)"},d={background:"transparent",color:"var(--text-secondary)",border:"1px solid var(--border-default)"},u={background:"transparent",color:"var(--accent-danger, #f87171)",border:"1px solid var(--accent-danger, #f87171)"};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:[l&&n.jsx("button",{onClick:a,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition cursor-pointer",style:c,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:l?d:c,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:d,type:"button",children:"Continue in Current Session"}),n.jsx("button",{onClick:r,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition cursor-pointer",style:u,type:"button","data-testid":"post-push-stop-building",children:"Stop Building"}),s&&n.jsx("button",{onClick:s,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:l?"Press Enter to pick a queued plan":"Press Enter to start a new feature with a fresh context"})]})}function Nx({onStartNextFeature:e,onContinueInSession:t,onStopBuilding:r,onSendTranscript:s,onSelectPlan:a,pendingPlanCount:o=0}){const l=i.useCallback(c=>{if(c.key!=="Enter"||wx(c.target))return;const d=c.target===document.body||c.target===document.documentElement||c.target===document;!jx(c.target)&&!d||(c.preventDefault(),o>0&&a?a():e())},[a,e,o]);return i.useEffect(()=>(window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)),[l]),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(kx,{onStartNextFeature:e,onContinueInSession:t,onStopBuilding:r,onSendTranscript:s,onSelectPlan:a,pendingPlanCount:o})})}function Cx({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(Lo,{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 Sx({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,fullWidth:m=!1,navigateToTab:h,onAgentActive:b,onAgentIdle:g,onUserInput:y,notifSettings:w,onSettingsChange:v,provider:x,onContinueInSession:j,onRestorePreview:k,onResultsScenarioSelect:N,previewSlug:C=null,onSessionDetected:S,onStartNextFeature:R,onStopBuilding:E,showPostPushModal:A,showResultsCommandKey:D,planChatOpen:B,onPlanChatOpenChange:T,showPlanCompleteModal:O,onCreateNewPlan:Y,onViewPlans:P,pendingPlans:$,onSelectPlan:V,selectPlanOpen:_,onPickPlan:X,onCancelSelectPlan:F,launchingPlanSlug:L,planLaunchError:M,showBuildLaunchModal:Q=!1,onSubmitBuildPrompt:q,submittingBuildPrompt:W=!1,buildPromptError:z=null,onCancelBuildLaunchModal:J,pendingPlansLoading:U,pendingPlansError:se,onReorderPlans:ie,buildDisabled:I=!1}){return n.jsxs("div",{className:`${m?"flex-1 w-full min-w-0":"shrink-0"} flex flex-col overflow-hidden`,style:m?{background:"var(--bg-deep)"}:{width:p,background:"var(--bg-deep)"},children:[n.jsx(Qm,{activeTab:e,onTabChange:h,onSendTranscript:t,buildIdle:l,isAgentBuilding:c,bannerVisible:d,onDismissIdleBanner:u,buildDisabled:I}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden relative",children:[n.jsx(uh,{awaitingPlanLaunchChoice:s,buildActivated:a,activeTab:e,onSessionDetected:S,onSelectScenario:N,previewSlug:C,showResultsCommandKey:D,hideResultsCommandKey:f,onAgentIdle:g,onAgentActive:b,onUserInput:y,notifSettings:w,onSettingsChange:v,provider:x,onRestorePreview:k,pendingPlans:$,pendingPlansLoading:U,pendingPlansError:se,onLaunchPlan:X,launchingSlug:L,launchError:M,onReorderPlans:ie,isAgentBuilding:c}),n.jsx(px,{activeTab:e,planActivated:o,chatOpen:B,onChatOpenChange:T,isAgentBuilding:c,launchingPlanSlug:L,planLaunchError:M,onLaunchPlan:X}),n.jsx(gx,{activeTab:e,appTabContent:r,leftWidth:p}),A&&e==="build"&&!_?n.jsx(Nx,{onStartNextFeature:R,onContinueInSession:j,onStopBuilding:E,onSendTranscript:t,onSelectPlan:V,pendingPlanCount:$.length}):null,_&&e==="build"?n.jsx(Cx,{plans:$,onSelect:X,onCancel:F,launchingSlug:L,error:M}):null,Q&&e==="build"&&!A&&q&&J?n.jsx(bx,{plans:$,onPickPlan:X,launchingSlug:L,planError:M,onSubmitPrompt:q,submittingPrompt:W,promptError:z,onCancel:J,pendingPlansLoading:U,pendingPlansError:se,isAgentBuilding:c}):null,O&&e==="plan"?n.jsx(yx,{onCreateNewPlan:Y,onViewPlans:P}):null]})]})}const Ys=5173;function es(e){if(e.startsWith("http"))try{return new URL(e).pathname}catch{return e}return e.split("?")[0]??e}function Go(e){return e?parseInt(e.port||(e.protocol==="https:"?"443":"80"),10):0}function Yo(e,{appPort:t,currentPort:r,previewOrigin:s}){return e.startsWith("http")?e:s?`${s}${e}`:r===t?e:`http://localhost:${t}${e}`}function qo(e,t,r,s,a){if(r&&r.length>0)return Yo(r,{appPort:s,currentPort:t,previewOrigin:a});const o=`/scenario/${e}`;return a?`${a}${o}`:t===Ys?o:`http://localhost:${Ys}${o}`}async function qs(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 Ex(e){try{await fetch("/api/editor-iframe-error",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({error:e})})}catch{}}async function Rx(e){try{await fetch("/api/editor-iframe-banner",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({seedError:e})})}catch{}}function Tx(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 Px=32;function Dx({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:Tx(s.width,s.height,t,e,Px);return{containerRef:d,containerSize:s,scale:u}}function Ax(){const[e,t]=i.useState({kind:"iframe",fallbackKind:null,fallbackPort:null,loading:!0});return i.useEffect(()=>{let r=!1;return fetch("/api/project-stack").then(s=>s.ok?s.json():{}).then(s=>{r||t(Fx(s))}).catch(()=>{r||t({kind:"iframe",fallbackKind:null,fallbackPort:null,loading:!1})}),()=>{r=!0}},[]),e}function Fx(e){const t=e&&typeof e=="object"&&"preview"in e?e.preview:null;if(!t||typeof t!="object")return{kind:"iframe",fallbackKind:null,fallbackPort:null,loading:!1};const r=t;return{kind:Lx(r.kind),fallbackKind:Mx(r.fallbackKind),fallbackPort:typeof r.fallbackPort=="number"?r.fallbackPort:null,loading:!1}}function Lx(e){return e==="simulator-ios"?"simulator-ios":"iframe"}function Mx(e){return e==="iframe"||e==="simulator-ios"?e:null}function Ix(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 Js(){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 $x=50,Bx={status:"loading",lastSuccessAt:null,lastErrorAt:null,lastErrorMessage:null,fetchCount:0,errorCount:0};function Ox(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 zx(e,t){return{timestamp:t,success:e.ok,statusCode:e.statusCode,durationMs:e.durationMs,error:e.error}}function _x(e,t){return[t,...e].slice(0,$x)}function Hx(){const[e,t]=i.useState(Bx),[r,s]=i.useState([]),a=i.useCallback(l=>{const c=Date.now();s(d=>_x(d,zx(l,c))),t(d=>Ox(d,l,c))},[]),o=i.useCallback(()=>{t(l=>({...l,status:"polling"}))},[]);return{connectionState:e,fetchLog:r,recordFetch:a,markPolling:o}}function Wx(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 Vx({state:e}){const t=Yt(),{dotClass:r,label:s,labelClass:a}=Wx(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 ",ul(e.lastSuccessAt,t)]})]})}function Ux({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:dr(e.durationMs)}),e.error&&n.jsx("span",{className:"text-red-500 truncate","data-testid":"connection-log-error",children:e.error})]})}function Kx({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(Ux,{entry:a},a.timestamp))})})]})}function Gx({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 Yx({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(Gr,{title:"Function Coverage",aggregate:t,aggregateTestId:"functions-coverage-aggregate"}),s&&n.jsx(Gx,{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(Jt,{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 qx({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(Gr,{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(Oo,{file:r},r.filePath))})]})]})}function Jx(){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 Xx({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(Dr,{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 Qx(){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 Zx({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 on(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 eg(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 ln({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 tg({failures:e}){const t=eg(e);return n.jsxs("div",{className:"space-y-3",children:[t.global.length>0&&n.jsx(ln,{title:"Global",items:t.global.map(on)}),t.perFile.length>0&&n.jsx(ln,{title:"Per-file",items:t.perFile.map(on)}),t.perGlossaryEntry.length>0&&n.jsx(ln,{title:"Per-glossary-entry",items:t.perGlossaryEntry.map(on)}),t.regression.length>0&&n.jsx(ln,{title:"Regression",items:t.regression.map(on)})]})}function ng({report:e}){if(!e)return n.jsx(Jx,{});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(Xx,{global:e.global,failureCount:e.failures.length}),e.usedDefaultThresholds&&n.jsx(Qx,{}),t?n.jsx(Zx,{ranRunners:e.ranRunners}):n.jsx(tg,{failures:e.failures})]})}const rg=new Set([3,4,6]),sg=5e3;function ag(){const[e,t]=i.useState(null),[r,s]=i.useState(!0),{connectionState:a,fetchLog:o,recordFetch:l,markPolling:c}=Hx(),d=i.useRef(null);if(i.useEffect(()=>{async function m(){const h=await Js();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&&rg.has(e.step)&&(d.current=setInterval(async()=>{c();const m=await Js();l(m),m.ok&&m.data&&t(m.data)},sg)),()=>{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=Ix(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(Vx,{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(Wa,{children:e.userPrompt})]})]}),n.jsx(gd,{currentStep:u}),n.jsx(bd,{stats:e.testRunnerStats}),n.jsx(zo,{warnings:e.coverageWarnings??[]}),p&&n.jsx("div",{className:"text-sm text-[var(--text-secondary)] text-center",children:p}),e.narrative&&n.jsx(vd,{narrative:e.narrative}),e.narrative?n.jsx(yd,{narrative:e.narrative}):n.jsx(kd,{step:u,fileCount:e.modifiedFiles.length,testCount:f}),n.jsx(qx,{projectWide:e.projectWideCoverage??null,orphanedFiles:e.orphanedFiles??[]}),n.jsx(Yx,{functions:e.functions,aggregate:e.coverage??null,projectWide:e.projectWideCoverage??null}),n.jsx(ng,{report:e.coverageThresholds??null}),e.modifiedFiles.length>0&&n.jsx(Cd,{files:e.modifiedFiles,defaultCollapsed:e.narrative!==null}),n.jsx(Kx,{state:a,entries:o})]})})}function og(){return n.jsx("div",{className:"flex-1 flex flex-col min-w-0 overflow-auto",style:{background:"var(--bg-deep)"},children:n.jsx(ag,{})})}function ig({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"})]})]})})}function lg(e,t){var c;const r=[],s=Object.entries(t.vars).filter(([,d])=>d&&d.trim());if(s.length>0){const d=s.map(([u,f])=>` ${u}: ${f};`).join(`
17
- `);r.push(`:root {
18
- ${d}
19
- }`)}if(t.primaryFont){const d=Xs(t.primaryFont,t.primaryFontStack);r.push(`body, p, li, span, button, input, textarea, select, label { font-family: ${d} !important; }`)}if(t.secondaryFont){const d=Xs(t.secondaryFont,t.secondaryFontStack);r.push(`h1, h2, h3, h4, h5, h6, .heading, [class*="title"], [class*="headline"] { font-family: ${d} !important; }`)}const a=r.length>0?`<style data-codeyam-overrides="1">
20
- ${r.join(`
21
-
22
- `)}
23
- </style>`:"",o=t.fontsHref?`<link rel="preconnect" href="https://fonts.googleapis.com">
24
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
25
- <link rel="stylesheet" href="${t.fontsHref}" data-codeyam-fonts="1">`:"";if(!a&&!o)return e;const l=e.search(/<\/head\s*>/i);if(l===-1){const d=e.search(/<body[^>]*>/i);if(d===-1)return`${o}
26
- ${a}
27
- ${e}`;const u=d+(((c=e.match(/<body[^>]*>/i))==null?void 0:c[0].length)??0);return`${e.slice(0,u)}
28
- ${o}
29
- ${a}
30
- ${e.slice(u)}`}return`${e.slice(0,l)}
31
- ${o}
32
- ${a}
33
- ${e.slice(l)}`}function Xs(e,t){const r=/\s/.test(e)?`"${e}"`:e,s=(t==null?void 0:t.trim())||"system-ui, sans-serif";return`${r}, ${s}`}const cg={vars:{},primaryFont:null,secondaryFont:null,primaryFontStack:null,secondaryFontStack:null};function ts(e){return e.replace(/^\d{1,2}-/,"").replace(/-mockup\.html$/i,"").replace(/\.html$/i,"")}function dg(e,t){if(e===null||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r].filename!==t[r].filename||e[r].url!==t[r].url||e[r].name!==t[r].name)return!1;return!0}const ug="\x1B[200~",fg="\x1B[201~";function pg(e,t=mg){const r=e.replace(/\r\n/g,"\r").replace(/\n/g,"\r"),s=`${ug}${r}${fg}`;return t(s),new Promise(a=>{setTimeout(()=>{t("\r"),a()},fl)})}function mg(e){window.dispatchEvent(new CustomEvent("miniagent-send-input",{detail:e}))}function hg({feedbackByFilename:e,mockupFilenames:t}){const r={};for(const o of t){const l=e[o];if(!l)continue;const c=typeof l.rating=="number",d=l.comment.trim().length>0;!c&&!d||(r[o]={rating:c?l.rating:null,comment:l.comment.trim()})}return Object.keys(r).length===0?"Iterate: before regenerating anything, first ask the user in the chat which of these designs (if any) are close enough to keep and just tweak — and let them know that every other design will be discarded and redesigned fresh. Wait for their reply before writing any mockup. No per-card feedback was provided, so let their answer guide what to keep vs. redesign from scratch.":`Iterate: before regenerating anything, first ask the user in the chat which of these designs (if any) are close enough to keep and just tweak — and let them know that every other design will be discarded and redesigned fresh from the feedback below. Wait for their reply before writing any mockup.
34
-
35
- Once they answer: for designs they choose to keep, refine them in place using their specific feedback, keeping the same numeric prefix and design system. For every other design, redesign it fresh from the feedback — each redesign must directly address the specific comment and rating for that card (a pointed comment is a concrete instruction the redesign must visibly resolve; a low rating means change direction further). For fresh redesigns, weigh the rating and comment to decide whether to keep the same design system with a new layout, or swap in a different system from .codeyam/design/design_systems/ — avoid duplicating a system already used by a kept card. When you change a slot's design system, delete the old NN-*.html file before writing the new NN-<newsystem>-mockup.html so each slot has exactly one file. Keep numeric filename prefixes stable so slots don't move.
36
-
37
- Per-card feedback (rating is 1-100 or null; comment may be empty):
38
-
39
- \`\`\`json
40
- `+JSON.stringify(r,null,2)+"\n```"}function xg(e){const t={},r={},s=e.split(`
41
- `);let a=!1,o=[];for(const l of s){const c=l.trim();if(/^```/.test(c)){a=!a;continue}if(a)continue;const d=/^(#{1,6})\s+(.+)$/.exec(c);if(d){const b=d[1].length;o=o.slice(0,b-1),o[b-1]=d[2].trim();continue}if(!c.startsWith("|"))continue;const u=c.split("|").map(b=>b.trim());if(u.length<3)continue;const f=u[1].replace(/`/g,"").trim(),p=u[2].replace(/`/g,"").trim();if(!/^--[A-Za-z0-9_-]+$/.test(f)||!gg(p))continue;const m=o.filter(Boolean).join(" / "),h=Jo(m)?r:t;f in h||(h[f]=p)}return{light:t,dark:r}}function Jo(e){return/\bdark[\s-]?mode\b|\bdark\b\s*(palette|variant|theme)?/i.test(e)}function gg(e){return!!(/^#[0-9a-fA-F]{3,8}$/.test(e)||/^rgba?\(/i.test(e)||/^hsla?\(/i.test(e)||/^oklch\(/i.test(e))}const bg=["Background","Surface","Text","Primary","Secondary","Accent"],vg={Background:[/^--bg(-default|-page|-canvas|-base)?$/,/^--page(-bg)?$/,/^--canvas$/,/^--background$/,/^--light-linen$/,/^--paper$/,/^--body-bg$/,/-canvas$/,/-page-bg$/],Surface:[/^--bg-surface$/,/^--surface(-1|-elevated)?$/,/^--card(-bg)?$/,/^--bg-elevated$/,/^--marketplace-gray$/,/^--panel(-bg)?$/,/^--cream$/,/-surface$/,/-porcelain-surface$/],Text:[/^--text(-primary|-default)?$/,/^--fg(-default)?$/,/^--foreground$/,/^--ink$/,/^--pitch-black$/,/^--body-text$/,/^--ink-text$/,/-ink-text$/,/-graphite-text$/],Primary:[/^--primary$/,/^--accent(-primary)?$/,/^--brand(-primary)?$/,/^--creator-pink$/,/^--palette-1$/,/^--lime$/,/^--burgundy$/,/-amethyst-accent$/,/-accent$/],Secondary:[/^--secondary$/,/^--accent-secondary$/,/^--brand-secondary$/,/^--sunshine-yellow$/,/^--palette-2$/,/^--sage$/,/^--sky-blue$/,/-sky-blue-highlight$/,/-highlight$/],Accent:[/^--accent(-tertiary|-highlight)?$/,/^--highlight$/,/^--lime-glow$/,/^--lime-deep$/,/^--firecracker-orange$/,/^--sky-blue$/,/^--gold$/,/^--palette-3$/,/-detail$/]};function yg(e){const t=[],r=e.split(`
42
- `);let s=!1,a="",o=0,l=null,c=[];for(let d=0;d<r.length;d++){const f=r[d].trim();if(!s){const p=/^(#{1,6})\s+(.+)$/.exec(f);if(p){const h=p[1].length;c=c.slice(0,h-1),c[h-1]=p[2].trim(),l=p[2].trim();continue}const m=/^```(\w*)/.exec(f);m&&(s=!0,a=m[1].toLowerCase(),o=d+1);continue}if(f==="```"){if(a==="css"||a===""){const p=r.slice(o,d).join(`
43
- `);for(const m of jg(p)){const h=c.filter(Boolean).join(" / "),b=wg(m.selector)||Jo(h);t.push({selector:m.selector,heading:l,isDark:b,vars:m.vars})}}s=!1,a=""}}return t}function wg(e){return/\[data-theme[~|*$^]?="?dark"?\]/.test(e)}function jg(e){const t=[],r=/(:root[^\{]*?)\{([\s\S]*?)\}/g;let s;for(;(s=r.exec(e))!==null;){const a=s[1].trim(),o=s[2],l={},c=/(--[A-Za-z0-9_-]+)\s*:\s*([^;\n]+?)\s*(?:;|$)/g;let d;for(;(d=c.exec(o))!==null;){const u=d[1],f=d[2].replace(/\/\*.*?\*\//g,"").trim();f&&(l[u]=f)}Object.keys(l).length>0&&t.push({selector:a,vars:l})}return t}function kg(e,t){const r=vg[t];for(const s of Object.keys(e))for(const a of r)if(a.test(s))return{cssVar:s,value:e[s]};return{cssVar:null,value:null}}function Ng(e){const t=/\[data-palette[~|*$^]?="?([^"\]]+)"?\]/.exec(e);return t?t[1].split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" "):null}function Cg(e){if(!e)return"Default";let t=e.replace(/\(.+?\)/g,"");return t=t.replace(/\bpalette\b/i,"").replace(/\bmode\b/i,""),/\bdark\b/i.test(t)?"Default":(t=t.replace(/\bdark\b/i,""),t=t.replace(/\blight\b/i,""),t=t.trim().replace(/\s+/g," "),t||"Default")}function Qs(e){const t=bg.map(r=>{const{cssVar:s,value:a}=kg(e,r);return{label:r,cssVar:s,value:a}});return{vars:e,slots:t}}function Xo(e){const t=yg(e),r=new Map,s=new Map,a=[];for(const o of t){const c=Ng(o.selector)??Cg(o.heading);a.includes(c)||a.push(c),o.isDark?s.has(c)||s.set(c,o.vars):r.has(c)||r.set(c,o.vars)}if(r.size===0){const o=xg(e);o.light&&Object.keys(o.light).length>0&&(a.unshift("Default"),r.set("Default",o.light),o.dark&&Object.keys(o.dark).length>0&&s.set("Default",o.dark))}return a.map(o=>{const l=r.get(o);if(!l)return null;const c=s.get(o)??null;return{name:o,light:Qs(l),dark:c?Qs(c):null}}).filter(o=>o!==null)}function Sg(e){const[t,r]=i.useState({}),s=i.useRef(!0);return i.useEffect(()=>(s.current=!0,()=>{s.current=!1}),[]),i.useEffect(()=>{if(!e)return;const a=new Set,o=e.map(l=>ts(l.filename)).filter(l=>a.has(l)?!1:(a.add(l),!(l in t)));o.length!==0&&(async()=>{var l,c;for(const d of o)try{const u=await fetch(`/api/editor-design-systems/${d}`);if(!u.ok)continue;const f=await u.json().catch(()=>null);if(!(f!=null&&f.content)){s.current&&r(h=>({...h,[d]:null}));continue}const m=((c=(l=Xo(f.content)[0])==null?void 0:l.dark)==null?void 0:c.vars)??null;s.current&&r(h=>({...h,[d]:m}))}catch{s.current&&r(u=>({...u,[d]:null}))}})()},[e,t]),t}function Eg(){const[e,t]=i.useState([]);return i.useEffect(()=>{let r=!1;async function s(){try{const o=await fetch("/api/editor-mockups-history");if(!o.ok)return;const l=await o.json();r||t(Array.isArray(l)?l:[])}catch{}}s();const a=window.setInterval(s,4e3);return()=>{r=!0,window.clearInterval(a)}},[]),e}function Rg({round:e}){return n.jsx("div",{"data-mockup-archived-round":!0,style:{display:"grid",gridTemplateColumns:"1fr 1fr",columnGap:"var(--spacing-lg, 16px)",rowGap:"var(--spacing-xl, 28px)"},children:e.mockups.map((t,r)=>{const s=e.feedback[t.filename],a=r+1,o=t.name.replace(/^\d{1,2}-/,"").replace(/-/g," ");return n.jsxs("div",{style:{display:"flex",flexDirection:"column",border:"1px solid var(--border-default)",borderRadius:12,overflow:"hidden",background:"var(--bg-surface)"},children:[n.jsxs("div",{style:{padding:"var(--spacing-sm, 10px) var(--spacing-md, 14px)",display:"flex",alignItems:"center",gap:6,color:"var(--text-primary)",fontSize:"var(--text-sm, 14px)"},children:[n.jsx("span",{style:{fontWeight:700,color:"var(--text-muted)"},children:String(a).padStart(2,"0")}),n.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",style:{textTransform:"capitalize",fontWeight:500,color:"var(--text-primary)",textDecoration:"none"},children:o})]}),n.jsx("iframe",{src:t.url,title:t.name,sandbox:"",style:{width:"100%",aspectRatio:"1 / 1",border:"none",pointerEvents:"none",background:"var(--bg-card, #1a1a1a)"}}),s&&(typeof s.rating=="number"||s.comment.trim().length>0)&&n.jsxs("div",{style:{padding:"var(--spacing-sm, 10px) var(--spacing-md, 14px)",borderTop:"1px solid var(--border-default)",display:"flex",flexDirection:"column",gap:4,fontSize:"var(--text-xs, 12px)",color:"var(--text-secondary)"},children:[typeof s.rating=="number"&&n.jsxs("div",{children:[n.jsxs("span",{style:{color:"var(--text-muted)"},children:["Rating ·"," "]}),n.jsxs("span",{style:{color:"var(--text-primary)"},children:[s.rating,"/100"]})]}),s.comment.trim().length>0&&n.jsxs("div",{style:{lineHeight:1.4},children:[n.jsxs("span",{style:{color:"var(--text-muted)"},children:["Note ·"," "]}),n.jsx("span",{style:{color:"var(--text-primary)"},children:s.comment})]})]})]},t.filename)})})}const ns=[{family:"Archivo",category:"sans",weights:[400,500,600,700]},{family:"DM Sans",category:"sans",weights:[400,500,700]},{family:"Inter",category:"sans",weights:[400,500,600,700]},{family:"Karla",category:"sans",weights:[400,500,700]},{family:"Manrope",category:"sans",weights:[400,500,700]},{family:"Nunito",category:"sans",weights:[400,600,700]},{family:"Plus Jakarta Sans",category:"sans",weights:[400,500,700]},{family:"Public Sans",category:"sans",weights:[400,500,700]},{family:"Roboto",category:"sans",weights:[400,500,700]},{family:"Work Sans",category:"sans",weights:[400,500,700]},{family:"Cormorant Garamond",category:"serif",weights:[400,500,700]},{family:"Crimson Pro",category:"serif",weights:[400,600,700]},{family:"Fraunces",category:"serif",weights:[400,600,700]},{family:"Lora",category:"serif",weights:[400,500,700]},{family:"Merriweather",category:"serif",weights:[400,700]},{family:"Playfair Display",category:"serif",weights:[400,600,700]},{family:"Source Serif 4",category:"serif",weights:[400,600,700]},{family:"Abril Fatface",category:"display",weights:[400]},{family:"Bebas Neue",category:"display",weights:[400]},{family:"Bricolage Grotesque",category:"display",weights:[400,600,800]},{family:"Chakra Petch",category:"display",weights:[400,600,700]},{family:"Lexend",category:"display",weights:[400,500,700]},{family:"Outfit",category:"display",weights:[400,600,800]},{family:"Rubik",category:"display",weights:[400,500,700]},{family:"Space Grotesk",category:"display",weights:[400,500,700]},{family:"Syne",category:"display",weights:[400,600,800]},{family:"Unbounded",category:"display",weights:[400,600,800]},{family:"Fira Code",category:"mono",weights:[400,500,700]},{family:"IBM Plex Mono",category:"mono",weights:[400,500,600]},{family:"JetBrains Mono",category:"mono",weights:[400,500,700]},{family:"Space Mono",category:"mono",weights:[400,700]}],Tg={sans:"Sans-serif",serif:"Serif",display:"Display",mono:"Monospace"};function Qo(e){const t=new Set,r=[];for(const s of e){if(!s||t.has(s))continue;t.add(s);const a=ns.find(c=>c.family===s),o=(a==null?void 0:a.weights)??[400,700],l=s.replace(/ /g,"+");r.push(`family=${l}:wght@${o.join(";")}`)}return r.length===0?"":`https://fonts.googleapis.com/css2?${r.join("&")}&display=swap`}function Pg(e,t,r){const s={},a=Zs(e,r),o=Zs(t,r),l=new Map;for(const c of a)c.cssVar&&l.set(c.label,c.cssVar);for(const c of o){if(!c.value)continue;const d=l.get(c.label)??c.cssVar;d&&(s[d]=c.value)}return s}function Zs(e,t){return e?t==="dark"&&e.dark?e.dark.slots:e.light.slots:[]}function Dg(e,t,r){var a,o;return t!=="dark"?r:{...((o=(a=e[0])==null?void 0:a.dark)==null?void 0:o.vars)??{},...r}}function Ag(e,t){const[r,s]=i.useState({kind:"loading"});return i.useEffect(()=>{let a=!1;return s({kind:"loading"}),(async()=>{try{const[o,l]=await Promise.all([fetch(e),fetch(`/api/editor-design-systems/${t}`)]),c=await o.text();let d="";if(l.ok){const u=await l.json().catch(()=>null);d=(u==null?void 0:u.content)??""}if(a)return;s({kind:"ready",html:c,palettes:Xo(d)})}catch(o){a||s({kind:"error",message:o instanceof Error?o.message:String(o)})}})(),()=>{a=!0}},[e,t]),r}function Zo(e,t,r){i.useEffect(()=>{if(!e)return;const s=o=>{var c;const l=o.target;(c=t.current)!=null&&c.contains(l)||r()},a=o=>{o.key==="Escape"&&r()};return document.addEventListener("mousedown",s),document.addEventListener("keydown",a),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",a)}},[e,t,r])}function cn(e,t,r){return{name:e,light:ea(t),dark:r?ea(r):null}}function ea(e){const t=[{label:"Background",cssVar:"--bg-default",value:e.bg},{label:"Surface",cssVar:"--bg-surface",value:e.surface},{label:"Text",cssVar:"--text-primary",value:e.text},{label:"Primary",cssVar:"--accent-primary",value:e.primary},{label:"Secondary",cssVar:"--accent-secondary",value:e.secondary},{label:"Accent",cssVar:"--accent-highlight",value:e.accent}],r={};for(const s of t)s.cssVar&&s.value&&(r[s.cssVar]=s.value);return{vars:r,slots:t}}function Fg(){return[cn("Lime Bright",{bg:"#F4F4EE",surface:"#FFFFFF",text:"#0F0F0F",primary:"#D7FF63",secondary:"#9DA48F",accent:"#FF6B5C"},{bg:"#14160F",surface:"#25251F",text:"#F1EFEA",primary:"#D7FF63",secondary:"#4D5247",accent:"#FF6B5C"}),cn("Warm Cream",{bg:"#EFE9DA",surface:"#F8F3E7",text:"#3B2F1C",primary:"#C44536",secondary:"#7A9E7E",accent:"#EAA64A"},{bg:"#1F1A11",surface:"#2A2418",text:"#EFE9DA",primary:"#E07767",secondary:"#A9CBA9",accent:"#EAA64A"}),cn("Cool Mono",{bg:"#F5F6F8",surface:"#FFFFFF",text:"#101218",primary:"#2B2D3A",secondary:"#8B8FA3",accent:"#5C8DFF"},{bg:"#0E1016",surface:"#181B23",text:"#E9EBF2",primary:"#E9EBF2",secondary:"#8B8FA3",accent:"#7CA0FF"}),cn("Bold Pop",{bg:"#FFF8F0",surface:"#FFFFFF",text:"#181818",primary:"#FF3D7F",secondary:"#3DD2FF",accent:"#FFD60A"},{bg:"#161113",surface:"#1F1A1D",text:"#FFF8F0",primary:"#FF3D7F",secondary:"#3DD2FF",accent:"#FFD60A"})]}function Lg({palettes:e,activeName:t,theme:r,onApply:s}){const a=(()=>{const o=new Set(e.map(c=>c.name.toLowerCase())),l=Fg().filter(c=>!o.has(c.name.toLowerCase()));return[...e,...l]})();return n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:a.map(o=>{const l=r==="dark"&&o.dark?o.dark:o.light,c=o.name===t;return n.jsx("button",{type:"button",onClick:()=>s(o),"aria-pressed":c,"aria-label":`Apply ${o.name} palette`,title:o.name,style:{padding:4,border:c?"2px solid var(--accent-active, #D7FF63)":"1px solid var(--border-default)",borderRadius:8,background:"var(--bg-elevated)",cursor:"pointer"},children:n.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 18px)",gridTemplateRows:"repeat(2, 18px)",gap:2},children:l.slots.map(d=>n.jsx("span",{title:d.label,style:{width:18,height:18,borderRadius:4,border:"1px solid var(--border-default)",background:d.value??"transparent"}},d.label))})},o.name)})})}function Mg({slots:e,values:t,onChange:r}){return n.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, minmax(0, 1fr))",gap:"8px 16px"},children:e.map(s=>{const a=!s.cssVar,o=s.cssVar?t[s.cssVar]??s.value??"":"",l=Ig(o);return n.jsxs("div",{style:{display:"grid",gridTemplateColumns:"70px 1fr 80px",alignItems:"center",gap:6,opacity:a?.4:1,minWidth:0},children:[n.jsx("span",{style:{fontSize:"var(--text-xs, 12px)",color:"var(--text-primary)",fontWeight:500},children:s.label}),n.jsx("input",{type:"color","aria-label":`${s.label} color`,disabled:a,value:l,onChange:c=>{s.cssVar&&r(s.cssVar,c.target.value)},style:{width:"100%",height:28,border:"1px solid var(--border-default)",borderRadius:6,background:"var(--bg-elevated)",cursor:a?"not-allowed":"pointer"}}),n.jsx("input",{type:"text","aria-label":`${s.label} hex`,disabled:a,value:o,onChange:c=>{s.cssVar&&r(s.cssVar,c.target.value)},spellCheck:!1,style:{padding:"4px 6px",fontSize:"var(--text-xs, 12px)",fontFamily:"var(--font-mono, monospace)",border:"1px solid var(--border-default)",borderRadius:6,background:"var(--bg-elevated)",color:"var(--text-primary)"}})]},s.label)})})}function Ig(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t.toLowerCase():/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`.toLowerCase():"#000000"}function ta({children:e}){return n.jsx("h4",{style:{margin:"0 0 8px",fontFamily:"var(--font-mono, 'IBM Plex Mono', monospace)",fontSize:11,fontWeight:500,color:"var(--text-secondary)",textTransform:"uppercase",letterSpacing:"0.08em"},children:e})}function $g({palettes:e,activeName:t,theme:r,slots:s,vars:a,onApplyPalette:o,onColorChange:l}){return n.jsxs("div",{role:"menu",style:{padding:"var(--spacing-md, 12px)",background:"var(--bg-surface)",borderBottom:"1px solid var(--border-default)",display:"flex",flexDirection:"column",gap:12},children:[n.jsxs("div",{children:[n.jsx(ta,{children:"Palettes"}),n.jsx(Lg,{palettes:e,activeName:t,theme:r,onApply:o})]}),n.jsxs("div",{children:[n.jsx(ta,{children:"Individual colors"}),n.jsx(Mg,{slots:s,values:a,onChange:l})]})]})}function Bg({message:e}){return n.jsx("div",{style:{padding:"var(--spacing-md, 12px)",color:"var(--accent-danger, #f87171)",fontSize:"var(--text-sm, 14px)"},children:e})}let na=!1;function Og(){if(na||typeof document>"u")return;na=!0;const e=Qo(ns.map(r=>r.family));if(!e)return;const t=document.createElement("link");t.rel="stylesheet",t.href=e,t.dataset.codeyamFontPreviews="1",document.head.appendChild(t)}function ra({label:e,value:t,onChange:r,hint:s}){const[a,o]=i.useState(!1),l=i.useRef(null),c=i.useRef(null),d=i.useRef(null);i.useEffect(()=>{Og()},[]);const u=i.useCallback(()=>o(!1),[]);Zo(a,d,u);const f={sans:[],serif:[],display:[],mono:[]};for(const p of ns)f[p.category].push(p);return n.jsxs("div",{ref:d,style:{display:"flex",flexDirection:"column",gap:4,fontSize:"var(--text-xs, 12px)",color:"var(--text-primary)",position:"relative"},children:[n.jsx("span",{style:{fontFamily:"var(--font-mono, 'IBM Plex Mono', monospace)",fontSize:11,fontWeight:500,letterSpacing:"0.08em",textTransform:"uppercase",color:"var(--text-secondary)"},children:e}),s&&n.jsx("span",{style:{color:"var(--text-secondary)",fontStyle:"italic"},children:s}),n.jsxs("button",{ref:l,type:"button","aria-haspopup":"listbox","aria-expanded":a,onClick:()=>o(p=>!p),style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:6,padding:"6px 10px",background:"var(--bg-elevated)",color:"var(--text-primary)",border:"1px solid var(--border-default)",borderRadius:6,fontSize:"var(--text-sm, 14px)",fontFamily:t?`"${t}", system-ui, sans-serif`:"inherit",cursor:"pointer",textAlign:"left"},children:[n.jsx("span",{children:t??"System default"}),n.jsx("span",{"aria-hidden":!0,style:{opacity:.6},children:"▾"})]}),a&&n.jsxs("div",{ref:c,role:"listbox",style:{position:"absolute",top:"100%",left:0,right:0,marginTop:4,zIndex:20,background:"var(--bg-surface)",border:"1px solid var(--border-default)",borderRadius:8,boxShadow:"0 8px 24px rgba(0,0,0,0.12)",maxHeight:320,overflowY:"auto",padding:4},children:[n.jsx(sa,{family:null,label:"System default",isActive:t===null,onPick:()=>{r(null),o(!1)}}),Object.keys(f).map(p=>n.jsxs("div",{children:[n.jsx("div",{style:{padding:"6px 10px 2px",fontSize:"var(--text-xs, 11px)",color:"var(--text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:700},children:Tg[p]}),f[p].map(m=>n.jsx(sa,{family:m.family,label:m.family,isActive:t===m.family,onPick:()=>{r(m.family),o(!1)}},m.family))]},p))]})]})}function sa({family:e,label:t,isActive:r,onPick:s}){return n.jsx("button",{type:"button",role:"option","aria-selected":r,onClick:s,style:{display:"block",width:"100%",padding:"8px 10px",background:r?"var(--bg-elevated)":"transparent",color:"var(--text-primary)",border:"none",borderRadius:4,fontSize:16,fontFamily:e?`"${e}", system-ui, sans-serif`:"inherit",textAlign:"left",cursor:"pointer"},children:t})}function zg({primaryFont:e,secondaryFont:t,onPrimaryChange:r,onSecondaryChange:s}){return n.jsxs("div",{role:"menu",style:{padding:"var(--spacing-md, 12px)",background:"var(--bg-surface)",borderBottom:"1px solid var(--border-default)",display:"grid",gridTemplateColumns:"1fr 1fr",gap:16},children:[n.jsx(ra,{label:"Headings",value:t,onChange:s}),n.jsx(ra,{label:"Body text",value:e,onChange:r})]})}function ei(e){const t=/<meta\b[^>]*>/gi;let r;for(;(r=t.exec(e))!==null;){const s=r[0];if(!/name=["']codeyam-viewport["']/i.test(s))continue;const a=/content=["']([^"']+)["']/i.exec(s);if(!a)continue;const o=a[1].toLowerCase().trim();return o==="desktop"||o==="tablet"||o==="mobile"?o:null}return null}function _g(e,t){const r=Object.entries(t).filter(([,o])=>o&&o.trim());if(r.length===0)return e;const s=`<style data-codeyam-dark="1">:root {
44
- `+r.map(([o,l])=>` ${o}: ${l};`).join(`
45
- `)+`
46
- }</style>`,a=e.search(/<\/head\s*>/i);return a===-1?`${s}
47
- ${e}`:`${e.slice(0,a)}
48
- ${s}
49
- ${e.slice(a)}`}function Hg({html:e,srcDoc:t,theme:r,mockupUrl:s,mockupName:a}){const o=ei(e)??"desktop",l=o==="mobile"||o==="tablet",c=o==="mobile"?390:o==="tablet"?834:null;return n.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto",background:l?"#1a1a1a":"white",backgroundImage:l?"radial-gradient(circle, rgba(255,255,255,0.07) 1px, transparent 1px)":void 0,backgroundSize:l?"12px 12px":void 0,display:"flex",justifyContent:"center"},children:n.jsx("iframe",{title:`Customize preview: ${a}`,srcDoc:t,sandbox:"",style:{width:l&&c?`${c}px`:"100%",height:"100%",minHeight:800,border:"none",background:"white",flexShrink:0}},`${s}-${r}`)})}function ti({theme:e,onToggle:t,size:r=28}){return n.jsx("button",{type:"button",onClick:t,"aria-label":e==="light"?"Switch to dark mode":"Switch to light mode","aria-pressed":e==="dark",title:e==="light"?"Dark mode":"Light mode",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:r,height:r,background:"var(--bg-card, #1a1a1a)",border:"1px solid var(--border-default)",borderRadius:6,cursor:"pointer",color:"var(--text-primary)",padding:0,fontSize:14,lineHeight:1},children:e==="light"?"☾":"☀"})}function dn(e){return{height:28,padding:"0 8px",background:e?"#555":"#3a3a3a",color:e?"#ffffff":"#d1d5db",border:"none",borderRadius:4,fontSize:11,fontFamily:"var(--font-mono, 'IBM Plex Mono', monospace)",fontWeight:400,letterSpacing:"0.04em",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4}}function Wg({systemName:e,openMenu:t,theme:r,hasDark:s,saving:a,toolbarRef:o,onBack:l,onToggleMenu:c,onToggleTheme:d,onReset:u,onSave:f}){return n.jsxs("div",{ref:o,style:{display:"flex",alignItems:"center",gap:8,padding:"0 8px",height:40,borderBottom:"1px solid #3d3d3d",background:"#2d2d2d",flexWrap:"nowrap"},children:[n.jsx("button",{type:"button",onClick:l,"aria-label":"Back to mockups",style:{...dn(!1),background:"transparent"},children:"← Back"}),n.jsxs("span",{style:{color:"#9ca3af",fontSize:13,fontFamily:"'IBM Plex Sans', system-ui, sans-serif",fontWeight:400,marginRight:4},children:["Customize: ",e]}),n.jsxs("button",{type:"button","aria-haspopup":"menu","aria-expanded":t==="fonts",onClick:()=>c("fonts"),style:dn(t==="fonts"),children:["Fonts ",n.jsx("span",{"aria-hidden":!0,style:{opacity:.7},children:"▾"})]}),n.jsxs("button",{type:"button","aria-haspopup":"menu","aria-expanded":t==="colors",onClick:()=>c("colors"),style:dn(t==="colors"),children:["Colors ",n.jsx("span",{"aria-hidden":!0,style:{opacity:.7},children:"▾"})]}),n.jsx("button",{type:"button",onClick:u,style:{...dn(!1),background:"transparent",color:"#9ca3af"},children:"Reset"}),n.jsx("div",{style:{flex:1}}),s&&n.jsx(ti,{theme:r,onToggle:d,size:28}),n.jsx("button",{type:"button",onClick:f,disabled:a,style:{height:28,padding:"0 10px",background:"var(--accent-active, #D7FF63)",color:"var(--text-on-accent, #0F0F0F)",border:"none",borderRadius:4,fontSize:11,fontFamily:"var(--font-mono, 'IBM Plex Mono', monospace)",fontWeight:500,letterSpacing:"0.04em",cursor:a?"wait":"pointer",opacity:a?.7:1},children:a?"SAVING…":"SAVE"})]})}function Vg({mockup:e,systemName:t,initial:r,onBack:s,onSave:a,saving:o=!1}){var R;const l=Ag(e.url,t),[c,d]=i.useState(r),[u,f]=i.useState(null),[p,m]=i.useState("light"),[h,b]=i.useState(null),g=i.useRef(null),y=i.useCallback(()=>b(null),[]);Zo(h!==null,g,y);const w=i.useMemo(()=>{const E=[];return c.primaryFont&&E.push(c.primaryFont),c.secondaryFont&&E.push(c.secondaryFont),E.length===0?null:Qo(E)},[c.primaryFont,c.secondaryFont]),v=i.useMemo(()=>l.kind!=="ready"?c.vars:Dg(l.palettes,p,c.vars),[l,c.vars,p]),x=i.useMemo(()=>l.kind!=="ready"?"":lg(l.html,{...c,vars:v,fontsHref:w}),[l,c,v,w]),j=i.useCallback(E=>{f(E.name);const A=l.kind==="ready"?l.palettes[0]:void 0,D=Pg(A,E,p);d(B=>({...B,vars:{...B.vars,...D}}))},[l,p]),k=i.useCallback((E,A)=>{f(null),d(D=>({...D,vars:{...D.vars,[E]:A}}))},[]),N=i.useCallback(()=>{d({vars:{},primaryFont:null,secondaryFont:null,primaryFontStack:null,secondaryFontStack:null}),f(null)},[]),C=i.useMemo(()=>{if(l.kind!=="ready"||l.palettes.length===0)return[{label:"Background",cssVar:"--bg-default",value:null},{label:"Surface",cssVar:"--bg-surface",value:null},{label:"Text",cssVar:"--text-primary",value:null},{label:"Primary",cssVar:"--accent-primary",value:null},{label:"Secondary",cssVar:"--accent-secondary",value:null},{label:"Accent",cssVar:"--accent-highlight",value:null}];const E=l.palettes[0];return p==="dark"&&E.dark?E.dark.slots:E.light.slots},[l,p]),S=l.kind==="ready"&&!!((R=l.palettes[0])!=null&&R.dark);return n.jsxs("div",{"data-testid":"mockup-customize-view",className:"flex-1 flex flex-col min-w-0",style:{overflow:"hidden",position:"relative"},children:[n.jsxs("div",{ref:g,children:[n.jsx(Wg,{systemName:t,openMenu:h,theme:p,hasDark:S,saving:o,toolbarRef:{current:null},onBack:()=>s(c),onToggleMenu:E=>b(A=>A===E?null:E),onToggleTheme:()=>m(E=>E==="light"?"dark":"light"),onReset:N,onSave:()=>a(c)}),h==="fonts"&&n.jsx(zg,{primaryFont:c.primaryFont,secondaryFont:c.secondaryFont,onPrimaryChange:E=>d(A=>({...A,primaryFont:E})),onSecondaryChange:E=>d(A=>({...A,secondaryFont:E}))}),h==="colors"&&n.jsx($g,{palettes:l.kind==="ready"?l.palettes:[],activeName:u,theme:p,slots:C,vars:c.vars,onApplyPalette:j,onColorChange:k})]}),l.kind==="error"&&n.jsx(Bg,{message:l.message}),l.kind==="loading"?n.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto",background:"white",padding:"var(--spacing-lg, 16px)",color:"var(--text-secondary)"},children:"Loading mockup…"}):l.kind==="ready"?n.jsx(Hg,{html:l.html,srcDoc:x,theme:p,mockupUrl:e.url,mockupName:e.name}):null]})}const Ug={desktop:{w:1440,h:900},tablet:{w:834,h:1112},mobile:{w:390,h:844}},aa="desktop",Kg=1280,Gg=1280,Yg="#1a1a1a",qg="radial-gradient(circle, rgba(255,255,255,0.07) 1px, transparent 1px)",Jg="12px 12px";function Xg(e,t,r,s){if(e<=0||t<=0||r<=0||s<=0)return{scale:0,offsetX:0,offsetY:0};const a=Math.min(e/r,t/s),o=r*a,l=s*a;return{scale:a,offsetX:Math.max(0,(e-o)/2),offsetY:Math.max(0,(t-l)/2)}}function Qg(){return n.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("path",{d:"M4.5 2.5h-2v7h7v-2"}),n.jsx("path",{d:"M7 2.5h2.5V5"}),n.jsx("path",{d:"M9.5 2.5L5.5 6.5"})]})}function Zg({displayNumber:e,formattedName:t,theme:r,showThemeToggle:s,busy:a,openInNewTabUrl:o,onToggleTheme:l,onChoose:c,onCustomize:d}){return n.jsxs("div",{style:{padding:"var(--spacing-sm, 10px) var(--spacing-md, 14px)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,color:"var(--text-primary)",fontSize:"var(--text-sm, 14px)",minWidth:0},children:[n.jsx("span",{style:{fontWeight:700,color:"var(--text-muted)"},children:String(e).padStart(2,"0")}),o?n.jsxs("a",{href:o,target:"_blank",rel:"noopener noreferrer","aria-label":`Open ${t} in new tab`,title:"Open in new tab",onClick:u=>u.stopPropagation(),style:{display:"inline-flex",alignItems:"center",gap:4,minWidth:0,color:"var(--text-primary)",textDecoration:"none"},children:[n.jsx("span",{style:{textTransform:"capitalize",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}),n.jsx("span",{style:{display:"inline-flex",alignItems:"center",color:"var(--text-muted)",lineHeight:1,flexShrink:0},children:n.jsx(Qg,{})})]}):n.jsx("span",{style:{textTransform:"capitalize",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--spacing-xs, 8px)",flexShrink:0},children:[s&&n.jsx(ti,{theme:r,onToggle:l}),n.jsx("button",{type:"button",onClick:d,disabled:a,style:{padding:"6px 14px",background:"var(--bg-card, #1a1a1a)",color:"var(--text-primary)",border:"1px solid var(--border-default)",borderRadius:6,fontSize:"var(--text-xs, 12px)",fontWeight:500,cursor:a?"wait":"pointer",opacity:a?.6:1},children:"Customize"}),n.jsx("button",{type:"button",onClick:c,disabled:a,style:{padding:"6px 14px",background:"var(--accent-active, #7c3aed)",color:"var(--text-on-accent, #fff)",border:"1px solid transparent",borderRadius:6,fontSize:"var(--text-xs, 12px)",fontWeight:600,cursor:a?"wait":"pointer",opacity:a?.6:1,boxShadow:a?"none":"0 0 0 3px color-mix(in srgb, var(--accent-active, #7c3aed) 30%, transparent), 0 2px 6px color-mix(in srgb, var(--accent-active, #7c3aed) 40%, transparent)"},children:"Select"})]})]})}function eb({html:e,url:t,title:r,viewport:s,theme:a,darkVars:o}){const l=i.useRef(null),[c,d]=i.useState(0),[u,f]=i.useState(0),p=Ug[s];i.useEffect(()=>{const N=l.current;if(!N)return;const C=()=>{const R=N.clientWidth,E=N.clientHeight;R>0&&d(R),E>0&&f(E)};if(C(),typeof ResizeObserver>"u")return;const S=new ResizeObserver(C);return S.observe(N),()=>S.disconnect()},[]);const{scale:m,offsetX:h,offsetY:b}=Xg(c,u,p.w,p.h),g=e&&a==="dark"&&o?_g(e,o):e,[y,w]=i.useState(!1),[v,x]=i.useState(!1);i.useEffect(()=>{w(!1),x(!1);const N=window.setTimeout(()=>x(!0),700);return()=>window.clearTimeout(N)},[g,t,a]);const j=e===null||!y||!v,k=()=>window.open(t,"_blank","noopener,noreferrer");return n.jsxs("div",{ref:l,onClick:k,style:{position:"relative",width:"100%",aspectRatio:`${Kg} / ${Gg}`,overflow:"hidden",cursor:"pointer",backgroundColor:Yg,backgroundImage:qg,backgroundSize:Jg},children:[e!==null&&n.jsx("iframe",{src:g?void 0:t,srcDoc:g??void 0,title:r,sandbox:"",onLoad:()=>w(!0),style:{width:p.w,height:p.h,border:"none",background:"white",transform:m>0?`scale(${m})`:"scale(0)",transformOrigin:"top left",pointerEvents:"none",position:"absolute",top:b,left:h,visibility:y?"visible":"hidden"}},a),j&&n.jsx(tb,{})]})}function tb(){return n.jsxs("div",{"aria-label":"Loading mockup",style:{position:"absolute",inset:0,padding:"10%",display:"flex",flexDirection:"column",gap:"5%"},children:[n.jsx("style",{children:`
50
- @keyframes mockup-skeleton-shimmer {
51
- 0% { background-position: -200% 0; }
52
- 100% { background-position: 200% 0; }
53
- }
54
- `}),n.jsx(pt,{widthPct:45,heightPx:14}),n.jsx(pt,{widthPct:70,heightPx:10}),n.jsx("div",{style:{height:"6%"}}),n.jsx(pt,{widthPct:100,heightPx:32}),n.jsxs("div",{style:{display:"flex",gap:"4%"},children:[n.jsx(pt,{widthPct:48,heightPx:48}),n.jsx(pt,{widthPct:48,heightPx:48})]}),n.jsx(pt,{widthPct:88,heightPx:10}),n.jsx(pt,{widthPct:60,heightPx:10})]})}function pt({widthPct:e,heightPx:t}){return n.jsx("div",{style:{width:`${e}%`,height:t,borderRadius:4,background:"linear-gradient(90deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0.12) 45%, rgba(255,255,255,0.04) 90%)",backgroundSize:"200% 100%",animation:"mockup-skeleton-shimmer 1.6s linear infinite"}})}const nb=`
55
- .mockup-feedback-slider {
56
- -webkit-appearance: none;
57
- appearance: none;
58
- background: transparent;
59
- height: 18px;
60
- padding: 0;
61
- margin: 0;
62
- cursor: pointer;
63
- }
64
- .mockup-feedback-slider:focus { outline: none; }
65
- .mockup-feedback-slider::-webkit-slider-runnable-track {
66
- height: 4px;
67
- background: #4a4a4a;
68
- border-radius: 2px;
69
- }
70
- .mockup-feedback-slider::-moz-range-track {
71
- height: 4px;
72
- background: #4a4a4a;
73
- border-radius: 2px;
74
- border: none;
75
- }
76
- .mockup-feedback-slider::-moz-range-progress {
77
- background: #4a4a4a;
78
- height: 4px;
79
- border-radius: 2px;
80
- }
81
- .mockup-feedback-slider::-webkit-slider-thumb {
82
- -webkit-appearance: none;
83
- appearance: none;
84
- width: 14px;
85
- height: 14px;
86
- border-radius: 50%;
87
- background: #5a5a5a;
88
- border: none;
89
- margin-top: -5px;
90
- cursor: pointer;
91
- transition: background 120ms ease;
92
- }
93
- .mockup-feedback-slider::-moz-range-thumb {
94
- width: 14px;
95
- height: 14px;
96
- border-radius: 50%;
97
- background: #5a5a5a;
98
- border: none;
99
- cursor: pointer;
100
- transition: background 120ms ease;
101
- }
102
- .mockup-feedback-slider[data-rated="true"]::-webkit-slider-runnable-track {
103
- /* Two stacked layers: a grey overlay that masks the right portion of
104
- * the track from progress% onward, and a full-width red-amber-keylime
105
- * rainbow underneath. The visible filled portion is the slice of the
106
- * rainbow up to the thumb position. */
107
- background:
108
- linear-gradient(
109
- to right,
110
- transparent 0%,
111
- transparent var(--mockup-feedback-progress, 0%),
112
- #4a4a4a var(--mockup-feedback-progress, 0%),
113
- #4a4a4a 100%
114
- ),
115
- linear-gradient(
116
- to right,
117
- rgb(239, 68, 68) 0%,
118
- rgb(251, 191, 36) 50%,
119
- rgb(215, 255, 99) 100%
120
- );
121
- }
122
- .mockup-feedback-slider[data-rated="true"]::-moz-range-track {
123
- background: linear-gradient(
124
- to right,
125
- rgb(239, 68, 68) 0%,
126
- rgb(251, 191, 36) 50%,
127
- rgb(215, 255, 99) 100%
128
- );
129
- }
130
- .mockup-feedback-slider[data-rated="true"]::-moz-range-progress {
131
- /* Firefox draws ::-moz-range-progress on top of ::-moz-range-track,
132
- * so the progress layer would otherwise hide the rainbow below it.
133
- * Leave it transparent so the rainbow shows through up to the value. */
134
- background: transparent;
135
- }
136
- .mockup-feedback-slider[data-rated="true"]::-webkit-slider-thumb {
137
- background: var(--mockup-feedback-color, var(--accent-active, #D7FF63));
138
- }
139
- .mockup-feedback-slider[data-rated="true"]::-moz-range-thumb {
140
- background: var(--mockup-feedback-color, var(--accent-active, #D7FF63));
141
- }
142
- `,rb=`
143
- .mockup-feedback-comment {
144
- width: 100%;
145
- padding: var(--spacing-sm, 8px) var(--spacing-sm, 10px);
146
- background: var(--bg-card, #1a1a1a);
147
- color: var(--text-primary);
148
- border: 1px solid var(--border-default);
149
- border-radius: 6px;
150
- font-size: var(--text-xs, 12px);
151
- line-height: 1.4;
152
- resize: vertical;
153
- box-sizing: border-box;
154
- min-height: 56px;
155
- outline: none;
156
- }
157
- .mockup-feedback-comment:focus,
158
- .mockup-feedback-comment:focus-visible {
159
- border-color: var(--text-primary, #ffffff);
160
- outline: none;
161
- box-shadow: 0 0 0 1px var(--text-primary, #ffffff);
162
- }
163
- `;function sb({comment:e,onCommentChange:t}){return n.jsxs(n.Fragment,{children:[n.jsx("style",{children:rb}),n.jsx("textarea",{value:e,onChange:r=>t(r.target.value),placeholder:"What do you like or would like to change? (optional)",rows:3,className:"mockup-feedback-comment"})]})}const ni=[239,68,68],yr=[251,191,36],ri=[215,255,99];function ab(e){const t=Math.max(1,Math.min(100,e));let r,s,a;t<=50?(r=ni,s=yr,a=(t-1)/49):(r=yr,s=ri,a=(t-50)/50);const o=Math.round(r[0]+(s[0]-r[0])*a),l=Math.round(r[1]+(s[1]-r[1])*a),c=Math.round(r[2]+(s[2]-r[2])*a);return`rgb(${o}, ${l}, ${c})`}`${ni.join(", ")}${yr.join(", ")}${ri.join(", ")}`;function ob(){return n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("path",{d:"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3z"}),n.jsx("path",{d:"M17 2h2.5a2.5 2.5 0 0 1 2.5 2.5v6A2.5 2.5 0 0 1 19.5 13H17"})]})}function ib(){return n.jsxs("svg",{width:"16",height:"16",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 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3z"}),n.jsx("path",{d:"M7 22H4.5a2.5 2.5 0 0 1-2.5-2.5v-6A2.5 2.5 0 0 1 4.5 11H7"})]})}function lb({rating:e,onRatingChange:t}){const r=e!=null,s=r&&e<=33,a=r&&e>=67;return n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--spacing-sm, 10px)"},children:[n.jsx("span",{"aria-hidden":"true",style:{color:s?"var(--text-primary)":"var(--text-muted)",display:"inline-flex",alignItems:"center"},children:n.jsx(ob,{})}),n.jsx("input",{type:"range",min:1,max:100,step:1,value:e??50,onPointerDown:()=>{r||t(50)},onChange:o=>t(Number(o.target.value)),"aria-label":"Rate this mockup from 1 to 100",className:"mockup-feedback-slider","data-rated":r?"true":"false",style:{flex:1,"--mockup-feedback-progress":`${e??0}%`,"--mockup-feedback-color":r?ab(e):"var(--accent-active, #D7FF63)"}}),n.jsx("span",{"aria-hidden":"true",style:{color:a?"var(--text-primary)":"var(--text-muted)",display:"inline-flex",alignItems:"center"},children:n.jsx(ib,{})})]})}const cb={rating:null,comment:""};function db({value:e,onChange:t}){return n.jsxs("div",{"data-mockup-feedback":!0,style:{padding:"var(--spacing-sm, 10px) var(--spacing-md, 14px)",borderTop:"1px solid var(--border-default)",display:"flex",flexDirection:"column",gap:"var(--spacing-sm, 10px)",background:"var(--bg-surface)"},children:[n.jsx("style",{children:nb}),n.jsx(lb,{rating:e.rating,onRatingChange:r=>t({...e,rating:r})}),n.jsx(sb,{comment:e.comment,onCommentChange:r=>t({...e,comment:r})})]})}function ub({mockup:e,displayNumber:t,onChoose:r,onCustomize:s,busy:a=!1,darkVars:o=null,feedback:l,onFeedbackChange:c}){const[d,u]=i.useState(null),[f,p]=i.useState(aa),[m,h]=i.useState("light");i.useEffect(()=>{let g=!1;return(async()=>{try{const y=await fetch(e.url);if(!y.ok)return;const w=await y.text();if(g)return;u(w),p(ei(w)??aa)}catch{}})(),()=>{g=!0}},[e.url]);const b=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(Zg,{displayNumber:t,formattedName:b,theme:m,showThemeToggle:!!o,busy:a,openInNewTabUrl:e.url,onToggleTheme:()=>h(g=>g==="light"?"dark":"light"),onChoose:()=>r==null?void 0:r(e),onCustomize:()=>s==null?void 0:s(e)}),n.jsx(eb,{html:d,url:e.url,title:e.name,viewport:f,theme:m,darkVars:o}),c&&n.jsx(db,{value:l??cb,onChange:c})]})}function mt({widthPct:e,heightPx:t,variant:r="surface"}){const s=r==="overlay"?"linear-gradient(90deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0.12) 45%, rgba(255,255,255,0.04) 90%)":"linear-gradient(90deg, var(--bg-surface) 0%, var(--border-default) 45%, var(--bg-surface) 90%)";return n.jsx("div",{style:{width:`${e}%`,height:t,borderRadius:4,background:s,backgroundSize:"200% 100%",animation:"mockup-skeleton-shimmer 1.6s linear infinite",opacity:r==="surface"?.85:1}})}function fb({displayNumber:e}){return n.jsxs("div",{"data-mockup-placeholder":!0,"aria-label":"The AI is designing this mockup",style:{position:"relative",display:"flex",flexDirection:"column",border:"1px solid var(--border-default)",borderRadius:12,overflow:"hidden",background:"var(--bg-surface)"},children:[n.jsx("style",{children:`
164
- @keyframes mockup-skeleton-shimmer {
165
- 0% { background-position: -200% 0; }
166
- 100% { background-position: 200% 0; }
167
- }
168
- `}),n.jsxs("div",{style:{position:"relative",width:"100%",aspectRatio:"1 / 1",overflow:"hidden",background:"var(--bg-elevated, #141414)",padding:"10%",display:"flex",flexDirection:"column",gap:"5%"},children:[n.jsx(mt,{widthPct:45,heightPx:14}),n.jsx(mt,{widthPct:70,heightPx:10}),n.jsx("div",{style:{height:"6%"}}),n.jsx(mt,{widthPct:100,heightPx:32}),n.jsxs("div",{style:{display:"flex",gap:"4%"},children:[n.jsx(mt,{widthPct:48,heightPx:48}),n.jsx(mt,{widthPct:48,heightPx:48})]}),n.jsx(mt,{widthPct:88,heightPx:10}),n.jsx(mt,{widthPct:60,heightPx:10})]}),n.jsx("div",{style:{padding:"var(--spacing-sm, 8px) var(--spacing-md, 12px)",display:"flex",alignItems:"center",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.jsx("span",{style:{fontWeight:700,color:"var(--text-muted)"},children:String(e).padStart(2,"0")}),n.jsx("span",{style:{color:"var(--text-secondary)",fontStyle:"italic"},"data-testid":"mockup-placeholder-label",children:"The AI is designing this mockup…"})]})})]})}function pb({slots:e,darkVarsBySystem:t,busyFilename:r,feedbackByFilename:s,onFeedbackChange:a,onChoose:o,onCustomize:l}){return n.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",columnGap:"var(--spacing-lg, 16px)",rowGap:"var(--spacing-xl, 28px)"},children:e.map(c=>c.mockup?n.jsx(ub,{mockup:c.mockup,displayNumber:c.number,onChoose:o,onCustomize:l,busy:r===c.mockup.filename,darkVars:t[ts(c.mockup.filename)]??null,feedback:s==null?void 0:s[c.mockup.filename],onFeedbackChange:a?d=>a(c.mockup.filename,d):void 0},`mockup-${c.mockup.filename}`):n.jsx(fb,{displayNumber:c.number},`placeholder-${c.number}`))})}function mb(){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."})]})}function hb(){return n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("path",{d:"M9 18h6"}),n.jsx("path",{d:"M10 22h4"}),n.jsx("path",{d:"M12 2a7 7 0 0 0-4 12.74V17a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1v-2.26A7 7 0 0 0 12 2z"})]})}function xb(){return n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]})}function gb({onDismiss:e}){return n.jsxs("div",{role:"note","data-mockup-info-banner":!0,style:{display:"flex",alignItems:"flex-start",gap:"var(--spacing-md, 14px)",padding:"var(--spacing-md, 14px) var(--spacing-md, 16px)",border:"1px solid var(--accent-active, #D7FF63)",borderRadius:12,background:"rgba(215, 255, 99, 0.04)"},children:[n.jsx("span",{"aria-hidden":"true",style:{color:"var(--accent-active, #D7FF63)",display:"inline-flex",alignItems:"center",flexShrink:0,paddingTop:1},children:n.jsx(hb,{})}),n.jsxs("p",{style:{flex:1,margin:0,color:"var(--text-primary)",fontSize:"var(--text-sm, 14px)",lineHeight:1.5},children:[n.jsx("strong",{style:{fontWeight:700},children:"Not sure which to pick?"})," ","Rate these designs and jot a quick note. We'll refine them into a fresh round — no need to choose yet."]}),n.jsx("button",{type:"button",onClick:e,"aria-label":"Dismiss tip",title:"Dismiss",style:{flexShrink:0,padding:4,background:"transparent",color:"var(--text-muted)",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center"},children:n.jsx(xb,{})})]})}function bb(){return n.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("path",{d:"M21 12a9 9 0 1 1-3.36-7"}),n.jsx("polyline",{points:"21 4 21 10 15 10"})]})}function vb({feedbackCount:e,busy:t,onIterate:r}){const s=e===0?"Add a rating or note above, then iterate.":e===1?"1 card has feedback — iterate to refresh the round.":`${e} cards have feedback — iterate to refresh the round.`;return n.jsxs("div",{style:{marginTop:"var(--spacing-md, 12px)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"var(--spacing-md, 16px)",padding:"var(--spacing-md, 16px) var(--spacing-lg, 20px)",border:"1px solid var(--border-default)",borderRadius:12,background:"var(--bg-card, #1a1a1a)"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--spacing-md, 14px)",minWidth:0},children:[n.jsx("span",{"aria-hidden":"true",style:{color:"var(--accent-active, #D7FF63)",display:"inline-flex",alignItems:"center",flexShrink:0},children:n.jsx(bb,{})}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0},children:[n.jsx("span",{style:{color:"var(--text-primary)",fontSize:"var(--text-sm, 14px)",fontWeight:600,lineHeight:1.3},children:"Ready for the next round?"}),n.jsx("span",{style:{color:"var(--text-muted)",fontSize:"var(--text-xs, 12px)",lineHeight:1.4,marginTop:2},children:s})]})]}),n.jsx("button",{type:"button",onClick:r,disabled:t,"data-mockup-iterate":!0,style:{flexShrink:0,padding:"10px 22px",background:"var(--accent-active, #D7FF63)",color:"var(--text-on-accent, #0F0F0F)",border:"1px solid var(--accent-active, #D7FF63)",borderRadius:8,fontSize:"var(--text-sm, 14px)",fontWeight:600,cursor:t?"wait":"pointer",opacity:t?.6:1},children:t?"Sending…":"Iterate"})]})}function yb(){return n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:n.jsx("polyline",{points:"15 18 9 12 15 6"})})}function wb(){return n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:n.jsx("polyline",{points:"9 18 15 12 9 6"})})}function jb({archivedRoundsNewestFirst:e,selected:t,onSelect:r}){if(e.length===0)return null;const a=[...[...e].reverse(),"current"],o=a.length,l=a.indexOf(t),c=l===-1?o-1:l,d=t==="current",u=c>0,f=c<o-1,p=d?`Round ${o} of ${o} · Current`:`Round ${c+1} of ${o} · Archived`;return n.jsxs("div",{"data-mockup-round-pager":!0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"var(--spacing-sm, 10px)",padding:"var(--spacing-xs, 6px) var(--spacing-md, 14px)",border:"1px solid var(--border-default)",borderRadius:10,background:"var(--bg-card, #1a1a1a)"},children:[n.jsx(oa,{ariaLabel:"Previous round",disabled:!u,onClick:()=>u&&r(a[c-1]),icon:n.jsx(yb,{})}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--spacing-md, 12px)",fontSize:"var(--text-xs, 12px)",color:"var(--text-secondary)"},children:[n.jsx("span",{style:{fontWeight:500,color:"var(--text-primary)"},children:p}),!d&&n.jsx("button",{type:"button",onClick:()=>r("current"),style:{padding:"4px 10px",background:"transparent",color:"var(--accent-active, #D7FF63)",border:"1px solid var(--accent-active, #D7FF63)",borderRadius:6,fontSize:"var(--text-xs, 11px)",fontWeight:500,cursor:"pointer"},children:"Return to current"})]}),n.jsx(oa,{ariaLabel:"Next round",disabled:!f,onClick:()=>f&&r(a[c+1]),icon:n.jsx(wb,{})})]})}function oa({ariaLabel:e,disabled:t,onClick:r,icon:s}){return n.jsx("button",{type:"button",onClick:r,disabled:t,"aria-label":e,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,background:"transparent",color:t?"var(--text-dim, #666)":"var(--text-primary)",border:"1px solid var(--border-default)",borderRadius:6,cursor:t?"default":"pointer",opacity:t?.5:1,padding:0},children:s})}function kb({mockup:e,busy:t,onCancel:r,onConfirm:s}){i.useEffect(()=>{const o=l=>{l.key==="Escape"&&!t&&r()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[t,r]);const a=e.name.replace(/^\d{1,2}-/,"").replace(/-/g," ");return n.jsx("div",{role:"presentation",onClick:r,style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.6)",backdropFilter:"blur(2px)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:200,padding:24},children:n.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Ready to start building?",onClick:o=>o.stopPropagation(),style:{background:"var(--bg-elevated, #141414)",border:"1px solid var(--border-default)",borderRadius:12,padding:24,width:"min(440px, 100%)",display:"flex",flexDirection:"column",gap:16,fontFamily:"'IBM Plex Mono', monospace",boxShadow:"0 20px 60px rgba(0,0,0,0.5)"},children:[n.jsx("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:8,overflow:"hidden",aspectRatio:"16 / 9",background:"#1a1a1a",position:"relative"},children:n.jsx("iframe",{src:e.url,title:`${a} thumbnail`,sandbox:"",style:{width:1440,height:900,border:"none",background:"white",transform:"scale(0.305)",transformOrigin:"top left",pointerEvents:"none",position:"absolute",top:0,left:0}})}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[n.jsx("h2",{style:{margin:0,color:"var(--text-primary)",fontSize:16,fontWeight:600},children:"Ready to start building?"}),n.jsxs("p",{style:{margin:0,color:"var(--text-secondary)",fontSize:13,textTransform:"capitalize"},children:["Using ",n.jsx("strong",{style:{color:"var(--text-primary)"},children:a})]})]}),n.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[n.jsx("button",{type:"button",onClick:r,disabled:t,style:{padding:"8px 16px",background:"transparent",color:"var(--text-secondary)",border:"1px solid var(--border-default)",borderRadius:6,fontSize:13,fontWeight:500,cursor:t?"wait":"pointer",opacity:t?.5:1,fontFamily:"inherit"},children:"Cancel"}),n.jsx("button",{type:"button",onClick:s,disabled:t,style:{padding:"8px 18px",background:"var(--accent-active, #D7FF63)",color:"var(--text-on-accent, #0F0F0F)",border:"1px solid var(--accent-active, #D7FF63)",borderRadius:6,fontSize:13,fontWeight:600,cursor:t?"wait":"pointer",opacity:t?.7:1,fontFamily:"inherit"},children:t?"Starting…":"Start building"})]})]})})}function Nb({onDesignConfirmed:e}={}){const[t,r]=i.useState(null),[s,a]=i.useState(null),[o,l]=i.useState(null),[c,d]=i.useState(null),[u,f]=i.useState(null),[p,m]=i.useState(null),[h,b]=i.useState({}),[g,y]=i.useState({}),[w,v]=i.useState(!1),[x,j]=i.useState(()=>typeof window>"u"?!1:window.sessionStorage.getItem("mockup-grid-tip-dismissed")==="1"),[k,N]=i.useState("current"),C=Eg(),S=i.useRef(null),R=Sg(t),E=i.useRef(!0),A=i.useCallback(async()=>{try{const[F,L]=await Promise.all([fetch("/api/editor-mockups"),fetch("/api/editor-mockups-target")]),M=await F.json(),Q=await L.json();E.current&&(r(q=>dg(q,M)?q:M),a(q=>q===Q.count?q:Q.count))}catch(F){E.current&&l(F instanceof Error?F.message:String(F))}},[]);i.useEffect(()=>{E.current=!0,A();const F=window.setInterval(A,4e3);return()=>{E.current=!1,window.clearInterval(F)}},[A]),i.useEffect(()=>{let F=!1;return(async()=>{try{const L=await fetch("/api/editor-mockups-feedback");if(!L.ok)return;const M=await L.json();if(F||!M||typeof M!="object"||Array.isArray(M))return;const Q={};for(const[q,W]of Object.entries(M)){if(!W||typeof W!="object")continue;const z=W;z.rating!=null&&typeof z.rating!="number"||z.comment!=null&&typeof z.comment!="string"||(Q[q]={rating:typeof z.rating=="number"?z.rating:null,comment:typeof z.comment=="string"?z.comment:""})}y(Q)}catch{}})(),()=>{F=!0}},[]);const D=i.useCallback((F,L)=>{y(M=>{const Q={...M,[F]:L};return S.current!=null&&window.clearTimeout(S.current),S.current=window.setTimeout(()=>{fetch("/api/editor-mockups-feedback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)}).catch(()=>{})},400),Q})},[]);i.useEffect(()=>()=>{S.current!=null&&window.clearTimeout(S.current)},[]);const B=i.useCallback(()=>{if(!t)return;v(!0),N("current");const F=hg({feedbackByFilename:g,mockupFilenames:t.map(L=>L.filename)});pg(F),y({}),fetch("/api/editor-mockups-feedback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})}).catch(()=>{}),window.setTimeout(()=>{E.current&&v(!1)},1e3)},[g,t]),T=i.useCallback(F=>{m(F)},[]),O=i.useCallback(async()=>{if(!p)return;const F=p;d(F.filename);try{const L=await fetch("/api/editor-design-select",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:F.filename})});if(!L.ok){const M=await L.text().catch(()=>`${L.status}`);throw new Error(M||`select failed: ${L.status}`)}E.current&&(m(null),e==null||e())}catch(L){l(L instanceof Error?L.message:String(L))}finally{E.current&&d(null)}},[p,e]),Y=i.useCallback(F=>{const L=ts(F.filename);f({mockup:F,systemName:L})},[]),P=i.useCallback(F=>{u&&b(L=>({...L,[u.mockup.filename]:F})),f(null)},[u]),$=i.useCallback(async F=>{if(u){d(u.mockup.filename);try{const L=await fetch("/api/editor-design-select",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:u.mockup.filename,overrides:{vars:F.vars,primaryFont:F.primaryFont,secondaryFont:F.secondaryFont}})});if(!L.ok){const M=await L.text().catch(()=>`${L.status}`);throw new Error(M||`select failed: ${L.status}`)}b(M=>({...M,[u.mockup.filename]:F})),f(null),e==null||e()}catch(L){l(L instanceof Error?L.message:String(L))}finally{E.current&&d(null)}}},[u,e]);if(u)return n.jsx(Vg,{mockup:u.mockup,systemName:u.systemName,initial:h[u.mockup.filename]??cg,onBack:P,onSave:$,saving:c===u.mockup.filename});if(!t)return n.jsx("div",{style:{padding:"var(--spacing-lg, 16px)"},children:n.jsx("div",{style:{color:"var(--text-secondary)"},children:"Loading design mockups…"})});const V=t.reduce((F,L)=>{const M=/^(\d{1,2})-/.exec(L.filename);return M?Math.max(F,parseInt(M[1],10)):F},0),_=Math.max(s??0,V);if(_===0)return n.jsx(mb,{});const X=Array.from({length:_},(F,L)=>{const M=L+1,Q=String(M).padStart(2,"0"),q=t.find(W=>W.filename.startsWith(`${Q}-`))??null;return{number:M,mockup:q}});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:[!x&&n.jsx(gb,{onDismiss:()=>{j(!0),typeof window<"u"&&window.sessionStorage.setItem("mockup-grid-tip-dismissed","1")}}),n.jsx(jb,{archivedRoundsNewestFirst:C.map(F=>F.round),selected:k,onSelect:N}),o&&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:o}),k==="current"?n.jsxs(n.Fragment,{children:[n.jsx(pb,{slots:X,darkVarsBySystem:R,busyFilename:c,feedbackByFilename:g,onFeedbackChange:D,onChoose:T,onCustomize:Y}),t.length>0&&n.jsx(vb,{feedbackCount:Object.values(g).filter(F=>typeof F.rating=="number"||F.comment.trim().length>0).length,busy:w,onIterate:B})]}):(()=>{const F=C.find(L=>L.round===k);return F?n.jsx(Rg,{round:F}):n.jsx("div",{style:{padding:"var(--spacing-md, 14px)",color:"var(--text-secondary)",fontSize:"var(--text-sm, 14px)"},children:"Loading archived round…"})})(),p&&n.jsx(kb,{mockup:p,busy:c===p.filename,onCancel:()=>m(null),onConfirm:O})]})}function wr(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 si(e){return Rr(e)?e.componentName??wr(e.name).pageName:wr(e.name).pageName}function rs(e){return wr(e.name).stateName}function Cb({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 ia({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 Sb({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 Eb({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 Rb(){return n.jsx("button",{onClick:()=>Pa(),className:"p-1.5 rounded text-gray-500 hover:text-gray-300 transition-colors cursor-pointer",title:"Refresh preview","aria-label":"Refresh preview",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("polyline",{points:"23 4 23 10 17 10"}),n.jsx("polyline",{points:"1 20 1 14 7 14"}),n.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})})}function ai(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 Tb(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 oi(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 Pb({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 Db({scenario:e,active:t,onClick:r}){const s=e.screenshotPaths[0],a=rs(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:Ge(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 Ab({group:e,currentSlug:t,onSelect:r}){const s=e.scenarios[0]?si(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(Db,{scenario:a,active:a.slug===t,onClick:()=>r(a.slug)},a.slug))})]})}function la({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 Fb({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()},[]),oi(u,s,a);const p=i.useMemo(()=>e.flatMap(w=>w.scenarios),[e]),m=i.useMemo(()=>Tb(p,c),[p,c]),h=i.useMemo(()=>m.filter(Et),[m]),b=i.useMemo(()=>m.filter(Rr),[m]),g=o==="pages"?h:b,y=i.useMemo(()=>ai(g),[g]);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(la,{label:"PAGES",active:o==="pages",count:h.length,onClick:()=>l("pages")}),n.jsx(la,{label:"COMPONENTS",active:o==="components",count:b.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:y.length===0?n.jsx(Pb,{tab:o,hasQuery:c.trim().length>0}):y.map(w=>n.jsx(Ab,{group:w,currentSlug:t,onSelect:v=>{r(v),s()}},w.route))})]})}function Lb(){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 Mb(){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 ii({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 Ib({currentScenario:e,isOpen:t,onClick:r,buttonRef:s}){const a=e?Rr(e):!1,o=(e==null?void 0:e.screenshotPaths[0])??null,l=e?a?e.componentName??e.name:si(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:Ge(o),alt:"",className:"w-full h-full object-cover"}):a?n.jsx(Mb,{}):n.jsx(Lb,{})}),n.jsx(ii,{})]}),n.jsx("span",{className:"truncate",children:l})]})}function $b(e,t){const r=e.url??"Uncategorized",s=t.find(a=>a.route===r);return(s==null?void 0:s.scenarios)??[e]}function Bb({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:Ge(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:rs(e)})]})}function Ob({currentScenario:e,scenarioGroups:t,onSelect:r,onCreateNew:s,onClose:a,triggerRef:o}){const l=i.useRef(null);oi(l,a,o);const c=i.useMemo(()=>$b(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(Bb,{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 zb({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(ii,{className:"opacity-70 shrink-0"})]})}function _b({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(Gm,{name:e.name})})}function Hb({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:b,onShowScenarioPreview:g,onCreateStateRequest:y,isNarrow:w=!1}){const[v,x]=i.useState(!1),[j,k]=i.useState(!1),N=i.useRef(null),C=i.useRef(null),S=d&&f?Math.round(f):s,R=d&&p?Math.round(p):a,E=h?rs(h):"No state",A=!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:!w&&n.jsx(Cb,{isCollapsed:l,onToggle:c})}),n.jsxs("div",{className:`flex items-center gap-2 justify-self-center ${w?"min-w-0 overflow-x-auto":""}`,children:[n.jsxs("div",{className:"relative flex items-center bg-[#3a3a3a] rounded h-7 px-1 gap-1",children:[n.jsx(Ib,{currentScenario:h,isOpen:v,onClick:()=>{x(D=>!D),k(!1)},buttonRef:N}),v&&n.jsx(Fb,{scenarioGroups:b,currentSlug:(h==null?void 0:h.slug)??null,onSelect:g,onClose:()=>x(!1),triggerRef:N}),n.jsx("span",{className:"w-px h-5 bg-[#555] mx-1 shrink-0","aria-hidden":"true"}),e.map(D=>n.jsx(_b,{viewport:D,isActive:!d&&t===D.name,onSelect:()=>{d&&u(),r(D.name)}},D.name)),n.jsx(Sb,{isFilled:d,onToggle:u}),n.jsx(ia,{label:"H",value:R,disabled:d,onCommit:D=>m(s,D)}),n.jsx(ia,{label:"W",value:S,disabled:d,onCommit:D=>m(D,a)}),n.jsx(Rb,{}),n.jsx(Eb,{previewUrl:o})]}),n.jsx("div",{className:"flex items-center gap-2 shrink-0",children:n.jsxs("div",{className:"relative",children:[n.jsx(zb,{label:E,disabled:A,isOpen:j,onClick:()=>{k(D=>!D),x(!1)},buttonRef:C}),j&&h&&n.jsx(Ob,{currentScenario:h,scenarioGroups:b,onSelect:g,onCreateNew:y,onClose:()=>k(!1),triggerRef:C})]})})]}),n.jsx("div",{"aria-hidden":"true"})]})}function Wb(){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 Vb({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})}const ca={prompt:null,title:null};function li(){const[e,t]=i.useState(ca),[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(ca)}finally{a||s(!1)}})(),()=>{a=!0}},[]),{...e,loading:r}}function Ub(){const{prompt:e,title:t,loading:r}=li();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?n.jsxs(n.Fragment,{children:[t?n.jsx(Vb,{title:t}):null,n.jsx(ht,{children:e})]}):n.jsx(Wb,{})})})}function Kb({message:e}){return n.jsx("span",{style:{color:"var(--text-dim)"},children:e})}function Gb({hasDevServerConfigured:e}){const t=e?"Starting your app…":"Your app will display here once set up";return n.jsx("div",{"data-testid":"preview-waiting-placeholder",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none",color:"var(--text-dim)"},children:n.jsx("span",{children:t})})}function Yb(e,t,r){const s=[e];return t&&s.push(`reload:${t}`),r&&s.push(`command:${r}`),s.join("::")}function qb({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 Jb=i.forwardRef(function({currentHeight:t,currentWidth:r,isFilled:s,previewUrl:a,scale:o,reloadNonce:l,commandNonce:c,onLoad:d,onError:u},f){if(vt())return n.jsx(qb,{currentWidth:r,currentHeight:t,isFilled:s,scale:o});const p=Yb(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 Xb(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 Qb(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 Zb(e,t){const[r,s]=i.useState(e),a=i.useRef(null);return i.useEffect(()=>{if(e!==!1){a.current!==null&&(window.clearTimeout(a.current),a.current=null),s(e);return}if(a.current===null)return a.current=window.setTimeout(()=>{a.current=null,s(!1)},t),()=>{a.current!==null&&(window.clearTimeout(a.current),a.current=null)}},[e,t]),r}function ev(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?(a.current=!1,l(f=>f+1)):s.current==null&&(a.current?t&&qs(e,c.current):l(f=>f+1)),s.current=e)},[e,t]);const d=i.useCallback(f=>{a.current=!0,f&&(c.current=f),t&&e!=null&&qs(e,f??c.current)},[e,t]),u=i.useCallback(f=>{t&&Ex(f)},[t]);return{reloadNonce:o,handleIframeLoad:d,handleIframeError:u}}const tv=1500,nv=2e3,rv=3e3,sv=2;function av(){return typeof window>"u"?!1:window.location.pathname.startsWith("/scenario/")?!0:vt()}function ov(e,t=!1){const r=av(),[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),b=i.useRef(!1),g=i.useRef(e),y=i.useRef(t);i.useEffect(()=>{g.current=e},[e]),i.useEffect(()=>{y.current=t},[t]);const w=i.useCallback(()=>{m.current!=null&&(clearTimeout(m.current),m.current=null)},[]),v=i.useCallback(async()=>{if(b.current||y.current)return;const N=g.current;if(!N)return;h.current&&h.current.abort();const C=new AbortController;h.current=C;const S=setTimeout(()=>C.abort(),rv);let R=!1;try{await fetch(N,{mode:"no-cors",cache:"no-store",signal:C.signal}),R=!0}catch{R=!1}finally{clearTimeout(S)}if(!b.current){if(l(Date.now()),R){if(d(0),p.current!==!0){const E=p.current===!1;p.current=!0,a(!0),E&&f(A=>A+1)}}else d(E=>{const A=E+1;return A>=sv&&p.current!==!1&&(p.current=!1,a(!1)),A});x()}},[]),x=i.useCallback(()=>{if(b.current)return;w();const N=p.current===!0?nv:tv;m.current=setTimeout(()=>{m.current=null,v()},N)},[w,v]),j=i.useCallback(()=>{w(),v()},[w,v]);i.useEffect(()=>{if(!r)return b.current=!1,v(),()=>{b.current=!0,w(),h.current&&(h.current.abort(),h.current=null)}},[v,w,r]),i.useEffect(()=>{r||v()},[e,v,r]);const k=i.useRef(t);return i.useEffect(()=>{if(r)return;const N=k.current;k.current=t,N&&!t&&v()},[t,v,r]),{healthy:s,lastProbeAt:o,failedProbeCount:c,reloadNonce:u,invalidate:j}}const da={loaded:!1,stalledRequests:0,fastRequests:0,longestStallMs:0,tailReadFailedReason:null};function iv(e){const{active:t,trigger:r}=e,[s,a]=i.useState(da),o=i.useRef(null),l=i.useCallback(()=>{var d;(d=o.current)==null||d.abort();const c=new AbortController;o.current=c,fetch("/api/dev-server-recent-requests",{signal:c.signal}).then(u=>{if(!u.ok)throw new Error(`HTTP ${u.status}`);return u.json()}).then(u=>{if(c.signal.aborted)return;const p=(u.stalls??[]).reduce((m,h)=>Math.max(m,h.durationMs??0),0);a({loaded:!0,stalledRequests:u.stalledRequests??0,fastRequests:u.fastRequests??0,longestStallMs:p,tailReadFailedReason:u.tailReadFailedReason??null})}).catch(u=>{c.signal.aborted||a({loaded:!0,stalledRequests:0,fastRequests:0,longestStallMs:0,tailReadFailedReason:u instanceof Error?u.message:"fetch failed"})})},[]);return i.useEffect(()=>{var c;if(!t){a(da),(c=o.current)==null||c.abort();return}return l(),()=>{var d;(d=o.current)==null||d.abort()}},[t,r,l]),s}function lv(e){return!e||!e.loaded||e.tailReadFailedReason?null:e.stalledRequests>0?`Recent requests took up to ${Math.max(1,Math.round(e.longestStallMs/1e3))}s — the dev server is responding, just slowly. Check the dev-server log for what's blocking the render.`:e.fastRequests===0?"No recent activity in the dev-server log — the dev server may have stopped accepting connections. Restart it if this persists.":null}function cv({liveIframeHealthy:e,previewReachable:t}){return e===!0||t===!0}function dv({hasDevServerConfigured:e,hasServed:t}){return!e||t}const uv=2e3;function fv(e,t){const[r,s]=i.useState(0),a=i.useRef(e),o=i.useRef(t),l=i.useRef(0);return i.useEffect(()=>{const c=a.current,d=o.current;if(a.current=e,o.current=t,!(t===!1)||!(e===!0)||!(c===!1&&e===!0)&&!(d===!0&&t===!1))return;const h=Date.now();h-l.current<uv||(l.current=h,s(b=>b+1))},[e,t]),r}const un={windowMs:1e4,threshold:4,ringBufferSize:16};function pv({pidNonce:e,probeNonce:t,draftNonce:r,windowMs:s=un.windowMs,threshold:a=un.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),b=i.useRef(r),g=i.useCallback(w=>{const v=Date.now(),x=v-s;let j=[];d(N=>{const C=N.filter(S=>S.timestampMs>=x);return C.push({reason:w,timestampMs:v}),C.length>un.ringBufferSize&&C.splice(0,C.length-un.ringBufferSize),j=C,C});const k=j.filter(N=>N.timestampMs>=x).length;if(!p.current&&k>=a){p.current=!0,l(!0);return}p.current||f(N=>N+1)},[s,a]);i.useEffect(()=>{e!==m.current&&(m.current=e,g("pid"))},[e,g]),i.useEffect(()=>{t!==h.current&&(h.current=t,g("probe"))},[t,g]),i.useEffect(()=>{r!==b.current&&(b.current=r,g("draft"))},[r,g]);const y=i.useCallback(()=>{p.current=!1,l(!1),d([]),f(w=>w+1)},[]);return{tripped:o,recentReloads:c,gatedNonce:u,reset:y}}const ua=20,mv="codeyam-error-capture";function hv(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!==mv)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>ua?m.slice(m.length-ua):m})}return window.addEventListener("message",o),()=>window.removeEventListener("message",o)},[e]),{errors:r,clear:a}}const sr=[500,1e3,2e3];async function xv(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 gv(){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 bv(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+sr.length;let l=null;for(let d=0;d<o;d++){if(a)return;const{status:u}=await xv(e);if(a)return;if(l=u,u===null||u<500){s({status:u,clickThroughBroken:!1,logLines:[],loading:!1});return}d<sr.length&&await new Promise(f=>setTimeout(f,sr[d]))}const c=await gv();a||s({status:l,clickThroughBroken:!0,logLines:c,loading:!1})})(),()=>{a=!0}},[e,t]),r}function vv({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(`
169
- `):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 yv(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&&(e.restartCount??0)>0,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}}const wv=20;function jv(e){const{hasDevServerConfigured:t,probeHealthy:r,backendIframeHealthy:s,isStarting:a,isRestarting:o,isFailed:l,isStopped:c,isPrePrototype:d,withinStartupGrace:u,previewReachable:f,hasEverServed:p}=e;return t?l?"crashed":s===!0||f===!0||r===!0&&s!==!1?null:d?"scaffolding":c?p?"stopped":null:o?"restarting":a||u||!p?null:r===!1?"reconnecting":s===!1&&r===!0?"disconnected":r===null?"probing":"reconnecting":null}function kv(e){return e===null||e.status!=="running"?!1:e.liveIframeHealthy!==!1}const Nv=5,Cv=3;function Sv(e,t){return e===null||e<=0?!1:e<=(t==="backend"?Cv:Nv)}const fa="Setting up your project",pa="Preparing your project — the preview will appear once it's ready.",Ev={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."},Rv={1:"Aligning on the plan with you.",2:"Aligning on the plan with you.",3:"Preparing the project environment."};function Tv(e,t){return e===null?{title:fa,body:pa}:{title:fa,body:(t==="backend"?Rv:Ev)[e]??pa}}function Pv({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 Dv={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},disconnected:{title:"Preview Disconnected",body:"The dev server is running, but the preview lost its connection after a restart. Reload the preview to reconnect — there's no need to restart the dev server.",spinner:!1},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 Av({variant:e,restartCount:t=0,showRetry:r=!1,onRetry:s,bodyOverride:a}){const{title:o,body:l,spinner:c}=Dv[e],d=a??l,u=e==="disconnected",f=!!s&&(u||r),p=u?"Reload preview":"Retry now";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(Pv,{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})]}),f&&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:p})]})})}function Fv(e){return e.slice().reverse().map(t=>{const r=t.filename!=null?`
170
- at ${t.filename}${t.lineno!=null?`:${t.lineno}`:""}${t.colno!=null?`:${t.colno}`:""}`:"",s=t.stack?`
171
- ${t.stack}`:"",a=t.count>1?` (×${t.count})`:"";return`[${t.type}]${a} ${t.message}${r}${s}`}).join(`
172
-
173
- `)}function Lv(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(", ")}function Mv({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 Iv({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 $v({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 Bv({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($v,{error:a,expanded:r===a.dedupeKey,onToggle:()=>s(r===a.dedupeKey?null:a.dedupeKey)},a.dedupeKey))})}function Ov({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 zv=`Fix this error in the live preview. Here is what the captured runtime error reported:
174
-
175
- `;function _v({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(()=>Fv(t),[t]),p=i.useMemo(()=>Lv(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,b=e?`Live Preview paused — ${t.length} error${t.length===1?"":"s"} captured`:`${t.length} runtime error${t.length===1?"":"s"} captured`;async function g(y){const w=await pl(y+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(Mv,{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(Iv,{headline:b,tripped:e,onClear:m?()=>u(!0):o,closeAriaLabel:m?"Minimize errors":"Dismiss errors"}),n.jsx(Bv,{errors:t,emptyHint:e?`Breaker tripped before any runtime error was reported. Reasons in window: ${p}.`:null}),n.jsx(Ov,{canCopy:t.length>0,reasonsSummary:p,copyState:l,onCopy:()=>g(""),onCopyForClaude:()=>g(zv),onRetry:a})]})})}function Hv({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 Wv(){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 Vv({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 Uv({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}=Sr({writer:s});return n.jsx("button",{type:"button",onClick:()=>{l(e)},disabled:e.length===0,className:a,children:o?r:t})}function Kv(){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 Gv({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(Kv,{}),n.jsx(Uv,{text:e.join(`
176
- `),label:"Copy logs",writer:t})]})})}function Yv({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(Wv,{}),n.jsx(Vv,{logs:e}),n.jsx(Gv,{logs:e})]})}const ma=20;function qv(e){if(!e)return null;try{return new Date(e).toLocaleTimeString()}catch{return null}}function Jv({lastError:e,failureCount:t,failedAtMs:r,holder:s,onRetry:a,onReap:o}){const[l,c]=i.useState(!1),d=e.split(`
177
- `),u=d.length>ma,f=l||!u?d:d.slice(d.length-ma),p=qv(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(`
178
- `)}),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"})]})]})]})}function Xv({diagnostic:e,onRetry:t}){const{expectedPort:r,actualPort:s,appName:a,currentStartCommand:o,remediation:l}=e;return n.jsxs("div",{"data-testid":"preview-port-mismatch-card",className:"absolute inset-0 bg-white dark:bg-gray-900 flex flex-col z-[60] overflow-auto",children:[n.jsxs("header",{className:"px-6 py-4 border-b border-gray-200 dark:border-gray-700",children:[n.jsx("h2",{className:"text-base font-semibold text-gray-900 dark:text-gray-100",children:"Dev server port conflict"}),n.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:[a," bound port"," ",n.jsx("span",{className:"font-semibold",children:s}),", but the editor needs the app on port"," ",n.jsx("span",{className:"font-semibold",children:r})," so its reverse proxy (mocking, capture) can sit in front."]})]}),n.jsxs("div",{className:"flex-1 px-6 py-4 text-sm text-gray-800 dark:text-gray-200 space-y-3",children:[n.jsx("p",{children:l}),n.jsxs("div",{children:[n.jsx("div",{className:"text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400 mb-1",children:"Current start command"}),n.jsx("pre",{className:"m-0 font-mono text-xs leading-relaxed whitespace-pre-wrap rounded bg-gray-100 dark:bg-gray-800 px-3 py-2",children:o||"(none configured)"})]})]}),n.jsx("footer",{className:"px-6 py-3 border-t border-gray-200 dark:border-gray-700 flex items-center justify-end",children:n.jsx("button",{type:"button","data-testid":"preview-port-mismatch-retry",onClick:t,className:"px-4 py-1.5 text-sm font-medium rounded bg-blue-600 text-white hover:bg-blue-700",children:"Retry"})})]})}const ha=48,Qv=100,Zv=320,e0=192;function t0({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:Zv,height:e0,hasViewport:!1};const o=t-ha*2,l=e-ha*2-Qv,c=Math.min(1,o/s,l/r);return{width:Math.round(s*c),height:Math.round(r*c),hasViewport:!0}}function n0({containerHeight:e,containerWidth:t,onDismiss:r,scenarioName:s,screenshotPath:a,viewportHeight:o,viewportWidth:l}){const{width:c,height:d,hasViewport:u}=t0({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(Io,{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 r0({isActive:e,onToggle:t,interactionAvailable:r=!0}){return n.jsx("button",{onClick:r?t:void 0,disabled:!r,title:r?e?"Exit Debug Mode":"Debug Mode":"Click-to-select is unavailable for this stack's preview (served from a separate origin)",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:r?"pointer":"not-allowed",display:"none",alignItems:"center",justifyContent:"center",opacity:r?e?1:.6:.35,transition:"all 0.15s ease",fontSize:18},onMouseEnter:s=>{r&&(s.currentTarget.style.opacity="1")},onMouseLeave:s=>{r&&(e||(s.currentTarget.style.opacity="0.6"))},children:e?"✕":"🔍"})}function s0(){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 a0({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 o0({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 i0({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(o0,{ancestors:e,onOpenInEditor:t})]})}function l0({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 c0({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:b}){const g=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(l0,{propsNames:f}),n.jsx(i0,{ancestors:u,onOpenInEditor:p}),n.jsx("textarea",{value:o,onChange:y=>l(y.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:g,className:"px-3 py-1.5 rounded text-sm flex-1",style:{background:g?"var(--bg-deep)":"var(--accent-blue)",border:"none",color:g?"var(--text-secondary)":"#000",cursor:g?"not-allowed":"pointer",fontWeight:600},children:c?"Creating...":"Create Fix Plan"}),n.jsx("button",{onClick:b,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 d0({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 u0({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}=s0(),m=async()=>{d(!0);try{await a(o,e)}finally{d(!1)}},h=e.componentName??`<${e.element.tag}>`,b=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:g=>g.stopPropagation(),children:[n.jsx(a0,{tag:e.element.tag,id:e.element.id,className:e.element.className,text:e.element.text,detectionMethod:e.detectionMethod,previewUrl:t}),n.jsx(c0,{componentDisplay:h,sourceDisplay:b,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(d0,{error:f,onDismiss:p})]})}function f0(){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 p0({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(f0,{})]})}function m0(){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, #D7FF63)",borderRadius:4,boxSizing:"border-box"},children:n.jsx("div",{style:{position:"absolute",top:0,left:16,padding:"2px 8px",background:"var(--accent-blue, #D7FF63)",color:"#000",fontSize:10,fontWeight:700,fontFamily:"system-ui, -apple-system, sans-serif",borderRadius:"0 0 4px 4px",letterSpacing:.5},children:"INSPECT MODE"})})}function h0(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 x0({onDismiss:e}){return n.jsx("div",{onClick:e,style:{position:"fixed",inset:0,zIndex:999998,background:"transparent"}})}function g0({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 b0({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(g0,{match:r,onOpen:t})},`${r.endpoint}${r.jsonPath}${s}`))})}function v0({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:y0(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(b0,{matches:t,onOpen:s})]})}function y0(e,t){return e.length<=t?e:e.slice(0,t-1)+"…"}function w0({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 xa=320,ga=320,j0=8;function k0({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}=h0(r,{width:c,height:l},{width:xa,maxHeight:ga,gap:j0});return n.jsxs(n.Fragment,{children:[n.jsx(x0,{onDismiss:a}),n.jsxs("div",{style:{position:"fixed",top:d,left:u,width:xa,maxHeight:ga,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(w0,{onDismiss:a}),n.jsx(v0,{clickedText:e,matches:t,corpusEmpty:o,onOpenInPanel:s})]})]})}function N0({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 ba(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 C0(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(ba(h.data.payload)):h.data.type==="codeyam:debug:selected"&&l(ba(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 S0=/^\/api\/mock-panel(\/.*)?$/;function E0(e,t){return e.toUpperCase()!=="GET"?!1:S0.test(t)}function R0(e){return Array.isArray(e)?e.filter(t=>t.consumedThisPageLoad&&!E0(t.method,t.pathPattern)).map(t=>({endpoint:`${t.method} ${t.pathPattern}`,body:t.body})):[]}async function T0(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 P0=12;function D0(e,t,r){if(t.length===0)return[];const s=[];return jr(e,t,r,"$",0,new Set,s),s}function A0(e,t){const r=[];for(const o of e)for(const l of D0(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 jr(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>=P0)&&!o.has(e)){if(o.add(e),Array.isArray(e))for(let d=0;d<e.length;d++)jr(e[d],t,r,`${s}[${d}]`,a+1,o,l);else if(c==="object")for(const[d,u]of Object.entries(e))jr(u,t,r,`${s}.${d}`,a+1,o,l);o.delete(e)}}function va(e,t){return(t==null?void 0:t.previewOrigin)??(e==null?void 0:e.previewOrigin)??null}function F0(e,t){if(!e||!/^https?:\/\//i.test(e))return!0;const r=typeof window<"u"?window.location.origin:null;if(!r)return!1;try{return new URL(e).origin===r}catch{return!0}}const L0={backgroundColor:"#1e1e1e",backgroundImage:"conic-gradient(#262626 25%, #1e1e1e 0 50%, #262626 0 75%, #1e1e1e 0)",backgroundSize:"16px 16px"};function M0({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:b,commandNonce:g}){var he,Ee;const y=i.useRef(null),w=a??y,v=i.useRef(null),{status:x,restart:j}=ml();Xb(x,j);const{isRestarting:k,isFailed:N,isStarting:C,isStopped:S}=yv(x),{stepState:R}=qt(),E=Sv((R==null?void 0:R.step)??null,(R==null?void 0:R.mode)??"ui"),A=(x==null?void 0:x.liveIframeHealthy)!==void 0,{reloadNonce:D,handleIframeLoad:B,handleIframeError:T}=ev((x==null?void 0:x.pid)??null,A,x==null?void 0:x.status),O=(x==null?void 0:x.status)==="failed",{healthy:Y,failedProbeCount:P,reloadNonce:$,invalidate:V}=ov(m,O),_=Zb(x==null?void 0:x.liveIframeHealthy,750),X=fv(Y,_),[F,L]=i.useState(0);i.useEffect(()=>hl(()=>{L(H=>H+1)}),[]);const M=pv({pidNonce:D,probeNonce:$+X,draftNonce:F}),Q=M.gatedNonce,{errors:q,clear:W}=hv(v,Q),z=bv(m,Q),J=i.useCallback(()=>{M.reset(),W(),V()},[M,W,V]),U=i.useCallback(()=>Pa(),[]),se=(x==null?void 0:x.devServerStartedSecsAgo)??null,ie=se!==null&&se<wv,I=!!(x!=null&&x.startCommand),ne=cv({liveIframeHealthy:_,previewReachable:(he=x==null?void 0:x.previewProbe)==null?void 0:he.reachable}),[le,Z]=i.useState(!1);i.useEffect(()=>{ne&&!le&&Z(!0)},[ne,le]);const de=ne||le,we=dv({hasDevServerConfigured:I,hasServed:de}),ce=we?m:"about:blank",re=jv({hasDevServerConfigured:I,probeHealthy:Y,backendRunning:(x==null?void 0:x.status)==="running",backendIframeHealthy:_,isStarting:C,isRestarting:k,isFailed:N,isStopped:S,isPrePrototype:E,withinStartupGrace:ie,previewReachable:((Ee=x==null?void 0:x.previewProbe)==null?void 0:Ee.reachable)===!0,hasEverServed:de}),Be=i.useRef(void 0);i.useEffect(()=>{var ae;if(Be.current===re)return;const H=Be.current;Be.current=re,console.debug(`[preview-overlay] ${H===void 0?"(init)":H??"none"} → ${re??"none"}`,{status:x==null?void 0:x.status,intendedRunning:x==null?void 0:x.intendedRunning,restartCount:x==null?void 0:x.restartCount,pid:x==null?void 0:x.pid,liveIframeHealthy:x==null?void 0:x.liveIframeHealthy,previewProbeReachable:(ae=x==null?void 0:x.previewProbe)==null?void 0:ae.reachable,devServerStartedSecsAgo:se,withinStartupGrace:ie,probeHealthy:Y,isStarting:C,isRestarting:k,isFailed:N,isStopped:S})},[re,x,se,ie,Y,C,k,N,S]);const Te=x==null?void 0:x.portDiagnostic,qe=(Te==null?void 0:Te.conflict)===!0,G=re==="scaffolding"?Tv((R==null?void 0:R.step)??null,(R==null?void 0:R.mode)??"ui").body:void 0,ut=iv({active:re==="reconnecting",trigger:P}),yt=re==="reconnecting"?lv(ut):null,Oe=G??yt??void 0,Ce=P>=10,{isActive:Pe,hoveredElement:wt,selectedElement:be,activate:Je,deactivate:Le,clearSelection:je}=C0(v),Xe=i.useCallback(()=>{Pe?Le():Je()},[Pe,Je,Le]),{entries:Qe}=xl(p??null),{isActive:Se,toggle:Ze}=Qb({activate:Je,deactivate:Le,clearSelection:je},D);i.useEffect(()=>(xs({isActive:Se,previewSlug:p??null}),()=>{xs({isActive:!1,previewSlug:null})}),[Se,p]),i.useEffect(()=>gl(()=>{Ze()}),[Ze]);const Ue=Se&&be?be.element.text.trim():"",ye=i.useMemo(()=>R0(Qe),[Qe]),Dt=i.useMemo(()=>!Se||!Ue?[]:A0(ye,Ue),[Se,Ue,ye]),ue=i.useCallback(async H=>{je(),Le();try{const fe=await(await fetch("/api/scenarios")).json(),xe=Array.isArray(fe)?fe.find(oe=>oe.componentName===H):null;if(xe!=null&&xe.slug){const oe=Go(window.location),De=qo(xe.slug,oe,null,0,h);window.history.pushState(null,"",De);return}}catch{}window.history.pushState(null,"","/entities")},[je,Le,h]),me=i.useCallback(async(H,ae)=>{try{await T0(H,ae,m),je(),Le()}catch(fe){console.error("Failed to create debug plan:",fe)}},[m,je,Le]);return n.jsx("div",{ref:w,className:`relative flex-1 flex overflow-hidden ${u?"":"items-center justify-center p-8"}`,style:u?{backgroundColor:"#fff"}:L0,children:m?n.jsxs(n.Fragment,{children:[n.jsx(Jb,{ref:v,currentHeight:l,currentWidth:c,isFilled:u,previewUrl:ce,scale:b,reloadNonce:Q,onLoad:()=>{we&&B(m)},onError:T}),!we&&n.jsx(Gb,{hasDevServerConfigured:I}),n.jsx(Hv,{previewUrl:m}),n.jsx(N0,{healthy:_,reason:(x==null?void 0:x.iframeLastError)??null}),Pe&&n.jsx(p0,{hoveredElement:wt}),Se&&n.jsx(m0,{}),be&&!Se&&n.jsx(u0,{element:be,previewUrl:m,onClose:je,onGoToIsolated:ue,onCreatePlan:me}),be&&Se&&n.jsx(k0,{clickedText:Ue,matches:Dt,anchor:be.element.boundingBox,corpusEmpty:ye.length===0,onOpenInPanel:H=>{bl({routeKey:H.endpoint,jsonPath:H.jsonPath}),je()},onDismiss:je}),!t&&n.jsx(r0,{isActive:Pe,onToggle:Xe,interactionAvailable:F0(h)}),O?n.jsx(Jv,{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:j,onReap:async()=>{await fetch("/api/editor-dev-server/reap",{method:"POST",headers:{"Content-Type":"application/json"}})}}):qe&&Te?n.jsx(Xv,{diagnostic:Te,onRetry:j}):re&&(re==="crashed"?n.jsx(Yv,{logs:(x==null?void 0:x.logs)??[]}):n.jsx(Av,{variant:re,restartCount:(x==null?void 0:x.restartCount)??0,showRetry:Ce,onRetry:re==="disconnected"?U:V,bodyOverride:Oe})),n.jsx(_v,{tripped:M.tripped,errors:q,recentReloads:M.recentReloads,serverHealthy:kv(x),onRetry:J,onClear:W}),z.clickThroughBroken&&z.status!==null&&n.jsx(vv,{url:m,status:z.status,logLines:z.logLines,onRetry:J}),t&&f&&n.jsx(n0,{containerHeight:s,containerWidth:o,onDismiss:f,scenarioName:e??null,screenshotPath:r??null,viewportHeight:l,viewportWidth:c})]}):n.jsx(Kb,{message:d})})}function I0({prompt:e}){const[t,r]=i.useState(!0);return n.jsxs("section",{"aria-label":"What you asked for",style:{border:"1px solid var(--border-subtle)",borderRadius:"8px",padding:"0.875rem 1rem",marginBottom:"1.5rem",background:"var(--bg-elevated)",fontFamily:"'IBM Plex Mono', monospace"},children:[n.jsxs("button",{type:"button",onClick:()=>r(s=>!s),"aria-expanded":t,style:{width:"100%",background:"transparent",border:"none",padding:0,margin:0,color:"var(--text-muted)",fontSize:"0.75rem",fontWeight:500,textAlign:"left",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"space-between",fontFamily:"inherit"},children:[n.jsx("span",{children:"What you asked for"}),n.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",transition:"transform 150ms ease",transform:t?"rotate(0deg)":"rotate(-90deg)",color:"var(--text-muted)",fontSize:"0.75rem"},children:"▾"})]}),t?n.jsx("div",{style:{marginTop:"0.625rem",fontFamily:"ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif",color:"var(--text-secondary)",fontSize:"0.8125rem",lineHeight:1.55},children:n.jsx(ht,{children:e})}):null]})}function $0(){return n.jsxs("header",{style:{marginBottom:"1.5rem",fontFamily:"'IBM Plex Mono', monospace"},children:[n.jsxs("h1",{style:{fontSize:"1.125rem",fontWeight:600,color:"var(--text-primary)",margin:"0 0 0.5rem 0",display:"flex",alignItems:"baseline",gap:"0.5rem"},children:[n.jsx("span",{"aria-hidden":"true",style:{color:"var(--text-muted)",letterSpacing:"-0.1em"},children:"::"}),"Your app is being built!"]}),n.jsx("p",{style:{margin:0,color:"var(--text-muted)",fontSize:"0.8125rem"},children:"This usually takes a few minutes."})]})}function B0(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 kr="#D7FF63",O0="var(--text-muted)";function z0({status:e}){return e==="complete"?n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 18 18","aria-hidden":"true",style:{flexShrink:0,display:"block"},children:[n.jsx("circle",{cx:"9",cy:"9",r:"7.5",fill:"none",stroke:"#FFFFFF",strokeWidth:"1.5"}),n.jsx("path",{d:"M5.5 9.2 L8 11.5 L12.5 6.5",fill:"none",stroke:"#FFFFFF",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"})]}):e==="active"?n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 18 18",role:"img","aria-label":"In progress",style:{flexShrink:0,display:"block",animation:"codeyam-setup-spin 1.1s linear infinite"},children:[n.jsx("circle",{cx:"9",cy:"9",r:"7.5",fill:"none",stroke:kr,strokeWidth:"1.5",opacity:"0.25"}),n.jsx("path",{d:"M9 1.5 A 7.5 7.5 0 0 1 16.5 9",fill:"none",stroke:kr,strokeWidth:"1.75",strokeLinecap:"round"})]}):n.jsx("svg",{width:"18",height:"18",viewBox:"0 0 18 18","aria-hidden":"true",style:{flexShrink:0,display:"block"},children:n.jsx("circle",{cx:"9",cy:"9",r:"7.5",fill:"none",stroke:O0,strokeWidth:"1.5"})})}function _0({phase:e,status:t}){const r=t==="active"?kr:t==="complete"?"var(--text-primary)":"var(--text-muted)";return n.jsxs("li",{"data-phase-id":e.phaseId,"data-phase-status":t,style:{display:"flex",alignItems:"center",gap:"0.625rem"},children:[n.jsx(z0,{status:t}),n.jsx("span",{style:{color:r,fontSize:"0.8125rem",fontFamily:"'IBM Plex Mono', monospace",fontWeight:t==="active"?600:400,letterSpacing:"0.01em"},children:e.phaseLabel})]})}function H0({currentStep:e,mode:t}){const r=xd(t);return n.jsx("section",{"aria-label":"Progress",style:{marginBottom:"0.5rem"},children:n.jsx("ol",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:"0.875rem"},children:r.map(s=>{const a=B0(s,e);return n.jsx(_0,{phase:s,status:a},s.phaseId)})})})}function W0(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(`
179
- `)&&(t=t.slice(0,-1)),t}function V0({prompt:e,currentStep:t,mode:r}){return n.jsxs("div",{style:{background:"var(--bg-elevated, #141414)",border:"1px solid var(--border-subtle)",borderRadius:"12px",padding:"1.5rem 1.75rem",maxWidth:"520px"},children:[n.jsx($0,{}),n.jsx(I0,{prompt:W0(e)}),n.jsx(H0,{currentStep:t,mode:r})]})}function U0(){const{prompt:e}=li(),{stepState:t}=qt();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:n.jsx(V0,{prompt:e??"",currentStep:(t==null?void 0:t.step)??1,mode:(t==null?void 0:t.mode)??"ui"})})})}function K0({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 G0(){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 Y0(e){return e.state==="preflight-running"||e.state==="booting-simulator"||e.state==="simulator-booted"||e.state==="building-app"}function q0({stderrTail:e,onClose:t}){return n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(0,0,0,0.6)"},onClick:t,children:n.jsxs("div",{className:"max-w-2xl w-full max-h-[80vh] overflow-auto rounded p-4 font-mono text-xs",style:{background:"var(--bg-elevated)",color:"var(--text-primary)"},onClick:r=>r.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsx("strong",{children:"Build logs (stderr tail)"}),n.jsx("button",{type:"button",onClick:t,className:"opacity-70 hover:opacity-100",children:"✕"})]}),n.jsx("pre",{className:"whitespace-pre-wrap",children:e||"(no stderr captured)"})]})})}const J0=1500;function X0({stackId:e,pollMs:t=J0,onStateChange:r}){const[s,a]=i.useState({state:"idle"}),[o,l]=i.useState(!1),[c,d]=i.useState(!1),u=i.useRef(r);u.current=r,i.useEffect(()=>{let m=!1,h=!0;const b=async()=>{var y;try{const w=await fetch("/api/simulator-status");if(!w.ok)return;const v=await w.json();if(m||!h)return;const{history:x,...j}=v;a(j),(y=u.current)==null||y.call(u,j)}catch{}};b();const g=window.setInterval(b,t);return()=>{m=!0,h=!1,window.clearInterval(g)}},[t]);const f=i.useCallback(async()=>{if(!o){l(!0);try{const m=e?JSON.stringify({stack_id:e}):"{}";await fetch("/api/start-simulator",{method:"POST",headers:{"content-type":"application/json"},body:m})}finally{l(!1)}}},[e,o]),p=o||Y0(s);return n.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 text-sm border-b",style:{background:"var(--bg-deep)",color:"var(--text-primary)"},children:[n.jsx("button",{type:"button",onClick:f,disabled:p,className:"px-3 py-1 rounded font-medium disabled:opacity-40 disabled:cursor-not-allowed",style:{background:"var(--accent)",color:"var(--bg-deep)"},children:s.state==="app-launched"?"Restart simulator":"Start simulator"}),n.jsx(Q0,{status:s}),s.state==="build-failed"?n.jsx("button",{type:"button",onClick:()=>d(!0),className:"text-xs underline opacity-80 hover:opacity-100",children:"see logs"}):null,c&&s.state==="build-failed"?n.jsx(q0,{stderrTail:s.stderrTail,onClose:()=>d(!1)}):null]})}function Q0({status:e}){const t=Z0(e);return n.jsx("span",{className:"text-xs opacity-80","data-testid":"simulator-status-pill",children:t})}function Z0(e){switch(e.state){case"idle":return"No simulator running";case"preflight-running":return"Pre-flight checks…";case"preflight-failed":return`Pre-flight failed: ${e.check} — ${e.message}`;case"booting-simulator":return`Booting ${e.device}…`;case"simulator-booted":return`Simulator booted (${e.name})`;case"building-app":return`Building (${ey(e.elapsedSec)})…`;case"build-failed":return"Build failed";case"app-launched":return"App running ▸";case"stopped":return e.reason.kind==="user-requested"?"Stopped":e.reason.kind==="editor-server-shutdown"?"Editor server shut down":e.reason.code!=null?`Stopped (exit ${e.reason.code})`:"Stopped"}}function ey(e){if(e<60)return`${e}s`;const t=Math.floor(e/60),r=e%60;return`${t}m ${r.toString().padStart(2,"0")}s`}function ty({currentWidth:e,currentHeight:t,isFilled:r,scale:s,variant:a}){const o=a==="xcode-missing"?"Xcode tooling not detected":"No iOS Simulator running",l=a==="xcode-missing"?"Install Xcode + command line tools, then boot a simulator.":"Boot a simulator (Xcode → Window → Devices and Simulators) to see the live preview.",c=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:o}),n.jsx("div",{className:"opacity-70 mt-1",children:l})]})});return r?c: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:c})}const ny=700;function ry({currentHeight:e,currentWidth:t,isFilled:r,scale:s,pollMs:a=ny,onError:o}){const[l,c]=i.useState(0),[d,u]=i.useState({kind:"loading"}),f=i.useRef(o);if(f.current=o,i.useEffect(()=>{let m=!1;const h=window.setInterval(()=>{m||c(b=>b+1)},a);return()=>{m=!0,window.clearInterval(h)}},[a]),i.useEffect(()=>{let m=!1;return fetch(`/api/simulator-frame?t=${l}`,{method:"HEAD"}).then(async h=>{var g;if(m)return;if(h.ok){u({kind:"ok"});return}if(h.status===503){const y=await sy(h);if(m)return;(typeof(y==null?void 0:y.error)=="string"?y.error:"").includes("xcode")?u({kind:"xcode-missing"}):u({kind:"no-device"});return}const b=`simulator frame request failed (${h.status})`;u({kind:"capture-failed",message:b}),(g=f.current)==null||g.call(f,b)}).catch(h=>{var g;if(m)return;const b=h instanceof Error?h.message:"simulator frame request errored";u({kind:"capture-failed",message:b}),(g=f.current)==null||g.call(f,b)}),()=>{m=!0}},[l]),d.kind==="no-device"||d.kind==="xcode-missing")return n.jsx(ty,{currentWidth:t,currentHeight:e,isFilled:r,scale:s,variant:d.kind});const p=`/api/simulator-frame?t=${l}`;return r?n.jsx("img",{src:p,alt:"iOS Simulator preview",className:"w-full h-full object-contain",style:{background:"var(--bg-deep)"}}):n.jsx("div",{className:"shadow-[0_10px_30px_rgba(0,0,0,0.45)]",style:{width:t,height:e,transform:s<1?`scale(${s})`:void 0,transformOrigin:"center center",flexShrink:0},children:n.jsx("img",{src:p,alt:"iOS Simulator preview",style:{width:"100%",height:"100%",background:"var(--bg-deep)",objectFit:"contain"}})})}async function sy(e){try{return await e.json()}catch{return null}}function ay({emptyStateMessage:e,firstSessionSetup:t,previewSlug:r,previewUrl:s,viewports:a,activeViewport:o,onViewportChange:l,isCollapsed:c,onToggleCollapsed:d,isFilled:u,onToggleFilled:f,currentWidth:p,currentHeight:m,onCustomSizeChange:h,buildingScenarioSlug:b,buildingScreenshotPath:g,buildingScenarioName:y,onDismissBuildingOverlay:w,previewSeeding:v,previewSeedError:x,onRetrySeed:j,currentScenario:k,scenarioGroups:N,onShowScenarioPreview:C,commandNonce:S,previewOrigin:R,isNarrow:E=!1,onDesignConfirmed:A}){const[D,B]=i.useState(!1),{containerRef:T,containerSize:O,scale:Y}=Dx({currentHeight:m,currentWidth:p,isFilled:u}),P=Ax();i.useEffect(()=>{vt()||Rx(x??null)},[x]);const $=s?es(s):"",V=$==="/results"||$.startsWith("/results/"),_=$==="/plan-preview",X=$==="/design-exploration";return _?n.jsx(Ub,{}):V?n.jsx(og,{}):X?n.jsx(Nb,{onDesignConfirmed:A}):t&&!s?n.jsx(U0,{}):n.jsxs("div",{"data-preview-pane":"true",className:"flex-1 flex flex-col min-w-0",children:[n.jsx(Hb,{viewports:a,active:o,onChange:l,currentWidth:p,currentHeight:m,previewUrl:s,isCollapsed:c,onToggleCollapsed:d,isFilled:u,onToggleFilled:f,containerWidth:(O==null?void 0:O.width)??null,containerHeight:(O==null?void 0:O.height)??null,onCustomSizeChange:h,currentScenario:k??null,scenarioGroups:N??[],onShowScenarioPreview:C??(()=>{}),onCreateStateRequest:()=>B(!0),isNarrow:E}),x?n.jsx(K0,{error:x,onRetry:j}):null,n.jsxs("div",{className:"relative flex-1 flex flex-col min-h-0",children:[P.kind==="simulator-ios"?n.jsxs(n.Fragment,{children:[n.jsx(X0,{}),n.jsx("div",{ref:T,className:"relative flex-1 flex overflow-hidden items-center justify-center p-8",style:{backgroundColor:"#1e1e1e"},children:n.jsx(ry,{currentHeight:m,currentWidth:p,isFilled:u,scale:Y})})]}):n.jsx(M0,{containerRef:T,containerHeight:O==null?void 0:O.height,containerWidth:O==null?void 0:O.width,currentHeight:m,currentWidth:p,emptyStateMessage:e??"Select a scenario to preview",isFilled:u,previewSlug:r,previewUrl:s,previewOrigin:R,scale:Y,buildingScenarioSlug:b,buildingScreenshotPath:g,buildingScenarioName:y,onDismissBuildingOverlay:w,commandNonce:S}),v?n.jsx(G0,{}):null]}),D?n.jsx(ig,{onClose:()=>B(!1)}):null]})}function oy(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),{scenariosVersion:l}=gt(),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(Tr);t(ai(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 iy(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),{scenariosVersion:l}=gt(),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(Tr):[]})):[])}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 ya(e){const t=new Map;for(const r of e){const s=ly(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 ly(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 ci(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 di(e,t,r){return r==="backend"?[]:e.map(s=>({...s,scenarios:s.scenarios.filter(Et)})).filter(s=>s.scenarios.length>0)}function ui(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 cy(e){return e.reduce((t,r)=>t+r.scenarios.length,0)}const dy=3e3;function uy(){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),[b,g]=i.useState(null),y=i.useRef(null),w=i.useRef(null),v=i.useRef(!1),x=i.useRef(null),{testsVersion:j}=gt(),k=i.useCallback(async(D=!1)=>{var Y;(Y=y.current)==null||Y.abort();const B=new AbortController;y.current=B;const{signal:T}=B;D&&(v.current=!0,o(!0));const O=!D&&x.current!==null;O||(s(!0),c(null));try{if(!D&&!O)try{const _=await fetch("/api/test-results/summary",{signal:T});if(_.ok){const X=await _.json();X.running?p(X.currentRunner??null):X.stats&&(h(X.stats),g(X.coverage??null))}}catch{}let P,$;if(O){P=x.current;const _=await fetch("/api/test-results",{signal:T});if(!_.ok)throw new Error(`test-results: HTTP ${_.status}`);$=await _.json()}else if(D){const _=await fetch("/api/test-results/refresh",{method:"POST",signal:T});if(!_.ok)throw new Error(`test-results: HTTP ${_.status}`);$=await _.json(),P=x.current??[]}else{const[_,X]=await Promise.all([fetch("/api/tests",{signal:T}),fetch("/api/test-results",{signal:T})]);if(!_.ok)throw new Error(`tests: HTTP ${_.status}`);if(!X.ok)throw new Error(`test-results: HTTP ${X.status}`);P=ya(await _.json()),$=await X.json(),x.current=P}if(p($.currentRunner??null),$.running&&v.current){w.current=setTimeout(()=>k(!1),dy);return}const V=v.current;if(v.current=!1,V){const _=await fetch("/api/tests",{signal:T});_.ok&&(P=ya(await _.json()),x.current=P)}t(P),u($.cached??!1),g($.coverage??null),h(null),s(!1),o(!1)}catch(P){if(P instanceof DOMException&&P.name==="AbortError")return;v.current=!1,c(P instanceof Error?P.message:"Failed to load tests"),s(!1),o(!1)}},[]);i.useEffect(()=>(x.current=null,k(),()=>{var D;(D=y.current)==null||D.abort(),w.current&&clearTimeout(w.current)}),[k,j]);const{total:N,passed:C,failed:S,ignored:R,discovered:E}=i.useMemo(()=>ui(e),[e]),A=i.useCallback(()=>{v.current||k(!0)},[k]);return{groups:e,loading:r,refreshing:a,error:l,cached:d,currentRunner:f,summaryStats:m,coverage:b,totalTests:N,passedTests:C,failedTests:S,ignoredTests:R,discoveredTests:E,reload:k,refresh:A}}function ss(e,t){return e.filter(r=>r.appDir===t)}function fi(e,t){return t?e.find(r=>r.route===t)??null:null}function pi(e,t,r){const s=di(e,t,r);return my(s)}function fy(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=>Nr(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 py(e){return(e==null?void 0:e.defaultScenarioSlug)??null}function mi(e,t){const r=e.find(s=>s.type==="web");return r?pi(t,r.dir,r.type):null}function my(e){const t=e.flatMap(c=>c.scenarios.filter(d=>Et(d)).map(d=>({route:c.route,scenario:d})));if(t.length===0)return null;const r=t.find(({route:c,scenario:d})=>c==="/"&&Nr(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})=>Nr(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(Et(d)){o=d.slug,l=c.route.length;break}}return o}function Nr(e){return/\bhome\b/i.test(e.name)}function wa(e){return new Set(e.flatMap(t=>t.scenarios.map(r=>r.slug)))}function ar({selectedApp:e,appRouteEntities:t,scenarioGroups:r}){return e?fy(t)??pi(r,e.dir,e.type):null}function hy({apps:e,hasExplicitAppSelection:t,scenarioGroups:r}){return t||e.length===0||r.length===0?null:mi(e,r)}function ja(e){return py(e)}function xy({apps:e,routeEntities:t,selectedApp:r,appRouteEntities:s}){if(r)return s;const a=e.find(o=>o.type==="web");return a?ss(t,a.dir):[]}function gy({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 by({previewRouteEntities:e,path:t}){var s;const r=es(t);return((s=fi(e,r))==null?void 0:s.defaultScenarioSlug)??null}function vy(e){return e.startsWith("/scenario/")||e.startsWith("/isolated-components/")}function yy(e){return vy(e)?!1:e==="/"||e==="/apps"||e==="/apps/"}function wy(e,t,r=""){const s=Un(r),[a,o]=i.useState(s.selectedAppDir),[l,c]=i.useState(s.selectedEntityHash);i.useEffect(()=>{const v=Un(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=Un(r);if(v.selectedAppDir||v.selectedEntityHash||!yy(r))return;const x=Kn(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=>lr(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?ss(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(Kn(v))}function b(){o(null),c(null),m("/apps")}function g(v){const x=f.find(N=>N.route===v);if(!x)return;const j=lr(x),k=$a(x);!j||!k||(c(j),m(k))}function y(v){c(v),m(`/entities/${v}`)}function w(){c(null),m(a?Kn(a):"/apps")}return{selectedApp:u,appRouteEntities:f,selectedEntityHash:l,selectedRouteEntity:p,selectApp:h,deselectApp:b,selectRoute:g,selectEntity:y,deselectRoute:w}}function jy(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:b,selectRoute:g,selectEntity:y,deselectRoute:w}=wy(e,t,a),v=i.useMemo(()=>wa(f),[f]),x=i.useMemo(()=>wa(m?[m]:[]),[m]),j=i.useMemo(()=>ar({selectedApp:u,appRouteEntities:f,scenarioGroups:r}),[f,r,u]),k=i.useMemo(()=>ja(m),[m]),N=i.useMemo(()=>u?ci(s,u.dir):[],[s,u]);i.useEffect(()=>{if(c.current)return;const B=hy({apps:e,scenarioGroups:r,hasExplicitAppSelection:!!u});B&&(l(B),c.current=!0)},[e,r,u]),i.useEffect(()=>{if(u){if(d.current){d.current=!1;return}if(m){if(!k||o&&x.has(o))return;l(k);return}j&&(o&&v.has(o)||l(j))}},[j,k,o,u,v,m,x]);function C(B){h(B);const T=e.find(Y=>Y.dir===B);if(!T)return;const O=ar({selectedApp:T,appRouteEntities:ss(t,T.dir),scenarioGroups:r});l(O)}function S(){b(),l(mi(e,r))}function R(B){g(B);const T=ja(fi(f,B));l(T)}const E=i.useCallback(B=>{d.current=!0,l(B)},[]);function A(){if(w(),!u)return;const B=ar({selectedApp:u,appRouteEntities:f,scenarioGroups:r});B&&l(B)}function D(B){y(B)}return{selectedApp:u,appRouteEntities:f,appTestGroups:N,selectedEntityHash:p,selectedRouteEntity:m,previewSlug:o,setPreviewSlug:l,setPreviewSlugExplicit:E,selectApp:C,deselectApp:S,selectRoute:R,selectEntity:D,deselectRoute:A}}const ky=1e3;function Ny(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,ky)}}return s(),()=>{r=!1}},[])}function Cy(){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(()=>uc(e),[e]);return{graph:e,entityLookup:l,loading:r,error:a}}const Sy=["/apps","/entities","/app","/build","/history","/settings","/plan"];function hi(e){if(!e)return!1;const t=es(e);return Sy.some(r=>t===r||t.startsWith(`${r}/`))}function Ey(e,t,r){const s=typeof window<"u"?Go(window.location):0;let a="";if(En(e)==="component"?a=qo(e.slug,s,e.url,t,r):e.url&&(a=Yo(e.url,{appPort:t,currentPort:s,previewOrigin:r})),a&&!hi(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 Ry(e){return e==="/design-exploration"}function Ty(e,t,r){return e.startsWith("http")||e?e:r?`${r}/results`:`http://127.0.0.1:${t}/results`}function Py(e,t,r){return e.startsWith("http")||e?e:r?`${r}/plan-preview`:`http://127.0.0.1:${t}/plan-preview`}function xi(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 Dy({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"?Ty(e,a,o):r==="plan-preview"?Py(e,a,o):e.startsWith("http")||Ry(e)?e:o?`${o}${e}`:`http://127.0.0.1:${a}${e}`:s?Ey({slug:s.slug,scenarioType:s.scenarioType,componentName:s.componentName,url:s.url},a,o):t?t.startsWith("http")?t:o?`${o}${t}`:`http://127.0.0.1:${a}${t}`:""}function Ay(e,t=Date.now()){const r=e.includes("?")?"&":"?";return`${e}${r}_cb=${t}`}function Cr(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 Fy({apps:e,appRouteEntities:t,directPreviewPath:r,fallbackPort:s,previewKind:a,previewOrigin:o,previewSlug:l,routeEntities:c,scenarioGroups:d,selectedApp:u,selectedRouteEntity:f}){const p=xi(d,l),m=xy({apps:e,routeEntities:c,selectedApp:u,appRouteEntities:t}),h=gy({previewRouteEntities:m,selectedRouteEntity:f}),b=e.some(w=>w.type==="web");let g="blank";a==="plan-preview"&&r?g="plan-preview":a==="results"&&r?g="results":a==="application"&&r?g="application":p?g=Et(p)?"application":"component":h&&(g="application");const y=Dy({directPreviewPath:r,fallbackPreviewPath:h,previewKind:g,selectedScenario:p,port:s,previewOrigin:o});return{selectedScenario:p,previewRouteEntities:m,fallbackPreviewPath:h,resolvedPreviewKind:g,basePreviewUrl:y,hasWebApp:b}}function Ly({allowEditorRoutePreview:e,command:t,configLoaded:r,previewRouteEntities:s,scenarioGroups:a,scenarioDeferAvailable:o=!1}){const l=t.dimension??null,c=!!t.dimension,d=t.commandNonce;if(t.scenarioSlug??t.scenarioId){const g=t.scenarioSlug??t.scenarioId,y=xi(a,g);return y?{clearCustomSize:c,scenarioSlug:y.slug,type:"show-scenario",viewportName:l,commandNonce:d}:o?{clearCustomSize:c,type:"defer",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:g,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=hi(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 b=by({previewRouteEntities:s,path:u});return b?{clearCustomSize:c,scenarioSlug:b,type:"show-scenario",viewportName:l,commandNonce:d}:{clearCustomSize:c,path:u,previewKind:"application",previewSlug:null,preserveDirectPreviewPathOnSlugChange:!1,type:"show-path",viewportName:l,commandNonce:d}}function My(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 Iy=[{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 $y(e,t){const r=Object.entries(e);if(r.length===0)return Iy;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 By({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 Oy({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(nf({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}}const zy=3;function _y({apps:e,appRouteEntities:t,configLoaded:r,defaultScreenSize:s,port:a,previewOrigin:o,projectTitle:l,previewSlug:c,routeEntities:d,scenarioGroups:u,scenariosLoaded:f,screenSizes:p,selectedApp:m,selectedRouteEntity:h,setPreviewSlug:b}){const[g,y]=i.useState("Desktop"),[w,v]=i.useState(null),[x,j]=i.useState(null),[k,N]=i.useState(null),[C,S]=i.useState(null),[R,E]=i.useState(()=>Date.now()),[A,D]=i.useState(0),B=i.useRef(null),T=i.useRef(!1),O=i.useMemo(()=>$y(p,s),[s,p]),Y=i.useMemo(()=>w!==null&&x!==null?{name:"Custom",width:w,height:x}:O.find(Z=>Z.name===g)??O[0]??{name:"Desktop",width:1440,height:900},[g,x,w,O]),P=vt(),$=l==="CodeYam Editor",{basePreviewUrl:V,fallbackPreviewPath:_,hasWebApp:X,previewRouteEntities:F,resolvedPreviewKind:L,selectedScenario:M}=i.useMemo(()=>Fy({apps:e,appRouteEntities:t,directPreviewPath:k,fallbackPort:a,previewKind:C,previewOrigin:o,previewSlug:c,routeEntities:d,scenarioGroups:u,selectedApp:m,selectedRouteEntity:h}),[e,t,k,a,C,o,c,d,u,m,h]),Q=i.useMemo(()=>V?Ay(V,R):"",[V,R]),q=i.useCallback(Z=>{y(Z),v(null),j(null)},[]),W=i.useCallback((Z,de)=>{v(Z),j(de)},[]),z=i.useCallback(Z=>{b(Z),N(null),S(null),E(Date.now());const de=Cr(Z,u);if(!de)return;const we=My(g,w,x,de,O);we!==null&&(y(we),v(null),j(null))},[g,x,w,u,b,O]),J=i.useCallback((Z,de)=>{const we=(de==null?void 0:de.retriesLeft)??zy,ce=Ly({allowEditorRoutePreview:$,command:Z,configLoaded:r,previewRouteEntities:F,scenarioGroups:u,scenarioDeferAvailable:we>0});if(ce.viewportName&&y(ce.viewportName),ce.clearCustomSize&&(v(null),j(null)),ce.type==="show-scenario"){z(ce.scenarioSlug),D(re=>re+1);return}if(ce.type==="defer"){B.current={command:Z,retriesLeft:we};return}if(ce.type==="refresh"){E(Date.now()),D(re=>re+1);return}ce.type!=="ignore"&&(ce.type==="show-path"&&(S(ce.previewKind),N(ce.path),T.current=ce.preserveDirectPreviewPathOnSlugChange,typeof ce.previewSlug=="string"?b(ce.previewSlug):ce.previewSlug===null&&b(null)),E(Date.now()),D(re=>re+1))},[r,$,F,u,b,z]);i.useEffect(()=>{if(!r)return;const Z=B.current;Z&&(B.current=null,J(Z.command,{retriesLeft:Z.retriesLeft-1}))},[r,u,J]),i.useEffect(()=>{if(!(!c||k===null)){if(T.current){T.current=!1;return}N(null),S(null),E(Date.now())}},[k,c]);const U=i.useMemo(()=>L==="results"||L==="plan-preview"?k:L==="application"?k??(M==null?void 0:M.url)??_:null,[k,_,L,M==null?void 0:M.url]),se=i.useCallback(()=>{E(Date.now())},[]);By({isInIframe:P,persistedPath:U,previewKind:L,resolvedViewport:Y,selectedScenario:M?{id:M.id??null,slug:M.slug}:null});const{seeding:ie,seedError:I}=Oy({isInIframe:P,onActivated:se,previewKind:L,scenariosLoaded:f,selectedScenario:M?{slug:M.slug,scenarioType:M.scenarioType,componentName:M.componentName??null}:null}),ne=X?"Select a scenario to preview":"No web app is available for Live Preview.",le=i.useCallback(Z=>{N(Z),S(Z?"application":null),E(Date.now())},[]);return{viewports:O,resolvedViewport:Y,previewUrl:Q,emptyStateMessage:ne,handleViewportChange:q,handleCustomSizeChange:W,showScenarioPreview:z,handlePreviewCommand:J,setPreviewPath:le,previewSeeding:ie,previewSeedError:I,commandNonce:A}}function Hy(){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 Wy(){const[e,t]=i.useState(!1),r=i.useCallback(()=>{t(!0)},[]),s=i.useCallback(()=>{t(!1)},[]);return{showPlanCompleteModal:e,onPlanCompleteCommand:r,dismissPlanCompleteModal:s}}function Vy(){const{showBuildTab:e}=Qr(typeof window>"u"?"/":window.location.pathname),{config:t}=dt(),[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 Jr()}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 Xr({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 Uy({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 Ky(e,t,r){return e.map(s=>{const a=ci(t,s.dir),o=di(r,s.dir,s.type),{total:l,passed:c,failed:d,ignored:u,discovered:f}=ui(a),p=cy(o);return{app:s,tests:{total:l,passed:c,failed:d,ignored:u,discovered:f},scenarios:{total:p,thumbnails:Gy(o)}}})}function Gy(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 Yy="Your app will display here once set up.",qy="Loading your app…";function Jy({configLoading:e,hasNoApps:t,hasStepState:r,defaultMessage:s}){return e?qy:t&&!r?Yy:s}function Xy(e,t){return t?{scenarioSlug:e,path:t}:{scenarioSlug:e}}function Qy(e,t){return e==="needs-login"&&!t}function Zy(e){return e.activeTab==="build"&&!e.hasActiveSession&&!e.isAgentBuilding&&!e.showPostPushModal&&e.launchingPlanSlug===null&&!e.submittingBuildPrompt&&!e.stepStateFeature&&e.pendingPlanCount>0&&!e.buildLaunchModalDismissed}const e1=4e3;function t1({state:e,provider:t,credsPresent:r=!0,reason:s=null,expiresAt:a=null,probeInFlight:o=!1,backendOutOfDate:l=!1,sessionOngoing:c=!1,onAuthenticated:d,onAuthorized:u}){const[f,p]=i.useState(!1),[m,h]=i.useState(!1),b=lt(t),[g,y]=i.useState(!1);i.useEffect(()=>{if(e!=="unknown"){y(!1);return}const j=window.setTimeout(()=>y(!0),e1);return()=>window.clearTimeout(j)},[e]);const w=i.useCallback(()=>{p(!1),d(),u==null||u()},[d,u]),v=i.useCallback(async()=>{h(!0);try{await fetch("/api/auth/refresh-cache",{method:"POST"}),d()}catch{}finally{h(!1)}},[d]);if(e==="authenticated")return null;const x=f?n.jsx(yl,{provider:t,onAuthenticated:w,onClose:()=>p(!1)}):null;return e==="unknown"?o||!g||l?null:n.jsxs("div",{"data-testid":"provider-auth-checking","data-auth-card":!0,className:"m-4 rounded-lg border border-[#3A3A3A] bg-[#1E1E1E] p-5 space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("span",{"data-testid":"provider-auth-checking-spinner","aria-hidden":"true",className:"h-4 w-4 rounded-full border-2 border-[#8E8E8E] border-t-transparent animate-spin"}),n.jsxs("p",{className:"text-sm text-[#8E8E8E]",children:["Checking your ",b," account… If this takes more than a few seconds, your token may need refresh."]})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx("button",{onClick:()=>p(!0),"data-testid":"provider-auth-checking-retry",className:"px-3 py-2 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer",children:"Authenticate"}),n.jsx("button",{onClick:()=>void v(),"data-testid":"provider-auth-checking-recheck",disabled:m,className:"px-3 py-2 text-sm rounded-md border border-[#3A3A3A] text-white cursor-pointer disabled:opacity-50",children:m?"Rechecking…":"Already logged in? Recheck"})]}),x]}):n.jsx(vl,{provider:t,credsPresent:r,reason:s,expiresAt:a,sessionOngoing:c,onAuthenticated:d,onAuthorized:u})}const n1=300,ka=150;function r1(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 g;if(!s.current)return;const m=((g=e.current)==null?void 0:g.getBoundingClientRect().left)??0,h=p.clientX-m,b=l();h<ka?r(0):h>b-ka?r(b):r(Math.max(n1,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}}function s1(e=768){const t=`(max-width: ${e-.02}px)`,[r,s]=i.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(t).matches);return i.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const a=window.matchMedia(t);s(a.matches);const o=l=>s(l.matches);return a.addEventListener("change",o),()=>a.removeEventListener("change",o)},[t]),r}const a1=3e3;function o1({hot:e,isInIframe:t,reload:r=()=>window.location.reload(),sustainedDisconnectMs:s=a1}){return()=>{}}function i1(){i.useEffect(()=>o1({hot:void 0,isInIframe:vt()}),[])}async function l1(){Ot("\x1B"),await vr(br),Ot("/clear\r"),await vr(br),Ot("/codeyam-plan\r")}function c1(){fetch("/api/clear-build-agent-session",{method:"POST"}).catch(()=>{})}function d1(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){K("favicon-redraw",{idle:e,hasIcon:!1});return}if(t.current||(t.current=s.href),!e){s.href=t.current,K("favicon-restore",{});return}K("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 u1=120*1e3,gi=1500;class f1{constructor(t,r,s=K){He(this,"deferred",!1);He(this,"userActiveSinceLastOutput",!1);He(this,"lastActivitySource",null);He(this,"lastActivityAt",null);He(this,"lastNotificationTime",null);He(this,"actions");He(this,"env");He(this,"now");He(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<gi;if(r&&s&&c)return this.userActiveSinceLastOutput=!1,this.log("suppressed-user-active",l),"suppressed";if(a!==null&&a<u1)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 p1(e,t){return new f1({playSound:Xa,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 m1(e,t){return e==="hook-stop"?t.idleOnStop:t.idleOnNotification}const h1=600*1e3,x1=3e3;function g1({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(qa),[b,g]=i.useState(!1),y=i.useRef(!1);y.current=b;const w=i.useRef(!1),v=i.useRef(null),x=i.useRef(null),j=i.useRef(null),k=i.useRef(typeof document<"u"&&document.hidden?Date.now():null),N=i.useRef(null),C=i.useRef(s??!1);C.current=s??!1,d1(b),j.current||(j.current=p1(d,x));const S=i.useCallback(P=>{h(P),Ja(P)},[]),R=i.useCallback(P=>{v.current!==null&&(clearTimeout(v.current),v.current=null,K("debounce-cancelled",{trigger:P}))},[]),E=i.useCallback(P=>{y.current&&K("idle-cleared",{trigger:P}),g(!1),y.current=!1,N.current=null,x.current&&(x.current.close(),x.current=null)},[]),A=i.useCallback(P=>{var $;if(!m1(P,m)){K("idle-suppressed-by-pref",{source:P});return}K("ws-idle-received",{buildTabActive:u.current,source:P}),($=f.current)==null||$.call(f),R("re-arm-on-idle"),v.current=setTimeout(()=>{var F;v.current=null;const V=k.current,_=V===null?null:Date.now()-V,X=V!==null&&Date.now()-V>h1;K("debounce-resolved",{suppressedForOvernight:X,msHidden:_,buildTabActive:u.current}),X||(F=j.current)==null||F.onIdle(m,u.current),g(!0),y.current=!0,N.current=Date.now(),w.current=!1,K("agent-currently-idle-set",{suppressedForOvernight:X}),u.current&&We()},gi)},[m,R]),D=i.useCallback(()=>{var P,$,V;(P=p.current)==null||P.call(p),R("agent-active"),($=j.current)==null||$.onActive(),(V=j.current)==null||V.resetActivityFlag(),y.current&&C.current&&N.current!==null&&Date.now()-N.current>x1&&E("remote-resume")},[R,E]),B=i.useCallback(()=>{var P,$;R("user-input"),y.current&&((P=j.current)==null||P.onUserEngagement(),($=j.current)==null||$.reportUserActivity("terminal-input"),w.current=!0,E("user-input"))},[R,E]),T=i.useCallback(P=>{var $;P==="build"&&(R("navigate-build"),y.current&&(($=j.current)==null||$.onUserEngagement(),w.current=!0,E("navigate-build"))),o(P)},[o,R,E]),O=i.useCallback(()=>{var P;R("dismiss-banner"),(P=j.current)==null||P.onUserEngagement(),w.current=!0,E("dismiss-banner")},[R,E]);i.useEffect(()=>{function P(){var Q;y.current&&(w.current||(R("ack-notification"),(Q=j.current)==null||Q.onUserEngagement(),w.current=!0,K("notification-acknowledged",{trigger:"user-return"})))}function $(Q){var q;y.current&&u.current&&document.hasFocus()&&(document.hidden||((q=j.current)==null||q.onUserEngagement(),w.current=!0,E(Q)))}function V(Q){var q;document.hasFocus()&&P(),(q=j.current)==null||q.reportUserActivity(Q)}const _=()=>V("mousemove"),X=()=>V("mousedown"),F=()=>V("keydown");function L(){document.hidden?k.current===null&&(k.current=Date.now()):(k.current=null,P(),$("tab-visible-on-build"))}function M(){var Q;P(),$("window-focus-on-build"),(Q=j.current)==null||Q.reportUserActivity("focus")}return window.addEventListener("focus",M),document.addEventListener("visibilitychange",L),document.addEventListener("mousemove",_),document.addEventListener("mousedown",X),document.addEventListener("keydown",F),()=>{R("unmount"),window.removeEventListener("focus",M),document.removeEventListener("visibilitychange",L),document.removeEventListener("mousemove",_),document.removeEventListener("mousedown",X),document.removeEventListener("keydown",F)}},[R,E]);const Y=i.useRef(a??0);return i.useEffect(()=>{var V;const P=a??0;if(P===Y.current)return;Y.current=P;const $=u.current&&document.hasFocus();K("feature-complete-fast-path",{skipBecauseWatching:$}),!$&&((V=j.current)==null||V.onIdle(m,!1),g(!0),y.current=!0,N.current=Date.now(),w.current=!1)},[a,m]),i.useEffect(()=>{var P,$;if((P=j.current)==null||P.onBuildTabChange(t,m),t)return y.current&&typeof document<"u"&&document.hasFocus()&&!document.hidden&&(($=j.current)==null||$.onUserEngagement(),w.current=!0,E("build-tab-active-on-focus")),We()},[t,m,E]),{buildIdle:b,bannerVisible:b,notifSettings:m,handleSettingsChange:S,handleAgentIdle:A,handleAgentActive:D,handleUserInput:B,handleNavigateToTab:T,dismissIdleBanner:O}}const b1=1e4;function v1(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&&(K("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()},b1);return()=>clearInterval(f)},[l,o]),{buildSessionLive:l,transitionBuildSessionLive:u}}function Na(e){const{isAgentBuilding:t,trigger:r,transitionBuildSessionLive:s}=e;if(t){K("build-session-live-suppress-clear",{trigger:r,reason:"agent-still-active"});return}s(!1,r)}function y1(){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
180
-
181
- ${a.trim()}
182
-
183
- ${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 w1(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(`
184
-
185
- `));return`mailto:${r}?subject=${s}&body=${a}`}const j1=["bug","suggestion","question","praise"];function k1({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}=y1(),m=i.useCallback(()=>{p(r)},[p,r]),h=i.useCallback(()=>{navigator.clipboard.writeText("feedback@codeyam.com").then(()=>{c(!0),setTimeout(()=>c(!1),2e3)})},[]),b=i.useCallback(g=>{o(y=>y===g?null:g)},[]);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:j1.map(g=>{const y=a===g;return n.jsx("button",{type:"button","aria-pressed":y,onClick:()=>b(g),className:"px-2.5 py-1 rounded-full text-xs transition cursor-pointer",style:{background:y?"var(--accent-active)":"transparent",color:y?"var(--bg-deep)":"var(--text-secondary)",border:"1px solid var(--border-default)"},children:g},g)})})]}),n.jsx("textarea",{value:r,onChange:g=>s(g.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:w1(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 N1({sha:e,onClick:t}){if(!e)return null;const r=e.slice(0,6),s="font-mono text-[11px] leading-none px-1.5 py-0.5 rounded border border-white/5 bg-black/55 backdrop-blur-sm hover:bg-black/75";return n.jsx("div",{className:`fixed bottom-1 left-1 z-30 ${t?"":"pointer-events-none"}`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:t?n.jsx("button",{type:"button",onClick:t,"data-testid":"build-sha-badge",title:e,"aria-label":`Build commit ${e}`,className:`cursor-pointer ${s}`,style:{color:"var(--text-secondary)"},children:r}):n.jsx("span",{"data-testid":"build-sha-badge",title:e,"aria-label":`Build commit ${e}`,className:s,style:{color:"var(--text-secondary)"},children:r})})}function C1(){return`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/raw-terminal`}function S1(){if(vt())return null;const e=i.useRef(null),t=i.useRef(null),r=i.useRef(null),s=i.useRef(null),a=i.useRef(!1),[o,l]=i.useState(!1),[c,d]=ao(1200);function u(f){const p=s.current;(p==null?void 0:p.readyState)===WebSocket.OPEN&&p.send(new TextEncoder().encode(f))}return so(e,()=>{if(r.current&&t.current){r.current.fit();const f=s.current;(f==null?void 0:f.readyState)===WebSocket.OPEN&&f.send(JSON.stringify({type:"resize",cols:t.current.cols,rows:t.current.rows}))}}),i.useEffect(()=>{if(!e.current||a.current)return;a.current=!0;const f=new Sa.Terminal({cursorBlink:!0,fontSize:13,fontFamily:"'IBM Plex Mono', monospace",rightClickSelectsWord:!1,theme:{background:"#1e1e1e",foreground:"#cccccc",cursor:"#D7FF63",selectionBackground:"#264f78"}}),p=new Ea.FitAddon;f.loadAddon(p),f.open(e.current),t.current=f,r.current=p;const m=Ra(f,e.current,{onCopy:()=>d()}),h=Ta(f,{sendInput:u});requestAnimationFrame(()=>{p.fit(),f.focus()});const b=new WebSocket(C1());return s.current=b,b.binaryType="arraybuffer",b.onmessage=g=>{g.data instanceof ArrayBuffer&&f.write(new Uint8Array(g.data))},b.onopen=()=>{b.send(JSON.stringify({type:"resize",cols:f.cols,rows:f.rows}))},b.onclose=()=>{l(!0),f.writeln(`\r
186
- \x1B[90m[Shell session ended]\x1B[0m`)},f.onData(u),()=>{var g;(g=s.current)==null||g.close(),h(),m(),f.dispose(),a.current=!1}},[]),n.jsxs("div",{className:"relative flex-1 flex flex-col",style:{minHeight:0},children:[n.jsx("div",{ref:e,className:"flex-1",style:{background:"#1e1e1e",minHeight:0,paddingTop:3,paddingLeft:3},onClick:()=>{var f;return(f=t.current)==null?void 0:f.focus()}}),o&&n.jsx("div",{role:"alert",className:"absolute bottom-2 left-2 rounded px-2 py-1 text-[11px]",style:{background:"var(--bg-card)",color:"var(--text-secondary)",border:"1px solid var(--border-subtle)"},children:"Shell disconnected — close and reopen for a fresh shell."}),c&&n.jsx(oo,{})]})}function E1({isOpen:e,onClose:t}){return i.useEffect(()=>{if(!e)return;const r=s=>{s.key==="Escape"&&t()};return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[e,t]),e?n.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"raw-terminal-modal-title",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onMouseDown:r=>{r.target===r.currentTarget&&t()},children:n.jsxs("div",{className:"flex flex-col rounded-lg shadow-xl",style:{width:"80vw",height:"80vh",maxWidth:1200,maxHeight:800,background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-[var(--border-default)]",children:[n.jsx("h2",{id:"raw-terminal-modal-title",className:"text-sm font-semibold text-[var(--text-primary)] m-0",children:"Terminal"}),n.jsx("button",{type:"button",onClick:t,"data-testid":"raw-terminal-modal-close","aria-label":"Close terminal",className:"text-sm text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer",children:"✕"})]}),n.jsx("div",{className:"flex-1 flex flex-col",style:{minHeight:0},children:n.jsx(S1,{})})]})}):null}let or=null;function R1(e){if(typeof e!="object"||e===null)return null;const t=e.buildCommitSha;return typeof t!="string"||t===""||t==="unknown"?null:t}async function T1(){try{const e=await fetch("/api/health");return e.ok?R1(await e.json()):null}catch{return null}}function P1(){const[e,t]=i.useState(null);return i.useEffect(()=>{let r=!0;return or||(or=T1()),or.then(s=>{r&&t(s)}),()=>{r=!1}},[]),{sha:e}}function D1(){var ms,hs;i1();const{sha:e}=P1(),t=El(),{state:r,provider:s,credsPresent:a,reason:o,expiresAt:l,probeInFlight:c,backendFieldAbsent:d,refresh:u}=wl(),{sessionInfo:f,refetch:p}=Mo({pollIntervalMs:15e3}),m=(f==null?void 0:f.agentBrokerLive)??!1,h=Qy(r,m),{activeTab:b,buildActivated:g,planActivated:y,navigateToTab:w,showBuildTab:v}=Qr(t,h,r==="needs-login"&&!m),[x,j]=i.useState(!1),[k,N]=i.useState(!1),[C,S]=i.useState(0),[R,E]=i.useState(0),[A,D]=i.useState(0),{showPostPushModal:B,onFeatureCompleteCommand:T,onAgentIdle:O,onAgentActive:Y,dismissModal:P}=Hy(),{showPlanCompleteModal:$,onPlanCompleteCommand:V,dismissPlanCompleteModal:_}=Wy(),[X,F]=i.useState(!1),[L,M]=i.useState(!1),[Q,q]=i.useState(!1),[W,z]=i.useState(!1),J=i.useCallback(()=>{q(!0)},[]),U=i.useCallback(()=>{q(!1)},[]),{plans:se,loading:ie,error:I,refetch:ne}=Yr(),{reorderPlans:le}=Uo(ne),{launchPlan:Z,launchingSlug:de,error:we}=Zr(),{launchPrompt:ce,launching:re,error:Be}=Vy(),[Te,qe]=i.useState(!1),{stepState:G}=qt(),ut=i.useRef(null),{leftWidth:yt,handleMouseDown:Oe}=r1(ut),Ce=s1(768),[Pe,wt]=i.useState("editor"),be=i.useCallback(ee=>{wt(ee),ee==="editor"&&(We(),typeof window<"u"&&window.dispatchEvent(new Event("resize")))},[]),Je=Ce?((ms=ut.current)==null?void 0:ms.clientWidth)??(typeof window<"u"?window.innerWidth:yt):yt,{entityLookup:Le}=Cy(),{groups:je,loading:Xe,refreshing:Qe,currentRunner:Se,coverage:Ze,refresh:Ue}=uy(),{groups:ye,loading:Dt,reload:ue}=oy(),{routeEntities:me,loading:he,error:Ee}=iy(),{config:H,apps:ae,loading:fe,refetch:xe}=dt(),oe=i.useMemo(()=>Ky(ae,je,ye),[ae,ye,je]),De=i.useCallback(()=>{j(ee=>!ee)},[]),Ae=i.useCallback(()=>{N(ee=>!ee)},[]),{selectedApp:ve,appRouteEntities:et,appTestGroups:ft,selectedEntityHash:ze,selectedRouteEntity:tt,previewSlug:Me,setPreviewSlugExplicit:bi,selectApp:An,deselectApp:as,selectRoute:Fn,selectEntity:vi,deselectRoute:yi}=jy(ae,me,ye,je,t),{viewports:wi,resolvedViewport:Ln,previewUrl:ji,emptyStateMessage:ki,handleViewportChange:Ni,handleCustomSizeChange:Ci,showScenarioPreview:Xt,handlePreviewCommand:Ie,setPreviewPath:Mn,previewSeeding:Si,previewSeedError:Ei,commandNonce:Ri}=_y({apps:ae,appRouteEntities:et,configLoaded:!fe,port:(H==null?void 0:H.port)??5173,previewOrigin:va(H,ve),projectTitle:(H==null?void 0:H.projectTitle)??null,routeEntities:me,screenSizes:(H==null?void 0:H.screenSizes)??{},defaultScreenSize:(H==null?void 0:H.defaultScreenSize)??null,scenarioGroups:ye,scenariosLoaded:!Dt,selectedApp:ve,selectedRouteEntity:tt,previewSlug:Me,setPreviewSlug:bi}),{isAgentBuilding:At,isAgentBuildingRef:In,buildingScenarioSlug:$n,onAgentIdle:os,onAgentActive:is,guardScenarioSelect:ls,clearBuildingOverlay:nt}=Uy({onTransitionToLive:Xt}),Bn=(f==null?void 0:f.resumeMode)==="resume"||(f==null?void 0:f.resumeMode)==="handoff",{buildSessionLive:On,transitionBuildSessionLive:Ft}=v1({isAgentBuilding:At,submittingBuildPrompt:re,launchingPlanSlug:de,sessionInfo:f,refetchSessionInfo:p});i.useEffect(()=>{qr({hasActiveSession:Bn,isAgentBuilding:At,stepStateFeature:(G==null?void 0:G.feature)??null})},[Bn,At,G==null?void 0:G.feature]),i.useEffect(()=>{const ee=H==null?void 0:H.projectTitle;document.title=typeof ee=="string"&&ee.length>0?`CodeYam: ${ee}`:"CodeYam"},[H==null?void 0:H.projectTitle]);const Ti=i.useCallback(()=>{O(),os()},[O,os]),Pi=i.useCallback(()=>{Y(),is()},[Y,is]),Qt=(H==null?void 0:H.provider)??jl,Di=lt(Qt),{buildIdle:cs,bannerVisible:Ai,notifSettings:ds,handleSettingsChange:us,handleAgentIdle:Fi,handleAgentActive:Li,handleUserInput:Mi,handleNavigateToTab:Ii,dismissIdleBanner:$i}=g1({agentName:Di,isBuildTabActive:b==="build",isAgentBuilding:At,buildSessionLive:On,featureCompleteKey:A,navigateToTab:w,onAgentIdleImmediate:Ti,onAgentActiveImmediate:Pi}),fs=i.useCallback(ee=>{ls(ee)||Xt(ee)},[ls,Xt]),jt=i.useMemo(()=>Cr($n,ye),[$n,ye]),Bi=((hs=jt==null?void 0:jt.screenshotPaths)==null?void 0:hs[0])??null,Oi=(jt==null?void 0:jt.name)??null,zi=i.useCallback(ee=>{switch(ee.type){case"preview":("scenarioSlug"in ee||"scenarioId"in ee)&&ue(),Ie(ee);break;case"showResults":nt(),ue(),S(_e=>_e+1),(G==null?void 0:G.mode)==="backend"&&Ie({path:"/results",dimension:"Desktop"});break;case"hideResults":E(_e=>_e+1);break;case"featureComplete":nt(),T(),D(_e=>_e+1),xe(),Na({isAgentBuilding:In.current,trigger:"feature-complete",transitionBuildSessionLive:Ft});break;case"planComplete":V(),xe(),Na({isAgentBuilding:In.current,trigger:"plan-complete",transitionBuildSessionLive:Ft});break}},[nt,Ie,In,T,V,xe,ue,G,Ft]);Ny(zi);const Zt=(G==null?void 0:G.slug)==="ui-confirm-plan"||(G==null?void 0:G.slug)==="backend-confirm-plan",zn=i.useRef(null);i.useEffect(()=>{if(!G||!Zt){zn.current=null;return}zn.current!==G.step&&(zn.current=G.step,Ie({path:"/plan-preview",dimension:"Desktop"}))},[G,Zt,Ie]);const _n=i.useRef(null);i.useEffect(()=>{if(!G||G.mode!=="backend"||G.step<2||Zt){_n.current=null;return}_n.current!==G.step&&(_n.current=G.step,Ie({path:"/results",dimension:"Desktop"}))},[G,Zt,Ie]);const Hn=i.useRef(!1);i.useEffect(()=>{(G==null?void 0:G.slug)==="ui-confirm-plan"?Hn.current=!0:Hn.current&&(Hn.current=!1,Mn(null))},[G,Mn]);const _i=i.useCallback(async()=>{P(),await Dh({provider:Qt,renameLabel:(G==null?void 0:G.feature)??void 0,caller:"post-push-modal",bypassLiveGuard:!0}),We()},[P,Qt,G]),Hi=i.useCallback(()=>{P(),We()},[P]),Wi=i.useCallback(async()=>{await Ph(),P(),Ft(!1,"stop-building"),nt(),p()},[P,Ft,nt,p]),Vi=i.useCallback(()=>{l1(),_(),We()},[_]),Ui=i.useCallback(()=>{F(!1),c1(),_()},[_]),Ki=i.useCallback(()=>{M(!0)},[]),Gi=i.useCallback(()=>{M(!1)},[]),Yi=i.useCallback(async(ee,_e)=>{await Z(ee,_e)&&(M(!1),qe(!0),P(),p())},[Z,P,p]),qi=i.useCallback(async ee=>{await ce(ee)&&(qe(!0),p())},[ce,p]),Ji=i.useCallback(()=>{qe(!0)},[]),ps=Zy({activeTab:b,hasActiveSession:Bn,isAgentBuilding:At,showPostPushModal:B,launchingPlanSlug:de,submittingBuildPrompt:re,stepStateFeature:(G==null?void 0:G.feature)??null,pendingPlanCount:se.length,buildLaunchModalDismissed:Te}),Xi=ps||L;i.useEffect(()=>{b==="build"&&p()},[b,p]),i.useEffect(()=>{b==="home"&&(xe(),u())},[b,xe,u]);const Qi=i.useCallback(async(ee,_e)=>{nt(),Ie(Xy(ee,_e))},[nt,Ie]),Zi=i.useCallback(ee=>{(ee.scenarioSlug||ee.path)&&Ie({...ee.scenarioSlug?{scenarioSlug:ee.scenarioSlug}:{},...ee.path?{path:ee.path}:{},...ee.dimension?{dimension:ee.dimension}:{}})},[Ie]),el=i.useMemo(()=>({apps:ae,isSingleApp:ae.length===1,onSelectApps:as,onSelectApp:An,onSelectRoute:Fn}),[ae,as,An,Fn]),tl=i.useMemo(()=>ve?oe.find(ee=>ee.app.dir===ve.dir)??null:null,[oe,ve]),nl=n.jsxs(n.Fragment,{children:[n.jsx(_o,{staleness:null,backendOutOfDate:d}),n.jsx(t1,{state:r,provider:s,credsPresent:a,reason:o,expiresAt:l,probeInFlight:c,backendOutOfDate:d,sessionOngoing:m,onAuthenticated:u,onAuthorized:()=>w("build")}),oe.length>0&&n.jsx(Ud,{settings:ds,onChange:us}),n.jsx(dh,{selectedApp:ve,appDetailProps:{navContext:el,routeEntities:et,routesLoading:he,routesError:Ee,selectedEntityHash:ze,selectedRouteEntity:tt,testGroups:ft,selectedSlug:Me,entityLookup:Le,allScenarios:ye.flatMap(ee=>ee.scenarios),onSelectScenario:fs,onSelectRoute:Fn,onSelectEntity:vi,onBackToRoutes:yi,onScenariosChanged:ue,projectTitle:(H==null?void 0:H.projectTitle)??null,coverage:Ze,showProjectBand:ae.length===1,stats:tl,testsLoading:Xe,testsRefreshing:Qe,onRunTests:Ue,currentRunner:Se},appOverviewProps:{projectTitle:(H==null?void 0:H.projectTitle)??"Project",projectDescription:(H==null?void 0:H.projectDescription)??null,stats:oe,coverage:Ze,onSelectApp:An,configLoading:fe,testsLoading:Xe,testsRefreshing:Qe,onRunTests:Ue,currentRunner:Se,stepState:G,onPreviewUrl:Mn,onComplete:async()=>{await xe(),w("build")},onOpenBuildTab:()=>w("build")}})]});return n.jsxs(n.Fragment,{children:[n.jsx(hh,{splitRef:ut,isCollapsed:x,onResizeStart:Oe,isNarrow:Ce,mobilePane:Pe,onMobilePaneChange:be,isAgentBuilding:On,buildIdle:cs,leftPane:n.jsx(Sx,{activeTab:b,onSendTranscript:J,appTabContent:nl,awaitingPlanLaunchChoice:Xi,buildActivated:g,planActivated:y,buildIdle:cs,isAgentBuilding:On,bannerVisible:Ai,onDismissIdleBanner:$i,hideResultsCommandKey:R,leftWidth:Je,fullWidth:Ce,navigateToTab:Ii,onAgentActive:Li,onAgentIdle:Fi,onUserInput:Mi,notifSettings:ds,onSettingsChange:us,provider:Qt,onRestorePreview:Zi,onResultsScenarioSelect:Qi,previewSlug:Me,onSessionDetected:v,showPostPushModal:B,onStartNextFeature:_i,onContinueInSession:Hi,onStopBuilding:Wi,showResultsCommandKey:C,planChatOpen:X,onPlanChatOpenChange:F,showPlanCompleteModal:$,onCreateNewPlan:Vi,onViewPlans:Ui,pendingPlans:se,onSelectPlan:Ki,selectPlanOpen:L,onPickPlan:Yi,onCancelSelectPlan:Gi,launchingPlanSlug:de,planLaunchError:we,showBuildLaunchModal:ps,onSubmitBuildPrompt:qi,submittingBuildPrompt:re,buildPromptError:Be,onCancelBuildLaunchModal:Ji,pendingPlansLoading:ie,pendingPlansError:I,onReorderPlans:le,buildDisabled:h}),previewPane:n.jsx(ay,{emptyStateMessage:Jy({configLoading:fe,hasNoApps:oe.length===0,hasStepState:!!G,defaultMessage:ki}),firstSessionSetup:oe.length===0&&!!G,previewSlug:Me,previewUrl:ji,viewports:wi,activeViewport:Ln.name,onViewportChange:Ni,isCollapsed:x,onToggleCollapsed:De,isNarrow:Ce,isFilled:k,onToggleFilled:Ae,currentWidth:Ln.width,currentHeight:Ln.height,onCustomSizeChange:Ci,buildingScenarioSlug:$n,buildingScreenshotPath:Bi,buildingScenarioName:Oi,onDismissBuildingOverlay:nt,previewSeeding:Si,previewSeedError:Ei,onRetrySeed:()=>{Me&&Xt(Me)},currentScenario:Cr(Me,ye),scenarioGroups:ye,onShowScenarioPreview:fs,commandNonce:Ri,previewOrigin:va(H,ve),onDesignConfirmed:()=>w("build")})}),Q?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(k1,{featureName:(G==null?void 0:G.feature)??null,onClose:U})}):null,n.jsx(E1,{isOpen:W,onClose:()=>z(!1)}),n.jsx(N1,{sha:e,onClick:()=>z(!0)})]})}const z1=Object.freeze(Object.defineProperty({__proto__:null,EditorShell:D1},Symbol.toStringTag,{value:"Module"}));export{Yv as $,Vl as A,Ul as B,Wa as C,Wl as D,qm as E,zl as F,Hl as G,Io as H,b0 as I,Gl as J,Ac as K,Dc as L,Pc as M,Ba as N,N1 as O,Gb as P,$o as Q,Pv as R,ad as S,rd as T,Mv as U,$v as V,Bv as W,Ov as X,Iv as Y,_v as Z,Av as _,wc as a,Nx as a$,Vv as a0,Wv as a1,Kv as a2,Gv as a3,Uv as a4,Qd as a5,Xd as a6,qd as a7,Yd as a8,Gd as a9,ag as aA,Pm as aB,Mm as aC,Lb as aD,ii as aE,Mb as aF,Bb as aG,Ab as aH,Db as aI,Pb as aJ,la as aK,_b as aL,zb as aM,ig as aN,Ob as aO,Fb as aP,Ib as aQ,Hb as aR,sf as aS,rf as aT,S1 as aU,E1 as aV,af as aW,yx as aX,vx as aY,Cx as aZ,kx as a_,Jd as aa,Al as ab,Pl as ac,Rl as ad,gs as ae,Tl as af,oh as ag,eh as ah,th as ai,nh as aj,ah as ak,rh as al,sh as am,ih as an,lh as ao,qx as ap,Gx as aq,Oo as ar,Gr as as,Yx as at,zo as au,Jt as av,Ka as aw,Kx as ax,Ux as ay,Vx as az,Kn as b,Fc as b$,bx as b0,Lr as b1,lx as b2,cx as b3,dx as b4,om as b5,sx as b6,rx as b7,nx as b8,ax as b9,Bh as bA,Yh as bB,Gh as bC,Fh as bD,fx as bE,xx as bF,Eb as bG,Sb as bH,Vn as bI,Il as bJ,nc as bK,Xl as bL,oc as bM,D1 as bN,ia as bO,Cb as bP,Dl as bQ,yc as bR,Mc as bS,Ic as bT,Lc as bU,mx as bV,Em as bW,Rm as bX,Kl as bY,Fa as bZ,Tc as b_,ox as ba,Jh as bb,Xh as bc,Kr as bd,Ih as be,Mh as bf,Lh as bg,am as bh,rm as bi,Qp as bj,nm as bk,Xp as bl,sm as bm,em as bn,Zp as bo,tm as bp,qp as bq,Lo as br,Do as bs,Ko as bt,Hh as bu,Vh as bv,Gs as bw,zh as bx,Kh as by,qh as bz,O1 as c,Rg as c$,La as c0,Sc as c1,Nc as c2,kc as c3,jc as c4,Cc as c5,Ec as c6,hc as c7,bc as c8,gc as c9,I0 as cA,$0 as cB,kb as cC,U0 as cD,V0 as cE,Vb as cF,Wb as cG,Ub as cH,og as cI,Jb as cJ,Kb as cK,M0 as cL,Sm as cM,fh as cN,Mt as cO,ju as cP,wu as cQ,no as cR,Nb as cS,jb as cT,fb as cU,vb as cV,gb as cW,lb as cX,sb as cY,db as cZ,ub as c_,mc as ca,xc as cb,cc,lc as cd,Da as ce,vs as cf,Vc as cg,Uc as ch,zc as ci,ed as cj,Wc as ck,Oc as cl,Bc as cm,bs as cn,Wn as co,$c as cp,it as cq,ku as cr,ty as cs,ry as ct,X0 as cu,q0 as cv,ay as cw,N0 as cx,_0 as cy,H0 as cz,Dr as d,Tm as d$,bu as d0,vu as d1,xu as d2,hu as d3,fu as d4,Ru as d5,Eu as d6,Cd as d7,kd as d8,yd as d9,Iu as dA,Mu as dB,Jm as dC,Qm as dD,Gm as dE,Km as dF,d0 as dG,f0 as dH,l0 as dI,i0 as dJ,o0 as dK,p0 as dL,c0 as dM,a0 as dN,u0 as dO,r0 as dP,n0 as dQ,Pr as dR,tc as dS,Aa as dT,of as dU,Xu as dV,lm as dW,_u as dX,Du as dY,Um as dZ,Pu as d_,vd as da,bd as db,gd as dc,hx as dd,ks as de,Od as df,Ud as dg,Mr as dh,Hd as di,Rd as dj,Ga as dk,Dd as dl,Fr as dm,Cm as dn,mh as dp,gx as dq,px as dr,Sx as ds,hh as dt,uh as du,dh as dv,Bu as dw,Qn as dx,zu as dy,$u as dz,nd as e,Tu as e0,td as e1,Fl as e2,t1 as e3,z1 as e4,Ha as f,k1 as g,mt as h,g0 as i,w0 as j,v0 as k,x0 as l,k0 as m,vv as n,m0 as o,Ia as p,ln as q,Ge as r,tg as s,Zx as t,Qx as u,Xx as v,Jx as w,ng as x,G0 as y,K0 as z};