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