@codeyam-editor/codeyam-editor 0.1.0-staging.01efa1a
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/npm/cli.js +19 -0
- package/npm/cloud-branch-switch.js +442 -0
- package/npm/cloud.js +2184 -0
- package/npm/container.js +54 -0
- package/npm/editor-dev.js +459 -0
- package/npm/editor.js +272 -0
- package/npm/empty-project-dir.js +33 -0
- package/npm/fleet-auth.js +111 -0
- package/npm/fleet-branch.js +49 -0
- package/npm/fleet-broker-death.js +44 -0
- package/npm/fleet-broker-debounce.js +63 -0
- package/npm/fleet-broker-status.js +45 -0
- package/npm/fleet-build-data.js +81 -0
- package/npm/fleet-cleanup.js +297 -0
- package/npm/fleet-effect-status.js +179 -0
- package/npm/fleet-env.js +125 -0
- package/npm/fleet-grouping.js +56 -0
- package/npm/fleet-job-badge.js +83 -0
- package/npm/fleet-memory.js +157 -0
- package/npm/fleet-plans.js +96 -0
- package/npm/fleet-pool-policy.js +78 -0
- package/npm/fleet-pool.js +401 -0
- package/npm/fleet-queue.js +40 -0
- package/npm/fleet-reconcile.js +93 -0
- package/npm/fleet-reset.js +222 -0
- package/npm/fleet-roster.js +81 -0
- package/npm/launch-config.js +717 -0
- package/npm/open.js +15 -0
- package/npm/preflight-guidance.js +77 -0
- package/npm/scenario-check.js +604 -0
- package/npm/scenario-handlers.js +82 -0
- package/npm/scenario-interactivity.js +245 -0
- package/npm/scenario-issues.js +35 -0
- package/npm/scenario-metrics.js +108 -0
- package/npm/scenario-mocks.js +107 -0
- package/npm/scenario-playwright.js +534 -0
- package/npm/utils.js +823 -0
- package/npm/vm-urls.js +117 -0
- package/package.json +32 -0
- package/ui/dist/assets/ContainerInspector-C8EkH4PP.js +2 -0
- package/ui/dist/assets/EditorShell-By-2rl7D.js +187 -0
- package/ui/dist/assets/Markdown-BHBqz-Mj.js +1 -0
- package/ui/dist/assets/ScenarioDataPanel-Cg8zOFNZ.js +5 -0
- package/ui/dist/assets/ScenarioDataPanel-DYP7pi_n.css +32 -0
- package/ui/dist/assets/ScenarioDataPanelFullPage-WOUYbba7.js +1 -0
- package/ui/dist/assets/ScenarioRenderer-CBTlIVPs.js +1 -0
- package/ui/dist/assets/StepsSimulator-CRtmlyNZ.js +1 -0
- package/ui/dist/assets/index-DzoF9RKw.js +27 -0
- package/ui/dist/assets/index-ckz94rKI.css +1 -0
- package/ui/dist/assets/markdown-v0F0UEt3.js +37 -0
- package/ui/dist/assets/react-CSS0HapR.js +28 -0
- package/ui/dist/assets/useEvents-DggWrtHe.js +1 -0
- package/ui/dist/assets/xterm--24IGk-x.js +9 -0
- package/ui/dist/favicon.ico +0 -0
- package/ui/dist/favicon.png +0 -0
- package/ui/dist/index.html +16 -0
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
var cl=Object.defineProperty;var dl=(e,t,r)=>t in e?cl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var _e=(e,t,r)=>dl(e,typeof t!="symbol"?t+"":t,r);import{j as n}from"./markdown-v0F0UEt3.js";import{b as i,R as Ee,c as kt}from"./react-CSS0HapR.js";import{S as ul,a0 as ot,a1 as st,_ as Sn,a2 as ir,a3 as gn,a4 as Ea,a5 as Ra,a6 as Pa,a7 as Ta,a8 as Da,W as fl,a9 as pl,aa as ml,ab as hl,ac as xl,ad as Sr,f as gl,ae as bl,e as Aa,af as vl,ag as yl,ah as wl,h as jl,ai as bs,aj as kl,ak as Nl,$ as Cl,Z as Sl,al as El,am as Rl}from"./ScenarioDataPanel-Cg8zOFNZ.js";import{e as Pl,a as Tl,g as Er,d as Dl,l as U,p as Lt,t as Al,u as Fl}from"./index-DzoF9RKw.js";import{M as pt}from"./Markdown-BHBqz-Mj.js";function vs({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 Ll({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 Fa({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(Ll,{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(vs,{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(vs,{onRunTests:s})]}):n.jsx("span",{className:"text-xs text-[var(--text-dim)]",children:"No tests"})}function Ml({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(Fa,{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 La({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 Il({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(La,{type:e.type})]}),e.description?n.jsx("p",{className:"text-sm text-[var(--text-muted)] leading-relaxed",children:e.description}):null]})}function Ue(e,t){if(e.startsWith("http"))return e;const r=`/api/screenshots/${e}`;return typeof t=="number"?`${r}?cb=${t}`:r}function $l({thumbnails:e}){return n.jsx("div",{className:"flex gap-2 overflow-hidden",children:e.map((t,r)=>n.jsx("img",{src:Ue(t.path,t.cacheBuster),alt:"",className:"h-20 w-32 rounded border border-[var(--border-default)] object-cover object-top"},`${t.path}:${r}`))})}function Bl({thumbnails:e}){return n.jsx("div",{className:"px-5 py-3 flex-1",children:e.length>0?n.jsx($l,{thumbnails:e.slice(0,4)}):n.jsx("div",{className:"h-20"})})}function Ol({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(Il,{app:l}),n.jsx(Bl,{thumbnails:d.thumbnails}),n.jsx(Ml,{tests:c,loading:r,refreshing:s,onRunTests:a,currentRunner:o})]})}const mt={apps:[],isSingleApp:!1,onSelectApps:()=>{},onSelectApp:()=>{},onSelectRoute:()=>{}};function En(e){return e.scenarioType==="application"||e.scenarioType==="component"?e.scenarioType:e.componentName?"component":"application"}function St(e){return En(e)==="application"}function Rr(e){return En(e)==="component"}function Pr(e){return{overrideCounts:{mocks:0,seeds:0,inheritedMocks:0,inheritedSeeds:0},...e,scenarioType:En(e)}}function ht(){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 _l(e){const[t,r]=i.useState({status:"idle"}),{scenariosVersion:s}=ht();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(Pr):[]};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 ys(){return n.jsx("div",{className:"px-5 py-8 text-center text-[var(--text-dim)]",children:"Loading routes..."})}function zl(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 Hl({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(Hl,{entityRef:r,onNavigate:t})},r.hash))})}function Wl(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 Vl(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 Ul({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 Kl({overrideCounts:e}){const t=e?Ul(e):null;return t?n.jsx("div",{className:"text-xs text-[var(--text-dim)] mt-1",children:t}):null}const Gl=new Set(["Desktop"]);function Yl({scenario:e,isSelected:t}){const r=e.dimensions.length>0&&!(e.dimensions.length===1&&Gl.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(Kl,{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 ql({screenshotPath:e,cacheBuster:t}){const[r,s]=i.useState(!1);return e&&!r?n.jsx("img",{src:Ue(e,t),alt:"",className:"h-[180px] w-[288px] rounded border border-[var(--border-subtle)] bg-[var(--bg-card)] object-cover object-top shrink-0",onError:()=>s(!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 Jl({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 Xl({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 Ql({scenario:e,isSelected:t,onSelect:r,onViewData:s,onScenariosChanged:a,children:o}){const l=Wl(e.slug,e.name,a),{deleting:c,handleDelete:d}=Vl(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(ql,{screenshotPath:e.screenshotPaths[0]??null,cacheBuster:e.screenshotCapturedAtMs}),n.jsx("div",{className:"flex-1 min-w-0",children:l.renaming?n.jsx(Xl,{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(Yl,{scenario:e,isSelected:t}),t&&n.jsx(Jl,{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 Zl(){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 Ma({scenarios:e,selectedSlug:t,onSelectScenario:r,onScenariosChanged:s}){const[a,o]=i.useState(null);return e.length===0?n.jsx(Zl,{}):n.jsx("div",{className:"grid grid-cols-1 gap-2",children:e.map(l=>n.jsx(Ql,{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(ul,{variant:"inline",slug:l.slug,scenarioName:l.name,onClose:()=>o(null)})},l.slug))})}const ec="This component renders no other tracked components.",tc="This component imports no tracked functions.",nc="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 rc({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:zl(t)}):n.jsx(Ma,{scenarios:t.scenarios,selectedSlug:a,onSelectScenario:o,onScenariosChanged:c})),e==="components"&&(r.length===0?n.jsx(en,{copy:ec}):n.jsx(Vn,{refs:r,onNavigate:l})),e==="functions"&&(s.length===0?n.jsx(en,{copy:tc}):n.jsx(Vn,{refs:s,onNavigate:l})),e==="callers"&&(t.callers.length===0?n.jsx(en,{copy:nc}):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 sc(e){return typeof e!="string"&&typeof e.onClick=="function"}function ac(e){return typeof e=="string"?e:e.label}function oc(e,t){(e.key==="Enter"||e.key===" ")&&(e.preventDefault(),t())}function ic({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=ac(r),o=s===t,l=!o&&sc(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=>oc(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 Tr({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(ic,{segments:d})}function lc({entity:e,app:t=null,routeEntity:r=null,navContext:s=mt}){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(Tr,{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 cc=["scenarios","components","functions"];function Ia({activeTab:e,onTabChange:t,scenarioCount:r,componentCount:s=0,functionCount:a=0,callersCount:o=0,tabs:l=cc}){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 dc=["scenarios","components","functions"],uc=["scenarios","callers"];function fc({app:e=null,navContext:t=mt,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=[],g=[];for(const b of s.directImports)b.kind==="function"?g.push(b):h.push(b);return{componentRefs:h,functionRefs:g}},[s.directImports]),m=s.kind==="function"?uc:dc;return n.jsxs("div",{className:"flex flex-col",children:[n.jsx(lc,{app:e,navContext:t,routeEntity:r,entity:s}),n.jsx(Ia,{activeTab:d,onTabChange:u,scenarioCount:s.scenarios.length,componentCount:f.length,functionCount:p.length,callersCount:s.callers.length,tabs:m}),n.jsx(rc,{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 xt(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}function pc(e){const t=[],r=[];for(const s of e){const a=xt(s);/^[A-Z]/.test(a)&&!a.startsWith("use")?t.push(s):r.push(s)}return{componentImports:t,functionImports:r}}function mc({ancestor:e,onNavigateToEntity:t}){const r=t?()=>t(Vt(e.filePath,xt(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 hc({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(mc,{ancestor:r,onNavigateToEntity:t},`${r.kind}:${r.filePath}`))})]})}function xc({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&&xt(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 gc(e){const t=new Map;for(const[r,s]of Object.entries(e)){const a=fn(r),o=xt(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 bc(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 $a(e,t){if(!e)return[];const r=[];for(const s of t){const a=bc(e,s);a&&r.push(a)}return r}function vc(e,t){return e.find(r=>r.pageFilePath===t)??null}function Ba(e){const t=e.split("/"),r=t.pop()??e,s=t.join("/");return{fileName:r,dirPath:s}}function yc({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 wc({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:Ue(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 jc({importPath:e,entity:t,scenarios:r,onNavigate:s,onSelectScenario:a}){const{fileName:o,dirPath:l}=Ba(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(yc,{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(wc,{scenarios:r,onSelectScenario:a})]})}function kc(){return n.jsx("p",{className:"py-4 text-center text-xs text-[var(--text-dim)]",children:"No dependencies found"})}function Nc({directImports:e,entityLookup:t,allScenarios:r,routeEntities:s,onNavigateToRoute:a,onNavigateToEntity:o,onSelectScenario:l}){const c=i.useMemo(()=>$a(t,e),[t,e]);return e.length===0?n.jsx(kc,{}):n.jsx("div",{className:"grid grid-cols-1 gap-1",children:e.map(d=>{const u=c.find(b=>b.filePath===d)??null,f=(u==null?void 0:u.entityName)??xt(d),p=xc({importPath:d,derivedName:f,allScenarios:r??[],routeEntities:s??[]}),m=vc(s??[],d),h=Vt(d,f),g=m?()=>a(m.route):o?()=>o(h):null;return n.jsx(jc,{importPath:d,entity:u,scenarios:p,onNavigate:g,onSelectScenario:l},d)})})}function Cc(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 Sc({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 Ec({test:e}){const t=e.description.length>0;return n.jsxs("div",{className:"flex items-start gap-2 py-1",children:[n.jsx(Sc,{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 Rc({importPath:e,entityName:t,tests:r,onNavigate:s}){const{dirPath:a}=Ba(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(Ec,{test:o},`${o.file}:${o.key??o.line??l}`))}):n.jsx("p",{className:"text-xs text-[var(--text-dim)] italic",children:"No tests"})})]})}function Pc(){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 Tc({functionImports:e,entityLookup:t,testGroups:r,onNavigateToEntity:s}){const a=i.useMemo(()=>$a(t,e),[t,e]);return e.length===0?n.jsx(Pc,{}):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)??xt(o),d=Cc(o,t,r),u=s?()=>s(Vt(o,c)):null;return n.jsx(Rc,{importPath:o,entityName:c,tests:d,onNavigate:u},o)})})}function Dc({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(Ma,{scenarios:t.scenarios,selectedSlug:o,onSelectScenario:u,onScenariosChanged:m}),e==="components"&&n.jsx(Nc,{directImports:r,entityLookup:l,allScenarios:c,routeEntities:d,onNavigateToRoute:f,onNavigateToEntity:p,onSelectScenario:u}),e==="functions"&&n.jsx(Tc,{functionImports:s,entityLookup:l,testGroups:a,onNavigateToEntity:p})]})}function Ac({displayName:e,pageFilePath:t,app:r=null,routeEntity:s=null,navContext:a=mt}){return n.jsxs("div",{className:"px-5 py-4",children:[n.jsx("div",{className:"mb-2",children:n.jsx(Tr,{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 Fc({app:e=null,navContext:t=mt,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:g,functionImports:b}=i.useMemo(()=>pc(r.directImports),[r.directImports]);return n.jsxs("div",{className:"flex flex-col",children:[n.jsx(Ac,{app:e,navContext:t,routeEntity:r,displayName:r.displayName,pageFilePath:r.pageFilePath}),n.jsx(hc,{layoutChain:r.layoutChain??[],onNavigateToEntity:f}),n.jsx(Ia,{activeTab:m,onTabChange:h,scenarioCount:r.scenarios.length,componentCount:g.length,functionCount:b.length}),n.jsx(Dc,{activeTab:m,routeEntity:r,componentImports:g,functionImports:b,testGroups:c,selectedSlug:s,entityLookup:a,allScenarios:o,routeEntities:l,onSelectScenario:d,onNavigateToRoute:u,onNavigateToEntity:f,onScenariosChanged:p})]})}function Un(e){const t=Pl(e);if(t)return{selectedAppDir:t,selectedEntityHash:null};const r=Tl(e);return r?{selectedAppDir:null,selectedEntityHash:r}:{selectedAppDir:null,selectedEntityHash:null}}function Kn(e){return`/apps/${e}`}function Lc(e){return`/entities/${e}`}function lr(e){return e.pageFilePath?Vt(e.pageFilePath,xt(e.pageFilePath)):null}function Oa(e){const t=lr(e);return t===null?null:Lc(t)}function _a({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 Mc({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:Ue(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 Ic({routeEntity:e,onSelectRoute:t,onSelectScenario:r}){const s=e.scenarios.length,a=Oa(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(_a,{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(Mc,{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 $c(){return n.jsx("div",{className:"px-5 py-8 text-center text-[var(--text-dim)]",children:"No routes discovered yet."})}function Bc(){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 Oc({routeEntities:e,onSelectRoute:t,onSelectScenario:r}){return e.length===0?n.jsx($c,{}):n.jsxs("div",{className:"px-5 py-5",children:[n.jsx(Bc,{}),n.jsx("div",{children:e.map(s=>n.jsx(Ic,{routeEntity:s,onSelectRoute:t,onSelectScenario:r},s.route))})]})}function _c({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 zc({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 Hc({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(_c,{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(zc,{test:o},`${o.file}-${o.key??o.line??l}`))})]},t.feature)})})}function Wc({app:e=null,navContext:t=mt,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:g,onBackToRoutes:b,onScenariosChanged:y}){const w=_l(l&&!c?l:null);return r?a?n.jsx(ys,{}):o?n.jsx(Wn,{message:o}):c?n.jsx(Fc,{app:e,navContext:t,routeEntity:c,selectedSlug:u,entityLookup:f,allScenarios:p,routeEntities:s,testGroups:d,onSelectScenario:m,onNavigateToRoute:h,onNavigateToEntity:g,onScenariosChanged:y}):l?w.status==="loading"||w.status==="idle"?n.jsx(ys,{}):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(fc,{app:e,navContext:t,routeEntity:c,entity:w.entity,selectedSlug:u,onSelectScenario:m,onNavigateToEntity:g??(()=>{}),onScenariosChanged:y}):n.jsx(Oc,{routeEntities:s,onSelectRoute:h,onSelectScenario:m}):n.jsx(Hc,{groups:d})}function Vc({app:e,showDetail:t,navContext:r=mt,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(Tr,{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(La,{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(Fa,{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 Uc({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 Kc({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"],za={"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"}},Ha={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 Gc(e){var t;return((t=za[e])==null?void 0:t.label)??e}function Yc(e,t){var a,o;const r=(a=za[e])==null?void 0:a.description,s=((o=Ha[t])==null?void 0:o.meaning)??"";return r?`${r}. ${s}`:s}function qc({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(ws,{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(ws,{token:c,state:e[c],unknown:!0},c))]}):null]}):null]})}function ws({token:e,state:t,unknown:r}){const s=Ha[t],a=r?"This token isn't recognized — may be a typo.":Yc(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:[Gc(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 Jc({capabilities:e}){return e&&Object.keys(e).length>0?n.jsx(qc,{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 Xc({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(Jc,{capabilities:t})})]})}function Qc({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 Zc=["dev","test","build"];function nt(e){return typeof e=="string"&&e.length>0?e:null}function Wa(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ed(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function td(e){const t=Wa(e);if(!t)return[];const r=[];for(const s of Zc){const a=nt(t[s]);a&&r.push({key:s,value:a})}return r}function nd(e){const t=Wa(e);if(!t)return null;const r=nt(t.type);if(!r)return null;const s=nt(t.pagesDir)??nt(t.isolationRoute)??nt(t.componentManifest);return s?`${r} (${s})`:r}function rd(e){const t=e.capabilities;return!t||typeof t!="object"||Array.isArray(t)?null:t}function sd(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 ad(e){return e?{id:nt(e.id),name:nt(e.name),description:nt(e.description),technologies:ed(e.technologies),commands:td(e.commands),routingSummary:nd(e.routing)}:{id:null,name:null,description:null,technologies:[],commands:[],routingSummary:null}}function od({stack:e,defaultExpanded:t=!1}){const r=e!==void 0,[s,a]=i.useState(t),o=Qc({skip:r}),l=r?e:o;if(!l||Object.keys(l).length===0)return null;const c=ad(l),d=rd(l);return n.jsxs("div",{className:"px-5 py-2","data-testid":"stack-panel",children:[n.jsx(Kc,{name:c.name,id:c.id,capabilitiesTally:sd(d),expanded:s,onToggle:()=>a(u=>!u)}),s?n.jsx(Xc,{fields:c,capabilities:d}):null]})}function id({app:e,navContext:t=mt,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:g,onScenariosChanged:b,projectTitle:y,coverage:w,showProjectBand:v,onCoverageClick:x,stats:j,testsLoading:k,testsRefreshing:N,onRunTests:S,currentRunner:C}){const R=e.type==="web",E=!!v&&!l;return n.jsxs("div",{children:[E?n.jsxs(n.Fragment,{children:[n.jsx(Uc,{projectTitle:y,coverage:w,onCoverageClick:x}),n.jsx(od,{})]}):null,n.jsx(Vc,{app:e,showDetail:!!(l||o),navContext:t,stats:j,testsLoading:k,testsRefreshing:N,onRunTests:S,currentRunner:C}),n.jsx(Wc,{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:g,onScenariosChanged:b})]})}function Va(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 ld(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 iw(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 cd({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 dd=192;function Ua({children:e,variant:t="compact",maxHeight:r=dd}){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(pt,{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 ud({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:Ue(t.screenshotPath,t.screenshotCapturedAtMs),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 fd={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"},pd={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"},md={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."},hd={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."},xd=24,Ka=19;function Ke(e){return e==="backend"?"backend":"ui"}function Ar(e,t){return(Ke(t)==="backend"?pd:fd)[e]??"?"}function gd(e,t){return(Ke(t)==="backend"?hd:md)[e]??""}function bd(e){return Ke(e)==="backend"?Ka:xd}function vd(e){return Ke(e)==="backend"?"Backend Flow":"UI Flow"}function Ga(e,t){const r=Ke(t);return{description:gd(e,r),label:Ar(e,r),prefix:vd(r),totalSteps:bd(r)}}const yd=[{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]}],wd=[{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 jd(e){return Ke(e)==="backend"?wd:yd}function kd({currentStep:e}){const t=Array.from({length:Ka},(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 Nd({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 Ya({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 Cd({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(Ya,{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 Sd({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(Ed,{change:t},r))]})}function Ed({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(Rd,{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 Rd({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(Ya,{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 Pd({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(js,{label:"Files Modified",value:t}),n.jsx(js,{label:"Tests Modified",value:r,color:r>0?"green":void 0})]})]})})}function js({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 Td=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/__tests__\//,/tests?\//];function Gn(e){return Td.some(t=>t.test(e))}function Dd({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 Ad=5e3,ks=50;function Fd(){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([]),g=i.useRef(null);i.useEffect(()=>{h.current=e},[e]),i.useEffect(()=>{g.current=a},[a]);const b=i.useCallback(async()=>{if(m.current==="idle"){m.current="initial",c(!0),p(null);try{const v=await fetch(`/api/history?limit=${ks}`);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 b();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(C=>C.commit.sha)),S=(k.entries??[]).filter(C=>!N.has(C.commit.sha));S.length>0&&(t(C=>[...S,...C]),s(C=>C+S.length))}catch(j){p(j instanceof Error?j.message:"Failed to poll history")}finally{m.current="idle"}},[b]),w=i.useCallback(async()=>{if(m.current!=="idle")return;const v=g.current;if(v){m.current="more",u(!0);try{const x=await fetch(`/api/history?limit=${ks}&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(()=>{b();const v=setInterval(()=>{y()},Ad);return()=>clearInterval(v)},[b,y]),{rows:e,total:r,hasMore:a!==null,loading:l,loadingMore:d,error:f,loadMore:w,reload:b}}function Ld({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:Va(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 Md=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/__tests__\//,/tests?\//];function Id(e){return e.filter(t=>Md.some(r=>r.test(t.path)))}function qa({entry:e,commit:t}){const r=Id(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 ${ld(e.type)}`,children:e.type}),n.jsx("span",{className:"text-xs",style:{color:"var(--text-dim)"},children:Va(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(Ua,{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(ud,{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(cd,{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 $d(){const{rows:e,total:t,hasMore:r,loading:s,loadingMore:a,error:o,loadMore:l}=Fd();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(qa,{entry:d.entry,commit:d.commit},d.commit.sha):n.jsx(Ld,{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 Bd="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 Od(){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 Ns(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 _d(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??Bd).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
|
+
`),g=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,"",g,"","## UI idle trace (persisted)","",Ns((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","",Ns((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 zd(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=Od(),o=Dl({agentName:e.agentName});return{markdown:_d({bundle:r,browser:a,uiBufferText:o,prompt:e.prompt,agentName:e.agentName}),bundle:r,error:s}}const Hd=1500;function Wd(e=Hd){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 Vd=2500;function Ud({agentName:e}){const[t,r]=i.useState(!1),{label:s,flash:a}=Wd(Vd),o=async()=>{r(!0);const{markdown:l,bundle:c,error:d}=await zd({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},Kd=[{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"}],Ja="codeyam-editor-notifications";function Xa(){try{const e=localStorage.getItem(Ja);if(!e)return qn;const t=JSON.parse(e);return{...qn,...t}}catch{return qn}}function Qa(e){localStorage.setItem(Ja,JSON.stringify(e))}const Gd={"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;U(e,{name:r==null?void 0:r.name,message:r==null?void 0:r.message})}function Za(e){if(e==="off")return;U("audio-playsound-entered",{soundId:e});let t;try{t=new AudioContext}catch(s){Jn("audio-context-failed",s);return}U("audio-context-created",{state:t.state});const r=()=>{let s;try{s=Gd[e](t)}catch(a){Jn("audio-context-failed",a),t.close().catch(()=>{});return}U("audio-oscillators-scheduled",{soundId:e,count:s.count,longestStopSec:s.longestStopSec}),setTimeout(()=>{t.close().then(()=>U("audio-context-closed")).catch(()=>{})},(s.longestStopSec+.1)*1e3)};t.state==="running"?r():t.state==="suspended"?(U("audio-context-resume-attempted"),t.resume().then(()=>{U("audio-context-resume-ok",{state:t.state}),r()},s=>{Jn("audio-context-resume-failed",s),t.close().catch(()=>{})})):(U("audio-context-failed",{name:"UnexpectedState",message:`AudioContext state "${t.state}"`}),t.close().catch(()=>{}))}function Cs({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:Kd.map(a=>n.jsx("button",{onClick:()=>{t({...e,sound:a.id}),a.id!=="off"&&Za(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(Cs,{label:"Claude stops",checked:r,onChange:a=>t({...e,idleOnStop:a})}),n.jsx(Cs,{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 Yd({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(Ud,{agentName:r})})]})]})]})}const eo="codeyam-editor-notifications-prompted",qd="codeyam-editor-notifications";function to(){try{localStorage.setItem(eo,"1")}catch{}}function Jd(){try{return localStorage.getItem(eo)!==null||localStorage.getItem(qd)!==null}catch{return!0}}function Xd({settings:e,onChange:t}){const[r,s]=i.useState(()=>!Jd());if(!r)return null;const a=()=>{to(),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 Qd(){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 Zd({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 eu(){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 tu({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 nu({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(Zd,{projectDescription:e}):n.jsx(eu,{}),n.jsx(tu,{onClick:t})]})}function ru({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(Ol,{stats:l,onClick:()=>t(l.app.dir),testsLoading:r,testsRefreshing:s,onRunTests:a,currentRunner:o},l.app.dir))})}function su({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 au(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 Ss=["product-type","description","tech-stack","notifications","design-approach"];function ou(e){return e==="files"||e==="chat"?[...Ss,"design-details"]:Ss}const no="codeyam.questionnaire.draft";function Ir(e){return`${no}:${e}`}function iu(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 iu(r)?r:null}catch{return null}}function lu(e,t){try{localStorage.setItem(Ir(e),JSON.stringify(t))}catch{}}function cu(e){try{localStorage.removeItem(Ir(e))}catch{}}function du(){try{localStorage.removeItem(no)}catch{}}function uu(){const[e,t]=i.useState([]);return i.useEffect(()=>{fetch("/api/editor-stacks").then(r=>r.json()).then(t).catch(()=>{})},[]),{techStacks:e}}function fu(){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,pu=3e4,mu=3e3;function ro(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 hu(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`drop-${Date.now()}-${Math.random().toString(36).slice(2)}`}function xu(e){return/^[A-Za-z0-9._/\-]+$/.test(e)?e:`"${e.replace(/(["\\$`])/g,"\\$1")}"`}function gu(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 bu({dragActive:e,inputRef:t,onDragOver:r,onDragLeave:s,onDrop:a,onFilePick:o}){return n.jsxs("label",{onDragOver:r,onDragLeave:s,onDrop:a,style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"var(--spacing-xl, 32px)",border:`2px dashed ${e?"var(--accent-active)":"var(--border-default)"}`,borderRadius:12,background:e?"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:t,type:"file",multiple:!0,onChange:o,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"})]})}function vu({pending:e,onDescriptionChange:t,onRemove:r}){return 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:e.file.name}),n.jsx("button",{type:"button",onClick:()=>r(e.id),style:{fontSize:"var(--text-xs, 12px)",color:"var(--text-secondary)",background:"transparent",border:"none",cursor:"pointer"},children:"Remove"})]}),n.jsx("textarea",{value:e.description,onChange:s=>t(e.id,s.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"}})]})}function yu({pending:e,onDescriptionChange:t,onRemove:r}){return e.length===0?null:n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-sm, 8px)",marginTop:"var(--spacing-md, 12px)"},children:e.map(s=>n.jsx(vu,{pending:s,onDescriptionChange:t,onRemove:r},s.id))})}function wu({message:e}){return e?n.jsx("div",{style:{marginTop:"var(--spacing-sm, 8px)",color:"var(--accent-danger, #f87171)",fontSize:"var(--text-xs, 12px)"},children:e}):null}function ju({filenames:e}){return!e||e.length===0?null:n.jsxs("div",{style:{marginTop:"var(--spacing-sm, 8px)",color:"var(--text-secondary)",fontSize:"var(--text-xs, 12px)"},children:["Uploaded ",e.length," file",e.length===1?"":"s","."]})}function ku({disabled:e,submitting:t,onClick:r}){return n.jsx("button",{type:"button",onClick:r,disabled:e,style:{marginTop:"var(--spacing-md, 12px)",padding:"var(--spacing-sm, 8px) var(--spacing-md, 12px)",background:e?"var(--bg-input)":"var(--accent-active)",color:e?"var(--text-muted)":"var(--text-on-accent, white)",border:e?"1px solid var(--border-default)":"1px solid var(--accent-active)",borderRadius:6,fontSize:"var(--text-sm, 14px)",fontWeight:500,cursor:e?"not-allowed":"pointer"},children:t?"Uploading…":"Save uploads"})}function so({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]),g=i.useCallback((w,v)=>{r(x=>x.map(j=>j.id===w?{...j,description:v}:j))},[]),b=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 ro(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),r([]),e==null||e(j)}catch(w){d(w instanceof Error?w.message:String(w))}finally{a(!1)}}},[t,e]);return n.jsxs(n.Fragment,{children:[n.jsx(bu,{dragActive:u,inputRef:p,onDragOver:w=>{w.preventDefault(),f(!0)},onDragLeave:()=>f(!1),onDrop:w=>{w.preventDefault(),f(!1),m(Array.from(w.dataTransfer.files))},onFilePick:h}),n.jsx(yu,{pending:t,onDescriptionChange:g,onRemove:b}),n.jsx(wu,{message:c}),n.jsx(ju,{filenames:o}),n.jsx(ku,{disabled:t.length===0||s,submitting:s,onClick:y})]})}function rt({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 Nu({onUploadComplete:e}){return n.jsx(rt,{title:"Add your design files",subtitle:"Drop in anything: brand assets, mockups, references. Tell us briefly what each one shows.",children:n.jsx(so,{onUploadComplete:e})})}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(Cu,{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 Cu({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 Su=[{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 Eu({selected:e,onSelect:t}){return n.jsx(rt,{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:Su.map(r=>n.jsx(Mt,{label:r.label,description:r.description,selected:e===r.id,onClick:()=>t(r.id)},r.id))})})}function Ru(){const[e,t]=i.useState(()=>Xa());i.useEffect(()=>{to()},[]);const r=a=>{t(a),Qa(a)},s=()=>{r({...e,systemNotification:!0}),typeof Notification<"u"&&Notification.permission==="default"&&Notification.requestPermission()};return n.jsx(rt,{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 Pu(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 Tu({providerLabel:e,preparing:t,onLaunch:r}){return n.jsxs("div",{children:[n.jsxs("p",{style:{margin:"0 0 var(--spacing-md, 12px)",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.jsxs("p",{style:{margin:"0 0 var(--spacing-lg, 16px)",fontSize:"var(--text-sm, 14px)",lineHeight:1.5,color:"var(--text-secondary)"},children:[e," will ask whether you have any design assets — logos, screenshots, brand guides, or inspiration. You can add them any time from the ",n.jsx("strong",{children:"Add assets"})," panel in the Live Preview on the right (drag-and-drop or browse)."]}),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 Du({description:e,launched:t,onLaunched:r,onDesignSelected:s,onPreviewUrl:a}){const[o,l]=i.useState({kind:"preparing"}),{config:c}=ot(),d=st(c==null?void 0:c.provider),u=i.useRef(t);i.useEffect(()=>(a==null||a("/design-exploration"),()=>{a==null||a(null)}),[a]),i.useEffect(()=>{let p=!1;return(async()=>{try{const m=!u.current,[h,g,b]=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:"{}"}),m?fetch("/api/editor-design-reset",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}):Promise.resolve(null)]);if(!g.ok){const y=await g.text().catch(()=>`${g.status}`);throw new Error(y||`install failed: ${g.status}`)}if(b&&!b.ok){const y=await b.text().catch(()=>`${b.status}`);throw new Error(y||`design-reset failed: ${b.status}`)}h.ok||console.warn("[QuestionnaireDesignChatStep] editor-project-info failed; skill will prompt for description",h.status),p||l({kind:"ready"})}catch(m){p||l({kind:"error",message:m instanceof Error?m.message:String(m)})}})(),()=>{p=!0}},[e]),Pu(t,s);const f=o.kind==="preparing";return n.jsx(rt,{title:"Explore design directions",subtitle:"Chat with the agent, share any design assets, 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(Tu,{providerLabel:d,preparing:f,onLaunch:r})})}const Au=[{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 Fu({selected:e,onSelect:t}){return n.jsx("div",{style:{marginTop:"var(--spacing-xl, 32px)"},children:n.jsx(rt,{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:Au.map(r=>n.jsx(Mt,{label:r.label,description:r.description,selected:e===r.id,onClick:()=>t(r.id)},r.id))})})})}function ao(){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 Lu({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 Mu({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 Iu=[{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"}],$u={"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"},Es=560,Bu=960;function Ou(e){const{projectDir:t,loaded:r}=fu(),s=i.useRef(!1);return i.useEffect(()=>{r&&!s.current&&(s.current=!0,du())},[r]),r?n.jsx(_u,{...e,projectDir:t}):n.jsx("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"auto"},children:n.jsx(ao,{})})}function _u({onComplete:e,onPreviewUrl:t,projectDir:r}){const[s,a]=i.useState(()=>{const P=r?Xn(r):null;return P?P.step:1}),[o,l]=i.useState(()=>{const P=r?Xn(r):null;return(P==null?void 0:P.answers)??{appFormats:[],description:"",techStackId:null,designApproach:null,defaultDevice:null}}),[c,d]=i.useState(null),[u,f]=i.useState(()=>{const P=r?Xn(r):null;return(P==null?void 0:P.designChatLaunched)??!1}),p=i.useRef(u),{techStacks:m}=uu(),h=ou(o.designApproach),g=h[s-1],b=s===h.length,y=h.map(P=>$u[P]);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&&lu(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 P=!1;return(async()=>{try{const G=await(await fetch("/api/editor-design-state")).json();P||j({state:"ready",active:G.active??null})}catch{P||j({state:"ready",active:null})}})(),()=>{P=!0}},[]);const k=i.useCallback(P=>{l(_=>{const G=_.appFormats.includes(P),D=G?_.appFormats.filter(W=>W!==P):[..._.appFormats,P],$=P==="web"&&G?null:_.defaultDevice;return{..._,appFormats:D,defaultDevice:$}})},[]),N=i.useCallback(P=>{l(_=>({..._,defaultDevice:P}))},[]),S=i.useCallback(P=>{l(_=>({..._,designApproach:_.designApproach===P?null:P}))},[]),C=i.useCallback(async()=>{await au(o),r!==null&&cu(r),e==null||e(o)},[o,e,r]),R=i.useRef(!1);i.useEffect(()=>{R.current||x.state==="ready"&&g==="design-details"&&o.designApproach==="chat"&&c!==null&&c!==x.active&&(R.current=!0,C())},[g,o.designApproach,c,C,x]);const E=i.useCallback(()=>{a(P=>P+1)},[]),T=o.appFormats.includes("web"),M=(()=>{switch(g){case"product-type":return o.appFormats.length>0&&(!T||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}})(),A=g==="description"?Bu:g==="design-details"&&o.designApproach==="chat"?"100%":Es;return n.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"auto"},children:[n.jsx(ao,{}),n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",padding:"var(--spacing-xl, 32px)"},children:[n.jsxs("div",{style:{maxWidth:A},children:[g==="product-type"&&n.jsxs(n.Fragment,{children:[n.jsx(rt,{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:Iu.map(P=>n.jsx(Mt,{label:P.label,selected:o.appFormats.includes(P.id),onClick:()=>k(P.id),multi:!0},P.id))})}),T&&n.jsx(Fu,{selected:o.defaultDevice,onSelect:N})]}),g==="description"&&n.jsx(rt,{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:P=>l(_=>({..._,description:P.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"}})}),g==="tech-stack"&&n.jsx(rt,{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(P=>({...P,techStackId:null}))}),m.map(P=>n.jsx(Mt,{label:P.name,description:P.description,selected:o.techStackId===P.id,onClick:()=>l(_=>({..._,techStackId:P.id}))},P.id))]})}),g==="notifications"&&n.jsx(Ru,{}),g==="design-approach"&&n.jsx(Eu,{selected:o.designApproach,onSelect:S}),g==="design-details"&&o.designApproach==="files"&&n.jsx(Nu,{}),g==="design-details"&&o.designApproach==="chat"&&n.jsx(Du,{description:o.description,launched:u,onLaunched:v,onDesignSelected:d,onPreviewUrl:t})]}),n.jsxs("div",{style:{maxWidth:Es},children:[n.jsx(Lu,{step:s,canAdvance:M,isFinalStep:b,onBack:()=>a(P=>P-1),onNext:()=>{M&&E()},onFinish:C}),n.jsx(Mu,{currentStep:s,stepLabels:y,onStepClick:a})]})]})]})}function zu({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:g}){const{saved:b}=Qd();return r.length===0?o||b===null?null:!f&&!b?n.jsx(Ou,{onPreviewUrl:p,onComplete:m}):n.jsx(nu,{projectDescription:t??null,onOpenBuildTab:h??(()=>{})}):n.jsxs("div",{className:"px-5 py-5",children:[n.jsx(su,{projectTitle:e,coverage:s,onCoverageClick:g}),n.jsx(ru,{stats:r,onSelectApp:a,testsLoading:l,testsRefreshing:c,onRunTests:d,currentRunner:u})]})}function Hu({sessionContent:e,stepIndicator:t}){return n.jsxs("div",{className:"flex flex-col h-full",children:[t,e]})}function Wu({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 Vu(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 Uu(e,t){const r=st(e),s=st(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 Ku({resumeMode:e,previousProvider:t,currentProvider:r,awaitingUserInput:s=!1}){return e!=="handoff"||t==null||r==null||t===r?Vu(s):Uu(t,r)}function Gu({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 Yu({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 qu({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 Ju({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 Xu(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 Qu({featureName:e,editorStep:t,workflowMode:r,previousProvider:s,currentProvider:a,resumeMode:o,awaitingUserInput:l=!1,onContinue:c}){const d=Ku({resumeMode:o,previousProvider:s,currentProvider:a,awaitingUserInput:l}),u=t==null?null:Ar(t,r);return Xu(c),n.jsxs(Yu,{children:[n.jsx(qu,{title:d.title,description:d.description}),n.jsx(Ju,{featureName:e,editorStep:t,editorStepLabel:u,providersLabel:d.providersLabel}),n.jsx(Gu,{label:d.buttonLabel,onContinue:c})]})}function Zu({awaitingUserInput:e,currentProvider:t,editorStep:r,featureName:s,onContinue:a,previousProvider:o,resumeMode:l,workflowMode:c}){return n.jsx(Qu,{featureName:s,editorStep:r,workflowMode:c,previousProvider:o,currentProvider:t,resumeMode:l,awaitingUserInput:e,onContinue:a})}function ef({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,tf="agent-banner-ready",nf="agent-auth-required";let vn=!1,yn=!1,Ve=[],Rs=!1,Ze=null,tt=null,mn=!1;function rf(){Rs||typeof window>"u"||(Rs=!0,window.addEventListener(tf,()=>{const e=!yn;if(e){yn=!0;const t=Ve;Ve=[];for(const r of t)r("banner")}if(mn&&(mn=!1,tt&&Ze===null)){U("dispatch-rename-after-auth",{label:tt.label,reason:"first-observed-frame-after-auth"}),Ze=tt,gn(tt.label,tt.send);return}Ze&&(U("dispatch-rename-reapply",{label:Ze.label,reason:e?"first-observed-frame":"second-observed-frame"}),gn(Ze.label,Ze.send))}),window.addEventListener(nf,()=>{mn=!0,U("agent-auth-required-observed",{});const e=Ve;Ve=[];for(const t of e)t("auth-required")}))}rf();function sf(){return yn?Promise.resolve("banner"):new Promise(e=>{let t=!1;const r=a=>{t||(t=!0,clearTimeout(s),e(a))};Ve.push(r);const s=setTimeout(()=>{if(t)return;t=!0;const a=Ve.indexOf(r);a>=0&&Ve.splice(a,1),e("fallback")},pn)})}async function oo(e,t,r=0,s=ir,a=!1){if(vn){U("dispatch-rename-suppressed",{caller:t,label:e});return}vn=!0,tt={label:e,send:s},U("dispatch-rename",{phase:"queued",caller:t,label:e,fallbackMs:pn,postReadyDelayMs:r});const o=await sf();if(o==="auth-required"){U("dispatch-rename-deferred-for-auth",{caller:t,label:e});return}if(a&&o==="fallback"){U("dispatch-rename-skipped-no-banner",{caller:t,label:e,fallbackMs:pn});return}r>0&&await new Promise(l=>setTimeout(l,r)),o==="fallback"&&U("dispatch-rename-fallback",{caller:t,label:e,fallbackMs:pn}),U("dispatch-rename",{phase:"fired",caller:t,label:e,source:o,postReadyDelayMs:r}),Ze={label:e,send:s},gn(e,s)}function af(){vn=!1,yn=!1,Ve=[],Ze=null,tt=null,mn=!1}function of(){vn=!1,Ve=[],tt=null}const lf="Editor";function cf({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,oo(lf,"build-session-seed",Ea,void 0,!0)}},[e,t,r])}function df({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 uf=1e3;let ur=0;function nn(){ur=Date.now()}function ff(){return ur===0?1/0:Date.now()-ur}function pf(){return ff()<uf}function wn(){window.focus()}function io(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 mf({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),mu);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 ro(x),N=hu(),S=new Promise((C,R)=>{const E=window.setTimeout(()=>{l.current.delete(N)&&R(new Error("Timed out waiting for save to complete"))},pu);l.current.set(N,{resolve:T=>{window.clearTimeout(E),C(T)},reject:T=>{window.clearTimeout(E),R(new Error(T))}})});return j.send(JSON.stringify({type:"drop",id:N,name:x.name||"unnamed",mime:x.type||"application/octet-stream",data:k})),S},[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 S=N instanceof Error?N.message:String(N);d(`Attach failed: ${S}`);return}t(j.map(xu).join(" ")+" ")},[m,d,t]),g=i.useCallback(x=>{x.dataTransfer.types.includes("Files")&&(x.preventDefault(),c.current+=1,s(!0))},[]),b=i.useCallback(x=>{x.dataTransfer.types.includes("Files")&&x.preventDefault()},[]),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),gu(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 S of Array.from(j))if(S.kind==="file"&&S.type.startsWith("image/")){const C=S.getAsFile();C&&k.push(C)}k.length!==0&&(x.preventDefault(),await h(k))},[h]);return{dragActive:r,errorToast:a,dropHandlers:{onDragEnter:g,onDragOver:b,onDragLeave:y,onDrop:w},pasteHandler:v,resolveDrop:u,rejectDrop:f,cancelAllDrops:p,showError:d}}function lo(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 gt(e=typeof window<"u"?window:void 0){return e?e.self!==e.top:!1}function hf({isInIframe:e,previewKind:t,selectedScenario:r}){return e?!1:t!=="application"?!0:!r||!St(r)}function xf(){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 gf({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 co(){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 Ps=15;function bf({provider:e,agentStartMode:t,sessionId:r,onAgentIdle:s,onAgentActive:a,onUserInput:o,onStartupFailed:l,onStartupFailedCleared:c,suppressReconnectOnStopBuilding:d=!1}){if(gt())return null;const u=i.useRef(null),f=i.useRef(null),p=i.useRef(null),m=i.useRef(null),h=i.useRef(!1),g=i.useRef(t??"fresh"),b=i.useRef(r??null),[y,w]=i.useState({kind:"connecting"}),[v,x]=i.useState(0),[j,k]=lo(1200);i.useEffect(()=>{g.current=t??"fresh",b.current=r??null},[t,r]);const N=i.useRef(s);N.current=s;const S=i.useRef(a);S.current=a;const C=i.useRef(o);C.current=o;const R=i.useRef(l);R.current=l;const E=i.useRef(c);E.current=c;const T=mf({wsRef:m,insertInput:A=>{var P,_;((P=m.current)==null?void 0:P.readyState)===WebSocket.OPEN&&m.current.send(JSON.stringify({type:"input",data:A})),nn(),(_=C.current)==null||_.call(C)}}),M=i.useRef(T);return M.current=T,io(u,()=>{var A;p.current&&f.current&&(p.current.fit(),((A=m.current)==null?void 0:A.readyState)===WebSocket.OPEN&&m.current.send(JSON.stringify({type:"resize",cols:f.current.cols,rows:f.current.rows})))}),i.useEffect(()=>{if(!u.current||h.current)return;h.current=!0;const A=new Ra.Terminal({cursorBlink:!0,fontSize:13,fontFamily:"'IBM Plex Mono', monospace",rightClickSelectsWord:!1,theme:{background:"#1e1e1e",foreground:"#cccccc",cursor:"#D7FF63",selectionBackground:"#264f78"}}),P=new Pa.FitAddon;A.loadAddon(P),A.open(u.current),f.current=A,p.current=P;const _=Ta(A,u.current,{onError:H=>M.current.showError(H),onCopy:()=>k()}),G=Da(A,{sendInput:H=>{var B,Z;((B=m.current)==null?void 0:B.readyState)===WebSocket.OPEN&&m.current.send(JSON.stringify({type:"input",data:H})),nn(),(Z=C.current)==null||Z.call(C)}});requestAnimationFrame(()=>{P.fit(),A.focus()});let D=!1,$=0,W=null;function z(){try{const H=new WebSocket(pl({provider:e,mode:g.current,sessionId:b.current??void 0,cols:A.cols,rows:A.rows}));m.current=H,H.binaryType="arraybuffer",H.onmessage=B=>{var Z,ne,K,se;if(B.data instanceof ArrayBuffer)A.write(new Uint8Array(B.data));else if(typeof B.data=="string")try{const I=JSON.parse(B.data);if(I.type==="error"){D=!0,w({kind:"server-error",message:ml(I)});return}if(I.type==="session-id")g.current="resume",b.current=I.sessionId??null;else if(I.type==="agent-idle"||I.type==="claude-idle"){const ae=typeof I.source=="string"?I.source:void 0;U("ws-message-received",{type:I.type,source:ae}),(Z=N.current)==null||Z.call(N,ae)}else if(I.type==="agent-active"||I.type==="claude-active")U("ws-message-received-active",{type:I.type}),(ne=S.current)==null||ne.call(S);else if(I.type==="idle-diag"){const{site:ae,event:ge,...oe}=I;U(`rust:${ge??"unknown"}`,{site:ae,...oe})}else I.type==="drop-complete"?M.current.resolveDrop(String(I.id??""),String(I.path??"")):I.type==="drop-error"?M.current.rejectDrop(String(I.id??""),String(I.message??"drop failed")):I.type==="startup-failed"?(K=R.current)==null||K.call(R,String(I.snippet??"")):I.type==="startup-failed-cleared"?(se=E.current)==null||se.call(E):I.type==="agent-banner-ready"?(U("agent-banner-ready",{}),window.dispatchEvent(new CustomEvent("agent-banner-ready"))):I.type==="agent-auth-required"?(U("agent-auth-required",{}),window.dispatchEvent(new CustomEvent("agent-auth-required"))):I.type==="agent-auth-resolved"&&(U("agent-auth-resolved",{}),window.dispatchEvent(new CustomEvent("agent-auth-resolved")))}catch{}},H.onopen=()=>{$=0,w({kind:"open"}),U("ws-open"),H.send(JSON.stringify({type:"resize",cols:A.cols,rows:A.rows}));try{typeof localStorage<"u"&&localStorage.getItem("codeyam.idleDebug")==="1"&&(H.send(JSON.stringify({type:"enable-idle-diag",sessionId:Er()})),U("idle-diag-enabled"))}catch{}},H.onerror=()=>{},H.onclose=async()=>{if(U("ws-close",{reconnectAttempts:$}),M.current.cancelAllDrops("Not connected"),D){w(Z=>Z.kind==="server-error"?Z:{kind:"ended"}),A.writeln(`\r
|
|
9
|
+
\x1B[90m[Terminal session ended]\x1B[0m`);return}const B=await hl();if(!D){if(!B){w({kind:"server-stopped"}),W==null||W(),W=xl(2e3,()=>{D||window.location.reload()});return}if($<Ps){const Z=$<4?1e3*Math.pow(2,$):1e4;$++,w({kind:"reconnecting",attempt:$,maxAttempts:Ps}),setTimeout(()=>{D||z()},Z)}else w({kind:"failed"})}}}catch{w({kind:"failed"})}}try{P.fit()}catch{}z();let q=0;const L=1e3;function F(){var B;const H=Date.now();H-q>=L&&((B=m.current)==null?void 0:B.readyState)===WebSocket.OPEN&&(m.current.send(JSON.stringify({type:"browser-activity"})),q=H)}document.addEventListener("mousemove",F),document.addEventListener("keydown",F),document.addEventListener("mousedown",F),A.onData(H=>{var B,Z;((B=m.current)==null?void 0:B.readyState)===WebSocket.OPEN?m.current.send(JSON.stringify({type:"input",data:H})):x(ne=>ne+1),nn(),(Z=C.current)==null||Z.call(C)});const O=u.current;function X(H){var I,ae,ge,oe;const B=H,Z=(I=B.clipboardData)==null?void 0:I.items;if(Z){for(const me of Array.from(Z))if(me.kind==="file"&&me.type.startsWith("image/")){H.preventDefault(),H.stopPropagation(),M.current.pasteHandler(B);return}}const ne=((ae=B.clipboardData)==null?void 0:ae.getData("text"))??"";if(!ne)return;H.preventDefault(),H.stopPropagation();const K=ne.replace(/\r\n/g,"\r").replace(/\n/g,"\r"),se=A.modes.bracketedPasteMode?`\x1B[200~${K}\x1B[201~`:K;((ge=m.current)==null?void 0:ge.readyState)===WebSocket.OPEN?m.current.send(JSON.stringify({type:"input",data:se})):x(me=>me+1),nn(),(oe=C.current)==null||oe.call(C)}O.addEventListener("paste",X,!0);function J(H){var ne,K;const B=H.detail;if(!B)return;((ne=m.current)==null?void 0:ne.readyState)===WebSocket.OPEN?((K=m.current)==null||K.send(JSON.stringify({type:"input",data:B})),U("terminal-send-input",{len:B.length,firstChars:B.slice(0,16),wsOpen:!0,dropped:!1})):U("terminal-send-input",{len:B.length,firstChars:B.slice(0,16),wsOpen:!1,dropped:!0})}window.addEventListener("terminal-send-input",J);function ie(){wn(),A.focus()}window.addEventListener("terminal-focus",ie);function ee(){var H;D=!0,(H=m.current)==null||H.close(),w({kind:"ended"}),A.reset()}return d&&window.addEventListener("build-session-stopped",ee),()=>{var H;D=!0,W==null||W(),W=null,document.removeEventListener("mousemove",F),document.removeEventListener("keydown",F),document.removeEventListener("mousedown",F),window.removeEventListener("terminal-send-input",J),window.removeEventListener("terminal-focus",ie),d&&window.removeEventListener("build-session-stopped",ee),O.removeEventListener("paste",X,!0),G(),(H=m.current)==null||H.close(),_(),A.dispose(),h.current=!1}},[e]),n.jsxs("div",{className:"relative flex-1 flex flex-col",style:{minHeight:0},"data-terminal-emulator":!0,onDragEnter:T.dropHandlers.onDragEnter,onDragOver:T.dropHandlers.onDragOver,onDragLeave:T.dropHandlers.onDragLeave,onDrop:T.dropHandlers.onDrop,onPaste:T.pasteHandler,children:[n.jsx("div",{ref:u,className:"flex-1",style:{background:"#1e1e1e",minHeight:0,paddingTop:3,paddingLeft:3},onClick:()=>{var A;wn(),(A=f.current)==null||A.focus()}}),T.dragActive&&n.jsx(xf,{}),T.errorToast&&n.jsx(gf,{message:T.errorToast}),j&&n.jsx(co,{}),n.jsx(fl,{status:y,pulseKey:v,onRefresh:()=>window.location.reload()})]})}function vf({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);cf({provider:s,agentStartMode:o?"resume":"fresh",currentFeature:l}),i.useEffect(()=>()=>{af()},[]);const p=i.useCallback(g=>{d(g)},[]),m=i.useCallback(()=>{d(null)},[]),h=i.useCallback(()=>{d(null),f(g=>g+1)},[]);return n.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[c!==null&&n.jsx(df,{snippet:c,onRetry:h,onDismiss:m}),n.jsx(bf,{provider:s,agentStartMode:o?"resume":"fresh",sessionId:o?a:null,onAgentIdle:t,onAgentActive:e,onUserInput:r,onStartupFailed:p,onStartupFailedCleared:m,suppressReconnectOnStopBuilding:!0},u)]})}function yf(){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 Et(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function $r(e){return"nodeType"in e}function Re(e){var t,r;return e?Et(e)?e:$r(e)&&(t=(r=e.ownerDocument)==null?void 0:r.defaultView)!=null?t:window:window}function Br(e){const{Document:t}=Re(e);return e instanceof t}function Ut(e){return Et(e)?!1:e instanceof Re(e).HTMLElement}function uo(e){return e instanceof Re(e).SVGElement}function Rt(e){return e?Et(e)?e.document:$r(e)?Br(e)?e:Ut(e)||uo(e)?e.ownerDocument:document:document:document}const He=Rn?i.useLayoutEffect:i.useEffect;function Or(e){const t=i.useRef(e);return He(()=>{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 wf(){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 _t(e,t){t===void 0&&(t=[e]);const r=i.useRef(e);return He(()=>{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 fo(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 Nt=fo(1),zt=fo(-1);function jf(e){return"clientX"in e&&"clientY"in e}function _r(e){if(!e)return!1;const{KeyboardEvent:t}=Re(e.target);return t&&e instanceof t}function kf(e){if(!e)return!1;const{TouchEvent:t}=Re(e.target);return t&&e instanceof t}function pr(e){if(kf(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 jf(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}}}),Ts="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Nf(e){return e.matches(Ts)?e:e.querySelector(Ts)}const Cf={display:"none"};function Sf(e){let{id:t,value:r}=e;return Ee.createElement("div",{id:t,style:Cf},r)}function Ef(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 Ee.createElement("div",{id:t,style:a,role:"status","aria-live":s,"aria-atomic":!0},r)}function Rf(){const[e,t]=i.useState("");return{announce:i.useCallback(s=>{s!=null&&t(s)},[]),announcement:e}}const po=i.createContext(null);function Pf(e){const t=i.useContext(po);i.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function Tf(){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 Df={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
|
+
`},Af={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 Ff(e){let{announcements:t=Af,container:r,hiddenTextDescribedById:s,screenReaderInstructions:a=Df}=e;const{announce:o,announcement:l}=Rf(),c=Gt("DndLiveRegion"),[d,u]=i.useState(!1);if(i.useEffect(()=>{u(!0)},[]),Pf(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=Ee.createElement(Ee.Fragment,null,Ee.createElement(Sf,{id:s,value:a.draggable}),Ee.createElement(Ef,{id:c,announcement:l}));return r?kt.createPortal(f,r):f}var xe;(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"})(xe||(xe={}));function kn(){}function Ds(e,t){return i.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function Lf(){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 Be=Object.freeze({x:0,y:0});function mo(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function ho(e,t){let{data:{value:r}}=e,{data:{value:s}}=t;return r-s}function Mf(e,t){let{data:{value:r}}=e,{data:{value:s}}=t;return s-r}function As(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 xo(e,t){if(!e||e.length===0)return null;const[r]=e;return r[t]}function Fs(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 If=e=>{let{collisionRect:t,droppableRects:r,droppableContainers:s}=e;const a=Fs(t,t.left,t.top),o=[];for(const l of s){const{id:c}=l,d=r.get(c);if(d){const u=mo(Fs(d),a);o.push({id:c,data:{droppableContainer:l,value:u}})}}return o.sort(ho)},$f=e=>{let{collisionRect:t,droppableRects:r,droppableContainers:s}=e;const a=As(t),o=[];for(const l of s){const{id:c}=l,d=r.get(c);if(d){const u=As(d),f=a.reduce((m,h,g)=>m+mo(u[g],h),0),p=Number((f/4).toFixed(4));o.push({id:c,data:{droppableContainer:l,value:p}})}}return o.sort(ho)};function Bf(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 Of=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=Bf(c,t);d>0&&a.push({id:l,data:{droppableContainer:o,value:d}})}}return a.sort(Mf)};function _f(e,t,r){return{...e,scaleX:t&&r?t.width/r.width:1,scaleY:t&&r?t.height/r.height:1}}function go(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Be}function zf(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 Hf=zf(1);function Wf(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 Vf(e,t,r){const s=Wf(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 Uf={ignoreTransform:!1};function Pt(e,t){t===void 0&&(t=Uf);let r=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:u,transformOrigin:f}=Re(e).getComputedStyle(e);u&&(r=Vf(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 Ls(e){return Pt(e,{ignoreTransform:!0})}function Kf(e){const t=e.innerWidth,r=e.innerHeight;return{top:0,left:0,right:t,bottom:r,width:t,height:r}}function Gf(e,t){return t===void 0&&(t=Re(e).getComputedStyle(e)),t.position==="fixed"}function Yf(e,t){t===void 0&&(t=Re(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 Pn(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)||uo(a)||r.includes(a))return r;const o=Re(e).getComputedStyle(a);return a!==e&&Yf(a,o)&&r.push(a),Gf(a,o)?r:s(a.parentNode)}return e?s(e):r}function bo(e){const[t]=Pn(e,1);return t??null}function er(e){return!Rn||!e?null:Et(e)?e:$r(e)?Br(e)||e===Rt(e).scrollingElement?window:Ut(e)?e:null:null}function vo(e){return Et(e)?e.scrollX:e.scrollLeft}function yo(e){return Et(e)?e.scrollY:e.scrollTop}function mr(e){return{x:vo(e),y:yo(e)}}var be;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(be||(be={}));function wo(e){return!Rn||!e?!1:e===document.scrollingElement}function jo(e){const t={x:0,y:0},r=wo(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 qf={x:.2,y:.2};function Jf(e,t,r,s,a){let{top:o,left:l,right:c,bottom:d}=r;s===void 0&&(s=10),a===void 0&&(a=qf);const{isTop:u,isBottom:f,isLeft:p,isRight:m}=jo(e),h={x:0,y:0},g={x:0,y:0},b={height:t.height*a.y,width:t.width*a.x};return!u&&o<=t.top+b.height?(h.y=be.Backward,g.y=s*Math.abs((t.top+b.height-o)/b.height)):!f&&d>=t.bottom-b.height&&(h.y=be.Forward,g.y=s*Math.abs((t.bottom-b.height-d)/b.height)),!m&&c>=t.right-b.width?(h.x=be.Forward,g.x=s*Math.abs((t.right-b.width-c)/b.width)):!p&&l<=t.left+b.width&&(h.x=be.Backward,g.x=s*Math.abs((t.left+b.width-l)/b.width)),{direction:h,speed:g}}function Xf(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 ko(e){return e.reduce((t,r)=>Nt(t,mr(r)),Be)}function Qf(e){return e.reduce((t,r)=>t+vo(r),0)}function Zf(e){return e.reduce((t,r)=>t+yo(r),0)}function ep(e,t){if(t===void 0&&(t=Pt),!e)return;const{top:r,left:s,bottom:a,right:o}=t(e);bo(e)&&(a<=0||o<=0||r>=window.innerHeight||s>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const tp=[["x",["left","right"],Qf],["y",["top","bottom"],Zf]];class zr{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=Pn(r),a=ko(s);this.rect={...t},this.width=t.width,this.height=t.height;for(const[o,l,c]of tp)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 np(e){const{EventTarget:t}=Re(e);return e instanceof t?e:Rt(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 Me;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(Me||(Me={}));function Ms(e){e.preventDefault()}function rp(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 No={start:[te.Space,te.Enter],cancel:[te.Esc],end:[te.Space,te.Enter,te.Tab]},sp=(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(Rt(r)),this.windowListeners=new It(Re(r)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Me.Resize,this.handleCancel),this.windowListeners.add(Me.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Me.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:r}=this.props,s=t.node.current;s&&ep(s),r(Be)}handleKeyDown(t){if(_r(t)){const{active:r,context:s,options:a}=this.props,{keyboardCodes:o=No,coordinateGetter:l=sp,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}:Be;this.referenceCoordinates||(this.referenceCoordinates=f);const p=l(t,{active:r,context:s.current,currentCoordinates:f});if(p){const m=zt(p,f),h={x:0,y:0},{scrollableAncestors:g}=s.current;for(const b of g){const y=t.code,{isTop:w,isRight:v,isLeft:x,isBottom:j,maxScroll:k,minScroll:N}=jo(b),S=Xf(b),C={x:Math.min(y===te.Right?S.right-S.width/2:S.right,Math.max(y===te.Right?S.left:S.left+S.width/2,p.x)),y:Math.min(y===te.Down?S.bottom-S.height/2:S.bottom,Math.max(y===te.Down?S.top:S.top+S.height/2,p.y))},R=y===te.Right&&!v||y===te.Left&&!x,E=y===te.Down&&!j||y===te.Up&&!w;if(R&&C.x!==p.x){const T=b.scrollLeft+m.x,M=y===te.Right&&T<=k.x||y===te.Left&&T>=N.x;if(M&&!m.y){b.scrollTo({left:T,behavior:c});return}M?h.x=b.scrollLeft-T:h.x=y===te.Right?b.scrollLeft-k.x:b.scrollLeft-N.x,h.x&&b.scrollBy({left:-h.x,behavior:c});break}else if(E&&C.y!==p.y){const T=b.scrollTop+m.y,M=y===te.Down&&T<=k.y||y===te.Up&&T>=N.y;if(M&&!m.x){b.scrollTo({top:T,behavior:c});return}M?h.y=b.scrollTop-T:h.y=y===te.Down?b.scrollTop-k.y:b.scrollTop-N.y,h.y&&b.scrollBy({top:-h.y,behavior:c});break}}this.handleMove(t,Nt(zt(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=No,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 Is(e){return!!(e&&"distance"in e)}function $s(e){return!!(e&&"delay"in e)}class Wr{constructor(t,r,s){var a;s===void 0&&(s=np(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=Rt(l),this.documentListeners=new It(this.document),this.listeners=new It(s),this.windowListeners=new It(Re(l)),this.initialCoordinates=(a=pr(o))!=null?a:Be,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(Me.Resize,this.handleCancel),this.windowListeners.add(Me.DragStart,Ms),this.windowListeners.add(Me.VisibilityChange,this.handleCancel),this.windowListeners.add(Me.ContextMenu,Ms),this.documentListeners.add(Me.Keydown,this.handleKeydown),r){if(s!=null&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if($s(r)){this.timeoutId=setTimeout(this.handleStart,r.delay),this.handlePending(r);return}if(Is(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(Me.Click,rp,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Me.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:Be,u=zt(a,d);if(!s&&c){if(Is(c)){if(c.tolerance!=null&&tr(u,c.tolerance))return this.handleCancel();if(tr(u,c.distance))return this.handleStart()}if($s(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 ap={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Vr extends Wr{constructor(t){const{event:r}=t,s=Rt(r.target);super(t,ap,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 op={move:{name:"mousemove"},end:{name:"mouseup"}};var hr;(function(e){e[e.RightClick=2]="RightClick"})(hr||(hr={}));class ip extends Wr{constructor(t){super(t,op,Rt(t.event.target))}}ip.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 lp 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(){}}}lp.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 cp(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=up({delta:p,disabled:!o}),[g,b]=wf(),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 S=y.current.x*w.current.x,C=y.current.y*w.current.y;N.scrollBy(S,C)},[]),k=i.useMemo(()=>c===Nn.TreeOrder?[...u].reverse():u,[c,u]);i.useEffect(()=>{if(!o||!u.length||!v){b();return}for(const N of k){if((s==null?void 0:s(N))===!1)continue;const S=u.indexOf(N),C=f[S];if(!C)continue;const{direction:R,speed:E}=Jf(N,C,v,t,m);for(const T of["x","y"])h[T][R[T]]||(E[T]=0,R[T]=0);if(E.x>0||E.y>0){b(),x.current=N,g(j,l),y.current=E,w.current=R;return}}y.current={x:0,y:0},w.current={x:0,y:0},b()},[t,j,s,b,o,l,JSON.stringify(v),JSON.stringify(h),g,u,k,f,JSON.stringify(m)])}const dp={x:{[be.Backward]:!1,[be.Forward]:!1},y:{[be.Backward]:!1,[be.Forward]:!1}};function up(e){let{delta:t,disabled:r}=e;const s=fr(t);return Kt(a=>{if(r||!s||!a)return dp;const o={x:Math.sign(t.x-s.x),y:Math.sign(t.y-s.y)};return{x:{[be.Backward]:a.x[be.Backward]||o.x===-1,[be.Forward]:a.x[be.Forward]||o.x===1},y:{[be.Backward]:a.y[be.Backward]||o.y===-1,[be.Forward]:a.y[be.Forward]||o.y===1}}},[r,t,s])}function fp(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 pp(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 Bs=new Map;function mp(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=_t(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]),g=i.useRef(null),b=Kt(w=>{if(p&&!r)return Bs;if(!w||w===Bs||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 zr(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"||g.current!==null||(g.current=setTimeout(()=>{h(),g.current=null},c))},[c,p,h,...s]),{droppableRects:b,measureDroppableContainers:h,measuringScheduled:o!=null};function y(){switch(u){case Wt.Always:return!1;case Wt.BeforeDragging:return r;default:return!r}}}function Co(e,t){return Kt(r=>e?r||(typeof t=="function"?t(e):e):null,[t,e])}function hp(e,t){return Co(e,t)}function xp(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 Tn(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 gp(e){return new zr(Pt(e),e)}function Os(e,t,r){t===void 0&&(t=gp);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=xp({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=Tn({callback:o});return He(()=>{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 bp(e){const t=Co(e);return go(e,t)}const _s=[];function vp(e){const t=i.useRef(e),r=Kt(s=>e?s&&s!==_s&&e&&t.current&&e.parentNode===t.current.parentNode?s:Pn(e):_s,[e]);return i.useEffect(()=>{t.current=e},[e]),r}function yp(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)=>Nt(o,l),Be):ko(e):Be,[e,t])}function zs(e,t){t===void 0&&(t=[]);const r=i.useRef(null);return i.useEffect(()=>{r.current=null},t),i.useEffect(()=>{const s=e!==Be;s&&!r.current&&(r.current=e),!s&&r.current&&(r.current=null)},[e]),r.current?zt(e,r.current):Be}function wp(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 jp(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 So(e){return i.useMemo(()=>e?Kf(e):null,[e])}const Hs=[];function kp(e,t){t===void 0&&(t=Pt);const[r]=e,s=So(r?Re(r):null),[a,o]=i.useState(Hs);function l(){o(()=>e.length?e.map(d=>wo(d)?s:new zr(t(d),d)):Hs)}const c=Tn({callback:l});return He(()=>{c==null||c.disconnect(),l(),e.forEach(d=>c==null?void 0:c.observe(d))},[e]),a}function Np(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return Ut(t)?t:e}function Cp(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=Tn({callback:a}),l=i.useCallback(u=>{const f=Np(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 Sp=[{sensor:Vr,options:{}},{sensor:Hr,options:{}}],Ep={current:{}},hn={draggable:{measure:Ls},droppable:{measure:Ls,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 Rp={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},Pp={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:kn,draggableNodes:new Map,over:null,measureDroppableContainers:kn},Dn=i.createContext(Pp),Eo=i.createContext(Rp);function Tp(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Bt}}}function Dp(e,t){switch(t.type){case xe.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case xe.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 xe.DragEnd:case xe.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case xe.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 xe.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 xe.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 Ap(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(!_r(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=Nf(f);if(p){p.focus();break}}})}},[s,t,a,l,o]),null}function Fp(e,t){let{transform:r,...s}=t;return e!=null&&e.length?e.reduce((a,o)=>o({transform:a,...s}),r):r}function Lp(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 Mp(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;He(()=>{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=go(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=bo(u);m&&m.scrollBy({top:p.y,left:p.x})}},[t,l,c,s,r])}const Ro=i.createContext({...Be,scaleX:1,scaleY:1});var et;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(et||(et={}));const Ip=i.memo(function(t){var r,s,a,o;let{id:l,accessibility:c,autoScroll:d=!0,children:u,sensors:f=Sp,collisionDetection:p=Of,measuring:m,modifiers:h,...g}=t;const b=i.useReducer(Dp,void 0,Tp),[y,w]=b,[v,x]=Tf(),[j,k]=i.useState(et.Uninitialized),N=j===et.Initialized,{draggable:{active:S,nodes:C,translate:R},droppable:{containers:E}}=y,T=S!=null?C.get(S):null,M=i.useRef({initial:null,translated:null}),A=i.useMemo(()=>{var ue;return S!=null?{id:S,data:(ue=T==null?void 0:T.data)!=null?ue:Ep,rect:M}:null},[S,T]),P=i.useRef(null),[_,G]=i.useState(null),[D,$]=i.useState(null),W=_t(g,Object.values(g)),z=Gt("DndDescribedBy",l),q=i.useMemo(()=>E.getEnabled(),[E]),L=Lp(m),{droppableRects:F,measureDroppableContainers:O,measuringScheduled:X}=mp(q,{dragging:N,dependencies:[R.x,R.y],config:L.droppable}),J=fp(C,S),ie=i.useMemo(()=>D?pr(D):null,[D]),ee=yt(),H=hp(J,L.draggable.measure);Mp({activeNode:S!=null?C.get(S):null,config:ee.layoutShiftCompensation,initialRect:H,measure:L.draggable.measure});const B=Os(J,L.draggable.measure,H),Z=Os(J?J.parentElement:null),ne=i.useRef({activatorEvent:null,active:null,activeNode:J,collisionRect:null,collisions:null,droppableRects:F,draggableNodes:C,draggingNode:null,draggingNodeRect:null,droppableContainers:E,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),K=E.getNodeFor((r=ne.current.over)==null?void 0:r.id),se=Cp({measure:L.dragOverlay.measure}),I=(s=se.nodeRef.current)!=null?s:J,ae=N?(a=se.rect)!=null?a:B:null,ge=!!(se.nodeRef.current&&se.rect),oe=bp(ge?null:B),me=So(I?Re(I):null),de=vp(N?K??J:null),Oe=kp(de),Pe=Fp(h,{transform:{x:R.x-oe.x,y:R.y-oe.y,scaleX:1,scaleY:1},activatorEvent:D,active:A,activeNodeRect:B,containerNodeRect:Z,draggingNodeRect:ae,over:ne.current.over,overlayNodeRect:se.rect,scrollableAncestors:de,scrollableAncestorRects:Oe,windowRect:me}),Ge=ie?Nt(ie,R):null,bt=yp(de),Tt=zs(bt),it=zs(bt,[B]),V=Nt(Pe,Tt),Ae=ae?Hf(ae,Pe):null,Te=A&&Ae?p({active:A,collisionRect:Ae,droppableRects:F,droppableContainers:q,pointerCoordinates:Ge}):null,vt=xo(Te,"id"),[pe,Ye]=i.useState(null),Ie=ge?Pe:Nt(Pe,it),Fe=_f(Ie,(o=pe==null?void 0:pe.rect)!=null?o:null,B),lt=i.useRef(null),ct=i.useCallback((ue,ce)=>{let{sensor:he,options:we}=ce;if(P.current==null)return;const le=C.get(P.current);if(!le)return;const fe=ue.nativeEvent,ve=new he({active:P.current,activeNode:le,event:fe,options:we,context:ne,onAbort(re){if(!C.get(re))return;const{onDragAbort:ye}=W.current,je={id:re};ye==null||ye(je),v({type:"onDragAbort",event:je})},onPending(re,Ce,ye,je){if(!C.get(re))return;const{onDragPending:ut}=W.current,ke={id:re,constraint:Ce,initialCoordinates:ye,offset:je};ut==null||ut(ke),v({type:"onDragPending",event:ke})},onStart(re){const Ce=P.current;if(Ce==null)return;const ye=C.get(Ce);if(!ye)return;const{onDragStart:je}=W.current,dt={activatorEvent:fe,active:{id:Ce,data:ye.data,rect:M}};kt.unstable_batchedUpdates(()=>{je==null||je(dt),k(et.Initializing),w({type:xe.DragStart,initialCoordinates:re,active:Ce}),v({type:"onDragStart",event:dt}),G(lt.current),$(fe)})},onMove(re){w({type:xe.DragMove,coordinates:re})},onEnd:Y(xe.DragEnd),onCancel:Y(xe.DragCancel)});lt.current=ve;function Y(re){return async function(){const{active:ye,collisions:je,over:dt,scrollAdjustedTranslate:ut}=ne.current;let ke=null;if(ye&&ut){const{cancelDrop:Xe}=W.current;ke={activatorEvent:fe,active:ye,collisions:je,delta:ut,over:dt},re===xe.DragEnd&&typeof Xe=="function"&&await Promise.resolve(Xe(ke))&&(re=xe.DragCancel)}P.current=null,kt.unstable_batchedUpdates(()=>{w({type:re}),k(et.Uninitialized),Ye(null),G(null),$(null),lt.current=null;const Xe=re===xe.DragEnd?"onDragEnd":"onDragCancel";if(ke){const Dt=W.current[Xe];Dt==null||Dt(ke),v({type:Xe,event:ke})}})}}},[C]),Ne=i.useCallback((ue,ce)=>(he,we)=>{const le=he.nativeEvent,fe=C.get(we);if(P.current!==null||!fe||le.dndKit||le.defaultPrevented)return;const ve={active:fe};ue(he,ce.options,ve)===!0&&(le.dndKit={capturedBy:ce.sensor},P.current=we,ct(he,ce))},[C,ct]),qe=pp(f,Ne);wp(f),He(()=>{B&&j===et.Initializing&&k(et.Initialized)},[B,j]),i.useEffect(()=>{const{onDragMove:ue}=W.current,{active:ce,activatorEvent:he,collisions:we,over:le}=ne.current;if(!ce||!he)return;const fe={active:ce,activatorEvent:he,collisions:we,delta:{x:V.x,y:V.y},over:le};kt.unstable_batchedUpdates(()=>{ue==null||ue(fe),v({type:"onDragMove",event:fe})})},[V.x,V.y]),i.useEffect(()=>{const{active:ue,activatorEvent:ce,collisions:he,droppableContainers:we,scrollAdjustedTranslate:le}=ne.current;if(!ue||P.current==null||!ce||!le)return;const{onDragOver:fe}=W.current,ve=we.get(vt),Y=ve&&ve.rect.current?{id:ve.id,rect:ve.rect.current,data:ve.data,disabled:ve.disabled}:null,re={active:ue,activatorEvent:ce,collisions:he,delta:{x:le.x,y:le.y},over:Y};kt.unstable_batchedUpdates(()=>{Ye(Y),fe==null||fe(re),v({type:"onDragOver",event:re})})},[vt]),He(()=>{ne.current={activatorEvent:D,active:A,activeNode:J,collisionRect:Ae,collisions:Te,droppableRects:F,draggableNodes:C,draggingNode:I,draggingNodeRect:ae,droppableContainers:E,over:pe,scrollableAncestors:de,scrollAdjustedTranslate:V},M.current={initial:ae,translated:Ae}},[A,J,Te,Ae,C,I,ae,F,E,pe,de,V]),cp({...ee,delta:R,draggingRect:Ae,pointerCoordinates:Ge,scrollableAncestors:de,scrollableAncestorRects:Oe});const We=i.useMemo(()=>({active:A,activeNode:J,activeNodeRect:B,activatorEvent:D,collisions:Te,containerNodeRect:Z,dragOverlay:se,draggableNodes:C,droppableContainers:E,droppableRects:F,over:pe,measureDroppableContainers:O,scrollableAncestors:de,scrollableAncestorRects:Oe,measuringConfiguration:L,measuringScheduled:X,windowRect:me}),[A,J,B,D,Te,Z,se,C,E,F,pe,O,de,Oe,L,X,me]),Je=i.useMemo(()=>({activatorEvent:D,activators:qe,active:A,activeNodeRect:B,ariaDescribedById:{draggable:z},dispatch:w,draggableNodes:C,over:pe,measureDroppableContainers:O}),[D,qe,A,B,w,z,C,pe,O]);return Ee.createElement(po.Provider,{value:x},Ee.createElement(Dn.Provider,{value:Je},Ee.createElement(Eo.Provider,{value:We},Ee.createElement(Ro.Provider,{value:Fe},u)),Ee.createElement(Ap,{disabled:(c==null?void 0:c.restoreFocus)===!1})),Ee.createElement(Ff,{...c,hiddenTextDescribedById:z}));function yt(){const ue=(_==null?void 0:_.autoScrollEnabled)===!1,ce=typeof d=="object"?d.enabled===!1:d===!1,he=N&&!ue&&!ce;return typeof d=="object"?{...d,enabled:he}:{enabled:he}}}),$p=i.createContext(null),Ws="button",Bp="Draggable";function Op(e){let{id:t,data:r,disabled:s=!1,attributes:a}=e;const o=Gt(Bp),{activators:l,activatorEvent:c,active:d,activeNodeRect:u,ariaDescribedById:f,draggableNodes:p,over:m}=i.useContext(Dn),{role:h=Ws,roleDescription:g="draggable",tabIndex:b=0}=a??{},y=(d==null?void 0:d.id)===t,w=i.useContext(y?Ro:$p),[v,x]=jn(),[j,k]=jn(),N=jp(l,t),S=_t(r);He(()=>(p.set(t,{id:t,key:o,node:v,activatorNode:j,data:S}),()=>{const R=p.get(t);R&&R.key===o&&p.delete(t)}),[p,t]);const C=i.useMemo(()=>({role:h,tabIndex:b,"aria-disabled":s,"aria-pressed":y&&h===Ws?!0:void 0,"aria-roledescription":g,"aria-describedby":f.draggable}),[s,h,b,y,g,f.draggable]);return{active:d,activatorEvent:c,activeNodeRect:u,attributes:C,isDragging:y,listeners:s?void 0:N,node:v,over:m,setNodeRef:x,setActivatorNodeRef:k,transform:w}}function _p(){return i.useContext(Eo)}const zp="Droppable",Hp={timeout:25};function Wp(e){let{data:t,disabled:r=!1,id:s,resizeObserverConfig:a}=e;const o=Gt(zp),{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:g,updateMeasurementsFor:b,timeout:y}={...Hp,...a},w=_t(b??s),v=i.useCallback(()=>{if(!p.current){p.current=!0;return}h.current!=null&&clearTimeout(h.current),h.current=setTimeout(()=>{u(Array.isArray(w.current)?w.current:[w.current]),h.current=null},y)},[y]),x=Tn({callback:v,disabled:g||!l}),j=i.useCallback((C,R)=>{x&&(R&&(x.unobserve(R),p.current=!1),C&&x.observe(C))},[x]),[k,N]=jn(j),S=_t(t);return i.useEffect(()=>{!x||!k.current||(x.disconnect(),p.current=!1,x.observe(k.current))},[k,x]),i.useEffect(()=>(c({type:xe.RegisterDroppable,element:{id:s,key:o,disabled:r,node:k,rect:m,data:S}}),()=>c({type:xe.UnregisterDroppable,key:o,id:s})),[s]),i.useEffect(()=>{r!==f.current.disabled&&(c({type:xe.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 Vp(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 Up(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 Kp(e){return typeof e=="boolean"?{draggable:e,droppable:e}:e}const Po=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},Gp=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=Yp(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 Yp(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 To="Sortable",Do=Ee.createContext({activeIndex:-1,containerId:To,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:Po,disabled:{draggable:!1,droppable:!1}});function qp(e){let{children:t,id:r,items:s,strategy:a=Po,disabled:o=!1}=e;const{active:l,dragOverlay:c,droppableRects:d,over:u,measureDroppableContainers:f}=_p(),p=Gt(To,r),m=c.rect!==null,h=i.useMemo(()=>s.map(N=>typeof N=="object"&&"id"in N?N.id:N),[s]),g=l!=null,b=l?h.indexOf(l.id):-1,y=u?h.indexOf(u.id):-1,w=i.useRef(h),v=!Up(h,w.current),x=y!==-1&&b===-1||v,j=Kp(o);He(()=>{v&&g&&f(h)},[v,h,g,f]),i.useEffect(()=>{w.current=h},[h]);const k=i.useMemo(()=>({activeIndex:b,containerId:p,disabled:j,disableTransforms:x,items:h,overIndex:y,useDragOverlay:m,sortedRects:Vp(h,d),strategy:a}),[b,p,j.draggable,j.droppable,x,h,y,d,m,a]);return Ee.createElement(Do.Provider,{value:k},t)}const Jp=e=>{let{id:t,items:r,activeIndex:s,overIndex:a}=e;return Ur(r,s,a).indexOf(t)},Xp=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},Qp={duration:200,easing:"ease"},Ao="transform",Zp=Ht.Transition.toString({property:Ao,duration:0,easing:"linear"}),em={roleDescription:"sortable"};function tm(e){let{disabled:t,index:r,node:s,rect:a}=e;const[o,l]=i.useState(null),c=i.useRef(r);return He(()=>{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 nm(e){let{animateLayoutChanges:t=Xp,attributes:r,disabled:s,data:a,getNewIndex:o=Jp,id:l,strategy:c,resizeObserverConfig:d,transition:u=Qp}=e;const{items:f,containerId:p,activeIndex:m,disabled:h,disableTransforms:g,sortedRects:b,overIndex:y,useDragOverlay:w,strategy:v}=i.useContext(Do),x=rm(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:S,node:C,isOver:R,setNodeRef:E}=Wp({id:l,data:k,disabled:x.droppable,resizeObserverConfig:{updateMeasurementsFor:N,...d}}),{active:T,activatorEvent:M,activeNodeRect:A,attributes:P,setNodeRef:_,listeners:G,isDragging:D,over:$,setActivatorNodeRef:W,transform:z}=Op({id:l,data:k,attributes:{...em,...r},disabled:x.draggable}),q=yf(E,_),L=!!T,F=L&&!g&&rn(m)&&rn(y),O=!w&&D,X=O&&F?z:null,ie=F?X??(c??v)({rects:b,activeNodeRect:A,activeIndex:m,overIndex:y,index:j}):null,ee=rn(m)&&rn(y)?o({id:l,items:f,activeIndex:m,overIndex:y}):j,H=T==null?void 0:T.id,B=i.useRef({activeId:H,items:f,newIndex:ee,containerId:p}),Z=f!==B.current.items,ne=t({active:T,containerId:p,isDragging:D,isSorting:L,id:l,index:j,items:f,newIndex:B.current.newIndex,previousItems:B.current.items,previousContainerId:B.current.containerId,transition:u,wasDragging:B.current.activeId!=null}),K=tm({disabled:!ne,index:j,node:C,rect:S});return i.useEffect(()=>{L&&B.current.newIndex!==ee&&(B.current.newIndex=ee),p!==B.current.containerId&&(B.current.containerId=p),f!==B.current.items&&(B.current.items=f)},[L,ee,p,f]),i.useEffect(()=>{if(H===B.current.activeId)return;if(H!=null&&B.current.activeId==null){B.current.activeId=H;return}const I=setTimeout(()=>{B.current.activeId=H},50);return()=>clearTimeout(I)},[H]),{active:T,activeIndex:m,attributes:P,data:k,rect:S,index:j,newIndex:ee,items:f,isOver:R,isSorting:L,isDragging:D,listeners:G,node:C,overIndex:y,over:$,setNodeRef:q,setActivatorNodeRef:W,setDroppableNodeRef:E,setDraggableNodeRef:_,transform:K??ie,transition:se()};function se(){if(K||Z&&B.current.newIndex===j)return Zp;if(!(O&&!_r(M)||!u)&&(L||ne))return Ht.Transition.toString({...u,property:Ao})}}function rm(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 sm=[te.Down,te.Right,te.Up,te.Left],am=(e,t)=>{let{context:{active:r,collisionRect:s,droppableRects:a,droppableContainers:o,over:l,scrollableAncestors:c}}=t;if(sm.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=$f({collisionRect:s,droppableRects:a,droppableContainers:d});let f=xo(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,g=m==null?void 0:m.node.current;if(g&&h&&p&&m){const y=Pn(g).some((N,S)=>c[S]!==N),w=Fo(p,m),v=om(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:zt(j,x)}}}};function Fo(e,t){return!Cn(e)||!Cn(t)?!1:e.data.current.sortable.containerId===t.data.current.sortable.containerId}function om(e,t){return!Cn(e)||!Cn(t)||!Fo(e,t)?!1:e.data.current.sortable.index<t.data.current.sortable.index}function at(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 Lo({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 Mo(e){return{dead:e.sessionAlive===!1}}function im({claim:e,staleFetch:t=!1}){const r=Yt(),{dead:s}=Mo(e),a=e.claimedBy.agentProvider??"agent",o=s?" (inactive)":"",l=at(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 lm(){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 cm({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 dm({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 um({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 fm({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 pm({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 mm({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(pm,{dep:t},t.slug))})]})}function hm({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(Lo,{title:e,filePath:t}),l&&l.length>0&&n.jsx(mm,{dependencies:l}),n.jsx("div",{className:"px-3 py-2 max-h-[40vh] overflow-y-auto",children:n.jsx(pt,{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(um,{onClick:a}),n.jsx(fm,{providerLabel:s,onClick:o})]})]})}function xm({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}=lm(),{config:p}=ot(),m=st(p==null?void 0:p.provider);return i.useEffect(()=>{o(e.title),c(e.body),s("view")},[e.slug]),r==="chat"?n.jsx(cm,{slug:e.slug,onClose:()=>s("view")}):r==="edit"?n.jsx(dm,{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(hm,{title:e.title,filePath:e.filePath,body:e.body,providerLabel:m,onEdit:()=>s("edit"),onChat:()=>s("chat"),dependencies:t})}const Io="Building is in progress, please wait for it to complete before starting a new build session.";function gm({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?Io:void 0,className:l+(u?c:""),children:r?"Launching…":"Run"})}function $o({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:g=0,unsatisfiedDepTooltip:b,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(gm,{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}),g>0&&n.jsxs("span",{"data-testid":`plan-row-blocked-${e.slug}`,title:b,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 · ",g," dep",g===1?"":"s"]}),w&&n.jsx(im,{claim:w,staleFetch:v}),n.jsx("span",{className:"text-[10px] text-[var(--text-dim)] whitespace-nowrap",children:at(e.createdAt)})]}),t&&(x==="view"?n.jsxs("div",{className:"border-t border-[var(--border-subtle)]",children:[n.jsx(Lo,{title:e.title,filePath:e.filePath}),n.jsx("div",{className:"px-3 py-2 max-h-[40vh] overflow-y-auto",children:n.jsx(pt,{variant:"compact",children:e.body})})]}):n.jsx(xm,{plan:e,dependencies:y}))]})}function bm({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:g,listeners:b,setNodeRef:y,setActivatorNodeRef:w,transform:v,transition:x,isDragging:j}=nm({id:e.slug,disabled:!d}),k={transform:Ht.Transform.toString(v),transition:x};return n.jsx($o,{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?g:void 0,dragHandleListeners:d?b: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,g]=i.useState(null),[b,y]=i.useState(null),[w,v]=i.useState(null);i.useEffect(()=>{y(null)},[e]);const x=b??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(vm,{plans:x,loading:t,error:r,expandedSlug:h,onToggle:k=>g(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 vm({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 g=Lf(Ds(Vr,{activationConstraint:{distance:4}}),Ds(Hr,{coordinateGetter:am})),b=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(S=>S.slug===x.id),N=e.findIndex(S=>S.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(bm,{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(Ip,{sensors:g,collisionDetection:If,onDragEnd:y,children:n.jsx(qp,{items:b,strategy:Gp,children:w})}):w}function ym({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:g,launchingSlug:b,launchError:y,onReorderPlans:w,isAgentBuilding:v}){const{recoveryFeatureName:x,recoveryStep:j,recoveryMode:k,showTerminal:N,shouldResumeSameProvider:S}=ef({sessionDecision:s,sessionInfo:a,stepState:o});return s==="pending"?n.jsx(Zu,{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:C=>{var E;const R=((E=p.find(T=>T.slug===C))==null?void 0:E.title)??C;g(C,R)},launchingSlug:b,launchError:y,blocked:v,onReorder:w})}):N?n.jsx(vf,{provider:l,shouldResumeSameProvider:S,sessionId:(a==null?void 0:a.sessionId)??null,onAgentIdle:d,onAgentActive:u,onUserInput:f,currentFeature:(o==null?void 0:o.feature)??null}):s==="no-session"&&o===null?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-slate-500 space-y-4 px-10 text-center",children:[n.jsx("div",{className:"text-lg font-medium text-slate-400",children:"Ready to build"}),n.jsx("p",{className:"max-w-md",children:"Your first session will start automatically. You can queue changes or wait for the project to initialize."})]}):null}function wm(e){return e?{step:e.step??0,feature:e.feature??null,startedAt:e.startedAt??"",mode:Ke(e.mode),slug:e.slug??null}:null}const jm=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=wm(c),u=JSON.stringify(d);u!==o.current&&(o.current=u,t(d)),s(!1)}).catch(()=>{s(!1)})};return l(),a.current=setInterval(l,jm),()=>{a.current&&clearInterval(a.current)}},[]),{stepState:e,loading:r}}const De={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 km(e){return{hasSession:(e==null?void 0:e.hasSession)??De.hasSession,resumeMode:(e==null?void 0:e.resumeMode)??De.resumeMode,provider:(e==null?void 0:e.provider)??De.provider,feature:(e==null?void 0:e.feature)??De.feature,step:(e==null?void 0:e.step)??De.step,mode:(e==null?void 0:e.mode)==null?De.mode:Ke(e.mode),label:(e==null?void 0:e.label)??De.label,sessionId:(e==null?void 0:e.sessionId)??De.sessionId,awaitingUserInput:(e==null?void 0:e.awaitingUserInput)??De.awaitingUserInput,reopenResults:(e==null?void 0:e.reopenResults)??De.reopenResults,preview:(e==null?void 0:e.preview)??De.preview,agentBrokerLive:(e==null?void 0:e.agentBrokerLive)??De.agentBrokerLive}}function Bo(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(km(d))}catch{s(De)}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 Nm=5e3;function Cm(){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,Nm),()=>{a.current&&clearInterval(a.current)}},[]),{prompt:e,loading:r}}function Sm({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 Em=1e4;function Rm(){xn=Date.now()}function Pm(){if(xn==null)return!1;const e=Date.now()-xn;return xn=null,e<=Em}function Tm({sessionLoading:e,sessionInfo:t,onSessionDetected:r}){const s=i.useRef(!1),[a,o]=i.useState(()=>Pm()?"fresh":"no-session");i.useEffect(()=>{o(c=>Sm({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 Dm(){const e=document.activeElement;return e===null||e===document.body||e===document.documentElement||e instanceof HTMLElement&&e.dataset.navTab==="true"}function Am(e,t,r,s=0){return e>=r.left-s&&e<=r.right+s&&t>=r.top-s&&t<=r.bottom+s}function Vs(e){wn(),e.blur(),window.dispatchEvent(new Event("terminal-focus")),queueMicrotask(()=>{document.activeElement instanceof HTMLIFrameElement&&window.dispatchEvent(new Event("terminal-focus"))})}function Fm(e){const t=i.useRef(!1);i.useEffect(()=>{if(!e)return;function r(){if(!t.current&&Dm()){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&&Vs(c)}function o(l){const c=document.activeElement;if(!(c instanceof HTMLIFrameElement))return;const d=c.getBoundingClientRect();Am(l.clientX,l.clientY,d,1)||Vs(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 Lm({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 Mm(e){const t=i.useRef(e);i.useEffect(()=>{e&&e!==t.current&&(gn(e),t.current=e)},[e])}function Im(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 $m({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 Bm({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(pt,{variant:"compact",children:e})})}function Om({currentStep:e,isExpanded:t,mode:r,onToggle:s=()=>{},stepNum:a}){const o=a===e,l=a<e,{description:c,label:d}=Ga(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 _m({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),g=i.useRef(null),b=i.useRef(null),y=i.useRef(null);i.useLayoutEffect(()=>{if(!o)return;const C=()=>{var E;const R=(E=g.current)==null?void 0:E.getBoundingClientRect();R&&m({top:R.bottom+4,right:window.innerWidth-R.right})};return C(),window.addEventListener("resize",C),window.addEventListener("scroll",C,!0),()=>{window.removeEventListener("resize",C),window.removeEventListener("scroll",C,!0)}},[o]),i.useEffect(()=>{if(!o)return;const C=R=>{var T,M;const E=R.target;(T=h.current)!=null&&T.contains(E)||(M=b.current)!=null&&M.contains(E)||l(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[o]),Im(y,u,i.useCallback(()=>f(!1),[]));const w=t&&e>0,v=t||"New Working Session",x=Ke(r),j=Ga(e,x),k=w?j.label:null,N=j.totalSteps,S=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($m,{displayName:v,hasPrompt:!!a,expanded:u,onToggle:()=>f(C=>!C)})]}),w&&n.jsxs("div",{className:"relative",ref:h,children:[n.jsxs("button",{ref:g,onClick:()=>l(C=>!C),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:[S," ",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&&kt.createPortal(n.jsx("div",{ref:b,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},(C,R)=>R+1).map(C=>{const R=c===C;return n.jsx(Om,{currentStep:e,isExpanded:R,mode:x,onToggle:()=>d(R?null:C),stepNum:C},C)})}),document.body)]})]}),u&&a&&n.jsx(Bm,{prompt:a})]})}function zm({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:g,isAgentBuilding:b}){const{stepState:y}=qt(),{config:w,loading:v}=ot(),{prompt:x}=Cm(),{sessionInfo:j,loading:k}=Bo(),{sessionDecision:N,handleContinueSession:S}=Tm({sessionLoading:k,sessionInfo:j,onSessionDetected:r});return Fm(t),Lm({sessionLoading:k,sessionInfo:j,onRestorePreview:c}),Mm((y==null?void 0:y.feature)??null),n.jsx(Hu,{stepIndicator:n.jsx(_m,{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(ym,{awaitingPlanLaunchChoice:e,configLoading:v,sessionLoading:k,sessionDecision:N,sessionInfo:j,stepState:y,provider:l,onContinueSession:S,onAgentIdle:s,onAgentActive:a,onUserInput:o,pendingPlans:d,pendingPlansLoading:u,pendingPlansError:f,onLaunchPlan:p,launchingSlug:m,launchError:h,onReorderPlans:g,isAgentBuilding:b})})}function Oo({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?Ue(e,t):"",p=()=>{l("success"),d(!0)},m=()=>{l("error"),d(!1)};return i.useEffect(()=>{l("loading"),d(!1);const h=u.current;h!=null&&h.complete&&(h.naturalHeight!==0?(l("success"),d(!0)):(l("error"),d(!1)))},[f]),e?n.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",title:a,children:[n.jsx("img",{ref:u,src:f,alt:r,onLoad:p,onError:m,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 Hm({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 jt(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]}:jt(e,{defaultSelection:!0,selectedIndex:t.selectedIndex})}const r=Math.min(t.selectedIndex??0,e.length-1);return{selectedIndex:r,scenario:e[r]}}function Wm(e){return e==null?"":typeof e=="string"?e:typeof e=="object"&&typeof e.name=="string"?e.name:String(e)}const Vm="/api/editor-session-summary",Um=3e3;function Km(e=Um){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(Vm);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 Gm({onClose:e,onSelectScenario:t,previewSlug:r=null}){var b;const{summary:s,loading:a,refreshing:o,refresh:l}=Km(),[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??((b=u[c])==null?void 0:b.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||pf()||(y.key==="ArrowRight"?(y.preventDefault(),d(w=>{const v=jt(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=jt(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=jt(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 g=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(Hm,{refreshing:o,onRefresh:l,onClose:e}),n.jsxs("div",{className:"flex-1 overflow-auto p-4 space-y-4",children:[s.userPrompt&&n.jsx(Ym,{text:s.userPrompt}),n.jsx(an,{title:"Application",icon:"🌐",count:s.application.length,empty:g===0?"No scenarios in this session":void 0,children:s.application.length>0&&n.jsx(Jm,{scenarios:s.application,selectedSlug:p,onSelect:(y,w)=>{var x,j;const v=jt(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(qm,{scenarios:s.components,selectedSlug:p,onSelect:(y,w)=>{var x,j;const v=jt(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(Qm,{functions:s.functions})}),n.jsx(an,{title:"Modified Files",icon:"📄",count:s.modifiedFiles.length,children:s.modifiedFiles.length>0&&n.jsx(Zm,{files:s.modifiedFiles})})]})]})}function Ym({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(pt,{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(Xm,{scenario:s,isSelected:s.slug===t,onSelect:r},s.slug))})})}function qm({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 Jm({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 Xm({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(Oo,{screenshotPath:e.screenshotPaths[0],cacheBuster:e.screenshotCapturedAtMs??void 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 Qm({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:Wm(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 Zm({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 eh({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 th({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]),eh({showStepResults:r,showResultsPanel:s,openResults:c,closeResults:d}),{closeResults:d,openResults:c,resultsKey:o,showResultsPanel:s}}function nh(e){return(e==null?void 0:e.mode)==="ui"&&(e==null?void 0:e.slug)==="feature-complete"}function rh({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:g,pendingPlans:b,pendingPlansLoading:y,pendingPlansError:w,onLaunchPlan:v,launchingSlug:x,launchError:j,onReorderPlans:k,isAgentBuilding:N}){const{stepState:S}=qt(),{closeResults:C,resultsKey:R,showResultsPanel:E}=th({showResultsCommandKey:l,hideResultsCommandKey:c,showStepResults:nh(S)});return t?n.jsx(Wu,{activeTab:r,showResultsPanel:E,buildTab:n.jsx(zm,{awaitingPlanLaunchChoice:e,isActive:r==="build",onSessionDetected:s,onAgentIdle:d,onAgentActive:u,onUserInput:f,provider:h,onRestorePreview:g,pendingPlans:b,pendingPlansLoading:y,pendingPlansError:w,onLaunchPlan:v,launchingSlug:x,launchError:j,onReorderPlans:k,isAgentBuilding:N}),resultsPanel:n.jsx(Gm,{onClose:C,onSelectScenario:a,previewSlug:o},R),footer:n.jsx(Yd,{settings:p,onChange:m,agentName:h})}):null}function sh({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 ah({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 Us=["·","✢","✳","✶","✻","✽"],oh=160;function _o(){const[e,t]=i.useState(0);return i.useEffect(()=>{const r=window.setInterval(()=>t(s=>(s+1)%Us.length),oh);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:Us[e]})}function ih({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 lh({onNavigateToBuild:e,onDismiss:t}){return i.useEffect(()=>(U("banner-mounted",{}),()=>{U("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 ze(){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 ch=[{key:"home",label:"Home"},{key:"plan",label:"Plan"},{key:"build",label:"Build"},{key:"history",label:"History"}];function Ks(){if(typeof document>"u")return;const e=document.activeElement;e instanceof HTMLElement&&e.blur()}function dh({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&&(U("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(sh,{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:ch.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"),Ks()},className:"px-2.5 py-2.5 text-sm text-[#5A5A5A] cursor-not-allowed font-light",children:h.label},h.key):n.jsxs(_a,{href:Lt(h.key),"data-nav-tab":"true",onNavigate:()=>{t(h.key),Ks(),h.key==="build"&&ze()},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(ih,{})}),!1]}),d&&n.jsx(lh,{onNavigateToBuild:()=>t("build"),onDismiss:l??(()=>{})})]})}function uh(e,t){for(const r of e.filesByDirectory)for(const s of r.files)if(s.filePath===t)return s;return null}function zo(e){return e>=80?"#16a34a":e>=50?"#eab308":"#dc2626"}function Jt({coverage:e}){const t=Math.max(0,Math.min(100,e.percent)),r=zo(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 fh({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 ph({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(fh,{file:r,onSelectFile:t},r.filePath))})]})}function mh({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(ph,{group:r,onSelectFile:t},r.directory||"(root)"))})]})}function hh({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 xh({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(hh,{entry:r,onSelectFile:t},`${r.filePath}::${r.name}`))})]})}function Ho({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 gh({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(Ho,{file:r})},r.filePath))})]})}function bh({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 vh({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(bh,{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:zo(t.percent)},"data-testid":r,children:[Math.round(t.percent),"% overall"]})]})]})}function Wo({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 yh({onClose:e,fetchDetails:t=wh,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=uh(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(vh,{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(Wo,{warnings:s.coverageWarnings}),n.jsx(xh,{entries:s.entries,onSelectFile:f}),n.jsx(gh,{files:s.orphanedFiles,onSelectFile:f}),n.jsx(mh,{directories:s.filesByDirectory,onSelectFile:d})]})]})})}function wh(){return fetch("/api/coverage/details").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()})}function jh({appDetailProps:e,appOverviewProps:t,selectedApp:r}){const[s,a]=i.useState(!1),o=()=>a(!0),l=()=>a(!1),c=r?n.jsx(id,{app:r,...e,onCoverageClick:o}):n.jsx(zu,{...t,onCoverageClick:o},"app-overview");return n.jsxs(n.Fragment,{children:[c,s&&n.jsx(yh,{onClose:l})]})}function kh({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:g,pendingPlans:b,pendingPlansLoading:y,pendingPlansError:w,onLaunchPlan:v,launchingSlug:x,launchError:j,onReorderPlans:k,isAgentBuilding:N}){return r?n.jsx(rh,{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:g,pendingPlans:b,pendingPlansLoading:y,pendingPlansError:w,onLaunchPlan:v,launchingSlug:x,launchError:j,onReorderPlans:k,isAgentBuilding:N}):null}function Nh({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 Ch=[{key:"editor",label:"Editor"},{key:"preview",label:"Preview"}];function Sh({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:Ch.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 Eh({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(Sh,{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(Nh,{onMouseDown:r})]}),s]})}function Yr(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),{plansVersion:l}=ht(),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 Rh(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),{plansVersion:l,claimsVersion:c}=ht(),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 Ph(){const[e,t]=i.useState(null),{claimsVersion:r}=ht(),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 Th(){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",Dh="git push origin HEAD";function Ah(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:Dh};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 Fh({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}=Ah(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 Gs="codeyam-editor editor restart-server";function Vo({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:Gs}),"."," ",n.jsx("button",{type:"button",className:"underline text-rose-700 hover:text-rose-900",onClick:()=>void s(Gs),children:r?"Copied":"Copy command"})]})]})})}function Lh(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 Mh(e,t){return e.filter(r=>r.source==="local"||!t.has(r.slug))}function Ih(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 Uo(){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 $h(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 Ko(e){return e.filter(t=>!t.satisfied)}function Go(e){const{slugs:t}=Uo();return i.useMemo(()=>{const r={},s={};for(const a of e){const o=a.dependsOn??[];if(o.length===0)continue;const l=$h({...a,dependsOn:o},e,t);s[a.slug]=l;const c=Ko(l);c.length!==0&&(r[a.slug]={count:c.length,tooltip:c.map(d=>d.title??`missing: ${d.slug}`).join(", ")})}return{annotationsBySlug:r,dependenciesBySlug:s}},[e,t])}let Ct={hasActiveSession:!1,isAgentBuilding:!1,stepStateFeature:null};function qr(e){Ct={...Ct,...e}}function Bh(){return Ct}function Oh(){return Ct.hasActiveSession||Ct.isAgentBuilding||!!Ct.stepStateFeature}const _h=500;async function zh(){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}),U("clear-editor-session",{ok:e,...t!==void 0?{status:t}:{},snapshotReset:e})}async function Hh(){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}),U("stop-building",{ok:e,...t!==void 0?{status:t}:{},snapshotReset:e})}async function Xr(e={}){const t=Bh(),r=e.caller??"unknown",s=e.bypassLiveGuard===!0;if(Oh()&&!s){U("launch-editor-skill",{caller:r,suppressed:!0,snapshot:t,bypassLiveGuard:!1});return}of(),U("launch-editor-skill",{caller:r,suppressed:!1,snapshot:t,bypassLiveGuard:s}),e.provider!=="gemini"&&(oo(e.renameLabel??"Editor",r,Ea),ir("/clear\r"),await new Promise(a=>setTimeout(()=>{ir("/codeyam-editor\r"),a()},_h)))}async function Wh(e={}){if(await Jr(),!await zh()){U("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=Al(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(m=>{if(t&&m==="build"){window.history.pushState(null,"",Lt("home"));return}window.history.pushState(null,"",Lt(m)),m==="build"&&l(!0),m==="plan"&&d(!0)},[t]),f=i.useCallback(()=>{t||(window.history.pushState(null,"",Lt("build")),l(!0))},[t]),p=i.useCallback(()=>{l(!1)},[]);return{activeTab:a,buildActivated:o,planActivated:c,navigateToTab:u,showBuildTab:f,deactivateBuild:p}}function Zr(){const{showBuildTab:e}=Qr(typeof window>"u"?"/":window.location.pathname),{config:t}=ot(),[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(),Rm()}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 Yo(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 Vh={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 Uh({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:Vh[e]})]})}function Kh({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:Io}),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 Gh({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 ",at(e.claimedBy.startedAt,s)]}),n.jsxs("span",{"data-testid":"plan-foreign-claim-step",children:["on step ",o," (",at(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 Yh({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 qh=[{id:"describe",label:"Describe A Plan"},{id:"prototype",label:"Prototype A Plan"}];function Jh({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:qh.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 Ys(e){return e.source==="prototype"}function Xh(e,t){const[r,s]=i.useState(!1),a=i.useRef(new Set),o=Zr(),l=()=>{a.current=new Set(e.filter(Ys).map(c=>c.slug)),s(!0)};return i.useEffect(()=>{if(!r||o.launchingSlug)return;const c=e.filter(Ys).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 Qh({onClose:e}){return n.jsx(Sn,{chatName:"prototype",slashCommand:"/codeyam-prototype",height:480,onClose:e})}const Zh="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 ex(){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."})," ",Zh]})}function qs({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 tx='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 nx({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(tx),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 rx(e,t){return`Launches a chat window with ${e} to ${t==="describe"?"describe your plan":"start prototyping"}.`}function qo({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:rx(e,t)})}function sx({isAgentBuilding:e,onLaunched:t}){const[r,s]=i.useState(!1),{plans:a}=Yr(),{config:o}=ot(),l=st(o==null?void 0:o.provider),c=Xh(a,()=>{s(!1),t==null||t()}),d=()=>{if(e)return;const f=!r;f&&ze(),s(f)},u=()=>{s(!1)};return e?n.jsxs("div",{"data-testid":"prototype-pane",children:[n.jsx(ex,{}),n.jsx(qs,{open:!1,disabled:!0,onToggle:()=>{}})]}):n.jsxs("div",{"data-testid":"prototype-pane",children:[n.jsx(qs,{open:r,onToggle:d}),!r&&n.jsx(qo,{providerLabel:l,kind:"prototype"}),r&&n.jsxs(n.Fragment,{children:[n.jsx(Qh,{onClose:u}),n.jsx(nx,{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 ax({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 ox({onClose:e}){return n.jsx(Sn,{chatName:"plan",slashCommand:"/codeyam-plan",height:360,onClose:e})}function ix({providerLabel:e,chatOpen:t,onChatToggle:r,onChatClose:s}){return n.jsxs("div",{"data-testid":"describe-pane",children:[n.jsx(ax,{open:t,onToggle:r}),!t&&n.jsx(qo,{providerLabel:e,kind:"describe"}),t&&n.jsx(ox,{onClose:s})]})}function lx({claim:e}){const t=Yt(),r=e.claimedBy.agentProvider??"agent",s=e.claimedBy.machine,a=e.claimedBy.currentStep??null,o=at(e.currentStepEnteredAt,t),l=at(e.claimedBy.startedAt,t),{dead:c}=Mo(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 cx({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(lx,{claim:t},`${t.slug}:${t.claimedBy.machine}:${t.claimedBy.sessionId}:${t.claimedBy.pid}:${t.claimedBy.startedAt}`))})]})}const dx=5e3;function ux(){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 g=await fetch("/api/branch-queue/status");if(!g.ok)throw new Error(`HTTP ${g.status}`);const b=await g.json();if(f.current)return;t(Array.isArray(b.entries)?b.entries:[]),s(b.branch??null),o(b.remote??null)}catch(g){if(f.current)return;u(g instanceof Error?g.message:"Failed to load branch queue"),t([])}finally{f.current||c(!1)}},[]);i.useEffect(()=>{f.current=!1,p();const g=setInterval(()=>{p()},dx);return()=>{f.current=!0,clearInterval(g)}},[p]);const m=i.useCallback(async(g,b,y)=>{const w={uuid:g,priority:b};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 g=>{const b=await fetch("/api/branch-queue/release",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({uuid:g})});if(!b.ok){const y=await b.text().catch(()=>"");throw new Error(`release ${b.status}: ${y}`)}await p()},[p]);return{entries:e,branch:r,remote:a,loading:l,error:d,setPriority:m,release:h,refetch:p}}function fx(){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 px(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 mx({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 hx({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 xx({entry:e,isHead:t}){const r=Yt(),s=e.meta.agentProvider??"agent",a=e.meta.machine,o=e.meta.currentStep??null,l=at(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 gx({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(xx,{entry:e,isHead:r}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(mx,{priority:e.meta.priority,uuid:e.uuid,onNudge:s}),n.jsx(hx,{uuid:e.uuid,onRelease:a})]})]})}function bx({entriesOverride:e,branchOverride:t}={}){const r=ux(),s=e??r.entries,a=t??r.branch,o=e?async()=>{}:r.setPriority,l=e?async()=>{}:r.release,c=fx(),[d,u]=i.useState(null);if(!e&&r.loading&&s.length===0||s.length===0)return null;const f=async h=>{const g=c.dragSourceUuid;if(g===null)return;const b=s.findIndex(v=>v.uuid===g);if(c.reset(),b===-1||b===h)return;const y=px(s,b,h),w=s[b].meta.priority;if(y!==w){u(null);try{await o(g,y,w)}catch(v){u(v instanceof Error?v.message:"Failed to update priority")}}},p=async(h,g)=>{const b=h.meta.priority;u(null);try{await o(h.uuid,b+g,b)}catch(y){u(y instanceof Error?y.message:"Failed to update priority")}},m=async h=>{u(null);try{await l(h.uuid)}catch(g){u(g instanceof Error?g.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,g)=>n.jsx(gx,{entry:h,position:g+1,isHead:g===0,onPriorityNudge:b=>p(h,b),onRelease:()=>m(h),onDragStart:()=>c.beginDrag(h.uuid),onDragOver:()=>c.hoverOver(h.uuid),onDrop:()=>f(g),isDragging:c.dragSourceUuid===h.uuid,isDragOver:c.dragOverUuid===h.uuid&&c.dragSourceUuid!==h.uuid},h.uuid))})]})}function vx(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 yx({journalTimestamp:e}){const{entry:t,loading:r,error:s}=vx(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(qa,{entry:t}):n.jsx("p",{className:"text-sm text-[var(--text-dim)]",children:"No journal entry found for this plan yet."})}function wx({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:at(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(yx,{journalTimestamp:e.journalTimestamp})})]})}function jx({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(kx,{plans:e,loading:t,error:r,expandedSlug:s,onToggle:l=>a(c=>c===l?null:l)})]})}function kx({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(wx,{plan:o,expanded:s===o.slug,onToggle:()=>a(o.slug)},o.slug))})}function Nx({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}=Rh(),{slugs:h}=Uo(),{status:g}=Ph(),{staleness:b}=Th(),y=((g==null?void 0:g.consecutiveFailures)??0)>=3,{plans:w,loading:v,error:x}=Ih(),{config:j}=ot(),k=st(j==null?void 0:j.provider),N=l!==void 0,S=Zr(),C=N?a??null:S.launchingSlug,R=N?o??null:S.error,[E,T]=i.useState(!1),[M,A]=i.useState(!1),[P,_]=i.useState(null),[G,D]=i.useState(null),$=i.useMemo(()=>Lh(m),[m]),W=i.useMemo(()=>Mh(m,h),[m,h]),[z,q]=i.useState(c),L=e!==void 0,F=L?e:E,O=K=>{L||T(K),t==null||t(K)},X=()=>{O(!1),p()},J=()=>{const K=!F;K&&ze(),O(K)};i.useEffect(()=>{if(!(!r||!F))return ze()},[r,F]);const{annotationsBySlug:ie,dependenciesBySlug:ee}=Go(d),H=K=>{var I;const se=((I=d.find(ae=>ae.slug===K))==null?void 0:I.title)??K;if(l){l(K,se);return}S.launchPlan(K,se)},B=K=>{const se=Ko(ee[K]??[]);if(se.length>0){_(se);return}const I=$.get(K);if(I&&I.source!=="local"){D(I);return}H(K)},Z=()=>{const K=G;if(K){if(D(null),K.sessionAlive===!1){fetch(`/api/plan-claims/${encodeURIComponent(K.slug)}/reclaim`,{method:"POST"}).catch(()=>{}).finally(()=>H(K.slug));return}H(K.slug)}},{reorderPlans:ne}=Yo(p);return n.jsxs(Lr,{testId:"plan-tab",children:[n.jsx(Uh,{subTab:z}),n.jsx(Jh,{active:z,onChange:q}),z==="describe"&&n.jsx(ix,{providerLabel:k,chatOpen:F,onChatToggle:J,onChatClose:X}),z==="prototype"&&n.jsx(sx,{isAgentBuilding:s,onLaunched:()=>q("describe")}),n.jsx(Vo,{staleness:b}),n.jsx(Fh,{status:g}),n.jsx(Kr,{plans:d,loading:u,error:f,onRun:B,launchingSlug:C,launchError:R,blocked:s,onBlockedClick:()=>A(!0),onReorder:ne,depAnnotationsBySlug:ie,dependenciesBySlug:ee,claimsBySlug:$,staleFetch:y}),n.jsx(cx,{claims:W}),n.jsx(bx,{}),n.jsx(jx,{plans:w,loading:v,error:x}),M&&n.jsx(Kh,{onClose:()=>A(!1)}),P&&!M&&n.jsx(Yh,{deps:P,onClose:()=>_(null)}),G&&n.jsx(Gh,{claim:G,onCancel:()=>D(null),onConfirm:Z})]})}function Cx({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(Nx,{chatOpen:r,onChatOpenChange:s,isActive:e==="plan",isAgentBuilding:a,launchingSlug:o,launchError:l,onLaunchPlan:c})}):null}function Sx({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 Ex({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(Sx,{visible:e===s,children:t[s]},s))})}function Rx({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 Px({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(Ex,{activeTab:e,width:r,children:{home:t,build:null,plan:null,history:a?n.jsx($d,{}):null,settings:n.jsx(Rx,{title:"Settings"})}})})}function Tx({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:g}=Go(e),b=i.useCallback(j=>{j.key==="Escape"&&(j.preventDefault(),c())},[c]);i.useEffect(()=>(window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)),[b]);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(S=>S.slug===j))==null?void 0:N.title)??j;t(j,k)},launchingSlug:r,launchError:s,blocked:f,depAnnotationsBySlug:h,dependenciesBySlug:g})}),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 Dx({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 Ax({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(Dx,{onCreateNewPlan:e,onViewPlans:t})})}function Fx(e){return!e||!(e instanceof Element)?!1:!!e.closest("[data-terminal-emulator], .xterm")}function Lx(e){return!e||!(e instanceof Element)?!1:!!e.closest("[data-post-push-modal]")}function Mx({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 Ix({onStartNextFeature:e,onContinueInSession:t,onStopBuilding:r,onSendTranscript:s,onSelectPlan:a,pendingPlanCount:o=0}){const l=i.useCallback(c=>{if(c.key!=="Enter"||Fx(c.target))return;const d=c.target===document.body||c.target===document.documentElement||c.target===document;!Lx(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(Mx,{onStartNextFeature:e,onContinueInSession:t,onStopBuilding:r,onSendTranscript:s,onSelectPlan:a,pendingPlanCount:o})})}function $x({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($o,{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 Bx({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:g,onAgentIdle:b,onUserInput:y,notifSettings:w,onSettingsChange:v,provider:x,onContinueInSession:j,onRestorePreview:k,onResultsScenarioSelect:N,previewSlug:S=null,onSessionDetected:C,onStartNextFeature:R,onStopBuilding:E,showPostPushModal:T,showResultsCommandKey:M,planChatOpen:A,onPlanChatOpenChange:P,showPlanCompleteModal:_,onCreateNewPlan:G,onViewPlans:D,pendingPlans:$,onSelectPlan:W,selectPlanOpen:z,onPickPlan:q,onCancelSelectPlan:L,launchingPlanSlug:F,planLaunchError:O,showBuildLaunchModal:X=!1,onSubmitBuildPrompt:J,submittingBuildPrompt:ie=!1,buildPromptError:ee=null,onCancelBuildLaunchModal:H,pendingPlansLoading:B,pendingPlansError:Z,onReorderPlans:ne,buildDisabled:K=!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(dh,{activeTab:e,onTabChange:h,onSendTranscript:t,buildIdle:l,isAgentBuilding:c,bannerVisible:d,onDismissIdleBanner:u,buildDisabled:K}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden relative",children:[n.jsx(kh,{awaitingPlanLaunchChoice:s,buildActivated:a,activeTab:e,onSessionDetected:C,onSelectScenario:N,previewSlug:S,showResultsCommandKey:M,hideResultsCommandKey:f,onAgentIdle:b,onAgentActive:g,onUserInput:y,notifSettings:w,onSettingsChange:v,provider:x,onRestorePreview:k,pendingPlans:$,pendingPlansLoading:B,pendingPlansError:Z,onLaunchPlan:q,launchingSlug:F,launchError:O,onReorderPlans:ne,isAgentBuilding:c}),n.jsx(Cx,{activeTab:e,planActivated:o,chatOpen:A,onChatOpenChange:P,isAgentBuilding:c,launchingPlanSlug:F,planLaunchError:O,onLaunchPlan:q}),n.jsx(Px,{activeTab:e,appTabContent:r,leftWidth:p}),T&&e==="build"&&!z?n.jsx(Ix,{onStartNextFeature:R,onContinueInSession:j,onStopBuilding:E,onSendTranscript:t,onSelectPlan:W,pendingPlanCount:$.length}):null,z&&e==="build"?n.jsx($x,{plans:$,onSelect:q,onCancel:L,launchingSlug:F,error:O}):null,X&&e==="build"&&!T&&J&&H?n.jsx(Tx,{plans:$,onPickPlan:q,launchingSlug:F,planError:O,onSubmitPrompt:J,submittingPrompt:ie,promptError:ee,onCancel:H,pendingPlansLoading:B,pendingPlansError:Z,isAgentBuilding:c}):null,_&&e==="plan"?n.jsx(Ax,{onCreateNewPlan:G,onViewPlans:D}):null]})]})}const Js=5173;function es(e){if(e.startsWith("http"))try{return new URL(e).pathname}catch{return e}return e.split("?")[0]??e}function Jo(e){return e?parseInt(e.port||(e.protocol==="https:"?"443":"80"),10):0}function Xo(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 Xo(r,{appPort:s,currentPort:t,previewOrigin:a});const o=`/scenario/${e}`;return a?`${a}${o}`:t===Js?o:`http://localhost:${Js}${o}`}async function Xs(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 Ox(e){try{await fetch("/api/editor-iframe-error",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({error:e})})}catch{}}async function _x(e){try{await fetch("/api/editor-iframe-banner",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({seedError:e})})}catch{}}function zx(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 Hx=32;function Wx({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:zx(s.width,s.height,t,e,Hx);return{containerRef:d,containerSize:s,scale:u}}function Vx(){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(Ux(s))}).catch(()=>{r||t({kind:"iframe",fallbackKind:null,fallbackPort:null,loading:!1})}),()=>{r=!0}},[]),e}function Ux(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:Kx(r.kind),fallbackKind:Gx(r.fallbackKind),fallbackPort:typeof r.fallbackPort=="number"?r.fallbackPort:null,loading:!1}}function Kx(e){return e==="simulator-ios"?"simulator-ios":"iframe"}function Gx(e){return e==="iframe"||e==="simulator-ios"?e:null}function Yx(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 Qs(){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 qx=50,Jx={status:"loading",lastSuccessAt:null,lastErrorAt:null,lastErrorMessage:null,fetchCount:0,errorCount:0};function Xx(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 Qx(e,t){return{timestamp:t,success:e.ok,statusCode:e.statusCode,durationMs:e.durationMs,error:e.error}}function Zx(e,t){return[t,...e].slice(0,qx)}function eg(){const[e,t]=i.useState(Jx),[r,s]=i.useState([]),a=i.useCallback(l=>{const c=Date.now();s(d=>Zx(d,Qx(l,c))),t(d=>Xx(d,l,c))},[]),o=i.useCallback(()=>{t(l=>({...l,status:"polling"}))},[]);return{connectionState:e,fetchLog:r,recordFetch:a,markPolling:o}}function tg(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 ng({state:e}){const t=Yt(),{dotClass:r,label:s,labelClass:a}=tg(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 ",gl(e.lastSuccessAt,t)]})]})}function rg({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 sg({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(rg,{entry:a},a.timestamp))})})]})}function ag({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 og({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(ag,{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 ig({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(Ho,{file:r},r.filePath))})]})]})}function lg(){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 cg({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 dg(){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 ug({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 fg(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 pg({failures:e}){const t=fg(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 mg({report:e}){if(!e)return n.jsx(lg,{});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(cg,{global:e.global,failureCount:e.failures.length}),e.usedDefaultThresholds&&n.jsx(dg,{}),t?n.jsx(ug,{ranRunners:e.ranRunners}):n.jsx(pg,{failures:e.failures})]})}const hg=new Set([3,4,6]),xg=5e3;function gg(){const[e,t]=i.useState(null),[r,s]=i.useState(!0),{connectionState:a,fetchLog:o,recordFetch:l,markPolling:c}=eg(),d=i.useRef(null);if(i.useEffect(()=>{async function m(){const h=await Qs();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&&hg.has(e.step)&&(d.current=setInterval(async()=>{c();const m=await Qs();l(m),m.ok&&m.data&&t(m.data)},xg)),()=>{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=Yx(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(ng,{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(Ua,{children:e.userPrompt})]})]}),n.jsx(kd,{currentStep:u}),n.jsx(Nd,{stats:e.testRunnerStats}),n.jsx(Wo,{warnings:e.coverageWarnings??[]}),p&&n.jsx("div",{className:"text-sm text-[var(--text-secondary)] text-center",children:p}),e.narrative&&n.jsx(Cd,{narrative:e.narrative}),e.narrative?n.jsx(Sd,{narrative:e.narrative}):n.jsx(Pd,{step:u,fileCount:e.modifiedFiles.length,testCount:f}),n.jsx(ig,{projectWide:e.projectWideCoverage??null,orphanedFiles:e.orphanedFiles??[]}),n.jsx(og,{functions:e.functions,aggregate:e.coverage??null,projectWide:e.projectWideCoverage??null}),n.jsx(mg,{report:e.coverageThresholds??null}),e.modifiedFiles.length>0&&n.jsx(Dd,{files:e.modifiedFiles,defaultCollapsed:e.narrative!==null}),n.jsx(sg,{state:a,entries:o})]})})}function bg(){return n.jsx("div",{className:"flex-1 flex flex-col min-w-0 overflow-auto",style:{background:"var(--bg-deep)"},children:n.jsx(gg,{})})}function vg({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 yg(){const[e,t]=i.useState(null),r=i.useRef(!0),s=i.useCallback(async()=>{try{const a=await fetch("/api/editor-design-uploads");if(!a.ok)return;const o=await a.json();r.current&&t(Array.isArray(o.uploads)?o.uploads:[])}catch{}},[]);return i.useEffect(()=>(r.current=!0,s(),()=>{r.current=!1}),[s]),n.jsxs("div",{className:"flex-1 flex flex-col min-w-0",style:{padding:"var(--spacing-lg, 16px)",gap:"var(--spacing-md, 12px)",overflow:"auto"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"var(--text-md, 15px)",fontWeight:600,color:"var(--text-primary)",marginBottom:"var(--spacing-xs, 4px)"},children:"Add design assets"}),n.jsx("div",{style:{fontSize:"var(--text-sm, 14px)",color:"var(--text-secondary)",lineHeight:1.5},children:"Drag design assets onto codeyam-editor, or browse to add them — logos, screenshots, brand guides, inspiration. The agent reads whatever you add and folds it into the mockups."})]}),n.jsx(so,{onUploadComplete:s}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-sm, 8px)"},children:[n.jsx("div",{style:{fontSize:"var(--text-sm, 14px)",fontWeight:600,color:"var(--text-primary)"},children:"Added assets"}),e===null?n.jsx("div",{style:{fontSize:"var(--text-sm, 14px)",color:"var(--text-secondary)"},children:"Loading…"}):e.length===0?n.jsx("div",{style:{fontSize:"var(--text-sm, 14px)",color:"var(--text-secondary)"},children:"No assets added yet."}):e.map(a=>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.jsx("span",{style:{fontSize:"var(--text-sm, 14px)",fontWeight:500,color:"var(--text-primary)"},children:a.filename}),a.description.trim().length>0&&n.jsx("span",{style:{fontSize:"var(--text-xs, 12px)",color:"var(--text-secondary)"},children:a.description})]},a.filename))]})]})}function wg(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=Zs(t.primaryFont,t.primaryFontStack);r.push(`body, p, li, span, button, input, textarea, select, label { font-family: ${d} !important; }`)}if(t.secondaryFont){const d=Zs(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 Zs(e,t){const r=/\s/.test(e)?`"${e}"`:e,s=(t==null?void 0:t.trim())||"system-ui, sans-serif";return`${r}, ${s}`}const jg={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 kg(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 Ng="\x1B[200~",Cg="\x1B[201~";function Sg(e,t=Eg){const r=e.replace(/\r\n/g,"\r").replace(/\n/g,"\r"),s=`${Ng}${r}${Cg}`;return t(s),new Promise(a=>{setTimeout(()=>{t("\r"),a()},bl)})}function Eg(e){window.dispatchEvent(new CustomEvent("miniagent-send-input",{detail:e}))}function Rg({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 Pg(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 g=d[1].length;o=o.slice(0,g-1),o[g-1]=d[2].trim();continue}if(!c.startsWith("|"))continue;const u=c.split("|").map(g=>g.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)||!Tg(p))continue;const m=o.filter(Boolean).join(" / "),h=Zo(m)?r:t;f in h||(h[f]=p)}return{light:t,dark:r}}function Zo(e){return/\bdark[\s-]?mode\b|\bdark\b\s*(palette|variant|theme)?/i.test(e)}function Tg(e){return!!(/^#[0-9a-fA-F]{3,8}$/.test(e)||/^rgba?\(/i.test(e)||/^hsla?\(/i.test(e)||/^oklch\(/i.test(e))}const Dg=["Background","Surface","Text","Primary","Secondary","Accent"],Ag={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 Fg(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 Mg(p)){const h=c.filter(Boolean).join(" / "),g=Lg(m.selector)||Zo(h);t.push({selector:m.selector,heading:l,isDark:g,vars:m.vars})}}s=!1,a=""}}return t}function Lg(e){return/\[data-theme[~|*$^]?="?dark"?\]/.test(e)}function Mg(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 Ig(e,t){const r=Ag[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 $g(e){const t=/\[data-palette[~|*$^]?="?([^"\]]+)"?\]/.exec(e);return t?t[1].split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" "):null}function Bg(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 ea(e){const t=Dg.map(r=>{const{cssVar:s,value:a}=Ig(e,r);return{label:r,cssVar:s,value:a}});return{vars:e,slots:t}}function ei(e){const t=Fg(e),r=new Map,s=new Map,a=[];for(const o of t){const c=$g(o.selector)??Bg(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=Pg(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:ea(l),dark:c?ea(c):null}}).filter(o=>o!==null)}function Og(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=ei(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 _g(){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 ti(){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 zg({round:e}){if(!e||!e.mockups||e.mockups.length===0)return n.jsx(ti,{});const t=e.feedback??{};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((r,s)=>{const a=t[r.filename],o=s+1,l=r.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(o).padStart(2,"0")}),n.jsx("a",{href:r.url,target:"_blank",rel:"noopener noreferrer",style:{textTransform:"capitalize",fontWeight:500,color:"var(--text-primary)",textDecoration:"none"},children:l})]}),n.jsx("iframe",{src:r.url,title:r.name,sandbox:"",style:{width:"100%",aspectRatio:"1 / 1",border:"none",pointerEvents:"none",background:"var(--bg-card, #1a1a1a)"}}),a&&(typeof a.rating=="number"||a.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 a.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:[a.rating,"/100"]})]}),a.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:a.comment})]})]})]},r.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]}],Hg={sans:"Sans-serif",serif:"Serif",display:"Display",mono:"Monospace"};function ni(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 Wg(e,t,r){const s={},a=ta(e,r),o=ta(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 ta(e,t){return e?t==="dark"&&e.dark?e.dark.slots:e.light.slots:[]}function Vg(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 Ug(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:ei(d)})}catch(o){a||s({kind:"error",message:o instanceof Error?o.message:String(o)})}})(),()=>{a=!0}},[e,t]),r}function ri(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:na(t),dark:r?na(r):null}}function na(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 Kg(){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 Gg({palettes:e,activeName:t,theme:r,onApply:s}){const a=(()=>{const o=new Set(e.map(c=>c.name.toLowerCase())),l=Kg().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 Yg({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=qg(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 qg(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 ra({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 Jg({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(ra,{children:"Palettes"}),n.jsx(Gg,{palettes:e,activeName:t,theme:r,onApply:o})]}),n.jsxs("div",{children:[n.jsx(ra,{children:"Individual colors"}),n.jsx(Yg,{slots:s,values:a,onChange:l})]})]})}function Xg({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 sa=!1;function Qg(){if(sa||typeof document>"u")return;sa=!0;const e=ni(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 aa({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(()=>{Qg()},[]);const u=i.useCallback(()=>o(!1),[]);ri(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(oa,{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:Hg[p]}),f[p].map(m=>n.jsx(oa,{family:m.family,label:m.family,isActive:t===m.family,onPick:()=>{r(m.family),o(!1)}},m.family))]},p))]})]})}function oa({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(aa,{label:"Headings",value:t,onChange:s}),n.jsx(aa,{label:"Body text",value:e,onChange:r})]})}function si(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 eb(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 tb({html:e,srcDoc:t,theme:r,mockupUrl:s,mockupName:a}){const o=si(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 ai({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 nb({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(ai,{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 rb({mockup:e,systemName:t,initial:r,onBack:s,onSave:a,saving:o=!1}){var R;const l=Ug(e.url,t),[c,d]=i.useState(r),[u,f]=i.useState(null),[p,m]=i.useState("light"),[h,g]=i.useState(null),b=i.useRef(null),y=i.useCallback(()=>g(null),[]);ri(h!==null,b,y);const w=i.useMemo(()=>{const E=[];return c.primaryFont&&E.push(c.primaryFont),c.secondaryFont&&E.push(c.secondaryFont),E.length===0?null:ni(E)},[c.primaryFont,c.secondaryFont]),v=i.useMemo(()=>l.kind!=="ready"?c.vars:Vg(l.palettes,p,c.vars),[l,c.vars,p]),x=i.useMemo(()=>l.kind!=="ready"?"":wg(l.html,{...c,vars:v,fontsHref:w}),[l,c,v,w]),j=i.useCallback(E=>{f(E.name);const T=l.kind==="ready"?l.palettes[0]:void 0,M=Wg(T,E,p);d(A=>({...A,vars:{...A.vars,...M}}))},[l,p]),k=i.useCallback((E,T)=>{f(null),d(M=>({...M,vars:{...M.vars,[E]:T}}))},[]),N=i.useCallback(()=>{d({vars:{},primaryFont:null,secondaryFont:null,primaryFontStack:null,secondaryFontStack:null}),f(null)},[]),S=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]),C=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:b,children:[n.jsx(nb,{systemName:t,openMenu:h,theme:p,hasDark:C,saving:o,toolbarRef:{current:null},onBack:()=>s(c),onToggleMenu:E=>g(T=>T===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(T=>({...T,primaryFont:E})),onSecondaryChange:E=>d(T=>({...T,secondaryFont:E}))}),h==="colors"&&n.jsx(Jg,{palettes:l.kind==="ready"?l.palettes:[],activeName:u,theme:p,slots:S,vars:c.vars,onApplyPalette:j,onColorChange:k})]}),l.kind==="error"&&n.jsx(Xg,{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(tb,{html:l.html,srcDoc:x,theme:p,mockupUrl:e.url,mockupName:e.name}):null]})}const sb={desktop:{w:1440,h:900},tablet:{w:834,h:1112},mobile:{w:390,h:844}},ia="desktop",ab=1280,ob=1280,ib="#1a1a1a",lb="radial-gradient(circle, rgba(255,255,255,0.07) 1px, transparent 1px)",cb="12px 12px";function db(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 ub({warnings:e}){const t=e.map(r=>`• ${r.message}`).join(`
|
|
50
|
+
`);return n.jsxs("span",{title:t,"aria-label":`${e.length} mockup lint warning${e.length===1?"":"s"}`,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 7px",borderRadius:6,border:"1px solid var(--border-default)",background:"var(--bg-card, #1a1a1a)",color:"var(--text-muted)",fontSize:"var(--text-xs, 12px)",fontWeight:500,cursor:"help",flexShrink:0},children:[n.jsx("span",{"aria-hidden":"true",children:"⚠"}),e.length]})}function fb(){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 pb({displayNumber:e,formattedName:t,theme:r,showThemeToggle:s,busy:a,warnings:o,openInNewTabUrl:l,onToggleTheme:c,onChoose:d,onCustomize:u}){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")}),l?n.jsxs("a",{href:l,target:"_blank",rel:"noopener noreferrer","aria-label":`Open ${t} in new tab`,title:"Open in new tab",onClick:f=>f.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(fb,{})})]}):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:[o&&o.length>0&&n.jsx(ub,{warnings:o}),s&&n.jsx(ai,{theme:r,onToggle:c}),n.jsx("button",{type:"button",onClick:u,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:d,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"})]})]})}const mb=700;function hb({srcDoc:e,url:t,theme:r,scale:s,hasContent:a}){const[o,l]=i.useState(!1),[c,d]=i.useState(!1),u=i.useRef([]);i.useEffect(()=>{l(!1),d(!1);const h=window.setTimeout(()=>d(!0),mb);return()=>window.clearTimeout(h)},[e,t,r]);const f=()=>{const h=window.requestAnimationFrame(()=>{const g=window.requestAnimationFrame(()=>l(!0));u.current.push(g)});u.current.push(h)};i.useEffect(()=>()=>{u.current.forEach(h=>window.cancelAnimationFrame(h)),u.current=[]},[]);const p=o&&s>0;return{handleIframeLoad:f,visible:p,showSkeleton:!a||!p||!c}}function Se({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 xb(){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:`
|
|
51
|
+
@keyframes mockup-skeleton-shimmer {
|
|
52
|
+
0% { background-position: -200% 0; }
|
|
53
|
+
100% { background-position: 200% 0; }
|
|
54
|
+
}
|
|
55
|
+
`}),n.jsx(Se,{widthPct:45,heightPx:14,variant:"overlay"}),n.jsx(Se,{widthPct:70,heightPx:10,variant:"overlay"}),n.jsx("div",{style:{height:"6%"}}),n.jsx(Se,{widthPct:100,heightPx:32,variant:"overlay"}),n.jsxs("div",{style:{display:"flex",gap:"4%"},children:[n.jsx(Se,{widthPct:48,heightPx:48,variant:"overlay"}),n.jsx(Se,{widthPct:48,heightPx:48,variant:"overlay"})]}),n.jsx(Se,{widthPct:88,heightPx:10,variant:"overlay"}),n.jsx(Se,{widthPct:60,heightPx:10,variant:"overlay"})]})}function gb({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=sb[s];i.useEffect(()=>{const j=l.current;if(!j)return;const k=()=>{const S=j.clientWidth,C=j.clientHeight;S>0&&d(S),C>0&&f(C)};if(k(),typeof ResizeObserver>"u")return;const N=new ResizeObserver(k);return N.observe(j),()=>N.disconnect()},[]);const{scale:m,offsetX:h,offsetY:g}=db(c,u,p.w,p.h),b=e&&a==="dark"&&o?eb(e,o):e,{handleIframeLoad:y,visible:w,showSkeleton:v}=hb({srcDoc:b,url:t,theme:a,scale:m,hasContent:e!==null}),x=()=>window.open(t,"_blank","noopener,noreferrer");return n.jsxs("div",{ref:l,onClick:x,style:{position:"relative",width:"100%",aspectRatio:`${ab} / ${ob}`,overflow:"hidden",cursor:"pointer",backgroundColor:ib,backgroundImage:lb,backgroundSize:cb},children:[e!==null&&n.jsx("iframe",{src:b?void 0:t,srcDoc:b??void 0,title:r,sandbox:"",onLoad:y,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:g,left:h,visibility:w?"visible":"hidden"}},a),v&&n.jsx(xb,{})]})}const bb=`
|
|
56
|
+
.mockup-feedback-slider {
|
|
57
|
+
-webkit-appearance: none;
|
|
58
|
+
appearance: none;
|
|
59
|
+
background: transparent;
|
|
60
|
+
height: 18px;
|
|
61
|
+
padding: 0;
|
|
62
|
+
margin: 0;
|
|
63
|
+
cursor: pointer;
|
|
64
|
+
}
|
|
65
|
+
.mockup-feedback-slider:focus { outline: none; }
|
|
66
|
+
.mockup-feedback-slider::-webkit-slider-runnable-track {
|
|
67
|
+
height: 4px;
|
|
68
|
+
background: #4a4a4a;
|
|
69
|
+
border-radius: 2px;
|
|
70
|
+
}
|
|
71
|
+
.mockup-feedback-slider::-moz-range-track {
|
|
72
|
+
height: 4px;
|
|
73
|
+
background: #4a4a4a;
|
|
74
|
+
border-radius: 2px;
|
|
75
|
+
border: none;
|
|
76
|
+
}
|
|
77
|
+
.mockup-feedback-slider::-moz-range-progress {
|
|
78
|
+
background: #4a4a4a;
|
|
79
|
+
height: 4px;
|
|
80
|
+
border-radius: 2px;
|
|
81
|
+
}
|
|
82
|
+
.mockup-feedback-slider::-webkit-slider-thumb {
|
|
83
|
+
-webkit-appearance: none;
|
|
84
|
+
appearance: none;
|
|
85
|
+
width: 14px;
|
|
86
|
+
height: 14px;
|
|
87
|
+
border-radius: 50%;
|
|
88
|
+
background: #5a5a5a;
|
|
89
|
+
border: none;
|
|
90
|
+
margin-top: -5px;
|
|
91
|
+
cursor: pointer;
|
|
92
|
+
transition: background 120ms ease;
|
|
93
|
+
}
|
|
94
|
+
.mockup-feedback-slider::-moz-range-thumb {
|
|
95
|
+
width: 14px;
|
|
96
|
+
height: 14px;
|
|
97
|
+
border-radius: 50%;
|
|
98
|
+
background: #5a5a5a;
|
|
99
|
+
border: none;
|
|
100
|
+
cursor: pointer;
|
|
101
|
+
transition: background 120ms ease;
|
|
102
|
+
}
|
|
103
|
+
.mockup-feedback-slider[data-rated="true"]::-webkit-slider-runnable-track {
|
|
104
|
+
/* Two stacked layers: a grey overlay that masks the right portion of
|
|
105
|
+
* the track from progress% onward, and a full-width red-amber-keylime
|
|
106
|
+
* rainbow underneath. The visible filled portion is the slice of the
|
|
107
|
+
* rainbow up to the thumb position. */
|
|
108
|
+
background:
|
|
109
|
+
linear-gradient(
|
|
110
|
+
to right,
|
|
111
|
+
transparent 0%,
|
|
112
|
+
transparent var(--mockup-feedback-progress, 0%),
|
|
113
|
+
#4a4a4a var(--mockup-feedback-progress, 0%),
|
|
114
|
+
#4a4a4a 100%
|
|
115
|
+
),
|
|
116
|
+
linear-gradient(
|
|
117
|
+
to right,
|
|
118
|
+
rgb(239, 68, 68) 0%,
|
|
119
|
+
rgb(251, 191, 36) 50%,
|
|
120
|
+
rgb(215, 255, 99) 100%
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
.mockup-feedback-slider[data-rated="true"]::-moz-range-track {
|
|
124
|
+
background: linear-gradient(
|
|
125
|
+
to right,
|
|
126
|
+
rgb(239, 68, 68) 0%,
|
|
127
|
+
rgb(251, 191, 36) 50%,
|
|
128
|
+
rgb(215, 255, 99) 100%
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
.mockup-feedback-slider[data-rated="true"]::-moz-range-progress {
|
|
132
|
+
/* Firefox draws ::-moz-range-progress on top of ::-moz-range-track,
|
|
133
|
+
* so the progress layer would otherwise hide the rainbow below it.
|
|
134
|
+
* Leave it transparent so the rainbow shows through up to the value. */
|
|
135
|
+
background: transparent;
|
|
136
|
+
}
|
|
137
|
+
.mockup-feedback-slider[data-rated="true"]::-webkit-slider-thumb {
|
|
138
|
+
background: var(--mockup-feedback-color, var(--accent-active, #D7FF63));
|
|
139
|
+
}
|
|
140
|
+
.mockup-feedback-slider[data-rated="true"]::-moz-range-thumb {
|
|
141
|
+
background: var(--mockup-feedback-color, var(--accent-active, #D7FF63));
|
|
142
|
+
}
|
|
143
|
+
`,vb=`
|
|
144
|
+
.mockup-feedback-comment {
|
|
145
|
+
width: 100%;
|
|
146
|
+
padding: var(--spacing-sm, 8px) var(--spacing-sm, 10px);
|
|
147
|
+
background: var(--bg-card, #1a1a1a);
|
|
148
|
+
color: var(--text-primary);
|
|
149
|
+
border: 1px solid var(--border-default);
|
|
150
|
+
border-radius: 6px;
|
|
151
|
+
font-size: var(--text-xs, 12px);
|
|
152
|
+
line-height: 1.4;
|
|
153
|
+
resize: vertical;
|
|
154
|
+
box-sizing: border-box;
|
|
155
|
+
min-height: 56px;
|
|
156
|
+
outline: none;
|
|
157
|
+
}
|
|
158
|
+
.mockup-feedback-comment:focus,
|
|
159
|
+
.mockup-feedback-comment:focus-visible {
|
|
160
|
+
border-color: var(--text-primary, #ffffff);
|
|
161
|
+
outline: none;
|
|
162
|
+
box-shadow: 0 0 0 1px var(--text-primary, #ffffff);
|
|
163
|
+
}
|
|
164
|
+
`;function yb({comment:e,onCommentChange:t}){return n.jsxs(n.Fragment,{children:[n.jsx("style",{children:vb}),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 oi=[239,68,68],yr=[251,191,36],ii=[215,255,99];function wb(e){const t=Math.max(1,Math.min(100,e));let r,s,a;t<=50?(r=oi,s=yr,a=(t-1)/49):(r=yr,s=ii,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})`}`${oi.join(", ")}${yr.join(", ")}${ii.join(", ")}`;function jb(){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 kb(){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 Nb({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(jb,{})}),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?wb(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(kb,{})})]})}const Cb={rating:null,comment:""};function Sb({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:bb}),n.jsx(Nb,{rating:e.rating,onRatingChange:r=>t({...e,rating:r})}),n.jsx(yb,{comment:e.comment,onCommentChange:r=>t({...e,comment:r})})]})}function Eb({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(ia),[m,h]=i.useState("light");if(i.useEffect(()=>{if(!e)return;let b=!1;return(async()=>{try{const y=await fetch(e.url);if(!y.ok)return;const w=await y.text();if(b)return;u(w),p(si(w)??ia)}catch{}})(),()=>{b=!0}},[e==null?void 0:e.url]),!e)return n.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",minHeight:160,border:"1px dashed var(--border-default)",borderRadius:12,background:"var(--bg-surface)",color:"var(--text-muted)",fontSize:"var(--text-sm, 14px)"},children:"No mockup to preview"});const g=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(pb,{displayNumber:t,formattedName:g,theme:m,showThemeToggle:!!o,busy:a,warnings:e.warnings,openInNewTabUrl:e.url,onToggleTheme:()=>h(b=>b==="light"?"dark":"light"),onChoose:()=>r==null?void 0:r(e),onCustomize:()=>s==null?void 0:s(e)}),n.jsx(gb,{html:d,url:e.url,title:e.name,viewport:f,theme:m,darkVars:o}),c&&n.jsx(Sb,{value:l??Cb,onChange:c})]})}function Rb({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:`
|
|
165
|
+
@keyframes mockup-skeleton-shimmer {
|
|
166
|
+
0% { background-position: -200% 0; }
|
|
167
|
+
100% { background-position: 200% 0; }
|
|
168
|
+
}
|
|
169
|
+
`}),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(Se,{widthPct:45,heightPx:14}),n.jsx(Se,{widthPct:70,heightPx:10}),n.jsx("div",{style:{height:"6%"}}),n.jsx(Se,{widthPct:100,heightPx:32}),n.jsxs("div",{style:{display:"flex",gap:"4%"},children:[n.jsx(Se,{widthPct:48,heightPx:48}),n.jsx(Se,{widthPct:48,heightPx:48})]}),n.jsx(Se,{widthPct:88,heightPx:10}),n.jsx(Se,{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(Eb,{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(Rb,{displayNumber:c.number},`placeholder-${c.number}`))})}function Tb(){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 Db(){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 Ab({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(Tb,{})}),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(Db,{})})]})}function Fb(){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 Lb({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(Fb,{})}),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 Mb(){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 Ib(){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 $b({archivedRoundsNewestFirst:e,selected:t,onSelect:r}){if(!e||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(la,{ariaLabel:"Previous round",disabled:!u,onClick:()=>u&&r(a[c-1]),icon:n.jsx(Mb,{})}),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(la,{ariaLabel:"Next round",disabled:!f,onClick:()=>f&&r(a[c+1]),icon:n.jsx(Ib,{})})]})}function la({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 Bb({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 Ob({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,g]=i.useState({}),[b,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"),S=_g(),C=i.useRef(null),R=Og(t),E=i.useRef(!0),T=i.useCallback(async()=>{try{const[L,F]=await Promise.all([fetch("/api/editor-mockups"),fetch("/api/editor-mockups-target")]),O=await L.json(),X=await F.json();E.current&&(r(J=>kg(J,O)?J:O),a(J=>J===X.count?J:X.count))}catch(L){E.current&&l(L instanceof Error?L.message:String(L))}},[]);i.useEffect(()=>{E.current=!0,T();const L=window.setInterval(T,4e3);return()=>{E.current=!1,window.clearInterval(L)}},[T]),i.useEffect(()=>{let L=!1;return(async()=>{try{const F=await fetch("/api/editor-mockups-feedback");if(!F.ok)return;const O=await F.json();if(L||!O||typeof O!="object"||Array.isArray(O))return;const X={};for(const[J,ie]of Object.entries(O)){if(!ie||typeof ie!="object")continue;const ee=ie;ee.rating!=null&&typeof ee.rating!="number"||ee.comment!=null&&typeof ee.comment!="string"||(X[J]={rating:typeof ee.rating=="number"?ee.rating:null,comment:typeof ee.comment=="string"?ee.comment:""})}y(X)}catch{}})(),()=>{L=!0}},[]);const M=i.useCallback((L,F)=>{y(O=>{const X={...O,[L]:F};return C.current!=null&&window.clearTimeout(C.current),C.current=window.setTimeout(()=>{fetch("/api/editor-mockups-feedback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)}).catch(()=>{})},400),X})},[]);i.useEffect(()=>()=>{C.current!=null&&window.clearTimeout(C.current)},[]);const A=i.useCallback(()=>{if(!t)return;v(!0),N("current");const L=Rg({feedbackByFilename:b,mockupFilenames:t.map(F=>F.filename)});Sg(L),y({}),fetch("/api/editor-mockups-feedback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})}).catch(()=>{}),window.setTimeout(()=>{E.current&&v(!1)},1e3)},[b,t]),P=i.useCallback(L=>{m(L)},[]),_=i.useCallback(async()=>{if(!p)return;const L=p;d(L.filename);try{const F=await fetch("/api/editor-design-select",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:L.filename})});if(!F.ok){const O=await F.text().catch(()=>`${F.status}`);throw new Error(O||`select failed: ${F.status}`)}E.current&&(m(null),e==null||e())}catch(F){l(F instanceof Error?F.message:String(F))}finally{E.current&&d(null)}},[p,e]),G=i.useCallback(L=>{const F=ts(L.filename);f({mockup:L,systemName:F})},[]),D=i.useCallback(L=>{u&&g(F=>({...F,[u.mockup.filename]:L})),f(null)},[u]),$=i.useCallback(async L=>{if(u){d(u.mockup.filename);try{const F=await fetch("/api/editor-design-select",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:u.mockup.filename,overrides:{vars:L.vars,primaryFont:L.primaryFont,secondaryFont:L.secondaryFont}})});if(!F.ok){const O=await F.text().catch(()=>`${F.status}`);throw new Error(O||`select failed: ${F.status}`)}g(O=>({...O,[u.mockup.filename]:L})),f(null),e==null||e()}catch(F){l(F instanceof Error?F.message:String(F))}finally{E.current&&d(null)}}},[u,e]);if(u)return n.jsx(rb,{mockup:u.mockup,systemName:u.systemName,initial:h[u.mockup.filename]??jg,onBack:D,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 W=t.reduce((L,F)=>{const O=/^(\d{1,2})-/.exec(F.filename);return O?Math.max(L,parseInt(O[1],10)):L},0),z=Math.max(s??0,W);if(z===0)return n.jsx(ti,{});const q=Array.from({length:z},(L,F)=>{const O=F+1,X=String(O).padStart(2,"0"),J=t.find(ie=>ie.filename.startsWith(`${X}-`))??null;return{number:O,mockup:J}});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(Ab,{onDismiss:()=>{j(!0),typeof window<"u"&&window.sessionStorage.setItem("mockup-grid-tip-dismissed","1")}}),n.jsx($b,{archivedRoundsNewestFirst:S.map(L=>L.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:q,darkVarsBySystem:R,busyFilename:c,feedbackByFilename:b,onFeedbackChange:M,onChoose:P,onCustomize:G}),t.length>0&&n.jsx(Lb,{feedbackCount:Object.values(b).filter(L=>typeof L.rating=="number"||L.comment.trim().length>0).length,busy:w,onIterate:A})]}):(()=>{const L=S.find(F=>F.round===k);return L?n.jsx(zg,{round:L}):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(Bb,{mockup:p,busy:c===p.filename,onCancel:()=>m(null),onConfirm:_})]})}function _b({onDesignConfirmed:e}){const[t,r]=i.useState("assets"),s=i.useRef(!0),a=i.useRef(0);return i.useEffect(()=>{s.current=!0;const o=async()=>{try{const d=await(await fetch("/api/editor-design-active-tab")).json();if(!s.current)return;d.tab!==null&&d.nonce!==null&&d.nonce>a.current&&(a.current=d.nonce,r(d.tab))}catch{}};o();const l=window.setInterval(o,4e3);return()=>{s.current=!1,window.clearInterval(l)}},[]),n.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[n.jsx("div",{role:"tablist",style:{display:"flex",gap:"var(--spacing-xs, 4px)",padding:"var(--spacing-sm, 8px) var(--spacing-md, 12px)",borderBottom:"1px solid var(--border-default)"},children:[{id:"assets",label:"Add assets"},{id:"mockups",label:"Mockups"}].map(({id:o,label:l})=>{const c=t===o;return n.jsx("button",{type:"button",role:"tab","aria-selected":c,onClick:()=>r(o),style:{padding:"var(--spacing-xs, 4px) var(--spacing-md, 12px)",borderRadius:6,border:"none",cursor:"pointer",fontSize:"var(--text-sm, 14px)",fontWeight:500,background:c?"var(--accent-active)":"transparent",color:c?"var(--text-on-accent, white)":"var(--text-secondary)"},children:l},o)})}),t==="assets"?n.jsx(yg,{}):n.jsx(Ob,{onDesignConfirmed:e})]})}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 li(e){return Rr(e)?e.componentName??wr(e.name).pageName:wr(e.name).pageName}function rs(e){return wr(e.name).stateName}function zb({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 ca({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 Hb({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 Wb({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 Vb(){return n.jsx("button",{onClick:()=>Aa(),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 ci(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 Ub(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 di(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 Kb({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 Gb({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:Ue(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 Yb({group:e,currentSlug:t,onSelect:r}){const s=e.scenarios[0]?li(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(Gb,{scenario:a,active:a.slug===t,onClick:()=>r(a.slug)},a.slug))})]})}function da({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 qb({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()},[]),di(u,s,a);const p=i.useMemo(()=>e.flatMap(w=>w.scenarios),[e]),m=i.useMemo(()=>Ub(p,c),[p,c]),h=i.useMemo(()=>m.filter(St),[m]),g=i.useMemo(()=>m.filter(Rr),[m]),b=o==="pages"?h:g,y=i.useMemo(()=>ci(b),[b]);return n.jsxs("div",{ref:u,className:"absolute top-full left-0 mt-1 bg-[#222] border border-[#3d3d3d] rounded-lg shadow-2xl z-50 w-[560px] max-h-[480px] flex flex-col",role:"dialog",children:[n.jsxs("div",{className:"flex items-center border-b border-[#3d3d3d] px-2 py-1.5 gap-2",children:[n.jsx(da,{label:"PAGES",active:o==="pages",count:h.length,onClick:()=>l("pages")}),n.jsx(da,{label:"COMPONENTS",active:o==="components",count:g.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(Kb,{tab:o,hasQuery:c.trim().length>0}):y.map(w=>n.jsx(Yb,{group:w,currentSlug:t,onSelect:v=>{r(v),s()}},w.route))})]})}function Jb(){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 Xb(){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 ui({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 Qb({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:li(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:Ue(o),alt:"",className:"w-full h-full object-cover"}):a?n.jsx(Xb,{}):n.jsx(Jb,{})}),n.jsx(ui,{})]}),n.jsx("span",{className:"truncate",children:l})]})}function Zb(e,t){const r=e.url??"Uncategorized",s=t.find(a=>a.route===r);return(s==null?void 0:s.scenarios)??[e]}function ev({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:Ue(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 tv({currentScenario:e,scenarioGroups:t,onSelect:r,onCreateNew:s,onClose:a,triggerRef:o}){const l=i.useRef(null);di(l,a,o);const c=i.useMemo(()=>Zb(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(ev,{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 nv({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(ui,{className:"opacity-70 shrink-0"})]})}function rv({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(ah,{name:e.name})})}function sv({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:g,onShowScenarioPreview:b,onCreateStateRequest:y,isNarrow:w=!1}){const[v,x]=i.useState(!1),[j,k]=i.useState(!1),N=i.useRef(null),S=i.useRef(null),C=d&&f?Math.round(f):s,R=d&&p?Math.round(p):a,E=h?rs(h):"No state",T=!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(zb,{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(Qb,{currentScenario:h,isOpen:v,onClick:()=>{x(M=>!M),k(!1)},buttonRef:N}),v&&n.jsx(qb,{scenarioGroups:g,currentSlug:(h==null?void 0:h.slug)??null,onSelect:b,onClose:()=>x(!1),triggerRef:N}),n.jsx("span",{className:"w-px h-5 bg-[#555] mx-1 shrink-0","aria-hidden":"true"}),e.map(M=>n.jsx(rv,{viewport:M,isActive:!d&&t===M.name,onSelect:()=>{d&&u(),r(M.name)}},M.name)),n.jsx(Hb,{isFilled:d,onToggle:u}),n.jsx(ca,{label:"H",value:R,disabled:d,onCommit:M=>m(s,M)}),n.jsx(ca,{label:"W",value:C,disabled:d,onCommit:M=>m(M,a)}),n.jsx(Vb,{}),n.jsx(Wb,{previewUrl:o})]}),n.jsx("div",{className:"flex items-center gap-2 shrink-0",children:n.jsxs("div",{className:"relative",children:[n.jsx(nv,{label:E,disabled:T,isOpen:j,onClick:()=>{k(M=>!M),x(!1)},buttonRef:S}),j&&h&&n.jsx(tv,{currentScenario:h,scenarioGroups:g,onSelect:b,onCreateNew:y,onClose:()=>k(!1),triggerRef:S})]})})]}),n.jsx("div",{"aria-hidden":"true"})]})}function av(){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 ov({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 ua={prompt:null,title:null};function fi(){const[e,t]=i.useState(ua),[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(ua)}finally{a||s(!1)}})(),()=>{a=!0}},[]),{...e,loading:r}}function iv(){const{prompt:e,title:t,loading:r}=fi();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(ov,{title:t}):null,n.jsx(pt,{children:e})]}):n.jsx(av,{})})})}function lv({message:e}){return n.jsx("span",{style:{color:"var(--text-dim)"},children:e})}function cv({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 dv(e,t,r){const s=[e];return t&&s.push(`reload:${t}`),r&&s.push(`command:${r}`),s.join("::")}function uv({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 fv=i.forwardRef(function({currentHeight:t,currentWidth:r,isFilled:s,previewUrl:a,scale:o,reloadNonce:l,commandNonce:c,onLoad:d,onError:u},f){if(gt())return n.jsx(uv,{currentWidth:r,currentHeight:t,isFilled:s,scale:o});const p=dv(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 pv(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 mv(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 hv(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 xv(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&&Xs(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&&Xs(e,f??c.current)},[e,t]),u=i.useCallback(f=>{t&&Ox(f)},[t]);return{reloadNonce:o,handleIframeLoad:d,handleIframeError:u}}const gv=1500,bv=2e3,vv=3e3,yv=2;function wv(){return typeof window>"u"?!1:window.location.pathname.startsWith("/scenario/")?!0:gt()}function jv(e,t=!1){const r=wv(),[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),g=i.useRef(!1),b=i.useRef(e),y=i.useRef(t);i.useEffect(()=>{b.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(g.current||y.current)return;const N=b.current;if(!N)return;h.current&&h.current.abort();const S=new AbortController;h.current=S;const C=setTimeout(()=>S.abort(),vv);let R=!1;try{await fetch(N,{mode:"no-cors",cache:"no-store",signal:S.signal}),R=!0}catch{R=!1}finally{clearTimeout(C)}if(!g.current){if(l(Date.now()),R){if(d(0),p.current!==!0){const E=p.current===!1;p.current=!0,a(!0),E&&f(T=>T+1)}}else d(E=>{const T=E+1;return T>=yv&&p.current!==!1&&(p.current=!1,a(!1)),T});x()}},[]),x=i.useCallback(()=>{if(g.current)return;w();const N=p.current===!0?bv:gv;m.current=setTimeout(()=>{m.current=null,v()},N)},[w,v]),j=i.useCallback(()=>{w(),v()},[w,v]);i.useEffect(()=>{if(!r)return g.current=!1,v(),()=>{g.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 fa={loaded:!1,stalledRequests:0,fastRequests:0,longestStallMs:0,tailReadFailedReason:null};function kv(e){const{active:t,trigger:r}=e,[s,a]=i.useState(fa),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(fa),(c=o.current)==null||c.abort();return}return l(),()=>{var d;(d=o.current)==null||d.abort()}},[t,r,l]),s}function Nv(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 Sv({hasDevServerConfigured:e,hasServed:t}){return!e||t}const Ev=2e3;function Rv(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<Ev||(l.current=h,s(g=>g+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),g=i.useRef(r),b=i.useCallback(w=>{const v=Date.now(),x=v-s;let j=[];d(N=>{const S=N.filter(C=>C.timestampMs>=x);return S.push({reason:w,timestampMs:v}),S.length>un.ringBufferSize&&S.splice(0,S.length-un.ringBufferSize),j=S,S});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,b("pid"))},[e,b]),i.useEffect(()=>{t!==h.current&&(h.current=t,b("probe"))},[t,b]),i.useEffect(()=>{r!==g.current&&(g.current=r,b("draft"))},[r,b]);const y=i.useCallback(()=>{p.current=!1,l(!1),d([]),f(w=>w+1)},[]);return{tripped:o,recentReloads:c,gatedNonce:u,reset:y}}const pa=20,Tv="codeyam-error-capture";function Dv(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!==Tv)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>pa?m.slice(m.length-pa):m})}return window.addEventListener("message",o),()=>window.removeEventListener("message",o)},[e]),{errors:r,clear:a}}const sr=[500,1e3,2e3];async function Av(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 Fv(){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 Lv(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 Av(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 Fv();a||s({status:l,clickThroughBroken:!0,logLines:c,loading:!1})})(),()=>{a=!0}},[e,t]),r}function Mv({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(`
|
|
170
|
+
`):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 Iv(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 $v=20;function Bv(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 Ov(e){return e===null||e.status!=="running"?!1:e.liveIframeHealthy!==!1}const _v=5,zv=3;function Hv(e,t){return e===null||e<=0?!1:e<=(t==="backend"?zv:_v)}const ma="Setting up your project",ha="Preparing your project — the preview will appear once it's ready.",Wv={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."},Vv={1:"Aligning on the plan with you.",2:"Aligning on the plan with you.",3:"Preparing the project environment."};function Uv(e,t){return e===null?{title:ma,body:ha}:{title:ma,body:(t==="backend"?Vv:Wv)[e]??ha}}function Kv({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 Gv={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 Yv({variant:e,restartCount:t=0,showRetry:r=!1,onRetry:s,bodyOverride:a}){const{title:o,body:l,spinner:c}=Gv[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(Kv,{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 qv(e){return e.slice().reverse().map(t=>{const r=t.filename!=null?`
|
|
171
|
+
at ${t.filename}${t.lineno!=null?`:${t.lineno}`:""}${t.colno!=null?`:${t.colno}`:""}`:"",s=t.stack?`
|
|
172
|
+
${t.stack}`:"",a=t.count>1?` (×${t.count})`:"";return`[${t.type}]${a} ${t.message}${r}${s}`}).join(`
|
|
173
|
+
|
|
174
|
+
`)}function Jv(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 Xv({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 Qv({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 Zv({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 e0({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(Zv,{error:a,expanded:r===a.dedupeKey,onToggle:()=>s(r===a.dedupeKey?null:a.dedupeKey)},a.dedupeKey))})}function t0({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 n0=`Fix this error in the live preview. Here is what the captured runtime error reported:
|
|
175
|
+
|
|
176
|
+
`;function r0({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(()=>qv(t),[t]),p=i.useMemo(()=>Jv(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,g=e?`Live Preview paused — ${t.length} error${t.length===1?"":"s"} captured`:`${t.length} runtime error${t.length===1?"":"s"} captured`;async function b(y){const w=await vl(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(Xv,{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(Qv,{headline:g,tripped:e,onClear:m?()=>u(!0):o,closeAriaLabel:m?"Minimize errors":"Dismiss errors"}),n.jsx(e0,{errors:t,emptyHint:e?`Breaker tripped before any runtime error was reported. Reasons in window: ${p}.`:null}),n.jsx(t0,{canCopy:t.length>0,reasonsSummary:p,copyState:l,onCopy:()=>b(""),onCopyForClaude:()=>b(n0),onRetry:a})]})})}function s0({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 a0(){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 o0({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 i0({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 l0(){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 c0({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(l0,{}),n.jsx(i0,{text:e.join(`
|
|
177
|
+
`),label:"Copy logs",writer:t})]})})}function d0({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(a0,{}),n.jsx(o0,{logs:e}),n.jsx(c0,{logs:e})]})}const xa=20;function u0(e){if(!e)return null;try{return new Date(e).toLocaleTimeString()}catch{return null}}function f0({lastError:e,failureCount:t,failedAtMs:r,holder:s,onRetry:a,onReap:o}){const[l,c]=i.useState(!1),d=e.split(`
|
|
178
|
+
`),u=d.length>xa,f=l||!u?d:d.slice(d.length-xa),p=u0(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(`
|
|
179
|
+
`)}),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 p0({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 ga=48,m0=100,h0=320,x0=192;function g0({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:h0,height:x0,hasViewport:!1};const o=t-ga*2,l=e-ga*2-m0,c=Math.min(1,o/s,l/r);return{width:Math.round(s*c),height:Math.round(r*c),hasViewport:!0}}function b0({containerHeight:e,containerWidth:t,onDismiss:r,scenarioName:s,screenshotPath:a,viewportHeight:o,viewportWidth:l}){const{width:c,height:d,hasViewport:u}=g0({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(Oo,{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 v0({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 y0(){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 w0({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 j0({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 k0({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(j0,{ancestors:e,onOpenInEditor:t})]})}function N0({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:g}){const b=c||!o.trim();return n.jsxs("div",{className:"flex-1 flex flex-col gap-3 min-w-0",children:[n.jsx("h3",{style:{color:"var(--text-primary)",fontSize:16,fontWeight:600,margin:0},children:e}),t&&n.jsx("div",{className:"px-2 py-1 rounded",style:{background:"var(--bg-deep)",fontSize:12,fontFamily:"monospace",color:"var(--accent-blue)"},children:t}),n.jsxs("div",{className:"flex flex-col gap-1",style:{color:"var(--text-secondary)",fontSize:12},children:[n.jsxs("div",{children:["Element: <",r,">",s?` #${s}`:""]}),n.jsxs("div",{children:["Position: ",Math.round(a.x),", ",Math.round(a.y)," (",Math.round(a.width),"x",Math.round(a.height),")"]})]}),n.jsx(N0,{propsNames:f}),n.jsx(k0,{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:b,className:"px-3 py-1.5 rounded text-sm flex-1",style:{background:b?"var(--bg-deep)":"var(--accent-blue)",border:"none",color:b?"var(--text-secondary)":"#000",cursor:b?"not-allowed":"pointer",fontWeight:600},children:c?"Creating...":"Create Fix Plan"}),n.jsx("button",{onClick:g,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 S0({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 E0({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}=y0(),m=async()=>{d(!0);try{await a(o,e)}finally{d(!1)}},h=e.componentName??`<${e.element.tag}>`,g=e.sourceFile?`${e.sourceFile}${e.lineNumber?`:${e.lineNumber}`:""}`:null;return n.jsxs("div",{className:"absolute inset-0 z-50 flex items-center justify-center",style:{background:"rgba(0, 0, 0, 0.7)"},onClick:r,children:[n.jsxs("div",{className:"flex gap-4 p-6 rounded-lg max-w-3xl w-full mx-4",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)",maxHeight:"80vh"},onClick:b=>b.stopPropagation(),children:[n.jsx(w0,{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:g,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(S0,{error:f,onDismiss:p})]})}function R0(){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(R0,{})]})}function T0(){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 D0(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 A0({onDismiss:e}){return n.jsx("div",{onClick:e,style:{position:"fixed",inset:0,zIndex:999998,background:"transparent"}})}function F0({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 L0({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(F0,{match:r,onOpen:t})},`${r.endpoint}${r.jsonPath}${s}`))})}function M0({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:I0(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(L0,{matches:t,onOpen:s})]})}function I0(e,t){return e.length<=t?e:e.slice(0,t-1)+"…"}function $0({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 ba=320,va=320,B0=8;function O0({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}=D0(r,{width:c,height:l},{width:ba,maxHeight:va,gap:B0});return n.jsxs(n.Fragment,{children:[n.jsx(A0,{onDismiss:a}),n.jsxs("div",{style:{position:"fixed",top:d,left:u,width:ba,maxHeight:va,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($0,{onDismiss:a}),n.jsx(M0,{clickedText:e,matches:t,corpusEmpty:o,onOpenInPanel:s})]})]})}function _0({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 ya(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 z0(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(ya(h.data.payload)):h.data.type==="codeyam:debug:selected"&&l(ya(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 H0=/^\/api\/mock-panel(\/.*)?$/;function W0(e,t){return e.toUpperCase()!=="GET"?!1:H0.test(t)}function V0(e){return Array.isArray(e)?e.filter(t=>t.consumedThisPageLoad&&!W0(t.method,t.pathPattern)).map(t=>({endpoint:`${t.method} ${t.pathPattern}`,body:t.body})):[]}async function U0(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 K0=12;function G0(e,t,r){if(t.length===0)return[];const s=[];return jr(e,t,r,"$",0,new Set,s),s}function Y0(e,t){const r=[];for(const o of e)for(const l of G0(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>=K0)&&!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 wa(e,t){return(t==null?void 0:t.previewOrigin)??(e==null?void 0:e.previewOrigin)??null}function q0(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 J0={backgroundColor:"#1e1e1e",backgroundImage:"conic-gradient(#262626 25%, #1e1e1e 0 50%, #262626 0 75%, #1e1e1e 0)",backgroundSize:"16px 16px"};function X0({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:g,commandNonce:b}){var he,we;const y=i.useRef(null),w=a??y,v=i.useRef(null),{status:x,restart:j}=yl();pv(x,j);const{isRestarting:k,isFailed:N,isStarting:S,isStopped:C}=Iv(x),{stepState:R}=qt(),E=Hv((R==null?void 0:R.step)??null,(R==null?void 0:R.mode)??"ui"),T=(x==null?void 0:x.liveIframeHealthy)!==void 0,{reloadNonce:M,handleIframeLoad:A,handleIframeError:P}=xv((x==null?void 0:x.pid)??null,T,x==null?void 0:x.status),_=(x==null?void 0:x.status)==="failed",{healthy:G,failedProbeCount:D,reloadNonce:$,invalidate:W}=jv(m,_),z=hv(x==null?void 0:x.liveIframeHealthy,750),q=Rv(G,z),[L,F]=i.useState(0);i.useEffect(()=>wl(()=>{F(le=>le+1)}),[]);const O=Pv({pidNonce:M,probeNonce:$+q,draftNonce:L}),X=O.gatedNonce,{errors:J,clear:ie}=Dv(v,X),ee=Lv(m,X),H=i.useCallback(()=>{O.reset(),ie(),W()},[O,ie,W]),B=i.useCallback(()=>Aa(),[]),Z=(x==null?void 0:x.devServerStartedSecsAgo)??null,ne=Z!==null&&Z<$v,K=!!(x!=null&&x.startCommand),se=Cv({liveIframeHealthy:z,previewReachable:(he=x==null?void 0:x.previewProbe)==null?void 0:he.reachable}),[I,ae]=i.useState(!1);i.useEffect(()=>{se&&!I&&ae(!0)},[se,I]);const ge=se||I,oe=Sv({hasDevServerConfigured:K,hasServed:ge}),me=oe?m:"about:blank",de=Bv({hasDevServerConfigured:K,probeHealthy:G,backendRunning:(x==null?void 0:x.status)==="running",backendIframeHealthy:z,isStarting:S,isRestarting:k,isFailed:N,isStopped:C,isPrePrototype:E,withinStartupGrace:ne,previewReachable:((we=x==null?void 0:x.previewProbe)==null?void 0:we.reachable)===!0,hasEverServed:ge}),Oe=i.useRef(void 0);i.useEffect(()=>{var fe;if(Oe.current===de)return;const le=Oe.current;Oe.current=de,console.debug(`[preview-overlay] ${le===void 0?"(init)":le??"none"} → ${de??"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:(fe=x==null?void 0:x.previewProbe)==null?void 0:fe.reachable,devServerStartedSecsAgo:Z,withinStartupGrace:ne,probeHealthy:G,isStarting:S,isRestarting:k,isFailed:N,isStopped:C})},[de,x,Z,ne,G,S,k,N,C]);const Pe=x==null?void 0:x.portDiagnostic,Ge=(Pe==null?void 0:Pe.conflict)===!0,bt=de==="scaffolding"?Uv((R==null?void 0:R.step)??null,(R==null?void 0:R.mode)??"ui").body:void 0,Tt=kv({active:de==="reconnecting",trigger:D}),it=de==="reconnecting"?Nv(Tt):null,V=bt??it??void 0,Ae=D>=10,{isActive:Te,hoveredElement:vt,selectedElement:pe,activate:Ye,deactivate:Ie,clearSelection:Fe}=z0(v),lt=i.useCallback(()=>{Te?Ie():Ye()},[Te,Ye,Ie]),{entries:ct}=jl(p??null),{isActive:Ne,toggle:qe}=mv({activate:Ye,deactivate:Ie,clearSelection:Fe},M);i.useEffect(()=>(bs({isActive:Ne,previewSlug:p??null}),()=>{bs({isActive:!1,previewSlug:null})}),[Ne,p]),i.useEffect(()=>kl(()=>{qe()}),[qe]);const We=Ne&&pe?pe.element.text.trim():"",Je=i.useMemo(()=>V0(ct),[ct]),yt=i.useMemo(()=>!Ne||!We?[]:Y0(Je,We),[Ne,We,Je]),ue=i.useCallback(async le=>{Fe(),Ie();try{const ve=await(await fetch("/api/scenarios")).json(),Y=Array.isArray(ve)?ve.find(re=>re.componentName===le):null;if(Y!=null&&Y.slug){const re=Jo(window.location),Ce=Qo(Y.slug,re,null,0,h);window.history.pushState(null,"",Ce);return}}catch{}window.history.pushState(null,"","/entities")},[Fe,Ie,h]),ce=i.useCallback(async(le,fe)=>{try{await U0(le,fe,m),Fe(),Ie()}catch(ve){console.error("Failed to create debug plan:",ve)}},[m,Fe,Ie]);return n.jsx("div",{ref:w,className:`relative flex-1 flex overflow-hidden ${u?"":"items-center justify-center p-8"}`,style:u?{backgroundColor:"#fff"}:J0,children:m?n.jsxs(n.Fragment,{children:[n.jsx(fv,{ref:v,currentHeight:l,currentWidth:c,isFilled:u,previewUrl:me,scale:g,reloadNonce:X,onLoad:()=>{oe&&A(m)},onError:P}),!oe&&n.jsx(cv,{hasDevServerConfigured:K}),n.jsx(s0,{previewUrl:m}),n.jsx(_0,{healthy:z,reason:(x==null?void 0:x.iframeLastError)??null}),Te&&n.jsx(P0,{hoveredElement:vt}),Ne&&n.jsx(T0,{}),pe&&!Ne&&n.jsx(E0,{element:pe,previewUrl:m,onClose:Fe,onGoToIsolated:ue,onCreatePlan:ce}),pe&&Ne&&n.jsx(O0,{clickedText:We,matches:yt,anchor:pe.element.boundingBox,corpusEmpty:Je.length===0,onOpenInPanel:le=>{Nl({routeKey:le.endpoint,jsonPath:le.jsonPath}),Fe()},onDismiss:Fe}),!t&&n.jsx(v0,{isActive:Te,onToggle:lt,interactionAvailable:q0(h)}),_?n.jsx(f0,{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"}})}}):Ge&&Pe?n.jsx(p0,{diagnostic:Pe,onRetry:j}):de&&(de==="crashed"?n.jsx(d0,{logs:(x==null?void 0:x.logs)??[]}):n.jsx(Yv,{variant:de,restartCount:(x==null?void 0:x.restartCount)??0,showRetry:Ae,onRetry:de==="disconnected"?B:W,bodyOverride:V})),n.jsx(r0,{tripped:O.tripped,errors:J,recentReloads:O.recentReloads,serverHealthy:Ov(x),onRetry:H,onClear:ie}),ee.clickThroughBroken&&ee.status!==null&&n.jsx(Mv,{url:m,status:ee.status,logLines:ee.logLines,onRetry:H}),t&&f&&n.jsx(b0,{containerHeight:s,containerWidth:o,onDismiss:f,scenarioName:e??null,screenshotPath:r??null,viewportHeight:l,viewportWidth:c})]}):n.jsx(lv,{message:d})})}function Q0({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(pt,{children:e})}):null]})}function Z0(){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:"::"}),"Setting up your project…"]}),n.jsx("p",{style:{margin:0,color:"var(--text-muted)",fontSize:"0.8125rem"},children:"This usually takes a few minutes."})]})}function ey(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",ty="var(--text-muted)";function ny({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:ty,strokeWidth:"1.5"})})}function ry({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(ny,{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 sy({currentStep:e,mode:t}){const r=jd(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=ey(s,e);return n.jsx(ry,{phase:s,status:a},s.phaseId)})})})}function ay(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(`
|
|
180
|
+
`)&&(t=t.slice(0,-1)),t}function oy({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(Z0,{}),n.jsx(Q0,{prompt:ay(e)}),n.jsx(sy,{currentStep:t,mode:r})]})}function iy(){const{prompt:e}=fi(),{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(oy,{prompt:e??"",currentStep:(t==null?void 0:t.step)??1,mode:(t==null?void 0:t.mode)??"ui"})})})}function ly({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 cy(){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 dy(e){return e.state==="preflight-running"||e.state==="booting-simulator"||e.state==="simulator-booted"||e.state==="building-app"}function uy({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 fy=1500;function py({stackId:e,pollMs:t=fy,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 g=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{}};g();const b=window.setInterval(g,t);return()=>{m=!0,h=!1,window.clearInterval(b)}},[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||dy(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(my,{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(uy,{stderrTail:s.stderrTail,onClose:()=>d(!1)}):null]})}function my({status:e}){const t=hy(e);return n.jsx("span",{className:"text-xs opacity-80","data-testid":"simulator-status-pill",children:t})}function hy(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 (${xy(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 xy(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 gy({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 by=700;function vy({currentHeight:e,currentWidth:t,isFilled:r,scale:s,pollMs:a=by,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(g=>g+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 b;if(m)return;if(h.ok){u({kind:"ok"});return}if(h.status===503){const y=await yy(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 g=`simulator frame request failed (${h.status})`;u({kind:"capture-failed",message:g}),(b=f.current)==null||b.call(f,g)}).catch(h=>{var b;if(m)return;const g=h instanceof Error?h.message:"simulator frame request errored";u({kind:"capture-failed",message:g}),(b=f.current)==null||b.call(f,g)}),()=>{m=!0}},[l]),d.kind==="no-device"||d.kind==="xcode-missing")return n.jsx(gy,{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 yy(e){try{return await e.json()}catch{return null}}function wy({emptyStateMessage:e,projectSetupInProgress: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:g,buildingScreenshotPath:b,buildingScenarioName:y,onDismissBuildingOverlay:w,previewSeeding:v,previewSeedError:x,onRetrySeed:j,currentScenario:k,scenarioGroups:N,onShowScenarioPreview:S,commandNonce:C,previewOrigin:R,isNarrow:E=!1,onDesignConfirmed:T}){const[M,A]=i.useState(!1),{containerRef:P,containerSize:_,scale:G}=Wx({currentHeight:m,currentWidth:p,isFilled:u}),D=Vx();i.useEffect(()=>{gt()||_x(x??null)},[x]);const $=s?es(s):"",W=$==="/results"||$.startsWith("/results/"),z=$==="/plan-preview",q=$==="/design-exploration";return z?n.jsx(iv,{}):W?n.jsx(bg,{}):q?n.jsx(_b,{onDesignConfirmed:T}):t&&!s?n.jsx(iy,{}):n.jsxs("div",{"data-preview-pane":"true",className:"flex-1 flex flex-col min-w-0",children:[n.jsx(sv,{viewports:a,active:o,onChange:l,currentWidth:p,currentHeight:m,previewUrl:s,isCollapsed:c,onToggleCollapsed:d,isFilled:u,onToggleFilled:f,containerWidth:(_==null?void 0:_.width)??null,containerHeight:(_==null?void 0:_.height)??null,onCustomSizeChange:h,currentScenario:k??null,scenarioGroups:N??[],onShowScenarioPreview:S??(()=>{}),onCreateStateRequest:()=>A(!0),isNarrow:E}),x?n.jsx(ly,{error:x,onRetry:j}):null,n.jsxs("div",{className:"relative flex-1 flex flex-col min-h-0",children:[D.kind==="simulator-ios"?n.jsxs(n.Fragment,{children:[n.jsx(py,{}),n.jsx("div",{ref:P,className:"relative flex-1 flex overflow-hidden items-center justify-center p-8",style:{backgroundColor:"#1e1e1e"},children:n.jsx(vy,{currentHeight:m,currentWidth:p,isFilled:u,scale:G})})]}):n.jsx(X0,{containerRef:P,containerHeight:_==null?void 0:_.height,containerWidth:_==null?void 0:_.width,currentHeight:m,currentWidth:p,emptyStateMessage:e??"Select a scenario to preview",isFilled:u,previewSlug:r,previewUrl:s,previewOrigin:R,scale:G,buildingScenarioSlug:g,buildingScreenshotPath:b,buildingScenarioName:y,onDismissBuildingOverlay:w,commandNonce:C}),v?n.jsx(cy,{}):null]}),M?n.jsx(vg,{onClose:()=>A(!1)}):null]})}function jy(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),{scenariosVersion:l}=ht(),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(Pr);t(ci(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 ky(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),{scenariosVersion:l}=ht(),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(Pr):[]})):[])}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 ja(e){const t=new Map;for(const r of e){const s=Ny(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 Ny(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 pi(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 mi(e,t,r){return r==="backend"?[]:e.map(s=>({...s,scenarios:s.scenarios.filter(St)})).filter(s=>s.scenarios.length>0)}function hi(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 Sy=3e3;function Ey(){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),[g,b]=i.useState(null),y=i.useRef(null),w=i.useRef(null),v=i.useRef(!1),x=i.useRef(null),{testsVersion:j}=ht(),k=i.useCallback(async(M=!1)=>{var G;(G=y.current)==null||G.abort();const A=new AbortController;y.current=A;const{signal:P}=A;M&&(v.current=!0,o(!0));const _=!M&&x.current!==null;_||(s(!0),c(null));try{if(!M&&!_)try{const z=await fetch("/api/test-results/summary",{signal:P});if(z.ok){const q=await z.json();q.running?p(q.currentRunner??null):q.stats&&(h(q.stats),b(q.coverage??null))}}catch{}let D,$;if(_){D=x.current;const z=await fetch("/api/test-results",{signal:P});if(!z.ok)throw new Error(`test-results: HTTP ${z.status}`);$=await z.json()}else if(M){const z=await fetch("/api/test-results/refresh",{method:"POST",signal:P});if(!z.ok)throw new Error(`test-results: HTTP ${z.status}`);$=await z.json(),D=x.current??[]}else{const[z,q]=await Promise.all([fetch("/api/tests",{signal:P}),fetch("/api/test-results",{signal:P})]);if(!z.ok)throw new Error(`tests: HTTP ${z.status}`);if(!q.ok)throw new Error(`test-results: HTTP ${q.status}`);D=ja(await z.json()),$=await q.json(),x.current=D}if(p($.currentRunner??null),$.running&&v.current){w.current=setTimeout(()=>k(!1),Sy);return}const W=v.current;if(v.current=!1,W){const z=await fetch("/api/tests",{signal:P});z.ok&&(D=ja(await z.json()),x.current=D)}t(D),u($.cached??!1),b($.coverage??null),h(null),s(!1),o(!1)}catch(D){if(D instanceof DOMException&&D.name==="AbortError")return;v.current=!1,c(D instanceof Error?D.message:"Failed to load tests"),s(!1),o(!1)}},[]);i.useEffect(()=>(x.current=null,k(),()=>{var M;(M=y.current)==null||M.abort(),w.current&&clearTimeout(w.current)}),[k,j]);const{total:N,passed:S,failed:C,ignored:R,discovered:E}=i.useMemo(()=>hi(e),[e]),T=i.useCallback(()=>{v.current||k(!0)},[k]);return{groups:e,loading:r,refreshing:a,error:l,cached:d,currentRunner:f,summaryStats:m,coverage:g,totalTests:N,passedTests:S,failedTests:C,ignoredTests:R,discoveredTests:E,reload:k,refresh:T}}function ss(e,t){return e.filter(r=>r.appDir===t)}function xi(e,t){return t?e.find(r=>r.route===t)??null:null}function gi(e,t,r){const s=mi(e,t,r);return Ty(s)}function Ry(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 bi(e,t){const r=e.find(s=>s.type==="web");return r?gi(t,r.dir,r.type):null}function Ty(e){const t=e.flatMap(c=>c.scenarios.filter(d=>St(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(St(d)){o=d.slug,l=c.route.length;break}}return o}function Nr(e){return/\bhome\b/i.test(e.name)}function ka(e){return new Set(e.flatMap(t=>t.scenarios.map(r=>r.slug)))}function ar({selectedApp:e,appRouteEntities:t,scenarioGroups:r}){return e?Ry(t)??gi(r,e.dir,e.type):null}function Dy({apps:e,hasExplicitAppSelection:t,scenarioGroups:r}){return t||e.length===0||r.length===0?null:bi(e,r)}function Na(e){return Py(e)}function Ay({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 Fy({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 Ly({previewRouteEntities:e,path:t}){var s;const r=es(t);return((s=xi(e,r))==null?void 0:s.defaultScenarioSlug)??null}function My(e){return e.startsWith("/scenario/")||e.startsWith("/isolated-components/")}function Iy(e){return My(e)?!1:e==="/"||e==="/apps"||e==="/apps/"}function $y(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||!Iy(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 g(){o(null),c(null),m("/apps")}function b(v){const x=f.find(N=>N.route===v);if(!x)return;const j=lr(x),k=Oa(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:g,selectRoute:b,selectEntity:y,deselectRoute:w}}function By(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:g,selectRoute:b,selectEntity:y,deselectRoute:w}=$y(e,t,a),v=i.useMemo(()=>ka(f),[f]),x=i.useMemo(()=>ka(m?[m]:[]),[m]),j=i.useMemo(()=>ar({selectedApp:u,appRouteEntities:f,scenarioGroups:r}),[f,r,u]),k=i.useMemo(()=>Na(m),[m]),N=i.useMemo(()=>u?pi(s,u.dir):[],[s,u]);i.useEffect(()=>{if(c.current)return;const A=Dy({apps:e,scenarioGroups:r,hasExplicitAppSelection:!!u});A&&(l(A),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 S(A){h(A);const P=e.find(G=>G.dir===A);if(!P)return;const _=ar({selectedApp:P,appRouteEntities:ss(t,P.dir),scenarioGroups:r});l(_)}function C(){g(),l(bi(e,r))}function R(A){b(A);const P=Na(xi(f,A));l(P)}const E=i.useCallback(A=>{d.current=!0,l(A)},[]);function T(){if(w(),!u)return;const A=ar({selectedApp:u,appRouteEntities:f,scenarioGroups:r});A&&l(A)}function M(A){y(A)}return{selectedApp:u,appRouteEntities:f,appTestGroups:N,selectedEntityHash:p,selectedRouteEntity:m,previewSlug:o,setPreviewSlug:l,setPreviewSlugExplicit:E,selectApp:S,deselectApp:C,selectRoute:R,selectEntity:M,deselectRoute:T}}const Oy=1e3;function _y(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,Oy)}}return s(),()=>{r=!1}},[])}function zy(){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(()=>gc(e),[e]);return{graph:e,entityLookup:l,loading:r,error:a}}const Hy=["/apps","/entities","/app","/build","/history","/settings","/plan"];function vi(e){if(!e)return!1;const t=es(e);return Hy.some(r=>t===r||t.startsWith(`${r}/`))}function Wy(e,t,r){const s=typeof window<"u"?Jo(window.location):0;let a="";if(En(e)==="component"?a=Qo(e.slug,s,e.url,t,r):e.url&&(a=Xo(e.url,{appPort:t,currentPort:s,previewOrigin:r})),a&&!vi(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 Vy(e){return e==="/design-exploration"}function Uy(e,t,r){return e.startsWith("http")||e?e:r?`${r}/results`:`http://127.0.0.1:${t}/results`}function Ky(e,t,r){return e.startsWith("http")||e?e:r?`${r}/plan-preview`:`http://127.0.0.1:${t}/plan-preview`}function yi(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 Gy({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"?Uy(e,a,o):r==="plan-preview"?Ky(e,a,o):e.startsWith("http")||Vy(e)?e:o?`${o}${e}`:`http://127.0.0.1:${a}${e}`:s?Wy({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 Yy(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 qy({apps:e,appRouteEntities:t,directPreviewPath:r,fallbackPort:s,previewKind:a,previewOrigin:o,previewSlug:l,routeEntities:c,scenarioGroups:d,selectedApp:u,selectedRouteEntity:f}){const p=yi(d,l),m=Ay({apps:e,routeEntities:c,selectedApp:u,appRouteEntities:t}),h=Fy({previewRouteEntities:m,selectedRouteEntity:f});let g="blank";a==="plan-preview"&&r?g="plan-preview":a==="results"&&r?g="results":a==="application"&&r?g="application":p?g=St(p)?"application":"component":h&&(g="application");const b=Gy({directPreviewPath:r,fallbackPreviewPath:h,previewKind:g,selectedScenario:p,port:s,previewOrigin:o});return{selectedScenario:p,previewRouteEntities:m,fallbackPreviewPath:h,resolvedPreviewKind:g,basePreviewUrl:b}}function Jy({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 b=t.scenarioSlug??t.scenarioId,y=yi(a,b);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:b,type:"show-scenario",viewportName:l,commandNonce:d}}if(!t.path)return{clearCustomSize:c,type:"refresh",viewportName:l,commandNonce:d};const u=t.path,f=u.startsWith("http")?new URL(u).pathname:u.split("?")[0]??u,p=f==="/results"||f.startsWith("/results/"),m=f==="/plan-preview",h=vi(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 g=Ly({previewRouteEntities:s,path:u});return g?{clearCustomSize:c,scenarioSlug:g,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 Xy(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 Qy=[{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 Zy(e,t){const r=Object.entries(e);if(r.length===0)return Qy;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 e1({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 t1({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(hf({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 n1=3;function r1({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:g}){const[b,y]=i.useState(s??"Desktop"),w=i.useRef(!1),[v,x]=i.useState(null),[j,k]=i.useState(null),[N,S]=i.useState(null),[C,R]=i.useState(null),[E,T]=i.useState(()=>Date.now()),[M,A]=i.useState(0),P=i.useRef(null),_=i.useRef(!1),G=i.useMemo(()=>Zy(p,s),[s,p]);i.useEffect(()=>{w.current||s&&(y(s),w.current=!0)},[s]);const D=i.useMemo(()=>v!==null&&j!==null?{name:"Custom",width:v,height:j}:G.find(I=>I.name===b)??G[0]??{name:"Desktop",width:1440,height:900},[b,j,v,G]),$=gt(),W=l==="CodeYam Editor",{basePreviewUrl:z,fallbackPreviewPath:q,previewRouteEntities:L,resolvedPreviewKind:F,selectedScenario:O}=i.useMemo(()=>qy({apps:e,appRouteEntities:t,directPreviewPath:N,fallbackPort:a,previewKind:C,previewOrigin:o,previewSlug:c,routeEntities:d,scenarioGroups:u,selectedApp:m,selectedRouteEntity:h}),[e,t,N,a,C,o,c,d,u,m,h]),X=i.useMemo(()=>z?Yy(z,E):"",[z,E]),J=i.useCallback(I=>{y(I),x(null),k(null)},[]),ie=i.useCallback((I,ae)=>{x(I),k(ae)},[]),ee=i.useCallback(I=>{g(I),S(null),R(null),T(Date.now());const ae=Cr(I,u);if(!ae)return;const ge=Xy(b,v,j,ae,G);ge!==null&&(y(ge),x(null),k(null))},[b,j,v,u,g,G]),H=i.useCallback((I,ae)=>{const ge=(ae==null?void 0:ae.retriesLeft)??n1,oe=Jy({allowEditorRoutePreview:W,command:I,configLoaded:r,previewRouteEntities:L,scenarioGroups:u,scenarioDeferAvailable:ge>0});if(oe.viewportName&&y(oe.viewportName),oe.clearCustomSize&&(x(null),k(null)),oe.type==="show-scenario"){ee(oe.scenarioSlug),A(me=>me+1);return}if(oe.type==="defer"){P.current={command:I,retriesLeft:ge};return}if(oe.type==="refresh"){T(Date.now()),A(me=>me+1);return}oe.type!=="ignore"&&(oe.type==="show-path"&&(R(oe.previewKind),S(oe.path),_.current=oe.preserveDirectPreviewPathOnSlugChange,typeof oe.previewSlug=="string"?g(oe.previewSlug):oe.previewSlug===null&&g(null)),T(Date.now()),A(me=>me+1))},[r,W,L,u,g,ee]);i.useEffect(()=>{if(!r)return;const I=P.current;I&&(P.current=null,H(I.command,{retriesLeft:I.retriesLeft-1}))},[r,u,H]),i.useEffect(()=>{if(!(!c||N===null)){if(_.current){_.current=!1;return}S(null),R(null),T(Date.now())}},[N,c]);const B=i.useMemo(()=>F==="results"||F==="plan-preview"?N:F==="application"?N??(O==null?void 0:O.url)??q:null,[N,q,F,O==null?void 0:O.url]),Z=i.useCallback(()=>{T(Date.now())},[]);e1({isInIframe:$,persistedPath:B,previewKind:F,resolvedViewport:D,selectedScenario:O?{id:O.id??null,slug:O.slug}:null});const{seeding:ne,seedError:K}=t1({isInIframe:$,onActivated:Z,previewKind:F,scenariosLoaded:f,selectedScenario:O?{slug:O.slug,scenarioType:O.scenarioType,componentName:O.componentName??null}:null}),se=i.useCallback(I=>{S(I),R(I?"application":null),T(Date.now())},[]);return{viewports:G,resolvedViewport:D,previewUrl:X,handleViewportChange:J,handleCustomSizeChange:ie,showScenarioPreview:ee,handlePreviewCommand:H,setPreviewPath:se,previewSeeding:ne,previewSeedError:K,commandNonce:M}}function s1(){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 a1(){const[e,t]=i.useState(!1),r=i.useCallback(()=>{t(!0)},[]),s=i.useCallback(()=>{t(!1)},[]);return{showPlanCompleteModal:e,onPlanCompleteCommand:r,dismissPlanCompleteModal:s}}function o1(){const{showBuildTab:e}=Qr(typeof window>"u"?"/":window.location.pathname),{config:t}=ot(),[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 i1({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 l1(e,t,r){return e.map(s=>{const a=pi(t,s.dir),o=mi(r,s.dir,s.type),{total:l,passed:c,failed:d,ignored:u,discovered:f}=hi(a),p=Cy(o);return{app:s,tests:{total:l,passed:c,failed:d,ignored:u,discovered:f},scenarios:{total:p,thumbnails:c1(o)}}})}function c1(e){const t=[];for(const r of e)for(const s of r.scenarios)if(s.screenshotPaths.length>0&&t.push({path:s.screenshotPaths[0],cacheBuster:s.screenshotCapturedAtMs}),t.length>=6)return t;return t}const d1="Your app will display here once set up.",u1="Loading your app…",f1="Setting up your project…",p1="Select a scenario to preview",m1="No preview is available for this project.";function h1({configLoading:e,hasNoApps:t,hasStepState:r,hasPreviewableApp:s,setupInProgress:a}){return e?u1:a?f1:t&&!r?d1:s?p1:m1}const x1=["web","mobile"];function g1(e){return x1.includes(e)}function b1(e,t){return t?{scenarioSlug:e,path:t}:{scenarioSlug:e}}function v1(e,t){return e==="needs-login"&&!t}function y1(e){return e.activeTab==="build"&&!e.hasActiveSession&&!e.isAgentBuilding&&!e.showPostPushModal&&e.launchingPlanSlug===null&&!e.submittingBuildPrompt&&!e.stepStateFeature&&e.pendingPlanCount>0&&!e.buildLaunchModalDismissed}function w1(e,t){const[r,s]=i.useState(!1),a=i.useCallback(()=>{s(!0)},[]),o=i.useCallback(l=>{s(!1),t(l)},[t]);return i.useEffect(()=>{r&&(e||(s(!1),t("build")))},[r,e,t]),{arm:a,navigateToTabUser:o,pendingBuildNav:r}}const j1=4e3;function k1({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),g=st(t),[b,y]=i.useState(!1);i.useEffect(()=>{if(e!=="unknown"){y(!1);return}const j=window.setTimeout(()=>y(!0),j1);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(Sl,{provider:t,onAuthenticated:w,onClose:()=>p(!1)}):null;return e==="unknown"?o||!b||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 ",g," 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(Cl,{provider:t,credsPresent:r,reason:s,expiresAt:a,sessionOngoing:c,onAuthenticated:d,onAuthorized:u})}const N1=300,Ca=150;function C1(e){const[t,r]=i.useState(null),s=i.useRef(!1),[a,o]=i.useState(!1),l=i.useCallback(()=>{var u;return((u=e.current)==null?void 0:u.clientWidth)??1200},[e]),c=t??Math.floor(l()/2),d=i.useCallback(u=>{u.preventDefault(),s.current=!0,o(!0)},[]);return i.useEffect(()=>{const u=p=>{var b;if(!s.current)return;const m=((b=e.current)==null?void 0:b.getBoundingClientRect().left)??0,h=p.clientX-m,g=l();h<Ca?r(0):h>g-Ca?r(g):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 E1=3e3;function R1({hot:e,isInIframe:t,reload:r=()=>window.location.reload(),sustainedDisconnectMs:s=E1}){return()=>{}}function P1(){i.useEffect(()=>R1({hot:void 0,isInIframe:gt()}),[])}async function T1(){Ot("\x1B"),await vr(br),Ot("/clear\r"),await vr(br),Ot("/codeyam-plan\r")}function D1(){fetch("/api/clear-build-agent-session",{method:"POST"}).catch(()=>{})}function A1(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){U("favicon-redraw",{idle:e,hasIcon:!1});return}if(t.current||(t.current=s.href),!e){s.href=t.current,U("favicon-restore",{});return}U("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 F1=120*1e3,wi=1500;class L1{constructor(t,r,s=U){_e(this,"deferred",!1);_e(this,"userActiveSinceLastOutput",!1);_e(this,"lastActivitySource",null);_e(this,"lastActivityAt",null);_e(this,"lastNotificationTime",null);_e(this,"actions");_e(this,"env");_e(this,"now");_e(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<wi;if(r&&s&&c)return this.userActiveSinceLastOutput=!1,this.log("suppressed-user-active",l),"suppressed";if(a!==null&&a<F1)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 M1(e,t){return new L1({playSound:Za,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 I1(e,t){return e==="hook-stop"?t.idleOnStop:t.idleOnNotification}const $1=600*1e3,B1=3e3;function O1({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(Xa),[g,b]=i.useState(!1),y=i.useRef(!1);y.current=g;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),S=i.useRef(s??!1);S.current=s??!1,A1(g),j.current||(j.current=M1(d,x));const C=i.useCallback(D=>{h(D),Qa(D)},[]),R=i.useCallback(D=>{v.current!==null&&(clearTimeout(v.current),v.current=null,U("debounce-cancelled",{trigger:D}))},[]),E=i.useCallback(D=>{y.current&&U("idle-cleared",{trigger:D}),b(!1),y.current=!1,N.current=null,x.current&&(x.current.close(),x.current=null)},[]),T=i.useCallback(D=>{var $;if(!I1(D,m)){U("idle-suppressed-by-pref",{source:D});return}U("ws-idle-received",{buildTabActive:u.current,source:D}),($=f.current)==null||$.call(f),R("re-arm-on-idle"),v.current=setTimeout(()=>{var L;v.current=null;const W=k.current,z=W===null?null:Date.now()-W,q=W!==null&&Date.now()-W>$1;U("debounce-resolved",{suppressedForOvernight:q,msHidden:z,buildTabActive:u.current}),q||(L=j.current)==null||L.onIdle(m,u.current),b(!0),y.current=!0,N.current=Date.now(),w.current=!1,U("agent-currently-idle-set",{suppressedForOvernight:q}),u.current&&ze()},wi)},[m,R]),M=i.useCallback(()=>{var D,$,W;(D=p.current)==null||D.call(p),R("agent-active"),($=j.current)==null||$.onActive(),(W=j.current)==null||W.resetActivityFlag(),y.current&&S.current&&N.current!==null&&Date.now()-N.current>B1&&E("remote-resume")},[R,E]),A=i.useCallback(()=>{var D,$;R("user-input"),y.current&&((D=j.current)==null||D.onUserEngagement(),($=j.current)==null||$.reportUserActivity("terminal-input"),w.current=!0,E("user-input"))},[R,E]),P=i.useCallback(D=>{var $;D==="build"&&(R("navigate-build"),y.current&&(($=j.current)==null||$.onUserEngagement(),w.current=!0,E("navigate-build"))),o(D)},[o,R,E]),_=i.useCallback(()=>{var D;R("dismiss-banner"),(D=j.current)==null||D.onUserEngagement(),w.current=!0,E("dismiss-banner")},[R,E]);i.useEffect(()=>{function D(){var X;y.current&&(w.current||(R("ack-notification"),(X=j.current)==null||X.onUserEngagement(),w.current=!0,U("notification-acknowledged",{trigger:"user-return"})))}function $(X){var J;y.current&&u.current&&document.hasFocus()&&(document.hidden||((J=j.current)==null||J.onUserEngagement(),w.current=!0,E(X)))}function W(X){var J;document.hasFocus()&&D(),(J=j.current)==null||J.reportUserActivity(X)}const z=()=>W("mousemove"),q=()=>W("mousedown"),L=()=>W("keydown");function F(){document.hidden?k.current===null&&(k.current=Date.now()):(k.current=null,D(),$("tab-visible-on-build"))}function O(){var X;D(),$("window-focus-on-build"),(X=j.current)==null||X.reportUserActivity("focus")}return window.addEventListener("focus",O),document.addEventListener("visibilitychange",F),document.addEventListener("mousemove",z),document.addEventListener("mousedown",q),document.addEventListener("keydown",L),()=>{R("unmount"),window.removeEventListener("focus",O),document.removeEventListener("visibilitychange",F),document.removeEventListener("mousemove",z),document.removeEventListener("mousedown",q),document.removeEventListener("keydown",L)}},[R,E]);const G=i.useRef(a??0);return i.useEffect(()=>{var W;const D=a??0;if(D===G.current)return;G.current=D;const $=u.current&&document.hasFocus();U("feature-complete-fast-path",{skipBecauseWatching:$}),!$&&((W=j.current)==null||W.onIdle(m,!1),b(!0),y.current=!0,N.current=Date.now(),w.current=!1)},[a,m]),i.useEffect(()=>{var D,$;if((D=j.current)==null||D.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")),ze()},[t,m,E]),{buildIdle:g,bannerVisible:g,notifSettings:m,handleSettingsChange:C,handleAgentIdle:T,handleAgentActive:M,handleUserInput:A,handleNavigateToTab:P,dismissIdleBanner:_}}const _1=1e4;function z1(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&&(U("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()},_1);return()=>clearInterval(f)},[l,o]),{buildSessionLive:l,transitionBuildSessionLive:u}}function Sa(e){const{isAgentBuilding:t,trigger:r,transitionBuildSessionLive:s}=e;if(t){U("build-session-live-suppress-clear",{trigger:r,reason:"agent-still-active"});return}s(!1,r)}function H1(){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
|
|
181
|
+
|
|
182
|
+
${a.trim()}
|
|
183
|
+
|
|
184
|
+
${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(`
|
|
185
|
+
|
|
186
|
+
`));return`mailto:${r}?subject=${s}&body=${a}`}const V1=["bug","suggestion","question","praise"];function U1({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}=H1(),m=i.useCallback(()=>{p(r)},[p,r]),h=i.useCallback(()=>{navigator.clipboard.writeText("feedback@codeyam.com").then(()=>{c(!0),setTimeout(()=>c(!1),2e3)})},[]),g=i.useCallback(b=>{o(y=>y===b?null:b)},[]);return n.jsxs("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] mb-2",children:"Send Session Transcript"}),n.jsx("p",{className:"text-sm text-[var(--text-muted)] mb-4",children:"Download your session transcript and send it to the CodeYam team for feedback or debugging."}),n.jsxs("div",{className:"mb-3",children:[n.jsx("span",{className:"block text-xs text-[var(--text-muted)] mb-1.5",children:"Tag (optional)"}),n.jsx("div",{className:"flex flex-wrap gap-1.5",children:V1.map(b=>{const y=a===b;return n.jsx("button",{type:"button","aria-pressed":y,onClick:()=>g(b),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:b},b)})})]}),n.jsx("textarea",{value:r,onChange:b=>s(b.target.value),placeholder:"What's on your mind? (optional)",className:"w-full h-20 px-3 py-2 text-sm rounded-md mb-4 resize-none",style:{background:"var(--bg-input, var(--bg-deep))",color:"var(--text-primary)",border:"1px solid var(--border-default)"}}),u&&n.jsx("p",{className:"text-sm text-red-400 mb-3",children:u}),n.jsxs("div",{className:"flex flex-col gap-3",children:[f?n.jsxs(n.Fragment,{children:[n.jsx("p",{className:"text-sm text-green-400 text-center",children:"Transcript downloaded!"}),n.jsx("a",{href: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 K1({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 G1(){return`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/raw-terminal`}function Y1(){if(gt())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]=lo(1200);function u(f){const p=s.current;(p==null?void 0:p.readyState)===WebSocket.OPEN&&p.send(new TextEncoder().encode(f))}return io(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 Ra.Terminal({cursorBlink:!0,fontSize:13,fontFamily:"'IBM Plex Mono', monospace",rightClickSelectsWord:!1,theme:{background:"#1e1e1e",foreground:"#cccccc",cursor:"#D7FF63",selectionBackground:"#264f78"}}),p=new Pa.FitAddon;f.loadAddon(p),f.open(e.current),t.current=f,r.current=p;const m=Ta(f,e.current,{onCopy:()=>d()}),h=Da(f,{sendInput:u});requestAnimationFrame(()=>{p.fit(),f.focus()});const g=new WebSocket(G1());return s.current=g,g.binaryType="arraybuffer",g.onmessage=b=>{b.data instanceof ArrayBuffer&&f.write(new Uint8Array(b.data))},g.onopen=()=>{g.send(JSON.stringify({type:"resize",cols:f.cols,rows:f.rows}))},g.onclose=()=>{l(!0),f.writeln(`\r
|
|
187
|
+
\x1B[90m[Shell session ended]\x1B[0m`)},f.onData(u),()=>{var b;(b=s.current)==null||b.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(co,{})]})}function q1({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(Y1,{})})]})}):null}let or=null;function J1(e){if(typeof e!="object"||e===null)return null;const t=e.buildCommitSha;return typeof t!="string"||t===""||t==="unknown"?null:t}async function X1(){try{const e=await fetch("/api/health");return e.ok?J1(await e.json()):null}catch{return null}}function Q1(){const[e,t]=i.useState(null);return i.useEffect(()=>{let r=!0;return or||(or=X1()),or.then(s=>{r&&t(s)}),()=>{r=!1}},[]),{sha:e}}function Z1(){var xs,gs;P1();const{sha:e}=Q1(),t=Fl(),{state:r,provider:s,credsPresent:a,reason:o,expiresAt:l,probeInFlight:c,backendFieldAbsent:d,refresh:u}=El(),{sessionInfo:f,refetch:p}=Bo({pollIntervalMs:15e3}),m=(f==null?void 0:f.agentBrokerLive)??!1,h=v1(r,m),{activeTab:g,buildActivated:b,planActivated:y,navigateToTab:w,showBuildTab:v,deactivateBuild:x}=Qr(t,h,r==="needs-login"&&!m),{arm:j,navigateToTabUser:k}=w1(h,w),[N,S]=i.useState(!1),[C,R]=i.useState(!1),[E,T]=i.useState(0),[M,A]=i.useState(0),[P,_]=i.useState(0),{showPostPushModal:G,onFeatureCompleteCommand:D,onAgentIdle:$,onAgentActive:W,dismissModal:z}=s1(),{showPlanCompleteModal:q,onPlanCompleteCommand:L,dismissPlanCompleteModal:F}=a1(),[O,X]=i.useState(!1),[J,ie]=i.useState(!1),[ee,H]=i.useState(!1),[B,Z]=i.useState(!1),ne=i.useCallback(()=>{H(!0)},[]),K=i.useCallback(()=>{H(!1)},[]),{plans:se,loading:I,error:ae,refetch:ge}=Yr(),{reorderPlans:oe}=Yo(ge),{launchPlan:me,launchingSlug:de,error:Oe}=Zr(),{launchPrompt:Pe,launching:Ge,error:bt}=o1(),[Tt,it]=i.useState(!1),{stepState:V}=qt(),Ae=i.useRef(null),{leftWidth:Te,handleMouseDown:vt}=C1(Ae),pe=S1(768),[Ye,Ie]=i.useState("editor"),Fe=i.useCallback(Q=>{Ie(Q),Q==="editor"&&(ze(),typeof window<"u"&&window.dispatchEvent(new Event("resize")))},[]),lt=pe?((xs=Ae.current)==null?void 0:xs.clientWidth)??(typeof window<"u"?window.innerWidth:Te):Te,{entityLookup:ct}=zy(),{groups:Ne,loading:qe,refreshing:We,currentRunner:Je,coverage:yt,refresh:ue}=Ey(),{groups:ce,loading:he,reload:we}=jy(),{routeEntities:le,loading:fe,error:ve}=ky(),{config:Y,apps:re,loading:Ce,refetch:ye}=ot(),je=i.useMemo(()=>l1(re,Ne,ce),[re,ce,Ne]),dt=i.useCallback(()=>{S(Q=>!Q)},[]),ut=i.useCallback(()=>{R(Q=>!Q)},[]),{selectedApp:ke,appRouteEntities:Xe,appTestGroups:Dt,selectedEntityHash:ji,selectedRouteEntity:as,previewSlug:ft,setPreviewSlugExplicit:ki,selectApp:An,deselectApp:os,selectRoute:Fn,selectEntity:Ni,deselectRoute:Ci}=By(re,le,ce,Ne,t),{viewports:Si,resolvedViewport:Ln,previewUrl:Ei,handleViewportChange:Ri,handleCustomSizeChange:Pi,showScenarioPreview:Xt,handlePreviewCommand:$e,setPreviewPath:Mn,previewSeeding:Ti,previewSeedError:Di,commandNonce:Ai}=r1({apps:re,appRouteEntities:Xe,configLoaded:!Ce,port:(Y==null?void 0:Y.port)??5173,previewOrigin:wa(Y,ke),projectTitle:(Y==null?void 0:Y.projectTitle)??null,routeEntities:le,screenSizes:(Y==null?void 0:Y.screenSizes)??{},defaultScreenSize:(Y==null?void 0:Y.defaultScreenSize)??null,scenarioGroups:ce,scenariosLoaded:!he,selectedApp:ke,selectedRouteEntity:as,previewSlug:ft,setPreviewSlug:ki}),{isAgentBuilding:At,isAgentBuildingRef:In,buildingScenarioSlug:$n,onAgentIdle:is,onAgentActive:ls,guardScenarioSelect:cs,clearBuildingOverlay:Qe}=i1({onTransitionToLive:Xt}),Bn=(f==null?void 0:f.resumeMode)==="resume"||(f==null?void 0:f.resumeMode)==="handoff",{buildSessionLive:On,transitionBuildSessionLive:Ft}=z1({isAgentBuilding:At,submittingBuildPrompt:Ge,launchingPlanSlug:de,sessionInfo:f,refetchSessionInfo:p});i.useEffect(()=>{qr({hasActiveSession:Bn,isAgentBuilding:At,stepStateFeature:(V==null?void 0:V.feature)??null})},[Bn,At,V==null?void 0:V.feature]),i.useEffect(()=>{const Q=Y==null?void 0:Y.projectTitle;document.title=typeof Q=="string"&&Q.length>0?`CodeYam: ${Q}`:"CodeYam"},[Y==null?void 0:Y.projectTitle]);const Fi=i.useCallback(()=>{$(),is()},[$,is]),Li=i.useCallback(()=>{W(),ls()},[W,ls]),Qt=(Y==null?void 0:Y.provider)??Rl,Mi=st(Qt),{buildIdle:ds,bannerVisible:Ii,notifSettings:us,handleSettingsChange:fs,handleAgentIdle:$i,handleAgentActive:Bi,handleUserInput:Oi,handleNavigateToTab:_i,dismissIdleBanner:zi}=O1({agentName:Mi,isBuildTabActive:g==="build",isAgentBuilding:At,buildSessionLive:On,featureCompleteKey:P,navigateToTab:k,onAgentIdleImmediate:Fi,onAgentActiveImmediate:Li}),ps=i.useCallback(Q=>{cs(Q)||Xt(Q)},[cs,Xt]),wt=i.useMemo(()=>Cr($n,ce),[$n,ce]),Hi=((gs=wt==null?void 0:wt.screenshotPaths)==null?void 0:gs[0])??null,Wi=(wt==null?void 0:wt.name)??null,Vi=i.useCallback(Q=>{switch(Q.type){case"preview":("scenarioSlug"in Q||"scenarioId"in Q)&&we(),$e(Q);break;case"showResults":Qe(),we(),T(Le=>Le+1),(V==null?void 0:V.mode)==="backend"&&$e({path:"/results",dimension:"Desktop"});break;case"hideResults":A(Le=>Le+1);break;case"featureComplete":Qe(),D(),_(Le=>Le+1),ye(),Sa({isAgentBuilding:In.current,trigger:"feature-complete",transitionBuildSessionLive:Ft});break;case"planComplete":L(),ye(),Sa({isAgentBuilding:In.current,trigger:"plan-complete",transitionBuildSessionLive:Ft});break}},[Qe,$e,In,D,L,ye,we,V,Ft]);_y(Vi);const Zt=(V==null?void 0:V.slug)==="ui-confirm-plan"||(V==null?void 0:V.slug)==="backend-confirm-plan",_n=i.useRef(null);i.useEffect(()=>{if(!V||!Zt){_n.current=null;return}_n.current!==V.step&&(_n.current=V.step,$e({path:"/plan-preview",dimension:"Desktop"}))},[V,Zt,$e]);const zn=i.useRef(null);i.useEffect(()=>{if(!V||V.mode!=="backend"||V.step<2||Zt){zn.current=null;return}zn.current!==V.step&&(zn.current=V.step,$e({path:"/results",dimension:"Desktop"}))},[V,Zt,$e]);const Hn=i.useRef(!1);i.useEffect(()=>{(V==null?void 0:V.slug)==="ui-confirm-plan"?Hn.current=!0:Hn.current&&(Hn.current=!1,Mn(null))},[V,Mn]);const Ui=i.useCallback(async()=>{z(),await Wh({provider:Qt,renameLabel:(V==null?void 0:V.feature)??void 0,caller:"post-push-modal",bypassLiveGuard:!0}),ze()},[z,Qt,V]),Ki=i.useCallback(()=>{z(),ze()},[z]),Gi=i.useCallback(async()=>{window.dispatchEvent(new CustomEvent("build-session-stopped")),await Hh(),z(),w("home"),x(),Ft(!1,"stop-building"),Qe(),p()},[z,w,x,Ft,Qe,p]),Yi=i.useCallback(()=>{T1(),F(),ze()},[F]),qi=i.useCallback(()=>{X(!1),D1(),F()},[F]),Ji=i.useCallback(()=>{ie(!0)},[]),Xi=i.useCallback(()=>{ie(!1)},[]),Qi=i.useCallback(async(Q,Le)=>{await me(Q,Le)&&(ie(!1),it(!0),z(),p())},[me,z,p]),Zi=i.useCallback(async Q=>{await Pe(Q)&&(it(!0),p())},[Pe,p]),el=i.useCallback(()=>{it(!0)},[]),ms=y1({activeTab:g,hasActiveSession:Bn,isAgentBuilding:At,showPostPushModal:G,launchingPlanSlug:de,submittingBuildPrompt:Ge,stepStateFeature:(V==null?void 0:V.feature)??null,pendingPlanCount:se.length,buildLaunchModalDismissed:Tt}),tl=ms||J;i.useEffect(()=>{g==="build"&&p()},[g,p]),i.useEffect(()=>{g==="home"&&(ye(),u())},[g,ye,u]);const nl=i.useCallback(async(Q,Le)=>{Qe(),$e(b1(Q,Le))},[Qe,$e]),rl=i.useCallback(Q=>{(Q.scenarioSlug||Q.path)&&$e({...Q.scenarioSlug?{scenarioSlug:Q.scenarioSlug}:{},...Q.path?{path:Q.path}:{},...Q.dimension?{dimension:Q.dimension}:{}})},[$e]),sl=i.useMemo(()=>({apps:re,isSingleApp:re.length===1,onSelectApps:os,onSelectApp:An,onSelectRoute:Fn}),[re,os,An,Fn]),al=i.useMemo(()=>ke?je.find(Q=>Q.app.dir===ke.dir)??null:null,[je,ke]),ol=n.jsxs(n.Fragment,{children:[n.jsx(Vo,{staleness:null,backendOutOfDate:d}),n.jsx(k1,{state:r,provider:s,credsPresent:a,reason:o,expiresAt:l,probeInFlight:c,backendOutOfDate:d,sessionOngoing:m,onAuthenticated:u,onAuthorized:()=>k("build")}),je.length>0&&n.jsx(Xd,{settings:us,onChange:fs}),n.jsx(jh,{selectedApp:ke,appDetailProps:{navContext:sl,routeEntities:Xe,routesLoading:fe,routesError:ve,selectedEntityHash:ji,selectedRouteEntity:as,testGroups:Dt,selectedSlug:ft,entityLookup:ct,allScenarios:ce.flatMap(Q=>Q.scenarios),onSelectScenario:ps,onSelectRoute:Fn,onSelectEntity:Ni,onBackToRoutes:Ci,onScenariosChanged:we,projectTitle:(Y==null?void 0:Y.projectTitle)??null,coverage:yt,showProjectBand:re.length===1,stats:al,testsLoading:qe,testsRefreshing:We,onRunTests:ue,currentRunner:Je},appOverviewProps:{projectTitle:(Y==null?void 0:Y.projectTitle)??"Project",projectDescription:(Y==null?void 0:Y.projectDescription)??null,stats:je,coverage:yt,onSelectApp:An,configLoading:Ce,testsLoading:qe,testsRefreshing:We,onRunTests:ue,currentRunner:Je,stepState:V,onPreviewUrl:Mn,onComplete:async()=>{await ye(),console.info("[EditorShell] questionnaire complete; arming pending build-nav",{providerAuthState:r,buildBlocked:h}),j()},onOpenBuildTab:()=>k("build")}})]}),il=je.some(Q=>g1(Q.app.type)),ll=ce.reduce((Q,Le)=>Q+Le.scenarios.length,0),hs=!!V&&!he&&ll===0;return n.jsxs(n.Fragment,{children:[n.jsx(Eh,{splitRef:Ae,isCollapsed:N,onResizeStart:vt,isNarrow:pe,mobilePane:Ye,onMobilePaneChange:Fe,isAgentBuilding:On,buildIdle:ds,leftPane:n.jsx(Bx,{activeTab:g,onSendTranscript:ne,appTabContent:ol,awaitingPlanLaunchChoice:tl,buildActivated:b,planActivated:y,buildIdle:ds,isAgentBuilding:On,bannerVisible:Ii,onDismissIdleBanner:zi,hideResultsCommandKey:M,leftWidth:lt,fullWidth:pe,navigateToTab:_i,onAgentActive:Bi,onAgentIdle:$i,onUserInput:Oi,notifSettings:us,onSettingsChange:fs,provider:Qt,onRestorePreview:rl,onResultsScenarioSelect:nl,previewSlug:ft,onSessionDetected:v,showPostPushModal:G,onStartNextFeature:Ui,onContinueInSession:Ki,onStopBuilding:Gi,showResultsCommandKey:E,planChatOpen:O,onPlanChatOpenChange:X,showPlanCompleteModal:q,onCreateNewPlan:Yi,onViewPlans:qi,pendingPlans:se,onSelectPlan:Ji,selectPlanOpen:J,onPickPlan:Qi,onCancelSelectPlan:Xi,launchingPlanSlug:de,planLaunchError:Oe,showBuildLaunchModal:ms,onSubmitBuildPrompt:Zi,submittingBuildPrompt:Ge,buildPromptError:bt,onCancelBuildLaunchModal:el,pendingPlansLoading:I,pendingPlansError:ae,onReorderPlans:oe,buildDisabled:h}),previewPane:n.jsx(wy,{emptyStateMessage:h1({configLoading:Ce,hasNoApps:je.length===0,hasStepState:!!V,hasPreviewableApp:il,setupInProgress:hs}),projectSetupInProgress:hs,previewSlug:ft,previewUrl:Ei,viewports:Si,activeViewport:Ln.name,onViewportChange:Ri,isCollapsed:N,onToggleCollapsed:dt,isNarrow:pe,isFilled:C,onToggleFilled:ut,currentWidth:Ln.width,currentHeight:Ln.height,onCustomSizeChange:Pi,buildingScenarioSlug:$n,buildingScreenshotPath:Hi,buildingScenarioName:Wi,onDismissBuildingOverlay:Qe,previewSeeding:Ti,previewSeedError:Di,onRetrySeed:()=>{ft&&Xt(ft)},currentScenario:Cr(ft,ce),scenarioGroups:ce,onShowScenarioPreview:ps,commandNonce:Ai,previewOrigin:wa(Y,ke),onDesignConfirmed:()=>k("build")})}),ee?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(U1,{featureName:(V==null?void 0:V.feature)??null,onClose:K})}):null,n.jsx(q1,{isOpen:B,onClose:()=>Z(!1)}),n.jsx(K1,{sha:e,onClick:()=>Z(!0)})]})}const lw=Object.freeze(Object.defineProperty({__proto__:null,EditorShell:Z1},Symbol.toStringTag,{value:"Module"}));export{d0 as $,Jl as A,Xl as B,Ua as C,ql as D,ih as E,Kl as F,Yl as G,Oo as H,L0 as I,Zl as J,Bc as K,$c as L,Ic as M,_a as N,K1 as O,cv as P,_o as Q,Kv as R,ud as S,cd as T,Xv as U,Zv as V,e0 as W,t0 as X,Qv as Y,r0 as Z,Yv as _,Ec as a,Ix as a$,o0 as a0,a0 as a1,l0 as a2,c0 as a3,i0 as a4,su as a5,ru as a6,tu as a7,eu as a8,Zd as a9,gg as aA,Hm as aB,Gm as aC,Jb as aD,ui as aE,Xb as aF,ev as aG,Yb as aH,Gb as aI,Kb as aJ,da as aK,rv as aL,nv as aM,vg as aN,tv as aO,qb as aP,Qb as aQ,sv as aR,gf as aS,xf as aT,Y1 as aU,q1 as aV,bf as aW,Ax as aX,Dx as aY,$x as aZ,Mx as a_,nu as aa,Bl as ab,Il as ac,Ll as ad,vs as ae,Ml as af,bh as ag,fh as ah,ph as ai,mh as aj,gh as ak,hh as al,xh as am,vh as an,yh as ao,ig as ap,ag as aq,Ho as ar,Gr as as,og as at,Wo as au,Jt as av,Ya as aw,sg as ax,rg as ay,ng as az,Kn as b,Oc as b$,Tx as b0,Lr as b1,yx as b2,wx as b3,jx as b4,bm as b5,xx as b6,hx as b7,mx as b8,gx as b9,Jh as bA,ox as bB,ax as bC,Uh as bD,Nx as bE,Rx as bF,Wb as bG,Hb as bH,Vn as bI,Hl as bJ,lc as bK,rc as bL,fc as bM,Z1 as bN,ca as bO,zb as bP,$l as bQ,Sc as bR,zc as bS,Hc as bT,_c as bU,Sx as bV,Om as bW,_m as bX,Ql as bY,Ma as bZ,Mc as b_,bx as ba,lx as bb,cx as bc,Kr as bd,Yh as be,Gh as bf,Kh as bg,gm as bh,hm as bi,dm as bj,mm as bk,cm as bl,xm as bm,fm as bn,um as bo,pm as bp,im as bq,$o as br,Lo as bs,qo as bt,ex as bu,nx as bv,qs as bw,Qh as bx,sx as by,ix as bz,iw as c,ub as c$,Ia as c0,Ac as c1,Tc as c2,Pc as c3,Rc as c4,Dc as c5,Fc as c6,wc as c7,Nc as c8,kc as c9,Q0 as cA,Z0 as cB,Bb as cC,iy as cD,oy as cE,ov as cF,av as cG,iv as cH,bg as cI,fv as cJ,lv as cK,X0 as cL,Bm as cM,Nh as cN,Mt as cO,Lu as cP,Fu as cQ,ao as cR,Ob as cS,$b as cT,Rb as cU,Lb as cV,Ab as cW,Nb as cX,yb as cY,Sb as cZ,gb as c_,yc as ca,jc as cb,hc as cc,mc as cd,Fa as ce,ws as cf,Jc as cg,Xc as ch,Kc as ci,od as cj,qc as ck,Uc as cl,Vc as cm,ys as cn,Wn as co,Wc as cp,rt as cq,Mu as cr,gy as cs,vy as ct,py as cu,uy as cv,wy as cw,_0 as cx,ry as cy,sy as cz,Dr as d,rh as d$,Eb as d0,zg as d1,Tu as d2,Du as d3,Ru as d4,Eu as d5,Nu as d6,_u as d7,Ou as d8,Dd as d9,Qu as dA,qu as dB,Yu as dC,Gu as dD,lh as dE,dh as dF,ah as dG,sh as dH,S0 as dI,R0 as dJ,N0 as dK,k0 as dL,j0 as dM,P0 as dN,C0 as dO,w0 as dP,E0 as dQ,v0 as dR,b0 as dS,Tr as dT,ic as dU,La as dV,vf as dW,df as dX,ym as dY,Zu as dZ,Wu as d_,Pd as da,Sd as db,Cd as dc,Nd as dd,kd as de,Ex as df,Cs as dg,Ud as dh,Xd as di,Mr as dj,Yd as dk,Ld as dl,qa as dm,$d as dn,Fr as dp,$m as dq,Sh as dr,Px as ds,Cx as dt,Bx as du,Eh as dv,kh as dw,jh as dx,Ju as dy,Qn as dz,ld as e,Hu as e0,zm as e1,zu as e2,id as e3,Ol as e4,k1 as e5,ju as e6,wu as e7,ku as e8,yu as e9,vu as ea,bu as eb,lw as ec,Va as f,U1 as g,Se as h,F0 as i,$0 as j,M0 as k,A0 as l,O0 as m,Mv as n,T0 as o,Ba as p,ln as q,Ue as r,pg as s,ug as t,dg as u,cg as v,lg as w,mg as x,cy as y,ly as z};
|